From 1f3a8d4ecf45576d42ac53dee04b3828cde51dcf Mon Sep 17 00:00:00 2001
From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
Date: Thu, 19 Nov 2026 11:36:54 +0000
Subject: [PATCH 1/4] [feat] agent: add read-only conversation trace index
---
apps/api/src/opendirector_api/agent.py | 64 +++++++++++++
tests/test_assistant_conversation_trace.py | 104 +++++++++++++++++++++
2 files changed, 168 insertions(+)
create mode 100644 tests/test_assistant_conversation_trace.py
diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py
index f516685b..49a28174 100644
--- a/apps/api/src/opendirector_api/agent.py
+++ b/apps/api/src/opendirector_api/agent.py
@@ -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()
@@ -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')
diff --git a/tests/test_assistant_conversation_trace.py b/tests/test_assistant_conversation_trace.py
new file mode 100644
index 00000000..6a236a24
--- /dev/null
+++ b/tests/test_assistant_conversation_trace.py
@@ -0,0 +1,104 @@
+import json
+from uuid import uuid4
+
+from test_assistant_conversations import assistant, send # noqa: F401
+
+
+def conversation_file(tmp_path):
+ return next(tmp_path.rglob('agent-runs/conversation.json'))
+
+
+def test_trace_lists_executed_turns_in_order_with_their_own_runtime(assistant, tmp_path):
+ client, path, _ = assistant
+ conversation = client.get(path).json()['conversationId']
+ for text in ('第一轮', '第二轮', '第三轮'):
+ send(client, path, conversation, text)
+ file = conversation_file(tmp_path)
+ saved = json.loads(file.read_text())
+ ids = [message['id'] for message in saved['messages'] if message['role'] == 'user']
+ # Turns keep the runtime persisted with them, not one for the whole conversation.
+ saved['messages'][3]['runtime'] = 'codex'
+ saved['messages'][5]['runtime'] = 'deepseek'
+ file.write_text(json.dumps(saved))
+
+ result = client.get(f'{path}/conversations/{conversation}/trace')
+ assert result.status_code == 200
+ body = result.json()
+ assert body['conversationId'] == conversation and body['active'] is True
+ assert [(turn['id'], turn['number'], turn['text'], turn['runtime']) for turn in body['turns']] == [
+ (ids[0], 1, '第一轮', 'default'), (ids[1], 2, '第二轮', 'codex'), (ids[2], 3, '第三轮', 'deepseek')]
+ assert all(turn['status'] == 'complete' for turn in body['turns'])
+
+
+def test_trace_ignores_messages_that_never_executed_and_does_not_pair_by_position(assistant, tmp_path):
+ client, path, _ = assistant
+ conversation = client.get(path).json()['conversationId']
+ send(client, path, conversation, '已执行')
+ file = conversation_file(tmp_path)
+ saved = json.loads(file.read_text())
+ executed = saved['messages'][0]['id']
+ # A queued or inserted user message sits between executed turns without an assistant record.
+ saved['messages'].insert(1, {'id': str(uuid4()), 'role': 'user', 'text': '排队中'})
+ saved['messages'].insert(0, {'id': 'not-a-uuid', 'role': 'user', 'text': '坏数据'})
+ saved['messages'].append({'id': str(uuid4()), 'role': 'assistant', 'text': '孤立回复', 'status': 'complete'})
+ file.write_text(json.dumps(saved))
+
+ turns = client.get(f'{path}/conversations/{conversation}/trace').json()['turns']
+ assert [(turn['id'], turn['text']) for turn in turns] == [(executed, '已执行')]
+
+
+def test_interrupted_streaming_turn_is_not_reported_as_running(assistant, tmp_path):
+ client, path, _ = assistant
+ conversation = client.get(path).json()['conversationId']
+ send(client, path, conversation, '中断')
+ file = conversation_file(tmp_path)
+ saved = json.loads(file.read_text())
+ saved['messages'][1]['status'] = 'streaming'
+ file.write_text(json.dumps(saved))
+ turns = client.get(f'{path}/conversations/{conversation}/trace').json()['turns']
+ assert turns[0]['status'] == 'interrupted'
+
+
+def test_trace_resolves_archived_and_aliased_conversations_without_activating(assistant, tmp_path):
+ client, path, _ = assistant
+ first = client.get(path).json()['conversationId']
+ send(client, path, first, '旧对话')
+ second = str(uuid4())
+ assert client.post(path + '/conversations', json={'id': second}).status_code == 200
+ send(client, path, second, '新对话')
+ before = conversation_file(tmp_path).read_bytes()
+
+ archived = client.get(f'{path}/conversations/{first}/trace').json()
+ current = client.get(f'{path}/conversations/{second}/trace').json()
+ assert archived['active'] is False and [turn['text'] for turn in archived['turns']] == ['旧对话']
+ assert current['active'] is True and [turn['text'] for turn in current['turns']] == ['新对话']
+ assert conversation_file(tmp_path).read_bytes() == before
+ assert client.get(path + '/conversations').json()['activeId'] == second
+
+ saved = json.loads(before)
+ saved['reusedCreateIds'] = [str(uuid4())]
+ alias = saved['reusedCreateIds'][0]
+ conversation_file(tmp_path).write_text(json.dumps(saved))
+ assert client.get(f'{path}/conversations/{alias}/trace').json()['conversationId'] == second
+
+
+def test_trace_of_unknown_conversation_is_404_and_empty_conversation_has_no_turns(assistant):
+ client, path, _ = assistant
+ assert client.get(f'{path}/conversations/{uuid4()}/trace').status_code == 404
+ conversation = client.get(path).json()['conversationId']
+ assert client.get(f'{path}/conversations/{conversation}/trace').json()['turns'] == []
+
+
+def test_turn_resolves_to_its_own_conversation_including_archived(assistant):
+ client, path, _ = assistant
+ first = client.get(path).json()['conversationId']
+ send(client, path, first, '旧对话')
+ old_turn = client.get(f'{path}/conversations/{first}/trace').json()['turns'][0]['id']
+ second = str(uuid4())
+ client.post(path + '/conversations', json={'id': second})
+ send(client, path, second, '新对话')
+ new_turn = client.get(f'{path}/conversations/{second}/trace').json()['turns'][0]['id']
+ assert client.get(f'{path}/traces/{old_turn}/conversation').json() == {'conversationId': first}
+ assert client.get(f'{path}/traces/{new_turn}/conversation').json() == {'conversationId': second}
+ assert client.get(f'{path}/traces/{uuid4()}/conversation').status_code == 404
+ assert client.get(path + '/conversations').json()['activeId'] == second
From 24341127f89fce12b69432216e9da63bb4d26beb Mon Sep 17 00:00:00 2001
From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
Date: Thu, 19 Nov 2026 11:38:51 +0000
Subject: [PATCH 2/4] [feat] agent: show every turn of a conversation on one
trace page
---
src/canvas/AssistantPanel.tsx | 2 +
src/canvas/AssistantTracePage.tsx | 145 ++++++++++++++++++++++++++----
src/canvas/assistant-trace.css | 19 ++++
src/canvas/traceTurns.ts | 39 ++++++++
src/i18n/messages/en-US/trace.ts | 8 ++
src/i18n/messages/zh-CN/trace.ts | 8 ++
tests/traceTurns.test.ts | 29 ++++++
7 files changed, 234 insertions(+), 16 deletions(-)
create mode 100644 src/canvas/traceTurns.ts
create mode 100644 tests/traceTurns.test.ts
diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx
index 93615664..e37b6a91 100644
--- a/src/canvas/AssistantPanel.tsx
+++ b/src/canvas/AssistantPanel.tsx
@@ -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" } : {}),
@@ -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",
});
diff --git a/src/canvas/AssistantTracePage.tsx b/src/canvas/AssistantTracePage.tsx
index e1560dca..a07a40e8 100644
--- a/src/canvas/AssistantTracePage.tsx
+++ b/src/canvas/AssistantTracePage.tsx
@@ -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";
@@ -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(null);
const [traces, setTraces] = useState([]);
const [showModel, setShowModel] = useState(false);
@@ -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 };
@@ -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;
@@ -267,10 +263,7 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
}, [project, turn, live, runtime]);
return (
-
-
- {t("trace.title")}
- {turn}
+ <>
{runtime === "opencode" && (
)}
-
{!rawModel && input !== null && }
{status === 200 ? (
rawModel && !traces[0]?.trim() ? (
@@ -296,6 +288,127 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
t("trace.loadFailed")}
)}
{jobs.length > 0 && }
+ >
+ );
+}
+
+const STATUS_KEYS: Record = {
+ 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>(() => new Set());
+ const [loaded, setLoaded] = useState>(() => 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 (
+ <>
+
+ {turns.length === 0 && {t("trace.turns.empty")}
}
+ {turns.map((item) => (
+ toggle(item.id, event.currentTarget.open)}>
+
+ {t("trace.turn.number", { number: item.number })}
+ {item.text}
+
+ {runtimeName(item.runtime)}
+ {t(STATUS_KEYS[item.status])}
+
+
+ {loaded.has(item.id) && (
+
+ )}
+
+ ))}
+ >
+ );
+}
+
+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 (
+
+
+ {wide ? t("trace.conversationTitle") : t("trace.title")}
+ {!wide && {turn}
}
+
+ {conversation === undefined ? {t("trace.loading")}
: wide ? (
+
+ ) : (
+
+ )}
);
}
diff --git a/src/canvas/assistant-trace.css b/src/canvas/assistant-trace.css
index 665cb166..6d612878 100644
--- a/src/canvas/assistant-trace.css
+++ b/src/canvas/assistant-trace.css
@@ -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; }
+}
diff --git a/src/canvas/traceTurns.ts b/src/canvas/traceTurns.ts
new file mode 100644
index 00000000..ad68dae5
--- /dev/null
+++ b/src/canvas/traceTurns.ts
@@ -0,0 +1,39 @@
+/** Turn index of a conversation on the Trace page, and the per-turn runtime choices. */
+import { normalizeClaudeTrace } from "./claudeTrace.ts";
+import { normalizeCodexTrace } from "./codexTrace.ts";
+import { normalizeDeepseekTrace } from "./deepseekTrace.ts";
+
+export type ConversationTurn = {
+ id: string;
+ number: number;
+ text: string;
+ runtime: string;
+ model: string | null;
+ status: "streaming" | "complete" | "stopped" | "interrupted";
+};
+
+const RUNTIME_NAMES: Record = {
+ default: "OpenCode", opencode: "OpenCode", codex: "Codex", claude: "Claude Code",
+ jiuwenswarm: "JiuwenSwarm", deepseek: "DeepSeek Harness",
+};
+
+/** The Default runtime logs under the opencode source. */
+export const traceRuntime = (runtime: string) => runtime === "default" ? "opencode" : runtime;
+
+export const runtimeName = (runtime: string) => RUNTIME_NAMES[runtime] ?? runtime;
+
+/** Log sources read for a runtime. Only opencode records raw model requests. */
+export const traceSources = (runtime: string) => runtime === "opencode" ? ["model", runtime] : [runtime];
+
+/** Each runtime keeps its own log format; the page never applies one runtime's parser to another turn. */
+export function normalizeTrace(source: string, body: string): string {
+ return source === "deepseek" ? normalizeDeepseekTrace(body)
+ : source === "codex" ? normalizeCodexTrace(body)
+ : source === "claude" ? normalizeClaudeTrace(body)
+ : body;
+}
+
+/** The linked turn if the conversation lists it, otherwise the latest turn. */
+export function initialTurn(turns: ConversationTurn[], target: string): string {
+ return turns.some((item) => item.id === target) ? target : turns.at(-1)?.id ?? "";
+}
diff --git a/src/i18n/messages/en-US/trace.ts b/src/i18n/messages/en-US/trace.ts
index f372cd08..115e1762 100644
--- a/src/i18n/messages/en-US/trace.ts
+++ b/src/i18n/messages/en-US/trace.ts
@@ -35,6 +35,14 @@ export const trace = {
"trace.jobs.adopted": "Adopted",
"trace.jobs.notAdopted": "Not adopted",
"trace.jobs.cancelRequested": "Cancel requested",
+ "trace.conversationTitle": "Conversation trace",
+ "trace.turns.nav": "Turns",
+ "trace.turns.empty": "This conversation has no executed turns.",
+ "trace.turn.number": "Turn {number}",
+ "trace.turn.status.streaming": "Running",
+ "trace.turn.status.complete": "Complete",
+ "trace.turn.status.stopped": "Stopped",
+ "trace.turn.status.interrupted": "Interrupted",
"trace.loading": "Loading…",
"trace.waiting": "Waiting for trace events…",
"trace.notFound": "No trace of this type for this turn.",
diff --git a/src/i18n/messages/zh-CN/trace.ts b/src/i18n/messages/zh-CN/trace.ts
index f57d9c50..6a43d6ad 100644
--- a/src/i18n/messages/zh-CN/trace.ts
+++ b/src/i18n/messages/zh-CN/trace.ts
@@ -35,6 +35,14 @@ export const trace = {
"trace.jobs.adopted": "已采用",
"trace.jobs.notAdopted": "未采用",
"trace.jobs.cancelRequested": "已请求取消",
+ "trace.conversationTitle": "对话轨迹",
+ "trace.turns.nav": "轮次",
+ "trace.turns.empty": "该对话还没有已执行的轮次。",
+ "trace.turn.number": "第 {number} 轮",
+ "trace.turn.status.streaming": "运行中",
+ "trace.turn.status.complete": "已完成",
+ "trace.turn.status.stopped": "已停止",
+ "trace.turn.status.interrupted": "已中断",
"trace.loading": "加载中…",
"trace.waiting": "等待首条轨迹…",
"trace.notFound": "该轮没有此类轨迹。",
diff --git a/tests/traceTurns.test.ts b/tests/traceTurns.test.ts
new file mode 100644
index 00000000..efd5462f
--- /dev/null
+++ b/tests/traceTurns.test.ts
@@ -0,0 +1,29 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { initialTurn, normalizeTrace, runtimeName, traceRuntime, traceSources, type ConversationTurn } from "../src/canvas/traceTurns.ts";
+
+const turn = (id: string, number: number, runtime = "default"): ConversationTurn =>
+ ({ id, number, text: id, runtime, model: null, status: "complete" });
+
+test("each turn reads its own runtime's log sources", () => {
+ assert.deepEqual(traceSources(traceRuntime("default")), ["model", "opencode"]);
+ assert.deepEqual(traceSources(traceRuntime("codex")), ["codex"]);
+ assert.deepEqual(traceSources(traceRuntime("deepseek")), ["deepseek"]);
+ assert.equal(runtimeName("deepseek"), "DeepSeek Harness");
+ assert.equal(runtimeName("unknown"), "unknown");
+});
+
+test("normalizers are selected by the turn's source, other sources pass through", () => {
+ const body = '{"event":"model.request"}\n';
+ assert.equal(normalizeTrace("opencode", body), body);
+ assert.equal(normalizeTrace("model", body), body);
+ assert.notEqual(normalizeTrace("codex", '{"type":"thread.started"}\n'), undefined);
+});
+
+test("linked turn is opened, otherwise the latest", () => {
+ const turns = [turn("a", 1), turn("b", 2, "codex"), turn("c", 3, "deepseek")];
+ assert.equal(initialTurn(turns, "a"), "a");
+ assert.equal(initialTurn(turns, ""), "c");
+ assert.equal(initialTurn(turns, "missing"), "c");
+ assert.equal(initialTurn([], "a"), "");
+});
From 2de2acc0ccbe18c7a4e0b56eb5526378ee885e64 Mon Sep 17 00:00:00 2001
From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
Date: Thu, 19 Nov 2026 11:42:06 +0000
Subject: [PATCH 3/4] [docs] agent: describe the conversation trace page and
its read-only index
---
docs/architecture/agent-runtime.md | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md
index 25d9d104..b7112235 100644
--- a/docs/architecture/agent-runtime.md
+++ b/docs/architecture/agent-runtime.md
@@ -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.
From 96e741591e5c5d802fe1f4b9da9544e378cd3a40 Mon Sep 17 00:00:00 2001
From: snoopyIsADog <35551877+yefuyou@users.noreply.github.com>
Date: Thu, 19 Nov 2026 21:13:35 +0800
Subject: [PATCH 4/4] [ci] retrigger checks after transient Ubuntu apt mirror
timeout
No source changes. The isolated browser check failed before running tests because the GitHub-hosted runner could not download libvpx7 and libx264-163 from the Ubuntu mirrors (apt exit 100).