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

Traces 3: one trace as a tree beside a time strip, with what it changed #17996

opened this in answer to

Merged 15h 25m ago, live in production

scout/forge:scout/17993-traces-3-one-trace-as-a-tree-beside-a-ti → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/17993-traces-3-one-trace-as-a-tree-beside-a-ti was merged into main as 2902a64.

Review

Sign in to review this change.
24 files changed +782 −14
docs/design/areas/traces.md added +3
@@ -0,0 +1,3 @@
1 # Traces
2
3 `/traces/:id` (`src/web/pages/trace.ts`), one crew run as a tree of steps beside a strip of them. Page-local classes, drawn from existing tokens: `.trace-strip` (the inline SVG, fixed 28px tall so nothing shifts; `.trace-tick-model`, `.trace-tick-tool` and `.trace-tick-bad` colour a tick by what the step was), `.trace-tree` (the collapsible tree, a group of `details`), `.trace-calls` (a step's tool calls, indented), `.trace-step` (one step's `details`; `.trace-bad` turns a failed one `--danger`, `.trace-here` rings the step a `#step-N` address names), `.trace-raw` (a step's raw lines, loaded when it opens, scrolls inside 24rem) and `.trace-n` (the step's number, quiet).
docs/features/traces.md +7 −1
@@ -9,6 +9,12 @@ Every conversation and run is a record the forge keeps; a trace is the same reco
99 - `forge trace <session.jsonl>` prints the tree: each turn's prompt, each step on one line (`Edit foo.ts +12 −3`, tokens, time), a total. Terminal door: `src/cli/commands/trace.ts`; the tree is also what `src/tui/` will show.
1010 - `forge trace <session.jsonl> --otlp` prints OTLP/JSON with the OpenTelemetry GenAI conventions, so a trace stays portable. Ids are derived from the session, so the same file always exports the same document.
1111
12 Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` (the reader), `src/trace/otlp.ts` (the export). Not yet: Codex files, storing an import, the /traces page, cost (the file holds none), compare, share.
12 ## One run as a tree (#17993)
13
14 `/traces/<run id>` reads a crew run's log as a trace: each stretch of the agent's words is a step with the tool calls (`→ Edit foo.ts`) after it nested under it, a `!` line a failed step. The page has a strip of the steps in order (a tick links to `#step-N`), the collapsible tree (`j`/`k` move, Enter opens), the run's cost for those who may see it, and **What it changed**: the files, additions and deletions of the pull the run became, with links to the run, issue, pull, checks and review. A step shows one line; its raw lines load only when it opens (`/traces/<run id>/steps/<n>`, text), so a 2,000-step trace is one small page. `#step-N` opens the tree at that step. A viewer who may not read the run's log gets the not-found a missing run does.
15
16 Each line a run appends is stamped in `<run id>.times` beside its log (`appendRunLog`), so a step shows what it took and when it ended (`2.3s, at 14s`, the last is the running total), and the strip puts each tick where and as wide as its time in the run: a slow tool or a long silence is a wide tick. A run from before the stamps shows order and says so. The log holds no tokens or cost, so a step carries neither; the run's cost is the only figure. Each run page lists a Trace fact (`runFacts`) and a Talk build card links its trace. Terminal door: `t` on a run's log opens `src/tui/screens/trace.ts` (the same rows, `traceRows`; `o` prints the web address). Reader: `src/trace/run_log.ts`, `src/trace/read.ts`.
17
18 Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` (the reader), `src/trace/otlp.ts` (the export). Not yet: Codex files, storing an import, tokens and cost per step (the file holds none), compare, share.
1319
1420 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.
src/core/reserved.ts +1
@@ -155,6 +155,7 @@ export const SYSTEM_NAMES: readonly string[] = [
155155 "offline",
156156 "tab",
157157 "tell",
158 "traces",
158159 "talk",
159160 "tabforge",
160161 "peek",
src/generated/marks.ts +5 −3
@@ -208,9 +208,10 @@ import k203 from "../http/marks/terms.json";
208208 import k204 from "../http/marks/theme.json";
209209 import k205 from "../http/marks/toolbar-lab.js.json";
210210 import k206 from "../http/marks/toolbar-lab.json";
211 import k207 from "../http/marks/verify.json";
212 import k208 from "../http/marks/welcome.json";
213 import k209 from "../http/marks/well-known.json";
211 import k207 from "../http/marks/traces.json";
212 import k208 from "../http/marks/verify.json";
213 import k209 from "../http/marks/welcome.json";
214 import k210 from "../http/marks/well-known.json";
214215
215216 /** Each file of `http/marks/`, parsed, in name order. */
216217 export const MARK_FILES: readonly unknown[] = [
@@ -424,4 +425,5 @@ export const MARK_FILES: readonly unknown[] = [
424425 k207,
425426 k208,
426427 k209,
428 k210,
427429 ];
src/http/lazy_lists.ts +2
@@ -695,6 +695,8 @@ export const OPERATIONS_ROUTES = [
695695 ["GET", "/fleet/graph.csv"],
696696 ["GET", "/__forge/domains/ask"],
697697 ["GET", "/runs/:id"],
698 ["GET", "/traces/:id"],
699 ["GET", "/traces/:id/steps/:n"],
698700 ] as const;
699701
700702 /** `originsRoutes` (`routes/origins.ts`). */
src/http/marks/traces.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/traces",
3 "mark": "open"
4 }
src/http/routes/operations.ts +4
@@ -22,6 +22,7 @@ import { pipelinePage } from "../../web/pages/pipeline.ts";
2222 import { advisoriesIngest, advisoriesPage } from "../../web/pages/advisories.ts";
2323 import { resiliencePage, nightlyOutputPage } from "../../web/pages/resilience.ts";
2424 import { runRedirect } from "../../web/pages/runs.ts";
25 import { tracePage, traceStep } from "../../web/pages/trace.ts";
2526 import { oauthCallbackUri } from "../api.ts";
2627 import { gamesRoutes } from "../games_routes.ts";
2728 import { infraRoutes } from "../infra_routes.ts";
@@ -118,4 +119,7 @@ export function operationsRoutes(router: Router<Handler>, knownPatterns: () => s
118119 });
119120 });
120121 router.add("GET", "/runs/:id", runRedirect);
122 // A crew run as a tree of steps (#17993). Literal, above /:owner.
123 router.add("GET", "/traces/:id", tracePage);
124 router.add("GET", "/traces/:id/steps/:n", traceStep);
121125 }
src/runs/log.ts +45 −7
@@ -35,6 +35,13 @@ export const runsRoot = (dataDir: string): string => join(dataDir, "runs");
3535 export const runLogPath = (dataDir: string, runId: string): string =>
3636 join(runsRoot(dataDir), `${runId}.log`);
3737
38 /**
39 * Beside the log, one epoch-millisecond per line, written with it: what a trace scales its strip by
40 * (#17993).
41 */
42 export const runTimesPath = (dataDir: string, runId: string): string =>
43 join(runsRoot(dataDir), `${runId}.times`);
44
3845 export type LogListener = (line: string) => void;
3946
4047 const listeners = new Map<string, Set<LogListener>>();
@@ -163,16 +170,16 @@ export function flushRunLogs(): void {
163170 Atomics.wait(done, 0, at, 250);
164171 }
165172
166 function enqueue(dataDir: string, runId: string, clean: string): void {
173 function enqueue(dataDir: string, path: string, text: string): void {
167174 if (!exitHooked) {
168175 exitHooked = true;
169176 process.on("exit", flushRunLogs);
170177 }
171 const key = `${dataDir}\0${runLogPath(dataDir, runId)}`;
178 const key = `${dataDir}\0${path}`;
172179 const lines = pending.get(key);
173 if (lines === undefined) pending.set(key, [`${clean}\n`]);
174 else lines.push(`${clean}\n`);
175 pendingBytes += clean.length + 1;
180 if (lines === undefined) pending.set(key, [text]);
181 else lines.push(text);
182 pendingBytes += text.length;
176183 if (pendingBytes >= FLUSH_BYTES) flushLater();
177184 else if (flushTimer === undefined) {
178185 flushTimer = setTimeout(() => background("run-log-flush", flushLater), FLUSH_MS);
@@ -187,8 +194,14 @@ export function appendRunLog(
187194 line: string,
188195 ): void {
189196 const clean = redactHeld(line.replace(/\r?\n/g, " ")).slice(0, MAX_LINE);
190 if (buffering) enqueue(dataDir, runId, clean);
191 else appendTo(runsRoot(dataDir), runLogPath(dataDir, runId), `${clean}\n`);
197 const at = `${Date.now()}\n`;
198 if (buffering) {
199 enqueue(dataDir, runLogPath(dataDir, runId), `${clean}\n`);
200 enqueue(dataDir, runTimesPath(dataDir, runId), at);
201 } else {
202 appendTo(runsRoot(dataDir), runLogPath(dataDir, runId), `${clean}\n`);
203 appendTo(runsRoot(dataDir), runTimesPath(dataDir, runId), at);
204 }
192205 noteActivity(runId);
193206 for (const tap of taps) {
194207 try {
@@ -239,6 +252,31 @@ export function readRunLog(
239252 }
240253 }
241254
255 /**
256 * The time each of the last `count` log lines was written, epoch ms, oldest first; `undefined`
257 * where the run has no times (written before they were kept) or they do not match the log.
258 */
259 export function readRunTimes(dataDir: string, runId: string, count: number): number[] | undefined {
260 flushRunLogs();
261 const path = runTimesPath(dataDir, runId);
262 if (count === 0 || !existsSync(path)) return undefined;
263 const size = statSync(path).size;
264 const maxBytes = (count + 1) * 14 + 64;
265 const start = Math.max(0, size - maxBytes);
266 const fd = openSync(path, "r");
267 try {
268 const buffer = Buffer.alloc(size - start);
269 readSync(fd, buffer, 0, buffer.length, start);
270 let text = buffer.toString("utf8");
271 if (start > 0) text = text.slice(text.indexOf("\n") + 1);
272 const all = text.split("\n").filter((l) => l !== "").map(Number);
273 if (all.length < count || all.some((n) => !Number.isFinite(n))) return undefined;
274 return all.slice(all.length - count);
275 } finally {
276 closeSync(fd);
277 }
278 }
279
242280 /**
243281 * A window onto the end of a run's log, sized for a caller that wants
244282 * `maxLines` of them rather than a byte count to guess at. A worst-case
src/runs/run_facts.ts +4
@@ -38,6 +38,8 @@ export interface RunFactsInput {
3838 * crew member that made it, which a stranger is not told (the run's title says "the crew").
3939 */
4040 readonly writer: boolean;
41 /** Whether the viewer may read the run's log, so its trace (`/traces/:id`) is theirs to open. */
42 readonly traceable?: boolean | undefined;
4143 /** How long it took, in the run page's words (`durationText`). */
4244 readonly took?: string | undefined;
4345 /**
@@ -133,6 +135,8 @@ export function runFacts(i: RunFactsInput): RunFact[] {
133135 if (i.lent !== undefined && i.lent !== "") facts.push({ label: "Server", text: i.lent });
134136 if (i.account !== undefined) facts.push({ label: "Account", text: i.account });
135137 if (run.feed !== null) facts.push({ label: "Fed", text: feedLine(run.feed) });
138 // A crew run's steps, as a tree (#17993): the log is read as a trace at `/traces/:id`.
139 if (run.kind === "agent" && i.traceable === true) facts.push({ label: "Trace", text: "steps and what changed", href: `/traces/${run.id}` });
136140 if (run.startedAt !== null) facts.push({ label: "Started", text: run.startedAt, at: run.startedAt });
137141 if (i.took !== undefined) facts.push({ label: run.finishedAt === null ? "Running for" : "Took", text: i.took });
138142 if (run.attempt > 0) facts.push({ label: "Attempt", text: String(run.attempt + 1) });
src/trace/read.ts added +126
@@ -0,0 +1,126 @@
1 /**
2 * One crew run as a trace, read for a viewer (#17993): the page, the step route and the terminal
3 * screen all take this one answer. Gated as the run's log is (`runLog`): a run the viewer cannot
4 * see, or whose log is hidden from them, is `undefined`, never a hint that it exists.
5 */
6 import { runLog } from "../actions/runs.ts";
7 import type { App } from "../app.ts";
8 import { getIssueById } from "../core/issues.ts";
9 import { getPull, openPullsClosing, type Pull } from "../core/pulls.ts";
10 import { canSeeOwnerFacts, type Repo } from "../core/repos.ts";
11 import type { Run } from "../core/runs.ts";
12 import type { User } from "../core/users.ts";
13 import { changeHref, tellHref } from "../web/studio/nouns.ts";
14 import { diffStatFor, type DiffStat } from "../web/studio/review_evidence.ts";
15 import { readRunTimes } from "../runs/log.ts";
16 import { stepsOf, type Step, type Trace } from "./model.ts";
17 import { parseRunLog, type Span } from "./run_log.ts";
18
19 export interface TraceLink {
20 readonly label: string;
21 readonly href: string;
22 }
23
24 export interface TraceView {
25 readonly run: Run;
26 readonly trace: Trace;
27 readonly spans: readonly Span[];
28 /** The steps carry times (the run kept them); false: no duration is shown. */
29 readonly timed: boolean;
30 readonly lines: readonly string[];
31 /** The log's start was cut (it is read from its last 512 KB): step numbers count from the cut. */
32 readonly truncated: boolean;
33 readonly title: string;
34 /** The pull the run became, and what its files changed in all: the net of the run's work. */
35 readonly pull: Pick<Pull, "number" | "title" | "state"> | undefined;
36 readonly changed: DiffStat | "loading" | "failed" | undefined;
37 /** What the run is tied to, each a path on this forge. */
38 readonly links: readonly TraceLink[];
39 /** The run's spend, a fact for those who may see the owner's (`canSeeOwnerFacts`). */
40 readonly costUsd: number | undefined;
41 }
42
43 /** `/traces/<run id>`: the one address of a run's trace. */
44 export const traceHref = (runId: string): string => `/traces/${runId}`;
45
46 export async function readTrace(app: App, actor: User | undefined, repo: Repo, runId: string): Promise<TraceView | undefined> {
47 const found = await runLog(app, actor, repo, runId);
48 if (!found.ok || found.value.logHidden) return undefined;
49 const { run, lines, truncated } = found.value;
50 const base = `/${repo.ownerName}/${repo.name}`;
51 const issue = run.issueId === null ? undefined : getIssueById(app.db, run.issueId);
52 const pull = issue === undefined ? undefined : issue.kind === "pull" ? getPull(app.db, repo.id, issue.number) : openPullsClosing(app.db, repo.id).get(issue.number);
53 const title = issue?.title ?? (run.summary === "" ? `${run.kind} run` : run.summary);
54 const { trace, spans, timed } = parseRunLog(run.id, title, lines, readRunTimes(app.config.dataDir, run.id, lines.length));
55 const links: TraceLink[] = [{ label: "Run", href: `${base}/runs/${run.id}` }];
56 if (issue !== undefined && issue.kind === "issue") links.push({ label: `Issue #${issue.number}`, href: tellHref(base, issue.number) });
57 if (pull !== undefined) {
58 links.push({ label: `Pull #${pull.number}`, href: changeHref(base, pull.number) });
59 links.push({ label: "Checks", href: `${changeHref(base, pull.number)}#checks` });
60 links.push({ label: "Review", href: `${changeHref(base, pull.number)}#review` });
61 }
62 return {
63 run,
64 trace,
65 spans,
66 timed,
67 lines,
68 truncated,
69 title,
70 pull: pull === undefined ? undefined : { number: pull.number, title: pull.title, state: pull.state },
71 changed: pull === undefined ? undefined : diffStatFor(app, repo, pull),
72 links,
73 costUsd: canSeeOwnerFacts(app.db, repo, actor) && run.costUsd > 0 ? run.costUsd : undefined,
74 };
75 }
76
77 /** The raw lines the log holds for step `n` (1-based), or undefined where there is no such step. */
78 export function stepPayload(view: Pick<TraceView, "spans" | "lines">, n: number): string[] | undefined {
79 const span = view.spans[n - 1];
80 return span === undefined ? undefined : view.lines.slice(span.from, span.to);
81 }
82
83 export const stepsInView = (view: Pick<TraceView, "trace">): Step[] => stepsOf(view.trace);
84
85 /** A span of time in words: `0.4s`, `12s`, `3m 05s`. */
86 export function spanWords(ms: number): string {
87 if (ms < 10_000) return `${(Math.round(ms / 100) / 10).toFixed(1)}s`;
88 const s = Math.round(ms / 1000);
89 return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;
90 }
91
92 /** What a step took and when it ended in the run, where the run kept times: `2.3s, at 14s`. */
93 export function stepTime(s: Pick<Step, "startMs" | "endMs">, timed: boolean): string | undefined {
94 return timed ? `${spanWords(s.endMs - s.startMs)}, at ${spanWords(s.endMs)}` : undefined;
95 }
96
97 /**
98 * A step as one terminal or page line: its number, the line, and what it took and when it ended.
99 */
100 export function stepLine(s: Step, n: number, total: number, timed = false): string {
101 const t = stepTime(s, timed);
102 return `${n}/${total} ${s.outcome === "error" ? "✗ " : ""}${s.line}${t === undefined ? "" : ` (${t})`}`;
103 }
104
105 /** What the net diff says in words, shared by the page and the terminal. */
106 export function changedWords(view: Pick<TraceView, "changed" | "pull">): string | undefined {
107 if (view.pull === undefined) return undefined;
108 const c = view.changed;
109 const stat = typeof c === "object" ? `${c.files} file${c.files === 1 ? "" : "s"} +${c.additions} −${c.deletions}` : "not counted yet";
110 return `${stat} in pull #${view.pull.number}`;
111 }
112
113 /** The trace as plain lines: the terminal screen's rows, a line a step, the changed total last. */
114 export function traceRows(view: TraceView): string[] {
115 const steps = stepsInView(view);
116 const out = [view.title];
117 steps.forEach((s, i) => out.push(`${s.kind === "tool" ? " " : " "}${stepLine(s, i + 1, steps.length, view.timed)}`));
118 const failed = steps.filter((s) => s.outcome === "error").length;
119 const last = steps[steps.length - 1];
120 out.push(`${steps.length} steps, ${failed} failed${last === undefined || !view.timed ? "" : `, ${spanWords(last.endMs)}`}${view.costUsd === undefined ? "" : `, $${view.costUsd.toFixed(2)}`}`);
121 const changed = changedWords(view);
122 if (changed !== undefined) out.push(`Changed: ${changed}`);
123 if (!view.timed && steps.length > 0) out.push("This run's log kept no times, so steps show none; it holds no tokens or cost per step.");
124 if (view.truncated) out.push("The start of the log was cut: steps count from the cut.");
125 return out;
126 }
src/trace/run_log.ts added +112
@@ -0,0 +1,112 @@
1 /**
2 * A crew run's log read as a trace (#17993): the run is one turn; a `→ Tool detail` line is a tool
3 * step, a `! …` line a failed one, and the words the agent wrote between them are a model step. The
4 * log holds no tokens or cost, so a step has none. Each line's write time is kept beside the log
5 * (`readRunTimes`): a step starts when its first line was written and ends when the next step's
6 * did, so a slow tool or a long silence is a long step. A run from before the times were kept has
7 * none: `timed` says so, and a step then has no duration, never an invented one.
8 */
9 import { oneLine } from "./claude_code.ts";
10 import type { Step, Trace } from "./model.ts";
11
12 /** The raw lines a step was read from: `from` inclusive, `to` exclusive, indexes into the log. */
13 export interface Span {
14 from: number;
15 to: number;
16 }
17
18 export interface RunTrace {
19 trace: Trace;
20 /** One span per step, in step order: what expands on demand. */
21 spans: Span[];
22 /** Every step has a start and an end in ms from the run's first line. */
23 timed: boolean;
24 }
25
26 /** The most steps one page reads; a log past it says so, never silently. */
27 export const MAX_STEPS = 20_000;
28
29 export function parseRunLog(runId: string, prompt: string, lines: readonly string[], times?: readonly number[]): RunTrace {
30 const timed = times !== undefined && times.length === lines.length && lines.length > 0;
31 const t0 = timed ? times[0]! : 0;
32 const steps: Step[] = [];
33 const spans: Span[] = [];
34 const add = (kind: Step["kind"], name: string, line: string, from: number, to: number, bad: boolean): void => {
35 steps.push({
36 id: `step-${steps.length + 1}`,
37 kind,
38 name,
39 line: oneLine(line),
40 startMs: timed ? Math.max(0, times[from]! - t0) : 0,
41 endMs: 0,
42 model: undefined,
43 tokensIn: 0,
44 tokensCached: 0,
45 tokensOut: 0,
46 outcome: bad ? "error" : "unknown",
47 });
48 spans.push({ from, to });
49 };
50 let words: number | undefined;
51 const closeWords = (end: number): void => {
52 if (words === undefined) return;
53 const first = lines.slice(words, end).find((l) => l.trim() !== "") ?? "";
54 add("model", "text", first, words, end, false);
55 words = undefined;
56 };
57 for (let i = 0; i < lines.length && steps.length < MAX_STEPS; i++) {
58 const line = lines[i] ?? "";
59 if (line.startsWith("→ ")) {
60 closeWords(i);
61 const body = line.slice(2);
62 add("tool", body.split(" ", 1)[0] ?? "tool", body, i, i + 1, false);
63 } else if (line.startsWith("! ")) {
64 closeWords(i);
65 add("tool", "error", line.slice(2), i, i + 1, true);
66 } else if (line.trim() !== "" && words === undefined) words = i;
67 }
68 closeWords(lines.length);
69 if (timed) {
70 // A step ends where the next begins; the last, at its own last line.
71 steps.forEach((st, i) => {
72 const next = steps[i + 1];
73 st.endMs = next !== undefined ? next.startMs : Math.max(st.startMs, times[spans[i]!.to - 1]! - t0);
74 });
75 }
76 const trace: Trace = {
77 source: "claude-code",
78 id: runId,
79 cwd: undefined,
80 turns: [{ index: 0, prompt, startMs: 0, steps }],
81 skipped: 0,
82 };
83 return { trace, spans, timed };
84 }
85
86 /** A model step with the tool calls that followed it: one branch of the tree. */
87 export interface Branch {
88 head: Step | undefined;
89 calls: Step[];
90 }
91
92 /** The steps as the tree shows them: each model step with the tool calls after it. */
93 export function branchesOf(steps: readonly Step[]): Branch[] {
94 const out: Branch[] = [];
95 for (const s of steps) {
96 if (s.kind === "model") out.push({ head: s, calls: [] });
97 else {
98 let last = out[out.length - 1];
99 if (last === undefined) {
100 last = { head: undefined, calls: [] };
101 out.push(last);
102 }
103 last.calls.push(s);
104 }
105 }
106 return out;
107 }
108
109 /** `step-12` → 12; anything else is not a step. */
110 export function stepNumber(raw: string): number | undefined {
111 return /^[1-9][0-9]{0,5}$/.test(raw) ? Number(raw) : undefined;
112 }
src/tui/screens/runlog.ts +8 −1
@@ -7,7 +7,7 @@
77 * place, one at the end follows the new lines.
88 */
99
10 import { requeueRepoRun, runLog, type RunLogView } from "../../actions/runs.ts";
10 import { requeueRepoRun, mayReadRunLog, runLog, type RunLogView } from "../../actions/runs.ts";
1111 import { keyOf } from "../../web/keymap.ts";
1212 import { canSeeOwnerFacts, canWrite, type Repo } from "../../core/repos.ts";
1313 import { RUN_NEXT_WORDS, runNext, type RunNext } from "../../runs/run_next.ts";
@@ -24,6 +24,7 @@ import { subscribeRunLog } from "../../runs/log.ts";
2424 import { stoppedWords } from "../../runs/cancelled.ts";
2525 import { withEnded } from "../../runs/ended_words.ts";
2626 import { stillEnding } from "../../runs/ending.ts";
27 import { traceScreen } from "./trace.ts";
2728 import { Scroll, live, openOnWeb, promptScreen, runAsync } from "./common.ts";
2829 import { offersOwnToken, startNowWithOwnToken, START_NOW_HEAD, START_NOW_WORDS } from "../../actions/own_token.ts";
2930 import { costText, envLabel, runTone } from "./runwords.ts";
@@ -120,6 +121,7 @@ export function runLogScreen(
120121 pullBranch: pull === undefined || pull.crossRepo ? undefined : pull.headBranch,
121122 admin: f.user?.isAdmin === true && f.user.kind === "user",
122123 writer: canSeeOwnerFacts(f.app.db, repo, f.user),
124 traceable: mayReadRunLog(f.app, f.user, repo),
123125 took: tookText(run, log),
124126 account: choiceOf(log),
125127 lent: canSeeOwnerFacts(f.app.db, repo, f.user) ? lentLineOf(f.app.db, run.id) : undefined,
@@ -144,6 +146,7 @@ export function runLogScreen(
144146 binding(["pgup", "pgdn"], "page"),
145147 binding(["g g", "G"], "top, end"),
146148 binding(["o"], "open on the web"),
149 ...(view?.run.kind === "agent" ? [binding(["t"], "its trace: steps and what changed")] : []),
147150 binding([keyOf("reread")], "refresh"),
148151 ...((n) => (n === null ? [] : [binding(["r"], RUN_NEXT_WORDS[n].toLowerCase())]))(next()),
149152 ...(offer() ? [binding(["a"], "start now on your own account")] : []),
@@ -293,6 +296,10 @@ export function runLogScreen(
293296 doNext();
294297 return true;
295298 }
299 if (e.key === "t" && !e.ctrl && !e.alt && view?.run.kind === "agent") {
300 ctx.push(traceScreen(f, ctx, repo, runId));
301 return true;
302 }
296303 if (e.key === "o" && !e.ctrl && !e.alt) {
297304 web();
298305 return true;
src/tui/screens/talk_chats.ts +1 −1
@@ -222,7 +222,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
222222 if (crew === undefined) return [];
223223 const l = crew.line;
224224 const said = l.change === undefined ? l.says : `${l.says} ${l.change.words}: ${f.app.config.url === undefined ? l.change.href : publicOrigin(f.app.config.url, "") + l.change.href}`;
225 return ["", `Crew: ${said}`, ...(crew.retry === true ? ["t tries it again."] : []), ...crew.steps.map((item) => (item.thought ? ` \u201c${item.text}\u201d` : ` ${item.text}`)), `The whole run: /${repo ?? ""}/runs/${crew.runId}`];
225 return ["", `Crew: ${said}`, ...(crew.retry === true ? ["t tries it again."] : []), ...crew.steps.map((item) => (item.thought ? ` \u201c${item.text}\u201d` : ` ${item.text}`)), `The whole run: /${repo ?? ""}/runs/${crew.runId}`, ...(crew.tail ? [`Its trace: /traces/${crew.runId}`] : [])];
226226 };
227227 // Where the terminal's c says words: the pull shown, the crew's run's issue, else the newest receipt's.
228228 const replyTarget = (user: User): { owner: string; name: string; number: number; object: string } | undefined => {
src/tui/screens/trace.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * A crew run's trace, in the terminal (#17993): the lines the trace page shows (`traceRows`, one a
3 * step, the net of what it changed last), read through the same gate (`readTrace`). `t` opens it
4 * from a run's log; `o` prints the web address.
5 */
6
7 import type { Repo } from "../../core/repos.ts";
8 import { readTrace, traceHref, traceRows } from "../../trace/read.ts";
9 import type { Ctx, Screen } from "../app/app.ts";
10 import { binding } from "../app/keys.ts";
11 import type { Session } from "../session.ts";
12 import { style } from "../term/style.ts";
13 import { truncate } from "../term/width.ts";
14 import { emptyState } from "../ui/widgets.ts";
15 import { Scroll, openOnWeb } from "./common.ts";
16
17 export function traceScreen(f: Session, ctx: Ctx, repo: Repo, runId: string): Screen {
18 const scroll = new Scroll();
19 let rows: string[] | undefined;
20 let loaded = false;
21 return {
22 title: "Trace",
23 here: () => ({ repo, run: runId }),
24 keys: [binding(["j", "k"], "scroll"), binding(["pgup", "pgdn"], "page"), binding(["o"], "open on the web")],
25 async load() {
26 const view = await readTrace(f.app, f.user, repo, runId);
27 rows = view === undefined ? undefined : traceRows(view);
28 loaded = true;
29 ctx.invalidate();
30 },
31 render(area, s) {
32 const c = ctx.theme.c;
33 if (rows === undefined) {
34 emptyState(s, area, c, { title: loaded ? "Not found" : "Reading…", body: loaded ? "There is no such trace here." : "Reading the run" });
35 return;
36 }
37 scroll.window(area.h, rows.length);
38 for (let i = 0; i < area.h; i++) {
39 const line = rows[scroll.top + i];
40 if (line === undefined) break;
41 s.text(area.x, area.y + i, truncate(line.replace(/[\u0000-\u001f\u007f]/g, " "), area.w), style(c.fg, c.bg), area.x + area.w);
42 }
43 },
44 key(e) {
45 if (e.key === "o" && !e.ctrl && !e.alt) {
46 openOnWeb(f, ctx, traceHref(runId), "the run's trace");
47 return true;
48 }
49 if (rows === undefined) return false;
50 const took = scroll.key(e, rows.length);
51 if (took) ctx.invalidate();
52 return took;
53 },
54 };
55 }
src/web/pages/talk_preview.ts +1 −1
@@ -230,7 +230,7 @@ function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: str
230230 const working = crew.state === "running" ? " talk-crew-working" : "";
231231 const line = html`<p class="small${working}">${workLineHtml(crew.line)}</p>`;
232232 const steps = !crew.tail || (crew.steps.length === 0 && crew.state !== "running") ? null : html`<div class="talk-crew-steps small muted" data-crew-steps="${crew.runId}" aria-live="polite">${crew.steps.map((item) => (item.thought ? html`<p class="talk-crew-thought">${item.text}</p>` : html`<p>${item.text}</p>`))}</div>`;
233 const run = html`<a class="small" href="${base}/runs/${crew.runId}">See the whole run</a>`;
233 const run = html`<a class="small" href="${base}/runs/${crew.runId}">See the whole run</a>${crew.tail ? html` <a class="small" href="/traces/${crew.runId}">Trace</a>` : null}`;
234234 // A run that did not finish offers its next step: Try again queues its task once more, and
235235 // answers on this page (`back`, read only then).
236236 const again = crew.retry !== true ? null : html`<form class="bar" method="post" action="${base}/runs/${crew.runId}/requeue"><input type="hidden" name="back" value="${back()}">${btn("Try again", { size: "sm", variant: "outline" })}</form>`;
src/web/pages/trace.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * `/traces/:id` (#17993): one crew run as a tree of its steps beside a strip of them, the net of
3 * what it changed, and links to its pull, checks and review. The first paint holds one line a step
4 * and no payload: a step's raw lines load when it is opened (`/traces/:id/steps/:n`), so a
5 * 2,000-step trace is one small page. `#step-N` opens the tree at that step. The terminal reads
6 * the same view (`src/tui/screens/trace.ts`, `traceRows`).
7 */
8 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
9 import { canRead, getRepoById, type Repo } from "../../core/repos.ts";
10 import { getRun } from "../../core/runs.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import { securityFloor } from "../../http/respond.ts";
13 import { branchesOf, stepNumber } from "../../trace/run_log.ts";
14 import { changedWords, readTrace, spanWords, stepLine, stepPayload, stepTime, stepsInView, traceHref, type TraceView } from "../../trace/read.ts";
15 import type { Step } from "../../trace/model.ts";
16 import { crumbsFor, notFoundPage, pageHead, repoPalette } from "../chrome.ts";
17 import { html, type Html } from "../html.ts";
18 import { page } from "../layout.ts";
19 import { behaviorsJs } from "../behaviors.ts";
20
21 /** A trace with this many steps or fewer opens its branches; a longer one opens none. */
22 export const OPEN_BELOW = 100;
23 /**
24 * The strip draws at most this many ticks; a longer trace is bucketed, never one element a step.
25 */
26 export const MAX_TICKS = 300;
27
28 const TRACE_CSS = `
29 .trace-strip{display:block;width:100%;height:28px;margin:.5rem 0}
30 .trace-strip rect{fill:var(--fg)}
outdated

Principle 5: the accent fills every model tick, so it is decoration. Use --fg for model ticks and keep --accent for hover and focus.

31 .trace-strip .trace-tick-tool rect{fill:var(--muted-fg)}
32 .trace-strip .trace-tick-bad rect{fill:var(--danger)}
33 .trace-strip a:focus rect,.trace-strip a:hover rect{fill:var(--accent)}
34 .trace-calls{padding-left:1.25rem}
35 .trace-step>summary{cursor:pointer;padding:.15rem 0;min-height:1.5rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
36 .trace-step.trace-bad>summary{color:var(--danger)}
37 .trace-step.trace-here>summary{outline:2px solid currentColor;outline-offset:2px}
38 .trace-raw{margin:.25rem 0 .5rem 1.25rem;padding:0;max-height:24rem;overflow:auto;white-space:pre-wrap;word-break:break-word}
39 .trace-n{color:var(--muted-fg);margin-right:.5rem}
outdated

Principle 4: use color:var(--muted-fg), not opacity, for the quiet step number.

40 .trace-time{color:var(--muted-fg);margin:0 .5rem}
41 `;
42
43 const TRACE_JS = `(function(){
44 var root=document.getElementById('trace-tree');if(!root)return;
45 var base=root.dataset.base;
46 function load(d){var pre=d.querySelector(':scope > pre');if(!pre||pre.dataset.done)return;pre.dataset.done='1';pre.textContent='Loading…';
47 fetch(base+'/steps/'+d.dataset.n,{credentials:'same-origin'}).then(function(r){return r.ok?r.text():Promise.reject()}).then(function(t){pre.textContent=t}).catch(function(){pre.textContent='Could not load this step.';delete pre.dataset.done})}
48 root.addEventListener('toggle',function(e){var d=e.target;if(d.open&&d.dataset.n)load(d)},true);
49 function go(){var id=location.hash.slice(1);if(!/^step-[0-9]+$/.test(id))return;var el=document.getElementById(id);if(!el)return;
50 for(var p=el;p&&p!==root;p=p.parentElement)if(p.tagName==='DETAILS')p.open=true;
51 el.classList.add('trace-here');el.scrollIntoView({block:'center'})}
52 addEventListener('hashchange',go);go();
53 document.addEventListener('keydown',function(e){if(e.ctrlKey||e.metaKey||e.altKey||/INPUT|TEXTAREA|SELECT/.test(e.target.tagName))return;
54 if(e.key!=='j'&&e.key!=='k')return;
55 var s=[].slice.call(root.querySelectorAll('summary')).filter(function(x){return x.offsetParent});
56 var i=s.indexOf(document.activeElement);i=e.key==='j'?Math.min(s.length-1,i+1):Math.max(0,i-1);if(s[i])s[i].focus();e.preventDefault()});
57 })();`;
58
59 function stepNode(s: Step, n: number, total: number, children: Html | null, base: string, open: boolean, timed: boolean): Html {
60 const took = stepTime(s, timed);
61 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}>
62 <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>
63 <pre class="trace-raw mono" aria-label="Raw lines of step ${String(n)}"></pre>
64 ${children}
65 </details>`;
66 }
67
68 /**
69 * The strip: one tick a step, or a bucket of them when there are more than `MAX_TICKS`. Where the
70 * run kept times a tick sits and is as wide as its time in the run, so a slow tool or a long
71 * silence is a wide tick; without times each is as wide as another.
72 */
73 function strip(steps: readonly Step[], timed: boolean): Html {
74 const ticks = Math.min(MAX_TICKS, steps.length);
75 const per = steps.length / ticks;
76 const whole = timed ? (steps[steps.length - 1]?.endMs ?? 0) : 0;
77 const out: Html[] = [];
78 for (let t = 0; t < ticks; t++) {
79 const from = Math.floor(t * per);
80 const to = Math.max(from + 1, Math.floor((t + 1) * per));
81 const bucket = steps.slice(from, to);
82 const bad = bucket.some((s) => s.outcome === "error");
83 const kind = bucket.some((s) => s.kind === "model") ? "model" : "tool";
84 let x = (t * 1000) / ticks;
85 let w = Math.max(0.5, 1000 / ticks - 0.4);
86 if (whole > 0) {
87 w = Math.max(1.5, ((bucket[bucket.length - 1]!.endMs - bucket[0]!.startMs) / whole) * 1000);
88 x = Math.min(1000 - w, (bucket[0]!.startMs / whole) * 1000);
89 }
90 out.push(html`<a href="#step-${String(from + 1)}" class="trace-tick-${bad ? "bad" : kind}" aria-label="Step ${String(from + 1)}${to - from > 1 ? ` to ${String(to)}` : ""}"><rect x="${x.toFixed(2)}" y="0" width="${w.toFixed(2)}" height="28"></rect></a>`);
91 }
92 return html`<svg class="trace-strip" viewBox="0 0 1000 28" preserveAspectRatio="none" role="group" aria-label="${timed ? `Steps over ${spanWords(whole)}` : "Steps in order"}">${out}</svg>`;
93 }
94
95 function body(view: TraceView): Html {
96 const steps = stepsInView(view);
97 const total = steps.length;
98 const base = traceHref(view.run.id);
99 const open = total <= OPEN_BELOW;
100 const timed = view.timed && total > 0;
101 let n = 0;
102 const rows = branchesOf(steps).map((b) => {
103 const first = n + 1;
104 n += b.calls.length + (b.head === undefined ? 0 : 1);
105 if (b.head === undefined) return html`${b.calls.map((c, i) => stepNode(c, first + i, total, null, base, false, timed))}`;
106 const inner = b.calls.map((c, i) => stepNode(c, first + 1 + i, total, null, base, false, timed));
107 return stepNode(b.head, first, total, html`<div class="trace-calls">${inner}</div>`, base, open, timed);
108 });
109 const failed = steps.filter((s) => s.outcome === "error").length;
110 const changed = changedWords(view);
111 return html`${pageHead(html`Trace: ${view.title}`, { sub: "One crew run, step by step, and what it changed." })}
112 <dl class="row-facts" id="trace-total">
113 <div><dt>Steps</dt><dd>${String(total)}</dd></div>
114 <div><dt>Failed</dt><dd>${String(failed)}</dd></div>
115 ${timed ? html`<div><dt>Time</dt><dd>${spanWords(steps[total - 1]!.endMs)}</dd></div>` : null}
116 ${view.costUsd === undefined ? null : html`<div><dt>Spent</dt><dd>$${view.costUsd.toFixed(2)}</dd></div>`}
117 <div><dt>State</dt><dd>${view.run.state}</dd></div>
118 </dl>
119 <nav class="bar small" id="trace-links" aria-label="Where this run went">${view.links.map((l) => html`<a href="${l.href}">${l.label}</a>`)}</nav>
120 ${changed === undefined ? null : html`<p id="trace-changed"><strong>What it changed:</strong> ${changed}. <a href="${view.links.find((l) => l.label.startsWith("Pull"))?.href ?? "#"}">Read the diff on the pull</a>.</p>`}
121 ${view.truncated ? html`<p class="small muted" id="trace-cut">The start of the log was cut, so steps count from the cut.</p>` : null}
122 ${total === 0 ? html`<p class="muted" id="trace-empty">This run wrote no steps.</p>` : html`${strip(steps, timed)}
123 <div class="trace-tree" id="trace-tree" data-base="${base}" role="group" aria-label="Steps">${rows}</div>
124 ${timed ? null : html`<p class="small muted" id="trace-untimed">This run's log kept no times, so steps show none; it holds no tokens or cost per step.</p>`}`}`;
125 }
126
127 /** The repository and run `:id` names, when the viewer may read the repository. */
128 function repoOfRun(ctx: Ctx): { repo: Repo; id: string } | undefined {
129 const id = ctx.params.id ?? "";
130 const run = /^[0-9A-Za-z_-]{1,64}$/.test(id) ? getRun(ctx.app.db, id) : undefined;
131 const repo = run === undefined ? undefined : getRepoById(ctx.app.db, run.repoId);
132 return repo === undefined || !canRead(ctx.app.db, repo, ctx.auth.user) ? undefined : { repo, id };
133 }
134
135 // GET /traces/:id
136 export async function tracePage(ctx: Ctx): Promise<Response> {
137 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
138 const found = repoOfRun(ctx);
139 if (found === undefined) return notFoundPage(ctx);
140 const view = await readTrace(ctx.app, ctx.auth.user, found.repo, found.id);
141 if (view === undefined) return notFoundPage(ctx);
142 return page({
143 ctx,
144 title: `Trace · ${view.title}`,
145 crumbs: crumbsFor(found.repo),
146 palette: repoPalette(ctx, found.repo),
147 body: body(view),
148 styleCss: TRACE_CSS,
149 scriptJs: `${behaviorsJs}\n${TRACE_JS}`,
150 });
151 }
152
153 // GET /traces/:id/steps/:n — the raw lines of one step, as text, read when a step is opened.
154 export async function traceStep(ctx: Ctx): Promise<Response> {
155 const found = repoOfRun(ctx);
156 const n = stepNumber(ctx.params.n ?? "");
157 if (found === undefined || n === undefined) return notFoundPage(ctx);
158 const view = await readTrace(ctx.app, ctx.auth.user, found.repo, found.id);
159 const raw = view === undefined ? undefined : stepPayload(view, n);
160 if (view === undefined || raw === undefined) return notFoundPage(ctx);
161 const step = stepsInView(view)[n - 1]!;
162 return securityFloor(
163 new Response(`${stepLine(step, n, view.trace.turns[0]?.steps.length ?? n, view.timed)}\n${raw.join("\n")}\n`, {
164 headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "private, no-store" },
165 }),
166 );
167 }
src/web/studio/run.ts +1
@@ -252,6 +252,7 @@ export async function runView(
252252 pullBranch: pull === undefined || pull.crossRepo ? undefined : pull.headBranch,
253253 admin: ctx.auth.user?.isAdmin === true && ctx.auth.user.kind === "user",
254254 writer,
255 traceable: !logHidden,
255256 took: duration,
256257 account: logHidden ? undefined : choiceOf(lines),
257258 lent: writer ? lentLineOf(db, run.id) : undefined,
test/budgets/unfixtured/traces-id-steps-n.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/traces/:id/steps/:n",
3 "why": "no fixture holds a crew run with a log"
4 }
test/budgets/unfixtured/traces-id.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/traces/:id",
3 "why": "no fixture holds a crew run with a log"
4 }
test/no-polling.test.ts +2
@@ -354,6 +354,8 @@ const NOT_WALKED: Record<string, string> = {
354354 "/pricing/orders/:id/receipt.html": "needs an order the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts)",
355355 "/resilience/nightly/:job": "needs a nightly job name",
356356 "/runs/:id": "the seed creates no run",
357 "/traces/:id": "the seed creates no crew run with a log",
358 "/traces/:id/steps/:n": "the seed creates no crew run with a log",
357359 "/signin/access/:token": "needs a one-time access link an admin minted",
358360 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
359361 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
test/security-floor-routes.test.ts +2
@@ -93,6 +93,8 @@ const UNSEEDED: Record<string, string> = {
9393 "/join/:token": "needs a one-use link to work on a repository, which the seed does not mint (test/invite-contributors.test.ts covers it)",
9494 "/signin/access/:token": "needs a one-time access link an admin minted",
9595 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
96 "/traces/:id": "needs a crew run with a log, which the seed has none of",
97 "/traces/:id/steps/:n": "needs a crew run with a log, which the seed has none of",
9698 "/pricing/orders/:id": "needs an order id the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts covers it)",
9799 "/pricing/orders/:id/receipt.html": "needs an order id the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts covers it)",
98100 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
test/talk-live-pane.test.ts +6
@@ -191,6 +191,12 @@ describe("the pane, by the crew's newest run on the repository", () => {
191191 expect(failed).not.toContain("talk-crew-fold");
192192 });
193193
194 test("the card links the run's trace to who may read its log, and to no one else (#17993)", async () => {
195 const { run, name } = await withRun("running", ["→ Read a.ts"]);
196 expect((await pane(name)).html.text).toContain(`href="/traces/${run.id}"`);
197 expect((await talkPane(ctx, bob, name, new Map(), "preview")).html.text).not.toContain(`/traces/${run.id}`);
198 });
199
194200 test("queued with no hold logged: it says it waits for a builder", async () => {
195201 const { name } = await withRun("queued");
196202 expect((await pane(name)).html.text).toContain(
test/trace-page.test.ts added +195
@@ -0,0 +1,195 @@
1 /** A crew run's trace page, step route and terminal rows (#17993). */
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 { openIssue } from "../src/actions/issues.ts";
8 import { openPull } from "../src/actions/pulls.ts";
9 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
10 import { createRun, finishRun } from "../src/core/runs.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { appendFileSync } from "node:fs";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { appendRunLog, flushRunLogs, readRunTimes, runLogPath } from "../src/runs/log.ts";
16 import { parseRunLog, branchesOf, stepNumber } from "../src/trace/run_log.ts";
17 import { readTrace, spanWords, traceRows } from "../src/trace/read.ts";
18 import { runFacts } from "../src/runs/run_facts.ts";
19 import type { Repo } from "../src/core/repos.ts";
20 import type { User } from "../src/core/users.ts";
21 import { seedAdmin } from "./helpers/admin.ts";
22
23 let dir = "";
24 let app: App, servers: Servers, bearer = "", runId = "", bigId = "", pullNo = 0;
25 let alice: User;
26 let repoRow: Repo;
27
28 const get = (path: string, auth = true) =>
29 fetch(`${servers.url}${path}`, { headers: auth ? { authorization: `Bearer ${bearer}` } : {} });
30
31 beforeAll(async () => {
32 dir = await mkdtemp(join(tmpdir(), "forge-trace-page-"));
33 app = createApp({ dataDir: dir, port: 0 });
34 servers = await serve(app);
35 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
36 if (!admin.ok) throw new Error(admin.error);
37 alice = admin.value;
38 const made = await createRepo(app, alice, { name: "notes", visibility: "public", description: "" });
39 if (!made.ok) throw new Error(String(made.error));
40 repoRow = made.value;
41 const seeded = await commitToBranch(app, alice, made.value, { message: "Start", files: [{ path: "README.md", content: "# notes\n" }] });
42 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
43 const issue = openIssue(app, alice, made.value, { title: "Add a footer", body: "" });
44 if (!issue.ok) throw new Error(String(issue.error));
45 const pushed = await commitToBranch(app, alice, made.value, { branch: "footer", message: "footer", files: [{ path: "footer.txt", content: "a\nb\n" }] });
46 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
47 const pull = await openPull(app, alice, made.value, { title: "Footer", body: `Closes #${issue.value.number}`, baseBranch: "main", headBranch: "footer" });
48 if (!pull.ok) throw new Error(String(pull.error));
49 pullNo = pull.value.number;
50 const run = createRun(app.db, { repoId: made.value.id, kind: "agent", issueId: issue.value.id, actorId: alice.id });
51 runId = run.id;
52 for (const line of ["I will read the README first.", "→ Read README.md", "Now the footer.", "→ Edit footer.txt", "→ Bash bun test", "! exit 1", "Done."]) appendRunLog(dir, runId, line);
53 finishRun(app.db, runId, { state: "ok", summary: "opened a pull" });
54 const big = createRun(app.db, { repoId: made.value.id, kind: "agent" });
55 bigId = big.id;
56 for (let i = 0; i < 2000; i++) appendRunLog(dir, bigId, `→ Read file-${i}.ts`);
57 finishRun(app.db, bigId, { state: "ok", summary: "big" });
58 flushRunLogs();
59 const minted = await fetch(`${servers.url}/api/v1/tokens`, {
60 method: "POST",
61 headers: { "content-type": "application/json" },
62 body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }),
63 });
64 bearer = ((await minted.json()) as { token: string }).token;
65 }, 30_000);
66
67 afterAll(async () => {
68 servers.stop();
69 app.close();
70 await rm(dir, { recursive: true, force: true });
71 });
72
73 test("a log reads as model steps with their tool calls, a failed line marked", () => {
74 const { trace, spans } = parseRunLog("r", "t", ["words", "more words", "→ Edit a.ts", "! bad", "→ Bash ls"]);
75 const steps = trace.turns[0]!.steps;
76 expect(steps.map((s) => [s.kind, s.outcome])).toEqual([["model", "unknown"], ["tool", "unknown"], ["tool", "error"], ["tool", "unknown"]]);
77 expect(spans[0]).toEqual({ from: 0, to: 2 });
78 expect(branchesOf(steps).map((b) => b.calls.length)).toEqual([3]);
79 expect(stepNumber("12")).toBe(12);
80 expect(stepNumber("0")).toBeUndefined();
81 expect(stepNumber("1; drop")).toBeUndefined();
82 });
83
84 test("the trace page shows one line a step, opens at a permalink's target, and reaches the pull", async () => {
85 const res = await get(`/traces/${runId}`);
86 expect(res.status).toBe(200);
87 const text = await res.text();
88 expect(text).toContain('id="step-1"');
89 expect(text).toContain("Edit footer.txt");
90 expect(text).toContain("✗");
91 expect(text).toContain("What it changed:");
92 expect(text).toContain(`href="/alice/notes/pulls/${pullNo}"`);
93 expect(text).toContain(`#checks`);
94 expect(text).toContain(`#review`);
95 // Every strip tick is a permalink to a step that is in the tree, and the tree opens at it.
96 for (const m of text.matchAll(/<a href="#(step-\d+)" class="trace-tick/g)) expect(text).toContain(`id="${m[1]}"`);
97 expect(text).toContain('id="trace-tree" data-base');
98 // Nothing in a step's raw lines is in the first paint beyond its one line.
99 expect(text).not.toContain("Now the footer.\n");
100 const pull = await get(`/alice/notes/pulls/${pullNo}`);
101 expect(pull.status).toBe(200);
102 });
103
104 test("a step's raw lines load on demand, and a bad step is a 404", async () => {
105 const step = await get(`/traces/${runId}/steps/4`);
106 expect(step.status).toBe(200);
107 expect(step.headers.get("content-type")).toContain("text/plain");
108 expect(await step.text()).toContain("→ Edit footer.txt");
109 const first = await (await get(`/traces/${runId}/steps/1`)).text();
110 expect(first).toContain("I will read the README first.");
111 expect((await get(`/traces/${runId}/steps/99`)).status).toBe(404);
112 expect((await get(`/traces/${runId}/steps/x`)).status).toBe(404);
113 expect((await get(`/traces/nope`)).status).toBe(404);
114 });
115
116 test("a viewer who may not read the log gets the not-found a missing run does", async () => {
117 expect((await get(`/traces/${runId}`, false)).status).toBe(404);
118 expect((await get(`/traces/${runId}/steps/1`, false)).status).toBe(404);
119 });
120
121 test("a 2,000-step trace is one page with no payload in it", async () => {
122 const res = await get(`/traces/${bigId}`);
123 expect(res.status).toBe(200);
124 const text = await res.text();
125 expect(text.match(/class="trace-step /g)?.length).toBe(2000);
126 expect(text.match(/<pre class="trace-raw[^>]*><\/pre>/g)?.length).toBe(2000);
127 expect(text.match(/<details[^>]* open/g)).toBeNull();
128 expect(text.match(/class="trace-tick-/g)!.length).toBeLessThanOrEqual(300);
129 expect(text.length).toBeLessThan(900_000);
130 expect((await get(`/traces/${bigId}/steps/2000`)).status).toBe(200);
131 });
132
133 test("the terminal rows and the run's facts name the trace and what it changed", async () => {
134 const view = await readTrace(app, alice, repoRow, runId);
135 const rows = traceRows(view!);
136 expect(rows.some((r) => r.includes("Edit footer.txt"))).toBe(true);
137 expect(rows.some((r) => r.startsWith("Changed:") && r.includes(`pull #${pullNo}`))).toBe(true);
138 const run = view!.run;
139 const facts = runFacts({ run, base: "/alice/notes", defaultBranch: "main", admin: false, writer: true, traceable: true });
140 expect(facts.find((f) => f.label === "Trace")?.href).toBe(`/traces/${runId}`);
141 });
142
143 test("a viewer who may not read the log is not offered the trace", async () => {
144 const view = await readTrace(app, alice, repoRow, runId);
145 const facts = runFacts({ run: view!.run, base: "/alice/notes", defaultBranch: "main", admin: false, writer: false });
146 expect(facts.some((f) => f.label === "Trace")).toBe(false);
147 });
148
149 test("each line is stamped, a step shows what it took and when it ended, and the strip is scaled by it (#17993)", () => {
150 const lines = ["words", "→ Read a.ts", "→ Bash bun test", "! exit 1"];
151 const timed = parseRunLog("r", "t", lines, [1000, 1500, 1600, 31_600]);
152 expect(timed.timed).toBe(true);
153 const steps = timed.trace.turns[0]!.steps;
154 expect(steps.map((s) => [s.startMs, s.endMs])).toEqual([[0, 500], [500, 600], [600, 30_600], [30_600, 30_600]]);
155 // Times that do not match the log are no times, never a guess.
156 expect(parseRunLog("r", "t", lines, [1, 2]).timed).toBe(false);
157 expect(parseRunLog("r", "t", lines).trace.turns[0]!.steps.every((s) => s.endMs === 0)).toBe(true);
158 expect(spanWords(500)).toBe("0.5s");
159 expect(spanWords(30_000)).toBe("30s");
160 expect(spanWords(185_000)).toBe("3m 05s");
161 });
162
163 test("the page shows each step's time and a running total, and says once when a log has none (#17993)", async () => {
164 const text = await (await get(`/traces/${runId}`)).text();
165 expect(text).toMatch(/class="trace-time small">[0-9.]+s, at [0-9.]+s</);
166 expect(text).toContain("<dt>Time</dt>");
167 expect(text).not.toContain("trace-untimed");
168 expect(readRunTimes(dir, runId, 7)?.length).toBe(7);
169 // A log written before times were kept: order only, and the page says so.
170 const old = createRun(app.db, { repoId: repoRow.id, kind: "agent" });
171 appendFileSync(runLogPath(dir, old.id), "→ Read old.ts\n");
172 finishRun(app.db, old.id, { state: "ok", summary: "old" });
173 const page = await (await get(`/traces/${old.id}`)).text();
174 expect(page).toContain('id="trace-untimed"');
175 expect(page).not.toContain("trace-time small");
176 expect(page).not.toContain("<dt>Time</dt>");
177 });
178
179 test("the strip uses the accent only on a tick pointed at, and nothing explains itself twice", async () => {
180 const text = await (await get(`/traces/${runId}`)).text();
181 expect(text).toContain(".trace-strip rect{fill:var(--fg)}");
182 expect(text).not.toContain("opacity:.6");
183 expect(text).not.toContain("j and k move");
184 });
185
186 test("the run page offers the trace to who may read the log, not to who may only see the run (#17993)", async () => {
187 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bobby", email: "[email protected]", password: "correct-horse-battery" });
188 if (!bob.ok) throw new Error(bob.error);
189 const theirs = createToken(app.db, bob.value.id, "t", "rw").token;
190 const asBob = await fetch(`${servers.url}/alice/notes/runs/${runId}`, { headers: { authorization: `Bearer ${theirs}` } });
191 expect(asBob.status).toBe(200);
192 expect(await asBob.text()).not.toContain(`/traces/${runId}`);
193 expect((await fetch(`${servers.url}/traces/${runId}`, { headers: { authorization: `Bearer ${theirs}` } })).status).toBe(404);
194 expect(await (await get(`/alice/notes/runs/${runId}`)).text()).toContain(`/traces/${runId}`);
195 });
test/tui-runlog.test.ts +23
@@ -221,6 +221,29 @@ test("R rereads the log, and o prints the web address", async () => {
221221 expect(app.screen.toText()).toContain(`/alice/lamp/runs/${run.id}`);
222222 });
223223
224 test("t opens the run's trace, as the page reads it, and o prints its address (#17993)", async () => {
225 const run = createRun(forge.db, { repoId: repo.id, kind: "agent" });
226 claimRun(forge.db, run.id);
227 appendRunLog(dir, run.id, "thinking about it");
228 appendRunLog(dir, run.id, "→ Edit footer.txt");
229 const app = await open(alice, run.id);
230 await key(app, "t");
231 const text = app.screen.toText();
232 expect(text).toContain("Edit footer.txt");
233 expect(text).toContain("2 steps, 0 failed");
234 await key(app, "o");
235 expect(app.screen.toText()).toContain(`/traces/${run.id}`);
236 });
237
238 test("t on a log the viewer may not read opens nothing of it", async () => {
239 const run = createRun(forge.db, { repoId: repo.id, kind: "agent" });
240 claimRun(forge.db, run.id);
241 appendRunLog(dir, run.id, "→ Edit SECRET-FILE");
242 const app = await open(bob, run.id);
243 await key(app, "t");
244 expect(app.screen.toText()).not.toContain("SECRET-FILE");
245 });
246
224247 test("an agent run's log screen shows tokens × price per million (#13968)", async () => {
225248 const run = createRun(forge.db, { repoId: repo.id, kind: "agent" });
226249 claimRun(forge.db, run.id);

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

Keyboard shortcuts

Docs