Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 90 additions & 5 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand All @@ -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']]
Expand Down Expand Up @@ -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', []):
Expand Down
13 changes: 12 additions & 1 deletion packages/core/src/opendirector/agent/native.py
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand Down Expand Up @@ -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')
Expand Down
21 changes: 21 additions & 0 deletions src/backend/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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;
Expand Down
44 changes: 43 additions & 1 deletion src/canvas/AssistantPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -487,6 +494,33 @@ export function AssistantPanel({
{t("assistant.panel.trace")} ↗
</a>
)}
{editable && (
<button
type="button"
className="cw-assistant-message-edit"
disabled={!!chat.editing}
onClick={() => chat.beginEdit(message)}
>
{t("assistant.panel.editResend")}
</button>
)}
{!!message.inheritedJobs?.length && (
<details className="cw-assistant-inherited">
<summary>
{t("assistant.panel.inheritedJobs", {
count: message.inheritedJobs.length,
})}
</summary>
<ul>
{message.inheritedJobs.map((job) => (
<li key={job.commandId}>
<span>{job.name}</span>
<small>{job.status}</small>
</li>
))}
</ul>
</details>
)}
{message.role === "user" && !!message.assets?.length && <AttachmentStrip projectId={documentId} assets={message.assets.map(resolveAsset)} />}
{(message.status === "stopped" ||
message.status === "interrupted") && (
Expand All @@ -500,7 +534,15 @@ export function AssistantPanel({
);
})}
</div>
<div className="cw-assistant-composer-area">
<div className={`cw-assistant-composer-area${chat.editing ? " is-editing" : ""}`}>
{chat.editing && (
<div className="cw-assistant-editing" role="status">
<span>{t("assistant.panel.editingNotice")}</span>
<button type="button" onClick={chat.cancelEdit}>
{t("assistant.panel.cancelEdit")}
</button>
</div>
)}
{chat.error && (
<div className="cw-assistant-error" role="alert">
<span>{chat.error}</span>
Expand Down
56 changes: 56 additions & 0 deletions src/canvas/assistant-panel.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading