Repository navigation
fix(agent): keep a CLI turn alive and store why it failed - #568
Zhangbo-cn wants to merge 12 commits into
Conversation
Harnesses occasionally write a human-readable warning or startup error to stdout. The reader parsed every line as JSON, so one plain line raised an unhandled JSONDecodeError: the turn died, the trace file stayed empty, and the user only saw a generic failure. Decode stdout defensively: JSON lines stream as before, plain lines become diagnostic events in the trace, and a turn that streamed no usable event now fails with the CLI's own first line (redacted, 200 chars) instead of an empty reply. The new agent_cli_output_invalid code keeps the message bilingual. Refs ThinkFlowLab#567
8d0b629 to
e92a11b
Compare
The lane hit a storage_busy 409 while asserting an unrelated assistant flow; this branch only touches harness stdout parsing and its localisation. Re-running to separate a flake from a regression.
|
重跑结果:全部检查通过(CodeQL / static / browser assistant + isolated + voice / frontend / python / route / tests)。 之前 |
One nit worth a follow-up: Ran: |
david6666666
left a comment
There was a problem hiding this comment.
REQUEST CHANGES aad67c7 Fixes #567
当前证据暂定 28/100,非批准分:范围 3/3、正确性 0/3、验证 2/3、主张证据 0/3、简洁度 0/3。把普通 CLI 提示与 JSON 事件拆开是对的,但现有回归只证明错误横幅会脱敏,新增的原始 stdout 诊断却会直接写入项目 trace。现有 stderr 路径会先脱敏,stdout 应复用同一原则。请在行内指出的位置加回归,检查实际落盘文本,而不仅是异常消息。没有运行 PR 代码。
该 head 的 Release、CodeQL、DSH 已通过。当前未找到证明错误横幅修复的实际界面截图;新增解释性代码注释按量表计零。与 main 的距离不是这里的阻塞。
English: Redact CLI diagnostics before writing to the project trace, and assert against the persisted trace as well as the display message.
Dot,代表 @david6666666 作非表决审查;没有批准或合入。
| raw, text = native_line(line) | ||
| if text is not None: | ||
| plain.append(text) | ||
| await queue.put({'native': {'type': 'diagnostic', 'stdout': text[:2000]}}) |
There was a problem hiding this comment.
错误提示里的脱敏不会覆盖这条路径:diagnostic 入队后会写进项目 trace,这里还是原始 stdout。请与现有 stderr 共用脱敏逻辑,在截断和落盘之前执行,并让回归同时检查最终错误和落盘的 trace。
…tdout # Conflicts: # apps/api/src/opendirector_api/localization.py
david6666666
left a comment
There was a problem hiding this comment.
REQUEST CHANGES 7966a15 Fixes #567
当前证据暂定 28/100,非批准分。 范围 3/3、正确性 0/3、验证 2/3、主张证据 0/3、简洁度 0/3。
合并 main 后 Release 七项、CodeQL、DSH 都绿,但原有的脱敏意见仍未解决。当前 main 已支持原样导出对话 trace,不能指望导出时再过滤:请在诊断进入 trace 前统一脱敏,并让回归核对落盘内容和错误横幅。具体代码位置沿用上轮行内意见,不重复留言。当前没有看到实际横幅的界面证据;新增解释性源码注释按量表计零。未运行 PR 代码。
Dot,代表 @david6666666 作非表决复审。
…hown ## summary - A failed turn lost its reason: the explanation was only returned on the event stream, never written to the assistant message, so reopening the project showed an empty reply and a generic interrupted line (ThinkFlowLab#557). - The assistant message now keeps the explanatory text and a stable `errorCode` (`agent_cli_login`, `agent_cli_exit`, `agent_cli_output_invalid`), and the panel renders that code in the language currently shown. Switching language afterwards keeps the same explanation instead of freezing the language that was on screen when the turn failed. - `agent_cli_login` marks a rejected CLI credential; `agent_cli_exit` marks a process that exited, carrying its own first output line; `agent_cli_output_invalid` marks output with no readable event. - Diagnostic stdout lines keep the turn token and provider key redacted, in the trace and in the failure text, on the same rules the stderr diagnostic already used. - `docs/architecture/agent-runtime.md` records the diagnostic channel and the three codes, in Chinese with an English summary. ## validation - `python3 -m pytest tests/test_native_runtime.py tests/test_localization.py tests/test_assistant_conversations.py tests/test_runtime_readiness.py` — 98 passed, 7 skipped. The three new turn tests fail on the previous revision (checked by stashing the source change). - `npm test` — 1075 passed. - `npm run check:i18n` — 3527 keys, 0 problems, 167 Chinese source lines. - `npx tsc --noEmit` — clean. - `python -m pre_commit run --files <changed files>` — passed. - `node tests/browser/assistant_activity.mjs` — 15 checks, including the stored-failure case in both languages, on a freshly started dev server. - Real app against an isolated API: a turn run with a CLI stub that exits with its own error line stores `errorCode: agent_cli_exit`, and the panel shows that cause in zh-CN and en-US before and after reload, where the previous revision showed "本次回复未生成内容。/This reply produced no content.". The CLI stub and the fixture model are doubles; no real provider credential was involved. Refs ThinkFlowLab#557 Refs ThinkFlowLab#567
The turn now stores agent_cli_login and agent_cli_exit, so an en-US reader must get the same explanation the zh-CN reader gets instead of the generic rejection text. Append the redacted CLI output for every agent CLI code. ## summary - agent_cli_login and agent_cli_exit join agent_cli_output_invalid in ENGLISH_BY_CODE. - The CLI output suffix applies to every agent_cli_* code, not just the invalid-output one.
david6666666
left a comment
There was a problem hiding this comment.
Non-voting COMMENT · technical verdict: REQUEST CHANGES · 4dbefee Fixes #567; Refs #557
普通 stdout 不再直接打断整轮,失败原因也能随会话保存。上一轮的脱敏意见部分修了,但 trace 和错误文本都仍需先脱敏再截断,并加落盘回归。#557 还有 runtime readiness 这条验收,本 PR 明确未做,建议改成 Refs,避免合入时误关。
Ran: 核对当前 diff、作者的双语 fixture 记录与 Release checks。OpenCode gateway 集成失败,其他已观察到的 frontend/browser 检查通过。Not run: 未独立运行应用,也未找到有实际界面截图的证据。
当前证据暂定 23/100,非批准分。 范围 2/3、正确性 0/3、验证 2/3、主张证据 0/3、简洁度 0/3(新增解释性源码注释)。
English: Apply redaction before truncation and verify the persisted trace. Use Refs #557 until runtime readiness is covered.
Dot,代表 @david6666666 作非表决复审。
| if text is not None: | ||
| plain.append(text) | ||
| await queue.put({'native': {'type': 'diagnostic', | ||
| 'stdout': redacted(text[:2000], config, token)}}) |
There was a problem hiding this comment.
现在 trace 已走脱敏,比上一版好。这里和 cli_detail() 仍先截断再脱敏;请把顺序统一成先脱敏再截断,并让测试读取实际落盘的 trace 和错误文本,不只检查异常对象。
david6666666
left a comment
There was a problem hiding this comment.
Non-voting COMMENT · technical verdict: REQUEST CHANGES · ad0d54f · Fixes #567; Refs #557
Dot,代表 @david6666666。
新 head 同步的是 main,产品改动里的上轮 blocker 还在。另外,native_line() 只确认输出是 JSON 对象就算事件;普通结构化日志如果不符合 Codex 的事件字段,仍可能打断本轮。这个边界已标在代码行。建议把「能解析」与「符合事件契约」分开判断,并确认后续正常事件仍继续处理。
之前的脱敏与 #557 readiness 范围意见不重复贴;当前还没看到双语失败状态的实际截图。Ran: 核对三点差异、#567/#557、已有 fixture 与 同 SHA Release,该 run 在检查时仍在跑。Not run: 未执行 PR 代码。
当前证据暂定 23/100,非批准分:范围 2/3、正确性 0/3、验证 2/3、主张证据 0/3、简洁度 0/3。
| continue | ||
| if raw is None: | ||
| continue | ||
| parsed = True |
There was a problem hiding this comment.
这里 parsed = True 实际只说明这一行可解析成 JSON 对象,不代表它有 Codex 事件所需的字段。遇到普通结构化日志时,下一段会直接读取 raw['type'],这轮还是可能提前退出。能先判断是不是可处理的事件,再把不匹配的日志走诊断,并断言后面的正常事件仍能到达吗?
The failed-turn text used a fixed #df9a9a, which is 2.3:1 on the light panel sheet. It now follows the panel tokens like --chat-muted, and the browser workflow measures the contrast on both sheets.
david6666666
left a comment
There was a problem hiding this comment.
WITHHOLD f3225e4 Fixes #567; Refs #557 · 非表决
我把中英文、深浅色四张图都下载看了,失败提示在该渲染夹具上确实能读清,样式更新有价值。它们是同组件的局部截图,不等于当前 head 在实际应用路径完成了「进程退出→保存→重开」。CLI 核心代码与上轮相同:还有两项已在旧行内记录,结构化日志的事件校验,以及脱敏要先于截断。#557 所要求的 readiness 也仍不在本改动里。
当前证据暂定 23/100(范围 2,正确性 0,验证 2,主张证据 0,简洁性 0)。Ran: 增量 diff、四张截图与相同 head 的 CI 核对。Not run: 实际 CLI。建议保留样式改动,补应用重开证据,并按实际完成范围链接 #557。Dot,代表 @david6666666。
Redaction used to run after the 200/2000/8192-character cut, so a long line could keep a partial secret that no replacement rule matches. Trim through one helper that redacts first, and cut the stderr buffer on a line boundary instead of in the middle of a token. A parsed JSON object is not yet an event: native_line() only proves the line decodes, so log-only lines still hit raw['type'] with a KeyError and the "nothing usable was streamed" branch never ran. Treat an object as an event only when it carries a string type or event field and send the rest down the diagnostic path, so a chatty CLI logs its output and the turn keeps going.
david6666666
left a comment
There was a problem hiding this comment.
WITHHOLD 2ee9345 Fixes #567; Refs #557
plain stdout 现在先脱敏再截断;普通 JSON 日志、报错原因落盘和重开的 fixture 也补上了。Event 检查仍只看字符串字段,不等同于 runtime schema,详见行内。stderr 的同类边界建议用能保证脱敏的流式处理或丢弃不完整片段,不要让原始缓冲裁剪先于脱敏。#557 的 readiness 仍是独立范围。
当前证据暂定 32/100,非批准分(范围 2、正确性 1、验证 2、主张证据 0、简洁度 0;各满分 3)。此前四张双语深浅色截图是局部夹具,新增用例验证服务端重开,不是当前应用的一次完整现场回放。同 SHA Release 的 macOS 安装 smoke 未过;不把 macOS failure 本身归因于这个 CLI patch。Ran: 增量源码、fixture、CI;Not run: 本地 CLI。
Dot,代表 @david6666666 作非表决复审。
|
|
||
| def event_like(raw: dict) -> bool: | ||
| """Whether a parsed JSON object is a harness event rather than a log record.""" | ||
| return isinstance(raw.get('type'), str) or isinstance(raw.get('event'), str) |
There was a problem hiding this comment.
现在这条只验证 type/event 是字符串,还没验证它是该 runtime 认识的事件且 payload 形状符合契约。建议在交给 parser 前做识别;普通日志继续走 diagnostic,未识别记录不计作有效输出。Dot,代表 @david6666666。
Unknown JSON objects and malformed events now go to the diagnostic channel instead of counting as a readable event, and stderr redacts whole lines before the tail is trimmed.
david6666666
left a comment
There was a problem hiding this comment.
COMMENT(非表决) bfb1fbc Fixes #567; Refs #557
75/100(范围 2、正确性 1、验证 3、主张证据 3、简洁度 2)。我下载看了四张中英文实际应用截图,首次打开和刷新后都显示同一失败原因;作者用真实子进程跑 stub,验证的是本地保存和重开,不是真实 provider 登录。同 SHA Release、CodeQL 和 DSH 均通过。#557 的 readiness 不在本次范围。
仍建议修完再合:保存退出原因只读第一条普通日志,但现在把每一条原文都保存在内存里,直到 CLI 进程结束。我已在对应行补了建议。上一轮的事件字段类型校验意见仍适用,不重复贴。未独立运行应用。Dot,代表 @david6666666。
| if text is None and raw is None: | ||
| continue | ||
| text = text if text is not None else json.dumps(raw, ensure_ascii=False) | ||
| plain.append(text) |
There was a problem hiding this comment.
这里退出原因只用第一条 plain,但每条普通日志都会把原文追加进列表。长回合里 trace 每条已经有限长,内存里的副本却会一直涨。建议只保存首条脱敏且限长的诊断摘要,其余继续按现有 trace 写出;补个多行诊断后仍能正确标记退出的回归即可。Dot,代表 @david6666666。
Fixes #567, and covers the "failure reason is persisted and still visible after reopening" part of #557. Runtime readiness probing remains a separate change.
Background
#567: an assistant turn aborted after about 300 ms; the UI only said "This reply produced no content / Reply interrupted", and the trace file was 0 bytes. The backend log shows the root cause: the read loop called
json.loadson every stdout line without checking:Harnesses (OpenCode in this case, Claude Code behaves the same) print a plain-text warning to stdout during startup. The exception is not a
ProjectErrorand was not converted into a user-readable error, so the whole turn aborted with an empty trace.#557: even when the failure reason had been computed it only lived in the event stream. The assistant message stored only
status: interrupted, so reopening the project still showed an empty reply; and runtime status still reported "available", leaving the authentication rejection only in the backend log.Changes
1. A stdout line is not necessarily an event (#567)
native_line()splits one stdout line into "JSON event / plain text / blank line". Plain text no longer raises; it is recorded as adiagnosticevent in this turn's trace (truncated to 2000 characters), and later lines keep parsing. The turn only fails when it produced no readable events at all.[redacted]in both the trace and the failure message, matching the existing stderr diagnostics.cli_detail()appends the CLI's first plain-text line (truncated to 200 characters, redacted the same way) to the failure message, for both a non-zero exit and "only plain text, no events", so the real reason is carried through.limited(text, config, token, limit)callsredacted()first and only then cuts to 200 / 2000 / 8192 characters. The other order can cut half a key (secret-key-va, neither the full key nor a match for the replacement rule) into the failure message and this turn's trace. stderr is now processed as complete lines: each line is redacted before entering the tail buffer, old lines are evicted only between redacted lines, and an unterminated over-long fragment is dropped outright, so every truncation happens after redaction.event_like(runtime, raw)decides whether a line is an event from each harness's event-type set (OpenCode / Codex / Claude / Pi / Antigravity) and its required fields (such asitemonitem.completed,message.contentonassistant,partontext). Structured logs like{"type": "log", ...}take the diagnostic channel even though they carry atype, so a turn that only printed logs is not mistaken for a success; normal events after the logs still flow.2. The failure reason is stored and stated in words a person can read (#557)
errorCode:agent_cli_login: the CLI credentials were rejected;agent_cli_exit: the process exited, with its first output line attached;agent_cli_output_invalid: only unreadable output, no events at all.src/canvas/assistantFailure.tsprefers the code's translation and falls back to the stored text for unknown codes. Switching language afterwards yields the same explanation.status === interruptedwithout anerrorkeeps the old subdued suffix; with anerrorthe panel renders.cw-chat-progress.is-failedinstead of pretending nothing happened.localization.pygives eachagent_cli_*code an English string and keeps the redacted CLI output.3. Readability in the light theme —
is-failedhard-coded#df9a9a; it now follows the panel token--chat-failure(one value for dark, one for light), and the browser workflow measures contrast in both themes.4. Documentation —
docs/architecture/agent-runtime.mdrecords the diagnostic channel and the Chinese/English contract for the three codes.Verification
CI repair: on
mainat8cdf67ec,scripts/ci/python_shards.jsondid not list thetests/test_ark_availability.py,tests/test_wait_outcome.pyandtests/test_trace_job_queries.pymodules added by fix: map Ark video generation availability (#675) #676 / [perf] agent: gate wait snapshots, avoid job-show project reads, unify discovery, and surface wait outcomes (#449) #681, sotest_ci_layersinpython (core)failed onmainand on every PR (the Release checks are also red on that SHA). This tip lists the three modules;pytest tests/test_ci_layers.py— 21 passed.pytest tests/test_native_runtime.py tests/test_localization.py— 51 passed / 7 skipped (this tip).pytest tests/test_native_runtime.py tests/test_localization.py tests/test_assistant_conversations.py tests/test_runtime_readiness.py— 106 passed / 7 skipped.Three new cases cover "process exit stores the reason", "no events stores the reason" and "rejected credentials store the reason", each asserting
error/errorCodestill there after reopening the conversation; the same three fail on the revision before the change (source stashed, re-run), confirming they are regression guards rather than descriptions of current behaviour.npm test— 1075 passed / 0 failed (this tip).npm run check:i18n— 3527 keys, 0 problems, 167 Chinese source lines (baseline 169).npx tsc --noEmit— passes.python -m pre_commit run --files <changed files>— all pass.node tests/browser/assistant_activity.mjs— all 16 checks pass, including the new "stored failure reason" and "failure contrast on both sheets": the sameerrorCoderenders its own text in zh-CN / en-US, "This reply produced no content" no longer appears, and an unknown code falls back to the stored text.pytest tests/test_native_runtime.py— 43 passed / 7 skipped (this tip). Eight new cases: the event contract is validated per runtime and required fields (test_an_event_matches_its_runtime_contract); a structured log withtypebefore normal events still lets the turn finish; a CLI that only prints structured logs storesagent_cli_output_invalidand keeps it after reopening the conversation; an over-long plain-text line is redacted before truncation; truncated stderr persisted in the trace contains no key fragment; a key split across stderr read chunks is still fully redacted.Those new cases fail on the source before the change (the "log line" case reproduces
KeyError: 'type'directly; the "only structured logs" case is misread as an event by the oldevent_likeand silently succeeds), confirming they are regression guards.Real application-path receipt (current tip, with no
AgentRuntimes.streamreplacement intests/browser/creation_server.py): start the API directly withcreate_app(LocalProjects(root))and put a stubopencodeonPATH—After the real child process exits, the project persists:
{"role": "assistant", "status": "interrupted", "runtime": "opencode", "model": "stub-agent", "errorCode": "agent_cli_exit", "error": "The Agent CLI exited before this turn finished. Check its sign-in and configuration; this turn's trace keeps its output. CLI output: {\"level\": \"error\", \"message\": \"provider rejected the request: invalid api key\"}"}Opening the same project in the dev server shows the same reason on first open and after a reload, in both languages (the localized text is re-rendered from
errorCode):main)The child process in this turn is a real CLI process (stub shown above), deterministic and offline; its log line lands exactly on the [bug] assistant: CLI 输出非 JSON 行导致整轮中断,界面只显示“Agent 执行失败” #567 crash path and no longer crashes.
Another stub that prints only
{"type": "log", "level": "error", "message": "provider unavailable"}exercises the event contract on the same application path: the line is no longer treated as a harness event, the turn storesagent_cli_output_invalidwith that log line (test_a_cli_that_prints_only_typed_log_json_stores_its_own_reason).Screenshots
Reply rendering uses the repository's harness-independent fixture (
tests/browser/assistant_activity.html, the sameAssistantReplycomponent as the panel) with theerror/errorCodepersisted by a real failure:main)The light-theme pair also covers this change's contrast fix:
is-failedwas hard-coded#df9a9a, only 2.3:1 on the light panel (#fff); it now follows the panel token (--chat-failure:#df9a9adark,#9a4d36light). The newassistant_activityassertion requires at least 4.5:1 in both themes; removing the fix reportslight failure contrast 2.276.Not included
runtime_status(probe=False)still reports an authentication-failed runtime as available; that is a separate status channel and a separate change.Refs #557
Fixes #567
The lane that used to be stuck is fixed
Earlier, this PR was blocked at
4dbefee3by theBundled OpenCode model gateway regressionstep inchecks / python(test_real_opencode_native_visual_input[image-model]hit the 60 s watchdog after the second tool call). That failure was the same onmainand on six unrelated branches, a known #162 problem; upstreamae04b58d [test] agent: isolate bundled OpenCode workers (#648)fixed it by isolating TMPDIR/XDG/pytest/HOME per worker.origin/main(8cdf67ec) is now merged into this branch, together with the three test modulesmainitself left unregistered (see above); the same command locally —OPENDIRECTOR_REAL_CLI=1 python3 -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q— is 7 passed / 2 skipped. CI verifies the new tip.checks / desktop / macosis a failure that already exists onmainmainatf3251839fails the same job with the same message (job 144895292605):Error: Rapid project switching did not settle(scripts/smoke-window.mjs:244).This PR touches neither desktop packaging, the window smoke test nor the project-switching path: the diff is the CLI diagnostic channel in
native.py, four pytest files and assistant panel colour tokens;checks / desktop / windowspasses.