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

Talk's confirms wait above the composer, things done fold into one line, and the pane shows the code and the diff itself #16297

Merged opened this

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

Merged

talk/look-5-dock-tabs → main 1 commit 1 thread · 1 unresolved

  • Merged. talk/look-5-dock-tabs was merged into main as ad99c66.

Review

Sign in to review this change.
20 files changed +857 −134
docs/design/areas/talk.md +4
@@ -127,3 +127,7 @@ Prior art: Claude and ChatGPT (one centred column, the person's words in a quiet
127127 - `.talk-work-line`: under a receipt that names an issue, what the crew is doing on it now (queued, working for how long, the pull it pushed and its checks, waiting for you, landed), a live region swapped from `/live/talk-work`.
128128 - `.talk-to`: the line above the composer's field while its words go to an issue (Reply on a receipt): to whom, and the way back to the forge.
129129 - `.talk-when`: a turn's or receipt's time, said quietly; in a receipt's line it stands apart from the title, as the time does in a reply's last row.
130 - `.talk-asks`, `.talk-asks-count`, `.talk-ask-list`: the dock directly above the composer holding what waits on the person (held actions): always in view, never in the thread; several read as a count and a stack, the first open, never taller than a third of the screen.
131 - `.talk-ask`, `.talk-ask-does`, `.talk-ask-left`, `.talk-ask-acts`: one ask: the engine's sentence of what will happen, the time left only under two minutes, Do it and a quiet Not now. Answered, it collapses out of the dock.
132 - `.talk-code`, `.talk-code-changed`, `.talk-code-files`, `.talk-code-tree`, `.talk-code-file`, `.talk-code-n`, `.talk-code-add`, `.talk-code-del`: the pane's Code tab: the files this conversation changed (with what each added and removed) above the repository's own explorer tree at the conversation's branch; a file opens in the pane from the blob page's fragment, with the way back to the files.
133 - `.talk-diff`, `.talk-diff-head`, `.talk-diff-versions`, `.talk-diff-pull`: the pane's Diff tab: which change (all, or one version), the totals, the pull as a quiet link with its checks in words, then the forge's own diff, each file folded open inline.
docs/design/baseline.json +1 −2
@@ -12,8 +12,7 @@
1212 "space": 7
1313 },
1414 "src/web/pages/talk_client.ts": {
15 "zindex": 2,
16 "space": 1
15 "zindex": 2
1716 },
1817 "src/web/pick.ts": {
1918 "space": 1
docs/design/quiet-debt.json −3
@@ -456,9 +456,6 @@
456456 "src/web/pages/talk.ts": {
457457 "bare-list": 3
458458 },
459 "src/web/pages/talk_preview.ts": {
460 "bare-list": 1
461 },
462459 "src/web/pages/teams.ts": {
463460 "bare-list": 2,
464461 "pagehead": 2
docs/design/size-budget.json +2 −2
@@ -68,8 +68,8 @@
6868 "css": 48384
6969 },
7070 "/talk": {
71 "js": 35584,
72 "css": 53504
71 "js": 37632,
72 "css": 53760
7373 },
7474 "/:owner/:name/pulls/:number": {
7575 "js": 32000,
docs/features/talk.md +17 −1
@@ -136,7 +136,7 @@ A reply is drawn by the README renderer and then, for Talk alone, by `linkTalk`
136136
137137 An agent reply is Markdown, drawn on the server by the same renderer as a README: fenced code is highlighted, tables and links render, and everything else is escaped (a `<script>` in a reply shows as text). A table wider than the column scrolls inside it; the page does not. The reply sits in the column like a person's turn, with none of the README's padding or line measure.
138138
139 A reply grows in one live element while it is written (see "Live") and is then stored as one finished turn; the page only appends a turn whose id it has not drawn (a repeat is ignored). Turns already on the page are not touched, so nothing above a new reply moves, and the page follows the end only if you were already there (otherwise "Latest" appears). An unfinished fence in a stored reply is closed for drawing. The page's own bytes are held by a test (`test/talk-page.test.ts`): the stylesheet under 15,500 B, the script under 35,200 B, and a page with a code reply under 45,000 B (its own page: one question and a code reply).
139 A reply grows in one live element while it is written (see "Live") and is then stored as one finished turn; the page only appends a turn whose id it has not drawn (a repeat is ignored). Turns already on the page are not touched, so nothing above a new reply moves, and the page follows the end only if you were already there (otherwise "Latest" appears). An unfinished fence in a stored reply is closed for drawing. The page's own bytes are held by a test (`test/talk-page.test.ts`): the stylesheet under 16,900 B, the script under 42,300 B, and a page with a code reply under 47,000 B (its own page: one question and a code reply).
140140
141141 ## Following
142142
@@ -206,3 +206,19 @@ A receipt is one calm line in the thread: a check, what was done and its link, t
206206 **Where the card opens:** below the link while it fits on the screen (over the composer at worst, never over what is being read above it), else above, and always held inside the screen under the top bar; the 300 ms and 150 ms intent delays are unchanged.
207207
208208 **In the terminal** a conversation keeps a receipt that names an issue in view (never folded with steps), with the same work line under it, and `c` comments on that issue through the same `addCommentThrough`.
209
210 ## Asks wait above the composer (#15734)
211
212 A held action (one that asks before it acts) is never drawn in the scrolled thread, where a long reply could push it off screen. It waits in a dock directly above the composer, always in view: the engine's one sentence of what will happen and to what, **Do it**, and a quiet **Not now**, with the time left only when under two minutes. Several read as "2 waiting" and a stack, the first open and the rest one line each; the stack never grows past a third of the screen and scrolls inside itself beyond that. The dock is part of the composer, so the thread's end stays clear of it and following holds; its buttons come before the box in the Tab order, Enter on Do it answers, and Escape is never Not now. A new ask is said once, politely.
213
214 Its buttons belong to the composer's form and post to the confirm's own address (`formaction`), so the dock works without the script. Answered, the ask collapses out of the dock (instantly where motion is reduced) and its outcome arrives in the thread where it happened: the receipt for Do it, or "Not now: nothing was done." Only an ask that ran out says so in the thread, with Ask again.
215
216 **Things done fold:** a run of receipts and steps in one reply reads as one line with a check, "2 things done, 3 steps", opening to the list; one receipt alone stays as itself. Proof: `test/talk-page.test.ts`, `test/talk-live.test.ts`.
217
218 **In the terminal** an ask still waiting is never in the scrolled thread either: it waits at the foot of the conversation with its sentence, and `a` opens Confirms, where `y` does it and `n` says not now.
219
220 ## The pane's Code and Diff (#15734)
221
222 Beside a conversation that builds or changes an app, the pane's **Code** tab is the repository's files at the conversation's branch from the first moment: the files this conversation changed come first under "Changed here", each with what it added and removed, and are marked in the tree; the tree is the repository page's own explorer, and a file opens in the pane from the blob page's own view, with **Files** to go back. **Diff** is the change itself, inline: the forge's diff with its highlighting, each file folded open, for everything the branch changed against the default branch, or one version's own change when its chip is chosen (All, v1, v2, …). The pull is a quiet link in the head with its checks in words ("Pull #2 · checks passing"). Both are read only when their tab is opened, and a tab swaps the pane in place from the page's own fragment (`?pane=code&fragment=pane`), so nothing is a page in a frame. A preview that has not loaded in ten seconds says so in words, and one not there yet says why, never a blank box. Proof: `test/talk-steps.test.ts`, `test/talk-page.test.ts`.
223
224 **In the terminal** the pane (`p`) lists what the conversation's branch changed, each file with its +/− counts, then the diff itself, read through the same `branchDiff`.
src/core/chat_build.ts +52
@@ -4,6 +4,11 @@
44 * Plain rows in, plain rows out; the git side lives in `actions/build.ts`.
55 */
66 import type { Database } from "bun:sqlite";
7 import { diffBetween, getPull } from "./pulls.ts";
8 import type { Repo } from "./repos.ts";
9 import type { Diff } from "../git/diff.ts";
10 import { refTip } from "../git/read.ts";
11 import { repoDir } from "../git/repos.ts";
712
813 export interface ChatBuild {
914 readonly conversationId: string;
@@ -78,3 +83,50 @@ export function buildsOf(db: Database, userId: string): BuildRow[] {
7883 .all(userId) as { conversation_id: string; repo_id: string; published_at: string | null; title: string; updated_at: string }[];
7984 return rows.map((r) => ({ conversationId: r.conversation_id, title: r.title, repoId: r.repo_id, published: r.published_at !== null, updatedAt: r.updated_at }));
8085 }
86
87 /** What the pane works on: the repository, the branch the conversation changes, its pull. */
88 export interface PaneWork {
89 readonly repo: Repo;
90 readonly build: ChatBuild | undefined;
91 readonly pull: number | undefined;
92 }
93
94 /** The branch the conversation's changes live on: its build's, else its pull's head, else the default. */
95 export const branchOf = (db: Database, w: PaneWork): string =>
96 w.build?.branch ??
97 (w.pull === undefined
98 ? undefined
99 : getPull(db, w.repo.id, w.pull)?.headBranch) ??
100 w.repo.defaultBranch;
101
102 /** The branch against the default branch, from where they parted: what this conversation changed. */
103 export async function branchDiff(
104 db: Database,
105 reposRoot: string,
106 w: PaneWork,
107 ): Promise<
108 { diff: Diff; from: string; head: string; branch: string } | undefined
109 > {
110 const dir = repoDir(reposRoot, w.repo.ownerName, w.repo.name);
111 const branch = branchOf(db, w);
112 const head = await refTip(dir, `refs/heads/${branch}`);
113 const base = await refTip(dir, `refs/heads/${w.repo.defaultBranch}`);
114 if (base === undefined) return undefined;
115 // A build's branch is made with its first change: until then nothing has changed.
116 if (head === undefined)
117 return {
118 diff: { files: [], additions: 0, deletions: 0 },
119 from: base,
120 head: base,
121 branch: w.repo.defaultBranch,
122 };
123 if (head === base)
124 return {
125 diff: { files: [], additions: 0, deletions: 0 },
126 from: base,
127 head,
128 branch,
129 };
130 const d = await diffBetween(dir, base, head);
131 return d.failed ? undefined : { diff: d.diff, from: d.from, head, branch };
132 }
src/tui/screens/talk_chats.ts +52 −2
@@ -33,6 +33,9 @@ import { cardsPlaced, plainVoice } from "../../core/talk_voice.ts";
3333 import { setTalkDisplay, talkDisplay } from "../../core/settings.ts";
3434 import { talkDisplayScreen } from "./talk_display.ts";
3535 import { liveReceipts, type LiveReceipt } from "../../core/talk_work.ts";
36 import { confirmsScreen } from "./confirms.ts";
37 import { waitingConfirms } from "../../actions/conversation_confirms.ts";
38 import { branchDiff, chatBuildOf } from "../../core/chat_build.ts";
3639 import { addCommentThrough } from "../../actions/issues.ts";
3740 import { getIssue } from "../../core/issues.ts";
3841 import { canRead, getRepo } from "../../core/repos.ts";
@@ -87,6 +90,15 @@ function downloadScreen(f: Session, ctx: Ctx, chat: Conversation): Screen {
8790 };
8891 }
8992
93 /** The confirm a confirm turn holds, or "" when its text is not one. */
94 const confirmOf = (text: string): string => {
95 try {
96 return String((JSON.parse(text) as { confirm?: unknown }).confirm ?? "");
97 } catch {
98 return "";
99 }
100 };
101
90102 /**
91103 * A link a reply makes to this forge, named as a person says it and as the page's peek shows it:
92104 * `owner/repo#12` for an issue or a pull, `owner/repo` for a repository; any other link stays.
@@ -115,6 +127,8 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
115127 let mark = 0;
116128 let placed = false;
117129 let pane = false;
130 // What the conversation's branch changed, read when the pane opens: the page's Code and Diff.
131 let changed: { branch: string; files: { path: string; additions: number; deletions: number; lines: string[] }[] } | undefined;
118132 // Display's steps choice is the person's own, the page's and the terminal's: v flips it here.
119133 const stepsNow = () => (f.user === undefined ? "folded" : talkDisplay(f.app.db, f.user.id).steps);
120134 type Turns = Exclude<ReturnType<typeof listTurns>, { ok: false }>["value"];
@@ -137,6 +151,20 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
137151 repo = repoOf(recent);
138152 };
139153 load();
154 const asksHere = () => {
155 if (f.user === undefined) return [];
156 const here = new Set(recent.filter((t) => t.role === "confirm").map((t) => confirmOf(t.text)));
157 return waitingConfirms(f, f.user).filter((w) => here.has(w.id));
158 };
159 // The branch this conversation changes against the default, as the page's Code and Diff read it.
160 const readChanged = async (): Promise<void> => {
161 const ws = repo === undefined || f.user === undefined ? undefined : workspaceOf(f.app, f.user, repo);
162 if (ws === undefined) return;
163 const build = chatBuildOf(f.app.db, chat.id);
164 const d = await branchDiff(f.app.db, f.app.reposRoot, { repo: ws.repo, build, pull: ws.pull ?? build?.pullNumber ?? undefined });
165 const sign = { add: "+", del: "-", context: " " } as const;
166 changed = d === undefined ? undefined : { branch: d.branch, files: d.diff.files.map((x) => ({ path: x.path, additions: x.additions, deletions: x.deletions, lines: x.hunks.flatMap((h) => h.lines.map((l) => `${sign[l.kind]}${l.content}`)) })) };
167 };
140168 const paneLines = (): string[] => {
141169 if (repo === undefined || f.user === undefined) return ["No repository yet."];
142170 const ws = workspaceOf(f.app, f.user, repo);
@@ -148,7 +176,13 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
148176 ws.url === undefined ? "Nothing running yet." : `Preview: ${ws.url}`,
149177 ws.pull === undefined ? "No open pull yet." : `Diff: /${repo}/pulls/${String(ws.pull)}/files`,
150178 "",
151 ...(files.length === 0 ? ["No files touched yet."] : ["Files touched:", ...files.map((p) => ` ${p}`)]),
179 ...(changed === undefined
180 ? files.length === 0
181 ? ["No files touched yet."]
182 : ["Files touched:", ...files.map((p) => ` ${p}`)]
183 : changed.files.length === 0
184 ? [`Nothing has changed yet on ${changed.branch}.`]
185 : [`Changed on ${changed.branch}:`, ...changed.files.map((d) => ` ${d.path} +${String(d.additions)} −${String(d.deletions)}`), "", ...changed.files.flatMap((d) => [d.path, ...d.lines, ""])]),
152186 ];
153187 };
154188 const lines = (): { text: string; style: ReturnType<typeof style> }[][] => {
@@ -162,8 +196,13 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
162196 const refs = refTarget(f.app.db, f.user, repo);
163197 let n = 0;
164198 const stepAt = (i: number) => (turns[i]?.role === "tool" && !receipts.has(turns[i]!.id) ? stepOf(turns[i]!.text) : undefined);
165 return turns.flatMap((t, i) => {
199 // An ask still waiting is never in the scrolled thread: it waits at the foot, as the page's dock.
200 const waiting = asksHere();
201 const asked = new Set(waiting.map((w) => w.id));
202 const dock = waiting.length === 0 ? [] : [[{ text: waiting.length === 1 ? "Waiting for you:" : `${String(waiting.length)} waiting:`, style: style(c.mutedFg, c.bg) }], ...waiting.map((w) => [{ text: ` ${w.does}`, style: style(c.fg, c.bg) }]), [{ text: "a answers: y does it, n not now. Nothing is done until you answer.", style: style(c.mutedFg, c.bg) }]];
203 const thread = turns.flatMap((t, i) => {
166204 if (t.id === around) mark = n;
205 if (t.role === "confirm" && asked.has(confirmOf(t.text))) return [];
167206 // A receipt that names an issue stays in view, with the crew's work line under it.
168207 const receipt = receipts.get(t.id);
169208 if (receipt !== undefined) {
@@ -189,6 +228,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
189228 [],
190229 ];
191230 });
231 return [...thread, ...dock];
192232 };
193233 const screen: Screen = {
194234 get title() {
@@ -204,6 +244,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
204244 binding(["v"], "steps open or folded"),
205245 binding(["D"], "display"),
206246 binding(["c"], "comment on the receipt's issue"),
247 binding(["a"], "answer what waits"),
207248 binding(["d", "x"], "export as Markdown"),
208249 binding(["esc"], "back"),
209250 ],
@@ -230,9 +271,18 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
230271 if (user === undefined || e.ctrl || e.alt) return false;
231272 if (e.key === "p" || (pane && e.key === "esc")) {
232273 pane = !pane;
274 if (pane)
275 runAsync(ctx, async () => {
276 await readChanged();
277 ctx.invalidate();
278 });
233279 ctx.invalidate();
234280 return true;
235281 }
282 if (e.key === "a") {
283 ctx.push(confirmsScreen(f, ctx));
284 return true;
285 }
236286 if (e.key === "D") {
237287 ctx.push(talkDisplayScreen(f, ctx));
238288 return true;
src/web/diff-view.ts +2 −1
@@ -21,6 +21,7 @@ import {
2121 import { composeLine } from "./code.ts";
2222 import type { Token } from "./highlight.ts";
2323 import { escapeHtml, html, raw, when, type Html } from "./html.ts";
24 import { urlPath } from "./pages/explorer.ts";
2425 import { btn, card, disclosure, empty, icon, time, userLink } from "./ui.ts";
2526 import { renderMarkdown } from "./markdown.ts";
2627 import { wordDiff, type Segment } from "./worddiff.ts";
@@ -443,7 +444,7 @@ function hunkHeader(hunk: Hunk): Html {
443444 * inside the same `<details>`; this adds why, the real counts, and a way to
444445 * read the file without paying for it here. No hunks reach the HTML. */
445446 function stubBody(file: FileDiff, stub: FileStub, opts: DiffViewOptions): Html {
446 const href = opts.fileLinkBase ? `${opts.fileLinkBase}/${file.path}` : null;
447 const href = opts.fileLinkBase ? `${opts.fileLinkBase}/${urlPath(file.path)}` : null;
447448 return html`<div class="diff-note diff-stub">
448449 <p>
449450 Diff not shown — ${stub.reason}.
src/web/icons.ts +1
@@ -84,6 +84,7 @@ const PATHS = {
8484 arrowDown: `<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>`,
8585 pause: `<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>`,
8686 arrowUp: `<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>`,
87 arrowLeft: `<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>`,
8788 paperclip: `<path d="m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"/>`,
8889 mic: `<path d="M12 19v3"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><rect x="9" y="2" width="6" height="13" rx="3"/>`,
8990 circleHalf: `<circle cx="12" cy="12" r="10"/><path d="M12 2a10 10 0 0 1 0 20z" fill="currentColor"/>`,
src/web/pages/explorer.ts +7 −4
@@ -29,6 +29,9 @@ import { icon } from "../icons.ts";
2929 import type { RepoScope } from "../scope.ts";
3030 import { refText } from "./refs.ts";
3131
32 /** A repository path as the code browser puts it in a link: each segment encoded, the slashes kept. */
33 export const urlPath = (path: string): string => path.split("/").map(encodeURIComponent).join("/");
34
3235 /** How deep the expanded spine goes. Past it, the column stops expanding. */
3336 export const MAX_EXPLORER_DEPTH = 12;
3437
@@ -134,7 +137,7 @@ function levelList(data: ExplorerData, base: string, at: number): Html {
134137 <details
135138 class="ex-dir"
136139 data-path="${path}"
137 data-url="${`${base}/tree/${encoded}/${path}`}"
140 data-url="${`${base}/tree/${encoded}/${urlPath(path)}`}"
138141 ${open ? raw("open") : null}
139142 >
140143 <summary ${current ? raw('data-current=""') : null}>
@@ -144,7 +147,7 @@ function levelList(data: ExplorerData, base: string, at: number): Html {
144147 ? levelList(data, base, at + 1)
145148 : html`<ul data-stub>
146149 <li>
147 <a class="ex-more" href="${`${base}/tree/${encoded}/${path}`}"
150 <a class="ex-more" href="${`${base}/tree/${encoded}/${urlPath(path)}`}"
148151 >${icon("folder")}Open ${entry.name}/</a
149152 >
150153 </li>
@@ -159,7 +162,7 @@ function levelList(data: ExplorerData, base: string, at: number): Html {
159162 data-ex-file
160163 data-nav
161164 tabindex="-1"
162 href="${`${base}/blob/${encoded}/${path}`}"
165 href="${`${base}/blob/${encoded}/${urlPath(path)}`}"
163166 ${current ? raw('aria-current="page"') : null}
164167 title="${path}"
165168 >${icon("file")}<span class="truncate">${entry.name}</span></a
@@ -174,7 +177,7 @@ function levelList(data: ExplorerData, base: string, at: number): Html {
174177 ? html`<li>
175178 <a
176179 class="ex-more"
177 href="${`${base}/tree/${encoded}${level.path === "" ? "" : `/${level.path}`}?all=1`}"
180 href="${`${base}/tree/${encoded}${level.path === "" ? "" : `/${urlPath(level.path)}`}?all=1`}"
178181 >Show all ${level.entries.length.toLocaleString("en-US")} entries</a
179182 >
180183 </li>`
src/web/pages/talk.ts +78 −30
@@ -18,7 +18,7 @@ import { blockedFlash } from "../blocked.ts";
1818 import { noTalkAccountBlocked } from "../../actions/blocked_words.ts";
1919 import type { Database } from "bun:sqlite";
2020 import { cancelTalk, queuedTalk, STARTER_PROMPTS, TALK_WORDS, talk, talkAgain } from "../../actions/talk.ts";
21 import { REFUSED, sayNo, sayYes, UNDO_REFUSED, undoReceipt, waitingConfirms } from "../../actions/conversation_confirms.ts";
21 import { REFUSED, sayNo, sayYes, UNDO_REFUSED, undoReceipt, waitingConfirms, type Waiting } from "../../actions/conversation_confirms.ts";
2222 import { filesOfTurns, type ConversationFile } from "../../core/conversation_files.ts";
2323 import {
2424 archiveConversation,
@@ -62,6 +62,8 @@ import { signInFirst, forbiddenPage, notFoundPage } from "../chrome.ts";
6262 import { field, readForm } from "../form.ts";
6363 import { html, raw, type Html } from "../html.ts";
6464 import { flashTo, fragment, page, redirect } from "../layout.ts";
65 import { getRepoById } from "../../core/repos.ts";
66 import { codePaneCss } from "../talk_code.ts";
6567 import { linkRefs, refTarget } from "../../text/talk_links.ts";
6668 import { appLook, linkTalk, talkLook, type TalkLook } from "../../text/talk_link_words.ts";
6769 import { liveCrewRows } from "../../actions/crew_now.ts";
@@ -123,21 +125,45 @@ const parse = (text: string): Record<string, unknown> | undefined => {
123125 }
124126 };
125127
126 /** Do it and Not now for a held action; each its own form, so each posts alone. */
127 function confirmButtons(id: string, tool: string): Html {
128 // A result shown once is drawn by Settings → Confirms, never kept in a turn.
128 /**
129 * One held action, as the dock draws it: the engine's sentence of what will happen and to what,
130 * Do it, and a quiet Not now. Its buttons belong to the composer's form and post to the confirm's
131 * own address (`formaction`), so the dock needs no form of its own and works without the script.
132 * A result shown once is answered in Settings → Confirms, which draws it there.
133 */
134 export function askItem(id: string, tool: string, does: string, expiresAt: string, shown = ""): Html {
129135 const once = ASKING[tool]?.once !== undefined;
130 return html`<div class="bar">
131 <form method="post" action="${once ? `/settings/confirms/${id}` : `${HERE}/confirm/${id}`}" ${once ? null : html`data-confirm`}>
132 <input type="hidden" name="answer" value="yes" />
133 ${btn("Do it", { variant: "primary", icon: "check", label: `Do it: ${tool}`, name: "answer", value: "yes" })}
134 </form>
135 <form method="post" action="${HERE}/confirm/${id}" data-confirm>
136 ${btn("Not now", { icon: "x", label: `Not now: ${tool}`, name: "answer", value: "no" })}
137 </form>
136 return html`<div class="talk-ask" id="ask-${id}" data-ask="${id}" data-expires="${expiresAt}">
137 <p class="talk-ask-does">${does}</p>
138 ${shown === "" ? null : html`<details><summary>Everything it will send</summary><pre>${shown}</pre></details>`}
139 <p class="talk-ask-left small muted">${WAITS}</p>
140 <div class="talk-ask-acts">
141 <button type="submit" class="btn" data-variant="primary" formaction="${once ? `/settings/confirms/${id}` : `${HERE}/confirm/${id}`}" formnovalidate name="answer" value="yes"${once ? null : raw(" data-answer")}>${icon("check")} Do it</button>
142 <button type="submit" class="btn" data-variant="ghost" formaction="${HERE}/confirm/${id}" formnovalidate name="answer" value="no" data-answer>Not now</button>
143 </div>
138144 </div>`;
139145 }
140146
147 /**
148 * What waits on the person in this conversation, docked directly above the composer: always in
149 * view, never in the thread. One shows whole; several are a count and a stack, the first open.
150 */
151 function asksDock(asks: Html[]): Html {
152 return html`<div class="talk-asks" data-asks role="region" aria-label="Waiting for your answer"${asks.length === 0 ? raw(" hidden") : null}${asks.length > 1 ? raw(" data-many") : null}>
153 <p class="talk-asks-count small muted" data-asks-count>${asks.length > 1 ? `${asks.length} waiting` : ""}</p>
154 <div class="talk-ask-list">${asks}</div>
155 </div>`;
156 }
157
158 /** The asks still waiting among these turns, in order, drawn for the dock. */
159 const asksOf = (turns: readonly Turn[], waiting: readonly Waiting[]): Html[] =>
160 turns.flatMap((t) => {
161 if (t.role !== "confirm" || t.replaced) return [];
162 const d = parse(t.text);
163 const w = waiting.find((x) => x.id === String(d?.["confirm"] ?? ""));
164 return w === undefined ? [] : [askItem(w.id, w.tool, typeof d?.["does"] === "string" ? d["does"] : w.does, w.expiresAt, typeof d?.["shown"] === "string" ? d["shown"] : "")];
165 });
166
141167 /** The turns a page holds that say they undid another: those receipts have no Undo left. */
142168 const undoneIn = (turns: readonly Turn[]): Set<string> =>
143169 new Set(
@@ -165,7 +191,7 @@ function receiptCard(id: string, turnId: string, receipt: Receipt, at: string, s
165191 : undone
166192 ? html`<span class="small muted">Undone.</span>`
167193 : html`<form method="post" action="${HERE}/undo/${turnId}">${btn(receipt.undo.label, { icon: "history", label: receipt.undo.label, size: "sm", variant: "ghost" })}</form>`;
168 return html`<li class="talk-turn talk-receipt${set}" id="${id}">
194 return html`<li class="talk-turn talk-receipt${set}" id="${id}" data-done>
169195 <p class="talk-receipt-line">${icon("check")}<span><strong>${receipt.verb}</strong> <a href="${receipt.href}">${receipt.object}</a>${title === "" ? null : html` <span class="muted">${title}</span>`} <span class="talk-when">${time(at)}</span></span></p>
170196 ${issue === null ? null : html`<p class="talk-work-line small muted" id="w-${turnId}" data-live="run.*,issue.*,pull.*,comment.*" data-live-repo="${issue[1]}/${issue[2]}" data-live-src="/live/talk-work?href=${encodeURIComponent(receipt.href)}&amp;id=w-${turnId}">${line}</p>`}
171197 ${undo === null && issue === null ? null : html`<div class="talk-receipt-acts">${undo}${issue === null ? null : html`<a class="btn" data-size="sm" data-variant="ghost" href="${receipt.href}#comment-body" data-reply="${receipt.href}" data-reply-to="${receipt.object}">${icon("comment")} Reply on ${receipt.object}</a>`}</div>`}
@@ -214,6 +240,10 @@ const stepCard = (id: string, step: Step, at: string, set = ""): Html =>
214240 * How a run of steps is named on its closed disclosure: one step by its own words ("Read
215241 * src/a.ts"), more by their count.
216242 */
243 /** "3 things done", and the steps beside them: the line a busy turn's run of actions reads as. */
244 export const doneWord = (done: number, steps: number): string =>
245 `${done === 1 ? "1 thing done" : `${done} things done`}${steps === 0 ? "" : `, ${steps === 1 ? "1 step" : `${steps} steps`}`}`;
246
217247 const stepsWord = (run: readonly Html[]): string =>
218248 run.length === 1 ? (/<summary>([^<]*)</.exec(run[0]!.text)?.[1]?.trim() ?? "1 step") : `${run.length} steps`;
219249
@@ -241,11 +271,15 @@ export function foldSteps(open: boolean, turns: readonly Html[]): Html[] {
241271 const out: Html[] = [];
242272 let run: Html[] = [];
243273 const close = (): void => {
244 if (run.length > 0) out.push(html`<li class="talk-fold" data-steps><details${open ? raw(" open") : null}><summary class="small muted">${raw(stepsWord(run))}</summary><ol class="talk-fold-list">${run}</ol></details></li>`);
274 const dones = run.filter((t) => /^<li [^>]*\bdata-done\b/.test(t.text.trimStart())).length;
275 // One thing done alone stays as its own calm line; anything more folds into one.
276 if (dones === 1 && run.length === 1) out.push(run[0]!);
277 else if (run.length > 0)
278 out.push(html`<li class="talk-fold" data-steps${dones > 0 ? raw(" data-dones") : null}><details${open ? raw(" open") : null}><summary class="small muted">${dones > 0 ? icon("check") : null}<span data-n>${raw(dones > 0 ? doneWord(dones, run.length - dones) : stepsWord(run))}</span></summary><ol class="talk-fold-list">${run}</ol></details></li>`);
245279 run = [];
246280 };
247281 for (const t of turns) {
248 if (/^<li [^>]*\bdata-step\b/.test(t.text.trimStart())) run.push(t);
282 if (/^<li [^>]*\bdata-(step|done)\b/.test(t.text.trimStart())) run.push(t);
249283 else {
250284 close();
251285 out.push(t);
@@ -339,19 +373,14 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend,
339373 </li>`;
340374 const data = parse(turn.text);
341375 const thought = thinkingOf(turn);
376 // An ask waits in the dock, not here; once answered, the thread keeps its outcome (the receipt,
377 // or Not now) in the place it happened. Only one that ran out says so here, with the way on.
342378 if (turn.role === "confirm") {
343379 const confirm = String(data?.["confirm"] ?? "");
344 const tool = String(data?.["tool"] ?? "");
380 if (turn.replaced || waiting.has(confirm) || !expired.has(confirm)) return html``;
345381 return html`<li class="talk-turn talk-confirm${set}" id="${id}">
346382 <p>${String(data?.["does"] ?? turn.text)}</p>
347 ${typeof data?.["shown"] === "string" ? html`<details><summary>Everything it will send</summary><pre>${data["shown"]}</pre></details>` : null}
348 ${turn.replaced
349 ? html`<p class="muted small">Replaced.</p>`
350 : waiting.has(confirm)
351 ? html`${confirmButtons(confirm, tool)}<p class="muted small">${WAITS}</p>`
352 : expired.has(confirm)
353 ? ranOut(turn.conversationId)
354 : html`<p class="muted small">Answered.</p>`}
383 ${ranOut(turn.conversationId)}
355384 </li>`;
356385 }
357386 if (thought !== undefined)
@@ -511,7 +540,9 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
511540 ...(before === undefined ? {} : { before }),
512541 });
513542 const turns = listed.ok ? listed.value : [];
514 const waiting = new Set(waitingConfirms(ctx, user).map((w) => w.id));
543 const waitingList = waitingConfirms(ctx, user);
544 const waiting = new Set(waitingList.map((w) => w.id));
545 const asks = asksOf(turns, waitingList);
515546 const expired = ranOutOf(ctx, user.id, turns);
516547 const undone = undoneIn(turns);
517548 const sent = filesOfTurns(ctx.app.db, user.id, turns.filter((t) => t.role === "person").map((t) => t.id));
@@ -545,7 +576,20 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
545576 const voice = voiceOf(ctx.app.db, user.id, conversation.id, turns, ctx.url.origin);
546577 // The forge paths the replies name, each read once for the page however often they repeat.
547578 const look = talkLook(ctx.app.db, user, turns.filter((t) => t.role === "agent").map((t) => t.text), appLook(ctx.app, user));
548 const pane = talkPane(ctx, user, cited, works, view);
579 // The pane works on the build's repository when the conversation builds one, else the one it names.
580 const buildRow = chatBuildOf(ctx.app.db, conversation.id);
581 const builtRepo = buildRow === undefined ? undefined : getRepoById(ctx.app.db, buildRow.repoId);
582 const v = Number(ctx.url.searchParams.get("v") ?? "");
583 const wait = panel === null ? undefined : pending ? "Starting the preview…" : undefined;
584 const idle = panel === null ? undefined : running ? "Making the first version…" : "Your app appears here as soon as the first change is made.";
585 const pane = await talkPane(ctx, user, builtRepo === undefined ? cited : `${builtRepo.ownerName}/${builtRepo.name}`, works, view, undefined, {
586 ...(buildRow === undefined ? {} : { build: buildRow }),
587 ...(Number.isInteger(v) && v > 0 ? { version: v } : {}),
588 ...(wait === undefined ? {} : { wait }),
589 ...(idle === undefined ? {} : { idle }),
590 });
591 // A tab asks for the pane alone, so it swaps in place without the page.
592 if (ctx.url.searchParams.get("fragment") === "pane") return fragment(pane.html, { request: ctx.request });
549593 // The side pane is there only when it has something to show: an app being built, or one running.
550594 const split = panel !== null || pane.live;
551595 // The frame shows what runs; beside a build it waits for the build's own preview.
@@ -577,6 +621,8 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
577621 ${about}
578622 ${editing === undefined && about !== null ? html`<input type="hidden" name="about" value="${ctx.url.searchParams.get("about")}" />` : null}
579623 ${chosen === undefined ? null : html`<input type="hidden" name="template" value="${chosen}" />`}
624 ${asksDock(asks)}
625 <p class="sr-only" role="status" data-asks-said></p>
580626 <div class="talk-box">
581627 <div class="talk-chips" data-chips role="group" aria-label="Attached files"></div>
582628 <p class="talk-to small" data-to-line hidden><span></span> <button type="button" class="btn btn-icon" data-variant="ghost" data-to-off aria-label="Talk to the forge instead" title="Talk to the forge instead">${icon("x")}</button></p>
@@ -597,9 +643,9 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
597643 </form>
598644 <template id="talk-ico">${icon("copy")}${icon("check")}</template>
599645 </div>
600 ${split ? html`<div class="talk-work">${panel}${framed || panel === null ? pane.html : html`<aside class="talk-pane" aria-label="Preview"><div class="talk-stage talk-stage-wait" data-stage><p class="talk-stage-note small" data-stage-note>${pending ? "Starting the preview…" : running ? "Making the first version…" : "Your app appears here as soon as the first change is made."}</p></div></aside>`}</div>` : null}
646 ${split ? html`<div class="talk-work">${panel}${pane.html}</div>` : null}
601647 </div>`;
602 return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: talkCss + peekCss + (split ? paneCss : "") + (panel === null ? "" : buildCss) + voiceCss, scriptJs: `${talkJs}\n${liveRegionsJs}`, description: "Talk to the forge.", wide: true, ...(pane.frame === undefined || !framed ? {} : { frameSrc: pane.frame }) });
648 return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: talkCss + peekCss + (split ? paneCss + codePaneCss : "") + (panel === null ? "" : buildCss) + voiceCss, scriptJs: `${talkJs}\n${liveRegionsJs}`, description: "Talk to the forge.", wide: true, ...(pane.frame === undefined || !framed ? {} : { frameSrc: pane.frame }) });
603649 }
604650
605651 /**
@@ -886,7 +932,8 @@ export function talkStream(ctx: Ctx): Response {
886932 const running = clock.running(app, user.id, conversation.id);
887933 const fresh = turnsAfter(app.db, user.id, conversation.id, cursor);
888934 if (fresh.length > 0) {
889 const waiting = new Set(waitingConfirms(ctx, user).map((w) => w.id));
935 const waitingList = waitingConfirms(ctx, user);
936 const waiting = new Set(waitingList.map((w) => w.id));
890937 const expired = ranOutOf(ctx, user.id, fresh);
891938 const undone = undoneIn(fresh);
892939 const works = worksOf(app.db, user.id, conversation.id, fresh);
@@ -898,7 +945,8 @@ export function talkStream(ctx: Ctx): Response {
898945 const look = talkLook(app.db, user, fresh.filter((t) => t.role === "agent").map((t) => t.text), appLook(app, user));
899946 for (const turn of fresh) {
900947 // A frame lands in a page whose sprite is its own: its icons are drawn inline (`inlineIcons`).
901 emit("turn", { id: turn.id, role: turn.role, html: inlineIcons(turnHtml(turn, waiting, undefined, undefined, works.get(turn.id), sent.get(turn.id), expired, undone, refs, voice, look, receiptLines(app.db, user, [turn])).text) }, turn.id);
948 const ask = asksOf([turn], waitingList)[0];
949 emit("turn", { id: turn.id, role: turn.role, html: inlineIcons(turnHtml(turn, waiting, undefined, undefined, works.get(turn.id), sent.get(turn.id), expired, undone, refs, voice, look, receiptLines(app.db, user, [turn])).text), ...(ask === undefined ? {} : { ask: inlineIcons(ask.text) }) }, turn.id);
902950 cursor = turn.id;
903951 }
904952 // The page is told at once what the block holds after these turns, empty once it is
src/web/pages/talk_client.ts +157 −27
@@ -137,9 +137,13 @@ body:has(.talk-page) .foot { display: none; }
137137 .talk[data-density=compact] .talk-body.prose :is(p, ul, ol, pre, table, blockquote) { margin-bottom: 8px; }
138138 @keyframes talk-in { from { opacity: 0; transform: translateY(4px); } }
139139 @keyframes talk-fade { from { opacity: 0; } }
140
140141 @media (prefers-reduced-motion: no-preference) {
141142 .talk:not([data-motion=reduced]) :is(.talk-log > [data-in], .talk-fold-list > [data-in], .talk-jump:not([hidden])) { animation: talk-in var(--dur-3) var(--ease); }
142143 .talk:not([data-motion=reduced]) .talk-live [data-in] { animation: talk-fade var(--dur-3) var(--ease); }
144 .talk:not([data-motion=reduced]) .talk-ask[data-in] { animation: talk-in var(--dur-3) var(--ease); }
145 .talk:not([data-motion=reduced]) .talk-asks { transition: height var(--dur-3) var(--ease), padding var(--dur-3) var(--ease); }
146 .talk:not([data-motion=reduced]) .talk-ask[data-out] { transition: opacity var(--dur-2) var(--ease); }
143147 .talk-versions [data-in] { animation: talk-in var(--dur-3) var(--ease); }
144148 }
145149 .talk[data-motion=reduced] :is(*, ::before, ::after) { animation: none !important; transition: none !important; }
@@ -177,8 +181,22 @@ body:has(.talk-page) .foot { display: none; }
177181 @media (prefers-reduced-motion: reduce) { .talk-live .talk-steps:last-child, .talk-status:not(:empty), .talk-stage-note { animation: none; color: var(--muted-fg); background: none; } }
178182 .talk-links { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 2px 0 0; font-size: 13px; }
179183 .talk-confirm { padding: 12px 16px; border: 1px solid var(--border); border-radius: var(--radius); }
180 .talk-confirm .bar { margin-top: 8px; gap: 8px; }
181 .talk-confirm .btn { min-height: 2.75rem; flex: 1 1 8rem; }
184 .talk-asks { display: grid; align-content: start; gap: 4px; padding-bottom: 8px; overflow: hidden; }
185 .talk-asks[data-out] { padding-bottom: 0; }
186 .talk-asks[hidden], .talk-asks-count:empty { display: none; }
187 .talk-asks-count { margin: 0; padding-inline: 4px; }
188 .talk-ask-list { display: grid; gap: 4px; }
189 .talk-asks[data-many] .talk-ask-list { max-height: 33dvh; overflow-y: auto; overscroll-behavior: contain; }
190 .talk-ask { display: grid; gap: 8px; padding: 12px 0; border-top: 1px solid var(--border); }
191 .talk-ask-does, .talk-ask-left { margin: 0; }
192 .talk-ask-does { font-size: 15px; }
193 .talk-ask-acts { display: flex; flex-wrap: wrap; gap: 8px; }
194 .talk-ask-acts .btn { min-height: 2.75rem; }
195 .talk-ask[data-out] { opacity: 0; }
196 .talk-asks[data-many] .talk-ask:not(:first-child) { padding-block: 8px; }
197 .talk-asks[data-many] .talk-ask:not(:first-child) .talk-ask-does { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 14px; color: var(--muted-fg); }
198 .talk-asks[data-many] .talk-ask:not(:first-child) :is(.talk-ask-acts, .talk-ask-left) { display: none; }
199 .talk-fold[data-dones] summary > .ico { margin-inline-end: 8px; vertical-align: -3px; color: var(--muted-fg); }
182200 .talk:has(.talk-hello) .talk-log { flex: 0; margin-top: auto; }
183201 .talk:has(.talk-hello) .talk-compose { position: static; margin-bottom: auto; padding-bottom: 32px; }
184202 .talk-crew { margin: 0 0 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
@@ -533,21 +551,32 @@ if (root) {
533551 const at = log.querySelector("#live, [data-queued]");
534552 const put = (x) => (at ? at.before(x) : log.append(x));
535553 if (!li.classList.contains("talk-agent")) li.setAttribute("data-in", "");
536 if (!li.hasAttribute("data-step")) return put(li);
554 // Steps and things done in a row read as one line; one thing done alone stays itself.
555 const foldable = (x) => !!x && (x.hasAttribute("data-step") || x.hasAttribute("data-done"));
556 if (!foldable(li)) return put(li);
537557 const prev = at ? at.previousElementSibling : log.lastElementChild;
538558 let fold = prev && prev.hasAttribute("data-steps") ? prev : null;
559 if (!fold && li.hasAttribute("data-done") && !foldable(prev)) return put(li);
539560 if (!fold) {
540561 fold = Object.assign(document.createElement("li"), { className: "talk-fold" });
541562 fold.setAttribute("data-steps", "");
542563 const d = document.createElement("details");
543564 d.open = root.dataset.fold === "open";
544 d.append(Object.assign(document.createElement("summary"), { className: "small muted" }), Object.assign(document.createElement("ol"), { className: "talk-fold-list" }));
565 const sum = Object.assign(document.createElement("summary"), { className: "small muted" });
566 sum.append(document.createElement("span"));
567 sum.lastChild.setAttribute("data-n", "");
568 d.append(sum, Object.assign(document.createElement("ol"), { className: "talk-fold-list" }));
545569 fold.append(d);
546570 put(fold);
571 if (foldable(prev)) fold.querySelector("ol").append(prev);
547572 }
548573 fold.querySelector("ol").append(li);
549 const n = fold.querySelector("ol").children.length;
550 fold.querySelector("summary").textContent = n === 1 ? li.querySelector("summary").firstChild.textContent.trim() : n + " steps";
574 const items = [...fold.querySelector("ol").children], done = items.filter((x) => x.hasAttribute("data-done")).length, steps = items.length - done;
575 const sum = fold.querySelector("summary");
576 if (done && !fold.hasAttribute("data-dones")) { fold.setAttribute("data-dones", ""); const ic = fold.querySelector(".talk-receipt-line > .ico"); if (ic) sum.prepend(ic.cloneNode(true)); }
577 sum.querySelector("[data-n]").textContent = done
578 ? (done === 1 ? "1 thing done" : done + " things done") + (steps ? ", " + (steps === 1 ? "1 step" : steps + " steps") : "")
579 : steps === 1 ? items[0].querySelector("summary").firstChild.textContent.trim() : steps + " steps";
551580 };
552581 const decorate = (scope) => {
553582 scope.querySelectorAll(".talk-body pre:not([data-c])").forEach((pre) => {
@@ -646,6 +675,7 @@ if (root) {
646675 source.addEventListener("turn", (e) => {
647676 const turn = JSON.parse(e.data);
648677 last = turn.id;
678 if (turn.ask) addAsk(turn.ask);
649679 if (!document.getElementById("t-" + turn.id)) {
650680 place(turn.html);
651681 decorate(log);
@@ -661,7 +691,7 @@ if (root) {
661691 source.addEventListener("running", () => { dropActs(); mode(true); log.setAttribute("aria-busy", "true"); say("The forge is answering…"); });
662692 source.addEventListener("done", (e) => {
663693 log.removeAttribute("aria-busy");
664 mode(false); dropActs(true); say("The forge replied."); source.close(); source = null;
694 mode(false); dropActs(true); if (hush) hush = false; else say("The forge replied."); source.close(); source = null;
665695 setTimeout(() => { if (status.textContent === "The forge replied.") say(""); }, 4000);
666696 reframe();
667697 pullBuild();
@@ -699,6 +729,75 @@ if (root) {
699729 if (r && !e.metaKey && !e.ctrlKey && !e.shiftKey) { e.preventDefault(); talkTo(r.dataset.reply, r.dataset.replyTo); }
700730 if (e.target.closest && e.target.closest("[data-to-off]")) talkTo("", "");
701731 });
732 // The dock: what waits on the person, above the composer. An answered ask collapses out of it
733 // (instantly where motion is reduced) and its outcome arrives in the thread as a turn.
734 const dock = form.querySelector("[data-asks]"), asks = dock.querySelector(".talk-ask-list"), said = form.querySelector("[data-asks-said]");
735 const tell = (words) => { said.textContent = words; };
736 // The stream is read again only to bring the answer's outcome: its end says nothing.
737 let hush = false;
738 const countAsks = () => {
739 const n = asks.children.length;
740 dock.hidden = !n;
741 dock.toggleAttribute("data-many", n > 1);
742 dock.querySelector("[data-asks-count]").textContent = n > 1 ? n + " waiting" : "";
743 for (const a of asks.children) timeLeft(a);
744 };
745 // The time left is said once it is under two minutes, by one timeout per confirm set for that
746 // moment and for its end: never a clock that ticks.
747 const timeLeft = (a) => {
748 if (a.dataset.timed) return;
749 a.dataset.timed = "1";
750 const end = Date.parse(a.dataset.expires), p = a.querySelector(".talk-ask-left");
751 const tell = (words, over) => { if (!a.isConnected) return; p.hidden = false; p.textContent = words; if (over) a.querySelectorAll("button").forEach((b) => { b.disabled = true; }); };
752 setTimeout(() => tell("Less than 2 minutes left.", false), Math.max(0, end - 120000 - Date.now()));
753 setTimeout(() => tell("This ran out: nothing was done.", true), Math.max(0, end - Date.now()));
754 };
755 // The dock moves once, from the height it had to the one it has now (the next ask opened, or
756 // none left), so the thread above glides with it and never jumps. Reduced motion: at once.
757 const dropAsk = (a) => {
758 const from = dock.offsetHeight, last = asks.children.length === 1;
759 if (last) { a.setAttribute("data-out", ""); dock.setAttribute("data-out", ""); } else { a.remove(); countAsks(); }
760 const to = last ? 0 : dock.offsetHeight;
761 let over = false;
762 const done = () => { if (over) return; over = true; dock.style.height = ""; dock.removeAttribute("data-out"); if (last) { a.remove(); countAsks(); } };
763 dock.style.height = from + "px";
764 const glide = (parseFloat(window.getComputedStyle(dock).transitionDuration) || 0) * 1000;
765 if (!glide || from === to) return done();
766 setTimeout(done, glide + 100);
767 void dock.offsetHeight;
768 dock.style.height = to + "px";
769 const end = (e) => { if (e.target === dock && e.propertyName === "height") { dock.removeEventListener("transitionend", end); done(); } };
770 dock.addEventListener("transitionend", end);
771 };
772 const addAsk = (markup) => {
773 const t = document.createElement("template");
774 t.innerHTML = markup.trim();
775 const a = t.content.firstElementChild;
776 if (!a || asks.querySelector('[data-ask="' + a.dataset.ask + '"]')) return;
777 a.setAttribute("data-in", "");
778 asks.append(a);
779 countAsks();
780 tell("Waiting for your answer: " + a.querySelector(".talk-ask-does").textContent);
781 };
782 const answerAsk = async (b) => {
783 const a = b.closest(".talk-ask"), yes = b.value === "yes", buttons = a.querySelectorAll("button");
784 // Said without a visible line, so answering moves nothing; a refusal is said on the ask itself.
785 const refused = (why) => { const p = a.querySelector(".talk-ask-left"); p.hidden = false; p.textContent = why; tell(why); buttons.forEach((x) => { x.disabled = false; }); };
786 buttons.forEach((x) => { x.disabled = true; });
787 try {
788 const res = await fetch(b.getAttribute("formaction"), { method: "POST", headers: { accept: "application/json" }, body: new URLSearchParams({ answer: b.value }) });
789 const out = await res.json().catch(() => ({}));
790 if (res.status === 410) { window.location.reload(); return; }
791 if (!res.ok) return refused(out.message || "Nothing was done.");
792 tell(yes ? "Done." : "Not now: nothing was done.");
793 dropAsk(a);
794 hush = !paged;
795 follow();
796 } catch (_) {
797 refused("That was not sent: no connection.");
798 }
799 };
800 countAsks();
702801 const picker = form.querySelector("[data-files]");
703802 const attach = form.querySelector("[data-attach]");
704803 if (attach) { attach.hidden = false; attach.addEventListener("click", () => picker.click()); }
@@ -745,8 +844,11 @@ ${dictateJs}
745844 take(e.dataTransfer.files);
746845 });
747846 const send = async (e) => {
847 const by = e.submitter;
848 if (by && by.hasAttribute("formaction")) { if (by.hasAttribute("data-answer")) { e.preventDefault(); answerAsk(by); } return; }
748849 if (form.hasAttribute("data-build")) { clearTimeout(draftTimer); draft.save(""); return; }
749850 e.preventDefault();
851 hush = false;
750852 const text = box.value.trim();
751853 if (text && form.dataset.to) {
752854 say("Sending…");
@@ -806,23 +908,7 @@ ${dictateJs}
806908 });
807909 log.addEventListener("submit", async (e) => {
808910 const r = e.target.closest("form[data-again]");
809 if (r) { e.preventDefault(); again(r.dataset.again, new URLSearchParams(new FormData(r))); return; }
810 const f = e.target.closest("form[data-confirm]");
811 if (!f) return;
812 e.preventDefault();
813 const answer = e.submitter ? e.submitter.value : "no";
814 const body = new URLSearchParams({ answer });
815 say(answer === "yes" ? "Doing it…" : "Noted…");
816 try {
817 const res = await fetch(f.action, { method: "POST", headers: { accept: "application/json" }, body });
818 const out = await res.json().catch(() => ({}));
819 if (res.status === 410) { location.reload(); return; }
820 say(res.ok ? "" : out.message || "Nothing was done.");
821 f.replaceWith(Object.assign(document.createElement("p"), { className: "muted small", textContent: res.ok ? (answer === "yes" ? "Done." : "Not now.") : "Not done." }));
822 follow();
823 } catch (_) {
824 say("That was not sent: no connection.");
825 }
911 if (r) { e.preventDefault(); again(r.dataset.again, new URLSearchParams(new FormData(r))); }
826912 });
827913 resume();
828914 if (root.dataset.running === "1" && !paged) { log.setAttribute("aria-busy", "true"); follow(); }
@@ -912,7 +998,7 @@ ${dictateJs}
912998 document.addEventListener("pointerdown", (e) => { if (peek && !peek.contains(e.target) && !peekOf(e.target)) unpeek(); });
913999 document.addEventListener("keydown", (e) => { if (e.key === "Escape" && peek) { e.preventDefault(); e.stopImmediatePropagation(); unpeek(); } }, true);
9141000 document.addEventListener("click", async (e) => {
915 const a = e.target.closest("[data-shell] :is(.talk-tabs, .talk-pane nav) a:not(.talk-back)"), shell = a && a.closest("[data-shell]");
1001 const a = e.target.closest("[data-shell] :is(.talk-tabs, .talk-pane nav.seg) a:not(.talk-back)"), shell = a && a.closest("[data-shell]");
9161002 if (!a || e.metaKey || e.ctrlKey || e.shiftKey) return;
9171003 e.preventDefault();
9181004 const href = a.getAttribute("href");
@@ -920,10 +1006,54 @@ ${dictateJs}
9201006 if (a.closest(".talk-tabs")) { shell.dataset.pane = href.slice(6); if (shell.dataset.pane === "chat") resume(); else { detach(); window.scrollTo({ top: 0, behavior: "instant" }); } return; }
9211007 try {
9221008 const t = document.createElement("template");
923 t.innerHTML = await (await fetch(href)).text();
1009 t.innerHTML = await (await fetch(href + "&fragment=pane")).text();
9241010 const p = t.content.querySelector(".talk-pane");
925 if (p) shell.querySelector(".talk-pane").replaceWith(p);
1011 if (p) { shell.querySelector(".talk-pane").replaceWith(p); codePane(); p.querySelectorAll("[data-frame]").forEach(watchFrame); }
9261012 } catch (_) { say("Could not load that; no connection."); }
9271013 });
1014 // Code: a file opens in the pane from the blob page's own fragment; a folder fills itself in
1015 // from the explorer's; the files this conversation changed are marked wherever they show.
1016 const codePane = () => {
1017 const c = document.querySelector("[data-code]");
1018 if (!c) return;
1019 const changed = new Set((c.dataset.changed || "").split("\\n"));
1020 c.querySelectorAll(".ex-file").forEach((a) => { a.removeAttribute("tabindex"); if (changed.has(a.title)) a.setAttribute("data-changed", ""); });
1021 };
1022 document.addEventListener("click", async (e) => {
1023 const a = e.target.closest && e.target.closest("[data-code] :is(a.ex-file, a[data-pane-file])"), c = a && a.closest("[data-code]");
1024 if (e.target.closest && e.target.closest("[data-code-back]")) { const k = document.querySelector("[data-code]"); k.removeAttribute("data-open"); k.querySelector("[data-code-file]").hidden = true; return; }
1025 if (!a || e.metaKey || e.ctrlKey || e.shiftKey) return;
1026 e.preventDefault();
1027 try {
1028 const res = await fetch(a.getAttribute("href") + "?fragment=1");
1029 if (!res.ok) throw new Error();
1030 c.querySelector("[data-code-body]").innerHTML = await res.text();
1031 c.setAttribute("data-open", "");
1032 c.querySelector("[data-code-file]").hidden = false;
1033 c.querySelector("[data-code-back]").focus();
1034 } catch (_) { window.location.href = a.getAttribute("href"); }
1035 });
1036 document.addEventListener("toggle", async (e) => {
1037 const d = e.target;
1038 if (!d.matches || !d.matches("[data-code] details.ex-dir[open]")) return;
1039 const stub = d.querySelector(":scope > ul[data-stub]");
1040 if (!stub) return;
1041 stub.removeAttribute("data-stub");
1042 try {
1043 const t = document.createElement("template");
1044 t.innerHTML = await (await fetch(d.dataset.url + "?fragment=explorer")).text();
1045 const list = t.content.querySelector("ul");
1046 if (list) { stub.replaceWith(list); codePane(); }
1047 } catch (_) { stub.setAttribute("data-stub", ""); }
1048 }, true);
1049 // A preview that has not loaded in ten seconds says so, never a blank box.
1050 const watchFrame = (f) => {
1051 const s = f.closest("[data-stage]"), n = s && s.querySelector("[data-stage-note]");
1052 if (!n) return;
1053 const late = setTimeout(() => { n.hidden = false; n.textContent = "The preview is not answering yet. Open it on its own to see why."; }, 10000);
1054 f.addEventListener("load", () => clearTimeout(late), { once: true });
1055 };
1056 document.querySelectorAll("[data-frame]").forEach(watchFrame);
1057 codePane();
9281058 }
9291059 `;
src/web/pages/talk_preview.ts +20 −12
@@ -4,8 +4,8 @@
44 * `actions/talk_workspace.ts`'s, the same the terminal's `p` view reads. The
55 * preview is a frame of the running app's own origin (the page names that one
66 * origin in `frame-src`, nothing wider), reloaded by the script when a turn
7 * ends, which is when a push has deployed. Code lists the files the chat
8 * touched; Diff links the pull's files page, which cannot be framed. The tabs
7 * ends, which is when a push has deployed. Code and Diff are the forge's own
8 * browser and diff for the conversation's branch (`talk_code.ts`). The tabs
99 * are links (`?pane=`), the chosen one drawn by the server, so all of it works
1010 * with the script off; with it, a tab swaps the pane in place and the reply
1111 * streaming beside it carries on.
@@ -18,6 +18,8 @@ import type { Ctx } from "../../http/context.ts";
1818 import { html, raw, type Html } from "../html.ts";
1919 import { emptyLine } from "../empty_words.ts";
2020 import { btn, icon, iconBtn } from "../ui.ts";
21 import type { ChatBuild } from "../../core/chat_build.ts";
22 import { codeView, diffView } from "../talk_code.ts";
2123
2224 export interface Pane {
2325 readonly html: Html;
@@ -30,7 +32,16 @@ export interface Pane {
3032 export const VIEWS = ["preview", "code", "diff"] as const;
3133 export type View = (typeof VIEWS)[number];
3234
33 export function talkPane(ctx: Ctx, user: User, name: string | undefined, works: ReadonlyMap<string, Work>, view: View = "preview", apps?: Apps): Pane {
35 /** What the pane is told beyond its repository: the conversation's build, the version chosen, and
36 * the words for a preview that is not there yet. */
37 export interface PaneAsk {
38 readonly build?: ChatBuild;
39 readonly version?: number;
40 readonly wait?: string;
41 readonly idle?: string;
42 }
43
44 export async function talkPane(ctx: Ctx, user: User, name: string | undefined, works: ReadonlyMap<string, Work>, view: View = "preview", apps?: Apps, ask: PaneAsk = {}): Promise<Pane> {
3445 const empty = (words: Html): Pane => ({
3546 frame: undefined,
3647 live: false,
@@ -41,18 +52,15 @@ export function talkPane(ctx: Ctx, user: User, name: string | undefined, works:
4152 if (ws === undefined) return empty(emptyLine("talkHidden"));
4253 const { pull, url } = ws;
4354 const tab = (id: View, label: string): Html => html`<a href="?pane=${id}"${view === id ? raw(' aria-current="page"') : null}>${label}</a>`;
44 const files = [...new Map([...works.values()].flatMap((w) => w.links).filter((l) => l.href.includes("/blob/")).map((l) => [l.href, l] as const)).values()].slice(0, 12);
55 // Code and Diff are the forge's own browser and diff, read only when their tab is chosen.
56 const work = { repo: ws.repo, build: ask.build, pull: pull ?? ask.build?.pullNumber ?? undefined };
4557 const panel =
4658 view === "code"
47 ? files.length === 0
48 ? emptyLine("talkFiles")
49 : html`<ul class="list">${files.map((f) => html`<li><a href="${f.href}">${f.label}</a></li>`)}</ul>`
59 ? await codeView(ctx.app, work)
5060 : view === "diff"
51 ? pull === undefined
52 ? emptyLine("talkPulls")
53 : html`<p><a class="btn" href="/${name}/pulls/${String(pull)}/files">Diff of pull #${String(pull)}</a></p>`
54 : url === undefined
55 ? emptyLine("talkIdle")
61 ? await diffView(ctx.app, work, ask.version)
62 : url === undefined || ask.wait !== undefined
63 ? html`<div class="talk-stage talk-stage-wait" data-stage><p class="talk-stage-note small" data-stage-note>${ask.wait ?? ask.idle ?? "Nothing is running yet: the app appears here once it is built."}</p></div>`
5664 : html`<div class="talk-stage" data-stage><iframe class="talk-frame" data-frame src="${url}" title="Live preview of ${name}" referrerpolicy="no-referrer" sandbox="allow-scripts allow-same-origin allow-forms allow-popups"></iframe><p class="talk-stage-note small" data-stage-note hidden>Updating the preview…</p></div>`;
5765 // The address bar of what runs: which environment, where it lives, reload and open on its own.
5866 const where = url === undefined ? null : html`<span class="talk-addr small" title="${url}"><span class="muted">${pull === undefined ? "Production" : `Pull #${String(pull)}`}</span> ${new URL(url).host}</span>`;
src/web/talk_code.ts added +207
@@ -0,0 +1,207 @@
1 /**
2 * The Code and Diff tabs of /talk's side pane (#15734): the forge's own code browser and diff
3 * renderer, drawn for the branch the conversation works on, inside the pane. Nothing here is a
4 * second browser: the tree is `explorerFragment` (the repository page's own column), a file opens
5 * from the blob page's own fragment (`?fragment=1`), and a change is `renderDiff` with the same
6 * syntax map the pull's Files tab uses. Each is read only when its tab is chosen; the page serves
7 * the pane alone as a fragment (`?pane=code&fragment=pane`) so a tab swaps in place.
8 *
9 * - **Code:** from the first moment, the repository's files at the branch; the files this
10 * conversation changed come first, marked, once there are any.
11 * - **Diff:** every file changed, with what was added and removed, each file's diff folded open
12 * inline; all of the branch against the default branch, or one version's own change when a
13 * version is chosen. The pull is a quiet link in the head, with its checks in words.
14 */
15
16 import { branchDiff, branchOf, type PaneWork } from "../core/chat_build.ts";
17 import { checkSummary } from "../core/runs.ts";
18 import { getPull } from "../core/pulls.ts";
19 import { versionsIn } from "../actions/build_pull.ts";
20 import type { App } from "../app.ts";
21 import { diffCommit, type Diff } from "../git/diff.ts";
22 import { listTree, refTip } from "../git/read.ts";
23 import { repoDir } from "../git/repos.ts";
24 import { diffSyntax } from "./diff-syntax.ts";
25 import { renderDiff } from "./diff-view.ts";
26 import { html, raw, type Html } from "./html.ts";
27 import { explorerFragment, urlPath } from "./pages/explorer.ts";
28 import { icon } from "./ui.ts";
29
30 const counts = (f: { additions: number; deletions: number }): Html =>
31 html`<span class="talk-code-n diff-stat"
32 ><span class="add">+${f.additions}</span>
33 <span class="del">−${f.deletions}</span></span
34 >`;
35
36 /** The Code tab: the files changed here first, then the whole tree, each opening in the pane. */
37 export async function codeView(app: App, w: PaneWork): Promise<Html> {
38 const dir = repoDir(app.reposRoot, w.repo.ownerName, w.repo.name);
39 const base = `/${w.repo.ownerName}/${w.repo.name}`;
40 const changed = await branchDiff(app.db, app.reposRoot, w);
41 const branch = changed?.branch ?? w.repo.defaultBranch;
42 const ref =
43 (await refTip(dir, `refs/heads/${branch}`)) === undefined
44 ? w.repo.defaultBranch
45 : branch;
46 const tree = await listTree(dir, ref, "");
47 const files = (changed?.diff.files ?? []).filter(
48 (f) => f.status !== "deleted",
49 );
50 const encoded = encodeURIComponent(ref);
51 return html`<div
52 class="talk-code"
53 data-code
54 data-changed="${files.map((f) => f.path).join("\n")}"
55 >
56 ${files.length === 0
57 ? null
58 : html`<section
59 class="talk-code-changed"
60 aria-label="Changed in this conversation"
61 >
62 <h2 class="small muted">Changed here</h2>
63 <div class="talk-code-files">
64 ${files.map(
65 (f) =>
66 html`<p>
67 <a
68 href="${base}/blob/${encoded}/${urlPath(f.path)}"
outdated

Medium. f.path is only HTML-escaped, never URL-encoded. A changed file named a b.ts, x#1.ts or q?.ts gives a broken or truncated blob URL. The pane's click handler then appends ?fragment=1 to it and fetches the wrong resource. Encode each path segment, for example f.path.split('/').map(encodeURIComponent).join('/'), here and in the diff's fileLinkBase. Add a test with a file name containing a space and a #.

69 data-pane-file
70 title="${f.path}"
71 >${icon("file")}<span class="truncate">${f.path}</span></a
72 >${counts(f)}
73 </p>`,
74 )}
75 </div>
76 </section>`}
77 <nav
78 class="explorer talk-code-tree"
79 aria-label="Files of ${w.repo.name} on ${ref}"
80 >
81 ${tree.ok
82 ? raw(
83 explorerFragment(base, ref, "", tree.value).text.replaceAll(
84 ' tabindex="-1"',
85 "",
86 ),
87 )
88 : html`<p class="muted small">
89 The files could not be read just now.
90 </p>`}
91 </nav>
92 <div class="talk-code-file" data-code-file hidden>
93 <button
94 type="button"
95 class="btn"
96 data-variant="ghost"
97 data-size="sm"
98 data-code-back
99 >
100 ${icon("arrowLeft")} Files
101 </button>
102 <div data-code-body></div>
103 </div>
104 </div>`;
105 }
106
107 /** Checks in words, for the pull in the Diff tab's head. */
108 const CHECKS: Readonly<Record<string, string>> = {
109 ok: "checks passing",
110 failed: "checks failing",
111 running: "checks running",
112 queued: "checks queued",
113 cancelled: "checks cancelled",
114 };
115
116 /** The Diff tab: the change itself, all of it or one version's, each file folded open inline. */
117 export async function diffView(
118 app: App,
119 w: PaneWork,
120 version: number | undefined,
121 ): Promise<Html> {
122 const dir = repoDir(app.reposRoot, w.repo.ownerName, w.repo.name);
123 const name = `${w.repo.ownerName}/${w.repo.name}`;
124 const versions =
125 w.build === undefined ? [] : await versionsIn(app, w.repo, w.build);
126 const chosen = versions.find((v) => v.number === version);
127 let diff: Diff | undefined;
128 let syntax: Awaited<ReturnType<typeof diffSyntax>> | undefined;
129 if (chosen !== undefined) {
130 const one = await diffCommit(dir, chosen.oid);
131 if (one.ok) {
132 diff = one.value;
133 syntax = await diffSyntax(dir, diff, `${chosen.oid}^`, chosen.oid);
134 }
135 } else {
136 const all = await branchDiff(app.db, app.reposRoot, w);
137 if (all !== undefined) {
138 diff = all.diff;
139 syntax = await diffSyntax(dir, diff, all.from, all.head);
140 }
141 }
142 const pull =
143 w.pull === undefined ? undefined : getPull(app.db, w.repo.id, w.pull);
144 const checks =
145 pull === undefined
146 ? undefined
147 : CHECKS[checkSummary(app.db, pull.id, pull.headOid).state];
148 const pick = (n: number | undefined, label: string, title: string): Html =>
149 html`<a
150 href="?pane=diff${n === undefined ? "" : `&amp;v=${n}`}"
151 title="${title}"
152 ${(chosen?.number ?? undefined) === n
153 ? raw(' aria-current="page"')
154 : null}
155 >${label}</a
156 >`;
157 return html`<div class="talk-diff">
158 <div class="talk-diff-head small">
159 ${versions.length < 2
160 ? null
161 : html`<nav class="seg talk-diff-versions" aria-label="Which change">
162 ${pick(
163 undefined,
164 "All",
165 "Everything this conversation changed",
166 )}${versions.map((v) => pick(v.number, `v${v.number}`, v.subject))}
167 </nav>`}
168 ${pull === undefined
169 ? null
170 : html`<a
171 class="talk-diff-pull muted"
172 href="/${name}/pulls/${pull.number}"
173 >Pull
174 #${pull.number}${checks === undefined ? null : ` · ${checks}`}</a
175 >`}
176 </div>
177 ${diff === undefined
178 ? html`<p class="muted small">The change could not be read just now.</p>`
179 : diff.files.length === 0
180 ? html`<p class="muted small">
181 Nothing has changed yet: the first change shows here as soon as it
182 is made.
183 </p>`
184 : renderDiff(diff, {
185 ...(syntax === undefined ? {} : { syntax }),
186 fileLinkBase: `/${name}/blob/${encodeURIComponent(chosen?.oid ?? branchOf(app.db, w))}`,
187 })}
188 </div>`;
189 }
190
191 /** The two tabs' own styles, beside the pane's. Spacing is the scale; the code and diff are the site's. */
192 export const codePaneCss = `
193 .talk-pane { min-width: 0; }
194 .talk-code, .talk-diff { display: grid; gap: 12px; min-width: 0; }
195 .talk-code h2 { margin: 0 0 4px; font-size: 12.5px; font-weight: 600; }
196 .talk-code-files { display: grid; gap: 2px; }
197 .talk-code-files p { display: flex; align-items: center; gap: 8px; min-width: 0; }
198 .talk-code-files a, .talk-code-tree a { display: flex; align-items: center; gap: 6px; min-width: 0; min-height: 2.75rem; flex: 1; }
199 .talk-code-n { flex: none; font-size: 12.5px; font-variant-numeric: tabular-nums; }
200 .talk-code-tree .ex-file[data-changed]::after { content: "changed"; margin-inline-start: auto; font-size: 11.5px; color: var(--muted-fg); }
201 .talk-code-file { display: grid; gap: 8px; min-width: 0; }
202 .talk-code-file[hidden], .talk-code[data-open] > :is(.talk-code-changed, .talk-code-tree) { display: none; }
203 .talk-code-file > .btn { justify-self: start; }
204 .talk-diff-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
205 .talk-diff-pull { margin-inline-start: auto; }
206 .talk-diff, .talk-diff :is(.diff, .diff-file, .diff-summary) { min-width: 0; max-width: 100%; }
207 `;
test/conversation-holds.test.ts +13 −8
@@ -21,7 +21,7 @@ import { mintViaToken } from "../src/core/via_token.ts";
2121 import { ASKING, UNDOABLE } from "../src/crew/conversation_confirm.ts";
2222 import { ASKED_WRITES_MAX } from "../src/http/mcp/shared.ts";
2323 import { serve, type Servers } from "../src/http/server.ts";
24 import { ASK_AGAIN, turnHtml, WAITS } from "../src/web/pages/talk.ts";
24 import { ASK_AGAIN, askItem, turnHtml, WAITS } from "../src/web/pages/talk.ts";
2525 import { promote } from "./helpers/members.ts";
2626
2727 let dataDir: string;
@@ -149,13 +149,17 @@ describe("what nobody asked for stays held, with buttons", () => {
149149 expect(getIssue(app.db, w.repoId, 2)).toBeUndefined();
150150 const turns = confirmsIn(w.id);
151151 expect(turns.map((t) => JSON.parse(t.text).confirm)).toEqual(asks.map((a) => a.needs_confirm));
152 const waiting = new Set(waitingConfirms({ app }, alice).map((c) => c.id));
152 // Each waits in the dock above the composer with both buttons; the thread draws no copy.
153 const listed = waitingConfirms({ app }, alice);
154 const waiting = new Set(listed.map((c) => c.id));
153155 for (const t of turns) {
154 const drawn = turnHtml(t, waiting).text;
155 expect(drawn).toContain(`/talk/confirm/${JSON.parse(t.text).confirm}`);
156 expect(drawn).toContain("Do it");
157 expect(drawn).toContain("Not now");
158 expect(drawn).toContain(WAITS);
156 expect(turnHtml(t, waiting).text).toBe("");
157 const c = listed.find((x) => x.id === JSON.parse(t.text).confirm)!;
158 const docked = askItem(c.id, c.tool, c.does, c.expiresAt).text;
159 expect(docked).toContain(`/talk/confirm/${c.id}`);
160 expect(docked).toContain("Do it");
161 expect(docked).toContain("Not now");
162 expect(docked).toContain(WAITS);
159163 }
160164 // Said as the person would say it: no tool's name, no argument list, no clock.
161165 expect(asks.map((a) => a.does)).toEqual([
@@ -268,8 +272,9 @@ describe("a confirm past its time says so", () => {
268272 const w = await world(undefined, "what is new?");
269273 await call(w.token, "tell", { repo: w.repo, text: "steered" });
270274 const [turn] = confirmsIn(w.id);
275 // Answered, the ask leaves nothing of its own in the thread: its outcome turn says what happened.
271276 const drawn = turnHtml(turn!, new Set()).text;
272 expect(drawn).toContain("Answered.");
277 expect(drawn).toBe("");
273278 expect(drawn).not.toContain("Ask again");
274279 });
275280 });
test/talk-live.test.ts +4 −1
@@ -836,7 +836,10 @@ describe("a turn stored by another door", () => {
836836 });
837837 expect(await res.text()).toContain("needs_confirm");
838838 const confirm = await s.until((f) => f.event === "turn" && f.data["role"] === "confirm");
839 expect(String(confirm.data["html"])).toContain("Do it");
839 // The ask goes to the dock above the composer, whole; the thread draws no copy of it.
840 expect(String(confirm.data["html"])).toBe("");
841 expect(String(confirm.data["ask"])).toContain("Do it");
842 expect(String(confirm.data["ask"])).toContain("Not now");
840843 s.close();
841844 await s.ended;
842845 } finally {
test/talk-page.test.ts +141 −23
@@ -284,12 +284,24 @@ describe("the page", () => {
284284 const turn = (id: string, role: string, text: string) => turnHtml({ id, role, text, createdAt: "2026-01-01T00:00:00Z" } as any, new Set());
285285 const out = foldSteps(false, [turn("1", "person", "why"), turn("2", "tool", 'read_file {"repo":"a/b","path":"x.ts"}'), turn("3", "tool", 'runs {"repo":"a/b"}'), turn("4", "agent", "Because."), turn("5", "tool", 'read_file {"repo":"a/b","path":"y.ts"}')]).map((h) => h.text).join("");
286286 expect(out.match(/data-steps/g)?.length).toBe(2);
287 expect(out).toContain('<summary class="small muted">2 steps</summary>');
288 expect(out).toContain('<summary class="small muted">Read y.ts</summary>');
287 expect(out).toContain('<summary class="small muted"><span data-n>2 steps</span></summary>');
288 expect(out).toContain('<summary class="small muted"><span data-n>Read y.ts</span></summary>');
289289 expect(out.indexOf('id="t-2"')).toBeGreaterThan(out.indexOf("data-steps"));
290290 expect(out).not.toMatch(/<details open/);
291291 });
292292
293 test("the server folds a run of things done into one line, \"2 things done\", and leaves one alone as itself", async () => {
294 const { foldSteps, turnHtml } = await import("../src/web/pages/talk.ts");
295 const filed = (id: string, n: number) => turnHtml({ id, role: "tool", text: JSON.stringify({ done: true, filed: true, receipt: { verb: "Filed", object: `#${n}`, href: `/a/b/issues/${n}` } }), createdAt: "2026-01-01T00:00:00Z" } as any, new Set());
296 const person = turnHtml({ id: "p", role: "person", text: "and?", createdAt: "2026-01-01T00:00:00Z" } as any, new Set());
297 const two = foldSteps(false, [filed("1", 1), filed("2", 2)]).map((h) => h.text).join("");
298 expect(two.match(/class="talk-fold" data-steps data-dones/g)?.length).toBe(1);
299 expect(two).toContain("<span data-n>2 things done</span>");
300 const one = foldSteps(false, [person, filed("3", 3)]).map((h) => h.text).join("");
301 expect(one).not.toContain("data-steps");
302 expect(one).toContain('id="t-3" data-done>');
303 });
304
293305 test("motion is one vocabulary under reduced motion and the person's own choice, opacity and transform only", async () => {
294306 const { talkCss } = await import("../src/web/pages/talk_client.ts");
295307 const anim = [...talkCss.matchAll(/@keyframes [\w-]+ \{([^@]*?)\}\s*\}/g)].map((m) => m[1]!);
@@ -359,7 +371,7 @@ describe("the page", () => {
359371 const { talkCss, talkJs } = await import("../src/web/pages/talk_client.ts");
360372 const page = await (await get("/talk", alice)).text();
361373 expect(page).not.toMatch(/tabindex="-1"/);
362 expect(talkCss).toMatch(/\.talk-confirm \.btn \{[^}]*min-height: 2\.75rem/);
374 expect(talkCss).toMatch(/\.talk-ask-acts \.btn \{[^}]*min-height: 2\.75rem/);
363375 expect(talkCss).not.toContain("outline: none");
364376 expect(talkCss).not.toContain("outline: 0");
365377 expect(talkJs).not.toContain('tabindex", "-1"');
@@ -390,30 +402,29 @@ describe("the page", () => {
390402 if (id === null) throw new Error("hold");
391403 say(me, "confirm", JSON.stringify({ confirm: id, tool: "archive", does: "Archive it." }));
392404 const doc1 = parse(await (await get("/talk", me)).text());
393 const forms = [...doc1.querySelectorAll(`form[action="/talk/confirm/${id}"]`)];
394 expect(forms.length).toBeGreaterThan(0);
395 const answers = new Set<string>();
396 for (const f of forms) {
397 expect(f.getAttribute("method")).toBe("post");
398 const b = f.querySelector("button");
399 expect(b?.getAttribute("type") ?? "submit").toBe("submit");
400 for (const i of f.querySelectorAll("input[name=answer]")) answers.add(i.getAttribute("value") ?? "");
401 if (b?.getAttribute("name") === "answer") answers.add(b.getAttribute("value") ?? "");
402 }
403 expect([...answers].sort()).toEqual(["no", "yes"]);
405 // An ask waits in the dock above the composer: its answers are buttons of the composer's post
406 // form sent to the confirm's own address, and the thread holds no copy of it.
407 const composer = doc1.querySelector("form.talk-compose");
408 expect(composer?.getAttribute("method")).toBe("post");
409 const buttons = [...composer!.querySelectorAll(`[data-asks] button[formaction="/talk/confirm/${id}"]`)];
410 expect(buttons.map((b) => [b.getAttribute("type"), b.getAttribute("name"), b.getAttribute("value"), b.hasAttribute("formnovalidate")])).toEqual([
411 ["submit", "answer", "yes", true],
412 ["submit", "answer", "no", true],
413 ]);
414 expect(doc1.querySelector(".talk-log")?.textContent).not.toContain("Archive it.");
404415 });
405416
406417 test("the page's own bytes are held: stylesheet and script stay small", async () => {
407418 const { talkCss, talkJs } = await import("../src/web/pages/talk_client.ts");
408 expect(Buffer.byteLength(talkCss)).toBeLessThan(15_500);
409 expect(Buffer.byteLength(talkJs)).toBeLessThan(35_200);
419 expect(Buffer.byteLength(talkCss)).toBeLessThan(16_900);
420 expect(Buffer.byteLength(talkJs)).toBeLessThan(42_300);
410421 // A page of its own, so what other tests said to alice never counts: one question and a code reply.
411422 const sizer = await createUser(app.db, { origin: "seed", trusted: true, username: "sizer", email: "[email protected]", password: "a-good-passphrase" });
412423 if (!sizer.ok) throw new Error(sizer.error);
413424 say(sizer.value, "person", "how?");
414425 say(sizer.value, "agent", "```ts\nlet x = 1;\n```");
415426 const size = (await (await get("/talk", sizer.value)).arrayBuffer()).byteLength;
416 expect(size).toBeLessThan(45_000);
427 expect(size).toBeLessThan(47_000);
417428 });
418429
419430 describe("the script, driven against a DOM", () => {
@@ -507,9 +518,10 @@ describe("the page", () => {
507518 const doc = window.document as any;
508519 doc.body.innerHTML = `<div class="talk" data-talk data-user="${user}" data-c="${conv}" data-paged="0" data-running="1"><header class="talk-head"><details><summary>More</summary></details></header><div>
509520 <ol class="talk-log" role="log" data-last=""><li class="talk-turn talk-agent" id="t-1"><div class="talk-body"><pre><code>let a = 1;</code></pre></div><p class="talk-meta">Forge · now</p></li></ol><div id="end"></div></div>
510 <form class="talk-compose"><div class="talk-box"><div data-chips></div><p data-to-line hidden><span></span><button type="button" data-to-off>x</button></p><textarea name="text" required></textarea><div class="talk-tools"><button type="button" data-attach hidden aria-label="Attach files"></button><input type="file" multiple hidden data-files /><span data-compose-hint></span><button class="btn" type="button" data-steer hidden>Steer</button><button class="btn" type="button" data-stop hidden aria-label="Stop the answer">Stop</button><button class="btn talk-send" type="submit" aria-label="Send">Send</button></div></div><p data-error hidden></p><p class="talk-status" role="status"></p><button type="button" class="btn talk-jump" data-jump hidden><span data-word></span></button></form></div>`;
521 <form class="talk-compose"><div data-asks hidden><p data-asks-count></p><div class="talk-ask-list"></div></div><p data-asks-said></p><div class="talk-box"><div data-chips></div><p data-to-line hidden><span></span><button type="button" data-to-off>x</button></p><textarea name="text" required></textarea><div class="talk-tools"><button type="button" data-attach hidden aria-label="Attach files"></button><input type="file" multiple hidden data-files /><span data-compose-hint></span><button class="btn" type="button" data-steer hidden>Steer</button><button class="btn" type="button" data-stop hidden aria-label="Stop the answer">Stop</button><button class="btn talk-send" type="submit" aria-label="Send">Send</button></div></div><p data-error hidden></p><p class="talk-status" role="status"></p><button type="button" class="btn talk-jump" data-jump hidden><span data-word></span></button></form></div>`;
511522 const how = { value: "started" };
512523 const cancel = { status: 200 };
524 const answer = { status: 200 };
513525 const page = { html: "" };
514526 const sent: string[] = [];
515527 const urls: string[] = [];
@@ -519,6 +531,9 @@ describe("the page", () => {
519531 const fetchStub = async (u: string, init: { body: string; method?: string }) => {
520532 urls.push(u);
521533 if (u.startsWith("?pane=") || u === "/talk" || u.endsWith("?fragment=build")) return { ok: true, text: async () => page.html };
534 if (u.endsWith("?fragment=1")) return { ok: true, text: async () => '<div class="blob">const a = 2;</div>' };
535 if (u.endsWith("?fragment=explorer")) return { ok: true, text: async () => '<ul><li><a class="ex-file" data-ex-file tabindex="-1" title="src/a.ts" href="/erin/site/blob/b/src/a.ts">a.ts</a></li></ul>' };
536 if (u.includes("/confirm/")) { sent.push("answer:" + u + ":" + String(init.body)); return { ok: answer.status === 200, status: answer.status, json: async () => (answer.status === 200 ? { ok: true } : { ok: false, message: "this confirm was already answered; it does nothing twice" }) }; }
522537 if (u.endsWith("/comments")) { sent.push("comment:" + u + ":" + String(init.body)); redirects.push(String((init as { redirect?: string }).redirect)); return cancel.status === 303 ? { ok: false, status: 0, type: "opaqueredirect" } : { ok: cancel.status === 200, status: cancel.status, text: async () => "" }; }
523538 if (u.endsWith("/files")) return { ok: true, json: async () => ({ id: "f1", name: "shot.png" }) };
524539 if (init.method === "DELETE") return { ok: true, json: async () => ({}) };
@@ -538,9 +553,10 @@ describe("the page", () => {
538553 new Function("document", "window", "EventSource", "fetch", "localStorage", "navigator", "setTimeout", "clearTimeout", talkJs)(doc, window, ES, fetchStub, local, nav, timers.setTimeout, timers.clearTimeout);
539554 const box = doc.querySelector("textarea");
540555 const key = (init: object) => box.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init }));
556 const emitAsk = (id: string, ask: string) => sources.at(-1)!.on["turn"]!({ data: JSON.stringify({ id, html: "", ask }) });
541557 const emit = (id: string, html: string) => sources.at(-1)!.on["turn"]!({ data: JSON.stringify({ id, html }) });
542558 const grow = () => { for (const f of grows) f(); };
543 return { how, cancel, redirects, page, emit, bodies, sources, urls, window, doc, box, sent, copied, store, key, view, grow, hand: () => doc.documentElement.dispatchEvent(new window.PointerEvent("pointerdown", { bubbles: true })), jump: doc.querySelector("[data-jump]"), status: doc.querySelector(".talk-status") };
559 return { how, cancel, answer, emitAsk, redirects, page, emit, bodies, sources, urls, window, doc, box, sent, copied, store, key, view, grow, hand: () => doc.documentElement.dispatchEvent(new window.PointerEvent("pointerdown", { bubbles: true })), jump: doc.querySelector("[data-jump]"), status: doc.querySelector(".talk-status") };
544560 };
545561 /** An element that scrolls `height` px in a `client` px view; each programmatic move is kept. */
546562 const scrollable = (el: any, height: number, client: number) => {
@@ -642,7 +658,7 @@ describe("the page", () => {
642658 t.page.html = `<html><body><div data-shell><aside class="talk-pane"><nav class="tabs"><a href="?pane=code" aria-current="page">Code</a></nav><p>new files</p></aside></div></body></html>`;
643659 click(shell.querySelector(".talk-pane nav a[href='?pane=code']"));
644660 await tick();
645 expect(t.urls.at(-1)).toBe("?pane=code");
661 expect(t.urls.at(-1)).toBe("?pane=code&fragment=pane");
646662 expect(shell.querySelector(".talk-pane").textContent).toContain("new files");
647663 expect(t.box.value).toBe("half typed");
648664 expect(t.sources.at(-1)).toBe(source);
@@ -1011,6 +1027,108 @@ describe("the page", () => {
10111027 expect(t.sent.at(-1)).toBe("back to the forge");
10121028 });
10131029
1030 test("an ask the stream brings docks above the composer, said once; Do it posts the yes, and the ask leaves the dock", async () => {
1031 const t = await boot();
1032 const dock = t.doc.querySelector("[data-asks]");
1033 expect(dock.hidden).toBe(true);
1034 const { askItem } = await import("../src/web/pages/talk.ts");
1035 const ask = (id: string, does: string) => askItem(id, "archive", does, new Date(Date.now() + 600_000).toISOString()).text;
1036 t.emitAsk("5", ask("h1", "Archive alice/site."));
1037 t.emitAsk("5", ask("h1", "Archive alice/site."));
1038 const said = t.doc.querySelector("[data-asks-said]");
1039 expect([dock.hidden, dock.querySelectorAll(".talk-ask").length, said.textContent]).toEqual([false, 1, "Waiting for your answer: Archive alice/site."]);
1040 expect(t.doc.querySelector(".talk-log").textContent).not.toContain("Archive alice/site.");
1041 t.emitAsk("6", ask("h2", "Close alice/site#4."));
1042 expect([dock.hasAttribute("data-many"), dock.querySelector("[data-asks-count]").textContent]).toEqual([true, "2 waiting"]);
1043 // Before the composer in the order, so Tab reaches the ask first.
1044 const order = [...t.doc.querySelectorAll("form.talk-compose button, form.talk-compose textarea")];
1045 expect(order.indexOf(dock.querySelector("[data-answer]"))).toBeLessThan(order.indexOf(t.box));
1046 t.doc.querySelector("form.talk-compose").requestSubmit(dock.querySelector('#ask-h1 button[value="yes"]'));
1047 await tick();
1048 expect(t.sent).toEqual(["answer:/talk/confirm/h1:answer=yes"]);
1049 expect([dock.querySelectorAll(".talk-ask").length, dock.querySelector("[data-asks-count]").textContent, said.textContent, t.status.textContent]).toEqual([1, "", "Done.", ""]);
1050 t.doc.querySelector("form.talk-compose").requestSubmit(dock.querySelector('#ask-h2 button[value="no"]'));
1051 await tick();
1052 expect(t.sent.at(-1)).toBe("answer:/talk/confirm/h2:answer=no");
1053 expect([dock.hidden, said.textContent]).toEqual([true, "Not now: nothing was done."]);
1054 });
1055
1056 test("an ask says its time left under two minutes and, run out, takes its buttons away; nothing ticks", async () => {
1057 const due: (() => void)[] = [];
1058 const timers = { setTimeout: ((f: () => void) => due.push(f)) as unknown as typeof setTimeout, clearTimeout: (() => {}) as unknown as typeof clearTimeout };
1059 const t = await boot("u1", {}, "c1", timers);
1060 const { askItem } = await import("../src/web/pages/talk.ts");
1061 t.emitAsk("5", askItem("h1", "archive", "Archive alice/site.", new Date(Date.now() + 600_000).toISOString()).text);
1062 const left = t.doc.querySelector("#ask-h1 .talk-ask-left");
1063 const buttons = [...t.doc.querySelectorAll("#ask-h1 button")];
1064 // Two timeouts set, one for each moment: never an interval.
1065 expect(due.length).toBe(2);
1066 due.shift()!();
1067 expect([left.hidden, left.textContent, buttons.some((b) => b.disabled)]).toEqual([false, "Less than 2 minutes left.", false]);
1068 due.shift()!();
1069 expect([left.textContent, buttons.every((b) => b.disabled)]).toEqual(["This ran out: nothing was done.", true]);
1070 });
1071
1072 test("an answer hushes only the stream it opens: the next reply is still announced", async () => {
1073 const t = await boot();
1074 const { askItem } = await import("../src/web/pages/talk.ts");
1075 t.emitAsk("5", askItem("h1", "archive", "Archive alice/site.", new Date(Date.now() + 600_000).toISOString()).text);
1076 t.doc.querySelector("form.talk-compose").requestSubmit(t.doc.querySelector('#ask-h1 button[value="yes"]'));
1077 await tick();
1078 // The answer's own stream ends unannounced.
1079 t.sources.at(-1)!.on["done"]!({ data: "{}" });
1080 expect(t.status.textContent).not.toBe("The forge replied.");
1081 // A send that follows is announced when its reply ends, even had the answer's stream never ended.
1082 t.emitAsk("6", askItem("h2", "archive", "Archive alice/two.", new Date(Date.now() + 600_000).toISOString()).text);
1083 t.doc.querySelector("form.talk-compose").requestSubmit(t.doc.querySelector('#ask-h2 button[value="yes"]'));
1084 await tick();
1085 t.box.value = "and then?";
1086 t.key({});
1087 await tick();
1088 t.sources.at(-1)!.on["done"]!({ data: "{}" });
1089 expect(t.status.textContent).toBe("The forge replied.");
1090 });
1091
1092 test("a refused answer keeps the ask, says why, and gives the buttons back", async () => {
1093 const t = await boot();
1094 const { askItem } = await import("../src/web/pages/talk.ts");
1095 t.emitAsk("5", askItem("h1", "archive", "Archive alice/site.", new Date(Date.now() + 600_000).toISOString()).text);
1096 t.answer.status = 409;
1097 const yes = t.doc.querySelector('#ask-h1 button[value="yes"]');
1098 t.doc.querySelector("form.talk-compose").requestSubmit(yes);
1099 await tick();
1100 const left = t.doc.querySelector("#ask-h1 .talk-ask-left");
1101 expect([t.doc.querySelectorAll(".talk-ask").length, left.hidden, left.textContent, yes.disabled]).toEqual([1, false, "this confirm was already answered; it does nothing twice", false]);
1102 });
1103
1104 test("things done in a row fold into one line as they stream in; one alone stays itself", async () => {
1105 const t = await boot();
1106 const done = (id: string, what: string) => t.emit(id, `<li class="talk-turn talk-receipt" id="t-${id}" data-done><p class="talk-receipt-line"><svg class="ico"></svg><span><strong>Filed</strong> ${what}</span></p></li>`);
1107 done("2", "#1");
1108 expect(t.doc.querySelector("#t-2").parentElement.className).toBe("talk-log");
1109 done("3", "#2");
1110 t.emit("4", '<li class="talk-turn talk-tool talk-step" id="t-4" data-step><details><summary>Read x.ts</summary></details></li>');
1111 const fold = t.doc.querySelector(".talk-fold");
1112 expect([fold.hasAttribute("data-dones"), fold.querySelector("summary").textContent, fold.querySelectorAll("ol > li").length, !!fold.querySelector("summary > .ico")]).toEqual([true, "2 things done, 1 step", 3, true]);
1113 });
1114
1115 test("Code: a file opens in the pane and Files goes back; a folder fills itself in, its changed files marked and in the Tab order", async () => {
1116 const t = await boot();
1117 t.doc.body.insertAdjacentHTML("beforeend", `<aside class="talk-pane"><div class="talk-code" data-code data-changed="src/a.ts"><section class="talk-code-changed"><a href="/erin/site/blob/b/src/a.ts" data-pane-file>src/a.ts</a></section><nav class="explorer talk-code-tree"><ul><li><details class="ex-dir" data-url="/erin/site/tree/b/src"><summary>src</summary><ul data-stub><li>x</li></ul></details></li></ul></nav><div class="talk-code-file" data-code-file hidden><button type="button" data-code-back>Files</button><div data-code-body></div></div></div></aside>`);
1118 const code = t.doc.querySelector("[data-code]");
1119 code.querySelector("[data-pane-file]").dispatchEvent(new t.window.MouseEvent("click", { bubbles: true, cancelable: true }));
1120 await tick();
1121 expect([code.hasAttribute("data-open"), code.querySelector("[data-code-file]").hidden, code.querySelector("[data-code-body]").textContent]).toEqual([true, false, "const a = 2;"]);
1122 code.querySelector("[data-code-back]").click();
1123 expect([code.hasAttribute("data-open"), code.querySelector("[data-code-file]").hidden]).toEqual([false, true]);
1124 const dir = code.querySelector("details.ex-dir");
1125 dir.setAttribute("open", "");
1126 dir.dispatchEvent(new t.window.Event("toggle"));
1127 await tick();
1128 const file = dir.querySelector("a.ex-file");
1129 expect([file.hasAttribute("data-changed"), file.hasAttribute("tabindex"), !!dir.querySelector("[data-stub]")]).toEqual([true, false, false]);
1130 });
1131
10141132 test("a code block in a streamed turn gets its Copy button too", async () => {
10151133 const t = await boot();
10161134 t.emit("2", '<li class="talk-turn" id="t-2"><div class="talk-body"><pre><code>x</code></pre></div><p class="talk-meta">Forge</p></li>');
@@ -1293,7 +1411,7 @@ describe("confirm and cancel", () => {
12931411 const h = await held(alice);
12941412 const page = await (await get("/talk", alice)).text();
12951413 expect(page).toContain("This will archive the app.");
1296 expect(page).toContain(`action="/talk/confirm/${h.id}"`);
1414 expect(page).toContain(`formaction="/talk/confirm/${h.id}"`);
12971415 expect(page).toContain("Do it");
12981416 expect(page).toContain("Not now");
12991417 const no = await post(`/talk/confirm/${h.id}`, alice, { answer: "no" }, { accept: "application/json" });
@@ -1304,7 +1422,7 @@ describe("confirm and cancel", () => {
13041422 expect(getRepoById(app.db, h.repoId)!.archivedAt).toBeNull();
13051423 const after = await (await get("/talk", alice)).text();
13061424 expect(after).toContain("Not now: nothing was done.");
1307 expect(after).not.toContain(`action="/talk/confirm/${h.id}"`);
1425 expect(after).not.toContain(`formaction="/talk/confirm/${h.id}"`);
13081426 });
13091427
13101428 test("nothing runs until Do it: the card shows both buttons, the page alone changes nothing, and a dismissal is remembered", async () => {
@@ -1320,7 +1438,7 @@ describe("confirm and cancel", () => {
13201438 expect(getRepoById(app.db, h.repoId)!.archivedAt).toBeNull();
13211439 const again = await (await get("/talk", alice)).text();
13221440 expect(again).toContain("Not now: nothing was done.");
1323 expect(again).not.toContain(`action="/talk/confirm/${h.id}"`);
1441 expect(again).not.toContain(`formaction="/talk/confirm/${h.id}"`);
13241442 const h2 = await held(alice);
13251443 expect((await post(`/talk/confirm/${h2.id}`, alice, { answer: "yes" }, { accept: "application/json" })).status).toBe(200);
13261444 expect(getRepoById(app.db, h2.repoId)!.archivedAt).not.toBeNull();
test/talk-receipt-live.test.ts +1 −1
@@ -167,7 +167,7 @@ test("the work line's other ends: checks failed, a run that did not finish, one
167167
168168 test("the page draws the receipt with its live line and Reply; the line's fragment answers only who may read the issue", async () => {
169169 const page = await (await get("/talk", alice)).text();
170 expect(page).toMatch(/<li class="talk-turn talk-receipt" id="t-[0-9a-z]+">/);
170 expect(page).toMatch(/<li class="talk-turn talk-receipt" id="t-[0-9a-z]+" data-done>/);
171171 expect(page).toMatch(
172172 /<p class="talk-work-line small muted" id="w-[0-9a-z]+" data-live="run\.\*,issue\.\*,pull\.\*,comment\.\*" data-live-repo="alice\/secret" data-live-src="\/live\/talk-work\?href=%2Falice%2Fsecret%2Fissues%2F1&amp;id=w-[0-9a-z]+">The crew landed #2\.<\/p>/,
173173 );
test/talk-steps.test.ts +59 −16
@@ -7,7 +7,12 @@ import { createApp, type App } from "../src/app.ts";
77 import { appendTurn, openConversation } from "../src/core/conversations.ts";
88 import { createSession } from "../src/core/sessions.ts";
99 import { repoOf, stepOf } from "../src/core/talk_steps.ts";
10 import { createRepo } from "../src/actions/repos.ts";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { startChatBuild } from "../src/core/chat_build.ts";
12 import { createIssue } from "../src/core/issues.ts";
13 import { renderDiff } from "../src/web/diff-view.ts";
14 import { createRun } from "../src/core/runs.ts";
15 import { getRepo } from "../src/core/repos.ts";
1116 import { createUser, type User } from "../src/core/users.ts";
1217 import type { Ctx } from "../src/http/context.ts";
1318 import { previewEnv } from "../src/apps/data.ts";
@@ -96,8 +101,8 @@ describe("a repository the person can read", () => {
96101 const works = new Map([["1", { steps: "", links: [{ href: "/erin/site/blob/main/a.ts", label: "a.ts" }, { href: "/erin/site/pulls/3", label: "#3" }] }]]) as any;
97102 const apps = (pull: number | undefined, urls: Record<string, string>) => ({ newestPull: () => pull, urlOf: (_: unknown, env: string) => urls[env] });
98103
99 test("the preview is the newest pull's environment, and its origin alone goes in frame-src", () => {
100 const pane = talkPane(ctx, user, "erin/site", works, "preview", apps(7, { [previewEnv(7)]: "https://lab--7--site.example.test/", production: "https://site.example.test/" }));
104 test("the preview is the newest pull's environment, and its origin alone goes in frame-src", async () => {
105 const pane = await talkPane(ctx, user, "erin/site", works, "preview", apps(7, { [previewEnv(7)]: "https://lab--7--site.example.test/", production: "https://site.example.test/" }));
101106 expect(pane.html.text).toContain('<iframe class="talk-frame" data-frame src="https://lab--7--site.example.test/"');
102107 expect(pane.html.text).toContain("Pull #7");
103108 expect(pane.frame).toBe("https://lab--7--site.example.test");
@@ -110,29 +115,67 @@ describe("a repository the person can read", () => {
110115 expect(frameSources({ frameSrc: pane.frame })).not.toContain("site.example.test/");
111116 });
112117
113 test("with no open pull the preview is production", () => {
114 const pane = talkPane(ctx, user, "erin/site", works, "preview", apps(undefined, { production: "https://site.example.test/" }));
118 test("with no open pull the preview is production", async () => {
119 const pane = await talkPane(ctx, user, "erin/site", works, "preview", apps(undefined, { production: "https://site.example.test/" }));
115120 expect(pane.html.text).toContain('src="https://site.example.test/"');
116121 expect(pane.html.text).toContain("Production");
117122 });
118123
119 test("nothing running draws no frame and no frame-src", () => {
120 const pane = talkPane(ctx, user, "erin/site", works, "preview", apps(undefined, {}));
124 test("nothing running draws no frame and no frame-src, and says so in words", async () => {
125 const pane = await talkPane(ctx, user, "erin/site", works, "preview", apps(undefined, {}));
121126 expect(pane.live).toBe(false);
122127 expect(pane.html.text).not.toContain("<iframe");
123128 expect(pane.frame).toBeUndefined();
129 expect(pane.html.text).toContain("Nothing is running yet: the app appears here once it is built.");
124130 });
125131
126 test("Code lists the files the chat touched and Diff links the pull, both without script", () => {
127 const code = talkPane(ctx, user, "erin/site", works, "code", apps(7, {}));
128 expect(code.html.text).toContain('<a href="/erin/site/blob/main/a.ts">a.ts</a>');
129 expect(code.html.text).not.toContain("pulls/3");
130 expect(code.html.text).not.toContain("<iframe");
132 test("Code is the repository's files at the conversation's branch, its changed files first; Diff is the change itself, inline", async () => {
133 const repo = getRepo(app.db, "erin", "site")!;
134 expect((await commitToBranch(app, user, repo, { message: "start", files: [{ path: "README.md", content: "# site\n" }, { path: "src/a.ts", content: "export const a = 1;\n" }] })).ok).toBe(true);
135 const build = startChatBuild(app.db, openConversation(app.db, user.id).id, repo.id);
136 // Before anything changed: the tree alone, from the first moment, never "no files touched yet".
137 const before = await talkPane(ctx, user, "erin/site", works, "code", apps(undefined, {}), { build });
138 expect(before.html.text).toContain('class="explorer talk-code-tree"');
139 expect(before.html.text).toContain('href="/erin/site/blob/main/README.md"');
140 expect(before.html.text).not.toContain("Changed here");
141 expect(before.html.text).not.toContain('tabindex="-1"');
142 expect(await talkPane(ctx, user, "erin/site", works, "diff", apps(undefined, {}), { build }).then((p) => p.html.text)).toContain("Nothing has changed yet");
143 expect((await commitToBranch(app, user, repo, { branch: build.branch, message: "v1", files: [{ path: "src/a.ts", content: "export const a = 2;\nexport const b = 3;\n" }] })).ok).toBe(true);
144 const code = await talkPane(ctx, user, "erin/site", works, "code", apps(undefined, {}), { build });
145 expect(code.html.text).toContain(`data-changed="src/a.ts"`);
146 const flat = code.html.text.replace(/\s+/g, " ");
147 expect(flat).toContain("Changed here");
148 expect(flat).toContain(`href="/erin/site/blob/${build.branch}/src/a.ts" data-pane-file`);
149 expect(flat).toMatch(/\+2<\/span> <span class="del">−1/);
131150 expect(code.html.text).toContain('<a href="?pane=code" aria-current="page">Code</a>');
132 const diff = talkPane(ctx, user, "erin/site", works, "diff", apps(7, {}));
133 expect(diff.html.text).toContain('href="/erin/site/pulls/7/files"');
134 expect(talkPane(ctx, user, "erin/site", works, "diff", apps(undefined, {})).html.text).toContain("No open pull yet.");
135 for (const p of [code, diff]) expect(p.html.text).not.toContain("hidden");
151 const diff = await talkPane(ctx, user, "erin/site", works, "diff", apps(undefined, {}), { build });
152 expect(diff.html.text).toContain("src/a.ts");
153 expect(diff.html.text.replace(/<[^>]+>/g, "")).toContain("export const b = 3;");
154 expect(diff.html.text).not.toContain("<iframe");
155 // A version picks its own change; the chips are there once there are two.
156 expect((await commitToBranch(app, user, repo, { branch: build.branch, message: "v2", files: [{ path: "src/c.ts", content: "export const c = 4;\n" }] })).ok).toBe(true);
157 const v1 = (await talkPane(ctx, user, "erin/site", works, "diff", apps(undefined, {}), { build, version: 1 })).html.text;
158 expect(v1).toContain('aria-label="Which change"');
159 expect(v1).toContain("src/a.ts");
160 expect(v1).not.toContain("src/c.ts");
161 // A name with a space, a # and a % is one path segment in every link to it, and the link opens it.
162 expect((await commitToBranch(app, user, repo, { branch: build.branch, message: "v3", files: [{ path: "src/odd #1 100%.ts", content: "export const d = 5;\n" }] })).ok).toBe(true);
163 const odd = "src/odd%20%231%20100%25.ts";
164 const listed = (await talkPane(ctx, user, "erin/site", works, "code", apps(undefined, {}), { build })).html.text.replace(/\s+/g, " ");
165 expect(listed).toContain(`href="/erin/site/blob/${build.branch}/${odd}" data-pane-file`);
166 const tree = (await fetch(`${servers.url}/erin/site/tree/${build.branch}/src?fragment=explorer`, { headers: { cookie } })).text();
167 expect(await tree).toContain(`href="/erin/site/blob/${build.branch}/${odd}"`);
168 const blob = await fetch(`${servers.url}/erin/site/blob/${build.branch}/${odd}?fragment=1`, { headers: { cookie } });
169 expect([blob.status, (await blob.text()).replace(/<[^>]+>/g, "").includes("export const d = 5;")]).toEqual([200, true]);
170 expect(renderDiff({ files: [{ status: "added", oldPath: null, newPath: "src/odd #1 100%.ts", path: "src/odd #1 100%.ts", binary: true, additions: 0, deletions: 0, similarity: null, hunks: [] }], additions: 0, deletions: 0 }, { fileLinkBase: "/erin/site/blob/b" }).text).not.toContain('href="/erin/site/blob/b/src/odd #1');
171
172 // The pull is a quiet link in the head, with its checks in words.
173 const pull = createIssue(app.db, { repoId: repo.id, authorId: user.id, title: "Build", body: "b", kind: "pull" });
174 if (!pull.ok) throw new Error("pull");
175 app.db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', ?2, '', 'h')", [pull.value.id, build.branch]);
176 app.db.run("UPDATE run SET state = 'ok' WHERE id = ?1", [createRun(app.db, { repoId: repo.id, kind: "check", issueId: pull.value.id, commitOid: "h" }).id]);
177 const head = (await talkPane(ctx, user, "erin/site", works, "diff", apps(pull.value.number, {}), { build })).html.text.replace(/\s+/g, " ");
178 expect(head).toContain(`href="/erin/site/pulls/${String(pull.value.number)}" >Pull #${String(pull.value.number)} · checks passing</a`);
136179 });
137180 });
138181
test/tui-talk-chats.test.ts +39 −1
@@ -12,7 +12,9 @@ import { appendTurn, archiveConversation, CONVERSATIONS_MAX, createConversation,
1212 import { createIssue } from "../src/core/issues.ts";
1313 import { createRun } from "../src/core/runs.ts";
1414 import { createUser, type User } from "../src/core/users.ts";
15 import { createRepo } from "../src/actions/repos.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { startChatBuild } from "../src/core/chat_build.ts";
17 import { hold } from "../src/core/fence.ts";
1618 import { STARTER_PROMPTS } from "../src/actions/talk.ts";
1719 import { setTalkDisplay, talkDisplay } from "../src/core/settings.ts";
1820 import { createForgeApp } from "../src/tui/forge.ts";
@@ -260,6 +262,42 @@ describe("the terminal's conversations screen", () => {
260262 expect(await drive(alice, [...open, "\r", "p"])).toContain("Not a repository you can see.");
261263 });
262264
265 test("an ask waits at the foot of the conversation, never in the thread, and a opens Confirms to answer it", async () => {
266 const made = createConversation(app.db, alice.id);
267 if (!made.ok) throw new Error(made.error);
268 const repo = await createRepo(app, alice, { name: "dockyard", visibility: "public" });
269 if (!repo.ok) throw new Error(String(repo.error));
270 appendTurn(app.db, alice.id, made.value.id, { role: "person", text: "archive it" });
271 const id = hold(app.db, "conversation:talk", alice.id, "archive", { repo: "alice/dockyard", archived: true, dryRun: false });
272 if (id === null) throw new Error("hold");
273 appendTurn(app.db, alice.id, made.value.id, { role: "confirm", text: JSON.stringify({ confirm: id, tool: "archive", does: "Archive alice/dockyard." }) });
274 renameConversation(app.db, alice.id, made.value.id, "Dock here");
275 const text = await drive(alice, [...open, "/", "Dock here", "\r", "\r"]);
276 expect(text).toContain("Waiting for you:");
277 expect(text).toContain("a answers: y does it, n not now.");
278 expect(text).not.toContain("Asks ·");
279 expect(text.indexOf("Waiting for you:")).toBeGreaterThan(text.indexOf("archive it"));
280 const confirms = await drive(alice, [...open, "/", "Dock here", "\r", "\r", "a"]);
281 expect(confirms).toContain("y does it once, as you; n says not now.");
282 });
283
284 test("the pane shows what the conversation's branch changed, file by file with +/−, and the diff itself", async () => {
285 const made = createConversation(app.db, alice.id);
286 if (!made.ok) throw new Error(made.error);
287 const repo = await createRepo(app, alice, { name: "panediff", visibility: "public" });
288 if (!repo.ok) throw new Error(String(repo.error));
289 expect((await commitToBranch(app, alice, repo.value, { message: "start", files: [{ path: "src/a.ts", content: "export const a = 1;\n" }] })).ok).toBe(true);
290 const build = startChatBuild(app.db, made.value.id, repo.value.id);
291 expect((await commitToBranch(app, alice, repo.value, { branch: build.branch, message: "v1", files: [{ path: "src/a.ts", content: "export const a = 2;\nexport const b = 3;\n" }] })).ok).toBe(true);
292 appendTurn(app.db, alice.id, made.value.id, { role: "tool", text: `mcp__forge__write_file {"repo":"alice/panediff","path":"src/a.ts","content":"a"}` });
293 renameConversation(app.db, alice.id, made.value.id, "Diff here");
294 const text = await drive(alice, [...open, "/", "Diff here", "\r", "\r", "p"]);
295 expect(text).toContain(`Changed on ${build.branch}:`);
296 expect(text).toContain("src/a.ts +2 −1");
297 expect(text).toContain("+export const b = 3;");
298 expect(text).toContain("-export const a = 1;");
299 });
300
263301 test("turns are read when the chat opens and on r, not on every draw", async () => {
264302 const made = createConversation(app.db, bob.id);
265303 if (!made.ok) throw new Error(made.error);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs