Public: anyone can read this; the crew can change it.
Talk's agent asks, plans and says what it knows in three fixed shapes, drawn on the page and in the terminal #16252
Check · Review · Land · Live done — Landed and live in production.
talk/04-blocks → main 1 commit
11 files
changed +982
−63
docs/design/areas/talk.md +4 −1
| @@ -68,11 +68,14 @@ On a phone the conversations list is its own view (`?chats=1`), reached from the | ||
| 68 | 68 | |
| 69 | 69 | `.talk-keys` is the keyboard help list (#15816): a bordered block above the about line, hidden until `?` is pressed, drawn from `TALK_KEYS`. |
| 70 | 70 | |
| 71 | Talk's voice (`src/web/talk_parts.ts`, docs/features/talk.md, Shown results): the forge's own data, drawn from `card` / `listCard` (`extra: "bare"`, so no box) and `row()`, so the only new classes are: | |
| 71 | Talk's voice (`src/web/talk_parts.ts`, docs/features/talk-voice.md): the forge's own data and the agent's three shapes, drawn from `card` / `listCard` (`extra: "bare"`, so no box) and `row()`, so the only new classes are: | |
| 72 | 72 | |
| 73 | 73 | - `.talk-card` — a shown result: the forge's card, set apart from the agent's words by a hairline on its start side; a wide card scrolls inside itself, never the page. |
| 74 | 74 | - `.talk-card-from` — the quiet line under a card: the call in plain words and "as of" its time. |
| 75 | 75 | - `.talk-card-missing` — "Result not found." where a handle names no card of this conversation (markup only). |
| 76 | - `.talk-choices` — the agent's question and one button per option (a starter form, so it works with the script off); `.talk-choices-options` is their row, which wraps where there is room and stacks, each the reply's width, below 40rem. None is primary. | |
| 77 | - `.talk-plan` — the agent's plan, a plain row per step at regular weight: its icon, then the step; a done or skipped step is muted. The state is in words in the row's name (`.sr-only`), and shown as `.talk-plan-state` only for a skipped step, so it never rests on colour. | |
| 78 | - `.talk-known` — Known, Suspected, Unknown, each a bare list at regular weight under a small muted label; an item's source, a result it names, follows its words as `.talk-known-src` (the result's title: a link where the reply places it, quiet text otherwise); an item that names none is its words alone. | |
| 76 | 79 | |
| 77 | 80 | ## #15734: one scroller, one column |
| 78 | 81 |
docs/features/talk-voice.md added +45
| @@ -0,0 +1,45 @@ | ||
| 1 | --- | |
| 2 | topic: Tell the crew | |
| 3 | row: Talk replies show the forge's own results as cards, and ask, plan and say what is known in three fixed shapes | |
| 4 | --- | |
| 5 | # Talk's voice: shown results and agent blocks | |
| 6 | ||
| 7 | A reply from the forge's agent on /talk is Markdown with two additions, drawn so the forge's data and the agent's words look different. | |
| 8 | ||
| 9 | ## Shown results | |
| 10 | ||
| 11 | When a tool answers the forge's agent in a conversation and the answer has a card (`cardFor`, `src/web/studio/cards.ts`), the forge keeps the card for that conversation (`conversation_card`, `src/core/talk_voice.ts`) and adds one text block after the answer, outside the fenced data: | |
| 12 | ||
| 13 | ||
| 14 | Shown result c7: a line `::show c7` in your reply draws this result for the person. | |
| 15 | ||
| 16 | ||
| 17 | The agent never receives the card itself. A line in its reply that is exactly `::show c7`, on its own line and outside a code fence, is drawn on the page as the kept card: its title and status, its rows, and a quiet line under it, "From the forge: <the call in plain words> · as of 14:02 UTC". A handle that names no card kept for this conversation and this person draws "Result not found." and nothing else. Answers to any other caller are unchanged. | |
| 18 | ||
| 19 | - Handles count up per conversation: `c1`, `c2`, and so on. The newest 200 cards of a conversation are kept, and they go when the conversation goes. A card over 16,000 characters of JSON, or a card with no rows, is not kept and its answer carries no handle. | |
| 20 | - A kept card is what the page draws: its title, status and rows. It has no buttons. | |
| 21 | - A row's link is drawn as a link only when it is a rooted path (`/owner/name/issues/3`) or an address on the page's own origin; anything else (another site, `//host`, a scheme such as `javascript:`) is drawn as text. Every title, status, label and value is escaped. | |
| 22 | - A kept card is a record of what the forge answered then, shown with its time. It is not read again, so it can outlive the person's access to what it shows, exactly as the reply's own words do. | |
| 23 | ||
| 24 | ## Agent blocks | |
| 25 | ||
| 26 | 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. | |
| 27 | ||
| 28 | ||
| 29 | ```forge | |
| 30 | choices | |
| 31 | {"question": "Which app should I deploy?", "options": ["alice/shop", "alice/blog"]} | |
| 32 | ||
| 33 | ||
| 34 | ||
| 35 | - `choices`: `question` (up to 300 characters) and `options`, 2 to 4 strings of up to 120 characters that still differ once cleaned. Drawn as the question, at the reply's own weight, and one button per option (none primary; they sit in a row where there is room and stack the width of the reply on a phone); a press sends that option, as cleaned and as shown, as the person's next message (a starter form, so it also works with the script off). It is the person's own message: the fence treats it as their words, the same as if they had typed it, so an option is only ever what the person read on the button. Only the last reply's choices are buttons: once the person has said something after it, they are plain text, and with the script on a press stills every choice button at once and puts the cursor back in the message box. | |
| 36 | - `plan`: `steps`, 1 to 12 of `{"text": "...", "state": "todo" | "doing" | "done" | "skipped"}`, text up to 200 characters. Drawn as plain rows at the reply's own weight, each starting with its state's icon; a done or skipped step is muted. The state is in words in each row's name for a screen reader, and on the page for a skipped step, so it never rests on an icon or a colour alone. | |
| 37 | - `known`: `known`, `suspected` and `unknown`, each a list of up to 8 items of up to 300 characters, with at least one item in all. Items are inline Markdown (code, emphasis, http(s) links). Drawn as three quiet groups, each under a small muted label, items at the reply's own weight; an empty one is left out. An Unknown item names what would settle it in its own words, or as `{"item": "...", "settle": "..."}`, drawn as one row ("...; to settle: ..."), so the two read together. A `::show c7` inside an item is its source: the result's title, linked to the card where this reply places it, and quiet text when the reply does not place it; a handle that names nothing kept draws nothing. No item is ever marked as lacking a source. | |
| 38 | ||
| 39 | ## Other doors | |
| 40 | ||
| 41 | - The terminal (Conversations, open one: `src/tui/screens/talk_chats.ts`) prints a placed card as where it came from, its title and status, and a `label: value` line per row, and each block as a plain list. `GET /api/v1/conversation/turns` carries a reply printed that way as `plain` beside its raw text, and `forge talk` prints it. | |
| 42 | - The Markdown download (`src/core/conversation_markdown.ts`) keeps the reply's raw text, `::show` lines and `forge` blocks included. | |
| 43 | - A README or any other Markdown on the forge is drawn as before: a `::show` line there is text and a `forge` block a code block. | |
| 44 | ||
| 45 | The parsing is one module for every door, `src/core/talk_voice.ts`; the page's drawing is `src/web/talk_parts.ts`, called once from `turnHtml` in `src/web/pages/talk.ts`. Proof: `test/talk-shown.test.ts` and `test/talk-blocks.test.ts`. |
docs/features/talk.md +1 −20
| @@ -134,7 +134,7 @@ A reply is drawn by the README renderer and then, for Talk alone, by `linkTalk` | ||
| 134 | 134 | |
| 135 | 135 | 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. |
| 136 | 136 | |
| 137 | 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 12,000 B, the script under 26,700 B, and a page with a code reply under 42,000 B. | |
| 137 | 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 12,000 B, the script under 26,900 B, and a page with a code reply under 42,000 B. | |
| 138 | 138 | |
| 139 | 139 | ## Following |
| 140 | 140 | |
| @@ -169,25 +169,6 @@ An empty conversation offers Build an app among its starters (#15734); it opens | ||
| 169 | 169 | - **Terminal:** `:` then **Build an app**. `n` says what to build (`t` chooses the template), Enter opens a build and lists its versions newest first, Enter again shows the files that version changed, `R` restores the chosen version, `P` publishes, `r` reloads. The screen calls the same `actions/build.ts` functions as the page, so it is gated the same way (your own conversation, a writer of the repository) and what it does is what the page shows on its next read. |
| 170 | 170 | - Proof: `test/talk-build.test.ts` runs prompt, repository, v1, v2, restore v1 and publish against a scratch forge; `test/tui-talk-build.test.ts` does the same from the terminal. |
| 171 | 171 | |
| 172 | ## Shown results (#10262) | |
| 173 | ||
| 174 | When a tool answers the forge's agent in a conversation and the answer has a card (`cardFor`, `src/web/studio/cards.ts`), the forge keeps the card for that conversation (`conversation_card`, `src/core/talk_voice.ts`) and adds one text block after the answer, outside the fenced data: | |
| 175 | ||
| 176 | ||
| 177 | Shown result c7: a line `::show c7` in your reply draws this result for the person. | |
| 178 | ||
| 179 | ||
| 180 | The agent never receives the card itself. A line in its reply that is exactly `::show c7`, on its own line and outside a code fence, is drawn on the page as the kept card: its title and status, its rows, and a quiet line under it, "From the forge: <the call in plain words> · as of 14:02 UTC". A handle that names no card kept for this conversation and this person draws "Result not found." and nothing else. Answers to any other caller are unchanged. | |
| 181 | ||
| 182 | - Handles count up per conversation: `c1`, `c2`, and so on. The newest 200 cards of a conversation are kept, and they go when the conversation goes. A card over 16,000 characters of JSON, or a card with no rows, is not kept and its answer carries no handle. | |
| 183 | - A kept card is what the page draws: its title, status and rows. It has no buttons. | |
| 184 | - A row's link is drawn as a link only when it is a rooted path (`/owner/name/issues/3`) or an address on the page's own origin; anything else (another site, `//host`, a scheme such as `javascript:`) is drawn as text. Every title, status, label and value is escaped. | |
| 185 | - A kept card is a record of what the forge answered then, shown with its time. It is not read again, so it can outlive the person's access to what it shows, exactly as the reply's own words do. | |
| 186 | - **Terminal:** the Conversations screen (`src/tui/screens/talk_chats.ts`) prints a placed card as where it came from, its title and status, and a `label: value` line per row. `forge talk` prints the same: `GET /api/v1/conversation/turns` carries a reply that places a card printed this way as `plain`, beside its raw text. The Markdown download keeps the raw `::show` lines. | |
| 187 | - A README or any other Markdown on the forge is drawn as before: a `::show` line there is text. | |
| 188 | ||
| 189 | The parsing is one module for every door, `src/core/talk_voice.ts`; the page's drawing is `src/web/talk_parts.ts`, called once from `turnHtml` in `src/web/pages/talk.ts`. Proof: `test/talk-shown.test.ts`. | |
| 190 | ||
| 191 | 172 | ## Receipts |
| 192 | 173 | |
| 193 | 174 | After you confirm a held action, the thread shows a receipt: the verb, the object, and a link to the page it changed. For `close` (close/reopen) and `assign` (assign/unassign) it also draws an Undo form (`POST /talk/undo/:turn`, same-origin, your own session) that does the inverse and writes its own receipt. It refuses, and says so, when the object has changed since (someone else's later change is never undone) or when it was already undone. Every other confirmed call that names a repository gets a receipt with no Undo. A failed undo changes nothing and can be tried again; a second tap while one runs is refused. |
src/core/talk_voice.ts +165 −15
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | /** |
| 2 | * Talk's voice (docs/features/talk.md, Shown results), one module for every door: the shown results | |
| 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 | 5 | * Shown results: the cards the forge's MCP drew for a conversation's own agent (a via token), |
| @@ -8,15 +8,22 @@ | ||
| 8 | 8 | * newest `CARDS_KEPT` of a conversation are kept (older ones go on every insert), and a card whose |
| 9 | 9 | * JSON is over `CARD_CHARS_MAX` is not kept at all. Every read checks `userId`. |
| 10 | 10 | * |
| 11 | * The vocabulary: a reply is ordinary Markdown in which a line that is exactly `::show c<n>`, | |
| 12 | * outside a code fence, places a shown result. `voiceParts` cuts a reply into its parts; the page | |
| 13 | * draws them (`web/talk_parts.ts`), the terminal prints them (`plainVoice`). A reply with no such | |
| 14 | * line is one text part, so it is drawn exactly as before. Plain data in and out. | |
| 11 | * The vocabulary: a reply is ordinary Markdown with two additions. | |
| 12 | * | |
| 13 | * - A line that is exactly `::show c<n>`, outside a code fence, places a shown result. | |
| 14 | * - A fenced block whose info string is `forge` and whose first line names a kind (`choices`, | |
| 15 | * `plan` or `known`); the rest of the block is JSON in that kind's one shape. A block that does | |
| 16 | * not validate stays an ordinary code block. | |
| 17 | * | |
| 18 | * `voiceParts` cuts a reply into those parts; the page draws them (`web/talk_parts.ts`), the | |
| 19 | * terminal prints them (`plainVoice`). A reply with neither addition is one text part, so it is | |
| 20 | * drawn exactly as before. Plain data in and out. | |
| 15 | 21 | */ |
| 16 | 22 | |
| 17 | 23 | import type { Database } from "bun:sqlite"; |
| 18 | 24 | import type { Card, CardRow } from "../web/studio/cards.ts"; |
| 19 | 25 | import { id } from "../kernel/id.ts"; |
| 26 | import { unsaid } from "../crew/conversation_ask.ts"; | |
| 20 | 27 | |
| 21 | 28 | /** The newest cards a conversation keeps. */ |
| 22 | 29 | export const CARDS_KEPT = 200; |
| @@ -198,26 +205,116 @@ export function cardsOf( | ||
| 198 | 205 | return out; |
| 199 | 206 | } |
| 200 | 207 | |
| 208 | export type PlanState = "todo" | "doing" | "done" | "skipped"; | |
| 209 | export const PLAN_STATES: readonly PlanState[] = ["todo", "doing", "done", "skipped"]; | |
| 210 | ||
| 201 | 211 | export type Part = |
| 202 | 212 | | { readonly kind: "text"; readonly text: string } |
| 203 | 213 | | { readonly kind: "show"; readonly n: number } |
| 204 | 214 | | { readonly kind: "fold"; readonly summary: string } |
| 205 | | { readonly kind: "unfold" }; | |
| 215 | | { readonly kind: "unfold" } | |
| 216 | | { readonly kind: "choices"; readonly question: string; readonly options: readonly string[] } | |
| 217 | | { readonly kind: "plan"; readonly steps: readonly { readonly text: string; readonly state: PlanState }[] } | |
| 218 | | { readonly kind: "known"; readonly known: readonly string[]; readonly suspected: readonly string[]; readonly unknown: readonly string[] }; | |
| 219 | ||
| 220 | /** The limits a block is held to; past any of them it is drawn as code. */ | |
| 221 | export const VOICE_LIMITS = { | |
| 222 | question: 300, | |
| 223 | options: [2, 4], | |
| 224 | option: 120, | |
| 225 | steps: [1, 12], | |
| 226 | step: 200, | |
| 227 | items: 8, | |
| 228 | item: 300, | |
| 229 | json: 8000, | |
| 230 | } as const; | |
| 206 | 231 | |
| 207 | 232 | const SHOW = /^::show c([1-9]\d{0,8})[ \t]*$/; |
| 233 | /** | |
| 234 | * The info strings a block may open with: `forge` (its kind on the first line, then the JSON), | |
| 235 | * `forge plan`, or the bare kind (`plan`); with a kind named, the whole body is the JSON. Lenient | |
| 236 | * about the fence, strict about the body: a fence so labelled is a block only when its body is | |
| 237 | * exactly that kind's shape, and any other is the code block it always was. | |
| 238 | */ | |
| 239 | export const BLOCK_INFO = /^(?:forge(?:[ \t]+(choices|plan|known))?|(choices|plan|known))[ \t]*$/; | |
| 240 | const FORGE_FENCE = /^(`{3,})(.*)$/; | |
| 208 | 241 | const OPEN_FENCE = /^( *)(`{3,})/; |
| 209 | 242 | const CLOSE_FENCE = /^( *)(`{3,})\s*$/; |
| 210 | 243 | /** The Markdown renderer's fold (`web/markdown.ts`): its own line, a short plain title. */ |
| 211 | const FOLD = /^<details><summary>([^<>&"'`]{1,80})<\/summary>$/; | |
| 244 | const FOLD = /^<details><summary>([^<>&"`]{1,80})<\/summary>$/; | |
| 212 | 245 | const UNFOLD = "</details>"; |
| 246 | /** One line of text: no line break or other control character. */ | |
| 247 | const ONE_LINE = /^[^\p{Cc}\u2028\u2029]+$/u; | |
| 248 | ||
| 249 | const only = (o: Obj, keys: readonly string[]): boolean => Object.keys(o).every((k) => keys.includes(k)); | |
| 250 | const line = (v: unknown, max: number): v is string => typeof v === "string" && v.trim() !== "" && v.length <= max && ONE_LINE.test(v); | |
| 213 | 251 | /** |
| 214 | * A reply cut into its parts, in order. Text between placed results stays Markdown; a fold that | |
| 215 | * holds one is split into its open and close, so the fold still holds it. | |
| 252 | * One line as it arrived, cleaned as a confirm sentence cleans an argument (`unsaid`); undefined | |
| 253 | * when nothing is left. | |
| 254 | */ | |
| 255 | const said = (v: unknown, max: number): string | undefined => (line(v, max) ? unsaid(v) || undefined : undefined); | |
| 256 | /** A list of such lines, `min` to `max` of them; undefined when any one fails. */ | |
| 257 | const saidAll = (v: unknown, min: number, max: number, chars: number): string[] | undefined => { | |
| 258 | if (!Array.isArray(v) || v.length < min || v.length > max) return undefined; | |
| 259 | const out = v.map((x) => said(x, chars)); | |
| 260 | return out.every((x) => x !== undefined) ? (out as string[]) : undefined; | |
| 261 | }; | |
| 262 | ||
| 263 | /** A `forge` block's body as its part, or undefined when it does not validate. */ | |
| 264 | export function blockOf(body: readonly string[]): Part | undefined { | |
| 265 | const [kind, ...rest] = body; | |
| 266 | const json = rest.join("\n"); | |
| 267 | if (json.length > VOICE_LIMITS.json) return undefined; | |
| 268 | let v: unknown; | |
| 269 | try { | |
| 270 | v = JSON.parse(json); | |
| 271 | } catch { | |
| 272 | return undefined; | |
| 273 | } | |
| 274 | if (!isObj(v)) return undefined; | |
| 275 | const L = VOICE_LIMITS; | |
| 276 | switch (kind?.trim()) { | |
| 277 | case "choices": { | |
| 278 | if (!only(v, ["question", "options"])) return undefined; | |
| 279 | const question = said(v["question"], L.question); | |
| 280 | const options = saidAll(v["options"], L.options[0], L.options[1], L.option); | |
| 281 | // Two options that read the same once cleaned are one option, and the block is refused. | |
| 282 | if (question === undefined || options === undefined || new Set(options).size !== options.length) return undefined; | |
| 283 | return { kind: "choices", question, options }; | |
| 284 | } | |
| 285 | case "plan": { | |
| 286 | if (!only(v, ["steps"]) || !Array.isArray(v["steps"])) return undefined; | |
| 287 | const steps = v["steps"]; | |
| 288 | if (steps.length < L.steps[0] || steps.length > L.steps[1]) return undefined; | |
| 289 | const made = steps.map((s) => (isObj(s) && only(s, ["text", "state"]) && PLAN_STATES.includes(s["state"] as PlanState) ? { text: said(s["text"], L.step), state: s["state"] as PlanState } : undefined)); | |
| 290 | return made.every((s) => s !== undefined && s.text !== undefined) ? { kind: "plan", steps: made as { text: string; state: PlanState }[] } : undefined; | |
| 291 | } | |
| 292 | case "known": { | |
| 293 | if (!only(v, ["known", "suspected", "unknown"])) return undefined; | |
| 294 | // An item is a line; an unknown one may also come as `{ item, settle }` (what would settle | |
| 295 | // it), the shape the brief asks for, kept as one line so the two read together. | |
| 296 | const one = (x: unknown): unknown => | |
| 297 | isObj(x) && only(x, ["item", "settle"]) && typeof x["item"] === "string" ? (typeof x["settle"] === "string" && x["settle"].trim() !== "" ? `${x["item"]}; to settle: ${x["settle"]}` : x["item"]) : x; | |
| 298 | const list = (k: string): string[] | undefined => (v[k] === undefined ? [] : saidAll(Array.isArray(v[k]) ? (v[k] as unknown[]).map(one) : v[k], 0, L.items, L.item)); | |
| 299 | const known = list("known"); | |
| 300 | const suspected = list("suspected"); | |
| 301 | const unknown = list("unknown"); | |
| 302 | if (known === undefined || suspected === undefined || unknown === undefined || known.length + suspected.length + unknown.length === 0) return undefined; | |
| 303 | return { kind: "known", known, suspected, unknown }; | |
| 304 | } | |
| 305 | default: | |
| 306 | return undefined; | |
| 307 | } | |
| 308 | } | |
| 309 | ||
| 310 | /** | |
| 311 | * A reply cut into its parts, in order. Text between the additions stays Markdown; a fold that | |
| 312 | * holds an addition is split into its open and close, so the fold still holds it. | |
| 216 | 313 | */ |
| 217 | 314 | export function voiceParts(text: string): Part[] { |
| 218 | 315 | const src = text.replaceAll("\r\n", "\n").split("\n"); |
| 219 | // Most replies place nothing: one text part, drawn as it always was. | |
| 220 | if (!src.some((l) => SHOW.test(l))) return [{ kind: "text", text }]; | |
| 316 | // Most replies hold neither addition: one text part, drawn as it always was. | |
| 317 | if (!src.some((l) => SHOW.test(l) || BLOCK_INFO.test(FORGE_FENCE.exec(l)?.[2] ?? "-"))) return [{ kind: "text", text }]; | |
| 221 | 318 | const parts: Part[] = []; |
| 222 | 319 | let buf: string[] = []; |
| 223 | 320 | const flush = (): void => { |
| @@ -227,6 +324,31 @@ export function voiceParts(text: string): Part[] { | ||
| 227 | 324 | let folded = false; |
| 228 | 325 | for (let i = 0; i < src.length; i++) { |
| 229 | 326 | const l = src[i]!; |
| 327 | const fenced = FORGE_FENCE.exec(l); | |
| 328 | const info = fenced === null ? null : BLOCK_INFO.exec(fenced[2]!); | |
| 329 | const forge = info === null ? null : fenced; | |
| 330 | if (forge !== null && info !== null) { | |
| 331 | const width = forge[1]!.length; | |
| 332 | const body: string[] = []; | |
| 333 | let j = i + 1; | |
| 334 | let closed = false; | |
| 335 | for (; j < src.length; j++) { | |
| 336 | const c = CLOSE_FENCE.exec(src[j]!); | |
| 337 | if (c !== null && c[1]!.length <= 3 && c[2]!.length >= width) { | |
| 338 | closed = true; | |
| 339 | break; | |
| 340 | } | |
| 341 | body.push(src[j]!); | |
| 342 | } | |
| 343 | const named = info[1] ?? info[2]; | |
| 344 | const block = closed ? blockOf(named === undefined ? body : [named, ...body]) : undefined; | |
| 345 | if (block !== undefined) { | |
| 346 | flush(); | |
| 347 | parts.push(block); | |
| 348 | } else buf.push(...src.slice(i, closed ? j + 1 : j)); | |
| 349 | i = j; | |
| 350 | continue; | |
| 351 | } | |
| 230 | 352 | const open = OPEN_FENCE.exec(l); |
| 231 | 353 | if (open !== null) { |
| 232 | 354 | // Any other fence is text, and nothing inside it is an addition. |
| @@ -265,16 +387,31 @@ export function voiceParts(text: string): Part[] { | ||
| 265 | 387 | } |
| 266 | 388 | flush(); |
| 267 | 389 | if (folded) parts.push({ kind: "unfold" }); |
| 268 | // Nothing placed outside a fence: the reply is drawn whole, as it was. | |
| 269 | return parts.some((p) => p.kind === "show") ? parts : [{ kind: "text", text }]; | |
| 390 | // Nothing validated: the reply is drawn whole, as it was. | |
| 391 | return parts.some((p) => p.kind !== "text" && p.kind !== "fold" && p.kind !== "unfold") ? parts : [{ kind: "text", text }]; | |
| 270 | 392 | } |
| 271 | 393 | |
| 272 | 394 | /** The handles a reply places, each once. */ |
| 273 | export const shownIn = (parts: readonly Part[]): number[] => [...new Set(parts.flatMap((p) => (p.kind === "show" ? [p.n] : [])))]; | |
| 395 | export const shownIn = (parts: readonly Part[]): number[] => [ | |
| 396 | ...new Set( | |
| 397 | parts.flatMap((p) => | |
| 398 | p.kind === "show" | |
| 399 | ? [p.n] | |
| 400 | : // A Known item that names a result is read with the cards, so it can say which one. | |
| 401 | p.kind === "known" | |
| 402 | ? [...p.known, ...p.suspected, ...p.unknown].flatMap((x) => [...x.matchAll(/::show c([1-9]\d{0,8})/g)].map((m) => Number(m[1]))) | |
| 403 | : [], | |
| 404 | ), | |
| 405 | ), | |
| 406 | ]; | |
| 274 | 407 | |
| 275 | 408 | /** What the page says where a handle names no kept card of this conversation. */ |
| 276 | 409 | export const NOT_FOUND_WORDS = "Result not found."; |
| 277 | 410 | |
| 411 | const STATE_WORD: Readonly<Record<PlanState, string>> = { todo: "to do", doing: "doing", done: "done", skipped: "skipped" }; | |
| 412 | /** A plan step's state as its word on the page and in the terminal. */ | |
| 413 | export const planWord = (s: PlanState): string => STATE_WORD[s]; | |
| 414 | ||
| 278 | 415 | /** |
| 279 | 416 | * The person's kept cards that these replies of their conversation place, by number: one |
| 280 | 417 | * statement whatever the number of replies (`test/talk-shown.test.ts` counts it). |
| @@ -305,7 +442,8 @@ export function cardLines(card: Card): string[] { | ||
| 305 | 442 | |
| 306 | 443 | /** |
| 307 | 444 | * A reply as the terminal prints it: a placed result as where it came from and its card's lines |
| 308 | * (or the not-found words). `cards` are this conversation's kept cards by number (`cardsPlaced`). | |
| 445 | * (or the not-found words), each block as a plain list. `cards` are this conversation's kept cards | |
| 446 | * by number (`cardsPlaced`). | |
| 309 | 447 | */ |
| 310 | 448 | export function plainVoice(text: string, cards: ReadonlyMap<number, ShownCard>): string { |
| 311 | 449 | const parts = voiceParts(text); |
| @@ -324,6 +462,18 @@ export function plainVoice(text: string, cards: ReadonlyMap<number, ShownCard>): | ||
| 324 | 462 | return [`${p.summary}:`]; |
| 325 | 463 | case "unfold": |
| 326 | 464 | return []; |
| 465 | case "choices": | |
| 466 | return [p.question, ...p.options.map((o, i) => ` ${i + 1}. ${o}`)]; | |
| 467 | case "plan": | |
| 468 | return ["Plan:", ...p.steps.map((s, i) => ` ${i + 1}. [${planWord(s.state)}] ${s.text}`)]; | |
| 469 | case "known": | |
| 470 | return ( | |
| 471 | [ | |
| 472 | ["Known", p.known], | |
| 473 | ["Suspected", p.suspected], | |
| 474 | ["Unknown", p.unknown], | |
| 475 | ] as const | |
| 476 | ).flatMap(([label, items]) => (items.length === 0 ? [] : [`${label}:`, ...items.map((x) => ` - ${x}`)])); | |
| 327 | 477 | } |
| 328 | 478 | }) |
| 329 | 479 | .join("\n"); |
src/crew/conversation_ask.ts +8
| @@ -24,6 +24,14 @@ type Form = (a: Args) => string; | ||
| 24 | 24 | */ |
| 25 | 25 | const UNSAID = /[\p{Cc}\p{Cf}\u2028\u2029`]+/gu; |
| 26 | 26 | |
| 27 | /** | |
| 28 | * A string as a person reads it: every control, format and line-breaking character (a zero-width | |
| 29 | * space, a direction override) made a space, and runs of space made one. Talk's blocks clean their | |
| 30 | * words with it (`core/talk_voice.ts`), so what is shown is what is sent; a block keeps its | |
| 31 | * backticks, which are inline code there. | |
| 32 | */ | |
| 33 | export const unsaid = (v: string): string => v.replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ").replace(/\s+/g, " ").trim(); | |
| 34 | ||
| 27 | 35 | /** Most characters of a value the sentence says back; past it the value is cut. */ |
| 28 | 36 | export const SAID_MAX = 60; |
| 29 | 37 |
src/web/markdown.ts +20 −7
| @@ -252,6 +252,14 @@ export function markdownTasks(rendered: Html): { done: number; total: number } | | ||
| 252 | 252 | return taskCounts.get(rendered); |
| 253 | 253 | } |
| 254 | 254 | |
| 255 | /** | |
| 256 | * One line of text with the inline marks alone (code, emphasis, http(s) links), escaped first like | |
| 257 | * every render: what a list item or a label holds, never a block. | |
| 258 | */ | |
| 259 | export function renderInline(source: string): Html { | |
| 260 | return raw(inline(escapeHtml(source.replace(/[\r\n]+/g, " ")))); | |
| 261 | } | |
| 262 | ||
| 255 | 263 | export function renderMarkdown(source: string, repo?: MarkdownRepo): Html { |
| 256 | 264 | if (source.length > MEMO_MAX_SOURCE) return renderUncached(source, repo); |
| 257 | 265 | const key = repo === undefined ? source : `${repo.base}\0${repo.ref}\0${repo.dir}\0\0${source}`; |
| @@ -395,18 +403,23 @@ function renderUncached(source: string, repo?: MarkdownRepo): Html { | ||
| 395 | 403 | } |
| 396 | 404 | |
| 397 | 405 | // A fold: `<details><summary>Title</summary>` on a line of its own, then |
| 398 | // `</details>`. The title is escaped text; nothing else opens a tag. | |
| 399 | const fold = /^<details><summary>([^<>&"'`]{1,80})<\/summary>$/.exec(raws[index] ?? ""); | |
| 406 | // `</details>`. The title is escaped text; nothing else opens a tag. An apostrophe is | |
| 407 | // allowed ("What's left"), escaped like the rest; `<`, `>`, `&`, a double quote and a | |
| 408 | // backtick keep the line plain text. | |
| 409 | const fold = /^<details><summary>([^<>&"`]{1,80})<\/summary>$/.exec(raws[index] ?? ""); | |
| 400 | 410 | if (fold !== null && !folded) { |
| 401 | 411 | closeBlocks(); |
| 402 | out.push(`<details><summary>${fold[1]}</summary>`); | |
| 412 | out.push(`<details><summary>${escapeHtml(fold[1]!)}</summary>`); | |
| 403 | 413 | folded = true; |
| 404 | 414 | continue; |
| 405 | 415 | } |
| 406 | if (folded && raws[index] === "</details>") { | |
| 407 | closeBlocks(); | |
| 408 | out.push("</details>"); | |
| 409 | folded = false; | |
| 416 | if (raws[index] === "</details>") { | |
| 417 | // A close with no fold open (one its open line did not make) is dropped, never shown as text. | |
| 418 | if (folded) { | |
| 419 | closeBlocks(); | |
| 420 | out.push("</details>"); | |
| 421 | folded = false; | |
| 422 | } | |
| 410 | 423 | continue; |
| 411 | 424 | } |
| 412 | 425 |
src/web/pages/talk_client.ts +3
| @@ -14,6 +14,8 @@ | ||
| 14 | 14 | * scrollbar, so the layout moving under them (a turn stored, the box shrinking) never lets go or |
| 15 | 15 | * takes hold. The one control above the composer pauses a reply being followed, and resumes or |
| 16 | 16 | * jumps to the latest once let go; End and Send do the same. |
| 17 | * - A choice (`web/talk_parts.ts`) is answered once: a press of one stills every choice button in | |
| 18 | * the log, since the stream does not draw the earlier reply again. | |
| 17 | 19 | * - Copy buttons are drawn by the script, not the server: without the script |
| 18 | 20 | * they would do nothing. |
| 19 | 21 | * - While a reply streams the composer stays open: Send queues the message, |
| @@ -702,6 +704,7 @@ ${dictateJs} | ||
| 702 | 704 | log.addEventListener("submit", (e) => { |
| 703 | 705 | const f = e.target.closest("form[data-starter]"); |
| 704 | 706 | if (f) { e.preventDefault(); box.value = f.elements.text.value; form.requestSubmit(); } |
| 707 | if (f && f.closest(".talk-choices")) { for (const b of log.querySelectorAll(".talk-choices button")) b.disabled = true; box.focus(); } | |
| 705 | 708 | }); |
| 706 | 709 | box.addEventListener("keydown", (e) => { |
| 707 | 710 | if (e.key === "Escape" && editing) { editing = false; box.value = ""; grow(); say(""); return; } |
src/web/talk_parts.ts +120 −18
| @@ -1,8 +1,11 @@ | ||
| 1 | 1 | /** |
| 2 | * Talk's voice on the page (docs/features/talk.md, Shown results): an agent reply drawn in its | |
| 3 | * fixed vocabulary (`core/talk_voice.ts`): a `::show c<n>` line draws the card the forge kept for | |
| 4 | * that handle in this conversation, the forge's own data in a `.talk-card` with a provenance line | |
| 5 | * under it, set apart from the model's words. | |
| 2 | * Talk's voice on the page (docs/features/talk-voice.md): an agent reply drawn in its fixed | |
| 3 | * vocabulary (`core/talk_voice.ts`). Two kinds, kept visibly apart: | |
| 4 | * | |
| 5 | * - Shown results: a `::show c<n>` line draws the card the forge kept for that handle in this | |
| 6 | * conversation (`core/talk_voice.ts`), the forge's own data in a `.talk-card` with a | |
| 7 | * provenance line under it. | |
| 8 | * - Agent blocks: `choices`, `plan` and `known`, the model's own words in three shapes. | |
| 6 | 9 | * |
| 7 | 10 | * Every string is escaped by the `html` tag; a card's link is a link only when it is a rooted path |
| 8 | 11 | * or an address on the page's own origin. A page of turns reads every card it places in one |
| @@ -12,15 +15,27 @@ | ||
| 12 | 15 | import type { Database } from "bun:sqlite"; |
| 13 | 16 | import type { ShownCard } from "../core/talk_voice.ts"; |
| 14 | 17 | import type { Turn } from "../core/conversations.ts"; |
| 15 | import { cardsPlaced, NOT_FOUND_WORDS, voiceParts, type Part } from "../core/talk_voice.ts"; | |
| 18 | import { cardsPlaced, NOT_FOUND_WORDS, planWord, voiceParts, type Part, type PlanState } from "../core/talk_voice.ts"; | |
| 16 | 19 | import { escapeHtml, html, raw, type Html } from "./html.ts"; |
| 17 | import { renderMarkdown } from "./markdown.ts"; | |
| 18 | import { card as surface, listCard, row, time } from "./ui.ts"; | |
| 20 | import type { IconName } from "./icons.ts"; | |
| 21 | import { renderInline, renderMarkdown } from "./markdown.ts"; | |
| 22 | import { btn, card as surface, icon, listCard, row, time } from "./ui.ts"; | |
| 19 | 23 | |
| 20 | /** What drawing a page of agent turns needs: the cards they place. */ | |
| 24 | /** What drawing a page of agent turns needs: the cards they place, and which replies are live. */ | |
| 21 | 25 | export interface Voice { |
| 22 | 26 | readonly cards: ReadonlyMap<number, ShownCard>; |
| 27 | /** | |
| 28 | * The person's newest standing message ("" when none): only reply turns after it, the last | |
| 29 | * reply, draw their `choices` as buttons. Ids grow with time (`kernel/id.ts`). | |
| 30 | */ | |
| 31 | readonly liveAfter: string; | |
| 32 | /** | |
| 33 | * The newest reply on the page that holds a plan: an earlier plan says its states are as of its | |
| 34 | * own reply, so a step left "doing" never claims to be going on now. | |
| 35 | */ | |
| 36 | readonly latestPlan?: string; | |
| 23 | 37 | readonly origin: string; |
| 38 | readonly conversationId: string; | |
| 24 | 39 | } |
| 25 | 40 | |
| 26 | 41 | /** Each reply's parts by its text, per page: a page parses each reply once. */ |
| @@ -37,12 +52,18 @@ const partsOf = (key: object | undefined, text: string): Part[] => { | ||
| 37 | 52 | }; |
| 38 | 53 | |
| 39 | 54 | /** |
| 40 | * What a page of `turns` of the person's conversation needs to draw its replies: one statement | |
| 41 | * whatever the number of turns or cards. | |
| 55 | * What a page of `turns` of the person's conversation needs to draw its replies: two statements | |
| 56 | * whatever the number of turns or cards (the cards the replies place, and the person's newest | |
| 57 | * message). | |
| 42 | 58 | */ |
| 43 | 59 | export function voiceOf(db: Database, userId: string, conversationId: string, turns: readonly Turn[], origin: string): Voice { |
| 60 | const newest = db | |
| 61 | .query<{ id: string }, [string]>("SELECT id FROM conversation_turn WHERE conversation_id = ?1 AND replaced_at IS NULL AND role = 'person' ORDER BY rowid DESC LIMIT 1") | |
| 62 | .get(conversationId); | |
| 44 | 63 | const key = {}; |
| 45 | const voice: Voice = { cards: cardsPlaced(db, userId, conversationId, turns, (text) => partsOf(key, text)), origin }; | |
| 64 | const cards = cardsPlaced(db, userId, conversationId, turns, (text) => partsOf(key, text)); | |
| 65 | const planned = turns.filter((t) => t.role === "agent" && !t.replaced && t.failed !== true && partsOf(key, t.text).some((p) => p.kind === "plan")).at(-1); | |
| 66 | const voice: Voice = { cards, liveAfter: newest?.id ?? "", ...(planned === undefined ? {} : { latestPlan: planned.id }), origin, conversationId }; | |
| 46 | 67 | parsed.set(voice, parsed.get(key) ?? new Map()); |
| 47 | 68 | return voice; |
| 48 | 69 | } |
| @@ -64,7 +85,7 @@ const hhmm = (iso: string): string => `${iso.slice(11, 16)} UTC`; | ||
| 64 | 85 | * A kept card as the page draws it: title and status, the rows (each a link only when `linkOf` |
| 65 | 86 | * allows it), and the line saying where it came from. |
| 66 | 87 | */ |
| 67 | export function cardHtml(shown: ShownCard, voice: Pick<Voice, "origin">): Html { | |
| 88 | export function cardHtml(shown: ShownCard, voice: Pick<Voice, "origin">, anchor?: string): Html { | |
| 68 | 89 | const c = shown.card; |
| 69 | 90 | const rows = c.rows.map((r) => { |
| 70 | 91 | const href = linkOf(r.link, voice.origin); |
| @@ -80,34 +101,100 @@ export function cardHtml(shown: ShownCard, voice: Pick<Voice, "origin">): Html { | ||
| 80 | 101 | head: html`<strong>${c.title}</strong>${c.status === "" ? null : html` <span class="muted">${c.status}</span>`}`, |
| 81 | 102 | foot: html`<p class="talk-card-from small muted">From the forge: ${shown.said} · as of ${time(shown.createdAt, { text: hhmm(shown.createdAt) })}</p>`, |
| 82 | 103 | attrs: html`data-card="${shown.id}"`, |
| 104 | ...(anchor === undefined ? {} : { id: anchor }), | |
| 83 | 105 | }; |
| 84 | 106 | return rows.length === 0 ? surface(html``, { ...o, pad: false }) : listCard(rows, o); |
| 85 | 107 | } |
| 86 | 108 | |
| 109 | const PLAN_ICON: Readonly<Record<PlanState, IconName>> = { todo: "dot", doing: "loader", done: "check", skipped: "ban" }; | |
| 110 | ||
| 111 | type Placed = ReadonlyMap<number, { anchor: string; title: string }>; | |
| 112 | ||
| 113 | /** | |
| 114 | * A Known, Suspected or Unknown item: its words as inline Markdown, and each `::show c<n>` in it | |
| 115 | * as its source (the result's title, linked where this reply places it). Nothing is ever labelled | |
| 116 | * as missing a source: an item that names none is its words alone. | |
| 117 | */ | |
| 118 | function itemHtml(item: string, placed: Placed, cards: ReadonlyMap<number, ShownCard>): Html { | |
| 119 | // A handle is the item's source: a link to the result where this reply places it, else the kept | |
| 120 | // result's title, quiet; one that names nothing kept draws nothing, never the handle's text. | |
| 121 | const out = item.split(/\s*\(?::show c([1-9]\d{0,8})\)?/).map((bit, i) => { | |
| 122 | if (i % 2 === 0) return renderInline(bit); | |
| 123 | const at = placed.get(Number(bit)); | |
| 124 | if (at !== undefined) return html` <a class="talk-known-src" href="#${at.anchor}">${at.title.slice(0, 60)}</a>`; | |
| 125 | const kept = cards.get(Number(bit)); | |
| 126 | return kept === undefined ? null : html` <span class="talk-known-src small muted">${kept.card.title.slice(0, 60)}</span>`; | |
| 127 | }); | |
| 128 | return html`${out}`; | |
| 129 | } | |
| 130 | ||
| 87 | 131 | /** One part of a reply that is not Markdown, as the page draws it. */ |
| 88 | function partHtml(p: Exclude<Part, { kind: "text" }>, voice: Voice | undefined): Html { | |
| 132 | function partHtml(p: Exclude<Part, { kind: "text" }>, live: boolean, voice: Voice | undefined, placed: Placed, anchors: Map<number, string>, turnId = ""): Html { | |
| 89 | 133 | switch (p.kind) { |
| 90 | 134 | case "show": { |
| 91 | 135 | const shown = voice?.cards.get(p.n); |
| 92 | 136 | if (shown === undefined || voice === undefined) return html`<p class="talk-card-missing small muted">${NOT_FOUND_WORDS}</p>`; |
| 93 | return cardHtml(shown, voice); | |
| 137 | const anchor = anchors.get(p.n); | |
| 138 | anchors.delete(p.n); | |
| 139 | return cardHtml(shown, voice, anchor); | |
| 94 | 140 | } |
| 95 | 141 | // The renderer's own fold, opened and closed around the parts it holds; the title is plain. |
| 96 | 142 | case "fold": |
| 97 | 143 | return raw(`<details><summary>${escapeHtml(p.summary)}</summary>`); |
| 98 | 144 | case "unfold": |
| 99 | 145 | return raw("</details>"); |
| 146 | case "choices": | |
| 147 | return html`<div class="talk-choices" role="group" aria-label="${p.question}"><p>${p.question}</p>${live && voice !== undefined | |
| 148 | ? html`<div class="talk-choices-options">${p.options.map((o) => html`<form method="post" action="/talk/${voice.conversationId}" data-starter><input type="hidden" name="text" value="${o}" />${btn(o)}</form>`)}</div>` | |
| 149 | : html`<p class="muted small">${p.options.join(" · ")}</p>`}</div>`; | |
| 150 | case "plan": | |
| 151 | // The icon says the state at a glance; the word is in the row's name for a screen reader, and | |
| 152 | // on the page only for a step left aside, which an icon alone would not say plainly. | |
| 153 | return listCard( | |
| 154 | p.steps.map((s) => row({ | |
| 155 | lead: icon(PLAN_ICON[s.state]), | |
| 156 | title: s.state === "skipped" ? html`${s.text} <span class="talk-plan-state small">skipped</span>` : html`<span class="sr-only">${planWord(s.state)}: </span>${s.text}`, | |
| 157 | data: { state: s.state }, | |
| 158 | })), | |
| 159 | { | |
| 160 | extra: "bare talk-plan", | |
| 161 | head: | |
| 162 | voice?.latestPlan !== undefined && turnId !== "" && voice.latestPlan !== turnId | |
| 163 | ? html`<span class="small muted">Plan, as of this reply; a newer one is below</span>` | |
| 164 | : html`<span class="small muted">Plan</span>`, | |
| 165 | }, | |
| 166 | ); | |
| 167 | case "known": { | |
| 168 | const part = (label: string, items: readonly string[]): Html | null => | |
| 169 | items.length === 0 | |
| 170 | ? null | |
| 171 | : listCard( | |
| 172 | items.map((x) => row({ title: itemHtml(x, placed, voice?.cards ?? new Map()) })), | |
| 173 | { extra: "bare talk-known", head: html`<span class="small muted">${label}</span>` }, | |
| 174 | ); | |
| 175 | return html`${part("Known", p.known)}${part("Suspected", p.suspected)}${part("Unknown", p.unknown)}`; | |
| 176 | } | |
| 100 | 177 | } |
| 101 | 178 | } |
| 102 | 179 | |
| 103 | 180 | /** |
| 104 | * An agent reply's body: its Markdown (each run through `linked`, the page's `2` links) and its | |
| 105 | * shown results. A reply with none is `linked(renderMarkdown(text))`, as before. | |
| 181 | * An agent reply's body: its Markdown (each run through `linked`, the page's `#12` links), its | |
| 182 | * shown results and its blocks. A reply with neither is `linked(renderMarkdown(text))`, as before. | |
| 106 | 183 | */ |
| 107 | 184 | export function agentHtml(turn: Turn, voice: Voice | undefined, linked: (md: Html) => Html): Html { |
| 108 | 185 | const parts = partsOf(voice, turn.text); |
| 109 | 186 | if (parts.length === 1 && parts[0]!.kind === "text") return linked(renderMarkdown(turn.text)); |
| 110 | return html`${parts.map((p) => (p.kind === "text" ? linked(renderMarkdown(p.text)) : partHtml(p, voice)))}`; | |
| 187 | const live = voice !== undefined && !turn.replaced && turn.id > voice.liveAfter; | |
| 188 | // The first placing of each handle carries the anchor a Known item links to. | |
| 189 | const anchors = new Map<number, string>(); | |
| 190 | const placed = new Map<number, { anchor: string; title: string }>(); | |
| 191 | for (const p of parts) { | |
| 192 | const shown = p.kind === "show" && !anchors.has(p.n) ? voice?.cards.get(p.n) : undefined; | |
| 193 | if (shown === undefined) continue; | |
| 194 | anchors.set(shown.n, `t-${turn.id}-c${shown.n}`); | |
| 195 | placed.set(shown.n, { anchor: `t-${turn.id}-c${shown.n}`, title: shown.card.title }); | |
| 196 | } | |
| 197 | return html`${parts.map((p) => (p.kind === "text" ? linked(renderMarkdown(p.text)) : partHtml(p, live, voice, placed, anchors, turn.id)))}`; | |
| 111 | 198 | } |
| 112 | 199 | |
| 113 | 200 | /** |
| @@ -118,9 +205,24 @@ export const voiceCss = /* css */ ` | ||
| 118 | 205 | /* Over .card.bare's own border and overflow: a hairline on the start side, and a wide card scrolls in itself. */ |
| 119 | 206 | .card.bare.talk-card { margin: 8px 0; max-width: 100%; overflow-x: auto; border-inline-start: 2px solid var(--border); padding-inline-start: 12px; } |
| 120 | 207 | .talk-card .row { min-height: 44px; padding-inline: 0; } |
| 121 | .talk-card .row-title, .talk-card .row-meta { white-space: normal; overflow-wrap: anywhere; } | |
| 208 | .talk-card .row-title, .talk-card .row-meta, .talk-known .row-title, .talk-plan .row-title { white-space: normal; overflow-wrap: anywhere; } | |
| 209 | /* The prose list's bullets and indent are not for these rows: at 360 px they pushed the state words off the edge. */ | |
| 210 | .talk-body :is(.talk-plan, .talk-known) .list { list-style: none; margin: 0; padding: 0; } | |
| 122 | 211 | .talk-card li[data-depth="1"] > .row { padding-inline-start: 16px; } |
| 123 | 212 | .talk-card li[data-depth="2"] > .row { padding-inline-start: 32px; } |
| 124 | 213 | .talk-card li[data-depth="3"] > .row { padding-inline-start: 48px; } |
| 214 | .talk-choices .btn { min-height: 2.75rem; } | |
| 125 | 215 | .talk-card-from { margin: 0; } |
| 216 | .talk-choices { margin: 12px 0; } | |
| 217 | .talk-choices > p { margin: 0 0 8px; } | |
| 218 | .talk-choices-options { display: flex; flex-wrap: wrap; gap: 8px; } | |
| 219 | /* At phone width the options stack, each the width of the reply. */ | |
| 220 | @media (max-width: 40rem) { .talk-choices-options { flex-direction: column; } .talk-choices-options .btn { width: 100%; justify-content: flex-start; } } | |
| 221 | /* The model's own words, plain: regular weight, no box, one quiet label a group. */ | |
| 222 | .talk-plan, .talk-known { margin: 12px 0; } | |
| 223 | .talk-plan > .card-head, .talk-known > .card-head { padding: 0 0 4px; } | |
| 224 | .talk-plan .row, .talk-known .row { padding: 4px 0; min-height: 0; align-items: baseline; } | |
| 225 | .talk-plan .row-title, .talk-known .row-title { font-weight: inherit; } | |
| 226 | .talk-plan .row-lead { align-self: center; } | |
| 227 | .talk-plan li[data-state="done"] .row-title, .talk-plan li[data-state="skipped"] .row-title, .talk-plan-state { color: var(--muted-fg); } | |
| 126 | 228 | `; |
test/note-context.test.ts +3 −1
| @@ -146,11 +146,13 @@ describe("the fold in user text", () => { | ||
| 146 | 146 | }); |
| 147 | 147 | |
| 148 | 148 | test("a title with disallowed characters is text", () => { |
| 149 | for (const title of ['x"onclick="1', "a<b", "a&b", "it's", "`t`", "", "z".repeat(81)]) { | |
| 149 | for (const title of ['x"onclick="1', "a<b", "a&b", "`t`", "", "z".repeat(81)]) { | |
| 150 | 150 | const h = html(`<details><summary>${title}</summary>\nbody\n</details>`); |
| 151 | 151 | expect(opens(h)).toBe(0); |
| 152 | 152 | expect(h).not.toContain("<summary>"); |
| 153 | 153 | } |
| 154 | 154 | expect(html("<details><summary>Fine title</summary>\nbody\n</details>")).toContain("<summary>Fine title</summary>"); |
| 155 | // An apostrophe is safe in a title: it folds, escaped. | |
| 156 | expect(html("<details><summary>What's left</summary>\nbody\n</details>")).toContain("<summary>What's left</summary>"); | |
| 155 | 157 | }); |
| 156 | 158 | }); |
test/talk-blocks.test.ts added +596
| @@ -0,0 +1,596 @@ | ||
| 1 | /** | |
| 2 | * Agent blocks (docs/features/talk-voice.md): a fenced `forge` block names its kind on its first | |
| 3 | * line and holds JSON in that kind's one shape: `choices`, `plan` or `known`. A valid block is | |
| 4 | * drawn as its shape; anything else is drawn as the code block it always was, never an error, and | |
| 5 | * its words stay escaped. Only the last reply's choices are buttons. A README is untouched, and | |
| 6 | * the terminal prints the same parts as plain lines. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { recordCard } from "../src/core/talk_voice.ts"; | |
| 14 | import { | |
| 15 | appendTurn, | |
| 16 | createConversation, | |
| 17 | listTurns, | |
| 18 | type Turn, | |
| 19 | } from "../src/core/conversations.ts"; | |
| 20 | import { | |
| 21 | cardLines, | |
| 22 | plainVoice, | |
| 23 | voiceParts, | |
| 24 | VOICE_LIMITS, | |
| 25 | } from "../src/core/talk_voice.ts"; | |
| 26 | import { createUser, type User } from "../src/core/users.ts"; | |
| 27 | import { renderInline, renderMarkdown } from "../src/web/markdown.ts"; | |
| 28 | import { turnHtml } from "../src/web/pages/talk.ts"; | |
| 29 | import { agentHtml, linkOf, voiceCss, voiceOf } from "../src/web/talk_parts.ts"; | |
| 30 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 31 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 32 | import { settleApp } from "./helpers/tui.ts"; | |
| 33 | import { proveAll } from "./helpers/verified.ts"; | |
| 34 | ||
| 35 | let dir: string; | |
| 36 | const add = (...a: Parameters<typeof appendTurn>): Turn => { | |
| 37 | const r = appendTurn(...a); | |
| 38 | if (!r.ok) throw new Error(r.error); | |
| 39 | return r.value; | |
| 40 | }; | |
| 41 | let app: App; | |
| 42 | let alice: User; | |
| 43 | ||
| 44 | const block = (kind: string, body: unknown): string => | |
| 45 | `\`\`\`forge\n${kind}\n${typeof body === "string" ? body : JSON.stringify(body)}\n\`\`\``; | |
| 46 | const agent = (text: string, id = "01m0000000000000000000000z"): Turn => | |
| 47 | ({ | |
| 48 | id, | |
| 49 | conversationId: "c", | |
| 50 | role: "agent", | |
| 51 | text, | |
| 52 | createdAt: "2026-11-22T10:00:00.000Z", | |
| 53 | replaced: false, | |
| 54 | failed: false, | |
| 55 | }) as Turn; | |
| 56 | const drawn = (text: string): string => turnHtml(agent(text), new Set()).text; | |
| 57 | ||
| 58 | beforeAll(async () => { | |
| 59 | dir = await mkdtemp(join(tmpdir(), "forge-talk-blocks-")); | |
| 60 | app = createApp({ dataDir: dir, port: 0 }); | |
| 61 | const u = await createUser(app.db, { | |
| 62 | origin: "seed", | |
| 63 | trusted: true, | |
| 64 | username: "alice", | |
| 65 | email: "[email protected]", | |
| 66 | password: "a-good-passphrase", | |
| 67 | adminIfFirst: true, | |
| 68 | }); | |
| 69 | if (!u.ok) throw new Error(u.error); | |
| 70 | alice = u.value; | |
| 71 | proveAll(app); | |
| 72 | }); | |
| 73 | afterAll(async () => { | |
| 74 | app.db.close(); | |
| 75 | await rm(dir, { recursive: true, force: true }); | |
| 76 | }); | |
| 77 | ||
| 78 | describe("each block, valid, is drawn as its shape", () => { | |
| 79 | test("choices: the question and one button per option, each a starter form that sends the option", () => { | |
| 80 | const c = createConversation(app.db, alice.id); | |
| 81 | if (!c.ok) throw new Error(c.error); | |
| 82 | appendTurn(app.db, alice.id, c.value.id, { | |
| 83 | role: "person", | |
| 84 | text: "deploy it", | |
| 85 | }); | |
| 86 | const reply = add(app.db, alice.id, c.value.id, { | |
| 87 | role: "agent", | |
| 88 | text: `Which one?\n\n${block("choices", { question: "Which app?", options: ["alice/shop", "alice/blog"] })}`, | |
| 89 | }); | |
| 90 | const turns = listTurns(app.db, alice.id, c.value.id, { limit: 10 }); | |
| 91 | const all = turns.ok ? turns.value : []; | |
| 92 | const voice = voiceOf( | |
| 93 | app.db, | |
| 94 | alice.id, | |
| 95 | c.value.id, | |
| 96 | all, | |
| 97 | "http://forge.test", | |
| 98 | ); | |
| 99 | const html = turnHtml( | |
| 100 | all.find((t) => t.id === reply.id)!, | |
| 101 | new Set(), | |
| 102 | undefined, | |
| 103 | undefined, | |
| 104 | undefined, | |
| 105 | [], | |
| 106 | new Set(), | |
| 107 | new Set(), | |
| 108 | undefined, | |
| 109 | voice, | |
| 110 | ).text; | |
| 111 | expect(html).toContain('class="talk-choices"'); | |
| 112 | expect(html).toContain("Which app?"); | |
| 113 | const forms = [ | |
| 114 | ...html.matchAll( | |
| 115 | /<form method="post" action="\/talk\/([0-9a-z]+)" data-starter><input type="hidden" name="text" value="([^"]*)" \/>/g, | |
| 116 | ), | |
| 117 | ]; | |
| 118 | expect(forms.map((f) => f[2])).toEqual(["alice/shop", "alice/blog"]); | |
| 119 | expect(forms.every((f) => f[1] === c.value.id)).toBe(true); | |
| 120 | expect(html).toContain("<p>Which one?</p>"); | |
| 121 | }); | |
| 122 | ||
| 123 | test("choices: only the last reply's are buttons; an earlier one is plain text", () => { | |
| 124 | const c = createConversation(app.db, alice.id); | |
| 125 | if (!c.ok) throw new Error(c.error); | |
| 126 | const ask = block("choices", { | |
| 127 | question: "Which one?", | |
| 128 | options: ["first", "second"], | |
| 129 | }); | |
| 130 | appendTurn(app.db, alice.id, c.value.id, { role: "person", text: "hi" }); | |
| 131 | const old = add(app.db, alice.id, c.value.id, { | |
| 132 | role: "agent", | |
| 133 | text: ask, | |
| 134 | }); | |
| 135 | appendTurn(app.db, alice.id, c.value.id, { role: "person", text: "first" }); | |
| 136 | const last = add(app.db, alice.id, c.value.id, { | |
| 137 | role: "agent", | |
| 138 | text: ask, | |
| 139 | }); | |
| 140 | const turns = listTurns(app.db, alice.id, c.value.id, { limit: 10 }); | |
| 141 | const all = turns.ok ? turns.value : []; | |
| 142 | const voice = voiceOf( | |
| 143 | app.db, | |
| 144 | alice.id, | |
| 145 | c.value.id, | |
| 146 | all, | |
| 147 | "http://forge.test", | |
| 148 | ); | |
| 149 | const of = (id: string) => | |
| 150 | turnHtml( | |
| 151 | all.find((t) => t.id === id)!, | |
| 152 | new Set(), | |
| 153 | undefined, | |
| 154 | undefined, | |
| 155 | undefined, | |
| 156 | [], | |
| 157 | new Set(), | |
| 158 | new Set(), | |
| 159 | undefined, | |
| 160 | voice, | |
| 161 | ).text; | |
| 162 | expect(of(old.id)).not.toContain("data-starter"); | |
| 163 | expect(of(old.id)).toContain("first · second"); | |
| 164 | expect(of(last.id).match(/data-starter/g)?.length).toBe(2); | |
| 165 | // With no page around it (no voice), nothing is live. | |
| 166 | expect(drawn(ask)).not.toContain("data-starter"); | |
| 167 | }); | |
| 168 | ||
| 169 | test("plan: each step a plain row with its icon, its state in words in its name, nothing bold and no number", () => { | |
| 170 | const html = drawn( | |
| 171 | block("plan", { | |
| 172 | steps: [ | |
| 173 | { text: "Read the issue", state: "done" }, | |
| 174 | { text: "Open a pull", state: "doing" }, | |
| 175 | { text: "Ship", state: "todo" }, | |
| 176 | { text: "Old idea", state: "skipped" }, | |
| 177 | ], | |
| 178 | }), | |
| 179 | ); | |
| 180 | expect(html).toContain("talk-plan"); | |
| 181 | // The state is in each row's name (hidden words, or the visible "skipped"), never colour alone. | |
| 182 | const names = html.split("</li>").filter((li) => li.includes("data-state")).map((li) => li.slice(li.lastIndexOf("<li")).replace(/<svg[\s\S]*?<\/svg>/g, "").replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim()); | |
| 183 | expect(names).toEqual(["done: Read the issue", "doing: Open a pull", "to do: Ship", "Old idea skipped"]); | |
| 184 | expect(html).not.toMatch(/<strong>|\b1\. Read/); | |
| 185 | expect(html.match(/<svg/g)?.length).toBe(4); | |
| 186 | expect( | |
| 187 | [...html.matchAll(/data-state="([a-z]+)"/g)].map((m) => m[1]), | |
| 188 | ).toEqual(["done", "doing", "todo", "skipped"]); | |
| 189 | }); | |
| 190 | ||
| 191 | test("known: three labelled lists, an empty one left out, and no item ever marked as lacking a source", () => { | |
| 192 | const html = drawn( | |
| 193 | block("known", { | |
| 194 | known: [ | |
| 195 | "The check is red ([run](/alice/w/runs/1))", | |
| 196 | "It failed on `bun test`", | |
| 197 | ], | |
| 198 | unknown: ["Whether it flakes"], | |
| 199 | }), | |
| 200 | ); | |
| 201 | expect(html).toContain('<span class="small muted">Known</span>'); | |
| 202 | expect(html).toContain('<span class="small muted">Unknown</span>'); | |
| 203 | expect(html).not.toContain(">Suspected<"); | |
| 204 | expect(html).toContain( | |
| 205 | '<a href="/alice/w/runs/1" rel="nofollow noopener">run</a>', | |
| 206 | ); | |
| 207 | expect(html).toContain("<code>bun test</code>"); | |
| 208 | expect(html).not.toContain("no source"); | |
| 209 | }); | |
| 210 | ||
| 211 | test("known: an empty Unknown is not drawn, and an Unknown item keeps what would settle it in its own row", () => { | |
| 212 | const none = drawn(block("known", { known: ["The check is red ([run](/alice/w/runs/1))"], unknown: [] })); | |
| 213 | expect(none).not.toContain(">Unknown<"); | |
| 214 | const html = drawn(block("known", { known: ["The check is red ([run](/alice/w/runs/1))"], unknown: ["Whether it flakes: run it again on main, or ask bob"] })); | |
| 215 | const unknown = html.slice(html.indexOf(">Unknown<")); | |
| 216 | // One item, one row: the thing and what would settle it read together, never as two lines. | |
| 217 | expect(unknown.match(/class="row-title"/g)?.length).toBe(1); | |
| 218 | expect(unknown).toMatch(/class="row-title"\s*>Whether it flakes: run it again on main, or ask bob</); | |
| 219 | }); | |
| 220 | ||
| 221 | test("plan: an earlier plan says it is as of its own reply once a newer one is below, so no step claims to be going on now", () => { | |
| 222 | const c = createConversation(app.db, alice.id); | |
| 223 | if (!c.ok) throw new Error(c.error); | |
| 224 | const first = add(app.db, alice.id, c.value.id, { role: "agent", text: block("plan", { steps: [{ text: "Make the toggle", state: "doing" }] }) }); | |
| 225 | const second = add(app.db, alice.id, c.value.id, { role: "agent", text: block("plan", { steps: [{ text: "Make the toggle", state: "done" }] }) }); | |
| 226 | const turns = listTurns(app.db, alice.id, c.value.id, { limit: 5 }); | |
| 227 | const all = turns.ok ? turns.value : []; | |
| 228 | const voice = voiceOf(app.db, alice.id, c.value.id, all, "http://forge.test"); | |
| 229 | const draw = (id: string) => agentHtml(all.find((x) => x.id === id)!, voice, (m) => m).text; | |
| 230 | expect(draw(first.id)).toContain("Plan, as of this reply; a newer one is below"); | |
| 231 | expect(draw(second.id)).not.toContain("as of this reply"); | |
| 232 | }); | |
| 233 | ||
| 234 | test("known: an item's handle is its source, linked where this reply places it, never its text", () => { | |
| 235 | const c = createConversation(app.db, alice.id); | |
| 236 | if (!c.ok) throw new Error(c.error); | |
| 237 | recordCard( | |
| 238 | app.db, | |
| 239 | `conversation:${c.value.id}`, | |
| 240 | alice.id, | |
| 241 | "now", | |
| 242 | "Now", | |
| 243 | { kind: "crew", title: "Working now", status: "", rows: [], actions: [] }, | |
| 244 | "", | |
| 245 | ); | |
| 246 | const t = add(app.db, alice.id, c.value.id, { | |
| 247 | role: "agent", | |
| 248 | text: `::show c1\n\n${block("known", { known: ["Nothing is running ::show c1", "The crew is idle"] })}`, | |
| 249 | }); | |
| 250 | const turns = listTurns(app.db, alice.id, c.value.id, { limit: 5 }); | |
| 251 | const all = turns.ok ? turns.value : []; | |
| 252 | const voice = voiceOf( | |
| 253 | app.db, | |
| 254 | alice.id, | |
| 255 | c.value.id, | |
| 256 | all, | |
| 257 | "http://forge.test", | |
| 258 | ); | |
| 259 | const html = agentHtml( | |
| 260 | all.find((x) => x.id === t.id)!, | |
| 261 | voice, | |
| 262 | (m) => m, | |
| 263 | ).text; | |
| 264 | expect(html).toContain(`id="t-${t.id}-c1"`); | |
| 265 | expect(html).toContain(`<a class="talk-known-src" href="#t-${t.id}-c1">Working now</a>`); | |
| 266 | expect(html).not.toContain("no source"); | |
| 267 | expect(html).not.toContain("::show"); | |
| 268 | }); | |
| 269 | }); | |
| 270 | ||
| 271 | describe("anything invalid is the code block it always was", () => { | |
| 272 | const variants: [string, string][] = [ | |
| 273 | ["bad JSON", block("choices", "{ question: nope")], | |
| 274 | ["one option", block("choices", { question: "Q?", options: ["only"] })], | |
| 275 | [ | |
| 276 | "five options", | |
| 277 | block("choices", { question: "Q?", options: ["a", "b", "c", "d", "e"] }), | |
| 278 | ], | |
| 279 | [ | |
| 280 | "a long option", | |
| 281 | block("choices", { | |
| 282 | question: "Q?", | |
| 283 | options: ["a", "b".repeat(VOICE_LIMITS.option + 1)], | |
| 284 | }), | |
| 285 | ], | |
| 286 | [ | |
| 287 | "a repeated option", | |
| 288 | block("choices", { question: "Q?", options: ["a", "a"] }), | |
| 289 | ], | |
| 290 | [ | |
| 291 | "an extra key", | |
| 292 | block("choices", { question: "Q?", options: ["a", "b"], onclick: "x" }), | |
| 293 | ], | |
| 294 | [ | |
| 295 | "a line break in an option", | |
| 296 | block("choices", { question: "Q?", options: ["a\nb", "c"] }), | |
| 297 | ], | |
| 298 | [ | |
| 299 | "a wrong state", | |
| 300 | block("plan", { steps: [{ text: "x", state: "finished" }] }), | |
| 301 | ], | |
| 302 | ["no steps", block("plan", { steps: [] })], | |
| 303 | [ | |
| 304 | "thirteen steps", | |
| 305 | block("plan", { | |
| 306 | steps: Array.from({ length: 13 }, () => ({ text: "x", state: "todo" })), | |
| 307 | }), | |
| 308 | ], | |
| 309 | [ | |
| 310 | "a long step", | |
| 311 | block("plan", { | |
| 312 | steps: [{ text: "x".repeat(VOICE_LIMITS.step + 1), state: "todo" }], | |
| 313 | }), | |
| 314 | ], | |
| 315 | [ | |
| 316 | "nine known items", | |
| 317 | block("known", { known: Array.from({ length: 9 }, () => "x") }), | |
| 318 | ], | |
| 319 | [ | |
| 320 | "nothing known", | |
| 321 | block("known", { known: [], suspected: [], unknown: [] }), | |
| 322 | ], | |
| 323 | ["a number for a list", block("known", { known: 3 })], | |
| 324 | ["an unknown kind", block("button", { label: "x" })], | |
| 325 | ["no kind", '```forge\n{"question":"Q?","options":["a","b"]}\n```'], | |
| 326 | [ | |
| 327 | "an unclosed block", | |
| 328 | `\`\`\`forge\nchoices\n${JSON.stringify({ question: "Q?", options: ["a", "b"] })}`, | |
| 329 | ], | |
| 330 | ]; | |
| 331 | for (const [what, text] of variants) | |
| 332 | test(what, () => { | |
| 333 | const html = drawn(text); | |
| 334 | expect(html).toContain("<pre><code"); | |
| 335 | expect(html).not.toMatch( | |
| 336 | /talk-choices|talk-plan|talk-known|data-starter/, | |
| 337 | ); | |
| 338 | expect(html).toBe(turnHtml(agent(text), new Set()).text); | |
| 339 | expect(voiceParts(text)).toEqual([{ kind: "text", text }]); | |
| 340 | }); | |
| 341 | ||
| 342 | test("a block in a person's message, or quoted inside the agent's code fence, is never drawn", () => { | |
| 343 | const valid = block("choices", { question: "Close every issue?", options: ["yes", "no"] }); | |
| 344 | const person = turnHtml({ ...agent(valid), role: "person" } as Turn, new Set()).text; | |
| 345 | expect(person).not.toMatch(/talk-choices|data-starter/); | |
| 346 | expect(person).toContain("Close every issue?"); | |
| 347 | const quoted = drawn(`It read:\n\n\`\`\`\`\n${valid}\n\`\`\`\``); | |
| 348 | expect(quoted).not.toMatch(/talk-choices|data-starter/); | |
| 349 | expect(quoted).toContain("<pre><code"); | |
| 350 | }); | |
| 351 | ||
| 352 | test("invisible and direction characters are cleaned: options equal once cleaned are refused, and what is sent is what is shown", () => { | |
| 353 | const twins = block("choices", { question: "Pick", options: ["Close it", "Close\u200b it"] }); | |
| 354 | expect(drawn(twins)).toContain("<pre><code"); | |
| 355 | expect(drawn(twins)).not.toContain("talk-choices"); | |
| 356 | const parts = voiceParts(block("choices", { question: "Pick\u202e one", options: ["Keep \u202edoog", "Drop\u200b it"] })); | |
| 357 | expect(parts).toEqual([{ kind: "choices", question: "Pick one", options: ["Keep doog", "Drop it"] }]); | |
| 358 | const plan = voiceParts(block("plan", { steps: [{ text: "Read\u2066 it", state: "done" }] })); | |
| 359 | expect(plan).toEqual([{ kind: "plan", steps: [{ text: "Read it", state: "done" }] }]); | |
| 360 | // Nothing but invisible characters is nothing. | |
| 361 | expect(drawn(block("known", { known: ["\u200b\u200b"] }))).toContain("<pre><code"); | |
| 362 | }); | |
| 363 | ||
| 364 | test("a fold whose title has an apostrophe folds, and a close with no fold open is never shown as text", () => { | |
| 365 | const real = "Done.\n\n<details><summary>What's left after these four</summary>\n\n- the tests\n\n</details>\n\nNext.\n\n</details>"; | |
| 366 | const html = drawn(real); | |
| 367 | expect(html).toContain("<details><summary>What's left after these four</summary>"); | |
| 368 | expect(html).not.toContain("</details>"); | |
| 369 | expect(html).not.toContain("<details"); | |
| 370 | expect(html.match(/<\/details>/g)?.length).toBe(1); | |
| 371 | }); | |
| 372 | ||
| 373 | test("known: a handle that names nothing kept draws nothing; none is ever printed as text", () => { | |
| 374 | const html = drawn(block("known", { known: ["Repo owner/dotfield and issue #1 exist ::show c1", "Spend is $0 (::show c3)"] })); | |
| 375 | expect(html).not.toContain("result c"); | |
| 376 | expect(html).not.toContain("::show"); | |
| 377 | expect(html).not.toContain("()"); | |
| 378 | expect(html).toContain("Repo owner/dotfield and issue #1 exist"); | |
| 379 | }); | |
| 380 | ||
| 381 | test("known: an unknown item may come with what would settle it, as the brief asks (a real reply)", () => { | |
| 382 | const real = '{"known": ["Diff of 06b1627: +2/-0 in src/beacon.ts", "::show c3"], "suspected": ["The drift is not fixed"], "unknown": [{"item": "Whether tests reference beacon.ts", "settle": "List the repo root on main"}]}'; | |
| 383 | const html = drawn("```known\n" + real + "\n```"); | |
| 384 | expect(html).toContain('class="card bare talk-known"'); | |
| 385 | expect(html).toContain("Whether tests reference beacon.ts; to settle: List the repo root on main"); | |
| 386 | expect(html).not.toContain(""known""); | |
| 387 | }); | |
| 388 | ||
| 389 | ||
| 390 | test("a block may be fenced `forge`, `forge <kind>` or the bare kind; only the exact shape is a block", () => { | |
| 391 | const plan = { steps: [{ text: "Read it", state: "done" }] }; | |
| 392 | const fenced = (info: string, body: string) => "```" + info + "\n" + body + "\n```"; | |
| 393 | for (const text of [block("plan", plan), fenced("forge plan", JSON.stringify(plan)), fenced("plan", JSON.stringify(plan))]) { | |
| 394 | expect(voiceParts(text)).toEqual([{ kind: "plan", steps: [{ text: "Read it", state: "done" }] }]); | |
| 395 | expect(drawn(text)).toContain("talk-plan"); | |
| 396 | } | |
| 397 | const choices = { question: "Which?", options: ["a", "b"] }; | |
| 398 | expect(voiceParts(fenced("choices", JSON.stringify(choices)))).toEqual([{ kind: "choices", ...choices }]); | |
| 399 | expect(voiceParts(fenced("forge known", JSON.stringify({ known: ["k"] })))).toEqual([{ kind: "known", known: ["k"], suspected: [], unknown: [] }]); | |
| 400 | // A real code block labelled with a kind, or with the wrong kind's shape, stays the code it | |
| 401 | // was. | |
| 402 | for (const text of [fenced("plan", "1. read it\n2. ship it"), fenced("plan", JSON.stringify(choices)), fenced("choices", JSON.stringify(plan)), fenced("forge plan", "plan\n" + JSON.stringify(plan)), fenced("planner", JSON.stringify(plan))]) { | |
| 403 | expect(voiceParts(text)).toEqual([{ kind: "text", text }]); | |
| 404 | expect(drawn(text)).toContain("<pre><code"); | |
| 405 | } | |
| 406 | }); | |
| 407 | ||
| 408 | test("HTML in a valid block's words is text", () => { | |
| 409 | const html = drawn( | |
| 410 | block("choices", { | |
| 411 | question: "<b>Pick</b> <script>x()</script>", | |
| 412 | options: [ | |
| 413 | '"><img src=x onerror=alert(1)>', | |
| 414 | "<a href=javascript:alert(1)>b</a>", | |
| 415 | ], | |
| 416 | }), | |
| 417 | ); | |
| 418 | expect(html).toContain("talk-choices"); | |
| 419 | expect(html).not.toContain("<script>x()"); | |
| 420 | expect(html).not.toContain("<img src=x"); | |
| 421 | expect(html).not.toContain("<a href=javascript"); | |
| 422 | expect(html).toContain("<b>Pick</b>"); | |
| 423 | const known = drawn( | |
| 424 | block("known", { known: ["[x](javascript:alert(1)) <i>y</i>"] }), | |
| 425 | ); | |
| 426 | expect(known).not.toContain('href="javascript'); | |
| 427 | expect(known).toContain("<i>y</i>"); | |
| 428 | }); | |
| 429 | ||
| 430 | test("a reply with no block and no ::show is drawn exactly as Markdown", () => { | |
| 431 | const text = | |
| 432 | "# Hi\n\nSome `code` and a [link](https://example.com).\n\n```ts\nlet a = 1;\n```\n\n<details><summary>More</summary>\n\nfolded\n\n</details>"; | |
| 433 | expect(agentHtml(agent(text), undefined, (m) => m).text).toBe( | |
| 434 | renderMarkdown(text).text, | |
| 435 | ); | |
| 436 | }); | |
| 437 | ||
| 438 | test("a ::show inside a fold is drawn inside the fold", () => { | |
| 439 | const html = agentHtml( | |
| 440 | agent( | |
| 441 | "<details><summary>The rows</summary>\n\n::show c4\n\n</details>\n\nAfter.", | |
| 442 | ), | |
| 443 | undefined, | |
| 444 | (m) => m, | |
| 445 | ).text; | |
| 446 | expect(html.indexOf("<details><summary>The rows</summary>")).toBeLessThan( | |
| 447 | html.indexOf("Result not found."), | |
| 448 | ); | |
| 449 | expect(html.indexOf("Result not found.")).toBeLessThan( | |
| 450 | html.indexOf("</details>"), | |
| 451 | ); | |
| 452 | expect(html.indexOf("</details>")).toBeLessThan( | |
| 453 | html.indexOf("<p>After.</p>"), | |
| 454 | ); | |
| 455 | }); | |
| 456 | }); | |
| 457 | ||
| 458 | describe("a README is untouched", () => { | |
| 459 | test("a forge block in a README renders as the code block it is", () => { | |
| 460 | const text = `# Readme\n\n${block("choices", { question: "Q?", options: ["a", "b"] })}\n\n::show c1\n`; | |
| 461 | const made = renderMarkdown(text, { | |
| 462 | base: "/alice/w", | |
| 463 | ref: "main", | |
| 464 | dir: "", | |
| 465 | }).text; | |
| 466 | expect(made).toContain("<pre><code"); | |
| 467 | expect(made).toContain("::show c1"); | |
| 468 | expect(made).not.toMatch(/talk-choices|talk-card/); | |
| 469 | }); | |
| 470 | ||
| 471 | test("renderInline draws inline marks only, escaped, http(s) links only", () => { | |
| 472 | expect(renderInline("# not a heading `x` **b**").text).toBe( | |
| 473 | "# not a heading <code>x</code> <strong>b</strong>", | |
| 474 | ); | |
| 475 | expect(renderInline("[a](javascript:alert(1)) <b>").text).toBe( | |
| 476 | "[a](javascript:alert(1)) <b>", | |
| 477 | ); | |
| 478 | expect(renderInline("a\nb").text).toBe("a b"); | |
| 479 | }); | |
| 480 | }); | |
| 481 | ||
| 482 | describe("the page's rules and links", () => { | |
| 483 | test("the stylesheet is small, uses tokens, and says sides logically", () => { | |
| 484 | expect(Buffer.byteLength(voiceCss)).toBeLessThan(2_600); | |
| 485 | expect(voiceCss).not.toMatch( | |
| 486 | /#[0-9a-f]{3,6}\b|rgb\(|(?:margin|padding)-(?:left|right)/i, | |
| 487 | ); | |
| 488 | expect(voiceCss).toContain("overflow-x: auto"); | |
| 489 | }); | |
| 490 | ||
| 491 | test("linkOf keeps rooted paths and this origin's addresses, and nothing else", () => { | |
| 492 | const o = "https://forge.test"; | |
| 493 | expect(linkOf("/a/b", o)).toBe("/a/b"); | |
| 494 | expect(linkOf("https://forge.test/a", o)).toBe("https://forge.test/a"); | |
| 495 | for (const bad of [ | |
| 496 | "//evil.test/a", | |
| 497 | "/\\evil.test", | |
| 498 | "https://forge.test.evil.test/a", | |
| 499 | "https://evil.test/a", | |
| 500 | "javascript:alert(1)", | |
| 501 | "/a b", | |
| 502 | "/a\tb", | |
| 503 | "https://forge.test", | |
| 504 | ]) | |
| 505 | expect(linkOf(bad, o)).toBeUndefined(); | |
| 506 | }); | |
| 507 | }); | |
| 508 | ||
| 509 | describe("the terminal prints the same parts", () => { | |
| 510 | test("plainVoice prints a card's rows, each block as a plain list, and a missing handle", () => { | |
| 511 | const shown = { | |
| 512 | id: "x", | |
| 513 | via: "conversation:c", | |
| 514 | userId: "u", | |
| 515 | n: 1, | |
| 516 | tool: "now", | |
| 517 | said: "Now", | |
| 518 | createdAt: "2026-11-22T10:00:00.000Z", | |
| 519 | card: { | |
| 520 | kind: "crew" as const, | |
| 521 | title: "Working now", | |
| 522 | status: "1 going", | |
| 523 | rows: [ | |
| 524 | { label: "smith on alice/w", value: "running" }, | |
| 525 | { label: "child", value: "x", depth: 1 }, | |
| 526 | ], | |
| 527 | actions: [], | |
| 528 | }, | |
| 529 | }; | |
| 530 | const text = `Here.\n\n::show c1\n\n::show c2\n\n${block("plan", { steps: [{ text: "Read", state: "done" }] })}\n\n${block("choices", { question: "Which?", options: ["a", "b"] })}\n\n${block("known", { known: ["k"], unknown: ["u"] })}`; | |
| 531 | const out = plainVoice(text, new Map([[1, shown]])); | |
| 532 | expect(out).toContain( | |
| 533 | "Working now · 1 going\n smith on alice/w: running\n child: x", | |
| 534 | ); | |
| 535 | expect(out).toContain("From the forge: Now, as of 2026-11-22 10:00 UTC"); | |
| 536 | expect(out).toContain("Result not found."); | |
| 537 | expect(out).toContain("Plan:\n 1. [done] Read"); | |
| 538 | expect(out).toContain("Which?\n 1. a\n 2. b"); | |
| 539 | expect(out).toContain("Known:\n - k\nUnknown:\n - u"); | |
| 540 | expect(out).not.toContain("Suspected"); | |
| 541 | expect(plainVoice("plain words", new Map())).toBe("plain words"); | |
| 542 | // Every spelling of a block's fence prints the same; a code block labelled with a kind stays | |
| 543 | // code. | |
| 544 | const steps = JSON.stringify({ steps: [{ text: "Read", state: "done" }] }); | |
| 545 | for (const info of ["forge plan", "plan"]) expect(plainVoice("```" + info + "\n" + steps + "\n```", new Map())).toBe("Plan:\n 1. [done] Read"); | |
| 546 | expect(plainVoice("```plan\nread, then ship\n```", new Map())).toBe("```plan\nread, then ship\n```"); | |
| 547 | expect(cardLines(shown.card)[0]).toBe("Working now · 1 going"); | |
| 548 | }); | |
| 549 | ||
| 550 | test("the terminal's conversation screen prints a placed card's rows and a plan", async () => { | |
| 551 | const c = createConversation(app.db, alice.id); | |
| 552 | if (!c.ok) throw new Error(c.error); | |
| 553 | recordCard( | |
| 554 | app.db, | |
| 555 | `conversation:${c.value.id}`, | |
| 556 | alice.id, | |
| 557 | "now", | |
| 558 | "Now", | |
| 559 | { | |
| 560 | kind: "crew", | |
| 561 | title: "Working now", | |
| 562 | status: "nothing running", | |
| 563 | rows: [{ label: "quiet row", value: "idle" }], | |
| 564 | actions: [], | |
| 565 | }, | |
| 566 | "", | |
| 567 | ); | |
| 568 | appendTurn(app.db, alice.id, c.value.id, { | |
| 569 | role: "agent", | |
| 570 | text: `Look:\n::show c1\n${block("plan", { steps: [{ text: "Check the crew", state: "done" }] })}`, | |
| 571 | }); | |
| 572 | const terminal = headlessTerminal(120, 40); | |
| 573 | const { app: tui } = createForgeApp( | |
| 574 | app, | |
| 575 | { | |
| 576 | sshUsername: "alice", | |
| 577 | remoteAddress: "127.0.0.1", | |
| 578 | fingerprint: "SHA256:test", | |
| 579 | user: alice, | |
| 580 | }, | |
| 581 | { terminal, exitHooks: false }, | |
| 582 | ); | |
| 583 | tui.start(); | |
| 584 | await settleApp(tui); | |
| 585 | for (const k of [":", "Conversations", "\r", "\r"]) { | |
| 586 | terminal.feed(k); | |
| 587 | await settleApp(tui); | |
| 588 | } | |
| 589 | const text = tui.screen.toText(); | |
| 590 | tui.stop?.(); | |
| 591 | expect(text).toContain("Working now · nothing running"); | |
| 592 | expect(text).toContain("quiet row: idle"); | |
| 593 | expect(text).toContain("1. [done] Check the crew"); | |
| 594 | expect(text).not.toContain("::show c1"); | |
| 595 | }); | |
| 596 | }); |
test/talk-page.test.ts +17 −1
| @@ -382,7 +382,7 @@ describe("the page", () => { | ||
| 382 | 382 | test("the page's own bytes are held: stylesheet and script stay small", async () => { |
| 383 | 383 | const { talkCss, talkJs } = await import("../src/web/pages/talk_client.ts"); |
| 384 | 384 | expect(Buffer.byteLength(talkCss)).toBeLessThan(12_000); |
| 385 | expect(Buffer.byteLength(talkJs)).toBeLessThan(26_700); | |
| 385 | expect(Buffer.byteLength(talkJs)).toBeLessThan(26_900); | |
| 386 | 386 | say(alice, "agent", "```ts\nlet x = 1;\n```"); |
| 387 | 387 | const page = await get("/talk", alice); |
| 388 | 388 | const size = (await page.arrayBuffer()).byteLength; |
| @@ -456,6 +456,22 @@ describe("the page", () => { | ||
| 456 | 456 | expect(t.bodies.at(-1)).toMatchObject({ text: "do this instead", during: "steer" }); |
| 457 | 457 | }); |
| 458 | 458 | |
| 459 | test("a choice is answered once: its press sends the option and stills every choice button in the log", async () => { | |
| 460 | const t = await boot(); | |
| 461 | const choices = (q: string) => `<div class="talk-choices"><p>${q}</p><div class="talk-choices-options"><form method="post" action="/talk/c1" data-starter><input type="hidden" name="text" value="Stop it" /><button>Stop it</button></form><form method="post" action="/talk/c1" data-starter><input type="hidden" name="text" value="Leave it" /><button>Leave it</button></form></div></div>`; | |
| 462 | t.emit("t-2", `<li class="talk-turn talk-agent" id="t-2"><div class="talk-body">${choices("Stop the run?")}</div></li>`); | |
| 463 | t.emit("t-3", `<li class="talk-turn talk-agent" id="t-3"><div class="talk-body">${choices("Stop the other?")}</div></li>`); | |
| 464 | const buttons = [...t.doc.querySelectorAll(".talk-choices button")]; | |
| 465 | expect(buttons).toHaveLength(4); | |
| 466 | t.doc.querySelector(".talk-choices form").dispatchEvent(new t.window.Event("submit", { bubbles: true, cancelable: true })); | |
| 467 | await tick(); | |
| 468 | expect(t.sent.at(-1)).toBe("Stop it"); | |
| 469 | expect(buttons.every((b: { disabled: boolean }) => b.disabled)).toBe(true); | |
| 470 | // The keyboard lands back in the message box, not at the top of the page. | |
| 471 | expect(t.doc.activeElement).toBe(t.box); | |
| 472 | expect(t.sent.filter((s) => s === "Stop it")).toHaveLength(1); | |
| 473 | }); | |
| 474 | ||
| 459 | 475 | const boot = async (user = "u1", store: Record<string, string> = {}, conv = "c1") => { |
| 460 | 476 | const sources: Array<{ on: Record<string, (e: { data: string }) => void> }> = []; |
| 461 | 477 | const { Window } = await import("happy-dom"); |
new above
offline