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

The /infra first page shows the costliest resources as a sortable table #17955

opened this

Merged 23h 3m ago, live in production

torque/forge:torque/17952-the-infra-first-page-shows-the-costliest → main 0 commits fork 2 threads · 2 unresolved

  • Merged. torque/17952-the-infra-first-page-shows-the-costliest was merged into main as e08c778.

Review

Sign in to review this change.
5 files changed +92 −11
docs/features/infra.md +1
@@ -104,6 +104,7 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
104104 - **With nothing open** the pane is where the money goes, then what the forge runs; under a filter it is the matches. **Build** (`c`) is `/infra/build`: the compose form, a build's progress (`?plan=`), a DNS record, the code it is kept as and the pinned forges. `/pinned` redirects there, and so does `/infra?plan=`.
105105 - **Filter.** `/`, then `kind:volume cloud:aws attached:no cost:>10 text`. Properties: kind, cloud, account, project, region, size, name, state, attached, made, for, app, cost, created. `!` negates a term or a word (`!web`), a comma means any of, and the sign carries on over it (`cost:>10,20`) until a value has its own (`cost:>10,=20`). `cost:unknown` is a value, and `app:unknown` finds what has no app known, on any cloud, which does not mean nothing uses it. Quotes are literal: `name:"old web"` holds a space, and `region:"none"` is the word and not the empty value. `created:` takes an age (`<7d` is younger, `>7d` older, `s m h d w`) or a date (`>2026-12-01` is after that day, UTC unless it has an offset). `machine:i-111` is an id, read as text. It is in the URL as `?q=`.
106106 - **A line that cannot be read whole** still draws rows, and the page and the terminal say what was made of it. An unknown property is text and the near one is named; a sign on a property without an order is left out; a sort by what is no property keeps the order; `group:` is a word this list cannot do yet. A bad `cost:` or `created:`, and what is past 12 words or 200 characters, narrow nothing. The `infra` tool names the first sort in `problems` and refuses the second (`invalid_filter`, with the place). The language is `src/list/line.ts`, for every list to share.
107 - **First page.** With no resource chosen, `/infra` shows the costliest resources in one table: resource, kind, where (cloud ▸ account ▸ region) and monthly cost, in the tree's own order, narrowed by the filter line, with no sum of its own. A cost says `billed` or `list price`; one that is not known says `unknown`, never $0 (`costWords`, `firstCell` in `src/cloud/tree.ts`). The terminal draws the same table (`src/tui/screens/cloudtree.ts`) when the cursor is at the top of the tree and nothing is opened; a branch's pane still opens with where its money goes.
107108 - **Sort.** `sort:cost`, `sort:-created,name`: `-` is the largest, the newest or Z first, 3 at most, what is not known last both ways, and `web-2` is before `web-10`. It orders the lists (the pane, the terminal's, the `infra` tool's), never the tree, whose branches carry bills that are no sum of rows. Without one a list is costliest first. A column's heading is a link that writes it, and `S` types `sort:` in the line, on the page and in the terminal. The table is `src/web/list.ts` and `src/tui/ui/list.ts`, over `src/list/order.ts`.
108109 - **Not known.** A comparison never holds for what is not known, so the page, the terminal and the tool (`unknown`: `left`, and `among` the rows under a `!`) say how many it could not judge: "3 more have no known created date." Add `,unknown` to see them.
109110 - **Changed with the shared language:** `!web` and `!machine:i-111` negate and a leading `"` quotes (both were part of the word); `sort:`, `group:` and `created:` were text; `cost:=10`, `cost:>10,=20` and `cost:>10,<5` were refused; a sign left out and a long line's rest are now said; over MCP `cost:abc` and `cost:none` listed everything and are refused. `test/cloud-filter-lines.test.ts` holds each, and every line that kept its rows.
src/cloud/tree.ts +17
@@ -478,6 +478,23 @@ export function cloudCell(n: CloudNode, field: string): string {
478478 return field === "kind" ? r.kind : field === "size" ? r.size : r.region;
479479 }
480480
481 /** A cost in words on a first-page row: billed, a list price, or not known (never $0). */
482 export const costWords = (m: Money): string => (m.billed + m.list === 0 ? "unknown" : `${dollars(m.cents)} ${m.billed > 0 ? "billed" : "list price"}`);
483
484 /** Where a resource is: cloud ▸ account ▸ region (its project's name where it has no region). */
485 export const whereOf = (n: CloudNode): string => [cloudName(n.path[0] ?? ""), n.path[1] ?? "", n.resource?.region || (n.path[2] ?? "")].filter((x) => x !== "").join(" ▸ ");
486
487 /**
488 * The first page's columns, on the page and in the terminal: the list's fields as it names them.
489 */
490 export const FIRST_COLUMNS = (["name", "kind", "region", "cost"] as const).map((name) => ({
491 field: fieldOf(LIST.fields, name)!,
492 label: { name: "Resource", kind: "Kind", region: "Where", cost: "Monthly cost" }[name],
493 }));
494
495 /** A first-page cell as every door says it. */
496 export const firstCell = (n: CloudNode, field: string): string => (field === "region" ? whereOf(n) : field === "cost" ? costWords(n.money) : field === "name" ? n.name : n.resource!.kind);
497
481498 /** A filter line for the cloud tree, in the language every list shares (`list/line.ts`). */
482499 export function parseCloudQuery(typed: string): CloudQuery {
483500 const line = parseLine(typed, LIST);
src/tui/screens/cloudtree.ts +10 −5
@@ -6,7 +6,7 @@
66 */
77
88 import { cloudResources, readProjectsNow } from "../../actions/infra.ts";
9 import { cloudCell, CLOUD_COLUMNS, cloudName, CONTAINER_COST, containersSay, costLine, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, listedOf, moneyMark, nodeAt, orderSays, readingOf, tabOf, tabsOf, unreadAccounts, unreadLine, unpricedSays, type CloudNode, type CloudView, type NodeTab } from "../../cloud/tree.ts";
9 import { cloudCell, CLOUD_COLUMNS, FIRST_COLUMNS, firstCell, cloudName, CONTAINER_COST, containersSay, costLine, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, listedOf, moneyMark, nodeAt, orderSays, readingOf, tabOf, tabsOf, unreadAccounts, unreadLine, unpricedSays, type CloudNode, type CloudView, type NodeTab } from "../../cloud/tree.ts";
1010 import { noFileSays, placeSays } from "../../cloud/declared_in.ts";
1111 import { filesByNode } from "../../cloud/declared_read.ts";
1212 import { CONTAINER_COLUMNS, containerCell } from "../../cloud/containers.ts";
@@ -71,17 +71,20 @@ export function cloudLines(v: CloudView, n: CloudNode, width = 80, tab: NodeTab
7171 if (n.container !== undefined) return [...head, "", ...facts, read];
7272 if (n.resource !== undefined)
7373 return [...head, "", ...facts, `${createdLabel(n.resource).padEnd(12)} ${n.resource.createdAt.slice(0, 10) || "not known"}`, read, ...(n.children.length === 0 ? [] : ["", containersSay(n), ...tableLines(CONTAINER_COLUMNS.map((k) => ({ field: { name: k.field, type: "text" }, label: k.label })), v.q.line, n.children.map((c) => CONTAINER_COLUMNS.map((k) => containerCell(c.container!, k.field, v.now))), width)])];
74 const goes = v.q.text === "" ? largestCosts(n, 6).filter((c) => c.from === "billed") : [];
74 // The first page is the page's own table: resource, kind, where, and a cost in words.
75 const first = n.path.length === 0;
76 const columns = first ? FIRST_COLUMNS : CLOUD_COLUMNS;
77 const goes = v.q.text === "" && !first ? largestCosts(n, 6).filter((c) => c.from === "billed") : [];
7578 const line = (sum: string, words: string): string => `${sum.padStart(13)} ${words}`;
7679 const cut = cutSays(PANE_LINES, n.count - PANE_LINES, "/ narrows the filter", orderSays(v.q));
77 const rows = listedOf(v, n).slice(0, PANE_LINES).map((c) => CLOUD_COLUMNS.map(({ field }) => cloudCell(c, field.name)));
80 const rows = listedOf(v, n).slice(0, PANE_LINES).map((c) => columns.map(({ field }) => (first ? firstCell(c, field.name) : cloudCell(c, field.name))));
7881 return [
7982 ...head,
8083 ...(read === "" ? [] : [read]),
8184 ...trouble,
8285 ...(n.note === "" ? [] : [`${n.note}.`]),
8386 ...(goes.length === 0 ? [] : ["", "Where it goes", ...goes.map((c) => line(dollars(c.cents), `${c.says} · ${c.where}${c.hint === "" ? "" : ` · ${c.hint}`}`))]),
84 ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...tableLines(CLOUD_COLUMNS, v.q.line, rows, width), ...(cut === "" ? [] : [cut])]),
87 ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...tableLines(columns, v.q.line, rows, width), ...(cut === "" ? [] : [cut])]),
8588 ];
8689 }
8790
@@ -209,7 +212,9 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
209212 });
210213 }
211214 if (right !== undefined) {
212 const at = shown ?? all[state.index]?.node;
215 // With the cursor at the top and nothing opened, the pane is the first page: every
216 // resource.
217 const at = shown ?? (state.index === 0 ? v.root : all[state.index]?.node);
213218 if (at !== undefined) {
214219 if (tabOf(at, tab) === "file") readFiles(v);
215220 room = Math.max(10, right.w - 2);
src/web/pages/cloud_tree.ts +29 −3
@@ -15,6 +15,9 @@ import {
1515 cloudName,
1616 cloudCell,
1717 CLOUD_COLUMNS,
18 costWords,
19 FIRST_COLUMNS,
20 firstCell,
1821 listedOf,
1922 orderSays,
2023 createdLabel,
@@ -210,6 +213,12 @@ function largest(v: CloudView, n: CloudNode, most = 6): Html {
210213 </section>`;
211214 }
212215
216 /** A first-page cost: `costWords` of the cloud tree, with its number and its kind set apart. */
217 function costMark(n: CloudNode): Html {
218 const m = n.money;
outdated

The 'billed' branch is never exercised by a test (box 4). Add a billed fixture and assert '$X billed'.

219 return m.billed + m.list === 0 ? html`<span class="muted">unknown</span>` : html`<span title="${costWords(m)}"><span class="num">${dollars(m.cents)}</span> <span class="muted">${m.billed > 0 ? "billed" : "list price"}</span></span>`;
220 }
221
outdated

Where text is only checked with a tautological assertion in the test; pin the exact 'cloud ▸ account ▸ region' string for a resource with a region and one without.

213222 /**
214223 * Every resource at or under a node, in the line's order, and once above them what has no price.
215224 */
@@ -231,11 +240,28 @@ function listed(v: CloudView, n: CloudNode): Html {
231240 ${all.length > PANE_ROWS ? html`<p class="muted small">The first ${PANE_ROWS}, ${orderSays(v.q)}: filter to see the rest.</p>` : null}`;
232241 }
233242
243 /** The costliest resources in one table, in the tree's order, narrowed by the filter line. */
244 function costliestTable(v: CloudView): Html {
245 const all = listedOf(v, v.root);
246 if (all.length === 0) return html`<p>${v.q.text === "" ? "Nothing here." : "Nothing here matches the filter."}</p>`;
247 return html`<section data-costliest>
248 <h2 class="${v.q.text !== "" ? "sr-only" : ""}">${all.length.toLocaleString("en-US")} ${all.length === 1 ? "resource" : "resources"}</h2>
249 ${listTable({
250 columns: FIRST_COLUMNS,
251 line: v.q.line,
252 rows: all.slice(0, PANE_ROWS),
253 cell: (c, field) => (field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : field === "cost" ? costMark(c) : firstCell(c, field)),
254 href: (text) => cloudHref([], { ...v.q, text }),
255 caption: `Resources, ${orderSays(v.q)}`,
256 })}
257 ${all.length > PANE_ROWS ? html`<p class="muted small">The first ${PANE_ROWS}, ${orderSays(v.q)}: filter to see the rest.</p>` : null}
258 </section>`;
259 }
260
234261 /** With nothing open: where the money goes and what the forge runs, or what the filter found. */
235262 export function cloudOverview(v: CloudView, running: Html): Html {
236 const goes = largestCosts(v.root, 2).length > 1;
237263 return html`<section id="code-pane" data-path="All clouds" data-cloud-pane="all">
238 ${v.q.text !== "" ? listed(v, v.root) : html`${goes ? largest(v, v.root) : v.root.count === 0 ? null : listed(v, v.root)}${running}`}
264 ${costliestTable(v)}${v.q.text === "" ? running : null}
239265 </section>`;
240266 }
241267
@@ -308,7 +334,7 @@ export const CLOUD_TREE_CSS = `/* ---- the resource tree (#17532): the code brow
308334 /* A phone with something open shows that: the whole forge's total is one tap back. */
309335 @media (max-width: 899px) { [data-infra][data-open] > [data-cloud-total] { display: none; } }
310336 [data-cloud-pane] > h2 { margin: 12px 0 4px; }
311 [data-cloud-pane], [data-largest] { max-width: 720px; }
337 [data-cloud-pane], [data-costliest] { max-width: 720px; }
312338 @media (min-width: 900px) { [data-infra] .code-layout { grid-template-columns: minmax(0, var(--ex-w, 400px)) auto minmax(0, 1fr); } }
313339 @media (min-width: 1200px) { [data-infra] .code-layout { grid-template-columns: minmax(0, var(--ex-w, 480px)) auto minmax(0, 1fr); } }
314340 /* On a phone the tree is the page: it scrolls with it, never inside it. */
test/cloud-tree.test.ts +35 −3
@@ -12,7 +12,7 @@ import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { cloudResources } from "../src/actions/infra.ts";
1414 import { keyOf } from "../src/web/keymap.ts";
15 import { costLine, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, readFixes, tiesOf, type CloudNode, type CloudView } from "../src/cloud/tree.ts";
15 import { costLine, costWords, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, readFixes, tiesOf, type CloudNode, type CloudView } from "../src/cloud/tree.ts";
1616 import { aboutContext, aboutLine } from "../src/core/talk_about.ts";
1717 import { createSession } from "../src/core/sessions.ts";
1818 import { createToken } from "../src/core/tokens.ts";
@@ -257,6 +257,39 @@ describe("with accounts", () => {
257257 ]);
258258 });
259259
260 test("the first page is one table of the costliest resources: where, and a cost that says what it is", async () => {
261 const rows = (html: string): string[][] =>
262 [...html.matchAll(/<tr><td[^>]*>([\s\S]*?)<\/tr>/g)].map((m) => [...`<td>${m[1]}`.matchAll(/<td[^>]*>([\s\S]*?)<\/td>/g)].map((c) => c[1]!.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim()));
263 const page = await (await get("/infra?fragment=1")).text();
264 expect(page).toContain("data-costliest");
265 expect(page).toContain("Monthly cost");
266 const all = rows(page);
267 const web = all.find((r) => r[0] === "web")!;
268 expect(web).toEqual(["web", "machine", "DigitalOcean ▸ main ▸ site", "$12.00 list price"]);
269 expect(all.find((r) => r[0] === "box")).toEqual(["box", "machine", "Hetzner Cloud ▸ eu ▸ games", "$5.99 list price"]);
270 // A resource with a region says it; the AWS ones are placed by theirs.
271 expect(all.find((r) => r[0] === "vol-2")).toEqual(["vol-2", "volume", "AWS ▸ main ▸ us-east-1", "unknown"]);
272 // Unknown is said, never $0; the tree's own order keeps the priced above the unpriced.
273 const unknown = all.filter((r) => r[3] === "unknown");
274 expect(unknown.length).toBeGreaterThan(0);
275 expect(page).not.toContain("$0.00");
276 expect(all.findIndex((r) => r[0] === "web")).toBeLessThan(all.findIndex((r) => r[3] === "unknown"));
277 expect(all.map((r) => r[0])).toEqual(costliestOf(view().root).map((n) => n.name));
278 // The filter line narrows the same table.
279 const narrowed = rows(await (await get("/infra?fragment=1&q=cloud%3Ahetzner")).text());
280 expect(narrowed.map((r) => r[0])).toEqual(["box"]);
281 });
282
283 test("a cost is worded billed, list price or unknown, and the terminal's first page is the same table", async () => {
284 const money = { cents: 4000, billed: 1, list: 0, unknown: 0, unread: 0 };
285 expect(costWords(money)).toBe("$40.00 billed");
286 expect(costWords({ ...money, billed: 0, list: 1 })).toBe("$40.00 list price");
287 expect(costWords({ ...money, cents: 0, billed: 0, unknown: 1 })).toBe("unknown");
288 const screen = await drawn("");
289 expect(screen).not.toContain("Where it goes");
290 for (const word of ["Resource", "Kind", "Where", "Monthly cost", "DigitalOcean ▸ main ▸ site", "$12.00 list price", "unknown"]) expect(screen).toContain(word);
291 });
292
260293 test("a filter's headline is what it found; Back's fragment is the pane alone; building is its own page", async () => {
261294 const found = await (await get("/infra?q=kind%3Avolume%20attached%3Ano")).text();
262295 expect(found).toContain("<strong>1 unattached volume</strong>");
@@ -268,8 +301,7 @@ describe("with accounts", () => {
268301 const back = await get("/infra?fragment=1");
269302 expect(back.status).toBe(200);
270303 const pane = await back.text();
271 expect(pane).toContain("Where it goes");
272 expect(pane).toContain("usually disks, snapshots, NAT gateways and data transfer");
304 expect(pane).toContain("data-costliest");
273305 expect(pane).not.toContain("<html");
274306 expect(await (await get("/infra/build")).text()).toContain('id="compose"');
275307 expect((await fetch(`${servers.url}/infra?plan=p1`, { redirect: "manual", headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } })).headers.get("location")).toBe("/infra/build?plan=p1");

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

Keyboard shortcuts

Docs