jackwener/OpenCLI · error · CommandExecutionError

Browser session required for zhihu answer

Error message

Browser session required for zhihu answer

What it means

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.

Source

Thrown at clis/zhihu/answer.js:22

import { buildResultRow, requireExecute, resolveCurrentUserIdentity, resolvePayload } from './write-shared.js';
cli({
    site: 'zhihu',
    name: 'answer',
    access: 'write',
    description: 'Answer a Zhihu question',
    domain: 'www.zhihu.com',
    strategy: Strategy.COOKIE,
    browser: true,
    args: [
        { name: 'target', positional: true, required: true, help: 'Zhihu question URL or typed target' },
        { name: 'text', positional: true, help: 'Answer text' },
        { name: 'file', help: 'Answer text file path' },
        { name: 'execute', type: 'boolean', help: 'Actually perform the write action' },
    ],
    columns: ['status', 'outcome', 'message', 'target_type', 'target', 'created_target', 'created_url', 'author_identity'],
    func: async (page, kwargs) => {
        if (!page)
            throw new CommandExecutionError('Browser session required for zhihu answer');
        requireExecute(kwargs);
        const rawTarget = String(kwargs.target);
        const target = assertAllowedKinds('answer', parseTarget(rawTarget));
        const payload = await resolvePayload(kwargs);
        await page.goto(target.url);
        await page.wait(3);
        const authorIdentity = await resolveCurrentUserIdentity(page);
        const apiResult = await page.evaluate(`(async () => {
            var questionId = ${JSON.stringify(target.id)};
            var content = ${JSON.stringify(payload)};
            var url = 'https://www.zhihu.com/api/v4/questions/' + questionId + '/answers';
            var resp = await fetch(url, {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ content: content, reshipment_settings: 'disallowed' }),
            });
            var data = await resp.json();

View on GitHub (pinned to 49907e53dc)

Solutions

  1. 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'.
  2. Verify the browser binary is installed and launchable in your environment (Chrome/Chromium present, not blocked in CI).
  3. If calling the command's func directly from code, pass the page obtained from the session manager as the first argument.
  4. Catch CommandExecutionError in your wrapper and print guidance that a browser session is required.

Example fix

// before
opencli zhihu answer --target question:123456 --file answer.md
// error: Browser session required
// after
opencli zhihu login   # ensure browser session with z_c0 cookie
opencli zhihu answer --target question:123456 --file answer.md --execute
Defensive patterns

Strategy: validation

Validate before calling

if (!page) throw new Error('Call `opencli zhihu login` / start a browser session before running zhihu answer');

Type guard

function hasBrowserSession(page) { return !!page && typeof page.goto === 'function'; }

Try / catch

try { await runZhihuAnswer(args); } catch (e) { if (String(e.message).includes('Browser session required')) { await openBrowserSession(); return runZhihuAnswer(args); } throw e; }

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of jackwener/OpenCLI@49907e53dc (2026-08-29). Data as JSON: /api/errors/c95e5d74e84b0ce9. Report an issue: GitHub.