Public: anyone can read this; the crew can change it.
Traces 2: /traces lists every trace with facets and search #18015
Merged 10h 28m ago, live in production
scout/forge:scout/17992-traces-2-traces-lists-every-trace-with-f → main 0 commits fork 4 threads · 4 unresolved
17 files
changed +765
−8
- docs/design/areas/traces.md
- docs/design/audit.md
- docs/features/traces.md
- src/core/migration-pins/20261204000000-run-agent-index.pin
- src/core/migrations/20261204000000-run-agent-index.ts
- src/generated/screens.ts
- src/http/lazy_lists.ts
- src/http/routes/operations.ts
- src/trace/list.ts
- src/tui/screens/traces.ts
- src/web/pages/trace.ts
- src/web/pages/traces.ts
- test/forge-looks.test.ts
- test/keymap-terminal.test.ts
- test/palette-roster.test.ts
- test/traces-leak.test.ts
- test/traces-list.test.ts
docs/design/areas/traces.md +2
| @@ -1,3 +1,5 @@ | ||
| 1 | 1 | # Traces |
| 2 | 2 | |
| 3 | 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). |
| 4 | ||
| 5 | `/traces` (`src/web/pages/traces.ts`), the list. Page-local classes, drawn from existing tokens: `.traces-search` (the search form: the input grows, the button and the Filters disclosure wrap under it on a phone) and `.traces-facets` (the facet selects and dates, an auto-fit grid of `.field`s). `#traces-list` only ellipsises a row's title and meta to one line each. A removable active filter is the shared `.badge` with the `x` icon inside its link. |
docs/design/audit.md +1
| @@ -81,6 +81,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 81 | 81 | - `/packs` — `pages/packs.ts` · the premade forges this forge ships, what each brings, how to deploy it and how a stranger helps build its apps · the user menu, the signed-out menu, the palette · none seen; uses the shared card, list and button components. |
| 82 | 82 | - `/map` — `pages/map.ts` (1,806 lines) · the dependency map of work across the forge · `/board`, issue dependency lists, `/:owner/:name/map` · colours 3, sizes 12: the largest private vocabulary. |
| 83 | 83 | - `/advisories` — `pages/advisories.ts` · known vulnerabilities, exploited ones first, each with the repositories whose lockfile it hits, and a form to paste a feed · the terminal's Advisories command, the MCP `audit` tool · none seen. |
| 84 | - `/traces` — `pages/traces.ts` · every crew run you may open, newest first, with facets and search in the URL · a trace page's "All traces" link, the terminal's Traces command · none seen; uses the shared card, row and button components. | |
| 84 | 85 | - `/audit` — `pages/audit.ts` · every app's contract, who can do what · the app page's one-line policy · none seen. Names the audit of apps, not this document. |
| 85 | 86 | - `/repos` — `pages/my-repos.ts` · the repositories you may write, from the account menu · `/` (your apps), `/:owner` (a profile's repositories) · none seen. |
| 86 | 87 | - `/releases` — `pages/releases.ts` · the forge's kept releases and rollback · `/settings/backups` (both are "go back") · none seen. |
docs/features/traces.md +6
| @@ -16,6 +16,12 @@ Every conversation and run is a record the forge keeps; a trace is the same reco | ||
| 16 | 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 | 17 | |
| 18 | 18 | |
| 19 | ## The list (#17992) | |
| 20 | ||
| 21 | `/traces` lists every crew run the viewer may open (a run's log is the crew's and the owner's, as on its run page), newest first, a line each: title, kind, repository, model, cost (for those who may see spend), time, outcome. The search and the facets (repository, model, outcome, person or agent, from and to dates) are query parameters, so a search is a link (`/traces?repo=alice/notes&model=claude-opus&q=footer`); a malformed one is dropped. `q` matches the run's issue title and summary. `j`/`k` move, Enter opens the trace, `/` searches; the first paint holds no script of its own. Older traces follow a cursor (`before`). Terminal door: the Traces command in the palette (`src/tui/screens/traces.ts`: `/` searches, `j`/`k` move, Enter opens, `n` older). Reader: `src/trace/list.ts`, over a partial index of crew runs (`run_agent`). | |
| 22 | ||
| 23 | Not yet: Talk conversations and outside imports as rows (they wait for the trace index of #17991), a kind facet (every row is a crew run), archived turns in the search, and a JSON twin of the list. | |
| 24 | ||
| 19 | 25 | 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), compare, share. |
| 20 | 26 | |
| 21 | 27 | 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/migration-pins/20261204000000-run-agent-index.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 9d9865d5e8a5234aaac923a123a185fcdb277994dfc9ed73aaf474352427aadc |
src/core/migrations/20261204000000-run-agent-index.ts added +5
src/generated/screens.ts +9 −7
| @@ -127,13 +127,14 @@ import * as s122 from "../tui/screens/tab.ts"; | ||
| 127 | 127 | import * as s123 from "../tui/screens/teams.ts"; |
| 128 | 128 | import * as s124 from "../tui/screens/telemetry.ts"; |
| 129 | 129 | import * as s125 from "../tui/screens/tell_undo.ts"; |
| 130 | import * as s126 from "../tui/screens/traffic.ts"; | |
| 131 | import * as s127 from "../tui/screens/trafficview.ts"; | |
| 132 | import * as s128 from "../tui/screens/valves.ts"; | |
| 133 | import * as s129 from "../tui/screens/waiting.ts"; | |
| 134 | import * as s130 from "../tui/screens/waiting_for_me.ts"; | |
| 135 | import * as s131 from "../tui/screens/wayback.ts"; | |
| 136 | import * as s132 from "../tui/screens/weekcard.ts"; | |
| 130 | import * as s126 from "../tui/screens/traces.ts"; | |
| 131 | import * as s127 from "../tui/screens/traffic.ts"; | |
| 132 | import * as s128 from "../tui/screens/trafficview.ts"; | |
| 133 | import * as s129 from "../tui/screens/valves.ts"; | |
| 134 | import * as s130 from "../tui/screens/waiting.ts"; | |
| 135 | import * as s131 from "../tui/screens/waiting_for_me.ts"; | |
| 136 | import * as s132 from "../tui/screens/wayback.ts"; | |
| 137 | import * as s133 from "../tui/screens/weekcard.ts"; | |
| 137 | 138 | |
| 138 | 139 | /** Each screen file that declares palette entries: its module and the export names. */ |
| 139 | 140 | export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [ |
| @@ -270,4 +271,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon | ||
| 270 | 271 | [s130, ["entry"]], |
| 271 | 272 | [s131, ["entry"]], |
| 272 | 273 | [s132, ["entry"]], |
| 274 | [s133, ["entry"]], | |
| 273 | 275 | ]; |
src/http/lazy_lists.ts +1
src/http/routes/operations.ts +2
| @@ -23,6 +23,7 @@ import { advisoriesIngest, advisoriesPage } from "../../web/pages/advisories.ts" | ||
| 23 | 23 | import { resiliencePage, nightlyOutputPage } from "../../web/pages/resilience.ts"; |
| 24 | 24 | import { runRedirect } from "../../web/pages/runs.ts"; |
| 25 | 25 | import { tracePage, traceStep } from "../../web/pages/trace.ts"; |
| 26 | import { tracesPage } from "../../web/pages/traces.ts"; | |
| 26 | 27 | import { oauthCallbackUri } from "../api.ts"; |
| 27 | 28 | import { gamesRoutes } from "../games_routes.ts"; |
| 28 | 29 | import { infraRoutes } from "../infra_routes.ts"; |
| @@ -120,6 +121,7 @@ export function operationsRoutes(router: Router<Handler>, knownPatterns: () => s | ||
| 120 | 121 | }); |
| 121 | 122 | router.add("GET", "/runs/:id", runRedirect); |
| 122 | 123 | // A crew run as a tree of steps (#17993). Literal, above /:owner. |
| 124 | router.add("GET", "/traces", tracesPage); | |
| 123 | 125 | router.add("GET", "/traces/:id", tracePage); |
| 124 | 126 | router.add("GET", "/traces/:id/steps/:n", traceStep); |
| 125 | 127 | } |
src/trace/list.ts added +246
| @@ -0,0 +1,246 @@ | ||
| 1 | /** | |
| 2 | * Every crew run as one line of a list (#17992): `/traces` and the terminal read this one answer. | |
| 3 | * Newest first by run id (a cursor), filtered by repository, model, outcome, date, who ran it and | |
| 4 | * a text over the run's title and summary. Gated as a run's log is (`mayReadRunLog`): a run the | |
| 5 | * viewer may not open is never a row, never a count. Plain data in, plain data out; a read of the | |
| 6 | * `run` table, no second copy of anything. | |
| 7 | */ | |
| 8 | import { mayReadRunLog } from "../actions/runs.ts"; | |
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { canRead, canSeeOwnerFacts, getRepo, getRepoById, type Repo } from "../core/repos.ts"; | |
| 11 | import type { User } from "../core/users.ts"; | |
| 12 | import { traceHref } from "./read.ts"; | |
| 13 | ||
| 14 | export const OUTCOMES = ["ok", "failed", "cancelled", "running", "queued"] as const; | |
| 15 | export type TraceOutcome = (typeof OUTCOMES)[number]; | |
| 16 | ||
| 17 | /** The query of the list, as the URL holds it. Every field is validated by `readFilter`. */ | |
| 18 | export interface TraceFilter { | |
| 19 | readonly repo?: string; | |
| 20 | readonly model?: string; | |
| 21 | readonly outcome?: TraceOutcome; | |
| 22 | readonly from?: string; | |
| 23 | readonly to?: string; | |
| 24 | readonly by?: string; | |
| 25 | readonly q?: string; | |
| 26 | readonly before?: string; | |
| 27 | } | |
| 28 | ||
| 29 | export interface TraceRow { | |
| 30 | readonly id: string; | |
| 31 | readonly title: string; | |
| 32 | readonly kind: "crew run"; | |
| 33 | readonly repo: string; | |
| 34 | readonly model: string; | |
| 35 | /** Only for those who may see the owner's spend. */ | |
| 36 | readonly costUsd: number | undefined; | |
| 37 | readonly at: string; | |
| 38 | readonly outcome: TraceOutcome; | |
| 39 | readonly by: string; | |
| 40 | readonly href: string; | |
| 41 | } | |
| 42 | ||
| 43 | export interface TraceFacets { | |
| 44 | readonly repos: string[]; | |
| 45 | readonly models: string[]; | |
| 46 | readonly people: string[]; | |
| 47 | } | |
| 48 | ||
| 49 | export interface TraceList { | |
| 50 | readonly rows: TraceRow[]; | |
| 51 | /** The cursor of the next page, when there is one. */ | |
| 52 | readonly next: string | undefined; | |
| 53 | readonly facets: TraceFacets; | |
| 54 | } | |
| 55 | ||
| 56 | export const PAGE = 50; | |
| 57 | /** | |
| 58 | * One read of this many runs; the scan stops after `SCAN` of them so a rare filter never holds a | |
| 59 | * request. | |
| 60 | */ | |
| 61 | const BATCH = 200; | |
| 62 | const SCAN = 4000; | |
| 63 | ||
| 64 | const DAY = /^\d{4}-\d{2}-\d{2}$/; | |
| 65 | const NAME = /^[A-Za-z0-9._-]{1,64}$/; | |
| 66 | ||
| 67 | /** The filter a query string asks for: anything malformed is dropped, never an error. */ | |
| 68 | export function readFilter(params: URLSearchParams): TraceFilter { | |
| 69 | const one = (k: string, max: number): string | undefined => { | |
| 70 | const v = (params.get(k) ?? "").trim().slice(0, max); | |
| 71 | return v === "" ? undefined : v; | |
| 72 | }; | |
| 73 | const repo = one("repo", 130); | |
| 74 | const outcome = one("outcome", 12); | |
| 75 | const from = one("from", 10); | |
| 76 | const to = one("to", 10); | |
| 77 | const by = one("by", 64); | |
| 78 | const model = one("model", 80); | |
| 79 | const before = one("before", 64); | |
| 80 | const q = one("q", 80); | |
| 81 | const out: { -readonly [K in keyof TraceFilter]: TraceFilter[K] } = {}; | |
| 82 | if (repo !== undefined && /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,63}\/[A-Za-z0-9_-][A-Za-z0-9._-]{0,63}$/.test(repo)) out.repo = repo; | |
| 83 | if (outcome !== undefined && (OUTCOMES as readonly string[]).includes(outcome)) out.outcome = outcome as TraceOutcome; | |
| 84 | if (from !== undefined && DAY.test(from)) out.from = from; | |
| 85 | if (to !== undefined && DAY.test(to)) out.to = to; | |
| 86 | if (by !== undefined && NAME.test(by)) out.by = by; | |
| 87 | if (model !== undefined) out.model = model; | |
| 88 | if (before !== undefined && /^[0-9A-Za-z_-]{1,64}$/.test(before)) out.before = before; | |
| 89 | if (q !== undefined) out.q = q; | |
| 90 | return out; | |
| 91 | } | |
| 92 | ||
| 93 | /** The query string of a filter, in a fixed order: the same search is the same link. */ | |
| 94 | export function filterQuery(f: TraceFilter, over: Partial<Record<keyof TraceFilter, string | undefined>> = {}): string { | |
| 95 | const merged: Record<string, string | undefined> = { ...f, ...over }; | |
| 96 | const p = new URLSearchParams(); | |
| 97 | for (const k of ["q", "repo", "model", "outcome", "by", "from", "to", "before"]) { | |
| 98 | const v = merged[k]; | |
| 99 | if (v !== undefined && v !== "") p.set(k, v); | |
| 100 | } | |
| 101 | const s = p.toString(); | |
| 102 | return s === "" ? "" : `?${s}`; | |
| 103 | } | |
| 104 | ||
| 105 | interface Row { | |
| 106 | id: string; | |
| 107 | repo_id: string; | |
| 108 | title: string; | |
| 109 | model: string; | |
| 110 | cost_usd: number; | |
| 111 | created_at: string; | |
| 112 | state: string; | |
| 113 | by: string | null; | |
| 114 | } | |
| 115 | ||
| 116 | const likeOf = (q: string): string => `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`; | |
| 117 | ||
| 118 | function where(f: TraceFilter, repoId: string | undefined, actorName: string | undefined): { sql: string; params: (string | number)[] } { | |
| 119 | const params: (string | number)[] = []; | |
| 120 | const add = (v: string | number): string => (params.push(v), `?${params.length}`); | |
| 121 | let sql = "r.kind = 'agent'"; | |
| 122 | if (repoId !== undefined) sql += ` AND r.repo_id = ${add(repoId)}`; | |
| 123 | if (f.model !== undefined) sql += ` AND r.model = ${add(f.model)}`; | |
| 124 | if (f.outcome !== undefined) sql += ` AND r.state = ${add(f.outcome)}`; | |
| 125 | if (f.from !== undefined) sql += ` AND r.created_at >= ${add(`${f.from}T00:00:00`)}`; | |
| 126 | if (f.to !== undefined) sql += ` AND r.created_at < ${add(`${nextDay(f.to)}T00:00:00`)}`; | |
| 127 | if (actorName !== undefined) sql += ` AND u.username = ${add(actorName)}`; | |
| 128 | if (f.q !== undefined) { | |
| 129 | const like = add(likeOf(f.q)); | |
| 130 | sql += ` AND (COALESCE(i.title, '') LIKE ${like} ESCAPE '\\' OR r.summary LIKE ${like} ESCAPE '\\')`; | |
| 131 | } | |
| 132 | return { sql, params }; | |
| 133 | } | |
| 134 | ||
| 135 | function nextDay(day: string): string { | |
| 136 | const d = new Date(`${day}T00:00:00Z`); | |
| 137 | if (Number.isNaN(d.getTime())) return day; | |
| 138 | d.setUTCDate(d.getUTCDate() + 1); | |
| 139 | return d.toISOString().slice(0, 10); | |
| 140 | } | |
| 141 | ||
| 142 | const FROM = `run r LEFT JOIN issue i ON i.id = r.issue_id LEFT JOIN user u ON u.id = r.actor_id`; | |
| 143 | ||
| 144 | /** One page of traces `actor` may open, newest first. */ | |
| 145 | export function listTraces(app: App, actor: User | undefined, f: TraceFilter): TraceList { | |
| 146 | const db = app.db; | |
| 147 | let repoId: string | undefined; | |
| 148 | if (f.repo !== undefined) { | |
| 149 | const [owner, name] = f.repo.split("/") as [string, string]; | |
| 150 | const found = getRepo(db, owner, name); | |
| 151 | // A repository the viewer cannot read is an empty list, not a hint that it exists. | |
| 152 | if (found === undefined || !canRead(db, found, actor)) return { rows: [], next: undefined, facets: facetsOf(app, actor) }; | |
| 153 | repoId = found.id; | |
| 154 | } | |
| 155 | const { sql, params } = where(f, repoId, f.by); | |
| 156 | // What the viewer may open, asked once a repository for this call. | |
| 157 | const repos = new Map<string, { repo: Repo; open: boolean; spend: boolean } | undefined>(); | |
| 158 | const seen = (id: string) => { | |
| 159 | if (!repos.has(id)) { | |
| 160 | const repo = getRepoById(db, id); | |
| 161 | repos.set(id, repo === undefined ? undefined : { repo, open: canRead(db, repo, actor) && mayReadRunLog(app, actor, repo), spend: canSeeOwnerFacts(db, repo, actor) }); | |
| 162 | } | |
| 163 | return repos.get(id); | |
| 164 | }; | |
| 165 | const rows: TraceRow[] = []; | |
| 166 | let cursor = f.before; | |
| 167 | let scanned = 0; | |
| 168 | let exhausted = false; | |
| 169 | let more = false; | |
| 170 | while (!more && scanned < SCAN && !exhausted) { | |
| 171 | const p = [...params]; | |
| 172 | const w = cursor === undefined ? sql : `${sql} AND r.id < ?${p.push(cursor)}`; | |
| 173 | p.push(BATCH); | |
| 174 | const got = db | |
| 175 | .query<Row, (string | number)[]>( | |
| 176 | `SELECT r.id, r.repo_id, COALESCE(NULLIF(i.title, ''), NULLIF(r.summary, ''), 'agent run') AS title, r.model, r.cost_usd, r.created_at, r.state, u.username AS by | |
| 177 | FROM ${FROM} WHERE ${w} ORDER BY r.id DESC LIMIT ?${p.length}`, | |
| 178 | ) | |
| 179 | .all(...p); | |
| 180 | scanned += got.length; | |
| 181 | if (got.length < BATCH) exhausted = true; | |
| 182 | for (const r of got) { | |
| 183 | const s = seen(r.repo_id); | |
| 184 | if (s === undefined || !s.open) { | |
| 185 | cursor = r.id; | |
| 186 | continue; | |
| 187 | } | |
| 188 | if (rows.length === PAGE) { | |
| 189 | more = true; | |
| 190 | break; | |
| 191 | } | |
| 192 | cursor = r.id; | |
| 193 | rows.push({ | |
| 194 | id: r.id, | |
| 195 | title: r.title, | |
| 196 | kind: "crew run", | |
| 197 | repo: `${s.repo.ownerName}/${s.repo.name}`, | |
| 198 | model: r.model, | |
| 199 | costUsd: s.spend && r.cost_usd > 0 ? r.cost_usd : undefined, | |
| 200 | at: r.created_at, | |
| 201 | outcome: r.state as TraceOutcome, | |
| 202 | by: r.by ?? "", | |
| 203 | href: traceHref(r.id), | |
| 204 | }); | |
| 205 | } | |
| 206 | } | |
| 207 | // More to read: a row waited past the page, or the scan's cap came before the end of the runs. | |
| 208 | const next = more || (!exhausted && cursor !== undefined) ? cursor : undefined; | |
| 209 | return { rows, next, facets: facetsOf(app, actor) }; | |
| 210 | } | |
| 211 | ||
| 212 | /** The values a facet offers: what the viewer's own traces hold. */ | |
| 213 | function facetsOf(app: App, actor: User | undefined): TraceFacets { | |
| 214 | const db = app.db; | |
| 215 | const ids = db.query<{ id: string }, []>(`SELECT DISTINCT repo_id AS id FROM run WHERE kind = 'agent'`).all(); | |
| 216 | const repos: string[] = []; | |
| 217 | const readable: string[] = []; | |
| 218 | for (const { id } of ids) { | |
| 219 | const repo = getRepoById(db, id); | |
| 220 | if (repo !== undefined && canRead(db, repo, actor) && mayReadRunLog(app, actor, repo)) { | |
| 221 | repos.push(`${repo.ownerName}/${repo.name}`); | |
| 222 | readable.push(id); | |
| 223 | } | |
| 224 | } | |
| 225 | // Models and people come only from runs in those repositories: a name is never a hint at private | |
| 226 | // work. | |
| 227 | if (readable.length === 0) return { repos, models: [], people: [] }; | |
| 228 | const marks = readable.map((_, i) => `?${i + 1}`).join(","); | |
| 229 | const models = db | |
| 230 | .query<{ m: string }, string[]>(`SELECT DISTINCT model AS m FROM run WHERE kind = 'agent' AND model <> '' AND repo_id IN (${marks}) ORDER BY m`) | |
| 231 | .all(...readable) | |
| 232 | .map((r) => r.m); | |
| 233 | const people = db | |
| 234 | .query<{ n: string }, string[]>(`SELECT DISTINCT u.username AS n FROM run r JOIN user u ON u.id = r.actor_id WHERE r.kind = 'agent' AND r.repo_id IN (${marks}) ORDER BY n`) | |
| 235 | .all(...readable) | |
| 236 | .map((r) => r.n); | |
| 237 | return { repos: repos.sort(), models, people }; | |
| 238 | } | |
| 239 | ||
| 240 | /** A cost the way a list shows it: `$0.42`. */ | |
| 241 | export const costWords = (usd: number | undefined): string => (usd === undefined ? "" : `$${usd.toFixed(2)}`); | |
| 242 | ||
| 243 | /** One row as a terminal line: title, repository, model, cost, outcome. */ | |
| 244 | export function traceLine(r: TraceRow): string { | |
| 245 | return [r.title, r.repo, r.model === "" ? "" : r.model, costWords(r.costUsd), r.at.slice(0, 16).replace("T", " "), r.outcome].filter((x) => x !== "").join(" · "); | |
| 246 | } |
src/tui/screens/traces.ts added +114
| @@ -0,0 +1,114 @@ | ||
| 1 | /** | |
| 2 | * The Traces command (#17992): what `/traces` says, one line a crew run, newest first. `/` types a | |
| 3 | * search (the same text as the page's `q`), `r` `m` `o` `p` cycle the repository, model, outcome | |
| 4 | * and person facets through what the list offers (then back to any), `f` and `t` type the from and | |
| 5 | * to days (YYYY-MM-DD), `c` clears them, `j`/`k` move, Enter opens the run's trace, `n` reads the | |
| 6 | * next older page. Every value goes through the page's own `readFilter`. Read-only; Esc closes. The | |
| 7 | * lines are `traceLine`, the page's own row. | |
| 8 | */ | |
| 9 | import { binding } from "../app/keys.ts"; | |
| 10 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 11 | import { listTraces, OUTCOMES, readFilter, traceLine, type TraceFilter, type TraceList } from "../../trace/list.ts"; | |
| 12 | import { Scroll, openOnWeb } from "./common.ts"; | |
| 13 | import { style } from "../term/style.ts"; | |
| 14 | import { truncate } from "../term/width.ts"; | |
| 15 | import { emptyState } from "../ui/widgets.ts"; | |
| 16 | import type { Session } from "../session.ts"; | |
| 17 | import type { PaletteEntry } from "./entries.ts"; | |
| 18 | ||
| 19 | function tracesScreen(f: Session, ctx: Ctx): Screen { | |
| 20 | const scroll = new Scroll(); | |
| 21 | // What the page holds in its URL, as strings; `readFilter` is the one validator of them. | |
| 22 | const facet: { [K in "q" | "repo" | "model" | "outcome" | "by" | "from" | "to"]?: string } = {}; | |
| 23 | let before: string | undefined; | |
| 24 | const filter = (): TraceFilter => { | |
| 25 | const p = new URLSearchParams(); | |
| 26 | for (const [k, v] of Object.entries(facet)) if (v !== undefined) p.set(k, v); | |
| 27 | if (before !== undefined) p.set("before", before); | |
| 28 | return readFilter(p); | |
| 29 | }; | |
| 30 | let list: TraceList = listTraces(f.app, f.user, {}); | |
| 31 | let at = 0; | |
| 32 | let typing: "q" | "from" | "to" | undefined; | |
| 33 | const read = (): void => { | |
| 34 | list = listTraces(f.app, f.user, filter()); | |
| 35 | at = 0; | |
| 36 | ctx.invalidate(); | |
| 37 | }; | |
| 38 | const set = (k: keyof typeof facet, v: string | undefined): void => { | |
| 39 | if (v === undefined || v === "") delete facet[k]; | |
| 40 | else facet[k] = v; | |
| 41 | before = undefined; | |
| 42 | read(); | |
| 43 | }; | |
| 44 | const cycle = (k: "repo" | "model" | "outcome" | "by", values: readonly string[]): void => { | |
| 45 | const i = facet[k] === undefined ? -1 : values.indexOf(facet[k]!); | |
| 46 | set(k, i + 1 >= values.length ? undefined : values[i + 1]); | |
| 47 | }; | |
| 48 | const summary = (): string => { | |
| 49 | const on = Object.entries(facet).filter(([k]) => k !== "q" && facet[k as keyof typeof facet] !== undefined); | |
| 50 | return on.length === 0 ? "" : ` [${on.map(([k, v]) => `${k}=${v}`).join(" ")}]`; | |
| 51 | }; | |
| 52 | return { | |
| 53 | title: "Traces", | |
| 54 | keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["n"], "older"), binding(["/"], "search"), binding(["r", "m", "o", "p"], "repo, model, outcome, person"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")], | |
| 55 | render(area, s) { | |
| 56 | const c = ctx.theme.c; | |
| 57 | s.text(area.x, area.y, truncate(`${typing === undefined ? "/ to search" : typing === "q" ? "Search" : typing === "from" ? "From (YYYY-MM-DD)" : "To (YYYY-MM-DD)"}: ${typing === undefined || typing === "q" ? (facet.q ?? "") : (facet[typing] ?? "")}${typing === undefined ? "" : "_"}${summary()}`, area.w), style(c.fg, c.bg), area.x + area.w); | |
| 58 | if (list.rows.length === 0) { | |
| 59 | emptyState(s, { ...area, y: area.y + 2, h: Math.max(1, area.h - 2) }, c, { title: Object.keys(facet).length === 0 ? "No traces yet" : "No trace matches", body: "" }); | |
| 60 | return; | |
| 61 | } | |
| 62 | const h = area.h - 2; | |
| 63 | scroll.window(h, list.rows.length); | |
| 64 | for (let i = 0; i < h; i++) { | |
| 65 | const r = list.rows[scroll.top + i]; | |
| 66 | if (r === undefined) break; | |
| 67 | const on = scroll.top + i === at; | |
| 68 | s.text(area.x, area.y + 2 + i, truncate(`${on ? "> " : " "}${traceLine(r).replace(/[\u0000-\u001f\u007f]/g, " ")}`, area.w), style(on ? c.fg : c.muted, c.bg), area.x + area.w); | |
| 69 | } | |
| 70 | }, | |
| 71 | key(e) { | |
| 72 | const move = (to: number): void => { | |
| 73 | at = Math.max(0, Math.min(list.rows.length - 1, to)); | |
| 74 | if (at < scroll.top) scroll.top = at; | |
| 75 | else if (at >= scroll.top + scroll.height) scroll.top = at - scroll.height + 1; | |
| 76 | }; | |
| 77 | if (typing !== undefined) { | |
| 78 | const cur = facet[typing] ?? ""; | |
| 79 | if (e.key === "esc" || e.key === "enter") typing = undefined; | |
| 80 | else if (e.key === "backspace") set(typing, [...cur].slice(0, -1).join("")); | |
| 81 | else if (!e.ctrl && !e.alt && [...e.key].length === 1 && [...cur].length < 80) set(typing, cur + e.key); | |
| 82 | } else if (e.key === "esc") ctx.pop(); | |
| 83 | else if (e.key === "/") typing = "q"; | |
| 84 | else if (e.key === "f") typing = "from"; | |
| 85 | else if (e.key === "t") typing = "to"; | |
| 86 | else if (e.key === "r") cycle("repo", list.facets.repos); | |
| 87 | else if (e.key === "m") cycle("model", list.facets.models); | |
| 88 | else if (e.key === "o") cycle("outcome", OUTCOMES); | |
| 89 | else if (e.key === "p") cycle("by", list.facets.people); | |
| 90 | else if (e.key === "c") { | |
| 91 | for (const k of Object.keys(facet)) delete facet[k as keyof typeof facet]; | |
| 92 | before = undefined; | |
| 93 | read(); | |
| 94 | } else if (e.key === "j" || e.key === "down") move(at + 1); | |
| 95 | else if (e.key === "k" || e.key === "up") move(at - 1); | |
| 96 | else if (e.key === "enter") { | |
| 97 | const r = list.rows[at]; | |
| 98 | if (r !== undefined) openOnWeb(f, ctx, r.href, "the trace"); | |
| 99 | } else if (e.key === "n" && list.next !== undefined) ((before = list.next), read()); | |
| 100 | ctx.invalidate(); | |
| 101 | return true; | |
| 102 | }, | |
| 103 | }; | |
| 104 | } | |
| 105 | ||
| 106 | export const entry: PaletteEntry = { | |
| 107 | rank: 236, | |
| 108 | id: "traces", | |
| 109 | title: "Traces", | |
| 110 | hint: "every crew run, newest first", | |
| 111 | after: ["advisories"], | |
| 112 | offered: (session) => session.user !== undefined, | |
| 113 | run: (session, ctx) => ctx.push(tracesScreen(session, ctx)), | |
| 114 | }; |
src/web/pages/trace.ts +1 −1
| @@ -116,7 +116,7 @@ function body(view: TraceView): Html { | ||
| 116 | 116 | ${view.costUsd === undefined ? null : html`<div><dt>Spent</dt><dd>$${view.costUsd.toFixed(2)}</dd></div>`} |
| 117 | 117 | <div><dt>State</dt><dd>${view.run.state}</dd></div> |
| 118 | 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> | |
| 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>`)}<a href="/traces">All traces</a></nav> | |
| 120 | 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 | 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 | 122 | ${total === 0 ? html`<p class="muted" id="trace-empty">This run wrote no steps.</p>` : html`${strip(steps, timed)} |
src/web/pages/traces.ts added +92
| @@ -0,0 +1,92 @@ | ||
| 1 | /** | |
| 2 | * `/traces` (#17992): every crew run the viewer may open, one line each, newest first. The facets | |
| 3 | * (repository, model, outcome, person or agent, dates) and the text search live in the URL, so a | |
| 4 | * search is a link. The first paint is the whole answer: no script of its own, the shell's `j`/`k`, | |
| 5 | * Enter and `/` move over the rows (`data-nav`, `data-search-input`). The terminal reads the same | |
| 6 | * list (`src/tui/screens/traces.ts`). | |
| 7 | */ | |
| 8 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { costWords, filterQuery, listTraces, OUTCOMES, readFilter, type TraceFilter, type TraceList, type TraceRow } from "../../trace/list.ts"; | |
| 11 | import { pageHead } from "../chrome.ts"; | |
| 12 | import { html, type Html } from "../html.ts"; | |
| 13 | import { page } from "../layout.ts"; | |
| 14 | import { badge, btn, disclosure, empty, listCard, row, time } from "../ui.ts"; | |
| 15 | ||
| 16 | const FILTERS: readonly [keyof TraceFilter, string][] = [ | |
| 17 | ["q", "Search"], | |
| 18 | ["repo", "Repository"], | |
| 19 | ["model", "Model"], | |
| 20 | ["outcome", "Outcome"], | |
| 21 | ["by", "Person or agent"], | |
| 22 | ["from", "From"], | |
| 23 | ["to", "To"], | |
| 24 | ]; | |
| 25 | ||
| 26 | const select = (name: string, label: string, values: readonly string[], now: string | undefined): Html => | |
| 27 | html`<label class="field"><span class="small muted">${label}</span> | |
| 28 | <select class="input" name="${name}"><option value="">Any</option>${values.map((v) => html`<option value="${v}"${v === now ? html` selected` : null}>${v}</option>`)}</select></label>`; | |
| 29 | ||
| 30 | const date = (name: string, label: string, now: string | undefined): Html => | |
| 31 | html`<label class="field"><span class="small muted">${label}</span><input class="input" type="date" name="${name}" value="${now ?? ""}" /></label>`; | |
| 32 | ||
| 33 | const line = (r: TraceRow): Html => | |
| 34 | row({ | |
| 35 | href: r.href, | |
| 36 | nav: true, | |
| 37 | title: r.title, | |
| 38 | titleAttr: r.title, | |
| 39 | meta: html`${r.kind} · ${r.repo}${r.model === "" ? "" : ` · ${r.model}`}${r.costUsd === undefined ? "" : ` · ${costWords(r.costUsd)}`} · ${time(r.at)}${r.by === "" ? "" : ` · ${r.by}`}`, | |
| 40 | trail: badge(r.outcome, { tone: r.outcome === "failed" ? "danger" : r.outcome === "ok" ? "success" : "default" }), | |
| 41 | data: { trace: r.id }, | |
| 42 | }); | |
| 43 | ||
| 44 | function controls(f: TraceFilter, list: TraceList): Html { | |
| 45 | const active = FILTERS.filter(([k]) => k !== "q" && f[k] !== undefined); | |
| 46 | return html`<form method="get" action="/traces" class="traces-search" role="search"> | |
| 47 | <input class="input" name="q" value="${f.q ?? ""}" placeholder="Search titles and summaries ( / )" aria-label="Search traces" data-search-input /> | |
| 48 | ${btn("Search", { size: "sm" })} | |
| 49 | ${disclosure( | |
| 50 | "Filters", | |
| 51 | html`<div class="traces-facets"> | |
| 52 | ${select("repo", "Repository", list.facets.repos, f.repo)}${select("model", "Model", list.facets.models, f.model)} | |
| 53 | ${select("outcome", "Outcome", OUTCOMES, f.outcome)}${select("by", "Person or agent", list.facets.people, f.by)} | |
| 54 | ${date("from", "From", f.from)}${date("to", "To", f.to)} | |
| 55 | </div>`, | |
| 56 | { small: true, extra: "mt", open: active.length > 0 }, | |
| 57 | )} | |
| 58 | </form> | |
| 59 | ${active.length === 0 | |
| 60 | ? null | |
| 61 | : html`<p class="small" id="traces-active">${active.map(([k, label]) => html`<a href="/traces${filterQuery(f, { [k]: undefined, before: undefined })}" aria-label="Remove ${label}: ${f[k] ?? ""}">${badge(`${label}: ${f[k] ?? ""}`, { variant: "secondary", icon: "x" })}</a> `)}</p>`}`; | |
| 62 | } | |
| 63 | ||
| 64 | const CSS = ` | |
| 65 | .traces-search{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-bottom:.5rem} | |
| 66 | .traces-search>.input{flex:1 1 14rem;min-width:0} | |
| 67 | .traces-search .disclosure{flex:1 0 100%} | |
| 68 | .traces-facets{display:grid;grid-template-columns:repeat(auto-fit,minmax(10rem,1fr));gap:.5rem;margin-top:.5rem} | |
| 69 | .traces-facets .field{display:flex;flex-direction:column;gap:.15rem} | |
| 70 | #traces-list .row-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 71 | #traces-list .row-meta{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 72 | `; | |
| 73 | ||
| 74 | // GET /traces | |
| 75 | export function tracesPage(ctx: Ctx): Response { | |
| 76 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 77 | const f = readFilter(ctx.url.searchParams); | |
| 78 | const reading = performance.now(); | |
| 79 | const list = listTraces(ctx.app, ctx.auth.user, f); | |
| 80 | notePhase(ctx.request, "read", performance.now() - reading); | |
| 81 | const searching = Object.keys(f).some((k) => k !== "before"); | |
| 82 | const body = html`${pageHead("Traces", { sub: "Every crew run you may open, newest first." })} | |
| 83 | ${controls(f, list)} | |
| 84 | ${list.rows.length === 0 | |
| 85 | ? empty({ icon: "activity", title: searching ? "No trace matches" : "No traces yet", note: searching ? "Take a filter off, or search for fewer words." : "A crew run's steps appear here once it has run." }) | |
| 86 | : html`<div id="traces-list">${listCard(list.rows.map(line))}</div>`} | |
| 87 | ${list.next === undefined ? null : html`<p><a class="btn" id="traces-more" href="/traces${filterQuery(f, { before: list.next })}" rel="next">Older traces</a></p>`}`; | |
| 88 | const rendering = performance.now(); | |
| 89 | const response = page({ ctx, title: "Traces", body, styleCss: CSS }); | |
| 90 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 91 | return response; | |
| 92 | } |
test/forge-looks.test.ts +1
| @@ -34,6 +34,7 @@ const NOT_A_PAGE: Record<string, string> = { | ||
| 34 | 34 | "/tabforge": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/tabforge-page.test.ts", |
| 35 | 35 | "/archive": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/archive-page.test.ts, with a 390 px measure, and test/apps-archived.test.ts", |
| 36 | 36 | "/templates": "no picture: not in app.looks; the page is covered by test/templates-page.test.ts", |
| 37 | "/traces": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/traces-list.test.ts", | |
| 37 | 38 | "/templates.json": "data, not a page: the same rows as /templates; covered by test/templates-json.test.ts", |
| 38 | 39 | "/terms": "no picture: not in app.looks; the page is covered by test/terms-page.test.ts", |
| 39 | 40 | "/audit": "no picture: its slot went to /pinned; /audit.csv is its download, covered by test/audit.test.ts", |
test/keymap-terminal.test.ts +1
| @@ -56,6 +56,7 @@ const OWN_R: Record<string, string> = { | ||
| 56 | 56 | "src/tui/screens/series.ts": "range", |
| 57 | 57 | "src/tui/screens/stalled.ts": "unblock", |
| 58 | 58 | "src/tui/screens/talk_chats.ts": "rename", |
| 59 | "src/tui/screens/traces.ts": "cycle the repository filter", | |
| 59 | 60 | "src/tui/screens/variants.ts": "run a branch", |
| 60 | 61 | }; |
| 61 | 62 |
test/palette-roster.test.ts +3
| @@ -169,6 +169,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 169 | 169 | ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"], |
| 170 | 170 | ["maintenance-duties", "Pause, resume or dismiss a maintenance duty", "switch a duty off, or on again after it paused itself"], |
| 171 | 171 | ["maintenance-budgets", "Set a maintenance duty's budget", "runs per day and dollars per day a duty may use"], |
| 172 | ["traces", "Traces", "every crew run, newest first"], | |
| 172 | 173 | ["crawlers", "Crawlers", "their share of answering time, and who was refused"], |
| 173 | 174 | ["scrapes", "Scrapes", "what was read by repository, and groups in a running capture"], |
| 174 | 175 | ["traffic", "Traffic", "who is using the forge's answering time, and the top readers"], |
| @@ -359,6 +360,7 @@ test("a site-admin agent is offered the roster without the person-only entries", | ||
| 359 | 360 | ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"], |
| 360 | 361 | ["design", "Design: the forge's theme", "colours and scales, the AA verdict; publish or revert"], |
| 361 | 362 | ["ship-time", "Ship time", "median time from the crew's first run to done"], |
| 363 | ["traces", "Traces", "every crew run, newest first"], | |
| 362 | 364 | ["buckets", "Buckets", "an object bucket's price a month, and binding it to an app"], |
| 363 | 365 | ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"], |
| 364 | 366 | ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"], |
| @@ -491,6 +493,7 @@ test("a member person is offered the signed-in roster without the admin entries" | ||
| 491 | 493 | ["next-all", "Next up, every repository", "the top of each list you administer"], |
| 492 | 494 | ["offers-upstream", "Offers upstream", "the receipts of what you offered from your forks"], |
| 493 | 495 | ["tell-undo", "Take a tell back", "a tell you sent in the last minute, while nobody has read it"], |
| 496 | ["traces", "Traces", "every crew run, newest first"], | |
| 494 | 497 | ["buckets", "Buckets", "an object bucket's price a month, and binding it to an app"], |
| 495 | 498 | ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"], |
| 496 | 499 | ["registry-items", "Component registry", "the forge's parts; install one into an app"], |
test/traces-leak.test.ts added +110
| @@ -0,0 +1,110 @@ | ||
| 1 | /** | |
| 2 | * `/traces` (#17992): what a facet offers and what a row costs are gated as the rows are; the | |
| 3 | * terminal's facet keys. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createRepo } from "../src/actions/repos.ts"; | |
| 10 | import { createApp, type App as Forge } from "../src/app.ts"; | |
| 11 | import { createUser, type User } from "../src/core/users.ts"; | |
| 12 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 13 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 14 | import { PAGE, listTraces } from "../src/trace/list.ts"; | |
| 15 | import { entry } from "../src/tui/screens/traces.ts"; | |
| 16 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | import { settleApp } from "./helpers/tui.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | let dir: string; | |
| 23 | let forge: Forge; | |
| 24 | let alice: User; | |
| 25 | let bob: User; | |
| 26 | let mallory: User; | |
| 27 | ||
| 28 | const put = (id: string, repoId: string, model: string, actor: User, state = "ok", cost = 0.5, at = "2026-11-10T10:00:00.000Z") => | |
| 29 | forge.db | |
| 30 | .query("INSERT INTO run (id, repo_id, kind, state, summary, model, actor_id, cost_usd, created_at) VALUES (?1, ?2, 'agent', ?3, ?4, ?5, ?6, ?7, ?8)") | |
| 31 | .run(id, repoId, state, `work ${id}`, model, actor.id, cost, at); | |
| 32 | ||
| 33 | beforeAll(async () => { | |
| 34 | dir = await mkdtemp(join(tmpdir(), "forge-traces-gate-")); | |
| 35 | forge = createApp({ dataDir: dir, port: 0 }); | |
| 36 | const a = await seedAdmin(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" }); | |
| 37 | if (!a.ok) throw new Error("signup failed"); | |
| 38 | alice = a.value; | |
| 39 | const mk = async (username: string) => { | |
| 40 | const u = await createUser(forge.db, { origin: "seed", trusted: true, username, email: `${username}@forge.test`, password: "a-long-passphrase" }); | |
| 41 | if (!u.ok) throw new Error(username); | |
| 42 | return u.value; | |
| 43 | }; | |
| 44 | bob = await mk("bob"); | |
| 45 | mallory = await mk("mallory"); | |
| 46 | const open = await createRepo(forge, alice, { name: "lamp", visibility: "public" }); | |
| 47 | const priv = await createRepo(forge, alice, { name: "vault", visibility: "private" }); | |
| 48 | if (!open.ok || !priv.ok) throw new Error("repo failed"); | |
| 49 | put("r0001", open.value.id, "model-open", alice, "ok", 0.5, "2026-11-10T10:00:00.000Z"); | |
| 50 | put("r0002", open.value.id, "model-two", alice, "failed", 0.25, "2026-11-12T10:00:00.000Z"); | |
| 51 | put("r0003", priv.value.id, "model-secret", mallory, "ok", 0.5, "2026-11-11T10:00:00.000Z"); | |
| 52 | }); | |
| 53 | afterAll(async () => { | |
| 54 | forge.close?.(); | |
| 55 | await rm(dir, { recursive: true, force: true }); | |
| 56 | }); | |
| 57 | ||
| 58 | test("a private repository's model and person are in no facet a stranger is offered", () => { | |
| 59 | for (const viewer of [undefined, bob]) { | |
| 60 | const { facets } = listTraces(forge, viewer, {}); | |
| 61 | expect(facets.models).not.toContain("model-secret"); | |
| 62 | expect(facets.people).not.toContain("mallory"); | |
| 63 | expect(facets.repos).not.toContain("alice/vault"); | |
| 64 | expect(listTraces(forge, viewer, { by: "mallory" }).rows).toHaveLength(0); | |
| 65 | } | |
| 66 | const mine = listTraces(forge, alice, {}).facets; | |
| 67 | expect(mine.models).toContain("model-secret"); | |
| 68 | expect(mine.people).toContain("mallory"); | |
| 69 | }); | |
| 70 | ||
| 71 | test("the spend is only for those who may see the owner's spend", () => { | |
| 72 | const seen = listTraces(forge, alice, {}).rows.find((r) => r.id === "r0001"); | |
| 73 | expect(seen?.costUsd).toBe(0.5); | |
| 74 | // A crew agent may read the run's log but not write the repository: it sees the row, not the | |
| 75 | // spend. | |
| 76 | const crew = { ...bob, kind: "agent" as const }; | |
| 77 | forge.db.query("UPDATE user SET is_agent = 1 WHERE id = ?1").run(bob.id); | |
| 78 | forge.db.query("INSERT INTO repo_crew (repo_id, user_id) SELECT repo_id, ?1 FROM run WHERE id = 'r0001'").run(bob.id); | |
| 79 | const other = listTraces(forge, crew, {}).rows.find((r) => r.id === "r0001"); | |
| 80 | expect(other).toBeDefined(); | |
| 81 | expect(other?.costUsd).toBeUndefined(); | |
| 82 | }); | |
| 83 | ||
| 84 | test("the terminal's keys cycle the facets, type the days and clear them", async () => { | |
| 85 | const { app, session } = createForgeApp(forge, { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice }, { terminal: headlessTerminal(110, 20), exitHooks: false }); | |
| 86 | app.start(); | |
| 87 | await settleApp(app); | |
| 88 | entry.run(session, app.ctx); | |
| 89 | await settleApp(app); | |
| 90 | const press = async (...keys: string[]) => { | |
| 91 | for (const key of keys) app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 92 | await settleApp(app); | |
| 93 | }; | |
| 94 | expect(app.screen.toText()).toContain("work r0001"); | |
| 95 | await press("o"); // the first outcome: ok | |
| 96 | expect(app.screen.toText()).toContain("outcome=ok"); | |
| 97 | expect(app.screen.toText()).not.toContain("work r0002"); | |
| 98 | await press("c", "m"); | |
| 99 | expect(app.screen.toText()).toContain("model=model-open"); | |
| 100 | expect(app.screen.toText()).not.toContain("work r0002"); | |
| 101 | await press("c", "f", ..."2026-11-12".split(""), "enter"); | |
| 102 | expect(app.screen.toText()).toContain("from=2026-11-12"); | |
| 103 | expect(app.screen.toText()).toContain("work r0002"); | |
| 104 | expect(app.screen.toText()).not.toContain("work r0001"); | |
| 105 | await press("c", "p"); | |
| 106 | expect(app.screen.toText()).toContain("by=alice"); | |
| 107 | await press("c"); | |
| 108 | expect(app.screen.toText()).toContain("work r0001"); | |
| 109 | expect(PAGE).toBeGreaterThan(2); | |
| 110 | }); |
test/traces-list.test.ts added +170
| @@ -0,0 +1,170 @@ | ||
| 1 | /** | |
| 2 | * `/traces` (#17992): the list of crew runs, its facets and search in the URL, the gate, the | |
| 3 | * terminal's lines, the budget. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createRepo } from "../src/actions/repos.ts"; | |
| 10 | import type { User } from "../src/core/users.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 13 | import { filterQuery, listTraces, readFilter, traceLine, PAGE } from "../src/trace/list.ts"; | |
| 14 | import { components } from "../src/web/style/components.ts"; | |
| 15 | import { expectWork, requestStatements } from "./helpers/work.ts"; | |
| 16 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | let root = ""; | |
| 22 | let app: App; | |
| 23 | let servers: Servers; | |
| 24 | let bearer = ""; | |
| 25 | let secretRepo = ""; | |
| 26 | let alice: User; | |
| 27 | const MODELS = ["claude-opus", "claude-sonnet", "claude-haiku"]; | |
| 28 | ||
| 29 | const get = (path: string, auth = true) => fetch(`${servers.url}${path}`, { headers: auth ? { authorization: `Bearer ${bearer}` } : {} }); | |
| 30 | ||
| 31 | beforeAll(async () => { | |
| 32 | root = mkdtempSync(join(tmpdir(), "forge-traces-list-")); | |
| 33 | app = createApp({ dataDir: root, 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 repos: string[] = []; | |
| 39 | for (const [name, visibility] of [["notes", "public"], ["tasks", "public"], ["vault", "private"]] as const) { | |
| 40 | const made = await createRepo(app, admin.value, { name, visibility, description: "" }); | |
| 41 | if (!made.ok) throw new Error(String(made.error)); | |
| 42 | repos.push(made.value.id); | |
| 43 | if (name === "vault") secretRepo = made.value.id; | |
| 44 | } | |
| 45 | const insert = app.db.prepare( | |
| 46 | "INSERT INTO run (id, repo_id, kind, state, summary, model, actor_id, cost_usd, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | |
| 47 | ); | |
| 48 | app.db.transaction(() => { | |
| 49 | for (let i = 0; i < 10_000; i++) { | |
| 50 | const day = String(1 + (i % 28)).padStart(2, "0"); | |
| 51 | insert.run( | |
| 52 | `r${String(i).padStart(8, "0")}`, | |
| 53 | repos[i % 3]!, | |
| 54 | i % 10 === 0 ? "deploy" : "agent", | |
| 55 | i % 7 === 0 ? "failed" : "ok", | |
| 56 | i === 9_996 ? "Fix the <b>footer</b> 100%" : `Run number ${i}`, | |
| 57 | MODELS[i % 3]!, | |
| 58 | admin.value.id, | |
| 59 | 0.25, | |
| 60 | `2026-11-${day}T10:00:00.000Z`, | |
| 61 | ); | |
| 62 | } | |
| 63 | })(); | |
| 64 | const res = await fetch(`${servers.url}/api/v1/tokens`, { | |
| 65 | method: "POST", | |
| 66 | headers: { "content-type": "application/json" }, | |
| 67 | body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }), | |
| 68 | }); | |
| 69 | bearer = ((await res.json()) as { token: string }).token; | |
| 70 | }); | |
| 71 | ||
| 72 | afterAll(() => { | |
| 73 | servers.stop(); | |
| 74 | app.close(); | |
| 75 | rmSync(root, { recursive: true, force: true }); | |
| 76 | }); | |
| 77 | ||
| 78 | describe("the list", () => { | |
| 79 | test("is newest first, one page, only crew runs, with a link to the next", async () => { | |
| 80 | const html = await (await get("/traces")).text(); | |
| 81 | expect(html).toContain('id="traces-more"'); | |
| 82 | expect([...html.matchAll(/data-trace="/g)]).toHaveLength(PAGE); | |
| 83 | const ids = [...html.matchAll(/data-trace="(r\d+)"/g)].map((m) => m[1]!); | |
| 84 | expect(ids[0]).toBe("r00009999"); | |
| 85 | expect(ids).toEqual([...ids].sort().reverse()); | |
| 86 | expect(html).not.toContain("r00009990"); // a deploy: not a trace | |
| 87 | }); | |
| 88 | ||
| 89 | test("filters by repository and model, and the facets are in the URL", async () => { | |
| 90 | const page = await (await get("/traces?repo=alice/notes&model=claude-opus")).text(); | |
| 91 | const rows = [...page.matchAll(/data-trace="(r\d+)"/g)].map((m) => Number(m[1]!.slice(1))); | |
| 92 | expect(rows.length).toBe(PAGE); | |
| 93 | for (const n of rows) { | |
| 94 | expect(n % 3).toBe(0); // notes and opus are both i % 3 === 0 | |
| 95 | expect(n % 10).not.toBe(0); | |
| 96 | } | |
| 97 | expect(page).toContain("Repository: alice/notes"); | |
| 98 | expect(page).toContain('href="/traces?model=claude-opus"'); // taking the repository off keeps the model | |
| 99 | }); | |
| 100 | ||
| 101 | test("filters by outcome, by date and by who ran it", () => { | |
| 102 | const failed = listTraces(app, alice, readFilter(new URLSearchParams("outcome=failed"))); | |
| 103 | expect(failed.rows.every((r) => r.outcome === "failed")).toBe(true); | |
| 104 | const day = listTraces(app, alice, readFilter(new URLSearchParams("from=2026-11-05&to=2026-11-05"))); | |
| 105 | expect(day.rows.length).toBeGreaterThan(0); | |
| 106 | expect(day.rows.every((r) => r.at.startsWith("2026-11-05"))).toBe(true); | |
| 107 | expect(listTraces(app, alice, readFilter(new URLSearchParams("by=nobody"))).rows).toHaveLength(0); | |
| 108 | expect(listTraces(app, alice, readFilter(new URLSearchParams("by=alice"))).rows).toHaveLength(PAGE); | |
| 109 | }); | |
| 110 | ||
| 111 | test("searches titles and summaries, a % or _ matching itself", () => { | |
| 112 | expect(listTraces(app, alice, readFilter(new URLSearchParams("q=footer"))).rows.map((r) => r.id)).toEqual(["r00009996"]); | |
| 113 | expect(listTraces(app, alice, readFilter(new URLSearchParams("q=100%25"))).rows).toHaveLength(1); | |
| 114 | expect(listTraces(app, alice, readFilter(new URLSearchParams("q=Run_number"))).rows).toHaveLength(0); | |
| 115 | }); | |
| 116 | ||
| 117 | test("escapes what a title says", async () => { | |
| 118 | const html = await (await get("/traces?q=footer")).text(); | |
| 119 | expect(html).toContain("Fix the <b>footer</b>"); | |
| 120 | expect(html).not.toContain("<b>footer</b>"); | |
| 121 | }); | |
| 122 | ||
| 123 | test("pages by cursor with no repeat", () => { | |
| 124 | const one = listTraces(app, alice, {}); | |
| 125 | const two = listTraces(app, alice, { before: one.next! }); | |
| 126 | expect(two.rows[0]!.id < one.rows[PAGE - 1]!.id).toBe(true); | |
| 127 | expect(new Set([...one.rows, ...two.rows].map((r) => r.id)).size).toBe(PAGE * 2); | |
| 128 | }); | |
| 129 | ||
| 130 | test("a private repository is no row, no facet and no hint to a stranger", async () => { | |
| 131 | app.db.query("UPDATE run SET summary = 'SECRET-WORK' WHERE repo_id = ?1").run(secretRepo); | |
| 132 | const anon = await (await get("/traces?q=SECRET-WORK", false)).text(); | |
| 133 | expect(anon).toContain("No trace matches"); | |
| 134 | expect(anon).not.toContain("alice/vault"); | |
| 135 | expect(listTraces(app, undefined, readFilter(new URLSearchParams("repo=alice/vault"))).rows).toHaveLength(0); | |
| 136 | expect(listTraces(app, undefined, {}).rows).toHaveLength(0); // a run's log is the crew's and the owner's, as on its run page | |
| 137 | expect((await (await get("/traces?q=SECRET-WORK")).text())).toContain("alice/vault"); | |
| 138 | }); | |
| 139 | ||
| 140 | test("malformed input is dropped, not an error", async () => { | |
| 141 | const f = readFilter(new URLSearchParams("repo=../etc&outcome=bad&from=yesterday&by=a b&before=x y")); | |
| 142 | expect(f).toEqual({}); | |
| 143 | expect((await get("/traces?repo=%27%3B--&before=%20x")).status).toBe(200); | |
| 144 | expect(filterQuery({ repo: "a/b", q: "x y" })).toBe("?q=x+y&repo=a%2Fb"); | |
| 145 | }); | |
| 146 | ||
| 147 | test("carries the security floor and fits a phone: no fixed width, rows ellipsise", async () => { | |
| 148 | const res = await get("/traces"); | |
| 149 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 150 | expect(res.headers.get("content-security-policy")).toBeTruthy(); | |
| 151 | const html = await res.text(); | |
| 152 | for (const m of html.matchAll(/\swidth=["']?(\d+)/gi)) expect(Number(m[1])).toBeLessThanOrEqual(390); | |
| 153 | expect(html).toContain("data-search-input"); // `/` focuses it | |
| 154 | expect(html).toContain("data-nav"); // j/k and Enter walk the rows | |
| 155 | expect(components).toContain("row-title"); | |
| 156 | }); | |
| 157 | ||
| 158 | test("the terminal's line says what the row says", () => { | |
| 159 | const r = listTraces(app, alice, readFilter(new URLSearchParams("q=footer"))).rows[0]!; | |
| 160 | expect(traceLine(r)).toContain("Fix the <b>footer</b> 100% · alice/"); | |
| 161 | expect(traceLine(r)).toContain("claude-"); | |
| 162 | }); | |
| 163 | ||
| 164 | test("costs a counted handful of statements with 10,000 traces, not a read of them all", async () => { | |
| 165 | await get("/traces"); | |
| 166 | const mine = await requestStatements(app.db, `${servers.url}/traces?model=claude-sonnet&repo=alice/tasks`, { headers: { authorization: `Bearer ${bearer}` } }); | |
| 167 | expectWork(mine, { max: 60 }); | |
| 168 | expect(listTraces(app, alice, {}).rows).toHaveLength(PAGE); | |
| 169 | }); | |
| 170 | }); |
new above
offline
The ternary returns the same value on both branches. Use
add(f.outcome).