Public: anyone can read this; the crew can change it.
Talk draws the two graphs the owner asked for: compute usage and shipping throughput #16330
Check · Review · Land · Live done — Landed and live in production.
talk/charts → main 0 commits
11 files
changed +207
−20
docs/features/talk-voice.md +5 −1
| @@ -54,9 +54,13 @@ A widget is a name, a title, one line telling the agent what it shows, the rende | ||
| 54 | 54 | |
| 55 | 55 | ### The forge's widgets |
| 56 | 56 | |
| 57 | Each takes `repo` (`owner/name`; without it, every repository you work on) and `days` (1 to 90, default 14, today included), and counts only what you may read. | |
| 57 | `checks` and `shipping` take `repo` (`owner/name`; without it, every repository you work on: your own and your teams') and `days` (1 to 90, default 14, today included), and count only what you may read. | |
| 58 | 58 | |
| 59 | 59 | - `checks` (chart): checks that passed and failed each day. |
| 60 | - `shipping` (chart): pulls merged each day. | |
| 61 | - `compute` (chart): the machine and the forge's own process by the hour, CPU cores, or `metric` `memory` (GiB) or `load`, over `hours` (1 to 72, default 24). Its values are levels, so its legend and the terminal say the value now, not a sum. Only who may read the machine's figures draws it: a forge admin, or an agent granted `telemetry:read`. | |
| 62 | ||
| 63 | Asked for a graph, a chart, usage, throughput or how the server is doing, the agent calls `show` with these (its brief says so). | |
| 60 | 64 | |
| 61 | 65 | ### How it is drawn |
| 62 | 66 |
src/core/pulls.ts +7 −6
| @@ -1647,20 +1647,21 @@ export function pullSummary(body: string, checkState: string): string { | ||
| 1647 | 1647 | export const MERGED_DAYS_MAX = 90; |
| 1648 | 1648 | |
| 1649 | 1649 | /** |
| 1650 | * Pulls merged into `repoId` each UTC day, the last `days` with today, oldest first: the series a | |
| 1651 | * chart of shipping draws from (`pulls` with `brief`). Read through `pull_merged` (a range on | |
| 1652 | * `merged_at`), days counted in code. A sealed pull is not counted. | |
| 1650 | * Pulls merged into these repositories each UTC day, the last `days` with today, oldest first: the | |
| 1651 | * series a chart of shipping draws from (`pulls` with `brief`, the `shipping` widget). One read | |
| 1652 | * through `pull_merged` (a range on `merged_at`) for every repository at once, days counted in | |
| 1653 | * code. A sealed pull is not counted. | |
| 1653 | 1654 | */ |
| 1654 | export function mergedPerDay(db: Database, repoId: string, days: number, now: number = Date.now()): { days: string[]; merged: number[] } { | |
| 1655 | export function mergedPerDay(db: Database, repoIds: readonly string[], days: number, now: number = Date.now()): { days: string[]; merged: number[] } { | |
| 1655 | 1656 | const today = Math.floor(now / 86_400_000); |
| 1656 | 1657 | const labels = Array.from({ length: days }, (_, i) => new Date((today - days + 1 + i) * 86_400_000).toISOString().slice(0, 10)); |
| 1657 | 1658 | const counts = new Map(labels.map((d) => [d, 0])); |
| 1658 | 1659 | const rows = db |
| 1659 | 1660 | .query<{ at: string }, [string, string]>( |
| 1660 | 1661 | `SELECT p.merged_at AS at FROM pull p INDEXED BY pull_merged JOIN issue i ON i.id = p.issue_id |
| 1661 | WHERE p.merged_at >= ?2 AND i.repo_id = ?1 AND i.sealed = 0`, | |
| 1662 | WHERE p.merged_at >= ?2 AND i.repo_id IN (SELECT value FROM json_each(?1)) AND i.sealed = 0`, | |
| 1662 | 1663 | ) |
| 1663 | .all(repoId, `${labels[0]!}T00:00:00.000Z`); | |
| 1664 | .all(JSON.stringify(repoIds), `${labels[0]!}T00:00:00.000Z`); | |
| 1664 | 1665 | for (const r of rows) { |
| 1665 | 1666 | const day = r.at.slice(0, 10); |
| 1666 | 1667 | const n = counts.get(day); |
src/core/talk_voice.ts +10 −3
| @@ -633,8 +633,13 @@ const BLOCKS = "▁▂▃▄▅▆▇█"; | ||
| 633 | 633 | * Values as block characters, scaled to `top`: a zero is the lowest block, so every day has a mark. |
| 634 | 634 | */ |
| 635 | 635 | const blocks = (xs: readonly number[], top: number): string => xs.map((v) => BLOCKS[Math.max(0, Math.min(7, Math.round((Math.max(0, v) / (top > 0 ? top : 1)) * 7)))]).join(""); |
| 636 | /** `YYYY-MM-DD` as "Nov 24". */ | |
| 637 | const dayWord = (d: string): string => (/^\d{4}-\d{2}-\d{2}$/.test(d) ? new Date(`${d}T00:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }) : d); | |
| 636 | /** `YYYY-MM-DD` as "Nov 24", and an hour (`YYYY-MM-DDTHH:…`) as "Nov 24 14:00". */ | |
| 637 | const dayWord = (d: string): string => { | |
| 638 | const day = (iso: string): string => new Date(`${iso}T00:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }); | |
| 639 | if (/^\d{4}-\d{2}-\d{2}$/.test(d)) return day(d); | |
| 640 | const hour = /^(\d{4}-\d{2}-\d{2})T(\d{2}):/.exec(d); | |
| 641 | return hour === null ? d : `${day(hour[1]!)} ${hour[2]}:00`; | |
| 642 | }; | |
| 638 | 643 | |
| 639 | 644 | /** |
| 640 | 645 | * A kept widget as the terminal prints it, in the same data the page draws: a chart as one line of |
| @@ -645,7 +650,9 @@ export function widgetLines(w: KeptWidget): string[] { | ||
| 645 | 650 | const width = Math.max(...d.series.map((s) => s.name.length)); |
| 646 | 651 | const top = Math.max(0, ...d.series.flatMap((s) => s.values)); |
| 647 | 652 | const span = d.x.length === 0 ? "no days" : `${dayWord(d.x[0]!)} to ${dayWord(d.x.at(-1)!)}`; |
| 648 | return [w.title, ...d.series.map((s) => ` ${s.name.padEnd(width)} ${blocks(s.values, top)} ${withUnit(s.values.reduce((a, b) => a + b, 0), d.unit)}`), ` ${" ".repeat(width)} ${span}`]; | |
| 653 | // Counts say their sum; levels say the last value, now. | |
| 654 | const figure = (xs: readonly number[]): string => (d.levels === true ? `${withUnit(xs.at(-1) ?? 0, d.unit)} now` : withUnit(xs.reduce((a, b) => a + b, 0), d.unit)); | |
| 655 | return [w.title, ...d.series.map((s) => ` ${s.name.padEnd(width)} ${blocks(s.values, top)} ${figure(s.values)}`), ` ${" ".repeat(width)} ${span}`]; | |
| 649 | 656 | } |
| 650 | 657 | |
| 651 | 658 | /** |
src/crew/conversation_brief.ts +1
| @@ -18,6 +18,7 @@ export const VOICE: readonly string[] = [ | ||
| 18 | 18 | "Open with the answer in one or two sentences. Then go as deep as the question deserves: when they ask why or how, or to go deeper, explain in full, and put detail they did not ask for inside a fold (a line `<details><summary>Title</summary>`, the detail, then a line `</details>`). A rule of theirs about length is about that opening and about noise, never a limit on depth they ask for.", |
| 19 | 19 | "Be brief and direct: say the thing, then stop; no preamble, no recap of what they said, no closing summary. Be the same every time: the same ask gets the same kind of answer, in the same order (what you did or found, what it means, what is next), and the same words for the same things, so they can rely on you without rereading. Spend invention where the work needs it (a name, a design, a way round a problem) and say that you chose, never on the form of the answer.", |
| 20 | 20 | "Show the forge's results, do not retell them: a tool answer that ends with a line naming a shown result (`Shown result c7`) can be drawn for the person as the forge returned it by writing a line that is exactly `::show c7`, at the margin, outside any code fence. Say in a sentence what it shows and what to look at; never copy its rows into prose, and say an empty result in a clause instead of showing it.", |
| 21 | "When the person asks for a graph or a chart, or how the server, compute, usage, shipping or throughput is doing, call `show` with the widget that draws it (`compute` for the machine's CPU, memory or load; `shipping` for pulls merged per day; `checks` for checks; `show` with no widget lists them) and place its result; never describe a series in prose or say you cannot draw it before you have called `show`.", | |
| 21 | 22 | "When a choice is small and can be undone, pick the sensible default and do it, then say in one line what you picked and how to change it; ask only when the choices lead to work that is costly to redo or cannot be undone.", |
| 22 | 23 | "A short message after a change is a correction to the last thing you changed (\"nah, rounder buttons\"): apply it there and keep everything else as it is.", |
| 23 | 24 | "After you act, say what changed and where in at most three lines, and give detail only when they ask; the known block is for questions about the state of things, never an appendix to a change.", |
src/http/mcp/tools/pulls.ts +1 −1
| @@ -38,7 +38,7 @@ export const tool: Tool = { | ||
| 38 | 38 | const days = args["days"] ?? 14; |
| 39 | 39 | if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > MERGED_DAYS_MAX) |
| 40 | 40 | return bad("invalid", `days is a whole number from 1 to ${MERGED_DAYS_MAX}`); |
| 41 | return good({ repo: `${repo.ownerName}/${repo.name}`, ...mergedPerDay(ctx.app.db, repo.id, days) }); | |
| 41 | return good({ repo: `${repo.ownerName}/${repo.name}`, ...mergedPerDay(ctx.app.db, [repo.id], days) }); | |
| 42 | 42 | } |
| 43 | 43 | if (args["repo"] === undefined) return pile(ctx, user, args); |
| 44 | 44 | const repo = repoArg(ctx, user, args); |
src/http/mcp/tools/show.ts +2 −2
| @@ -3,8 +3,8 @@ import { readWidget, searchWidgets } from "../../../widgets/registry.ts"; | ||
| 3 | 3 | |
| 4 | 4 | export const tool: Tool = { |
| 5 | 5 | name: "show", |
| 6 | doc: "`{ widget?, args?, query? }`: draw a widget (a chart of the forge's data) read as you, and in Talk get its handle for `::show cN`; with no `widget`, the widgets matching `query` with their arguments", | |
| 7 | description: "Show a chart of forge data by widget name; no widget: list them.", | |
| 6 | doc: "`{ widget?, args?, query? }`: draw a widget (a graph of the forge's data) read as you, and in Talk get its handle for `::show cN`; with no `widget`, the widgets matching `query` with their arguments", | |
| 7 | description: "Draw a graph of the forge's own data: compute usage, shipping throughput, checks. No widget: list them.", | |
| 8 | 8 | inputSchema: { |
| 9 | 9 | type: "object", |
| 10 | 10 | properties: { widget: { type: "string" }, args: { type: "object" }, query: { type: "string" } }, |
src/http/mcp/tools/usage.ts +4 −1
| @@ -28,7 +28,10 @@ export const tool: Tool = { | ||
| 28 | 28 | } |
| 29 | 29 | if (args["repo"] === undefined) { |
| 30 | 30 | if (args["days"] !== undefined) |
| 31 | return bad("invalid_days", "days needs a repo; without one the answer is today and last24h"); | |
| 31 | return bad( | |
| 32 | "invalid_days", | |
| 33 | "days counts one repository's crew spend: call usage with `repo` and `days`, or usage with neither for the forge's spend today and over the last 24 hours. The machine's CPU, memory and load over time is show with widget `compute`", | |
| 34 | ); | |
| 32 | 35 | return good(readForgeUsage(ctx.app, user)); |
| 33 | 36 | } |
| 34 | 37 | const repo = repoArg(ctx, user, args); |
src/web/talk_parts.ts +3 −2
| @@ -408,9 +408,10 @@ export function chartHtml(data: ChartData, title: string, uid: string): Html { | ||
| 408 | 408 | const xAxis = data.kind === "bar" |
| 409 | 409 | ? html`<div class="wchart-x is-slots" aria-hidden="true">${Array.from({ length: n }, (_, i) => html`<span>${picks.includes(i) ? day(i) : ""}</span>`)}</div>` |
| 410 | 410 | : html`<div class="wchart-x" aria-hidden="true">${picks.map((i) => html`<span>${day(i)}</span>`)}</div>`; |
| 411 | const totals = series.map((s) => s.values.reduce((a, v) => a + v, 0)); | |
| 411 | // Counts say their sum; levels (cores in use, memory held) say where they are now. | |
| 412 | const totals = series.map((s) => (data.levels === true ? (s.values.at(-1) ?? 0) : s.values.reduce((a, v) => a + v, 0))); | |
| 412 | 413 | const key = html`<div class="wchart-key" role="list">${series.map((s, k) => html`<span role="listitem"><i class="${s.cls}" aria-hidden="true"></i>${s.name} <b>${withUnit(totals[k]!, data.unit)}</b></span>`)}</div>`; |
| 413 | const summary = n === 0 ? `${title}: no points.` : `${title}, ${day(0)} to ${day(n - 1)}: ${series.map((s, k) => `${s.name} ${withUnit(totals[k]!, data.unit)} in all`).join("; ")}.`; | |
| 414 | const summary = n === 0 ? `${title}: no points.` : `${title}, ${day(0)} to ${day(n - 1)}: ${series.map((s, k) => `${s.name} ${withUnit(totals[k]!, data.unit)}${data.levels === true ? " now" : " in all"}`).join("; ")}.`; | |
| 414 | 415 | // In a box, not on the table: a table grows to its cells whatever width it is given. |
| 415 | 416 | const table = html`<div class="sr-only"><table><caption>${title}</caption><thead><tr><th scope="col">Day</th>${series.map((s) => html`<th scope="col">${s.name}</th>`)}</tr></thead><tbody>${Array.from({ length: n }, (_, i) => html`<tr><th scope="row">${day(i)}</th>${series.map((s) => html`<td>${withUnit(s.values[i]!, data.unit)}</td>`)}</tr>`)}</tbody></table></div>`; |
| 416 | 417 | return html`<figure class="wchart" data-kind="${data.kind}" role="group" aria-label="${summary.slice(0, 300)}"> |
src/widgets/registry.ts +92 −1
| @@ -13,6 +13,10 @@ | ||
| 13 | 13 | import type { App } from "../app.ts"; |
| 14 | 14 | import type { User } from "../core/users.ts"; |
| 15 | 15 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 16 | import { noteRead, telemetryReader } from "../actions/telemetry.ts"; | |
| 17 | import { mergedPerDay } from "../core/pulls.ts"; | |
| 18 | import { historyBrief } from "../system/telemetry.ts"; | |
| 19 | import { withUnit } from "../core/talk_voice.ts"; | |
| 16 | 20 | import type { Database } from "bun:sqlite"; |
| 17 | 21 | import { canRead, getRepo, listReposWritableTo, type Repo } from "../core/repos.ts"; |
| 18 | 22 | |
| @@ -34,6 +38,11 @@ export interface ChartData { | ||
| 34 | 38 | }[]; |
| 35 | 39 | /** What a value counts, said after it: "checks", "$", "hours". */ |
| 36 | 40 | readonly unit?: string; |
| 41 | /** | |
| 42 | * The values are levels (cores in use, memory held), not counts: the legend and the terminal say | |
| 43 | * the last one, "now", never their sum. | |
| 44 | */ | |
| 45 | readonly levels?: boolean; | |
| 37 | 46 | } |
| 38 | 47 | export type WidgetData = ChartData; |
| 39 | 48 | |
| @@ -168,6 +177,7 @@ export const DATA_SCHEMA: Readonly<Record<Renderer, Schema>> = { | ||
| 168 | 177 | }, |
| 169 | 178 | }, |
| 170 | 179 | unit: { type: "string", maxLength: 20 }, |
| 180 | levels: { type: "boolean" }, | |
| 171 | 181 | }, |
| 172 | 182 | }, |
| 173 | 183 | }; |
| @@ -321,8 +331,89 @@ const checks: Widget = { | ||
| 321 | 331 | }, |
| 322 | 332 | }; |
| 323 | 333 | |
| 334 | /** What `compute` charts, each in its own unit. */ | |
| 335 | const METRICS = { | |
| 336 | cpu: { title: "CPU in use", unit: "cores", of: "cpuCores" }, | |
| 337 | memory: { title: "Memory in use", unit: "GiB", of: "memoryGiB" }, | |
| 338 | load: { title: "Load", unit: "", of: "load" }, | |
| 339 | } as const; | |
| 340 | ||
| 341 | /** | |
| 342 | * The forge's machine over the last hours: cores in use (or memory, or load) each hour, for the | |
| 343 | * node and the forge's own process, from the same hourly history `telemetry_history { brief }` | |
| 344 | * answers. Who may read the machine's figures may draw it (an admin, or an agent granted | |
| 345 | * `telemetry:read`); anyone else is not found. | |
| 346 | */ | |
| 347 | const compute: Widget = { | |
| 348 | name: "compute", | |
| 349 | title: "Compute usage", | |
| 350 | description: | |
| 351 | "Compute usage by the hour: CPU cores, or `metric` memory or load. For: how is the server doing, a graph of compute or CPU usage. An admin's.", | |
| 352 | renderer: "chart", | |
| 353 | args: { | |
| 354 | type: "object", | |
| 355 | additionalProperties: false, | |
| 356 | properties: { | |
| 357 | hours: { type: "integer", minimum: 1, maximum: 72, description: "how many hours back (default 24)" }, | |
| 358 | metric: { type: "string", enum: ["cpu", "memory", "load"], description: "cpu (default), memory or load" }, | |
| 359 | }, | |
| 360 | }, | |
| 361 | read(app, user, args) { | |
| 362 | const reader = telemetryReader(app, user); | |
| 363 | if (reader === undefined || user === undefined) return err("not_found"); | |
| 364 | noteRead(app, user, reader, "history"); | |
| 365 | const hours = typeof args["hours"] === "number" ? args["hours"] : 24; | |
| 366 | const metric = METRICS[args["metric"] === "memory" || args["metric"] === "load" ? args["metric"] : "cpu"]; | |
| 367 | const brief = historyBrief(app, hours); | |
| 368 | // An hour with no sample carries the last one forward, so a line never drops to zero for a gap. | |
| 369 | const filled = (xs: readonly (number | null)[]): number[] => { | |
| 370 | let last = 0; | |
| 371 | return xs.map((v) => (last = v ?? last)); | |
| 372 | }; | |
| 373 | const node = filled(brief.node[metric.of]); | |
| 374 | const forge = brief.forge[metric.of].some((v) => v !== null) ? filled(brief.forge[metric.of]) : undefined; | |
| 375 | const peak = Math.max(0, ...node); | |
| 376 | const at = (v: number): string => (metric.unit === "" ? said(v) : withUnit(v, metric.unit)); | |
| 377 | return ok({ | |
| 378 | data: { kind: "line", x: brief.at.map((h) => `${h}:00:00.000Z`), unit: metric.unit, levels: true, series: [{ name: "Machine", values: node }, ...(forge === undefined ? [] : [{ name: "Forge", values: forge }])] }, | |
| 379 | says: | |
| 380 | node.length === 0 | |
| 381 | ? `No machine samples in the last ${hours} hours.` | |
| 382 | : `${metric.title} on the machine: ${at(node.at(-1)!)} now, ${at(peak)} at the busiest hour of the last ${hours}${forge === undefined ? "" : `; the forge's own process ${at(forge.at(-1)!)} now`}.`, | |
| 383 | }); | |
| 384 | }, | |
| 385 | }; | |
| 386 | ||
| 387 | /** | |
| 388 | * Pulls merged each day: the shipping a repository (or every one the person works on: their own | |
| 389 | * and their teams', as every widget's scope) did, from the same read `pulls { brief }` answers. | |
| 390 | */ | |
| 391 | const shipping: Widget = { | |
| 392 | name: "shipping", | |
| 393 | title: "Pulls merged per day", | |
| 394 | description: | |
| 395 | "Shipping throughput: pulls merged each day, for one repository or all you work on. For: what shipped, a graph of merges or landings.", | |
| 396 | renderer: "chart", | |
| 397 | args: { type: "object", additionalProperties: false, properties: SCOPE_ARGS }, | |
| 398 | read(app, user, args) { | |
| 399 | const scope = scopeOf(app, user, args); | |
| 400 | if (!scope.ok) return scope; | |
| 401 | const { days } = windowOf(args); | |
| 402 | const { merged } = mergedPerDay(app.db, scope.value.repos.map((r) => r.id), days.length); | |
| 403 | const all = merged.reduce((a, b) => a + b, 0); | |
| 404 | const best = merged.indexOf(Math.max(...merged)); | |
| 405 | return ok({ | |
| 406 | data: { kind: "bar", x: [...days], unit: "pulls", series: [{ name: "Merged", values: merged, tone: "good" }] }, | |
| 407 | says: | |
| 408 | all === 0 | |
| 409 | ? `No pulls merged in the last ${days.length} days on ${scope.value.where}.` | |
| 410 | : `${said(all)} pulls merged in the last ${days.length} days on ${scope.value.where}, ${said(all / days.length)} a day; the most on ${days[best]} (${said(merged[best]!)}).`, | |
| 411 | }); | |
| 412 | }, | |
| 413 | }; | |
| 414 | ||
| 324 | 415 | /** Every widget, by name. */ |
| 325 | export const WIDGETS: readonly Widget[] = [checks]; | |
| 416 | export const WIDGETS: readonly Widget[] = [checks, compute, shipping]; | |
| 326 | 417 | |
| 327 | 418 | export const widgetNamed = (name: string): Widget | undefined => |
| 328 | 419 | WIDGETS.find((w) => w.name === name); |
test/mcp-usage-forge.test.ts +10 −1
| @@ -146,8 +146,17 @@ test("a site admin sees every app's spend", () => { | ||
| 146 | 146 | expect(r.last24h.costUsd).toBe(60); |
| 147 | 147 | }); |
| 148 | 148 | |
| 149 | test("days without a repo is refused rather than ignored", () => { | |
| 149 | test("days without a repo is refused rather than ignored", async () => { | |
| 150 | 150 | expect(JSON.stringify(tool.run({ app } as never, alice, { days: 3 }))).toContain("invalid_days"); |
| 151 | // The refusal says what to call instead, so an agent that asked for the forge's week tries it. | |
| 152 | const res = await fetch(`${servers.url}/mcp`, { | |
| 153 | method: "POST", | |
| 154 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${createToken(app.db, alice.id, "t", "ro").token}` }, | |
| 155 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "usage", arguments: { days: 3 } } }), | |
| 156 | }); | |
| 157 | const said = JSON.stringify(await res.json()); | |
| 158 | expect(said).toContain("call usage with `repo` and `days`"); | |
| 159 | expect(said).toContain("widget `compute`"); | |
| 151 | 160 | }); |
| 152 | 161 | |
| 153 | 162 | test("GET /api/v1/usage answers the caller's apps and refuses a guest", async () => { |
test/widgets.test.ts +72 −2
| @@ -21,6 +21,8 @@ import { createUser, type User } from "../src/core/users.ts"; | ||
| 21 | 21 | import { mintViaToken } from "../src/core/via_token.ts"; |
| 22 | 22 | import { id } from "../src/kernel/id.ts"; |
| 23 | 23 | import { serve, type Servers } from "../src/http/server.ts"; |
| 24 | import { tool as showTool } from "../src/http/mcp/tools/show.ts"; | |
| 25 | import { VOICE } from "../src/crew/conversation_brief.ts"; | |
| 24 | 26 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 25 | 27 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 26 | 28 | import { settleApp } from "./helpers/tui.ts"; |
| @@ -68,6 +70,25 @@ beforeAll(async () => { | ||
| 68 | 70 | for (const s of ["ok", "failed"] as const) check(open, 8, s); |
| 69 | 71 | // The private repository's checks are counted for alice, never for bob. |
| 70 | 72 | for (const s of ["failed", "failed"] as const) check(closed, 1, s); |
| 73 | // The machine: two hours of 15-s samples, the node at 2 cores then 4, the forge at 1. | |
| 74 | const sample = app.db.query("INSERT INTO machine_sample (at, step, target, cpu_cores, memory_bytes, load) VALUES (?1, 15, ?2, ?3, ?4, ?5)"); | |
| 75 | const hour = 3_600_000; | |
| 76 | const top = Math.floor(Date.now() / hour) * hour; | |
| 77 | for (let i = 0; i < 8; i++) { | |
| 78 | const at = new Date(top - hour + i * 15 * 60_000 + 1_000).toISOString(); | |
| 79 | sample.run(at, "node", i < 4 ? 2 : 4, 8 * 2 ** 30, 1); | |
| 80 | sample.run(at, "forge", 1, 2 * 2 ** 30, 0.5); | |
| 81 | } | |
| 82 | // Merged pulls: two on open today, one on open three days ago, one on the private repository. | |
| 83 | const merged = async (repo: Repo, back: number, n: number) => { | |
| 84 | const issueId = id(); | |
| 85 | app.db.query("INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at) VALUES (?1, ?2, ?3, 'pull', 'p', '', ?4, 'closed', ?5)").run(issueId, repo.id, 900 + n, alice.id, ago(back)); | |
| 86 | app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, merged_at) VALUES (?1, 'main', ?2, '', '', ?3, ?4)").run(issueId, `m${n}`, repo.id, ago(back)); | |
| 87 | }; | |
| 88 | await merged(open, 0, 1); | |
| 89 | await merged(open, 0, 2); | |
| 90 | await merged(open, 3, 3); | |
| 91 | await merged(closed, 1, 4); | |
| 71 | 92 | }, 30_000); |
| 72 | 93 | afterAll(async () => { |
| 73 | 94 | servers.stop(); |
| @@ -90,7 +111,8 @@ function plans(work: () => void): string[] { | ||
| 90 | 111 | (db as unknown as { query: unknown }).query = original; |
| 91 | 112 | } |
| 92 | 113 | return sqls |
| 93 | .filter((s) => s.includes("INDEXED BY")) | |
| 114 | // A WITHOUT ROWID table (machine_sample) is its primary key: its plan is read the same way. | |
| 115 | .filter((s) => s.includes("INDEXED BY") || /FROM machine_sample\b/.test(s)) | |
| 94 | 116 | .flatMap((sql) => { |
| 95 | 117 | const n = (sql.match(/\?\d+/g) ?? []).reduce((m, p) => Math.max(m, Number(p.slice(1))), 0); |
| 96 | 118 | return [`-- ${sql.replace(/\s+/g, " ")}`, ...app.db.query<{ detail: string }, string[]>(`EXPLAIN QUERY PLAN ${sql}`).all(...Array.from({ length: n }, () => "x")).map((r) => r.detail)]; |
| @@ -137,6 +159,53 @@ describe("checks", () => { | ||
| 137 | 159 | |
| 138 | 160 | }); |
| 139 | 161 | |
| 162 | describe("compute", () => { | |
| 163 | test("the machine and the forge each hour, as levels: the legend and the terminal say now, never a sum", () => { | |
| 164 | const { data, says } = chart("compute", alice, { hours: 3 }); | |
| 165 | expect(data.kind).toBe("line"); | |
| 166 | expect(data.levels).toBe(true); | |
| 167 | expect(data.unit).toBe("cores"); | |
| 168 | expect(data.series.map((s) => s.name)).toEqual(["Machine", "Forge"]); | |
| 169 | expect(data.x.every((x) => /^\d{4}-\d{2}-\d{2}T\d{2}:00:00\.000Z$/.test(x))).toBe(true); | |
| 170 | expect(data.series[1]!.values.every((v) => v === 1)).toBe(true); | |
| 171 | expect(says).toMatch(/^CPU in use on the machine: [\d.]+ cores now, [\d.]+ cores? at the busiest hour of the last 3; the forge's own process 1 core now\.$/); | |
| 172 | expect(chart("compute", alice, { hours: 3, metric: "memory" }).data.unit).toBe("GiB"); | |
| 173 | const lines = widgetLines({ name: "compute", renderer: "chart", title: "Compute usage", data }); | |
| 174 | expect(lines[2]).toContain("1 core now"); | |
| 175 | }); | |
| 176 | ||
| 177 | test("only who may read the machine draws it: anyone else is not found", () => { | |
| 178 | expect(readWidget(app, bob, "compute", {})).toEqual({ ok: false, error: "not_found" }); | |
| 179 | expect(readWidget(app, undefined, "compute", {})).toEqual({ ok: false, error: "not_found" }); | |
| 180 | expect(readWidget(app, alice, "compute", { hours: 100 })).toEqual({ ok: false, error: "invalid" }); | |
| 181 | }); | |
| 182 | }); | |
| 183 | ||
| 184 | describe("shipping", () => { | |
| 185 | test("pulls merged each day, for one repository or every one the person works on", () => { | |
| 186 | const one = chart("shipping", alice, { repo: "alice/open", days: 7 }); | |
| 187 | expect(one.data.x).toEqual(dayLabels(7)); | |
| 188 | expect(one.data.series[0]!.values).toEqual([0, 0, 0, 1, 0, 0, 2]); | |
| 189 | expect(one.says).toBe(`3 pulls merged in the last 7 days on alice/open, 0.4 a day; the most on ${dayLabels(1)[0]} (2).`); | |
| 190 | // With no repository: every one alice works on, the private one included. | |
| 191 | expect(chart("shipping", alice, { days: 7 }).data.series[0]!.values.reduce((a, b) => a + b, 0)).toBe(4); | |
| 192 | expect(chart("shipping", bob, { days: 7 }).says).toBe("No pulls merged in the last 7 days on every repository you work on."); | |
| 193 | }); | |
| 194 | }); | |
| 195 | ||
| 196 | describe("the words that lead to a graph", () => { | |
| 197 | test("show and the widgets are found by what a person asks: graph, compute, usage, throughput, how is the server", () => { | |
| 198 | const described = showTool.description.toLowerCase(); | |
| 199 | for (const word of ["graph", "compute", "usage", "throughput"]) expect(described).toContain(word); | |
| 200 | expect(searchWidgets("compute usage").map((w) => w.name)).toEqual(["compute"]); | |
| 201 | expect(searchWidgets("how is the server").map((w) => w.name)).toEqual(["compute"]); | |
| 202 | expect(searchWidgets("shipping throughput").map((w) => w.name)).toEqual(["shipping"]); | |
| 203 | expect(searchWidgets("graph").map((w) => w.name).sort()).toEqual(["compute", "shipping"]); | |
| 204 | // The brief sends a request for a graph to show, never to prose. | |
| 205 | expect(VOICE.join(" ")).toContain("When the person asks for a graph or a chart, or how the server, compute, usage, shipping or throughput is doing, call `show`"); | |
| 206 | }); | |
| 207 | }); | |
| 208 | ||
| 140 | 209 | describe("show in Talk", () => { |
| 141 | 210 | test("keeps the widget under the next handle, says what it shows, and the page draws it", async () => { |
| 142 | 211 | const c = createConversation(app.db, alice.id); |
| @@ -270,7 +339,8 @@ describe("the registry", () => { | ||
| 270 | 339 | }); |
| 271 | 340 | |
| 272 | 341 | describe("each widget answers in its own shape, and only what the person may read", () => { |
| 273 | for (const name of files) { | |
| 342 | // The widgets that read repositories; `compute` reads the machine and has its own tests above. | |
| 343 | for (const name of WIDGETS.filter((w) => w.args.properties?.["repo"] !== undefined).map((w) => w.name)) { | |
| 274 | 344 | test(`${name}: its data fits its renderer's schema, for a repository and for every one the person works on`, () => { |
| 275 | 345 | for (const args of [{ repo: "alice/open", days: 7 }, { days: 30 }, {}]) { |
| 276 | 346 | const read = readWidget(app, alice, name, args); |
new above
offline