Public: anyone can read this; the crew can change it.
Talk's agent shows the forge's checks as a chart in a reply, drawn by the forge, on the page and in the terminal #16290
Check · Review · Land · Live done — Landed and live in production.
talk/08-widgets-chart → main 0 commits
20 files
changed +1392
−34
docs/design/areas/widgets.md added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | # Widgets | |
| 2 | ||
| 3 | What the forge's agent shows in a reply (#6009, `src/widgets/`), drawn by the forge's own renderers in `src/web/talk_parts.ts`: server-drawn markup, no script, the same in light and dark, at 360 px and in `dir="rtl"`. In Talk a widget sits on the card surface (`.talk-card`), under a one-line head (`.talk-widget`). | |
| 4 | ||
| 5 | - `.wchart` — a chart (`data-kind` line, bar or area). Each series' colour is one custom property, `--c`, that its class sets from the series tokens (success and danger for a series marked good or bad), and every mark of the series takes that class (`.s0`, `.s1`, `.s2`, `.s3`, `.s4`, `.s5`, `.s6`, `.s7`, `.tg`, `.tb`), so dark mode is the tokens' flip. the type floor (`--fs-min`, 12 px), tabular numbers; it is its own size container. | |
| 6 | - `.wchart-key` — the legend above the plot: an 8 px swatch, the series' name and its total. | |
| 7 | - `.wchart-plot` — the box the plot fills, 128 px high (112 px under 440 px of chart) before paint, days running left to right in any language. `.wchart-tick` is a quiet number of the scale at the start edge, the top and (`.is-zero`) the floor. | |
| 8 | - `.wchart-svg` — the stretched SVG: `.wchart-grid` its two lines, the top of the scale and the floor, at half the border's strength (the plot is not boxed in), `.wchart-line` a series' line (2 px, 1.5 px over an area), `.wchart-fill` an area's gradient (series colour, 0.8 at the top to 0.1 at the bottom), bars in the series colour, stacked with a hairline seam in the card's colour between segments (so a stack reads without colour), only the top of a stack rounded and only its top corners. | |
| 9 | - `.wchart-hit` — a day's full-height column: its `<title>` says that day's values on hover; it washes faintly under the pointer. | |
| 10 | - `.wchart-x` — at most five labels under the plot (the first, the middle and the last under 440 px); `.is-slots` puts a bar's label under its bar. | |
| 11 | - `.talk-widget` — a widget in a reply, bare under the same start-side hairline as a shown card (`.talk-card`), never a box: the forge's mark and the title, then `.talk-card-from`, where it came from with its window, time and named repository, small and muted, which is also the widget's accessible description. |
docs/features/talk-voice.md +31 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | topic: Tell the crew |
| 3 | row: Talk replies show the forge's own results as cards with buttons, and ask, plan and say what is known in three fixed shapes | |
| 3 | row: Talk replies show the forge's own results as cards with buttons and as charts, and ask, plan and say what is known in three fixed shapes | |
| 4 | 4 | --- |
| 5 | 5 | # Talk's voice: shown results and agent blocks |
| 6 | 6 | |
| @@ -44,6 +44,36 @@ The buttons drawn on Talk (`ACTS`, `src/actions/talk_act.ts`); none takes an arg | ||
| 44 | 44 | |
| 45 | 45 | Not drawn in this version: a button that sends typed words (`tell`), the asks card's per-row Ship, Decline and Decide (each only plans), its Undo, and the archive card's Undo. |
| 46 | 46 | |
| 47 | ## Widgets: the forge's data as a chart | |
| 48 | ||
| 49 | A widget (#6009) is something the forge's agent can show you in a Talk reply, drawn by the forge itself from the forge's own data: for now, a chart. The agent never writes the drawing; it asks the forge for a widget by name, the forge reads the data as you, and the reply places the result with a `::show c7` line, exactly as it places a card. | |
| 50 | ||
| 51 | ### The registry | |
| 52 | ||
| 53 | A widget is a name, a title, one line telling the agent what it shows, the renderer that draws it, a JSON schema of its arguments, and `read`, which returns the data through the same access checks every page uses. A repository you may not read is "not found", the same as one that does not exist. The data is held to its renderer's schema (`DATA_SCHEMA` in `src/widgets/registry.ts`), so every widget of one renderer has one shape. The widgets are `WIDGETS` in the same file; `show` with no widget lists them with what each takes, and /llms.txt names them, live, to a reader with an account. | |
| 54 | ||
| 55 | ### The forge's widgets | |
| 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. | |
| 58 | ||
| 59 | - `checks` (chart): checks that passed and failed each day. | |
| 60 | ||
| 61 | ### How it is drawn | |
| 62 | ||
| 63 | The renderer is server-drawn markup with no script, in `src/web/talk_parts.ts`, the same in light and dark, at phone width and right to left: | |
| 64 | ||
| 65 | - **chart**: line, bars or stacked areas. Days across; up to eight series, each in its series colour, or the success and danger colours for a series that is good or bad news; areas fill with a gradient from the series colour. Above the plot, a legend with each series' total; at its start edge, the top of the scale and zero; under it, up to five days at an even step. A day says its values when you point at it. Every number is also in a table a screen reader reads. | |
| 66 | ||
| 67 | In Talk a widget is drawn as a shown card is, bare under a hairline on its start side: the forge's mark and its title, then the line no reply's Markdown carries, where it came from with its window, time and repository ("From the forge: Checks per day · 7 days · as of 14:02 UTC · alice/shop"). A widget is a record of what the forge answered then; it is not read again. It has no buttons. | |
| 68 | ||
| 69 | ### In the terminal | |
| 70 | ||
| 71 | `forge talk` and the terminal's Talk screen print a placed widget from the same data, through the parser every door uses: a chart as one line of block characters a series (one scale for all, its total after it) over the days it spans. `GET /api/v1/conversation/turns` carries the printed reply as `plain` when it places a card or a widget. | |
| 72 | ||
| 73 | ### Limits | |
| 74 | ||
| 75 | A chart holds at most 120 points and 8 series, and a label 80 characters. A kept widget is held to the same 16,000 characters of JSON as a card, and to its renderer's schema when it is read back: one that does not fit draws "Result not found." | |
| 76 | ||
| 47 | 77 | ## Agent blocks |
| 48 | 78 | |
| 49 | 79 | A fenced code block whose info string is `forge` and whose first line names the kind, the rest of the block JSON in that kind's one shape with no other keys; or one whose info string names the kind itself (`forge plan`, or just `plan`), the whole block that JSON. The fence is read leniently and the body strictly: a block so labelled is drawn only when its body is exactly that shape, so an ordinary code block marked `plan` stays code. Strings are one line each, and every one is cleaned the way a confirm sentence cleans an argument (`unsaid`, `src/crew/conversation_ask.ts`): an invisible or direction-changing character (a zero-width space, a right-to-left override) becomes a space, so what is drawn is what is sent. A block that does not validate (bad JSON, a wrong count, a long string, an unknown kind or state) is drawn as the ordinary code block it is, never as an error. |
docs/features/talk.md +1 −1
| @@ -136,7 +136,7 @@ A reply is drawn by the README renderer and then, for Talk alone, by `linkTalk` | ||
| 136 | 136 | |
| 137 | 137 | An agent reply is Markdown, drawn on the server by the same renderer as a README: fenced code is highlighted, tables and links render, and everything else is escaped (a `<script>` in a reply shows as text). A table wider than the column scrolls inside it; the page does not. The reply sits in the column like a person's turn, with none of the README's padding or line measure. |
| 138 | 138 | |
| 139 | A reply grows in one live element while it is written (see "Live") and is then stored as one finished turn; the page only appends a turn whose id it has not drawn (a repeat is ignored). Turns already on the page are not touched, so nothing above a new reply moves, and the page follows the end only if you were already there (otherwise "Latest" appears). An unfinished fence in a stored reply is closed for drawing. The page's own bytes are held by a test (`test/talk-page.test.ts`): the stylesheet under 16,900 B, the script under 42,300 B, and a page with a code reply under 47,000 B (its own page: one question and a code reply). | |
| 139 | A reply grows in one live element while it is written (see "Live") and is then stored as one finished turn; the page only appends a turn whose id it has not drawn (a repeat is ignored). Turns already on the page are not touched, so nothing above a new reply moves, and the page follows the end only if you were already there (otherwise "Latest" appears). An unfinished fence in a stored reply is closed for drawing. The page's own bytes are held by a test (`test/talk-page.test.ts`): the stylesheet under 16,900 B, the script under 42,300 B, and a page with a code reply under 49,500 B (its own page: one question and a code reply; the widgets' rules ride every page, so a chart drawn in a live reply is styled at once). | |
| 140 | 140 | |
| 141 | 141 | ## Following |
| 142 | 142 |
src/actions/talk_act.ts +9 −7
| @@ -18,14 +18,14 @@ | ||
| 18 | 18 | */ |
| 19 | 19 | |
| 20 | 20 | import { appendTurn, getConversation } from "../core/conversations.ts"; |
| 21 | import { cardById, pressOnce, unpress, type ShownCard } from "../core/talk_voice.ts"; | |
| 21 | import { cardById, pressOnce, unpress } from "../core/talk_voice.ts"; | |
| 22 | 22 | import { hold } from "../core/fence.ts"; |
| 23 | 23 | import type { User } from "../core/users.ts"; |
| 24 | 24 | import { confirmSentence } from "../crew/conversation_ask.ts"; |
| 25 | 25 | import { tooBigToApprove } from "../crew/conversation_confirm.ts"; |
| 26 | 26 | import type { Ctx } from "../http/context.ts"; |
| 27 | 27 | import { loadMcp } from "../http/mcp/load.ts"; |
| 28 | import type { CardAction, CardKind } from "../web/studio/cards.ts"; | |
| 28 | import type { Card, CardAction, CardKind } from "../web/studio/cards.ts"; | |
| 29 | 29 | |
| 30 | 30 | /** A kept card acts for ten minutes, the same time a held write waits for its yes. */ |
| 31 | 31 | export const CARD_FRESH_MS = 600_000; |
| @@ -66,7 +66,7 @@ export const mayAct = (kind: CardKind, action: CardAction): boolean => { | ||
| 66 | 66 | export const ACTION_PATH = /^(?:a(\d{1,3})|r(\d{1,3})\.(\d{1,3}))$/; |
| 67 | 67 | |
| 68 | 68 | /** The button `path` names on a card, or undefined. */ |
| 69 | export function actionAt(card: ShownCard["card"], path: string): CardAction | undefined { | |
| 69 | export function actionAt(card: Card, path: string): CardAction | undefined { | |
| 70 | 70 | const m = ACTION_PATH.exec(path); |
| 71 | 71 | if (m === null) return undefined; |
| 72 | 72 | if (m[1] !== undefined) return card.actions[Number(m[1])]; |
| @@ -104,9 +104,11 @@ export async function pressCard(ctx: Ctx, user: User, cardId: string, path: stri | ||
| 104 | 104 | const conversation = shown === undefined ? undefined : getConversation(ctx.app.db, user.id, shown.via.slice("conversation:".length)); |
| 105 | 105 | if (shown === undefined || conversation === undefined) return { ok: false, error: "not_found" }; |
| 106 | 106 | const at = { conversationId: conversation.id }; |
| 107 | const action = actionAt(shown.card, path); | |
| 108 | if (action === undefined) return { ok: false, error: "not_found", ...at }; | |
| 109 | if (!mayAct(shown.card.kind, action)) return { ok: false, error: "not_allowed", ...at }; | |
| 107 | // A widget has no buttons: there is nothing on it to press. | |
| 108 | const card = shown.card; | |
| 109 | const action = card === undefined ? undefined : actionAt(card, path); | |
| 110 | if (card === undefined || action === undefined) return { ok: false, error: "not_found", ...at }; | |
| 111 | if (!mayAct(card.kind, action)) return { ok: false, error: "not_allowed", ...at }; | |
| 110 | 112 | if (tooBigToApprove(action.args)) return { ok: false, error: "too_big", ...at }; |
| 111 | 113 | // What the person may not do is never asked for in their name. |
| 112 | 114 | const { TOOLS } = await loadMcp(); |
| @@ -139,7 +141,7 @@ export async function pressCard(ctx: Ctx, user: User, cardId: string, path: stri | ||
| 139 | 141 | unpress(db, shown.id, path); |
| 140 | 142 | return "full"; |
| 141 | 143 | } |
| 142 | appendTurn(db, user.id, conversation.id, { role: "confirm", text: JSON.stringify({ confirm: held, tool: action.tool, does: `${confirmSentence(action.tool, args, tool.description)} From the result shown above: ${shown.card.title}.` }) }); | |
| 144 | appendTurn(db, user.id, conversation.id, { role: "confirm", text: JSON.stringify({ confirm: held, tool: action.tool, does: `${confirmSentence(action.tool, args, tool.description)} From the result shown above: ${shown.title}.` }) }); | |
| 143 | 145 | return held; |
| 144 | 146 | })(); |
| 145 | 147 | if (kept === "pressed" || kept === "full") return { ok: false, error: kept, ...at }; |
src/core/talk_voice.ts +108 −11
| @@ -2,11 +2,12 @@ | ||
| 2 | 2 | * Talk's voice (docs/features/talk-voice.md), one module for every door: the shown results |
| 3 | 3 | * the forge keeps for a conversation, and the fixed vocabulary an agent reply is parsed in. |
| 4 | 4 | * |
| 5 | * Shown results: the cards the forge's MCP drew for a conversation's own agent (a via token), | |
| 6 | * kept so the agent can place one in its reply with a `::show c<n>` line. The agent never reads | |
| 7 | * the card; it reads the tool's fenced text and, outside the fence, the handle. Bounded: the | |
| 8 | * newest `CARDS_KEPT` of a conversation are kept (older ones go on every insert), and a card whose | |
| 9 | * JSON is over `CARD_CHARS_MAX` is not kept at all. Every read checks `userId`. | |
| 5 | * Shown results: the cards the forge's MCP drew for a conversation's own agent (a via token), and | |
| 6 | * the widgets it showed (`widgets/registry.ts`), kept so the agent can place one in its reply with | |
| 7 | * a `::show c<n>` line. A kept item is a card or a widget: one store, one handle, one line. The | |
| 8 | * agent never reads the card; it reads the tool's fenced text and, outside the fence, the handle. | |
| 9 | * Bounded: the newest `CARDS_KEPT` of a conversation are kept (older ones go on every insert), and | |
| 10 | * a card whose JSON is over `CARD_CHARS_MAX` is not kept at all. Every read checks `userId`. | |
| 10 | 11 | * |
| 11 | 12 | * The vocabulary: a reply is ordinary Markdown with two additions. |
| 12 | 13 | * |
| @@ -23,7 +24,9 @@ | ||
| 23 | 24 | import type { Database } from "bun:sqlite"; |
| 24 | 25 | import type { Card, CardAction, CardRow } from "../web/studio/cards.ts"; |
| 25 | 26 | import { id } from "../kernel/id.ts"; |
| 27 | import { formatValue } from "../boards/chart.ts"; | |
| 26 | 28 | import { unsaid } from "../crew/conversation_ask.ts"; |
| 29 | import { DATA_SCHEMA, RENDERERS, validate, type Renderer, type WidgetData } from "../widgets/registry.ts"; | |
| 27 | 30 | |
| 28 | 31 | /** The newest cards a conversation keeps. */ |
| 29 | 32 | export const CARDS_KEPT = 200; |
| @@ -38,12 +41,56 @@ export interface ShownCard { | ||
| 38 | 41 | readonly tool: string; |
| 39 | 42 | /** The call in plain words (`core/talk_steps.ts`), for the line under the card. */ |
| 40 | 43 | readonly said: string; |
| 41 | readonly card: Card; | |
| 44 | /** What the person reads at its top: the card's title, or the widget's. */ | |
| 45 | readonly title: string; | |
| 46 | /** A card the tool's answer drew, or a widget the agent showed: exactly one of the two. */ | |
| 47 | readonly card?: Card; | |
| 48 | readonly widget?: KeptWidget; | |
| 42 | 49 | readonly createdAt: string; |
| 43 | 50 | /** Its buttons already pressed (`a0`, `r3.0`): each asked once, read with the card. */ |
| 44 | 51 | readonly pressed: readonly string[]; |
| 45 | 52 | } |
| 46 | 53 | |
| 54 | /** A kept item that is a card: only a card has buttons. */ | |
| 55 | export const holdsCard = (shown: ShownCard): shown is ShownCard & { readonly card: Card } => shown.card !== undefined; | |
| 56 | ||
| 57 | /** A widget as kept: its name, its renderer, the title it was shown under and the data it drew. */ | |
| 58 | export interface KeptWidget { | |
| 59 | readonly name: string; | |
| 60 | readonly renderer: Renderer; | |
| 61 | readonly title: string; | |
| 62 | readonly data: WidgetData; | |
| 63 | /** What it was read over: how many days, and the one repository named (none: every one). */ | |
| 64 | readonly days?: number; | |
| 65 | readonly repo?: string; | |
| 66 | } | |
| 67 | ||
| 68 | /** | |
| 69 | * A kept widget read back from its JSON, its data held to its renderer's schema; undefined when the | |
| 70 | * text is not one. | |
| 71 | */ | |
| 72 | export function readWidget(text: string): KeptWidget | undefined { | |
| 73 | let v: unknown; | |
| 74 | try { | |
| 75 | v = JSON.parse(text); | |
| 76 | } catch { | |
| 77 | return undefined; | |
| 78 | } | |
| 79 | const w = typeof v === "object" && v !== null ? (v as Record<string, unknown>)["widget"] : undefined; | |
| 80 | if (typeof w !== "object" || w === null) return undefined; | |
| 81 | const { name, renderer, title, data, days, repo } = w as Record<string, unknown>; | |
| 82 | if (typeof name !== "string" || typeof title !== "string" || !RENDERERS.includes(renderer as Renderer)) return undefined; | |
| 83 | if (validate(DATA_SCHEMA[renderer as Renderer], data) !== undefined) return undefined; | |
| 84 | return { | |
| 85 | name, | |
| 86 | renderer: renderer as Renderer, | |
| 87 | title, | |
| 88 | data: data as WidgetData, | |
| 89 | ...(Number.isInteger(days) && (days as number) > 0 && (days as number) <= 365 ? { days: days as number } : {}), | |
| 90 | ...(typeof repo === "string" && repo.length <= 200 ? { repo } : {}), | |
| 91 | }; | |
| 92 | } | |
| 93 | ||
| 47 | 94 | interface Row { |
| 48 | 95 | id: string; |
| 49 | 96 | via: string; |
| @@ -119,7 +166,8 @@ export function readCard(text: string): Card | undefined { | ||
| 119 | 166 | |
| 120 | 167 | const shownOf = (r: Row): ShownCard | undefined => { |
| 121 | 168 | const card = readCard(r.card); |
| 122 | return card === undefined | |
| 169 | const widget = card === undefined ? readWidget(r.card) : undefined; | |
| 170 | return card === undefined && widget === undefined | |
| 123 | 171 | ? undefined |
| 124 | 172 | : { |
| 125 | 173 | id: r.id, |
| @@ -128,7 +176,9 @@ const shownOf = (r: Row): ShownCard | undefined => { | ||
| 128 | 176 | n: r.n, |
| 129 | 177 | tool: r.tool, |
| 130 | 178 | said: r.said, |
| 131 | card, | |
| 179 | title: card?.title ?? widget?.title ?? "", | |
| 180 | ...(card === undefined ? {} : { card }), | |
| 181 | ...(widget === undefined ? {} : { widget }), | |
| 132 | 182 | createdAt: r.created_at, |
| 133 | 183 | pressed: (JSON.parse(r.pressed ?? "[]") as unknown[]).filter((x): x is string => typeof x === "string"), |
| 134 | 184 | }; |
| @@ -164,7 +214,22 @@ export function recordCard( | ||
| 164 | 214 | r.link === undefined ? r : { ...r, link: rooted(r.link, origin) }, |
| 165 | 215 | ), |
| 166 | 216 | }; |
| 167 | const text = JSON.stringify(kept); | |
| 217 | return keep(db, via, userId, tool, said, JSON.stringify(kept), now); | |
| 218 | } | |
| 219 | ||
| 220 | /** | |
| 221 | * Keep a widget the agent showed in the conversation `via` names: its number, or undefined when its | |
| 222 | * JSON is over `CARD_CHARS_MAX`. Kept, numbered and pruned exactly as a card is. | |
| 223 | */ | |
| 224 | export function recordWidget(db: Database, via: string, userId: string, said: string, widget: KeptWidget, now: number = Date.now()): number | undefined { | |
| 225 | return keep(db, via, userId, "show", said, JSON.stringify({ widget }), now); | |
| 226 | } | |
| 227 | ||
| 228 | /** | |
| 229 | * One kept item's row: numbered next in its conversation, the oldest past `CARDS_KEPT` going with | |
| 230 | * their presses. | |
| 231 | */ | |
| 232 | function keep(db: Database, via: string, userId: string, tool: string, said: string, text: string, now: number): number | undefined { | |
| 168 | 233 | if (text.length > CARD_CHARS_MAX) return undefined; |
| 169 | 234 | return db.transaction(() => { |
| 170 | 235 | const n = |
| @@ -552,6 +617,37 @@ export function cardLines(card: Card): string[] { | ||
| 552 | 617 | ]; |
| 553 | 618 | } |
| 554 | 619 | |
| 620 | /** | |
| 621 | * A counted word said of one: "checks" is "check", "hours" is "hour"; a unit not ending in s stays. | |
| 622 | */ | |
| 623 | const one = (unit: string): string => (/[^s]s$/.test(unit) ? unit.slice(0, -1) : unit); | |
| 624 | ||
| 625 | /** | |
| 626 | * A value with its unit, the one way the page and the terminal say a widget's number (`formatValue`, | |
| 627 | * as the boards say theirs): "$" before it, any other unit after. $3.25, 92%, 12.5k checks, 1 check. | |
| 628 | */ | |
| 629 | export const withUnit = (v: number, unit?: string): string => | |
| 630 | unit === "$" ? `$${formatValue(v)}` : unit === "%" ? `${formatValue(v)}%` : unit === undefined || unit === "" ? formatValue(v) : `${formatValue(v)} ${v === 1 ? one(unit) : unit}`; | |
| 631 | const BLOCKS = "▁▂▃▄▅▆▇█"; | |
| 632 | /** | |
| 633 | * Values as block characters, scaled to `top`: a zero is the lowest block, so every day has a mark. | |
| 634 | */ | |
| 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); | |
| 638 | ||
| 639 | /** | |
| 640 | * A kept widget as the terminal prints it, in the same data the page draws: a chart as one line of | |
| 641 | * block characters a series (one scale for all, its total after it) over the days it spans. | |
| 642 | */ | |
| 643 | export function widgetLines(w: KeptWidget): string[] { | |
| 644 | const d = w.data; | |
| 645 | const width = Math.max(...d.series.map((s) => s.name.length)); | |
| 646 | const top = Math.max(0, ...d.series.flatMap((s) => s.values)); | |
| 647 | 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}`]; | |
| 649 | } | |
| 650 | ||
| 555 | 651 | /** |
| 556 | 652 | * A reply as the terminal prints it: a placed result as where it came from and its card's lines |
| 557 | 653 | * (or the not-found words), each block as a plain list. `cards` are this conversation's kept cards |
| @@ -569,8 +665,9 @@ export function plainVoice(text: string, cards: ReadonlyMap<number, ShownCard>): | ||
| 569 | 665 | const shown = cards.get(p.n); |
| 570 | 666 | if (shown === undefined) return [NOT_FOUND_WORDS]; |
| 571 | 667 | // Drawn once a reply, as on the page; where it came from comes first. |
| 572 | if (p.again === true) return [`(shown above: ${shown.card.title})`]; | |
| 573 | return [`From the forge: ${shown.said}, as of ${shown.createdAt.slice(0, 16).replace("T", " ")} UTC`, ...cardLines(shown.card)]; | |
| 668 | if (p.again === true) return [`(shown above: ${shown.title})`]; | |
| 669 | const from = `From the forge: ${shown.said}, as of ${shown.createdAt.slice(0, 16).replace("T", " ")} UTC`; | |
| 670 | return shown.card !== undefined ? [from, ...cardLines(shown.card)] : shown.widget !== undefined ? [from, ...widgetLines(shown.widget)] : [from]; | |
| 574 | 671 | } |
| 575 | 672 | case "over": |
| 576 | 673 | return [overWords(p.cards, p.blocks)]; |
src/http/mcp.ts +12 −1
| @@ -49,7 +49,7 @@ import { adminRefusal, everydayOf } from "../core/everyday.ts"; | ||
| 49 | 49 | import { claimDone, completeWrite, dropWrite, recordWrite } from "../core/conversation_writes.ts"; |
| 50 | 50 | import { type Args, alreadyDone, notAdminTool, listable, visible, plansOnly, str, REPO_ARG, lean, fenceAnswer, heldWrite, askedFirst, destroysTo, readThrough, type ToolShape } from "./mcp/shared.ts"; |
| 51 | 51 | import { CONVERSATION_BRIEF } from "../crew/conversation_brief.ts"; |
| 52 | import { recordCard, shownLine } from "../core/talk_voice.ts"; | |
| 52 | import { readWidget as readKept, recordCard, recordWidget, shownLine } from "../core/talk_voice.ts"; | |
| 53 | 53 | import { stepOf } from "../core/talk_steps.ts"; |
| 54 | 54 | import { TOOLS } from "./mcp/tools.ts"; |
| 55 | 55 | import { runMcpRefusal } from "./run_gate.ts"; |
| @@ -149,6 +149,17 @@ function cardResult( | ||
| 149 | 149 | * agent. |
| 150 | 150 | */ |
| 151 | 151 | function keepShown(ctx: Ctx, user: User, via: string, tool: string, args: Args, value: unknown, extra: Record<string, unknown> | undefined): { type: "text"; text: string }[] { |
| 152 | // A widget `show` drew is kept the same way, in the same store, under the same kind of handle. | |
| 153 | const widget = tool === "show" ? readKept(JSON.stringify({ widget: extra?.["widget"] })) : undefined; | |
| 154 | if (widget !== undefined) { | |
| 155 | // What it was read over, kept with it for the head: "the last 7 days on alice/shop". | |
| 156 | const given = typeof args["args"] === "object" && args["args"] !== null ? (args["args"] as Args) : {}; | |
| 157 | const days = typeof given["days"] === "number" ? given["days"] : 14; | |
| 158 | const repo = typeof given["repo"] === "string" ? given["repo"] : undefined; | |
| 159 | const over = `the last ${days} days on ${repo ?? "every repository you work on"}`; | |
| 160 | const n = recordWidget(ctx.app.db, via, user.id, over, { ...widget, days, ...(repo === undefined ? {} : { repo }) }); | |
| 161 | return n === undefined ? [] : [{ type: "text", text: shownLine(n) }]; | |
| 162 | } | |
| 152 | 163 | const card = cardFor(tool, value, ctx.url.origin, extra); |
| 153 | 164 | // A card of nothing (no rows, no buttons) is not handed out: there is nothing to place. |
| 154 | 165 | if (card === undefined || (card.rows.length === 0 && card.actions.length === 0)) return []; |
src/http/mcp/catalog.ts +3 −2
| @@ -23,7 +23,8 @@ export const DEFAULT_TOOLS: readonly string[] = [ | ||
| 23 | 23 | * `tools/list` named, so a tool left out here is one Talk cannot use at all. The rule: the reads a |
| 24 | 24 | * question about the work needs (issues, pulls and their commits, threads and checks, search, |
| 25 | 25 | * files, runs and logs, health, releases, people, and who the person is and what they may |
| 26 | * do, `whoami_can`), and the everyday writes on that work (comment, close or reopen, assign, | |
| 26 | * do, `whoami_can`, and `show`, which draws the forge's own data in a reply as a chart), and the | |
| 27 | * everyday writes on that work (comment, close or reopen, assign, | |
| 27 | 28 | * labels, edit, review, merge, the plan on an issue, a word to or a stop of a crew run, a |
| 28 | 29 | * branch, a file and a pull for an app built in Talk, a new app). Each write is held as any write |
| 29 | 30 | * of this token is: after the agent has read text someone else wrote, a write the person's own |
| @@ -44,7 +45,7 @@ export const DEFAULT_TOOLS: readonly string[] = [ | ||
| 44 | 45 | export const TALK_TOOLS: readonly string[] = [ |
| 45 | 46 | ...DEFAULT_TOOLS, |
| 46 | 47 | "issue", "issues", "pull", "pulls", "commits", "threads", "search", "read_file", "repo", "run_log", |
| 47 | "preview", "assigned", "health", "releases", "person", "whoami_can", | |
| 48 | "preview", "assigned", "health", "releases", "person", "whoami_can", "show", | |
| 48 | 49 | "close", "assign", "labels", "edit", "review", "merge", "keep_plan", "steer", "stop", |
| 49 | 50 | "write_file", "branches", "open_pull", "new_app", |
| 50 | 51 | ]; |
src/http/mcp/tools/index.ts +1
| @@ -162,6 +162,7 @@ export { tool as secrets } from "./secrets.ts"; | ||
| 162 | 162 | export { tool as sessions } from "./sessions.ts"; |
| 163 | 163 | export { tool as sever } from "./sever.ts"; |
| 164 | 164 | export { tool as share } from "./share.ts"; |
| 165 | export { tool as show } from "./show.ts"; | |
| 165 | 166 | export { tool as signup } from "./signup.ts"; |
| 166 | 167 | export { tool as sizes } from "./sizes.ts"; |
| 167 | 168 | export { tool as snapshot_now } from "./snapshot_now.ts"; |
src/http/mcp/tools/show.ts added +28
| @@ -0,0 +1,28 @@ | ||
| 1 | import { bad, good, str, type Tool } from "../shared.ts"; | |
| 2 | import { readWidget, searchWidgets } from "../../../widgets/registry.ts"; | |
| 3 | ||
| 4 | export const tool: Tool = { | |
| 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.", | |
| 8 | inputSchema: { | |
| 9 | type: "object", | |
| 10 | properties: { widget: { type: "string" }, args: { type: "object" }, query: { type: "string" } }, | |
| 11 | }, | |
| 12 | writes: false, | |
| 13 | run(ctx, user, args) { | |
| 14 | const name = str(args["widget"]); | |
| 15 | // No widget named: which there are, and what each takes, so the next call can draw one. | |
| 16 | if (name === "") | |
| 17 | return good({ widgets: searchWidgets(str(args["query"])).map((w) => ({ name: w.name, title: w.title, description: w.description, renderer: w.renderer, args: w.args })) }); | |
| 18 | const given = typeof args["args"] === "object" && args["args"] !== null && !Array.isArray(args["args"]) ? (args["args"] as Record<string, unknown>) : {}; | |
| 19 | const read = readWidget(ctx.app, user, name, given); | |
| 20 | if (!read.ok) | |
| 21 | return read.error === "not_found" | |
| 22 | ? bad("not_found", "no such widget, or no such repository you may read: call show with no widget to list them") | |
| 23 | : bad("invalid", "the arguments are outside the widget's schema: call show with no widget to read them"); | |
| 24 | const { widget, data, says } = read.value; | |
| 25 | // The kept item (http/mcp.ts keeps it for a conversation and hands the agent its handle). | |
| 26 | return { ok: true, value: { widget: widget.name, title: widget.title, says }, card: { widget: { name: widget.name, renderer: widget.renderer, title: widget.title, data } } }; | |
| 27 | }, | |
| 28 | }; |
src/tui/screens/talk_chats.ts +2 −2
| @@ -29,7 +29,7 @@ import { | ||
| 29 | 29 | import { conversationMarkdown } from "../../core/conversation_markdown.ts"; |
| 30 | 30 | import { publicOrigin } from "../../core/public_origin.ts"; |
| 31 | 31 | import { filesOf, repoOf, stepOf } from "../../core/talk_steps.ts"; |
| 32 | import { cardsPlaced, plainVoice } from "../../core/talk_voice.ts"; | |
| 32 | import { cardsPlaced, holdsCard, plainVoice } from "../../core/talk_voice.ts"; | |
| 33 | 33 | import { setTalkDisplay, talkDisplay } from "../../core/settings.ts"; |
| 34 | 34 | import { talkDisplayScreen } from "./talk_display.ts"; |
| 35 | 35 | import { liveReceipts, type LiveReceipt } from "../../core/talk_work.ts"; |
| @@ -316,7 +316,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 316 | 316 | if (e.key === "b") { |
| 317 | 317 | // The buttons of the shown results, as the page draws them: fresh, allowed, not pressed. |
| 318 | 318 | const now = Date.now(); |
| 319 | const items: PickItem[] = [...cards.values()].filter((c) => fresh(c.createdAt, now)).flatMap((c) => [ | |
| 319 | const items: PickItem[] = [...cards.values()].filter(holdsCard).filter((c) => fresh(c.createdAt, now)).flatMap((c) => [ | |
| 320 | 320 | ...c.card.actions.flatMap((a, i) => (mayAct(c.card.kind, a) && !c.pressed.includes(`a${i}`) ? [{ id: `${c.id} a${i}`, label: `${a.label}: ${c.card.title}` }] : [])), |
| 321 | 321 | ...c.card.rows.flatMap((r, i) => (r.actions ?? []).flatMap((a, j) => (mayAct(c.card.kind, a) && !c.pressed.includes(`r${i}.${j}`) ? [{ id: `${c.id} r${i}.${j}`, label: `${a.label}: ${r.label}` }] : []))), |
| 322 | 322 | ]); |
src/web/standards.ts +2
| @@ -59,6 +59,7 @@ import { SELF_HOST_NEEDS } from "../core/self_host.ts"; | ||
| 59 | 59 | import { SITE_PATH, SITE_LINE } from "./site_line.ts"; |
| 60 | 60 | import { holds } from "./feeds.ts"; |
| 61 | 61 | import { mcpToolsSection, mcpToolsVersion, readerKey, type Reader } from "./llms_tools.ts"; |
| 62 | import { widgetsSection } from "../widgets/registry.ts"; | |
| 62 | 63 | import { threeDoors } from "./doors_words.ts"; |
| 63 | 64 | import { OAUTH_SCOPES } from "../core/oauth.ts"; |
| 64 | 65 | import { SERVER_CARD_PATH, wellKnownServerCard, agentCard, serverCard, toolsKey, apiCatalog, cardsLine, DISCOVERY, mcpCard, mcpDoor, offeredPlugins, mcpPointers, toolCount, offeredPluginRepo, pluginSource } from "../core/mcp_card.ts"; |
| @@ -675,6 +676,7 @@ function renderLlmsTxt(ctx: Ctx, o: string, tell: string | undefined, running: s | ||
| 675 | 676 | "", |
| 676 | 677 | ...mcpToolsSection(o, reader, sshOn(ctx.app.db)), |
| 677 | 678 | cardsLine(), |
| 679 | ...(reader === undefined ? [] : widgetsSection()), | |
| 678 | 680 | "", |
| 679 | 681 | "## Public repositories", |
| 680 | 682 | "", |
src/web/talk_parts.ts +225 −5
| @@ -16,9 +16,11 @@ | ||
| 16 | 16 | import type { Database } from "bun:sqlite"; |
| 17 | 17 | import type { ShownCard } from "../core/talk_voice.ts"; |
| 18 | 18 | import type { Turn } from "../core/conversations.ts"; |
| 19 | import { cardsPlaced, NOT_FOUND_WORDS, overWords, planWord, voiceParts, wholeSoFar, type Part, type PlanState } from "../core/talk_voice.ts"; | |
| 19 | import { cardsPlaced, NOT_FOUND_WORDS, overWords, planWord, voiceParts, wholeSoFar, withUnit, type Part, type PlanState } from "../core/talk_voice.ts"; | |
| 20 | 20 | import { fresh, mayAct } from "../actions/talk_act.ts"; |
| 21 | 21 | import { escapeHtml, html, raw, type Html } from "./html.ts"; |
| 22 | import { formatValue, sayLabels } from "../boards/chart.ts"; | |
| 23 | import type { ChartData, Renderer, WidgetData } from "../widgets/registry.ts"; | |
| 22 | 24 | import type { IconName } from "./icons.ts"; |
| 23 | 25 | import { renderInline, renderMarkdown } from "./markdown.ts"; |
| 24 | 26 | import type { CardAction } from "./studio/cards.ts"; |
| @@ -92,7 +94,23 @@ const hhmm = (iso: string): string => `${iso.slice(11, 16)} UTC`; | ||
| 92 | 94 | const actForm = (shown: ShownCard, path: string, a: CardAction): Html => |
| 93 | 95 | shown.pressed.includes(path) |
| 94 | 96 | ? btn("Asked", { disabled: true, label: `${a.label}: asked`, extra: "talk-card-asked" }) |
| 95 | : html`<form method="post" action="/talk/act" class="talk-card-act"><input type="hidden" name="card" value="${shown.id}" /><input type="hidden" name="action" value="${path}" />${btn(a.label, { label: `${a.label}: ${shown.card.title}` })}</form>`; | |
| 97 | : html`<form method="post" action="/talk/act" class="talk-card-act"><input type="hidden" name="card" value="${shown.id}" /><input type="hidden" name="action" value="${path}" />${btn(a.label, { label: `${a.label}: ${shown.title}` })}</form>`; | |
| 98 | ||
| 99 | /** | |
| 100 | * A kept widget as the page draws it: bare under the same hairline as a card, under the same head | |
| 101 | * (the forge's mark and its title, then where it came from with its window and `time`, and the | |
| 102 | * repository it reads when it names one), its renderer's drawing below. A widget has no buttons. | |
| 103 | */ | |
| 104 | function widgetCard(shown: ShownCard, anchor?: string): Html { | |
| 105 | const w = shown.widget!; | |
| 106 | const from = `wf-${shown.id}`; | |
| 107 | return surface(widgetHtml(w.renderer, w.data, w.title, `${shown.id}`), { | |
| 108 | extra: "bare talk-card talk-widget", | |
| 109 | head: html`<p class="talk-card-title">${icon("anvil")}<span><strong>${w.title}</strong></span></p><p class="talk-card-from small muted" id="${from}">From the forge: ${shown.said} · ${w.days === undefined ? null : html`${w.days} days · `}as of ${time(shown.createdAt, { text: hhmm(shown.createdAt) })}${w.repo === undefined ? null : html` · ${w.repo}`}</p>`, | |
| 110 | attrs: html`data-card="${shown.id}" data-widget="${w.name}" role="group" aria-label="${w.title}" aria-describedby="${from}"`, | |
| 111 | ...(anchor === undefined ? {} : { id: anchor }), | |
| 112 | }); | |
| 113 | } | |
| 96 | 114 | |
| 97 | 115 | /** |
| 98 | 116 | * A kept card as the page draws it: bare, set apart from the agent's words by a hairline on its |
| @@ -105,6 +123,7 @@ const actForm = (shown: ShownCard, path: string, a: CardAction): Html => | ||
| 105 | 123 | */ |
| 106 | 124 | export function cardHtml(shown: ShownCard, voice: Pick<Voice, "origin" | "conversationId" | "now">, anchor?: string): Html { |
| 107 | 125 | const c = shown.card; |
| 126 | if (c === undefined) return widgetCard(shown, anchor); | |
| 108 | 127 | const live = fresh(shown.createdAt, voice.now); |
| 109 | 128 | const acts = c.actions.map((a, i) => [a, `a${i}`] as const).filter(([a]) => mayAct(c.kind, a)); |
| 110 | 129 | const actable = acts.length > 0 || c.rows.some((r) => (r.actions ?? []).some((a) => mayAct(c.kind, a))); |
| @@ -157,7 +176,7 @@ function itemHtml(item: string, placed: Placed, cards: ReadonlyMap<number, Shown | ||
| 157 | 176 | const at = placed.get(Number(bit)); |
| 158 | 177 | if (at !== undefined) return html` <a class="talk-known-src" href="#${at.anchor}">${at.title.slice(0, 60)}</a>`; |
| 159 | 178 | const kept = cards.get(Number(bit)); |
| 160 | return kept === undefined ? null : html` <span class="talk-known-src small muted">${kept.card.title.slice(0, 60)}</span>`; | |
| 179 | return kept === undefined ? null : html` <span class="talk-known-src small muted">${kept.title.slice(0, 60)}</span>`; | |
| 161 | 180 | }); |
| 162 | 181 | return html`${out}`; |
| 163 | 182 | } |
| @@ -229,7 +248,7 @@ export function agentHtml(turn: Turn, voice: Voice | undefined, linked: (md: Htm | ||
| 229 | 248 | const shown = p.kind === "show" && !anchors.has(p.n) ? voice?.cards.get(p.n) : undefined; |
| 230 | 249 | if (shown === undefined) continue; |
| 231 | 250 | anchors.set(shown.n, `t-${turn.id}-c${shown.n}`); |
| 232 | placed.set(shown.n, { anchor: `t-${turn.id}-c${shown.n}`, title: shown.card.title }); | |
| 251 | placed.set(shown.n, { anchor: `t-${turn.id}-c${shown.n}`, title: shown.title }); | |
| 233 | 252 | } |
| 234 | 253 | return html`${parts.map((p) => (p.kind === "text" ? linked(renderMarkdown(p.text)) : partHtml(p, live, voice, placed, anchors, turn.id)))}`; |
| 235 | 254 | } |
| @@ -245,6 +264,207 @@ export function liveHtml(db: Database, userId: string, conversationId: string, t | ||
| 245 | 264 | return agentHtml(turn, voiceOf(db, userId, conversationId, [turn], origin), linked); |
| 246 | 265 | } |
| 247 | 266 | |
| 267 | /** | |
| 268 | * Widgets (#6009), the forge's renderers: a widget's data (`widgets/registry.ts`) drawn on the | |
| 269 | * server as markup, no script and no dependency, the same in a Talk reply, on the card surface and | |
| 270 | * in every theme. One renderer for now: | |
| 271 | * | |
| 272 | * - `chart` (line, bar, area): the plot is an SVG that stretches to its box with strokes that do | |
| 273 | * not scale; each series' colour is one custom property (`--c`) its class sets from the series | |
| 274 | * tokens, a series marked good or bad takes the success or danger token, and dark mode is the | |
| 275 | * tokens' flip. Areas fill with a gradient from the series colour; the grid is two quiet lines | |
| 276 | * (the scale's top and its floor) at half the border's strength; every word (the days under the plot, the legend with each | |
| 277 | * series' total, the top of the scale) is page text at 12 px. Each day's slot says its values on | |
| 278 | * hover (its `<title>`), and a visually hidden table holds every number for a screen reader. | |
| 279 | * | |
| 280 | * Every string is escaped by the `html` tag or `escapeHtml`; the SVG carries numbers only. | |
| 281 | */ | |
| 282 | const num = (n: number): string => String(Math.round(n * 100) / 100); | |
| 283 | /** A scale's label at the start edge: the number, with only a short unit ($, %). */ | |
| 284 | const tick = (v: number, unit?: string): string => (unit === "$" || unit === "%" ? withUnit(v, unit) : formatValue(v)); | |
| 285 | ||
| 286 | /** The top of the scale: the first of these steps, times a power of ten, at or above `v`. */ | |
| 287 | function niceTop(v: number): number { | |
| 288 | if (!(v > 0)) return 1; | |
| 289 | const pow = 10 ** Math.floor(Math.log10(v)); | |
| 290 | return ([1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10].find((s) => s * pow >= v * 0.999999) ?? 10) * pow; | |
| 291 | } | |
| 292 | ||
| 293 | /** | |
| 294 | * A smooth path through the points that never overshoots between them (monotone cubic, | |
| 295 | * Fritsch-Carlson), so a count never seems to dip below zero or above its peak. | |
| 296 | */ | |
| 297 | export function monotone(xs: readonly number[], ys: readonly number[]): string { | |
| 298 | const n = xs.length; | |
| 299 | if (n === 0) return ""; | |
| 300 | if (n === 1) return `M0 ${num(ys[0]!)} L100 ${num(ys[0]!)}`; | |
| 301 | const d = xs.slice(1).map((x, i) => (ys[i + 1]! - ys[i]!) / (x - xs[i]! || 1)); | |
| 302 | const m = xs.map((_, i) => (i === 0 ? d[0]! : i === n - 1 ? d[n - 2]! : d[i - 1]! * d[i]! <= 0 ? 0 : (d[i - 1]! + d[i]!) / 2)); | |
| 303 | for (let i = 0; i < n - 1; i++) { | |
| 304 | if (d[i] === 0) { | |
| 305 | m[i] = 0; | |
| 306 | m[i + 1] = 0; | |
| 307 | continue; | |
| 308 | } | |
| 309 | const a = m[i]! / d[i]!; | |
| 310 | const b = m[i + 1]! / d[i]!; | |
| 311 | const s = a * a + b * b; | |
| 312 | if (s > 9) { | |
| 313 | const t = 3 / Math.sqrt(s); | |
| 314 | m[i] = t * a * d[i]!; | |
| 315 | m[i + 1] = t * b * d[i]!; | |
| 316 | } | |
| 317 | } | |
| 318 | let out = `M${num(xs[0]!)} ${num(ys[0]!)}`; | |
| 319 | for (let i = 0; i < n - 1; i++) { | |
| 320 | const h = (xs[i + 1]! - xs[i]!) / 3; | |
| 321 | out += ` C${num(xs[i]! + h)} ${num(ys[i]! + m[i]! * h)} ${num(xs[i + 1]! - h)} ${num(ys[i + 1]! - m[i + 1]! * h)} ${num(xs[i + 1]!)} ${num(ys[i + 1]!)}`; | |
| 322 | } | |
| 323 | return out; | |
| 324 | } | |
| 325 | ||
| 326 | /** | |
| 327 | * The series' colour classes: good and bad take the success and danger tokens, the rest the series | |
| 328 | * tokens. | |
| 329 | */ | |
| 330 | const swatch = (tone: string | undefined, k: number): string => (tone === "good" ? "tg" : tone === "bad" ? "tb" : `s${k % 8}`); | |
| 331 | ||
| 332 | /** | |
| 333 | * Up to five labels under the plot, from the first point to the last at an even step: the most | |
| 334 | * labels that divide the days exactly (a week is four, every other day), else five rounded, so no | |
| 335 | * two labels ever sit side by side. | |
| 336 | */ | |
| 337 | function ticks(n: number): number[] { | |
| 338 | if (n < 2) return [0]; | |
| 339 | const count = [5, 4, 3].find((c) => c <= n && (n - 1) % (c - 1) === 0) ?? Math.min(5, n); | |
| 340 | return [...new Set(Array.from({ length: count }, (_, k) => Math.round((k * (n - 1)) / (count - 1))))]; | |
| 341 | } | |
| 342 | ||
| 343 | /** | |
| 344 | * A chart: line, bars or stacked areas, with its legend, its scale's top and a table for a screen | |
| 345 | * reader. | |
| 346 | */ | |
| 347 | export function chartHtml(data: ChartData, title: string, uid: string): Html { | |
| 348 | const n = data.x.length; | |
| 349 | const say = sayLabels(data.x.map((l) => (/^\d{4}-\d{2}-\d{2}$/.test(l) ? `${l}T00:00:00.000Z` : l))); | |
| 350 | const day = (i: number): string => say(/^\d{4}-\d{2}-\d{2}$/.test(data.x[i] ?? "") ? `${data.x[i]}T00:00:00.000Z` : (data.x[i] ?? "")); | |
| 351 | const series = data.series.map((s, k) => ({ ...s, values: Array.from({ length: n }, (_, i) => Math.max(0, s.values[i] ?? 0)), cls: swatch(s.tone, k) })); | |
| 352 | const stacked = data.kind !== "line"; | |
| 353 | const tops = Array.from({ length: n }, (_, i) => (stacked ? series.reduce((a, s) => a + s.values[i]!, 0) : Math.max(0, ...series.map((s) => s.values[i]!)))); | |
| 354 | const top = niceTop(Math.max(0, ...tops)); | |
| 355 | const y = (v: number): number => 100 - (v / top) * 100; | |
| 356 | const slot = n === 0 ? 100 : 100 / n; | |
| 357 | const xAt = (i: number): number => (data.kind === "bar" ? slot * i + slot / 2 : n < 2 ? 50 : (i * 100) / (n - 1)); | |
| 358 | const grid = [0, 100].map((g) => `<line class="wchart-grid" x1="0" x2="100" y1="${g}" y2="${g}"/>`).join(""); | |
| 359 | let marks = ""; | |
| 360 | let defs = ""; | |
| 361 | if (data.kind === "bar") { | |
| 362 | const base = Array.from({ length: n }, () => 0); | |
| 363 | for (const s of series) { | |
| 364 | for (let i = 0; i < n; i++) { | |
| 365 | const v = s.values[i]!; | |
| 366 | if (v <= 0) continue; | |
| 367 | const y0 = y(base[i]!); | |
| 368 | const y1 = y(base[i]! + v); | |
| 369 | base[i] = base[i]! + v; | |
| 370 | const x0 = slot * i + slot * 0.18; | |
| 371 | const w = slot * 0.64; | |
| 372 | // Only the top of a stack has rounded corners, its top ones only; the segments under it | |
| 373 | // meet square. | |
| 374 | const rx = Math.min(w / 4, 1.2); | |
| 375 | const ry = Math.min(y0 - y1, 1.6); | |
| 376 | marks += base[i]! >= tops[i]! | |
| 377 | ? `<path class="${s.cls}" d="M${num(x0)} ${num(y0)}V${num(y1 + ry)}Q${num(x0)} ${num(y1)} ${num(x0 + rx)} ${num(y1)}H${num(x0 + w - rx)}Q${num(x0 + w)} ${num(y1)} ${num(x0 + w)} ${num(y1 + ry)}V${num(y0)}Z"/>` | |
| 378 | : `<rect class="${s.cls}" x="${num(x0)}" y="${num(y1)}" width="${num(w)}" height="${num(y0 - y1)}"/>`; | |
| 379 | } | |
| 380 | } | |
| 381 | } else { | |
| 382 | const xs = Array.from({ length: n }, (_, i) => xAt(i)); | |
| 383 | const base = Array.from({ length: n }, () => 0); | |
| 384 | const layers: string[] = []; | |
| 385 | series.forEach((s, k) => { | |
| 386 | const lows = base.slice(); | |
| 387 | const highs = stacked ? s.values.map((v, i) => lows[i]! + v) : s.values.slice(); | |
| 388 | if (stacked) highs.forEach((v, i) => (base[i] = v)); | |
| 389 | const line = monotone(xs, highs.map(y)); | |
| 390 | if (data.kind === "area") { | |
| 391 | const id = `wg-${uid}-${k}`; | |
| 392 | defs += `<linearGradient id="${id}" x1="0" y1="0" x2="0" y2="1"><stop class="${s.cls}" offset="5%" stop-opacity=".8"/><stop class="${s.cls}" offset="95%" stop-opacity=".1"/></linearGradient>`; | |
| 393 | const under = stacked && k > 0 ? monotone([...xs].reverse(), [...lows].reverse().map(y)).replace(/^M/, "L") : `L${num(xs[n - 1] ?? 100)} 100 L${num(xs[0] ?? 0)} 100`; | |
| 394 | layers.push(`<path class="wchart-fill" fill="url(#${id})" d="${line} ${under} Z"/><path class="wchart-line ${s.cls}" d="${line}"/>`); | |
| 395 | } else layers.push(`<path class="wchart-line ${s.cls}" d="${line}"/>`); | |
| 396 | }); | |
| 397 | // The upper series is drawn last, over the ones it stands on. | |
| 398 | marks = layers.join(""); | |
| 399 | } | |
| 400 | const hits = Array.from({ length: n }, (_, i) => { | |
| 401 | const left = data.kind === "bar" ? slot * i : i === 0 ? 0 : (xAt(i - 1) + xAt(i)) / 2; | |
| 402 | const right = data.kind === "bar" ? slot * (i + 1) : i === n - 1 ? 100 : (xAt(i) + xAt(i + 1)) / 2; | |
| 403 | const words = series.map((s) => `${s.name} ${withUnit(s.values[i]!, data.unit)}`).join(", "); | |
| 404 | return `<rect class="wchart-hit" x="${num(left)}" y="0" width="${num(right - left)}" height="100"><title>${escapeHtml(`${day(i)}: ${words}`)}</title></rect>`; | |
| 405 | }).join(""); | |
| 406 | const svg = `<svg class="wchart-svg" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true" focusable="false">${defs === "" ? "" : `<defs>${defs}</defs>`}${grid}${marks}${hits}</svg>`; | |
| 407 | const picks = ticks(n); | |
| 408 | const xAxis = data.kind === "bar" | |
| 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 | : 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)); | |
| 412 | 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 | // In a box, not on the table: a table grows to its cells whatever width it is given. | |
| 415 | 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 | return html`<figure class="wchart" data-kind="${data.kind}" role="group" aria-label="${summary.slice(0, 300)}"> | |
| 417 | ${key} | |
| 418 | <div class="wchart-plot"><span class="wchart-tick" aria-hidden="true">${tick(top, data.unit)}</span><span class="wchart-tick is-zero" aria-hidden="true">${tick(0, data.unit)}</span>${raw(svg)}</div> | |
| 419 | ${xAxis} | |
| 420 | ${table} | |
| 421 | </figure>`; | |
| 422 | } | |
| 423 | ||
| 424 | /** A widget's data drawn by its renderer; `uid` keeps each chart's gradients its own on a page. */ | |
| 425 | export function widgetHtml(renderer: Renderer, data: WidgetData, title: string, uid: string): Html { | |
| 426 | switch (renderer) { | |
| 427 | case "chart": | |
| 428 | return chartHtml(data as ChartData, title, uid); | |
| 429 | } | |
| 430 | } | |
| 431 | ||
| 432 | /** | |
| 433 | * The renderers' rules: tokens only, 12 px words, a plot that holds its height before paint. Days | |
| 434 | * run left to right in any language (`direction: ltr` on the plot and its days), so in rtl each | |
| 435 | * label stays under its own mark. | |
| 436 | */ | |
| 437 | export const widgetCss = /* css */ ` | |
| 438 | .wchart { margin: 0; font-size: var(--fs-min); line-height: 16px; color: var(--muted-fg); font-variant-numeric: tabular-nums; min-width: 0; container-type: inline-size; } | |
| 439 | .wchart .s0 { --c: var(--series-0); } .wchart .s1 { --c: var(--series-1); } .wchart .s2 { --c: var(--series-2); } .wchart .s3 { --c: var(--series-3); } | |
| 440 | .wchart .s4 { --c: var(--series-4); } .wchart .s5 { --c: var(--series-5); } .wchart .s6 { --c: var(--series-6); } .wchart .s7 { --c: var(--series-7); } | |
| 441 | .wchart .tg { --c: var(--success); } .wchart .tb { --c: var(--danger); } | |
| 442 | .wchart-plot { position: relative; height: 128px; padding: 0 12px 0 32px; } | |
| 443 | .wchart-svg { display: block; width: 100%; height: 100%; overflow: visible; } | |
| 444 | .wchart-grid { stroke: var(--border); stroke-opacity: .5; vector-effect: non-scaling-stroke; shape-rendering: crispEdges; } | |
| 445 | .wchart-line { fill: none; stroke: var(--c); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; } | |
| 446 | .wchart[data-kind="area"] .wchart-line { stroke-width: 1.5; } | |
| 447 | .wchart stop { stop-color: var(--c); } | |
| 448 | .wchart :is(rect, path):not(.wchart-line, .wchart-fill, .wchart-hit) { fill: var(--c); stroke: var(--card); stroke-width: 1; vector-effect: non-scaling-stroke; } | |
| 449 | .wchart-hit { fill: var(--fg); fill-opacity: 0; } | |
| 450 | .wchart-hit:hover { fill-opacity: .05; } | |
| 451 | .wchart-tick { position: absolute; left: 0; width: 28px; text-align: right; top: 0; transform: translateY(-50%); } | |
| 452 | .wchart-tick.is-zero { top: 100%; } | |
| 453 | .wchart-x { display: flex; justify-content: space-between; margin: 6px 12px 0 32px; } | |
| 454 | .wchart-plot, .wchart-x { direction: ltr; } | |
| 455 | .wchart-x > span { width: 0; display: flex; justify-content: center; white-space: nowrap; } | |
| 456 | .wchart-x > span:first-child { justify-content: flex-start; } | |
| 457 | .wchart-x > span:last-child { justify-content: flex-end; } | |
| 458 | .wchart-x.is-slots > span { flex: 1; justify-content: center; } | |
| 459 | .wchart-key { display: flex; flex-wrap: wrap; gap: 4px 16px; margin: 0 0 12px; } | |
| 460 | .wchart-key > span { display: inline-flex; align-items: center; gap: 6px; } | |
| 461 | .wchart-key i { width: 8px; height: 8px; border-radius: 2px; background: var(--c); flex: none; } | |
| 462 | .wchart-key b { font-weight: 500; color: var(--fg); } | |
| 463 | @container (max-width: 440px) { .wchart-x:not(.is-slots) > span:nth-child(2):nth-last-child(4), .wchart-x:not(.is-slots) > span:nth-child(4):nth-last-child(2) { display: none; } .wchart-plot { height: 112px; } } | |
| 464 | .talk-widget > .card-head { padding: 0; } | |
| 465 | .talk-widget > .card-body { padding: 8px 0 0; } | |
| 466 | `; | |
| 467 | ||
| 248 | 468 | /** |
| 249 | 469 | * The voice's rules, appended to the page's stylesheet: existing tokens, 44 px targets, logical |
| 250 | 470 | * sides. |
| @@ -280,4 +500,4 @@ p.talk-card-from { padding-inline-start: 24px; } | ||
| 280 | 500 | .talk-plan .row-title, .talk-known .row-title { font-weight: inherit; } |
| 281 | 501 | .talk-plan .row-lead { align-self: center; } |
| 282 | 502 | .talk-plan li[data-state="done"] .row-title, .talk-plan li[data-state="skipped"] .row-title, .talk-plan-state { color: var(--muted-fg); } |
| 283 | `; | |
| 503 | ` + widgetCss; |
src/widgets/registry.ts added +371
| @@ -0,0 +1,371 @@ | ||
| 1 | /** | |
| 2 | * Widgets (#6009): what the forge's agent can show a person in a reply, drawn by the forge itself. | |
| 3 | * A widget is a name, a title, one line telling the agent what it shows, the renderer that draws it | |
| 4 | * (a `chart`), a JSON schema for its arguments, and `read`, which returns its data through the | |
| 5 | * access checks every page uses. The data's schema is its renderer's (`DATA_SCHEMA`), so every | |
| 6 | * widget of one renderer is drawn the same way and an outside host reads one shape per renderer. | |
| 7 | * | |
| 8 | * The roster is `WIDGETS`; the first widget, `checks`, and what it reads with (the scope, the | |
| 9 | * window of days, the read of the checks) are here. Nothing here draws: the page's renderer is in | |
| 10 | * `web/talk_parts.ts`, the terminal's in `core/talk_voice.ts`. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { App } from "../app.ts"; | |
| 14 | import type { User } from "../core/users.ts"; | |
| 15 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 16 | import type { Database } from "bun:sqlite"; | |
| 17 | import { canRead, getRepo, listReposWritableTo, type Repo } from "../core/repos.ts"; | |
| 18 | ||
| 19 | /** The forge's renderers a widget may name. */ | |
| 20 | export const RENDERERS = ["chart"] as const; | |
| 21 | export type Renderer = (typeof RENDERERS)[number]; | |
| 22 | ||
| 23 | /** A chart: days (or other labels) across, up to eight named series of numbers. */ | |
| 24 | export interface ChartData { | |
| 25 | readonly kind: "line" | "bar" | "area"; | |
| 26 | readonly x: readonly string[]; | |
| 27 | readonly series: readonly { | |
| 28 | readonly name: string; | |
| 29 | readonly values: readonly number[]; | |
| 30 | /** | |
| 31 | * A series that is good news or bad (checks passed, failed) takes the success or danger colour. | |
| 32 | */ | |
| 33 | readonly tone?: "good" | "bad"; | |
| 34 | }[]; | |
| 35 | /** What a value counts, said after it: "checks", "$", "hours". */ | |
| 36 | readonly unit?: string; | |
| 37 | } | |
| 38 | export type WidgetData = ChartData; | |
| 39 | ||
| 40 | /** The subset of JSON Schema a widget's arguments and data are written in, and `validate` reads. */ | |
| 41 | export interface Schema { | |
| 42 | readonly type: | |
| 43 | | "object" | |
| 44 | | "array" | |
| 45 | | "string" | |
| 46 | | "number" | |
| 47 | | "integer" | |
| 48 | | "boolean"; | |
| 49 | readonly description?: string; | |
| 50 | readonly properties?: Readonly<Record<string, Schema>>; | |
| 51 | readonly required?: readonly string[]; | |
| 52 | readonly additionalProperties?: false; | |
| 53 | readonly items?: Schema | { readonly anyOf: readonly Schema[] }; | |
| 54 | readonly enum?: readonly (string | number)[]; | |
| 55 | readonly minItems?: number; | |
| 56 | readonly maxItems?: number; | |
| 57 | readonly maxLength?: number; | |
| 58 | readonly minimum?: number; | |
| 59 | readonly maximum?: number; | |
| 60 | readonly pattern?: string; | |
| 61 | } | |
| 62 | ||
| 63 | /** Where `value` breaks `schema` (a path and the rule), or undefined when it fits. */ | |
| 64 | export function validate( | |
| 65 | schema: Schema, | |
| 66 | value: unknown, | |
| 67 | at = "$", | |
| 68 | ): string | undefined { | |
| 69 | const is = (t: Schema["type"]): boolean => | |
| 70 | t === "integer" | |
| 71 | ? Number.isInteger(value) | |
| 72 | : t === "number" | |
| 73 | ? typeof value === "number" && Number.isFinite(value) | |
| 74 | : t === "array" | |
| 75 | ? Array.isArray(value) | |
| 76 | : t === "object" | |
| 77 | ? typeof value === "object" && | |
| 78 | value !== null && | |
| 79 | !Array.isArray(value) | |
| 80 | : typeof value === t; | |
| 81 | if (!is(schema.type)) return `${at}: not ${schema.type}`; | |
| 82 | if ( | |
| 83 | schema.enum !== undefined && | |
| 84 | !schema.enum.includes(value as string | number) | |
| 85 | ) | |
| 86 | return `${at}: not one of ${schema.enum.join(", ")}`; | |
| 87 | if (typeof value === "string") { | |
| 88 | if (schema.maxLength !== undefined && value.length > schema.maxLength) | |
| 89 | return `${at}: longer than ${schema.maxLength}`; | |
| 90 | if (schema.pattern !== undefined && !new RegExp(schema.pattern).test(value)) | |
| 91 | return `${at}: not of the form ${schema.pattern}`; | |
| 92 | } | |
| 93 | if (typeof value === "number") { | |
| 94 | if (schema.minimum !== undefined && value < schema.minimum) | |
| 95 | return `${at}: below ${schema.minimum}`; | |
| 96 | if (schema.maximum !== undefined && value > schema.maximum) | |
| 97 | return `${at}: above ${schema.maximum}`; | |
| 98 | } | |
| 99 | if (Array.isArray(value)) { | |
| 100 | if (schema.minItems !== undefined && value.length < schema.minItems) | |
| 101 | return `${at}: fewer than ${schema.minItems}`; | |
| 102 | if (schema.maxItems !== undefined && value.length > schema.maxItems) | |
| 103 | return `${at}: more than ${schema.maxItems}`; | |
| 104 | const items = schema.items; | |
| 105 | if (items !== undefined) | |
| 106 | for (const [i, v] of value.entries()) { | |
| 107 | const where = `${at}[${i}]`; | |
| 108 | const broke = | |
| 109 | "anyOf" in items | |
| 110 | ? items.anyOf.some((s) => validate(s, v, where) === undefined) | |
| 111 | ? undefined | |
| 112 | : `${where}: fits none of its forms` | |
| 113 | : validate(items, v, where); | |
| 114 | if (broke !== undefined) return broke; | |
| 115 | } | |
| 116 | } | |
| 117 | if (schema.type === "object") { | |
| 118 | const o = value as Record<string, unknown>; | |
| 119 | for (const k of schema.required ?? []) | |
| 120 | if (o[k] === undefined) return `${at}.${k}: missing`; | |
| 121 | for (const [k, v] of Object.entries(o)) { | |
| 122 | const p = schema.properties?.[k]; | |
| 123 | if (p === undefined) { | |
| 124 | if (schema.additionalProperties === false) | |
| 125 | return `${at}.${k}: not a field`; | |
| 126 | continue; | |
| 127 | } | |
| 128 | const broke = validate(p, v, `${at}.${k}`); | |
| 129 | if (broke !== undefined) return broke; | |
| 130 | } | |
| 131 | } | |
| 132 | return undefined; | |
| 133 | } | |
| 134 | ||
| 135 | const LABEL: Schema = { type: "string", maxLength: 80 }; | |
| 136 | /** Most points across a chart, and series of a chart. */ | |
| 137 | export const WIDGET_LIMITS = { | |
| 138 | points: 120, | |
| 139 | series: 8, | |
| 140 | } as const; | |
| 141 | ||
| 142 | /** The data each renderer draws, as JSON Schema: a widget's output schema is its renderer's. */ | |
| 143 | export const DATA_SCHEMA: Readonly<Record<Renderer, Schema>> = { | |
| 144 | chart: { | |
| 145 | type: "object", | |
| 146 | additionalProperties: false, | |
| 147 | required: ["kind", "x", "series"], | |
| 148 | properties: { | |
| 149 | kind: { type: "string", enum: ["line", "bar", "area"] }, | |
| 150 | x: { type: "array", maxItems: WIDGET_LIMITS.points, items: LABEL }, | |
| 151 | series: { | |
| 152 | type: "array", | |
| 153 | minItems: 1, | |
| 154 | maxItems: WIDGET_LIMITS.series, | |
| 155 | items: { | |
| 156 | type: "object", | |
| 157 | additionalProperties: false, | |
| 158 | required: ["name", "values"], | |
| 159 | properties: { | |
| 160 | name: LABEL, | |
| 161 | values: { | |
| 162 | type: "array", | |
| 163 | maxItems: WIDGET_LIMITS.points, | |
| 164 | items: { type: "number" }, | |
| 165 | }, | |
| 166 | tone: { type: "string", enum: ["good", "bad"] }, | |
| 167 | }, | |
| 168 | }, | |
| 169 | }, | |
| 170 | unit: { type: "string", maxLength: 20 }, | |
| 171 | }, | |
| 172 | }, | |
| 173 | }; | |
| 174 | ||
| 175 | /** Why a widget did not answer: the usual ambiguity for what the person may not read. */ | |
| 176 | export type WidgetRefusal = "not_found" | "invalid"; | |
| 177 | ||
| 178 | export interface Widget { | |
| 179 | readonly name: string; | |
| 180 | /** What the person reads above it: "Checks per day". */ | |
| 181 | readonly title: string; | |
| 182 | /** One line for the agent: what it shows and when to use it. */ | |
| 183 | readonly description: string; | |
| 184 | readonly renderer: Renderer; | |
| 185 | /** Its arguments, as JSON Schema; an object with no other fields. */ | |
| 186 | readonly args: Schema; | |
| 187 | /** | |
| 188 | * Its data, read as `user` through the same access checks every page uses; a repository the | |
| 189 | * person may not read is `not_found`. The words say in one sentence what the data shows, for the | |
| 190 | * agent to talk about it truthfully. | |
| 191 | */ | |
| 192 | read( | |
| 193 | app: App, | |
| 194 | user: User | undefined, | |
| 195 | args: Readonly<Record<string, unknown>>, | |
| 196 | ): Result<{ data: WidgetData; says: string }, WidgetRefusal>; | |
| 197 | } | |
| 198 | ||
| 199 | /** The arguments most widgets take: which repository, and how many days back. */ | |
| 200 | export const SCOPE_ARGS = { | |
| 201 | repo: { | |
| 202 | type: "string", | |
| 203 | maxLength: 200, | |
| 204 | pattern: "^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$", | |
| 205 | description: "owner/name; absent: every repository you work on", | |
| 206 | }, | |
| 207 | days: { | |
| 208 | type: "integer", | |
| 209 | minimum: 1, | |
| 210 | maximum: 90, | |
| 211 | description: "how many days back, today included (default 14)", | |
| 212 | }, | |
| 213 | } as const satisfies Record<string, Schema>; | |
| 214 | ||
| 215 | /** The most repositories "every repository you work on" spans. */ | |
| 216 | export const SCOPE_REPOS = 100; | |
| 217 | ||
| 218 | /** | |
| 219 | * The repositories a widget reads: the one named, when the person may read it, else `not_found`, | |
| 220 | * whether it is missing or hidden; or the ones they work on (their own and their teams'), at most | |
| 221 | * `SCOPE_REPOS`. | |
| 222 | */ | |
| 223 | export function scopeOf( | |
| 224 | app: App, | |
| 225 | user: User | undefined, | |
| 226 | args: Readonly<Record<string, unknown>>, | |
| 227 | ): Result<{ repos: Repo[]; where: string }, "not_found"> { | |
| 228 | const named = typeof args["repo"] === "string" ? args["repo"] : undefined; | |
| 229 | if (named === undefined) { | |
| 230 | const repos = listReposWritableTo(app.db, user, { | |
| 231 | withoutCounts: true, | |
| 232 | limit: SCOPE_REPOS, | |
| 233 | }); | |
| 234 | return ok({ repos, where: "every repository you work on" }); | |
| 235 | } | |
| 236 | const [owner = "", name = ""] = named.split("/"); | |
| 237 | const repo = getRepo(app.db, owner, name); | |
| 238 | return repo !== undefined && canRead(app.db, repo, user) | |
| 239 | ? ok({ repos: [repo], where: `${repo.ownerName}/${repo.name}` }) | |
| 240 | : err("not_found"); | |
| 241 | } | |
| 242 | ||
| 243 | /** The UTC days of a window of `days` ending today, oldest first, as `YYYY-MM-DD`. */ | |
| 244 | export function dayLabels(days: number, now: number = Date.now()): string[] { | |
| 245 | const today = Math.floor(now / 86_400_000); | |
| 246 | return Array.from({ length: days }, (_, i) => | |
| 247 | new Date((today - days + 1 + i) * 86_400_000).toISOString().slice(0, 10), | |
| 248 | ); | |
| 249 | } | |
| 250 | ||
| 251 | /** | |
| 252 | * The days a widget draws, `days` back (default 14) with today, and the instant the first begins. | |
| 253 | */ | |
| 254 | export interface Window { | |
| 255 | readonly days: readonly string[]; | |
| 256 | readonly since: string; | |
| 257 | } | |
| 258 | ||
| 259 | /** The window `args` asks for. */ | |
| 260 | export function windowOf(args: Readonly<Record<string, unknown>>, now: number = Date.now()): Window { | |
| 261 | const days = dayLabels(typeof args["days"] === "number" ? args["days"] : 14, now); | |
| 262 | return { days, since: `${days[0] ?? ""}T00:00:00.000Z` }; | |
| 263 | } | |
| 264 | ||
| 265 | /** | |
| 266 | * Counts per day per series from instants: one array per series, a slot per day; an instant outside | |
| 267 | * the window is dropped. | |
| 268 | */ | |
| 269 | export function perDay<S extends string>(days: readonly string[], series: readonly S[], rows: Iterable<{ at: string; series: S | undefined; value?: number }>): Record<S, number[]> { | |
| 270 | const at = new Map(days.map((d, i) => [d, i])); | |
| 271 | const out = Object.fromEntries(series.map((s) => [s, days.map(() => 0)])) as Record<S, number[]>; | |
| 272 | for (const r of rows) { | |
| 273 | const i = at.get(r.at.slice(0, 10)); | |
| 274 | if (i === undefined || r.series === undefined) continue; | |
| 275 | out[r.series][i]! += r.value ?? 1; | |
| 276 | } | |
| 277 | return out; | |
| 278 | } | |
| 279 | ||
| 280 | /** The repositories as the one JSON list every read binds. */ | |
| 281 | const idsOf = (repos: readonly Repo[]): string => JSON.stringify(repos.map((r) => r.id)); | |
| 282 | ||
| 283 | /** | |
| 284 | * Each check finished on these repositories since an instant: when, and how it ended. One covering | |
| 285 | * walk of `run_finished_cov`. | |
| 286 | */ | |
| 287 | export const checksSince = (db: Database, repos: readonly Repo[], since: string): { at: string; state: string }[] => | |
| 288 | db | |
| 289 | .query<{ at: string; state: string }, [string, string]>( | |
| 290 | `SELECT finished_at AS at, state FROM run INDEXED BY run_finished_cov | |
| 291 | WHERE kind = 'check' AND finished_at IS NOT NULL AND finished_at >= ?1 AND repo_id IN (SELECT value FROM json_each(?2))`, | |
| 292 | ) | |
| 293 | .all(since, idsOf(repos)); | |
| 294 | ||
| 295 | /** A number rounded for a sentence: whole above ten, one place below. */ | |
| 296 | export const said = (v: number): string => (Math.abs(v) >= 10 ? Math.round(v) : Math.round(v * 10) / 10).toLocaleString("en-US"); | |
| 297 | ||
| 298 | /** The first widget: checks per day, passed and failed. */ | |
| 299 | const checks: Widget = { | |
| 300 | name: "checks", | |
| 301 | title: "Checks per day", | |
| 302 | description: "Checks that passed and failed each day, for one repository or all you work on. For: how are my checks doing?", | |
| 303 | renderer: "chart", | |
| 304 | args: { type: "object", additionalProperties: false, properties: SCOPE_ARGS }, | |
| 305 | read(app, user, args) { | |
| 306 | const scope = scopeOf(app, user, args); | |
| 307 | if (!scope.ok) return scope; | |
| 308 | const { days, since } = windowOf(args); | |
| 309 | const by = perDay(days, ["ok", "failed"] as const, checksSince(app.db, scope.value.repos, since).map((r) => ({ at: r.at, series: r.state === "ok" ? "ok" : r.state === "failed" ? "failed" : undefined }))); | |
| 310 | const passed = by.ok.reduce((a, b) => a + b, 0); | |
| 311 | const failed = by.failed.reduce((a, b) => a + b, 0); | |
| 312 | const all = passed + failed; | |
| 313 | const worst = by.failed.indexOf(Math.max(...by.failed)); | |
| 314 | return ok({ | |
| 315 | data: { kind: "bar", x: days, unit: "checks", series: [{ name: "Passed", values: by.ok, tone: "good" }, { name: "Failed", values: by.failed, tone: "bad" }] }, | |
| 316 | says: | |
| 317 | all === 0 | |
| 318 | ? `No checks finished in the last ${days.length} days on ${scope.value.where}.` | |
| 319 | : `${said(all)} checks finished in the last ${days.length} days on ${scope.value.where}: ${said(passed)} passed and ${said(failed)} failed (${said((passed / all) * 100)}% passed)${failed === 0 ? "" : `; the most failures were on ${days[worst]} (${said(by.failed[worst]!)})`}.`, | |
| 320 | }); | |
| 321 | }, | |
| 322 | }; | |
| 323 | ||
| 324 | /** Every widget, by name. */ | |
| 325 | export const WIDGETS: readonly Widget[] = [checks]; | |
| 326 | ||
| 327 | export const widgetNamed = (name: string): Widget | undefined => | |
| 328 | WIDGETS.find((w) => w.name === name); | |
| 329 | ||
| 330 | /** | |
| 331 | * The widgets whose name, title or description holds every word of `query` (all of them when | |
| 332 | * empty). | |
| 333 | */ | |
| 334 | export function searchWidgets(query: string): Widget[] { | |
| 335 | const words = query | |
| 336 | .toLowerCase() | |
| 337 | .split(/\W+/) | |
| 338 | .filter((w) => w.length > 1); | |
| 339 | return WIDGETS.filter((w) => { | |
| 340 | const hay = `${w.name} ${w.title} ${w.description}`.toLowerCase(); | |
| 341 | return words.every((word) => hay.includes(word)); | |
| 342 | }); | |
| 343 | } | |
| 344 | ||
| 345 | /** One widget's data, its arguments and its answer both held to their schemas. */ | |
| 346 | export function readWidget( | |
| 347 | app: App, | |
| 348 | user: User | undefined, | |
| 349 | name: string, | |
| 350 | args: Readonly<Record<string, unknown>>, | |
| 351 | ): Result<{ widget: Widget; data: WidgetData; says: string }, WidgetRefusal> { | |
| 352 | const widget = widgetNamed(name); | |
| 353 | if (widget === undefined) return err("not_found"); | |
| 354 | if (validate(widget.args, args) !== undefined) return err("invalid"); | |
| 355 | const read = widget.read(app, user, args); | |
| 356 | if (!read.ok) return read; | |
| 357 | // A widget that answers outside its renderer's shape is a defect drawn as nothing, never half. | |
| 358 | if (validate(DATA_SCHEMA[widget.renderer], read.value.data) !== undefined) | |
| 359 | return err("invalid"); | |
| 360 | return ok({ widget, ...read.value }); | |
| 361 | } | |
| 362 | ||
| 363 | /** | |
| 364 | * The `## Widgets` section of /llms.txt for a reader with an account: one line naming every | |
| 365 | * widget (`show` with no widget describes each); nothing while there are none. The roster, live, as | |
| 366 | * the MCP tools' section is. | |
| 367 | */ | |
| 368 | export function widgetsSection(): string[] { | |
| 369 | if (WIDGETS.length === 0) return []; | |
| 370 | return ["## Widgets", "", `\`show\` draws: ${WIDGETS.map((w) => w.name).join(", ")}.`, ""]; | |
| 371 | } |
test/mcp-forge-protocol.test.ts +1
| @@ -128,6 +128,7 @@ describe("the forge over MCP: protocol", () => { | ||
| 128 | 128 | "tell", |
| 129 | 129 | "templates", |
| 130 | 130 | "share", |
| 131 | "show", | |
| 131 | 132 | "say", |
| 132 | 133 | "issue", |
| 133 | 134 | "pull", |
test/mcp-widgets.test.ts added +99
| @@ -0,0 +1,99 @@ | ||
| 1 | /** | |
| 2 | * The agent's widget tool (#6009): `show` with no widget lists the widgets and what each takes; | |
| 3 | * with one, it draws it read as the caller and, in Talk, keeps it under a handle exactly as a card | |
| 4 | * is kept. A read on Talk's list: never held, never asking, never written into the conversation's | |
| 5 | * writes. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { appendTurn, createConversation } from "../src/core/conversations.ts"; | |
| 13 | import { cardsOf } from "../src/core/talk_voice.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { mintViaToken } from "../src/core/via_token.ts"; | |
| 16 | import { TALK_TOOLS } from "../src/http/mcp/catalog.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | import { WIDGETS } from "../src/widgets/registry.ts"; | |
| 19 | import { promote } from "./helpers/members.ts"; | |
| 20 | ||
| 21 | let dir: string; | |
| 22 | let app: App; | |
| 23 | let servers: Servers; | |
| 24 | let alice: User; | |
| 25 | let rpc = 1; | |
| 26 | ||
| 27 | const call = async (token: string, name: string, args: Record<string, unknown>) => { | |
| 28 | const res = await fetch(`${servers.url}/mcp`, { | |
| 29 | method: "POST", | |
| 30 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 31 | body: JSON.stringify({ jsonrpc: "2.0", id: rpc++, method: "tools/call", params: { name, arguments: args } }), | |
| 32 | }); | |
| 33 | return ((await res.json()) as { result: Record<string, unknown> }).result; | |
| 34 | }; | |
| 35 | const textOf = (r: Record<string, unknown>) => (r["content"] as { text: string }[]).map((c) => c.text).join("\n"); | |
| 36 | const talk = (u: User, words: string) => { | |
| 37 | const c = createConversation(app.db, u.id); | |
| 38 | if (!c.ok) throw new Error(c.error); | |
| 39 | appendTurn(app.db, u.id, c.value.id, { role: "person", text: words }); | |
| 40 | const minted = mintViaToken(app.db, u.id, `conversation:${c.value.id}`, words, new Date(Date.now() + 600_000).toISOString()); | |
| 41 | if (!minted.ok) throw new Error(minted.error); | |
| 42 | return { via: `conversation:${c.value.id}`, token: minted.value.token }; | |
| 43 | }; | |
| 44 | ||
| 45 | beforeAll(async () => { | |
| 46 | dir = await mkdtemp(join(tmpdir(), "forge-mcp-widgets-")); | |
| 47 | app = createApp({ dataDir: dir, port: 0 }); | |
| 48 | servers = await serve(app); | |
| 49 | const mk = async (username: string, first: boolean) => { | |
| 50 | const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first }); | |
| 51 | if (!u.ok) throw new Error(u.error); | |
| 52 | promote(app.db, u.value); | |
| 53 | return u.value; | |
| 54 | }; | |
| 55 | alice = await mk("alice", true); | |
| 56 | }, 30_000); | |
| 57 | afterAll(async () => { | |
| 58 | servers.stop(); | |
| 59 | app.close(); | |
| 60 | await rm(dir, { recursive: true, force: true }); | |
| 61 | }); | |
| 62 | ||
| 63 | describe("the widget tools", () => { | |
| 64 | test("show is on Talk's list, and is a read", async () => { | |
| 65 | expect(TALK_TOOLS).toContain("show"); | |
| 66 | const t = talk(alice, "what can you show me?"); | |
| 67 | const res = await fetch(`${servers.url}/mcp`, { | |
| 68 | method: "POST", | |
| 69 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${t.token}` }, | |
| 70 | body: JSON.stringify({ jsonrpc: "2.0", id: rpc++, method: "tools/list" }), | |
| 71 | }); | |
| 72 | const listed = ((await res.json()) as { result: { tools: { name: string; annotations?: { readOnlyHint?: boolean } }[] } }).result.tools; | |
| 73 | expect(listed.find((x) => x.name === "show")?.annotations?.readOnlyHint).toBe(true); | |
| 74 | }); | |
| 75 | ||
| 76 | test("show with no widget lists every widget with its arguments; a widget it does not have is not found", async () => { | |
| 77 | const t = talk(alice, "what can you show me?"); | |
| 78 | // Every string the forge read is fenced as data, its names included. | |
| 79 | const all = JSON.parse(textOf(await call(t.token, "show", {})).split("\n").find((l) => l.startsWith("{"))!) as { widgets: { name: string; args: unknown }[] }; | |
| 80 | expect(all.widgets.map((w) => w.name.replace(/\[\[\/?data [0-9a-f]+\]\]/g, "").trim())).toEqual(WIDGETS.map((w) => w.name)); | |
| 81 | expect(all.widgets.every((w) => typeof w.args === "object")).toBe(true); | |
| 82 | expect(textOf(await call(t.token, "show", { widget: "no-such-widget" }))).toContain("not_found"); | |
| 83 | }); | |
| 84 | ||
| 85 | test("in Talk, show answers in fenced text and a handle only: no data beside it for the agent to read unfenced", async () => { | |
| 86 | const t = talk(alice, "how are my checks?"); | |
| 87 | const r = await call(t.token, "show", { widget: "checks", args: { days: 7 } }); | |
| 88 | expect(r["structuredContent"]).toBeUndefined(); | |
| 89 | expect(textOf(r)).toContain("[[data "); | |
| 90 | }); | |
| 91 | ||
| 92 | test("show of a widget the forge does not have is not found, and keeps nothing", async () => { | |
| 93 | const t = talk(alice, "show me a pie"); | |
| 94 | const r = await call(t.token, "show", { widget: "pie" }); | |
| 95 | expect(r["isError"]).toBe(true); | |
| 96 | expect(textOf(r)).toContain("not_found"); | |
| 97 | expect(cardsOf(app.db, alice.id, t.via, [1]).size).toBe(0); | |
| 98 | }); | |
| 99 | }); |
test/talk-blocks.test.ts +4 −1
| @@ -27,6 +27,7 @@ import { createUser, type User } from "../src/core/users.ts"; | ||
| 27 | 27 | import { renderInline, renderMarkdown } from "../src/web/markdown.ts"; |
| 28 | 28 | import { turnHtml } from "../src/web/pages/talk.ts"; |
| 29 | 29 | import { agentHtml, linkOf, voiceCss, voiceOf } from "../src/web/talk_parts.ts"; |
| 30 | import { widgetCss } from "../src/web/talk_parts.ts"; | |
| 30 | 31 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 31 | 32 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 32 | 33 | import { settleApp } from "./helpers/tui.ts"; |
| @@ -481,7 +482,8 @@ describe("a README is untouched", () => { | ||
| 481 | 482 | |
| 482 | 483 | describe("the page's rules and links", () => { |
| 483 | 484 | test("the stylesheet is small, uses tokens, and says sides logically", () => { |
| 484 | expect(Buffer.byteLength(voiceCss)).toBeLessThan(2_600); | |
| 485 | // The widgets' own rules ride on the same sheet and are held by test/widget-view.test.ts. | |
| 486 | expect(Buffer.byteLength(voiceCss) - Buffer.byteLength(widgetCss)).toBeLessThan(2_600); | |
| 485 | 487 | expect(voiceCss).not.toMatch( |
| 486 | 488 | /#[0-9a-f]{3,6}\b|rgb\(|(?:margin|padding)-(?:left|right)/i, |
| 487 | 489 | ); |
| @@ -515,6 +517,7 @@ describe("the terminal prints the same parts", () => { | ||
| 515 | 517 | n: 1, |
| 516 | 518 | tool: "now", |
| 517 | 519 | said: "Now", |
| 520 | title: "Working now", | |
| 518 | 521 | createdAt: "2026-11-22T10:00:00.000Z", |
| 519 | 522 | pressed: [] as string[], |
| 520 | 523 | card: { |
test/talk-page.test.ts +4 −1
| @@ -424,7 +424,10 @@ describe("the page", () => { | ||
| 424 | 424 | say(sizer.value, "person", "how?"); |
| 425 | 425 | say(sizer.value, "agent", "```ts\nlet x = 1;\n```"); |
| 426 | 426 | const size = (await (await get("/talk", sizer.value)).arrayBuffer()).byteLength; |
| 427 | expect(size).toBeLessThan(47_000); | |
| 427 | // Raised from 47,000 by the widgets' rules and no more (widgetCss, 2,495 B raw): they ride every | |
| 428 | // Talk page, because a chart can arrive in a live reply, and a page drawn without them would | |
| 429 | // show it unstyled until a reload. 48,328 measured. | |
| 430 | expect(size).toBeLessThan(49_500); | |
| 428 | 431 | }); |
| 429 | 432 | |
| 430 | 433 | describe("the script, driven against a DOM", () => { |
test/talk-shown.test.ts +2 −2
| @@ -314,8 +314,8 @@ describe("what is kept", () => { | ||
| 314 | 314 | const c = chat(alice); |
| 315 | 315 | const { n, id } = keep(alice, c, { ...stopCard(), rows: [{ label: "smith", value: "running", actions: [{ label: "Stop", tool: "stop", args: {} }] }] }); |
| 316 | 316 | const shown = cardsOf(app.db, alice.id, via(c), [n]).get(n)!; |
| 317 | expect(shown.card.actions.map((a) => a.label)).toEqual(["Stop smith"]); | |
| 318 | expect(shown.card.rows[0]!.actions?.map((a) => a.label)).toEqual(["Stop"]); | |
| 317 | expect(shown.card!.actions.map((a) => a.label)).toEqual(["Stop smith"]); | |
| 318 | expect(shown.card!.rows[0]!.actions?.map((a) => a.label)).toEqual(["Stop"]); | |
| 319 | 319 | app.db.query("INSERT INTO conversation_card_press (card_id, action, user_id, pressed_at) VALUES (?1, 'a0', ?2, ?3)").run(id, alice.id, new Date().toISOString()); |
| 320 | 320 | dropConversation(app.db, alice.id, c.id); |
| 321 | 321 | expect(app.db.query("SELECT COUNT(*) AS n FROM conversation_card_press WHERE card_id = ?1").get(id)).toEqual({ n: 0 }); |
test/widget-view.test.ts added +169
| @@ -0,0 +1,169 @@ | ||
| 1 | /** | |
| 2 | * The widget renderers (#6009, src/web/talk_parts.ts): every shape drawn on the server from data | |
| 3 | * alone, its words escaped and its numbers in a table only a screen reader hears; and a widget kept | |
| 4 | * for a conversation drawn at `::show cN` on the card surface under the forge's head, never for | |
| 5 | * another person and never from data outside its renderer's shape. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { appendTurn, createConversation } from "../src/core/conversations.ts"; | |
| 13 | import { createSession } from "../src/core/sessions.ts"; | |
| 14 | import { widgetLines, withUnit } from "../src/core/talk_voice.ts"; | |
| 15 | import { createUser, type User } from "../src/core/users.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { chartHtml, monotone, widgetCss } from "../src/web/talk_parts.ts"; | |
| 18 | import type { ChartData } from "../src/widgets/registry.ts"; | |
| 19 | ||
| 20 | const HOSTILE = `<script>alert(1)</script>"&`; | |
| 21 | const week = ["2026-11-18", "2026-11-19", "2026-11-20", "2026-11-21", "2026-11-22", "2026-11-23", "2026-11-24"]; | |
| 22 | const checks: ChartData = { kind: "bar", x: week, unit: "checks", series: [{ name: "Passed", values: [5, 7, 3, 9, 6, 8, 4], tone: "good" }, { name: "Failed", values: [1, 0, 2, 0, 1, 0, 1], tone: "bad" }] }; | |
| 23 | ||
| 24 | describe("the chart", () => { | |
| 25 | for (const kind of ["line", "bar", "area"] as const) | |
| 26 | test(`a ${kind} chart says every number and escapes every word`, () => { | |
| 27 | const h = chartHtml({ ...checks, kind, series: [...checks.series, { name: HOSTILE, values: [1, 1, 1, 1, 1, 1, 1] }] }, `Checks ${HOSTILE}`, "u1").text; | |
| 28 | expect(h).toContain(`data-kind="${kind}"`); | |
| 29 | expect(h).not.toContain("<script>"); | |
| 30 | expect(h).toContain("<script>"); | |
| 31 | // A table only a screen reader hears: a row a day, a column a series. | |
| 32 | const table = h.slice(h.indexOf('<div class="sr-only"><table>')); | |
| 33 | expect(table.match(/<tr>/g)?.length).toBe(8); | |
| 34 | expect(table).toContain("<th scope=\"row\">Nov 24</th>"); | |
| 35 | // The legend says each series' total; a day says its values on hover. | |
| 36 | expect(h).toContain("Passed <b>42 checks</b>"); | |
| 37 | expect(h).toContain("<title>Nov 24: Passed 4 checks, Failed 1 check, <script>"); | |
| 38 | expect(h).toContain('class="tg"'); | |
| 39 | expect(h).toContain('class="tb"'); | |
| 40 | }); | |
| 41 | ||
| 42 | test("a week's days are labelled at an even step, so no two labels ever touch", () => { | |
| 43 | const h = chartHtml(checks, "Checks", "w").text; | |
| 44 | const labels = [...h.slice(h.indexOf('class="wchart-x')).matchAll(/<span>([^<]*)<\/span>/g)].map((m) => m[1]); | |
| 45 | expect(labels).toEqual(["Nov 18", "", "Nov 20", "", "Nov 22", "", "Nov 24"]); | |
| 46 | // Only the top of a stack is rounded. | |
| 47 | expect((h.match(/<path class="t[gb]" d="M/g) ?? []).length).toBe(7); | |
| 48 | expect(h).not.toContain(" rx="); | |
| 49 | }); | |
| 50 | ||
| 51 | test("gradients are named by the widget, so two charts on a page never share one", () => { | |
| 52 | const a = chartHtml({ ...checks, kind: "area" }, "A", "one").text; | |
| 53 | const b = chartHtml({ ...checks, kind: "area" }, "B", "two").text; | |
| 54 | expect(a).toContain('id="wg-one-0"'); | |
| 55 | expect(b).toContain('id="wg-two-0"'); | |
| 56 | expect(a).toContain('fill="url(#wg-one-0)"'); | |
| 57 | }); | |
| 58 | ||
| 59 | test("the curve never overshoots its points, so a count never dips below zero", () => { | |
| 60 | const d = monotone([0, 25, 50, 75, 100], [100, 100, 0, 100, 100]); | |
| 61 | const ys = [...d.matchAll(/-?\d+(?:\.\d+)?/g)].map((m) => Number(m[0])).filter((_, i) => i % 2 === 1); | |
| 62 | expect(Math.max(...ys)).toBeLessThanOrEqual(100); | |
| 63 | expect(Math.min(...ys)).toBeGreaterThanOrEqual(0); | |
| 64 | }); | |
| 65 | ||
| 66 | test("no points draws an empty plot and says so", () => { | |
| 67 | const h = chartHtml({ kind: "line", x: [], series: [{ name: "x", values: [] }] }, "Nothing", "e").text; | |
| 68 | expect(h).toContain("Nothing: no points."); | |
| 69 | }); | |
| 70 | }); | |
| 71 | ||
| 72 | describe("a number with its unit", () => { | |
| 73 | test("is said one way, by the page and by the terminal", () => { | |
| 74 | // Where the page and the terminal once differed: thousands (12,500), a fraction under ten (3.3) | |
| 75 | // and dollars past ten ($12.35). | |
| 76 | expect([withUnit(12_500, "checks"), withUnit(3.256), withUnit(12.345, "$"), withUnit(1234.5, "$")]).toEqual(["12.5k checks", "3.26", "$12.3", "$1,235"]); | |
| 77 | expect([withUnit(3.25, "$"), withUnit(92, "%"), withUnit(0.5, "%"), withUnit(14, ""), withUnit(1234)]).toEqual(["$3.25", "92%", "0.5%", "14", "1,234"]); | |
| 78 | // One of a counted word loses its s; a word that only ends in ss, or in no s, stays. | |
| 79 | expect([withUnit(1, "checks"), withUnit(2, "checks"), withUnit(0, "checks"), withUnit(1, "hours"), withUnit(1, "class"), withUnit(1, "ms")]).toEqual(["1 check", "2 checks", "0 checks", "1 hour", "1 class", "1 m"]); | |
| 80 | // The same total, on the page's legend and on the terminal's line. | |
| 81 | const big: ChartData = { kind: "bar", x: ["2026-11-23", "2026-11-24"], unit: "checks", series: [{ name: "Passed", values: [12_000, 500] }] }; | |
| 82 | expect(chartHtml(big, "Checks", "b").text).toContain("<b>12.5k checks</b>"); | |
| 83 | expect(widgetLines({ name: "checks", renderer: "chart", title: "Checks", data: big })[1]).toEndWith(" 12.5k checks"); | |
| 84 | }); | |
| 85 | }); | |
| 86 | ||
| 87 | describe("the rules", () => { | |
| 88 | test("in rtl, days still run left to right under their own marks", () => { | |
| 89 | expect(widgetCss).toContain(".wchart-plot, .wchart-x { direction: ltr; }"); | |
| 90 | }); | |
| 91 | ||
| 92 | test("the rules are small and use tokens only", () => { | |
| 93 | // 3,600: the chart's start-edge scale, the bars' seams, and Talk's one-line widget head and row | |
| 94 | // of figures (the polish pass) took it past 3,000. | |
| 95 | expect(Buffer.byteLength(widgetCss)).toBeLessThan(3_600); | |
| 96 | expect(widgetCss).not.toMatch(/#[0-9a-f]{3,6}\b|rgb\(|(?:margin|padding)-(?:left|right)/i); | |
| 97 | }); | |
| 98 | }); | |
| 99 | ||
| 100 | let dir: string; | |
| 101 | let app: App; | |
| 102 | let servers: Servers; | |
| 103 | let alice: User; | |
| 104 | let bob: User; | |
| 105 | ||
| 106 | beforeAll(async () => { | |
| 107 | dir = await mkdtemp(join(tmpdir(), "forge-widget-view-")); | |
| 108 | app = createApp({ dataDir: dir, port: 0 }); | |
| 109 | servers = await serve(app); | |
| 110 | const mk = async (username: string, first = false) => { | |
| 111 | const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first }); | |
| 112 | if (!u.ok) throw new Error(u.error); | |
| 113 | return u.value; | |
| 114 | }; | |
| 115 | alice = await mk("alice", true); | |
| 116 | bob = await mk("bob"); | |
| 117 | }); | |
| 118 | afterAll(async () => { | |
| 119 | servers.stop(); | |
| 120 | app.close(); | |
| 121 | await rm(dir, { recursive: true, force: true }); | |
| 122 | }); | |
| 123 | ||
| 124 | const page = async (u: User, path: string) => (await fetch(`${servers.url}${path}`, { headers: { cookie: `forge_session=${createSession(app.db, u.id).token}` } })).text(); | |
| 125 | ||
| 126 | describe("a kept widget in a reply", () => { | |
| 127 | test("is drawn at ::show on the card surface, under the forge's head and its time", async () => { | |
| 128 | const c = createConversation(app.db, alice.id); | |
| 129 | if (!c.ok) throw new Error(c.error); | |
| 130 | // As the agent's `show` keeps it (the next pull): the widget's JSON in the conversation's | |
| 131 | // store. | |
| 132 | app.db | |
| 133 | .query("INSERT INTO conversation_card (id, via, user_id, n, tool, said, card, created_at) VALUES ('w0', ?1, ?2, 1, 'show', 'Checks per day', ?3, ?4)") | |
| 134 | .run(`conversation:${c.value.id}`, alice.id, JSON.stringify({ widget: { name: "checks", renderer: "chart", title: "Checks per day", data: checks } }), new Date().toISOString()); | |
| 135 | appendTurn(app.db, alice.id, c.value.id, { role: "agent", text: "This week:\n\n::show c1" }); | |
| 136 | const html = await page(alice, `/talk/${c.value.id}`); | |
| 137 | // Bare under the cards' hairline, never a box of its own. | |
| 138 | expect(html).toContain('class="card bare talk-card talk-widget"'); | |
| 139 | expect(html).toContain('data-widget="checks"'); | |
| 140 | // Where it came from, seen: the line no reply's Markdown carries. | |
| 141 | expect(html).toMatch(/<p class="talk-card-from small muted" id="wf-w0">From the forge: Checks per day · as of <time/); | |
| 142 | expect(html).toContain('class="wchart" data-kind="bar"'); | |
| 143 | // Another person never draws it, even naming the conversation. | |
| 144 | const theirs = await page(bob, `/talk/${c.value.id}`); | |
| 145 | expect(theirs).not.toContain("wchart"); | |
| 146 | }); | |
| 147 | ||
| 148 | test("the line under the title names the window, the time and a named repository", async () => { | |
| 149 | const c = createConversation(app.db, alice.id); | |
| 150 | if (!c.ok) throw new Error(c.error); | |
| 151 | app.db | |
| 152 | .query("INSERT INTO conversation_card (id, via, user_id, n, tool, said, card, created_at) VALUES (?1, ?2, ?3, 1, 'show', 'the last 7 days on alice/shop', ?4, ?5)") | |
| 153 | .run(`r1-${c.value.id}`, `conversation:${c.value.id}`, alice.id, JSON.stringify({ widget: { name: "checks", renderer: "chart", title: "Checks per day", days: 7, repo: "alice/shop", data: checks } }), new Date().toISOString()); | |
| 154 | appendTurn(app.db, alice.id, c.value.id, { role: "agent", text: "This week:\n\n::show c1" }); | |
| 155 | const html = await page(alice, `/talk/${c.value.id}`); | |
| 156 | expect(html).toMatch(/From the forge: the last 7 days on alice\/shop · 7 days · as of <time[^]*?<\/time\s*> · alice\/shop<\/p>/); | |
| 157 | }); | |
| 158 | ||
| 159 | test("a kept widget whose data is outside its renderer's shape is not drawn", async () => { | |
| 160 | const c = createConversation(app.db, alice.id); | |
| 161 | if (!c.ok) throw new Error(c.error); | |
| 162 | app.db.query("INSERT INTO conversation_card (id, via, user_id, n, tool, said, card, created_at) VALUES ('w1', ?1, ?2, 1, 'show', 'x', ?3, ?4)") | |
| 163 | .run(`conversation:${c.value.id}`, alice.id, JSON.stringify({ widget: { name: "x", renderer: "chart", title: "x", data: { kind: "pie" } } }), new Date().toISOString()); | |
| 164 | appendTurn(app.db, alice.id, c.value.id, { role: "agent", text: "::show c1" }); | |
| 165 | const html = await page(alice, `/talk/${c.value.id}`); | |
| 166 | expect(html).not.toContain('class="wchart"'); | |
| 167 | expect(html).toContain("Result not found."); | |
| 168 | }); | |
| 169 | }); |
test/widgets.test.ts added +309
| @@ -0,0 +1,309 @@ | ||
| 1 | /** | |
| 2 | * The widget registry and the forge's own widgets (#6009, src/widgets/): every widget named once, | |
| 3 | * its arguments and data held to their schemas, and a repository the person may not read is | |
| 4 | * `not_found`, the same as one that does not exist; each read names its index and walks it, with no | |
| 5 | * planner statistics and no temporary sort (the pattern of test/hot-reads-indexed.test.ts); each | |
| 6 | * counts what happened, day by day, only on repositories the person may read; and `show` in Talk | |
| 7 | * keeps what it drew under a handle the page draws. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { appendTurn, createConversation } from "../src/core/conversations.ts"; | |
| 16 | import type { Repo } from "../src/core/repos.ts"; | |
| 17 | import { createSession } from "../src/core/sessions.ts"; | |
| 18 | import { cardsOf, plainVoice, recordWidget, widgetLines } from "../src/core/talk_voice.ts"; | |
| 19 | import { createToken } from "../src/core/tokens.ts"; | |
| 20 | import { createUser, type User } from "../src/core/users.ts"; | |
| 21 | import { mintViaToken } from "../src/core/via_token.ts"; | |
| 22 | import { id } from "../src/kernel/id.ts"; | |
| 23 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 24 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 25 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 26 | import { settleApp } from "./helpers/tui.ts"; | |
| 27 | import { proveAll } from "./helpers/verified.ts"; | |
| 28 | import { DATA_SCHEMA, dayLabels, readWidget, searchWidgets, validate, WIDGETS } from "../src/widgets/registry.ts"; | |
| 29 | import type { ChartData } from "../src/widgets/registry.ts"; | |
| 30 | ||
| 31 | let dir: string; | |
| 32 | let app: App; | |
| 33 | let servers: Servers; | |
| 34 | let alice: User; | |
| 35 | let bob: User; | |
| 36 | let open: Repo; | |
| 37 | let closed: Repo; | |
| 38 | ||
| 39 | const DAY = 86_400_000; | |
| 40 | /** An instant `back` days before now, at noon UTC so it never crosses a day. */ | |
| 41 | const ago = (back: number) => new Date(Math.floor(Date.now() / DAY) * DAY - back * DAY + DAY / 2).toISOString(); | |
| 42 | ||
| 43 | const check = (repo: Repo, back: number, state: "ok" | "failed") => | |
| 44 | app.db.query("INSERT INTO run (id, repo_id, kind, env, state, created_at, started_at, finished_at) VALUES (?1, ?2, 'check', 'verify', ?3, ?4, ?4, ?4)").run(id(), repo.id, state, ago(back)); | |
| 45 | ||
| 46 | beforeAll(async () => { | |
| 47 | dir = await mkdtemp(join(tmpdir(), "forge-widget-reads-")); | |
| 48 | app = createApp({ dataDir: dir, port: 0 }); | |
| 49 | servers = await serve(app); | |
| 50 | const mk = async (username: string, first = false) => { | |
| 51 | const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first }); | |
| 52 | if (!u.ok) throw new Error(u.error); | |
| 53 | return u.value; | |
| 54 | }; | |
| 55 | alice = await mk("alice", true); | |
| 56 | bob = await mk("bob"); | |
| 57 | const made = async (name: string, visibility: "public" | "private") => { | |
| 58 | const r = await createRepo(app, alice, { name, visibility }); | |
| 59 | if (!r.ok) throw new Error(String(r.error)); | |
| 60 | return r.value; | |
| 61 | }; | |
| 62 | open = await made("open", "public"); | |
| 63 | closed = await made("closed", "private"); | |
| 64 | // Today: 3 passed, 1 failed on open; two days ago 2 passed; eight days ago (the week before) 1 | |
| 65 | // passed, 1 failed. | |
| 66 | for (const s of ["ok", "ok", "ok", "failed"] as const) check(open, 0, s); | |
| 67 | for (const s of ["ok", "ok"] as const) check(open, 2, s); | |
| 68 | for (const s of ["ok", "failed"] as const) check(open, 8, s); | |
| 69 | // The private repository's checks are counted for alice, never for bob. | |
| 70 | for (const s of ["failed", "failed"] as const) check(closed, 1, s); | |
| 71 | }, 30_000); | |
| 72 | afterAll(async () => { | |
| 73 | servers.stop(); | |
| 74 | app.close(); | |
| 75 | await rm(dir, { recursive: true, force: true }); | |
| 76 | }); | |
| 77 | ||
| 78 | /** The query plans of every statement `work` runs, as EXPLAIN QUERY PLAN says them. */ | |
| 79 | function plans(work: () => void): string[] { | |
| 80 | const db = app.db; | |
| 81 | const original = db.query.bind(db); | |
| 82 | const sqls: string[] = []; | |
| 83 | (db as unknown as { query: unknown }).query = (sql: string) => { | |
| 84 | sqls.push(sql); | |
| 85 | return original(sql); | |
| 86 | }; | |
| 87 | try { | |
| 88 | work(); | |
| 89 | } finally { | |
| 90 | (db as unknown as { query: unknown }).query = original; | |
| 91 | } | |
| 92 | return sqls | |
| 93 | .filter((s) => s.includes("INDEXED BY")) | |
| 94 | .flatMap((sql) => { | |
| 95 | const n = (sql.match(/\?\d+/g) ?? []).reduce((m, p) => Math.max(m, Number(p.slice(1))), 0); | |
| 96 | 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)]; | |
| 97 | }); | |
| 98 | } | |
| 99 | ||
| 100 | describe("every widget's reads walk a named index", () => { | |
| 101 | for (const w of WIDGETS) | |
| 102 | test(`${w.name}: its reads name their index, and none scans or sorts in a temporary tree`, () => { | |
| 103 | for (const args of [{}, { repo: "alice/open" }]) { | |
| 104 | const lines = plans(() => void w.read(app, alice, args)); | |
| 105 | const sql = lines.filter((l) => l.startsWith("-- ")); | |
| 106 | expect(sql.length).toBeGreaterThan(0); | |
| 107 | for (const line of lines.filter((l) => !l.startsWith("-- ") && !l.startsWith("SCAN json_each"))) { | |
| 108 | expect(line).not.toMatch(/^SCAN (?!.*USING (COVERING )?INDEX)/); | |
| 109 | expect(line).not.toContain("TEMP B-TREE"); | |
| 110 | } | |
| 111 | } | |
| 112 | }); | |
| 113 | }); | |
| 114 | ||
| 115 | const chart = (name: string, user: User | undefined, args: Record<string, unknown>) => { | |
| 116 | const r = readWidget(app, user, name, args); | |
| 117 | if (!r.ok) throw new Error(r.error); | |
| 118 | return { data: r.value.data as ChartData, says: r.value.says }; | |
| 119 | }; | |
| 120 | ||
| 121 | describe("checks", () => { | |
| 122 | test("counts each day's passed and failed checks, today last", () => { | |
| 123 | const { data, says } = chart("checks", alice, { repo: "alice/open", days: 7 }); | |
| 124 | expect(data.x).toEqual(dayLabels(7)); | |
| 125 | expect(data.series.map((s) => [s.name, s.tone, s.values])).toEqual([ | |
| 126 | ["Passed", "good", [0, 0, 0, 0, 2, 0, 3]], | |
| 127 | ["Failed", "bad", [0, 0, 0, 0, 0, 0, 1]], | |
| 128 | ]); | |
| 129 | expect(says).toBe(`6 checks finished in the last 7 days on alice/open: 5 passed and 1 failed (83% passed); the most failures were on ${dayLabels(1)[0]} (1).`); | |
| 130 | }); | |
| 131 | ||
| 132 | test("every repository the person works on, and only those", () => { | |
| 133 | expect(chart("checks", alice, { days: 7 }).data.series[1]!.values.reduce((a, b) => a + b, 0)).toBe(3); | |
| 134 | expect(chart("checks", bob, { days: 7 }).says).toBe("No checks finished in the last 7 days on every repository you work on."); | |
| 135 | expect(chart("checks", bob, { repo: "alice/open", days: 7 }).data.series[0]!.values.reduce((a, b) => a + b, 0)).toBe(5); | |
| 136 | }); | |
| 137 | ||
| 138 | }); | |
| 139 | ||
| 140 | describe("show in Talk", () => { | |
| 141 | test("keeps the widget under the next handle, says what it shows, and the page draws it", async () => { | |
| 142 | const c = createConversation(app.db, alice.id); | |
| 143 | if (!c.ok) throw new Error(c.error); | |
| 144 | const via = `conversation:${c.value.id}`; | |
| 145 | appendTurn(app.db, alice.id, c.value.id, { role: "person", text: "how are my checks doing this week?" }); | |
| 146 | const minted = mintViaToken(app.db, alice.id, via, "how are my checks doing this week?", new Date(Date.now() + 600_000).toISOString()); | |
| 147 | if (!minted.ok) throw new Error(minted.error); | |
| 148 | const res = await fetch(`${servers.url}/mcp`, { | |
| 149 | method: "POST", | |
| 150 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${minted.value.token}` }, | |
| 151 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "show", arguments: { widget: "checks", args: { repo: "alice/open", days: 7 } } } }), | |
| 152 | }); | |
| 153 | const text = ((await res.json()) as { result: { content: { text: string }[] } }).result.content.map((x) => x.text).join("\n"); | |
| 154 | expect(text).toContain("6 checks finished in the last 7 days on alice/open"); | |
| 155 | expect(text).toContain("c1"); | |
| 156 | const kept = cardsOf(app.db, alice.id, via, [1]).get(1); | |
| 157 | expect(kept?.widget?.name).toBe("checks"); | |
| 158 | expect(kept?.card).toBeUndefined(); | |
| 159 | appendTurn(app.db, alice.id, c.value.id, { role: "agent", text: "Mostly green.\n\n::show c1" }); | |
| 160 | const page = await (await fetch(`${servers.url}/talk/${c.value.id}`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } })).text(); | |
| 161 | expect(page).toContain('data-widget="checks"'); | |
| 162 | // The head says what it was read over, not its title again. | |
| 163 | expect(page).toContain("From the forge: the last 7 days on alice/open"); | |
| 164 | expect(page).toContain('class="wchart" data-kind="bar"'); | |
| 165 | }); | |
| 166 | ||
| 167 | test("bob's show of alice's private repository keeps nothing", async () => { | |
| 168 | const c = createConversation(app.db, bob.id); | |
| 169 | if (!c.ok) throw new Error(c.error); | |
| 170 | const via = `conversation:${c.value.id}`; | |
| 171 | appendTurn(app.db, bob.id, c.value.id, { role: "person", text: "show alice/closed checks" }); | |
| 172 | const minted = mintViaToken(app.db, bob.id, via, "show alice/closed checks", new Date(Date.now() + 600_000).toISOString()); | |
| 173 | if (!minted.ok) throw new Error(minted.error); | |
| 174 | const res = await fetch(`${servers.url}/mcp`, { | |
| 175 | method: "POST", | |
| 176 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${minted.value.token}` }, | |
| 177 | body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "show", arguments: { widget: "checks", args: { repo: "alice/closed" } } } }), | |
| 178 | }); | |
| 179 | expect(JSON.stringify(await res.json())).toContain("not_found"); | |
| 180 | expect(cardsOf(app.db, bob.id, via, [1]).size).toBe(0); | |
| 181 | }); | |
| 182 | }); | |
| 183 | ||
| 184 | describe("the terminal", () => { | |
| 185 | test("a chart prints a line of blocks a series on one scale, its total, and the days it spans", () => { | |
| 186 | const lines = widgetLines({ name: "checks", renderer: "chart", title: "Checks per day", data: { kind: "bar", x: ["2026-11-22", "2026-11-23", "2026-11-24"], unit: "checks", series: [{ name: "Passed", values: [0, 4, 8] }, { name: "Failed", values: [2, 0, 0] }] } }); | |
| 187 | expect(lines).toEqual(["Checks per day", " Passed ▁▅█ 12 checks", " Failed ▃▁▁ 2 checks", " Nov 22 to Nov 24"]); | |
| 188 | }); | |
| 189 | ||
| 190 | test("forge talk and the TUI print a placed widget through the one parser; the API carries it as plain", async () => { | |
| 191 | const c = createConversation(app.db, alice.id); | |
| 192 | if (!c.ok) throw new Error(c.error); | |
| 193 | const via = `conversation:${c.value.id}`; | |
| 194 | const read = readWidget(app, alice, "checks", { repo: "alice/open", days: 3 }); | |
| 195 | if (!read.ok) throw new Error(read.error); | |
| 196 | const kept = { name: "checks", renderer: read.value.widget.renderer, title: "Checks per day", data: read.value.data }; | |
| 197 | expect(recordWidget(app.db, via, alice.id, "Checks per day", kept)).toBe(1); | |
| 198 | appendTurn(app.db, alice.id, c.value.id, { role: "agent", text: "Mostly green.\n\n::show c1" }); | |
| 199 | appendTurn(app.db, alice.id, c.value.id, { role: "agent", text: "Nothing placed here." }); | |
| 200 | const res = await fetch(`${servers.url}/api/v1/conversation/turns?conversation=${c.value.id}`, { headers: { authorization: `Bearer ${createToken(app.db, alice.id, "t", "ro").token}` } }); | |
| 201 | const turns = ((await res.json()) as { turns: { text: string; plain?: string }[] }).turns; | |
| 202 | const placed = turns.find((t) => t.text.includes("::show"))!; | |
| 203 | expect(placed.plain).toBe(plainVoice(placed.text, cardsOf(app.db, alice.id, via, [1]))); | |
| 204 | expect(placed.plain).toContain("Checks per day\n Passed "); | |
| 205 | expect(placed.plain).toContain("From the forge: Checks per day"); | |
| 206 | expect(turns.find((t) => t.text === "Nothing placed here.")!.plain).toBeUndefined(); | |
| 207 | }); | |
| 208 | ||
| 209 | test("the Conversations screen prints the chart a conversation holds, and b finds no button on it", async () => { | |
| 210 | // A person of their own, so the conversation Enter opens is this one whatever ran before. | |
| 211 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" }); | |
| 212 | if (!made.ok) throw new Error(made.error); | |
| 213 | proveAll(app); | |
| 214 | const carol = made.value; | |
| 215 | const c = createConversation(app.db, carol.id); | |
| 216 | if (!c.ok) throw new Error(c.error); | |
| 217 | const data: ChartData = { kind: "bar", x: ["2026-11-22", "2026-11-23", "2026-11-24"], unit: "checks", series: [{ name: "Passed", values: [0, 4, 8] }, { name: "Failed", values: [2, 0, 0] }] }; | |
| 218 | expect(recordWidget(app.db, `conversation:${c.value.id}`, carol.id, "the last 3 days on alice/open", { name: "checks", renderer: "chart", title: "Checks per day", data, days: 3, repo: "alice/open" })).toBe(1); | |
| 219 | appendTurn(app.db, carol.id, c.value.id, { role: "agent", text: "Mostly green.\n\n::show c1" }); | |
| 220 | const drive = async (keys: string[]): Promise<string> => { | |
| 221 | const terminal = headlessTerminal(120, 30); | |
| 222 | const { app: tui } = createForgeApp(app, { sshUsername: carol.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: carol }, { terminal, exitHooks: false }); | |
| 223 | tui.start(); | |
| 224 | await settleApp(tui); | |
| 225 | for (const k of keys) { | |
| 226 | terminal.feed(k); | |
| 227 | await settleApp(tui); | |
| 228 | } | |
| 229 | const text = tui.screen.toText(); | |
| 230 | tui.stop?.(); | |
| 231 | return text; | |
| 232 | }; | |
| 233 | const text = await drive([":", "Conversations", "\r", "\r"]); | |
| 234 | expect(text).toContain("Mostly green."); | |
| 235 | expect(text).toContain("From the forge: the last 3 days on alice/open, as of "); | |
| 236 | expect(text).toContain("Checks per day"); | |
| 237 | expect(text).toContain("Passed ▁▅█ 12 checks"); | |
| 238 | expect(text).toContain("Failed ▃▁▁ 2 checks"); | |
| 239 | expect(text).toContain("Nov 22 to Nov 24"); | |
| 240 | expect(text).not.toContain("::show"); | |
| 241 | // A widget is a read with no buttons: b offers nothing, where a card's buttons would be listed. | |
| 242 | expect(await drive([":", "Conversations", "\r", "\r", "b"])).toContain("No result here has a button to press now."); | |
| 243 | }); | |
| 244 | }); | |
| 245 | ||
| 246 | test("a window of days ends today, oldest first", () => { | |
| 247 | expect(dayLabels(3, Date.parse("2026-11-24T12:00:00Z"))).toEqual(["2026-11-22", "2026-11-23", "2026-11-24"]); | |
| 248 | }); | |
| 249 | ||
| 250 | const files = WIDGETS.map((w) => w.name); | |
| 251 | ||
| 252 | describe("the registry", () => { | |
| 253 | test("names each widget once, sorted, with an object schema of its arguments and one line for the agent", () => { | |
| 254 | expect(files).toEqual([...new Set(files)].sort()); | |
| 255 | for (const w of WIDGETS) { | |
| 256 | expect(w.name).toMatch(/^[a-z][a-z_]*$/); | |
| 257 | expect(w.title.trim().length).toBeGreaterThan(0); | |
| 258 | expect(w.description).not.toContain("\n"); | |
| 259 | expect(w.description.length).toBeLessThanOrEqual(160); | |
| 260 | expect(Object.keys(DATA_SCHEMA)).toContain(w.renderer); | |
| 261 | expect(w.args.type).toBe("object"); | |
| 262 | expect(w.args.additionalProperties).toBe(false); | |
| 263 | } | |
| 264 | }); | |
| 265 | ||
| 266 | test("search finds by every word of the query, and an empty query lists them all", () => { | |
| 267 | expect(searchWidgets("").length).toBe(WIDGETS.length); | |
| 268 | expect(searchWidgets("no such widget anywhere zzz")).toEqual([]); | |
| 269 | }); | |
| 270 | }); | |
| 271 | ||
| 272 | describe("each widget answers in its own shape, and only what the person may read", () => { | |
| 273 | for (const name of files) { | |
| 274 | test(`${name}: its data fits its renderer's schema, for a repository and for every one the person works on`, () => { | |
| 275 | for (const args of [{ repo: "alice/open", days: 7 }, { days: 30 }, {}]) { | |
| 276 | const read = readWidget(app, alice, name, args); | |
| 277 | expect(read.ok).toBe(true); | |
| 278 | if (!read.ok) continue; | |
| 279 | expect(validate(DATA_SCHEMA[read.value.widget.renderer], read.value.data)).toBeUndefined(); | |
| 280 | expect(read.value.says.length).toBeGreaterThan(0); | |
| 281 | } | |
| 282 | }); | |
| 283 | ||
| 284 | test(`${name}: a repository the person may not read is not found, the same as one that does not exist`, () => { | |
| 285 | expect(readWidget(app, bob, name, { repo: "alice/closed" })).toEqual({ ok: false, error: "not_found" }); | |
| 286 | expect(readWidget(app, bob, name, { repo: "alice/nothing" })).toEqual({ ok: false, error: "not_found" }); | |
| 287 | expect(readWidget(app, undefined, name, { repo: "alice/closed" })).toEqual({ ok: false, error: "not_found" }); | |
| 288 | }); | |
| 289 | ||
| 290 | test(`${name}: arguments outside its schema are refused`, () => { | |
| 291 | expect(readWidget(app, alice, name, { repo: "alice/open", nonsense: 1 })).toEqual({ ok: false, error: "invalid" }); | |
| 292 | expect(readWidget(app, alice, name, { days: 1000 })).toEqual({ ok: false, error: "invalid" }); | |
| 293 | }); | |
| 294 | } | |
| 295 | ||
| 296 | test("an unknown widget is not found", () => { | |
| 297 | expect(readWidget(app, alice, "no_such_widget", {})).toEqual({ ok: false, error: "not_found" }); | |
| 298 | }); | |
| 299 | }); | |
| 300 | ||
| 301 | describe("the schema check", () => { | |
| 302 | test("says where data breaks its renderer's shape", () => { | |
| 303 | expect(validate(DATA_SCHEMA.chart, { kind: "line", x: ["a"], series: [{ name: "s", values: [1] }] })).toBeUndefined(); | |
| 304 | expect(validate(DATA_SCHEMA.chart, { kind: "pie", x: [], series: [{ name: "s", values: [] }] })).toContain("$.kind"); | |
| 305 | expect(validate(DATA_SCHEMA.chart, { kind: "line", x: [], series: [] })).toContain("$.series"); | |
| 306 | expect(validate(DATA_SCHEMA.chart, { kind: "bar", x: ["a"], series: [{ name: "s", values: [Number.NaN] }] })).toContain("$.series[0].values[0]"); | |
| 307 | expect(validate(DATA_SCHEMA.chart, { kind: "bar", x: [], series: [{ name: "s", values: [] }], html: "<b>" })).toContain("not a field"); | |
| 308 | }); | |
| 309 | }); |
new above
offline