{"record":{"id":"cb7829a47864a241","repo":"jackwener/OpenCLI","slug":"browser-session-required-for-zhihu-comment","errorCode":null,"errorMessage":"Browser session required for zhihu comment","messagePattern":"Browser session required for zhihu comment","errorType":"exception","errorClass":"CommandExecutionError","httpStatus":null,"severity":"error","filePath":"clis/zhihu/comment.js","lineNumber":22,"sourceCode":"import { buildResultRow, requireExecute, resolveCurrentUserIdentity, resolvePayload } from './write-shared.js';\ncli({\n    site: 'zhihu',\n    name: 'comment',\n    access: 'write',\n    description: 'Create a top-level comment on a Zhihu answer or article',\n    domain: 'zhihu.com',\n    strategy: Strategy.COOKIE,\n    browser: true,\n    args: [\n        { name: 'target', positional: true, required: true, help: 'Zhihu target URL or typed target' },\n        { name: 'text', positional: true, help: 'Comment text' },\n        { name: 'file', help: 'Comment text file path' },\n        { name: 'execute', type: 'boolean', help: 'Actually perform the write action' },\n    ],\n    columns: ['status', 'outcome', 'message', 'target_type', 'target', 'author_identity', 'created_url'],\n    func: async (page, kwargs) => {\n        if (!page)\n            throw new CommandExecutionError('Browser session required for zhihu comment');\n        requireExecute(kwargs);\n        const rawTarget = String(kwargs.target);\n        const target = assertAllowedKinds('comment', parseTarget(rawTarget));\n        const payload = await resolvePayload(kwargs);\n        await page.goto(target.url);\n        await page.wait(3);\n        const authorIdentity = await resolveCurrentUserIdentity(page);\n        const apiResult = await page.evaluate(`(async () => {\n            var targetKind = ${JSON.stringify(target.kind)};\n            var targetId = ${JSON.stringify(target.id)};\n            var content = ${JSON.stringify(payload)};\n            var resourceType = targetKind === 'answer' ? 'answers' : 'articles';\n            var url = 'https://www.zhihu.com/api/v4/' + resourceType + '/' + targetId + '/comments';\n            var resp = await fetch(url, {\n                method: 'POST',\n                credentials: 'include',\n                headers: { 'Content-Type': 'application/json' },\n                body: JSON.stringify({ content: content }),","sourceCodeStart":4,"sourceCodeEnd":40,"githubUrl":"https://github.com/jackwener/OpenCLI/blob/49907e53dc3ade5c223ff0c4c2c2785687cec4e6/clis/zhihu/comment.js#L4-L40","documentation":"The `zhihu comment` command requires a live browser page session because it navigates to the target URL and performs the comment write in the browser. CommandExecutionError (code COMMAND_EXEC) is thrown at the top of func when `page` is falsy, i.e. the command was invoked without a connected browser session. This is a precondition guard, not a runtime failure.","triggerScenarios":"Invoking `opencli zhihu comment ...` when the browser daemon is not running, the extension is not connected, or the adapter was called programmatically with no page argument — so `page` is null/undefined at func entry.","commonSituations":"Running the CLI on a machine where the opencli browser daemon was never started; the Chrome extension disconnected after a browser restart; calling the CLI function directly in tests or scripts without establishing a browser session.","solutions":["Start/reconnect the browser session: launch the opencli-connected Chrome (or run the command via the normal CLI entry which connects the browser) and retry.","Check the extension/daemon status and reconnect if the browser was restarted.","If calling the API programmatically, obtain a page from the browser adapter and pass it instead of null."],"exampleFix":"// before\nawait cli.run('zhihu', 'comment', { target: '...', file: '...' }); // no browser\n// after\nconst browser = await opencli.browser.connect();\nconst page = await browser.newPage();\nawait zhihuComment(page, { target: '...', file: '...', execute: true });","handlingStrategy":"validation","validationCode":"if (!page) throw new Error('Connect a browser session before running zhihu comment'); // or check daemon status via opencli browser status","typeGuard":"function hasPage(p) { return p != null && typeof p.goto === 'function'; }","tryCatchPattern":"try {\n  await zhihuComment(page, kwargs);\n} catch (e) {\n  if (e.code === 'COMMAND_EXEC' && /Browser session required/i.test(e.message)) {\n    page = await connectBrowserAndNewPage();\n    return zhihuComment(page, kwargs);\n  }\n  throw e;\n}","preventionTips":["Start the opencli browser daemon and connect the extension before any write command.","In scripts, assert the page object exists before calling browser-backed CLI functions.","Re-verify the session after every browser restart — pages and connections do not survive it."],"tags":["zhihu","browser-session","precondition","write-command"],"backgroundTag":"browser-session-required","analyzedSha":"49907e53dc3ade5c223ff0c4c2c2785687cec4e6","analyzedAt":"2026-08-29T08:14:47.543Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}