{"record":{"id":"c95e5d74e84b0ce9","repo":"jackwener/OpenCLI","slug":"browser-session-required-for-zhihu-answer","errorCode":null,"errorMessage":"Browser session required for zhihu answer","messagePattern":"Browser session required for zhihu answer","errorType":"exception","errorClass":"CommandExecutionError","httpStatus":null,"severity":"error","filePath":"clis/zhihu/answer.js","lineNumber":22,"sourceCode":"import { buildResultRow, requireExecute, resolveCurrentUserIdentity, resolvePayload } from './write-shared.js';\ncli({\n    site: 'zhihu',\n    name: 'answer',\n    access: 'write',\n    description: 'Answer a Zhihu question',\n    domain: 'www.zhihu.com',\n    strategy: Strategy.COOKIE,\n    browser: true,\n    args: [\n        { name: 'target', positional: true, required: true, help: 'Zhihu question URL or typed target' },\n        { name: 'text', positional: true, help: 'Answer text' },\n        { name: 'file', help: 'Answer text file path' },\n        { name: 'execute', type: 'boolean', help: 'Actually perform the write action' },\n    ],\n    columns: ['status', 'outcome', 'message', 'target_type', 'target', 'created_target', 'created_url', 'author_identity'],\n    func: async (page, kwargs) => {\n        if (!page)\n            throw new CommandExecutionError('Browser session required for zhihu answer');\n        requireExecute(kwargs);\n        const rawTarget = String(kwargs.target);\n        const target = assertAllowedKinds('answer', 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 questionId = ${JSON.stringify(target.id)};\n            var content = ${JSON.stringify(payload)};\n            var url = 'https://www.zhihu.com/api/v4/questions/' + questionId + '/answers';\n            var resp = await fetch(url, {\n                method: 'POST',\n                credentials: 'include',\n                headers: { 'Content-Type': 'application/json' },\n                body: JSON.stringify({ content: content, reshipment_settings: 'disallowed' }),\n            });\n            var data = await resp.json();","sourceCodeStart":4,"sourceCodeEnd":40,"githubUrl":"https://github.com/jackwener/OpenCLI/blob/49907e53dc3ade5c223ff0c4c2c2785687cec4e6/clis/zhihu/answer.js#L4-L40","documentation":"The zhihu 'answer' command is a browser-automated CLI command; its func receives an active browser `page`. The library throws CommandExecutionError when `page` is falsy because writing a Zhihu answer requires a real, logged-in browser session — there is no pure-HTTP fallback. This guards against running the command in headless/no-session mode where the automation would silently fail or misbehave.","triggerScenarios":"Running `opencli zhihu answer` (or invoking the command's func directly) without first launching/attaching a browser session, or when the session manager fails to open a page so `page` is null/undefined.","commonSituations":"Forgetting to run `opencli login` or a browser-start command first; running in CI or an environment where the browser failed to start; calling the exported func programmatically without passing a page; browser crash or timeout that left the session null.","solutions":["Start a browser session first (run the CLI's browser/login command, e.g. `opencli zhihu login`) so a page is available before invoking 'answer'.","Verify the browser binary is installed and launchable in your environment (Chrome/Chromium present, not blocked in CI).","If calling the command's func directly from code, pass the page obtained from the session manager as the first argument.","Catch CommandExecutionError in your wrapper and print guidance that a browser session is required."],"exampleFix":"// before\nopencli zhihu answer --target question:123456 --file answer.md\n// error: Browser session required\n// after\nopencli zhihu login   # ensure browser session with z_c0 cookie\nopencli zhihu answer --target question:123456 --file answer.md --execute","handlingStrategy":"validation","validationCode":"if (!page) throw new Error('Call `opencli zhihu login` / start a browser session before running zhihu answer');","typeGuard":"function hasBrowserSession(page) { return !!page && typeof page.goto === 'function'; }","tryCatchPattern":"try { await runZhihuAnswer(args); } catch (e) { if (String(e.message).includes('Browser session required')) { await openBrowserSession(); return runZhihuAnswer(args); } throw e; }","preventionTips":["Always run the login/browser-start command before zhihu answer","In CI, use a persisted browser profile and verify the browser launches before invoking","When calling func directly, assert page is provided","Wrap session setup in a helper that fails fast with a clear message"],"tags":["browser-session","zhihu","cli","authentication"],"backgroundTag":"browser-session-required","analyzedSha":"49907e53dc3ade5c223ff0c4c2c2785687cec4e6","analyzedAt":"2026-08-29T08:14:47.543Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}