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

The cloud tree's lists sort by any column, from the one line, at every door #17750

opened this

Merged 9h 59m ago, live in production

sold/leaf-table-2 → main 0 commits

  • Merged. sold/leaf-table-2 was merged into main as a4750d3.

Review

Sign in to review this change.
15 files changed +464 −69
docs/features/infra.md +3 −1
@@ -103,7 +103,9 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
103103 - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. One resource says "About $12.00 a month at list price", or "No list price is known for it" and which bill any cost is inside, with no region's total beside it. An ECS service says "Its tasks, about $9.02 a month at list price", and only the tasks are added. A bill's Tax line says it is included in the AWS total. A screen reader hears each in full. Under a filter the headline is what was found ("10 unattached volumes") and only resources' own prices are added.
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=`.
106 - **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; `sort:` and `group:` are words 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.
106 - **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 - **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`.
108 - **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.
107109 - **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.
108110 - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds (an address its balancer, NAT gateway or task; an ECS service its balancer and cluster; a balancer the services known behind it, "Shared by" when there are several; a link AWS does not state is not drawn, which does not mean nothing uses it), an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was created, when it was read, and Ask about this (a talk with those facts, fenced as data).
109111 - **Created.** An EC2 instance's is when its primary network interface was attached, which is its first launch: AWS's `launchTime` is its last start and is not shown. "not known" when the cloud does not state a date, or the forge does not read one (an AWS address, function, table, cluster or zone). An S3 bucket's is "Created, or last changed", because AWS moves it when the bucket changes, its policy for one; a filter by `created:` uses that date all the same.
src/actions/infra.ts +2 −2
@@ -16,7 +16,7 @@
1616 import type { App } from "../app.ts";
1717 import { accountReads, projectsOf, refreshProjects } from "../cloud/projects.ts";
1818 import { containersOf } from "../cloud/containers.ts";
19 import { cloudTree, parseCloudQuery, type CloudView } from "../cloud/tree.ts";
19 import { cloudTree, cloudUnknowns, parseCloudQuery, type CloudView } from "../cloud/tree.ts";
2020 import { requestConsole, type ProviderConsole } from "../cloud/provider_console.ts";
2121 import { gatedFetch } from "../cloud/gate.ts";
2222 import { resolveSecrets } from "../core/secret_store.ts";
@@ -836,7 +836,7 @@ export function cloudResources(app: App, actor: User | undefined, line: string,
836836 const [projects, reads] = [projectsOf(app.db), accountReads(app.db)];
837837 const inside = containersOf(app.db, who.value, now);
838838 const whole = cloudTree(projects, reads, held, parseCloudQuery(""), now, inside);
839 return ok({ root: q.text === "" ? whole : cloudTree(projects, reads, held, q, now, inside), whole, q, held: held.length, now });
839 return ok({ root: q.text === "" ? whole : cloudTree(projects, reads, held, q, now, inside), whole, q, unknown: cloudUnknowns(whole, q, now), held: held.length, now });
840840 }
841841
842842 /**
src/cloud/tree.ts +41 −8
@@ -15,7 +15,8 @@ import { dollars } from "./prices.ts";
1515 import { PROJECT_CLOUDS, readEveryMs, type AccountRead, type CloudResource, type ProjectView } from "./projects.ts";
1616 import { agoWords } from "../kernel/ago.ts";
1717 import { LABEL, isProvider } from "./providers.ts";
18 import { holds, parseLine, wordsOf, type Line, type List } from "../list/line.ts";
18 import { fieldOf, holds, parseLine, wordsOf, type Line, type List } from "../list/line.ts";
19 import { sorted, sortSays, unknownSays, unknownsOf, type Unknown } from "../list/order.ts";
1920
2021 /** What some resources cost a month, and how much of that is known. */
2122 export interface Money {
@@ -359,6 +360,8 @@ export interface CloudView {
359360 */
360361 readonly whole: CloudNode;
361362 readonly q: CloudQuery;
363 /** What the line's comparisons could not judge, over the whole tree. */
364 readonly unknown: readonly Unknown[];
362365 /** How many accounts the forge holds; none is its own state. */
363366 readonly held: number;
364367 readonly now: number;
@@ -390,7 +393,7 @@ export function resourcesOf(n: CloudNode): CloudNode[] {
390393 export const costliestOf = (n: CloudNode): CloudNode[] => resourcesOf(n).sort(costliest);
391394
392395 /** Where a list stops short, what it leaves out and how to see it; empty when it names them all. */
393 export const cutSays = (shown: number, more: number, how: string): string => (more <= 0 ? "" : `${shown.toLocaleString("en-US")} named here, the costliest first; ${more.toLocaleString("en-US")} more: ${how}`);
396 export const cutSays = (shown: number, more: number, how: string, order = "the costliest first"): string => (more <= 0 ? "" : `${shown.toLocaleString("en-US")} named here, ${order}; ${more.toLocaleString("en-US")} more: ${how}`);
394397
395398 // ---- the filter line ----
396399
@@ -425,8 +428,10 @@ const LIST: List<Placed> = {
425428 { name: "for", type: "text", of: ({ r }) => r.label, blank: "none" },
426429 { name: "app", type: "text", of: ({ r }) => r.partOf?.app ?? "", blank: "unknown" },
427430 { name: "cost", type: "number", of: ({ r }) => r.cents, blank: "unknown", takes: "dollars a month, like cost:>10" },
428 { name: "created", type: "time", of: ({ r }) => r.createdAt, blank: "unknown", takes: "an age or a date, like created:<7d or created:>2026-12-01" },
431 { name: "created", type: "time", of: ({ r }) => r.createdAt, blank: "unknown", noun: "created date", takes: "an age or a date, like created:<7d or created:>2026-12-01" },
429432 ],
433 columns: ["name", "kind", "state", "size", "region", "created", "cost"],
434 most: { chars: 200, words: 12 },
430435 };
431436
432437 /** The properties a filter line takes, as every door lists them. */
@@ -440,19 +445,47 @@ export interface CloudQuery {
440445 readonly problems: readonly string[];
441446 }
442447
448 const placed = (whole: CloudNode, n: CloudNode): Placed => ({ r: n.resource!, project: nodeAt(whole, n.path.slice(0, 3))?.name ?? "" });
449
450 /**
451 * Every resource under a node in the line's own order, the costliest first where it has none: the
452 * lists, not the tree, whose branches carry bills that are no sum of rows.
453 */
454 export const listedOf = (v: CloudView, n: CloudNode): CloudNode[] => sorted(LIST, v.q.line, costliestOf(n), (c) => placed(v.whole, c));
455
456 /** The order of a list in words, after "the first 200, ". */
457 export const orderSays = (q: CloudQuery): string => (q.line.sort.length === 0 ? "the costliest first" : sortSays(LIST, q.line));
458
459 /** What a comparison could not judge: rows left out, or let in, for a value that is not known. */
460 export const cloudUnknowns = (whole: CloudNode, q: CloudQuery, now: number): Unknown[] => (q.line.terms.length === 0 ? [] : unknownsOf(LIST, q.line, resourcesOf(whole).map((n) => placed(whole, n)), now));
461
462 /** The columns of a list of resources. */
463 export const CLOUD_COLUMNS = LIST.columns!.map((name) => ({ field: fieldOf(LIST.fields, name)!, label: `${name.charAt(0).toUpperCase()}${name.slice(1)}` }));
464
465 /** A resource's cell, as every door says it; the page draws its own name and cost. */
466 export function cloudCell(n: CloudNode, field: string): string {
467 const r = n.resource!;
468 if (field === "name") return n.name;
469 if (field === "state") return unused(r) ? "unattached" : r.state;
470 if (field === "created") return r.createdAt === "" ? "not known" : `${r.createdAt.slice(0, 10)}${createdLabel(r) === "Created" ? "" : ", or changed"}`;
471 if (field === "cost") return [moneyMark(n.money).mark, moneyMark(n.money).sum].filter((x) => x !== "").join(" ");
472 return field === "kind" ? r.kind : field === "size" ? r.size : r.region;
473 }
474
443475 /** A filter line for the cloud tree, in the language every list shares (`list/line.ts`). */
444476 export function parseCloudQuery(typed: string): CloudQuery {
445 const line = parseLine(typed, LIST.fields, { chars: 200, words: 12 });
477 const line = parseLine(typed, LIST);
446478 return { text: line.text, line, problems: line.problems.filter((p) => p.level === "slip" || p.level === "wide").map((p) => p.says) };
447479 }
448480
449481 /**
450 * What every door says beside the rows: the line's problems, how its marks, quotes and dates were
451 * read, and, with nothing found, what is half typed in it.
482 * What every door says beside the rows, the most needed first: the line's problems (with nothing
483 * found, also what is half typed), the rows a value not known left out, and how its marks, quotes
484 * and dates were read.
452485 */
453 export function readingOf(v: CloudView): string[] {
486 export function readingOf(v: CloudView): { readonly problems: string[]; readonly unknown: string[]; readonly words: string[] } {
454487 const half = v.root.count > 0 ? [] : v.q.line.problems.filter((p) => p.level === "half" && p.says !== "").map((p) => p.says);
455 return [...v.q.problems, ...half, ...wordsOf(v.q.line, LIST.fields)];
488 return { problems: [...v.q.problems, ...half], unknown: unknownSays(LIST, v.unknown), words: wordsOf(v.q.line, LIST.fields) };
456489 }
457490
458491 /** One offered narrowing: the term it adds, its words, and how many resources it would leave. */
src/http/mcp/tools/infra.ts +10 −9
@@ -1,7 +1,7 @@
11 import { cloudLinesFresh } from "../../../actions/cloud_says.ts";
22 import { infraCode } from "../../../cloud/infra_read.ts";
33 import { accountReads, projectsOf, projectsSays } from "../../../cloud/projects.ts";
4 import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, moneyWords, nodeAt, pathIn, readingOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts";
4 import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, listedOf, moneyWords, nodeAt, orderSays, pathIn, readingOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts";
55 import { buildOf, cloudResources, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
66 import { machineView } from "../../../actions/machine_view.ts";
77 import { bindBucket, readBucket } from "../../../actions/bucket.ts";
@@ -27,15 +27,15 @@ function attachedTo(whole: CloudNode, n: CloudNode): { id: string; name?: string
2727 }
2828
2929 /**
30 * Cloud resources a page at a time, the costliest first, each with the app it is part of (null when
30 * Cloud resources a page at a time, in the order given, each with the app it is part of (null when
3131 * none is known) and what it is attached to, beside `rest`. `says` ends with how many more there
3232 * are, so no list reads as whole when it is not.
3333 */
34 function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: string, rest: object): Answer {
34 function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: string, rest: object, order?: string): Answer {
3535 const page = pageRows(nodes, (n) => n.path.join("/"), args);
3636 if (!page.ok) return page;
3737 const { items, next_cursor } = page.value as { items: CloudNode[]; next_cursor: string | null };
38 const more = next_cursor === null ? "" : cutSays(items.length, nodes.length - nodes.indexOf(items.at(-1)!) - 1, "pass next_cursor as cursor, or narrow the filter");
38 const more = next_cursor === null ? "" : cutSays(items.length, nodes.length - nodes.indexOf(items.at(-1)!) - 1, "pass next_cursor as cursor, or narrow the filter", order);
3939 return good({
4040 says: more === "" ? says : `${says.replace(/\.$/, "")}. ${more}`,
4141 ...rest,
@@ -53,7 +53,7 @@ function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says:
5353 export const tool: Tool = {
5454 name: "infra",
5555 listedTo: "admin",
56 doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cloud:aws cost:>10`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read; a game box's machine names its `containers`, each by the `id` this takes); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
56 doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cost:>10 sort:-created`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read; a game box's machine names its `containers`, each by the `id` this takes); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
5757 description: "Machines, spend.",
5858 inputSchema: {
5959 type: "object",
@@ -80,15 +80,16 @@ export const tool: Tool = {
8080 const names = Array.isArray(args["names"]) ? args["names"].slice(0, 20).map((n) => s(n, 40)) : [];
8181 const id = s(args["id"], 300);
8282 if (action === "list" && id !== "") {
83 // A filter line, /infra's own: every cloud resource it leaves, the costliest first.
83 // A filter line, /infra's own: every cloud resource it leaves, in its own order.
8484 const v = cloudResources(ctx.app, user, id);
8585 if (!v.ok) return bad("not_found", "no such tool here");
8686 const wide = refusalOf(v.value.q.line);
8787 if (wide !== undefined) return bad("invalid_filter", `${wide.says} (at character ${wide.at + 1}) Nothing was listed, because without that part the line finds more than was asked. The fields are ${CLOUD_PROPS.join(", ")}.`);
88 const all = costliestOf(v.value.root);
88 const all = listedOf(v.value, v.value.root);
89 const reading = readingOf(v.value);
8990 const f = findingOf(v.value);
90 const says = [f.found, f.cost, f.caveat, ...readingOf(v.value)].filter((x) => x !== "").map((x, i, all) => (i < all.length - 1 ? x.replace(/\.$/, "") : x)).join(". ");
91 return named(v.value.whole, all, args, says, { problems: v.value.q.problems });
91 const says = [f.found, f.cost, f.caveat, ...reading.problems, ...reading.unknown, ...reading.words].filter((x) => x !== "").map((x, i, all) => (i < all.length - 1 ? x.replace(/\.$/, "") : x)).join(". ");
92 return named(v.value.whole, all, args, says, { problems: v.value.q.problems, unknown: v.value.unknown }, orderSays(v.value.q));
9293 }
9394 if (action === "list") {
9495 const v = infraOf(ctx.app, user);
src/list/line.ts +70 −18
@@ -28,12 +28,21 @@ export interface Field<R> {
2828 readonly blank?: "none" | "unknown";
2929 /** For a field with an order: what it takes, as the sentence about a bad value says it. */
3030 readonly takes?: string;
31 /** What is not known when it is empty, where its name does not say it: "created date". */
32 readonly noun?: string;
3133 }
3234
33 export interface List<R> {
35 /** What a line can ask of a list, without its rows. */
36 export interface Shape<F = Named> {
37 readonly fields: readonly F[];
38 /** The fields its table shows, in order. With these it can be sorted, by any field. */
39 readonly columns?: readonly string[];
40 readonly most?: { readonly chars: number; readonly words: number };
41 }
42
43 export interface List<R> extends Shape<Field<R>> {
3444 /** What plain words look in, its parts apart by line breaks. */
3545 readonly text: (r: R) => string;
36 readonly fields: readonly Field<R>[];
3746 }
3847
3948 interface Choice {
@@ -44,7 +53,7 @@ interface Choice {
4453 readonly literal: boolean;
4554 }
4655
47 interface Term {
56 export interface Term {
4857 /** Null is plain text, somewhere in the row. */
4958 readonly field: string | null;
5059 readonly not: boolean;
@@ -67,6 +76,10 @@ export interface Line {
6776 /** As typed, within the list's limit. */
6877 readonly text: string;
6978 readonly terms: readonly Term[];
79 /** The first decides, the next its ties; `down` is the largest, the newest or Z first. */
80 readonly sort: readonly { readonly field: string; readonly down: boolean }[];
81 /** Where each `sort:` is in the text. */
82 readonly sortAt: readonly (readonly [number, number])[];
7083 readonly problems: readonly Problem[];
7184 /** Its last quote is not closed, so nothing can be added after it. */
7285 readonly open: boolean;
@@ -80,8 +93,8 @@ const AGE = /^(\d+(?:\.\d+)?)([smhdw])$/;
8093 const DATE = /^\d{4}-\d\d-\d\d(?:t\d\d:\d\d(?::\d\d)?(?:z|[+-]\d\d:\d\d)?)?$/;
8194 const SPAN = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 } as const;
8295
83 const fieldOf = <F extends { readonly name: string }>(fields: readonly F[], name: string): F | undefined => fields.find((f) => f.name.toLowerCase() === name.toLowerCase());
84 const ordered = (f: Pick<Named, "type">): boolean => f.type === "number" || f.type === "time";
96 export const fieldOf = <F extends { readonly name: string }>(fields: readonly F[], name: string): F | undefined => fields.find((f) => f.name.toLowerCase() === name.toLowerCase());
97 export const ordered = (f: Pick<Named, "type">): boolean => f.type === "number" || f.type === "time";
8598
8699 const cents = (value: string): number | undefined => (/^\$?\d+(\.\d+)?$/.test(value) ? Math.round(Number(value.replace("$", "")) * 100) : undefined);
87100
@@ -109,12 +122,15 @@ function unknownField(name: string, fields: readonly Named[]): string {
109122 }
110123
111124 /** A line's terms and what is wrong with it. It never fails: what cannot be read is a problem. */
112 export function parseLine(line: string, fields: readonly Named[], most: { readonly chars: number; readonly words: number } = { chars: 500, words: 20 }): Line {
125 export function parseLine(line: string, list: Shape): Line {
126 const { fields, columns, most = { chars: 500, words: 20 } } = list;
113127 const whole = line.trim();
114128 // Cut inside an emoji, half of it is left, and no link can encode that.
115129 const text = whole.slice(0, most.chars).toWellFormed();
116130 const terms: Term[] = [];
117131 const problems: Problem[] = [];
132 const sort: { field: string; down: boolean }[] = [];
133 const sortAt: [number, number][] = [];
118134 let i = 0;
119135 let open = false;
120136 const space = (at: number): boolean => at >= text.length || /\s/.test(text[at]!);
@@ -136,6 +152,25 @@ export function parseLine(line: string, fields: readonly Named[], most: { readon
136152 return { value: (value + text.slice(from, i)).toLowerCase(), literal };
137153 };
138154
155 /** The keys after `sort:`, 3 at most in a line; one this list cannot sort by is left out. */
156 const sortKeys = (at: number): void => {
157 let keys = 0;
158 for (; ; i++) {
159 const down = text[i] === "-";
160 if (down) i++;
161 const { value } = word(true);
162 const f = fieldOf(fields, value);
163 if (value !== "") keys++;
164 if (value !== "" && f === undefined) problem(at, "slip", `This list cannot sort by "${short(value)}"; it can by ${fields.map((x) => x.name).join(", ")}.`);
165 else if (f !== undefined && !sort.some((k) => k.field === f.name)) {
166 if (sort.length < 3) sort.push({ field: f.name, down });
167 else problem(at, "slip", `A line sorts by 3 fields at most, so ${f.name} is left out.`);
168 }
169 if (text[i] !== ",") break;
170 }
171 if (keys === 0) problem(at, "half", "");
172 };
173
139174 for (let count = 0; ; count++) {
140175 while (i < text.length && space(i)) i++;
141176 if (i >= text.length) break;
@@ -148,8 +183,20 @@ export function parseLine(line: string, fields: readonly Named[], most: { readon
148183 const m = HEAD.exec(text);
149184 const quoted = m?.[2]?.replace(/\\(["\\])/g, "$1");
150185 const name = quoted ?? m?.[3] ?? "";
151 const f = m === null ? undefined : fieldOf(fields, name);
152186 const view = /^(sort|group)$/i.exec(m?.[3] ?? "")?.[1]!.toLowerCase();
187 // A field with one of those names is quoted.
188 const f = m === null || view !== undefined ? undefined : fieldOf(fields, name);
189
190 if (m !== null && view === "sort" && columns !== undefined) {
191 i += m[0].length;
192 if (m[1] === "") sortKeys(at);
193 else {
194 word(false);
195 problem(at, "slip", "sort: takes no mark before it: write sort:-name for the largest, the newest or Z first.");
196 }
197 sortAt.push([at, Math.min(i, text.length)]);
198 continue;
199 }
153200
154201 if (m !== null && (f !== undefined || view !== undefined)) {
155202 i += m[0].length;
@@ -205,7 +252,7 @@ export function parseLine(line: string, fields: readonly Named[], most: { readon
205252 }
206253 if (open) problem(text.lastIndexOf('"'), "half", "The quote is not closed, so all after it is in it.");
207254 if (whole.length > most.chars) problem(most.chars, "wide", `A line here is at most ${most.chars} characters, so this is left out: ${short(whole.slice(most.chars).toWellFormed().trim())}`);
208 return { text, terms, problems, open };
255 return { text, terms, sort, sortAt, problems, open };
209256 }
210257
211258 /**
@@ -223,28 +270,33 @@ function timeHolds(have: number, c: Choice, now: number): boolean {
223270 return c.op === "<" ? have < from : c.op === "<=" ? have < to : c.op === ">" ? have >= to : c.op === ">=" ? have >= from : have >= from && have < to;
224271 }
225272
273 /** Whether a row has no value for a field; a time that is no date is none. */
274 export function blankIn<R>(f: Field<R>, r: R): boolean {
275 const have = f.of(r);
276 return have === null || have === "" || (f.type === "time" && Number.isNaN(Date.parse(String(have))));
277 }
278
226279 function choiceHolds<R>(f: Field<R>, c: Choice, r: R, now: number): boolean {
227280 const have = f.of(r);
228 const at = f.type === "time" ? Date.parse(String(have)) : 0;
229 const empty = have === null || have === "" || Number.isNaN(at);
281 const empty = blankIn(f, r);
230282 if (!c.literal && c.value === f.blank) return empty;
231283 // A comparison never holds for what is not known.
232284 if (empty) return false;
233285 if (f.type === "number") return compared(Number(have), c.op, cents(c.value)!);
234 if (f.type === "time") return timeHolds(at, c, now);
286 if (f.type === "time") return timeHolds(Date.parse(String(have)), c, now);
235287 const value = String(have).toLowerCase();
236288 return f.type === "word" ? value === c.value : f.type === "start" ? value.startsWith(c.value) : value.includes(c.value);
237289 }
238290
239 /** Whether every term holds for one row. */
240 export function holds<R>(list: List<R>, line: Line, r: R, now: number): boolean {
241 return line.terms.every((t) => {
242 const f = t.field === null ? undefined : fieldOf(list.fields, t.field)!;
243 const text = f === undefined ? list.text(r).toLowerCase() : "";
244 return t.any.some((c) => (f === undefined ? text.includes(c.value) : choiceHolds(f, c, r, now))) !== t.not;
245 });
291 export function termHolds<R>(list: List<R>, t: Term, r: R, now: number): boolean {
292 const f = t.field === null ? undefined : fieldOf(list.fields, t.field)!;
293 const text = f === undefined ? list.text(r).toLowerCase() : "";
294 return t.any.some((c) => (f === undefined ? text.includes(c.value) : choiceHolds(f, c, r, now))) !== t.not;
246295 }
247296
297 /** Whether every term holds for one row. */
298 export const holds = <R>(list: List<R>, line: Line, r: R, now: number): boolean => line.terms.every((t) => termHolds(list, t, r, now));
299
248300 /** How the parts that can be read two ways were read: a mark, quotes, an age and a date. */
249301 export function wordsOf(line: Line, fields: readonly Named[]): string[] {
250302 return line.terms.flatMap((t): string[] => {
src/list/order.ts added +94
@@ -0,0 +1,94 @@
1 /**
2 * The order of a list, and what a comparison could not judge, from its one line (`line.ts`). Pure:
3 * the page, the terminal and the tools draw the same order and the same counts.
4 */
5
6 import { blankIn, fieldOf, ordered, termHolds, type Field, type Line, type List } from "./line.ts";
7
8 /** Text with numbers inside, as people read it: `web-2` before `web-10`. */
9 const READ = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
10
11 /**
12 * The items as the line's `sort:` puts them; a copy. What is not known is last whichever way it
13 * runs, and ties keep the order they came in.
14 */
15 export function sorted<R, T>(list: List<R>, line: Line, items: readonly T[], rowOf: (t: T) => R): T[] {
16 const by = line.sort.map((k) => ({ ...k, f: fieldOf(list.fields, k.field)! }));
17 if (by.length === 0) return [...items];
18 const key = (f: Field<R>, r: R): string | number | null => (blankIn(f, r) ? null : f.type === "time" ? Date.parse(String(f.of(r))) : f.of(r));
19 return items
20 .map((item) => ({ item, keys: by.map((k) => key(k.f, rowOf(item))) }))
21 .sort((a, b) => {
22 for (const [i, k] of by.entries()) {
23 const [x, y] = [a.keys[i]!, b.keys[i]!];
24 if (x === null || y === null) {
25 if (x !== y) return x === null ? 1 : -1;
26 continue;
27 }
28 const n = typeof x === "number" && typeof y === "number" ? x - y : READ.compare(String(x), String(y));
29 if (n !== 0) return k.down ? -n : n;
30 }
31 return 0;
32 })
33 .map((x) => x.item);
34 }
35
36 /** The order in words: "sorted by created, newest first". */
37 export const sortSays = (list: Pick<List<never>, "fields">, line: Line): string =>
38 `sorted by ${line.sort
39 .map((k) => {
40 const [up, down] = { number: ["smallest", "largest"], time: ["oldest", "newest"], other: ["A", "Z"] }[((t) => (t === "number" || t === "time" ? t : "other"))(fieldOf(list.fields, k.field)!.type)];
41 return `${k.field}, ${k.down ? down : up} first`;
42 })
43 .join(", then ")}`;
44
45 /** A field's name as a line writes it. */
46 const written = (name: string): string => (/^[a-z][\w-]*$/i.test(name) && !/^(sort|group)$/i.test(name) ? name : `"${name.replace(/["\\]/g, "\\$&")}"`);
47
48 /**
49 * The line a heading leads to: numbers and times the largest or newest first and text A first, then
50 * the other way, then the list's own order.
51 */
52 export function sortLine(line: Line, f: Pick<Field<never>, "name" | "type">): string {
53 const now = line.sort.length === 1 && line.sort[0]!.field === f.name ? line.sort[0] : undefined;
54 const next = now === undefined ? { down: ordered(f) } : now.down === ordered(f) ? { down: !now.down } : undefined;
55 let rest = "";
56 let from = 0;
57 for (const [at, end] of line.sortAt) {
58 rest += line.text.slice(from, at);
59 from = end;
60 }
61 return [(rest + line.text.slice(from)).trim(), next === undefined ? "" : `sort:${next.down ? "-" : ""}${written(f.name)}`].filter((x) => x !== "").join(" ");
62 }
63
64 /** Rows whose value for a compared field is not known: left out for that alone, or let in by `!`. */
65 export interface Unknown {
66 readonly field: string;
67 readonly left: number;
68 readonly among: number;
69 }
70
71 export function unknownsOf<R>(list: List<R>, line: Line, rows: readonly R[], now: number): Unknown[] {
72 const compared = line.terms.flatMap((t) => {
73 const f = t.field === null ? undefined : fieldOf(list.fields, t.field);
74 return f === undefined || !ordered(f) || f.blank !== "unknown" || t.any.length === 0 || t.any.some((c) => !c.literal && c.value === f.blank) ? [] : [{ t, f }];
75 });
76 if (compared.length === 0) return [];
77 const count = new Map(compared.map(({ f }) => [f.name, { left: 0, among: 0 }]));
78 for (const r of rows) {
79 const failed = line.terms.filter((t) => !termHolds(list, t, r, now));
80 const blank = compared.filter(({ f }) => blankIn(f, r));
81 const alone = failed.length > 0 && failed.every((t) => blank.some((b) => b.t === t));
82 const fields = new Set(failed.length === 0 ? blank.map((b) => b.f.name) : alone ? blank.filter((b) => failed.includes(b.t)).map((b) => b.f.name) : []);
83 for (const name of fields) count.get(name)![failed.length === 0 ? "among" : "left"]++;
84 }
85 return [...count].map(([field, n]) => ({ field, ...n })).filter((n) => n.left + n.among > 0);
86 }
87
88 /** "3 more have no known created date." */
89 export const unknownSays = (list: Pick<List<never>, "fields">, all: readonly Unknown[]): string[] =>
90 all.flatMap((u) => {
91 const noun = fieldOf(list.fields, u.field)?.noun ?? u.field;
92 const say = (n: number, of: string): string[] => (n === 0 ? [] : [`${n.toLocaleString("en-US")} ${of} ${n === 1 ? "has" : "have"} no known ${noun}.`]);
93 return [...say(u.left, "more"), ...say(u.among, "of these")];
94 });
src/tui/screens/cloudtree.ts +19 −6
@@ -6,7 +6,7 @@
66 */
77
88 import { cloudResources, readProjectsNow } from "../../actions/infra.ts";
9 import { cloudName, CONTAINER_COST, containersSay, costLine, costliestOf, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, readingOf, unreadAccounts, unreadLine, unpricedSays, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts";
9 import { cloudCell, CLOUD_COLUMNS, cloudName, CONTAINER_COST, containersSay, costLine, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, listedOf, moneyMark, nodeAt, orderSays, readingOf, unreadAccounts, unreadLine, unpricedSays, type CloudNode, type CloudView } from "../../cloud/tree.ts";
1010 import { dollars } from "../../cloud/prices.ts";
1111 import { keyOf } from "../../web/keymap.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
@@ -15,6 +15,7 @@ import type { Session } from "../session.ts";
1515 import { style } from "../term/style.ts";
1616 import { truncate, wrap } from "../term/width.ts";
1717 import { fill, len, split } from "../ui/layout.ts";
18 import { tableLines } from "../ui/list.ts";
1819 import { accountScreen } from "./cloud_account.ts";
1920 import { Filter, ListState, Scroll, ago, drawLines, hitList, openOnWeb } from "./common.ts";
2021 import type { PaletteEntry } from "./entries.ts";
@@ -41,7 +42,7 @@ const markOf = (n: CloudNode): string => {
4142 const PANE_LINES = 200;
4243
4344 /** What a node says when it is open: its cost first, then its facts or its costliest resources. */
44 export function cloudLines(v: CloudView, n: CloudNode): string[] {
45 export function cloudLines(v: CloudView, n: CloudNode, width = 80): string[] {
4546 const cost = n.container !== undefined ? CONTAINER_COST : costLine(n) || (n.count === 0 ? "No resources." : unpricedSays(v, n));
4647 const head = [n.path.map((p, i) => (i === 0 ? cloudName(p) : (nodeAt(v.whole, n.path.slice(0, i + 1))?.name ?? p))).join(" ▸ "), cost];
4748 const read = n.readAt === "" ? "" : `Read ${ago(n.readAt)}${n.trouble.length === 0 && isStale(n.path[0]!, n.readAt, v.now) ? " (old)" : ""}`;
@@ -54,14 +55,15 @@ export function cloudLines(v: CloudView, n: CloudNode): string[] {
5455 return [...head, "", ...facts, `${createdLabel(n.resource).padEnd(12)} ${n.resource.createdAt.slice(0, 10) || "not known"}`, read, ...(n.children.length === 0 ? [] : ["", containersSay(n), ...n.children.map((c) => `${c.name} · ${c.container!.state} · ${c.container!.memory}`)])];
5556 const goes = v.q.text === "" ? largestCosts(n, 6).filter((c) => c.from === "billed") : [];
5657 const line = (sum: string, words: string): string => `${sum.padStart(13)} ${words}`;
57 const cut = cutSays(PANE_LINES, n.count - PANE_LINES, "/ narrows the filter");
58 const cut = cutSays(PANE_LINES, n.count - PANE_LINES, "/ narrows the filter", orderSays(v.q));
59 const rows = listedOf(v, n).slice(0, PANE_LINES).map((c) => CLOUD_COLUMNS.map(({ field }) => cloudCell(c, field.name)));
5860 return [
5961 ...head,
6062 ...(read === "" ? [] : [read]),
6163 ...trouble,
6264 ...(n.note === "" ? [] : [`${n.note}.`]),
6365 ...(goes.length === 0 ? [] : ["", "Where it goes", ...goes.map((c) => line(dollars(c.cents), `${c.says} · ${c.where}${c.hint === "" ? "" : ` · ${c.hint}`}`))]),
64 ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...costliestOf(n).slice(0, PANE_LINES).map((c) => line(markOf(c), `${c.name} · ${[c.resource!.kind, unused(c.resource!) ? "unattached" : c.resource!.state].filter((x) => x !== "").join(" · ")}`)), ...(cut === "" ? [] : [cut])]),
66 ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...tableLines(CLOUD_COLUMNS, v.q.line, rows, width), ...(cut === "" ? [] : [cut])]),
6567 ];
6668 }
6769
@@ -76,7 +78,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
7678 let note = "";
7779 /** The pane's width as last drawn: a reason is read whole, so its line wraps. */
7880 let room = 80;
79 const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(v, n).flatMap((l) => (l.length <= room ? [l] : wrap(l, room)));
81 const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(v, n, room).flatMap((l) => (l.length <= room ? [l] : wrap(l, room)));
8082 let kept: { readonly query: string; readonly view: CloudView | undefined } | undefined;
8183
8284 /**
@@ -115,6 +117,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
115117 binding(["enter", "l"], "open / expand"),
116118 binding(["h"], "collapse"),
117119 binding([keyOf("search")], "filter: kind: cloud: region: cost:>10 text"),
120 binding([keyOf("sort")], "sort the list: name, cost, -created"),
118121 binding(["tab"], "tree / what is open"),
119122 binding(["a"], "check the account: what was not read, and the fix"),
120123 binding(["w"], "open on the web"),
@@ -131,7 +134,10 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
131134 const total = v.q.text === "" ? costLine(v.root) || (v.root.count === 0 ? "" : [`${v.root.count} resources, no price known`, unreadLine(v.root)].filter((x) => x !== "").join(", ")) : [f.found, f.caveat, f.cost].filter((x) => x !== "").join(" · ");
132135 const says = note !== "" ? note : v.held === 0 ? "No cloud account is attached: press I on Cloud accounts, or open /settings/cloud." : total === "" ? "Nothing read yet: press P to read every account now." : total;
133136 const reading = readingOf(v);
134 const said = wrap([...reading, ...(v.q.problems.length > 0 ? [] : [says])].join(" "), area.w).slice(0, f.caveat === "" && reading.length === 0 ? 2 : 3);
137 // Where three lines are not enough, how the line was read is what is cut.
138 const beside = [...reading.unknown, ...reading.words];
139 const ended = beside.length === 0 || /[.…:]$/.test(says) ? says : `${says}.`;
140 const said = wrap([...reading.problems, ended, ...beside].join(" "), area.w).slice(0, f.caveat === "" && reading.problems.length + beside.length === 0 ? 2 : 3);
135141 const [head, box, body] = split(area, "v", [len(said.length), len(1), fill(1)]);
136142 said.forEach((l, i) => s.text(head!.x, head!.y + i, truncate(l, head!.w), style(c.fg, c.bg), head!.x + head!.w));
137143 const caret = filter.render(s, box!, c, "/ kind:volume cloud:aws cost:>10");
@@ -195,6 +201,13 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
195201 if (focus === "tree" && state.key(e, all.length)) return true;
196202 if (e.ctrl || e.alt) return false;
197203 const n = all[state.index]?.node;
204 if (e.key === keyOf("sort")) {
205 // The one line, with the word typed: a sort is part of the view it makes.
206 focus = "tree";
207 filter.open();
208 if (!/(^|\s)sort:$/.test(filter.query)) filter.query = `${filter.query} sort:`.trimStart();
209 return true;
210 }
198211 if (e.key === "P") {
199212 note = "Reading every account…";
200213 void readProjectsNow(f.app, f.user).then((done) => {
src/tui/ui/list.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * A list as lines of text, for every screen: the columns `src/web/list.ts` draws. The last columns
3 * go first when there is no room, and the first one gives way before a column goes.
4 */
5
6 import type { Line } from "../../list/line.ts";
7 import { displayWidth, truncate } from "../term/width.ts";
8
9 /** The first column is never cut under this many cells while another can go. */
10 const LEAD = 16;
11 const GAP = 2;
12
13 export function tableLines(columns: readonly { readonly field: { readonly name: string; readonly type: string }; readonly label: string }[], line: Line, rows: readonly (readonly string[])[], width: number): string[] {
14 const first = line.sort[0];
15 const head = columns.map((c) => `${c.label}${first?.field === c.field.name ? (first.down ? " ↓" : " ↑") : ""}`);
16 const wide = head.map((h, i) => Math.max(displayWidth(h), ...rows.map((r) => displayWidth(r[i]!))));
17 let shown = columns.length;
18 const rest = (): number => wide.slice(1, shown).reduce((n, w) => n + w + GAP, 0);
19 while (shown > 1 && rest() + Math.min(LEAD, wide[0]!) > width) shown--;
20 const size = [Math.max(1, Math.min(wide[0]!, width - rest())), ...wide.slice(1, shown)];
21 return [head, ...rows].map((cells) =>
22 size
23 .map((w, i) => {
24 const text = truncate(cells[i]!, w);
25 const gap = " ".repeat(Math.max(0, w - displayWidth(text)));
26 return columns[i]!.field.type === "number" ? gap + text : text + gap;
27 })
28 .join(" ".repeat(GAP))
29 .trimEnd(),
30 );
31 }
src/web/keymap.ts +1 −1
@@ -101,7 +101,7 @@ export const VERBS = {
101101 now: { key: "n", label: "Now", what: "Jump to now", kinds: ["space"] },
102102 nextBody: { key: "]", label: "Next", what: "Go to the next body", kinds: ["space"] },
103103 prevBody: { key: "[", label: "Previous", what: "Go to the previous body", kinds: ["space"] },
104 sort: { key: "S", label: "Sort", what: "Sort the table by the other measure (CPU, memory)", kinds: ["table"] },
104 sort: { key: "S", label: "Sort", what: "Sort the list (on System, by the other measure: CPU, memory)", kinds: ["table"] },
105105 set: { key: "Enter", label: "Set", what: "Set the figure to what it shows", kinds: ["figure"] },
106106 undo: { key: "z", label: "Undo", what: "Put back what was just done", kinds: ["any"] },
107107 edit: { key: "e", label: "Propose a change", what: "Propose a change to the file", kinds: ["file"] },
src/web/list.ts added +33
@@ -0,0 +1,33 @@
1 /**
2 * A list as a table, for every page: its columns are the list's (`src/list/line.ts`), and a heading
3 * is a link that rewrites `sort:` in the line, so a view is always its address. No script.
4 */
5
6 import type { Field, Line } from "../list/line.ts";
7 import { sortLine } from "../list/order.ts";
8 import { html, type Html } from "./html.ts";
9
10 export interface TableOf<T> {
11 readonly columns: readonly { readonly field: Pick<Field<never>, "name" | "type">; readonly label: string }[];
12 readonly line: Line;
13 readonly rows: readonly T[];
14 readonly cell: (row: T, field: string) => Html | string;
15 /** Where a line leads, on this page. */
16 readonly href: (line: string) => string;
17 readonly caption: string;
18 }
19
20 export function listTable<T>(o: TableOf<T>): Html {
21 const first = o.line.sort[0];
22 const num = (type: string): Html | null => (type === "number" ? html` class="num"` : null);
23 return html`<div class="table-scroll"><table class="table" data-dense data-sortable data-sticky-lead>
24 <caption class="sr-only">${o.caption}</caption>
25 <thead><tr>${o.columns.map(
26 (c) => html`<th scope="col"${num(c.field.type)}${first?.field === c.field.name ? html` aria-sort="${first.down ? "descending" : "ascending"}"` : null}>${
27 // After a quote that is not closed, a sort would be inside it.
28 o.line.open ? c.label : html`<a href="${o.href(sortLine(o.line, c.field))}">${c.label}</a>`
29 }</th>`,
30 )}</tr></thead>
31 <tbody>${o.rows.map((r) => html`<tr>${o.columns.map((c) => html`<td${num(c.field.type)}>${o.cell(r, c.field.name)}</td>`)}</tr>`)}</tbody>
32 </table></div>`;
33 }
src/web/pages/cloud_tree.ts +20 −18
@@ -13,7 +13,10 @@
1313 import {
1414 CLOUD_PROPS,
1515 cloudName,
16 costliestOf,
16 cloudCell,
17 CLOUD_COLUMNS,
18 listedOf,
19 orderSays,
1720 createdLabel,
1821 facetsOf,
1922 readingOf,
@@ -48,6 +51,7 @@ import { emptySection } from "../empty_words.ts";
4851 import { html, raw, type Html } from "../html.ts";
4952 import { icon } from "../icons.ts";
5053 import { keyOf } from "../keymap.ts";
54 import { listTable } from "../list.ts";
5155 import { btn, copyField, crumbs, hintAttr, row, rowList, time } from "../ui.ts";
5256 import { codeLayout, COLUMN_WINDOW } from "./explorer.ts";
5357 import { treeStep } from "./family_tree_js.ts";
@@ -108,7 +112,7 @@ function level(v: CloudView, n: CloudNode, current: readonly string[], openAll:
108112 </details><a class="ex-file ex-total" tabindex="-1" href="${href}" aria-label="${c.name}: ${moneyWords(c.money) || "no resources"}">${cost(c)}</a></li>`;
109113 }),
110114 ...(n.empty === 0 ? [] : [html`<li><span class="muted">${n.empty} more with nothing in ${n.empty === 1 ? "it" : "them"}</span></li>`]),
111 ...(n.children.length > shown.length ? [html`<li><a class="ex-more" href="${cloudHref(n.path, v.q)}" data-ex-page>All ${n.children.length.toLocaleString("en-US")}, costliest first</a></li>`] : []),
115 ...(n.children.length > shown.length ? [html`<li><a class="ex-more" href="${cloudHref(n.path, v.q)}" data-ex-page>All ${n.children.length.toLocaleString("en-US")}, ${orderSays(v.q)}</a></li>`] : []),
112116 ]);
113117 }
114118
@@ -118,13 +122,14 @@ export const cloudBranch = (v: CloudView, n: CloudNode): Html => level(v, n, n.p
118122 /** The region a filter swaps: the narrowings it offers, what it left, and the tree. */
119123 export function cloudList(v: CloudView, current: readonly string[]): Html {
120124 const { root, q } = v;
125 const reading = readingOf(v);
121126 const filtering = q.text !== "";
122127 const openAll = root.count <= (filtering ? OPEN_ALL : OPEN_SMALL);
123128 return html`<div id="cloud-list" data-q="${q.text}">
124 ${readingOf(v).map((p) => html`<p class="small" role="status">${p}</p>`)}
129 ${[...reading.problems, ...reading.unknown, ...reading.words].map((p) => html`<p class="small" role="status">${p}</p>`)}
125130 <p class="ex-facets small">${facetsOf(root, q).map(
126131 (f) => html`<a href="${withQuery("/infra", { ...q, text: `${q.text} ${f.term}`.trim() })}" data-term="${f.term}">${f.term} <span class="num muted">${f.count}</span></a> `,
127 )}</p>
132 )}${q.line.open || root.count < 2 ? null : html`<a href="${withQuery("/infra", { ...q, text: `${q.text} sort:`.trim() })}" data-term="sort:" data-shortcut="${keyOf("sort")}" ${hintAttr(keyOf("sort"))}>sort:</a>`}</p>
128133 ${filtering ? html`<p class="small"><a href="/infra">Clear the filter</a></p>` : null}
129134 ${marks(root)}
130135 ${level(v, root, current, openAll)}
@@ -199,27 +204,24 @@ function largest(v: CloudView, n: CloudNode, most = 6): Html {
199204 }
200205
201206 /**
202 * Every resource at or under a node, the costliest first, and once above them what has no price.
207 * Every resource at or under a node, in the line's order, and once above them what has no price.
203208 */
204209 function listed(v: CloudView, n: CloudNode): Html {
205 const all = costliestOf(n);
210 const all = listedOf(v, n);
206211 if (all.length === 0) return html`<p>${v.q.text === "" ? "Nothing here." : "Nothing here matches the filter."}</p>`;
207212 const bare = all.filter((c) => c.resource!.cents === null).length;
208213 // A filter's headline has said how many.
209214 return html`<h2 class="${v.q.text !== "" && n.path.length === 0 ? "sr-only" : ""}">${all.length.toLocaleString("en-US")} ${all.length === 1 ? "resource" : "resources"}</h2>
210215 ${bare === 0 ? null : html`<p class="muted small">– ${bare === all.length ? "none has a price of its own" : `${bare.toLocaleString("en-US")} without a price of ${bare === 1 ? "its" : "their"} own`}.</p>`}
211 ${rowList(
212 all.slice(0, PANE_ROWS).map((c) =>
213 row({
214 href: cloudHref(c.path, v.q),
215 title: c.name,
216 meta: html`${[c.resource!.kind, unused(c.resource!) ? "unattached" : c.resource!.state, c.resource!.size, c.resource!.region].filter((x) => x !== "").join(" · ")}`,
217 trail: cost(c),
218 }),
219 ),
220 { label: "Resources, costliest first" },
221 )}
222 ${all.length > PANE_ROWS ? html`<p class="muted small">The first ${PANE_ROWS}, costliest first: filter to see the rest.</p>` : null}`;
216 ${listTable({
217 columns: CLOUD_COLUMNS,
218 line: v.q.line,
219 rows: all.slice(0, PANE_ROWS),
220 cell: (c, field) => (field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : field === "cost" ? cost(c) : cloudCell(c, field)),
221 href: (text) => cloudHref(n.path, { ...v.q, text }),
222 caption: `Resources, ${orderSays(v.q)}`,
223 })}
224 ${all.length > PANE_ROWS ? html`<p class="muted small">The first ${PANE_ROWS}, ${orderSays(v.q)}: filter to see the rest.</p>` : null}`;
223225 }
224226
225227 /** With nothing open: where the money goes and what the forge runs, or what the filter found. */
test/cloud-filter-lines.test.ts +1 −1
@@ -76,7 +76,7 @@ const DELIBERATE: readonly (readonly [string, string, string])[] = [
7676 ['"vol-1"', "B", "nothing: the quotes were part of the word"],
7777 ['name:"web"', "A", "nothing: the quotes were part of the word"],
7878 ['state:"running"', "AE", "nothing: the quotes were part of the word"],
79 ["sort:-cost", "ABCDEF !", "nothing: it was text, and is a word of the language this list does not have yet"],
79 ["sort:-cost", "ABCDEF", "nothing: it was text, and is the order"],
8080 ["sort:", "ABCDEF", "nothing: it was text"],
8181 ["group:region", "ABCDEF !", "nothing: it was text, as sort:"],
8282 ["created:>7d", "", "nothing: it was text, and is a field"],
test/cloud-tree.test.ts +43 −2
@@ -11,6 +11,7 @@ import { tmpdir } from "node:os";
1111 import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { cloudResources } from "../src/actions/infra.ts";
14 import { keyOf } from "../src/web/keymap.ts";
1415 import { costLine, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, readFixes, tiesOf, type CloudNode, type CloudView } from "../src/cloud/tree.ts";
1516 import { aboutContext, aboutLine } from "../src/core/talk_about.ts";
1617 import { createSession } from "../src/core/sessions.ts";
@@ -361,8 +362,8 @@ test("ECS clusters, services and tasks are drawn, labelled and counted, in the t
361362 expect(lines).toContain("4 resources");
362363 for (const [kind, title, , state] of things) {
363364 expect(explorer).toContain(`<span class="truncate">${title}</span><span class="ex-kind">${kind}`);
364 expect(pane).toContain(`${kind} · ${state}`);
365 expect(lines).toContain(`${title} · ${kind} · ${state}`);
365 expect(pane).toContain(`<td>${kind}</td><td>${state}</td>`);
366 expect(lines).toMatch(new RegExp(`^${title} +${kind} +${state} `, "m"));
366367 }
367368 for (const [kind, found] of [["cluster", "1 cluster"], ["service", "1 service"], ["task", "2 tasks"]] as const) {
368369 expect(await (await get(`/infra?q=${encodeURIComponent(`account:ecs kind:${kind}`)}`)).text()).toContain(found);
@@ -651,6 +652,46 @@ test("the infra tool's list says what each resource is attached to: ids it can o
651652 expect((await mcpTool(servers.url, token, "infra", { action: "list", id: "account:tied kind:machine" })).value.resources[0].attachedTo).toBeNull();
652653 });
653654
655 test("one sort at every door, over the lists and not the tree, with what a comparison could not judge", async () => {
656 ownAccount("aws", "sorts");
657 project("aws", "sorts", "us-east-1");
658 for (const [id, cents] of [["volume:s-1", 300], ["volume:s-2", -1], ["volume:s-10", 100]] as const) resource("aws", "sorts", "us-east-1", id, cents);
659 app.db.run("UPDATE cloud_resource SET created_at = '' WHERE cloud_resource_id = 'volume:s-2'");
660 const token = createToken(app.db, alice.id, "sorts", "admin").token;
661 for (const [sort, want] of [["", ["s-1", "s-10", "s-2"]], ["sort:cost", ["s-10", "s-1", "s-2"]], ["sort:-name", ["s-10", "s-2", "s-1"]], ["sort:name", ["s-1", "s-2", "s-10"]]] as const) {
662 const line = `account:sorts ${sort}`.trim();
663 const pane = await (await get(`/infra/-/aws/sorts?fragment=1&q=${encodeURIComponent(line)}`)).text();
664 expect([sort, [...pane.slice(pane.indexOf("<tbody>")).matchAll(/<td><a [^>]*>([^<]+)</g)].map((m) => m[1]!)]).toEqual([sort, [...want]]);
665 const told = await mcpTool(servers.url, token, "infra", { action: "list", id: line });
666 expect(told.value.resources.map((r: { name: string }) => r.name)).toEqual([...want]);
667 const lines = cloudLines(view(line), at(view(line), "aws", "sorts"));
668 expect(lines.flatMap((l) => /^s-\d+/.exec(l) ?? [])).toEqual([...want]);
669 }
670 // The tree keeps its own order, whose branches carry bills.
671 expect(at(view("account:sorts sort:cost"), "aws", "sorts", "us-east-1").children.map((c) => c.name)).toEqual(["s-1", "s-10", "s-2"]);
672 const line = "account:sorts created:<900w";
673 expect((await mcpTool(servers.url, token, "infra", { action: "list", id: line })).value.unknown).toEqual([{ field: "created", left: 1, among: 0 }]);
674 expect(await (await get(`/infra?q=${encodeURIComponent(line)}`)).text()).toContain("1 more has no known created date.");
675 const page = await (await get("/infra?q=account%3Asorts")).text();
676 expect(page).toContain('data-term="sort:"');
677 expect(page).toContain(`data-shortcut="${keyOf("sort")}"`);
678 // The terminal: the key types the word; a problem is first, and how the line was read is last.
679 const terminal = headlessTerminal(120, 30);
680 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
681 tui.start();
682 tui.ctx.push(cloudTreeScreen(session, tui.ctx));
683 await settleApp(tui);
684 for (const k of `/${line} !zzz kind:>volume\r${keyOf("sort")}-cost\r`) terminal.feed(k);
685 await settleApp(tui);
686 const said = tui.screen.toText().replace(/\s+/g, " ");
687 tui.stop?.();
688 expect(said).toContain(`${line} !zzz kind:>volume sort:-cost`);
689 const places = ["takes no comparison", "2 volumes matching", "1 more has no known created date"].map((x) => said.indexOf(x));
690 expect(places.every((p, i) => p >= 0 && p > (places[i - 1] ?? -1))).toBe(true);
691 for (const table of ["cloud_resource", "cloud_project"]) app.db.run(`DELETE FROM ${table} WHERE cloud_account_id = 'sorts'`);
692 app.db.run("DELETE FROM cloud_account WHERE name = 'sorts'");
693 });
694
654695 test("a date says what it is: an S3 bucket's may be its last change, and one that is missing is not known", async () => {
655696 account("aws", "dates");
656697 project("aws", "dates", "us-east-1");
test/list-line.test.ts +3 −3
@@ -25,7 +25,7 @@ const ROWS: readonly Row[] = [
2525 { name: "", kind: 'say "hi"', cents: null, made: "" },
2626 { name: "unit:7", kind: "c\\d", cents: 500, made: "2026-12-01T23:59:59Z" },
2727 ];
28 const read = (line: string) => parseLine(line, FIELDS);
28 const read = (line: string) => parseLine(line, { fields: FIELDS });
2929 /** The rows a line holds for, by number. */
3030 const rows = (line: string): string => ROWS.flatMap((r, i) => (holds(LIST, read(line), r, NOW) ? [i] : [])).join("");
3131 const levels = (line: string): string => read(line).problems.map((p) => p.level).join(" ");
@@ -71,9 +71,9 @@ test("a problem says what it is, and only a wide one is refused", () => {
7171
7272 test("past the list's limit the rest is left out, named, and wide", () => {
7373 const most = { chars: 20, words: 2 };
74 const words = parseLine("a b c d", FIELDS, most);
74 const words = parseLine("a b c d", { fields: FIELDS, most });
7575 expect([words.terms.length, words.problems[0]]).toEqual([2, { at: 4, says: "A line here is at most 2 words, so this is left out: c d", level: "wide" }]);
76 const chars = parseLine(`${"a".repeat(20)} kind:x`, FIELDS, most);
76 const chars = parseLine(`${"a".repeat(20)} kind:x`, { fields: FIELDS, most });
7777 expect([chars.text, refusalOf(chars)?.says]).toEqual(["a".repeat(20), "A line here is at most 20 characters, so this is left out: kind:x"]);
7878 });
7979
test/list-order.test.ts added +93
@@ -0,0 +1,93 @@
1 /**
2 * The order a line gives a list, what a heading does to the line, and the rows a comparison could
3 * not judge (`src/list/order.ts`); and the table both faces draw from them.
4 */
5 import { expect, test } from "bun:test";
6 import { parseLine, type List } from "../src/list/line.ts";
7 import { sorted, sortLine, sortSays, unknownSays, unknownsOf } from "../src/list/order.ts";
8 import { tableLines } from "../src/tui/ui/list.ts";
9 import { listTable } from "../src/web/list.ts";
10
11 interface Row {
12 readonly name: string;
13 readonly cents: number | null;
14 readonly made: string;
15 }
16 const NOW = Date.parse("2026-12-02T12:00:00Z");
17 const LIST: List<Row> = {
18 text: (r) => r.name,
19 fields: [
20 { name: "name", type: "text", of: (r) => r.name },
21 { name: "cost", type: "number", of: (r) => r.cents, blank: "unknown", takes: "dollars" },
22 { name: "created", type: "time", of: (r) => r.made, blank: "unknown", takes: "an age or a date", noun: "created date" },
23 { name: "Sort", type: "text", of: () => "" },
24 ],
25 columns: ["name", "cost", "created"],
26 };
27 const ROWS: readonly Row[] = [
28 { name: "web-10", cents: 900, made: "2026-12-02T11:00:00Z" },
29 { name: "web-2", cents: null, made: "" },
30 { name: "Api", cents: 10_000, made: "2026-11-01T00:00:00+02:00" },
31 { name: "", cents: 900, made: "soon" },
32 ];
33 const read = (line: string) => parseLine(line, LIST);
34 const order = (line: string): string => sorted(LIST, read(line), ROWS.map((r, i) => ({ r, i })), (x) => x.r).map((x) => x.i).join("");
35
36 test.each([
37 ["", "0123"], ["sort:name", "2103"], ["sort:-name", "0123"], ["sort:cost", "0321"], ["sort:-cost", "2031"], ["sort:created", "2013"], ["sort:-created", "0213"],
38 ["sort:cost,name", "0321"], ["sort:cost,-created", "0321"], ["sort:cost sort:-name", "0321"], ["SORT:-Cost", "2031"], ['sort:-"cost"', "2031"], ["sort:nope,-cost", "2031"], ["sort:cost,-cost", "0321"],
39 ] as const)("%p puts the rows as %p: not known is last both ways, and ties keep their order", (line, want) => {
40 expect(order(line)).toBe(want);
41 });
42
43 test("a sort the list cannot do, a mark and a fourth key are said; half typed is not", () => {
44 const says = (line: string): string => read(line).problems.map((p) => `${p.level}: ${p.says}`).join(" ");
45 expect(says("sort:labels")).toBe('slip: This list cannot sort by "labels"; it can by name, cost, created, Sort.');
46 expect(says("-sort:cost")).toStartWith("slip: sort: takes no mark before it");
47 expect(read("-sort:cost").sort).toEqual([]);
48 expect(says('sort:name,cost,created,"sort"')).toBe("slip: A line sorts by 3 fields at most, so Sort is left out.");
49 for (const line of ["sort:", "sort:-", "sort:,"]) expect(says(line)).toBe("half: ");
50 expect(parseLine("sort:cost", { fields: LIST.fields }).problems[0]!.says).toBe("This list cannot sort.");
51 });
52
53 test("a heading goes largest, newest or A first, then the other way, then back to the list's own order", () => {
54 const press = (line: string, name: string): string => sortLine(read(line), LIST.fields.find((f) => f.name === name)!);
55 expect([press("web", "cost"), press("web sort:-cost", "cost"), press("web sort:cost", "cost")]).toEqual(["web sort:-cost", "web sort:cost", "web"]);
56 expect([press("", "name"), press("sort:name", "name"), press("sort:-name", "name")]).toEqual(["sort:name", "sort:-name", ""]);
57 expect(press('sort:name "a sort:name b" sort:-cost cost:>1', "created")).toBe('"a sort:name b" cost:>1 sort:-created');
58 expect(press("", "Sort")).toBe('sort:"Sort"');
59 expect(read(press("", "Sort")).sort).toEqual([{ field: "Sort", down: false }]);
60 });
61
62 test("the order in words", () => {
63 expect(sortSays(LIST, read("sort:-created,cost,name"))).toBe("sorted by created, newest first, then cost, smallest first, then name, A first");
64 });
65
66 test("a comparison says how many rows it could not judge: left out for that alone, or let in by !", () => {
67 const says = (line: string): string => unknownSays(LIST, unknownsOf(LIST, read(line), ROWS, NOW)).join(" ");
68 expect(says("created:<7d")).toBe("2 more have no known created date.");
69 expect(says("created:<7d web")).toBe("1 more has no known created date.");
70 expect(says("created:<7d api")).toBe("");
71 expect(says("cost:>5 created:<7d")).toBe("1 more has no known cost. 2 more have no known created date.");
72 expect(says("!created:<7d")).toBe("2 of these have no known created date.");
73 for (const line of ["", "web", "cost:unknown", "created:<7d,unknown", "!cost:unknown", "name:web", "cost:,"]) expect(says(line)).toBe("");
74 });
75
76 const COLUMNS = LIST.columns!.map((name) => ({ field: LIST.fields.find((f) => f.name === name)!, label: name }));
77
78 test("the web's table: a heading is a link that rewrites the line, and the sorted one says its way", () => {
79 const draw = (line: string): string =>
80 String(listTable({ columns: COLUMNS, line: read(line), rows: ROWS, cell: (r, f) => (f === "name" ? r.name : "<b>"), href: (q) => `/x?q=${encodeURIComponent(q)}`, caption: "Rows" }));
81 expect(draw("web sort:-cost")).toContain('aria-sort="descending"><a href="/x?q=web%20sort%3Acost">cost</a>');
82 expect(draw("web")).not.toContain("aria-sort");
83 expect(draw('"web')).not.toContain("<a href");
84 expect(draw("web")).not.toContain("<b>");
85 });
86
87 test("the terminal's table: columns line up, the last go when there is no room, the name is never all gone", () => {
88 const lines = (width: number): string[] => tableLines(COLUMNS, read("sort:-cost"), [["a-long-name-of-a-thing", "$9.00", "2026-12-02"], ["b", "–", "not known"]], width);
89 expect(lines(80)).toEqual(["name cost ↓ created", "a-long-name-of-a-thing $9.00 2026-12-02", "b – not known"]);
90 expect(lines(30)[1]).toBe("a-long-name-of-a-thing $9.00");
91 expect(lines(10)[1]!.length).toBeLessThanOrEqual(10);
92 for (const w of [1, 5, 16, 24, 36, 40]) for (const l of lines(w)) expect(l.length).toBeLessThanOrEqual(w);
93 });

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

Keyboard shortcuts

Docs