Public: anyone can read this; the crew can change it.
A shown result's buttons ask for the kept card's call on the forge's own card surface, once a reply and within caps #16285
Check · Review · Land · Live done — Landed and live in production.
talk/05-act → main 0 commits 1 thread · 1 unresolved
17 files
changed +835
−59
docs/design/areas/talk.md +5 −3
| @@ -70,9 +70,11 @@ On a phone the conversations list is its own view (`?chats=1`), reached from the | ||
| 70 | 70 | |
| 71 | 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 | - `.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 | - `.talk-card-from` — the quiet line under a card: the call in plain words and "as of" its time. | |
| 75 | - `.talk-card-missing` — "Result not found." where a handle names no card of this conversation (markup only). | |
| 73 | - `.talk-card` — a shown result: the forge's data, bare, set apart from the agent's words by a hairline on its start side; a wide card scrolls inside itself, never the page. | |
| 74 | - `.talk-card-title` — the forge's mark (`anvil`), the card's title and status. | |
| 75 | - `.talk-card-from` — the quiet line under the title: the call in plain words and "as of" its time. | |
| 76 | - `.talk-card-acts`, `.talk-card-act` — the card's buttons, each a plain `.btn` in its own form; a pressed one is a still "Asked" (`.talk-card-asked`, markup only), and a card past 10 minutes says so with Ask again. | |
| 77 | - `.talk-card-missing` — "Result not found." where a handle names no card of this conversation, and the one line saying how many placings and blocks past the caps were left as text (markup only); `.talk-card-again` is the one-line pointer a repeated placing draws to the first (markup only). | |
| 76 | 78 | - `.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 | 79 | - `.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 | 80 | - `.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. |
docs/features/talk-voice.md +28 −5
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | --- |
| 2 | 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 | |
| 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 | |
| 4 | 4 | --- |
| 5 | 5 | # Talk's voice: shown results and agent blocks |
| 6 | 6 | |
| @@ -14,13 +14,36 @@ When a tool answers the forge's agent in a conversation and the answer has a car | ||
| 14 | 14 | Shown result c7: a line `::show c7` in your reply draws this result for the person. |
| 15 | 15 | |
| 16 | 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. | |
| 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, bare, set apart from the agent's words by a hairline on its start side: a head with the forge's mark, its title and status, and under them, small and muted, "From the forge: <the call in plain words> · as of 14:02 UTC"; its rows, each a plain row that opens its page; its buttons, at the end, each a plain button. The line saying where it came from, with its time, is what no reply's Markdown carries: a reply that quotes a card's words is a quote. A card with no rows is that head on one line. 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 | 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. | |
| 19 | - Handles count up per conversation: `c1`, `c2`, and so on. The newest 200 cards of a conversation are kept, and they go, with their presses, when the conversation goes. A card over 16,000 characters of JSON, or a card of nothing (no rows and no buttons), is not kept and its answer carries no handle. | |
| 21 | 20 | - 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. |
| 21 | - A page reads every card its turns place, and which of their buttons were pressed, in one statement (`voiceOf`, `src/web/talk_parts.ts`). | |
| 22 | - One reply draws a card once: a later `::show` of the same handle is a one-line pointer to the first. One reply draws at most 10 cards, 10 pointers and 6 blocks (`VOICE_CAPS`, `src/core/talk_voice.ts`); past them a line or a block stays the text it is, and one quiet line says how many. The terminal and the reply being written keep the same caps. | |
| 22 | 23 | - 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 | |
| 25 | ### Buttons on a shown result | |
| 26 | ||
| 27 | A card's buttons post only the card's id and which button (`a0`, or `r3.0` for a row's button) to `POST /talk/act`, from the person's own signed-in session on the same origin; a token is refused (403), another site is refused. The tool and its arguments are read from the kept card, never from the request. A press first checks that the forge would still let the person make the call: a call that plans first is planned as them now, and one the tool refuses is not offered. A press never writes: it keeps the call as a held write and draws the ordinary Do it and Not now turn, with the forge's own sentence for it (`confirmSentence`, `src/crew/conversation_ask.ts`) and the card it came from ("From the result shown above: Working now."). The button is claimed only once that confirm is kept, and is then drawn still, reading Asked, even after Not now. Do it then runs it once, as the person, now, so access is checked again at that moment however old the card, the way every confirmed call runs (`sayYes`, `src/actions/conversation_confirms.ts`), and leaves the same result turn. Refusals, each said in words: | |
| 28 | ||
| 29 | - another person's card, or a button that does not exist: not found (404); | |
| 30 | - a button not on the list below: not done (409), and the page does not draw it; | |
| 31 | - a call the tool would refuse the person now: not offered (403); | |
| 32 | - a second press of the same button: not done again (409); | |
| 33 | - a conversation already holding its most confirms: not done (409), and the button stays to press again; | |
| 34 | - a card more than 10 minutes old: not done (410), and a turn in the thread says so, once a card however often it is pressed; no button is claimed; the page draws an old card without its buttons and offers Ask again, which sends "Show result c7 again, fresh." | |
| 35 | ||
| 36 | The buttons drawn on Talk (`ACTS`, `src/actions/talk_act.ts`); none takes an argument from a row's words: | |
| 37 | ||
| 38 | | Card | Button | | |
| 39 | | --- | --- | | |
| 40 | | A planned bulk decision (`asks_act` plan) | Confirm (`dryRun: false`) | | |
| 41 | | Working now (`now`, `crew`) | Stop | | |
| 42 | | Archive | Archive, Wake | | |
| 43 | | The Later gate (`held`) | Close the done ones | | |
| 44 | ||
| 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 | ||
| 24 | 47 | ## Agent blocks |
| 25 | 48 | |
| 26 | 49 | 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. |
| @@ -38,7 +61,7 @@ choices | ||
| 38 | 61 | |
| 39 | 62 | ## Other doors |
| 40 | 63 | |
| 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. | |
| 64 | - 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. `b` there lists the buttons of the shown results that are still fresh, each named by its label and card; Enter presses one through the same `pressCard` (`src/actions/talk_act.ts`), so the thread draws the same Do it / Not now, answered on the Confirms screen. `GET /api/v1/conversation/turns` carries a reply printed that way as `plain` beside its raw text, and `forge talk` prints it. | |
| 42 | 65 | - The Markdown download (`src/core/conversation_markdown.ts`) keeps the reply's raw text, `::show` lines and `forge` blocks included. |
| 43 | 66 | - 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 | 67 |
src/actions/talk_act.ts added +147
| @@ -0,0 +1,147 @@ | ||
| 1 | /** | |
| 2 | * A press of a shown result's button on /talk (docs/features/talk-voice.md). The page posts only | |
| 3 | * the kept card's id and which of its buttons; the tool and its arguments are read from the kept | |
| 4 | * card, never from the request, so a press asks for exactly what the forge drew. A press never | |
| 5 | * writes: it keeps the call as a held write and draws the ordinary Do it / Not now turn with the | |
| 6 | * forge's own confirm sentence (`crew/conversation_ask.ts`), and the person's Do it runs it | |
| 7 | * once, as a confirmed call runs (`actions/conversation_confirms.ts`, `sayYes`). | |
| 8 | * | |
| 9 | * Refused: another person's card (`not_found`, the usual ambiguity), a button that needs typed | |
| 10 | * words, a button not on `ACTS`, a call that plans first and whose plan the tool refuses the | |
| 11 | * person now, a second press of the same button, and any press on a card older than | |
| 12 | * `CARD_FRESH_MS`, which answers with a turn saying so (once a card) instead of a stale confirm. A | |
| 13 | * button is claimed only once its confirm is kept: a refused or full press leaves it to press | |
| 14 | * again. | |
| 15 | * | |
| 16 | * Who is asking is decided at the door (the person's own session, same origin), so this takes a | |
| 17 | * person who already passed it. | |
| 18 | */ | |
| 19 | ||
| 20 | import { appendTurn, getConversation } from "../core/conversations.ts"; | |
| 21 | import { cardById, pressOnce, unpress, type ShownCard } from "../core/talk_voice.ts"; | |
| 22 | import { hold } from "../core/fence.ts"; | |
| 23 | import type { User } from "../core/users.ts"; | |
| 24 | import { confirmSentence } from "../crew/conversation_ask.ts"; | |
| 25 | import { tooBigToApprove } from "../crew/conversation_confirm.ts"; | |
| 26 | import type { Ctx } from "../http/context.ts"; | |
| 27 | import { loadMcp } from "../http/mcp/load.ts"; | |
| 28 | import type { CardAction, CardKind } from "../web/studio/cards.ts"; | |
| 29 | ||
| 30 | /** A kept card acts for ten minutes, the same time a held write waits for its yes. */ | |
| 31 | export const CARD_FRESH_MS = 600_000; | |
| 32 | ||
| 33 | type Args = Readonly<Record<string, unknown>>; | |
| 34 | ||
| 35 | /** | |
| 36 | * The buttons a press may ask for, by tool: the card kinds that draw them and the arguments they | |
| 37 | * carry. Each was read against `cardFor` (`web/studio/cards.ts`): none takes an argument from a | |
| 38 | * row's words, which may quote someone else's text. Every one is held for the person's Do it. | |
| 39 | * | |
| 40 | * - `asks_act` with `dryRun: false`: the Confirm button under a planned bulk decision, whose | |
| 41 | * action and items are the ones the plan was made from (the plan's rows are on the card). Like | |
| 42 | * every button here, its press only draws Do it / Not now; the plan is applied on Do it. | |
| 43 | * - `stop`: Stop under a run of the crew; the repository and run id are the forge's. | |
| 44 | * - `archive`: Archive or Wake under an archive answer; the names are the forge's rows. | |
| 45 | * - `held`: Close under the Later gate's review; the numbers are only those the card shows, and the | |
| 46 | * digest is the review's. | |
| 47 | * | |
| 48 | * Left out, each refused as `not_allowed`: `asks_act` with no `dryRun: false` (Ship, Decline, | |
| 49 | * Decide and Undo on an asks card only plan, and a plan's own card is not drawn back), `limb` undo | |
| 50 | * (its card leaves out `dryRun: false`, so the tool refuses it), and `tell` (it takes typed words). | |
| 51 | */ | |
| 52 | export const ACTS: Readonly<Record<string, { readonly kinds: readonly CardKind[]; readonly args: (a: Args) => boolean }>> = { | |
| 53 | asks_act: { kinds: ["asks"], args: (a) => a["dryRun"] === false && a["action"] !== "undo" }, | |
| 54 | stop: { kinds: ["crew", "run"], args: (a) => typeof a["repo"] === "string" && typeof a["run"] === "string" }, | |
| 55 | archive: { kinds: ["app"], args: () => true }, | |
| 56 | held: { kinds: ["held"], args: (a) => Array.isArray(a["apply"]) }, | |
| 57 | }; | |
| 58 | ||
| 59 | /** Whether a press may ask for this button of a card of `kind`. */ | |
| 60 | export const mayAct = (kind: CardKind, action: CardAction): boolean => { | |
| 61 | const act = ACTS[action.tool]; | |
| 62 | return action.words !== true && act !== undefined && act.kinds.includes(kind) && act.args(action.args); | |
| 63 | }; | |
| 64 | ||
| 65 | /** Which button: `a<i>` for the card's own, `r<row>.<i>` for a row's. */ | |
| 66 | export const ACTION_PATH = /^(?:a(\d{1,3})|r(\d{1,3})\.(\d{1,3}))$/; | |
| 67 | ||
| 68 | /** The button `path` names on a card, or undefined. */ | |
| 69 | export function actionAt(card: ShownCard["card"], path: string): CardAction | undefined { | |
| 70 | const m = ACTION_PATH.exec(path); | |
| 71 | if (m === null) return undefined; | |
| 72 | if (m[1] !== undefined) return card.actions[Number(m[1])]; | |
| 73 | return card.rows[Number(m[2])]?.actions?.[Number(m[3])]; | |
| 74 | } | |
| 75 | ||
| 76 | /** Whether a kept card is still fresh enough to act on. */ | |
| 77 | export const fresh = (createdAt: string, now: number = Date.now()): boolean => now - Date.parse(createdAt) < CARD_FRESH_MS; | |
| 78 | ||
| 79 | export const CARD_ID = /^[0-9a-z]{1,40}$/; | |
| 80 | ||
| 81 | /** The claim a card's first stale press makes, so the thread says it once. */ | |
| 82 | const STALE = "stale"; | |
| 83 | ||
| 84 | /** Why a press did nothing, with the status the page answers and its words. */ | |
| 85 | export const PRESS_REFUSED = { | |
| 86 | not_found: [404, "no such result of yours"], | |
| 87 | not_allowed: [409, "this button does not act from Talk yet; ask the forge to do it"], | |
| 88 | pressed: [409, "this button was already pressed; it does nothing twice"], | |
| 89 | stale: [410, "this result is more than 10 minutes old, so nothing was done; ask again for a fresh one"], | |
| 90 | too_big: [422, "what this button would send is too large to show you first"], | |
| 91 | full: [409, "too many confirms are waiting in this conversation; answer one first"], | |
| 92 | forbidden: [403, "this action is not yours to take"], | |
| 93 | } as const; | |
| 94 | ||
| 95 | export type PressRefusal = keyof typeof PRESS_REFUSED; | |
| 96 | ||
| 97 | export type Pressed = { ok: false; error: PressRefusal; conversationId?: string } | { ok: true; conversationId: string; confirm: string }; | |
| 98 | ||
| 99 | /** | |
| 100 | * The person's press of button `path` on their kept card `cardId`: the confirm it drew, or why not. | |
| 101 | */ | |
| 102 | export async function pressCard(ctx: Ctx, user: User, cardId: string, path: string, now: number = Date.now()): Promise<Pressed> { | |
| 103 | const shown = CARD_ID.test(cardId) ? cardById(ctx.app.db, user.id, cardId) : undefined; | |
| 104 | const conversation = shown === undefined ? undefined : getConversation(ctx.app.db, user.id, shown.via.slice("conversation:".length)); | |
| 105 | if (shown === undefined || conversation === undefined) return { ok: false, error: "not_found" }; | |
| 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 }; | |
| 110 | if (tooBigToApprove(action.args)) return { ok: false, error: "too_big", ...at }; | |
| 111 | // What the person may not do is never asked for in their name. | |
| 112 | const { TOOLS } = await loadMcp(); | |
| 113 | const tool = TOOLS.find((t) => t.name === action.tool); | |
| 114 | if (tool === undefined || ((tool.adminOnly === true || tool.needsAdminScope === true) && !user.isAdmin)) return { ok: false, error: "forbidden", ...at }; | |
| 115 | if (shown.pressed.includes(path)) return { ok: false, error: "pressed", ...at }; | |
| 116 | if (!fresh(shown.createdAt, now)) { | |
| 117 | // Said in the thread, where the person pressed, as a call that did not go through, once a card: | |
| 118 | // the first stale press claims `stale`, so pressing an old card again adds nothing (a page | |
| 119 | // left open, a terminal). Its buttons are not drawn again. | |
| 120 | if (pressOnce(ctx.app.db, shown.id, STALE, user.id, now)) | |
| 121 | appendTurn(ctx.app.db, user.id, conversation.id, { role: "tool", text: JSON.stringify({ confirm: "", tool: action.tool, done: false, error: "stale", message: PRESS_REFUSED.stale[1], says: "This result is more than 10 minutes old, so nothing was done; ask again for a fresh one." }) }); | |
| 122 | return { ok: false, error: "stale", ...at }; | |
| 123 | } | |
| 124 | const args = { ...action.args }; | |
| 125 | // A call that plans first is planned as the person now, so one the tool would refuse them is | |
| 126 | // never offered as Do it. | |
| 127 | if (tool.dryByDefault === true) { | |
| 128 | const asPerson: Ctx = { ...ctx, auth: { ...ctx.auth, user, scope: user.isAdmin ? "admin" : "rw" } }; | |
| 129 | const plan = await Promise.resolve(tool.run(asPerson, user, { ...args, dryRun: true })); | |
| 130 | if (!plan.ok) return { ok: false, error: "forbidden", ...at }; | |
| 131 | } | |
| 132 | // Claimed, kept and said in one transaction, with nothing awaited: a second press finds the | |
| 133 | // claim, and a press that kept nothing (the conversation's confirms are full) claims nothing. | |
| 134 | const db = ctx.app.db; | |
| 135 | const kept = db.transaction((): string | "pressed" | "full" => { | |
| 136 | if (!pressOnce(db, shown.id, path, user.id, now)) return "pressed"; | |
| 137 | const held = hold(db, shown.via, user.id, action.tool, args, now); | |
| 138 | if (held === null) { | |
| 139 | unpress(db, shown.id, path); | |
| 140 | return "full"; | |
| 141 | } | |
| 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}.` }) }); | |
| 143 | return held; | |
| 144 | })(); | |
| 145 | if (kept === "pressed" || kept === "full") return { ok: false, error: kept, ...at }; | |
| 146 | return { ok: true, confirm: kept, ...at }; | |
| 147 | } |
src/core/account_purge.ts +1
| @@ -68,6 +68,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 68 | 68 | "comment.origin_author": { do: "none", why: "the outside author's name a mirrored comment came with" }, |
| 69 | 69 | // The results the forge kept for their own conversations' agent (`core/talk_voice.ts`). |
| 70 | 70 | "conversation_card.user_id": DELETE, |
| 71 | "conversation_card_press.user_id": DELETE, | |
| 71 | 72 | "conversation_find.user_id": DELETE, |
| 72 | 73 | "curated_pack_change.actor": FORMER, |
| 73 | 74 | "decision.by": FORMER, |
src/core/migration-pins/20261124034500-conversation-card-press.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | b53c00bc9866e17ddadebb912acb24c31754a56831f9f23c4098dcfb919fe18a |
src/core/migrations/20261124034500-conversation-card-press.ts added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | // A press of a shown result's button on /talk (`actions/talk_act.ts`): one row per card and | |
| 2 | // button, so a second press of the same button does nothing. A card's presses go with the card, | |
| 3 | // whichever way it goes (pruned past the newest 200, or with its conversation). | |
| 4 | export default ` | |
| 5 | CREATE TABLE conversation_card_press ( | |
| 6 | card_id TEXT NOT NULL, | |
| 7 | action TEXT NOT NULL, | |
| 8 | user_id TEXT NOT NULL, | |
| 9 | pressed_at TEXT NOT NULL, | |
| 10 | PRIMARY KEY (card_id, action) | |
| 11 | ); | |
| 12 | CREATE TRIGGER conversation_card_press_gone AFTER DELETE ON conversation_card BEGIN | |
| 13 | DELETE FROM conversation_card_press WHERE card_id = old.id; | |
| 14 | END; | |
| 15 | `; |
src/core/talk_voice.ts +111 −19
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | */ |
| 22 | 22 | |
| 23 | 23 | import type { Database } from "bun:sqlite"; |
| 24 | import type { Card, CardRow } from "../web/studio/cards.ts"; | |
| 24 | import type { Card, CardAction, CardRow } from "../web/studio/cards.ts"; | |
| 25 | 25 | import { id } from "../kernel/id.ts"; |
| 26 | 26 | import { unsaid } from "../crew/conversation_ask.ts"; |
| 27 | 27 | |
| @@ -40,6 +40,8 @@ export interface ShownCard { | ||
| 40 | 40 | readonly said: string; |
| 41 | 41 | readonly card: Card; |
| 42 | 42 | readonly createdAt: string; |
| 43 | /** Its buttons already pressed (`a0`, `r3.0`): each asked once, read with the card. */ | |
| 44 | readonly pressed: readonly string[]; | |
| 43 | 45 | } |
| 44 | 46 | |
| 45 | 47 | interface Row { |
| @@ -51,6 +53,7 @@ interface Row { | ||
| 51 | 53 | said: string; |
| 52 | 54 | card: string; |
| 53 | 55 | created_at: string; |
| 56 | pressed?: string; | |
| 54 | 57 | } |
| 55 | 58 | |
| 56 | 59 | type Obj = Record<string, unknown>; |
| @@ -58,9 +61,24 @@ const isObj = (v: unknown): v is Obj => | ||
| 58 | 61 | typeof v === "object" && v !== null && !Array.isArray(v); |
| 59 | 62 | const isStr = (v: unknown): v is string => typeof v === "string"; |
| 60 | 63 | |
| 64 | /** An action as kept, or undefined when it is not one. */ | |
| 65 | function actionOf(v: unknown): CardAction | undefined { | |
| 66 | if (!isObj(v) || !isStr(v["label"]) || !isStr(v["tool"]) || !isObj(v["args"])) | |
| 67 | return undefined; | |
| 68 | return { | |
| 69 | label: v["label"], | |
| 70 | tool: v["tool"], | |
| 71 | args: v["args"], | |
| 72 | ...(v["words"] === true ? { words: true as const } : {}), | |
| 73 | }; | |
| 74 | } | |
| 75 | ||
| 61 | 76 | /** A row as kept, or undefined when it is not one. */ |
| 62 | 77 | function rowOf(v: unknown): CardRow | undefined { |
| 63 | 78 | if (!isObj(v) || !isStr(v["label"]) || !isStr(v["value"])) return undefined; |
| 79 | const actions = Array.isArray(v["actions"]) | |
| 80 | ? v["actions"].map(actionOf).filter((a) => a !== undefined) | |
| 81 | : []; | |
| 64 | 82 | const depth = Number.isInteger(v["depth"]) |
| 65 | 83 | ? Math.max(0, Math.min(8, v["depth"] as number)) |
| 66 | 84 | : 0; |
| @@ -69,13 +87,11 @@ function rowOf(v: unknown): CardRow | undefined { | ||
| 69 | 87 | value: v["value"], |
| 70 | 88 | ...(isStr(v["link"]) ? { link: v["link"] } : {}), |
| 71 | 89 | ...(depth > 0 ? { depth } : {}), |
| 90 | ...(actions.length > 0 ? { actions } : {}), | |
| 72 | 91 | }; |
| 73 | 92 | } |
| 74 | 93 | |
| 75 | /** | |
| 76 | * A card read back from its JSON, shape checked; undefined when the text is not one. A kept card | |
| 77 | * has no buttons: what it shows is its rows. | |
| 78 | */ | |
| 94 | /** A card read back from its JSON, shape checked; undefined when the text is not one. */ | |
| 79 | 95 | export function readCard(text: string): Card | undefined { |
| 80 | 96 | let v: unknown; |
| 81 | 97 | try { |
| @@ -88,7 +104,8 @@ export function readCard(text: string): Card | undefined { | ||
| 88 | 104 | !isStr(v["kind"]) || |
| 89 | 105 | !isStr(v["title"]) || |
| 90 | 106 | !isStr(v["status"]) || |
| 91 | !Array.isArray(v["rows"]) | |
| 107 | !Array.isArray(v["rows"]) || | |
| 108 | !Array.isArray(v["actions"]) | |
| 92 | 109 | ) |
| 93 | 110 | return undefined; |
| 94 | 111 | return { |
| @@ -96,7 +113,7 @@ export function readCard(text: string): Card | undefined { | ||
| 96 | 113 | title: v["title"], |
| 97 | 114 | status: v["status"], |
| 98 | 115 | rows: v["rows"].map(rowOf).filter((r) => r !== undefined), |
| 99 | actions: [], | |
| 116 | actions: v["actions"].map(actionOf).filter((a) => a !== undefined), | |
| 100 | 117 | }; |
| 101 | 118 | } |
| 102 | 119 | |
| @@ -113,6 +130,7 @@ const shownOf = (r: Row): ShownCard | undefined => { | ||
| 113 | 130 | said: r.said, |
| 114 | 131 | card, |
| 115 | 132 | createdAt: r.created_at, |
| 133 | pressed: (JSON.parse(r.pressed ?? "[]") as unknown[]).filter((x): x is string => typeof x === "string"), | |
| 116 | 134 | }; |
| 117 | 135 | }; |
| 118 | 136 | |
| @@ -128,8 +146,7 @@ const rooted = (link: string, origin: string): string => | ||
| 128 | 146 | |
| 129 | 147 | /** |
| 130 | 148 | * Keep a card the forge drew for the agent of `via`; its number in the conversation, or undefined |
| 131 | * when it was too big to keep. The oldest past `CARDS_KEPT` go. What is kept is what the page | |
| 132 | * draws: the title, the status and the rows, never a button. | |
| 149 | * when it was too big to keep. The oldest past `CARDS_KEPT` go, and their presses with them. | |
| 133 | 150 | */ |
| 134 | 151 | export function recordCard( |
| 135 | 152 | db: Database, |
| @@ -142,13 +159,10 @@ export function recordCard( | ||
| 142 | 159 | now: number = Date.now(), |
| 143 | 160 | ): number | undefined { |
| 144 | 161 | const kept: Card = { |
| 145 | kind: card.kind, | |
| 146 | title: card.title, | |
| 147 | status: card.status, | |
| 148 | rows: card.rows.map(({ actions: _, ...r }) => | |
| 162 | ...card, | |
| 163 | rows: card.rows.map((r) => | |
| 149 | 164 | r.link === undefined ? r : { ...r, link: rooted(r.link, origin) }, |
| 150 | 165 | ), |
| 151 | actions: [], | |
| 152 | 166 | }; |
| 153 | 167 | const text = JSON.stringify(kept); |
| 154 | 168 | if (text.length > CARD_CHARS_MAX) return undefined; |
| @@ -183,6 +197,9 @@ export function recordCard( | ||
| 183 | 197 | })(); |
| 184 | 198 | } |
| 185 | 199 | |
| 200 | /** A card's pressed buttons, read in the same statement as the card (its primary key leads). */ | |
| 201 | const PRESSED = "(SELECT json_group_array(p.action) FROM conversation_card_press p WHERE p.card_id = c.id)"; | |
| 202 | ||
| 186 | 203 | /** The person's kept cards of the conversation `via` names with these numbers: one statement. */ |
| 187 | 204 | export function cardsOf( |
| 188 | 205 | db: Database, |
| @@ -196,7 +213,7 @@ export function cardsOf( | ||
| 196 | 213 | .query< |
| 197 | 214 | Row, |
| 198 | 215 | [string, string, string] |
| 199 | >("SELECT * FROM conversation_card WHERE via = ?1 AND user_id = ?2 AND n IN (SELECT value FROM json_each(?3))") | |
| 216 | >(`SELECT c.*, ${PRESSED} AS pressed FROM conversation_card c WHERE c.via = ?1 AND c.user_id = ?2 AND c.n IN (SELECT value FROM json_each(?3))`) | |
| 200 | 217 | .all(via, userId, JSON.stringify([...new Set(ns)])); |
| 201 | 218 | for (const r of rows) { |
| 202 | 219 | const shown = shownOf(r); |
| @@ -205,18 +222,65 @@ export function cardsOf( | ||
| 205 | 222 | return out; |
| 206 | 223 | } |
| 207 | 224 | |
| 225 | /** One kept card by id, only when it is the person's; anything else is nothing. */ | |
| 226 | export function cardById( | |
| 227 | db: Database, | |
| 228 | userId: string, | |
| 229 | cardId: string, | |
| 230 | ): ShownCard | undefined { | |
| 231 | const row = db | |
| 232 | .query< | |
| 233 | Row, | |
| 234 | [string, string] | |
| 235 | >(`SELECT c.*, ${PRESSED} AS pressed FROM conversation_card c WHERE c.id = ?1 AND c.user_id = ?2`) | |
| 236 | .get(cardId, userId); | |
| 237 | return row === null ? undefined : shownOf(row); | |
| 238 | } | |
| 239 | ||
| 240 | /** Give a claim back: the press it stood for kept nothing, so the button may be pressed again. */ | |
| 241 | export function unpress(db: Database, cardId: string, action: string): void { | |
| 242 | db.query("DELETE FROM conversation_card_press WHERE card_id = ?1 AND action = ?2").run(cardId, action); | |
| 243 | } | |
| 244 | ||
| 245 | /** Claim one press of a card's button: true the first time, false ever after. */ | |
| 246 | export function pressOnce( | |
| 247 | db: Database, | |
| 248 | cardId: string, | |
| 249 | action: string, | |
| 250 | userId: string, | |
| 251 | now: number = Date.now(), | |
| 252 | ): boolean { | |
| 253 | return ( | |
| 254 | db | |
| 255 | .query( | |
| 256 | "INSERT OR IGNORE INTO conversation_card_press (card_id, action, user_id, pressed_at) VALUES (?1,?2,?3,?4)", | |
| 257 | ) | |
| 258 | .run(cardId, action, userId, new Date(now).toISOString()).changes === 1 | |
| 259 | ); | |
| 260 | } | |
| 261 | ||
| 208 | 262 | export type PlanState = "todo" | "doing" | "done" | "skipped"; |
| 209 | 263 | export const PLAN_STATES: readonly PlanState[] = ["todo", "doing", "done", "skipped"]; |
| 210 | 264 | |
| 211 | 265 | export type Part = |
| 212 | 266 | | { readonly kind: "text"; readonly text: string } |
| 213 | | { readonly kind: "show"; readonly n: number } | |
| 267 | /** `again`: a handle this reply already placed, drawn as a pointer to the first. */ | |
| 268 | | { readonly kind: "show"; readonly n: number; readonly again?: true } | |
| 269 | /** How many placings and blocks past `VOICE_CAPS` were left as text. */ | |
| 270 | | { readonly kind: "over"; readonly cards: number; readonly blocks: number } | |
| 214 | 271 | | { readonly kind: "fold"; readonly summary: string } |
| 215 | 272 | | { readonly kind: "unfold" } |
| 216 | 273 | | { readonly kind: "choices"; readonly question: string; readonly options: readonly string[] } |
| 217 | 274 | | { readonly kind: "plan"; readonly steps: readonly { readonly text: string; readonly state: PlanState }[] } |
| 218 | 275 | | { readonly kind: "known"; readonly known: readonly string[]; readonly suspected: readonly string[]; readonly unknown: readonly string[] }; |
| 219 | 276 | |
| 277 | /** | |
| 278 | * The most one reply draws: distinct cards, pointers back to one already drawn, and blocks. Past | |
| 279 | * them a line or a block stays the text it is, and one quiet line says how many, so a reply cannot | |
| 280 | * draw a page of megabytes. | |
| 281 | */ | |
| 282 | export const VOICE_CAPS = { cards: 10, again: 10, blocks: 6 } as const; | |
| 283 | ||
| 220 | 284 | /** The limits a block is held to; past any of them it is drawn as code. */ |
| 221 | 285 | export const VOICE_LIMITS = { |
| 222 | 286 | question: 300, |
| @@ -322,6 +386,10 @@ export function voiceParts(text: string): Part[] { | ||
| 322 | 386 | buf = []; |
| 323 | 387 | }; |
| 324 | 388 | let folded = false; |
| 389 | const seen = new Set<number>(); | |
| 390 | let again = 0; | |
| 391 | let blocks = 0; | |
| 392 | const over = { cards: 0, blocks: 0 }; | |
| 325 | 393 | for (let i = 0; i < src.length; i++) { |
| 326 | 394 | const l = src[i]!; |
| 327 | 395 | const fenced = FORGE_FENCE.exec(l); |
| @@ -342,10 +410,14 @@ export function voiceParts(text: string): Part[] { | ||
| 342 | 410 | } |
| 343 | 411 | const named = info[1] ?? info[2]; |
| 344 | 412 | const block = closed ? blockOf(named === undefined ? body : [named, ...body]) : undefined; |
| 345 | if (block !== undefined) { | |
| 413 | if (block !== undefined && blocks < VOICE_CAPS.blocks) { | |
| 346 | 414 | flush(); |
| 347 | 415 | parts.push(block); |
| 348 | } else buf.push(...src.slice(i, closed ? j + 1 : j)); | |
| 416 | blocks++; | |
| 417 | } else { | |
| 418 | if (block !== undefined) over.blocks++; | |
| 419 | buf.push(...src.slice(i, closed ? j + 1 : j)); | |
| 420 | } | |
| 349 | 421 | i = j; |
| 350 | 422 | continue; |
| 351 | 423 | } |
| @@ -366,8 +438,17 @@ export function voiceParts(text: string): Part[] { | ||
| 366 | 438 | } |
| 367 | 439 | const show = SHOW.exec(l); |
| 368 | 440 | if (show !== null) { |
| 441 | const n = Number(show[1]); | |
| 442 | const repeat = seen.has(n); | |
| 443 | if (repeat ? again >= VOICE_CAPS.again : seen.size >= VOICE_CAPS.cards) { | |
| 444 | over.cards++; | |
| 445 | buf.push(l); | |
| 446 | continue; | |
| 447 | } | |
| 369 | 448 | flush(); |
| 370 | parts.push({ kind: "show", n: Number(show[1]) }); | |
| 449 | if (repeat) again++; | |
| 450 | else seen.add(n); | |
| 451 | parts.push(repeat ? { kind: "show", n, again: true } : { kind: "show", n }); | |
| 371 | 452 | continue; |
| 372 | 453 | } |
| 373 | 454 | const fold = FOLD.exec(l); |
| @@ -387,6 +468,7 @@ export function voiceParts(text: string): Part[] { | ||
| 387 | 468 | } |
| 388 | 469 | flush(); |
| 389 | 470 | if (folded) parts.push({ kind: "unfold" }); |
| 471 | if (over.cards + over.blocks > 0) parts.push({ kind: "over", ...over }); | |
| 390 | 472 | // Nothing validated: the reply is drawn whole, as it was. |
| 391 | 473 | return parts.some((p) => p.kind !== "text" && p.kind !== "fold" && p.kind !== "unfold") ? parts : [{ kind: "text", text }]; |
| 392 | 474 | } |
| @@ -405,6 +487,12 @@ export const shownIn = (parts: readonly Part[]): number[] => [ | ||
| 405 | 487 | ), |
| 406 | 488 | ]; |
| 407 | 489 | |
| 490 | /** The one quiet line under a reply that placed or held more than `VOICE_CAPS` draws. */ | |
| 491 | export function overWords(cards: number, blocks: number): string { | |
| 492 | const said = [cards > 0 ? `${cards} more result${cards === 1 ? "" : "s"}` : "", blocks > 0 ? `${blocks} more block${blocks === 1 ? "" : "s"}` : ""].filter((x) => x !== ""); | |
| 493 | return `${said.join(" and ")} in this reply ${cards + blocks === 1 ? "was" : "were"} left as text.`; | |
| 494 | } | |
| 495 | ||
| 408 | 496 | /** What the page says where a handle names no kept card of this conversation. */ |
| 409 | 497 | export const NOT_FOUND_WORDS = "Result not found."; |
| 410 | 498 | |
| @@ -456,8 +544,12 @@ export function plainVoice(text: string, cards: ReadonlyMap<number, ShownCard>): | ||
| 456 | 544 | case "show": { |
| 457 | 545 | const shown = cards.get(p.n); |
| 458 | 546 | if (shown === undefined) return [NOT_FOUND_WORDS]; |
| 547 | // Drawn once a reply, as on the page; where it came from comes first. | |
| 548 | if (p.again === true) return [`(shown above: ${shown.card.title})`]; | |
| 459 | 549 | return [`From the forge: ${shown.said}, as of ${shown.createdAt.slice(0, 16).replace("T", " ")} UTC`, ...cardLines(shown.card)]; |
| 460 | 550 | } |
| 551 | case "over": | |
| 552 | return [overWords(p.cards, p.blocks)]; | |
| 461 | 553 | case "fold": |
| 462 | 554 | return [`${p.summary}:`]; |
| 463 | 555 | case "unfold": |
src/http/mcp.ts +2 −2
| @@ -150,8 +150,8 @@ function cardResult( | ||
| 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 | 152 | const card = cardFor(tool, value, ctx.url.origin, extra); |
| 153 | // A card of nothing (no rows) is not handed out: there is nothing to place. | |
| 154 | if (card === undefined || card.rows.length === 0) return []; | |
| 153 | // A card of nothing (no rows, no buttons) is not handed out: there is nothing to place. | |
| 154 | if (card === undefined || (card.rows.length === 0 && card.actions.length === 0)) return []; | |
| 155 | 155 | const n = recordCard(ctx.app.db, via, user.id, tool, stepOf(`${tool} ${JSON.stringify(args)}`)?.label ?? tool, card, ctx.url.origin); |
| 156 | 156 | return n === undefined ? [] : [{ type: "text", text: shownLine(n) }]; |
| 157 | 157 | } |
src/http/mcp/tools/issues.ts +3 −1
| @@ -70,7 +70,9 @@ export const tool: Tool = { | ||
| 70 | 70 | if (marking) for (const m of markReaders(db, repo, rows)) marked.set(m.id, m.untrusted); |
| 71 | 71 | const labels = labelsForIssues(db, rows.map((i) => i.id)); |
| 72 | 72 | const last = rows[rows.length - 1]; |
| 73 | const card = ctx.auth.through === undefined ? cardExtras(db, repo, user, rows) : undefined; | |
| 73 | // Talk's own agent gets the card's repository only (no pillar or blocker reads), so the card it | |
| 74 | // keeps for the person still links each issue to its page. | |
| 75 | const card = ctx.auth.through === undefined ? cardExtras(db, repo, user, rows) : { repo: `${repo.ownerName}/${repo.name}` }; | |
| 74 | 76 | const answer = good({ |
| 75 | 77 | items: rows.map((i) => ({ |
| 76 | 78 | number: i.number, |
src/http/server.ts +2 −1
| @@ -171,7 +171,7 @@ import { | ||
| 171 | 171 | themeSubmit, |
| 172 | 172 | } from "../web/pages/site.ts"; |
| 173 | 173 | import { talkBuild, talkPublish, talkRestore } from "../web/talk_build.ts"; |
| 174 | import { talkAgainSend, talkArchive, talkConfirm, talkDownload, talkNew, talkPin, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView } from "../web/pages/talk.ts"; | |
| 174 | import { talkAct, talkAgainSend, talkArchive, talkConfirm, talkDownload, talkNew, talkPin, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView } from "../web/pages/talk.ts"; | |
| 175 | 175 | import { |
| 176 | 176 | recoverFinish, |
| 177 | 177 | recoverOptions, |
| @@ -1244,6 +1244,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1244 | 1244 | router.add("POST", "/talk/queue/:id/cancel", talkQueueCancel); |
| 1245 | 1245 | router.add("POST", "/talk/confirm/:id", talkConfirm); |
| 1246 | 1246 | router.add("POST", "/talk/undo/:turn", talkUndo); |
| 1247 | router.add("POST", "/talk/act", talkAct); | |
| 1247 | 1248 | router.add("POST", "/talk/new", talkNew); |
| 1248 | 1249 | router.add("POST", "/talk/build", talkBuild); |
| 1249 | 1250 | router.add("GET", "/talk/:id", talkView); |
src/kernel/body_caps.ts +4
| @@ -96,6 +96,10 @@ export const BODY_CAPS = { | ||
| 96 | 96 | bytes: 5 * MIB, |
| 97 | 97 | reason: "a picture attached to a conversation: a screenshot or a photo; the limit is stated to the person in every refusal", |
| 98 | 98 | }, |
| 99 | talkAct: { | |
| 100 | bytes: 1 * KIB, | |
| 101 | reason: "a press of a shown result's button on /talk: a card id and which button, nothing else is read", | |
| 102 | }, | |
| 99 | 103 | buildShot: { |
| 100 | 104 | bytes: 3 * MIB, |
| 101 | 105 | reason: "one screenshot a build uploads of itself: a single picture", |
src/tui/screens/talk_chats.ts +41 −2
| @@ -38,7 +38,8 @@ import { style } from "../term/style.ts"; | ||
| 38 | 38 | import { truncate, wrap } from "../term/width.ts"; |
| 39 | 39 | import type { Session } from "../session.ts"; |
| 40 | 40 | import { fill, len, split } from "../ui/layout.ts"; |
| 41 | import { ListState, Scroll, ago, drawLines, drawList, promptScreen, type ListRow } from "./common.ts"; | |
| 41 | import { ListState, Scroll, ago, drawLines, drawList, pickerScreen, promptScreen, runAsync, type ListRow, type PickItem } from "./common.ts"; | |
| 42 | import { fresh, mayAct, pressCard, PRESS_REFUSED } from "../../actions/talk_act.ts"; | |
| 42 | 43 | |
| 43 | 44 | const BAD_TITLE = `A title is up to ${TITLE_MAX} characters, on one line.`; |
| 44 | 45 | |
| @@ -86,7 +87,9 @@ function downloadScreen(f: Session, ctx: Ctx, chat: Conversation): Screen { | ||
| 86 | 87 | * it, that turn marked ▶. p flips to what the chat is working on, the web's |
| 87 | 88 | * pane beside the chat: the repository, what runs and where, the newest pull's |
| 88 | 89 | * diff, and the files the chat touched. Turns are read when the view opens |
| 89 | * and on r, not on every draw. | |
| 90 | * and on r, not on every draw. b lists the buttons of the results the replies show, while each | |
| 91 | * is fresh: Enter presses one through the page's own `pressCard`, which draws the same Do it / Not | |
| 92 | * now in the thread (answered under Confirms). | |
| 90 | 93 | */ |
| 91 | 94 | function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Screen { |
| 92 | 95 | const scroll = new Scroll(); |
| @@ -163,6 +166,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 163 | 166 | binding(["1", "2", "3"], "starter"), |
| 164 | 167 | binding(["r"], "reload"), |
| 165 | 168 | binding(["p"], "pane"), |
| 169 | binding(["b"], "a result's buttons"), | |
| 166 | 170 | binding(["d", "x"], "export as Markdown"), |
| 167 | 171 | binding(["esc"], "back"), |
| 168 | 172 | ], |
| @@ -211,6 +215,41 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 211 | 215 | ctx.invalidate(); |
| 212 | 216 | return true; |
| 213 | 217 | } |
| 218 | if (e.key === "b") { | |
| 219 | // The buttons of the shown results, as the page draws them: fresh, allowed, not pressed. | |
| 220 | const now = Date.now(); | |
| 221 | const items: PickItem[] = [...cards.values()].filter((c) => fresh(c.createdAt, now)).flatMap((c) => [ | |
| 222 | ...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}` }] : [])), | |
| 223 | ...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}` }] : []))), | |
| 224 | ]); | |
| 225 | if (items.length === 0) { | |
| 226 | note = "No result here has a button to press now."; | |
| 227 | ctx.invalidate(); | |
| 228 | return true; | |
| 229 | } | |
| 230 | ctx.push( | |
| 231 | pickerScreen(ctx, screen, { | |
| 232 | title: "Press", | |
| 233 | items, | |
| 234 | onPick: ([picked]) => { | |
| 235 | const [cardId, path] = (picked ?? "").split(" "); | |
| 236 | runAsync(ctx, async () => { | |
| 237 | const url = new URL(f.app.config.url ?? `http://${f.app.config.host ?? "localhost"}`); | |
| 238 | const pressed = await pressCard( | |
| 239 | { app: f.app, request: new Request(url.href, { method: "POST" }), url, params: {}, auth: { user, scope: undefined, via: "none" as const }, theme: undefined }, | |
| 240 | user, | |
| 241 | cardId ?? "", | |
| 242 | path ?? "", | |
| 243 | ); | |
| 244 | note = pressed.ok ? "Do it or Not now: the confirm is in the thread; answer it under Confirms." : `Nothing was done: ${PRESS_REFUSED[pressed.error][1]}.`; | |
| 245 | load(); | |
| 246 | ctx.invalidate(); | |
| 247 | }); | |
| 248 | }, | |
| 249 | }), | |
| 250 | ); | |
| 251 | return true; | |
| 252 | } | |
| 214 | 253 | if (e.key === "d" || e.key === "x") { |
| 215 | 254 | ctx.push(downloadScreen(f, ctx, chat)); |
| 216 | 255 | return true; |
src/web/pages/talk.ts +20 −1
| @@ -55,9 +55,11 @@ import { liveBlock, subscribe } from "../../crew/conversation_live.ts"; | ||
| 55 | 55 | import { during } from "../../perf/jobs.ts"; |
| 56 | 56 | import type { Ctx } from "../../http/context.ts"; |
| 57 | 57 | import { json } from "../../http/respond.ts"; |
| 58 | import { ACTION_PATH, PRESS_REFUSED, pressCard, type Pressed } from "../../actions/talk_act.ts"; | |
| 59 | import { BODY_CAPS } from "../../kernel/body_caps.ts"; | |
| 58 | 60 | import { eventStream } from "../../http/sse.ts"; |
| 59 | 61 | import { signInFirst, forbiddenPage, notFoundPage } from "../chrome.ts"; |
| 60 | import { readForm } from "../form.ts"; | |
| 62 | import { field, readForm } from "../form.ts"; | |
| 61 | 63 | import { html, raw, type Html } from "../html.ts"; |
| 62 | 64 | import { flashTo, fragment, page, redirect } from "../layout.ts"; |
| 63 | 65 | import { linkRefs, refTarget } from "../../text/talk_links.ts"; |
| @@ -718,6 +720,23 @@ export async function talkQueueCancel(ctx: Ctx): Promise<Response> { | ||
| 718 | 720 | return flashTo(ctx, `${HERE}`, gone ? { tone: "danger", message: "That message already went." } : { tone: "success", message: "Cancelled." }); |
| 719 | 721 | } |
| 720 | 722 | |
| 723 | // POST /talk/act — a press of a shown result's button, from the person's own session. | |
| 724 | export async function talkAct(ctx: Ctx): Promise<Response> { | |
| 725 | const user = ctx.auth.user; | |
| 726 | if (user === undefined) return signInFirst(ctx); | |
| 727 | if (ctx.auth.via !== "session") return forbiddenPage(ctx, "Press this from your own signed-in browser."); | |
| 728 | const form = await readForm(ctx, "rw", BODY_CAPS.talkAct.bytes); | |
| 729 | if (form instanceof Response) return form; | |
| 730 | // The card's id and which button: everything else the press does is read from the kept card. | |
| 731 | const path = field(form, "action"); | |
| 732 | const pressed: Pressed = ACTION_PATH.test(path) ? await pressCard(ctx, user, field(form, "card"), path) : { ok: false, error: "not_found" }; | |
| 733 | const back = pressed.conversationId === undefined ? "/talk#end" : `/talk/${pressed.conversationId}`; | |
| 734 | const asJson = (ctx.request.headers.get("accept") ?? "").includes("application/json"); | |
| 735 | if (pressed.ok) return asJson ? json({ ok: true, confirm: pressed.confirm }) : flashTo(ctx, back, { tone: "success", message: "Do it or Not now: the confirm is in the thread." }); | |
| 736 | const [status, refused] = PRESS_REFUSED[pressed.error]; | |
| 737 | return asJson ? json({ ok: false, message: refused }, status) : flashTo(ctx, back, { tone: "danger", message: `Nothing was done: ${refused}.` }); | |
| 738 | } | |
| 739 | ||
| 721 | 740 | // POST /talk/confirm/:id — the person's yes or no, from their own session. |
| 722 | 741 | export async function talkConfirm(ctx: Ctx): Promise<Response> { |
| 723 | 742 | const user = ctx.auth.user; |
src/web/studio/cards.ts +7 −2
| @@ -593,7 +593,7 @@ export function cardFor( | ||
| 593 | 593 | const repo = text(made["repo"]); |
| 594 | 594 | const run = text(made["run"]); |
| 595 | 595 | status = run === "none" || run === "" ? "alive" : `alive · first run ${run}`; |
| 596 | rows.push({ label: "App", value: repo }); | |
| 596 | rows.push({ label: "App", value: repo, ...(web(origin) && slugOf(repo) ? { link: `${origin}/${repo}` } : {}) }); | |
| 597 | 597 | if (made["url"]) { |
| 598 | 598 | const url = text(made["url"]); |
| 599 | 599 | rows.push({ |
| @@ -602,7 +602,12 @@ export function cardFor( | ||
| 602 | 602 | ...(web(url) ? { link: url } : {}), |
| 603 | 603 | }); |
| 604 | 604 | } |
| 605 | if (made["issue"]) rows.push({ label: "First issue", value: `#${text(made["issue"])}` }); | |
| 605 | if (made["issue"]) { | |
| 606 | // The issue it was made with, linked to its page as every issue row is. | |
| 607 | const n = text(made["issue"]); | |
| 608 | const path = `/${repo}/issues/${n}`; | |
| 609 | rows.push({ label: "First issue", value: `#${n}`, ...(web(origin) && slugOf(repo) && /^[1-9]\d*$/.test(n) && here(origin, path) ? { link: origin + path } : {}) }); | |
| 610 | } | |
| 606 | 611 | if (made["agent"]) rows.push({ label: "Agent", value: text(made["agent"]) }); |
| 607 | 612 | rows.push({ label: "First run", value: run === "" ? "none" : run }); |
| 608 | 613 | if (repo !== "") |
src/web/talk_parts.ts +59 −15
| @@ -4,7 +4,8 @@ | ||
| 4 | 4 | * |
| 5 | 5 | * - Shown results: a `::show c<n>` line draws the card the forge kept for that handle in this |
| 6 | 6 | * conversation (`core/talk_voice.ts`), the forge's own data in a `.talk-card` with a |
| 7 | * provenance line under it. | |
| 7 | * provenance line under it; its buttons post the card's id and which button to `POST /talk/act` | |
| 8 | * (`talkAct`, `web/pages/talk.ts`), nothing else. | |
| 8 | 9 | * - Agent blocks: `choices`, `plan` and `known`, the model's own words in three shapes. |
| 9 | 10 | * |
| 10 | 11 | * Every string is escaped by the `html` tag; a card's link is a link only when it is a rooted path |
| @@ -15,10 +16,12 @@ | ||
| 15 | 16 | import type { Database } from "bun:sqlite"; |
| 16 | 17 | import type { ShownCard } from "../core/talk_voice.ts"; |
| 17 | 18 | import type { Turn } from "../core/conversations.ts"; |
| 18 | import { cardsPlaced, NOT_FOUND_WORDS, planWord, voiceParts, type Part, type PlanState } from "../core/talk_voice.ts"; | |
| 19 | import { cardsPlaced, NOT_FOUND_WORDS, overWords, planWord, voiceParts, type Part, type PlanState } from "../core/talk_voice.ts"; | |
| 20 | import { fresh, mayAct } from "../actions/talk_act.ts"; | |
| 19 | 21 | import { escapeHtml, html, raw, type Html } from "./html.ts"; |
| 20 | 22 | import type { IconName } from "./icons.ts"; |
| 21 | 23 | import { renderInline, renderMarkdown } from "./markdown.ts"; |
| 24 | import type { CardAction } from "./studio/cards.ts"; | |
| 22 | 25 | import { btn, card as surface, icon, listCard, row, time } from "./ui.ts"; |
| 23 | 26 | |
| 24 | 27 | /** What drawing a page of agent turns needs: the cards they place, and which replies are live. */ |
| @@ -36,6 +39,7 @@ export interface Voice { | ||
| 36 | 39 | readonly latestPlan?: string; |
| 37 | 40 | readonly origin: string; |
| 38 | 41 | readonly conversationId: string; |
| 42 | readonly now: number; | |
| 39 | 43 | } |
| 40 | 44 | |
| 41 | 45 | /** Each reply's parts by its text, per page: a page parses each reply once. */ |
| @@ -56,14 +60,14 @@ const partsOf = (key: object | undefined, text: string): Part[] => { | ||
| 56 | 60 | * whatever the number of turns or cards (the cards the replies place, and the person's newest |
| 57 | 61 | * message). |
| 58 | 62 | */ |
| 59 | export function voiceOf(db: Database, userId: string, conversationId: string, turns: readonly Turn[], origin: string): Voice { | |
| 63 | export function voiceOf(db: Database, userId: string, conversationId: string, turns: readonly Turn[], origin: string, now: number = Date.now()): Voice { | |
| 60 | 64 | const newest = db |
| 61 | 65 | .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 | 66 | .get(conversationId); |
| 63 | 67 | const key = {}; |
| 64 | 68 | const cards = cardsPlaced(db, userId, conversationId, turns, (text) => partsOf(key, text)); |
| 65 | 69 | 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 }; | |
| 70 | const voice: Voice = { cards, liveAfter: newest?.id ?? "", ...(planned === undefined ? {} : { latestPlan: planned.id }), origin, conversationId, now }; | |
| 67 | 71 | parsed.set(voice, parsed.get(key) ?? new Map()); |
| 68 | 72 | return voice; |
| 69 | 73 | } |
| @@ -82,24 +86,54 @@ export function linkOf(link: string | undefined, origin: string): string | undef | ||
| 82 | 86 | const hhmm = (iso: string): string => `${iso.slice(11, 16)} UTC`; |
| 83 | 87 | |
| 84 | 88 | /** |
| 85 | * A kept card as the page draws it: title and status, the rows (each a link only when `linkOf` | |
| 86 | * allows it), and the line saying where it came from. | |
| 89 | * One button of a card: its own form posting the card's id and which button, nothing else; or, | |
| 90 | * once pressed, a still button that says it asked. | |
| 87 | 91 | */ |
| 88 | export function cardHtml(shown: ShownCard, voice: Pick<Voice, "origin">, anchor?: string): Html { | |
| 92 | const actForm = (shown: ShownCard, path: string, a: CardAction): Html => | |
| 93 | shown.pressed.includes(path) | |
| 94 | ? 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>`; | |
| 96 | ||
| 97 | /** | |
| 98 | * A kept card as the page draws it: bare, set apart from the agent's words by a hairline on its | |
| 99 | * start side, with a head that says what it is and where it came from (the forge's mark, the | |
| 100 | * title and status, then the call in plain words and its `time`: the line no reply's Markdown | |
| 101 | * carries), the rows (each a link only | |
| 102 | * when `linkOf` allows it), and the buttons a press may ask for while it is fresh. A card with no | |
| 103 | * rows is its head alone, one line. A card past its ten minutes draws no buttons and offers to ask | |
| 104 | * again instead. | |
| 105 | */ | |
| 106 | export function cardHtml(shown: ShownCard, voice: Pick<Voice, "origin" | "conversationId" | "now">, anchor?: string): Html { | |
| 89 | 107 | const c = shown.card; |
| 90 | const rows = c.rows.map((r) => { | |
| 108 | const live = fresh(shown.createdAt, voice.now); | |
| 109 | const acts = c.actions.map((a, i) => [a, `a${i}`] as const).filter(([a]) => mayAct(c.kind, a)); | |
| 110 | const actable = acts.length > 0 || c.rows.some((r) => (r.actions ?? []).some((a) => mayAct(c.kind, a))); | |
| 111 | const rows = c.rows.map((r, i) => { | |
| 91 | 112 | const href = linkOf(r.link, voice.origin); |
| 113 | const after = live ? (r.actions ?? []).flatMap((a, j) => (mayAct(c.kind, a) ? [actForm(shown, `r${i}.${j}`, a)] : [])) : []; | |
| 92 | 114 | return row({ |
| 93 | 115 | title: r.label, |
| 94 | 116 | ...(r.value === "" ? {} : { meta: html`${r.value}` }), |
| 95 | 117 | ...(href === undefined ? {} : { href }), |
| 96 | 118 | ...(r.depth === undefined ? {} : { data: { depth: String(Math.min(3, r.depth)) } }), |
| 119 | ...(after.length === 0 ? {} : { after: html`${after}` }), | |
| 97 | 120 | }); |
| 98 | 121 | }); |
| 122 | const bar = live | |
| 123 | ? acts.length === 0 ? null : html`<div class="bar talk-card-acts">${acts.map(([a, path]) => actForm(shown, path, a))}</div>` | |
| 124 | : actable | |
| 125 | ? html`<div class="bar talk-card-acts"><span class="muted small">This result is more than 10 minutes old.</span><form method="post" action="/talk/${voice.conversationId}" data-starter><input type="hidden" name="text" value="${`Show result c${shown.n} again, fresh.`}" />${btn("Ask again", { icon: "sync", label: "Ask again for this result" })}</form></div>` | |
| 126 | : null; | |
| 127 | const said = html`From the forge: ${shown.said} · as of ${time(shown.createdAt, { text: hhmm(shown.createdAt) })}`; | |
| 128 | const titled = html`<strong>${c.title}</strong>${c.status === "" ? null : html` <span class="muted">${c.status}</span>`}`; | |
| 99 | 129 | const o = { |
| 100 | 130 | extra: "bare talk-card", |
| 101 | head: html`<strong>${c.title}</strong>${c.status === "" ? null : html` <span class="muted">${c.status}</span>`}`, | |
| 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>`, | |
| 131 | // The forge's mark, the title and status; where it came from small under it, or after it when | |
| 132 | // the card has no rows and is that one line. | |
| 133 | head: rows.length === 0 | |
| 134 | ? html`<p class="talk-card-title">${icon("anvil")}<span>${titled} <span class="talk-card-from small muted">· ${said}</span></span></p>` | |
| 135 | : html`<p class="talk-card-title">${icon("anvil")}<span>${titled}</span></p><p class="talk-card-from small muted">${said}</p>`, | |
| 136 | ...(bar === null ? {} : { foot: bar }), | |
| 103 | 137 | attrs: html`data-card="${shown.id}"`, |
| 104 | 138 | ...(anchor === undefined ? {} : { id: anchor }), |
| 105 | 139 | }; |
| @@ -134,10 +168,13 @@ function partHtml(p: Exclude<Part, { kind: "text" }>, live: boolean, voice: Voic | ||
| 134 | 168 | case "show": { |
| 135 | 169 | const shown = voice?.cards.get(p.n); |
| 136 | 170 | if (shown === undefined || voice === undefined) return html`<p class="talk-card-missing small muted">${NOT_FOUND_WORDS}</p>`; |
| 137 | const anchor = anchors.get(p.n); | |
| 138 | anchors.delete(p.n); | |
| 139 | return cardHtml(shown, voice, anchor); | |
| 171 | // A card is drawn once a reply; a later placing points back at it. | |
| 172 | const first = placed.get(p.n); | |
| 173 | if (p.again === true) return first === undefined ? html`` : html`<p class="talk-card-again small muted">Shown above: <a href="#${first.anchor}">${first.title.slice(0, 60)}</a></p>`; | |
| 174 | return cardHtml(shown, voice, anchors.get(p.n)); | |
| 140 | 175 | } |
| 176 | case "over": | |
| 177 | return html`<p class="talk-card-missing small muted">${overWords(p.cards, p.blocks)}</p>`; | |
| 141 | 178 | // The renderer's own fold, opened and closed around the parts it holds; the title is plain. |
| 142 | 179 | case "fold": |
| 143 | 180 | return raw(`<details><summary>${escapeHtml(p.summary)}</summary>`); |
| @@ -204,15 +241,22 @@ export function agentHtml(turn: Turn, voice: Voice | undefined, linked: (md: Htm | ||
| 204 | 241 | export const voiceCss = /* css */ ` |
| 205 | 242 | /* Over .card.bare's own border and overflow: a hairline on the start side, and a wide card scrolls in itself. */ |
| 206 | 243 | .card.bare.talk-card { margin: 8px 0; max-width: 100%; overflow-x: auto; border-inline-start: 2px solid var(--border); padding-inline-start: 12px; } |
| 244 | .talk-card > .card-head { display: block; } | |
| 245 | .talk-body .talk-card :is(.talk-card-from, .talk-card-title) { margin: 0; } | |
| 246 | .talk-card-title { display: flex; gap: 8px; align-items: baseline; overflow-wrap: anywhere; } | |
| 247 | .talk-card-title svg { flex: none; align-self: center; color: var(--muted-fg); } | |
| 248 | p.talk-card-from { padding-inline-start: 24px; } | |
| 249 | .talk-body .talk-card .list { list-style: none; margin: 0; padding: 0; } | |
| 207 | 250 | .talk-card .row { min-height: 44px; padding-inline: 0; } |
| 251 | /* A row that opens its page is a row, as in every list on the forge, not a run of underlined prose links. */ | |
| 252 | .talk-body .talk-card a.row { color: inherit; text-decoration: none; } | |
| 208 | 253 | .talk-card .row-title, .talk-card .row-meta, .talk-known .row-title, .talk-plan .row-title { white-space: normal; overflow-wrap: anywhere; } |
| 209 | 254 | /* The prose list's bullets and indent are not for these rows: at 360 px they pushed the state words off the edge. */ |
| 210 | 255 | .talk-body :is(.talk-plan, .talk-known) .list { list-style: none; margin: 0; padding: 0; } |
| 211 | 256 | .talk-card li[data-depth="1"] > .row { padding-inline-start: 16px; } |
| 212 | 257 | .talk-card li[data-depth="2"] > .row { padding-inline-start: 32px; } |
| 213 | 258 | .talk-card li[data-depth="3"] > .row { padding-inline-start: 48px; } |
| 214 | .talk-choices .btn { min-height: 2.75rem; } | |
| 215 | .talk-card-from { margin: 0; } | |
| 259 | .talk-card .btn, .talk-choices .btn { min-height: 2.75rem; } | |
| 216 | 260 | .talk-choices { margin: 12px 0; } |
| 217 | 261 | .talk-choices > p { margin: 0 0 8px; } |
| 218 | 262 | .talk-choices-options { display: flex; flex-wrap: wrap; gap: 8px; } |
test/talk-blocks.test.ts +1
| @@ -516,6 +516,7 @@ describe("the terminal prints the same parts", () => { | ||
| 516 | 516 | tool: "now", |
| 517 | 517 | said: "Now", |
| 518 | 518 | createdAt: "2026-11-22T10:00:00.000Z", |
| 519 | pressed: [] as string[], | |
| 519 | 520 | card: { |
| 520 | 521 | kind: "crew" as const, |
| 521 | 522 | title: "Working now", |
test/talk-shown.test.ts +388 −8
| @@ -2,7 +2,8 @@ | ||
| 2 | 2 | * Shown results (docs/features/talk.md, Shown results): an MCP answer to a conversation's via token |
| 3 | 3 | * that has a card keeps the card for that conversation and hands the agent its handle outside the |
| 4 | 4 | * fence; a `::show c<n>` line in a reply draws the kept card on /talk, the forge's own data and |
| 5 | * never the model's; and another person's or conversation's handle draws nothing of it. | |
| 5 | * never the model's; another person's or conversation's handle draws nothing of it; and a press of | |
| 6 | * a card's button runs only what the kept card says, once, the way a confirmed call runs. | |
| 6 | 7 | */ |
| 7 | 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 8 | 9 | import { mkdtemp, rm } from "node:fs/promises"; |
| @@ -10,6 +11,7 @@ import { tmpdir } from "node:os"; | ||
| 10 | 11 | import { join } from "node:path"; |
| 11 | 12 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 13 | import { createRepo } from "../src/actions/repos.ts"; |
| 14 | import { ACTS, CARD_FRESH_MS, mayAct } from "../src/actions/talk_act.ts"; | |
| 13 | 15 | import { |
| 14 | 16 | CARD_CHARS_MAX, |
| 15 | 17 | CARDS_KEPT, |
| @@ -22,8 +24,11 @@ import { | ||
| 22 | 24 | appendTurn, |
| 23 | 25 | createConversation, |
| 24 | 26 | dropConversation, |
| 27 | listTurns, | |
| 25 | 28 | type Conversation, |
| 26 | 29 | } from "../src/core/conversations.ts"; |
| 30 | import { cancelHeld, hold, HELD_MAX, waitingFor } from "../src/core/fence.ts"; | |
| 31 | import { sayNo } from "../src/actions/conversation_confirms.ts"; | |
| 27 | 32 | import { createIssue } from "../src/core/issues.ts"; |
| 28 | 33 | import { createSession } from "../src/core/sessions.ts"; |
| 29 | 34 | import { createToken } from "../src/core/tokens.ts"; |
| @@ -34,6 +39,7 @@ import { createForgeApp } from "../src/tui/forge.ts"; | ||
| 34 | 39 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 35 | 40 | import { settleApp } from "./helpers/tui.ts"; |
| 36 | 41 | import type { Card } from "../src/web/studio/cards.ts"; |
| 42 | import { cardFor } from "../src/web/studio/cards.ts"; | |
| 37 | 43 | import { promote } from "./helpers/members.ts"; |
| 38 | 44 | import { quietLogs } from "./helpers/globals.ts"; |
| 39 | 45 | import { statements } from "./helpers/statements.ts"; |
| @@ -56,6 +62,23 @@ const get = (path: string, u: User) => | ||
| 56 | 62 | redirect: "manual", |
| 57 | 63 | headers: { cookie: cookie(u) }, |
| 58 | 64 | }); |
| 65 | const press = ( | |
| 66 | u: User, | |
| 67 | form: Record<string, string>, | |
| 68 | headers: Record<string, string> = {}, | |
| 69 | ) => | |
| 70 | fetch(`${servers.url}/talk/act`, { | |
| 71 | method: "POST", | |
| 72 | redirect: "manual", | |
| 73 | headers: { | |
| 74 | origin: servers.url, | |
| 75 | cookie: cookie(u), | |
| 76 | accept: "application/json", | |
| 77 | ...headers, | |
| 78 | }, | |
| 79 | body: new URLSearchParams(form), | |
| 80 | }); | |
| 81 | ||
| 59 | 82 | async function call( |
| 60 | 83 | token: string, |
| 61 | 84 | name: string, |
| @@ -208,7 +231,8 @@ describe("a via caller's answer keeps its card", () => { | ||
| 208 | 231 | ); |
| 209 | 232 | expect( |
| 210 | 233 | kept.rows.every( |
| 211 | (r) => r.link === undefined || r.link.startsWith("/alice/w/issues/"), | |
| 234 | // Every issue row links to its page, Talk's own agent's card as anyone's. | |
| 235 | (r) => r.link !== undefined && r.link.startsWith("/alice/w/issues/"), | |
| 212 | 236 | ), |
| 213 | 237 | ).toBe(true); |
| 214 | 238 | // A second answer is the next handle. |
| @@ -286,14 +310,15 @@ describe("a via caller's answer keeps its card", () => { | ||
| 286 | 310 | }); |
| 287 | 311 | |
| 288 | 312 | describe("what is kept", () => { |
| 289 | test("a kept card is what the page draws: its title, status and rows, never a button", () => { | |
| 313 | test("a kept card keeps its buttons, and a press of one goes with the card", () => { | |
| 290 | 314 | const c = chat(alice); |
| 291 | const { n } = keep(alice, c, { ...stopCard(), rows: [{ label: "smith", value: "running", actions: [{ label: "Stop", tool: "stop", args: {} }] }] }); | |
| 292 | const text = cardRows(via(c)).find((r) => r.n === n)!.card; | |
| 293 | expect(text).not.toContain("Stop"); | |
| 315 | const { n, id } = keep(alice, c, { ...stopCard(), rows: [{ label: "smith", value: "running", actions: [{ label: "Stop", tool: "stop", args: {} }] }] }); | |
| 294 | 316 | const shown = cardsOf(app.db, alice.id, via(c), [n]).get(n)!; |
| 295 | expect(shown.card.actions).toEqual([]); | |
| 296 | expect(shown.card.rows).toEqual([{ label: "smith", value: "running" }]); | |
| 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 | 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 | dropConversation(app.db, alice.id, c.id); | |
| 321 | expect(app.db.query("SELECT COUNT(*) AS n FROM conversation_card_press WHERE card_id = ?1").get(id)).toEqual({ n: 0 }); | |
| 297 | 322 | }); |
| 298 | 323 | |
| 299 | 324 | test("a conversation's cards go when the conversation goes", () => { |
| @@ -337,6 +362,17 @@ describe("the terminal prints a placed card", () => { | ||
| 337 | 362 | expect(text).not.toContain("::show c1"); |
| 338 | 363 | }); |
| 339 | 364 | |
| 365 | test("the terminal keeps the page's caps: a card once a reply, a pointer after, and past the caps one line", () => { | |
| 366 | const c = chat(alice); | |
| 367 | const { n } = keep(alice, c, stopCard()); | |
| 368 | const cards = cardsOf(app.db, alice.id, via(c), [n]); | |
| 369 | const twice = plainVoice(`::show c${n}\n\n::show c${n}`, cards); | |
| 370 | expect(twice.match(/Working now · 1 going/g)?.length).toBe(1); | |
| 371 | expect(twice).toContain("(shown above: Working now)"); | |
| 372 | const many = plainVoice(Array.from({ length: 12 }, () => `::show c${n}`).join("\n\n"), cards); | |
| 373 | expect(many).toContain("1 more result in this reply was left as text."); | |
| 374 | }); | |
| 375 | ||
| 340 | 376 | test("forge talk reads the same printing from the turns API, as plain beside the raw text", async () => { |
| 341 | 377 | const c = chat(alice); |
| 342 | 378 | keep(alice, c, stopCard()); |
| @@ -504,3 +540,347 @@ describe("::show draws the kept card", () => { | ||
| 504 | 540 | expect(await at(5)).toBe(await at(1)); |
| 505 | 541 | }); |
| 506 | 542 | }); |
| 543 | ||
| 544 | describe("POST /talk/act", () => { | |
| 545 | test("the allowed buttons are a named list, and a button that takes typed words is never one", () => { | |
| 546 | expect(Object.keys(ACTS).sort()).toEqual([ | |
| 547 | "archive", | |
| 548 | "asks_act", | |
| 549 | "held", | |
| 550 | "stop", | |
| 551 | ]); | |
| 552 | expect( | |
| 553 | mayAct("app", { | |
| 554 | label: "Tell", | |
| 555 | tool: "tell", | |
| 556 | args: { repo: "a/b" }, | |
| 557 | words: true, | |
| 558 | }), | |
| 559 | ).toBe(false); | |
| 560 | expect( | |
| 561 | mayAct("asks", { | |
| 562 | label: "Ship", | |
| 563 | tool: "asks_act", | |
| 564 | args: { action: "ship", items: ["x"] }, | |
| 565 | }), | |
| 566 | ).toBe(false); | |
| 567 | expect( | |
| 568 | mayAct("asks", { | |
| 569 | label: "Ship 2", | |
| 570 | tool: "asks_act", | |
| 571 | args: { action: "ship", items: ["x"], dryRun: false }, | |
| 572 | }), | |
| 573 | ).toBe(true); | |
| 574 | expect( | |
| 575 | mayAct("issues", { | |
| 576 | label: "Stop", | |
| 577 | tool: "stop", | |
| 578 | args: { repo: "a/b", run: "r" }, | |
| 579 | }), | |
| 580 | ).toBe(false); | |
| 581 | // Every card kind `cardFor` builds a button on is either listed or refused: a crew card's Stop | |
| 582 | // is listed. | |
| 583 | const crew = cardFor( | |
| 584 | "now", | |
| 585 | [ | |
| 586 | { | |
| 587 | who: "smith", | |
| 588 | app: "alice/w", | |
| 589 | run: "01jabcdefghjkmnpqrstvwxyz0", | |
| 590 | state: "running", | |
| 591 | }, | |
| 592 | ], | |
| 593 | "http://x", | |
| 594 | ); | |
| 595 | expect(crew?.actions.every((a) => mayAct(crew.kind, a))).toBe(true); | |
| 596 | }); | |
| 597 | ||
| 598 | test("a press of a tool that asks first is held as Do it / Not now with the kept card's call, whatever the body says", async () => { | |
| 599 | const c = chat(alice); | |
| 600 | const { id } = keep(alice, c, stopCard()); | |
| 601 | const before = waitingFor(app.db, alice.id).length; | |
| 602 | const res = await press(alice, { | |
| 603 | card: id, | |
| 604 | action: "a0", | |
| 605 | tool: "close", | |
| 606 | args: JSON.stringify({ repo, number: 2 }), | |
| 607 | repo: "evil/x", | |
| 608 | }); | |
| 609 | expect(res.status).toBe(200); | |
| 610 | const body = (await res.json()) as { ok: boolean; confirm: string }; | |
| 611 | const waiting = waitingFor(app.db, alice.id); | |
| 612 | expect(waiting.length).toBe(before + 1); | |
| 613 | const held = waiting.at(-1)!; | |
| 614 | expect(body).toEqual({ ok: true, confirm: held.id }); | |
| 615 | expect(held.tool).toBe("stop"); | |
| 616 | expect(held.args).toEqual({ | |
| 617 | repo: "alice/w", | |
| 618 | run: "01jabcdefghjkmnpqrstvwxyz0", | |
| 619 | }); | |
| 620 | const turns = listTurns(app.db, alice.id, c.id, { limit: 10 }); | |
| 621 | const confirm = turns.ok | |
| 622 | ? turns.value.find((t) => t.role === "confirm") | |
| 623 | : undefined; | |
| 624 | expect(JSON.parse(confirm!.text)).toMatchObject({ | |
| 625 | confirm: held.id, | |
| 626 | tool: "stop", | |
| 627 | }); | |
| 628 | // The thread draws the ordinary buttons for it. | |
| 629 | const page = await (await get(`/talk/${c.id}`, alice)).text(); | |
| 630 | expect(page).toContain(`action="/talk/confirm/${held.id}"`); | |
| 631 | }); | |
| 632 | ||
| 633 | test("a plan card's Confirm never writes on the press: it draws Do it / Not now with the forge's sentence, once", async () => { | |
| 634 | const c = chat(alice); | |
| 635 | const card: Card = { kind: "asks", title: "Confirm", status: "", rows: [], actions: [{ label: "Dismiss 1", tool: "asks_act", args: { action: "dismiss", items: ["nothing:1"], dryRun: false } }] }; | |
| 636 | const { id } = keep(alice, c, card); | |
| 637 | const turns = () => { | |
| 638 | const t = listTurns(app.db, alice.id, c.id, { limit: 20 }); | |
| 639 | return t.ok ? t.value : []; | |
| 640 | }; | |
| 641 | const first = await press(alice, { card: id, action: "a0" }); | |
| 642 | expect(first.status).toBe(200); | |
| 643 | // Nothing ran: no result turn, one confirm turn with its sentence, and the call held as kept. | |
| 644 | expect(turns().filter((x) => x.role === "tool")).toEqual([]); | |
| 645 | const confirms = turns().filter((x) => x.role === "confirm"); | |
| 646 | expect(confirms.length).toBe(1); | |
| 647 | const drawn = JSON.parse(confirms[0]!.text) as { confirm: string; tool: string; does: string }; | |
| 648 | expect(drawn.tool).toBe("asks_act"); | |
| 649 | expect(drawn.does).toBe("Dismiss 1 ask. From the result shown above: Confirm."); | |
| 650 | const held = waitingFor(app.db, alice.id).find((w) => w.id === drawn.confirm)!; | |
| 651 | expect(held.args).toEqual({ action: "dismiss", items: ["nothing:1"], dryRun: false }); | |
| 652 | const page = await (await get(`/talk/${c.id}`, alice)).text(); | |
| 653 | expect(page).toContain(`action="/talk/confirm/${held.id}"`); | |
| 654 | // A second press does nothing, and keeps nothing more. | |
| 655 | const second = await press(alice, { card: id, action: "a0" }); | |
| 656 | expect(second.status).toBe(409); | |
| 657 | expect(((await second.json()) as { message: string }).message).toContain("already pressed"); | |
| 658 | expect(turns().filter((x) => x.role === "confirm").length).toBe(1); | |
| 659 | }); | |
| 660 | ||
| 661 | test("another person's card is not found; a token is refused; another site is refused", async () => { | |
| 662 | const c = chat(alice); | |
| 663 | const { id } = keep(alice, c, stopCard()); | |
| 664 | const theirs = await press(bob, { card: id, action: "a0" }); | |
| 665 | expect(theirs.status).toBe(404); | |
| 666 | const token = createToken(app.db, alice.id, "rw", "rw").token; | |
| 667 | const byToken = await fetch(`${servers.url}/talk/act`, { | |
| 668 | method: "POST", | |
| 669 | redirect: "manual", | |
| 670 | headers: { authorization: `Bearer ${token}`, origin: servers.url }, | |
| 671 | body: new URLSearchParams({ card: id, action: "a0" }), | |
| 672 | }); | |
| 673 | expect(byToken.status).toBe(403); | |
| 674 | const elsewhere = await press( | |
| 675 | alice, | |
| 676 | { card: id, action: "a0" }, | |
| 677 | { origin: "https://evil.example" }, | |
| 678 | ); | |
| 679 | expect(elsewhere.status).toBe(403); | |
| 680 | const nothing = await press(alice, { card: id, action: "a9" }); | |
| 681 | expect(nothing.status).toBe(404); | |
| 682 | const junk = await press(alice, { card: id, action: "a0; drop" }); | |
| 683 | expect(junk.status).toBe(404); | |
| 684 | // None of them held or ran anything, and the button still works for Alice. | |
| 685 | expect( | |
| 686 | waitingFor(app.db, alice.id).some( | |
| 687 | (w) => | |
| 688 | w.args["run"] === "01jabcdefghjkmnpqrstvwxyz0" && w.via === via(c), | |
| 689 | ), | |
| 690 | ).toBe(false); | |
| 691 | expect((await press(alice, { card: id, action: "a0" })).status).toBe(200); | |
| 692 | }); | |
| 693 | ||
| 694 | test("a button not on the list is refused and drawn nowhere", async () => { | |
| 695 | const c = chat(alice); | |
| 696 | const card: Card = { | |
| 697 | kind: "issues", | |
| 698 | title: "Issues", | |
| 699 | status: "", | |
| 700 | rows: [ | |
| 701 | { | |
| 702 | label: "#1", | |
| 703 | value: "", | |
| 704 | actions: [ | |
| 705 | { label: "Close it", tool: "close", args: { repo, number: 1 } }, | |
| 706 | ], | |
| 707 | }, | |
| 708 | ], | |
| 709 | actions: [ | |
| 710 | { | |
| 711 | label: "Tell", | |
| 712 | tool: "tell", | |
| 713 | args: { repo, context: {} }, | |
| 714 | words: true, | |
| 715 | }, | |
| 716 | ], | |
| 717 | }; | |
| 718 | const { id } = keep(alice, c, card); | |
| 719 | expect((await press(alice, { card: id, action: "a0" })).status).toBe(409); | |
| 720 | expect((await press(alice, { card: id, action: "r0.0" })).status).toBe(409); | |
| 721 | appendTurn(app.db, alice.id, c.id, { role: "agent", text: "::show c1" }); | |
| 722 | const page = await (await get(`/talk/${c.id}`, alice)).text(); | |
| 723 | expect(page).toContain("data-card="); | |
| 724 | expect(page).not.toContain('action="/talk/act"'); | |
| 725 | }); | |
| 726 | ||
| 727 | test("a card older than ten minutes does not act: the press says so in the thread, and the page offers to ask again", async () => { | |
| 728 | const c = chat(alice); | |
| 729 | const { id } = keep( | |
| 730 | alice, | |
| 731 | c, | |
| 732 | stopCard("01jabcdefghjkmnpqrstvwxy99"), | |
| 733 | Date.now() - CARD_FRESH_MS - 1000, | |
| 734 | ); | |
| 735 | const before = waitingFor(app.db, alice.id).length; | |
| 736 | const res = await press(alice, { card: id, action: "a0" }); | |
| 737 | expect(res.status).toBe(410); | |
| 738 | expect(waitingFor(app.db, alice.id).length).toBe(before); | |
| 739 | const turns = listTurns(app.db, alice.id, c.id, { limit: 10 }); | |
| 740 | const said = turns.ok | |
| 741 | ? turns.value.find((t) => t.role === "tool") | |
| 742 | : undefined; | |
| 743 | expect(JSON.parse(said!.text)).toMatchObject({ | |
| 744 | tool: "stop", | |
| 745 | done: false, | |
| 746 | error: "stale", | |
| 747 | }); | |
| 748 | appendTurn(app.db, alice.id, c.id, { role: "agent", text: "::show c1" }); | |
| 749 | const page = await (await get(`/talk/${c.id}`, alice)).text(); | |
| 750 | expect(page).toContain( | |
| 751 | "This result is more than 10 minutes old, so nothing was done; ask again for a fresh one.", | |
| 752 | ); | |
| 753 | expect(page).toContain("This result is more than 10 minutes old."); | |
| 754 | expect(page).not.toContain('action="/talk/act"'); | |
| 755 | expect(page).toContain('value="Show result c1 again, fresh."'); | |
| 756 | }); | |
| 757 | ||
| 758 | test("a fresh card's button posts the card's id and which button, nothing else", async () => { | |
| 759 | const c = chat(alice); | |
| 760 | const { id } = keep(alice, c, stopCard()); | |
| 761 | appendTurn(app.db, alice.id, c.id, { role: "agent", text: "::show c1" }); | |
| 762 | const page = await (await get(`/talk/${c.id}`, alice)).text(); | |
| 763 | const form = | |
| 764 | /<form method="post" action="\/talk\/act"[^>]*>([\s\S]*?)<\/form>/.exec( | |
| 765 | page, | |
| 766 | )?.[1] ?? ""; | |
| 767 | const names = [...form.matchAll(/name="([^"]+)"/g)].map((m) => m[1]); | |
| 768 | expect(names).toEqual(["card", "action"]); | |
| 769 | expect(form).toContain(`value="${id}"`); | |
| 770 | expect(form).toContain('value="a0"'); | |
| 771 | }); | |
| 772 | }); | |
| 773 | ||
| 774 | describe("the forge's surface, the caps and a press's claim", () => { | |
| 775 | test("one reply draws a card once and at most the caps; the rest stays text with one line saying so", async () => { | |
| 776 | const c = chat(alice); | |
| 777 | for (let i = 0; i < 20; i++) keep(alice, c, stopCard(`01jabcdefghjkmnpqrstvw${String(i).padStart(4, "0")}`)); | |
| 778 | const plan = "```forge\nplan\n" + JSON.stringify({ steps: [{ text: "x", state: "todo" }] }) + "\n```"; | |
| 779 | const text = [...Array.from({ length: 500 }, () => "::show c4"), ...Array.from({ length: 20 }, (_, i) => `::show c${i + 1}`), ...Array.from({ length: 10 }, () => plan)].join("\n"); | |
| 780 | appendTurn(app.db, alice.id, c.id, { role: "agent", text }); | |
| 781 | const res = await get(`/talk/${c.id}`, alice); | |
| 782 | const page = await res.text(); | |
| 783 | expect(page.length).toBeLessThan(250_000); | |
| 784 | expect(page.match(/data-card="/g)?.length).toBe(10); | |
| 785 | expect(page.match(/action="\/talk\/act"/g)?.length).toBe(10); | |
| 786 | expect(page.match(/class="talk-card-again/g)?.length).toBe(10); | |
| 787 | expect(page.match(/data-state="todo"/g)?.length).toBe(6); | |
| 788 | expect(page).toContain("500 more results and 4 more blocks in this reply were left as text."); | |
| 789 | const ids = [...page.matchAll(/\sid="([^"]+)"/g)].map((m) => m[1]); | |
| 790 | expect(new Set(ids).size).toBe(ids.length); | |
| 791 | }); | |
| 792 | ||
| 793 | test("a card is bare under a hairline, its head the forge's mark, title and where it came from; a forged quote is only Markdown; a card with no rows is one line", async () => { | |
| 794 | const c = chat(alice); | |
| 795 | keep(alice, c, stopCard()); | |
| 796 | keep(alice, c, { kind: "crew", title: "Working now", status: "nothing running", rows: [], actions: [] }); | |
| 797 | appendTurn(app.db, alice.id, c.id, { role: "agent", text: "::show c1\n\n> **Issues** 2 open issues\n>\n> *From the forge: Issues · as of 14:02 UTC*\n\n::show c2" }); | |
| 798 | const page = await (await get(`/talk/${c.id}`, alice)).text(); | |
| 799 | const cards = page.split('class="card bare talk-card"').slice(1); | |
| 800 | expect(cards).toHaveLength(2); | |
| 801 | const head = cards[0]!.slice(cards[0]!.indexOf('class="card-head"')); | |
| 802 | const end = head.indexOf("</div>"); | |
| 803 | expect(head.indexOf("<svg")).toBeLessThan(head.indexOf("Working now")); | |
| 804 | expect(head.indexOf("Working now")).toBeLessThan(head.indexOf("From the forge: Now")); | |
| 805 | expect(head.indexOf("<time")).toBeLessThan(end); | |
| 806 | // The forged quote is a blockquote, never the card's surface. | |
| 807 | const quote = page.slice(page.indexOf("<blockquote"), page.indexOf("</blockquote>")); | |
| 808 | expect(quote).toContain("From the forge: Issues"); | |
| 809 | expect(quote).not.toMatch(/card|<svg|<time/); | |
| 810 | // The empty card is its head alone. | |
| 811 | const empty = cards[1]!.slice(0, cards[1]!.indexOf("</div>")); | |
| 812 | expect(cards[1]!.slice(0, cards[1]!.indexOf("talk-meta"))).not.toContain('class="list"'); | |
| 813 | expect(empty.match(/<p /g)?.length).toBe(1); | |
| 814 | expect(empty).toMatch(/Working now<\/strong> <span class="muted">nothing running<\/span> <span class="talk-card-from small muted">· From the forge: Now/); | |
| 815 | }); | |
| 816 | ||
| 817 | test("a press claims its button only once its confirm is kept: a full conversation leaves it to press again", async () => { | |
| 818 | const c = chat(alice); | |
| 819 | const { id } = keep(alice, c, stopCard()); | |
| 820 | for (let i = 0; i < HELD_MAX; i++) hold(app.db, via(c), alice.id, "close", { repo, number: 1 }); | |
| 821 | const full = await press(alice, { card: id, action: "a0" }); | |
| 822 | expect(full.status).toBe(409); | |
| 823 | expect(((await full.json()) as { message: string }).message).toContain("too many confirms"); | |
| 824 | expect(app.db.query("SELECT COUNT(*) AS n FROM conversation_card_press WHERE card_id = ?1").get(id)).toEqual({ n: 0 }); | |
| 825 | cancelHeld(app.db, via(c)); | |
| 826 | expect((await press(alice, { card: id, action: "a0" })).status).toBe(200); | |
| 827 | }); | |
| 828 | ||
| 829 | test("after Not now the button is drawn still, reading Asked, and a press does nothing", async () => { | |
| 830 | const c = chat(alice); | |
| 831 | const { id } = keep(alice, c, stopCard("01jabcdefghjkmnpqrstvwxy77")); | |
| 832 | appendTurn(app.db, alice.id, c.id, { role: "agent", text: "::show c1" }); | |
| 833 | const pressed = (await (await press(alice, { card: id, action: "a0" })).json()) as { confirm: string }; | |
| 834 | expect(sayNo({ app }, alice, pressed.confirm).ok).toBe(true); | |
| 835 | const page = await (await get(`/talk/${c.id}`, alice)).text(); | |
| 836 | expect(page).not.toContain('action="/talk/act"'); | |
| 837 | expect(page).toMatch(/<button[^>]*disabled[^>]*aria-label="Stop smith: asked"/); | |
| 838 | expect((await press(alice, { card: id, action: "a0" })).status).toBe(409); | |
| 839 | }); | |
| 840 | ||
| 841 | test("a stale press claims no button, and the thread says it once a card however often it is pressed", async () => { | |
| 842 | const c = chat(alice); | |
| 843 | const { id } = keep(alice, c, stopCard(), Date.now() - CARD_FRESH_MS - 1000); | |
| 844 | for (let n = 0; n < 3; n++) expect((await press(alice, { card: id, action: "a0" })).status).toBe(410); | |
| 845 | expect(app.db.query("SELECT action FROM conversation_card_press WHERE card_id = ?1").all(id)).toEqual([{ action: "stale" }]); | |
| 846 | const turns = listTurns(app.db, alice.id, c.id, { limit: 10 }); | |
| 847 | expect((turns.ok ? turns.value : []).filter((t) => t.role === "tool")).toHaveLength(1); | |
| 848 | }); | |
| 849 | ||
| 850 | test("the terminal presses a result's button through the same pressCard: b lists it, Enter draws Do it / Not now", async () => { | |
| 851 | const c = chat(alice); | |
| 852 | keep(alice, c, stopCard("01jabcdefghjkmnpqrstvwxy77")); | |
| 853 | appendTurn(app.db, alice.id, c.id, { role: "agent", text: "Here:\n\n::show c1" }); | |
| 854 | const terminal = headlessTerminal(120, 40); | |
| 855 | const { app: tui } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false }); | |
| 856 | tui.start(); | |
| 857 | await settleApp(tui); | |
| 858 | for (const k of [":", "Conversations", "\r", "\r", "b"]) { | |
| 859 | terminal.feed(k); | |
| 860 | await settleApp(tui); | |
| 861 | } | |
| 862 | expect(tui.screen.toText()).toContain("Stop smith: Working now"); | |
| 863 | terminal.feed("\r"); | |
| 864 | await settleApp(tui); | |
| 865 | const turns = listTurns(app.db, alice.id, c.id, { limit: 10 }); | |
| 866 | const confirm = (turns.ok ? turns.value : []).find((t) => t.role === "confirm"); | |
| 867 | tui.stop?.(); | |
| 868 | expect((JSON.parse(confirm!.text) as { tool: string }).tool).toBe("stop"); | |
| 869 | expect(app.db.query("SELECT action FROM conversation_card_press WHERE card_id = (SELECT id FROM conversation_card WHERE via = ?1)").all(via(c))).toEqual([{ action: "a0" }]); | |
| 870 | }); | |
| 871 | ||
| 872 | test("a call the tool would refuse the person is never offered as Do it; the confirm names the card it came from", async () => { | |
| 873 | const c = chat(bob); | |
| 874 | const { id } = keep(bob, c, { kind: "app", title: "Archive", status: "", rows: [], actions: [{ label: "Archive", tool: "archive", args: { repo, archived: true, dryRun: false } }] }); | |
| 875 | expect((await press(bob, { card: id, action: "a0" })).status).toBe(403); | |
| 876 | const turns = listTurns(app.db, bob.id, c.id, { limit: 10 }); | |
| 877 | expect((turns.ok ? turns.value : []).filter((t) => t.role === "confirm")).toEqual([]); | |
| 878 | const mine = chat(alice); | |
| 879 | const own = keep(alice, mine, stopCard("01jabcdefghjkmnpqrstvwxy55")); | |
| 880 | await press(alice, { card: own.id, action: "a0" }); | |
| 881 | const said = listTurns(app.db, alice.id, mine.id, { limit: 10 }); | |
| 882 | const confirm = (said.ok ? said.value : []).find((t) => t.role === "confirm")!; | |
| 883 | expect((JSON.parse(confirm.text) as { does: string }).does).toEndWith("From the result shown above: Working now."); | |
| 884 | }); | |
| 885 | }); | |
| 886 |
new above
offline
Principles 6 and 7: this draws a box (the card's own background and border) around a list of rows. Use rows under a hairline, as the bare card did, and keep the buttons as plain
.btnforms. The 'Markdown cannot imitate it' argument belongs in docs/DESIGN.md if it stays.