diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 37fb0ca47..1a25cab6e 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -759,7 +759,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] = {} positions: dict[str, int] = {} @@ -857,6 +857,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), @@ -877,7 +878,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/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 94914358a..8fd19d04a 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -30,6 +30,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_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.', @@ -282,6 +285,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.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 opendirector.domain.voices import VOICE_MESSAGES detail = chinese.removeprefix(VOICE_MESSAGES[code]).strip() diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index add7c4d89..86cebbaa4 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -69,6 +69,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. 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 来源追溯 Agent 的 `generation.submit` 接受任务时,把本轮标识和工具调用标识写入 Job 自身: diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index e584456e7..1f94cd3ef 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -159,22 +159,97 @@ 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]: + 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 redacted(text: str, config, token: str = '') -> str: + if token: + text = text.replace(token, '[redacted]') + secret = (config or {}).get('apiKey') + return text.replace(secret, '[redacted]') if secret else text + + +def limited(text: str, config, token: str = '', limit: int = 200) -> str: + return redacted(text, config, token)[:limit] + + +def cli_detail(detail: str | None, config, token: str = '') -> str: + return f' CLI 输出:{limited(detail, config, token)}' if detail else '' + + +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': + message = raw.get('message') + content = message.get('content') if isinstance(message, dict) else None + return isinstance(content, list) and all( + isinstance(part, dict) + and (part.get('type') != 'text' or isinstance(part.get('text'), str)) + for part in content) + 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]: + kind = raw.get('type') if runtime == 'claude' and raw.get('error') == 'authentication_failed': - raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401) - if runtime == 'codex' and raw['type'] == 'error': + raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401, + code='agent_cli_login') + 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': + message = raw.get('message') + content = message.get('content') if isinstance(message, dict) else None + return [{'type': 'delta', 'text': part['text']} for part in content or [] + if isinstance(part, dict) and part.get('type') == 'text' + and isinstance(part.get('text'), str)] return [] @@ -301,11 +376,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) - del 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' @@ -318,14 +406,13 @@ 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 = ''.join(stderr_lines)[-8192:] await queue.put({'native': {'type': 'diagnostic', 'stderr': diagnostic, 'exitCode': process.returncode}}) async def output(): try: reported_session = None + plain, parsed = None, False if runtime == 'deepseek': async def observe(raw): await queue.put({'native': raw}) @@ -340,7 +427,18 @@ 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 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) + diagnostic = limited(text, config, token, 2000) + if plain is None: + plain = diagnostic + await queue.put({'native': {'type': 'diagnostic', + 'stdout': diagnostic}}) + continue + parsed = True previous_session = reported_session if runtime == 'codex' and raw['type'] == 'thread.started': reported_session = raw.get('thread_id') @@ -358,7 +456,13 @@ 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, token)}', 502, code='agent_cli_exit') + if not parsed and plain: + await record_exit() + raise ProjectError(f'{runtime} 未返回可识别的输出,请检查 CLI 登录和配置。' + f'{cli_detail(plain, config, token)}', 502, + code='agent_cli_output_invalid') if reported_session: run.save_native_session(reported_session, selection, engine_directory=native_work, diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 0223ea3e1..819f3f202 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -90,6 +90,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 9a3508642..fc19e9138 100644 --- a/src/canvas/AssistantReply.tsx +++ b/src/canvas/AssistantReply.tsx @@ -10,6 +10,7 @@ import { activityProgress, replySections, toolCounts, toolDisplayStatus, toolLab import type { ToolDisplayStatus } 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"; @@ -186,7 +187,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..eca958728 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: 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; } .cw-chat-waiting i:nth-child(2) { animation-delay: 0.15s; } 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/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 54947276f..05e473098 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -138,6 +138,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 4790b4645..92bde2bd1 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -137,6 +137,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..9862e1de2 100644 --- a/tests/browser/assistant_activity.mjs +++ b/tests/browser/assistant_activity.mjs @@ -230,6 +230,76 @@ 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."); + + 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. const longSource = { ...sourceA, url: 'https://example.test/' + 'long-path-'.repeat(70) + '?q=full-address' }; await page.setViewportSize({ width: 390, height: 800 }); @@ -284,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"] })); + 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"); diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 93d03f592..37521d47d 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -338,6 +338,26 @@ 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 native.event_like('claude', {'type': 'assistant', 'message': {'content': [ + {'type': 'text', 'text': 'hello'}, {'type': 'tool_use', 'id': 't1', 'name': 'read', 'input': {}}]}}) + assert not native.event_like('claude', {'type': 'assistant'}) + assert not native.event_like('claude', {'type': 'assistant', 'message': 'not-an-object'}) + assert not native.event_like('claude', {'type': 'assistant', 'message': {'content': ['not-a-part']}}) + assert not native.event_like('claude', {'type': 'assistant', 'message': {'content': [{'type': 'text'}]}}) + 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 @@ -919,3 +939,226 @@ 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, runtime='opencode'): + from opendirector.infrastructure.creation_projects import CreationProjects + run = RunContext(runtime=runtime, 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) + + +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_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_malformed_claude_assistant_event_keeps_the_turn_running(tmp_path, monkeypatch): + events = _plain_line_run(tmp_path, monkeypatch, + 'import json\n' + 'print(json.dumps({"type": "assistant", ' + '"message": {"content": [{"type": "text"}]}}), flush=True)\n' + 'print(json.dumps({"type": "assistant", ' + '"message": {"content": [{"type": "text", "text": "done"}]}}), flush=True)\n', + runtime='claude') + assert [event['text'] for event in events if event['type'] == 'delta'] == ['done'] + [trace] = (tmp_path / 'agent-runs').glob('*.claude.jsonl') + stored = [json.loads(line) for line in trace.read_text(encoding='utf-8').splitlines()] + diagnostics = [event['native']['stdout'] for event in stored + if event.get('native', {}).get('type') == 'diagnostic' and 'stdout' in event['native']] + assert any('"assistant"' in text for text in diagnostics) + + +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_multiple_plain_lines_keep_only_the_first_for_the_exit_reason(tmp_path, monkeypatch): + source = ('import sys\n' + 'sys.stdin.read()\n' + 'print("first warning", flush=True)\n' + 'print("second warning", flush=True)\n' + 'sys.exit(1)\n') + with pytest.raises(ProjectError) as caught: + _plain_line_run(tmp_path, monkeypatch, source) + assert '进程退出' in str(caught.value) + assert 'first warning' in str(caught.value) + assert 'second warning' not in str(caught.value) + [trace] = (tmp_path / 'agent-runs').glob('*.opencode.jsonl') + stored = trace.read_text(encoding='utf-8') + assert 'first warning' in stored + assert 'second warning' in stored + + +def test_the_stored_trace_redacts_a_truncated_stderr(tmp_path, monkeypatch): + source = ('import sys\n' + 'sys.stdin.read()\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, + 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') +sys.exit(1) +''' + +QUIET_EXIT_CLI = '''import sys +sys.stdin.read() +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) +''' + +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', + '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_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_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] + 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']