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

The lane is visible: queue depth, the running check and its age, median duration and the time to clear, on the home and in /api/v1/health; the 30-minute card names the cause #1280

Closed opened this in answer to
Closed without merging

mason/forge:mason/1277-the-lane-is-visible-queue-depth-the-runn → main 5 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +1032 −32
README.md +17
@@ -334,6 +334,23 @@ Crew shows **Unsandboxed** with it, and every agent run's page says
334334 "Sandboxed" or "Unsandboxed" from what it was actually started with (runs
335335 from before this record say nothing).
336336
337 **Is it working?** The home's **At work** card answers, and the terminal's
338 dashboard shows the same lines above your repositories. For each of your apps
339 there is one row per crew run in flight (agent, issue or pull, what it is
340 doing, since when). When nothing is in flight, one line gives the reason:
341 `Crew: nobody is working — autonomy off | no crew | ceiling reached | waiting
342 for a crew slot | nothing ready`. A site admin also gets the check lane in one
343 line whenever a check waits or runs:
344 `Lane: 43 checks queued · running #1171 for 6 min · median 20 min · clears in ~15 h`.
345 Here `clears in` is how long the queue would take to drain if nothing new
346 arrived: the queued checks, plus what is left of the running ones, at the
347 median of the last twenty, spread over the lanes (Settings → Capacity,
348 *Checks at once*). When the queue has waited over thirty minutes, the same
349 line becomes one of the forge's own asks, with its cause and what would help.
350 To name the fix, label an open issue `lane`. The ask then links the oldest
351 such issue on the forge. With no such issue, it suggests more lanes.
352 `/api/v1/health` carries the same lane as `lane` for an admin.
353
337354 `docs/APPS.md` is the contract: the vocabulary, and the rules that are
338355 mechanical rather than advisory.
339356
docs/ARCHITECTURE.md +15 −4
@@ -601,10 +601,21 @@ platform's word, read from the read-only `forge-guard` ConfigMap mounted at
601601 `FORGE_GUARD_DIR` (default `/etc/forge-guard`, `kernel/guard.ts`): a `stuck`
602602 incident blocks, `held` holds, a view older than ten minutes is stale. A
603603 site admin, by session or any token scope, also gets `{ needs, disk, memory,
604 queue, stuck, apps, at }` (`kernel/vitals.ts`), and the board shows
605 `rollout blocked: <reason>` in its status line. `needs` is one sentence per thing off: disk under
606 10% free on the `FORGE_DATA` volume, a run running with a lapsed lease (or
607 past six hours), a queue whose oldest run has waited over thirty minutes.
604 queue, lane, stuck, apps, at }` (`kernel/vitals.ts`), and the board shows
605 `rollout blocked: <reason>` in its status line. `lane` is the check lane
606 (`kernel/lane.ts`): `{ queued, running: { repo, pull, branch, since },
607 lanes, medianMinutes, clearsInMinutes, line, cause, fix }`, the median over
608 the last twenty finished checks; its `line` is what the home's *At work*
609 card shows a site admin whenever a check waits or runs, and the terminal's
610 dashboard shows above the repositories (`crew/at_work.ts` makes both: the
611 lane for an admin, the crew's runs or why none runs on the viewer's apps).
612 `needs` is one
613 sentence per thing off: disk under 10% free on the `FORGE_DATA` volume, a
614 run running with a lapsed lease (or past six hours), a queue whose oldest
615 run has waited over thirty minutes. For the check queue that sentence is
616 the lane's line, its cause (how many lanes; checks running past the fast
617 tier's budget) and its lever: the oldest open issue labelled `lane`
618 anywhere on the forge, or else more lanes in Capacity.
608619 It is a fixed handful of queries however many runs and apps exist, measured
609620 per request and never cached. `/healthz` stays the orchestrator's answer.
610621
scripts/gate.ts +1
@@ -100,6 +100,7 @@ export const GATE: readonly string[] = [
100100 "test/suspended-hidden.test.ts",
101101 "test/verify-email.test.ts",
102102 "test/web.test.ts",
103 "test/tui-at-work.test.ts",
103104 "test/git-trust.test.ts",
104105 "test/helpers.test.ts",
105106 "test/shards.test.ts",
src/crew/at_work.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * What the forge is doing right now, for one viewer (#1277): the check
3 * lane in one line for a site admin (`kernel/lane.ts`), and for the apps
4 * the viewer can write, one entry per crew run in flight — or, when none
5 * is, why. Plain data; the web home's At work card and the terminal's
6 * dashboard both render this, so the gates and the words are made once.
7 */
8
9 import type { App } from "../app.ts";
10 import { crewForRepos } from "../core/agents.ts";
11 import { appsForRepos } from "../core/apps.ts";
12 import { getIssueById } from "../core/issues.ts";
13 import { listReposWritableTo, type Repo } from "../core/repos.ts";
14 import { listActiveRuns } from "../core/runs.ts";
15 import { getUsersByIds, type User } from "../core/users.ts";
16 import { laneLine, readLane, type Lane } from "../kernel/lane.ts";
17 import {
18 isPausedAtCeiling,
19 spentTodayEverywhere,
20 spentTodayForRepos,
21 } from "./autonomy.ts";
22 import type { RunReason } from "./brief.ts";
23
24 /** What a crew run is doing, by why it was started. */
25 export const DOING: Record<RunReason, string> = {
26 assigned: "working the issue",
27 feedback: "answering a review",
28 check_failed: "fixing a red check",
29 conflict: "bringing the branch up to date",
30 converge: "following main",
31 review: "reviewing the pull",
32 };
33
34 /** Why no crew member is working, when none is: the first that holds. */
35 export type IdleWhy =
36 | "autonomy off"
37 | "no crew"
38 | "ceiling reached"
39 | "waiting for a crew slot"
40 | "nothing ready";
41
42 /**
43 * `queued` is the agent runs ready to start — not those backing off
44 * (`not_before` still ahead), which wait for a time, not for a slot.
45 */
46 export function idleWhy(
47 app: App,
48 repos: readonly Repo[],
49 queued: number,
50 ): IdleWhy {
51 const on = repos.filter((r) => r.autonomy !== "off" && r.autonomyBy !== null);
52 if (on.length === 0) return "autonomy off";
53 const db = app.db;
54 const ids = on.map((r) => r.id);
55 const crew = crewForRepos(db, ids);
56 const manned = on.filter((r) => (crew.get(r.id)?.length ?? 0) > 0);
57 if (manned.length === 0) return "no crew";
58 const spent = spentTodayForRepos(db, ids);
59 const cap = app.config.crewCeilingUsd;
60 if (
outdated

Untested: ceiling reached, both the per-repo pause and the forge-wide crewCeilingUsd. Add a case in test/web.test.ts that seeds today's cost_usd on an agent run at or over the ceiling and expects Crew: nobody is working — ceiling reached.

61 manned.every((r) => isPausedAtCeiling(r, crew, spent)) ||
outdated

Untested, and queued counts runs held back by not_before, which are not waiting for a slot. Filter those out, and add a test where one queued agent run produces waiting for a crew slot.

62 (cap !== undefined && spentTodayEverywhere(db) >= cap)
outdated

Untested: nothing ready, one of the reasons the issue names. Add a test with autonomy on, a crew member assigned and nothing queued.

63 )
64 return "ceiling reached";
65 if (queued > 0) return "waiting for a crew slot";
66 return "nothing ready";
67 }
68
69 /** One crew run in flight. */
70 export interface CrewAtWork {
71 readonly runId: string;
72 readonly repo: Repo;
73 /** The agent's username, when the run names one. */
74 readonly agent: string | null;
75 readonly issue: { readonly number: number; readonly kind: "issue" | "pull" } | null;
76 readonly doing: string;
77 readonly since: string;
78 }
79
80 export interface AtWork {
81 /** `Lane: …` for a site admin while a check waits or runs; else null. */
82 readonly lane: string | null;
83 readonly crew: readonly CrewAtWork[];
84 /** Why nobody is working, when the viewer has apps and no run is in flight. */
85 readonly idle: IdleWhy | null;
86 }
87
88 /** Who works on what: `scout · square#12`. */
89 export function crewTitle(run: CrewAtWork): string {
90 const what =
91 run.issue === null ? run.repo.name : `${run.repo.name}#${run.issue.number}`;
92 return `${run.agent ?? "an agent"} · ${what}`;
93 }
94
95 /** The idle line, in words. */
96 export const idleWords = (why: IdleWhy): string =>
97 `Crew: nobody is working — ${why}`;
98
99 /**
100 * At work for `user`. The lane only for a site admin; the crew only on the
101 * apps `user` can write — the same set the home's shelf shows. `lane` is the
102 * one the caller already read (the vitals carry it), else it is read here.
103 */
104 export function atWork(
105 app: App,
106 user: User,
107 now: number,
108 lane?: Lane,
109 ): AtWork {
110 const db = app.db;
111 const line = user.isAdmin ? laneLine(lane ?? readLane(db, now), now) : null;
112 const writable = listReposWritableTo(db, user, { limit: 200 });
113 const records = appsForRepos(
114 db,
115 writable.map((r) => r.id),
116 );
117 const repos = writable.filter((r) => records.has(r.id));
118 if (repos.length === 0) return { lane: line, crew: [], idle: null };
119 const byId = new Map(repos.map((r) => [r.id, r]));
120 const active = listActiveRuns(
121 db,
122 repos.map((r) => r.id),
123 );
124 const running = active.filter((r) => r.state === "running");
125 const ready = active.filter(
126 (r) =>
127 r.state === "queued" &&
128 (r.notBefore === null || new Date(r.notBefore).getTime() <= now),
129 ).length;
130 const agents = getUsersByIds(
131 db,
132 running.map((r) => r.actorId).filter((id): id is string => id !== null),
133 );
134 const crew = running.map((run): CrewAtWork => {
135 const issue =
136 run.issueId === null ? undefined : getIssueById(db, run.issueId);
137 return {
138 runId: run.id,
139 repo: byId.get(run.repoId)!,
140 agent:
141 run.actorId === null ? null : (agents.get(run.actorId)?.username ?? null),
142 issue:
143 issue === undefined ? null : { number: issue.number, kind: issue.kind },
144 doing: DOING[run.reason as RunReason] ?? "working",
145 since: run.startedAt ?? run.createdAt,
146 };
147 });
148 return {
149 lane: line,
150 crew,
151 idle: crew.length === 0 ? idleWhy(app, repos, ready) : null,
152 };
153 }
src/http/server.ts +2
@@ -231,6 +231,7 @@ import {
231231 } from "../web/pages/runs.ts";
232232 import { lookImage } from "../web/pages/looks.ts";
233233 import { bigRedirect, boardPage } from "../web/pages/board.ts";
234 import { liveAtWorkFragment } from "../web/studio/at_work.ts";
234235 import { returnsPage } from "../web/pages/returns.ts";
235236 import {
236237 fleetGraphCsv,
@@ -596,6 +597,7 @@ export function buildRouter(): Router<Handler> {
596597 // fetches a region and not the page. Literal, above /:owner.
597598 router.add("GET", "/live/apps", liveAppsFragment);
598599 router.add("GET", "/live/on-you", liveOnYouFragment);
600 router.add("GET", "/live/at-work", liveAtWorkFragment);
599601 router.add("GET", "/live/feed", liveFeedFragment);
600602 // Whether a hostname is an app's verified domain — what Caddy's
601603 // `on_demand_tls { ask … }` asks before it fetches a certificate for a
src/kernel/lane.ts added +210
@@ -0,0 +1,210 @@
1 /**
2 * The check lane (#1277): how many checks wait, which one runs and for how
3 * long, how long a check takes lately, and when the queue would clear —
4 * the numbers a person needs to tell a slow forge from a stuck one, read
5 * from the run table in a fixed handful of queries. When the queue has
6 * waited too long the lane also says why (its cause) and what would help
7 * (its lever): an open issue labelled `lane` when one is, else more lanes.
8 *
9 * Plain data in, plain data out; `laneLine` and `laneCause` are the one
10 * place the words are made, so the home, the board and the health answer
11 * cannot word it differently.
12 */
13
14 import type { Database } from "bun:sqlite";
15 import { capacityCount } from "../core/capacity.ts";
16 import { FAST_BUDGET_SECONDS } from "../checks/tiers.ts";
17
18 /** How many finished checks the median is taken over. */
19 export const MEDIAN_OVER = 20;
20
21 /** The label that marks an open issue as the fix for a slow lane. */
22 export const LANE_LABEL = "lane";
23
24 export interface Lane {
25 readonly queued: number;
26 /** The oldest queued check's creation, when any waits. */
27 readonly oldest: string | null;
28 /** The longest-running check: its pull's number (null for a branch push), its branch, since when. */
29 readonly running: {
30 readonly repo: string;
31 readonly pull: number | null;
32 readonly branch: string;
33 readonly since: string;
34 } | null;
35 /** How many checks may run at once (`checks.concurrency`). */
36 readonly lanes: number;
37 /** Median wall-clock of the last `MEDIAN_OVER` finished checks; null before the first. */
38 readonly medianMinutes: number | null;
39 /** The queue and what runs, spread over the lanes at the median; null without a median. */
40 readonly clearsInMinutes: number | null;
41 }
42
43 /** An open issue that would make the lane faster, as a link names it. */
44 export interface LaneFix {
45 readonly repo: string;
46 readonly number: number;
47 readonly title: string;
48 }
49
50 function median(values: readonly number[]): number | null {
51 if (values.length === 0) return null;
52 const sorted = [...values].sort((a, b) => a - b);
53 const mid = sorted.length >> 1;
54 return sorted.length % 2 === 1
55 ? sorted[mid]!
56 : (sorted[mid - 1]! + sorted[mid]!) / 2;
57 }
58
59 /** The lane now. `queued` and `oldest` come from `queueDepth`'s check row when the caller has it. */
60 export function readLane(
61 db: Database,
62 now: number,
63 queue?: { queued: number; oldest: string } | undefined,
64 ): Lane {
65 const waiting =
66 queue ??
67 db
68 .query<{ queued: number; oldest: string | null }, [string]>(
69 `SELECT COUNT(*) AS queued, MIN(created_at) AS oldest FROM run
70 WHERE kind = 'check' AND state = 'queued'
71 AND (not_before IS NULL OR not_before <= ?1)`,
72 )
73 .get(new Date(now).toISOString()) ?? { queued: 0, oldest: null };
74 const running = db
75 .query<
76 {
77 slug: string;
78 number: number | null;
79 kind: string | null;
80 branch: string;
81 since: string;
82 },
83 []
84 >(
85 `SELECT user.username || '/' || repo.name AS slug, issue.number AS number,
86 issue.kind AS kind, run.branch AS branch,
87 COALESCE(run.started_at, run.created_at) AS since
88 FROM run
89 JOIN repo ON repo.id = run.repo_id
90 JOIN user ON user.id = repo.owner_id
91 LEFT JOIN issue ON issue.id = run.issue_id
92 WHERE run.kind = 'check' AND run.state = 'running'
93 ORDER BY since`,
94 )
95 .all();
96 const minutes = db
97 .query<{ m: number }, [number]>(
98 `SELECT (julianday(finished_at) - julianday(started_at)) * 1440 AS m
99 FROM run
100 WHERE kind = 'check' AND state IN ('ok','failed')
101 AND started_at IS NOT NULL AND finished_at IS NOT NULL
102 ORDER BY finished_at DESC LIMIT ?1`,
103 )
104 .all(MEDIAN_OVER)
105 .map((r) => r.m);
106 const lanes = capacityCount(db, "checks.concurrency", 1);
107 const mid = median(minutes);
108 const medianMinutes = mid === null ? null : Math.round(mid);
109 let clearsInMinutes: number | null = null;
110 if (mid !== null) {
111 const left = running.reduce(
112 (sum, r) =>
113 sum + Math.max(0, mid - (now - new Date(r.since).getTime()) / 60_000),
114 0,
115 );
116 clearsInMinutes = Math.round((waiting.queued * mid + left) / lanes);
117 }
118 const first = running[0];
119 return {
120 queued: waiting.queued,
121 oldest: waiting.queued > 0 ? waiting.oldest : null,
122 running:
123 first === undefined
124 ? null
125 : {
126 repo: first.slug,
127 pull: first.kind === "pull" ? first.number : null,
128 branch: first.branch,
129 since: first.since,
130 },
131 lanes,
132 medianMinutes,
133 clearsInMinutes,
134 };
135 }
136
137 /** The oldest open issue labelled `lane`, anywhere on the forge — the fix the card links. */
138 export function laneFix(db: Database): LaneFix | null {
139 const row = db
140 .query<{ slug: string; number: number; title: string }, [string]>(
141 `SELECT user.username || '/' || repo.name AS slug, issue.number AS number,
142 issue.title AS title
143 FROM issue
144 JOIN issue_label ON issue_label.issue_id = issue.id
145 JOIN label ON label.id = issue_label.label_id AND label.name = ?1 COLLATE NOCASE
146 JOIN repo ON repo.id = issue.repo_id
147 JOIN user ON user.id = repo.owner_id
148 WHERE issue.state = 'open'
149 ORDER BY issue.created_at LIMIT 1`,
150 )
151 .get(LANE_LABEL);
152 return row === null
153 ? null
154 : { repo: row.slug, number: row.number, title: row.title };
155 }
156
157 /** Minutes as a person reads a wait: `6 min` under the hour, `~15 h` over it. */
158 export function spanWords(minutes: number): string {
159 return minutes < 60
160 ? `${Math.max(0, Math.round(minutes))} min`
161 : `~${Math.round(minutes / 60)} h`;
162 }
163
164 /**
165 * The lane in one line, or null when nothing waits and nothing runs:
166 * `Lane: 43 checks queued · running #1171 for 6 min · median 20 min · clears in ~15 h`.
outdated

With the numbers in this example, the test in vitals.test.ts gets clears in ~15 h (874 min). Make the doc example match.

167 */
168 export function laneLine(lane: Lane, now: number): string | null {
169 if (lane.queued === 0 && lane.running === null) return null;
170 const parts = [
171 `${lane.queued} check${lane.queued === 1 ? "" : "s"} queued`,
172 ];
173 if (lane.running !== null) {
174 const age = (now - new Date(lane.running.since).getTime()) / 60_000;
175 const what =
176 lane.running.pull === null
177 ? lane.running.branch || lane.running.repo
178 : `#${lane.running.pull}`;
179 parts.push(`running ${what} for ${spanWords(age)}`);
180 }
181 if (lane.medianMinutes !== null)
182 parts.push(`median ${spanWords(lane.medianMinutes)}`);
183 if (lane.clearsInMinutes !== null)
184 parts.push(
185 `clears in ${lane.clearsInMinutes < 60 ? "~" : ""}${spanWords(lane.clearsInMinutes)}`,
186 );
187 return `Lane: ${parts.join(" · ")}`;
188 }
189
190 /**
191 * Why the lane is slow, from what the forge knows without reading git:
192 * how many lanes there are, and whether checks run longer than the fast
193 * tier's budget — the sign that pulls are getting the full gate.
194 */
195 export function laneCause(lane: Lane): string {
196 const causes = [lane.lanes === 1 ? "one lane" : `${lane.lanes} lanes`];
197 const budget = FAST_BUDGET_SECONDS / 60;
198 if (lane.medianMinutes !== null && lane.medianMinutes > budget)
199 causes.push(
200 `checks run the full gate (median ${spanWords(lane.medianMinutes)}, the fast tier's budget is ${budget} min)`,
201 );
202 return causes.join("; ");
203 }
204
205 /** What would help, in words: the open fix when there is one, else more lanes. */
206 export function laneLever(fix: LaneFix | null): string {
207 return fix === null
208 ? "more lanes: raise Checks at once in Capacity"
209 : `${fix.repo}#${fix.number} ${fix.title}`;
210 }
src/kernel/vitals.ts +41 −5
@@ -3,9 +3,10 @@
33 * a person now is a need; a setting that is not the default is a note on its
44 * own page (`web/pages/capacity.ts`), never here. Plain data in,
55 * plain data out — the disk under `FORGE_DATA`, this process's memory, the
6 * queue, runs that stopped making progress, and how many apps are serving,
7 * asleep or previewed. A fixed handful of queries however many runs and
8 * apps there are; nothing is cached, nothing shelled out.
6 * queue and the check lane in it (`lane.ts`), runs that stopped making
7 * progress, and how many apps are serving, asleep or previewed. A fixed
8 * handful of queries however many runs and apps there are; nothing is
9 * cached, nothing shelled out.
910 */
1011
1112 import type { Database } from "bun:sqlite";
@@ -14,6 +15,15 @@ import { freemem, totalmem } from "node:os";
1415 import { recentErrors, type ErrorLine } from "./log.ts";
1516 import { leaseLapsed, listRunning, queueDepth } from "../core/runs.ts";
1617 import { STALE_AFTER_MS } from "../runs/lease.ts";
18 import {
19 laneCause,
20 laneFix,
21 laneLever,
22 laneLine,
23 readLane,
24 type Lane,
25 type LaneFix,
26 } from "./lane.ts";
1727
1828 /** Free disk under this share of the volume is something to say. */
1929 export const DISK_FREE_MIN = 0.1;
@@ -39,6 +49,15 @@ export interface Vitals {
3949 hostTotalBytes: number;
4050 };
4151 readonly queue: Record<string, number>;
52 /**
53 * The check lane (`kernel/lane.ts`) and its line; once the queue has
54 * waited over `QUEUE_WAIT_MAX_MS`, its cause and the open fix too.
55 */
56 readonly lane: Lane & {
57 line: string | null;
58 cause: string | null;
59 fix: LaneFix | null;
60 };
4261 readonly stuck: {
4362 runId: string;
4463 repo: string;
@@ -74,9 +93,25 @@ export function vitals(input: VitalsInput): Vitals {
7493 );
7594
7695 const queue: Record<string, number> = {};
77 for (const row of queueDepth(input.db, now)) {
96 const depth = queueDepth(input.db, now);
97 const lane = readLane(
98 input.db,
99 now,
100 depth.find((row) => row.kind === "check") ?? { queued: 0, oldest: "" },
101 );
102 const line = laneLine(lane, now);
103 let cause: string | null = null;
104 let fix: LaneFix | null = null;
105 for (const row of depth) {
78106 queue[row.kind] = row.queued;
79 if (now - new Date(row.oldest).getTime() > QUEUE_WAIT_MAX_MS)
107 if (now - new Date(row.oldest).getTime() <= QUEUE_WAIT_MAX_MS) continue;
108 if (row.kind === "check" && line !== null) {
109 // The check queue says how deep it is, why, and what would help —
110 // never only that it is old.
111 cause = laneCause(lane);
112 fix = laneFix(input.db);
113 needs.push(`${line} — ${cause} — ${laneLever(fix)}`);
114 } else
80115 needs.push(
81116 `The ${row.kind} queue has waited over ${QUEUE_WAIT_MAX_MS / 60_000} minutes.`,
82117 );
@@ -121,6 +156,7 @@ export function vitals(input: VitalsInput): Vitals {
121156 hostTotalBytes: totalmem(),
122157 },
123158 queue,
159 lane: { ...lane, line, cause, fix },
124160 stuck,
125161 apps,
126162 errors: { lastHour: seen.lastHour, latest: seen.latest },
src/tui/screens/dashboard.ts +45 −1
@@ -12,9 +12,16 @@
1212 * Every card here is a **pane**: a thing with a cursor, that `tab` moves
1313 * between, that `enter` opens from, and that a click lands in. That is the
1414 * whole of this screen's design.
15 *
16 * Above the repositories, a few lines of what is at work (#1277): the
17 * check lane for a site admin, the crew's runs on your apps or why none
18 * runs — `crew/at_work.ts`, the same data and gates as the web home's
19 * At work card.
1520 */
1621
1722 import { mayView } from "../../core/sealed.ts";
23 import { atWork, crewTitle, idleWords, type AtWork } from "../../crew/at_work.ts";
24 import { spanWords } from "../../kernel/lane.ts";
1825 import { pinRepo, unpinRepo } from "../../actions/origins.ts";
1926 import { listAssignedTo, type Issue } from "../../core/issues.ts";
2027 import { listPins, pinnedRepoIds, type Pin } from "../../core/pins.ts";
@@ -88,6 +95,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
8895 let pins: Pin[] = [];
8996 let pinned = new Set<string>();
9097 let onYou: OnYouItem[] = [];
98 let working: string[] = [];
9199 const filter = new Filter();
92100 /** One cursor per pane: moving in one must never move another. */
93101 const cursors: Record<PaneId, ListState> = {
@@ -104,6 +112,8 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
104112 pinned = f.user ? pinnedRepoIds(f.db, f.user.id) : new Set<string>();
105113 all = listReposVisibleTo(f.db, f.user, { limit: 200 });
106114 onYou = assignedToMe();
115 const now = Date.now();
116 working = f.user ? atWorkLines(atWork(f.app, f.user, now), now) : [];
107117 // "Yours" is ownership plus the orgs you are on a team of; typing in the
108118 // filter reaches every repository you can see.
109119 const orgs = f.user
@@ -276,8 +286,13 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
276286 drawn = here;
277287 if (!here.has(focus)) focus = "repos";
278288
279 const [box, list] = split(main, "v", [len(1), fill(1)]);
289 const [box, at, list] = split(main, "v", [
290 len(1),
291 len(working.length),
292 fill(1),
293 ]);
280294 ctx.setCursor(filter.render(s, box!, c, "find a repository"));
295 drawWorking(s, at!, c);
281296 drawRepos(s, list!, c, set);
282297 if (aside === undefined) return;
283298 if (!f.signedIn) {
@@ -347,6 +362,19 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
347362
348363 // ---- the panes ----
349364
365 /** What is at work, one plain line each; the lane, when shown, first. */
366 function drawWorking(s: Surface, r: Rect, c: Tokens): void {
367 working.slice(0, r.h).forEach((line, i) =>
368 s.text(
369 r.x,
370 r.y + i,
371 truncate(line, r.w),
372 style(line.startsWith("Lane:") ? c.fg : c.mutedFg, c.bg),
373 r.x + r.w,
374 ),
375 );
376 }
377
350378 /** The inbox: what is assigned to this account, across every repository. */
351379 function drawOnYou(s: Surface, r: Rect, c: Tokens, set: IconSet): void {
352380 const on = focus === "onyou";
@@ -497,6 +525,22 @@ function repoMark(isPinned: boolean, set: IconSet): string {
497525 return isPinned ? `${PIN_MARK} ` : "";
498526 }
499527
528 /** The crew rows a dashboard shows before it says how many more. */
529 const CREW_SHOWN = 3;
530
531 /** At work as the dashboard's lines: the lane, then each crew run, or why none. */
532 export function atWorkLines(w: AtWork, now: number): string[] {
533 const lines = w.lane === null ? [] : [w.lane];
534 for (const run of w.crew.slice(0, CREW_SHOWN)) {
535 const age = (now - new Date(run.since).getTime()) / 60_000;
536 lines.push(`${crewTitle(run)} · ${run.doing} · for ${spanWords(age)}`);
537 }
538 if (w.crew.length > CREW_SHOWN)
539 lines.push(`and ${w.crew.length - CREW_SHOWN} more at work`);
540 if (w.idle !== null) lines.push(idleWords(w.idle));
541 return lines;
542 }
543
500544 /** Plain lines in a card — what a pane says when it has no rows. */
501545 function note(s: Surface, r: Rect, c: Tokens, lines: readonly string[]): void {
502546 lines
src/web/pages/board.ts +5 −1
@@ -303,8 +303,12 @@ export function bigRedirect(ctx: Ctx): Response {
303303
304304 // ---- the forge ----
305305
306 /** Where a need can be acted on, when it can: a stuck run's page. */
306 /** Where a need can be acted on, when it can: a stuck run's page, or the slow lane's lever. */
307307 function needHref(need: string, v: Vitals): string | undefined {
308 if (v.lane.line !== null && need.startsWith(v.lane.line))
309 return v.lane.fix === null
310 ? "/settings/capacity"
311 : `/${v.lane.fix.repo}/issues/${v.lane.fix.number}`;
308312 if (/ stuck\.$/.test(need) && v.stuck[0] !== undefined)
309313 return `/${v.stuck[0].repo}/runs/${v.stuck[0].runId}`;
310314 return undefined;
src/web/studio/asks.ts +13 −7
@@ -49,7 +49,7 @@ import { CHECK_FAILED_LIMIT } from "../../crew/dispatch.ts";
4949 import { isStalePull, mergesAgainSince } from "../../crew/stale_asks.ts";
5050 import { waitsForPerson, type ReviewWait } from "../../crew/review.ts";
5151 import type { Ctx } from "../../http/context.ts";
52 import { vitals } from "../../kernel/vitals.ts";
52 import { vitals, type Vitals } from "../../kernel/vitals.ts";
5353 import { repoBase } from "../chrome.ts";
5454 import { html, when, type Html } from "../html.ts";
5555 import { btn, card, icon, row } from "../ui.ts";
@@ -933,12 +933,13 @@ export function decisionActions(ctx: Ctx, d: Decision): Html {
933933 }
934934
935935 /**
936 * What the forge itself needs, for a site admin: each sentence of the
937 * health answer (`/api/v1/health`) as one ask. Anyone else gets none — the
938 * forge's standing is the admin's to read and nobody else's to know about.
936 * The forge's standing, for a site admin: the health answer
937 * (`/api/v1/health`) whose needs are each one ask. Anyone else gets none —
938 * the forge's standing is the admin's to read and nobody else's to know
939 * about.
939940 */
940 export function forgeNeedsFor(ctx: Ctx, user: User | undefined): string[] {
941 if (!user?.isAdmin) return [];
941 export function forgeVitalsFor(ctx: Ctx, user: User | undefined): Vitals | undefined {
942 if (!user?.isAdmin) return undefined;
942943 const runtime = appsRuntime(ctx.app);
943944 const envs = runtime
944945 ? listApps(ctx.app.db).flatMap((record) => runtime.status(record))
@@ -947,7 +948,12 @@ export function forgeNeedsFor(ctx: Ctx, user: User | undefined): string[] {
947948 db: ctx.app.db,
948949 dataDir: ctx.app.config.dataDir,
949950 envs,
950 }).needs;
951 });
952 }
953
954 /** What the forge itself needs, for a site admin: each sentence of its vitals. */
955 export function forgeNeedsFor(ctx: Ctx, user: User | undefined): string[] {
956 return forgeVitalsFor(ctx, user)?.needs ?? [];
951957 }
952958
953959 /**
src/web/studio/asks_page.ts +47 −6
@@ -33,12 +33,14 @@ import {
3333 decisionActions,
3434 decisionForm,
3535 decisionsFor,
36 forgeNeedsFor,
36 forgeVitalsFor,
3737 type AskRow,
3838 type Consequence,
3939 type Decision,
4040 } from "./asks.ts";
4141 import { changeHref } from "./nouns.ts";
42 import type { Lane } from "../../kernel/lane.ts";
43 import type { Vitals } from "../../kernel/vitals.ts";
4244
4345 /** The kinds a bulk action takes: a ceiling and a planner's decline are decided where they live. */
4446 const BULK_KINDS: ReadonlySet<Decision["kind"]> = new Set(["look", "review", "stopped", "parked"]);
@@ -178,6 +180,42 @@ const forgeCard = (sentence: string): Html =>
178180 ${btn("Health", { href: "/api/v1/health", size: "sm" })}`,
179181 });
180182
183 /**
184 * The check queue's need, as its own card (#1277): the lane in one line,
185 * why it is slow, and the lever — the open issue labelled `lane` that
186 * would fix it, or the capacity setting that adds a lane.
187 */
188 function laneCard(lane: Vitals["lane"]): Html {
189 const lever =
190 lane.fix === null
191 ? html`<a href="/settings/capacity">more lanes: raise Checks at once</a>`
192 : html`<a href="/${lane.fix.repo}/issues/${lane.fix.number}"
193 >#${lane.fix.number} ${lane.fix.title}</a
194 >`;
195 return card(
196 html`<p>${lane.line}</p>
197 <p class="small">Why: ${lane.cause}. What would help: ${lever}.</p>`,
198 {
199 tone: "danger",
200 id: "lane-card",
201 head: html`${icon("activity")}
202 <h2>The check lane</h2>
203 <span class="spacer"></span>
204 ${btn("Health", { href: "/api/v1/health", size: "sm" })}`,
205 },
206 );
207 }
208
209 /** One card per thing the forge needs; the check lane's is its own. */
210 function forgeCards(v: Vitals | undefined): Html[] {
211 if (v === undefined) return [];
212 return v.needs.map((need) =>
213 v.lane.cause !== null && v.lane.line !== null && need.startsWith(v.lane.line)
214 ? laneCard(v.lane)
215 : forgeCard(need),
216 );
217 }
218
181219 /** What sits above the asks after a bulk step: a preview to confirm, a receipt, or why nothing was done. */
182220 export interface AsksTop {
183221 readonly banner: Html;
@@ -206,24 +244,27 @@ export function homeTop(ctx: Ctx): AsksTop | undefined {
206244 /** What needs you, as the home's pinned section: what asks you, with a
207245 * bulk step's preview or receipt on top. Nothing on screen when nothing
208246 * asks — the header's Asks link says so — but the sentence stays for a
209 * screen reader. */
247 * screen reader. The lane its vitals read comes back too, for the At work
248 * card beside it, so the home reads the lane once. */
210249 export function needsYouSection(
211250 ctx: Ctx,
212251 user: User,
213252 top?: AsksTop,
214 ): { body: Html; scriptJs: string } {
253 ): { body: Html; scriptJs: string; lane: Lane | undefined } {
215254 const picked = top?.picked ?? new Set<string>();
216255 const decisions = decisionsFor(
217256 ctx,
218257 listReposVisibleTo(ctx.app.db, user, { limit: 200 }),
219258 );
220 const needs = forgeNeedsFor(ctx, user);
259 const forge = forgeVitalsFor(ctx, user);
260 const needs = forge?.needs ?? [];
221261 const rows = askRows(decisions);
222262 const count = rows.length + needs.length;
223263 if (count === 0 && top === undefined)
224264 return {
225265 body: html`<h2 id="asks-sentence" class="sr-only">${askSentence(0)}</h2>`,
226266 scriptJs: "",
267 lane: forge?.lane,
227268 };
228269 // The forge's own health first, then the few asks that matter most;
229270 // the rest are one tap away, in the same order. A phone shows fewer
@@ -248,7 +289,7 @@ export function needsYouSection(
248289 const body = html`<section id="needs-you" class="needs-you stack">
249290 <h2 id="asks-sentence">${askSentence(count)}</h2>
250291 ${top?.banner ?? null}
251 ${needs.map(forgeCard)} ${first.map((r) => rowCard(ctx, r, picked))}
292 ${forgeCards(forge)} ${first.map((r) => rowCard(ctx, r, picked))}
252293 ${middle.length === 0
253294 ? null
254295 : more(
@@ -270,7 +311,7 @@ export function needsYouSection(
270311 </form>`}
271312 ${decisions.map((d) => decisionForm(d))}
272313 </section>`;
273 return { body, scriptJs: pickable < 2 ? "" : SELECT_ALL_JS };
314 return { body, scriptJs: pickable < 2 ? "" : SELECT_ALL_JS, lane: forge?.lane };
274315 }
275316
276317 /** The home with a bulk step's preview or receipt on top of what needs
src/web/studio/at_work.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * At work (#1277): what the forge is doing right now, on the home — the
3 * check lane for a site admin, the crew's runs in flight on the viewer's
4 * apps, or why none is (`crew/at_work.ts` decides who sees what and words
5 * it; the terminal's dashboard renders the same data). A live region with
6 * an address of its own (`GET /live/at-work`), so a run starting or
7 * finishing redraws this and nothing else.
8 */
9
10 import {
11 atWork,
12 crewTitle,
13 idleWords,
14 type CrewAtWork,
15 } from "../../crew/at_work.ts";
16 import type { User } from "../../core/users.ts";
17 import type { Ctx } from "../../http/context.ts";
18 import type { Lane } from "../../kernel/lane.ts";
19 import { repoBase } from "../chrome.ts";
20 import { html, type Html } from "../html.ts";
21 import { fragment } from "../layout.ts";
22 import { icon, listCard, row, time } from "../ui.ts";
23 import { changeHref, tellHref } from "./nouns.ts";
24
25 /** The events that can change what is at work. */
26 const AT_WORK_LIVE = "run.*";
27
28 function crewRow(run: CrewAtWork): Html {
29 const base = repoBase(run.repo);
30 const href =
31 run.issue === null
32 ? `${base}/runs/${run.runId}`
33 : run.issue.kind === "pull"
34 ? changeHref(base, run.issue.number)
35 : tellHref(base, run.issue.number);
36 return row({
37 href,
38 lead: icon("activity"),
39 title: html`${crewTitle(run)}`,
40 meta: html`${run.doing}`,
41 trail: html`since ${time(run.since)}`,
42 });
43 }
44
45 /** The card's body, or null when there is nothing to say to this viewer. */
46 export function atWorkCard(ctx: Ctx, user: User, lane?: Lane): Html | null {
47 const now = atWork(ctx.app, user, Date.now(), lane);
48 const rows: Html[] = [];
49 if (now.lane !== null)
50 rows.push(html`<li class="row" id="lane-line">
51 <span class="row-lead">${icon("activity")}</span>
52 <span class="row-main"><span class="row-title">${now.lane}</span></span>
53 </li>`);
54 for (const run of now.crew) rows.push(crewRow(run));
55 if (now.idle !== null)
56 rows.push(html`<li class="row" id="crew-idle">
57 <span class="row-main"
58 ><span class="row-title muted">${idleWords(now.idle)}</span></span
59 >
60 </li>`);
61 if (rows.length === 0) return null;
62 return listCard(rows, {
63 head: html`${icon("activity")}
64 <h2>At work</h2>`,
65 extra: "at-work",
66 });
67 }
68
69 /** The region; `lane` is the one the home's vitals already read, when it has them. */
70 export const atWorkRegion = (ctx: Ctx, user: User, lane?: Lane): Html =>
71 html`<div id="live-at-work" data-live="${AT_WORK_LIVE}" data-live-src="/live/at-work">
72 ${atWorkCard(ctx, user, lane)}
73 </div>`;
74
75 // GET /live/at-work — the lane and the crew alone, for the region that shows them.
76 export function liveAtWorkFragment(ctx: Ctx): Response {
77 const user = ctx.auth.user;
78 if (!user) return fragment(html``, { status: 404 });
79 return fragment(atWorkRegion(ctx, user), { request: ctx.request });
80 }
src/web/studio/home.ts +2 −1
@@ -49,6 +49,7 @@ import { needsYouSection, type AsksTop } from "./asks_page.ts";
4949 import { composer, feedJs, feedNote, feedRegion } from "./feed.ts";
5050 import { homeTabs } from "./home_tabs.ts";
5151 import { crewKeyNote } from "./crew.ts";
52 import { atWorkRegion } from "./at_work.ts";
5253 import { everydayCard } from "../pages/everyday.ts";
5354 import { nextStepsCard } from "../pages/next-steps.ts";
5455 import { spawnedOrg } from "../../spawn/claim.ts";
@@ -182,7 +183,7 @@ export async function studioHome(
182183 ${homeTabs("feed")}
183184 <div class="dash">
184185 <div class="dash-main stack">
185 ${needsYou.body} ${composer(ctx, user)}
186 ${needsYou.body} ${atWorkRegion(ctx, user, needsYou.lane)} ${composer(ctx, user)}
186187 <div class="bar feed-head">
187188 <span class="spacer"></span>
188189 <a class="small muted" href="/asked">What you asked for</a>
test/asks.test.ts +5 −2
@@ -158,11 +158,14 @@ describe("the asks page", () => {
158158 .query("UPDATE run SET created_at = ?1 WHERE state = 'queued'")
159159 .run(new Date(Date.now() - 3 * 3_600_000).toISOString());
160160 const admin = await get(alice, "/");
161 expect(admin).toContain("queue has waited over");
161 // The check queue's card is the lane: its line, why, and what would help.
162 expect(admin).toContain('id="lane-card"');
163 expect(admin).toContain("Lane: ");
164 expect(admin).toContain("Why: one lane");
162165 expect(sentence(admin)).toBe("2 things need you");
163166 expect(headerCount(admin)).toBe(2);
164167 const other = await get(bob, "/");
165 expect(other).not.toContain("queue has waited");
168 expect(other).not.toContain("Lane: ");
166169 expect(sentence(other)).toBe("All fine");
167170 });
168171
test/board.test.ts +27 −2
@@ -14,9 +14,9 @@ import { createApp, type App } from "../src/app.ts";
1414 import { changeCapacity } from "../src/actions/capacity.ts";
1515 import { enableApp } from "../src/actions/apps.ts";
1616 import { addToCrew, createAgent } from "../src/actions/crew.ts";
17 import { openIssue } from "../src/actions/issues.ts";
17 import { openIssue, setIssueLabels } from "../src/actions/issues.ts";
1818 import { mergePull, openPull } from "../src/actions/pulls.ts";
19 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
19 import { commitToBranch, createLabel, createRepo } from "../src/actions/repos.ts";
2020 import { getAppByRepo } from "../src/core/apps.ts";
2121 import { recordDecision } from "../src/core/decisions.ts";
2222 import { recordLook } from "../src/core/looks.ts";
@@ -476,6 +476,31 @@ describe("the board's forge strip", () => {
476476 }
477477 });
478478
479 test("a slow lane links its lever: Capacity, or the open issue labelled lane", async () => {
480 const made = await createRepo(app, admin, { name: "slow" });
481 if (!made.ok) throw new Error(String(made.error));
482 const check = createRun(app.db, { repoId: made.value.id, kind: "check" });
483 // Queued past the thirty minutes the forge allows a wait.
484 app.db
485 .query("UPDATE run SET created_at = ?2 WHERE id = ?1")
486 .run(check.id, new Date(Date.now() - 40 * 60_000).toISOString());
487 try {
488 expect(await board("root")).toContain(
489 'class="board-forge-need" href="/settings/capacity">Lane: 1 check queued',
490 );
491 const label = createLabel(app, admin, made.value, "lane", "cc0000");
492 if (!label.ok) throw new Error(String(label.error));
493 const issue = openIssue(app, admin, made.value, { title: "More lanes" });
494 if (!issue.ok) throw new Error(String(issue.error));
495 expect(setIssueLabels(app, admin, made.value, issue.value, ["lane"]).ok).toBe(true);
496 expect(await board("root")).toContain(
497 `class="board-forge-need" href="/root/slow/issues/${issue.value.number}">Lane: 1 check queued`,
498 );
499 } finally {
500 app.db.query("UPDATE run SET state = 'failed' WHERE id = ?1").run(check.id);
501 }
502 });
503
479504 test("a blocked rollout shows in the status line, escaped, for an admin only", async () => {
480505 const guard = mkdtempSync(join(tmpdir(), "forge-board-guard-"));
481506 process.env["FORGE_GUARD_DIR"] = guard;
test/tui-at-work.test.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * The terminal's dashboard says what is at work (#1277), with the web home's
3 * gates: the check lane to a site admin only, the crew's runs (or why none
4 * runs) on the apps the viewer can write.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { newApp } from "../src/actions/apps.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { getRepoById } from "../src/core/repos.ts";
15 import { createRun } from "../src/core/runs.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { headlessTerminal } from "../src/tui/term/terminal.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { settleApp } from "./helpers/tui.ts";
21
22 quietLogs();
23
24 describe("at work on the terminal's dashboard", () => {
25 let dataDir: string;
26 let forge: App;
27 let alice: User;
28 let carol: User;
29 let repoId = "";
30
31 /** The dashboard as `user` first sees it. */
32 const dashboard = async (user: User): Promise<string> => {
33 const { app } = createForgeApp(
34 forge,
35 { sshUsername: user.username, remoteAddress: "127.0.0.1", user },
36 { terminal: headlessTerminal(140, 30), exitHooks: false },
37 );
38 app.start();
39 try {
40 await settleApp(app);
41 return app.screen.toText();
42 } finally {
43 app.stop();
44 }
45 };
46
47 beforeAll(async () => {
48 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-at-work-"));
49 forge = createApp({ dataDir, port: 0 });
50 for (const [username, first] of [
51 ["alice", true],
52 ["carol", false],
53 ] as const) {
54 const made = await createUser(forge.db, {
55 trusted: true,
56 username,
57 email: `${username}@forge.local`,
58 password: "a-good-passphrase",
59 adminIfFirst: first,
60 });
61 if (!made.ok) throw new Error(made.error);
62 if (username === "alice") alice = made.value;
63 else carol = made.value;
64 }
65 const made = await newApp(forge, alice, { name: "square", visibility: "public" });
66 if (!made.ok) throw new Error(String(made.error));
67 repoId = made.value.app.repoId;
68 });
69
70 afterAll(async () => {
71 forge.close();
72 await rm(dataDir, { recursive: true, force: true });
73 });
74
75 test("with nothing running, the crew's line says why — to whoever has apps", async () => {
76 expect(await dashboard(alice)).toContain(
77 "Crew: nobody is working — autonomy off",
78 );
79 // Carol has no apps of her own; alice's public app is not hers to watch.
80 expect(await dashboard(carol)).not.toContain("Crew:");
81 });
82
83 test("the lane is a line for a site admin, and nobody else", async () => {
84 const running = createRun(forge.db, { repoId, kind: "check", branch: "main" });
85 forge.db
86 .query("UPDATE run SET state = 'running', started_at = ?2 WHERE id = ?1")
87 .run(running.id, new Date(Date.now() - 6 * 60_000).toISOString());
88 for (let i = 0; i < 2; i++) createRun(forge.db, { repoId, kind: "check" });
89 expect(await dashboard(alice)).toContain(
90 "Lane: 2 checks queued · running main for 6 min",
91 );
92 expect(await dashboard(carol)).not.toContain("Lane:");
93 });
94
95 test("a crew run in flight is a line: agent, issue, what it is doing, for how long", async () => {
96 const issue = openIssue(forge, alice, getRepoById(forge.db, repoId)!, {
97 title: "Make it square",
98 });
99 if (!issue.ok) throw new Error(String(issue.error));
100 const run = createRun(forge.db, {
101 repoId,
102 kind: "agent",
103 issueId: issue.value.id,
104 actorId: alice.id,
105 reason: "assigned",
106 });
107 forge.db
108 .query("UPDATE run SET state = 'running', started_at = ?2 WHERE id = ?1")
109 .run(run.id, new Date(Date.now() - 3 * 60_000).toISOString());
110 const text = await dashboard(alice);
111 expect(text).toContain(
112 `alice · square#${issue.value.number} · working the issue · for 3 min`,
113 );
114 expect(text).not.toContain("nobody is working");
115 expect(await dashboard(carol)).not.toContain("square#");
116 });
117 });
test/vitals.test.ts +113 −3
@@ -81,7 +81,7 @@ test("a site admin with a read-only token gets the shape; others get the short o
8181 expect(Object.keys(v).sort()).toEqual(
8282 [
8383 "apps", "at", "checkedAt", "commit", "disk", "draining", "errors",
84 "incidents", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck",
84 "incidents", "lane", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck",
8585 "version",
8686 ].sort(),
8787 );
@@ -148,8 +148,9 @@ test("the number of queries does not grow with runs", () => {
148148 if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id);
149149 }
150150 expect(count()).toBe(before);
151 // The queue and the running runs.
152 expect(before).toBe(2);
151 // The queue, the running runs, and the lane: its running checks, the
152 // last twenty finished, and how many lanes there are.
153 expect(before).toBe(5);
153154 });
154155
155156 test("errors are counted, bounded, redacted, and a burst is said", async () => {
@@ -183,3 +184,112 @@ test("errors are counted, bounded, redacted, and a burst is said", async () => {
183184 clearErrors();
184185 }
185186 });
187
188 /** A forge of its own with one pull, for the lane: nothing else queued there. */
189 async function laneForge() {
190 const dir = await mkdtemp(join(tmpdir(), "forge-lane-"));
191 const forge = createApp({ dataDir: dir, port: 0 });
192 const owner = "lane-owner";
193 forge.db
194 .query(
195 "INSERT INTO user (id, username, email, password_hash) VALUES (?1, 'ada', '[email protected]', '')",
196 )
197 .run(owner);
198 forge.db
199 .query("INSERT INTO repo (id, owner_id, name) VALUES ('lane-repo', ?1, 'engine')")
200 .run(owner);
201 forge.db
202 .query(
203 `INSERT INTO issue (id, repo_id, number, kind, title, author_id)
204 VALUES ('lane-pull', 'lane-repo', 1171, 'pull', 'a pull', ?1)`,
205 )
206 .run(owner);
207 return { forge, dir, owner };
208 }
209
210 test("the lane: depth, the running check and its age, the median of the last twenty, the time to clear", async () => {
211 const { forge, dir, owner } = await laneForge();
212 try {
213 const now = Date.now();
214 const at = (ms: number) => new Date(now - ms).toISOString();
215 // Twenty-five finished checks: the five oldest took an hour, the
216 // twenty newest twenty minutes — the median is over the newest only.
217 for (let i = 0; i < 25; i++) {
218 const r = createRun(forge.db, { repoId: "lane-repo", kind: "check" });
219 const took = i < 5 ? 60 : 20;
220 const end = 10 * 3_600_000 - i * 1_800_000;
221 forge.db
222 .query("UPDATE run SET state='ok', started_at=?2, finished_at=?3 WHERE id=?1")
223 .run(r.id, at(end + took * 60_000), at(end));
224 }
225 const running = createRun(forge.db, {
226 repoId: "lane-repo",
227 kind: "check",
228 issueId: "lane-pull",
229 });
230 forge.db
231 .query("UPDATE run SET state='running', started_at=?2, heartbeat_at=?3 WHERE id=?1")
232 .run(running.id, at(6 * 60_000), at(0));
233 for (let i = 0; i < 43; i++)
234 createRun(forge.db, { repoId: "lane-repo", kind: "check" });
235 forge.db.query("UPDATE run SET created_at=?1 WHERE state='queued'").run(at(40 * 60_000));
236
237 const v = vitals({ db: forge.db, dataDir: dir, now });
238 expect(v.lane.queued).toBe(43);
239 expect(v.lane.running).toMatchObject({ pull: 1171, repo: "ada/engine" });
240 expect(v.lane.medianMinutes).toBe(20);
241 expect(v.lane.lanes).toBe(1);
242 // 43 × 20 minutes, and 14 left of the one running, over one lane.
243 expect(v.lane.clearsInMinutes).toBe(874);
244 expect(v.lane.line).toBe(
245 "Lane: 43 checks queued · running #1171 for 6 min · median 20 min · clears in ~15 h",
246 );
247 // Forty minutes waiting: the need is the line, its cause and its lever.
248 expect(v.lane.cause).toBe(
249 "one lane; checks run the full gate (median 20 min, the fast tier's budget is 5 min)",
250 );
251 const need = v.needs.find((n) => n.startsWith("Lane:"))!;
252 expect(need).toContain(v.lane.line!);
253 expect(need).toContain("raise Checks at once");
254 expect(v.needs.some((n) => n.includes("check queue has waited"))).toBe(false);
255
256 // An open issue labelled `lane` is the lever once there is one.
257 forge.db
258 .query(
259 `INSERT INTO issue (id, repo_id, number, kind, title, author_id)
260 VALUES ('lane-fix', 'lane-repo', 1275, 'issue', 'tiers from the base', ?1)`,
261 )
262 .run(owner);
263 forge.db
264 .query("INSERT INTO label (id, repo_id, name, color) VALUES ('l1', 'lane-repo', 'Lane', '#000000')")
265 .run();
266 forge.db.query("INSERT INTO issue_label (issue_id, label_id) VALUES ('lane-fix', 'l1')").run();
267 const fixed = vitals({ db: forge.db, dataDir: dir, now });
268 expect(fixed.lane.fix).toEqual({ repo: "ada/engine", number: 1275, title: "tiers from the base" });
269 expect(fixed.needs.find((n) => n.startsWith("Lane:"))).toContain(
270 "ada/engine#1275 tiers from the base",
271 );
272 } finally {
273 forge.close();
274 await rm(dir, { recursive: true, force: true });
275 }
276 });
277
278 test("an empty lane has no line, no median and no time to clear", async () => {
279 const { forge, dir } = await laneForge();
280 try {
281 const v = vitals({ db: forge.db, dataDir: dir });
282 expect(v.lane).toMatchObject({
283 queued: 0,
284 running: null,
285 medianMinutes: null,
286 clearsInMinutes: null,
287 line: null,
288 cause: null,
289 fix: null,
290 });
291 } finally {
292 forge.close();
293 await rm(dir, { recursive: true, force: true });
294 }
295 });
test/web.test.ts +139
@@ -19,6 +19,15 @@ import { securityFloor } from "../src/http/respond.ts";
1919 import { THEME_NAMES } from "../src/design/themes.ts";
2020 import { sha256 } from "../src/kernel/hash.ts";
2121 import { css } from "../src/web/style.ts";
22 import { newApp } from "../src/actions/apps.ts";
23 import { openIssue } from "../src/actions/issues.ts";
24 import { createAgent } from "../src/actions/crew.ts";
25 import { addCrew } from "../src/core/agents.ts";
26 import { getRepoById } from "../src/core/repos.ts";
27 import { createRun } from "../src/core/runs.ts";
28 import { createUser, type User } from "../src/core/users.ts";
29 import type { Ctx } from "../src/http/context.ts";
30 import { liveAtWorkFragment } from "../src/web/studio/at_work.ts";
2231
2332 describe("stylesheet asset", () => {
2433 test("its path is a hash over the css, so changing the css moves it", () => {
@@ -941,3 +950,133 @@ describe("a refused cross-origin mutation says why in the log", () => {
941950 expect(logs).not.toContain("refused cross-origin mutation");
942951 });
943952 });
953
954 describe("at work on the home: the check lane and the crew", () => {
955 let dataDir: string;
956 let app: App;
957 let alice: User;
958 let carol: User;
959 let repoId = "";
960
961 /** The region as `GET /live/at-work` answers it for this viewer. */
962 const atWork = async (user: User, on: App = app): Promise<string> =>
963 (
964 await liveAtWorkFragment({
965 app: on,
966 auth: { user },
967 request: new Request("http://forge.test/live/at-work"),
968 url: new URL("http://forge.test/live/at-work"),
969 params: {},
970 theme: undefined,
971 } as unknown as Ctx)
972 ).text();
973
974 beforeAll(async () => {
975 dataDir = await mkdtemp(join(tmpdir(), "forge-at-work-"));
976 app = createApp({ dataDir, port: 0 });
977 for (const [username, first] of [
978 ["alice", true],
979 ["carol", false],
980 ] as const) {
981 const made = await createUser(app.db, {
982 trusted: true,
983 username,
984 email: `${username}@forge.local`,
985 password: "a-good-passphrase",
986 adminIfFirst: first,
987 });
988 if (!made.ok) throw new Error(made.error);
989 if (username === "alice") alice = made.value;
990 else carol = made.value;
991 }
992 const made = await newApp(app, alice, { name: "square", visibility: "public" });
993 if (!made.ok) throw new Error(String(made.error));
994 repoId = made.value.app.repoId;
995 });
996
997 afterAll(async () => {
998 app.close();
999 await rm(dataDir, { recursive: true, force: true });
1000 });
1001
1002 test("with nothing running, the crew's line says why", async () => {
1003 const text = await atWork(alice);
1004 expect(text).toContain('id="live-at-work"');
1005 expect(text).not.toContain("Lane:");
1006 expect(text).toContain("Crew: nobody is working — autonomy off");
1007 app.db
1008 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1")
1009 .run(repoId, alice.id);
1010 expect(await atWork(alice)).toContain("Crew: nobody is working — no crew");
1011 });
1012
1013 test("with a crew and autonomy on: nothing ready, waiting for a slot, ceiling reached", async () => {
1014 const bot = await createAgent(app, alice, { username: "bot" });
1015 if (!bot.ok) throw new Error(String(bot.error));
1016 addCrew(app.db, repoId, bot.value.user.id, alice.id);
1017 expect(await atWork(alice)).toContain("Crew: nobody is working — nothing ready");
1018
1019 // Backing off is not waiting for a slot.
1020 const later = createRun(app.db, {
1021 repoId,
1022 kind: "agent",
1023 notBefore: new Date(Date.now() + 60 * 60_000).toISOString(),
1024 });
1025 expect(await atWork(alice)).toContain("Crew: nobody is working — nothing ready");
1026
1027 const ready = createRun(app.db, { repoId, kind: "agent" });
1028 expect(await atWork(alice)).toContain(
1029 "Crew: nobody is working — waiting for a crew slot",
1030 );
1031
1032 // The repository's own ceiling, then the forge's.
1033 const ceiling = getRepoById(app.db, repoId)!.autonomyCeilingUsd;
1034 app.db.query("UPDATE run SET cost_usd = ?2 WHERE id = ?1").run(ready.id, ceiling);
1035 expect(await atWork(alice)).toContain("Crew: nobody is working — ceiling reached");
1036 app.db.query("UPDATE run SET cost_usd = 1 WHERE id = ?1").run(ready.id);
1037 expect(await atWork(alice)).toContain(
1038 "Crew: nobody is working — waiting for a crew slot",
1039 );
1040 const capped = { ...app, config: { ...app.config, crewCeilingUsd: 1 } } as App;
1041 expect(await atWork(alice, capped)).toContain(
1042 "Crew: nobody is working — ceiling reached",
1043 );
1044
1045 app.db
1046 .query("UPDATE run SET state = 'failed', cost_usd = 0 WHERE id IN (?1, ?2)")
1047 .run(later.id, ready.id);
1048 });
1049
1050 test("a seeded lane is one line, for a site admin only", async () => {
1051 const running = createRun(app.db, { repoId, kind: "check", branch: "main" });
1052 app.db
1053 .query("UPDATE run SET state = 'running', started_at = ?2 WHERE id = ?1")
1054 .run(running.id, new Date(Date.now() - 6 * 60_000).toISOString());
1055 for (let i = 0; i < 2; i++) createRun(app.db, { repoId, kind: "check" });
1056 expect(await atWork(alice)).toContain(
1057 "Lane: 2 checks queued · running main for 6 min",
1058 );
1059 expect(await atWork(carol)).not.toContain("Lane:");
1060 });
1061
1062 test("a crew run in flight is a row: agent, issue, what it is doing, since", async () => {
1063 const issue = openIssue(app, alice, getRepoById(app.db, repoId)!, {
1064 title: "Make it square",
1065 });
1066 if (!issue.ok) throw new Error(String(issue.error));
1067 const run = createRun(app.db, {
1068 repoId,
1069 kind: "agent",
1070 issueId: issue.value.id,
1071 actorId: alice.id,
1072 reason: "assigned",
1073 });
1074 app.db
1075 .query("UPDATE run SET state = 'running', started_at = ?2 WHERE id = ?1")
1076 .run(run.id, new Date().toISOString());
1077 const text = await atWork(alice);
1078 expect(text).toContain(`alice · square#${issue.value.number}`);
1079 expect(text).toContain("working the issue");
1080 expect(text).not.toContain("nobody is working");
1081 });
1082 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs