From e92a11b6617a2bcea9d6537571e7d84255d0bc1a Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:52:44 +0800 Subject: [PATCH 1/8] fix(agent): keep the turn alive when a CLI prints plain stdout lines 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 #567 --- apps/api/src/opendirector_api/localization.py | 4 ++ .../core/src/opendirector/agent/native.py | 47 ++++++++++++++++++- tests/test_native_runtime.py | 44 +++++++++++++++++ 3 files changed, 93 insertions(+), 2 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 183412a69..9837ec38b 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -16,6 +16,7 @@ from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { + 'agent_cli_output_invalid': 'The agent CLI returned no usable output. Check its login and configuration.', 'higgsfield_model': 'Choose MAGI-2 with the official Higgsfield Open API address.', 'higgsfield_key': 'Enter your Higgsfield Open KEY_ID:KEY_SECRET.', 'higgsfield_output': 'MAGI-2 supports 1080p and whole-second durations from 4 to 30 seconds.', @@ -196,6 +197,9 @@ def localized_error_for_language( if generic and status in {413, 502, 504}: return ENGLISH_BY_STATUS[status] specific = None if code == "operation_rejected" else ENGLISH_BY_CODE.get(code) + if code == 'agent_cli_output_invalid': + detail = chinese.split('CLI 输出:', 1)[-1].strip() if 'CLI 输出:' in chinese else '' + return specific + (' CLI output: ' + detail if detail else '') if code == 'voice_provider_error': from opendirector.domain.voices import VOICE_MESSAGES detail = chinese.removeprefix(VOICE_MESSAGES[code]).strip() diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index 36cc3764d..a0a4da01f 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -153,6 +153,33 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None return args, env +def native_line(line: bytes) -> tuple[dict | None, str | None]: + """Split one CLI stdout line into a JSON event, plain text, or nothing. + + Harnesses occasionally print human-readable warnings or startup errors on + stdout; that must stay diagnosable instead of ending the turn. + """ + text = line.decode('utf-8', errors='replace').strip() + if not text: + return None, None + try: + raw = json.loads(text) + except ValueError: + return None, text + return (raw, None) if isinstance(raw, dict) else (None, text) + + +def cli_detail(lines: list[str], config) -> str: + """The first plain CLI line, redacted and trimmed, for a failure message.""" + if not lines: + return '' + detail = lines[0][:200] + secret = (config or {}).get('apiKey') + if secret: + detail = detail.replace(secret, '[redacted]') + return f' CLI 输出:{detail}' + + def text_events(runtime: str, raw: dict) -> list[dict]: if runtime == 'claude' and raw.get('error') == 'authentication_failed': raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401) @@ -304,6 +331,7 @@ async def record_exit(): async def output(): try: reported_session = None + plain, parsed = [], False if runtime == 'deepseek': async def observe(raw): await queue.put({'native': raw}) @@ -318,7 +346,14 @@ async def observe(raw): deepseek_server, observe, session_id) else: while line := await process.stdout.readline(): - raw = json.loads(line) + raw, text = native_line(line) + if text is not None: + plain.append(text) + await queue.put({'native': {'type': 'diagnostic', 'stdout': text[:2000]}}) + continue + if raw is None: + continue + parsed = True previous_session = reported_session if runtime == 'codex' and raw['type'] == 'thread.started': reported_session = raw.get('thread_id') @@ -332,7 +367,15 @@ async def observe(raw): await queue.put({'native': raw}) if await process.wait(): await record_exit() - raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。', 502) + raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。' + f'{cli_detail(plain, config)}', 502) + if not parsed and plain: + # Nothing usable was streamed: report what the CLI + # printed instead of an empty reply. + await record_exit() + raise ProjectError(f'{runtime} 未返回可识别的输出,请检查 CLI 登录和配置。' + f'{cli_detail(plain, config)}', 502, + code='agent_cli_output_invalid') if reported_session: run.save_native_session(reported_session, selection, engine_directory=native_work, diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 93f2035f0..dd9f99ed2 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -857,3 +857,47 @@ def test_codex_resume_requires_a_persisted_rollout(tmp_path, monkeypatch): rollout.parent.mkdir(parents=True) rollout.write_text('{}\n') assert native.codex_session_available(session) + + +def _plain_line_run(tmp_path, monkeypatch, source, config=None): + from opendirector.infrastructure.creation_projects import CreationProjects + run = RunContext(runtime='opencode', project_id=uuid4(), turn_id=uuid4(), + session=str(uuid4()), conversation_id=uuid4(), runtime_model='test-model', + directory=tmp_path, config=config, selected_skills=[], + messages=[{'role': 'user', 'content': 'first'}]) + monkeypatch.setattr(native, 'command', lambda *args, **kwargs: + ([sys.executable, '-c', source], dict(os.environ))) + instance = AgentRuntimes(CreationProjects(LocalProjects(tmp_path)), None, ModelConfigs(tmp_path)) + async def consume(): + events = [] + async for event in instance.stream(run): + events.append(event) + return events + return asyncio.run(consume()) + + +def test_plain_cli_line_before_events_keeps_the_turn(tmp_path, monkeypatch): + events = _plain_line_run(tmp_path, monkeypatch, + 'import json\n' + 'print("Warning: telemetry disabled", flush=True)\n' + 'print(json.dumps({"type": "text", "sessionID": "s-1", "part": {"text": "output"}}), flush=True)\n') + assert [event['text'] for event in events if event['type'] == 'delta'] == ['output'] + + +def test_plain_cli_output_without_events_reports_the_line(tmp_path, monkeypatch): + with pytest.raises(ProjectError) as caught: + _plain_line_run(tmp_path, monkeypatch, + 'print("Error: no provider configured for this account", flush=True)\n') + assert '未返回可识别的输出' in str(caught.value) + assert 'no provider configured for this account' in str(caught.value) + assert caught.value.status == 502 + assert caught.value.code == 'agent_cli_output_invalid' + + +def test_plain_cli_line_never_leaks_the_api_key(tmp_path, monkeypatch): + with pytest.raises(ProjectError) as caught: + _plain_line_run(tmp_path, monkeypatch, + 'print("auth failed for secret-key-value", flush=True)\n', + config={'id': 'c1', 'modelId': 'm', 'apiKey': 'secret-key-value'}) + assert 'secret-key-value' not in str(caught.value) + assert '[redacted]' in str(caught.value) From aad67c794e65d86fa68a9b51a9a13abb4665894d Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:36:53 +0800 Subject: [PATCH 2/8] ci: retrigger the assistant browser lane 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. From f61397c21d0026b5d8e12c758b04ea2ffdaf17e1 Mon Sep 17 00:00:00 2001 From: dev Date: Thu, 3 Dec 2026 10:14:31 +0800 Subject: [PATCH 3/8] [bugfix] agent: store why a turn failed, and say it in the language shown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 (#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 ` — 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 #557 Refs #567 --- apps/api/src/opendirector_api/agent.py | 7 ++- docs/architecture/agent-runtime.md | 4 ++ .../core/src/opendirector/agent/native.py | 28 +++++---- src/backend/chat.ts | 2 + src/canvas/AssistantPanel.tsx | 5 +- src/canvas/AssistantReply.tsx | 5 +- src/canvas/assistant-experience.css | 4 ++ src/canvas/assistantFailure.ts | 19 ++++++ src/i18n/messages/en-US/assistant.ts | 6 ++ src/i18n/messages/zh-CN/assistant.ts | 6 ++ tests/assistantFailure.test.ts | 30 +++++++++ tests/browser/assistant_activity.mjs | 25 +++++++- tests/test_native_runtime.py | 61 +++++++++++++++++++ 13 files changed, 184 insertions(+), 18 deletions(-) create mode 100644 src/canvas/assistantFailure.ts create mode 100644 tests/assistantFailure.test.ts diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 726697149..645a7c76c 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -758,7 +758,7 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None project_id = chain.project_id message = plan['message'] turn_id = UUID(message['id']) - text, status, error = '', 'complete', None + text, status, error, error_code = '', 'complete', None, None activities: list[dict] = [] edited_documents: dict[str, int] = {} sources: dict = {} @@ -847,6 +847,7 @@ async def renew_session() -> None: except Exception as failure: # Persist partial output even when an integration fails unexpectedly. status = 'interrupted' + error_code = failure.code if isinstance(failure, ProjectError) else 'operation_rejected' if isinstance(failure, ProjectError): error = localized_error_for_language( plan.get('accept_language'), chinese=str(failure), @@ -867,7 +868,9 @@ async def renew_session() -> None: 'model': plan['model'], 'modelIsCliDefault': plan.get('model_is_cli_default', False), 'runtime': message['runtime'], 'thinking': plan['thinking'], 'tools': activities, 'sources': list(sources.values()), - **({'plan': steps} if steps is not None else {})}, conversation_id=chain.conversation_id, + **({'plan': steps} if steps is not None else {}), + **({'error': error, 'errorCode': error_code} if error else {})}, + conversation_id=chain.conversation_id, finish_turn_id=turn_id, edited_documents=edited_documents) except Exception: logger.exception(f'agent.turn.unfinished project_id={project_id} turn_id={turn_id}') diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 2be3abacc..34f84a6dd 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -67,6 +67,10 @@ Default 的模型网关在 `agent-runs/.model.jsonl` 记录实际转发 停止或流连接断开时,适配层终止进程组,Gateway 关闭新调用入口并等待已接受操作结束;API 保存部分回复并释放运行占用。业务操作以各自回执确认,远端生成任务仍通过任务取消命令处理。 +原生 CLI 的 stdout 不保证每行都是事件:它会在事件之间输出警告、横幅或纯文本错误。这类行按诊断记入本轮轨迹(截断到 2000 字符,并替换本轮任务令牌与 provider 密钥),本轮继续;失败信息里保留它的首行,按 200 字符截断;只有整轮没有任何可读事件才判为失败。失败的一轮在助手消息上同时保存解释文字和稳定的 `errorCode`:`agent_cli_login` 表示命令行凭据被拒绝,`agent_cli_exit` 表示进程退出并附带它自己的首行输出,`agent_cli_output_invalid` 表示只有不可读输出而没有事件。界面按当前显示语言重新渲染该代码,事后切换语言仍是同一句解释;原始输出留在轨迹与错误文本里供排查。 + +English summary: a native CLI line is not guaranteed to be an event. Unparseable lines are kept as diagnostics in the turn's trace, truncated to 2000 characters with the turn token and provider key redacted, and the turn continues; only a turn whose output holds no readable event fails. A failed turn stores both an explanatory text and a stable `errorCode` (`agent_cli_login` for a rejected CLI credential, `agent_cli_exit` for a process that exited, carrying its own first output line, and `agent_cli_output_invalid` for unreadable output only), so reopening the project still explains the failure. The UI renders that code in the language currently shown, and the raw output stays in the trace. + ## Agent 来源追溯 Agent 的 `generation.submit` 接受任务时,把本轮标识和工具调用标识写入 Job 自身: diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index 205b176f8..0eba7805e 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -175,20 +175,23 @@ def native_line(line: bytes) -> tuple[dict | None, str | None]: return (raw, None) if isinstance(raw, dict) else (None, text) -def cli_detail(lines: list[str], config) -> str: - """The first plain CLI line, redacted and trimmed, for a failure message.""" - if not lines: - return '' - detail = lines[0][:200] +def redacted(text: str, config, token: str = '') -> str: + """A CLI line without the turn token or the provider key.""" + if token: + text = text.replace(token, '[redacted]') secret = (config or {}).get('apiKey') - if secret: - detail = detail.replace(secret, '[redacted]') - return f' CLI 输出:{detail}' + return text.replace(secret, '[redacted]') if secret else text + + +def cli_detail(lines: list[str], config, token: str = '') -> str: + """The first plain CLI line, redacted and trimmed, for a failure message.""" + return f' CLI 输出:{redacted(lines[0][:200], config, token)}' if lines else '' def text_events(runtime: str, raw: dict) -> list[dict]: if runtime == 'claude' and raw.get('error') == 'authentication_failed': - raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401) + raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401, + code='agent_cli_login') if runtime == 'codex' and raw['type'] == 'error': # Codex also emits this event while reconnecting. Wait for turn.failed or process exit. return [] @@ -372,7 +375,8 @@ async def observe(raw): raw, text = native_line(line) if text is not None: plain.append(text) - await queue.put({'native': {'type': 'diagnostic', 'stdout': text[:2000]}}) + await queue.put({'native': {'type': 'diagnostic', + 'stdout': redacted(text[:2000], config, token)}}) continue if raw is None: continue @@ -395,13 +399,13 @@ async def observe(raw): if await process.wait(): await record_exit() raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。' - f'{cli_detail(plain, config)}', 502) + f'{cli_detail(plain, config, token)}', 502, code='agent_cli_exit') if not parsed and plain: # Nothing usable was streamed: report what the CLI # printed instead of an empty reply. await record_exit() raise ProjectError(f'{runtime} 未返回可识别的输出,请检查 CLI 登录和配置。' - f'{cli_detail(plain, config)}', 502, + f'{cli_detail(plain, config, token)}', 502, code='agent_cli_output_invalid') if reported_session: run.save_native_session(reported_session, selection, diff --git a/src/backend/chat.ts b/src/backend/chat.ts index c75bb3d31..2fb0f7269 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -84,6 +84,8 @@ export interface ChatMessage { text: string; content?: ReferenceContent | null; status: "complete" | "streaming" | "stopped" | "interrupted"; + error?: string; + errorCode?: string; assets?: ChatAsset[]; model?: string | null; modelIsCliDefault?: boolean; diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 58f6f6149..0d4c2a502 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -2,6 +2,7 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; import openDirectorLogo from "../assets/open_director_logo.png"; import { runtimeModels, type AssistantModelSelection, type ChatAsset, type ModelSelections } from "../backend/chat"; import { assistantModelSelection } from "./agentPreferences"; +import { assistantFailureText } from "./assistantFailure"; import { creationClient } from "../backend/creationClient.ts"; import { fingerprint } from "../backend/generation.ts"; import type { BackendModels } from "../backend/models"; @@ -574,7 +575,7 @@ export function AssistantPanel({ ? chat.thinkingNow ? t("assistant.activity.thinking") : t("assistant.activity.replying") - : t("assistant.reply.empty")) + : assistantFailureText(message, t) || t("assistant.reply.empty")) )} {!collapsible && message.role === "assistant" && previous?.role === "user" && @@ -606,7 +607,7 @@ export function AssistantPanel({ )} {message.role === "user" && !!message.assets?.length && } {(message.status === "stopped" || - message.status === "interrupted") && ( + (message.status === "interrupted" && !message.error)) && ( {message.status === "stopped" ? t("assistant.panel.stopped") diff --git a/src/canvas/AssistantReply.tsx b/src/canvas/AssistantReply.tsx index dae6a71f1..580c89cdc 100644 --- a/src/canvas/AssistantReply.tsx +++ b/src/canvas/AssistantReply.tsx @@ -9,6 +9,7 @@ import { AssistantLinkInfo } from "./AssistantLinkInfo"; import { activityProgress, replySections, toolLabel } from "./assistantActivity.ts"; import { assistantToolText } from "./assistantToolText.ts"; import { assistantCitationFormatter } from "./assistantCitations.ts"; +import { assistantFailureText } from "./assistantFailure"; import { defaultTranslate } from "./assistantTranslate.ts"; import { chatTurnTiming } from "./turnTiming.ts"; import { hidePartialSuggestionMarker, parseSuggestedReplies } from "./suggestedReplies.ts"; @@ -185,7 +186,9 @@ export const AssistantReply = memo(function AssistantReply({ {!message.text && !message.tools?.length && message.status !== "streaming" && ( -

{t("assistant.reply.empty")}

+

+ {assistantFailureText(message, t) || t("assistant.reply.empty")} +

)} {!!message.text && message.status !== "streaming" && (
diff --git a/src/canvas/assistant-experience.css b/src/canvas/assistant-experience.css index 45178aecb..8ed735a23 100644 --- a/src/canvas/assistant-experience.css +++ b/src/canvas/assistant-experience.css @@ -196,6 +196,10 @@ color: var(--chat-muted); font-size: 12px; } + +.cw-chat-progress.is-failed { + color: #df9a9a; +} .cw-chat-waiting { display: inline-flex; align-items: center; gap: 3px; } .cw-chat-waiting i { width: 4px; height: 4px; border-radius: 50%; background: currentColor; animation: cw-chat-wait 1.2s ease-in-out infinite; } .cw-chat-waiting i:nth-child(2) { animation-delay: 0.15s; } diff --git a/src/canvas/assistantFailure.ts b/src/canvas/assistantFailure.ts new file mode 100644 index 000000000..181a35ec0 --- /dev/null +++ b/src/canvas/assistantFailure.ts @@ -0,0 +1,19 @@ +import type { ChatMessage } from "../backend/chat"; +import type { Translate } from "../i18n/I18nProvider.tsx"; +import type { MessageKey } from "../i18n/types.ts"; +import { defaultTranslate } from "./assistantTranslate.ts"; + +const BY_CODE: Record = { + agent_cli_login: "assistant.failure.login", + agent_cli_exit: "assistant.failure.exit", + agent_cli_output_invalid: "assistant.failure.output", +}; + +export function assistantFailureText( + message: Pick, + t: Translate = defaultTranslate, +): string { + const key = message.errorCode ? BY_CODE[message.errorCode] : undefined; + if (key) return t(key); + return message.error ?? ""; +} diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts index b4166f972..373b48496 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -134,6 +134,12 @@ export const assistant = { "assistant.reply.task": "Task: ", "assistant.reply.plan": "Execution plan", "assistant.reply.empty": "This reply produced no content.", + "assistant.failure.login": + "The Agent CLI is not signed in, or its credential was rejected. Sign in with that CLI, or choose another runtime in the Agent panel.", + "assistant.failure.exit": + "The Agent CLI exited before this turn finished. Check its sign-in and configuration; this turn keeps its output in the trace.", + "assistant.failure.output": + "The Agent CLI returned output this app cannot read, so this turn has no reply. Check its version and this turn's trace, or choose another runtime.", "assistant.reply.copy": "Copy", "assistant.reply.suggestions": "Suggested replies", "assistant.reply.useSuggestion": "Use this suggestion as the draft text", diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts index d5530c54b..04d72dafc 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -133,6 +133,12 @@ export const assistant = { "assistant.reply.task": "任务:", "assistant.reply.plan": "执行计划", "assistant.reply.empty": "本次回复未生成内容。", + "assistant.failure.login": + "Agent 命令行未登录或凭据被拒绝:先用该命令行登录,或在助手面板改用其他运行时。", + "assistant.failure.exit": + "Agent 命令行在本轮结束前退出:请检查其登录与配置,原始输出见本轮轨迹。", + "assistant.failure.output": + "Agent 命令行返回了无法识别的内容,本轮没有回复:请检查其版本与本轮轨迹,或改用其他运行时。", "assistant.reply.copy": "复制", "assistant.reply.suggestions": "建议回复", "assistant.reply.useSuggestion": "用这条建议填写草稿", diff --git a/tests/assistantFailure.test.ts b/tests/assistantFailure.test.ts new file mode 100644 index 000000000..2bb55cef3 --- /dev/null +++ b/tests/assistantFailure.test.ts @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { getActiveLocale, setActiveLocale } from "../src/i18n/messages.ts"; +import { assistantFailureText } from "../src/canvas/assistantFailure.ts"; +import { defaultTranslate as tNow } from "../src/canvas/assistantTranslate.ts"; + +const original = getActiveLocale(); + +function inLocale(locale: typeof original, run: () => T): T { + setActiveLocale(locale); + try { return run(); } finally { setActiveLocale(original); } +} + +test("translates a stored failure code in the language shown now", () => { + const message = { error: "Claude Code 登录已过期…", errorCode: "agent_cli_login" }; + const chinese = inLocale("zh-CN", () => assistantFailureText(message, tNow)); + const english = inLocale("en-US", () => assistantFailureText(message, tNow)); + assert.equal(chinese, inLocale("zh-CN", () => tNow("assistant.failure.login"))); + assert.equal(english, inLocale("en-US", () => tNow("assistant.failure.login"))); + assert.notEqual(chinese, english); +}); + +test("keeps the stored reason for a code the interface does not translate", () => { + assert.equal(assistantFailureText({ error: "Agent 执行失败,请检查后端日志。", errorCode: "operation_rejected" }, tNow), + "Agent 执行失败,请检查后端日志。"); +}); + +test("a turn without a stored failure has nothing to say", () => { + assert.equal(assistantFailureText({}, tNow), ""); +}); diff --git a/tests/browser/assistant_activity.mjs b/tests/browser/assistant_activity.mjs index d51eb4b35..973ec6b3c 100644 --- a/tests/browser/assistant_activity.mjs +++ b/tests/browser/assistant_activity.mjs @@ -230,6 +230,29 @@ try { await modal.getByRole('button', { name: locale === 'zh-CN' ? '关闭' : 'Close', exact: true }).click(); } + const failed = { + id: "reply", role: "assistant", status: "interrupted", text: "", + error: "ignored when the code is known", errorCode: "agent_cli_login", + }; + for (const [locale, expected] of [ + ["zh-CN", "Agent 命令行未登录或凭据被拒绝"], + ["en-US", "The Agent CLI is not signed in"], + ]) { + await page.evaluate(({ value, locale }) => window.replyFixture.render(value, false, locale), { value: failed, locale }); + const line = page.locator(".cw-chat-progress.is-failed"); + await line.waitFor(); + const shown = await line.innerText(); + assert.ok(shown.includes(expected), shown); + assert.equal(shown.includes(locale === "zh-CN" ? "本次回复未生成内容" : "produced no content"), false); + } + await render({ ...failed, status: "complete", errorCode: "agent_cli_login" }); + assert.ok((await page.locator(".cw-chat-progress.is-failed").innerText()).includes("The Agent CLI is not signed in")); + await render({ ...failed, status: "interrupted", error: "Agent 执行失败,请检查后端日志。", errorCode: undefined }); + assert.equal(await page.locator(".cw-chat-progress.is-failed").innerText(), "Agent 执行失败,请检查后端日志。"); + await render({ id: "reply", role: "assistant", status: "interrupted", text: "" }); + assert.equal(await page.locator(".cw-chat-progress").innerText(), "This reply produced no content."); + await render(complete); + // Long URLs, geometry and keyboard behavior in both theme presentations. const longSource = { ...sourceA, url: 'https://example.test/' + 'long-path-'.repeat(70) + '?q=full-address' }; await page.setViewportSize({ width: 390, height: 800 }); @@ -284,7 +307,7 @@ try { await page.locator('.cw-chat-message-actions').click(); await modal.waitFor({ state: 'detached' }); assert.deepEqual(errors, []); - console.log(JSON.stringify({ passed: true, checks: ["1000 collapsed calls", "lazy pagination", "stable disclosure state", "muted failure with expandable details", "public messages", "plan and thinking", "four citation groups", "copy and reopen", "partial streaming citation", "bilingual missing sources", "card border and top-right close", "dark and light long URLs", "keyboard and focus restoration", "copy errors and opening links"] })); + console.log(JSON.stringify({ passed: true, checks: ["1000 collapsed calls", "lazy pagination", "stable disclosure state", "muted failure with expandable details", "public messages", "plan and thinking", "four citation groups", "copy and reopen", "partial streaming citation", "bilingual missing sources", "card border and top-right close", "dark and light long URLs", "keyboard and focus restoration", "copy errors and opening links", "stored failure reason"] })); } finally { await page.evaluate(() => window.replyFixture?.unmount()).catch(() => {}); await browser.close(); diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index f42f64f29..8a08f59ea 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -901,3 +901,64 @@ def test_plain_cli_line_never_leaks_the_api_key(tmp_path, monkeypatch): config={'id': 'c1', 'modelId': 'm', 'apiKey': 'secret-key-value'}) assert 'secret-key-value' not in str(caught.value) assert '[redacted]' in str(caught.value) + + +EXITING_CLI = '''import sys +sys.stdin.read() +print('error: invalid provider configuration') +sys.exit(1) +''' + +QUIET_EXIT_CLI = '''import sys +sys.stdin.read() +print('error: missing ANTHROPIC_API_KEY') +''' + +REJECTED_LOGIN = '''import json, sys +sys.stdin.read() +print(json.dumps({'type':'assistant','error':'authentication_failed', + 'message':{'content':[]}})) +''' + + +def broken_cli_turn(tmp_path, monkeypatch, script, runtime='opencode'): + local = LocalProjects(tmp_path) + source = tmp_path / 'broken_cli.py' + source.write_text(script) + monkeypatch.setattr(native, 'command', + lambda *args, **kwargs: ([sys.executable, str(source)], dict(os.environ))) + monkeypatch.setattr(native, 'executable', lambda _: sys.executable) + with TestClient(create_app(local), headers={'X-OpenDirector-Request': '1', + 'X-OpenDirector-Session': str(uuid4())}) as client: + path = project(client) + response = client.post(path + '/assistant/turns', json={'id': str(uuid4()), + 'runtime': runtime, 'runtimeModel': 'test-model', 'text': 'hello'}) + events = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith('data: ')] + return path, client, events + + +def test_a_cli_that_exits_stores_its_own_reason(tmp_path, monkeypatch): + path, client, events = broken_cli_turn(tmp_path, monkeypatch, EXITING_CLI) + reply = events[-1]['conversation']['messages'][-1] + assert reply['errorCode'] == 'agent_cli_exit', reply + assert 'invalid provider configuration' in reply['error'] + reloaded = client.get(path + '/assistant').json()['messages'][-1] + assert reloaded['error'] == reply['error'] + assert reloaded['errorCode'] == 'agent_cli_exit' + + +def test_a_cli_with_no_readable_event_stores_its_own_reason(tmp_path, monkeypatch): + path, client, events = broken_cli_turn(tmp_path, monkeypatch, QUIET_EXIT_CLI) + reply = events[-1]['conversation']['messages'][-1] + assert reply['errorCode'] == 'agent_cli_output_invalid', reply + assert 'missing ANTHROPIC_API_KEY' in reply['error'] + + +def test_a_rejected_login_is_stored_with_its_cause(tmp_path, monkeypatch): + path, client, events = broken_cli_turn(tmp_path, monkeypatch, REJECTED_LOGIN, runtime='claude') + reply = events[-1]['conversation']['messages'][-1] + assert reply['errorCode'] == 'agent_cli_login', reply + assert reply['text'] == '' + reloaded = client.get(path + '/assistant').json()['messages'][-1] + assert reloaded['errorCode'] == 'agent_cli_login' + assert reloaded['error'] == reply['error'] From 4dbefee38d1c208705af3cccac801032e48715c4 Mon Sep 17 00:00:00 2001 From: dev Date: Thu, 3 Dec 2026 10:16:37 +0800 Subject: [PATCH 4/8] fix(agent): give every agent CLI code its own English text 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. --- apps/api/src/opendirector_api/localization.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index f263900ff..c4ab8f50d 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -27,7 +27,9 @@ 'keyframe_needs_reference': 'Keyframes also need at least one ordinary reference image or video.', 'keyframe_time': 'Each keyframe needs its own time, earlier than the end of the video and at least 1/24 second from the others.', 'keyframe_image': 'A keyframe must be a PNG, JPEG or WebP image within the size limit.', - 'agent_cli_output_invalid': 'The agent CLI returned no usable output. Check its login and configuration.', + 'agent_cli_login': 'The Agent CLI is not signed in, or its credential was rejected. Sign in with that CLI, or choose another runtime in the Agent panel.', + 'agent_cli_exit': 'The Agent CLI exited before this turn finished. Check its sign-in and configuration; this turn\'s trace keeps its output.', + 'agent_cli_output_invalid': 'The Agent CLI produced no usable output. Check its sign-in and configuration; this turn\'s trace keeps its output.', 'higgsfield_model': 'Choose MAGI-2 with the official Higgsfield Open API address.', 'higgsfield_key': 'Enter your Higgsfield Open KEY_ID:KEY_SECRET.', 'higgsfield_output': 'MAGI-2 supports 1080p and whole-second durations from 4 to 30 seconds.', @@ -235,7 +237,7 @@ def localized_error_for_language( if generic and status in {413, 502, 504}: return ENGLISH_BY_STATUS[status] specific = None if code == "operation_rejected" else ENGLISH_BY_CODE.get(code) - if code == 'agent_cli_output_invalid': + if code.startswith('agent_cli_'): detail = chinese.split('CLI 输出:', 1)[-1].strip() if 'CLI 输出:' in chinese else '' return specific + (' CLI output: ' + detail if detail else '') if code == 'voice_provider_error': From f3225e492c9c40c0bbaa1d0746d68bbf041963f8 Mon Sep 17 00:00:00 2001 From: Zhangbo-cn Date: Fri, 4 Dec 2026 15:33:11 +0800 Subject: [PATCH 5/8] [fix] assistant: keep the failure line readable on the light sheet 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. --- src/canvas/assistant-experience.css | 2 +- src/canvas/assistant-panel.css | 2 + tests/browser/assistant_activity.mjs | 49 +++++++++++++++++++- tests/browser/assistant_activity_fixture.tsx | 1 + 4 files changed, 52 insertions(+), 2 deletions(-) diff --git a/src/canvas/assistant-experience.css b/src/canvas/assistant-experience.css index 8ed735a23..eca958728 100644 --- a/src/canvas/assistant-experience.css +++ b/src/canvas/assistant-experience.css @@ -198,7 +198,7 @@ } .cw-chat-progress.is-failed { - color: #df9a9a; + color: var(--chat-failure, #df9a9a); } .cw-chat-waiting { display: inline-flex; align-items: center; gap: 3px; } .cw-chat-waiting i { width: 4px; height: 4px; border-radius: 50%; background: currentColor; animation: cw-chat-wait 1.2s ease-in-out infinite; } diff --git a/src/canvas/assistant-panel.css b/src/canvas/assistant-panel.css index ccb538459..07b13c2b9 100644 --- a/src/canvas/assistant-panel.css +++ b/src/canvas/assistant-panel.css @@ -4,6 +4,7 @@ --chat-surface: #242424; --chat-text: #ededee; --chat-muted: #858589; + --chat-failure: #df9a9a; --chat-border: #ffffff14; --chat-hover: #ffffff0a; position: absolute; @@ -763,6 +764,7 @@ --chat-surface: #eef0f4; --chat-text: #30343c; --chat-muted: #757b86; + --chat-failure: #9a4d36; --chat-border: #dfe2e7; --chat-hover: #e9edf3; box-shadow: 0 12px 40px #30374420; diff --git a/tests/browser/assistant_activity.mjs b/tests/browser/assistant_activity.mjs index 973ec6b3c..9862e1de2 100644 --- a/tests/browser/assistant_activity.mjs +++ b/tests/browser/assistant_activity.mjs @@ -251,6 +251,53 @@ try { assert.equal(await page.locator(".cw-chat-progress.is-failed").innerText(), "Agent 执行失败,请检查后端日志。"); await render({ id: "reply", role: "assistant", status: "interrupted", text: "" }); assert.equal(await page.locator(".cw-chat-progress").innerText(), "This reply produced no content."); + + const failureContrast = async (theme) => { + await page.evaluate((theme) => { + document.documentElement.dataset.theme = theme; + const host = document.getElementById('activity-test'); + if (!host.parentElement.classList.contains('cw-assistant-panel')) { + const panel = document.createElement('div'); + panel.className = 'cw-assistant-panel'; + host.after(panel); + panel.append(host); + } + }, theme); + await page.locator('.cw-chat-progress.is-failed').waitFor(); + return page.evaluate(() => { + const channels = (value) => { + if (value.startsWith('#')) { + const hex = value.slice(1); + const full = hex.length === 3 ? [...hex].map((digit) => digit + digit).join('') : hex; + return [0, 2, 4].map((index) => parseInt(full.slice(index, index + 2), 16)); + } + return value.match(/\d+/g).slice(0, 3).map(Number); + }; + const luminance = (value) => { + const [r, g, b] = channels(value).map((channel) => { + const scaled = channel / 255; + return scaled <= 0.04045 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; + }; + const line = document.querySelector('.cw-chat-progress.is-failed'); + const panel = line.closest('.cw-assistant-panel'); + const sheet = getComputedStyle(panel).getPropertyValue('--chat-background').trim(); + const [front, back] = [luminance(getComputedStyle(line).color), luminance(sheet)]; + return (Math.max(front, back) + 0.05) / (Math.min(front, back) + 0.05); + }); + }; + await render(failed); + const measured = {}; + for (const theme of ['dark', 'light']) measured[theme] = await failureContrast(theme); + assert.ok(measured.dark >= 4.5, `dark failure contrast ${measured.dark}`); + assert.ok(measured.light >= 4.5, `light failure contrast ${measured.light}`); + await page.evaluate(() => { + delete document.documentElement.dataset.theme; + const host = document.getElementById('activity-test'); + document.body.append(host); + host.parentElement.querySelectorAll('.cw-assistant-panel').forEach((panel) => panel.remove()); + }); await render(complete); // Long URLs, geometry and keyboard behavior in both theme presentations. @@ -307,7 +354,7 @@ try { await page.locator('.cw-chat-message-actions').click(); await modal.waitFor({ state: 'detached' }); assert.deepEqual(errors, []); - console.log(JSON.stringify({ passed: true, checks: ["1000 collapsed calls", "lazy pagination", "stable disclosure state", "muted failure with expandable details", "public messages", "plan and thinking", "four citation groups", "copy and reopen", "partial streaming citation", "bilingual missing sources", "card border and top-right close", "dark and light long URLs", "keyboard and focus restoration", "copy errors and opening links", "stored failure reason"] })); + console.log(JSON.stringify({ passed: true, checks: ["1000 collapsed calls", "lazy pagination", "stable disclosure state", "muted failure with expandable details", "public messages", "plan and thinking", "four citation groups", "copy and reopen", "partial streaming citation", "bilingual missing sources", "card border and top-right close", "dark and light long URLs", "keyboard and focus restoration", "copy errors and opening links", "stored failure reason", "failure contrast on both sheets"] })); } finally { await page.evaluate(() => window.replyFixture?.unmount()).catch(() => {}); await browser.close(); diff --git a/tests/browser/assistant_activity_fixture.tsx b/tests/browser/assistant_activity_fixture.tsx index ab9512273..171c72622 100644 --- a/tests/browser/assistant_activity_fixture.tsx +++ b/tests/browser/assistant_activity_fixture.tsx @@ -6,6 +6,7 @@ import { setActiveLocale, translate } from "../../src/i18n/messages"; import type { Translate } from "../../src/i18n/I18nProvider"; import type { Locale } from "../../src/i18n/types"; import "../../src/canvas/assistant-experience.css"; +import "../../src/canvas/assistant-panel.css"; export function mountReply(element: HTMLElement) { setActiveLocale("en-US"); From 2ee93457341c03cf8f7a1dc8b759d437c4ad98b6 Mon Sep 17 00:00:00 2001 From: Zhangbo-cn Date: Fri, 4 Dec 2026 16:12:51 +0800 Subject: [PATCH 6/8] [fix] agent: redact CLI diagnostics before trimming them 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. --- .../core/src/opendirector/agent/native.py | 50 ++++++++++++------- tests/test_native_runtime.py | 47 +++++++++++++++++ 2 files changed, 78 insertions(+), 19 deletions(-) diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index 0eba7805e..eb9663d6e 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -183,28 +183,41 @@ def redacted(text: str, config, token: str = '') -> str: return text.replace(secret, '[redacted]') if secret else text +def limited(text: str, config, token: str = '', limit: int = 200) -> str: + """The text redacted before it is trimmed, so a cut never splits a secret.""" + return redacted(text, config, token)[:limit] + + def cli_detail(lines: list[str], config, token: str = '') -> str: """The first plain CLI line, redacted and trimmed, for a failure message.""" - return f' CLI 输出:{redacted(lines[0][:200], config, token)}' if lines else '' + return f' CLI 输出:{limited(lines[0], config, token)}' if lines else '' + + +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) def text_events(runtime: str, raw: dict) -> list[dict]: + kind = raw.get('type') if runtime == 'claude' and raw.get('error') == 'authentication_failed': raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401, code='agent_cli_login') - if runtime == 'codex' and raw['type'] == 'error': + if runtime == 'codex' and kind == 'error': # Codex also emits this event while reconnecting. Wait for turn.failed or process exit. return [] - if raw['type'] in {'error', 'turn.failed'} or raw['type'] == 'result' and raw.get('is_error'): + if kind in {'error', 'turn.failed'} or kind == 'result' and raw.get('is_error'): raise ProjectError(f'{runtime} 运行失败,请检查登录、模型或原生轨迹。', 502) - if runtime == 'opencode' and raw['type'] == 'text': - return [{'type': 'delta', 'text': raw['part']['text']}] - if runtime == 'codex' and raw['type'] == 'item.completed' and raw['item']['type'] == 'agent_message': - return [{'type': 'delta', 'text': raw['item']['text']}] + if runtime == 'opencode' and kind == 'text': + return [{'type': 'delta', 'text': (raw.get('part') or {}).get('text', '')}] + if runtime == 'codex' and kind == 'item.completed' and (raw.get('item') or {}).get('type') == 'agent_message': + return [{'type': 'delta', 'text': (raw.get('item') or {}).get('text', '')}] if runtime == 'codex' and (sources := search_sources(raw)): return [{'type': 'sources', 'sources': sources}] - if runtime == 'claude' and raw['type'] == 'assistant': - return [{'type': 'delta', 'text': part['text']} for part in raw['message']['content'] if part['type'] == 'text'] + if runtime == 'claude' and kind == 'assistant': + return [{'type': 'delta', 'text': part['text']} + for part in (raw.get('message') or {}).get('content') or [] + if isinstance(part, dict) and part.get('type') == 'text'] return [] @@ -336,7 +349,9 @@ async def stream(self, run: RunContext, gateway: ToolGateway): async def drain_stderr(): while chunk := await process.stderr.read(4096): stderr_tail.extend(chunk) - del stderr_tail[:-8192] + if len(stderr_tail) > 8192: + edge = stderr_tail.rfind(b'\n', 0, len(stderr_tail) - 8192) + del stderr_tail[:edge + 1 if edge >= 0 else len(stderr_tail) - 8192] stderr_task = asyncio.create_task(drain_stderr()) if runtime == 'antigravity': instructions = '' if session_id else runtime_instructions(runtime) + '\n' + antigravity.APPENDIX + '\n' @@ -349,9 +364,7 @@ async def drain_stderr(): process.stdin.close() async def record_exit(): await stderr_task - diagnostic = stderr_tail.decode('utf-8', errors='replace').replace(token, '[redacted]') - if config and config.get('apiKey'): - diagnostic = diagnostic.replace(config['apiKey'], '[redacted]') + diagnostic = limited(stderr_tail.decode('utf-8', errors='replace'), config, token, 8192) await queue.put({'native': {'type': 'diagnostic', 'stderr': diagnostic, 'exitCode': process.returncode}}) async def output(): @@ -373,12 +386,13 @@ async def observe(raw): else: while line := await process.stdout.readline(): raw, text = native_line(line) - if text is not None: + if raw is None or not event_like(raw): + 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) await queue.put({'native': {'type': 'diagnostic', - 'stdout': redacted(text[:2000], config, token)}}) - continue - if raw is None: + 'stdout': limited(text, config, token, 2000)}}) continue parsed = True previous_session = reported_session @@ -401,8 +415,6 @@ async def observe(raw): raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。' f'{cli_detail(plain, config, token)}', 502, code='agent_cli_exit') if not parsed and plain: - # Nothing usable was streamed: report what the CLI - # printed instead of an empty reply. await record_exit() raise ProjectError(f'{runtime} 未返回可识别的输出,请检查 CLI 登录和配置。' f'{cli_detail(plain, config, token)}', 502, diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 1a7f864ff..48cdb19d4 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -956,6 +956,38 @@ def test_plain_cli_line_never_leaks_the_api_key(tmp_path, monkeypatch): assert '[redacted]' in str(caught.value) +def test_a_json_log_line_before_events_keeps_the_turn(tmp_path, monkeypatch): + events = _plain_line_run(tmp_path, monkeypatch, + 'import json\n' + 'print(json.dumps({"level": "info", "message": "telemetry disabled"}), flush=True)\n' + 'print(json.dumps({"type": "text", "sessionID": "s-1", "part": {"text": "output"}}), flush=True)\n') + assert [event['text'] for event in events if event['type'] == 'delta'] == ['output'] + + +def test_a_truncated_plain_line_is_redacted_before_it_is_trimmed(tmp_path, monkeypatch): + with pytest.raises(ProjectError) as caught: + _plain_line_run(tmp_path, monkeypatch, + 'print("x" * 190 + "secret-key-value", flush=True)\n', + config={'id': 'c1', 'modelId': 'm', 'apiKey': 'secret-key-value'}) + assert 'secret-key' not in str(caught.value) + assert '[redacted]' in str(caught.value) + + +def test_the_stored_trace_redacts_a_truncated_stderr(tmp_path, monkeypatch): + source = ('import sys\n' + 'sys.stdin.read()\n' + 'sys.stderr.write("y" * 8186 + "\\n" + "secret-key-value" + "\\n" + "z" * 8180)\n' + 'sys.exit(1)\n') + with pytest.raises(ProjectError): + _plain_line_run(tmp_path, monkeypatch, source, + config={'id': 'c1', 'modelId': 'm', 'apiKey': 'secret-key-value'}) + [trace] = (tmp_path / 'agent-runs').glob('*.opencode.jsonl') + stored = trace.read_text(encoding='utf-8') + assert '"diagnostic"' in stored + assert '[redacted]' in stored + assert 'key-value' not in stored + + EXITING_CLI = '''import sys sys.stdin.read() print('error: invalid provider configuration') @@ -967,6 +999,11 @@ def test_plain_cli_line_never_leaks_the_api_key(tmp_path, monkeypatch): print('error: missing ANTHROPIC_API_KEY') ''' +LOG_ONLY_CLI = '''import json, sys +sys.stdin.read() +print(json.dumps({'level': 'error', 'message': 'provider unavailable'}), flush=True) +''' + REJECTED_LOGIN = '''import json, sys sys.stdin.read() print(json.dumps({'type':'assistant','error':'authentication_failed', @@ -1007,6 +1044,16 @@ def test_a_cli_with_no_readable_event_stores_its_own_reason(tmp_path, monkeypatc assert 'missing ANTHROPIC_API_KEY' in reply['error'] +def test_a_cli_that_prints_only_log_json_stores_its_own_reason(tmp_path, monkeypatch): + path, client, events = broken_cli_turn(tmp_path, monkeypatch, LOG_ONLY_CLI) + reply = events[-1]['conversation']['messages'][-1] + assert reply['errorCode'] == 'agent_cli_output_invalid', reply + assert 'provider unavailable' in reply['error'] + reloaded = client.get(path + '/assistant').json()['messages'][-1] + assert reloaded['error'] == reply['error'] + assert reloaded['errorCode'] == 'agent_cli_output_invalid' + + def test_a_rejected_login_is_stored_with_its_cause(tmp_path, monkeypatch): path, client, events = broken_cli_turn(tmp_path, monkeypatch, REJECTED_LOGIN, runtime='claude') reply = events[-1]['conversation']['messages'][-1] From c2621591330298686518bc2bd7a13245ece140e2 Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:45:43 +0800 Subject: [PATCH 7/8] [bugfix] agent: recognize harness events by runtime contract 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. --- docs/architecture/agent-runtime.md | 4 +- .../core/src/opendirector/agent/native.py | 72 ++++++++++++++----- tests/test_native_runtime.py | 55 +++++++++++++- 3 files changed, 110 insertions(+), 21 deletions(-) diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 34f84a6dd..db920dc35 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -67,9 +67,9 @@ Default 的模型网关在 `agent-runs/.model.jsonl` 记录实际转发 停止或流连接断开时,适配层终止进程组,Gateway 关闭新调用入口并等待已接受操作结束;API 保存部分回复并释放运行占用。业务操作以各自回执确认,远端生成任务仍通过任务取消命令处理。 -原生 CLI 的 stdout 不保证每行都是事件:它会在事件之间输出警告、横幅或纯文本错误。这类行按诊断记入本轮轨迹(截断到 2000 字符,并替换本轮任务令牌与 provider 密钥),本轮继续;失败信息里保留它的首行,按 200 字符截断;只有整轮没有任何可读事件才判为失败。失败的一轮在助手消息上同时保存解释文字和稳定的 `errorCode`:`agent_cli_login` 表示命令行凭据被拒绝,`agent_cli_exit` 表示进程退出并附带它自己的首行输出,`agent_cli_output_invalid` 表示只有不可读输出而没有事件。界面按当前显示语言重新渲染该代码,事后切换语言仍是同一句解释;原始输出留在轨迹与错误文本里供排查。 +原生 CLI 的 stdout 不保证每行都是事件:它会在事件之间输出警告、横幅、纯文本错误或结构化日志。事件按各运行时自己的类型集合与必需字段识别,其余行按诊断记入本轮轨迹(截断到 2000 字符,并替换本轮任务令牌与 provider 密钥),本轮继续;失败信息里保留它的首行,按 200 字符截断;只有整轮没有任何可读事件才判为失败。失败的一轮在助手消息上同时保存解释文字和稳定的 `errorCode`:`agent_cli_login` 表示命令行凭据被拒绝,`agent_cli_exit` 表示进程退出并附带它自己的首行输出,`agent_cli_output_invalid` 表示只有不可读输出而没有事件。界面按当前显示语言重新渲染该代码,事后切换语言仍是同一句解释;原始输出留在轨迹与错误文本里供排查。 -English summary: a native CLI line is not guaranteed to be an event. Unparseable lines are kept as diagnostics in the turn's trace, truncated to 2000 characters with the turn token and provider key redacted, and the turn continues; only a turn whose output holds no readable event fails. A failed turn stores both an explanatory text and a stable `errorCode` (`agent_cli_login` for a rejected CLI credential, `agent_cli_exit` for a process that exited, carrying its own first output line, and `agent_cli_output_invalid` for unreadable output only), so reopening the project still explains the failure. The UI renders that code in the language currently shown, and the raw output stays in the trace. +English summary: a native CLI line is not guaranteed to be an event. Events are recognized by each runtime's own type set and required fields; other lines are kept as diagnostics in the turn's trace, truncated to 2000 characters with the turn token and provider key redacted, and the turn continues; only a turn whose output holds no readable event fails. A failed turn stores both an explanatory text and a stable `errorCode` (`agent_cli_login` for a rejected CLI credential, `agent_cli_exit` for a process that exited, carrying its own first output line, and `agent_cli_output_invalid` for unreadable output only), so reopening the project still explains the failure. The UI renders that code in the language currently shown, and the raw output stays in the trace. ## Agent 来源追溯 diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index eb9663d6e..6de49d7ee 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -160,11 +160,6 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None def native_line(line: bytes) -> tuple[dict | None, str | None]: - """Split one CLI stdout line into a JSON event, plain text, or nothing. - - Harnesses occasionally print human-readable warnings or startup errors on - stdout; that must stay diagnosable instead of ending the turn. - """ text = line.decode('utf-8', errors='replace').strip() if not text: return None, None @@ -176,7 +171,6 @@ def native_line(line: bytes) -> tuple[dict | None, str | None]: def redacted(text: str, config, token: str = '') -> str: - """A CLI line without the turn token or the provider key.""" if token: text = text.replace(token, '[redacted]') secret = (config or {}).get('apiKey') @@ -184,18 +178,49 @@ def redacted(text: str, config, token: str = '') -> str: def limited(text: str, config, token: str = '', limit: int = 200) -> str: - """The text redacted before it is trimmed, so a cut never splits a secret.""" return redacted(text, config, token)[:limit] def cli_detail(lines: list[str], config, token: str = '') -> str: - """The first plain CLI line, redacted and trimmed, for a failure message.""" return f' CLI 输出:{limited(lines[0], config, token)}' if lines else '' -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) +EVENT_TYPES = { + 'opencode': {'step_start', 'step_finish', 'tool_use', 'text', 'reasoning', + 'error', 'diagnostic', 'session'}, + 'codex': {'thread.started', 'turn.started', 'turn.completed', 'turn.failed', + 'item.started', 'item.updated', 'item.completed', 'error'}, + 'claude': {'system', 'assistant', 'user', 'result', 'stream_event', 'error'}, + 'pi': {'session', 'agent_start', 'agent_end', 'turn_start', 'turn_end', + 'message_start', 'message_update', 'message_end', 'tool_execution_start', + 'tool_execution_update', 'tool_execution_end', 'compaction_start', + 'compaction_end', 'auto_retry_start', 'auto_retry_end'}, + 'antigravity': {'init', 'step_update', 'result', 'error'}, +} + + +def event_like(runtime: str, raw: dict) -> bool: + kind = raw.get('event') if runtime == 'antigravity' else raw.get('type') + if not isinstance(kind, str): + return False + kinds = EVENT_TYPES.get(runtime) + if kinds is None: + return True + if kind not in kinds: + return False + if runtime == 'codex' and kind.startswith('item.'): + return isinstance(raw.get('item'), dict) + if runtime == 'claude' and kind == 'assistant': + return isinstance((raw.get('message') or {}).get('content'), list) + if runtime == 'opencode' and kind == 'text': + return isinstance(raw.get('part'), dict) + if runtime == 'pi' and kind.startswith('message_'): + return isinstance(raw.get('message'), dict) + if runtime == 'antigravity' and kind == 'step_update': + return isinstance(raw.get('step_update'), dict) + if runtime == 'antigravity' and kind == 'result': + return isinstance(raw.get('result'), dict) + return True def text_events(runtime: str, raw: dict) -> list[dict]: @@ -345,13 +370,24 @@ async def stream(self, run: RunContext, gateway: ToolGateway): if run.runtime == 'default': raise ProjectError(BUNDLED_INSTALL_ERROR, 503, code='agent_dependency_unavailable') from error raise - stderr_tail = bytearray() + stderr_lines = [] + stderr_bytes = 0 async def drain_stderr(): + nonlocal stderr_bytes + pending = b'' while chunk := await process.stderr.read(4096): - stderr_tail.extend(chunk) - if len(stderr_tail) > 8192: - edge = stderr_tail.rfind(b'\n', 0, len(stderr_tail) - 8192) - del stderr_tail[:edge + 1 if edge >= 0 else len(stderr_tail) - 8192] + pending += chunk + while (edge := pending.find(b'\n')) >= 0: + line, pending = pending[:edge], pending[edge + 1:] + text = redacted(line.decode('utf-8', errors='replace'), config, token) + '\n' + stderr_lines.append(text) + stderr_bytes += len(text) + while stderr_bytes > 8192 and len(stderr_lines) > 1: + stderr_bytes -= len(stderr_lines.pop(0)) + if len(pending) > 8192: + pending = b'' + if pending: + stderr_lines.append(redacted(pending.decode('utf-8', errors='replace'), config, token)) stderr_task = asyncio.create_task(drain_stderr()) if runtime == 'antigravity': instructions = '' if session_id else runtime_instructions(runtime) + '\n' + antigravity.APPENDIX + '\n' @@ -364,7 +400,7 @@ async def drain_stderr(): process.stdin.close() async def record_exit(): await stderr_task - diagnostic = limited(stderr_tail.decode('utf-8', errors='replace'), config, token, 8192) + diagnostic = ''.join(stderr_lines)[-8192:] await queue.put({'native': {'type': 'diagnostic', 'stderr': diagnostic, 'exitCode': process.returncode}}) async def output(): @@ -386,7 +422,7 @@ async def observe(raw): else: while line := await process.stdout.readline(): raw, text = native_line(line) - if raw is None or not event_like(raw): + if raw is None or not event_like(runtime, raw): if text is None and raw is None: continue text = text if text is not None else json.dumps(raw, ensure_ascii=False) diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 48cdb19d4..670411a67 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -329,6 +329,21 @@ def test_codex_reconnect_does_not_end_turn(): native.text_events('codex', {'type': 'turn.failed'}) +def test_an_event_matches_its_runtime_contract(): + assert native.event_like('opencode', {'type': 'text', 'part': {'text': ''}}) + assert not native.event_like('opencode', {'type': 'text'}) + assert not native.event_like('opencode', {'type': 'info', 'message': 'telemetry disabled'}) + assert native.event_like('codex', {'type': 'item.completed', 'item': { + 'type': 'agent_message', 'text': ''}}) + assert not native.event_like('codex', {'type': 'item.completed'}) + assert native.event_like('claude', {'type': 'assistant', 'message': {'content': []}}) + assert not native.event_like('claude', {'type': 'assistant'}) + assert native.event_like('pi', {'type': 'message_end', 'message': {'role': 'assistant'}}) + assert not native.event_like('pi', {'type': 'message_end'}) + assert native.event_like('antigravity', {'event': 'result', 'result': {}}) + assert not native.event_like('antigravity', {'event': 'heartbeat'}) + + @pytest.mark.parametrize('identities', [['unexpected'], ['original', 'unexpected']]) def test_opencode_resume_rejects_unexpected_or_changing_session_ids(tmp_path, monkeypatch, identities): from opendirector.infrastructure.creation_projects import CreationProjects @@ -964,6 +979,14 @@ def test_a_json_log_line_before_events_keeps_the_turn(tmp_path, monkeypatch): assert [event['text'] for event in events if event['type'] == 'delta'] == ['output'] +def test_a_typed_log_line_before_events_keeps_the_turn(tmp_path, monkeypatch): + events = _plain_line_run(tmp_path, monkeypatch, + 'import json\n' + 'print(json.dumps({"type": "log", "level": "info", "message": "telemetry disabled"}), flush=True)\n' + 'print(json.dumps({"type": "text", "sessionID": "s-1", "part": {"text": "output"}}), flush=True)\n') + assert [event['text'] for event in events if event['type'] == 'delta'] == ['output'] + + def test_a_truncated_plain_line_is_redacted_before_it_is_trimmed(tmp_path, monkeypatch): with pytest.raises(ProjectError) as caught: _plain_line_run(tmp_path, monkeypatch, @@ -976,7 +999,22 @@ def test_a_truncated_plain_line_is_redacted_before_it_is_trimmed(tmp_path, monke def test_the_stored_trace_redacts_a_truncated_stderr(tmp_path, monkeypatch): source = ('import sys\n' 'sys.stdin.read()\n' - 'sys.stderr.write("y" * 8186 + "\\n" + "secret-key-value" + "\\n" + "z" * 8180)\n' + 'sys.stderr.write("y" * 8000 + "\\n" + "secret-key-value" + "\\n" + "z" * 4000)\n' + 'sys.exit(1)\n') + with pytest.raises(ProjectError): + _plain_line_run(tmp_path, monkeypatch, source, + config={'id': 'c1', 'modelId': 'm', 'apiKey': 'secret-key-value'}) + [trace] = (tmp_path / 'agent-runs').glob('*.opencode.jsonl') + stored = trace.read_text(encoding='utf-8') + assert '"diagnostic"' in stored + assert '[redacted]' in stored + assert 'key-value' not in stored + + +def test_a_stderr_secret_split_across_reads_is_redacted(tmp_path, monkeypatch): + source = ('import sys\n' + 'sys.stdin.read()\n' + 'sys.stderr.write("y" * 8180 + "secret-key-value" + "\\n")\n' 'sys.exit(1)\n') with pytest.raises(ProjectError): _plain_line_run(tmp_path, monkeypatch, source, @@ -1004,6 +1042,11 @@ def test_the_stored_trace_redacts_a_truncated_stderr(tmp_path, monkeypatch): print(json.dumps({'level': 'error', 'message': 'provider unavailable'}), flush=True) ''' +TYPED_LOG_ONLY_CLI = '''import json, sys +sys.stdin.read() +print(json.dumps({'type': 'log', 'level': 'error', 'message': 'provider unavailable'}), flush=True) +''' + REJECTED_LOGIN = '''import json, sys sys.stdin.read() print(json.dumps({'type':'assistant','error':'authentication_failed', @@ -1054,6 +1097,16 @@ def test_a_cli_that_prints_only_log_json_stores_its_own_reason(tmp_path, monkeyp assert reloaded['errorCode'] == 'agent_cli_output_invalid' +def test_a_cli_that_prints_only_typed_log_json_stores_its_own_reason(tmp_path, monkeypatch): + path, client, events = broken_cli_turn(tmp_path, monkeypatch, TYPED_LOG_ONLY_CLI) + reply = events[-1]['conversation']['messages'][-1] + assert reply['errorCode'] == 'agent_cli_output_invalid', reply + assert 'provider unavailable' in reply['error'] + reloaded = client.get(path + '/assistant').json()['messages'][-1] + assert reloaded['error'] == reply['error'] + assert reloaded['errorCode'] == 'agent_cli_output_invalid' + + def test_a_rejected_login_is_stored_with_its_cause(tmp_path, monkeypatch): path, client, events = broken_cli_turn(tmp_path, monkeypatch, REJECTED_LOGIN, runtime='claude') reply = events[-1]['conversation']['messages'][-1] From bfb1fbc0ff1dc8a80c9b7bebdb40a9de2e56d7ee Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:55:12 +0800 Subject: [PATCH 8/8] [ci] python: list the test modules main added without a shard --- scripts/ci/python_shards.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/ci/python_shards.json b/scripts/ci/python_shards.json index c2b76342c..470bc6a29 100644 --- a/scripts/ci/python_shards.json +++ b/scripts/ci/python_shards.json @@ -4,6 +4,7 @@ "core": [ "tests/test_a2_repros.py", "tests/test_app_settings.py", + "tests/test_ark_availability.py", "tests/test_ark_plan_models.py", "tests/test_asset_names.py", "tests/test_atlascloud.py", @@ -103,6 +104,7 @@ "tests/test_self_hosted_proxy.py", "tests/test_self_hosted_queue.py", "tests/test_structure_reference.py", + "tests/test_trace_job_queries.py", "tests/test_vllm_omni_h3.py", "tests/test_vllm_omni_image.py", "tests/test_voice_library.py", @@ -136,7 +138,8 @@ "tests/test_native_runtime.py", "tests/test_native_sessions.py", "tests/test_pi_runtime.py", - "tests/test_skill_snapshot.py" + "tests/test_skill_snapshot.py", + "tests/test_wait_outcome.py" ], "media": [ "tests/test_canvas_text_cli_http.py",