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

/traces lists Talk and imported traces with a kind facet, and the terminal's kind key is tested #18365

opened this

Merged 5h 8m ago, live in production

scout/forge:scout/18364-traces-lists-talk-and-imported-traces-wi → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/18364-traces-lists-talk-and-imported-traces-wi was merged into main as c5e780a.

Review

Sign in to review this change.
6 files changed +378 −34
docs/features/traces.md +1 −1
@@ -20,7 +20,7 @@ Each line a run appends is stamped in `<run id>.times` beside its log (`appendRu
2020
2121 `/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, `v` marks a row (two at most) and `d` opens the two as the comparison below, #18085; two runs of different issues are told so). Reader: `src/trace/list.ts`, over a partial index of crew runs (`run_agent`).
2222
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.
23 Talk turns and imported sessions are rows too (#18356): the viewer's own, read from the trace index behind the API's gate (`listSeenTraces`: a Talk turn to its person, an imported session to its owner, no one else), merged by time with the crew runs. The `kind` facet (`run`, `talk`, `imported`; the Kind select under Filters, `i` in the terminal) narrows to one; a malformed one is dropped. A Talk row opens `/traces/<id>`; an imported row is plain text until its page lands. The repository facet leaves out Talk and imported rows (they have no repository). Older pages carry both places in one opaque `before`; one this list did not write starts the list over. Not yet: archived turns in the search, and a JSON twin of the list.
2424
2525 ## Compare two runs, and share one (#17995)
2626
src/trace/list.ts +130 −13
@@ -9,16 +9,22 @@ import { mayReadRunLog } from "../actions/runs.ts";
99 import type { App } from "../app.ts";
1010 import { canRead, canSeeOwnerFacts, getRepo, getRepoById, type Repo } from "../core/repos.ts";
1111 import type { User } from "../core/users.ts";
12 import { cursorOf, TRACE_CURSOR, type TraceQuery } from "./index_table.ts";
1213 import { traceHref } from "./read.ts";
14 import { LIST_OUTCOMES, listSeenTraces } from "./tree.ts";
1315
1416 export const OUTCOMES = ["ok", "failed", "cancelled", "running", "queued"] as const;
1517 export type TraceOutcome = (typeof OUTCOMES)[number];
18 /** The kinds of trace the list tells apart: a crew run, a Talk turn, an imported session. */
19 export const SOURCES = ["run", "talk", "imported"] as const;
20 export type TraceSource = (typeof SOURCES)[number];
1621
1722 /** The query of the list, as the URL holds it. Every field is validated by `readFilter`. */
1823 export interface TraceFilter {
1924 readonly repo?: string;
2025 readonly model?: string;
2126 readonly outcome?: TraceOutcome;
27 readonly kind?: TraceSource;
2228 readonly from?: string;
2329 readonly to?: string;
2430 readonly by?: string;
@@ -29,15 +35,18 @@ export interface TraceFilter {
2935 export interface TraceRow {
3036 readonly id: string;
3137 readonly title: string;
32 readonly kind: "crew run";
38 /** What the row is, in words. */
39 readonly kind: "crew run" | "Talk" | "imported";
40 readonly source: TraceSource;
3341 readonly repo: string;
3442 readonly model: string;
3543 /** Only for those who may see the owner's spend. */
3644 readonly costUsd: number | undefined;
3745 readonly at: string;
38 readonly outcome: TraceOutcome;
46 readonly outcome: string;
3947 readonly by: string;
40 readonly href: string;
48 /** Where the trace opens; none for an imported session until its page lands. */
49 readonly href: string | undefined;
4150 }
4251
4352 export interface TraceFacets {
@@ -76,16 +85,18 @@ export function readFilter(params: URLSearchParams): TraceFilter {
7685 const to = one("to", 10);
7786 const by = one("by", 64);
7887 const model = one("model", 80);
79 const before = one("before", 64);
88 const before = one("before", 256);
89 const kind = one("kind", 10);
8090 const q = one("q", 80);
8191 const out: { -readonly [K in keyof TraceFilter]: TraceFilter[K] } = {};
8292 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;
8393 if (outcome !== undefined && (OUTCOMES as readonly string[]).includes(outcome)) out.outcome = outcome as TraceOutcome;
94 if (kind !== undefined && (SOURCES as readonly string[]).includes(kind)) out.kind = kind as TraceSource;
8495 if (from !== undefined && DAY.test(from)) out.from = from;
8596 if (to !== undefined && DAY.test(to)) out.to = to;
8697 if (by !== undefined && NAME.test(by)) out.by = by;
8798 if (model !== undefined) out.model = model;
88 if (before !== undefined && /^[0-9A-Za-z_-]{1,64}$/.test(before)) out.before = before;
99 if (before !== undefined && /^(?:[0-9A-Za-z_-]{1,64}|m\.[0-9A-Za-z_-]{1,200})$/.test(before)) out.before = before;
89100 if (q !== undefined) out.q = q;
90101 return out;
91102 }
@@ -94,7 +105,7 @@ export function readFilter(params: URLSearchParams): TraceFilter {
94105 export function filterQuery(f: TraceFilter, over: Partial<Record<keyof TraceFilter, string | undefined>> = {}): string {
95106 const merged: Record<string, string | undefined> = { ...f, ...over };
96107 const p = new URLSearchParams();
97 for (const k of ["q", "repo", "model", "outcome", "by", "from", "to", "before"]) {
108 for (const k of ["q", "kind", "repo", "model", "outcome", "by", "from", "to", "before"]) {
98109 const v = merged[k];
99110 if (v !== undefined && v !== "") p.set(k, v);
100111 }
@@ -141,15 +152,21 @@ function nextDay(day: string): string {
141152
142153 const FROM = `run r LEFT JOIN issue i ON i.id = r.issue_id LEFT JOIN user u ON u.id = r.actor_id`;
143154
144 /** One page of traces `actor` may open, newest first. */
145 export function listTraces(app: App, actor: User | undefined, f: TraceFilter): TraceList {
155 /** One stream of the list: its rows, and where to resume when more wait behind them. */
156 interface Stream<T> {
157 readonly rows: T[];
158 readonly next: string | undefined;
159 }
160
161 /** The crew runs `actor` may open, newest run id first, from `cursor`. */
162 function crewRuns(app: App, actor: User | undefined, f: TraceFilter, cursor0: string | undefined): Stream<TraceRow> {
146163 const db = app.db;
147164 let repoId: string | undefined;
148165 if (f.repo !== undefined) {
149166 const [owner, name] = f.repo.split("/") as [string, string];
150167 const found = getRepo(db, owner, name);
151168 // 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) };
169 if (found === undefined || !canRead(db, found, actor)) return { rows: [], next: undefined };
153170 repoId = found.id;
154171 }
155172 const { sql, params } = where(f, repoId, f.by);
@@ -163,7 +180,7 @@ export function listTraces(app: App, actor: User | undefined, f: TraceFilter): T
163180 return repos.get(id);
164181 };
165182 const rows: TraceRow[] = [];
166 let cursor = f.before;
183 let cursor = cursor0;
167184 let scanned = 0;
168185 let exhausted = false;
169186 let more = false;
@@ -194,11 +211,12 @@ export function listTraces(app: App, actor: User | undefined, f: TraceFilter): T
194211 id: r.id,
195212 title: r.title,
196213 kind: "crew run",
214 source: "run",
197215 repo: `${s.repo.ownerName}/${s.repo.name}`,
198216 model: r.model,
199217 costUsd: s.spend && r.cost_usd > 0 ? r.cost_usd : undefined,
200218 at: r.created_at,
201 outcome: r.state as TraceOutcome,
219 outcome: r.state,
202220 by: r.by ?? "",
203221 href: traceHref(r.id),
204222 });
@@ -206,7 +224,106 @@ export function listTraces(app: App, actor: User | undefined, f: TraceFilter): T
206224 }
207225 // More to read: a row waited past the page, or the scan's cap came before the end of the runs.
208226 const next = more || (!exhausted && cursor !== undefined) ? cursor : undefined;
209 return { rows, next, facets: facetsOf(app, actor) };
227 return { rows, next };
228 }
229
230 const NOT_MORE = "!";
231 const RUN_ID = /^[0-9A-Za-z_-]{1,64}$/;
232 const kinds = { talk: "Talk", imported: "imported" } as const;
233
234 /**
235 * What the index holds for `actor` under this filter: Talk turns and imported sessions, gated as
236 * the API gates them.
237 */
238 function personal(app: App, actor: User | undefined, f: TraceFilter, cursor: string | undefined): Stream<TraceRow> {
239 const none = { rows: [], next: undefined };
240 if (actor === undefined || f.kind === "run" || f.repo !== undefined) return none;
241 if (f.by !== undefined && f.by !== actor.username) return none;
242 if (f.outcome !== undefined && !(LIST_OUTCOMES as readonly string[]).includes(f.outcome)) return none;
243 const query: TraceQuery = {};
244 if (f.kind !== undefined) query.kind = f.kind;
245 if (f.model !== undefined) query.model = f.model;
246 if (f.outcome !== undefined) query.outcome = f.outcome;
247 if (f.from !== undefined) query.since = `${f.from}T00:00:00.000Z`;
248 if (f.to !== undefined) query.until = `${nextDay(f.to)}T00:00:00.000Z`;
249 const q = f.q?.toLowerCase();
250 const rows: TraceRow[] = [];
251 let from = cursor;
252 let next: string | undefined;
253 // The gate is the API's (`listSeenTraces`); a row of a crew run is the other stream's.
254 for (let i = 0; i < 5 && rows.length <= PAGE; i += 1) {
255 const got = listSeenTraces(app, actor, { query, cursor: from, limit: PAGE + 1 });
256 for (const t of got.items) {
257 if ((t.kind !== "talk" && t.kind !== "imported") || (q !== undefined && !t.title.toLowerCase().includes(q))) continue;
258 rows.push({
259 id: t.id,
260 title: t.title === "" ? kinds[t.kind] : t.title,
261 kind: kinds[t.kind],
262 source: t.kind,
263 repo: "",
264 model: t.model,
265 costUsd: t.costUsd > 0 ? t.costUsd : undefined,
266 at: t.started,
267 outcome: t.outcome,
268 by: actor.username,
269 href: t.kind === "talk" ? traceHref(t.id) : undefined,
270 });
271 }
272 from = got.next_cursor ?? undefined;
273 next = from;
274 if (from === undefined) break;
275 }
276 return { rows, next };
277 }
278
279 /** Where each stream resumes: a plain run id (runs alone), or both in one opaque cursor. */
280 function readCursor(before: string | undefined): { runs: string | undefined; mine: string | undefined } {
281 if (before === undefined) return { runs: undefined, mine: undefined };
282 if (!before.startsWith("m.")) return { runs: before, mine: undefined };
283 const parts = Buffer.from(before.slice(2), "base64url").toString().split("~");
284 const [runs = "", mine = ""] = parts;
285 // A cursor this list did not write starts the list over, as a malformed facet is dropped.
286 const runsOk = runs === "" || runs === NOT_MORE || RUN_ID.test(runs);
287 const mineOk = mine === "" || mine === NOT_MORE || TRACE_CURSOR.test(mine);
288 if (parts.length !== 2 || !runsOk || !mineOk) return { runs: undefined, mine: undefined };
289 return { runs: runs === "" ? undefined : runs, mine: mine === "" ? undefined : mine };
290 }
291
292 /**
293 * One page of traces `actor` may open, newest first: crew runs (read from the `run` table, by run
294 * id) and the viewer's own Talk turns and imported sessions (read from the trace index, behind the
295 * API's gate), merged by time. A `kind` narrows to one stream.
296 */
297 export function listTraces(app: App, actor: User | undefined, f: TraceFilter): TraceList {
298 const cur = readCursor(f.before);
299 const facets = facetsOf(app, actor);
300 const runsOn = f.kind === undefined || f.kind === "run";
301 const mineOn = f.kind !== "run" && actor !== undefined && f.repo === undefined;
302 const runs = cur.runs === NOT_MORE || !runsOn ? { rows: [], next: undefined } : crewRuns(app, actor, f, cur.runs);
303 if (!mineOn) return { rows: runs.rows, next: runs.next, facets };
304 const mine = cur.mine === NOT_MORE ? { rows: [], next: undefined } : personal(app, actor, f, cur.mine);
305 if (!runsOn) return { rows: mine.rows.slice(0, PAGE), next: resume(mine, Math.min(PAGE, mine.rows.length), cur.mine), facets };
306 const rows: TraceRow[] = [];
307 let i = 0;
308 let j = 0;
309 while (rows.length < PAGE && (i < runs.rows.length || j < mine.rows.length)) {
310 const r = runs.rows[i];
311 const m = mine.rows[j];
312 if (m === undefined || (r !== undefined && r.at >= m.at)) (rows.push(r!), (i += 1));
313 else (rows.push(m), (j += 1));
314 }
315 const a = resume(runs, i, cur.runs);
316 const b = resume(mine, j, cur.mine);
317 const next = a === undefined && b === undefined ? undefined : `m.${Buffer.from(`${a === undefined ? NOT_MORE : a}~${b === undefined ? NOT_MORE : b}`).toString("base64url")}`;
318 return { rows, next, facets };
319 }
320
321 /** Where a stream resumes after `used` of its rows were shown; undefined when nothing is left. */
322 function resume(s: Stream<TraceRow>, used: number, prior: string | undefined): string | undefined {
323 if (used >= s.rows.length) return s.next;
324 const last = s.rows[used - 1];
325 if (last === undefined) return prior ?? "";
326 return last.source === "run" ? last.id : cursorOf({ started: last.at, id: last.id });
210327 }
211328
212329 /** The values a facet offers: what the viewer's own traces hold. */
@@ -242,5 +359,5 @@ export const costWords = (usd: number | undefined): string => (usd === undefined
242359
243360 /** One row as a terminal line: title, repository, model, cost, outcome. */
244361 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(" · ");
362 return [r.title, r.kind === "crew run" ? "" : r.kind, r.repo, r.model === "" ? "" : r.model, costWords(r.costUsd), r.at.slice(0, 16).replace("T", " "), r.outcome].filter((x) => x !== "").join(" · ");
246363 }
src/tui/screens/traces.ts +16 −13
@@ -1,16 +1,17 @@
11 /**
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. `v` marks a row (two at most, the older mark drops) and `d` opens the two as
7 * a comparison (#18085): the trace screen's own, so the page's words; two runs of different issues
8 * are told so. Every value goes through the page's own `readFilter`. Read-only; Esc closes. The
9 * lines are `traceLine`, the page's own row.
2 * The Traces command (#17992): what `/traces` says, one line a crew run, Talk turn or imported
3 * session (`i` cycles the kind), newest first. `/` types a search (the same text as the page's
4 * `q`), `r` `m` `o` `p` cycle the repository, model, outcome and person facets through what the
5 * list offers (then back to any), `f` and `t` type the from and to days (YYYY-MM-DD), `c` clears
6 * them, `j`/`k` move, Enter opens the run's trace, `n` reads the next older page. `v` marks a row
7 * (two at most, the older mark drops) and `d` opens the two as a comparison (#18085): the trace
8 * screen's own, so the page's words; two runs of different issues are told so. Every value goes
9 * through the page's own `readFilter`. Read-only; Esc closes. The lines are `traceLine`, the page's
10 * own row.
1011 */
1112 import { binding } from "../app/keys.ts";
1213 import type { Ctx, Screen } from "../app/app.ts";
13 import { listTraces, OUTCOMES, readFilter, traceLine, type TraceFilter, type TraceList } from "../../trace/list.ts";
14 import { listTraces, OUTCOMES, readFilter, SOURCES, traceLine, type TraceFilter, type TraceList } from "../../trace/list.ts";
1415 import { getRepoById } from "../../core/repos.ts";
1516 import { getRun } from "../../core/runs.ts";
1617 import { sameIssue } from "../../trace/compare.ts";
@@ -25,7 +26,7 @@ import type { PaletteEntry } from "./entries.ts";
2526 function tracesScreen(f: Session, ctx: Ctx): Screen {
2627 const scroll = new Scroll();
2728 // What the page holds in its URL, as strings; `readFilter` is the one validator of them.
28 const facet: { [K in "q" | "repo" | "model" | "outcome" | "by" | "from" | "to"]?: string } = {};
29 const facet: { [K in "q" | "kind" | "repo" | "model" | "outcome" | "by" | "from" | "to"]?: string } = {};
2930 let before: string | undefined;
3031 const filter = (): TraceFilter => {
3132 const p = new URLSearchParams();
@@ -49,7 +50,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
4950 before = undefined;
5051 read();
5152 };
52 const cycle = (k: "repo" | "model" | "outcome" | "by", values: readonly string[]): void => {
53 const cycle = (k: "kind" | "repo" | "model" | "outcome" | "by", values: readonly string[]): void => {
5354 const i = facet[k] === undefined ? -1 : values.indexOf(facet[k]!);
5455 set(k, i + 1 >= values.length ? undefined : values[i + 1]);
5556 };
@@ -60,7 +61,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
6061 };
6162 return {
6263 title: "Traces",
63 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), 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")],
64 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["i", "r", "m", "o", "p"], "kind, repo, model, outcome, person"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")],
6465 render(area, s) {
6566 const c = ctx.theme.c;
6667 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);
@@ -92,6 +93,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
9293 else if (e.key === "/") typing = "q";
9394 else if (e.key === "f") typing = "from";
9495 else if (e.key === "t") typing = "to";
96 else if (e.key === "i") cycle("kind", SOURCES);
9597 else if (e.key === "r") cycle("repo", list.facets.repos);
9698 else if (e.key === "m") cycle("model", list.facets.models);
9799 else if (e.key === "o") cycle("outcome", OUTCOMES);
@@ -117,7 +119,8 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
117119 else if (e.key === "k" || e.key === "up") move(at - 1);
118120 else if (e.key === "enter") {
119121 const r = list.rows[at];
120 if (r !== undefined) openOnWeb(f, ctx, r.href, "the trace");
122 if (r?.href !== undefined) openOnWeb(f, ctx, r.href, "the trace");
123 else if (r !== undefined) ctx.toast("an imported session has no page yet", "attn");
121124 } else if (e.key === "n" && list.next !== undefined) ((before = list.next), read());
122125 ctx.invalidate();
123126 return true;
src/web/pages/traces.ts +8 −7
@@ -7,7 +7,7 @@
77 */
88 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
99 import type { Ctx } from "../../http/context.ts";
10 import { costWords, filterQuery, listTraces, OUTCOMES, readFilter, type TraceFilter, type TraceList, type TraceRow } from "../../trace/list.ts";
10 import { costWords, filterQuery, listTraces, OUTCOMES, SOURCES, readFilter, type TraceFilter, type TraceList, type TraceRow } from "../../trace/list.ts";
1111 import { pageHead } from "../chrome.ts";
1212 import { html, type Html } from "../html.ts";
1313 import { page } from "../layout.ts";
@@ -15,6 +15,7 @@ import { badge, btn, disclosure, empty, listCard, row, time } from "../ui.ts";
1515
1616 const FILTERS: readonly [keyof TraceFilter, string][] = [
1717 ["q", "Search"],
18 ["kind", "Kind"],
1819 ["repo", "Repository"],
1920 ["model", "Model"],
2021 ["outcome", "Outcome"],
@@ -32,11 +33,11 @@ const date = (name: string, label: string, now: string | undefined): Html =>
3233
3334 const line = (r: TraceRow): Html =>
3435 row({
35 href: r.href,
36 nav: true,
36 // An imported session has no page yet: a plain row, not a link that goes nowhere.
37 ...(r.href === undefined ? {} : { href: r.href, nav: true }),
3738 title: r.title,
3839 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 meta: html`${r.kind}${r.repo === "" ? "" : ` · ${r.repo}`}${r.model === "" ? "" : ` · ${r.model}`}${r.costUsd === undefined ? "" : ` · ${costWords(r.costUsd)}`} · ${time(r.at)}${r.by === "" ? "" : ` · ${r.by}`}`,
4041 trail: badge(r.outcome, { tone: r.outcome === "failed" ? "danger" : r.outcome === "ok" ? "success" : "default" }),
4142 data: { trace: r.id },
4243 });
@@ -49,10 +50,10 @@ function controls(f: TraceFilter, list: TraceList): Html {
4950 ${disclosure(
5051 "Filters",
5152 html`<div class="traces-facets">
52 ${select("repo", "Repository", list.facets.repos, f.repo)}${select("model", "Model", list.facets.models, f.model)}
53 ${select("kind", "Kind", SOURCES, f.kind)}${select("repo", "Repository", list.facets.repos, f.repo)}${select("model", "Model", list.facets.models, f.model)}
5354 ${select("outcome", "Outcome", OUTCOMES, f.outcome)}${select("by", "Person or agent", list.facets.people, f.by)}
5455 ${date("from", "From", f.from)}${date("to", "To", f.to)}
55 </div>`,
56 </div>${f.repo === undefined ? "" : html`<p class="muted" data-repo-note>A repository narrows to crew runs: Talk turns and imported sessions have none.</p>`}`,
5657 { small: true, extra: "mt", open: active.length > 0 },
5758 )}
5859 </form>
@@ -79,7 +80,7 @@ export function tracesPage(ctx: Ctx): Response {
7980 const list = listTraces(ctx.app, ctx.auth.user, f);
8081 notePhase(ctx.request, "read", performance.now() - reading);
8182 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 const body = html`${pageHead("Traces", { sub: "Every crew run, Talk turn and imported session you may open, newest first." })}
8384 ${controls(f, list)}
8485 ${list.rows.length === 0
8586 ? 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." })
test/traces-kinds.test.ts added +134
@@ -0,0 +1,134 @@
1 /**
2 * `/traces` lists Talk turns and imported sessions beside crew runs, each to its person alone
3 * (#18356).
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 } from "../src/app.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { newConversation } from "../src/core/conversations.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { indexTalkTurn, putTraceRow } from "../src/trace/index_table.ts";
16 import { listTraces, PAGE, readFilter } from "../src/trace/list.ts";
17 import { seedAdmin } from "./helpers/admin.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 let dir = "";
23 let app: App;
24 let servers: Servers;
25 let alice: User;
26 let bob: User;
27 let aliceToken = "";
28 let bobToken = "";
29
30 const page = async (token: string, path: string): Promise<string> => (await fetch(`${servers.url}${path}`, { headers: { authorization: `Bearer ${token}` } })).text();
31 const ids = (u: User, q: string): string[] => listTraces(app, u, readFilter(new URLSearchParams(q))).rows.map((r) => r.id);
32
33 beforeAll(async () => {
34 dir = await mkdtemp(join(tmpdir(), "forge-traces-kinds-"));
35 app = createApp({ dataDir: dir, port: 0 });
36 servers = await serve(app);
37 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
38 if (!a.ok) throw new Error(a.error);
39 alice = a.value;
40 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
41 if (!b.ok) throw new Error("bob");
42 bob = b.value;
43 aliceToken = createToken(app.db, alice.id, "t", "ro").token;
44 bobToken = createToken(app.db, bob.id, "t", "ro").token;
45 const convo = newConversation(app.db, alice.id);
46 app.db
47 .query(
48 "INSERT INTO conversation_run (id, conversation_id, user_id, state, prompt, started_at, finished_at, model) VALUES ('talk1', ?1, ?2, 'ok', 'plan <i>the</i> week', '2026-12-04T13:00:00.000Z', '2026-12-04T13:00:01.000Z', 'm')",
49 )
50 .run(convo.id, alice.id);
51 indexTalkTurn(app.db, dir, "talk1");
52 putTraceRow(
53 app.db,
54 { id: "imp1", kind: "imported", repository: "", title: "an outside session", model: "claude-x", account: "", steps: 1, errors: 0, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, outcome: "ok", started: "2026-12-05T09:00:00.000Z", ended: "2026-12-05T09:01:00.000Z" },
55 alice.id,
56 );
57 });
58
59 afterAll(async () => {
60 servers.stop();
61 app.close();
62 await rm(dir, { recursive: true, force: true });
63 });
64
65 test("a Talk turn and an imported session show for their person and for no one else", async () => {
66 expect(ids(alice, "")).toEqual(["imp1", "talk1"]); // newest first
67 expect(ids(bob, "")).toEqual([]);
68 expect(listTraces(app, undefined, {}).rows).toEqual([]);
69 const mine = await page(aliceToken, "/traces");
70 expect(mine).toContain('data-trace="talk1"');
71 expect(mine).toContain('data-trace="imp1"');
72 expect(mine).toContain('href="/traces/talk1"');
73 expect(mine).not.toContain('href="/traces/imp1"'); // its page is the next issue: plain text
74 expect(mine).toContain("plan &lt;i&gt;the&lt;/i&gt; week");
75 expect(mine.slice(mine.indexOf("<main"), mine.indexOf("</main>"))).not.toContain("<script"); // the first paint adds none
76 const theirs = await page(bobToken, "/traces");
77 expect(theirs).not.toContain("talk1");
78 expect(theirs).not.toContain("imp1");
79 expect(theirs).not.toContain("outside session");
80 });
81
82 test("a repository facet says it leaves Talk and imported rows out", async () => {
83 expect(await page(aliceToken, "/traces?repo=alice/mix")).toContain("data-repo-note");
84 expect(await page(aliceToken, "/traces")).not.toContain("data-repo-note");
85 });
86
87 test("the kind facet narrows, is a link, and a malformed one is dropped", async () => {
88 expect(ids(alice, "kind=talk")).toEqual(["talk1"]);
89 expect(ids(alice, "kind=imported")).toEqual(["imp1"]);
90 expect(ids(alice, "kind=run")).toEqual([]);
91 expect(readFilter(new URLSearchParams("kind=bogus"))).toEqual({});
92 expect(ids(alice, "kind=talk&by=bob")).toEqual([]);
93 expect(ids(alice, "q=outside")).toEqual(["imp1"]);
94 const html = await page(aliceToken, "/traces?kind=talk");
95 expect(html).toContain('data-trace="talk1"');
96 expect(html).not.toContain('data-trace="imp1"');
97 expect(html).toContain('<option value="talk" selected>'); // the one way to set it: the Kind select
98 expect(html).toContain('aria-label="Remove Kind: talk"');
99 expect(html).not.toContain('href="/traces?kind=imported"');
100 });
101
102 test("pages of runs and index rows merged hold every row once, newest first, and a foreign cursor starts over", async () => {
103 const repo = await createRepo(app, alice, { name: "mix", visibility: "public", description: "" });
104 if (!repo.ok) throw new Error(String(repo.error));
105 const run = app.db.prepare("INSERT INTO run (id, repo_id, kind, state, summary, model, actor_id, cost_usd, created_at) VALUES (?1, ?2, 'agent', 'ok', ?3, 'm', ?4, 0, ?5)");
106 const want: string[] = [];
107 // 60 runs and 60 imported sessions, interleaved minute by minute: more than two pages.
108 for (let i = 0; i < 120; i += 1) {
109 const at = new Date(Date.UTC(2026, 10, 1, 0, i)).toISOString();
110 const id = `${i % 2 === 0 ? "mr" : "mi"}${String(i).padStart(4, "0")}`;
111 if (i % 2 === 0) run.run(id, repo.value.id, `run ${i}`, alice.id, at);
112 else putTraceRow(app.db, { id, kind: "imported", repository: "", title: `imp ${i}`, model: "m", account: "", steps: 1, errors: 0, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, outcome: "ok", started: at, ended: at }, alice.id);
113 want.unshift(id);
114 }
115 const seen: string[] = [];
116 const ats: string[] = [];
117 let before: string | undefined;
118 for (let n = 0; n < 10; n += 1) {
119 const got = listTraces(app, alice, { from: "2026-11-01", to: "2026-11-01", ...(before === undefined ? {} : { before }) });
120 expect(got.rows.length).toBeLessThanOrEqual(PAGE);
121 seen.push(...got.rows.map((r) => r.id));
122 ats.push(...got.rows.map((r) => r.at));
123 if (got.next === undefined) break;
124 expect(readFilter(new URLSearchParams({ before: got.next })).before).toBe(got.next); // the cursor survives the URL
125 before = got.next;
126 }
127 expect(seen).toEqual(want); // no duplicate, no gap
128 expect([...ats].sort().reverse()).toEqual(ats);
129 // A garbage `m.` cursor is the first page again, not an error or an empty list.
130 const first = listTraces(app, alice, { from: "2026-11-01", to: "2026-11-01" }).rows.map((r) => r.id);
131 for (const junk of ["m.AAAA", `m.${Buffer.from("x y~nope").toString("base64url")}`, `m.${Buffer.from("a~b~c").toString("base64url")}`]) {
132 expect(listTraces(app, alice, { from: "2026-11-01", to: "2026-11-01", before: junk }).rows.map((r) => r.id)).toEqual(first);
133 }
134 });
test/traces-tui.test.ts added +89
@@ -0,0 +1,89 @@
1 /**
2 * The terminal's Traces screen: `i` cycles the kind, and an imported session has no page to open
3 * (#18364).
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 { newConversation } from "../src/core/conversations.ts";
12 import type { User } from "../src/core/users.ts";
13 import { indexTalkTurn, putTraceRow } from "../src/trace/index_table.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { headlessTerminal } from "../src/tui/term/terminal.ts";
16 import { entry } from "../src/tui/screens/traces.ts";
17 import { seedAdmin } from "./helpers/admin.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { settleApp } from "./helpers/tui.ts";
20
21 quietLogs();
22
23 let dir: string;
24 let forge: Forge;
25 let alice: User;
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-tui-traces-"));
29 forge = createApp({ dataDir: dir, port: 0 });
30 const a = await seedAdmin(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" });
31 if (!a.ok) throw new Error("signup failed");
32 alice = a.value;
33 const repo = await createRepo(forge, alice, { name: "mix", visibility: "public", description: "" });
34 if (!repo.ok) throw new Error("repo failed");
35 forge.db
36 .prepare("INSERT INTO run (id, repo_id, kind, state, summary, model, actor_id, cost_usd, created_at) VALUES ('run1', ?1, 'agent', 'ok', 'crew run summary', 'm', ?2, 0, '2026-12-03T10:00:00.000Z')")
37 .run(repo.value.id, alice.id);
38 const convo = newConversation(forge.db, alice.id);
39 forge.db
40 .query("INSERT INTO conversation_run (id, conversation_id, user_id, state, prompt, started_at, finished_at, model) VALUES ('talk1', ?1, ?2, 'ok', 'plan the week', '2026-12-04T13:00:00.000Z', '2026-12-04T13:00:01.000Z', 'm')")
41 .run(convo.id, alice.id);
42 indexTalkTurn(forge.db, dir, "talk1");
43 putTraceRow(
44 forge.db,
45 { id: "imp1", kind: "imported", repository: "", title: "an outside session", model: "claude-x", account: "", steps: 1, errors: 0, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, outcome: "ok", started: "2026-12-05T09:00:00.000Z", ended: "2026-12-05T09:01:00.000Z" },
46 alice.id,
47 );
48 });
49 afterAll(async () => {
50 forge.close?.();
51 await rm(dir, { recursive: true, force: true });
52 });
53
54 test("i cycles the kind: runs, then only Talk, then only imported; Enter on an imported session says it has no page", async () => {
55 const { app, session } = createForgeApp(forge, { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice }, { terminal: headlessTerminal(120, 30), exitHooks: false });
56 app.start();
57 await settleApp(app);
58 entry.run(session, app.ctx);
59 await settleApp(app);
60 const press = async (key: string): Promise<string> => {
61 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
62 await settleApp(app);
63 return app.screen.toText();
64 };
65 const all = app.screen.toText();
66 expect(all).toContain("crew run summary");
67 expect(all).toContain("plan the week");
68 expect(all).toContain("an outside session");
69
70 // The cycle starts at the crew runs: run, talk, imported, then any.
71 const runs = await press("i");
72 expect(runs).toContain("crew run summary");
73 expect(runs).not.toContain("plan the week");
74
75 const talk = await press("i");
76 expect(talk).toContain("plan the week");
77 expect(talk).not.toContain("crew run summary");
78 expect(talk).not.toContain("an outside session");
79
80 const imported = await press("i");
81 expect(imported).toContain("an outside session");
82 expect(imported).not.toContain("plan the week");
83 expect(imported).not.toContain("crew run summary");
84
85 const after = await press("enter");
86 expect(after).toContain("an imported session has no page yet");
87 expect(after).toContain("an outside session"); // still on the list: nothing was pushed
88 app.stop();
89 });

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

Keyboard shortcuts

Docs