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

After a held action is confirmed in /talk the reply carries a receipt: what changed, where to see it, and the one tap to undo when it can be undone #12713

Merged opened this

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

Merged

scout/forge:scout/12680-after-a-held-action-is-confirmed-in-talk → main 8 commits fork

  • Merged. scout/12680-after-a-held-action-is-confirmed-in-talk was merged into main as 2d108ac.

Review

Sign in to review this change.
12 files changed +643 −7
docs/features/talk.md +6
@@ -125,3 +125,9 @@ An empty `/talk` asks "What do you want to build?" with starters from the marked
125125 - **Limits:** five builds an hour and ten unpublished at once, per person (`BUILDS_PER_HOUR`, `UNPUBLISHED_MAX`); a template must be one on offer to that person, on the API as on the page; a start that fails takes back the repository and conversation it made.
126126 - **Terminal:** `:` then **Build an app**. `n` says what to build (`t` chooses the template), Enter opens a build and lists its versions newest first, Enter again shows the files that version changed, `R` restores the chosen version, `P` publishes, `r` reloads. The screen calls the same `actions/build.ts` functions as the page, so it is gated the same way (your own conversation, a writer of the repository) and what it does is what the page shows on its next read.
127127 - Proof: `test/talk-build.test.ts` runs prompt, repository, v1, v2, restore v1 and publish against a scratch forge; `test/tui-talk-build.test.ts` does the same from the terminal.
128
129 ## Receipts
130
131 After you confirm a held action, the thread shows a receipt: the verb, the object, and a link to the page it changed. For `close` (close/reopen) and `assign` (assign/unassign) it also draws an Undo form (`POST /talk/undo/:turn`, same-origin, your own session) that does the inverse and writes its own receipt. It refuses, and says so, when the object has changed since (someone else's later change is never undone) or when it was already undone. Every other confirmed call that names a repository gets a receipt with no Undo. A failed undo changes nothing and can be tried again; a second tap while one runs is refused.
132
133 **Terminal:** `:` then **Receipts** lists your receipts that can still be undone; `u` asks, then runs the same `undoReceipt` as the page's form, so it is gated the same (your own receipt, once, only while the object is as it was left). Proof: `test/tui-talk-receipts.test.ts`.
src/actions/conversation_confirms.ts +113 −1
@@ -12,13 +12,17 @@
1212 * token — so this module takes a person who already passed it.
1313 */
1414
15 import type { Database } from "bun:sqlite";
1516 import { actingVia } from "../core/acting_via.ts";
16 import { appendTurn, conversationOfVia, MAX_TURN_CHARS } from "../core/conversations.ts";
17 import { appendTurn, conversationOfVia, getConversation, getTurn, listConversations, listTurns, MAX_TURN_CHARS, undoneBy } from "../core/conversations.ts";
18 import { getIssue } from "../core/issues.ts";
19 import { getRepo } from "../core/repos.ts";
1720 import { answerHeld, countWaiting, HELD_TTL_MS, waitingFor, type YesRefusal } from "../core/fence.ts";
1821 import type { User } from "../core/users.ts";
1922 import { argumentsShown, confirmSentence, keptOf, undoOf } from "../crew/conversation_confirm.ts";
2023 import type { Ctx } from "../http/context.ts";
2124 import { loadMcp } from "../http/mcp/load.ts";
25 import { INVERSES, readReceipt, receiptOf, stillSo, targetOf, type Seen } from "../crew/receipt.ts";
2226
2327 /** A confirm as the person reads it before saying yes. */
2428 export interface Waiting {
@@ -69,6 +73,17 @@ const kept = (value: unknown): unknown => {
6973 return text.length <= MAX_TURN_CHARS / 2 ? value : `${text.slice(0, MAX_TURN_CHARS / 2)}…`;
7074 };
7175
76 /** The issue or pull a call names as it stands, for a receipt; undefined when it names none. */
77 function seen(ctx: Ctx, args: Record<string, unknown>): Seen | undefined {
78 const target = targetOf(args);
79 if (target === undefined) return undefined;
80 const [owner = "", name = ""] = target.repo.split("/");
81 const repo = getRepo(ctx.app.db, owner, name);
82 const issue = repo === undefined ? undefined : getIssue(ctx.app.db, repo.id, target.number);
83 if (issue === undefined) return undefined;
84 return { kind: issue.kind, state: issue.state, assignee: issue.assigneeName };
85 }
86
7287 /** Say yes to `confirmId` as `user`, whose own session asked. */
7388 export async function sayYes(ctx: Ctx, user: User, confirmId: string): Promise<Yes> {
7489 if (!CONFIRM_ID.test(confirmId)) return { ok: false, error: "not_found" };
@@ -84,16 +99,19 @@ export async function sayYes(ctx: Ctx, user: User, confirmId: string): Promise<Y
8499 // The session's own authority, as a token would carry it: admin scope
85100 // for an admin only, as only an admin mints an admin token.
86101 const asPerson: Ctx = { ...ctx, auth: { ...ctx.auth, user, scope: user.isAdmin ? "admin" : "rw" } };
102 const before = seen(ctx, held.args);
87103 const ran = await actingVia({ userId: user.id, via: held.via }, () =>
88104 Promise.resolve(tool.run(asPerson, user, held.args)),
89105 );
90106 const undo = ran.ok ? undoOf(held.tool, held.args) : undefined;
107 const receipt = ran.ok ? receiptOf(held.tool, held.args, ran.value, before) : undefined;
91108 const turn = {
92109 confirm: held.id,
93110 tool: held.tool,
94111 done: ran.ok,
95112 ...(ran.ok ? { result: kept(keptOf(held.tool, ran.value)) } : { error: ran.error, message: ran.message }),
96113 ...(undo === undefined ? {} : { undo }),
114 ...(receipt === undefined ? {} : { receipt }),
97115 };
98116 const conversation = conversationOfVia(ctx.app.db, user.id, held.via);
99117 appendTurn(ctx.app.db, user.id, conversation.id, { role: "tool", text: JSON.stringify(turn) });
@@ -114,3 +132,97 @@ export function sayNo(ctx: Pick<Ctx, "app">, user: User, confirmId: string): { o
114132 appendTurn(ctx.app.db, user.id, conversation.id, { role: "tool", text: JSON.stringify(turn) });
115133 return { ok: true, turn };
116134 }
135
136 /** The Undo taps being run, per forge: a second tap while one runs is refused. */
137 const claims = new WeakMap<object, Set<string>>();
138
139 /** Why an undo did nothing, with the status the page answers. */
140 export const UNDO_REFUSED = {
141 not_found: [404, "no such receipt of yours"],
142 no_undo: [409, "this receipt has no undo"],
143 undone: [409, "this was already undone"],
144 moved_on: [409, "it has changed since: undoing now would undo someone else's change, so nothing was done"],
145 } as const;
146
147 export type Undone =
148 | { ok: false; error: keyof typeof UNDO_REFUSED | "failed"; message: string }
149 | { ok: true; turn: Record<string, unknown> };
150
151 /**
152 * The person's tap on a receipt's Undo: the stored inverse, run as them once,
153 * and only while the object is still as the receipt left it. It writes its own
154 * receipt turn, which names the turn it undid.
155 */
156 export async function undoReceipt(ctx: Ctx, user: User, turnId: string): Promise<Undone> {
157 const refuse = (error: keyof typeof UNDO_REFUSED): Undone => ({ ok: false, error, message: UNDO_REFUSED[error][1] });
158 const turn = CONFIRM_ID.test(turnId) ? getTurn(ctx.app.db, user.id, turnId) : undefined;
159 if (turn === undefined || turn.role !== "tool" || turn.replaced) return refuse("not_found");
160 let data: Record<string, unknown> | undefined;
161 try {
162 data = JSON.parse(turn.text) as Record<string, unknown>;
163 } catch {
164 return refuse("not_found");
165 }
166 const receipt = readReceipt(data?.["receipt"]);
167 if (receipt === undefined) return refuse("not_found");
168 const undo = receipt.undo;
169 if (undo === undefined || !INVERSES.has(undo.tool)) return refuse("no_undo");
170 const { TOOLS } = await loadMcp();
171 const tool = TOOLS.find((t) => t.name === undo.tool);
172 if (tool === undefined) return refuse("no_undo");
173 // From here to the inverse's start nothing awaits: a second tap of the same
174 // Undo meets the claim (or, once written, the undone turn) and does nothing.
175 const claimed = claims.get(ctx.app) ?? new Set<string>();
176 claims.set(ctx.app, claimed);
177 if (claimed.has(turn.id) || undoneBy(ctx.app.db, user.id, turn.conversationId, turn.id)) return refuse("undone");
178 const now = seen(ctx, undo.args);
179 if (now === undefined || !stillSo(now, undo.expect)) return refuse("moved_on");
180 claimed.add(turn.id);
181 const asPerson: Ctx = { ...ctx, auth: { ...ctx.auth, user, scope: user.isAdmin ? "admin" : "rw" } };
182 const via = `conversation:${turn.conversationId}`;
183 const ran = await actingVia({ userId: user.id, via }, () => Promise.resolve(tool.run(asPerson, user, undo.args))).finally(() =>
184 claimed.delete(turn.id),
185 );
186 const own = ran.ok ? receiptOf(undo.tool, undo.args, ran.value, now) : undefined;
187 const written = {
188 undid: turn.id,
189 tool: undo.tool,
190 done: ran.ok,
191 ...(ran.ok ? {} : { error: ran.error, message: ran.message }),
192 ...(own === undefined ? {} : { receipt: { verb: `Undone: ${own.verb.toLowerCase()}`, object: own.object, href: own.href } }),
193 };
194 const conversation = getConversation(ctx.app.db, user.id, turn.conversationId) ?? conversationOfVia(ctx.app.db, user.id, via);
195 appendTurn(ctx.app.db, user.id, conversation.id, { role: "tool", text: JSON.stringify(written) });
196 return ran.ok ? { ok: true, turn: written } : { ok: false, error: "failed", message: String(ran.message) };
197 }
198
199 /** A receipt of the person's with an Undo still to tap. */
200 export interface Undoable {
201 readonly id: string;
202 readonly verb: string;
203 readonly object: string;
204 readonly label: string;
205 }
206
207 /** The person's recent receipts whose Undo has not been done: the terminal's list, the page's
208 * buttons. */
209 export function undoableReceipts(db: Database, userId: string): Undoable[] {
210 const out: Undoable[] = [];
211 for (const c of listConversations(db, userId).slice(0, 5)) {
212 const turns = listTurns(db, userId, c.id, { limit: 100 });
213 if (!turns.ok) continue;
214 for (const t of turns.value) {
215 if (t.role !== "tool" || t.replaced) continue;
216 let data: Record<string, unknown> | null = null;
217 try {
218 data = JSON.parse(t.text) as Record<string, unknown> | null;
219 } catch {
220 continue;
221 }
222 const receipt = data?.["done"] === true ? readReceipt(data["receipt"]) : undefined;
223 if (receipt?.undo === undefined || !INVERSES.has(receipt.undo.tool) || undoneBy(db, userId, c.id, t.id)) continue;
224 out.push({ id: t.id, verb: receipt.verb, object: receipt.object, label: receipt.undo.label });
225 }
226 }
227 return out;
228 }
src/core/conversations.ts +24
@@ -177,6 +177,30 @@ const owned = (db: Database, userId: string, conversationId: string): boolean =>
177177 .query("SELECT 1 FROM conversation WHERE id = ?1 AND user_id = ?2")
178178 .get(conversationId, userId) !== null;
179179
180 /** One of the person's turns by id, in a conversation of theirs. */
181 export function getTurn(db: Database, userId: string, turnId: string): Turn | undefined {
182 const row = db
183 .query(
184 "SELECT t.* FROM conversation_turn t JOIN conversation c ON c.id = t.conversation_id WHERE t.id = ?1 AND c.user_id = ?2",
185 )
186 .get(turnId, userId) as TurnRow | null;
187 return row === null ? undefined : turnOf(row);
188 }
189
190 /** Whether a tool turn of this conversation says it undid turn `turnId` and did: a failed try
191 * leaves it open. */
192 export function undoneBy(db: Database, userId: string, conversationId: string, turnId: string): boolean {
193 if (!owned(db, userId, conversationId) || !/^[0-9a-z]{1,40}$/.test(turnId)) return false;
194 return (
195 db
196 .query(
197 `SELECT 1 FROM conversation_turn WHERE conversation_id = ?1 AND role = 'tool'
198 AND CASE WHEN json_valid(text) THEN json_extract(text, '$.undid') = ?2 AND json_extract(text, '$.done') = 1 END LIMIT 1`,
199 )
200 .get(conversationId, turnId) !== null
201 );
202 }
203
180204 /** Add a turn at the end. Text is 1 to `MAX_TURN_CHARS` characters. */
181205 export function appendTurn(
182206 db: Database,
src/crew/receipt.ts added +128
@@ -0,0 +1,128 @@
1 /**
2 * What a confirmed action leaves in the thread (#12680): a receipt, not
3 * prose — the verb, the object, the page it changed, and, where an inverse
4 * exists, the one call that performs it. Only `close` (close/reopen) and
5 * `assign` (assign/unassign) have one; every other call that names a
6 * repository still leaves a receipt, with no button.
7 *
8 * Plain data in, plain data out: `actions/conversation_confirms.ts` takes
9 * the look before and after, and runs the undo.
10 */
11
12 type Args = Record<string, unknown>;
13
14 /** An issue or pull as a receipt needs to know it. */
15 export interface Seen {
16 readonly kind: "issue" | "pull";
17 readonly state: "open" | "closed";
18 readonly assignee: string | null;
19 }
20
21 export interface Receipt {
22 readonly verb: string;
23 /** `owner/name#N`. */
24 readonly object: string;
25 readonly href: string;
26 readonly undo?: {
27 /** The label on the button. */
28 readonly label: string;
29 readonly tool: "close" | "assign";
30 readonly args: Args;
31 /** What the object must still look like for the undo to be ours to do. */
32 readonly expect: Partial<Seen>;
33 };
34 }
35
36 /** The tools an undo may run: a stored receipt naming any other is ignored. */
37 export const INVERSES: ReadonlySet<string> = new Set(["close", "assign"]);
38
39 /** The repository and number a call names, when it names an issue or pull. */
40 export function targetOf(args: Args): { repo: string; number: number } | undefined {
41 const { repo, number } = args;
42 return typeof repo === "string" && /^[^/\s]+\/[^/\s]+$/.test(repo) && typeof number === "number" && Number.isInteger(number) && number > 0
43 ? { repo, number }
44 : undefined;
45 }
46
47 /** The repository a call names, whether or not it names a number. */
48 const repoOf = (args: Args): string | undefined => {
49 const { repo } = args;
50 return typeof repo === "string" && /^[^/\s]+\/[^/\s]+$/.test(repo) ? repo : undefined;
51 };
52
53 /** `list_issues` as a verb: "List issues". */
54 const verbOf = (tool: string): string => {
55 const words = tool.replace(/[^A-Za-z0-9]+/g, " ").trim();
56 return words === "" ? "Done" : words[0]!.toUpperCase() + words.slice(1).toLowerCase();
57 };
58
59 /**
60 * The receipt of a done `tool` call, from the object before and the tool's answer.
61 * `close` and `assign` carry an Undo; any other call that names a repository (and
62 * a number) gets a receipt with no Undo; one that names neither has none.
63 */
64 export function receiptOf(tool: string, args: Args, value: unknown, before: Seen | undefined): Receipt | undefined {
65 const target = targetOf(args);
66 if (!INVERSES.has(tool) || target === undefined || before === undefined || typeof value !== "object" || value === null) {
67 const repo = repoOf(args);
68 if (repo === undefined) return undefined;
69 const number = target?.number;
70 const page = number === undefined ? `/${repo}` : `/${repo}/${before?.kind === "pull" ? "pulls" : "issues"}/${number}`;
71 return { verb: verbOf(tool), object: number === undefined ? repo : `${repo}#${number}`, href: page };
72 }
73 const answer = value as Record<string, unknown>;
74 const object = `${target.repo}#${target.number}`;
75 const href = `/${target.repo}/${before.kind === "pull" ? "pulls" : "issues"}/${target.number}`;
76 if (tool === "close") {
77 const state = answer["state"];
78 if (state !== "open" && state !== "closed") return undefined;
79 const back = state === "closed" ? "open" : "closed";
80 return {
81 verb: state === "closed" ? "Closed" : "Reopened",
82 object,
83 href,
84 ...(before.state === state
85 ? {}
86 : {
87 undo: {
88 label: state === "closed" ? "Undo: reopen" : "Undo: close",
89 tool: "close" as const,
90 args: { repo: target.repo, number: target.number, state: back },
91 expect: { state },
92 },
93 }),
94 };
95 }
96 if (tool === "assign") {
97 const assignee = answer["assignee"];
98 if (assignee !== null && typeof assignee !== "string") return undefined;
99 return {
100 verb: assignee === null ? "Unassigned" : `Assigned to ${assignee}`,
101 object,
102 href,
103 ...(before.assignee === assignee
104 ? {}
105 : {
106 undo: {
107 label: before.assignee === null ? "Undo: unassign" : `Undo: assign back to ${before.assignee}`,
108 tool: "assign" as const,
109 args: { repo: target.repo, number: target.number, kind: before.kind, assignee: before.assignee },
110 expect: { assignee },
111 },
112 }),
113 };
114 }
115 return undefined;
116 }
117
118 /** Whether the object is still as the receipt left it: nobody changed it since. */
119 export const stillSo = (now: Seen, expect: Partial<Seen>): boolean =>
120 Object.entries(expect).every(([k, v]) => now[k as keyof Seen] === v);
121
122 /** Reads a stored receipt back: the turn is data, so its shape is checked, never trusted. */
123 export function readReceipt(value: unknown): Receipt | undefined {
124 if (typeof value !== "object" || value === null) return undefined;
125 const r = value as Record<string, unknown>;
126 if (typeof r["verb"] !== "string" || typeof r["object"] !== "string" || typeof r["href"] !== "string") return undefined;
127 return value as Receipt;
128 }
src/http/server.ts +2 −1
@@ -167,7 +167,7 @@ import {
167167 themeSubmit,
168168 } from "../web/pages/site.ts";
169169 import { talkBuild, talkPublish, talkRestore } from "../web/talk_build.ts";
170 import { talkAgainSend, talkArchive, talkConfirm, talkNew, talkQueueCancel, talkRename, talkSend, talkStream, talkView } from "../web/pages/talk.ts";
170 import { talkAgainSend, talkArchive, talkConfirm, talkNew, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView } from "../web/pages/talk.ts";
171171 import {
172172 recoverFinish,
173173 recoverOptions,
@@ -1139,6 +1139,7 @@ export function buildRouter(): Router<Handler> {
11391139 router.add("POST", "/talk/again/:how", talkAgainSend);
11401140 router.add("POST", "/talk/queue/:id/cancel", talkQueueCancel);
11411141 router.add("POST", "/talk/confirm/:id", talkConfirm);
1142 router.add("POST", "/talk/undo/:turn", talkUndo);
11421143 router.add("POST", "/talk/new", talkNew);
11431144 router.add("POST", "/talk/build", talkBuild);
11441145 router.add("GET", "/talk/:id", talkView);
src/tui/forge.ts +10
@@ -72,6 +72,7 @@ import { talkChatsScreen } from "./screens/talk_chats.ts";
7272 import { sshKeysScreen } from "./screens/sshkeys.ts";
7373 import { passkeysScreen } from "./screens/passkeys.ts";
7474 import { confirmsScreen } from "./screens/confirms.ts";
75 import { receiptsScreen } from "./screens/receipts.ts";
7576 import { mayTrust, trustedScreen } from "./screens/trusted.ts";
7677 import { proposalTokensPrompt } from "./screens/proposal_tokens.ts";
7778 import { signInsScreen } from "./screens/signins.ts";
@@ -426,6 +427,15 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
426427 hint: "what the forge's agent asked to do; y does it once",
427428 run: () => ctx.push(confirmsScreen(session, ctx)),
428429 });
430 // What a confirmed action left that can still be undone (#12680): the page's Undo, from the
431 // terminal.
432 if (session.signedIn && session.user?.kind !== "agent")
433 commands.push({
434 id: "receipts",
435 title: "Receipts",
436 hint: "what you confirmed in /talk; u undoes it once",
437 run: () => ctx.push(receiptsScreen(session, ctx)),
438 });
429439 // Who folds in without a person's review, and the kill switch (#8937): a forge admin's.
430440 if (session.signedIn && mayTrust(session))
431441 commands.push({
src/tui/screens/receipts.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * Receipts in the terminal (#12680): what a confirmed action in /talk left
3 * that can still be undone, one line each. `u` undoes the one under the
4 * cursor after a dialog that repeats it, through the same action the page's
5 * Undo form calls (`undoReceipt`): your own receipt only, once, and only while
6 * the object is as the receipt left it.
7 */
8
9 import { undoableReceipts, undoReceipt, UNDO_REFUSED } from "../../actions/conversation_confirms.ts";
10 import type { Ctx, Screen } from "../app/app.ts";
11 import { binding } from "../app/keys.ts";
12 import { style } from "../term/style.ts";
13 import { truncate } from "../term/width.ts";
14 import type { Session } from "../session.ts";
15 import { fill, len, split } from "../ui/layout.ts";
16 import { ListState, confirmScreen, drawList, runAsync, type ListRow } from "./common.ts";
17
18 export function receiptsScreen(f: Session, ctx: Ctx): Screen {
19 const state = new ListState();
20 let note = "";
21 const items = () => (f.user === undefined ? [] : undoableReceipts(f.app.db, f.user.id));
22 const rows = (): ListRow[] => items().map((r) => ({ title: `${r.verb} ${r.object}`, secondary: r.label, meta: "" }));
23
24 const screen: Screen = {
25 title: "Receipts",
26 keys: [binding(["j", "k"], "move cursor"), binding(["u"], "undo")],
27 render(area, s) {
28 const c = ctx.theme.c;
29 const [head, body] = split(area, "v", [len(1), fill(1)]);
30 const text =
31 note !== "" ? note : items().length === 0 ? "Nothing to undo." : "What you confirmed in /talk; u undoes it once.";
32 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
33 drawList(s, body!, c, state, rows());
34 },
35 key(e) {
36 if (state.key(e, items().length)) return true;
37 if (e.ctrl || e.alt || e.key !== "u") return false;
38 const r = items()[state.index];
39 const user = f.user;
40 if (r === undefined || user === undefined) return false;
41 ctx.push(
42 confirmScreen(ctx, screen, {
43 title: "Undo this",
44 body: [`${r.verb} ${r.object}`, r.label],
45 actions: [{ label: "Keep", variant: "ghost" }, { label: "Undo it", variant: "default" }],
46 onChoose: (i) => {
47 if (i !== 1) return;
48 runAsync(ctx, async () => {
49 const url = new URL(f.app.config.url ?? `http://${f.app.config.host ?? "localhost"}`);
50 const done = await undoReceipt(
51 {
52 app: f.app,
53 request: new Request(url.href, { method: "POST" }),
54 url,
55 params: {},
56 auth: { user, scope: undefined, via: "none" as const },
57 theme: undefined,
58 },
59 user,
60 r.id,
61 );
62 note = done.ok ? "Undone." : `Nothing was undone: ${done.error === "failed" ? done.message : UNDO_REFUSED[done.error][1]}`;
63 ctx.invalidate();
64 });
65 },
66 }),
67 );
68 return true;
69 },
70 };
71 return screen;
72 }
src/web/pages/talk.ts +47 −4
@@ -16,7 +16,7 @@
1616
1717 import type { Database } from "bun:sqlite";
1818 import { cancelTalk, queuedTalk, TALK_WORDS, talk, talkAgain } from "../../actions/talk.ts";
19 import { REFUSED, sayNo, sayYes, waitingConfirms } from "../../actions/conversation_confirms.ts";
19 import { REFUSED, sayNo, sayYes, UNDO_REFUSED, undoReceipt, waitingConfirms } from "../../actions/conversation_confirms.ts";
2020 import { filesOfTurns, type ConversationFile } from "../../core/conversation_files.ts";
2121 import {
2222 archiveConversation,
@@ -43,6 +43,7 @@ import { WORDS_MAX } from "../../core/fence.ts";
4343 import { thinkingOf, worksOf, type Work } from "../../core/talk_work.ts";
4444 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
4545 import { ASKING } from "../../crew/conversation_confirm.ts";
46 import { INVERSES, readReceipt, type Receipt } from "../../crew/receipt.ts";
4647 import { pastTime } from "../../core/fence.ts";
4748 import { turnRunning, type RedoHow } from "../../crew/conversation.ts";
4849 import type { Ctx } from "../../http/context.ts";
@@ -110,6 +111,27 @@ function confirmButtons(id: string, tool: string): Html {
110111 </div>`;
111112 }
112113
114 /** The turns a page holds that say they undid another: those receipts have no Undo left. */
115 const undoneIn = (turns: readonly Turn[]): Set<string> =>
116 new Set(
117 turns.flatMap((t) => {
118 const data = t.role === "tool" ? parse(t.text) : undefined;
119 return data?.["done"] === true ? [String(data["undid"] ?? "")] : [];
120 }).filter((id) => id !== ""),
121 );
122
123 /** A receipt as a line: what changed, its page, and the one tap to undo it when it can be. */
124 function receiptCard(id: string, turnId: string, receipt: Receipt, at: string, set: string, undone: boolean): Html {
125 return html`<li class="talk-turn talk-tool${set}" id="${id}">
126 <p><strong>${receipt.verb}</strong> <a href="${receipt.href}">${receipt.object}</a> <span class="talk-when">${time(at)}</span></p>
127 ${receipt.undo === undefined || !INVERSES.has(receipt.undo.tool)
128 ? null
129 : undone
130 ? html`<p class="muted small">Undone.</p>`
131 : html`<form method="post" action="${HERE}/undo/${turnId}" class="bar">${btn(receipt.undo.label, { icon: "history", label: receipt.undo.label })}</form>`}
132 </li>`;
133 }
134
113135 /** What Ask again says for the person: no sentence of the agent's, so it asks and never itself names the write. */
114136 export const ASK_AGAIN = "That ran out before I answered. Ask me again.";
115137
@@ -177,7 +199,7 @@ const contextLine = (c: Context | undefined): Html =>
177199 const costLine = (usd: number): Html => html`<p class="talk-cost small muted">${dollars(usd)} this turn</p>`;
178200
179201 /** One turn as the page and the stream both draw it; `waiting` is the confirms still open. */
180 export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: number, act?: Html, work?: Work, files: readonly ConversationFile[] = [], expired: ReadonlySet<string> = new Set()): Html {
202 export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: number, act?: Html, work?: Work, files: readonly ConversationFile[] = [], expired: ReadonlySet<string> = new Set(), undone: ReadonlySet<string> = new Set()): Html {
181203 const id = `t-${turn.id}`;
182204 const set = turn.replaced ? " talk-replaced" : "";
183205 const acts = act === undefined ? null : html`<div class="talk-acts">${act}</div>`;
@@ -219,6 +241,11 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: number
219241 if (thought !== undefined)
220242 return html`<li class="talk-turn talk-tool talk-thinking${set}" id="${id}"><details><summary>Thinking <span class="talk-when">${time(turn.createdAt)}</span></summary><p>${thought}</p></details></li>`;
221243 // A tool turn: the confirm's outcome as JSON, or the call the agent made as text.
244 const receipt = data?.["done"] === true ? readReceipt(data["receipt"]) : undefined;
245 if (data !== undefined && receipt !== undefined && ("confirm" in data || "undid" in data))
246 return receiptCard(id, turn.id, receipt, turn.createdAt, set, undone.has(turn.id));
247 if (data !== undefined && "undid" in data)
248 return toolCard(id, data["done"] === true ? `Undone: ${String(data["tool"])}.` : `Undo did not go through: ${String(data["message"] ?? data["error"] ?? "")}`, String(data["tool"] ?? "undo"), turn.createdAt, set);
222249 if (data !== undefined && "confirm" in data) {
223250 const tool = String(data["tool"] ?? "");
224251 const says = data["cancelled"] === true ? `Cancelled: ${tool}.` : data["done"] === true ? `Done: ${tool}.${typeof data["undo"] === "string" ? ` To undo: ${data["undo"]}.` : ""}` : `${tool} did not go through: ${String(data["message"] ?? data["error"] ?? "")}`;
@@ -305,6 +332,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
305332 const turns = listed.ok ? listed.value : [];
306333 const waiting = new Set(waitingConfirms(ctx, user).map((w) => w.id));
307334 const expired = ranOutOf(ctx, user.id, turns);
335 const undone = undoneIn(turns);
308336 const sent = filesOfTurns(ctx.app.db, user.id, turns.filter((t) => t.role === "person").map((t) => t.id));
309337 const running = clock.running(ctx.app, user.id, conversation.id);
310338 const costs = turnCosts(ctx.app.db, conversation.id);
@@ -339,7 +367,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
339367 ${turns.length === 0
340368 ? html`<li class="muted talk-turn">Ask the forge anything, or tell it what to change. It acts as you, with your permissions, and asks before anything hard to undo.
341369 <span class="talk-suggest">${SUGGESTIONS.map((q) => html`<a class="btn" href="${here}?q=${encodeURIComponent(q)}" data-suggest="${q}">${q}</a>`)}</span></li>`
342 : turns.map((t) => turnHtml(t, waiting, costs.get(t.id), acts.get(t.id), works.get(t.id), sent.get(t.id), expired))}
370 : turns.map((t) => turnHtml(t, waiting, costs.get(t.id), acts.get(t.id), works.get(t.id), sent.get(t.id), expired, undone))}
343371 ${!paged && running ? queuedTalk(ctx.app, user, conversation.id).map(queuedHtml) : null}
344372 </ol>
345373 <div id="end"></div>
@@ -510,6 +538,20 @@ export async function talkConfirm(ctx: Ctx): Promise<Response> {
510538 return flashTo(ctx, `${HERE}#end`, refused === undefined ? { tone: "success", message: answer === "yes" ? "Confirmed." : "Cancelled." } : { tone: "danger", message: `Nothing was done: ${refused}` });
511539 }
512540
541 // POST /talk/undo/:turn — the person's tap on a receipt's Undo, from their own session.
542 export async function talkUndo(ctx: Ctx): Promise<Response> {
543 const user = ctx.auth.user;
544 if (user === undefined) return signInFirst(ctx);
545 if (ctx.auth.via !== "session") return forbiddenPage(ctx, "Undo this from your own signed-in browser.");
546 const form = await readForm(ctx);
547 if (form instanceof Response) return form;
548 const done = await undoReceipt(ctx, user, ctx.params["turn"] ?? "");
549 const status = done.ok ? 200 : done.error === "failed" ? 422 : UNDO_REFUSED[done.error][0];
550 if ((ctx.request.headers.get("accept") ?? "").includes("application/json"))
551 return json(done.ok ? { ok: true } : { ok: false, message: done.message }, status);
552 return flashTo(ctx, `${HERE}#end`, done.ok ? { tone: "success", message: "Undone." } : { tone: "danger", message: `Nothing was undone: ${done.message}` });
553 }
554
513555 // GET /talk/stream?after=<turn id> — turns as they are written, ended with the turn.
514556 export function talkStream(ctx: Ctx): Response {
515557 const user = ctx.auth.user;
@@ -534,10 +576,11 @@ export function talkStream(ctx: Ctx): Response {
534576 if (fresh.length > 0) {
535577 const waiting = new Set(waitingConfirms(ctx, user).map((w) => w.id));
536578 const expired = ranOutOf(ctx, user.id, fresh);
579 const undone = undoneIn(fresh);
537580 const works = worksOf(app.db, user.id, conversation.id, fresh);
538581 const sent = filesOfTurns(app.db, user.id, fresh.filter((t) => t.role === "person").map((t) => t.id));
539582 for (const turn of fresh) {
540 emit("turn", { id: turn.id, role: turn.role, html: turnHtml(turn, waiting, undefined, undefined, works.get(turn.id), sent.get(turn.id), expired).text }, turn.id);
583 emit("turn", { id: turn.id, role: turn.role, html: turnHtml(turn, waiting, undefined, undefined, works.get(turn.id), sent.get(turn.id), expired, undone).text }, turn.id);
541584 cursor = turn.id;
542585 }
543586 }
test/palette-roster.test.ts +2
@@ -95,6 +95,7 @@ test("a site-admin person is offered the whole roster", () => {
9595 ["shells", "Your shells", "the machine shells you hold, live then ended"],
9696 ["notify", "Phone notifications", "where the crew reaches your phone; s sets, x turns off"],
9797 ["confirms", "Confirms", "what the forge's agent asked to do; y does it once"],
98 ["receipts", "Receipts", "what you confirmed in /talk; u undoes it once"],
9899 ["trusted", "Trusted sources", "who folds in without review; a trusts, x removes, s stops all, v reverts"],
99100 ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"],
100101 ["build-app", "Build an app", "say what to build; versions, diff, restore and publish. n starts one"],
@@ -357,6 +358,7 @@ test("a member person is offered the signed-in roster without the admin entries"
357358 ["shells", "Your shells", "the machine shells you hold, live then ended"],
358359 ["notify", "Phone notifications", "where the crew reaches your phone; s sets, x turns off"],
359360 ["confirms", "Confirms", "what the forge's agent asked to do; y does it once"],
361 ["receipts", "Receipts", "what you confirmed in /talk; u undoes it once"],
360362 ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"],
361363 ["build-app", "Build an app", "say what to build; versions, diff, restore and publish. n starts one"],
362364 ["ssh-keys", "Computer keys", "list, add and remove the keys that sign in as you"],
test/talk-page.test.ts +1 −1
@@ -704,7 +704,7 @@ describe("confirm and cancel", () => {
704704 expect(yes.status).toBe(200);
705705 expect(getRepoById(app.db, h.repoId)!.archivedAt).not.toBeNull();
706706 expect((await post(`/talk/confirm/${h.id}`, alice, { answer: "yes" }, { accept: "application/json" })).status).toBe(409);
707 expect(await (await get("/talk", alice)).text()).toContain("Done: archive.");
707 expect(await (await get("/talk", alice)).text()).toContain("<strong>Archive</strong>");
708708 });
709709
710710 test("nobody else's yes or no counts, nor a cross-origin one, nor a bad answer", async () => {
test/talk-receipt.test.ts added +147
@@ -0,0 +1,147 @@
1 /**
2 * A confirmed action leaves a receipt in /talk (#12680): verb, object, link,
3 * and an Undo form only where an inverse exists.
4 */
5
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { appendTurn, openConversation, undoneBy } from "../src/core/conversations.ts";
14 import { hold } from "../src/core/fence.ts";
15 import { createIssue, getIssue } from "../src/core/issues.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { promote } from "./helpers/members.ts";
19
20 let dataDir: string;
21 let app: App;
22 let servers: Servers;
23 let alice: User;
24 let repoId: string;
25 let name: string;
26
27 const cookie = (u: User): string => `forge_session=${createSession(app.db, u.id).token}`;
28 const get = (path: string) => fetch(`${servers.url}${path}`, { headers: { cookie: cookie(alice) } });
29 const post = (path: string, form: Record<string, string>) =>
30 fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { origin: servers.url, cookie: cookie(alice), accept: "application/json" }, body: new URLSearchParams(form) });
31 const holdCall = (tool: string, args: Record<string, unknown>): string => {
32 const id = hold(app.db, `conversation:${openConversation(app.db, alice.id).id}`, alice.id, tool, args);
33 if (id === null) throw new Error("hold");
34 return id;
35 };
36 const makeIssue = (title: string): number => {
37 const i = createIssue(app.db, { repoId, authorId: alice.id, title, body: "b" });
38 if (!i.ok) throw new Error(i.error);
39 return i.value.number;
40 };
41 const undoAction = (page: string): string | undefined => /action="(\/talk\/undo\/[0-9a-z]+)"/.exec(page)?.[1];
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-talk-receipt-"));
45 app = createApp({ dataDir, port: 0 });
46 servers = await serve(app);
47 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
48 if (!u.ok) throw new Error(u.error);
49 promote(app.db, u.value);
50 alice = u.value;
51 name = "rcpt";
52 const made = await createRepo(app, alice, { name, visibility: "public" });
53 if (!made.ok) throw new Error(String(made.error));
54 repoId = made.value.id;
55 }, 30_000);
56
57 afterAll(async () => {
58 await servers.stop();
59 app.close();
60 await rm(dataDir, { recursive: true, force: true });
61 });
62
63 describe("a confirmed close", () => {
64 test("leaves a receipt with its link and an Undo that reopens, receipted in turn, once", async () => {
65 const n = makeIssue("close me");
66 const id = holdCall("close", { repo: `alice/${name}`, number: n });
67 expect((await post(`/talk/confirm/${id}`, { answer: "yes" })).status).toBe(200);
68 expect(getIssue(app.db, repoId, n)?.state).toBe("closed");
69 const page = await (await get("/talk")).text();
70 expect(page).toContain("Closed");
71 expect(page).toContain(`href="/alice/${name}/issues/${n}"`);
72 const action = undoAction(page);
73 expect(action).toBeDefined();
74 const undo = await post(action!, {});
75 expect(undo.status).toBe(200);
76 expect(getIssue(app.db, repoId, n)?.state).toBe("open");
77 const after = await (await get("/talk")).text();
78 expect(after).toContain("Undone: reopened");
79 expect(after).toContain("Undone.");
80 // The first receipt's Undo is gone and refused if posted again.
81 expect((await post(action!, {})).status).toBe(409);
82 });
83
84 test("refuses to undo when the object moved on, and says so", async () => {
85 const n = makeIssue("moved on");
86 const id = holdCall("close", { repo: `alice/${name}`, number: n });
87 await post(`/talk/confirm/${id}`, { answer: "yes" });
88 const action = [...(await (await get("/talk")).text()).matchAll(/action="(\/talk\/undo\/[0-9a-z]+)"/g)].at(-1)![1]!;
89 // Someone reopens it by hand: undoing now would not be ours to do.
90 app.db.query("UPDATE issue SET state = 'open' WHERE repo_id = ?1 AND number = ?2").run(repoId, n);
91 const res = await post(action, {});
92 expect(res.status).toBe(409);
93 expect(((await res.json()) as { message: string }).message).toContain("changed since");
94 expect(getIssue(app.db, repoId, n)?.state).toBe("open");
95 });
96 });
97
98 describe("a confirmed assign", () => {
99 test("Undo puts the assignee back", async () => {
100 const n = makeIssue("assign me");
101 const id = holdCall("assign", { repo: `alice/${name}`, number: n, kind: "issue", assignee: "alice" });
102 expect((await post(`/talk/confirm/${id}`, { answer: "yes" })).status).toBe(200);
103 expect(getIssue(app.db, repoId, n)?.assigneeName).toBe("alice");
104 const page = await (await get("/talk")).text();
105 expect(page).toContain("Assigned to alice");
106 const action = [...page.matchAll(/action="(\/talk\/undo\/[0-9a-z]+)"/g)].at(-1)![1]!;
107 expect((await post(action, {})).status).toBe(200);
108 expect(getIssue(app.db, repoId, n)?.assigneeName).toBeNull();
109 });
110 });
111
112 describe("an action with no inverse", () => {
113 test("shows no Undo, and a forged one is refused", async () => {
114 const other = await createRepo(app, alice, { name: "plain", visibility: "public" });
115 if (!other.ok) throw new Error(String(other.error));
116 const id = holdCall("archive", { repo: "alice/plain", archived: true, dryRun: false });
117 const before = (await (await get("/talk")).text()).match(/\/talk\/undo\//g)?.length ?? 0;
118 expect((await post(`/talk/confirm/${id}`, { answer: "yes" })).status).toBe(200);
119 const page = await (await get("/talk")).text();
120 expect(page).toContain("Archive");
121 expect(page).toContain('href="/alice/plain"');
122 expect(page.match(/\/talk\/undo\//g)?.length ?? 0).toBe(before);
123 const forged = await post("/talk/undo/nosuchturn", {});
124 expect(forged.status).toBe(404);
125 });
126 });
127
128 describe("an undo", () => {
129 test("a failed try is not an undone: only a turn that says done counts", () => {
130 const c = openConversation(app.db, alice.id);
131 appendTurn(app.db, alice.id, c.id, { role: "tool", text: JSON.stringify({ undid: "abc", done: false }) });
132 expect(undoneBy(app.db, alice.id, c.id, "abc")).toBe(false);
133 appendTurn(app.db, alice.id, c.id, { role: "tool", text: "not json" });
134 appendTurn(app.db, alice.id, c.id, { role: "tool", text: JSON.stringify({ undid: "abc", done: true }) });
135 expect(undoneBy(app.db, alice.id, c.id, "abc")).toBe(true);
136 });
137
138 test("two taps at once run the inverse once", async () => {
139 const n = makeIssue("double tap");
140 const id = holdCall("close", { repo: `alice/${name}`, number: n });
141 await post(`/talk/confirm/${id}`, { answer: "yes" });
142 const action = [...(await (await get("/talk")).text()).matchAll(/action="(\/talk\/undo\/[0-9a-z]+)"/g)].at(-1)![1]!;
143 const both = await Promise.all([post(action, {}), post(action, {})]);
144 expect(both.map((r) => r.status).sort()).toEqual([200, 409]);
145 expect(getIssue(app.db, repoId, n)?.state).toBe("open");
146 });
147 });
test/tui-talk-receipts.test.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * The terminal's Receipts screen (#12680): the page's Undo, from the terminal,
3 * through the same `undoReceipt`: only your own receipts, once.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { sayYes } from "../src/actions/conversation_confirms.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { openConversation } from "../src/core/conversations.ts";
13 import { hold } from "../src/core/fence.ts";
14 import { createIssue, getIssue } from "../src/core/issues.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { createForgeApp } from "../src/tui/forge.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { settleApp } from "./helpers/tui.ts";
19 import { proveAll } from "./helpers/verified.ts";
20
21 let dir: string;
22 let app: App;
23 let alice: User;
24 let bob: User;
25 let repoId: string;
26 let number: number;
27 const open = [":", "Receipts", "\r"];
28
29 async function drive(user: User, keys: string[]): Promise<string> {
30 const terminal = headlessTerminal(120, 30);
31 const { app: tui } = createForgeApp(
32 app,
33 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
34 { terminal, exitHooks: false },
35 );
36 tui.start();
37 await settleApp(tui);
38 for (const k of keys) {
39 terminal.feed(k);
40 await settleApp(tui);
41 }
42 const text = tui.screen.toText();
43 tui.stop?.();
44 return text;
45 }
46
47 beforeAll(async () => {
48 dir = await mkdtemp(join(tmpdir(), "forge-tui-receipts-"));
49 app = createApp({ dataDir: dir, port: 0 });
50 const mk = async (username: string, first = false) => {
51 const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
52 if (!r.ok) throw new Error(r.error);
53 return r.value;
54 };
55 alice = await mk("alice", true);
56 bob = await mk("bob");
57 proveAll(app);
58 const made = await createRepo(app, alice, { name: "rt", visibility: "public" });
59 if (!made.ok) throw new Error(String(made.error));
60 repoId = made.value.id;
61 const i = createIssue(app.db, { repoId, authorId: alice.id, title: "close me", body: "b" });
62 if (!i.ok) throw new Error(i.error);
63 number = i.value.number;
64 const id = hold(app.db, `conversation:${openConversation(app.db, alice.id).id}`, alice.id, "close", { repo: "alice/rt", number });
65 if (id === null) throw new Error("hold");
66 const url = new URL("http://localhost");
67 const yes = await sayYes({ app, request: new Request(url.href, { method: "POST" }), url, params: {}, auth: { user: alice, scope: undefined, via: "none" as const }, theme: undefined }, alice, id);
68 if (!yes.ok) throw new Error(yes.error);
69 });
70 afterAll(async () => {
71 app.db.close();
72 await rm(dir, { recursive: true, force: true });
73 });
74
75 describe("the terminal's receipts screen", () => {
76 test("another person sees none of it", async () => {
77 const text = await drive(bob, open);
78 expect(text).toContain("Nothing to undo");
79 expect(getIssue(app.db, repoId, number)?.state).toBe("closed");
80 });
81
82 test("u undoes the receipt under the cursor, once", async () => {
83 const text = await drive(alice, open);
84 expect(text).toContain("Closed alice/rt#");
85 expect(text).toContain("Undo: reopen");
86 const after = await drive(alice, [...open, "u", "\t", "\r"]);
87 expect(getIssue(app.db, repoId, number)?.state).toBe("open");
88 expect(after).toContain("Undone");
89 expect(await drive(alice, open)).toContain("Nothing to undo");
90 });
91 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs