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

A check's run page shows its steps and live progress, and the runs list shows checks by default #2367

Parked opened this
Closed without merging

scout/forge:scout/1124-a-check-s-run-page-shows-its-steps-and-l → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +426 −23
src/checks/progress.ts +4
@@ -17,6 +17,8 @@ export type CheckProgress = {
1717 files?: number;
1818 passed?: number;
1919 failed?: number;
20 /** The files of the shard running now, when a live shard has opened and not yet finished. */
21 current?: string;
2022 };
2123
2224 const BANNER = /^test-shards: (?:recording |measuring )?(\d+) files\b/;
@@ -48,12 +50,14 @@ export function parseShardProgress(lines: readonly string[]): CheckProgress {
4850 const live = SHARD_LIVE_OPEN.exec(line);
4951 if (live) {
5052 open = fileCount(live[1]!);
53 out.current = live[1]!.trim();
5154 out.files ??= 0;
5255 continue;
5356 }
5457 if (SHARD_DONE.test(line)) {
5558 out.files = (out.files ?? 0) + open;
5659 open = 0;
60 delete out.current;
5761 continue;
5862 }
5963 // `bun test`'s own tail counts only inside a shard's report.
src/checks/service.ts +18 −1
@@ -78,6 +78,7 @@ import {
7878 import { summariseCheckFailure } from "./summary.ts";
7979 import type { Result } from "../kernel/result.ts";
8080 import { placementFromEnv, type Placement } from "./placement.ts";
81 import { stepLine, TESTS_BANNER } from "./steps.ts";
8182 import { JOB_VANISHED, runJobStep } from "./job_step.ts";
8283 import type { JobOptions } from "../cluster/jobs.ts";
8384 import type { CheckDetail } from "../core/runs.ts";
@@ -827,6 +828,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
827828 });
828829 } else {
829830 if (manifest.install !== null) {
831 const began = Date.now();
830832 const installed = await runStep("install", manifest.install, {
831833 cwd: dir,
832834 env,
@@ -835,8 +837,13 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
835837 timeoutMs: manifest.timeout * 1000,
836838 cell,
837839 });
840 write(stepLine("install", installed.ok ? "ok" : "failed", Date.now() - began));
838841 if (!installed.ok) return { ok: false, error: installed.error };
839 }
842 } else write(stepLine("install", "none", 0));
843 // Everything before the shard runner's banner is the typecheck; the
844 // banner is where the tests begin (`checks/steps.ts`).
845 const checkBegan = Date.now();
846 let testsBegan: number | undefined;
840847 // The check step's own lines are kept beside what `write` already
841848 // logs, so a failure can be summarised once here — never by reading
842849 // the log back, on this run or any later render of it. `runStep`
@@ -849,12 +856,22 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
849856 log: (line) => {
850857 if (sawEcho) checkLines.push(line);
851858 sawEcho = true;
859 if (testsBegan === undefined && TESTS_BANNER.test(line)) {
860 testsBegan = Date.now();
861 write(stepLine("typecheck", "ok", testsBegan - checkBegan));
862 }
852863 write(line);
853864 },
854865 signal,
855866 timeoutMs: manifest.timeout * 1000,
856867 cell,
857868 });
869 const ended = Date.now();
870 write(
871 testsBegan === undefined
872 ? stepLine("typecheck", ran.ok ? "ok" : "failed", ended - checkBegan)
873 : stepLine("tests", ran.ok ? "ok" : "failed", ended - testsBegan),
874 );
858875 }
859876 if (!ran.ok && ran.error === JOB_VANISHED) return { ok: false, error: JOB_VANISHED };
860877 if (!ran.ok) {
src/checks/steps.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * A check run read as the three steps a person expects of it — install,
3 * typecheck, tests — and the failures it has shown so far. Plain data in
4 * (the run's own lines and state), plain data out: the same lines the
5 * pull's checks line reads (`progress.ts`), never a second source.
6 *
7 * `checks/service.ts` writes a `step <name> <ok|failed|none> <ms>` line as
8 * each step ends; the shard runner's banner (`test-shards: N files`) says
9 * the typecheck before it passed and the tests began. A log without either
10 * (an older run) still gets its three rows, with the state worked out from
11 * how the run ended and no duration claimed.
12 */
13
14 import type { RunState } from "../core/runs.ts";
15 import { parseShardProgress, type CheckProgress } from "./progress.ts";
16
17 export const STEP_NAMES = ["install", "typecheck", "tests"] as const;
18 export type StepName = (typeof STEP_NAMES)[number];
19
20 export type StepState = "waiting" | "running" | "ok" | "failed" | "none" | "skipped";
21
22 export interface Step {
23 readonly name: StepName;
24 readonly state: StepState;
25 /** Milliseconds, only when the step's end was logged. */
26 readonly ms: number | undefined;
27 }
28
29 /** The line the check service writes as a step ends. */
30 export const stepLine = (name: StepName, outcome: "ok" | "failed" | "none", ms: number): string =>
31 `step ${name} ${outcome} ${Math.max(0, Math.round(ms))}`;
32
33 const MARKER = /^step (install|typecheck|tests) (ok|failed|none) (\d+)$/;
34 export const TESTS_BANNER = /^test-shards: (?:recording |measuring )?\d+ files\b/;
35
36 export function checkSteps(lines: readonly string[], state: RunState): Step[] {
37 const marks = new Map<StepName, { outcome: "ok" | "failed" | "none"; ms: number }>();
38 let testsBegan = false;
39 for (const line of lines) {
40 const m = MARKER.exec(line);
41 if (m) marks.set(m[1] as StepName, { outcome: m[2] as "ok" | "failed" | "none", ms: Number(m[3]) });
42 else if (TESTS_BANNER.test(line)) testsBegan = true;
43 }
44 const over = state !== "queued" && state !== "running";
45 let blocked = false;
46 return STEP_NAMES.map((name): Step => {
47 const mark = marks.get(name);
48 let result: StepState | undefined =
49 mark === undefined ? undefined : mark.outcome === "none" ? "none" : mark.outcome;
50 // The typecheck passed if the tests began; the tests are not green
51 // unless the run is.
52 if (result === undefined && name === "typecheck" && testsBegan) result = "ok";
53 if (result === undefined && name === "install" && (testsBegan || marks.has("typecheck")))
54 result = "ok";
55 if (result === undefined && over && state === "ok") result = "ok";
56 if (result === "failed") blocked = true;
57 if (result !== undefined) return { name, state: result, ms: mark?.ms };
58 if (blocked) return { name, state: over ? "skipped" : "waiting", ms: undefined };
59 // The first step without a result is the one the run is in, or the one it died in.
60 blocked = true;
61 if (!over) return { name, state: state === "running" ? "running" : "waiting", ms: undefined };
62 return { name, state: state === "failed" ? "failed" : "skipped", ms: undefined };
63 });
64 }
65
66 export interface PinnedFailure {
67 readonly name: string;
68 /** The lines `bun test` printed just before the `(fail)` line, bounded. */
69 readonly lines: readonly string[];
70 }
71
72 const FAIL_LINE = /^\(fail\) (.+?)(?: \[[0-9.]+m?s\])?(?: \[shard [0-9]+\])?$/;
73 const EDGE = /^(\(pass\)|\(fail\)|── |test-shards:|\$ |step )|\.(?:test\.)?[tj]sx?:$/;
74 const FIRST_LINES = 4;
75 const BLOCK_MAX = 12;
76 export const PINNED_MAX = 10;
77
78 /**
79 * Every failed test seen so far, each once, with the first lines of what
80 * bun printed for it. The runner's closing echo of the same names carries
81 * no lines of its own and never replaces the first sighting.
82 */
83 export function pinnedFailures(lines: readonly string[]): PinnedFailure[] {
84 const seen = new Map<string, string[]>();
85 lines.forEach((line, i) => {
86 const m = FAIL_LINE.exec(line);
87 if (!m) return;
88 const name = m[1]!;
89 const block: string[] = [];
90 for (let j = i - 1; j >= 0 && block.length < BLOCK_MAX; j--) {
91 const prev = lines[j]!;
92 if (EDGE.test(prev)) break;
93 block.unshift(prev);
94 }
95 const kept = block.map((l) => l.trimEnd()).filter((l) => l.trim() !== "").slice(0, FIRST_LINES);
96 const had = seen.get(name);
97 if (had === undefined || (had.length === 0 && kept.length > 0)) seen.set(name, kept);
98 });
99 return [...seen].map(([name, ls]) => ({ name, lines: ls }));
100 }
101
102 /** What the run page draws from one read of the log. */
103 export interface CheckView {
104 readonly steps: Step[];
105 readonly progress: CheckProgress;
106 readonly failures: PinnedFailure[];
107 }
108
109 export function checkView(lines: readonly string[], state: RunState): CheckView {
110 return {
111 steps: checkSteps(lines, state),
112 progress: parseShardProgress(lines),
113 failures: pinnedFailures(lines),
114 };
115 }
src/web/client.ts +19
@@ -327,6 +327,23 @@ export const studioRunJs = /* js */ `
327327 }
328328
329329 if (!url || typeof EventSource === 'undefined') return;
330 // A check's steps, progress and pinned failures: the page's own block,
331 // fetched again at most once a second while lines land.
332 var stepsTimer = 0;
333 function refreshSteps() {
334 if (stepsTimer || !document.getElementById('run-steps') || !window.fetch || !window.DOMParser) return;
335 stepsTimer = window.setTimeout(function () {
336 stepsTimer = 0;
337 fetch(location.href, { credentials: 'same-origin', headers: { accept: 'text/html' } })
338 .then(function (r) { return r.ok ? r.text() : ''; })
339 .then(function (text) {
340 var fresh = text && new DOMParser().parseFromString(text, 'text/html').getElementById('run-steps');
341 var here = document.getElementById('run-steps');
342 if (fresh && here) here.innerHTML = fresh.innerHTML;
343 })
344 .catch(function () {});
345 }, 1000);
346 }
330347 var source = new EventSource(url);
331348 var empty = document.getElementById('run-empty');
332349 var seeded = false;
@@ -341,9 +358,11 @@ export const studioRunJs = /* js */ `
341358 var text = event.data;
342359 try { var parsed = JSON.parse(text); if (typeof parsed === 'string') text = parsed; } catch (err) {}
343360 add(draw(text));
361 refreshSteps();
344362 });
345363 source.addEventListener('done', function (event) {
346364 source.close();
365 refreshSteps();
347366 var run;
348367 try { run = JSON.parse(event.data); } catch (err) { return; }
349368 paint(run);
src/web/pages/runs.ts +1 −1
@@ -142,7 +142,7 @@ export function runTokens(db: Database, run: Run): Html {
142142 export type LineKind = "tool" | "forge" | "say" | "you";
143143
144144 const FORGE_LINE =
145 /^(claude:|done:|failed:|paused|declined:|cloning |branch |forked |pushing |push refused|clone kept|nothing to propose|opened pull|updated pull|committed the|could not|checking out|deploy |data: |\$ |session |the session|interrupted|passed in|install |test |start |ready |process |timing: )/;
145 /^(claude:|done:|failed:|paused|declined:|cloning |branch |forked |pushing |push refused|clone kept|nothing to propose|opened pull|updated pull|committed the|could not|checking out|deploy |data: |\$ |session |the session|interrupted|passed in|step |install |test |start |ready |process |timing: )/;
146146
147147 export function lineKind(line: string): LineKind {
148148 if (line.startsWith("→ ")) return "tool";
src/web/studio/check_steps.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * A check's run page above its log: the three steps as rows (all three from
3 * the first paint, so nothing shifts as they land), the tests' progress bar,
4 * and the failures pinned as they appear. Drawn from `checkView`
5 * (`checks/steps.ts`) — the same lines the pull's checks line reads.
6 */
7
8 import { checkView, PINNED_MAX, type Step, type StepState } from "../../checks/steps.ts";
9 import { spanWords } from "../../checks/summary.ts";
10 import type { CheckProgress } from "../../checks/progress.ts";
11 import type { RunState } from "../../core/runs.ts";
12 import { html, when, type Html } from "../html.ts";
13
14 const STATE_WORDS: Record<StepState, string> = {
15 waiting: "waiting",
16 running: "running",
17 ok: "passed",
18 failed: "failed",
19 none: "not needed",
20 skipped: "not run",
21 };
22
23 const stepRow = (step: Step): Html => html`<li class="check-step" data-state="${step.state}">
24 <span class="step-name">${step.name}</span>
25 <span class="step-state">${STATE_WORDS[step.state]}</span>
26 <span class="step-time num">${step.ms === undefined ? "" : spanWords(step.ms)}</span>
27 </li>`;
28
29 function bar(p: CheckProgress): Html {
30 const known = p.of !== undefined && p.of > 0 && p.files !== undefined && p.files <= p.of;
31 const words =
32 p.of === undefined
33 ? "Counting files…"
34 : `${p.files ?? 0} of ${p.of} files started`;
35 const counts =
36 p.passed === undefined || p.failed === undefined
37 ? ""
38 : `${p.passed} passed, ${p.failed} failed`;
39 return html`<div class="check-progress">
40 <progress class="check-bar" aria-label="Test files" max="${p.of ?? 1}" value="${known ? p.files! : 0}"></progress>
41 <div class="check-progress-words small muted"><span>${words}</span><span>${counts}</span></div>
42 <div class="check-now small muted">${p.current === undefined ? "" : html`Running ${p.current}`}</div>
43 </div>`;
44 }
45
46 /** The block for one check run; it replaces itself wholesale when the page refetches it. */
47 export function checkSteps(lines: readonly string[], state: RunState): Html {
48 const view = checkView(lines, state);
49 const shown = view.failures.slice(0, PINNED_MAX);
50 return html`<section class="check-steps" id="run-steps" aria-label="Steps">
51 <ol class="check-step-list">
52 ${view.steps.map(stepRow)}
53 </ol>
54 ${bar(view.progress)}
55 ${when(
56 shown.length > 0,
57 () => html`<div class="check-failures" id="run-failures">
58 <h2 class="small">Failures so far · ${view.failures.length}</h2>
59 ${shown.map(
60 (f) => html`<details class="check-failure" open>
61 <summary>${f.name}</summary>
62 ${when(f.lines.length > 0, () => html`<pre>${f.lines.join("\n")}</pre>`)}
63 </details>`,
64 )}
65 ${when(
66 view.failures.length > shown.length,
67 () => html`<p class="muted small">and ${view.failures.length - shown.length} more in the log below.</p>`,
68 )}
69 </div>`,
70 )}
71 </section>`;
72 }
src/web/studio/lists.ts +25 −20
@@ -52,7 +52,7 @@ import {
5252 seg,
5353 time,
5454 } from "../ui.ts";
55 import { actorsFor, issuesFor, runTitleFrom } from "../pages/runs.ts";
55 import { actorsFor, durationText, issuesFor, runTitleFrom } from "../pages/runs.ts";
5656 import { originGlyph } from "../pages/thread.ts";
5757 import { changeHref, PAGE_TITLES, pageTitle, tellHref } from "./nouns.ts";
5858 import { tellLine, tellsAnswered } from "./branch_tell.ts";
@@ -553,14 +553,13 @@ export async function changesList(ctx: Ctx): Promise<Response> {
553553 });
554554 }
555555
556 /** Which runs a list shows: the crew's by default, or the deploys or the
557 * checks that `?kind=` asks for — the narrowing dev's list offered, kept
558 * so a link written to it keeps meaning what it said. */
559 type RunsKind = "agent" | "deploy" | "check";
556 /** Which runs a list shows: all of them by default, or the crew's, the
557 * deploys or the checks that `?kind=` asks for. */
558 type RunsKind = "all" | "agent" | "deploy" | "check";
560559
561560 function readRunsKind(ctx: Ctx): RunsKind {
562561 const raw = ctx.url.searchParams.get("kind");
563 return raw === "deploy" || raw === "check" ? raw : "agent";
562 return raw === "deploy" || raw === "check" || raw === "agent" ? raw : "all";
564563 }
565564
566565 /** The runs list's own address with a word, a kind and a cursor. */
@@ -571,7 +570,7 @@ function runsHref(
571570 cursor?: string,
572571 ): string {
573572 const params = new URLSearchParams();
574 if (kind !== "agent") params.set("kind", kind);
573 if (kind !== "all") params.set("kind", kind);
575574 if (word !== undefined) params.set("word", word);
576575 if (cursor !== undefined) params.set("cursor", cursor);
577576 const text = params.toString();
@@ -579,6 +578,7 @@ function runsHref(
579578 }
580579
581580 const RUNS_KIND_WORDS: Record<RunsKind, string> = {
581 all: "all runs",
582582 agent: "the crew's runs",
583583 deploy: "deploys",
584584 check: "checks",
@@ -587,9 +587,9 @@ const RUNS_KIND_WORDS: Record<RunsKind, string> = {
587587 /**
588588 * GET /:owner/:name/runs: every run, for every repository and every viewer,
589589 * one row per run in its studio word — who ran it, when it last moved, and
590 * the transcript as the row's own link. The crew's runs by default;
591 * `?kind=deploy|check` reads the deploys or the checks instead, from one
592 * quiet line under the list. `?word=` narrows any of them.
590 * the transcript as the row's own link. Checks, deploys and the crew's runs
591 * together by default; `?kind=agent|deploy|check` narrows to one of the
592 * three, from one quiet line under the list. `?word=` narrows any of them.
593593 */
594594 export async function runsListPage(ctx: Ctx, repo: Repo): Promise<Response> {
595595 const db = ctx.app.db;
@@ -601,7 +601,7 @@ export async function runsListPage(ctx: Ctx, repo: Repo): Promise<Response> {
601601 // A private app's runs are for those who may enter it, and a sealed
602602 // report's for those who may see it (`listRepoRuns`).
603603 const listed = listRepoRuns(ctx.app, ctx.auth.user, repo, {
604 kind,
604 ...(kind === "all" ? {} : { kind }),
605605 limit: LIST_PAGE,
606606 ...(cursor ? { cursor } : {}),
607607 });
@@ -632,7 +632,9 @@ export async function runsListPage(ctx: Ctx, repo: Repo): Promise<Response> {
632632 "No run",
633633 kind === "agent"
634634 ? "Nothing open. A run is one go the crew takes at a job; each one shows up here."
635 : `Nothing open. Every ${kind === "deploy" ? "deploy" : "check"} shows up here while it runs.`,
635 : kind === "all"
636 ? "Nothing open. A run is one go the crew takes at a job; each one, and every check and deploy, shows up here."
637 : `Nothing open. Every ${kind === "deploy" ? "deploy" : "check"} shows up here while it runs.`,
636638 ),
637639 })
638640 : listCard(
@@ -650,15 +652,16 @@ export async function runsListPage(ctx: Ctx, repo: Repo): Promise<Response> {
650652 : icon(run.kind === "check" ? "check" : "rocket"),
651653 title: runTitleFrom(run, actors, issues),
652654 meta: html`${run.kind === "agent" ? html`${who} · ` : null}${info.note}
655 ${run.kind === "check" && durationText(run) !== undefined
656 ? html`· ${run.finishedAt === null ? "running for" : "took"} ${durationText(run)}`
657 : null}
653658 · ${time(run.finishedAt ?? run.createdAt)}`,
654659 trail: wordBadge(info.word, undefined, record === undefined),
655660 });
656661 }),
657662 );
658663 const last = fetched[fetched.length - 1];
659 const others = (["agent", "deploy", "check"] as const).filter(
660 (k) => k !== kind,
661 );
664 const kinds = ["all", "agent", "deploy", "check"] as const;
662665
663666 const body = html`${repoHeader(ctx, repo, "runs", { compact: true })}
664667 <div class="mt">
@@ -674,12 +677,14 @@ export async function runsListPage(ctx: Ctx, repo: Repo): Promise<Response> {
674677 : {},
675678 )}
676679 </div>
677 <p class="muted small mt">
678 Also ${others.map(
680 <p class="muted small mt" id="runs-kinds">
681 Show ${kinds.map(
679682 (k, i) =>
680 html`${i > 0 ? " · " : ""}<a href="${runsHref(base, k, undefined)}"
681 >${RUNS_KIND_WORDS[k]}</a
682 >`,
683 html`${i > 0 ? " · " : ""}${k === kind
684 ? html`<b>${RUNS_KIND_WORDS[k]}</b>`
685 : html`<a href="${runsHref(base, k, undefined)}"
686 >${RUNS_KIND_WORDS[k]}</a
687 >`}`,
683688 )}
684689 </p>
685690 ${liveMount({ repo: base })}`;
src/web/studio/run.ts +2
@@ -28,6 +28,7 @@ import { page } from "../layout.ts";
2828 import { btn, sha } from "../ui.ts";
2929 import { previewCard } from "../pages/apps.ts";
3030 import { costText, durationText, runTitle, runTokens } from "../pages/runs.ts";
31 import { checkSteps } from "./check_steps.ts";
3132 import { placementLine, sandboxLine } from "./sandbox.ts";
3233 import { logBox, runVoice, RUN_TRANSCRIPT_CAP } from "./log.ts";
3334 import { changeHref, tellHref } from "./nouns.ts";
@@ -220,6 +221,7 @@ export async function runView(
220221 </form>
221222 </div>`,
222223 )}
224 ${when(run.kind === "check" && !logHidden, () => checkSteps(lines, run.state))}
223225 ${when(pull, (p) => previewCard(ctx, repo, p))}
224226 ${when(
225227 logHidden,
src/web/style/content.ts +21
@@ -865,6 +865,27 @@ form.inline { display: inline; margin-left: auto; }
865865 .checks-line .ok { display: inline-flex; align-items: center; gap: 4px; color: var(--success); }
866866 .checks-line .bad { display: inline-flex; align-items: center; gap: 4px; color: var(--danger); }
867867 .checks-line .now { display: inline-flex; align-items: center; gap: 4px; color: var(--attn); }
868 /* A check's steps: three rows from the first paint, a bar of fixed height. */
869 .check-steps { margin-top: 12px; }
870 .check-step-list { list-style: none; margin: 0; padding: 0; border: 1px solid var(--border); border-radius: var(--radius); }
871 .check-step { display: grid; grid-template-columns: 1fr auto 5em; gap: 10px; padding: 8px 14px; min-height: 38px; align-items: center; }
872 .check-step + .check-step { border-top: 1px solid var(--border); }
873 .check-step .step-time { text-align: right; color: var(--faint); }
874 .check-step[data-state="ok"] .step-state { color: var(--success); }
875 .check-step[data-state="failed"] .step-state { color: var(--danger); }
876 .check-step[data-state="running"] .step-state { color: var(--attn); }
877 .check-step[data-state="waiting"], .check-step[data-state="skipped"], .check-step[data-state="none"] { color: var(--faint); }
878 .check-progress { margin-top: 10px; min-height: 64px; }
879 .check-bar { display: block; width: 100%; height: 8px; appearance: none; border: 0; border-radius: 4px; background: var(--muted); overflow: hidden; accent-color: var(--accent); }
880 .check-bar::-webkit-progress-bar { background: var(--muted); }
881 .check-bar::-webkit-progress-value { background: var(--accent); }
882 .check-bar::-moz-progress-bar { background: var(--accent); }
883 .check-progress-words { display: flex; justify-content: space-between; gap: 10px; margin-top: 4px; min-height: 1.4em; }
884 .check-now { min-height: 1.4em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
885 .check-failures { margin-top: 10px; }
886 .check-failure { border: 1px solid var(--danger); border-radius: var(--radius); margin-top: 6px; padding: 6px 12px; }
887 .check-failure summary { cursor: pointer; font-weight: 600; overflow-wrap: anywhere; }
888 .check-failure pre { margin: 6px 0 0; font-size: 12.5px; white-space: pre-wrap; overflow-wrap: anywhere; }
868889 /* A run, live: a transcript with a speaker column, bounded so the page
869890 head stays reachable, and a composer that sits under it. */
870891 .run-live { position: relative; margin-top: 12px; }
test/check-progress.test.ts +1 −1
@@ -16,7 +16,7 @@ const live = [
1616 ];
1717
1818 test("counts come from the runner's own lines, and only those", () => {
19 expect(parseShardProgress(live)).toEqual({ of: 170, files: 2, passed: 812, failed: 0 });
19 expect(parseShardProgress(live)).toEqual({ of: 170, files: 2, passed: 812, failed: 0, current: "c.test.ts" });
2020 expect(progressWords(parseShardProgress(live))).toBe("2 of 170 files · 812 passed, 0 failed");
2121 const batched = [
2222 "test-shards: 3 files in 2 shards",
test/check-steps.test.ts added +55
@@ -0,0 +1,55 @@
1 import { expect, test } from "bun:test";
2 import { checkSteps, pinnedFailures, stepLine } from "../src/checks/steps.ts";
3
4 const states = (lines: string[], run: Parameters<typeof checkSteps>[1]) =>
5 checkSteps(lines, run).map((s) => `${s.name}:${s.state}`);
6
7 test("all three steps are always there, and the first without a result is the one running", () => {
8 expect(states([], "running")).toEqual(["install:running", "typecheck:waiting", "tests:waiting"]);
9 const afterInstall = [stepLine("install", "ok", 4200), "$ bun run check"];
10 expect(states(afterInstall, "running")).toEqual(["install:ok", "typecheck:running", "tests:waiting"]);
11 expect(checkSteps(afterInstall, "running")[0]!.ms).toBe(4200);
12 const testing = [stepLine("install", "none", 0), stepLine("typecheck", "ok", 9000), "test-shards: 10 files in 2 shards"];
13 expect(states(testing, "running")).toEqual(["install:none", "typecheck:ok", "tests:running"]);
14 });
15
16 test("a red run marks the step it died in and leaves the rest not run", () => {
17 const tc = [stepLine("install", "ok", 100), stepLine("typecheck", "failed", 5000)];
18 expect(states(tc, "failed")).toEqual(["install:ok", "typecheck:failed", "tests:skipped"]);
19 const red = [stepLine("typecheck", "ok", 1), "test-shards: 3 files", stepLine("tests", "failed", 7000)];
20 expect(states(red, "failed")).toEqual(["install:ok", "typecheck:ok", "tests:failed"]);
21 // an older log with no markers: green is green, red dies in the first step it cannot clear
22 expect(states(["whatever"], "ok")).toEqual(["install:ok", "typecheck:ok", "tests:ok"]);
23 expect(states(["test-shards: 3 files"], "failed")).toEqual(["install:ok", "typecheck:ok", "tests:failed"]);
24 expect(checkSteps(["whatever"], "ok")[0]!.ms).toBeUndefined();
25 });
26
27 test("a failure pins once, with the first lines bun printed for it", () => {
28 const lines = [
29 "test-shards: 3 files in 1 shard",
30 "── shard 1/1: a.test.ts",
31 "a.test.ts:",
32 "(pass) fine [1ms]",
33 "error: expect(received).toBe(expected)",
34 "Expected: 1",
35 "Received: 2",
36 " at <anonymous> (a.test.ts:3:5)",
37 " at more (a.test.ts:4:5)",
38 "(fail) adds up [2ms]",
39 " 1 pass",
40 " 1 fail",
41 "(fail) adds up [shard 1]",
42 ];
43 expect(pinnedFailures(lines)).toEqual([
44 {
45 name: "adds up",
46 lines: [
47 "error: expect(received).toBe(expected)",
48 "Expected: 1",
49 "Received: 2",
50 " at <anonymous> (a.test.ts:3:5)",
51 ],
52 },
53 ]);
54 expect(pinnedFailures(["(pass) ok"])).toEqual([]);
55 });
test/studio-runs.test.ts +93
@@ -1967,3 +1967,96 @@ describe("a deploy that just landed is news on the front door", () => {
19671967 * as `canWrite` today — that every surface carrying money, the crew or the
19681968 * decision ledger must ask before it computes or renders one of those.
19691969 */
1970
1971 describe("a check's run page and the default runs list", () => {
1972 let dataDir: string;
1973 let app: App;
1974 let servers: Servers;
1975 let base: string;
1976 let cookie: string;
1977 let repo: Repo;
1978
1979 beforeAll(async () => {
1980 dataDir = await mkdtemp(join(tmpdir(), "forge-check-page-"));
1981 app = createApp({ dataDir, port: 0 });
1982 servers = await serve(app);
1983 base = servers.url;
1984 const a = await createUser(app.db, {
1985 trusted: true,
1986 username: "alice",
1987 email: "[email protected]",
1988 password: "a-good-passphrase",
1989 adminIfFirst: true,
1990 });
1991 if (!a.ok) throw new Error(a.error);
1992 const made = await createRepo(app, a.value, { name: "gauge", description: "x" });
1993 if (!made.ok) throw new Error(String(made.error));
1994 repo = made.value;
1995 cookie = (
1996 (
1997 await fetch(`${base}/signin`, {
1998 method: "POST",
1999 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
2000 redirect: "manual",
2001 })
2002 ).headers.get("set-cookie") ?? ""
2003 ).split(";")[0]!;
2004 });
2005 afterAll(async () => {
2006 servers.stop();
2007 app.close();
2008 await rm(dataDir, { recursive: true, force: true });
2009 });
2010
2011 const get = async (path: string) =>
2012 await (await fetch(`${base}${path}`, { headers: { cookie: `${cookie}; forge_mode=studio` } })).text();
2013
2014 test("the steps, the bar and the pinned failure are on the page; the log stays below", async () => {
2015 const run = createRun(app.db, { repoId: repo.id, kind: "check", env: "pull-7", reason: "push" });
2016 claimRun(app.db, run.id);
2017 for (const line of [
2018 "step install none 0",
2019 "$ gate",
2020 "step typecheck ok 3000",
2021 "test-shards: 10 files in 2 shards",
2022 "── shard 1/2: a.test.ts b.test.ts",
2023 "error: expect(received).toBe(expected)",
2024 "Expected: 1",
2025 "(fail) pinned name [1ms]",
2026 " 4 pass",
2027 " 1 fail",
2028 "── shard 1/2 done (exit 1, 2.0s)",
2029 "── shard 2/2: c.test.ts",
2030 ])
2031 appendRunLog(dataDir, run.id, line);
2032 const page = await get(`/alice/gauge/runs/${run.id}`);
2033 for (const name of ["install", "typecheck", "tests"]) expect(page).toContain(`<span class="step-name">${name}</span>`);
2034 expect(page).toContain('data-state="running"');
2035 expect(page).toContain("2 of 10 files started");
2036 expect(page).toContain("4 passed, 1 failed");
2037 expect(page).toContain("Running c.test.ts");
2038 const pinned = page.indexOf('id="run-failures"');
2039 expect(pinned).toBeGreaterThan(-1);
2040 expect(page).toContain("Expected: 1");
2041 expect(pinned).toBeLessThan(page.indexOf('id="run-log"'));
2042 });
2043
2044 test("a queued check already draws all three rows; an agent's run has none", async () => {
2045 const queued = createRun(app.db, { repoId: repo.id, kind: "check", env: "pull-8", reason: "push" });
2046 const page = await get(`/alice/gauge/runs/${queued.id}`);
2047 expect((page.match(/class="check-step"/g) ?? []).length).toBe(3);
2048 const agent = createRun(app.db, { repoId: repo.id, kind: "agent", reason: "assigned" });
2049 expect(await get(`/alice/gauge/runs/${agent.id}`)).not.toContain('id="run-steps"');
2050 });
2051
2052 test("the runs list holds checks, deploys and the crew's by default, with the three as filters", async () => {
2053 const all = await get("/alice/gauge/runs");
2054 expect(all).toContain("Check of");
2055 expect(all).toContain("at work");
2056 expect(all).toContain('href="/alice/gauge/runs?kind=check"');
2057 expect(all).toContain('href="/alice/gauge/runs?kind=agent"');
2058 const checks = await get("/alice/gauge/runs?kind=check");
2059 expect(checks).toContain("Check of");
2060 expect(checks).not.toContain("at work");
2061 });
2062 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs