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

A talk conversation can be downloaded as one Markdown file #13357

Merged opened this

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

Merged

scout/forge:scout/13307-a-talk-conversation-can-be-downloaded-as → main 7 commits fork

  • Merged. scout/13307-a-talk-conversation-can-be-downloaded-as was merged into main as c0340b5.

Review

Sign in to review this change.
12 files changed +344 −24
docs/MCP.md +1 −1
@@ -202,7 +202,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
202202 | `rollback` | — | Plan, then apply, a rollback to a kept release (admin) | 209 |
203203 | `run_log` | — | A run's log, or its last `tail` lines, as GET /api/v1/repos/:owner/:name/runs/:id/log | 332 |
204204 | `runs` | `agent`, `deploy`, `check` | A repository's runs, newest first: id, kind, state, number, start, end | 525 |
205 | `say` | `list`, `find`, `new`, `rename`, `archive`, `restore`, `build`, `build_state`, `build_diff`, `build_restore`, `build_publish` | Say something on an issue or pull; with no repo, to the forge's agent; manage and find conversations (action) | 589 |
205 | `say` | `list`, `find`, `new`, `rename`, `archive`, `restore`, `download`, `build`, `build_state`, `build_diff`, `build_restore`, `build_publish` | Say something on an issue or pull; with no repo, to the forge agent; manage, find, download chats | 588 |
206206 | `scorecard` | — | Crew scorecard (forge admin): per agent, all time and 30 days | 284 |
207207 | `seal` | `private` | Seal or unseal an issue or pull: a sealed one is seen only by writers and crew | 297 |
208208 | `search` | `all`, `issues`, `repos`, `code` | Find issues, pulls, repositories and code you can read; `kind` and `repo` narrow | 473 |
docs/features/talk.md +6
@@ -132,3 +132,9 @@ An empty `/talk` asks "What do you want to build?" with starters from the marked
132132 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.
133133
134134 **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`.
135
136 ## Download
137
138 `GET /talk/:id/download` (the Download link beside Archive) returns the conversation as one `text/markdown` attachment: a title, then each turn under `## who · when` in the order written, attachments as links. Only its owner gets it; anyone else sees not found. The MCP `say` tool with `action: download` and `conversation` returns the same text as `markdown`. Code: `src/core/conversation_markdown.ts`; test: `test/conversation-download.test.ts`.
139
140 The terminal's Talk screen reads the same file: `d` on the list or in a chat shows the conversation as the Markdown `/talk/:id/download` serves (`conversationMarkdown`), its owner's alone. Each turn's words sit in a fenced block, so no message can forge a turn heading; past a million characters the earliest turns are left out and the file says so. The MCP `say` tool's `download` with no `conversation` takes the latest one.
src/core/conversation_markdown.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * A talk conversation as one Markdown document (#13307): who, when, the text,
3 * and each attachment as a link, turns in the order they were written. The
4 * download route, the MCP `say` tool (`action: download`) and the terminal's talk screen all
5 * return this text; each turn's words sit in a fenced block, and only the conversation's owner is ever served it.
6 */
7 import type { Database } from "bun:sqlite";
8 import { err, ok, type Result } from "../kernel/result.ts";
9 import { filesOfTurns } from "./conversation_files.ts";
10 import { getConversation, listTurns, MAX_PAGE, type Turn, type TurnRole } from "./conversations.ts";
11
12 const WHO: Readonly<Record<TurnRole, string>> = { person: "You", agent: "The forge", tool: "Tool", confirm: "Held action" };
13
14 /** A line of text safe inside a heading or link label: no newlines, no brackets. */
15 const plain = (s: string): string => s.replace(/[\r\n]+/g, " ").replace(/[[\]()<>]/g, "").trim();
16
17 /** The most text a download holds; older turns are left out past it, and the file says so. */
18 export const MAX_TEXT = 1_000_000;
19
20 /**
21 * The newest turns that still count (an edit's replaced ones are left out), oldest first, read a page
22 * at a time until `MAX_TEXT` is reached. `cut` is true when older turns were left unread.
23 */
24 function recentTurns(db: Database, userId: string, conversationId: string): { turns: Turn[]; cut: boolean } {
25 const out: Turn[] = [];
26 let size = 0;
27 let before: string | undefined;
28 for (;;) {
29 const page = listTurns(db, userId, conversationId, { limit: MAX_PAGE, ...(before === undefined ? {} : { before }) });
30 if (!page.ok || page.value.length === 0) return { turns: out, cut: false };
31 for (let i = page.value.length - 1; i >= 0; i--) {
32 const t = page.value[i]!;
33 if (t.replaced) continue;
34 size += t.text.length + 64;
35 if (size > MAX_TEXT && out.length > 0) return { turns: out, cut: true };
36 out.unshift(t);
37 }
38 if (page.value.length < MAX_PAGE) return { turns: out, cut: false };
39 before = page.value[0]!.id;
40 }
41 }
42
43 /**
44 * Turn text inside a fenced block longer than any run of backticks in it, so nothing a person or an
45 * agent wrote can close the block or start a heading of its own.
46 */
47 export function fenced(text: string): string {
48 const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((r) => r.length));
49 const fence = "`".repeat(Math.max(3, longest + 1));
50 return `${fence}text\n${text.trim()}\n${fence}`;
51 }
52
53 /** The Markdown file name for a conversation: its title or day, as safe ASCII. */
54 export const markdownName = (id: string, title: string, createdAt: string): string => {
55 const base = (title === "" ? `chat-${createdAt.slice(0, 10)}` : title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50);
56 return `${base === "" ? "chat" : base}-${id}.md`;
57 };
58
59 /**
60 * The person's conversation as Markdown, or `not_found` when it is not theirs. `origin` prefixes
61 * attachment links.
62 */
63 export function conversationMarkdown(db: Database, userId: string, conversationId: string, origin: string): Result<{ readonly name: string; readonly text: string; readonly truncated: boolean }, "not_found"> {
64 const c = getConversation(db, userId, conversationId);
65 if (c === undefined) return err("not_found");
66 const { turns, cut } = recentTurns(db, userId, c.id);
67 const files = filesOfTurns(db, userId, turns.map((t) => t.id));
68 const lines = [`# ${plain(c.title) === "" ? `Chat of ${c.createdAt.slice(0, 10)}` : plain(c.title)}`, "", `Started ${c.createdAt}`, ""];
69 if (cut) lines.push("> Truncated: this conversation is longer than a download holds, so its earliest turns are left out.", "");
70 for (const t of turns) {
71 lines.push(`## ${WHO[t.role]} · ${t.createdAt}`, "", fenced(t.text), "");
72 for (const f of files.get(t.id) ?? []) lines.push(`- Attachment: [${plain(f.name)}](${origin}/api/v1/conversation/files/${f.id})`);
73 if ((files.get(t.id) ?? []).length > 0) lines.push("");
74 }
75 return ok({ name: markdownName(c.id, c.title, c.createdAt), text: lines.join("\n").replace(/\n+$/, "\n"), truncated: cut });
76 }
src/http/mcp/tools/say.ts +12 −4
@@ -6,6 +6,7 @@ import { getIssue } from "../../../core/issues.ts";
66 import { archiveConversation, createConversation, findConversations, getConversation, listConversations, renameConversation, TOO_MANY_WORDS } from "../../../core/conversations.ts";
77 import { BUILD_WORDS, buildState, publishBuild, restoreVersion, startBuild, versionDiff, type BuildError } from "../../../actions/build.ts";
88 import { BUILD_ID, promptRefusal, templateRefusal, versionRefusal } from "../../../actions/build_input.ts";
9 import { conversationMarkdown } from "../../../core/conversation_markdown.ts";
910 import { talk, TALK_WORDS } from "../../../actions/talk.ts";
1011 import { WORDS_MAX } from "../../../core/fence.ts";
1112 import { good, bad, type Tool, str, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
@@ -15,9 +16,9 @@ const buildBad = (error: BuildError) => bad(error, BUILD_WORDS[error] ?? error);
1516
1617 export const tool: Tool = {
1718 name: "say",
18 doc: "`{ repo?, number?, text?, conversation?, action?, title?, archived? }`: speak on an issue or a pull; a working builder hears it as its next step. With no `repo` or `number` it speaks to the forge's own agent (`forge talk`), which answers in `GET /api/v1/conversation/turns`. `conversation` names one of your conversations (default: the latest); `action` list | find (`text`: words; matching line) | new | rename | archive | restore manages them (`title` for rename and new; `archived` lists archived ones); `action` build (`text` prompt, `template`) | build_state | build_diff (`version`) | build_restore (`version`) | build_publish drives a talk build of `conversation`",
19 doc: "`{ repo?, number?, text?, conversation?, action?, title?, archived? }`: speak on an issue or a pull; a working builder hears it as its next step. With no `repo` or `number` it speaks to the forge's own agent (`forge talk`), which answers in `GET /api/v1/conversation/turns`. `conversation` names one of your conversations (default: the latest); `action` list | find (`text`: words; matching line) | new | rename | archive | restore | download (Markdown) manages them (`title` for rename and new; `archived` lists archived); `action` build (`text` prompt, `template`) | build_state | build_diff (`version`) | build_restore (`version`) | build_publish drives a talk build of `conversation`",
1920 description:
20 "Say something on an issue or pull; with no repo, to the forge's agent; manage and find conversations (action).",
21 "Say something on an issue or pull; with no repo, to the forge agent; manage, find, download chats.",
2122 inputSchema: {
2223 type: "object",
2324 properties: {
@@ -25,7 +26,7 @@ export const tool: Tool = {
2526 number: { type: "integer", minimum: 1 },
2627 text: { type: "string", maxLength: 8000 },
2728 conversation: { type: "string" },
28 action: { type: "string", enum: ["list", "find", "new", "rename", "archive", "restore", ...BUILD_ACTIONS] },
29 action: { type: "string", enum: ["list", "find", "new", "rename", "archive", "restore", "download", ...BUILD_ACTIONS] },
2930 template: { type: "string" },
3031 version: { type: "integer", minimum: 1 },
3132 title: { type: "string", maxLength: 80 },
@@ -81,6 +82,13 @@ export const tool: Tool = {
8182 const restored = await restoreVersion(ctx.app, user, id, n);
8283 return restored.ok ? good({ version: restored.value }) : buildBad(restored.error);
8384 }
85 if (action === "download") {
86 const asked = str(args["conversation"]);
87 // No conversation named: the latest one, as the tool's own doc says.
88 const which = asked !== "" ? asked : (listConversations(db, user.id)[0]?.id ?? "");
89 const made = conversationMarkdown(db, user.id, which, ctx.url.origin);
90 return made.ok ? good({ name: made.value.name, markdown: made.value.text, truncated: made.value.truncated }) : bad("not_found", "no such conversation of yours");
91 }
8492 if (action === "new") {
8593 const started = createConversation(db, user.id);
8694 if (!started.ok) return bad("too_many", TOO_MANY_WORDS);
@@ -97,7 +105,7 @@ export const tool: Tool = {
97105 const named = renameConversation(db, user.id, target.id, args["title"]);
98106 return named.ok ? good({ says: "Renamed." }) : bad("invalid_title", "title is up to 80 characters, on one line");
99107 }
100 if (action !== "archive" && action !== "restore") return bad("invalid", "action is list, find, new, rename, archive or restore");
108 if (action !== "archive" && action !== "restore") return bad("invalid", "action is list, find, new, rename, archive, restore or download");
101109 archiveConversation(db, user.id, target.id, action === "archive");
102110 return good({ says: action === "archive" ? "Archived." : "Restored." });
103111 }
src/http/server.ts +2 −1
@@ -175,7 +175,7 @@ import {
175175 themeSubmit,
176176 } from "../web/pages/site.ts";
177177 import { talkBuild, talkPublish, talkRestore } from "../web/talk_build.ts";
178 import { talkAgainSend, talkArchive, talkConfirm, talkNew, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView } from "../web/pages/talk.ts";
178 import { talkAgainSend, talkArchive, talkConfirm, talkDownload, talkNew, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView } from "../web/pages/talk.ts";
179179 import {
180180 recoverFinish,
181181 recoverOptions,
@@ -1177,6 +1177,7 @@ export function buildRouter(): Router<Handler> {
11771177 router.add("POST", "/talk/new", talkNew);
11781178 router.add("POST", "/talk/build", talkBuild);
11791179 router.add("GET", "/talk/:id", talkView);
1180 router.add("GET", "/talk/:id/download", talkDownload);
11801181 router.add("POST", "/talk/:id", talkSend);
11811182 router.add("POST", "/talk/:id/rename", talkRename);
11821183 router.add("POST", "/talk/:id/archive", talkArchive);
src/tui/screens/talk_chats.ts +39 −2
@@ -3,7 +3,8 @@
33 * Archive/Restore /talk has, through the same `core/conversations.ts` calls,
44 * so a change here is the next thing a web viewer's list or stream reads.
55 * `a` flips between the live list and the archived one; Enter opens one,
6 * to read it and, with `s`, say something in it through `talk()`.
6 * to read it and, with `s`, say something in it through `talk()`. `d` reads the conversation
7 * as the Markdown file /talk/:id/download serves (`conversationMarkdown`, its owner's alone).
78 */
89
910 import { TALK_WORDS, talk } from "../../actions/talk.ts";
@@ -20,6 +21,8 @@ import {
2021 TOO_MANY_WORDS,
2122 type Conversation,
2223 } from "../../core/conversations.ts";
24 import { conversationMarkdown } from "../../core/conversation_markdown.ts";
25 import { publicOrigin } from "../../core/public_origin.ts";
2326 import { filesOf, repoOf, stepOf } from "../../core/talk_steps.ts";
2427 import { workspaceOf } from "../../actions/talk_workspace.ts";
2528 import type { Ctx, Screen } from "../app/app.ts";
@@ -34,6 +37,31 @@ const BAD_TITLE = `A title is up to ${TITLE_MAX} characters, on one line.`;
3437
3538 const WHO: Readonly<Record<string, string>> = { person: "You", agent: "Forge", tool: "Tool", confirm: "Asks" };
3639
40 /** The conversation as the Markdown download holds it, to read and scroll; the file itself is the web's /talk/:id/download. */
41 function downloadScreen(f: Session, ctx: Ctx, chat: Conversation): Screen {
42 const scroll = new Scroll();
43 const made = f.user === undefined ? undefined : conversationMarkdown(f.app.db, f.user.id, chat.id, publicOrigin(f.app.config.url, `http://localhost:${f.app.config.port}`));
44 const text = made?.ok === true ? made.value.text : "Not a conversation of yours.";
45 const head = made?.ok === true ? `${made.value.name}${made.value.truncated ? " · truncated" : ""} · the file is at /talk/${chat.id}/download` : "";
46 let cache: { w: number; lines: { text: string; style: ReturnType<typeof style> }[][] } | undefined;
47 return {
48 title: "Download",
49 keys: [binding(["j", "k"], "scroll"), binding(["esc", "q"], "back")],
50 render(area, s) {
51 const c = ctx.theme.c;
52 const [top, body] = split(area, "v", [len(1), fill(1)]);
53 s.text(top!.x, top!.y, truncate(head, top!.w), style(c.mutedFg, c.bg), top!.x + top!.w);
54 if (cache === undefined || cache.w !== body!.w) cache = { w: body!.w, lines: text.split("\n").flatMap((l) => wrap(l, Math.max(10, body!.w - 2))).map((l) => [{ text: l, style: style(c.fg, c.bg) }]) };
55 drawLines(s, body!, c, scroll, cache.lines);
56 },
57 key(e) {
58 if (e.key === "esc" || e.key === "q") ctx.pop();
59 else scroll.key(e, cache?.lines.length ?? 0);
60 return true;
61 },
62 };
63 }
64
3765 /**
3866 * One conversation, newest turns last: j/k scroll, s says something in it, r
3967 * reloads. `hit` is a search result's turn: the view opens on the page around
@@ -102,7 +130,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
102130 get title() {
103131 return chat.title === "" ? "Untitled conversation" : chat.title;
104132 },
105 keys: [binding(["j", "k"], "scroll"), binding(["s"], "say"), binding(["r"], "reload"), binding(["p"], "pane"), binding(["esc"], "back")],
133 keys: [binding(["j", "k"], "scroll"), binding(["s"], "say"), binding(["r"], "reload"), binding(["p"], "pane"), binding(["d"], "download"), binding(["esc"], "back")],
106134 render(area, s) {
107135 const c = ctx.theme.c;
108136 width = area.w;
@@ -141,6 +169,10 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
141169 ctx.invalidate();
142170 return true;
143171 }
172 if (e.key === "d") {
173 ctx.push(downloadScreen(f, ctx, chat));
174 return true;
175 }
144176 if (e.key === "s") {
145177 ctx.push(
146178 promptScreen(ctx, screen, {
@@ -196,6 +228,7 @@ export function talkChatsScreen(f: Session, ctx: Ctx): Screen {
196228 binding(["r"], "rename"),
197229 binding(["x"], "archive or restore"),
198230 binding(["a"], "archived"),
231 binding(["d"], "download"),
199232 binding(["/"], "search"),
200233 ],
201234 render(area, s) {
@@ -285,6 +318,10 @@ export function talkChatsScreen(f: Session, ctx: Ctx): Screen {
285318 );
286319 return true;
287320 }
321 if (e.key === "d") {
322 ctx.push(downloadScreen(f, ctx, here));
323 return true;
324 }
288325 if (e.key === "x") {
289326 archiveConversation(f.app.db, user.id, here.id, !archived);
290327 say(archived ? "Restored." : "Archived.");
src/web/pages/talk.ts +51 −16
@@ -4,8 +4,8 @@
44 * `http/sse.ts` as it is written, each turn drawn by the same function the
55 * first paint uses. A stream ends with the turn (or after `STREAM_MS`, well
66 * inside the edge's timeout) and the client reconnects from the last turn id
7 * it saw. A held action draws Confirm and Cancel buttons; Confirm is the
8 * existing yes (`actions/conversation_confirms.ts`), Cancel is the no.
7 * it saw. A held action draws Do it and Not now buttons; Do it is the
8 * existing yes (`actions/conversation_confirms.ts`), Not now is the no, kept as a turn.
99 * Edit and Regenerate are drawn by the script on the last message and reply;
1010 * a failed turn says in plain words what happened and carries Retry, a plain
1111 * form. What they replace stays in the log, marked (#8817).
@@ -39,6 +39,7 @@ import {
3939 turnsAfter,
4040 type Turn,
4141 } from "../../core/conversations.ts";
42 import { conversationMarkdown } from "../../core/conversation_markdown.ts";
4243 import { contextOf, contextText, dollars, turnCosts, type Context } from "../../core/conversation_cost.ts";
4344 import { aboutLine as aboutText } from "../../core/talk_about.ts";
4445 import { WORDS_MAX } from "../../core/fence.ts";
@@ -69,7 +70,10 @@ export const STREAM_MS = 40_000;
6970 export const POLL_MS = 400;
7071 /** Streams one person may hold open at once; a fourth is told to wait. */
7172 export const STREAMS_MAX = 3;
72 /** What a stream consults: how long it lasts and whether a turn runs. Tests move it; nothing else does. */
73 /**
74 * What a stream consults: how long it lasts and whether a turn runs. Tests move it; nothing else
75 * does.
76 */
7377 export const clock = { streamMs: STREAM_MS, running: turnRunning };
7478 const open = new Map<string, number>();
7579 const TURN_ID = /^[0-9a-z]{0,40}$/;
@@ -98,17 +102,17 @@ const parse = (text: string): Record<string, unknown> | undefined => {
98102 }
99103 };
100104
101 /** Confirm and Cancel for a held action; each its own form, so each posts alone. */
105 /** Do it and Not now for a held action; each its own form, so each posts alone. */
102106 function confirmButtons(id: string, tool: string): Html {
103107 // A result shown once is drawn by Settings → Confirms, never kept in a turn.
104108 const once = ASKING[tool]?.once !== undefined;
105109 return html`<div class="bar">
106110 <form method="post" action="${once ? `/settings/confirms/${id}` : `${HERE}/confirm/${id}`}" ${once ? null : html`data-confirm`}>
107111 <input type="hidden" name="answer" value="yes" />
108 ${btn("Confirm", { variant: "primary", icon: "check", label: `Confirm: ${tool}`, name: "answer", value: "yes" })}
112 ${btn("Do it", { variant: "primary", icon: "check", label: `Do it: ${tool}`, name: "answer", value: "yes" })}
109113 </form>
110114 <form method="post" action="${HERE}/confirm/${id}" data-confirm>
111 ${btn("Cancel", { icon: "x", label: `Cancel: ${tool}`, name: "answer", value: "no" })}
115 ${btn("Not now", { icon: "x", label: `Not now: ${tool}`, name: "answer", value: "no" })}
112116 </form>
113117 </div>`;
114118 }
@@ -134,7 +138,10 @@ function receiptCard(id: string, turnId: string, receipt: Receipt, at: string, s
134138 </li>`;
135139 }
136140
137 /** What Ask again says for the person: no sentence of the agent's, so it asks and never itself names the write. */
141 /**
142 * What Ask again says for the person: no sentence of the agent's, so it asks and never itself names
143 * the write.
144 */
138145 export const ASK_AGAIN = "That ran out before I answered. Ask me again.";
139146
140147 /** A confirm past its time, said in the thread, with the one way on. */
@@ -164,7 +171,10 @@ const stepCard = (id: string, step: Step, at: string, set = ""): Html =>
164171 const workHtml = (work: Work): Html =>
165172 html`<p class="talk-steps small muted">${work.steps.charAt(0).toUpperCase() + work.steps.slice(1)}</p>${work.links.length === 0 ? null : html`<p class="talk-links small">${work.links.map((l) => html`<a href="${l.href}">${l.label}</a>`)}</p>`}`;
166173
167 /** What an empty chat offers to start with; each is a link that fills the composer (`?q=`), so it works without the script. */
174 /**
175 * What an empty chat offers to start with; each is a link that fills the composer (`?q=`), so it
176 * works without the script.
177 */
168178 const SUGGESTIONS = ["What needs my attention?", "What did the crew do today?", "Show me my apps"] as const;
169179
170180 /** Ask again as a form, so it works without the script; the script only enhances it. */
@@ -193,7 +203,10 @@ export const queuedHtml = (q: { id: string; text: string }): Html =>
193203 html`<li class="talk-turn talk-person talk-queued" data-queued="${q.id}"><div class="talk-body talk-plain">${q.text}</div>
194204 <form class="talk-meta small muted" method="post" action="${HERE}/queue/${q.id}/cancel" data-unqueue>Queued, sends after this answer ${btn("Cancel", { label: "Cancel this queued message" })}</form></li>`;
195205
196 /** How full the context is, one quiet line above the log; always drawn so a finished run can fill it. */
206 /**
207 * How full the context is, one quiet line above the log; always drawn so a finished run can fill
208 * it.
209 */
197210 const contextLine = (c: Context | undefined): Html =>
198211 html`<p class="talk-context small muted" data-context ${c === undefined ? html`hidden` : null}>${c === undefined ? "" : contextText(c)}</p>`;
199212
@@ -250,7 +263,7 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: number
250263 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);
251264 if (data !== undefined && "confirm" in data) {
252265 const tool = String(data["tool"] ?? "");
253 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"] ?? "")}`;
266 const says = data["cancelled"] === true ? `Not now: ${tool}.` : data["done"] === true ? `Done: ${tool}.${typeof data["undo"] === "string" ? ` To undo: ${data["undo"]}.` : ""}` : `${tool} did not go through: ${String(data["message"] ?? data["error"] ?? "")}`;
254267 return toolCard(id, says, tool, turn.createdAt, set);
255268 }
256269 const step = stepOf(turn.text);
@@ -259,7 +272,10 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: number
259272 return toolCard(id, call, call.split(/[\s(:{]/, 1)[0] ?? "tool", turn.createdAt, set);
260273 }
261274
262 /** The conversations list, then this one's name with Rename and Archive: each a plain form, so none needs the script. */
275 /**
276 * The conversations list, then this one's name with Rename and Archive: each a plain form, so none
277 * needs the script.
278 */
263279 function chats(ctx: Ctx, conversation: Conversation, showArchived: boolean, typed: string): Html {
264280 const user = ctx.auth.user!;
265281 const found = typed === "" ? undefined : findConversations(ctx.app.db, user.id, typed);
@@ -309,6 +325,7 @@ function chats(ctx: Ctx, conversation: Conversation, showArchived: boolean, type
309325 ${btn("Save")}
310326 </form>
311327 </details>
328 <a class="btn" href="${urlOf(conversation)}/download" download>Download</a>
312329 <form method="post" action="${urlOf(conversation)}/archive">
313330 <input type="hidden" name="archived" value="${archived ? "0" : "1"}" />
314331 ${btn(archived ? "Restore" : "Archive")}
@@ -324,7 +341,8 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
324341 const typed = (ctx.url.searchParams.get("find") ?? "").slice(0, FIND_CHARS);
325342 // A search result names its turn: show the page that holds it, and let the fragment scroll there.
326343 const focus = ctx.url.searchParams.get("turn");
327 // Near the end pageAround has no `before`: that is the latest page, unpaged, and the fragment still lands.
344 // Near the end pageAround has no `before`: that is the latest page, unpaged, and the fragment
345 // still lands.
328346 if (before === undefined && focus !== null && focus !== "" && TURN_ID.test(focus)) before = pageAround(ctx.app.db, user.id, conversation.id, focus);
329347 const paged = before !== undefined;
330348 const listed = listTurns(ctx.app.db, user.id, conversation.id, {
@@ -345,7 +363,8 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
345363 const acts = !paged ? exchangeActs(ctx.app.db, user.id, conversation.id, running, here) : new Map<string, Html>();
346364 // Edit shows the composer holding the last message, posting to Edit instead of Send.
347365 const editing = edit ? lastExchange(ctx.app.db, user.id, conversation.id).person : undefined;
348 // A conversation that builds an app shows its versions and preview; an empty one offers the one box (#11010).
366 // A conversation that builds an app shows its versions and preview; an empty one offers the one
367 // box (#11010).
349368 const building = chatBuildOf(ctx.app.db, conversation.id) !== undefined;
350369 const panel = building ? await panelFor(ctx, conversation.id, here) : null;
351370 const box = !building && !paged && turns.length === 0 ? buildBox(ctx.app.db, user, chosenTemplate(ctx.app.db, user, ctx.url.searchParams.get("template"))) : null;
@@ -398,7 +417,10 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
398417 return page({ ctx, title: "Talk", body, styleCss: panel === null && box === null ? talkCss : talkCss + buildCss, scriptJs: talkJs, description: "Talk to the forge.", ...(pane.frame === undefined ? {} : { frameSrc: pane.frame }) });
399418 }
400419
401 /** The conversation a request names (`:id`), or the person's latest when it names none; undefined when it is not theirs. */
420 /**
421 * The conversation a request names (`:id`), or the person's latest when it names none; undefined
422 * when it is not theirs.
423 */
402424 const conversationOf = (ctx: Ctx, user: { readonly id: string }): Conversation | undefined => {
403425 const named = ctx.params["id"];
404426 if (named === undefined) return openConversation(ctx.app.db, user.id);
@@ -474,9 +496,22 @@ export async function talkArchive(ctx: Ctx): Promise<Response> {
474496 return flashTo(ctx, archive ? HERE : urlOf(conversation), { tone: "success", message: archive ? "Archived. It is under Archived." : "Restored." });
475497 }
476498
499 // GET /talk/:id/download — the conversation as one Markdown file, its owner's alone.
500 export function talkDownload(ctx: Ctx): Response {
501 const user = ctx.auth.user;
502 if (user === undefined) return signInFirst(ctx);
503 const id = ctx.params["id"] ?? "";
504 const made = CONVERSATION_ID.test(id) ? conversationMarkdown(ctx.app.db, user.id, id, ctx.url.origin) : undefined;
505 if (made === undefined || !made.ok) return notFoundPage(ctx);
506 return new Response(made.value.text, {
507 headers: { "content-type": "text/markdown; charset=utf-8", "content-disposition": `attachment; filename="${made.value.name}"`, "cache-control": "private, no-store" },
508 });
509 }
510
477511 const AGAIN: readonly RedoHow[] = ["edit", "regenerate", "retry"];
478512
479 // POST /talk/again/:how and POST /talk/:id/again/:how — edit and resend the last message, regenerate the last reply, retry a failed turn.
513 // POST /talk/again/:how and POST /talk/:id/again/:how — edit and resend the last message,
514 // regenerate the last reply, retry a failed turn.
480515 export async function talkAgainSend(ctx: Ctx): Promise<Response> {
481516 const user = ctx.auth.user;
482517 if (user === undefined) return signInFirst(ctx);
@@ -538,7 +573,7 @@ export async function talkConfirm(ctx: Ctx): Promise<Response> {
538573 else if (!yes.done) refused = `${String(yes.turn["tool"])} did not go through: ${String(yes.turn["message"] ?? yes.turn["error"])}`;
539574 }
540575 if (asJson) return json(refused === undefined ? { ok: true } : { ok: false, message: refused }, refused === undefined ? 200 : status);
541 return flashTo(ctx, `${HERE}#end`, refused === undefined ? { tone: "success", message: answer === "yes" ? "Confirmed." : "Cancelled." } : { tone: "danger", message: `Nothing was done: ${refused}` });
576 return flashTo(ctx, `${HERE}#end`, refused === undefined ? { tone: "success", message: answer === "yes" ? "Done." : "Not now." } : { tone: "danger", message: `Nothing was done: ${refused}` });
542577 }
543578
544579 // POST /talk/undo/:turn — the person's tap on a receipt's Undo, from their own session.
test/conversation-download.test.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * A talk conversation downloads as one Markdown file (#13307): its owner's alone, in order, over
3 * the page and the MCP.
4 */
5 import { afterAll, beforeAll, 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 { createApp, type App } from "../src/app.ts";
10 import { attach, storeFile } from "../src/core/conversation_files.ts";
11 import { fenced, MAX_TEXT, conversationMarkdown } from "../src/core/conversation_markdown.ts";
12 import { appendTurn, createConversation } from "../src/core/conversations.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let app: App;
22 let servers: Servers;
23 let aliceId: string;
24 let alice: string;
25 let bob: string;
26 let convo: string;
27 let fileId: string;
28
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "forge-conv-download-"));
31 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
32 servers = await serve(app);
33 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
34 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
35 if (!a.ok || !b.ok) throw new Error("user");
36 aliceId = a.value.id;
37 alice = createToken(app.db, a.value.id, "personal", "rw").token;
38 bob = createToken(app.db, b.value.id, "personal", "rw").token;
39 const c = createConversation(app.db, aliceId);
40 if (!c.ok) throw new Error("conversation");
41 convo = c.value.id;
42 const first = appendTurn(app.db, aliceId, convo, { role: "person", text: "first question" });
43 appendTurn(app.db, aliceId, convo, { role: "agent", text: "second: an answer" });
44 appendTurn(app.db, aliceId, convo, { role: "person", text: "third thing" });
45 const f = storeFile(app.db, dir, aliceId, "notes.txt", new TextEncoder().encode("hi"));
46 if (!first.ok || !f.ok) throw new Error("seed");
47 attach(app.db, [f.value], first.value.id);
48 fileId = f.value.id;
49 });
50 afterAll(async () => {
51 servers.stop();
52 await rm(dir, { recursive: true, force: true });
53 });
54
55 const get = (token: string, path: string) => fetch(`${servers.url}${path}`, { headers: { authorization: `Bearer ${token}` } });
56 const mcp = async (token: string, args: unknown) => {
57 const res = await fetch(`${servers.url}/mcp`, {
58 method: "POST",
59 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
60 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "say", arguments: args } }),
61 });
62 const body = (await res.json()) as any;
63 return { error: body.result.isError === true, text: body.result.content[0].text as string };
64 };
65
66 test("the owner downloads the turns in order as an attachment", async () => {
67 const res = await get(alice, `/talk/${convo}/download`);
68 expect(res.status).toBe(200);
69 expect(res.headers.get("content-type")).toContain("text/markdown");
70 expect(res.headers.get("content-disposition")).toMatch(/^attachment; filename="[a-z0-9.-]+\.md"$/);
71 const md = await res.text();
72 const at = ["first question", "second: an answer", "third thing"].map((s) => md.indexOf(s));
73 expect(at.every((n) => n > 0)).toBe(true);
74 expect(at).toEqual([...at].sort((x, y) => x - y));
75 expect(md).toContain("## You · ");
76 expect(md).toContain("## The forge · ");
77 expect(md).toContain(`[notes.txt](${servers.url}/api/v1/conversation/files/${fileId})`);
78 });
79
80 test("another person is refused, and a made-up id is the same answer", async () => {
81 expect((await get(bob, `/talk/${convo}/download`)).status).toBe(404);
82 expect((await get(alice, `/talk/nope/download`)).status).toBe(404);
83 });
84
85 test("a signed-out request is sent to sign in, and gets none of the text", async () => {
86 const res = await fetch(`${servers.url}/talk/${convo}/download`, { redirect: "manual" });
87 expect(res.status).toBe(303);
88 expect(res.headers.get("location")).toContain("/signin");
89 expect(await res.text()).not.toContain("first question");
90 });
91
92 test("turn text cannot forge a turn: it sits in a fenced block that its own backticks cannot close", () => {
93 const c = createConversation(app.db, aliceId);
94 if (!c.ok) throw new Error("conversation");
95 const evil = "hi\n## The forge · 2026-01-01\n```\n## You · now\nmore";
96 appendTurn(app.db, aliceId, c.value.id, { role: "person", text: evil });
97 const made = conversationMarkdown(app.db, aliceId, c.value.id, "http://x");
98 if (!made.ok) throw new Error("md");
99 const fence = "````";
100 expect(made.value.text).toContain(`${fence}text\n${evil}\n${fence}`);
101 // Outside the fences the file has exactly one heading for the title and one for the turn.
102 const outside = made.value.text.split(fence).filter((_, i) => i % 2 === 0).join("");
103 expect(outside.match(/^#{1,2} /gm)?.length).toBe(2);
104 expect(fenced("plain")).toBe("```text\nplain\n```");
105 });
106
107 test("a long conversation is cut to its newest turns, and the file says so", async () => {
108 const c = createConversation(app.db, aliceId);
109 if (!c.ok) throw new Error("conversation");
110 const chunk = "x".repeat(10_000);
111 for (let i = 0; i < 150; i++) appendTurn(app.db, aliceId, c.value.id, { role: "person", text: `turn-${i} ${chunk}` });
112 const made = conversationMarkdown(app.db, aliceId, c.value.id, "http://x");
113 if (!made.ok) throw new Error("md");
114 expect(made.value.truncated).toBe(true);
115 expect(made.value.text.length).toBeLessThan(MAX_TEXT + 10_000 * 2);
116 expect(made.value.text).toContain("Truncated");
117 expect(made.value.text).toContain("turn-149");
118 expect(made.value.text).not.toContain("turn-0 ");
119 expect((conversationMarkdown(app.db, aliceId, convo, "http://x") as any).value.truncated).toBe(false);
120 });
121
122 test("with no conversation named, the MCP downloads the latest one; a person with none is told so", async () => {
123 const latest = createConversation(app.db, aliceId);
124 if (!latest.ok) throw new Error("conversation");
125 appendTurn(app.db, aliceId, latest.value.id, { role: "person", text: "the newest words" });
126 const got = await mcp(alice, { action: "download" });
127 expect(got.error).toBe(false);
128 expect(JSON.parse(got.text).markdown).toContain("the newest words");
129 expect((await mcp(bob, { action: "download" })).error).toBe(true);
130 });
131
132 test("the MCP say tool returns the same text, to the owner alone", async () => {
133 const page = await (await get(alice, `/talk/${convo}/download`)).text();
134 const mine = await mcp(alice, { action: "download", conversation: convo });
135 expect(mine.error).toBe(false);
136 expect(JSON.parse(mine.text).markdown).toBe(page);
137 expect((await mcp(bob, { action: "download", conversation: convo })).error).toBe(true);
138 });
test/no-polling.test.ts +1
@@ -324,6 +324,7 @@ const NOT_WALKED: Record<string, string> = {
324324 "/settings/origins/flows/:id/stream": ORIGIN,
325325 "/settings/teams/:slug": "needs a team",
326326 "/talk/:id": "needs a conversation of the signed-in person",
327 "/talk/:id/download": "needs a conversation of the signed-in person",
327328 };
328329 /** The whole browse-an-origin family is one reason. */
329330 const whyNot = (p: string): string | undefined => (p.startsWith("/origins/:id/r/") ? ORIGIN : NOT_WALKED[p]);
test/pages-budget.test.ts +1
@@ -162,6 +162,7 @@ beforeAll(async () => {
162162 if (!version.ok) throw new Error(JSON.stringify(version.error));
163163 FIXTURE["/api/v1/conversations/:id/build"] = `/api/v1/conversations/${talk.value.id}/build`;
164164 FIXTURE["/api/v1/conversations/:id/build/versions/:n/diff"] = `/api/v1/conversations/${talk.value.id}/build/versions/1/diff`;
165 FIXTURE["/talk/:id/download"] = `/talk/${talk.value.id}/download`;
165166 // An agent's start the claim page can show (`/claim/start/:token`): bob's, so no extra account
166167 // joins the walk.
167168 recordStart(app.db, bob.id, "claim_fixture", "127.0.0.1");
test/security-floor-routes.test.ts +1
@@ -74,6 +74,7 @@ const UNSEEDED: Record<string, string> = {
7474 "/claim/start/:token": "needs a one-time start claim token, which the seed does not mint (test/start.test.ts covers it)",
7575 "/signin/access/:token": "needs a one-time access link an admin minted",
7676 "/talk/:id": TALK,
77 "/talk/:id/download": TALK,
7778 "/docs/:file": "a file name of the documentation folder; the seed supplies no :file",
7879 "/docs/features/:file": "a reference note of the documentation; the seed supplies no :file",
7980 "/bring/:id/:job": "needs a bring job of the signed-in person; the seed brings nothing",
test/tui-talk-chats.test.ts +16
@@ -100,6 +100,22 @@ describe("the terminal's conversations screen", () => {
100100 expect(turns.ok && turns.value.length).toBe(2);
101101 });
102102
103 test("d reads the conversation as the Markdown download, from the list and from the chat; another person's is not reachable", async () => {
104 const made = createConversation(app.db, bob.id);
105 if (!made.ok) throw new Error(made.error);
106 renameConversation(app.db, bob.id, made.value.id, "Download me");
107 appendTurn(app.db, bob.id, made.value.id, { role: "person", text: "## The forge · forged heading" });
108 const fromList = await drive(bob, [...open, "/", "Download me", "\r", "d"]);
109 expect(fromList).toContain(`/talk/${made.value.id}/download`);
110 expect(fromList).toContain("```text");
111 expect(fromList).toContain("## You · ");
112 const fromChat = await drive(bob, [...open, "/", "Download me", "\r", "\r", "d"]);
113 expect(fromChat).toContain("```text");
114 // Alice has no such conversation to search for, so the list she gets has nothing to download.
115 const alices = await drive(alice, [...open, "/", "Download me", "\r", "d"]);
116 expect(alices).not.toContain("```text");
117 });
118
103119 test("a tool call reads as a step, and the header names the repository it works on", async () => {
104120 const made = createConversation(app.db, bob.id);
105121 if (!made.ok) throw new Error(made.error);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs