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

The terminal opens the board's returns, in the same rows as /board/returns #16798

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/16267-the-terminal-opens-the-board-s-returns-i → main 0 commits fork

  • Merged. mason/16267-the-terminal-opens-the-board-s-returns-i was merged into main as 6c3a514.

Review

Sign in to review this change.
5 files changed +312 −0
docs/features/returns-terminal.md added +12
@@ -0,0 +1,12 @@
1 ---
2 topic: Bring your own AI
3 row: The terminal opens the board's returns, in the same rows as /board/returns
4 ---
5 # The terminal opens the board's returns (#16267)
6
7 What the tokens bought, as `/board/returns` has it: spent and landed first, then what did not land and why, then the issues that cost the most.
8
9 - **Open it:** on the dashboard, the *Tokens, 7 days* line (shown when something ran) opens with `T`; or the palette, "What the tokens bought".
10 - **Window:** `d` cycles 1, 7 and 30 days. `j`/`k` scroll, `esc` goes back.
11 - **Who:** owner facts only, as the page: the owner, their organisation's writers, a site admin. Anyone else has no line, no palette entry, and a screen reached any other way is empty.
12 - **Same numbers:** read through `readReturns` in `src/actions/returns.ts`, the page's own reader; `test/tui-returns.test.ts` checks every figure appears on the page.
scripts/gate.ts +1
@@ -211,6 +211,7 @@ export const SLOW: readonly Exclusion[] = [
211211 { file: "test/tui-deploys.test.ts", reason: "drives a real terminal session through adding, checking and removing a domain; 4.8 s a test on the gate box", issue: 1242 },
212212 { file: "test/tui-economics.test.ts", reason: "drives a real terminal session through the economics screens; 3.1 s a test on the gate box", issue: 1242 },
213213 { file: "test/tui-fleet.test.ts", reason: "drives a real terminal session through preview, apply and undo; 2.7 s a test on the gate box", issue: 1242 },
214 { file: "test/tui-returns.test.ts", reason: "drives a real terminal session and a real page over one fixture of runs; about 3 s a file", issue: 16267 },
214215 { file: "test/tui-notes.test.ts", reason: "drives a real terminal session as a person and as the admin over notes; 3.1 s a test on the gate box", issue: 1242 },
215216 { file: "test/tui-talk-build.test.ts", reason: "drives a real terminal session through a build, its files, restore and publish; 2.1 s a test on the gate box", issue: 1242 },
216217 { file: "test/tui-tell.test.ts", reason: "drives a real terminal session to send and read tells; 2.7 s a test on the gate box", issue: 1242 },
src/tui/screens/dashboard.ts +11
@@ -64,6 +64,7 @@ import { pipelineNow } from "../../web/studio/living.ts";
6464 import { mayView } from "../../core/sealed.ts";
6565 import { applyFleetIds, previewFleetIds, undoFleetOp } from "../../actions/fleet.ts";
6666 import { plain } from "./boards.ts";
67 import { returnsScreen, returnsStrip } from "./returns.ts";
6768 import { pinRepo, unpinRepo } from "../../actions/origins.ts";
6869 import { getProposal } from "../../core/proposals.ts";
6970 import { getIssueById, listAssignedTo, type Issue } from "../../core/issues.ts";
@@ -298,6 +299,8 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
298299 let lane: string | null = null;
299300 /** The week's flaky tests, one line; null when none flaked. */
300301 let flaky: string | null = null;
302 /** The board's tokens line, owner facts only; null when nothing ran. */
303 let tokens: string | null = null;
301304 /** What the decider did today, the board's Today line; null on a quiet day or for a reader. */
302305 let decider: string | null = null;
303306 /**
@@ -571,6 +574,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
571574 waits = ownerWaits(f.db, all.filter((r) => facts.has(r.id))).map(waitLine);
572575 lane = forgeLane(f.app, f.user);
573576 flaky = forgeFlakes(f.app, f.user);
577 tokens = returnsStrip(f);
574578 decider = deciderLine(f.app, f.user);
575579 moving = f.user ? movingLines(f.db, f.user, f.user.isAdmin ? pipelineNow(f.db) : undefined) : [];
576580 const commit = running().commit;
@@ -1268,6 +1272,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
12681272 disabled: focus !== "machine" || machineRows() === 0,
12691273 }),
12701274 binding(["C"], "decider", { disabled: !f.user }),
1275 ...(tokens !== null ? [binding(["T"], "what the tokens bought")] : []),
12711276 ...(firstTell
12721277 ? [binding(["t"], "say what you want built")]
12731278 : clientLines.length > 0
@@ -1378,6 +1383,11 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
13781383 s.text(strip!.x, strip!.y, truncate(panelLines[0]!, strip!.w), style(c.mutedFg, c.bg), strip!.x + strip!.w);
13791384 body = rest!;
13801385 }
1386 if (tokens !== null) {
1387 const [strip, rest] = split(body, "v", [len(1), fill(1)]);
1388 s.text(strip!.x, strip!.y, truncate(tokens, strip!.w), style(c.mutedFg, c.bg), strip!.x + strip!.w);
1389 body = rest!;
1390 }
13811391 if (decider !== null) {
13821392 const [strip, rest] = split(body, "v", [len(1), fill(1)]);
13831393 s.text(
@@ -1522,6 +1532,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
15221532 if (e.key === "U" && f.user) return undoHand(), true;
15231533 if (e.key === "L" && f.user) return listenAgain(), true;
15241534 if (e.key === "F" && f.user) return showAll(), true;
1535 if (e.key === "T" && tokens !== null) return ctx.push(returnsScreen(f, ctx)), true;
15251536 if (e.key === "C" && f.user) return ctx.push(deciderScreen(f, ctx)), true;
15261537 if (e.key === "P" && f.user) return showPeople(), true;
15271538 if (f.user && e.key >= "1" && e.key <= String(KIND_CHIPS.length))
src/tui/screens/returns.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * What the tokens bought, in the terminal: the board's /board/returns in the
3 * same rows. Spent and landed first, then what did not land and why, then the
4 * issues that cost the most. `d` cycles the window through 1, 7 and 30 days.
5 * Read through `readReturns`, behind the page's own gate: owner facts only
6 * (`returnsRepos`); anyone who holds none sees nothing.
7 */
8
9 import { readReturns, returnsRepos } from "../../actions/returns.ts";
10 import { usd } from "../../core/money.ts";
11 import type { Money } from "../../core/returns.ts";
12 import { getReposByIds } from "../../core/repos.ts";
13 import { plural } from "../../kernel/plural.ts";
14 import type { Ctx, Screen } from "../app/app.ts";
15 import { binding } from "../app/keys.ts";
16 import type { Session } from "../session.ts";
17 import { style } from "../term/style.ts";
18 import { Scroll, drawLines, hitScroll } from "./common.ts";
19 import type { PaletteEntry } from "./entries.ts";
20
21 /** The windows `d` cycles through, in days; the board's own is 7. */
22 export const RETURNS_WINDOWS = [1, 7, 30] as const;
23
24 /** Whether this session holds owner facts for any repository, as the page's gate has it. */
25 export const mayReadReturns = (session: Session): boolean =>
26 session.user !== undefined && returnsRepos(session.app, session.user).length > 0;
27
28 const runs = (m: Money): string => plural(m.runs, "run");
29
30 /** One row, as the page's: title, runs and a note, dollars at the end. */
31 const line = (title: string, m: Money, note?: string): string =>
32 ` ${title} — ${runs(m)}${note === undefined ? "" : ` · ${note}`} · ${usd(m.usd)}`;
33
34 /** The screen's lines for a window; empty for anyone the gate refuses. */
35 export function returnsLines(session: Session, days: number): string[] {
36 if (!mayReadReturns(session)) return [];
37 const read = readReturns(session.app, session.user, { days });
38 if (!read.ok) return [];
39 const r = read.value;
40 const nothing = r.landedNothing;
41 const lines = [
42 `What the tokens bought, ${days} ${days === 1 ? "day" : "days"}`,
43 `${usd(r.spent.usd)} over ${runs(r.spent)} · ${r.landed} changes landed` +
44 (r.onLanded.perChange.changes === 0
45 ? ""
46 : ` · ${usd(r.onLanded.perChange.median)} a landed change (median), ${usd(r.onLanded.usd)} in all`) +
47 ` · ${usd(nothing.closed.usd)} closed with nothing · ${usd(nothing.open.usd)} still open`,
48 "",
49 "Where it went",
50 line("On work that landed", r.onLanded, `${r.onLanded.perChange.changes} changes`),
51 line("On work closed without a merge", nothing.closed),
52 line("On work still open, nothing merged yet", nothing.open),
53 "",
54 "What did not land, and why",
55 line("Runs that failed", nothing.failed),
56 ...nothing.topFailures.map((f) => line(`of which: ${f.reason}`, f)),
57 line("Runs cancelled", nothing.cancelled),
58 "",
59 "What cost the most",
60 ];
61 const repos = getReposByIds(session.db, r.costliest.map((c) => c.repoId));
62 if (r.costliest.length === 0) lines.push(" Nothing yet.");
63 for (const c of r.costliest) {
64 const repo = repos.get(c.repoId);
65 const slug = repo ? `${repo.ownerName}/${repo.name}` : "";
66 const outcome = c.outcome === "landed" ? "landed" : c.outcome === "closed" ? "closed with nothing merged" : "nothing merged yet";
67 lines.push(` #${c.number} ${c.title} — ${slug} · ${runs(c)} · ${outcome} · ${usd(c.usd)}`);
68 }
69 return lines;
70 }
71
72 /**
73 * The dashboard's one line over the board's window, with the key that opens the screen; null when
74 * nothing ran.
75 */
76 export function returnsStrip(session: Session): string | null {
77 if (!mayReadReturns(session)) return null;
78 const read = readReturns(session.app, session.user, { days: 7 });
79 if (!read.ok || read.value.spent.runs === 0) return null;
80 const r = read.value;
81 return `Tokens, 7 days: ${usd(r.spent.usd)} → ${r.landed} landed · ${usd(r.landedNothing.closed.usd)} closed with nothing · ${usd(r.landedNothing.open.usd)} still open T opens`;
82 }
83
84 export function returnsScreen(session: Session, ctx: Ctx, days: number = 7): Screen {
85 const scroll = new Scroll();
86 let window = RETURNS_WINDOWS.includes(days as 1) ? days : 7;
87 let lines = returnsLines(session, window);
88 return {
89 title: "What the tokens bought",
90 keys: [binding(["j", "k"], "scroll"), binding(["d"], "1, 7 or 30 days"), binding(["esc", "q"], "back")],
91 render(area, s) {
92 const c = ctx.theme.c;
93 const shown = lines.length === 0 ? ["Nothing here for you."] : lines;
94 drawLines(
95 s,
96 area,
97 c,
98 scroll,
99 shown.map((text) => [{ text, style: style(text === "" || text.startsWith(" ") ? c.mutedFg : c.fg, c.bg) }]),
100 );
101 hitScroll(ctx, area, scroll, shown.length);
102 },
103 key(e) {
104 if (scroll.key(e, lines.length)) return true;
105 if (e.key === "d") {
106 window = RETURNS_WINDOWS[(RETURNS_WINDOWS.indexOf(window as 1) + 1) % RETURNS_WINDOWS.length]!;
107 lines = returnsLines(session, window);
108 return true;
109 }
110 if (e.key === "esc" || e.key === "q") {
111 ctx.pop();
112 return true;
113 }
114 return false;
115 },
116 };
117 }
118
119 export const entry: PaletteEntry = {
120 rank: 112,
121 id: "returns",
122 title: "What the tokens bought",
123 hint: "spent and landed, what did not land and why, the costliest issues",
124 after: ["bottleneck", "system"],
125 offered: mayReadReturns,
126 run: (session, ctx) => ctx.push(returnsScreen(session, ctx)),
127 };
test/tui-returns.test.ts added +161
@@ -0,0 +1,161 @@
1 /**
2 * What the tokens bought, in the terminal: the owner's numbers are the page's
3 * for one fixture, `d` cycles the window through 1, 7 and 30 days, the
4 * dashboard's tokens line opens it with `T`, and anyone who holds no owner
5 * facts is refused and sees nothing.
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 { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { createApp, type App as Forge } from "../src/app.ts";
15 import { createRun } from "../src/core/runs.ts";
16 import { createUser, getUserByName } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { createForgeApp } from "../src/tui/forge.ts";
19 import { returnsLines } from "../src/tui/screens/returns.ts";
20 import { Session, type TuiIdentity } from "../src/tui/session.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { settleApp } from "./helpers/tui.ts";
24
25 quietLogs();
26
27 const PASSWORD = "a-long-returns-passphrase";
28
29 describe("what the tokens bought in the terminal", () => {
30 let dataDir: string;
31 let forge: Forge;
32 let servers: Servers;
33
34 function boot(username: string) {
35 const terminal = headlessTerminal(180, 60);
36 const user = getUserByName(forge.db, username)!;
37 const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1", user };
38 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
39 app.start();
40 const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
41 return {
42 text: () => app.screen.toText(),
43 press: async (...keys: string[]) => {
44 keys.forEach(key);
45 await settleApp(app);
46 },
47 ctrl: async (k: string) => {
48 app.dispatch({ type: "key", key: k, ctrl: true, alt: false, shift: false });
49 await settleApp(app);
50 },
51 type: async (t: string) => {
52 for (const ch of t) key(ch);
53 await settleApp(app);
54 },
55 stop: () => app.stop(),
56 };
57 }
58 const session = (username: string): Session => {
59 const user = getUserByName(forge.db, username)!;
60 return new Session(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user });
61 };
62
63 beforeAll(async () => {
64 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-returns-"));
65 forge = createApp({ dataDir, port: 0 });
66 servers = await serve(forge);
67 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
68 const made = await createUser(forge.db, {
69 origin: "seed",
70 trusted: true,
71 username,
72 email: `${username}@forge.local`,
73 password: PASSWORD,
74 adminIfFirst,
75 });
76 if (!made.ok) throw new Error(made.error);
77 }
78 const alice = getUserByName(forge.db, "alice")!;
79 const made = await createRepo(forge, alice, { name: "mill", visibility: "public" });
80 if (!made.ok) throw new Error(String(made.error));
81 const repo = made.value;
82 await commitToBranch(forge, alice, repo, { message: "seed", files: [{ path: "README.md", content: "# mill\n" }] });
83 await createAgent(forge, alice, { username: "bot" });
84 addToCrew(forge, alice, repo, "bot");
85 const opened = openIssue(forge, alice, repo, { title: "Declined work" });
86 if (!opened.ok) throw new Error(String(opened.error));
87 for (const [state, cost, summary] of [
88 ["ok", 1.25, "ok"],
89 ["failed", 2.5, "failed: the check is red"],
90 ] as const) {
91 const run = createRun(forge.db, {
92 repoId: repo.id,
93 kind: "agent",
94 issueId: opened.value.id,
95 branch: "",
96 actorId: getUserByName(forge.db, "bot")!.id,
97 reason: "assigned",
98 });
99 forge.db
100 .query("UPDATE run SET state = ?2, cost_usd = ?3, summary = ?4, started_at = ?5, finished_at = ?6 WHERE id = ?1")
101 .run(run.id, state, cost, summary, new Date(Date.now() - 600_000).toISOString(), new Date().toISOString());
102 }
103 });
104 afterAll(async () => {
105 await servers.stop?.();
106 forge.close();
107 await rm(dataDir, { recursive: true, force: true });
108 });
109
110 test("a non-owner is refused: no lines, no entry, nothing on screen", async () => {
111 expect(returnsLines(session("bob"), 7)).toEqual([]);
112 const h = boot("bob");
113 await h.ctrl("k");
114 await h.type("tokens bought");
115 expect(h.text()).not.toContain("What the tokens bought");
116 h.stop();
117 });
118
119 test("the owner's numbers are the page's", async () => {
120 const res = await fetch(`${servers.url}/signin`, {
121 method: "POST",
122 body: new URLSearchParams({ username: "alice", password: PASSWORD }),
123 redirect: "manual",
124 });
125 const cookie = `${(res.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=studio`;
126 const page = await (await fetch(`${servers.url}/board/returns?days=7`, { headers: { cookie } })).text();
127 const pageText = page.replace(/<[^>]*>/g, " ").replace(/&#39;|&amp;/g, "'");
128 const lines = returnsLines(session("alice"), 7);
129 expect(lines.length).toBeGreaterThan(8);
130 const figures = lines.join("\n").match(/\$\d+(\.\d+)?/g) ?? [];
131 expect(figures).toContain("$3.75");
132 expect(figures).toContain("$2.50");
133 for (const f of figures) expect(pageText).toContain(f);
134 expect(lines.join("\n")).toContain("of which: failed: the check is red");
135 expect(pageText).toContain("of which: failed: the check is red");
136 expect(lines.join("\n")).toContain("#1 Declined work");
137 });
138
139 test("the palette opens it and d cycles 1, 7 and 30 days", async () => {
140 const h = boot("alice");
141 await h.ctrl("k");
142 await h.type("tokens bought");
143 await h.press("enter");
144 expect(h.text()).toContain("What the tokens bought, 7 days");
145 await h.press("d");
146 expect(h.text()).toContain("What the tokens bought, 30 days");
147 await h.press("d");
148 expect(h.text()).toContain("What the tokens bought, 1 day");
149 await h.press("d");
150 expect(h.text()).toContain("What the tokens bought, 7 days");
151 h.stop();
152 });
153
154 test("one key from the dashboard's tokens line opens it", async () => {
155 const h = boot("alice");
156 expect(h.text()).toContain("Tokens, 7 days: $3.75");
157 await h.press("T");
158 expect(h.text()).toContain("Where it went");
159 h.stop();
160 });
161 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs