Public: anyone can read this; the crew can change it.

An imported session's steps carry their tokens and the page shows them, where the file holds them #18372

opened this

Merged 4h 8m ago, live in production

scout/forge:scout/18367-an-imported-session-s-steps-carry-their → main 0 commits fork

  • Merged. scout/18367-an-imported-session-s-steps-carry-their was merged into main as 5739158.

Review

Sign in to review this change.
4 files changed +110 −5
docs/features/traces.md +2 −2
@@ -32,7 +32,7 @@ Terminal: on a run's trace (`src/tui/screens/trace.ts`) `c` reads it against the
3232
3333 MCP: the `trace` tool, `action` `list`, `read`, `compare` (`with`), `share`, `unshare`. `list` is `GET /api/v1/traces` for `repo`: one reader serves both (`readListAsk` and `listSeenTraces` in `src/trace/tree.ts`, gated as a run's log is), so the tool's body is the API's `{ items, next_cursor }` and it takes the API's filters `kind`, `model`, `outcome` (ok, failed, cancelled, stopped), `since`, `until`, `limit` and `cursor`; a malformed one is refused with the API's error code. `read` answers the trace as `rows` and `tree`, the very tree `GET /api/v1/traces/:id` answers (`treeOf` in `src/trace/tree.ts`, built from the one parse that gave the rows, behind the API's gate on the row; `null` where the run is not in the trace index). `compare` answers the API's table. A viewer who may not read a run gets from the tool what the API gives them: not found, an empty list.
3434
35 Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` and `src/trace/codex.ts` (the readers), `src/trace/session.ts` (which one), `src/trace/otlp.ts` (the export). Not yet: storing an import, tokens and cost per step (the file holds none).
35 Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` and `src/trace/codex.ts` (the readers), `src/trace/session.ts` (which one), `src/trace/otlp.ts` (the export). Not yet: cost per step or per import (prices change; the file holds none).
3636
3737 The file is read whole, then parsed, so the 256 MB limit is memory-bound: a session near it holds a few copies at once. Streaming the read is a later step.
3838
@@ -54,7 +54,7 @@ For Codex, point the same command at a rollout: `--data-binary @"$(ls -t ~/.code
5454
5555 A new source is one file implementing `ImportAdapter` (`src/trace/import_adapter.ts`, see `import_claude_code.ts`) and one line in `ADAPTERS`; Codex rollouts are taken the same way (`import_codex.ts`). Not yet: deleting one.
5656
57 `/traces/<id>` of an imported trace (#18357) is the same tree and strip a crew run has, read from the stored file (`src/trace/imported_read.ts`, `src/web/pages/trace_imported.ts`), with `#step-N` permalinks and each step's raw lines (the file's lines that name it) on demand at `/traces/<id>/steps/<n>`. Only the importer reads it; anyone else gets the not-found an unknown id gets. A session holds no cost, and often no tokens: the page says "not recorded in this file" rather than zero. Steps are capped at 20,000. `GET /api/v1/traces/<id>` answers the same tree for an imported id.
57 `/traces/<id>` of an imported trace (#18357) is the same tree and strip a crew run has, read from the stored file (`src/trace/imported_read.ts`, `src/web/pages/trace_imported.ts`), with `#step-N` permalinks and each step's raw lines (the file's lines that name it) on demand at `/traces/<id>/steps/<n>`. Only the importer reads it; anyone else gets the not-found an unknown id gets. Each step line shows the tokens its file held for it (`5 in, 7 cached, 9 out`; a reply split across records is counted once) and the total is their sum; a session holds no cost, and sometimes no tokens: the page says "not recorded in this file" rather than zero. Steps are capped at 20,000. `GET /api/v1/traces/<id>` answers the same tree for an imported id.
5858 ## One trace as a tree (#18022)
5959
6060 `GET /api/v1/traces/:id` answers the thread, its turns and their steps as one tree, rebuilt from the raw log with `parseRunLog` (a Talk turn's log is a run log): the thread's figures are the list's row (model, account, tokens in, cached and out, cost, outcome, started, ended, steps, errors), each step has its start and end in ms, kind, name, line, model, tokens and outcome (a run log holds no tokens per step, so those are 0). `timed` is false where the log kept no times. `truncated` is true when the log's start was cut (it is read from its last 512 KB) or it holds more than `MAX_STEPS` (20,000) steps. A trace the caller may not see answers exactly as an unknown id: 404 `not_found`. The tree is answered whole (about 15 ms for 5,000 steps). Code: `readTraceTree` in `src/http/api/traces.ts`.
src/trace/read.ts +9 −1
@@ -94,12 +94,20 @@ export function stepTime(s: Pick<Step, "startMs" | "endMs">, timed: boolean): st
9494 return timed ? `${spanWords(s.endMs - s.startMs)}, at ${spanWords(s.endMs)}` : undefined;
9595 }
9696
97 /**
98 * What a step cost in tokens where its file held them: `5 in, 7 cached, 9 out`; none, undefined.
99 */
100 export function stepTokens(s: Pick<Step, "tokensIn" | "tokensCached" | "tokensOut">): string | undefined {
101 return s.tokensIn + s.tokensCached + s.tokensOut === 0 ? undefined : `${s.tokensIn} in, ${s.tokensCached} cached, ${s.tokensOut} out`;
102 }
103
97104 /**
98105 * A step as one terminal or page line: its number, the line, and what it took and when it ended.
99106 */
100107 export function stepLine(s: Step, n: number, total: number, timed = false): string {
101108 const t = stepTime(s, timed);
102 return `${n}/${total} ${s.outcome === "error" ? "✗ " : ""}${s.line}${t === undefined ? "" : ` (${t})`}`;
109 const k = stepTokens(s);
110 return `${n}/${total} ${s.outcome === "error" ? "✗ " : ""}${s.line}${t === undefined ? "" : ` (${t})`}${k === undefined ? "" : ` [${k}]`}`;
103111 }
104112
105113 /** What the net diff says in words, shared by the page and the terminal. */
src/web/pages/trace.ts +3 −2
@@ -12,7 +12,7 @@ import { sharedNow } from "../../actions/trace_share.ts";
1212 import type { Ctx } from "../../http/context.ts";
1313 import { securityFloor } from "../../http/respond.ts";
1414 import { branchesOf, stepNumber } from "../../trace/run_log.ts";
15 import { changedWords, readTrace, spanWords, stepLine, stepPayload, stepTime, stepsInView, traceHref, type TraceView } from "../../trace/read.ts";
15 import { changedWords, readTrace, spanWords, stepLine, stepPayload, stepTime, stepTokens, stepsInView, traceHref, type TraceView } from "../../trace/read.ts";
1616 import type { Step } from "../../trace/model.ts";
1717 import { crumbsFor, notFoundPage, pageHead, repoPalette } from "../chrome.ts";
1818 import { html, type Html } from "../html.ts";
@@ -60,8 +60,9 @@ var i=s.indexOf(document.activeElement);i=e.key==='j'?Math.min(s.length-1,i+1):M
6060
6161 function stepNode(s: Step, n: number, total: number, children: Html | null, base: string, open: boolean, timed: boolean): Html {
6262 const took = stepTime(s, timed);
63 const spent = stepTokens(s);
6364 return html`<details class="trace-step trace-${s.kind}${s.outcome === "error" ? " trace-bad" : ""}" id="${s.id}" data-n="${String(n)}"${open ? html` open` : null}>
64 <summary><span class="trace-n mono">${String(n)}/${String(total)}</span>${s.outcome === "error" ? "✗ " : ""}${s.line}${took === undefined ? null : html`<span class="trace-time small">${took}</span>`} <a class="small muted" href="${base}/steps/${String(n)}">raw</a></summary>
65 <summary><span class="trace-n mono">${String(n)}/${String(total)}</span>${s.outcome === "error" ? "✗ " : ""}${s.line}${took === undefined ? null : html`<span class="trace-time small">${took}</span>`}${spent === undefined ? null : html`<span class="trace-time small trace-tokens">${spent}</span>`} <a class="small muted" href="${base}/steps/${String(n)}">raw</a></summary>
6566 <pre class="trace-raw mono" aria-label="Raw lines of step ${String(n)}"></pre>
6667 ${children}
6768 </details>`;
test/trace-imported-tokens.test.ts added +96
@@ -0,0 +1,96 @@
1 /** An imported session's steps carry their tokens, and the page and API show them (#18367). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createToken } from "../src/core/tokens.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { parseCodexSession } from "../src/trace/codex.ts";
10 import { parseClaudeSession } from "../src/trace/claude_code.ts";
11 import { stepsOf, totalsOf } from "../src/trace/model.ts";
12 import { seedAdmin } from "./helpers/admin.ts";
13
14 const rec = (o: object): string => JSON.stringify({ sessionId: "sess-t", cwd: "/w", ...o });
15 const reply = (id: string, ts: string, content: object[], usage?: unknown) =>
16 rec({ type: "assistant", timestamp: ts, message: { id, model: "claude-x", role: "assistant", content, ...(usage === undefined ? {} : { usage }) } });
17 const prompt = rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "go" } });
18
19 const WITH = [
20 prompt,
21 reply("m1", "2026-12-01T09:00:01Z", [{ type: "text", text: "Looking" }], { input_tokens: 5, cache_read_input_tokens: 7, output_tokens: 1 }),
22 // The same reply again, one block per record: counted once.
23 reply("m1", "2026-12-01T09:00:02Z", [{ type: "tool_use", id: "t1", name: "Read", input: { file_path: "a.ts" } }], { input_tokens: 5, cache_read_input_tokens: 7, output_tokens: 9 }),
24 reply("m2", "2026-12-01T09:00:05Z", [{ type: "text", text: "Done" }], { input_tokens: 6, output_tokens: 2 }),
25 ].join("\n");
26 const WITHOUT = [prompt, reply("m1", "2026-12-01T09:00:01Z", [{ type: "text", text: "Hi" }])].join("\n");
27 const MALFORMED = [prompt, reply("m1", "2026-12-01T09:00:01Z", [{ type: "text", text: "Hi" }], { input_tokens: "lots", cache_read_input_tokens: -4, output_tokens: { n: 1 } })].join("\n");
28
29 test("per-step tokens are read once per message and total as their sum", () => {
30 const t = parseClaudeSession(WITH);
31 expect(stepsOf(t).map((s) => [s.tokensIn, s.tokensCached, s.tokensOut])).toEqual([[5, 7, 9], [0, 0, 0], [6, 0, 2]]);
32 expect(totalsOf(t)).toMatchObject({ tokensIn: 11, tokensCached: 7, tokensOut: 11 });
33 });
34
35 test("a file without usage, or with a malformed value, yields 0, never a figure or a crash", () => {
36 for (const text of [WITHOUT, MALFORMED]) expect(totalsOf(parseClaudeSession(text))).toMatchObject({ tokensIn: 0, tokensCached: 0, tokensOut: 0 });
37 expect(parseClaudeSession(`${prompt}\n${rec({ type: "assistant", message: { id: "m", usage: "x", content: [] } })}`).skipped).toBe(0);
38 });
39
40 test("a Codex token_count lands on the reply it follows; a malformed one is ignored", () => {
41 const line = (type: string, payload: object) => JSON.stringify({ timestamp: "2026-12-01T09:00:01Z", type, payload });
42 const t = parseCodexSession(
43 [
44 line("session_meta", { id: "c1", cwd: "/w" }),
45 line("response_item", { type: "message", role: "user", content: [{ text: "go" }] }),
46 line("response_item", { type: "message", role: "assistant", content: [{ text: "ok" }] }),
47 line("event_msg", { type: "token_count", info: { last_token_usage: { input_tokens: 10, cached_input_tokens: 4, output_tokens: 3 } } }),
48 line("response_item", { type: "message", role: "assistant", content: [{ text: "again" }] }),
49 line("event_msg", { type: "token_count", info: { last_token_usage: { input_tokens: "x", output_tokens: null } } }),
50 ].join("\n"),
51 );
52 expect(stepsOf(t).map((s) => [s.tokensIn, s.tokensCached, s.tokensOut])).toEqual([[6, 4, 3], [0, 0, 0]]);
53 });
54
55 let dir = "";
56 let app: App, servers: Servers;
57 let tok = "";
58 const ids: Record<string, string> = {};
59 const get = (path: string) => fetch(`${servers.url}${path}`, { headers: { authorization: `Bearer ${tok}` } });
60
61 beforeAll(async () => {
62 dir = await mkdtemp(join(tmpdir(), "forge-trace-imported-tokens-"));
63 app = createApp({ dataDir: dir, port: 0 });
64 servers = await serve(app);
65 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
66 if (!a.ok) throw new Error(a.error);
67 tok = createToken(app.db, a.value.id, "t", "rw").token;
68 for (const [name, text] of Object.entries({ WITH, WITHOUT: WITHOUT.replaceAll("sess-t", "sess-u") })) {
69 const sent = await fetch(`${servers.url}/api/v1/traces/import`, { method: "POST", headers: { authorization: `Bearer ${tok}` }, body: text });
70 ids[name] = ((await sent.json()) as { id: string }).id;
71 }
72 }, 30_000);
73 afterAll(async () => {
74 await servers.stop();
75 await rm(dir, { recursive: true, force: true });
76 });
77
78 test("the page shows tokens on the steps that have them and in the total", async () => {
79 const text = await (await get(`/traces/${ids.WITH}`)).text();
80 expect(text).toContain("5 in, 7 cached, 9 out</span>");
81 expect(text).toContain("6 in, 0 cached, 2 out</span>");
82 expect(text).toContain('id="trace-tokens">11 in, 7 cached, 11 out');
83 expect(text.match(/small trace-tokens"/g)?.length).toBe(2);
84 });
85
86 test("a session without usage says not recorded, on the page", async () => {
87 const text = await (await get(`/traces/${ids.WITHOUT}`)).text();
88 expect(text).toMatch(/id="trace-tokens">not recorded in this file/);
89 expect(text).not.toContain(" cached, ");
90 });
91
92 test("the API answers per-step tokens and the totals", async () => {
93 const tree = (await (await get(`/api/v1/traces/${ids.WITH}`)).json()) as any;
94 expect(tree).toMatchObject({ tokensIn: 11, tokensCached: 7, tokensOut: 11 });
95 expect(tree.turns[0].steps.map((s: any) => s.tokensOut)).toEqual([9, 0, 2]);
96 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs