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

Talk's pane frames the starter from the start and streams what the crew member says and does #16347

Merged opened this

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

Merged

talk/live-pane-2 → main 0 commits 4 threads · 4 unresolved

  • Merged. talk/live-pane-2 was merged into main as 8510b24.

Review

Sign in to review this change.
10 files changed +253 −38
docs/design/areas/talk.md +1
@@ -134,3 +134,4 @@ Prior art: Claude and ChatGPT (one centred column, the person's words in a quiet
134134 - `.talk-links`: what a reply opened or changed, folded behind its count ("3 files") on the reply's one last line, each file by its path in its repository.
135135 - `.talk-stage-files`: before a first version, the pane says what will appear and when, and shows the files the app starts from.
136136 - `.talk-crew-now`, `.talk-crew-steps`: the crew's run in the pane's wait stage: why it waits or that it works, its newest steps in plain words as lines of text, and the run's page.
137 - `.talk-crew-working`, `.talk-crew-thought`: the crew member's working line (with the shine Talk's own agent uses while it answers) and its own words among its steps, in the pane's crew block.
docs/design/size-budget.json +2 −2
@@ -68,8 +68,8 @@
6868 "css": 48640
6969 },
7070 "/talk": {
71 "js": 39168,
72 "css": 55040
71 "js": 39680,
72 "css": 55808
7373 },
7474 "/:owner/:name/pulls/:number": {
7575 "js": 32000,
docs/features/talk.md +3 −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 18,000 B, the script under 47,300 B, and a page with a code reply under 52,000 B (its own page: one question and a code reply; the widgets' rules ride every page, so a chart drawn in a live reply is styled at once).
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 18,100 B, the script under 49,100 B, and a page with a code reply under 53,000 B (its own page: one question and a code reply; the widgets' rules ride every page, so a chart drawn in a live reply is styled at once).
140140
141141 ## Following
142142
@@ -234,3 +234,5 @@ A private preview signs the person in inside the frame through their own grant.
234234 ## The pane while the crew works (#15734)
235235
236236 Until the app answers, the pane's Preview tab shows what the crew is doing on the repository: its newest run in plain words (`crewNow`, `src/core/talk_work.ts`). A queued run says why it waits (the hold sentence, with the control that changes it); a running one lists its newest six steps (a file read or changed, a search, the checks, a commit, a push), each added as the run writes it, from the forge's own event stream (`run.log`), by the same `plainStep` the server uses; a finished or failed one says how it ended. A log line is the builder's untrusted text: it is only ever drawn as text, and only for a reader who may read the run's log (`mayReadRunLog`: the repository's own facts or the crew); anyone else who may see the runs reads how it stands and the link, never a step, and the live tail is never sent them (`/events` sends `run.log` only to who may read it). "See the whole run" links the run's page, which is all of it without the script. The pane is a live region on the repository's runs, so the first deploy that turns running swaps the frame in; the page names the app's production origin in `frame-src` ahead, and a frame of another origin draws the page once. The pane opens by itself once the crew is on the repository the conversation names; a new app is named by its receipt (`New app owner/name`). In the terminal, the conversation's pane (`p`) prints the same lines and redraws as the run writes. Proof: `test/talk-live-pane.test.ts`.
237
238 What runs is framed from the start: a new app's starter answers seconds after it is made, so the pane frames production (until a pull's own preview answers) and the crew's block sits under the frame, which gives it room. The block says who works ("cheffry-james is working.", with the same shine Talk's own agent uses while it answers) and lists its newest eight lines: its own words (`plainThought`: the short text between its calls, trimmed to about two lines) and its steps. The block is a live region of its own, so the frame is never redrawn for the crew; a deploy that turns running reloads the frame in place, and a pull's preview that comes up while production is framed draws the page once (its origin joins `frame-src`).
src/actions/talk_workspace.ts +8 −2
@@ -31,6 +31,8 @@ export interface Workspace {
3131 readonly name: string;
3232 readonly repo: Repo;
3333 readonly pull: number | undefined;
34 /** The pull whose preview is framed; undefined when production is (its own preview not up yet). */
35 readonly shows: number | undefined;
3436 /** The running app's address, and its origin alone (what `frame-src` may name); both or neither. */
3537 readonly url: string | undefined;
3638 readonly origin: string | undefined;
@@ -48,7 +50,11 @@ export function workspaceOf(app: App, user: User, name: string, apps: Apps = rea
4850 const repo = getRepo(app.db, owner, repoName);
4951 if (repo === undefined || !requireReader(app, user, repo).ok) return undefined;
5052 const pull = apps.newestPull(repo);
51 const found = apps.urlOf(repo, pull === undefined ? "production" : previewEnv(pull));
53 // The newest pull's preview, else production: a pull the crew has just opened shows the app as it
54 // runs until its own preview answers, never an empty stage.
55 const ahead = pull === undefined ? undefined : apps.urlOf(repo, previewEnv(pull));
56 const shows = ahead === undefined ? undefined : pull;
57 const found = ahead ?? apps.urlOf(repo, "production");
5258 const origin = found === undefined ? undefined : originOf(found);
53 return { name, repo, pull, url: origin === undefined ? undefined : found, origin };
59 return { name, repo, pull, shows, url: origin === undefined ? undefined : found, origin };
5460 }
src/core/talk_work.ts +41 −8
@@ -439,8 +439,29 @@ export function plainStep(line: string): string | undefined {
439439 return undefined;
440440 }
441441
442 /** How many of a run's plain steps the pane shows at once: enough to see it move. */
443 export const STEPS_SHOWN = 6;
442 /**
443 * A line of a crew run's log that is the crew member's own words (its short text between calls: "I'll
444 * read the template first", "Now the styles"), trimmed to about two lines; undefined for anything
445 * the forge wrote (those start lower case or with a known prefix) and for the calls (`plainStep`).
446 * The page's live tail runs this same function, as it does `plainStep`.
447 */
448 export function plainThought(line: string): string | undefined {
449 const said = line.replace(/\s+/g, " ").trim();
450 if (!/^[A-Z][a-z']*\b/.test(said) || said.startsWith("\u2192") || /^(The last \d+ crew runs|Crew runs get past)/.test(said)) return undefined;

Next: the capital-letter heuristic plus the two-prefix exclusion is fragile (principle 8, plain words, depends on it). Mark the crew's own text in the log where it is written.

451 if (said.length <= 160) return said;
452 const cut = said.slice(0, 159);
453 const end = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf(" "));
454 return `${cut.slice(0, end > 80 ? end : 159).trimEnd()}\u2026`;
455 }
456
457 /** One line of the crew's run as the pane shows it: a step it took, or its own words. */
458 export interface CrewItem {
459 readonly thought: boolean;
460 readonly text: string;
461 }
462
463 /** How many of a run's steps and words the pane shows at once: enough to see it move. */
464 export const STEPS_SHOWN = 8;
444465
445466 /** What the crew is doing on a repository now, for the pane: its newest run, in words. */
446467 export interface PaneCrew {
@@ -448,8 +469,10 @@ export interface PaneCrew {
448469 readonly state: "queued" | "running" | "ok" | "failed";
449470 /** One line: why it waits, that it is working, or how it ended. */
450471 readonly line: WorkLine;
451 /** The newest plain steps of its log, oldest first; none for a reader who may not read the log. */
452 readonly steps: readonly string[];
472 /** The newest steps and words of its log, oldest first; none for a reader who may not read the log. */
473 readonly steps: readonly CrewItem[];
474 /** The crew member working it, by name; "the crew" when none is named. */
475 readonly who: string;
453476 /** The reader may read the run's log: the page tails it live, by the run's id. */
454477 readonly tail: boolean;
455478 }
@@ -469,16 +492,26 @@ export interface RunsSeen {
469492 export function paneCrew(db: Database, dataDir: string, repoId: string, reader: User | undefined, seen: RunsSeen): PaneCrew | undefined {
470493 if (!seen.runs) return undefined;
471494 const run = db
472 .query<{ id: string; state: string }, [string]>("SELECT id, state FROM run WHERE repo_id = ?1 AND kind = 'agent' ORDER BY id DESC LIMIT 1")
495 .query<{ id: string; state: string; actor_id: string | null }, [string]>("SELECT id, state, actor_id FROM run WHERE repo_id = ?1 AND kind = 'agent' ORDER BY id DESC LIMIT 1")
473496 .get(repoId);
474497 if (run === null) return undefined;
475 const steps = seen.logs ? readRunLogTail(dataDir, run.id, 200).lines.flatMap((l) => plainStep(l) ?? []).slice(-STEPS_SHOWN) : [];
476 const at = { runId: run.id, steps, tail: seen.logs };
498 const steps: CrewItem[] = seen.logs
499 ? readRunLogTail(dataDir, run.id, 200)
500 .lines.flatMap((l): CrewItem[] => {
501 const step = plainStep(l);
502 if (step !== undefined) return [{ thought: false, text: step }];
503 const thought = plainThought(l);
504 return thought === undefined ? [] : [{ thought: true, text: thought }];
505 })
506 .slice(-STEPS_SHOWN)
507 : [];
508 const who = (run.actor_id === null ? undefined : getUserById(db, run.actor_id)?.username) ?? "the crew";
509 const at = { runId: run.id, steps, tail: seen.logs, who };
477510 if (run.state === "queued") {
478511 const hold = holdNow(db, dataDir, run.id);
479512 return { ...at, state: "queued", line: hold === undefined ? { says: "Queued for the crew: it starts when a builder is free." } : holdWords(hold, holdReader(db, repoId, reader)) };
480513 }
481 if (run.state === "running") return { ...at, state: "running", line: { says: "The crew is building it now." } };
514 if (run.state === "running") return { ...at, state: "running", line: { says: `${who === "the crew" ? "The crew" : who} is working.` } };
482515 if (run.state === "ok") return { ...at, state: "ok", line: { says: "The crew finished this run." } };
483516 return { ...at, state: "failed", line: { says: "The crew's run did not finish." } };
484517 }
src/tui/screens/talk_chats.ts +2 −2
@@ -177,7 +177,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
177177 if (crew === undefined) return [];
178178 const l = crew.line;
179179 const said = l.change === undefined ? l.says : `${l.says} ${l.change.words}: ${f.app.config.url === undefined ? l.change.href : publicOrigin(f.app.config.url, "") + l.change.href}`;
180 return ["", `Crew: ${said}`, ...crew.steps.map((step) => ` ${step}`), `The whole run: /${repo ?? ""}/runs/${crew.runId}`];
180 return ["", `Crew: ${said}`, ...crew.steps.map((item) => (item.thought ? ` \u201c${item.text}\u201d` : ` ${item.text}`)), `The whole run: /${repo ?? ""}/runs/${crew.runId}`];
181181 };
182182 const paneLines = (): string[] => {
183183 if (repo === undefined || f.user === undefined) return ["No repository yet."];
@@ -185,7 +185,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
185185 if (ws === undefined) return ["Not a repository you can see."];
186186 const files = filesOf(recent, repo);
187187 return [
188 `${repo} · ${ws.pull === undefined ? "Production" : `Pull #${String(ws.pull)}`}`,
188 `${repo} · ${ws.shows === undefined ? "Production" : `Pull #${String(ws.shows)}`}`,
189189 "",
190190 ws.url === undefined ? "Nothing running yet." : `Preview: ${ws.url}`,
191191 ...(ws.url === undefined ? crewLines(ws.repo.id) : []),
src/web/pages/talk_client.ts +24 −5
@@ -50,7 +50,7 @@
5050 * phone, is a plain link: the list is its own page below 900 px.
5151 */
5252
53 import { plainStep, STEPS_SHOWN } from "../../core/talk_work.ts";
53 import { plainStep, plainThought, STEPS_SHOWN } from "../../core/talk_work.ts";
5454
5555 export const talkCss = /* css */ `
5656 #main:has(> .talk-page) { padding-top: 0; padding-bottom: 0; }
@@ -190,9 +190,9 @@ body:has(.talk-page) .foot { display: none; }
190190 .talk-fold > details > summary:hover { color: var(--fg); }
191191 .talk-fold-list { list-style: none; margin: 0; margin-inline-start: 8px; padding: 0; padding-inline-start: 12px; border-inline-start: 2px solid var(--border); display: grid; gap: 2px; }
192192 .talk-steps { margin: 4px 0 0; }
193 .talk-live .talk-steps:last-child, .talk-status:not(:empty), .talk-stage[data-busy] .talk-stage-note { background: linear-gradient(90deg, var(--muted-fg) 40%, var(--fg) 50%, var(--muted-fg) 60%) 0 0 / 300% 100%; -webkit-background-clip: text; background-clip: text; color: transparent; animation: talk-shine 2s linear infinite; }
193 .talk-live .talk-steps:last-child, .talk-status:not(:empty), .talk-stage[data-busy] .talk-stage-note, .talk-crew-working { background: linear-gradient(90deg, var(--muted-fg) 40%, var(--fg) 50%, var(--muted-fg) 60%) 0 0 / 300% 100%; -webkit-background-clip: text; background-clip: text; color: transparent; animation: talk-shine 2s linear infinite; }
194194 @keyframes talk-shine { from { background-position: 100% 0; } to { background-position: 0 0; } }
195 @media (prefers-reduced-motion: reduce) { .talk-live .talk-steps:last-child, .talk-status:not(:empty), .talk-stage[data-busy] .talk-stage-note { animation: none; color: var(--muted-fg); background: none; } }
195 @media (prefers-reduced-motion: reduce) { .talk-live .talk-steps:last-child, .talk-status:not(:empty), .talk-stage[data-busy] .talk-stage-note, .talk-crew-working { animation: none; color: var(--muted-fg); background: none; } }
196196 .talk-confirms { display: grid; align-content: start; gap: 4px; padding-bottom: 8px; overflow: hidden; }
197197 .talk-confirms[data-out] { padding-bottom: 0; }
198198 .talk-confirms[hidden], .talk-confirms-count:empty { display: none; }
@@ -930,18 +930,37 @@ ${dictateJs}
930930 // The crew's run in the pane's wait stage: each line it writes, in the same plain words the server
931931 // drew the first ones in, added as text only (a log line is never markup), the newest few kept.
932932 const plainStep = ${String(plainStep)};
933 const plainThought = ${String(plainThought)};
933934 document.addEventListener("forge:run-log", (e) => {
934935 const d = e.detail, steps = d && [...document.querySelectorAll("[data-crew-steps]")].find((el) => el.dataset.crewSteps === d.run);
935936 if (!steps || !Array.isArray(d.lines)) return;
936937 for (const line of d.lines) {
937938 const step = typeof line === "string" ? plainStep(line) : undefined;
938 if (!step) continue;
939 const thought = step || typeof line !== "string" ? undefined : plainThought(line);
940 if (!step && !thought) continue;
939941 const p = document.createElement("p");
940 p.textContent = step;
942 if (thought) p.className = "talk-crew-thought";
943 p.textContent = step || thought;
941944 steps.append(p);
942945 }
943946 while (steps.children.length > ${STEPS_SHOWN}) steps.firstElementChild.remove();
944947 });
948 document.addEventListener("forge:event", (e) => {
949 const d = e.detail, pane = document.querySelector("[data-pane-of]"), stage = pane && pane.querySelector("[data-stage][data-env]");
950 if (!d || !stage || d.kind !== "run.finished" || !d.payload || d.payload.kind !== "deploy" || d.payload.state !== "ok" || d.repo !== pane.dataset.paneOf) return;
951 if (d.payload.env === stage.dataset.env) reframe();
952 else if (answering || box.value.trim()) return;
953 else if (stage.dataset.env === "production") window.location.reload();
954 // A pull's preview framed when production deploys: the pane is asked what it frames now. Still the
955 // open pull, the frame stays; the pull landed, production is its change, and the page draws once

Next: this reloads on any pull's preview deploy while production is framed; narrow it to the newest pull's env so a person is not reloaded for an unrelated pull.

956 // for production's origin.
957 else if (d.payload.env === "production") fetch("?pane=preview&fragment=pane", { headers: { accept: "text/html" } }).then((r) => r.text()).then((text) => {
958 const t = document.createElement("template");
959 t.innerHTML = text;
960 const now = t.content.querySelector("[data-stage][data-env]");
961 if (now && now.dataset.env !== stage.dataset.env && !answering && !box.value.trim()) window.location.reload();
962 }).catch(() => {});
963 });
945964 // A reply that set the crew on an app opens the pane in place: the page is read again and its head
946965 // (the Chat and Preview tabs) and its pane are swapped in. Only a pane that already frames the app
947966 // draws the page once, since its origin must join frame-src, which a page cannot change on itself.
src/web/pages/talk_preview.ts +27 −8
@@ -12,6 +12,7 @@
1212 */
1313
1414 import { workspaceOf, type Apps } from "../../actions/talk_workspace.ts";
15 import { previewEnv } from "../../apps/data.ts";
1516 import type { User } from "../../core/users.ts";
1617 import { paneCrew, type PaneCrew, type Work } from "../../core/talk_work.ts";
1718 import { mayReadRunLog, mayReadRuns } from "../../actions/runs.ts";
@@ -68,7 +69,7 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
6869 // Code and Diff are the forge's own browser and diff, read only when their tab is chosen.
6970 const work = { repo: ws.repo, build: ask.build, pull: pull ?? ask.build?.pullNumber ?? undefined };
7071 // While nothing is framed, what the crew is doing on the repository, read from its newest run.
71 const crew = view === "preview" && (url === undefined || ask.wait !== undefined) ? paneCrew(ctx.app.db, ctx.app.config.dataDir, ws.repo.id, user, { runs: mayReadRuns(ctx.app, user, ws.repo), logs: mayReadRunLog(ctx.app, user, ws.repo) }) : undefined;
72 const crew = view === "preview" ? paneCrew(ctx.app.db, ctx.app.config.dataDir, ws.repo.id, user, { runs: mayReadRuns(ctx.app, user, ws.repo), logs: mayReadRunLog(ctx.app, user, ws.repo) }) : undefined;

crew! further down relies on going implying defined; restructure so the type narrows without the assertion.

7273 const going = crew !== undefined && (crew.state === "queued" || crew.state === "running");
7374 const panel =
7475 view === "code"
@@ -76,10 +77,10 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
7677 : view === "diff"
7778 ? await diffView(ctx.app, work, ask.version)
7879 : url === undefined || ask.wait !== undefined
79 ? html`<div class="talk-stage talk-stage-wait" data-stage${ask.busy === true ? raw(" data-busy") : null}><p class="talk-stage-note" data-stage-note>${ask.wait ?? ask.idle ?? "Nothing is running yet: the app appears here once it is built."}</p>${crew === undefined ? null : crewBlock(crew, `/${ws.repo.ownerName}/${ws.repo.name}`)}</div>${ask.build === undefined ? null : html`<h2 class="talk-stage-files small muted">The files it starts from</h2>${await codeView(ctx.app, work)}`}`
80 : 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>`;
80 ? html`<div class="talk-stage talk-stage-wait" data-stage${ask.busy === true ? raw(" data-busy") : null}><p class="talk-stage-note" data-stage-note>${ask.wait ?? ask.idle ?? "Nothing is running yet: the app appears here once it is built."}</p>${crew === undefined ? null : crewBlock(crew, `/${ws.repo.ownerName}/${ws.repo.name}`, ws.repo)}</div>${ask.build === undefined ? null : html`<h2 class="talk-stage-files small muted">The files it starts from</h2>${await codeView(ctx.app, work)}`}`
81 : html`<div class="talk-stage" data-stage data-env="${ws.shows === undefined ? "production" : previewEnv(ws.shows)}"><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>${crewRegion(crew !== undefined && (going || crew.state === "failed") ? crew : undefined, ws.repo)}`;
8182 // The address bar of what runs: which environment, where it lives, reload and open on its own.
82 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>`;
83 const where = url === undefined ? null : html`<span class="talk-addr small" title="${url}"><span class="muted">${ws.shows === undefined ? "Production" : `Pull #${String(ws.shows)}`}</span> ${new URL(url).host}</span>`;
8384 // Waiting, the pane is a live region on the repository's runs: a deploy that turns running swaps
8485 // the frame in, and the crew's next run is read as it is queued, starts or ends.
8586 const waiting = url === undefined && view === "preview";
@@ -106,15 +107,28 @@ function productionOrigin(ctx: Ctx, repoId: string): string | undefined {
106107 return record === undefined || runtime === undefined ? undefined : originOf(runtime.urlFor(record, "production"));
107108 }
108109
110 /**
111 * Under a frame, the crew's run while it works or after it failed, else the region empty: it is there
112 * whenever the pane is open, so the crew's next run (the person's next change) is picked up on
113 * run.* and drawn under the same frame, which the swap never touches.
114 */
115 function crewRegion(crew: PaneCrew | undefined, repo: { readonly ownerName: string; readonly name: string }): Html {
116 return crew === undefined
117 ? html`<div class="talk-crew-now" id="talk-crew-now" data-live="run.*" data-live-repo="${repo.ownerName}/${repo.name}" data-live-src="?pane=preview&amp;fragment=pane"></div>`
118 : crewBlock(crew, `/${repo.ownerName}/${repo.name}`, repo);
outdated

High-ish: this region only exists while the run is going or failed. When it is absent (run ok, or none), nothing listens for the crew's next run under a framed app, because the aside's own data-live is only set when waiting. Keep one live region present whenever the pane is open, and prove the swap leaves the iframe alone.

119 }
120
109121 /**
110122 * The crew's run in the wait stage: why it waits or that it works, its newest steps in plain words
111123 * (the script adds each new one as the run writes it; a log line is only ever text here), and the
112124 * run's own page, which is the whole of it without the script.
113125 */
114 function crewBlock(crew: PaneCrew, base: string): Html {
115 return html`<div class="talk-crew-now">
116 <p class="small">${workLineHtml(crew.line)}</p>
117 ${!crew.tail || (crew.steps.length === 0 && crew.state !== "running") ? null : html`<div class="talk-crew-steps small muted" data-crew-steps="${crew.runId}" aria-live="polite">${crew.steps.map((step) => html`<p>${step}</p>`)}</div>`}
126 function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: string; readonly name: string }): Html {
127 // Its own live region: the crew's next run is read as it is queued, starts or ends, and the frame
128 // above it is never redrawn for it.
129 return html`<div class="talk-crew-now" id="talk-crew-now" data-live="run.*" data-live-repo="${repo.ownerName}/${repo.name}" data-live-src="?pane=preview&amp;fragment=pane">
130 <p class="small${crew.state === "running" ? " talk-crew-working" : ""}">${workLineHtml(crew.line)}</p>
131 ${!crew.tail || (crew.steps.length === 0 && crew.state !== "running") ? null : html`<div class="talk-crew-steps small muted" data-crew-steps="${crew.runId}" aria-live="polite">${crew.steps.map((item) => (item.thought ? html`<p class="talk-crew-thought">${item.text}</p>` : html`<p>${item.text}</p>`))}</div>`}
118132 <a class="small" href="${base}/runs/${crew.runId}">See the whole run</a>
119133 </div>`;
120134 }
@@ -134,10 +148,15 @@ export const paneCss = /* css */ `
134148 .talk-stage-wait .talk-stage-note { position: static; padding: 0; text-align: start; }
135149 .talk-stage-files { margin: 16px 0 8px; font-size: 12.5px; font-weight: 600; }
136150 .talk-stage-note[hidden] { display: none; }
151 .talk-crew-now:empty { display: none; }
137152 .talk-crew-now { display: grid; gap: 8px; justify-items: start; margin-top: 12px; }
138153 .talk-crew-now p { margin: 0; }
139154 .talk-crew-steps { display: grid; gap: 2px; overflow-wrap: anywhere; }
140155 .talk-crew-steps p { margin: 0; }
156 .talk-crew-steps .talk-crew-thought { color: var(--fg); }
157 .talk-stage:not(.talk-stage-wait) + .talk-crew-now { margin-top: 12px; }
158 /* While the crew works under it, the frame gives it room: both in view at once. */
159 .talk-stage:has(+ .talk-crew-now:not(:empty)) .talk-frame { height: calc(100dvh - 30rem); min-height: 14rem; }
141160 @media (max-width: 30rem) { .talk-addr { display: none; } }
142161 @media (prefers-reduced-motion: reduce) { .talk-frame { transition: none; } }
143162 `;
test/talk-live-pane.test.ts +108 −6
@@ -13,12 +13,16 @@ import { join } from "node:path";
1313 import { createRepo } from "../src/actions/repos.ts";
1414 import { createApp, type App } from "../src/app.ts";
1515 import { appendTurn, createConversation } from "../src/core/conversations.ts";
16 import { announceRun } from "../src/actions/runs.ts";
17 import { listEvents } from "../src/core/events.ts";
1618 import { createRun } from "../src/core/runs.ts";
1719 import { createSession } from "../src/core/sessions.ts";
1820 import { repoOf } from "../src/core/talk_steps.ts";
19 import { paneCrew, plainStep } from "../src/core/talk_work.ts";
21 import { paneCrew, plainStep, plainThought } from "../src/core/talk_work.ts";
2022 import { createUser, type User } from "../src/core/users.ts";
2123 import { receiptOf } from "../src/crew/receipt.ts";
24 import { liveRegionsJs } from "../src/web/client.ts";
25 import { pollUntil } from "./helpers/poll.ts";
2226 import type { Ctx } from "../src/http/context.ts";
2327 import { serve, type Servers } from "../src/http/server.ts";
2428 import { appendRunLog, flushRunLogs } from "../src/runs/log.ts";
@@ -170,10 +174,10 @@ describe("the pane, by the crew's newest run on the repository", () => {
170174 { runs: true, logs: true },
171175 )!;
172176 expect(now.state).toBe("running");
173 expect(now.steps).toHaveLength(6);
174 expect(now.steps.at(-1)).toBe("Read <img src=x onerror=alert(1)>");
177 expect(now.steps).toHaveLength(8);
178 expect(now.steps.at(-1)?.text).toBe("Read <img src=x onerror=alert(1)>");
175179 const html = (await pane(name)).html.text;
176 expect(html).toContain("The crew is building it now.");
180 expect(html).toContain("The crew is working.");
177181 expect(html).toContain(`data-crew-steps="${run.id}"`);
178182 expect(html).toContain("<p>Changed src/f7.ts</p>");
179183 expect(html).toContain("<p>Read &lt;img src=x onerror=alert(1)&gt;</p>");
@@ -201,7 +205,7 @@ describe("the pane, by the crew's newest run on the repository", () => {
201205 const repo = (await import("../src/core/repos.ts")).getRepo(app.db, "alice", name.split("/")[1]!)!;
202206 expect([mayReadRuns(app, bob, repo), mayReadRunLog(app, bob, repo)]).toEqual([true, false]);
203207 const theirs = (await talkPane(ctx, bob, name, new Map(), "preview")).html.text;
204 expect(theirs).toContain("The crew is building it now.");
208 expect(theirs).toContain("The crew is working.");
205209 expect(theirs).toContain(`href="/${name}/runs/${run.id}"`);
206210 expect(theirs).not.toContain("secret-plan");
207211 expect(theirs).not.toContain("data-crew-steps");
@@ -216,6 +220,38 @@ describe("the pane, by the crew's newest run on the repository", () => {
216220 expect(none).not.toContain("vault.ts");
217221 });
218222
223 test("the starter framed from the start, the crew working under it: who works, its own words and its steps; the crew block is a live region of its own", async () => {
224 const lines = ["cloning alice/clicker", "I'll read the template first to see what the starter gives us.", "\u2192 Read src/main.ts", "Now the counter: one button, and the count kept in the page.", "\u2192 Edit src/main.ts", "\u2192 Bash bun test", "Done with the counter; the checks pass, so I'll push.", "\u2192 Bash git push origin crew/clicker"];
225 const { run, name } = await withRun("running", lines);
226 app.db.run("UPDATE run SET actor_id = ?1 WHERE id = ?2", [alice.id, run.id]);
227 // The newest pull has no preview yet: production, the starter, is framed.
228 const starter = { newestPull: () => 2, urlOf: (_: unknown, env: string) => (env === "production" ? "https://clicker.apps.test/" : undefined) };
229 const p = await talkPane(ctx, alice, name, new Map(), "preview", starter);
230 const html = p.html.text.replace(/\s+/g, " ");
231 expect(html).toContain('<iframe class="talk-frame" data-frame src="https://clicker.apps.test/"');
232 expect(html).toContain('data-stage data-env="production"');
233 expect(html).toContain('<span class="muted">Production</span>');
234 expect(html).toContain('<p class="small talk-crew-working">alice is working.</p>');
235 expect(html).toContain('id="talk-crew-now" data-live="run.*"');
236 expect(html).not.toMatch(/<aside[^>]*data-live=/);
237 // The one escaping the page's html does to a thought: the apostrophe.
238 expect(html).toContain('<p class="talk-crew-thought">I&#39;ll read the template first to see what the starter gives us.</p>');
239 expect(html).toContain("<p>Read src/main.ts</p>");
240 expect(html).toContain("<p>Pushed its work</p>");
241 expect(html.indexOf("talk-frame")).toBeLessThan(html.indexOf("talk-crew-now"));
242 });
243
244 test("the crew's own words, trimmed, and nothing the forge wrote", () => {
245 expect(plainThought("I'll read the template first.")).toBe("I'll read the template first.");
246 expect(plainThought("Now the styles.")).toBe("Now the styles.");
247 const long = "Now " + "the counter keeps its value ".repeat(10) + "end.";
248 const cut = plainThought(long)!;
249 expect(cut.length).toBeLessThanOrEqual(160);
250 expect(cut.endsWith("\u2026")).toBe(true);
251 for (const forge of ["subscription: main", "cloning alice/x", "egress: +npmjs.org for this run", "queued, not started: 2 of 2 concurrent runs", "\u2192 Read a.ts", "you: make it blue", "The last 3 crew runs died cloning their repository: one run at a time starts"])
252 expect([forge, plainThought(forge)]).toEqual([forge, undefined]);
253 });
254
219255 test("the page opens the pane once the crew is on the repository a new app's receipt names", async () => {
220256 const { repo, name } = await withRun("queued");
221257 const chat = createConversation(app.db, alice.id);
@@ -257,6 +293,7 @@ describe("the pane, by the crew's newest run on the repository", () => {
257293 test("the terminal's pane says the same and names the whole run", async () => {
258294 const { run, name } = await withRun("running", [
259295 "→ Read src/a.ts",
296 "Now the push, so the preview picks it up.",
260297 "→ Bash git push",
261298 ]);
262299 const chat = createConversation(app.db, alice.id);
@@ -282,9 +319,74 @@ describe("the pane, by the crew's newest run on the repository", () => {
282319 await settleApp(tui);
283320 }
284321 const text = tui.screen.toText();
285 expect(text).toContain("Crew: The crew is building it now.");
322 expect(text).toContain("Crew: The crew is working.");
286323 expect(text).toContain(" Read src/a.ts");
324 expect(text).toContain(" \u201cNow the push, so the preview picks it up.\u201d");
287325 expect(text).toContain(" Pushed its work");
288326 expect(text).toContain(`The whole run: /${name}/runs/${run.id}`);
289327 });
328
329 test("framed, a finished run leaves the crew region empty; the crew's next run is swapped into it under the same frame", async () => {
330 const { repo, name } = await withRun("ok", ["→ Read src/a.ts"]);
331 const starter = { newestPull: () => undefined, urlOf: (_: unknown, env: string) => (env === "production" ? "https://clicker.apps.test/" : undefined) };
332 const first = (await talkPane(ctx, alice, name, new Map(), "preview", starter)).html.text;
333 expect(first).toContain(`<div class="talk-crew-now" id="talk-crew-now" data-live="run.*" data-live-repo="${name}" data-live-src="?pane=preview&amp;fragment=pane"></div>`);
334 // The person asks for a change: the crew's next run starts on the same repository.
335 const next = createRun(app.db, { repoId: repo.id, kind: "agent", reason: "assigned" });
336 app.db.run("UPDATE run SET state = 'running', actor_id = ?1 WHERE id = ?2", [alice.id, next.id]);
337 appendRunLog(dir, next.id, "→ Edit src/a.ts");
338 flushRunLogs();
339 const fragment = (await talkPane(ctx, alice, name, new Map(), "preview", starter)).html.text;
340 // The page as drawn, its live regions run, the event the stream sends, and the fragment it fetches.
341 const { Window } = await import("happy-dom");
342 const window = new Window({ url: "http://localhost/talk/c1" });
343 // eslint-disable-next-line @typescript-eslint/no-explicit-any
344 const doc = window.document as any;
345 doc.body.innerHTML = first;
346 const frame = doc.querySelector("iframe");
347 const handlers: Record<string, (e: { lastEventId?: string; data: string }) => void> = {};
348 class ES { addEventListener(t: string, f: (e: { data: string }) => void) { handlers[t] = f; } close() {} }
349 const asked: string[] = [];
350 const fetchFn = async (u: string) => { asked.push(u); return { status: 200, ok: true, headers: { get: () => null }, text: async () => fragment }; };
351 const now = (f: () => void) => { queueMicrotask(f); return 1; };
352 new Function("document", "window", "EventSource", "CustomEvent", "fetch", "location", "setTimeout", "Date", "DOMParser", liveRegionsJs)(doc, window, ES, window.CustomEvent, fetchFn, { href: "http://localhost/talk/c1" }, now, Date, window.DOMParser);
353 handlers["forge"]!({ lastEventId: "1", data: JSON.stringify({ kind: "run.started", repo: name }) });
354 await pollUntil(() => doc.querySelector("#talk-crew-now .talk-crew-working") !== null, "the next run in the crew region");
355 expect(asked).toEqual(["?pane=preview&fragment=pane"]);
356 expect(doc.querySelector("#talk-crew-now")!.textContent).toContain("Changed src/a.ts");
357 // The frame is the same element at the same address: never redrawn for the crew.
358 expect(doc.querySelector("iframe")).toBe(frame);
359 expect(frame!.getAttribute("src")).toBe("https://clicker.apps.test/");
360 });
361
362 test("a deploy of production that ends ok reaches the page as the event the pane reframes on: run.finished, the repository, a deploy, ok, its environment", async () => {
363 // The page's handler (talk_client.ts) reads kind, repo, payload.kind, payload.state and payload.env;
364 // this is that event as /events sends it to the app's owner, not a shape written by hand.
365 n += 1;
366 const repo = await createRepo(app, alice, { name: `deployed${String(n)}`, visibility: "private" });
367 if (!repo.ok) throw new Error(String(repo.error));
368 const since = listEvents(app.db, { limit: 1 })[0]?.id ?? "";
369 const run = createRun(app.db, { repoId: repo.value.id, kind: "deploy", env: "production", reason: "merge" });
370 app.db.run("UPDATE run SET state = 'ok' WHERE id = ?1", [run.id]);
371 announceRun(app, { ...run, state: "ok" });
372 const res = await fetch(`${servers.url}/events?since=${encodeURIComponent(since)}`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } });
373 const reader = res.body!.getReader();
374 const decoder = new TextDecoder();
375 let text = "";
376 type Sent = { kind?: string; repo?: string; payload?: Record<string, unknown> };
377 let seen: Sent | undefined;
378 while (seen === undefined) {
379 const chunk = await reader.read();
380 if (chunk.done) break;
381 text += decoder.decode(chunk.value);
382 for (const block of text.split("\n\n")) {
383 const data = /^event: forge\n(?:.*\n)*?data: (.*)$/m.exec(block)?.[1];
384 const event: Sent | undefined = data === undefined ? undefined : (JSON.parse(data) as Sent);
385 if (event?.kind === "run.finished" && event.payload?.["runId"] === run.id) seen = event;
386 }
387 }
388 await reader.cancel();
389 expect(seen).toMatchObject({ kind: "run.finished", repo: `alice/${repo.value.name}`, payload: { kind: "deploy", state: "ok", env: "production" } });
390 });
290391 });
392
test/talk-page.test.ts +37 −4
@@ -11,6 +11,7 @@ import { mkdtemp, rm } from "node:fs/promises";
1111 import { tmpdir } from "node:os";
1212 import { join } from "node:path";
1313 import { createApp, type App } from "../src/app.ts";
14 import { pollUntil } from "./helpers/poll.ts";
1415 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1516 import { sayNo, sayYes } from "../src/actions/conversation_confirms.ts";
1617 import { openIssue } from "../src/actions/issues.ts";
@@ -452,8 +453,8 @@ describe("the page", () => {
452453
453454 test("the page's own bytes are held: stylesheet and script stay small", async () => {
454455 const { talkCss, talkJs } = await import("../src/web/pages/talk_client.ts");
455 expect(Buffer.byteLength(talkCss)).toBeLessThan(18_000);
456 expect(Buffer.byteLength(talkJs)).toBeLessThan(47_300);
456 expect(Buffer.byteLength(talkCss)).toBeLessThan(18_100);
457 expect(Buffer.byteLength(talkJs)).toBeLessThan(49_100);
457458 // A page of its own, so what other tests said to alice never counts: one question and a code reply.
458459 const sizer = await createUser(app.db, { origin: "seed", trusted: true, username: "sizer", email: "[email protected]", password: "a-good-passphrase" });
459460 if (!sizer.ok) throw new Error(sizer.error);
@@ -468,7 +469,7 @@ describe("the page", () => {
468469 // Talk page, because a chart can arrive in a live reply, and a page drawn without them would
469470 // show it unstyled until a reload. 48,328 measured. Then to 50,000 by the reply's one last line
470471 // and the pane's first-version words: 49,466 measured.
471 expect(size).toBeLessThan(52_000);
472 expect(size).toBeLessThan(53_000);
472473 });
473474
474475 describe("the script, driven against a DOM", () => {
@@ -1195,7 +1196,7 @@ describe("the page", () => {
11951196 expect([...steps.children].map((li: any) => li.textContent)).toEqual(["Read a.ts", "Pushed its work", "Read <img src=x onerror=alert(1)>"]);
11961197 expect(steps.querySelector("img")).toBeNull();
11971198 tail("r1", Array.from({ length: 8 }, (_, i) => "\u2192 Edit f" + String(i) + ".ts"));
1198 expect([...steps.children].map((li: any) => li.textContent)).toEqual(["Changed f2.ts", "Changed f3.ts", "Changed f4.ts", "Changed f5.ts", "Changed f6.ts", "Changed f7.ts"]);
1199 expect([...steps.children].map((li: any) => li.textContent)).toEqual(["Changed f0.ts", "Changed f1.ts", "Changed f2.ts", "Changed f3.ts", "Changed f4.ts", "Changed f5.ts", "Changed f6.ts", "Changed f7.ts"]);
11991200 // The same words as the server's: the script runs core's own function.
12001201 const { plainStep } = await import("../src/core/talk_work.ts");
12011202 expect(steps.lastElementChild.textContent).toBe(plainStep("\u2192 Edit f7.ts"));
@@ -1222,6 +1223,38 @@ describe("the page", () => {
12221223 expect([redraws, u.doc.querySelector("body > [data-shell]").hasAttribute("data-split")]).toEqual([1, false]);
12231224 });
12241225
1226 test("the crew's own words join its steps as text; a deploy that turns running reloads the frame it serves, a pull's preview draws the page once, and production after a framed pull lands draws it once", async () => {
1227 const t = await boot();
1228 let reloads = 0;
1229 Object.defineProperty(t.window.location, "reload", { value: () => { reloads += 1; }, configurable: true });
1230 t.doc.body.insertAdjacentHTML("beforeend", '<aside class="talk-pane" data-pane-of="alice/x"><div class="talk-stage" data-stage data-env="production"><iframe data-frame src="http://app.test/"></iframe><p data-stage-note hidden></p></div><div data-crew-steps="r1"></div></aside>');
1231 const steps = t.doc.querySelector("[data-crew-steps]");
1232 t.doc.dispatchEvent(new t.window.CustomEvent("forge:run-log", { detail: { run: "r1", lines: ["I'll read the template <b>first</b>.", "\u2192 Read a.ts", "subscription: main"] } }));
1233 expect([...steps.children].map((p: any) => [p.className, p.textContent])).toEqual([["talk-crew-thought", "I'll read the template <b>first</b>."], ["", "Read a.ts"]]);
1234 expect(steps.querySelector("b")).toBeNull();
1235 const deploy = (env: string, repo = "alice/x") => t.doc.dispatchEvent(new t.window.CustomEvent("forge:event", { detail: { kind: "run.finished", repo, payload: { kind: "deploy", state: "ok", env } } }));
1236 deploy("production", "bob/other");
1237 expect(t.doc.querySelector("[data-stage]").hasAttribute("data-busy")).toBe(false);
1238 deploy("production");
1239 expect([t.doc.querySelector("[data-stage]").hasAttribute("data-busy"), reloads]).toEqual([true, 0]);
1240 deploy("pull-2");
1241 expect(reloads).toBe(1);
1242 // A pull's preview framed when production deploys: the pane is asked what it frames now. The
1243 // pull still open, it frames the pull and nothing moves; the pull landed, production is framed
1244 // and the page draws once for its origin.
1245 t.doc.querySelector("[data-stage]").setAttribute("data-env", "pull-2");
1246 t.page.html = '<aside class="talk-pane"><div class="talk-stage" data-stage data-env="pull-2"></div></aside>';
1247 deploy("production");
1248 await pollUntil(() => t.urls.filter((u: string) => u === "?pane=preview&fragment=pane").length === 1, "the pane asked once");
1249 // Its answer read and judged: a few turns of the microtask queue, no clock.
1250 for (let i = 0; i < 10; i++) await Promise.resolve();
1251 expect(reloads).toBe(1);
1252 t.page.html = '<aside class="talk-pane"><div class="talk-stage" data-stage data-env="production"></div></aside>';
1253 deploy("production");
1254 await pollUntil(() => reloads === 2, "the page drawn once for production");
1255 expect(t.urls.filter((u: string) => u === "?pane=preview&fragment=pane")).toHaveLength(2);
1256 });
1257
12251258 test("a code block in a streamed turn gets its Copy button too", async () => {
12261259 const t = await boot();
12271260 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>');

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs