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
64 changes: 64 additions & 0 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,60 @@ def list(self, project_id: UUID) -> dict:
'hasDraft': bool((item.get('draft') or '').strip() or item.get('assets') or item.get('skills'))}
for item in [current, *current.get('archivedConversations', [])]]}

def trace(self, project_id: UUID, conversation_id: UUID, running: UUID | None = None) -> dict:
"""Executed turns of one conversation, read-only: no lease, no activation, no log bodies.

A turn is a user message together with the assistant message whose id is derived from
it (``uuid5(user id, 'assistant')``), which is how a turn is persisted when it is accepted.
A user message without that assistant record was never executed and is not a turn.
"""
directory = self.path(project_id)
file = child(child(directory, 'agent-runs'), 'conversation.json')
with self.projects.local.transaction():
current = read_json(file) if file.is_file() else {'messages': []}
current['conversationId'] = current.get('conversationId') or str(uuid5(project_id, 'assistant'))
requested = str(conversation_id)
found = next((item for item in [current, *current.get('archivedConversations', [])]
if item.get('conversationId') == requested or requested in reused_ids(item)), None)
if found is None:
raise ProjectError('对话不存在。', 404)
replies = {message.get('id'): message for message in found.get('messages', [])
if message.get('role') == 'assistant'}
turns = []
for message in found.get('messages', []):
if message.get('role') != 'user':
continue
try:
reply = replies.get(str(uuid5(UUID(message['id']), 'assistant')))
except (KeyError, ValueError, TypeError):
reply = None
if reply is None:
continue
status = reply.get('status') or 'complete'
if status == 'streaming' and (found is not current or running != UUID(message['id'])):
status = 'interrupted'
turns.append({'id': message['id'], 'number': len(turns) + 1,
'text': (message.get('text') or '')[:200],
'runtime': reply.get('runtime') or message.get('runtime') or 'default',
'model': reply.get('model') or message.get('model'),
'status': status})
return {'conversationId': found['conversationId'], 'active': found is current, 'turns': turns}

def conversation_of(self, project_id: UUID, turn_id: UUID) -> str:
"""Id of the conversation that persisted this executed turn, current or archived."""
directory = self.path(project_id)
file = child(child(directory, 'agent-runs'), 'conversation.json')
with self.projects.local.transaction():
current = read_json(file) if file.is_file() else {}
current['conversationId'] = current.get('conversationId') or str(uuid5(project_id, 'assistant'))
reply = str(uuid5(turn_id, 'assistant'))
for item in [current, *current.get('archivedConversations', [])]:
messages = item.get('messages', [])
if (any(m.get('role') == 'user' and m.get('id') == str(turn_id) for m in messages)
and any(m.get('role') == 'assistant' and m.get('id') == reply for m in messages)):
return item['conversationId']
raise ProjectError('该轮用户消息不存在。', 404)

def activate(self, project_id: UUID, conversation_id: UUID, session: str, *, create=False) -> dict:
with self.projects.local.transaction() as db:
self.projects._recover()
Expand Down Expand Up @@ -250,6 +304,16 @@ def agent_routes(projects, generation, configs, provider=None) -> APIRouter:
conversations = Conversations(projects)
runtimes = AgentRuntimes(projects, generation, configs, provider)

@router.get('/conversations/{conversation_id}/trace')
def conversation_trace(project_id: UUID, conversation_id: UUID):
running = active.get(project_id)
live = running[0] if running and not running[1].done() else None
return conversations.trace(project_id, conversation_id, live)

@router.get('/traces/{turn_id}/conversation')
def trace_conversation(project_id: UUID, turn_id: UUID):
return {'conversationId': conversations.conversation_of(project_id, turn_id)}

@router.get('/traces/{turn_id}/input')
def trace_input(project_id: UUID, turn_id: UUID):
file = child(child(conversations.path(project_id), 'agent-runs'), 'conversation.json')
Expand Down
6 changes: 6 additions & 0 deletions docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,9 @@ Windows 上的 Codex 启动显式设置 `windows.sandbox="elevated"`,避免隔
On Windows, Codex explicitly sets `windows.sandbox="elevated"` so ignoring user configuration does not downgrade `workspace-write` to read-only and block Shell execution. Sandbox restrictions remain enabled. Discover the CLI with `Get-Command opendirector` in PowerShell or `command -v opendirector` in POSIX shells.

CLI 通过环境变量中的本轮本地 Socket 地址连接业务网关,不使用连接令牌或凭据文件。网关继续校验工程范围、轮次生命周期及业务输入。

## 对话轨迹页 / Conversation trace page

轨迹页 `/?traceProject=…&conversation=…&turn=…` 在一页内按顺序列出一个对话的全部已执行轮次,每轮可独立展开,展开时才读取该轮日志与关联 Job。轮次索引来自只读接口 `GET .../assistant/conversations/{conversation_id}/trace`,它解析当前对话、已归档对话和 `reusedCreateIds` 别名,只返回轮次元数据(序号、用户输入摘要、运行时、状态),不读取日志正文,不激活对话,不获取编辑租约。轮次由持久化的身份关系确定:用户消息与 id 为 `uuid5(用户消息 id, 'assistant')` 的助手消息成对才算已执行的一轮;没有该助手记录的用户消息(例如排队中、未执行)不出现。每轮使用自己记录的运行时选择日志源和解析器,仅 Default(opencode)显示模型原始请求。`GET .../traces/{turn_id}/conversation` 供旧的单轮链接查找所属对话;找不到时保持原单轮页面。

English summary: the trace page lists every executed turn of a conversation, expanded one at a time, and reads a turn's logs and linked Jobs only when it is opened. The turn index comes from the read-only `GET .../assistant/conversations/{conversation_id}/trace`, which resolves current, archived and aliased (`reusedCreateIds`) conversation ids and returns metadata only (number, input summary, runtime, status). It never reads log bodies, activates a conversation or takes a lease. A turn is a user message paired with the assistant message whose id is `uuid5(user id, 'assistant')`, so queued or never executed user messages are not listed. Each turn uses its own recorded runtime for the log source and parser, and raw model requests are offered for the Default (opencode) runtime only. `GET .../traces/{turn_id}/conversation` lets old single-turn links find their conversation; when none is found the single-turn page remains.
2 changes: 2 additions & 0 deletions src/canvas/AssistantPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ export function AssistantPanel({
const latestTrace = latestReply?.role === "assistant" && latestUser?.role === "user" &&
new URLSearchParams({
traceProject: documentId,
...(value.conversationId ? { conversation: value.conversationId } : {}),
turn: latestUser.id,
runtime: latestReply.runtime === "default" ? "opencode" : latestReply.runtime ?? "opencode",
...(latestReply.status === "streaming" ? { live: "1" } : {}),
Expand Down Expand Up @@ -416,6 +417,7 @@ export function AssistantPanel({
const trace = message.role === "assistant" && message !== latestReply && message.status !== "streaming" &&
previous?.role === "user" && new URLSearchParams({
traceProject: documentId,
...(value.conversationId ? { conversation: value.conversationId } : {}),
turn: previous.id,
runtime: message.runtime === "default" ? "opencode" : message.runtime ?? "opencode",
});
Expand Down
145 changes: 129 additions & 16 deletions src/canvas/AssistantTracePage.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { useT } from "../i18n/I18nProvider";
import type { MessageKey } from "../i18n/types";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";

import { traceCategory, isThinkingTokenEstimate, readableTraceValue } from "./traceCategory.ts";

import { normalizeClaudeTrace } from "./claudeTrace.ts";
import { normalizeCodexTrace } from "./codexTrace.ts";
import { normalizeDeepseekTrace } from "./deepseekTrace.ts";
import { initialTurn, normalizeTrace, runtimeName, traceRuntime, traceSources, type ConversationTurn } from "./traceTurns.ts";

import { readTurnJobs, turnJobView, type TurnJob } from "./traceJobs.ts";

Expand Down Expand Up @@ -207,11 +205,9 @@ function TraceJobs({ jobs }: { jobs: TurnJob[] }) {
);
}

export default function AssistantTracePage({ params }: { params: URLSearchParams }) {
const project = params.get("traceProject") ?? "";
const turn = params.get("turn") ?? "";
const runtime = params.get("runtime") ?? "opencode";
const live = params.get("live") === "1";
function TurnTrace({ project, turn, runtime, live }: {
project: string; turn: string; runtime: string; live: boolean;
}) {
const [input, setInput] = useState<string | null>(null);
const [traces, setTraces] = useState<string[]>([]);
const [showModel, setShowModel] = useState(false);
Expand All @@ -223,7 +219,7 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
useEffect(() => {
const controller = new AbortController();
const [projectPath, turnPath] = [project, turn].map(encodeURIComponent);
const sources = runtime === "opencode" ? ["model", runtime] : [runtime];
const sources = traceSources(runtime);
setInput(null);
const traceUrl = `/api/creation/projects/${projectPath}/assistant/traces/${turnPath}`;
const options = { headers: { "X-OpenDirector-Request": "1" }, signal: controller.signal };
Expand All @@ -244,7 +240,7 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
const snapshots = await Promise.all(sources.map(async (name) => {
const response = await fetch(`${traceUrl}/${encodeURIComponent(name)}`, options);
const body = response.ok ? await response.text() : "";
return { status: response.status, body: name === "deepseek" ? normalizeDeepseekTrace(body) : name === "codex" ? normalizeCodexTrace(body) : name === "claude" ? normalizeClaudeTrace(body) : body };
return { status: response.status, body: normalizeTrace(name, body) };
}));
const nextJobs = await jobsRequest;
const status = snapshots.some((item) => item.status === 200) ? 200 : snapshots[0].status;
Expand All @@ -267,10 +263,7 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
}, [project, turn, live, runtime]);

return (
<main className="cw-trace-page">
<header className="cw-trace-header">
<h1>{t("trace.title")}</h1>
<p><code>{turn}</code></p>
<>
{runtime === "opencode" && (
<nav className="cw-trace-tabs" aria-label={t("trace.views")}>
<button type="button" aria-pressed={!rawModel} onClick={() => setShowModel(false)}>
Expand All @@ -281,7 +274,6 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
</button>
</nav>
)}
</header>
{!rawModel && input !== null && <TraceRow kind="user" summary={input} value={input} />}
{status === 200 ? (
rawModel && !traces[0]?.trim() ? (
Expand All @@ -296,6 +288,127 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
t("trace.loadFailed")}</p>
)}
{jobs.length > 0 && <TraceJobs jobs={jobs} />}
</>
);
}

const STATUS_KEYS: Record<ConversationTurn["status"], MessageKey> = {
streaming: "trace.turn.status.streaming", complete: "trace.turn.status.complete",
stopped: "trace.turn.status.stopped", interrupted: "trace.turn.status.interrupted",
};

function ConversationTrace({ project, target, turns }: {
project: string; target: string; turns: ConversationTurn[];
}) {
const t = useT();
const [open, setOpen] = useState<Set<string>>(() => new Set());
const [loaded, setLoaded] = useState<Set<string>>(() => new Set());
const placed = useRef(false);
const initial = initialTurn(turns, target);

function toggle(id: string, value: boolean) {
setOpen((previous) => {
if (previous.has(id) === value) return previous;
const next = new Set(previous);
if (value) next.add(id); else next.delete(id);
return next;
});
if (value) setLoaded((previous) => previous.has(id) ? previous : new Set(previous).add(id));
}
function reveal(id: string) {
toggle(id, true);
window.requestAnimationFrame(() => document.getElementById(`turn-${id}`)?.scrollIntoView({ block: "start" }));
}
useEffect(() => {
if (placed.current || !initial) return;
placed.current = true;
reveal(initial);
}, [initial]);

return (
<>
<nav className="cw-trace-turnnav" aria-label={t("trace.turns.nav")}>
{turns.map((item) => (
<button key={item.id} type="button" aria-pressed={open.has(item.id)}
title={item.text} onClick={() => reveal(item.id)}>{item.number}</button>
))}
</nav>
{turns.length === 0 && <p role="status">{t("trace.turns.empty")}</p>}
{turns.map((item) => (
<details key={item.id} id={`turn-${item.id}`} className="cw-trace-turn"
open={open.has(item.id)} onToggle={(event) => toggle(item.id, event.currentTarget.open)}>
<summary>
<span className="cw-trace-turn-number">{t("trace.turn.number", { number: item.number })}</span>
<span className="cw-trace-preview">{item.text}</span>
<span className="cw-trace-turn-meta">
<span>{runtimeName(item.runtime)}</span>
<span className={`cw-trace-badge is-turn-${item.status}`}>{t(STATUS_KEYS[item.status])}</span>
</span>
</summary>
{loaded.has(item.id) && (
<TurnTrace project={project} turn={item.id} runtime={traceRuntime(item.runtime)}
live={item.status === "streaming"} />
)}
</details>
))}
</>
);
}

export default function AssistantTracePage({ params }: { params: URLSearchParams }) {
const project = params.get("traceProject") ?? "";
const turn = params.get("turn") ?? "";
const runtime = params.get("runtime") ?? "opencode";
const live = params.get("live") === "1";
const requested = params.get("conversation");
// undefined: not resolved yet. null: no conversation could be found, show the single turn.
const [conversation, setConversation] = useState<{ id: string; turns: ConversationTurn[] } | null | undefined>();
const t = useT();

useEffect(() => {
const controller = new AbortController();
let timer: number | undefined;
const base = `/api/creation/projects/${encodeURIComponent(project)}/assistant`;
const options = { headers: { "X-OpenDirector-Request": "1" }, signal: controller.signal };
async function load() {
try {
let id = requested;
if (!id && turn) {
const found = await fetch(`${base}/traces/${encodeURIComponent(turn)}/conversation`, options);
if (found.ok) id = ((await found.json()) as { conversationId: string }).conversationId;
}
const response = id ? await fetch(`${base}/conversations/${encodeURIComponent(id)}/trace`, options) : null;
if (controller.signal.aborted) return;
if (!response?.ok) return setConversation((previous) => previous === undefined ? null : previous);
const body = await response.json() as { conversationId: string; turns: ConversationTurn[] };
setConversation((previous) => JSON.stringify(previous) === JSON.stringify(body) ? previous : { id: body.conversationId, turns: body.turns });
if (body.turns.some((item) => item.status === "streaming"))
timer = window.setTimeout(load, 2000);
} catch {
if (!controller.signal.aborted) setConversation((previous) => previous === undefined ? null : previous);
}
}
void load();
return () => {
controller.abort();
window.clearTimeout(timer);
};
}, [project, turn, requested]);

// A link to a turn that the conversation does not list keeps the single-turn view.
const listed = conversation?.turns.some((item) => item.id === turn) ?? false;
const wide = conversation && (listed || !turn);
return (
<main className="cw-trace-page">
<header className="cw-trace-header">
<h1>{wide ? t("trace.conversationTitle") : t("trace.title")}</h1>
{!wide && <p><code>{turn}</code></p>}
</header>
{conversation === undefined ? <p role="status">{t("trace.loading")}</p> : wide ? (
<ConversationTrace project={project} target={turn} turns={conversation.turns} />
) : (
<TurnTrace project={project} turn={turn} runtime={runtime} live={live} />
)}
</main>
);
}
19 changes: 19 additions & 0 deletions src/canvas/assistant-trace.css
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,22 @@
.cw-trace-job .cw-trace-preview { white-space: normal; overflow-wrap: anywhere; }
.cw-trace-badge.is-job-succeeded { background: #254034; color: #91d6ab; }
.cw-trace-badge.is-job-failed, .cw-trace-badge.is-job-interrupted { background: #4d2a2a; color: #f0a3a3; }

.cw-trace-tabs { padding: 8px 20px; }
.cw-trace-turnnav { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 20px; border-bottom: 1px solid #3c3c3c; background: #272727; }
.cw-trace-turnnav button { min-width: 28px; border: 1px solid #444; border-radius: 4px; padding: 2px 8px; background: transparent; color: #bbb; font: inherit; cursor: pointer; }
.cw-trace-turnnav button:hover { background: #303030; }
.cw-trace-turnnav button[aria-pressed="true"] { border-color: #4d5d6d; background: #303c48; color: #d6e8f7; }
.cw-trace-turn { border-bottom: 1px solid #444; scroll-margin-top: 48px; }
.cw-trace-turn > summary { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 12px; padding: 10px 20px; background: #2a2a2a; cursor: pointer; font-weight: 600; }
.cw-trace-turn > summary:hover, .cw-trace-turn[open] > summary { background: #303030; }
.cw-trace-turn-number { white-space: nowrap; }
.cw-trace-turn-meta { display: flex; align-items: center; gap: 8px; color: #aaa; font-size: 12px; font-weight: 400; white-space: nowrap; }
.cw-trace-badge.is-turn-streaming { background: #30415c; color: #a6c7ff; }
.cw-trace-badge.is-turn-complete { background: #254034; color: #91d6ab; }
.cw-trace-badge.is-turn-stopped { background: #473829; color: #f0c38b; }
.cw-trace-badge.is-turn-interrupted { background: #4d2a2a; color: #f0a3a3; }
@media (max-width: 600px) {
.cw-trace-turn > summary { grid-template-columns: auto minmax(0, 1fr); }
.cw-trace-turn-meta { grid-column: 1 / -1; }
}
Loading
Loading