From 29962be16710e8c51aa4253f3fa0907802e4378b Mon Sep 17 00:00:00 2001
From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com>
Date: Sat, 21 Nov 2026 22:19:05 +0800
Subject: [PATCH 1/5] feat(assistant): edit and resend the last stopped message
(#375)
A stopped turn can be revised in place: the new attempt records the turn it
replaces, so the active path follows that chain instead of slicing messages
positionally. Project changes and accepted jobs are preserved, and a snapshot
of the replaced attempt's tool records rides on the new turn.
Server:
- Turn gains revisionOf and expectedRevision; conversation.json keeps an
incrementing revision so a stale view cannot overwrite a newer one.
- active_messages() replaces the positional slicing that fed the runtime
context; the superseded request and its partial reply leave the active path
but stay in history.
- Validation inside the begin transaction: expected revision, then the target
turn, then its terminal status, then the duplicate id.
- inherited_jobs() keeps the idempotency key for every replaced call and
resolves the job record when one was accepted.
Client:
- Editing a stopped message fills the composer with its text, references and
skills, and leaves the conversation untouched until the server accepts.
- pendingTurnId in sessionStorage keeps one operation identity across retries
of an uncertain edit.
- Inherited jobs render in a collapsed section.
Also tolerate plain-text stdout from a harness: Claude Code prints an
unrecognized-model warning between JSON events, which failed the whole turn
on a parse error.
---
apps/api/src/opendirector_api/agent.py | 95 +++++-
.../core/src/opendirector/agent/native.py | 13 +-
src/backend/chat.ts | 21 ++
src/canvas/AssistantPanel.tsx | 44 ++-
src/canvas/assistant-panel.css | 56 ++++
src/canvas/chatTurnRequest.ts | 69 ++++
src/canvas/useAssistantChat.ts | 119 ++++++-
src/i18n/messages/en-US/assistant.ts | 4 +
src/i18n/messages/zh-CN/assistant.ts | 4 +
tests/assistantRevision.test.ts | 56 ++++
tests/test_agent_citations.py | 7 +
tests/test_assistant_revision.py | 311 ++++++++++++++++++
12 files changed, 779 insertions(+), 20 deletions(-)
create mode 100755 src/canvas/chatTurnRequest.ts
create mode 100755 tests/assistantRevision.test.ts
create mode 100755 tests/test_assistant_revision.py
diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py
index ac2b19481..87f964d4a 100644
--- a/apps/api/src/opendirector_api/agent.py
+++ b/apps/api/src/opendirector_api/agent.py
@@ -67,6 +67,76 @@ class Turn(BaseModel):
thinking: Literal['auto', 'low', 'medium', 'high'] = 'auto'
modelSelections: dict[str, str | None] = Field(default_factory=dict)
skills: list[str] = Field(default_factory=list, max_length=1)
+ revisionOf: UUID | None = None
+ expectedRevision: int | None = None
+
+
+def superseded_turn_ids(messages):
+ """Turn ids a revision replaced; they stay in history but leave the active path.
+
+ The link is one field per turn, so the active path is derived from the chain
+ instead of from message positions.
+ """
+ return {str(message['revisionOf']) for message in messages if message.get('revisionOf')}
+
+
+def active_messages(messages):
+ """Messages of the surviving attempt, in order.
+
+ A revised turn keeps the replaced request and its reply in history for
+ traceability, but neither may reach the next attempt's context. The reply id
+ repeats the rule used when a turn is accepted.
+ """
+ gone = superseded_turn_ids(messages)
+ reply_ids = {str(uuid5(UUID(turn_id), 'assistant')) for turn_id in gone}
+ return [message for message in messages
+ if str(message.get('id')) not in gone and str(message.get('id')) not in reply_ids]
+
+
+def revision_error(messages, revision_of):
+ """Why a turn may not be revised, or None when it may.
+
+ Only the newest turn can be revised, and only once: a second revision would
+ have to pick between competing successors.
+ """
+ if revision_of in superseded_turn_ids(messages):
+ return '这条消息已经修订过,请编辑最新一条。'
+ if revision_of not in {message['id'] for message in messages}:
+ return '找不到要修订的消息,请刷新后重试。'
+ turns = [message['id'] for message in messages if message.get('role') == 'user']
+ if not turns or turns[-1] != revision_of:
+ return '只能修订刚才停止的那条消息。'
+ reply = next((message for message in messages
+ if message['id'] == str(uuid5(UUID(revision_of), 'assistant'))), None)
+ if reply is None or reply.get('status') not in {'stopped', 'interrupted'}:
+ return '只能修订已停止的消息。'
+ return None
+
+
+def inherited_jobs(messages, revision_of, jobs=()):
+ """Jobs the replaced turn already had accepted, so a retry does not repeat them.
+
+ The command id is the idempotency key the host derives from the turn and call,
+ so it is always present. The job record only exists when the submission was
+ accepted; ``jobId`` stays None for a call that never produced one, which is
+ what tells the new attempt to submit rather than reuse.
+ """
+ reply = next((message for message in messages
+ if message['id'] == str(uuid5(UUID(revision_of), 'assistant'))), None)
+ if not reply:
+ return []
+ turn = UUID(revision_of)
+ by_call = {str(job.agentCallId): job for job in jobs if str(job.agentRunId) == revision_of}
+ snapshot = []
+ for tool in reply.get('tools', []):
+ job = by_call.get(str(tool.get('id')))
+ snapshot.append({'commandId': str(agent_command_id(turn, tool.get('id'))),
+ 'callId': tool.get('id'), 'name': tool.get('name'),
+ 'jobId': str(job.id) if job else None,
+ 'status': str(job.status) if job else tool.get('status'),
+ 'asset': job.asset.model_dump(mode='json') if job and job.asset else None,
+ 'errorDetails': job.errorDetails.model_dump(mode='json') if job and job.errorDetails else None})
+ return snapshot
def draft_content_is_empty(content):
@@ -124,7 +194,7 @@ def path(self, project_id: UUID, session: str | None = None) -> Path:
def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | None = None,
begin: dict | None = None, finish: dict | None = None, conversation_id: UUID | None = None,
- before_begin=None) -> dict:
+ before_begin=None, expected_revision: int | None = None) -> dict:
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _, _ = self.projects._load(db, project_id)
@@ -145,13 +215,24 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft |
if begin is not None:
if any(message['id'] == begin['id'] for message in value['messages']):
raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409)
+ expected = begin.pop('expectedRevision', expected_revision)
+ if expected is not None and expected != value.get('revision', 0):
+ raise ProjectError('对话已在别处更新,请刷新后重试。', 409)
+ revision_of = begin.get('revisionOf')
+ if revision_of is not None:
+ blocked = revision_error(value['messages'], str(revision_of))
+ if blocked:
+ raise ProjectError(blocked, 409)
+ begin['inheritedJobs'] = inherited_jobs(value['messages'], str(revision_of),
+ self.projects.snapshot(project_id).jobs)
if before_begin is not None:
before_begin()
value['messages'].append(begin)
value['messages'].append({'id': str(uuid5(UUID(begin['id']), 'assistant')),
'role': 'assistant', 'text': '', 'status': 'streaming',
**{key: begin[key] for key in ('model', 'modelIsCliDefault', 'runtime') if key in begin}})
- value.update(draft='', draftContent=None, assets=[], skills=[])
+ value.update(draft='', draftContent=None, assets=[], skills=[],
+ revision=value.get('revision', 0) + 1)
changed = True
if finish is not None:
value['messages'] = [finish if message['id'] == finish['id'] else message for message in value['messages']]
@@ -420,14 +501,18 @@ async def produce() -> None:
'skills': value.skills, 'runtime': value.runtime, 'runtimeModel': value.runtimeModel,
'modelSelections': dict(value.modelSelections),
'model': model, 'modelIsCliDefault': model_is_cli_default, 'status': 'complete'}
+ if value.revisionOf is not None:
+ user['revisionOf'] = str(value.revisionOf)
saved = await asyncio.to_thread(conversations.update, project_id, session, begin=user,
- conversation_id=value.conversationId, before_begin=validate_connection)
+ conversation_id=value.conversationId, before_begin=validate_connection,
+ expected_revision=value.expectedRevision)
accepted = True
events.put({'type': 'start', 'conversation': saved})
- previous_sources = {source['id']: source for message in saved['messages'][:-2]
+ active = active_messages(saved['messages'])
+ previous_sources = {source['id']: source for message in active
for source in message.get('sources', [])}
context = []
- for message in saved['messages'][:-1]:
+ for message in active[:-1]:
content = message['text'] or '(empty reply)'
references = []
for attachment in message.get('assets', []):
diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py
index e9f6beab0..52cb3b875 100644
--- a/packages/core/src/opendirector/agent/native.py
+++ b/packages/core/src/opendirector/agent/native.py
@@ -148,6 +148,9 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None
def text_events(runtime: str, raw: dict) -> list[dict]:
+ if 'type' not in raw:
+ # Plain-text stdout the harness printed outside its event protocol.
+ return []
if runtime == 'claude' and raw.get('error') == 'authentication_failed':
raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401)
if runtime == 'codex' and raw['type'] == 'error':
@@ -309,7 +312,15 @@ async def observe(raw):
deepseek_server, observe, session_id)
else:
while line := await process.stdout.readline():
- raw = json.loads(line)
+ # A harness may print plain text on stdout, for example a
+ # warning about an unrecognized model. Keep it in the trace
+ # instead of failing the whole turn on a parse error.
+ try:
+ raw = json.loads(line)
+ except ValueError:
+ if line.strip():
+ await queue.put({'native': {'text': line.decode('utf-8', 'replace')}})
+ continue
previous_session = reported_session
if runtime == 'codex' and raw['type'] == 'thread.started':
reported_session = raw.get('thread_id')
diff --git a/src/backend/chat.ts b/src/backend/chat.ts
index 51da14a15..58cb4cad8 100644
--- a/src/backend/chat.ts
+++ b/src/backend/chat.ts
@@ -62,7 +62,21 @@ export interface ChatSource {
url: string;
title: string;
}
+/** A job the superseded attempt had already accepted, kept for the retry. */
+export interface InheritedJob {
+ commandId: string;
+ callId: string;
+ name: string;
+ jobId: string | null;
+ status: string;
+ asset?: unknown;
+ errorDetails?: unknown;
+}
export interface ChatMessage {
+ /** The stopped attempt this message revises, so history keeps both. */
+ revisionOf?: string;
+ /** Jobs accepted before the revised attempt, so it does not submit them again. */
+ inheritedJobs?: InheritedJob[];
sources?: ChatSource[];
plan?: ChatPlanEntry[];
runtime?: AgentRuntime;
@@ -73,6 +87,7 @@ export interface ChatMessage {
content?: ReferenceContent | null;
status: "complete" | "streaming" | "stopped" | "interrupted";
assets?: ChatAsset[];
+ skills?: string[];
model?: string | null;
modelIsCliDefault?: boolean;
runtimeModel?: string | null;
@@ -108,6 +123,8 @@ export interface ChatDraft {
}
export interface Conversation extends ChatDraft {
messages: ChatMessage[];
+ /** Increments on every accepted turn; a stale value means the view is behind. */
+ revision?: number;
}
export function draftContentIsEmpty(
@@ -144,6 +161,10 @@ export type ChatEvent =
export interface ChatRequest {
conversationId?: string;
id: string;
+ /** The turn this request replaces. Absent for an ordinary turn. */
+ revisionOf?: string;
+ /** The conversation revision this request was composed against. */
+ expectedRevision?: number;
modelId?: string;
text: string;
content?: ReferenceContent | null;
diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx
index 70bb8f507..e5cf077cb 100644
--- a/src/canvas/AssistantPanel.tsx
+++ b/src/canvas/AssistantPanel.tsx
@@ -413,6 +413,13 @@ export function AssistantPanel({
)}
{value.messages.map((message, index) => {
const previous = value.messages[index - 1];
+ const next = value.messages[index + 1];
+ // Only the newest stopped attempt can be revised, matching the server.
+ const editable = message.role === "user" &&
+ next?.role === "assistant" &&
+ (next.status === "stopped" || next.status === "interrupted") &&
+ index === value.messages.length - 2 &&
+ !chat.sending;
const trace = message.role === "assistant" && message !== latestReply && message.status !== "streaming" &&
previous?.role === "user" && new URLSearchParams({
traceProject: documentId,
@@ -487,6 +494,33 @@ export function AssistantPanel({
{t("assistant.panel.trace")} ↗
)}
+ {editable && (
+ chat.beginEdit(message)}
+ >
+ {t("assistant.panel.editResend")}
+
+ )}
+ {!!message.inheritedJobs?.length && (
+
+
+ {t("assistant.panel.inheritedJobs", {
+ count: message.inheritedJobs.length,
+ })}
+
+
+ {message.inheritedJobs.map((job) => (
+
+ {job.name}
+ {job.status}
+
+ ))}
+
+
+ )}
{message.role === "user" && !!message.assets?.length && }
{(message.status === "stopped" ||
message.status === "interrupted") && (
@@ -500,7 +534,15 @@ export function AssistantPanel({
);
})}
-
+
+ {chat.editing && (
+
+ {t("assistant.panel.editingNotice")}
+
+ {t("assistant.panel.cancelEdit")}
+
+
+ )}
{chat.error && (
{chat.error}
diff --git a/src/canvas/assistant-panel.css b/src/canvas/assistant-panel.css
index aecc065b2..2362863fa 100644
--- a/src/canvas/assistant-panel.css
+++ b/src/canvas/assistant-panel.css
@@ -306,6 +306,62 @@
color: var(--chat-muted);
font-size: 11px;
}
+.cw-assistant-message-edit {
+ margin-top: 8px;
+ padding: 3px 9px;
+ border: 1px solid var(--chat-border);
+ border-radius: 6px;
+ background: transparent;
+ color: var(--chat-muted);
+ font-size: 11px;
+ cursor: pointer;
+}
+.cw-assistant-message-edit:hover:not(:disabled) {
+ border-color: var(--chat-accent);
+ color: var(--chat-accent);
+}
+.cw-assistant-message-edit:disabled {
+ opacity: 0.45;
+ cursor: default;
+}
+.cw-assistant-inherited {
+ margin-top: 8px;
+ color: var(--chat-muted);
+ font-size: 11px;
+}
+.cw-assistant-inherited summary {
+ cursor: pointer;
+ opacity: 0.75;
+}
+.cw-assistant-inherited ul {
+ margin: 6px 0 0;
+ padding-left: 16px;
+ opacity: 0.7;
+}
+.cw-assistant-inherited li {
+ display: flex;
+ gap: 8px;
+ list-style: disc;
+}
+.cw-assistant-editing {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ margin-bottom: 8px;
+ padding: 7px 10px;
+ border: 1px solid var(--chat-border);
+ border-radius: 8px;
+ color: var(--chat-muted);
+ font-size: 11px;
+}
+.cw-assistant-editing button {
+ border: none;
+ background: transparent;
+ color: var(--chat-accent);
+ font-size: 11px;
+ cursor: pointer;
+}
.cw-assistant-message-assets {
display: flex;
flex-wrap: wrap;
diff --git a/src/canvas/chatTurnRequest.ts b/src/canvas/chatTurnRequest.ts
new file mode 100755
index 000000000..d3765495a
--- /dev/null
+++ b/src/canvas/chatTurnRequest.ts
@@ -0,0 +1,69 @@
+import { builtinThinking } from "./agentPreferences.ts";
+import type {
+ AgentRuntime,
+ Conversation,
+ ModelSelections,
+ Thinking,
+} from "../backend/chat.ts";
+import type { ReferenceContent } from "./chatReferenceContent";
+
+/** The turn being edited: a stopped attempt and the draft it is replacing. */
+export interface ChatEditing {
+ turnId: string;
+ conversationId: string;
+ saved: Pick
;
+}
+
+export interface TurnRequest {
+ id: string;
+ conversationId?: string;
+ modelId?: string;
+ runtime: AgentRuntime;
+ runtimeModel?: string | null;
+ text: string;
+ content?: ReferenceContent | null;
+ assets: string[];
+ thinking: Thinking;
+ modelSelections: ModelSelections;
+ skills: string[];
+ /** The turn this request replaces. Absent for an ordinary turn. */
+ revisionOf?: string;
+ /** The conversation revision this request was composed against. */
+ expectedRevision?: number;
+}
+
+/**
+ * The request body for a turn, including the identity an edit must carry so the
+ * server can validate it against the conversation it was composed on.
+ */
+export function turnRequest(
+ input: Conversation,
+ {
+ id,
+ modelId,
+ editing,
+ revision,
+ }: {
+ id: string;
+ modelId?: string;
+ editing: ChatEditing | null;
+ revision?: number;
+ },
+): TurnRequest {
+ return {
+ id,
+ conversationId: input.conversationId,
+ modelId,
+ runtime: input.runtime ?? "default",
+ runtimeModel: input.runtimeModel,
+ text: input.draft,
+ content: input.draftContent,
+ assets: input.assets.map((asset) => asset.id),
+ thinking: builtinThinking(input, modelId),
+ modelSelections: input.modelSelections,
+ skills: input.skills ?? [],
+ ...(editing
+ ? { revisionOf: editing.turnId, expectedRevision: revision }
+ : {}),
+ };
+}
diff --git a/src/canvas/useAssistantChat.ts b/src/canvas/useAssistantChat.ts
index 3b223a198..f98909451 100644
--- a/src/canvas/useAssistantChat.ts
+++ b/src/canvas/useAssistantChat.ts
@@ -18,6 +18,7 @@ import {
stopChat,
type ChatAsset,
type Conversation,
+ type ChatMessage,
conversationIsEmpty,
} from "../backend/chat";
import { flushChatDraft, rememberChat } from "../backend/chatDrafts";
@@ -38,6 +39,7 @@ import {
import type { CanvasNode } from "./model";
import { pendingCanvasReferences } from "./pendingCanvasReferences.ts";
import type { Translate } from "../i18n/I18nProvider.tsx";
+import { turnRequest, type ChatEditing } from "./chatTurnRequest.ts";
export interface ProjectChatAsset extends ReferenceAsset {
kind: string;
@@ -49,6 +51,32 @@ export const attachment = ({
size,
fingerprint,
}: ChatAsset): ChatAsset => ({ id, name, type, size, fingerprint });
+/**
+ * The id an uncertain submission keeps, so retrying an edit resends the same
+ * operation instead of creating a second attempt.
+ */
+const pendingKey = (conversationId: string) =>
+ `opendirector.chat.revision.${conversationId}`;
+const pendingTurnId = (conversationId: string) => {
+ try {
+ const store = globalThis.sessionStorage;
+ if (!store) return undefined;
+ return store.getItem(pendingKey(conversationId)) ?? undefined;
+ } catch {
+ return undefined;
+ }
+};
+const rememberPendingTurnId = (conversationId: string, id?: string) => {
+ try {
+ const store = globalThis.sessionStorage;
+ if (!store) return;
+ if (id) store.setItem(pendingKey(conversationId), id);
+ else store.removeItem(pendingKey(conversationId));
+ } catch {
+ // Storage can be unavailable; the retry then creates a fresh turn.
+ }
+};
+
const empty = (): Conversation => ({
messages: [],
draft: "",
@@ -91,6 +119,9 @@ export function useAssistantChat(
const [threadsLoading, setThreadsLoading] = useState(false);
const [threadsError, setThreadsError] = useState("");
const [changing, setChanging] = useState(false);
+ // The stopped attempt being revised: its user message id plus the draft the
+ // edit replaced, so cancelling restores exactly what the user had typed.
+ const [editing, setEditing] = useState(null);
const switching = useRef(false);
const [error, setError] = useState("");
const displayError = (text: string) =>
@@ -459,28 +490,87 @@ export function useAssistantChat(
)
return;
const input = current.current;
- await follow(crypto.randomUUID(), async (id, signal, onEvent) => {
+ const revising = editing;
+ // A retry of the same edit keeps its id, so an uncertain submission cannot
+ // become a second attempt. An ordinary turn always gets a fresh one.
+ const id =
+ (revising &&
+ input.conversationId &&
+ pendingTurnId(input.conversationId)) ||
+ crypto.randomUUID();
+ if (revising && input.conversationId)
+ rememberPendingTurnId(input.conversationId, id);
+ await follow(id, async (turn, signal, onEvent) => {
await flushChatDraft(projectId);
await streamChat(
projectId,
- {
- id,
- conversationId: input.conversationId,
+ turnRequest(input, {
+ id: turn,
modelId: agent?.id,
- runtime: input.runtime ?? "default",
- runtimeModel: input.runtimeModel,
- text: input.draft,
- content: input.draftContent,
- assets: input.assets.map((asset) => asset.id),
- thinking: builtinThinking(input, agent?.id),
- modelSelections: input.modelSelections,
- skills: input.skills ?? [],
- },
+ editing: revising,
+ revision: input.revision,
+ }),
signal,
onEvent,
t,
);
});
+ // The server accepted the attempt; the id must not be reused afterwards.
+ if (revising && input.conversationId)
+ rememberPendingTurnId(input.conversationId);
+ if (revising) setEditing(null);
+ };
+ /**
+ * Open a stopped attempt for editing. The conversation itself is untouched:
+ * the active path only changes once the server accepts the revised turn.
+ */
+ const beginEdit = (turn: ChatMessage) => {
+ if (submitting.current || !loaded) return;
+ const input = current.current;
+ setEditing({
+ turnId: turn.id,
+ conversationId: input.conversationId ?? "",
+ saved: {
+ draft: input.draft,
+ draftContent: input.draftContent,
+ assets: input.assets,
+ skills: input.skills,
+ },
+ });
+ const assets = (turn.assets ?? []).flatMap((asset) => {
+ const known = knownAssets.current.get(asset.id);
+ return known ? [attachment(known)] : [attachment(asset)];
+ });
+ assets.forEach((asset) => knownAssets.current.set(asset.id, asset));
+ const next: Conversation = {
+ ...input,
+ draft: turn.text,
+ // Reuse the stored content so references and skills survive the edit.
+ draftContent: referenceContent(
+ turn.text,
+ (turn.assets ?? []).map((asset) => asset.id),
+ turn.assets ?? [],
+ turn.content,
+ t,
+ ),
+ assets,
+ skills: turn.skills ?? input.skills,
+ };
+ current.current = next;
+ rememberChat(projectId, next);
+ setValue(next);
+ setError("");
+ };
+ /** Leave editing without sending; the original message stays untouched. */
+ const cancelEdit = () => {
+ if (!editing) return;
+ const next: Conversation = { ...current.current, ...editing.saved };
+ current.current = next;
+ rememberChat(projectId, next);
+ setValue(next);
+ if (next.conversationId) rememberPendingTurnId(next.conversationId);
+ setEditing(null);
+ setError("");
};
/** Re-attach to a turn that kept running while this project was not shown. */
resume.current = async (id: string) => {
@@ -690,6 +780,9 @@ export function useAssistantChat(
addNodes,
addAssets,
send,
+ editing,
+ beginEdit,
+ cancelEdit,
stop,
reload: () => setLoadAttempt((n) => n + 1),
};
diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts
index 3e19abda4..fd0c49fad 100644
--- a/src/i18n/messages/en-US/assistant.ts
+++ b/src/i18n/messages/en-US/assistant.ts
@@ -58,6 +58,10 @@ export const assistant = {
"assistant.panel.connecting": "Connecting to the conversation service…",
"assistant.panel.refreshCatalog": "Read again",
"assistant.panel.stopped": "Reply stopped",
+ "assistant.panel.editResend": "Edit and resend",
+ "assistant.panel.editingNotice": "Editing a stopped message. Sending it starts a new attempt.",
+ "assistant.panel.cancelEdit": "Cancel editing",
+ "assistant.panel.inheritedJobs": "Tasks already submitted ({{count}})",
"assistant.panel.interrupted": "Reply interrupted",
"assistant.panel.send": "Send message",
"assistant.panel.stop": "Stop reply",
diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts
index 4c95240b8..f5f48d731 100644
--- a/src/i18n/messages/zh-CN/assistant.ts
+++ b/src/i18n/messages/zh-CN/assistant.ts
@@ -57,6 +57,10 @@ export const assistant = {
"assistant.panel.connecting": "正在连接对话服务…",
"assistant.panel.refreshCatalog": "重新读取",
"assistant.panel.stopped": "已停止回复",
+ "assistant.panel.editResend": "编辑并重发",
+ "assistant.panel.editingNotice": "正在编辑已停止的消息,发送后会作为新的尝试。",
+ "assistant.panel.cancelEdit": "取消编辑",
+ "assistant.panel.inheritedJobs": "已提交的任务({{count}})",
"assistant.panel.interrupted": "回复已中断",
"assistant.panel.send": "发送消息",
"assistant.panel.stop": "停止回复",
diff --git a/tests/assistantRevision.test.ts b/tests/assistantRevision.test.ts
new file mode 100755
index 000000000..bc65ad0ba
--- /dev/null
+++ b/tests/assistantRevision.test.ts
@@ -0,0 +1,56 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { turnRequest } from "../src/canvas/chatTurnRequest.ts";
+import type { Conversation } from "../src/backend/chat.ts";
+
+const conversation = (patch: Partial = {}): Conversation => ({
+ messages: [],
+ draft: "NEW-标记",
+ assets: [],
+ thinking: "auto",
+ modelSelections: {},
+ conversationId: "conversation-1",
+ revision: 4,
+ ...patch,
+});
+
+test("an ordinary turn carries no revision identity", () => {
+ const body = turnRequest(conversation(), { id: "turn-2", modelId: "model", editing: null });
+ assert.equal(body.revisionOf, undefined);
+ assert.equal(body.expectedRevision, undefined);
+ assert.equal(body.text, "NEW-标记");
+});
+
+test("an edit names the stopped turn and the revision it was composed on", () => {
+ const editing = {
+ turnId: "turn-stopped",
+ conversationId: "conversation-1",
+ saved: { draft: "", draftContent: null, assets: [], skills: [] },
+ };
+ const body = turnRequest(conversation(), {
+ id: "turn-3", modelId: "model", editing, revision: 4,
+ });
+ assert.equal(body.revisionOf, "turn-stopped");
+ assert.equal(body.expectedRevision, 4);
+ // The revised text is what the new attempt sends, exactly once.
+ assert.equal(body.text, "NEW-标记");
+});
+
+test("an edit keeps the references and skills of the message it revises", () => {
+ const editing = {
+ turnId: "turn-stopped",
+ conversationId: "conversation-1",
+ saved: { draft: "", draftContent: null, assets: [], skills: [] },
+ };
+ const body = turnRequest(
+ conversation({
+ assets: [{ id: "asset-1", name: "a", type: "image/png", size: 1, fingerprint: "f" }],
+ skills: ["canvas"],
+ draftContent: [{ type: "text", text: "NEW-标记" }],
+ }),
+ { id: "turn-3", modelId: "model", editing, revision: 4 },
+ );
+ assert.deepEqual(body.assets, ["asset-1"]);
+ assert.deepEqual(body.skills, ["canvas"]);
+ assert.deepEqual(body.content, [{ type: "text", text: "NEW-标记" }]);
+});
diff --git a/tests/test_agent_citations.py b/tests/test_agent_citations.py
index 9f6284bf8..c4bb09765 100644
--- a/tests/test_agent_citations.py
+++ b/tests/test_agent_citations.py
@@ -81,3 +81,10 @@ def test_historical_sources_reuse_prior_turn_evidence_but_do_not_follow_trace_li
(folder / f'{turn}.codex.jsonl').symlink_to(external)
conversation['messages'][-1]['text'] = 'Other\ue200cite\ue202turn2view0\ue201'
assert with_trace_sources(conversation, tmp_path)['messages'][-1]['sources'] == []
+
+
+def test_plain_stdout_outside_the_event_protocol_is_ignored():
+ # A harness may print a warning on stdout, for example about an unrecognized
+ # model. It must not fail the turn, and it carries no events.
+ assert text_events('claude', {'text': '[claude-code:unrecognized_model]\n'}) == []
+ assert text_events('codex', {'text': 'warning\n'}) == []
diff --git a/tests/test_assistant_revision.py b/tests/test_assistant_revision.py
new file mode 100755
index 000000000..5278032d7
--- /dev/null
+++ b/tests/test_assistant_revision.py
@@ -0,0 +1,311 @@
+"""Tests for editing and resending a stopped user turn (#375).
+
+Covered behaviours follow the agreed design:
+
+* ``revisionOf`` links a new turn back to the turn it replaces; the active path
+ is derived by following that chain, not by slicing ``messages`` positionally.
+* ``expectedRevision`` guards concurrent writes inside the same transaction.
+* A revision carries a snapshot of the original turn's accepted jobs.
+"""
+import json
+import threading
+import time
+from io import BytesIO
+from uuid import uuid4
+
+from PIL import Image
+
+from fastapi.testclient import TestClient
+import pytest
+
+from opendirector.infrastructure.local_projects import LocalProjects
+from opendirector_api.main import create_app
+from opendirector_api import agent
+
+
+def frames(response):
+ return [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith('data: ')]
+
+
+async def empty_skills(*args):
+ return []
+
+
+@pytest.fixture
+def assistant(tmp_path, monkeypatch):
+ contexts = []
+ # Replies stay streaming until released, so a stop request is what ends a
+ # turn and the server records ``stopped`` instead of ``complete``.
+ release = threading.Event()
+
+ async def stream(self, run):
+ contexts.append(run.messages)
+ # Emit the tool record before waiting, so a stopped turn still owns the
+ # accepted job a revision has to inherit.
+ yield {'type': 'tool', 'id': 'call-known', 'name': 'run_command', 'status': 'complete'}
+ while not release.is_set():
+ import asyncio
+ await asyncio.sleep(0.01)
+ yield {'type': 'delta', 'text': 'REVISED-ATTEMPT' if len(contexts) > 1 else 'FIRST-ATTEMPT'}
+
+ monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream)
+ monkeypatch.setattr(agent, 'runtime_available', lambda _: True)
+ monkeypatch.setattr(agent, 'skills', empty_skills)
+ from opendirector.infrastructure.model_configs import ModelConfigs
+ config = {'id': str(uuid4()), 'modelId': 'test-model', 'kind': 'agent', 'url': 'http://models.test/v1',
+ 'connectionType': 'api', 'protocol': 'openai', 'authMode': 'none', 'apiKey': ''}
+ monkeypatch.setattr(ModelConfigs, 'resolve', lambda *args: dict(config))
+ with TestClient(create_app(LocalProjects(tmp_path)), headers={
+ 'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': str(uuid4())}) as client:
+ pid = str(uuid4())
+ root = f'/api/creation/projects/{pid}'
+ assert client.post(root + '/commands', json={'type': 'project.create', 'projectId': pid,
+ 'commandId': str(uuid4()), 'payload': {'name': '修订'}}).status_code == 200
+ assert client.post(root + '/open').status_code == 200
+ yield client, root + '/assistant', contexts, release
+
+
+def open_turn(client, path, conversation_id, text, *, revision_of=None, assets=()):
+ """Send a turn without waiting for its reply, and return (thread, turn id)."""
+ body = {'id': str(uuid4()), 'runtime': 'default', 'conversationId': conversation_id, 'text': text}
+ if revision_of is not None:
+ body['revisionOf'] = revision_of
+ if assets:
+ body['assets'] = list(assets)
+ captured = {}
+
+ def run():
+ captured['response'] = client.post(path + '/turns', json=body)
+
+ thread = threading.Thread(target=run, daemon=True)
+ thread.start()
+ deadline = time.time() + 10
+ while time.time() < deadline:
+ state = client.get(path).json()
+ streaming = [message for message in state['messages'] if message.get('status') == 'streaming']
+ if streaming:
+ break
+ time.sleep(0.02)
+ turn = body['id']
+ return thread, turn, captured
+
+
+def finish(client, path, thread, turn, captured):
+ assert client.post(f'{path}/turns/{turn}/stop').status_code == 200
+ thread.join(timeout=10)
+ assert not thread.is_alive(), 'the stopped turn did not end'
+ return captured['response']
+
+
+def error_of(response):
+ ends = [frame for frame in frames(response) if frame['type'] == 'end']
+ assert ends, response.text
+ return ends[-1]['error']
+
+
+def conversation(client, path):
+ response = client.get(path)
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def test_revised_attempt_replaces_the_stopped_turn_on_the_active_path(assistant):
+ client, path, contexts, release = assistant
+ active = conversation(client, path)['conversationId']
+ thread, original, captured = open_turn(client, path, active, 'OLD-标记')
+ finish(client, path, thread, original, captured)
+ assert conversation(client, path)['messages'][-1]['status'] == 'stopped'
+
+ release.set()
+ revised = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original})
+ assert revised.status_code == 200, revised.text
+ assert error_of(revised) is None, error_of(revised)
+
+ seen = json.dumps(contexts[-1], ensure_ascii=False)
+ assert 'NEW-标记' in seen
+ assert 'OLD-标记' not in seen, 'the replaced request must leave the active path'
+
+ saved = conversation(client, path)
+ assert [message['id'] for message in saved['messages']].count(original) == 1, \
+ 'the stopped turn is kept for history, not rewritten'
+ assert saved['messages'][-2].get('revisionOf') == original
+ # Later turns continue from the revised attempt, not from the replaced one.
+ again = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'third'})
+ assert error_of(again) is None, error_of(again)
+ later = json.dumps(contexts[-1], ensure_ascii=False)
+ assert 'third' in later
+ assert 'OLD-标记' not in later
+
+
+def test_revision_of_an_unrelated_turn_is_rejected(assistant):
+ client, path, contexts, release = assistant
+ release.set()
+ active = conversation(client, path)['conversationId']
+ assert error_of(client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'seed'})) is None
+ response = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'x', 'revisionOf': str(uuid4())})
+ assert response.status_code == 200, response.text
+ assert error_of(response), 'an unknown turn cannot be revised'
+
+
+def test_a_turn_that_is_not_the_newest_cannot_be_revised(assistant):
+ client, path, contexts, release = assistant
+ release.set()
+ active = conversation(client, path)['conversationId']
+ for text in ('first', 'second'):
+ assert error_of(client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': text})) is None
+ first = [message for message in conversation(client, path)['messages'] if message['role'] == 'user'][0]['id']
+ response = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'too late', 'revisionOf': first})
+ assert response.status_code == 200, response.text
+ assert error_of(response), 'only the newest turn can be revised'
+
+
+def test_a_turn_cannot_be_revised_twice(assistant):
+ client, path, contexts, release = assistant
+ active = conversation(client, path)['conversationId']
+ thread, original, captured = open_turn(client, path, active, 'OLD-标记')
+ finish(client, path, thread, original, captured)
+
+ release.set()
+ first = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original})
+ assert error_of(first) is None, error_of(first)
+ again = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'NEW-again', 'revisionOf': original})
+ assert again.status_code == 200, again.text
+ assert error_of(again), 'a turn can only be revised once'
+
+
+def test_expected_revision_blocks_a_concurrent_write(assistant):
+ client, path, contexts, release = assistant
+ release.set()
+ active = conversation(client, path)['conversationId']
+ assert error_of(client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'seed'})) is None
+ revision = conversation(client, path)['revision']
+
+ fresh = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'second', 'expectedRevision': revision})
+ assert error_of(fresh) is None, error_of(fresh)
+ stale = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'third', 'expectedRevision': revision})
+ assert stale.status_code == 200, stale.text
+ assert error_of(stale), 'a stale expectedRevision must not overwrite'
+
+
+def test_revision_snapshots_the_stopped_turns_tool_records(assistant):
+ client, path, contexts, release = assistant
+ active = conversation(client, path)['conversationId']
+ thread, original, captured = open_turn(client, path, active, 'OLD-标记')
+ finish(client, path, thread, original, captured)
+ assert conversation(client, path)['messages'][-1]['status'] == 'stopped'
+
+ release.set()
+ revised = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original})
+ assert error_of(revised) is None, error_of(revised)
+ new_turn = frames(revised)[0]['conversation']['messages'][-2]
+ assert new_turn.get('inheritedJobs'), 'the snapshot is written together with the new turn'
+ assert [job['callId'] for job in new_turn['inheritedJobs']] == ['call-known']
+ from uuid import UUID
+ expected = str(agent.agent_command_id(UUID(original), 'call-known'))
+ assert [job['commandId'] for job in new_turn['inheritedJobs']] == [expected]
+
+
+def test_inherited_jobs_resolves_the_job_receipt_by_call_id():
+ """The snapshot carries the idempotency key and, when one exists, the job."""
+ from types import SimpleNamespace
+ from uuid import UUID
+
+ turn = str(uuid4())
+ reply_id = str(agent.uuid5(UUID(turn), 'assistant'))
+ messages = [
+ {'id': turn, 'role': 'user', 'text': 'OLD'},
+ {'id': reply_id, 'role': 'assistant', 'status': 'stopped',
+ 'tools': [{'id': 'call-done', 'name': 'generate', 'status': 'running'},
+ {'id': 'call-lost', 'name': 'generate', 'status': 'failed'}]},
+ ]
+ job = SimpleNamespace(id=uuid4(), agentRunId=turn, agentCallId='call-done', status='succeeded',
+ asset=None, errorDetails=None)
+ snapshot = agent.inherited_jobs(messages, turn, [job])
+
+ done = next(item for item in snapshot if item['callId'] == 'call-done')
+ lost = next(item for item in snapshot if item['callId'] == 'call-lost')
+ # The accepted job is resolved and its status wins over the stale tool record.
+ assert done['jobId'] == str(job.id) and done['status'] == 'succeeded'
+ assert done['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-done'))
+ # A call that never produced a job keeps its command id and reports no job.
+ assert lost['jobId'] is None and lost['status'] == 'failed'
+ assert lost['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-lost'))
+
+
+def test_a_running_turn_rejects_a_concurrent_submission(assistant):
+ """A second submit while a turn is running is refused before it streams."""
+ client, path, contexts, release = assistant
+ active = conversation(client, path)['conversationId']
+ thread, original, captured = open_turn(client, path, active, 'OLD-标记')
+ try:
+ blocked = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'concurrent', 'revisionOf': original})
+ assert blocked.status_code == 409, blocked.text
+ finally:
+ finish(client, path, thread, original, captured)
+ # The refused submission left no trace.
+ texts = [message.get('text') for message in conversation(client, path)['messages']]
+ assert 'concurrent' not in texts
+
+
+def test_the_revision_survives_reloading_the_conversation(assistant):
+ """Both attempts stay inspectable; the active path still excludes the old one."""
+ client, path, contexts, release = assistant
+ active = conversation(client, path)['conversationId']
+ thread, original, captured = open_turn(client, path, active, 'OLD-标记')
+ finish(client, path, thread, original, captured)
+ release.set()
+ revised_id = str(uuid4())
+ revised = client.post(path + '/turns', json={'id': revised_id, 'runtime': 'default',
+ 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original})
+ assert error_of(revised) is None, error_of(revised)
+
+ reloaded = conversation(client, path)
+ users = [message for message in reloaded['messages'] if message['role'] == 'user']
+ # The replaced request is kept for inspection, not rewritten.
+ assert [message['text'] for message in users] == ['OLD-标记', 'NEW-标记']
+ assert next(message for message in users if message['id'] == revised_id)['revisionOf'] == original
+ assert reloaded['revision'] == conversation(client, path)['revision']
+
+
+def test_the_revised_attempt_keeps_attachments_of_the_edited_message(assistant):
+ client, path, contexts, release = assistant
+ active = conversation(client, path)['conversationId']
+ base = path.removesuffix('/assistant')
+ image = BytesIO()
+ Image.new('RGB', (5, 4), 'purple').save(image, format='PNG')
+ handle = str(uuid4())
+ assert client.put(base + '/uploads/' + handle, content=image.getvalue(),
+ headers={'X-Asset-Name': 'keep.png'}).status_code == 200
+ imported = client.post(base + '/commands', json={'type': 'asset.import',
+ 'commandId': str(uuid4()), 'projectId': base.rsplit('/', 1)[-1],
+ 'payload': {'uploadHandle': handle, 'name': 'keep.png', 'expectedKind': 'image'}})
+ assert imported.status_code == 200, imported.text
+ asset = imported.json()['changed'][0]['id']
+
+ thread, original, captured = open_turn(client, path, active, 'OLD-标记', assets=[asset])
+ finish(client, path, thread, original, captured)
+ assert conversation(client, path)['messages'][-1]['status'] == 'stopped'
+ assert conversation(client, path)['messages'][-2]['assets'][0]['id'] == asset
+
+ release.set()
+ revised = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
+ 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original,
+ 'assets': [asset]})
+ assert error_of(revised) is None, error_of(revised)
+ new_turn = frames(revised)[0]['conversation']['messages'][-2]
+ assert [item['id'] for item in new_turn.get('assets') or []] == [asset]
+ # The reference still reaches the runtime context of the revised attempt.
+ assert asset in json.dumps(contexts[-1], ensure_ascii=False)
From 6f6c42228ed387ea3c15107a1c2b0c566385b03e Mon Sep 17 00:00:00 2001
From: dev
Date: Wed, 25 Nov 2026 10:25:57 +0800
Subject: [PATCH 2/5] [bugfix] assistant: keep only the inherited calls'
identity in the new turn
An edit/resend wrote the inherited jobs' status, asset and error into the new
user message. Those are facts about the job record, not about the call, so the
copy stopped being true as soon as a job progressed: expanding the block later
reported the status from the moment of the write.
Persist the ids only -- command id, call id, name and job id -- because that is
what cannot change and what a retry needs to decide between reusing a job and
submitting again. A reader that wants the current state looks the job up by id;
a missing lookup is not proof that resubmitting is safe, so the id stays.
The block also counted every inherited call as "already submitted", including
calls that never produced a job. The count now covers the submitted ones and a
call without a job is marked as such.
---
apps/api/src/opendirector_api/agent.py | 13 +++++++++----
src/backend/chat.ts | 4 +---
src/canvas/AssistantPanel.tsx | 15 ++++++++++-----
src/i18n/messages/en-US/assistant.ts | 1 +
src/i18n/messages/zh-CN/assistant.ts | 1 +
tests/test_assistant_revision.py | 11 ++++++++---
6 files changed, 30 insertions(+), 15 deletions(-)
diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py
index 4e5f5eb4b..a659fab2e 100644
--- a/apps/api/src/opendirector_api/agent.py
+++ b/apps/api/src/opendirector_api/agent.py
@@ -122,6 +122,14 @@ def inherited_jobs(messages, revision_of, jobs=()):
so it is always present. The job record only exists when the submission was
accepted; ``jobId`` stays None for a call that never produced one, which is
what tells the new attempt to submit rather than reuse.
+
+ Only the identity of the inherited calls is written here, because only that
+ cannot change. Job status, its asset and its error belong to the job record:
+ a copy taken at the moment the new turn is written goes stale as soon as the
+ job progresses, and an expanded view that reads it would report a state that
+ is no longer true. Readers that want the current state query the job by the
+ ids kept here; a missing or failed lookup must not be read as proof that
+ resubmitting a side-effectful call is safe.
"""
reply = next((message for message in messages
if message['id'] == str(uuid5(UUID(revision_of), 'assistant'))), None)
@@ -134,10 +142,7 @@ def inherited_jobs(messages, revision_of, jobs=()):
job = by_call.get(str(tool.get('id')))
snapshot.append({'commandId': str(agent_command_id(turn, tool.get('id'))),
'callId': tool.get('id'), 'name': tool.get('name'),
- 'jobId': str(job.id) if job else None,
- 'status': str(job.status) if job else tool.get('status'),
- 'asset': job.asset.model_dump(mode='json') if job and job.asset else None,
- 'errorDetails': job.errorDetails.model_dump(mode='json') if job and job.errorDetails else None})
+ 'jobId': str(job.id) if job else None})
return snapshot
diff --git a/src/backend/chat.ts b/src/backend/chat.ts
index 58cb4cad8..b9b503252 100644
--- a/src/backend/chat.ts
+++ b/src/backend/chat.ts
@@ -67,10 +67,8 @@ export interface InheritedJob {
commandId: string;
callId: string;
name: string;
+ /** Null when the earlier attempt never produced a job for this call. */
jobId: string | null;
- status: string;
- asset?: unknown;
- errorDetails?: unknown;
}
export interface ChatMessage {
/** The stopped attempt this message revises, so history keeps both. */
diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx
index d4f7ff8ce..a81fb8046 100644
--- a/src/canvas/AssistantPanel.tsx
+++ b/src/canvas/AssistantPanel.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from "react";
import openDirectorLogo from "../assets/open_director_logo.png";
-import { runtimeModels, type ChatAsset, type ModelSelections } from "../backend/chat";
+import { runtimeModels, type ChatAsset, type ChatMessage, type ModelSelections } from "../backend/chat";
import { creationClient } from "../backend/creationClient.ts";
import { fingerprint } from "../backend/generation.ts";
import type { BackendModels } from "../backend/models";
@@ -53,6 +53,11 @@ function kindOf(asset: ChatAsset) {
: "text";
}
+/** The inherited calls that produced a job, so the count does not claim a submission that never happened. */
+function submittedJobs(message: ChatMessage) {
+ return (message.inheritedJobs ?? []).filter((job) => job.jobId);
+}
+
/** OpenDirector conversation tools in an OpenDirector floating canvas window. */
export function AssistantPanel({
documentId,
@@ -517,18 +522,18 @@ export function AssistantPanel({
{t("assistant.panel.editResend")}
)}
- {!!message.inheritedJobs?.length && (
+ {!!submittedJobs(message).length && (
{t("assistant.panel.inheritedJobs", {
- count: message.inheritedJobs.length,
+ count: submittedJobs(message).length,
})}
- {message.inheritedJobs.map((job) => (
+ {(message.inheritedJobs ?? []).map((job) => (
{job.name}
- {job.status}
+ {!job.jobId && {t("assistant.panel.inheritedJobNotSubmitted")} }
))}
diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts
index 3f30cc502..9743347e3 100644
--- a/src/i18n/messages/en-US/assistant.ts
+++ b/src/i18n/messages/en-US/assistant.ts
@@ -62,6 +62,7 @@ export const assistant = {
"assistant.panel.editingNotice": "Editing a stopped message. Sending it starts a new attempt.",
"assistant.panel.cancelEdit": "Cancel editing",
"assistant.panel.inheritedJobs": "Tasks already submitted ({{count}})",
+ "assistant.panel.inheritedJobNotSubmitted": "not submitted",
"assistant.panel.interrupted": "Reply interrupted",
"assistant.panel.send": "Send message",
"assistant.panel.stop": "Stop reply",
diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts
index 040c1dbcd..cb4d3b809 100644
--- a/src/i18n/messages/zh-CN/assistant.ts
+++ b/src/i18n/messages/zh-CN/assistant.ts
@@ -61,6 +61,7 @@ export const assistant = {
"assistant.panel.editingNotice": "正在编辑已停止的消息,发送后会作为新的尝试。",
"assistant.panel.cancelEdit": "取消编辑",
"assistant.panel.inheritedJobs": "已提交的任务({{count}})",
+ "assistant.panel.inheritedJobNotSubmitted": "未提交",
"assistant.panel.interrupted": "回复已中断",
"assistant.panel.send": "发送消息",
"assistant.panel.stop": "停止回复",
diff --git a/tests/test_assistant_revision.py b/tests/test_assistant_revision.py
index 5278032d7..4784d2cf6 100755
--- a/tests/test_assistant_revision.py
+++ b/tests/test_assistant_revision.py
@@ -236,12 +236,17 @@ def test_inherited_jobs_resolves_the_job_receipt_by_call_id():
done = next(item for item in snapshot if item['callId'] == 'call-done')
lost = next(item for item in snapshot if item['callId'] == 'call-lost')
- # The accepted job is resolved and its status wins over the stale tool record.
- assert done['jobId'] == str(job.id) and done['status'] == 'succeeded'
+ # The accepted job is resolved to its id.
+ assert done['jobId'] == str(job.id)
assert done['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-done'))
# A call that never produced a job keeps its command id and reports no job.
- assert lost['jobId'] is None and lost['status'] == 'failed'
+ assert lost['jobId'] is None
assert lost['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-lost'))
+ # Only identity is persisted: a status or asset copied here would go stale as
+ # the job progresses, and the expanded view would report a state that is no
+ # longer true. The job id is the handle a live lookup needs.
+ for item in snapshot:
+ assert set(item) == {'commandId', 'callId', 'name', 'jobId'}, item
def test_a_running_turn_rejects_a_concurrent_submission(assistant):
From e62b66a97aac9df186b516e54a3e87b047c68b28 Mon Sep 17 00:00:00 2001
From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com>
Date: Sat, 5 Dec 2026 14:56:22 +0800
Subject: [PATCH 3/5] [ci] python: list the revision and base test modules in
shards
---
scripts/ci/python_shards.json | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/scripts/ci/python_shards.json b/scripts/ci/python_shards.json
index c2b76342c..60281a195 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",
@@ -126,6 +128,7 @@
"tests/test_assistant_conversation_trace.py",
"tests/test_assistant_conversations.py",
"tests/test_assistant_queue.py",
+ "tests/test_assistant_revision.py",
"tests/test_cli.py",
"tests/test_cli_discovery.py",
"tests/test_deepseek_engine.py",
@@ -136,7 +139,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",
From 369f4e943d7d232c9081f2fccdbb5d8b1aebaedf Mon Sep 17 00:00:00 2001
From: Zhangbo-cn
Date: Sat, 5 Dec 2026 16:26:52 +0800
Subject: [PATCH 4/5] [bugfix] assistant: keep the conversation revision across
a turn
---
.gitignore | 2 +-
node_modules | 1 -
.../core/src/opendirector/agent/native.py | 13 +-
src/backend/chat.ts | 7 -
src/canvas/AssistantPanel.tsx | 2 -
src/canvas/chatTurnRequest.ts | 7 -
src/canvas/useAssistantChat.ts | 17 +-
tests/assistantRevision.test.ts | 1 -
tests/browser/assistant_revision.mjs | 165 ++++++++++++++++++
tests/browser/manifest.json | 10 ++
tests/test_agent_citations.py | 7 -
tests/test_assistant_revision.py | 13 --
12 files changed, 178 insertions(+), 67 deletions(-)
delete mode 120000 node_modules
mode change 100755 => 100644 src/canvas/chatTurnRequest.ts
mode change 100755 => 100644 tests/assistantRevision.test.ts
create mode 100644 tests/browser/assistant_revision.mjs
mode change 100755 => 100644 tests/test_assistant_revision.py
diff --git a/.gitignore b/.gitignore
index 791b20f0a..3846e52d4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,4 @@
-node_modules/
+node_modules
dist/
.DS_Store
diff --git a/node_modules b/node_modules
deleted file mode 120000
index 5b63a7658..000000000
--- a/node_modules
+++ /dev/null
@@ -1 +0,0 @@
-/home/ubuntu/projects/OpenDirector/node_modules
\ No newline at end of file
diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py
index 82056d0bf..e584456e7 100644
--- a/packages/core/src/opendirector/agent/native.py
+++ b/packages/core/src/opendirector/agent/native.py
@@ -160,9 +160,6 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None
def text_events(runtime: str, raw: dict) -> list[dict]:
- if 'type' not in raw:
- # Plain-text stdout the harness printed outside its event protocol.
- return []
if runtime == 'claude' and raw.get('error') == 'authentication_failed':
raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401)
if runtime == 'codex' and raw['type'] == 'error':
@@ -343,15 +340,7 @@ async def observe(raw):
deepseek_server, observe, session_id)
else:
while line := await process.stdout.readline():
- # A harness may print plain text on stdout, for example a
- # warning about an unrecognized model. Keep it in the trace
- # instead of failing the whole turn on a parse error.
- try:
- raw = json.loads(line)
- except ValueError:
- if line.strip():
- await queue.put({'native': {'text': line.decode('utf-8', 'replace')}})
- continue
+ raw = json.loads(line)
previous_session = reported_session
if runtime == 'codex' and raw['type'] == 'thread.started':
reported_session = raw.get('thread_id')
diff --git a/src/backend/chat.ts b/src/backend/chat.ts
index fbad67d84..58a4a9819 100644
--- a/src/backend/chat.ts
+++ b/src/backend/chat.ts
@@ -70,18 +70,14 @@ export interface ChatSource {
url: string;
title: string;
}
-/** A job the superseded attempt had already accepted, kept for the retry. */
export interface InheritedJob {
commandId: string;
callId: string;
name: string;
- /** Null when the earlier attempt never produced a job for this call. */
jobId: string | null;
}
export interface ChatMessage {
- /** The stopped attempt this message revises, so history keeps both. */
revisionOf?: string;
- /** Jobs accepted before the revised attempt, so it does not submit them again. */
inheritedJobs?: InheritedJob[];
publishedTimelines?: {
projectId: string;
@@ -148,7 +144,6 @@ export interface ChatDraft {
}
export interface Conversation extends ChatDraft {
messages: ChatMessage[];
- /** Increments on every accepted turn; a stale value means the view is behind. */
revision?: number;
}
@@ -192,9 +187,7 @@ export const streamedText = (
export interface ChatRequest {
conversationId?: string;
id: string;
- /** The turn this request replaces. Absent for an ordinary turn. */
revisionOf?: string;
- /** The conversation revision this request was composed against. */
expectedRevision?: number;
modelId?: string;
text: string;
diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx
index 98a2eb895..b9199e08f 100644
--- a/src/canvas/AssistantPanel.tsx
+++ b/src/canvas/AssistantPanel.tsx
@@ -67,7 +67,6 @@ function kindOf(asset: ChatAsset) {
: "text";
}
-/** The inherited calls that produced a job, so the count does not claim a submission that never happened. */
function submittedJobs(message: ChatMessage) {
return (message.inheritedJobs ?? []).filter((job) => job.jobId);
}
@@ -511,7 +510,6 @@ export function AssistantPanel({
{value.messages.map((message, index) => {
const previous = value.messages[index - 1];
const next = value.messages[index + 1];
- // Only the newest stopped attempt can be revised, matching the server.
const editable = message.role === "user" &&
next?.role === "assistant" &&
(next.status === "stopped" || next.status === "interrupted") &&
diff --git a/src/canvas/chatTurnRequest.ts b/src/canvas/chatTurnRequest.ts
old mode 100755
new mode 100644
index 0cfd42da3..39e95497a
--- a/src/canvas/chatTurnRequest.ts
+++ b/src/canvas/chatTurnRequest.ts
@@ -7,7 +7,6 @@ import type {
} from "../backend/chat.ts";
import type { ReferenceContent } from "./chatReferenceContent";
-/** The turn being edited: a stopped attempt and the draft it is replacing. */
export interface ChatEditing {
turnId: string;
conversationId: string;
@@ -26,16 +25,10 @@ export interface TurnRequest {
thinking: Thinking;
modelSelections: ModelSelections;
skills: string[];
- /** The turn this request replaces. Absent for an ordinary turn. */
revisionOf?: string;
- /** The conversation revision this request was composed against. */
expectedRevision?: number;
}
-/**
- * The request body for a turn, including the identity an edit must carry so the
- * server can validate it against the conversation it was composed on.
- */
export function turnRequest(
input: Conversation,
{
diff --git a/src/canvas/useAssistantChat.ts b/src/canvas/useAssistantChat.ts
index 570b2d5a7..75e5a3f75 100644
--- a/src/canvas/useAssistantChat.ts
+++ b/src/canvas/useAssistantChat.ts
@@ -51,10 +51,6 @@ export const attachment = ({
size,
fingerprint,
}: ChatAsset): ChatAsset => ({ id, name, type, size, fingerprint });
-/**
- * The id an uncertain submission keeps, so retrying an edit resends the same
- * operation instead of creating a second attempt.
- */
const pendingKey = (conversationId: string) =>
`opendirector.chat.revision.${conversationId}`;
const pendingTurnId = (conversationId: string) => {
@@ -73,7 +69,6 @@ const rememberPendingTurnId = (conversationId: string, id?: string) => {
if (id) store.setItem(pendingKey(conversationId), id);
else store.removeItem(pendingKey(conversationId));
} catch {
- // Storage can be unavailable; the retry then creates a fresh turn.
}
};
@@ -122,8 +117,6 @@ export function useAssistantChat(
const [threadsLoading, setThreadsLoading] = useState(false);
const [threadsError, setThreadsError] = useState("");
const [changing, setChanging] = useState(false);
- // The stopped attempt being revised: its user message id plus the draft the
- // edit replaced, so cancelling restores exactly what the user had typed.
const [editing, setEditing] = useState(null);
const switching = useRef(false);
const [error, setError] = useState("");
@@ -499,8 +492,6 @@ export function useAssistantChat(
return;
const input = current.current;
const revising = editing;
- // A retry of the same edit keeps its id, so an uncertain submission cannot
- // become a second attempt. An ordinary turn always gets a fresh one.
const id =
(revising &&
input.conversationId &&
@@ -523,15 +514,10 @@ export function useAssistantChat(
t,
);
});
- // The server accepted the attempt; the id must not be reused afterwards.
if (revising && input.conversationId)
rememberPendingTurnId(input.conversationId);
if (revising) setEditing(null);
};
- /**
- * Open a stopped attempt for editing. The conversation itself is untouched:
- * the active path only changes once the server accepts the revised turn.
- */
const beginEdit = (turn: ChatMessage) => {
if (submitting.current || !loaded) return;
const input = current.current;
@@ -553,7 +539,6 @@ export function useAssistantChat(
const next: Conversation = {
...input,
draft: turn.text,
- // Reuse the stored content so references and skills survive the edit.
draftContent: referenceContent(
turn.text,
(turn.assets ?? []).map((asset) => asset.id),
@@ -569,7 +554,6 @@ export function useAssistantChat(
setValue(next);
setError("");
};
- /** Leave editing without sending; the original message stays untouched. */
const cancelEdit = () => {
if (!editing) return;
const next: Conversation = { ...current.current, ...editing.saved };
@@ -628,6 +612,7 @@ export function useAssistantChat(
draftContent: event.conversation.draftContent,
assets: event.conversation.assets,
skills: event.conversation.skills,
+ revision: event.conversation.revision,
messages: event.conversation.messages.map((message) =>
message.status === "streaming"
? {
diff --git a/tests/assistantRevision.test.ts b/tests/assistantRevision.test.ts
old mode 100755
new mode 100644
index bc65ad0ba..3d7c06d75
--- a/tests/assistantRevision.test.ts
+++ b/tests/assistantRevision.test.ts
@@ -32,7 +32,6 @@ test("an edit names the stopped turn and the revision it was composed on", () =>
});
assert.equal(body.revisionOf, "turn-stopped");
assert.equal(body.expectedRevision, 4);
- // The revised text is what the new attempt sends, exactly once.
assert.equal(body.text, "NEW-标记");
});
diff --git a/tests/browser/assistant_revision.mjs b/tests/browser/assistant_revision.mjs
new file mode 100644
index 000000000..4155ec143
--- /dev/null
+++ b/tests/browser/assistant_revision.mjs
@@ -0,0 +1,165 @@
+import assert from "node:assert/strict";
+import { mkdirSync } from "node:fs";
+import { launchBrowser } from "./engine.mjs";
+
+mkdirSync("/tmp/evidence/424", { recursive: true });
+
+const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179";
+const headers = {
+ "X-OpenDirector-Request": "1",
+ "X-OpenDirector-Session": crypto.randomUUID(),
+};
+async function api(path, value) {
+ const response = await fetch(base + "/api" + path, {
+ headers: { ...headers, "Content-Type": "application/json" },
+ ...(value ? { method: "POST", body: JSON.stringify(value) } : {}),
+ });
+ assert.ok(response.ok, await response.clone().text());
+ return response.json();
+}
+async function until(read, matches, label) {
+ const deadline = Date.now() + 15000;
+ while (true) {
+ const value = await read();
+ if (matches(value)) return value;
+ assert.ok(Date.now() < deadline, `${label}: ${JSON.stringify(value)}`);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+}
+const health = await api("/creation-test-health");
+assert.equal(health.isolated, true);
+assert.equal(health.assistantFixture, true);
+const projectId = crypto.randomUUID();
+await api(`/creation/projects/${projectId}/commands`, {
+ type: "project.create",
+ projectId,
+ commandId: crypto.randomUUID(),
+ payload: { name: `修订 ${crypto.randomUUID().slice(0, 8)}` },
+});
+const path = `/creation/projects/${projectId}/assistant`;
+
+const browser = await launchBrowser();
+try {
+ const page = await browser.newPage({
+ locale: "zh-CN",
+ viewport: { width: 1440, height: 1000 },
+ });
+ page.setDefaultTimeout(15000);
+ const errors = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ await page.route(/\/assistant\/runtimes(?:\?.*)?$/, (route) =>
+ route.fulfill({
+ json: [
+ {
+ id: "default",
+ label: "Default",
+ group: "default",
+ modelSource: "settings",
+ available: true,
+ status: "ready",
+ modelOverride: false,
+ supportsSkills: true,
+ },
+ ],
+ }),
+ );
+ await page.addInitScript((id) => {
+ localStorage.setItem("opendirector.lastUnifiedFilesystemProject", id);
+ localStorage.setItem("opendirector.modelSetup.v1", "dismissed");
+ localStorage.setItem("opendirector.locale.v1", "zh-CN");
+ }, projectId);
+ await page.goto(base);
+ await page.getByText("已保存到本机", { exact: true }).waitFor({ state: "attached" });
+ const panel = page.getByRole("complementary", { name: "AI 对话", exact: true });
+ const editor = panel.getByRole("textbox", { name: "消息内容", exact: true });
+ const editorText = async () =>
+ (await editor.textContent()).replaceAll("\u200b", "");
+ await page.locator('[data-testid="canvas-workspace"][aria-busy="false"]').waitFor();
+ const openChat = page.getByRole("button", {
+ name: "与 AI 对话",
+ exact: true,
+ expanded: false,
+ });
+ if (await openChat.isVisible()) await openChat.click();
+ await editor.waitFor();
+ await until(
+ () => api(path),
+ (value) => !!value.modelSelections.agent,
+ "Default model must be saved",
+ );
+
+ await api("/creation-test-assistant-gate", { open: false });
+ await editor.fill("第一版:海边短片");
+ await panel.getByRole("button", { name: "发送消息", exact: true }).click();
+ await panel.getByText("已收到创作要求。", { exact: false }).waitFor();
+ const streaming = await until(
+ () => api(path),
+ (value) => value.messages.at(-1)?.status === "streaming",
+ "Reply must stream",
+ );
+ const original = streaming.messages[0].id;
+
+ await panel.getByRole("button", { name: "停止回复", exact: true }).click();
+ await until(
+ () => api(path),
+ (value) =>
+ value.messages.at(-1)?.status === "stopped" &&
+ value.activeTurnId === undefined,
+ "Stop must persist",
+ );
+ await panel.getByText("已停止回复", { exact: true }).waitFor();
+ const editButton = panel.getByRole("button", { name: "编辑并重发", exact: true });
+ await editButton.waitFor();
+ assert.equal(await panel.getByRole("button", { name: "编辑并重发", exact: true }).count(), 1);
+
+ await editButton.click();
+ await panel.getByText("正在编辑已停止的消息,发送后会作为新的尝试。", { exact: true }).waitFor();
+ assert.equal(await editorText(), "第一版:海边短片");
+ await panel.screenshot({ path: "/tmp/evidence/424/editing-zh-CN.png" });
+
+ await panel.getByRole("button", { name: "取消编辑", exact: true }).click();
+ assert.equal(await editorText(), "");
+ assert.equal(await panel.getByText("正在编辑已停止的消息,发送后会作为新的尝试。", { exact: true }).count(), 0);
+
+ await editButton.click();
+ await editor.fill("第二版:森林短片");
+ await api("/creation-test-assistant-gate", { open: true });
+ const submit = page.waitForRequest(
+ (request) =>
+ request.method() === "POST" &&
+ request.url().endsWith(`${path}/turns`),
+ );
+ await panel.getByRole("button", { name: "发送消息", exact: true }).click();
+ const body = (await submit).postDataJSON();
+ assert.equal(body.revisionOf, original, "the edit names the stopped turn");
+ assert.equal(typeof body.expectedRevision, "number", "the edit carries the conversation revision");
+ assert.equal(body.text, "第二版:森林短片");
+
+ const revised = await until(
+ () => api(path),
+ (value) =>
+ value.messages.length === 4 &&
+ value.messages.at(-1)?.status === "complete",
+ "The revised attempt must finish",
+ );
+ assert.deepEqual(
+ revised.messages.map((message) => message.text),
+ ["第一版:海边短片", "已收到创作要求。", "第二版:森林短片", "已收到创作要求。这是隔离测试回复。"],
+ "both attempts stay in history",
+ );
+ assert.equal(revised.messages[2].revisionOf, original);
+ const contexts = (await api("/creation-test-health")).assistantContexts;
+ const seen = JSON.stringify(contexts.at(-1));
+ assert.ok(seen.includes("第二版:森林短片"), "the revised text reaches the runtime");
+ assert.ok(!seen.includes("第一版:海边短片"), "the replaced request leaves the active path");
+ assert.equal(
+ await panel.getByRole("button", { name: "编辑并重发", exact: true }).count(),
+ 0,
+ "a completed reply cannot be revised",
+ );
+ await panel.screenshot({ path: "/tmp/evidence/424/revised-zh-CN.png" });
+ assert.deepEqual(errors, [], `page errors: ${errors.join("; ")}`);
+ console.log(JSON.stringify({ passed: true, checks: 12 }));
+} finally {
+ await browser.close();
+}
diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json
index 769fae4c9..c5e02cedb 100644
--- a/tests/browser/manifest.json
+++ b/tests/browser/manifest.json
@@ -105,6 +105,16 @@
],
"note": "Needs --assistant-fixture services; holds the fixture gate."
},
+ {
+ "file": "assistant_revision.mjs",
+ "fixture": true,
+ "previewSafe": true,
+ "lanes": [
+ "extendedFixture",
+ "production"
+ ],
+ "note": "Needs --assistant-fixture services; stops a reply, edits and resends it, and checks the request identity and the active path."
+ },
{
"file": "prompt_optimizer_workspace.mjs",
"previewSafe": true,
diff --git a/tests/test_agent_citations.py b/tests/test_agent_citations.py
index 3fe6f1ffc..5b66ee297 100644
--- a/tests/test_agent_citations.py
+++ b/tests/test_agent_citations.py
@@ -84,10 +84,3 @@ def test_historical_sources_reuse_prior_turn_evidence_but_do_not_follow_trace_li
(folder / f'{turn}.codex.jsonl').symlink_to(external)
conversation['messages'][-1]['text'] = 'Other\ue200cite\ue202turn2view0\ue201'
assert with_trace_sources(conversation, tmp_path)['messages'][-1]['sources'] == []
-
-
-def test_plain_stdout_outside_the_event_protocol_is_ignored():
- # A harness may print a warning on stdout, for example about an unrecognized
- # model. It must not fail the turn, and it carries no events.
- assert text_events('claude', {'text': '[claude-code:unrecognized_model]\n'}) == []
- assert text_events('codex', {'text': 'warning\n'}) == []
diff --git a/tests/test_assistant_revision.py b/tests/test_assistant_revision.py
old mode 100755
new mode 100644
index 4784d2cf6..68f83ac19
--- a/tests/test_assistant_revision.py
+++ b/tests/test_assistant_revision.py
@@ -34,14 +34,10 @@ async def empty_skills(*args):
@pytest.fixture
def assistant(tmp_path, monkeypatch):
contexts = []
- # Replies stay streaming until released, so a stop request is what ends a
- # turn and the server records ``stopped`` instead of ``complete``.
release = threading.Event()
async def stream(self, run):
contexts.append(run.messages)
- # Emit the tool record before waiting, so a stopped turn still owns the
- # accepted job a revision has to inherit.
yield {'type': 'tool', 'id': 'call-known', 'name': 'run_command', 'status': 'complete'}
while not release.is_set():
import asyncio
@@ -130,7 +126,6 @@ def test_revised_attempt_replaces_the_stopped_turn_on_the_active_path(assistant)
assert [message['id'] for message in saved['messages']].count(original) == 1, \
'the stopped turn is kept for history, not rewritten'
assert saved['messages'][-2].get('revisionOf') == original
- # Later turns continue from the revised attempt, not from the replaced one.
again = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default',
'conversationId': active, 'text': 'third'})
assert error_of(again) is None, error_of(again)
@@ -236,15 +231,10 @@ def test_inherited_jobs_resolves_the_job_receipt_by_call_id():
done = next(item for item in snapshot if item['callId'] == 'call-done')
lost = next(item for item in snapshot if item['callId'] == 'call-lost')
- # The accepted job is resolved to its id.
assert done['jobId'] == str(job.id)
assert done['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-done'))
- # A call that never produced a job keeps its command id and reports no job.
assert lost['jobId'] is None
assert lost['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-lost'))
- # Only identity is persisted: a status or asset copied here would go stale as
- # the job progresses, and the expanded view would report a state that is no
- # longer true. The job id is the handle a live lookup needs.
for item in snapshot:
assert set(item) == {'commandId', 'callId', 'name', 'jobId'}, item
@@ -260,7 +250,6 @@ def test_a_running_turn_rejects_a_concurrent_submission(assistant):
assert blocked.status_code == 409, blocked.text
finally:
finish(client, path, thread, original, captured)
- # The refused submission left no trace.
texts = [message.get('text') for message in conversation(client, path)['messages']]
assert 'concurrent' not in texts
@@ -279,7 +268,6 @@ def test_the_revision_survives_reloading_the_conversation(assistant):
reloaded = conversation(client, path)
users = [message for message in reloaded['messages'] if message['role'] == 'user']
- # The replaced request is kept for inspection, not rewritten.
assert [message['text'] for message in users] == ['OLD-标记', 'NEW-标记']
assert next(message for message in users if message['id'] == revised_id)['revisionOf'] == original
assert reloaded['revision'] == conversation(client, path)['revision']
@@ -312,5 +300,4 @@ def test_the_revised_attempt_keeps_attachments_of_the_edited_message(assistant):
assert error_of(revised) is None, error_of(revised)
new_turn = frames(revised)[0]['conversation']['messages'][-2]
assert [item['id'] for item in new_turn.get('assets') or []] == [asset]
- # The reference still reaches the runtime context of the revised attempt.
assert asset in json.dumps(contexts[-1], ensure_ascii=False)
From ba6ba6c301aa54a17496dcd3f15bed15793dc137 Mon Sep 17 00:00:00 2001
From: Zhangbo-cn
Date: Sat, 5 Dec 2026 16:31:27 +0800
Subject: [PATCH 5/5] [cleanup] browser: leave screenshots out of the revision
check
---
tests/browser/assistant_revision.mjs | 5 -----
1 file changed, 5 deletions(-)
diff --git a/tests/browser/assistant_revision.mjs b/tests/browser/assistant_revision.mjs
index 4155ec143..dfb15c211 100644
--- a/tests/browser/assistant_revision.mjs
+++ b/tests/browser/assistant_revision.mjs
@@ -1,9 +1,6 @@
import assert from "node:assert/strict";
-import { mkdirSync } from "node:fs";
import { launchBrowser } from "./engine.mjs";
-mkdirSync("/tmp/evidence/424", { recursive: true });
-
const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179";
const headers = {
"X-OpenDirector-Request": "1",
@@ -115,7 +112,6 @@ try {
await editButton.click();
await panel.getByText("正在编辑已停止的消息,发送后会作为新的尝试。", { exact: true }).waitFor();
assert.equal(await editorText(), "第一版:海边短片");
- await panel.screenshot({ path: "/tmp/evidence/424/editing-zh-CN.png" });
await panel.getByRole("button", { name: "取消编辑", exact: true }).click();
assert.equal(await editorText(), "");
@@ -157,7 +153,6 @@ try {
0,
"a completed reply cannot be revised",
);
- await panel.screenshot({ path: "/tmp/evidence/424/revised-zh-CN.png" });
assert.deepEqual(errors, [], `page errors: ${errors.join("; ")}`);
console.log(JSON.stringify({ passed: true, checks: 12 }));
} finally {