Public: anyone can read this; the crew can change it.
An imported session opens at /traces/<id> as the same tree and time strip a crew run has #18366
Merged 3h 58m ago, live in production
mason/forge:mason/18357-an-imported-session-opens-at-traces-id-a → main 0 commits fork 2 threads · 2 unresolved
8 files
changed +310
−12
docs/features/traces.md +3 −1
| @@ -52,7 +52,9 @@ For Codex, point the same command at a rollout: `--data-binary @"$(ls -t ~/.code | ||
| 52 | 52 | |
| 53 | 53 | `POST /api/v1/traces/import` takes the session JSONL (Claude Code or Codex) as the raw body, at most 32 MiB (a plain 413 past it; `traceImport` in `src/kernel/body_caps.ts`). The file is read by the reader of its source (`src/trace/claude_code.ts`, `src/trace/codex.ts`), stored gzipped as `traces/imported/<id>.jsonl.gz` under the data directory, and indexed as a trace of kind `imported`, attributed to the caller and private to them: `GET /api/v1/traces?kind=imported` lists it for them and for no one else. The id comes from the caller and the session's own id, so sending the same session again answers 200 and replaces its trace; a first send answers 201. A file that is not UTF-8, is empty, holds no session records or carries no usable `sessionId` is a 422 (`invalid_session`) that says which. An account keeps at most 256 MiB of imported sessions (compressed, as stored; `IMPORT_QUOTA_BYTES` in `src/trace/import.ts`): an import that would pass it is a 413 (`quota_exceeded`), and re-sending a session replaces its own copy in the count. A person's imported files are deleted with their account. A session caller's cross-origin request is a 403. |
| 54 | 54 | |
| 55 | 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: a page for an imported trace, deleting one. | |
| 55 | 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. | |
| 56 | ||
| 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. | |
| 56 | 58 | ## One trace as a tree (#18022) |
| 57 | 59 | |
| 58 | 60 | `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/import.ts +10
| @@ -54,6 +54,16 @@ export function removeImported(dataDir: string, ids: readonly string[]): void { | ||
| 54 | 54 | for (const id of ids) rmSync(fileOf(dataDir, id), { force: true }); |
| 55 | 55 | } |
| 56 | 56 | |
| 57 | /** What the stored file is now (size and mtime), so a re-import, which replaces it, is seen. */ | |
| 58 | export function stampOf(dataDir: string, id: string): string | undefined { | |
| 59 | try { | |
| 60 | const st = statSync(fileOf(dataDir, id)); | |
| 61 | return `${st.size}:${st.mtimeMs}`; | |
| 62 | } catch { | |
| 63 | return undefined; | |
| 64 | } | |
| 65 | } | |
| 66 | ||
| 57 | 67 | /** The raw session as it was sent, from the stored file. */ |
| 58 | 68 | export function readImported(dataDir: string, id: string): string { |
| 59 | 69 | return gunzipSync(readFileSync(fileOf(dataDir, id))).toString("utf8"); |
src/trace/imported_read.ts added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | /** | |
| 2 | * An imported session read back for its owner (#18357): the stored gzipped file parsed by the | |
| 3 | * reader of its source into the same `Trace` a crew run's page shows, steps capped at `MAX_STEPS` | |
| 4 | * and times counted from the session's first moment. The caller has already passed the row | |
| 5 | * through `seenTraceRow`; this only reads. Plain data in, plain data out. | |
| 6 | */ | |
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { TraceRow } from "./index_table.ts"; | |
| 9 | import { readImported, stampOf } from "./import.ts"; | |
| 10 | import type { Step, Trace } from "./model.ts"; | |
| 11 | import { stepsOf, totalsOf } from "./model.ts"; | |
| 12 | import { MAX_STEPS } from "./run_log.ts"; | |
| 13 | import { parseSession } from "./session.ts"; | |
| 14 | ||
| 15 | export interface ImportedParse { | |
| 16 | readonly trace: Trace; | |
| 17 | /** The steps carry times (the session's records were stamped). */ | |
| 18 | readonly timed: boolean; | |
| 19 | /** The session held more than `MAX_STEPS` steps; the rest are not read. */ | |
| 20 | readonly truncated: boolean; | |
| 21 | /** The file as stored, for a step's raw lines on demand. */ | |
| 22 | readonly text: string; | |
| 23 | } | |
| 24 | ||
| 25 | /** Parses made, for a test to count: a page view and its step opens share one. */ | |
| 26 | export const parseCount = { n: 0 }; | |
| 27 | ||
| 28 | /** | |
| 29 | * The latest parses of a forge, by id and file stamp; a re-import changes the stamp. Few, as each | |
| 30 | * holds a file. | |
| 31 | */ | |
| 32 | const KEEP = 2; | |
| 33 | const kept = new WeakMap<App, Map<string, ImportedParse>>(); | |
| 34 | ||
| 35 | /** The session behind an `imported` row, or `undefined` when its file is gone or unreadable. */ | |
| 36 | export function parseImported(app: App, row: Pick<TraceRow, "id">): ImportedParse | undefined { | |
| 37 | const stamp = stampOf(app.config.dataDir, row.id); | |
| 38 | if (stamp === undefined) return undefined; | |
| 39 | const key = `${row.id}\0${stamp}`; | |
| 40 | let parsed = kept.get(app); | |
| 41 | if (parsed === undefined) kept.set(app, (parsed = new Map())); | |
| 42 | const hit = parsed.get(key); | |
| 43 | if (hit !== undefined) { | |
| 44 | parsed.delete(key); | |
| 45 | parsed.set(key, hit); | |
| 46 | return hit; | |
| 47 | } | |
| 48 | const read = parseFresh(app, row); | |
| 49 | if (read === undefined) return undefined; | |
| 50 | parsed.set(key, read); | |
| 51 | while (parsed.size > KEEP) parsed.delete(parsed.keys().next().value!); | |
| 52 | return read; | |
| 53 | } | |
| 54 | ||
| 55 | function parseFresh(app: App, row: Pick<TraceRow, "id">): ImportedParse | undefined { | |
| 56 | let text: string; | |
| 57 | try { | |
| 58 | text = readImported(app.config.dataDir, row.id); | |
| 59 | } catch { | |
| 60 | return undefined; | |
| 61 | } | |
| 62 | parseCount.n++; | |
| 63 | const trace = parseSession(text); | |
| 64 | const t0 = totalsOf(trace).startMs; | |
| 65 | let left = MAX_STEPS; | |
| 66 | let cut = false; | |
| 67 | for (const turn of trace.turns) { | |
| 68 | if (turn.steps.length > left) cut = true; | |
| 69 | turn.steps = turn.steps.slice(0, left); | |
| 70 | left -= turn.steps.length; | |
| 71 | for (const s of turn.steps) { | |
| 72 | s.startMs = Math.max(0, s.startMs - t0); | |
| 73 | s.endMs = Math.max(s.startMs, s.endMs - t0); | |
| 74 | } | |
| 75 | } | |
| 76 | const all = stepsOf(trace); | |
| 77 | return { trace, timed: all.length > 0 && all[all.length - 1]!.endMs > 0, truncated: cut, text }; | |
| 78 | } | |
| 79 | ||
| 80 | /** Most raw lines of one step, and most characters of each, the on-demand route answers. */ | |
| 81 | const RAW_LINES = 40; | |
| 82 | const RAW_CHARS = 8000; | |
| 83 | ||
| 84 | /** The lines of the file that name this step's id (a reply's, a tool call's and its result's). */ | |
| 85 | export function rawLinesOf(text: string, step: Pick<Step, "id">): string[] { | |
| 86 | const needle = JSON.stringify(step.id); | |
| 87 | const out: string[] = []; | |
| 88 | for (const line of text.split("\n")) { | |
| 89 | if (!line.includes(needle)) continue; | |
| 90 | out.push(line.length > RAW_CHARS ? `${line.slice(0, RAW_CHARS)}…` : line); | |
| 91 | if (out.length === RAW_LINES) break; | |
| 92 | } | |
| 93 | return out; | |
| 94 | } |
src/trace/index_table.ts +1 −1
| @@ -323,7 +323,7 @@ interface Stored { | ||
| 323 | 323 | /** One row of the index by its id, or undefined where none was written. */ |
| 324 | 324 | export function getTraceRow(db: Database, id: string): TraceRow | undefined { |
| 325 | 325 | const r = db.query<Stored, [string]>("SELECT * FROM trace_index WHERE id = ?1").get(id); |
| 326 | return r === null ? undefined : { id: r.id, kind: r.kind, repository: r.repository, title: r.title, model: r.model, account: r.account, steps: r.steps, errors: r.errors, tokensIn: r.tokens_in, tokensCached: r.tokens_cached, tokensOut: r.tokens_out, costUsd: r.cost_usd, outcome: r.outcome, started: r.started, ended: r.ended }; | |
| 326 | return r === null ? undefined : { id: r.id, kind: r.owner === "" ? r.kind : "imported", repository: r.repository, title: r.title, model: r.model, account: r.account, steps: r.steps, errors: r.errors, tokensIn: r.tokens_in, tokensCached: r.tokens_cached, tokensOut: r.tokens_out, costUsd: r.cost_usd, outcome: r.outcome, started: r.started, ended: r.ended }; | |
| 327 | 327 | } |
| 328 | 328 | |
| 329 | 329 | /** |
src/trace/tree.ts +5
| @@ -11,6 +11,7 @@ import { getRepo, getRepoById, type Repo } from "../core/repos.ts"; | ||
| 11 | 11 | import type { User } from "../core/users.ts"; |
| 12 | 12 | import { readRunLog, readRunTimes } from "../runs/log.ts"; |
| 13 | 13 | import { cursorOf, DEFAULT_LIMIT, getTraceRow, listTraceIndex, MAX_LIMIT, TRACE_CURSOR, type TraceKind, type TraceQuery, type TraceRow } from "./index_table.ts"; |
| 14 | import { parseImported } from "./imported_read.ts"; | |
| 14 | 15 | import type { Trace } from "./model.ts"; |
| 15 | 16 | import { MAX_STEPS, parseRunLog } from "./run_log.ts"; |
| 16 | 17 | |
| @@ -130,6 +131,10 @@ export function seenTraceRow(app: App, actor: User, id: string): TraceRow | unde | ||
| 130 | 131 | export function traceTree(app: App, actor: User, id: string): object | undefined { |
| 131 | 132 | const row = seenTraceRow(app, actor, id); |
| 132 | 133 | if (row === undefined) return undefined; |
| 134 | if (row.kind === "imported") { | |
| 135 | const read = parseImported(app, row); | |
| 136 | return read === undefined ? undefined : treeOf(row, read); | |
| 137 | } | |
| 133 | 138 | const dataDir = app.config.dataDir; |
| 134 | 139 | const { lines, truncated } = readRunLog(dataDir, row.id); |
| 135 | 140 | return treeOf(row, { ...parseRunLog(row.id, row.title, lines, readRunTimes(dataDir, row.id, lines.length)), truncated }); |
src/web/pages/trace.ts +24 −10
| @@ -18,6 +18,7 @@ import { crumbsFor, notFoundPage, pageHead, repoPalette } from "../chrome.ts"; | ||
| 18 | 18 | import { html, type Html } from "../html.ts"; |
| 19 | 19 | import { page } from "../layout.ts"; |
| 20 | 20 | import { behaviorsJs } from "../behaviors.ts"; |
| 21 | import { importedRowOf, importedStep, importedTracePage } from "./trace_imported.ts"; | |
| 21 | 22 | |
| 22 | 23 | /** A trace with this many steps or fewer opens its branches; a longer one opens none. */ |
| 23 | 24 | export const OPEN_BELOW = 100; |
| @@ -26,7 +27,7 @@ export const OPEN_BELOW = 100; | ||
| 26 | 27 | */ |
| 27 | 28 | export const MAX_TICKS = 300; |
| 28 | 29 | |
| 29 | const TRACE_CSS = ` | |
| 30 | export const TRACE_CSS = ` | |
| 30 | 31 | .trace-strip{display:block;width:100%;height:28px;margin:.5rem 0} |
| 31 | 32 | .trace-strip rect{fill:var(--fg)} |
| 32 | 33 | .trace-strip .trace-tick-tool rect{fill:var(--muted-fg)} |
| @@ -41,7 +42,7 @@ const TRACE_CSS = ` | ||
| 41 | 42 | .trace-time{color:var(--muted-fg);margin:0 .5rem} |
| 42 | 43 | `; |
| 43 | 44 | |
| 44 | const TRACE_JS = `(function(){ | |
| 45 | export const TRACE_JS = `(function(){ | |
| 45 | 46 | var root=document.getElementById('trace-tree');if(!root)return; |
| 46 | 47 | var base=root.dataset.base; |
| 47 | 48 | function load(d){var pre=d.querySelector(':scope > pre');if(!pre||pre.dataset.done)return;pre.dataset.done='1';pre.textContent='Loading…'; |
| @@ -71,7 +72,7 @@ function stepNode(s: Step, n: number, total: number, children: Html | null, base | ||
| 71 | 72 | * run kept times a tick sits and is as wide as its time in the run, so a slow tool or a long |
| 72 | 73 | * silence is a wide tick; without times each is as wide as another. |
| 73 | 74 | */ |
| 74 | function strip(steps: readonly Step[], timed: boolean): Html { | |
| 75 | export function strip(steps: readonly Step[], timed: boolean): Html { | |
| 75 | 76 | const ticks = Math.min(MAX_TICKS, steps.length); |
| 76 | 77 | const per = steps.length / ticks; |
| 77 | 78 | const whole = timed ? (steps[steps.length - 1]?.endMs ?? 0) : 0; |
| @@ -93,20 +94,26 @@ function strip(steps: readonly Step[], timed: boolean): Html { | ||
| 93 | 94 | 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>`; |
| 94 | 95 | } |
| 95 | 96 | |
| 96 | function body(view: TraceView, others: readonly { id: string; title: string }[], shared: boolean | undefined): Html { | |
| 97 | const steps = stepsInView(view); | |
| 97 | /** The tree: each model step open or shut with its tool calls nested under it. */ | |
| 98 | export function treeRows(steps: readonly Step[], base: string, timed: boolean): Html[] { | |
| 98 | 99 | const total = steps.length; |
| 99 | const base = traceHref(view.run.id); | |
| 100 | 100 | const open = total <= OPEN_BELOW; |
| 101 | const timed = view.timed && total > 0; | |
| 102 | 101 | let n = 0; |
| 103 | const rows = branchesOf(steps).map((b) => { | |
| 102 | return branchesOf(steps).map((b) => { | |
| 104 | 103 | const first = n + 1; |
| 105 | 104 | n += b.calls.length + (b.head === undefined ? 0 : 1); |
| 106 | 105 | if (b.head === undefined) return html`${b.calls.map((c, i) => stepNode(c, first + i, total, null, base, false, timed))}`; |
| 107 | 106 | const inner = b.calls.map((c, i) => stepNode(c, first + 1 + i, total, null, base, false, timed)); |
| 108 | 107 | return stepNode(b.head, first, total, html`<div class="trace-calls">${inner}</div>`, base, open, timed); |
| 109 | 108 | }); |
| 109 | } | |
| 110 | ||
| 111 | function body(view: TraceView, others: readonly { id: string; title: string }[], shared: boolean | undefined): Html { | |
| 112 | const steps = stepsInView(view); | |
| 113 | const total = steps.length; | |
| 114 | const base = traceHref(view.run.id); | |
| 115 | const timed = view.timed && total > 0; | |
| 116 | const rows = treeRows(steps, base, timed); | |
| 110 | 117 | const failed = steps.filter((s) => s.outcome === "error").length; |
| 111 | 118 | const changed = changedWords(view); |
| 112 | 119 | return html`${pageHead(html`Trace: ${view.title}`, { sub: "One crew run, step by step, and what it changed." })} |
| @@ -142,7 +149,10 @@ export function repoOfRun(ctx: Ctx): { repo: Repo; id: string } | undefined { | ||
| 142 | 149 | export async function tracePage(ctx: Ctx): Promise<Response> { |
| 143 | 150 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 144 | 151 | const found = repoOfRun(ctx); |
| 145 | if (found === undefined) return notFoundPage(ctx); | |
| 152 | if (found === undefined) { | |
| 153 | const imported = importedRowOf(ctx); | |
| 154 | return imported === undefined ? notFoundPage(ctx) : importedTracePage(ctx, imported); | |
| 155 | } | |
| 146 | 156 | const view = await readTrace(ctx.app, ctx.auth.user, found.repo, found.id); |
| 147 | 157 | if (view === undefined) return notFoundPage(ctx); |
| 148 | 158 | const others = view.run.issueId === null ? [] : otherRunsOfIssue(ctx.app.db, view.run.issueId, view.run.id, 10).map((r) => ({ id: r.id, title: `${r.model === "" ? r.kind : r.model} · ${r.state} · ${r.createdAt.slice(0, 16).replace("T", " ")} UTC` })); |
| @@ -162,7 +172,11 @@ export async function tracePage(ctx: Ctx): Promise<Response> { | ||
| 162 | 172 | export async function traceStep(ctx: Ctx): Promise<Response> { |
| 163 | 173 | const found = repoOfRun(ctx); |
| 164 | 174 | const n = stepNumber(ctx.params.n ?? ""); |
| 165 | if (found === undefined || n === undefined) return notFoundPage(ctx); | |
| 175 | if (found === undefined) { | |
| 176 | const imported = importedRowOf(ctx); | |
| 177 | return imported === undefined ? notFoundPage(ctx) : importedStep(ctx, imported); | |
| 178 | } | |
| 179 | if (n === undefined) return notFoundPage(ctx); | |
| 166 | 180 | const view = await readTrace(ctx.app, ctx.auth.user, found.repo, found.id); |
| 167 | 181 | const raw = view === undefined ? undefined : stepPayload(view, n); |
| 168 | 182 | if (view === undefined || raw === undefined) return notFoundPage(ctx); |
src/web/pages/trace_imported.ts added +66
| @@ -0,0 +1,66 @@ | ||
| 1 | /** | |
| 2 | * `/traces/:id` for an imported session (#18357): the tree and strip a crew run has, read from the | |
| 3 | * stored file by `parseImported`, for the person who imported it alone (anyone else is the | |
| 4 | * not-found an unknown id gets, `seenTraceRow`). The file holds no cost and often no tokens; the | |
| 5 | * page says so rather than showing zero. Raw lines load per step, as on a run's page. | |
| 6 | */ | |
| 7 | import type { Ctx } from "../../http/context.ts"; | |
| 8 | import { securityFloor } from "../../http/respond.ts"; | |
| 9 | import { parseImported, rawLinesOf } from "../../trace/imported_read.ts"; | |
| 10 | import type { TraceRow } from "../../trace/index_table.ts"; | |
| 11 | import { stepsOf } from "../../trace/model.ts"; | |
| 12 | import { spanWords, stepLine } from "../../trace/read.ts"; | |
| 13 | import { stepNumber } from "../../trace/run_log.ts"; | |
| 14 | import { seenTraceRow } from "../../trace/tree.ts"; | |
| 15 | import { notFoundPage, pageHead } from "../chrome.ts"; | |
| 16 | import { html } from "../html.ts"; | |
| 17 | import { page } from "../layout.ts"; | |
| 18 | import { behaviorsJs } from "../behaviors.ts"; | |
| 19 | import { strip, TRACE_CSS, TRACE_JS, treeRows } from "./trace.ts"; | |
| 20 | ||
| 21 | /** The imported row `ctx`'s viewer imported, or undefined: signed out or another's is the same. */ | |
| 22 | export function importedRowOf(ctx: Ctx): TraceRow | undefined { | |
| 23 | const user = ctx.auth.user; | |
| 24 | const row = user === undefined ? undefined : seenTraceRow(ctx.app, user, ctx.params.id ?? ""); | |
| 25 | return row?.kind === "imported" ? row : undefined; | |
| 26 | } | |
| 27 | ||
| 28 | export function importedTracePage(ctx: Ctx, row: TraceRow): Response { | |
| 29 | const read = parseImported(ctx.app, row); | |
| 30 | if (read === undefined) return notFoundPage(ctx); | |
| 31 | // The session's own step ids (a message's, a tool call's) are not permalinks: `step-N` is. | |
| 32 | const steps = stepsOf(read.trace).map((s, i) => ({ ...s, id: `step-${i + 1}` })); | |
| 33 | const total = steps.length; | |
| 34 | const base = `/traces/${row.id}`; | |
| 35 | const timed = read.timed; | |
| 36 | const failed = steps.filter((s) => s.outcome === "error").length; | |
| 37 | const tokens = row.tokensIn + row.tokensCached + row.tokensOut; | |
| 38 | const content = html`${pageHead(html`Trace: ${row.title}`, { sub: `An imported ${read.trace.source} session, step by step. Only you can read it.` })} | |
| 39 | <dl class="row-facts" id="trace-total"> | |
| 40 | <div><dt>Steps</dt><dd>${String(total)}</dd></div> | |
| 41 | <div><dt>Failed</dt><dd>${String(failed)}</dd></div> | |
| 42 | ${timed ? html`<div><dt>Time</dt><dd>${spanWords(steps[total - 1]!.endMs)}</dd></div>` : null} | |
| 43 | <div><dt>Tokens</dt><dd id="trace-tokens">${tokens === 0 ? "not recorded in this file" : `${row.tokensIn} in, ${row.tokensCached} cached, ${row.tokensOut} out`}</dd></div> | |
| 44 | <div><dt>Cost</dt><dd id="trace-cost">${row.costUsd > 0 ? `$${row.costUsd.toFixed(2)}` : "not recorded in this file"}</dd></div> | |
| 45 | </dl> | |
| 46 | <nav class="bar small" id="trace-links" aria-label="Where this trace is"><a href="/traces">All traces</a></nav> | |
| 47 | ${read.truncated ? html`<p class="small muted" id="trace-cut">The session is longer than the page reads; only its first steps are shown.</p>` : null} | |
| 48 | ${total === 0 ? html`<p class="muted" id="trace-empty">This session holds no steps.</p>` : html`${strip(steps, timed)} | |
| 49 | <div class="trace-tree" id="trace-tree" data-base="${base}" role="group" aria-label="Steps">${treeRows(steps, base, timed)}</div> | |
| 50 | ${timed ? null : html`<p class="small muted" id="trace-untimed">This session's records carry no times, so steps show none.</p>`}`}`; | |
| 51 | return page({ ctx, title: `Trace · ${row.title}`, body: content, styleCss: TRACE_CSS, scriptJs: `${behaviorsJs}\n${TRACE_JS}` }); | |
| 52 | } | |
| 53 | ||
| 54 | /** The raw lines of step `:n` of an imported session, as text. */ | |
| 55 | export function importedStep(ctx: Ctx, row: TraceRow): Response { | |
| 56 | const n = stepNumber(ctx.params.n ?? ""); | |
| 57 | const read = n === undefined ? undefined : parseImported(ctx.app, row); | |
| 58 | const step = read === undefined ? undefined : stepsOf(read.trace)[n! - 1]; | |
| 59 | if (read === undefined || step === undefined) return notFoundPage(ctx); | |
| 60 | const raw = rawLinesOf(read.text, step); | |
| 61 | return securityFloor( | |
| 62 | new Response(`${stepLine(step, n!, stepsOf(read.trace).length, read.timed)}\n${raw.length === 0 ? "No raw line of the file names this step." : raw.join("\n")}\n`, { | |
| 63 | headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "private, no-store" }, | |
| 64 | }), | |
| 65 | ); | |
| 66 | } |
test/trace-imported-page.test.ts added +107
| @@ -0,0 +1,107 @@ | ||
| 1 | /** /traces/<id> for an imported session (#18357): the importer reads a tree, anyone else a 404. */ | |
| 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 { createUser } from "../src/core/users.ts"; | |
| 9 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 10 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 11 | ||
| 12 | const rec = (o: object): string => JSON.stringify({ sessionId: "sess-p", cwd: "/w", ...o }); | |
| 13 | const SESSION = [ | |
| 14 | rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "fix <b>the</b> login bug" } }), | |
| 15 | rec({ type: "assistant", timestamp: "2026-12-01T09:00:01Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "text", text: "Looking <script>x</script>" }, { type: "tool_use", id: "t1", name: "Edit", input: { file_path: "a.ts", old_string: "a", new_string: "a\nb" } }] } }), | |
| 16 | rec({ type: "user", timestamp: "2026-12-01T09:00:04Z", message: { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] } }), | |
| 17 | rec({ type: "assistant", timestamp: "2026-12-01T09:00:05Z", message: { id: "m2", model: "claude-x", role: "assistant", content: [{ type: "text", text: "Done" }] } }), | |
| 18 | ].join("\n"); | |
| 19 | ||
| 20 | let dir = ""; | |
| 21 | let app: App, servers: Servers; | |
| 22 | let alice = "", bob = "", id = ""; | |
| 23 | ||
| 24 | const get = (path: string, token: string | undefined) => fetch(`${servers.url}${path}`, { headers: token === undefined ? {} : { authorization: `Bearer ${token}` } }); | |
| 25 | ||
| 26 | beforeAll(async () => { | |
| 27 | dir = await mkdtemp(join(tmpdir(), "forge-trace-imported-page-")); | |
| 28 | app = createApp({ dataDir: dir, port: 0 }); | |
| 29 | servers = await serve(app); | |
| 30 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 31 | if (!a.ok) throw new Error(a.error); | |
| 32 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 33 | if (!b.ok) throw new Error(b.error); | |
| 34 | alice = createToken(app.db, a.value.id, "t", "rw").token; | |
| 35 | bob = createToken(app.db, b.value.id, "t", "rw").token; | |
| 36 | const sent = await fetch(`${servers.url}/api/v1/traces/import`, { method: "POST", headers: { authorization: `Bearer ${alice}` }, body: SESSION }); | |
| 37 | id = ((await sent.json()) as { id: string }).id; | |
| 38 | }, 30_000); | |
| 39 | ||
| 40 | afterAll(async () => { | |
| 41 | await servers.stop(); | |
| 42 | await rm(dir, { recursive: true, force: true }); | |
| 43 | }); | |
| 44 | ||
| 45 | test("the importer reads the tree, strip and permalinks, escaped, and is told what the file lacks", async () => { | |
| 46 | const res = await get(`/traces/${id}`, alice); | |
| 47 | expect(res.status).toBe(200); | |
| 48 | const text = await res.text(); | |
| 49 | expect(text).toContain('id="step-1"'); | |
| 50 | expect(text).toContain('id="step-3"'); | |
| 51 | expect(text).toContain("Edit a.ts +2 −1"); | |
| 52 | expect(text).toContain('id="trace-tree" data-base="/traces/'); | |
| 53 | for (const m of text.matchAll(/<a href="#(step-\d+)" class="trace-tick/g)) expect(text).toContain(`id="${m[1]}"`); | |
| 54 | expect(text).not.toContain("<script>x</script>"); | |
| 55 | expect(text).not.toContain("<b>the</b>"); | |
| 56 | expect(text).toMatch(/id="trace-tokens">not recorded in this file/); | |
| 57 | expect(text).toMatch(/id="trace-cost">not recorded in this file/); | |
| 58 | }); | |
| 59 | ||
| 60 | test("a step's raw lines load on demand, only for the importer", async () => { | |
| 61 | const step = await get(`/traces/${id}/steps/2`, alice); | |
| 62 | expect(step.status).toBe(200); | |
| 63 | expect(step.headers.get("content-type")).toContain("text/plain"); | |
| 64 | const raw = await step.text(); | |
| 65 | expect(raw).toContain('"id":"t1"'); | |
| 66 | expect(raw).toContain("tool_result"); | |
| 67 | expect((await get(`/traces/${id}/steps/99`, alice)).status).toBe(404); | |
| 68 | expect((await get(`/traces/${id}/steps/2`, bob)).status).toBe(404); | |
| 69 | }); | |
| 70 | ||
| 71 | test("another user and a signed-out visitor get the 404 an unknown id gets", async () => { | |
| 72 | const unknown = await get(`/traces/${"0".repeat(32)}`, bob); | |
| 73 | expect(unknown.status).toBe(404); | |
| 74 | expect((await get(`/traces/${id}`, bob)).status).toBe(404); | |
| 75 | expect((await get(`/traces/${id}`, undefined)).status).toBe(404); | |
| 76 | expect((await get(`/api/v1/traces/${id}`, bob)).status).toBe(404); | |
| 77 | const tree: any = await (await get(`/api/v1/traces/${id}`, alice)).json(); | |
| 78 | expect(tree.steps).toBe(3); | |
| 79 | expect(tree.turns[0].steps.length).toBe(3); | |
| 80 | }); | |
| 81 | ||
| 82 | test("a page view and its step opens share one parse, and a re-import is read afresh", async () => { | |
| 83 | const { parseCount } = await import("../src/trace/imported_read.ts"); | |
| 84 | const send = async (text: string) => ((await (await fetch(`${servers.url}/api/v1/traces/import`, { method: "POST", headers: { authorization: `Bearer ${alice}` }, body: text })).json()) as { id: string }).id; | |
| 85 | const own = await send(SESSION.replaceAll("sess-p", "sess-cache")); | |
| 86 | const before = parseCount.n; | |
| 87 | for (const path of [`/traces/${own}`, `/traces/${own}/steps/1`, `/traces/${own}/steps/2`]) expect((await get(path, alice)).status).toBe(200); | |
| 88 | expect(parseCount.n - before).toBe(1); | |
| 89 | expect(await send(SESSION.replaceAll("sess-p", "sess-cache").replace("fix <b>the", "fix <b>that"))).toBe(own); | |
| 90 | expect(await (await get(`/traces/${own}`, alice)).text()).toContain("fix <b>that"); | |
| 91 | expect(parseCount.n - before).toBe(2); | |
| 92 | }); | |
| 93 | ||
| 94 | test("one parse of a near-cap session is measured", async () => { | |
| 95 | const { parseImported } = await import("../src/trace/imported_read.ts"); | |
| 96 | const line = (i: number) => rec({ type: i % 2 ? "assistant" : "user", timestamp: new Date(Date.UTC(2026, 11, 1) + i * 1000).toISOString(), message: i % 2 ? { id: `m${i}`, model: "x", role: "assistant", content: [{ type: "text", text: "y".repeat(2000) }] } : { role: "user", content: "z".repeat(2000) } }); | |
| 97 | const lines: string[] = []; | |
| 98 | for (let n = 0, i = 0; n < 31 * 1024 * 1024; i++) { const l = line(i); lines.push(l); n += l.length + 1; } | |
| 99 | const big = lines.join("\n").replaceAll("sess-p", "sess-big"); | |
| 100 | const sent = await fetch(`${servers.url}/api/v1/traces/import`, { method: "POST", headers: { authorization: `Bearer ${alice}` }, body: big }); | |
| 101 | const out = (await sent.json()) as { id: string }; | |
| 102 | if (sent.status !== 201 && sent.status !== 200) throw new Error(JSON.stringify(out)); | |
| 103 | const bigId = out.id; | |
| 104 | const t = performance.now(); | |
| 105 | expect(parseImported(app, { id: bigId })).toBeDefined(); | |
| 106 | expect(performance.now() - t).toBeLessThan(2000); | |
| 107 | }, 60_000); |
new above
offline
A 32 MiB parse per request on the event loop (item 2). Cache by id and file mtime, bounded.