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

Talk's live reply draws shown results and blocks as the stored reply will, and a queued message is answered with no reload #16287

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

talk/06-live → main 0 commits

  • Merged. talk/06-live was merged into main as 95e6eca.

Review

Sign in to review this change.
7 files changed +207 −9
docs/features/talk-voice.md +4
@@ -59,6 +59,10 @@ choices
5959 - `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.
6060 - `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.
6161
62 ## While the reply is written
63
64 The live block (`docs/features/talk.md`, "Live") is drawn through the same code as a stored reply (`liveHtml` in `src/web/talk_parts.ts`): a result placed so far shows as its card at once. A `forge` block is left out until its fence is closed, and a last line that may still become `::show cN` waits until it is whole (`wholeSoFar`), so the reader never sees a block's JSON or a handle turn into its drawing. The choices of a reply still being written are drawn as text; only the stored reply's are buttons. The terminal's `ssh <forge> talk --follow` prints the same whole parts as they arrive, as `forge talk` prints a stored reply (`plainVoice`): a placed result as its lines, a block as a plain list, never a handle or a block's JSON (`src/tui/talk_follow.ts`). Proof: `test/talk-live-voice.test.ts`, and the follow tests in `test/talk-live.test.ts`.
65
6266 ## Other doors
6367
6468 - 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.
src/core/talk_voice.ts +24
@@ -500,6 +500,30 @@ const STATE_WORD: Readonly<Record<PlanState, string>> = { todo: "to do", doing:
500500 /** A plan step's state as its word on the page and in the terminal. */
501501 export const planWord = (s: PlanState): string => STATE_WORD[s];
502502
503 /**
504 * What of a reply still being written may be drawn: a `forge` block whose fence is not closed yet
505 * and a last line that may still become a `::show` are left out until they are whole, so the
506 * reader never sees a block's JSON or a handle turn into its drawing.
507 */
508 export function wholeSoFar(text: string): string {
509 const lines = text.replaceAll("\r\n", "\n").split("\n");
510 let open = -1;
511 let ticks = 0;
512 for (let i = 0; i < lines.length; i += 1) {
513 const fence = /^ *(`{3,})(.*)$/.exec(lines[i]!);
514 if (fence === null) continue;
515 if (open === -1) {
516 if (BLOCK_INFO.test(fence[2]!)) open = i;
517 else open = -2 - i;
518 ticks = fence[1]!.length;
519 } else if (fence[1]!.length >= ticks && fence[2]!.trim() === "") open = -1;
520 }
521 const kept = open >= 0 ? lines.slice(0, open) : lines;
522 // Outside any fence, a last line that is the start of `::show cN` waits for its end.
523 if (open === -1 && /^:{1,2}(s(h(o(w( (c\d{0,9})?)?)?)?)?)?$/.test(kept.at(-1) ?? "")) kept.pop();
524 return kept.join("\n");
525 }
526
503527 /**
504528 * The person's kept cards that these replies of their conversation place, by number: one
505529 * statement whatever the number of replies (`test/talk-shown.test.ts` counts it).
src/tui/talk_follow.ts +11 −4
@@ -8,14 +8,16 @@
88 * a failure line, a fresh attempt after a lost session), what was printed stands and only the part
99 * after where they differ follows, on a line of its own. A held action the agent asks for (a
1010 * `confirm` turn) is printed as its sentence and how to answer it; the exec still ends with the
11 * turn. Steps and thinking are left to /talk and `forge talk`. Every control character but a line
12 * break is a space.
11 * turn. A shown result and a block print as `forge talk` prints them, whole, never as a handle
12 * or JSON. Steps and thinking are left to /talk and `forge talk`. Every control character but a
13 * line break is a space.
1314 */
1415
1516 import type { App } from "../app.ts";
1617 import { listTurns, turnsAfter } from "../core/conversations.ts";
1718 import { turnRunning } from "../crew/conversation.ts";
1819 import { liveBlock, subscribe } from "../crew/conversation_live.ts";
20 import { cardsPlaced, plainVoice, wholeSoFar } from "../core/talk_voice.ts";
1921 import type { SshSession } from "../ssh/server.ts";
2022
2123 const CRLF = "\r\n";
@@ -86,12 +88,16 @@ export function followTalk(app: App, session: SshSession, userId: string, conver
8688 write(text.slice(same));
8789 printed = text;
8890 };
91 // A reply as the terminal prints it, live or stored: a placed result as its lines, a block as a
92 // plain list, never a bare `::show c1` or a block's JSON (`plainVoice`, the one parser every door
93 // uses); while it is written, only what is whole so far (`wholeSoFar`), as the page draws it.
94 const printable = (text: string): string => plainVoice(text, cardsPlaced(app.db, userId, conversationId, [{ role: "agent", text }]));
8995 const look = (): void => {
9096 if (over) return;
9197 for (const turn of turnsAfter(app.db, userId, conversationId, cursor)) {
9298 cursor = turn.id;
9399 if (turn.role === "agent") {
94 show(turn.text);
100 show(printable(turn.text));
95101 endLine();
96102 printed = "";
97103 } else if (turn.role === "confirm") {
@@ -102,7 +108,8 @@ export function followTalk(app: App, session: SshSession, userId: string, conver
102108 write(asked);
103109 }
104110 }
105 show(liveBlock(app.db, conversationId)?.text ?? "");
111 const live = liveBlock(app.db, conversationId)?.text ?? "";
112 show(live === "" ? "" : printable(wholeSoFar(live)));
106113 if (turnRunning(app, userId, conversationId)) return;
107114 over = true;
108115 stop();
src/web/pages/talk.ts +5 −4
@@ -66,8 +66,7 @@ import { linkRefs, refTarget } from "../../text/talk_links.ts";
6666 import { appLook, linkTalk, talkLook, type TalkLook } from "../../text/talk_link_words.ts";
6767 import { liveCrewRows } from "../../actions/crew_now.ts";
6868 import { crewLineHtml } from "../crew_now.ts";
69 import { renderMarkdown } from "../markdown.ts";
70 import { agentHtml, voiceCss, voiceOf, type Voice } from "../talk_parts.ts";
69 import { agentHtml, liveHtml, voiceCss, voiceOf, type Voice } from "../talk_parts.ts";
7170 import { badge, btn, icon, iconBtn, menu, meter, row, time } from "../ui.ts";
7271 import { inlineIcons } from "../icons.ts";
7372 import { buildCss, chosenTemplate, panelFor, templateChips } from "../talk_build.ts";
@@ -822,7 +821,7 @@ export function talkStream(ctx: Ctx): Response {
822821 const block = liveBlock(app.db, conversation.id);
823822 const refs = refTarget(app.db, user, cited);
824823 const frame = {
825 html: block === undefined || block.text === "" ? "" : inlineIcons(html`<div class="talk-body prose">${linkedOf(refs, talkLook(app.db, user, [block.text], appLook(app, user)))(renderMarkdown(block.text))}</div>`.text),
824 html: block === undefined || block.text === "" ? "" : inlineIcons(html`<div class="talk-body prose">${liveHtml(app.db, user.id, conversation.id, block.text, ctx.url.origin, linkedOf(refs, talkLook(app.db, user, [block.text], appLook(app, user))))}</div>`.text),
826825 thinking: block?.thinking === true,
827826 tool: block?.tool === undefined ? "" : runningStep(block.tool),
828827 };
@@ -871,7 +870,9 @@ export function talkStream(ctx: Ctx): Response {
871870 emit("queued", { items: waits.map((q) => ({ id: q.id, html: queuedHtml(q).text })) });
872871 }
873872 if (fresh.length >= MAX_PAGE) return;
874 if (!running) {
873 // A message still queued is the next turn: the answer that ended hands over to it (`drain`,
874 // after the build's pull), so the stream waits for it rather than ending in between.
875 if (!running && waits.length === 0) {
875876 // The run stored its figures before it stopped running: send them with the end.
876877 const costs = [...turnSpend(app.db, conversation.id)].slice(-5).map(([id, spend]) => ({ id: `t-${id}`, html: costLine(spend).text }));
877878 const context = contextOf(app.db, conversation.id);
src/web/talk_parts.ts +12 −1
@@ -16,7 +16,7 @@
1616 import type { Database } from "bun:sqlite";
1717 import type { ShownCard } from "../core/talk_voice.ts";
1818 import type { Turn } from "../core/conversations.ts";
19 import { cardsPlaced, NOT_FOUND_WORDS, overWords, planWord, voiceParts, type Part, type PlanState } from "../core/talk_voice.ts";
19 import { cardsPlaced, NOT_FOUND_WORDS, overWords, planWord, voiceParts, wholeSoFar, type Part, type PlanState } from "../core/talk_voice.ts";
2020 import { fresh, mayAct } from "../actions/talk_act.ts";
2121 import { escapeHtml, html, raw, type Html } from "./html.ts";
2222 import type { IconName } from "./icons.ts";
@@ -234,6 +234,17 @@ export function agentHtml(turn: Turn, voice: Voice | undefined, linked: (md: Htm
234234 return html`${parts.map((p) => (p.kind === "text" ? linked(renderMarkdown(p.text)) : partHtml(p, live, voice, placed, anchors, turn.id)))}`;
235235 }
236236
237 /**
238 * The block being written, drawn as the stored reply will be: the same Markdown, the cards it has
239 * placed so far and its whole blocks. Its choices are never buttons: only a stored reply's are.
240 */
241 export function liveHtml(db: Database, userId: string, conversationId: string, text: string, origin: string, linked: (md: Html) => Html): Html {
242 const whole = wholeSoFar(text);
243 if (!/^::show c|^`{3,}(?:forge|choices|plan|known)/m.test(whole)) return linked(renderMarkdown(whole));
244 const turn: Turn = { id: "", conversationId, role: "agent", text: whole, createdAt: "", replaced: false, failed: false };
245 return agentHtml(turn, voiceOf(db, userId, conversationId, [turn], origin), linked);
246 }
247
237248 /**
238249 * The voice's rules, appended to the page's stylesheet: existing tokens, 44 px targets, logical
239250 * sides.
test/talk-live-voice.test.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * The block being written is drawn as the stored reply will be (docs/features/talk-voice.md,
3 * docs/features/talk.md "Live"): a `forge` block shows only once its fence is closed, a `::show`
4 * line only once it is whole, and the choices of a reply still being written are never buttons.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createConversation } from "../src/core/conversations.ts";
12 import { recordCard, wholeSoFar } from "../src/core/talk_voice.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { agentHtml, liveHtml, voiceOf } from "../src/web/talk_parts.ts";
15 import type { Html } from "../src/web/html.ts";
16
17 const same = (md: Html): Html => md;
18
19 describe("what of a reply being written may be drawn", () => {
20 test("an open forge block is left out until its fence closes", () => {
21 const head = "Here is the plan.\n\n";
22 const block = '```forge\nplan\n{"steps":[{"text":"One","state":"todo"}]}\n';
23 expect(wholeSoFar(head + "```forge").trimEnd()).toBe(head.trimEnd());
24 expect(wholeSoFar(head + block).trimEnd()).toBe(head.trimEnd());
25 expect(wholeSoFar(head + block + "```\nAfter")).toBe(head + block + "```\nAfter");
26 });
27
28 test("a block fenced with its kind (`forge plan`, bare `plan`) is held back the same way; another fence is not", () => {
29 const head = "Here is the plan.\n\n";
30 for (const info of ["forge plan", "plan", "known", "choices", "forge known"]) {
31 const open = "```" + info + '\n{"steps":[{"text":"One",';
32 expect(wholeSoFar(head + open).trimEnd()).toBe(head.trimEnd());
33 }
34 const code = head + "```planner\nstep one";
35 expect(wholeSoFar(code)).toBe(code);
36 });
37
38 test("an ordinary code fence being written stays, forge-looking lines inside it too", () => {
39 const text = "Look:\n\n```ts\nconst a = 1;\n```forge-is-not-a-close\n::show c1";
40 expect(wholeSoFar(text)).toBe(text);
41 const closed = "```ts\nconst a = 1;\n```\n\n```forge\nknown";
42 expect(wholeSoFar(closed).trimEnd()).toBe("```ts\nconst a = 1;\n```");
43 });
44
45 test("a last line that may become a show line waits; a whole one and other lines stay", () => {
46 for (const tail of [":", "::", "::sh", "::show", "::show ", "::show c", "::show c1"])
47 expect(wholeSoFar(`Answer.\n\n${tail}`)).toBe("Answer.\n");
48 expect(wholeSoFar("Answer.\n\n::show c1\n")).toBe("Answer.\n\n::show c1\n");
49 expect(wholeSoFar("Answer.\n\n::shown")).toBe("Answer.\n\n::shown");
50 expect(wholeSoFar("a: b")).toBe("a: b");
51 });
52 });
53
54 describe("the live block's markup", () => {
55 let dir: string;
56 let app: App;
57 let user: User;
58 let conversationId: string;
59
60 beforeAll(async () => {
61 dir = await mkdtemp(join(tmpdir(), "forge-live-voice-"));
62 app = createApp({ dataDir: dir, port: 0 });
63 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
64 if (!made.ok) throw new Error("no user");
65 user = made.value;
66 const c = createConversation(app.db, user.id);
67 if (!c.ok) throw new Error("no conversation");
68 conversationId = c.value.id;
69 recordCard(app.db, `conversation:${conversationId}`, user.id, "now", "Read what the crew is doing", { kind: "crew", title: "Working now", status: "1 going", rows: [{ label: "mason", value: "on #12" }], actions: [] }, "http://forge.test");
70 });
71 afterAll(async () => {
72 app.close();
73 await rm(dir, { recursive: true, force: true });
74 });
75
76 test("text with neither addition is the plain Markdown", () => {
77 expect(liveHtml(app.db, user.id, conversationId, "Just **words**.", "http://forge.test", same).text).toContain("<strong>words</strong>");
78 });
79
80 test("a placed result is drawn as its card while the reply is still being written", () => {
81 const out = liveHtml(app.db, user.id, conversationId, "The crew:\n\n::show c1\n\nAnd then", "http://forge.test", same).text;
82 expect(out).toContain("talk-card");
83 expect(out).toContain("Working now");
84 expect(out).not.toContain("::show");
85 });
86
87 test("whole choices are drawn, never as buttons that send", () => {
88 const text = 'Which?\n\n```forge\nchoices\n{"question":"Which one?","options":["The first","The second"]}\n```\n';
89 const out = liveHtml(app.db, user.id, conversationId, text, "http://forge.test", same).text;
90 expect(out).toContain("Which one?");
91 expect(out).toContain("The first");
92 expect(out).not.toContain("<form");
93 });
94
95 test("a stored reply with the same words draws the same card", () => {
96 const text = "The crew:\n\n::show c1\n";
97 const turn = { id: "zz", conversationId, role: "agent" as const, text, createdAt: "", replaced: false, failed: false };
98 const stored = agentHtml(turn, voiceOf(app.db, user.id, conversationId, [turn], "http://forge.test"), same).text;
99 const live = liveHtml(app.db, user.id, conversationId, text, "http://forge.test", same).text;
100 expect(live.replaceAll(/t-zz-|t--/g, "")).toContain("Working now");
101 expect(stored).toContain("Working now");
102 });
103 });
test/talk-live.test.ts +48
@@ -907,6 +907,26 @@ describe("the terminal", () => {
907907 expect(t.out().split("Line one.").length).toBe(2);
908908 });
909909
910 test("`talk --follow` prints a block and a shown result as forge talk does, never a handle or a block's JSON, live or stored", async () => {
911 const name = "follow-voice";
912 const block = '```plan\n{"steps":[{"text":"Read the logs","state":"done"}]}\n```';
913 const whole = `Here is the plan.\n${block}\n::show c9\nDone.`;
914 const bin = stub(name, [start(0, { type: "text", text: "" }), text('Here is the plan.\n```plan\n{"steps":[{"text":"Read'), "gate:one", text(' the logs","state":"done"}]}\n```\n::show c9\nDone.'), assistant("m1", [{ type: "text", text: whole }]), result(whole)]);
915 configureConversation(app, options(bin));
916 const t = terminal("--follow show me the plan");
917 await t.until("Here is the plan.");
918 // Mid-block the open fence and its JSON are held back.
919 expect(t.out()).not.toContain("steps");
920 open(name, "one");
921 await t.exited;
922 expect(t.code()).toBe(0);
923 expect(t.out()).toContain("Plan:\r\n 1. [done] Read the logs");
924 expect(t.out()).toContain("Result not found.");
925 expect(t.out()).not.toContain("::show");
926 expect(t.out()).not.toContain('"steps"');
927 expect(t.out()).not.toContain("```");
928 });
929
910930 test("a held action is printed with how to answer it, and the exec still ends with the turn", async () => {
911931 const made = await createRepo(app, alice, { name: "follow-held", visibility: "public" });
912932 if (!made.ok) throw new Error(String(made.error));
@@ -1006,3 +1026,31 @@ describe("a credential-shaped string", () => {
10061026 expect(runningStep('mcp__claude_ai_forge__issue {"number":3}')).toBe("Opening issue #3…");
10071027 });
10081028 });
1029
1030 describe("a queued message", () => {
1031 test("runs after the answer on the same stream: the queue empties on the page, and its turn and answer arrive", async () => {
1032 const name = "queued";
1033 const bin = stub(name, [start(0, { type: "text", text: "" }), text("First answer."), "gate:one", assistant("m1", [{ type: "text", text: "First answer." }]), result("First answer.")]);
1034 const first = say(app, options(bin), alice.id, "first");
1035 if (!first.ok) throw new Error(first.error);
1036 const conversation = openConversation(app.db, alice.id);
1037 const queued = say(app, options(bin), alice.id, "second", [], "queue");
1038 expect(queued.ok && queued.value.how).toBe("queued");
1039 const s = await stream(`/talk/stream?c=${conversation.id}&after=`, alice);
1040 await s.until((f) => f.event === "queued" && (f.data["items"] as unknown[]).length === 1);
1041 open(name, "one");
1042 // The stand-in's gate is open, so the queued turn answers at once.
1043 const emptied = await s.until((f) => f.event === "queued" && (f.data["items"] as unknown[]).length === 0);
1044 const sent = await s.until((f) => f.event === "turn" && f.data["role"] === "person" && String(f.data["html"]).includes("second"));
1045 const done = await s.until((f) => f.event === "done");
1046 const order = (f: Frame) => s.frames.indexOf(f);
1047 // The stream did not end between the two answers.
1048 expect(s.frames.filter((f) => f.event === "done")).toHaveLength(1);
1049 expect(order(emptied)).toBeLessThan(order(done));
1050 expect(order(sent)).toBeLessThan(order(done));
1051 const answers = s.frames.filter((f) => f.event === "turn" && f.data["role"] === "agent" && String(f.data["html"]).includes("First answer."));
1052 expect(answers).toHaveLength(2);
1053 expect(order(answers[1]!)).toBeLessThan(order(done));
1054 await s.ended;
1055 });
1056 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs