Skip to content
Open
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
node_modules/
node_modules
dist/
.DS_Store

Expand Down
113 changes: 107 additions & 6 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
1 change: 1 addition & 0 deletions scripts/ci/python_shards.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
12 changes: 12 additions & 0 deletions src/backend/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -135,6 +144,7 @@ export interface ChatDraft {
}
export interface Conversation extends ChatDraft {
messages: ChatMessage[];
revision?: number;
}

export function draftContentIsEmpty(
Expand Down Expand Up @@ -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;
Expand Down
55 changes: 53 additions & 2 deletions src/canvas/AssistantPanel.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -604,6 +620,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>
)}
{!!submittedJobs(message).length && (
<details className="cw-assistant-inherited">
<summary>
{t("assistant.panel.inheritedJobs", {
count: submittedJobs(message).length,
})}
</summary>
<ul>
{(message.inheritedJobs ?? []).map((job) => (
<li key={job.commandId}>
<span>{job.name}</span>
{!job.jobId && <small>{t("assistant.panel.inheritedJobNotSubmitted")}</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 @@ -617,7 +660,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>
)}
{readOnly && projectAssetsButton}
{chat.error && (
<div className="cw-assistant-error" role="alert">
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 @@ -352,6 +352,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