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
35 changes: 24 additions & 11 deletions docs/development/turn-timing.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[中文](turn-timing.zh-CN.md)

Issue #468. This page records what "turn duration" means for the Assistant (Slice A, implemented) and the design of the Trace Timing Overview (Slice B, design only, not implemented). The code in `apps/api/src/opendirector_api/agent.py` (`Conversations.update`, `Conversations.trace`) and `src/canvas/turnTiming.ts` is the source of truth for Slice A.
Issue #468. This page records what "turn duration" means for the Assistant (Slice A, implemented) and the Trace Timing Overview (Slice B, implemented). The code in `apps/api/src/opendirector_api/agent.py` (`Conversations.update`, `Conversations.trace`) and `src/canvas/turnTiming.ts` is the source of truth for Slice A; `src/canvas/traceTimingOverview.ts` and `src/canvas/TraceTimingOverview.tsx` are the source of truth for Slice B.

## Slice A: recorded timing

Expand Down Expand Up @@ -44,18 +44,18 @@ Each assistant message in `agent-runs/conversation.json` can carry:

`src/canvas/turnTiming.ts` is the only formatter. `820 ms`, `12.4 s`, `2m 5s`, `1h 2m`. `AssistantReply.tsx` shows `status · duration` only when a duration exists. `AssistantTracePage.tsx` shows the duration, or `Unavailable`, for every turn that is not running.

## Slice B design: Trace Timing Overview
## Slice B: Trace Timing Overview

Status: design only. Slice B adds no backend field, endpoint or event timestamp.
Status: implemented in `src/canvas/traceTimingOverview.ts` (pure model) and `src/canvas/TraceTimingOverview.tsx` (component). Slice B adds no backend field, endpoint or event timestamp.

### Choice: Per-turn Duration Comparison

The overview is a **Per-turn Duration Comparison**. It does not draw a wall-clock timeline. Gaps between one turn's end and the next user message are time the user spent reading or typing, not agent work, so they are not drawn and no idle time is shown.

### Component layering

1. `traceTiming.ts`: a pure model. Input: the `turns` array from the trace response. Output: one row per turn with `id`, `number`, `runtime`, `status`, `durationMs | null`, `ratio | null`. No React, no fetching, unit tested.
2. `TraceTimingOverview`: a presentational component rendered inside `AssistantTracePage`. It receives the rows and a `reveal(turnId)` callback. It does not fetch.
1. `traceTimingOverview.ts`: a pure model. Input: the `turns` array from the trace response. Output: one row per turn with `id`, `number`, `status`, `kind`, `durationMs | null`, `fraction | null`, `zero` and `slowest`. No React, no fetching, unit tested.
2. `TraceTimingOverview.tsx`: a presentational component rendered inside `AssistantTracePage`. It receives the turns, the selected turn ID and the `reveal(turnId)` callback. It does not fetch.
3. `AssistantTracePage` keeps owning data loading and the existing scroll and open logic. `AssistantPanel.tsx` is not changed.

### Data source
Expand All @@ -64,21 +64,21 @@ Only the existing `GET .../conversations/{id}/trace` response. The overview neve

### Bar computation

- `ratio = durationMs / max(durationMs)` over the turns of the loaded conversation that have a duration. All bars share one scale.
- `fraction = durationMs / max(durationMs)` over the turns of the loaded conversation that have a duration. All bars share one scale.
- The horizontal axis is a duration scale. It is reliable only as relative length. Bars do not align to times of day, and two bars side by side do not imply one started after the other finished.
- A conversation with one timed turn shows a full-width bar. Zero durations render a minimum-width bar so the turn stays visible.
- A conversation with one timed turn shows a full-width bar. A zero duration gets a thin marker instead of a bar; any other bar has a minimum visible width.
- Each bar shows the formatted duration from `formatTurnDuration`.

### Running and Unknown

- **Running** (`streaming`, live): the bar has no end. It is animated or hatched. Elapsed time is computed from `startedAt` for display only, labelled approximate, and is excluded from `max` so it does not rescale other bars.
- **Unknown** (no `durationMs`, including legacy and restart-interrupted turns): a hatched placeholder with the label "Unavailable". It is excluded from `max`.
- **Running** (`streaming`, live): only the status badge. No bar and no elapsed or provisional duration. It is excluded from `max`, so it does not rescale other bars.
- **Unknown** (no `durationMs`, including legacy and restart-interrupted turns): no bar, with the label "Unavailable". It is excluded from `max`.

### Interaction

- Click, or Enter or Space on a bar, calls `reveal(turnId)`, which uses the existing logic to scroll to and open that turn.
- Bars are `button` elements in a list. Each has `aria-label` of the form "Turn N, runtime, status, duration". Arrow-key roving focus is optional.
- Narrow screens: bars stack below the summary row, labels are truncated, and horizontal scrolling is never required.
- Bars are `button` elements in a list. Each has an `aria-label` of the form "Select turn N, status, duration", with the status named once. Arrow-key roving focus is not implemented.
- Narrow screens: the row keeps one line with narrower columns, and horizontal scrolling is never required.

### Jobs

Expand All @@ -103,3 +103,16 @@ PR #469 (issue #449) records where a turn's time goes. The two features measure
| Read by | `scripts/bench_turn_timing.py` | Trace API, Chat and Trace UI |

The two windows share nearly the same end. The start differs by the pre-accept work in `produce()` (validation, model availability, the `begin` write), usually milliseconds, so the numbers are not expected to match. Neither is derived from the other. Each keeps its own monotonic clock: #469's clock lives in `produce()` and a ledger of tool events, ours lives in `Conversations.update`, which is the only place that sees both the accept and the finish write. Persistence does not conflict: #469 writes a separate file, this work writes the message. Do not show `turnSeconds` in the UI and do not read `durationMs` in the ledger.

### Trace timing overview

The Conversation Trace page shows a compact overview above the turn list. Each turn is one button row with its number, status, a bar and the duration. Bar length is linear against the longest finished turn. It reads only the persisted `durationMs` of each turn, never `startedAt`/`finishedAt`, and it does not load any trace logs.

- A running turn shows "Running" and no bar. A missing or invalid `durationMs` shows "Unavailable" and no bar.
- Stopped and interrupted turns show their status and bar when `durationMs` is valid.
- A zero duration gets a thin marker instead of a bar. Any other bar has a minimum visible width.
- With two or more timed turns, the slowest one is marked with an accent colour, a symbol and an accessible label.
- Selecting a row (click, Enter, Space) reuses the existing reveal: it opens the turn, lazy-loads its trace and scrolls to it.
- If no turn has valid timing, the overview shows "No timing data" and the turn list works as before.

Logic lives in `src/canvas/traceTimingOverview.ts`. The overview adds none of the #449 metrics.
35 changes: 24 additions & 11 deletions docs/development/turn-timing.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[English](turn-timing.md)

Issue #468。本文记录 Assistant“轮次耗时”的含义(Slice A,已实现)和 Trace 计时概览的设计(Slice B,仅设计,未实现)。Slice A 以 `apps/api/src/opendirector_api/agent.py`(`Conversations.update`、`Conversations.trace`)和 `src/canvas/turnTiming.ts` 的代码为准。
Issue #468。本文记录 Assistant“轮次耗时”的含义(Slice A,已实现)和 Trace 计时概览(Slice B,已实现)。Slice A 以 `apps/api/src/opendirector_api/agent.py`(`Conversations.update`、`Conversations.trace`)和 `src/canvas/turnTiming.ts` 的代码为准;Slice B 以 `src/canvas/traceTimingOverview.ts` 和 `src/canvas/TraceTimingOverview.tsx` 的代码为准。

## Slice A:已记录的计时

Expand Down Expand Up @@ -44,18 +44,18 @@ Issue #468。本文记录 Assistant“轮次耗时”的含义(Slice A,已

`src/canvas/turnTiming.ts` 是唯一的格式化入口:`820 ms`、`12.4 s`、`2m 5s`、`1h 2m`。`AssistantReply.tsx` 仅在存在时长时显示“状态 · 时长”。`AssistantTracePage.tsx` 对每个非进行中的轮次显示时长或“不可用”。

## Slice B 设计:Trace 计时概览
## Slice B:Trace 计时概览

状态:仅设计。Slice B 不新增后端字段、接口或事件时间戳。
状态:已实现,入口为 `src/canvas/traceTimingOverview.ts`(纯模型)和 `src/canvas/TraceTimingOverview.tsx`(组件)。Slice B 不新增后端字段、接口或事件时间戳。

### 选择:逐轮耗时对比

概览是**逐轮耗时对比**(Per-turn Duration Comparison),不绘制挂钟时间线。一个轮次结束到下一条用户消息之间的间隔是用户阅读或输入的时间,不是 agent 工作,因此不绘制,也不显示空闲时间。

### 组件分层

1. `traceTiming.ts`:纯模型。输入为 trace 响应中的 `turns`,输出每个轮次一行:`id`、`number`、`runtime`、`status`、`durationMs | null`、`ratio | null`。不含 React 和请求,带单元测试。
2. `TraceTimingOverview`:渲染在 `AssistantTracePage` 内的展示组件。接收行数据和 `reveal(turnId)` 回调,不发起请求。
1. `traceTimingOverview.ts`:纯模型。输入为 trace 响应中的 `turns`,输出每个轮次一行:`id`、`number`、`status`、`kind`、`durationMs | null`、`fraction | null`、`zero` 和 `slowest`。不含 React 和请求,带单元测试。
2. `TraceTimingOverview.tsx`:渲染在 `AssistantTracePage` 内的展示组件。接收轮次数据、选中的轮次 ID 和 `reveal(turnId)` 回调,不发起请求。
3. `AssistantTracePage` 继续负责数据加载以及现有的滚动与展开逻辑。不修改 `AssistantPanel.tsx`。

### 数据来源
Expand All @@ -64,21 +64,21 @@ Issue #468。本文记录 Assistant“轮次耗时”的含义(Slice A,已

### 条形计算

- `ratio = durationMs / max(durationMs)`,范围是已加载会话中有时长的轮次,所有条形共用同一比例尺。
- `fraction = durationMs / max(durationMs)`,范围是已加载会话中有时长的轮次,所有条形共用同一比例尺。
- 横轴是时长刻度,只有相对长度可靠。条形不对应具体时刻,并排的两个条形也不表示一个在另一个结束后才开始。
- 只有一个有时长的轮次时显示满宽条形。时长为 0 时显示最小宽度条形,使该轮次仍可见。
- 只有一个有时长的轮次时显示满宽条形。时长为 0 时显示细标记而不是条形,其他条形有最小可见宽度。
- 每个条形显示 `formatTurnDuration` 格式化后的时长。

### 进行中与未知

- **进行中**(`streaming`,实时):条形没有终点,使用动画或斜纹。已用时间仅用于显示,由 `startedAt` 计算并标注为近似值,且不计入 `max`,不会使其他条形重新缩放。
- **未知**(没有 `durationMs`,包括旧数据和重启中断的轮次):斜纹占位并标注“不可用”,不计入 `max`。
- **进行中**(`streaming`,实时):只显示状态徽标,不绘制条形,也不显示已用时间或临时时长。不计入 `max`,不会使其他条形重新缩放。
- **未知**(没有 `durationMs`,包括旧数据和重启中断的轮次):不绘制条形,标注“不可用”,不计入 `max`。

### 交互

- 点击条形,或在条形上按 Enter 或 Space,调用 `reveal(turnId)`,沿用现有逻辑滚动到并展开该轮次。
- 条形是列表中的 `button` 元素,`aria-label` 形如“Turn N,运行时,状态,时长”。方向键漫游焦点为可选项。
- 窄屏:条形堆叠在摘要行下方,标签截断,永远不需要横向滚动。
- 条形是列表中的 `button` 元素,`aria-label` 形如“选择第 N 轮,状态,时长”,状态只出现一次。未实现方向键漫游焦点。
- 窄屏:每行保持一行,列宽收窄,永远不需要横向滚动。

### Jobs

Expand All @@ -103,3 +103,16 @@ PR #469(issue #449)记录一个轮次的时间花在哪里。两项功能度
| 读取方 | `scripts/bench_turn_timing.py` | Trace API、Chat 与 Trace 界面 |

两个窗口的终点几乎相同,起点相差 `produce()` 中接受前的工作(校验、模型可用性检查、`begin` 写入),通常为毫秒级,数值不要求完全一致,也不互相推导。各自保留单调时钟:#469 的时钟在 `produce()` 和工具事件账本中,本工作的时钟在 `Conversations.update`,那里是唯一同时看到接受与 finish 写入的位置。持久化不冲突:#469 写独立文件,本工作写消息。UI 不展示 `turnSeconds`,账本不读取 `durationMs`。

### Trace 耗时概览

对话 Trace 页面在轮次列表上方显示紧凑的耗时概览。每个轮次对应一个按钮行,包含编号、状态、条形和耗时。条形长度相对已结束轮次中最长的一个按线性比例绘制。概览只读取各轮已持久化的 `durationMs`,不使用 `startedAt`/`finishedAt`,也不加载任何 Trace 日志。

- 运行中的轮次显示“运行中”,不绘制条形。`durationMs` 缺失或无效时显示“不可用”,不绘制条形。
- 已停止和已中断的轮次在 `durationMs` 有效时显示状态与条形。
- 耗时为零时显示细标记而不是条形,其他条形有最小可见宽度。
- 有两个及以上带耗时的轮次时,最慢的一轮以强调色、符号和无障碍文本标出。
- 选中某行(点击、Enter、空格)复用现有的定位逻辑:展开该轮、懒加载其 Trace 并滚动到位。
- 若没有任何轮次有有效耗时,概览显示“暂无耗时数据”,轮次列表照常可用。

逻辑位于 `src/canvas/traceTimingOverview.ts`。概览不引入 #449 的任何指标。
13 changes: 10 additions & 3 deletions src/canvas/AssistantTracePage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useT } from "../i18n/I18nProvider";
import type { MessageKey } from "../i18n/types";
import { memo, useEffect, useMemo, useRef, useState } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";

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

Expand All @@ -9,6 +9,7 @@ import { initialTurn, runtimeName, traceRuntime, traceSources, type Conversation

import { createTraceCursor, type TraceSnapshot } from "./traceCursor.ts";
import { readTurnJobs, turnJobView, type TurnJob } from "./traceJobs.ts";
import TraceTimingOverview from "./TraceTimingOverview.tsx";
import { downloadFile } from "./assets.ts";
import { conversationTraceArchive, TraceExportError } from "./traceExport.ts";

Expand Down Expand Up @@ -313,6 +314,7 @@ function ConversationTrace({ project, conversationId, target, turns }: {
const t = useT();
const [open, setOpen] = useState<Set<string>>(() => new Set());
const [loaded, setLoaded] = useState<Set<string>>(() => new Set());
const [selected, setSelected] = useState<string | null>(null);
const placed = useRef(false);
const initial = initialTurn(turns, target);
const [exporting, setExporting] = useState(false);
Expand Down Expand Up @@ -360,12 +362,16 @@ function ConversationTrace({ project, conversationId, target, turns }: {
if (value) next.add(id); else next.delete(id);
return next;
});
// Opening selects the turn. Closing keeps the selection: it marks the last turn the user worked on, and the turnnav shows open state.
if (value) setSelected(id);
if (value) setLoaded((previous) => previous.has(id) ? previous : new Set(previous).add(id));
}
function reveal(id: string) {
// Only calls state setters, so it is stable and memoized overview rows are not re-rendered by it.
const reveal = useCallback((id: string) => {
setSelected(id);
toggle(id, true);
window.requestAnimationFrame(() => document.getElementById(`turn-${id}`)?.scrollIntoView({ block: "start" }));
}
}, []);
useEffect(() => {
if (placed.current || !initial) return;
placed.current = true;
Expand All @@ -382,6 +388,7 @@ function ConversationTrace({ project, conversationId, target, turns }: {
{running && !exporting && <span role="status">{t("trace.export.blockedRunning")}</span>}
{exportError && <span role="alert">{exportError}</span>}
</div>
<TraceTimingOverview turns={turns} selected={selected} onSelect={reveal} />
<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)}
Expand Down
68 changes: 68 additions & 0 deletions src/canvas/TraceTimingOverview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { memo, useEffect, useMemo, useRef } from "react";
import { useT } from "../i18n/I18nProvider";
import { barPercent, buildTimingOverview, statusBadgeClass, type OverviewRow } from "./traceTimingOverview.ts";
import { formatTurnDuration, TURN_STATUS_KEYS } from "./turnTiming.ts";
import type { ConversationTurn } from "./traceTurns.ts";

const OverviewItem = memo(function OverviewItem({ row, selected, onSelect }: {
row: OverviewRow; selected: boolean; onSelect: (id: string) => void;
}) {
const t = useT();
const status = row.status ? t(TURN_STATUS_KEYS[row.status]) : t("trace.turn.duration.unavailable");
// A running turn has only its status badge: no bar and no duration text.
const duration = row.kind === "running" ? ""
: formatTurnDuration(row.durationMs) ?? t("trace.turn.duration.unavailable");
const label = [t("trace.overview.select", { number: row.number }), status,
row.kind === "timed" ? duration : row.kind === "unavailable" ? t("trace.turn.duration.unavailable") : "",
row.slowest ? t("trace.overview.slowest") : "", row.zero ? t("trace.overview.zero") : ""]
.filter(Boolean).join(", ");
return (
<li>
<button type="button" data-turn-id={row.id} className={`cw-trace-overview-row${row.slowest ? " is-slowest" : ""}`}
aria-pressed={selected} aria-label={label} onClick={() => onSelect(row.id)}>
<span className="cw-trace-overview-number">{row.number}</span>
<span className={`cw-trace-badge ${statusBadgeClass(row.status)}`} aria-hidden="true">{status}</span>
<span className="cw-trace-overview-track" aria-hidden="true">
{row.fraction !== null && !row.zero && (
<span className="cw-trace-overview-bar" style={{ width: `${barPercent(row.fraction)}%` }} />
)}
{row.zero && <span className="cw-trace-overview-zero" />}
</span>
<span className="cw-trace-overview-value" aria-hidden="true">
{duration}{row.slowest && <span className="cw-trace-overview-flag"> ▲</span>}
</span>
</button>
</li>
);
});

export default function TraceTimingOverview({ turns, selected, onSelect }: {
turns: ConversationTurn[]; selected: string | null; onSelect: (id: string) => void;
}) {
const t = useT();
const overview = useMemo(() => buildTimingOverview(turns), [turns]);
const list = useRef<HTMLOListElement>(null);
// Keep the selected row visible by moving only the list's own scrollTop, never the page.
useEffect(() => {
const box = list.current;
if (!box || selected === null) return;
const row = Array.from(box.querySelectorAll<HTMLElement>("[data-turn-id]")).find((el) => el.dataset.turnId === selected);
if (!row) return;
const top = row.getBoundingClientRect().top - box.getBoundingClientRect().top;
const bottom = row.getBoundingClientRect().bottom - box.getBoundingClientRect().bottom;
if (top < 0) box.scrollTop += top;
else if (bottom > 0) box.scrollTop += bottom;
}, [selected, overview]);
if (overview.rows.length === 0) return null;
return (
<section className="cw-trace-overview" aria-label={t("trace.overview.title")}>
<h2>{t("trace.overview.title")}</h2>
{!overview.hasTiming && <p role="status">{t("trace.overview.noData")}</p>}
<ol ref={list} className="cw-trace-overview-list">
{overview.rows.map((row) => (
<OverviewItem key={row.id} row={row} selected={row.id === selected} onSelect={onSelect} />
))}
</ol>
</section>
);
}
Loading
Loading