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

A run that waits says why, in plain words, with the control that changes it #16322

Merged opened this

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

Merged

talk/hold-reason → main 0 commits

  • Merged. talk/hold-reason was merged into main as e4bb9f0.

Review

Sign in to review this change.
14 files changed +639 −25
docs/features/talk.md +2
@@ -207,6 +207,8 @@ A receipt is one calm line in the thread: a check, what was done and its link, t
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`.
209209
210 **A run that waits says why.** When the crew's run is queued and its log names a hold (`queued, not started: …`), the work line says it in plain words and links the exact control that changes it, for whoever may turn it: "Waits for the reset, Sun 29 Nov, 02:00 UTC: the crew has used 92% of this week and may use 90%. Change the limit" (`/settings/crew#knob-budget`). The others: the account's runs or checks at once (`/admin/limits#quotas`), the owner's focus (`/settings#focus`), a shut valve (`/flow#valves`), a bet's daily cap (its bets page), memory and clone failures (no control: the sentence says when it starts). A bet is named, with its cap, only to who may read its bets page; anyone else reads "a bet's daily cap". A hold no sentence knows is never quoted: the line points at the run's page. A run a person sent is never said to wait on the week under 100%: the cap does not hold it. The terminal prints the same line with the control's address, and the `runs`, `new_app` and `tell` answers carry it as `waiting`, `change` and `changeWords`, so the agent says it too (`holdWords`, `src/core/talk_work.ts`; proof `test/talk-hold.test.ts`).
211
210212 ## Confirms wait above the composer (#15734)
211213
212214 A confirm (an action held for the person's yes) 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 confirm is said once, politely.
src/core/talk_work.ts +137 −7
@@ -10,10 +10,11 @@
1010 import type { Database } from "bun:sqlite";
1111 import { getIssue, type Issue } from "./issues.ts";
1212 import { listTurns } from "./conversations.ts";
13 import { canRead, getRepo, type Repo } from "./repos.ts";
13 import { canAdmin, canRead, getRepo, getRepoById, type Repo } from "./repos.ts";
1414 import { mayView } from "./sealed.ts";
1515 import { getUserById, type User } from "./users.ts";
1616 import { callState } from "./talk_steps.ts";
17 import { readRunLogTail } from "../runs/log.ts";
1718
1819 /** The part of a turn the reading needs: its role and its stored text. */
1920 export type Said = { readonly role: string; readonly text: string };
@@ -221,7 +222,7 @@ export function workLine(db: Database, issue: Issue, now: number): string {
221222 if (issue.state === "closed") return WORK_WORDS.closed;
222223 const named = issue.assigneeId === null ? undefined : getUserById(db, issue.assigneeId)?.username;
223224 const who = named ?? WORK_WORDS.crew;
224 const run = db.query<{ state: string; started_at: string | null; branch: string }, [string]>("SELECT state, started_at, branch FROM run WHERE issue_id = ?1 AND kind = 'agent' ORDER BY id DESC LIMIT 1").get(issue.id);
225 const run = lastRun(db, issue);
225226 const pull = run === null || run.branch === "" ? null : db.query<{ id: string; number: number; merged_at: string | null }, [string, string]>("SELECT i.id, i.number, p.merged_at FROM pull p JOIN issue i ON i.id = p.issue_id WHERE p.head_branch = ?1 AND i.repo_id = ?2 ORDER BY i.number DESC LIMIT 1").get(run.branch, issue.repoId);
226227 if (pull !== null) {
227228 if (pull.merged_at !== null) return `${who} ${WORK_WORDS.landed} #${pull.number}.`;
@@ -236,6 +237,135 @@ export function workLine(db: Database, issue: Issue, now: number): string {
236237 return issue.assigneeId === null ? "" : `${WORK_WORDS.assigned} ${who}.`;
237238 }
238239
240 /** The issue's newest crew run: its id, state, start and branch. */
241 const lastRun = (db: Database, issue: Issue) =>
242 db.query<{ id: string; state: string; started_at: string | null; branch: string }, [string]>("SELECT id, state, started_at, branch FROM run WHERE issue_id = ?1 AND kind = 'agent' ORDER BY id DESC LIMIT 1").get(issue.id);
243
244 /** A line of what the crew does, and, when a run waits on something a person can change, that control. */
245 export interface WorkLine {
246 readonly says: string;
247 /** The exact control that changes what the run waits on, and its words; absent when none does, or the reader may not. */
248 readonly change?: { readonly href: string; readonly words: string };
249 }
250
251 /** The prefix every hold is logged with (`crew/dispatch.ts`, `crew/week_hold.ts`, `crew/bet_cap.ts`, `checks/scheduler.ts`). */
252 export const HOLD_PREFIX = "queued, not started: ";
253
254 /** The newest hold a queued run's log names, without its prefix; undefined when it names none. */
255 export function holdOf(dataDir: string, runId: string): string | undefined {
256 const lines = readRunLogTail(dataDir, runId, 40).lines;
257 for (let i = lines.length - 1; i >= 0; i--) {
258 const at = lines[i]!.indexOf(HOLD_PREFIX);
259 if (at >= 0) return lines[i]!.slice(at + HOLD_PREFIX.length).trim();
260 }
261 return undefined;
262 }
263
264 /** A UTC moment as a person reads it: "Sun 29 Nov, 02:00 UTC". */
265 const dayAt = (iso: string): string => {
266 const d = new Date(iso.replace(" UTC", "Z").replace(" ", "T"));
267 if (Number.isNaN(d.getTime())) return iso;
268 const day = d.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short", timeZone: "UTC" }).replace(",", "");
269 return `${day}, ${d.toISOString().slice(11, 16)} UTC`;
270 };
271
272 /** Who may turn each control, and who may read a bet: what a hold's words may name for this reader. */
273 export interface HoldReader {
274 /** The forge's admin: the week's budget, the account's limits, the valves. */
275 readonly admin: boolean;
276 /** The repository's owner: their own focus. */
277 readonly owner: boolean;
278 /** May see the repository's bets page (its admins): a bet's name and its cap. */
279 readonly bets: boolean;
280 readonly repo?: string;
281 }
282
283 /** What `reader` may read and turn of a hold on `repoId`'s run: the one place it is decided. */
284 export function holdReader(db: Database, repoId: string, reader: User | undefined): HoldReader {
285 const repo = getRepoById(db, repoId);
286 return {
287 admin: reader?.isAdmin === true,
288 owner: reader !== undefined && repo?.ownerId === reader.id,
289 bets: reader !== undefined && reader.kind !== "agent" && repo !== undefined && canAdmin(db, repo, reader),
290 ...(repo === undefined ? {} : { repo: `${repo.ownerName}/${repo.name}` }),
291 };
292 }
293
294 /**
295 * A logged hold as one sentence, with the control that changes it for whoever may turn it. Each
296 * shape is one the dispatcher writes (test/talk-hold.test.ts lists where); one it does not know is never quoted, since a
297 * log may name what the reader may not see: the run's page says why.
298 */
299 export function holdWords(hold: string, reader: HoldReader): WorkLine {
300 const link = (may: boolean, href: string, words: string): Pick<WorkLine, "change"> => (may ? { change: { href, words } } : {});
301 let m = /^(\d+)% of the week used, the crew may use up to (\d+)%(?:; it waits for the reset (\d{4}-\d\d-\d\d \d\d:\d\d UTC))?\.?$/.exec(hold);
302 if (m !== null)
303 return {
304 says: m[3] === undefined ? `Waits for room in the week: the crew has used ${m[1]}% of it and may use ${m[2]}%.` : `Waits for the reset, ${dayAt(m[3])}: the crew has used ${m[1]}% of this week and may use ${m[2]}%.`,
305 ...link(reader.admin, "/settings/crew#knob-budget", "Change the limit"),
306 };
307 m = /^(\d+) of (\d+) concurrent (runs|checks)$/.exec(hold);
308 if (m !== null) return { says: `Waits for one of this account's ${m[2]} ${m[3] === "runs" ? "crew runs" : "checks"} at once to end.`, ...link(reader.admin, "/admin/limits#quotas", "Change the limit") };
309 m = /^this forge holds (\d+)% of its memory/.exec(hold);
310 if (m !== null) return { says: `Waits for a running job to finish: this forge is using ${m[1]}% of its memory.` };
311 m = /^its last runs could not clone; it tries again at (.+)$/.exec(hold);
312 if (m !== null) return { says: `Tries again at ${m[1]}: the last runs could not clone this repository.` };
313 m = /^The last (\d+) crew runs died cloning their repository/.exec(hold);
314 if (m !== null) return { says: `Waits its turn: the last ${m[1]} crew runs could not clone their repository, so one starts at a time.` };
315 if (hold.startsWith("its owner is in focus")) return { says: "Waits for the repository's owner to end their focus.", ...link(reader.owner, "/settings#focus", "End focus") };
316 if (hold.startsWith("its repository's valve is shut")) return { says: "Waits for this repository's valve to open on the flow page.", ...link(reader.admin, "/flow#valves", "Open the valve") };
317 m = /^the bet "(.+)" is at its daily cap of (\$[\d.]+)/.exec(hold);
318 if (m !== null)
319 return reader.bets
320 ? { says: `Waits for 00:00 UTC: the bet "${m[1]}" has spent its daily cap of ${m[2]}.`, ...link(reader.repo !== undefined, `/${reader.repo ?? ""}/bets`, "Change the cap") }
321 : { says: "Waits for 00:00 UTC: a bet's daily cap is spent." };
322 return { says: "Waits: its run's page says on what." };
323 }
324
325 /**
326 * A run a person sent passes the week's cap short of the provider's own limit (`crew/dispatch.ts`):
327 * a week hold under 100% in its log is from before, not why it waits now.
328 */
329 const stale = (hold: string, sent: boolean): boolean => {
330 const used = /^(\d+)% of the week used/.exec(hold)?.[1];
331 return sent && used !== undefined && Number(used) < 100;
332 };
333
334 /** The hold a queued run waits on now, or undefined: none logged, or one that no longer holds it. */
335 const holdNow = (db: Database, dataDir: string, runId: string): string | undefined => {
336 const hold = holdOf(dataDir, runId);
337 const sent = db.query<{ sent: number }, [string]>("SELECT sent FROM run WHERE id = ?1").get(runId)?.sent === 1;
338 return hold === undefined || stale(hold, sent) ? undefined : hold;
339 };
340
341 /**
342 * What a queued run waits on, for a reader, as a tool answer carries it: the sentence and the
343 * control's full address; undefined when the run is not queued or nothing holds it.
344 */
345 export function runHold(db: Database, dataDir: string, run: { readonly id: string; readonly state: string; readonly repoId: string }, reader: User | undefined, origin: string): { waiting: string; change?: string; changeWords?: string } | undefined {
346 if (run.state !== "queued") return undefined;
347 const hold = holdNow(db, dataDir, run.id);
348 if (hold === undefined) return undefined;
349 const l = holdWords(hold, holdReader(db, run.repoId, reader));
350 return { waiting: l.says, ...(l.change === undefined ? {} : { change: new URL(l.change.href, origin).href, changeWords: l.change.words }) };
351 }
352
353 /** What an issue's newest crew run waits on, as a tool answer carries it (`runHold`). */
354 export const issueHold = (db: Database, dataDir: string, issue: Issue, reader: User | undefined, origin: string): ReturnType<typeof runHold> => {
355 const run = lastRun(db, issue);
356 return run === null ? undefined : runHold(db, dataDir, { id: run.id, state: run.state, repoId: issue.repoId }, reader, origin);
357 };
358
359 /**
360 * The work line as a reader sees it: a run that waits says on what, from its own log, and links the
361 * control that changes it; anything else is `workLine`.
362 */
363 export function workLineFor(db: Database, dataDir: string, issue: Issue, now: number, reader: User | undefined): WorkLine {
364 const run = issue.state === "closed" ? null : lastRun(db, issue);
365 const hold = run?.state === "queued" ? holdNow(db, dataDir, run.id) : undefined;
366 return hold === undefined ? { says: workLine(db, issue, now) } : holdWords(hold, holdReader(db, issue.repoId, reader));
367 }
368
239369 /** A receipt that names an issue the person may read: what it says, the issue, and its work line now. */
240370 export interface LiveReceipt {
241371 /** "Filed alice/site#3 Round the corners": the verb, the object and the title. */
@@ -244,7 +374,7 @@ export interface LiveReceipt {
244374 readonly owner: string;
245375 readonly name: string;
246376 readonly number: number;
247 readonly line: string;
377 readonly line: WorkLine;
248378 }
249379
250380 const RECEIPT_ISSUE = /^\/([^/]+)\/([^/]+)\/issues\/(\d+)$/;
@@ -253,7 +383,7 @@ const RECEIPT_ISSUE = /^\/([^/]+)\/([^/]+)\/issues\/(\d+)$/;
253383 * Every receipt in these turns that names an issue the person may read, by turn id: the one reader
254384 * of a receipt both doors draw from (the page's live line, the terminal's line and its comment).
255385 */
256 export function liveReceipts(db: Database, user: User, turns: readonly { readonly id: string; readonly role: string; readonly text: string }[]): Map<string, LiveReceipt> {
386 export function liveReceipts(db: Database, dataDir: string, user: User, turns: readonly { readonly id: string; readonly role: string; readonly text: string }[]): Map<string, LiveReceipt> {
257387 const out = new Map<string, LiveReceipt>();
258388 for (const t of turns) {
259389 if (t.role !== "tool" || !t.text.includes("/issues/")) continue;
@@ -270,11 +400,11 @@ export function liveReceipts(db: Database, user: User, turns: readonly { readonl
270400 const issue = repo === undefined || !canRead(db, repo, user) ? undefined : getIssue(db, repo.id, Number(m[3]));
271401 if (repo === undefined || issue === undefined || !mayView(db, repo, issue, user)) continue;
272402 const title = typeof d.title === "string" && d.title !== "" ? ` ${d.title}` : "";
273 out.set(t.id, { says: `${r.verb} ${r.object}${title}`, object: r.object, owner: repo.ownerName, name: repo.name, number: issue.number, line: workLine(db, issue, Date.now()) });
403 out.set(t.id, { says: `${r.verb} ${r.object}${title}`, object: r.object, owner: repo.ownerName, name: repo.name, number: issue.number, line: workLineFor(db, dataDir, issue, Date.now(), user) });
274404 }
275405 return out;
276406 }
277407
278408 /** The work line of each receipt, by turn id, as the page draws it. */
279 export const receiptLines = (db: Database, user: User, turns: readonly { readonly id: string; readonly role: string; readonly text: string }[]): Map<string, string> =>
280 new Map([...liveReceipts(db, user, turns)].map(([id, r]) => [id, r.line]));
409 export const receiptLines = (db: Database, dataDir: string, user: User, turns: readonly { readonly id: string; readonly role: string; readonly text: string }[]): Map<string, WorkLine> =>
410 new Map([...liveReceipts(db, dataDir, user, turns)].map(([id, r]) => [id, r.line]));
src/crew/conversation_brief.ts +1
@@ -24,6 +24,7 @@ export const VOICE: readonly string[] = [
2424 "After you act, say what changed and where in at most three lines, and give detail only when they ask; the known block is for questions about the state of things, never an appendix to a change.",
2525 "Use a value the person gave (a colour, a name, a number) exactly; if it fails something real, such as contrast, say so in one line and offer the nearest value that passes.",
2626 "Never say the forge lacks something you have not looked for, and never say a held action will do more than its call does.",
27 "When a tool answer about a run carries `waiting`, say that sentence as it is and give its `change` address as a link worded with `changeWords`; never say only that it is queued or has not started.",
2728 "Say each thing once: a choice offered as buttons is not asked again in prose, and never say nothing is waiting on them while you hold an ask.",
2829 "When you make an app, say in the same reply who can open it: a new app is private, so only they and people they invite can, and anyone else gets a not-found page; say how they open it up or invite someone.",
2930 "Link the forge's things with a path that starts with one slash, like [pull 4](/owner/repo/pulls/4) or [the app](/owner/repo), or write owner/repo#12 as words; write a full https:// address for anything else, and never a relative path such as src/a.ts, which goes nowhere from a conversation.",
src/http/mcp/tools/new_app.ts +3
@@ -10,6 +10,7 @@ import { err, ok } from "../../../kernel/result.ts";
1010 import type { User } from "../../../core/users.ts";
1111 import type { App } from "../../../app.ts";
1212 import { good, bad, type Tool, str } from "../shared.ts";
13 import { runHold } from "../../../core/talk_work.ts";
1314
1415 /** `newAppFromSentence`, answered in `newApp`'s shape so one switch maps both paths' refusals. */
1516 async function fromSentence(app: App, user: User, sentence: string, input: Omit<NewAppInput, "name">) {
@@ -84,6 +85,8 @@ export const tool: Tool = {
8485 issue: issue === undefined ? null : issue.number,
8586 agent: issue?.assigneeName ?? null,
8687 run: run?.state ?? "none",
88 // A run that waits says on what, and links the control that changes it.
89 ...(run === undefined ? {} : runHold(ctx.app.db, ctx.app.config.dataDir, run, user, ctx.url.origin)),
8790 });
8891 },
8992 };
src/http/mcp/tools/runs.ts +4 −1
@@ -4,10 +4,11 @@ import { mayView } from "../../../core/sealed.ts";
44 import { markReaders } from "../../../crew/direct.ts";
55 import { getIssueById } from "../../../core/issues.ts";
66 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
7 import { runHold } from "../../../core/talk_work.ts";
78
89 export const tool: Tool = {
910 name: "runs",
10 doc: "`{ repo, kind?, limit? }`: the repository's recent runs (kind agent, deploy or check), newest first (id, kind, state, issue or pull number and title, `untrusted: true` on a title from someone who cannot write, started, ended; draws the `ui://forge/runs` card, a failed run first in its status, each row linked to its run page), 1–50, default 20; read as the runs page reads them",
11 doc: "`{ repo, kind?, limit? }`: the repository's recent runs (kind agent, deploy or check), newest first (id, kind, state, issue or pull number and title, `untrusted: true` on a title from someone who cannot write, started, ended; draws the `ui://forge/runs` card, a failed run first in its status, each row linked to its run page; a queued run that waits on something says it as `waiting`, in plain words, with `change`, the address of the control that changes it, and `changeWords`, when the reader may turn it), 1–50, default 20; read as the runs page reads them",
1112 description:
1213 "A repo's runs, newest first: id, kind, state, number, start, end.",
1314 inputSchema: {
@@ -63,6 +64,8 @@ export const tool: Tool = {
6364 ...(issue !== undefined && untrusted.has(issue.id) ? { untrusted: true } : {}),
6465 startedAt: r.startedAt,
6566 endedAt: r.finishedAt,
67 // A queued run says what it waits on, from its own log, and the control that changes it.
68 ...runHold(ctx.app.db, ctx.app.config.dataDir, r, user, ctx.url.origin),
6669 })),
6770 });
6871 return { ...answer, card: { repo: `${repo.ownerName}/${repo.name}` } };
src/http/mcp/tools/tell.ts +3 −1
@@ -9,6 +9,7 @@ import { TAKEN_BACK_WORDS, undoRefusalWords, undoTell } from "../../../actions/t
99 import { mayReadRuns } from "../../../actions/runs.ts";
1010 import { getIssue } from "../../../core/issues.ts";
1111 import { tellStatusFields } from "../../../runs/tell_status.ts";
12 import { issueHold } from "../../../core/talk_work.ts";
1213 import { good, bad, type Tool, str, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1314
1415 export const tool: Tool = {
@@ -94,7 +95,8 @@ export const tool: Tool = {
9495 const n = args["issue"];
9596 const found = typeof n === "number" && Number.isInteger(n) && n > 0 ? getIssue(ctx.app.db, repo.id, n) : undefined;
9697 if (found === undefined || !mayReadRuns(ctx.app, user, repo)) return bad("not_found", "no such tell");
97 return good({ issue: found.number, ...tellStatusFields(ctx.app.db, repo.id, found) });
98 // A run that waits says on what, from its own log, and links the control that changes it.
99 return good({ issue: found.number, ...tellStatusFields(ctx.app.db, repo.id, found), ...issueHold(ctx.app.db, ctx.app.config.dataDir, found, user, ctx.url.origin) });
98100 }
99101 const where = parseContext(args["context"]);
100102 if (where === null)
src/tui/screens/talk_chats.ts +4 −2
@@ -145,7 +145,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
145145 const listed = listTurns(f.app.db, f.user.id, chat.id, { limit: 50, ...(before === undefined ? {} : { before }) });
146146 turns = listed.ok ? listed.value : [];
147147 cards = cardsPlaced(f.app.db, f.user.id, chat.id, turns);
148 receipts = liveReceipts(f.app.db, f.user, turns);
148 receipts = liveReceipts(f.app.db, f.app.config.dataDir, f.user, turns);
149149 const last = before === undefined ? listed : listTurns(f.app.db, f.user.id, chat.id, { limit: 50 });
150150 recent = last.ok ? last.value : [];
151151 repo = repoOf(recent);
@@ -206,7 +206,9 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
206206 // A receipt that names an issue stays in view, with the crew's work line under it.
207207 const receipt = receipts.get(t.id);
208208 if (receipt !== undefined) {
209 const work = receipt.line;
209 // The line, and the control that changes what a waiting run waits on, by its address.
210 const l = receipt.line;
211 const work = 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}`;
210212 n += work === "" ? 2 : 3;
211213 return [[{ text: `✓ ${receipt.says}`, style: style(c.fg, c.bg) }], ...(work === "" ? [] : [[{ text: ` ${work}`, style: style(c.mutedFg, c.bg) }]]), []];
212214 }
src/web/pages/account.ts +1 −1
@@ -202,7 +202,7 @@ function focusActions(ctx: Ctx): Html | null {
202202 if (user.kind !== "user") return null;
203203 const to = "/settings/focus";
204204 const until = focusUntil(ctx.app.db, user.id);
205 return html`<span class="small muted">${focusSentence(until)}</span>
205 return html`<span class="small muted" id="focus">${focusSentence(until)}</span>
206206 ${until === null
207207 ? html`${btn("1h", { name: "for", value: "1h", formaction: to })} ${btn("4h", { name: "for", value: "4h", formaction: to })}`
208208 : btn("End", { name: "for", value: "off", formaction: to })}`;
src/web/pages/admin-limits.ts +1 −1
@@ -101,7 +101,7 @@ export function limitsPage(ctx: Ctx): Response {
101101 meta: html`${c.actorName === "" ? "someone" : c.actorName} · ${time(c.at)}`,
102102 }),
103103 );
104 const quotaRow = html`<div class="status-row">
104 const quotaRow = html`<div class="status-row" id="quotas">
105105 <dt>Account quotas</dt>
106106 <dd>
107107 <form class="row-fields" method="post" action="/admin/quotas">
src/web/pages/knobs.ts +1 −1
@@ -38,7 +38,7 @@ export function knobsCard(ctx: Ctx): Html {
3838 <h2 class="mb">Knobs</h2>
3939 <dl class="status-rows">
4040 ${rows.map(
41 (r) => html`<div class="status-row" data-knob="${r.id}">
41 (r) => html`<div class="status-row" id="knob-${r.id}${r.repo === undefined ? "" : `-${r.repo}`}" data-knob="${r.id}">
4242 <dt title="${r.does}">${r.name}${r.repo === undefined ? html`` : html` <span class="mono muted">${r.repo}</span>`}</dt>
4343 <dd>${r.effect}</dd>
4444 ${control(r)}
src/web/pages/talk.ts +9 −9
@@ -72,8 +72,8 @@ import { agentHtml, liveHtml, voiceCss, voiceOf, type Voice } from "../talk_part
7272 import { badge, btn, icon, iconBtn, menu, meter, row, time } from "../ui.ts";
7373 import { inlineIcons } from "../icons.ts";
7474 import { DISPLAY_NAMES, setTalkDisplay, TALK_DISPLAY, talkDisplay, type TalkDisplay } from "../../core/settings.ts";
75 import { peekCss } from "../talk_peek.ts";
76 import { receiptLines } from "../../core/talk_work.ts";
75 import { peekCss, workLineHtml } from "../talk_peek.ts";
76 import { receiptLines, type WorkLine } from "../../core/talk_work.ts";
7777 import { buildCss, chosenTemplate, panelFor, templateChips } from "../talk_build.ts";
7878 import type { User } from "../../core/users.ts";
7979 import { chatBuildOf } from "../../core/chat_build.ts";
@@ -184,7 +184,7 @@ const ISSUE_PAGE = /^\/([A-Za-z0-9][A-Za-z0-9_.-]{0,63})\/([A-Za-z0-9][A-Za-z0-9
184184 * and Reply sends the composer's words to the issue, where a working crew member hears them as its
185185 * next step.
186186 */
187 function receiptCard(id: string, turnId: string, receipt: Receipt, at: string, set: string, undone: boolean, title = "", line = ""): Html {
187 function receiptCard(id: string, turnId: string, receipt: Receipt, at: string, set: string, undone: boolean, title = "", line: WorkLine = { says: "" }): Html {
188188 const issue = ISSUE_PAGE.exec(receipt.href);
189189 const undo = receipt.undo === undefined || !INVERSES.has(receipt.undo.tool)
190190 ? null
@@ -193,7 +193,7 @@ function receiptCard(id: string, turnId: string, receipt: Receipt, at: string, s
193193 : html`<form method="post" action="${HERE}/undo/${turnId}">${btn(receipt.undo.label, { icon: "history", label: receipt.undo.label, size: "sm", variant: "ghost" })}</form>`;
194194 return html`<li class="talk-turn talk-receipt${set}" id="${id}" data-done>
195195 <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>
196 ${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>`}
196 ${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}">${workLineHtml(line)}</p>`}
197197 ${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>`}
198198 </li>`;
199199 }
@@ -355,7 +355,7 @@ const linkedOf =
355355 };
356356
357357 /** One turn as the page and the stream both draw it; `waiting` is the confirms still open. */
358 export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend, act?: Html, work?: Work, files: readonly ConversationFile[] = [], expired: ReadonlySet<string> = new Set(), undone: ReadonlySet<string> = new Set(), refs?: (n: number) => string | undefined, voice?: Voice, look?: TalkLook, lines?: ReadonlyMap<string, string>): Html {
358 export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend, act?: Html, work?: Work, files: readonly ConversationFile[] = [], expired: ReadonlySet<string> = new Set(), undone: ReadonlySet<string> = new Set(), refs?: (n: number) => string | undefined, voice?: Voice, look?: TalkLook, lines?: ReadonlyMap<string, WorkLine>): Html {
359359 const id = `t-${turn.id}`;
360360 const set = turn.replaced ? " talk-replaced" : "";
361361 const acts = act === undefined ? null : html`<div class="talk-acts">${act}</div>`;
@@ -395,10 +395,10 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend,
395395 // A tool turn: the confirm's outcome as JSON, or the call the agent made as text.
396396 const receipt = data?.["done"] === true ? readReceipt(data["receipt"]) : undefined;
397397 if (data !== undefined && receipt !== undefined && ("confirm" in data || "undid" in data))
398 return receiptCard(id, turn.id, receipt, turn.createdAt, set, undone.has(turn.id), "", lines?.get(turn.id) ?? "");
398 return receiptCard(id, turn.id, receipt, turn.createdAt, set, undone.has(turn.id), "", lines?.get(turn.id));
399399 // Where a line went (#13942): the issue it opened, linked, or the plain word that none was.
400400 if (data?.["filed"] === true && receipt !== undefined && /^\/[^/]/.test(receipt.href))
401 return receiptCard(id, turn.id, receipt, turn.createdAt, set, false, typeof data["title"] === "string" ? data["title"] : "", lines?.get(turn.id) ?? "");
401 return receiptCard(id, turn.id, receipt, turn.createdAt, set, false, typeof data["title"] === "string" ? data["title"] : "", lines?.get(turn.id));
402402 if (data?.["filed"] === false && typeof data["says"] === "string")
403403 return html`<li class="talk-turn talk-tool${set}" id="${id}"><p class="muted">${data["says"]} <span class="talk-when">${time(turn.createdAt)}</span></p></li>`;
404404 if (data !== undefined && "undid" in data)
@@ -604,7 +604,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
604604 const framed = pane.live && !pending;
605605 const about = editing === undefined ? aboutLine(ctx) : null;
606606 const display = talkDisplay(ctx.app.db, user.id);
607 const lines = receiptLines(ctx.app.db, user, turns);
607 const lines = receiptLines(ctx.app.db, ctx.app.config.dataDir, user, turns);
608608 // The crew's line says something only while a run is live: idle is silence.
609609 const crew = liveCrewRows(ctx, user);
610610 const body = html`<div class="talk-page" data-shell data-pane="${shown}"${listing ? raw(" data-view=\"list\"") : null}${split ? raw(" data-split") : null}><h1 class="sr-only">Talk</h1>
@@ -954,7 +954,7 @@ export function talkStream(ctx: Ctx): Response {
954954 for (const turn of fresh) {
955955 // A frame lands in a page whose sprite is its own: its icons are drawn inline (`inlineIcons`).
956956 const held = confirmsOf([turn], waitingList)[0];
957 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), ...(held === undefined ? {} : { held: inlineIcons(held.text) }) }, turn.id);
957 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, app.config.dataDir, user, [turn])).text), ...(held === undefined ? {} : { held: inlineIcons(held.text) }) }, turn.id);
958958 cursor = turn.id;
959959 }
960960 // The page is told at once what the block holds after these turns, empty once it is
src/web/talk_peek.ts +5 −2
@@ -20,7 +20,7 @@ import { notePhase, takeSessionTime } from "../core/route_timing.ts";
2020 import { fragment } from "./layout.ts";
2121 import { liveCrewRows } from "../actions/crew_now.ts";
2222 import { crewLine } from "./crew_now.ts";
23 import { workLine } from "../core/talk_work.ts";
23 import { workLine, workLineFor, type WorkLine } from "../core/talk_work.ts";
2424
2525 /** The paths a peek reads: a repository, or one of its issues or pulls. */
2626 const PEEK =
@@ -177,7 +177,7 @@ function workFragment(ctx: Ctx): Response {
177177 const repo = getRepo(ctx.app.db, m[1] ?? "", m[2] ?? "");
178178 const issue = repo === undefined || !canRead(ctx.app.db, repo, ctx.auth.user) ? undefined : getIssue(ctx.app.db, repo.id, Number(m[4]));
179179 if (repo === undefined || issue === undefined || !mayView(ctx.app.db, repo, issue, ctx.auth.user)) return fragment(html``, { status: 404 });
180 return fragment(html`<p class="talk-work-line small muted" id="${id}">${workLine(ctx.app.db, issue, Date.now())}</p>`, { request: ctx.request });
180 return fragment(html`<p class="talk-work-line small muted" id="${id}">${workLineHtml(workLineFor(ctx.app.db, ctx.app.config.dataDir, issue, Date.now(), ctx.auth.user))}</p>`, { request: ctx.request });
181181 }
182182
183183 // GET /live/talk-crew — the crew's one line on Talk, empty when it is idle.
@@ -205,3 +205,6 @@ export const peekCss = /* css */ `
205205 .talk-peek-sheet .dialog-body { padding: 16px; }
206206 @media (prefers-reduced-motion: no-preference) { .talk-peek:not([hidden]) { animation: talk-in var(--dur-2) var(--ease); } }
207207 `;
208
209 /** A work line's words, and the control that changes what it waits on as a link. */
210 export const workLineHtml = (l: WorkLine): Html => html`${l.says}${l.change === undefined ? null : html` <a href="${l.change.href}">${l.change.words}</a>`}`;
test/talk-brief-voice.test.ts +6
@@ -66,6 +66,12 @@ describe("the brief and the parser agree", () => {
6666 });
6767
6868 describe("how the agent is told to answer", () => {
69 test("a run that waits is said with its reason and its control, never as a bare queued", () => {
70 expect(brief).toContain("carries `waiting`, say that sentence as it is");
71 expect(brief).toContain("give its `change` address as a link worded with `changeWords`");
72 expect(brief).toContain("never say only that it is queued");
73 });
74
6975 test("the answer first, depth when asked, and no fixed length", () => {
7076 expect(brief).toContain("Open with the answer");
7177 expect(brief).toContain("<details><summary>");
test/talk-hold.test.ts added +462
@@ -0,0 +1,462 @@
1 /**
2 * A run that waits says why (#15734): the hold its own log names, as one sentence, with the exact
3 * control that changes it for whoever may turn it, wherever Talk shows or reads the run (the
4 * receipt's work line and its live fragment, the terminal's line, the `runs` / `new_app` / `tell`
5 * answers). Every hold the dispatcher logs has its sentence, made by the code that logs it where that
6 * code is exported; a hold it does not know is never quoted, and a bet is named only to who may read
7 * its bets page.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { readFileSync } from "node:fs";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createRepo } from "../src/actions/repos.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import { appendTurn, createConversation } from "../src/core/conversations.ts";
17 import { createIssue, type Issue } from "../src/core/issues.ts";
18 import { createRun } from "../src/core/runs.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import {
21 HOLD_PREFIX,
22 holdOf,
23 holdWords,
24 runHold,
25 workLineFor,
26 type HoldReader,
27 } from "../src/core/talk_work.ts";
28 import { createToken } from "../src/core/tokens.ts";
29 import { createUser, type User } from "../src/core/users.ts";
30 import { capNote } from "../src/crew/bet_cap.ts";
31 import { weekDecision } from "../src/crew/week.ts";
32 import { weekHold } from "../src/crew/week_hold.ts";
33 import { serve, type Servers } from "../src/http/server.ts";
34 import { appendRunLog, flushRunLogs } from "../src/runs/log.ts";
35 import { memoryHold } from "../src/runs/memory_hold.ts";
36 import { createForgeApp } from "../src/tui/forge.ts";
37 import { headlessTerminal } from "../src/tui/term/terminal.ts";
38 import { quietLogs } from "./helpers/globals.ts";
39 import { promote } from "./helpers/members.ts";
40 import { settleApp } from "./helpers/tui.ts";
41
42 quietLogs();
43
44 const admin: HoldReader = {
45 admin: true,
46 owner: true,
47 bets: true,
48 repo: "alice/site",
49 };
50 const stranger: HoldReader = {
51 admin: false,
52 owner: false,
53 bets: false,
54 repo: "alice/site",
55 };
56 const logged = (line: string): string => {
57 expect(line.startsWith(HOLD_PREFIX)).toBe(true);
58 return line.slice(HOLD_PREFIX.length);
59 };
60 const FALLBACK = "Waits: its run's page says on what.";
61
62 /**
63 * Every place the dispatcher logs a hold, by the words it logs, with a hold it writes there. A site
64 * that is gone, or a hold the sentences no longer know, fails here by name.
65 */
66 const SITES: readonly { file: string; needle: string; hold: string }[] = [
67 {
68 file: "src/crew/week_hold.ts",
69 needle: "queued, not started: ${week.sentence}",
70 hold: "92% of the week used, the crew may use up to 90%; it waits for the reset 2026-11-29 02:00 UTC.",
71 },
72 {
73 file: "src/crew/dispatch.ts",
74 needle: "queued, not started: its repository's valve is shut (/flow)",
75 hold: "its repository's valve is shut (/flow)",
76 },
77 {
78 file: "src/crew/dispatch.ts",
79 needle:
80 "queued, not started: its owner is in focus and the crew starts nothing new until it ends",
81 hold: "its owner is in focus and the crew starts nothing new until it ends",
82 },
83 {
84 file: "src/crew/dispatch.ts",
85 needle:
86 "queued, not started: its last runs could not clone; it tries again at",
87 hold: "its last runs could not clone; it tries again at 14:05 UTC",
88 },
89 {
90 file: "src/crew/dispatch.ts",
91 needle: "queued, not started: ${full}",
92 hold: "2 of 2 concurrent runs",
93 },
94 {
95 file: "src/checks/scheduler.ts",
96 needle: "queued, not started: ${full}",
97 hold: "3 of 3 concurrent checks",
98 },
99 {
100 file: "src/crew/dispatch.ts",
101 needle: "queued, not started: ${tight}",
102 hold: memoryHold(1, () => 0.93)!,
103 },
104 {
105 file: "src/crew/dispatch.ts",
106 needle: "queued, not started: ${breaker.says}",
107 hold: "The last 3 crew runs died cloning their repository: one run at a time starts until one gets past its clone.",
108 },
109 {
110 file: "src/crew/bet_cap.ts",
111 needle: 'queued, not started: the bet "${name}" is at its daily cap',
112 hold: logged(capNote("speed", 5)),
113 },
114 ];
115
116 describe("every hold the dispatcher logs is one sentence, with its control for who may turn it", () => {
117 test("each place that logs a hold still does, and its hold has a sentence of its own", () => {
118 for (const site of SITES) {
119 expect([
120 site.file,
121 readFileSync(site.file, "utf8").includes(site.needle),
122 ]).toEqual([site.file, true]);
123 expect([site.hold, holdWords(site.hold, admin).says]).not.toEqual([
124 site.hold,
125 FALLBACK,
126 ]);
127 }
128 });
129
130 test("the week: when it starts and why, said once, and the limit's control", () => {
131 const week = weekDecision({
132 meter: {
133 freePct: 8,
134 keptPct: 0,
135 resetsAt: new Date("2026-11-29T02:00:00Z"),
136 },
137 now: new Date("2026-11-24T12:00:00Z"),
138 ceiling: 4,
139 reserve: 0.1,
140 });
141 const hold = logged(weekHold(week)!);
142 expect(holdWords(hold, admin)).toEqual({
143 says: "Waits for the reset, Sun 29 Nov, 02:00 UTC: the crew has used 92% of this week and may use 90%.",
144 change: { href: "/settings/crew#knob-budget", words: "Change the limit" },
145 });
146 // The sentence for everyone; the control only for who may turn it.
147 expect(holdWords(hold, stranger).change).toBeUndefined();
148 // Said once: no "Waiting:" before the reason.
149 for (const site of SITES)
150 expect(holdWords(site.hold, admin).says).not.toContain("Waiting");
151 });
152
153 test("the account's runs or checks at once, memory, clones, focus, a valve", () => {
154 expect(holdWords("2 of 2 concurrent runs", admin)).toEqual({
155 says: "Waits for one of this account's 2 crew runs at once to end.",
156 change: { href: "/admin/limits#quotas", words: "Change the limit" },
157 });
158 expect(holdWords("3 of 3 concurrent checks", stranger)).toEqual({
159 says: "Waits for one of this account's 3 checks at once to end.",
160 });
161 expect(holdWords(memoryHold(1, () => 0.93)!, admin)).toEqual({
162 says: "Waits for a running job to finish: this forge is using 93% of its memory.",
163 });
164 expect(
165 holdWords(
166 "its last runs could not clone; it tries again at 14:05 UTC",
167 admin,
168 ).says,
169 ).toBe(
170 "Tries again at 14:05 UTC: the last runs could not clone this repository.",
171 );
172 expect(holdWords("The last 3 crew runs died cloning their repository: one run at a time starts until one gets past its clone.", admin).says).toBe(
173 "Waits its turn: the last 3 crew runs could not clone their repository, so one starts at a time.",
174 );
175 expect(
176 holdWords(
177 "its owner is in focus and the crew starts nothing new until it ends",
178 admin,
179 ),
180 ).toEqual({
181 says: "Waits for the repository's owner to end their focus.",
182 change: { href: "/settings#focus", words: "End focus" },
183 });
184 expect(
185 holdWords(
186 "its owner is in focus and the crew starts nothing new until it ends",
187 { ...admin, owner: false },
188 ).change,
189 ).toBeUndefined();
190 expect(holdWords("its repository's valve is shut (/flow)", admin)).toEqual({
191 says: "Waits for this repository's valve to open on the flow page.",
192 change: { href: "/flow#valves", words: "Open the valve" },
193 });
194 });
195
196 test("a bet is named, with its cap and its page, only to who may read its bets page; anyone else hears of a bet's cap", () => {
197 const hold = logged(capNote("speed", 5));
198 expect(holdWords(hold, admin)).toEqual({
199 says: 'Waits for 00:00 UTC: the bet "speed" has spent its daily cap of $5.00.',
200 change: { href: "/alice/site/bets", words: "Change the cap" },
201 });
202 const said = holdWords(hold, stranger);
203 expect(said).toEqual({
204 says: "Waits for 00:00 UTC: a bet's daily cap is spent.",
205 });
206 expect(JSON.stringify(said)).not.toContain("speed");
207 expect(JSON.stringify(said)).not.toContain("$5");
208 });
209
210 test("a hold no sentence knows is never quoted: the run's page says why", () => {
211 expect(holdWords('the bet "secret plan" is somewhere new', admin)).toEqual({
212 says: FALLBACK,
213 });
214 });
215 });
216
217 describe("where Talk shows or reads a waiting run", () => {
218 let dir: string;
219 let app: App;
220 let servers: Servers;
221 let alice: User;
222 let bob: User;
223 let issue: Issue;
224 let runId: string;
225 let id = 1;
226 const WEEK =
227 "queued, not started: 92% of the week used, the crew may use up to 90%; it waits for the reset 2026-11-29 02:00 UTC.";
228 const SAYS =
229 "Waits for the reset, Sun 29 Nov, 02:00 UTC: the crew has used 92% of this week and may use 90%.";
230 /** A tool's answer through /mcp, as a token of `who`. */
231 const tool = async (who: User, name: string, args: unknown) => {
232 const res = await fetch(`${servers.url}/mcp`, {
233 method: "POST",
234 headers: {
235 "content-type": "application/json",
236 accept: "application/json, text/event-stream",
237 authorization: `Bearer ${createToken(app.db, who.id, `t${String(id)}`, "ro").token}`,
238 },
239 body: JSON.stringify({
240 jsonrpc: "2.0",
241 id: id++,
242 method: "tools/call",
243 params: { name, arguments: args },
244 }),
245 });
246 const body = (await res.json()) as {
247 result: { content: { text: string }[]; isError?: boolean };
248 };
249 const text = body.result.content[0]!.text;
250 if (body.result.isError === true) throw new Error(text);
251 return JSON.parse(text) as Record<string, unknown>;
252 };
253 beforeAll(async () => {
254 dir = await mkdtemp(join(tmpdir(), "forge-talk-hold-"));
255 app = createApp({ dataDir: dir, port: 0 });
256 servers = await serve(app);
257 for (const name of ["alice", "bob"]) {
258 const made = await createUser(app.db, {
259 origin: "seed",
260 trusted: true,
261 username: name,
262 email: `${name}@forge.local`,
263 password: "a-good-passphrase",
264 adminIfFirst: name === "alice",
265 });
266 if (!made.ok) throw new Error(made.error);
267 promote(app.db, made.value);
268 if (name === "alice") alice = made.value;
269 else bob = made.value;
270 }
271 const repo = await createRepo(app, alice, {
272 name: "arena",
273 visibility: "public",
274 });
275 if (!repo.ok) throw new Error("repo");
276 const made = createIssue(app.db, {
277 repoId: repo.value.id,
278 authorId: alice.id,
279 title: "Build the arena",
280 body: "b",
281 });
282 if (!made.ok) throw new Error("issue");
283 issue = made.value;
284 runId = createRun(app.db, {
285 repoId: repo.value.id,
286 kind: "agent",
287 issueId: issue.id,
288 reason: "assigned",
289 }).id;
290 appendRunLog(dir, runId, WEEK);
291 flushRunLogs();
292 });
293 afterAll(async () => {
294 servers.stop();
295 app.close();
296 await rm(dir, { recursive: true, force: true });
297 });
298
299 test("the run's own log names its hold, and the work line says it, with the control only for who may turn it", () => {
300 expect(holdOf(dir, runId)).toBe(WEEK.slice(HOLD_PREFIX.length));
301 const mine = workLineFor(app.db, dir, issue, Date.now(), alice);
302 expect(mine).toEqual({
303 says: SAYS,
304 change: { href: "/settings/crew#knob-budget", words: "Change the limit" },
305 });
306 expect(workLineFor(app.db, dir, issue, Date.now(), bob)).toEqual({
307 says: SAYS,
308 });
309 expect(
310 runHold(
311 app.db,
312 dir,
313 { id: runId, state: "running", repoId: issue.repoId },
314 alice,
315 "https://forge.example",
316 ),
317 ).toBeUndefined();
318 });
319
320 test("a run a person sent is not said to wait on the week under 100%: that hold is from before", () => {
321 const other = createIssue(app.db, { repoId: issue.repoId, authorId: alice.id, title: "Sent work", body: "b" });
322 if (!other.ok) throw new Error("issue");
323 const sent = createRun(app.db, {
324 repoId: issue.repoId,
325 kind: "agent",
326 issueId: other.value.id,
327 reason: "assigned",
328 sent: true,
329 });
330 appendRunLog(dir, sent.id, WEEK);
331 flushRunLogs();
332 expect(
333 runHold(app.db, dir, sent, alice, "https://forge.example"),
334 ).toBeUndefined();
335 const full = createRun(app.db, {
336 repoId: issue.repoId,
337 kind: "agent",
338 issueId: other.value.id,
339 reason: "assigned",
340 sent: true,
341 });
342 appendRunLog(
343 dir,
344 full.id,
345 "queued, not started: 100% of the week used, the crew may use up to 90%; it waits for the reset 2026-11-29 02:00 UTC.",
346 );
347 flushRunLogs();
348 expect(
349 runHold(app.db, dir, full, alice, "https://forge.example")?.waiting,
350 ).toBe(
351 "Waits for the reset, Sun 29 Nov, 02:00 UTC: the crew has used 100% of this week and may use 90%.",
352 );
353 app.db.run("UPDATE run SET state = 'cancelled' WHERE id IN (?1, ?2)", [
354 sent.id,
355 full.id,
356 ]);
357 });
358
359 test("the doors: runs and tell carry waiting, change and changeWords for an admin, and no change for anyone else", async () => {
360 const runs = (
361 await tool(alice, "runs", { repo: "alice/arena", kind: "agent" })
362 )["runs"] as Record<string, unknown>[];
363 expect(runs.find((r) => r["id"] === runId)).toMatchObject({
364 waiting: SAYS,
365 change: `${servers.url}/settings/crew#knob-budget`,
366 changeWords: "Change the limit",
367 });
368 const seen = (
369 (await tool(bob, "runs", { repo: "alice/arena", kind: "agent" }))[
370 "runs"
371 ] as Record<string, unknown>[]
372 ).find((r) => r["id"] === runId)!;
373 expect([seen["waiting"], seen["change"], seen["changeWords"]]).toEqual([
374 SAYS,
375 undefined,
376 undefined,
377 ]);
378 const told = await tool(alice, "tell", {
379 repo: "alice/arena",
380 issue: issue.number,
381 });
382 expect(told).toMatchObject({
383 waiting: SAYS,
384 change: `${servers.url}/settings/crew#knob-budget`,
385 });
386 const toldBob = await tool(bob, "tell", {
387 repo: "alice/arena",
388 issue: issue.number,
389 });
390 expect([toldBob["waiting"], toldBob["change"]]).toEqual([SAYS, undefined]);
391 });
392
393 test("the receipt's live line carries the link, and the link lands on the control", async () => {
394 const cookie = {
395 cookie: `forge_session=${createSession(app.db, alice.id).token}`,
396 };
397 const line = await (
398 await fetch(
399 `${servers.url}/live/talk-work?href=${encodeURIComponent("/alice/arena/issues/1")}&id=w-1`,
400 { headers: cookie },
401 )
402 ).text();
403 expect(line).toContain(
404 `${SAYS} <a href="/settings/crew#knob-budget">Change the limit</a>`,
405 );
406 // Each control a hold names is on its page under that anchor.
407 for (const [page, anchor] of [
408 ["/settings/crew", 'id="knob-budget"'],
409 ["/admin/limits", 'id="quotas"'],
410 ["/settings", 'id="focus"'],
411 ["/flow", 'id="valves"'],
412 ] as const)
413 expect([
414 page,
415 (
416 await (
417 await fetch(`${servers.url}${page}`, { headers: cookie })
418 ).text()
419 ).includes(anchor),
420 ]).toEqual([page, true]);
421 });
422
423 test("the terminal says the same, with the control's path when the forge's address is not set, never an invented host", async () => {
424 const chat = createConversation(app.db, alice.id);
425 if (!chat.ok) throw new Error(chat.error);
426 appendTurn(app.db, alice.id, chat.value.id, {
427 role: "tool",
428 text: JSON.stringify({
429 done: true,
430 filed: true,
431 title: "Build the arena",
432 receipt: {
433 verb: "Filed",
434 object: "alice/arena#1",
435 href: "/alice/arena/issues/1",
436 },
437 }),
438 });
439 const terminal = headlessTerminal(160, 30);
440 const { app: tui } = createForgeApp(
441 app,
442 {
443 sshUsername: "alice",
444 remoteAddress: "127.0.0.1",
445 fingerprint: "SHA256:test",
446 user: alice,
447 },
448 { terminal, exitHooks: false },
449 );
450 tui.start();
451 for (const k of [":", "Conversations", "\r", "\r"]) {
452 terminal.feed(k);
453 await settleApp(tui);
454 }
455 const text = tui.screen.toText();
456 expect(app.config.url).toBeUndefined();
457 expect(text).toContain(
458 `${SAYS} Change the limit: /settings/crew#knob-budget`,
459 );
460 expect(text).not.toContain("localhost");
461 });
462 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs