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/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py
index 37fb0ca47..a8817a9aa 100644
--- a/apps/api/src/opendirector_api/agent.py
+++ b/apps/api/src/opendirector_api/agent.py
@@ -74,6 +74,81 @@ 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.
+
+ 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)
+ 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})
+ return snapshot
def draft_content_is_empty(content):
@@ -163,7 +238,8 @@ 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,
finish_turn_id: UUID | None = None, edited_documents: dict[str, int] | None = None,
- before_begin=None, agent_session: str | None = None) -> dict:
+ before_begin=None, expected_revision: int | None = None,
+ agent_session: str | None = None) -> dict:
finish_mono, finish_at = (_monotonic(), _utc_now()) if finish is not None else (None, None)
mutating = draft is not None or begin is not None or finish is not None
with self.projects.local.transaction() as db:
@@ -190,6 +266,16 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft |
for conversation in [value, *value.get('archivedConversations', [])]
for message in conversation['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()
if agent_session is not None:
@@ -199,7 +285,8 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft |
value['messages'].append({'id': reply_id,
'role': 'assistant', 'text': '', 'status': 'streaming', 'startedAt': _utc_now(),
**{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:
# Unlike job results, directly published files can later be deleted.
@@ -278,6 +365,16 @@ def queue(self, project_id: UUID, session: str, message: dict, conversation_id:
for conversation in [value, *value.get('archivedConversations', [])]
for item in conversation['messages']):
raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409)
+ expected = message.pop('expectedRevision', None)
+ if expected is not None and expected != value.get('revision', 0):
+ raise ProjectError('对话已在别处更新,请刷新后重试。', 409)
+ revision_of = message.get('revisionOf')
+ if revision_of is not None:
+ blocked = revision_error(value['messages'], str(revision_of))
+ if blocked:
+ raise ProjectError(blocked, 409)
+ message['inheritedJobs'] = inherited_jobs(value['messages'], str(revision_of),
+ self.projects.snapshot(project_id).jobs)
if 'queueSeq' in value:
value['_queueSeq'] = value.pop('queueSeq')
value['_queueSeq'] = value.get('_queueSeq', 0) + 1
@@ -316,7 +413,8 @@ def dispatch(self, project_id: UUID, session: str | None = None,
'id': reply_id,
'role': 'assistant', 'text': '', 'status': 'streaming', 'startedAt': _utc_now(),
**{key: pending[key] for key in ('model', 'runtime') if key in pending}})
- value.update(draft='', draftContent=None, assets=[], skills=[])
+ value.update(draft='', draftContent=None, assets=[], skills=[],
+ revision=value.get('revision', 0) + 1)
durable_json(file, value)
# Same boundary as update(begin): the clock starts once the write succeeded, inside the transaction.
with self._started_lock:
@@ -728,6 +826,8 @@ async def prepare(project_id: UUID, value: Turn, session: str, accept_language:
'modelSelections': dict(value.modelSelections), 'model': model,
'modelIsCliDefault': model_is_cli_default,
'thinking': value.thinking, 'status': 'complete',
+ **({'revisionOf': str(value.revisionOf)} if value.revisionOf is not None else {}),
+ **({'expectedRevision': value.expectedRevision} if value.expectedRevision is not None else {}),
**({'modelConfigId': str(value.modelId)} if value.modelId else {})}}
async def plan_for(project_id: UUID, message: dict, session: str, directory: Path, accept_language: str | None) -> dict:
@@ -786,12 +886,13 @@ async def renew_session() -> None:
chain.conversation_id = UUID(saved['conversationId'])
chain.events.put({'type': 'start', 'conversation': saved})
renewal = asyncio.create_task(renew_session())
- previous_sources = {source['id']: source for reply in saved['messages'][:-2]
+ active = active_messages(saved['messages'])
+ previous_sources = {source['id']: source for reply in active[:-2]
for source in reply.get('sources', [])}
snapshot = await asyncio.to_thread(projects.snapshot, project_id)
assets = {str(asset.id): asset for asset in snapshot.assets}
context = []
- for reply in saved['messages'][:-1]:
+ for reply in active[:-1]:
content = reply['text'] or '(empty reply)'
bound = [TurnReference.model_validate(ref).observation() for ref in reply.get('turnReferences', [])]
if bound:
@@ -816,7 +917,7 @@ async def renew_session() -> None:
model_selections=plan['model_selections'], runtime_model=message.get('runtimeModel'),
skills=plan['available'], conversation_id=chain.conversation_id, edited_documents=edited_documents,
turn_references=tuple(TurnReference.model_validate(ref) for ref in message.get('turnReferences', [])),
- earlier_references=tuple(TurnReference.model_validate(ref) for reply in saved['messages'][:-2]
+ earlier_references=tuple(TurnReference.model_validate(ref) for reply in active[:-2]
for ref in reply.get('turnReferences', [])))
async with aclosing(runtimes.stream(run)) as stream:
async for event in stream:
diff --git a/scripts/ci/python_shards.json b/scripts/ci/python_shards.json
index 56d52ff47..4c02ec3f2 100644
--- a/scripts/ci/python_shards.json
+++ b/scripts/ci/python_shards.json
@@ -19,6 +19,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",
diff --git a/src/backend/chat.ts b/src/backend/chat.ts
index 0223ea3e1..58a4a9819 100644
--- a/src/backend/chat.ts
+++ b/src/backend/chat.ts
@@ -70,7 +70,15 @@ export interface ChatSource {
url: string;
title: string;
}
+export interface InheritedJob {
+ commandId: string;
+ callId: string;
+ name: string;
+ jobId: string | null;
+}
export interface ChatMessage {
+ revisionOf?: string;
+ inheritedJobs?: InheritedJob[];
publishedTimelines?: {
projectId: string;
eventCursor?: number;
@@ -91,6 +99,7 @@ export interface ChatMessage {
content?: ReferenceContent | null;
status: "complete" | "streaming" | "stopped" | "interrupted";
assets?: ChatAsset[];
+ skills?: string[];
model?: string | null;
modelIsCliDefault?: boolean;
runtimeModel?: string | null;
@@ -135,6 +144,7 @@ export interface ChatDraft {
}
export interface Conversation extends ChatDraft {
messages: ChatMessage[];
+ revision?: number;
}
export function draftContentIsEmpty(
@@ -177,6 +187,8 @@ export const streamedText = (
export interface ChatRequest {
conversationId?: string;
id: string;
+ revisionOf?: string;
+ expectedRevision?: number;
modelId?: string;
text: string;
content?: ReferenceContent | null;
diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx
index 58f6f6149..b9199e08f 100644
--- a/src/canvas/AssistantPanel.tsx
+++ b/src/canvas/AssistantPanel.tsx
@@ -1,6 +1,12 @@
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 {
+ runtimeModels,
+ type AssistantModelSelection,
+ type ChatAsset,
+ type ChatMessage,
+ type ModelSelections,
+} from "../backend/chat";
import { assistantModelSelection } from "./agentPreferences";
import { creationClient } from "../backend/creationClient.ts";
import { fingerprint } from "../backend/generation.ts";
@@ -61,6 +67,10 @@ function kindOf(asset: ChatAsset) {
: "text";
}
+function submittedJobs(message: ChatMessage) {
+ return (message.inheritedJobs ?? []).filter((job) => job.jobId);
+}
+
/** Shared conversation and composer for chat creation and the canvas assistant. */
export function AssistantPanel({
documentId,
@@ -499,6 +509,12 @@ export function AssistantPanel({
)}
{value.messages.map((message, index) => {
const previous = value.messages[index - 1];
+ const next = value.messages[index + 1];
+ 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,
@@ -604,6 +620,33 @@ export function AssistantPanel({
{t("assistant.panel.trace")} ↗
)}
+ {editable && (
+
+ )}
+ {!!submittedJobs(message).length && (
+
+
+ {t("assistant.panel.inheritedJobs", {
+ count: submittedJobs(message).length,
+ })}
+
+