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

/talk lists conversations: new, rename, archive, each at its own URL #8837

Closed opened this
Closed without merging

scout/forge:scout/8814-talk-lists-conversations-new-rename-arch → main 14 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
29 files changed +1136 −86
docs/design/areas/talk.md +2
@@ -18,6 +18,8 @@
1818 - `.talk-copy` — a quiet text button that copies a message or a code block.
1919 - `.talk-suggest` — the starter questions on an empty chat; each fills the composer.
2020 - `.talk-jump` — "Latest" button, shown when you have scrolled up from the end.
21 - `.talk-chats` — the conversations list above the chat (#8814): New, the person's conversations newest first, and the Archived filter link.
22 - `.talk-here` — the line naming the open conversation, with its Rename and Archive forms.
2123 - `.talk-steps` — the quiet steps line under a reply ("read 3 files, opened #12").
2224 - `.talk-links` — the links under a reply to what the turn opened or changed.
2325 - `.talk-replaced` — a turn the person edited, regenerated or retried past: kept in the log, dimmer, labelled "replaced".
docs/features/talk.md +12 −1
@@ -18,6 +18,16 @@ A reply streams in over `GET /talk/stream?after=<turn id>` (server-sent events,
1818
1919 When the agent asks first (`needs_confirm`), the turn draws **Confirm** (the existing yes) and **Cancel** (a no: the confirm is spent, nothing runs, a turn says it was cancelled). A result shown once (an invite link) is drawn by Settings → Confirms instead, where Confirm leads.
2020
21 ## Many conversations (#8814)
22
23 A person has any number. `/talk` is their latest, with the list above it (newest activity first), **New**, and **Archived (n)** as the one filter (`/talk?archived=1`). Each opens at `/talk/<id>`, stable across reloads; Rename and Archive/Restore are plain forms (`POST /talk/:id/rename`, `/talk/:id/archive`, `POST /talk/new`), so they work without the script. Another person's id is 404 everywhere. A message with no conversation named goes to the latest one that is not archived.
24
25 - **Cap:** a person holds at most 100 conversations, archived ones counted; past it New is refused (page flash, API 409 `too_many`, MCP `too_many`). Stop ends every reply the person has running, in any conversation.
26 - **API:** `GET /api/v1/conversations[?archived=1]`, `POST /api/v1/conversations {title?}`, `PATCH /api/v1/conversations/:id {title?, archived?}`; `conversation` on `POST …/messages` and `GET …/turns?conversation=` picks one.
27 - **MCP:** `say` with `action` list | new | rename | archive | restore, and `conversation` to speak in one.
28 - **Terminal:** Palette → Conversations: `n` new, `r` rename, `x` archive or restore, `a` the archived list, Enter opens one (its last 50 turns; `s` says something in it, `r` reloads); the same calls, so the web list and stream read what it writes.
29 - Sending to an archived conversation keeps it archived; the page says so above the composer.
30
2131 ## Edit, regenerate, retry (#8817)
2232
2333 Three actions on the last exchange, one door, `talkAgain()` in `src/actions/talk.ts` (the same 12-a-minute throttle and refusals as sending):
@@ -28,6 +38,7 @@ Three actions on the last exchange, one door, `talkAgain()` in `src/actions/talk
2838 - Refused while a turn runs (`running`, 409), or when there is nothing to act on (`nothing`, 409).
2939 - **Web:** Edit under your last message (opens the composer holding it, `/talk?edit=1`; Send resends), Regenerate under the last reply, Retry under a failed one. All are plain forms or links, so they work without the script, which only does them in place. They post to `POST /talk/again/edit|regenerate|retry`, from your own signed-in browser only.
3040 - **Terminal:** `ssh <forge> talk-again edit <words>`, `ssh <forge> talk-again regenerate`, `ssh <forge> talk-again retry`.
41 - With several conversations they act on the one open: the forms post to `/talk/<id>/again/<how>` (`/talk/again/<how>` on the latest); the action takes the conversation as an optional argument.
3142 - There is no API or MCP door for these yet.
3243
3344 ## Stop
@@ -56,7 +67,7 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha
5667 | Starter questions on an empty chat (links to `/talk?q=`, so they work without the script) | this pull | AI Elements `Suggestion` |
5768 | Stick to bottom, "Latest" jump button | this pull | AI Elements `Conversation` |
5869 | Thinking as one closed line; a steps line under a reply ("read 3 files, opened #12"); links to each issue, pull, file or app the turn opened or changed | this pull | AI Elements `Reasoning`, `ChainOfThought` |
59 | Many conversations: new, list, search, rename, archive, URL each | next pull | needs a migration: today one row per person |
70 | Many conversations: new, list, rename, archive, URL each | have (#8814) | search is not added yet |
6071 | Edit and resend, regenerate, Retry (see below) | have (#8817) | replaced turns are kept and marked, not deleted |
6172 | Queue | next pull | needs a queue on `crew/conversation.ts` |
6273 | Cost under each reply and how full the context is (header, and in the terminal) | this pull | the run's own usage record, never an estimate |
src/actions/talk.ts +8 −5
@@ -6,6 +6,7 @@
66 */
77
88 import type { App } from "../app.ts";
9 import { getConversation } from "../core/conversations.ts";
910 import { RateLimiter } from "../core/ratelimit.ts";
1011 import type { User } from "../core/users.ts";
1112 import { conversationOptions, redo, say, stopTurn, type RedoHow, type RedoRefusal, type SayRefusal, type Said } from "../crew/conversation.ts";
@@ -18,6 +19,7 @@ export type TalkRefusal = SayRefusal | RedoRefusal | "off" | "rate_limited";
1819
1920 /** What each refusal says, with its status. */
2021 export const TALK_WORDS: Readonly<Record<TalkRefusal, readonly [number, string]>> = {
22 not_found: [404, "no such conversation"],
2123 unauthorized: [401, "sign in to talk to the forge"],
2224 empty: [422, "say something"],
2325 too_long: [422, "the message is too long"],
@@ -46,23 +48,24 @@ const watch = (app: App, said: Said): void => {
4648 said.done?.catch((error: unknown) => app.log.error("conversation turn crashed", { error: String(error) }));
4749 };
4850
49 export function talk(app: App, user: User | undefined, text: string): Result<Said, TalkRefusal> {
51 export function talk(app: App, user: User | undefined, text: string, conversationId?: string): Result<Said, TalkRefusal> {
5052 if (user === undefined) return err("unauthorized");
53 if (conversationId !== undefined && getConversation(app.db, user.id, conversationId) === undefined) return err("not_found");
5154 const options = conversationOptions(app);
5255 if (options === undefined) return err("off");
5356 if (!take(app, user)) return err("rate_limited");
54 const said = say(app, options, user.id, text);
57 const said = say(app, options, user.id, text, conversationId);
5558 if (said.ok) watch(app, said.value);
5659 return said;
5760 }
5861
59 /** Edit the last message and resend it, regenerate the last reply, or retry a failed turn (#8817). */
60 export function talkAgain(app: App, user: User | undefined, how: RedoHow, text = ""): Result<Said, TalkRefusal> {
62 /** Edit the last message and resend it, regenerate the last reply, or retry a failed turn (#8817), in the named conversation or the latest. */
63 export function talkAgain(app: App, user: User | undefined, how: RedoHow, text = "", conversationId?: string): Result<Said, TalkRefusal> {
6164 if (user === undefined) return err("unauthorized");
6265 const options = conversationOptions(app);
6366 if (options === undefined) return err("off");
6467 if (!take(app, user)) return err("rate_limited");
65 const said = redo(app, options, user.id, how, text);
68 const said = redo(app, options, user.id, how, text, conversationId);
6669 if (said.ok) watch(app, said.value);
6770 return said;
6871 }
src/contract/openapi/routes/getApiV1ConversationTurns.ts +1 −1
@@ -5,6 +5,6 @@ export const route: Route = {
55 path: "/api/v1/conversation/turns",
66 summary: "The signed-in person's conversation with the forge's agent: the latest turns, oldest first, and whether an answer is being written now",
77 auth: true,
8 query: { limit: "integer", before: "string" },
8 query: { limit: "integer", before: "string", conversation: "string" },
99 reply: { running: "boolean", turns: "array" },
1010 };
src/contract/openapi/routes/getApiV1Conversations.ts added +10
@@ -0,0 +1,10 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/conversations",
6 summary: "The signed-in person's conversations with the forge's agent, newest activity first; archived: 1 lists the put-away ones",
7 auth: true,
8 query: { archived: "string" },
9 reply: { conversations: "array" },
10 };
src/contract/openapi/routes/index.ts +3
@@ -55,6 +55,7 @@ export { route as getApiV1Changelog } from "./getApiV1Changelog.ts";
5555 export { route as getApiV1CloudAccounts } from "./getApiV1CloudAccounts.ts";
5656 export { route as getApiV1Contribute } from "./getApiV1Contribute.ts";
5757 export { route as getApiV1ConversationTurns } from "./getApiV1ConversationTurns.ts";
58 export { route as getApiV1Conversations } from "./getApiV1Conversations.ts";
5859 export { route as getApiV1CrewNow } from "./getApiV1CrewNow.ts";
5960 export { route as getApiV1CrewScorecard } from "./getApiV1CrewScorecard.ts";
6061 export { route as getApiV1Explore } from "./getApiV1Explore.ts";
@@ -181,6 +182,7 @@ export { route as getContractOpenapiJson } from "./getContractOpenapiJson.ts";
181182 export { route as getMetrics } from "./getMetrics.ts";
182183 export { route as patchApiV1AdminSettings } from "./patchApiV1AdminSettings.ts";
183184 export { route as patchApiV1AgentsUsername } from "./patchApiV1AgentsUsername.ts";
185 export { route as patchApiV1ConversationsId } from "./patchApiV1ConversationsId.ts";
184186 export { route as patchApiV1ForgeFollowing } from "./patchApiV1ForgeFollowing.ts";
185187 export { route as patchApiV1ReposOwnerName } from "./patchApiV1ReposOwnerName.ts";
186188 export { route as patchApiV1ReposOwnerNameApp } from "./patchApiV1ReposOwnerNameApp.ts";
@@ -214,6 +216,7 @@ export { route as postApiV1ConversationConfirmsId } from "./postApiV1Conversatio
214216 export { route as postApiV1ConversationMessages } from "./postApiV1ConversationMessages.ts";
215217 export { route as postApiV1ConversationStop } from "./postApiV1ConversationStop.ts";
216218 export { route as postApiV1ConversationTokens } from "./postApiV1ConversationTokens.ts";
219 export { route as postApiV1Conversations } from "./postApiV1Conversations.ts";
217220 export { route as postApiV1Drills } from "./postApiV1Drills.ts";
218221 export { route as postApiV1FeedChips } from "./postApiV1FeedChips.ts";
219222 export { route as postApiV1FeedInteractions } from "./postApiV1FeedInteractions.ts";
src/contract/openapi/routes/patchApiV1ConversationsId.ts added +11
@@ -0,0 +1,11 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "patch",
5 path: "/api/v1/conversations/{id}",
6 summary: "Rename a conversation (title) or put it away and bring it back (archived: true or false); another person's id is 404",
7 auth: true,
8 body: { title: "string", archived: "boolean" },
9 reply: { conversation: "object" },
10 refusals: { invalid_title: "title is over 80 characters or has a line break (422)", not_found: "no such conversation of yours (404)", forbidden: "the request is cross-origin, or the token is read-only" },
11 };
src/contract/openapi/routes/postApiV1ConversationMessages.ts +2 −1
@@ -6,9 +6,10 @@ export const route: Route = {
66 summary: "Say something to the forge's own agent, as the signed-in person: it answers through the forge's MCP with that person's permissions, resuming their conversation; a message sent while it answers is steered into the turn; answers 202 at once, read the answer from the turns; at most 12 a minute per person",
77 auth: true,
88 status: 202,
9 body: { text: "string" },
9 body: { text: "string", conversation: "string" },
1010 reply: { how: "string" },
1111 refusals: {
12 not_found: "conversation names none of the person's (404)",
1213 invalid_text: "text is not a string of 1 to 20000 characters",
1314 too_large: "the body is over 128000 bytes (413)",
1415 no_account: "no Claude account is granted to the person (403)",
src/contract/openapi/routes/postApiV1Conversations.ts added +12
@@ -0,0 +1,12 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/conversations",
6 summary: "Start a new, empty conversation with the forge's agent; answers it, and it opens at /talk/<id>",
7 auth: true,
8 status: 201,
9 body: { title: "string" },
10 reply: { conversation: "object" },
11 refusals: { invalid_title: "title is over 80 characters or has a line break (422)", forbidden: "the request is cross-origin, or the token is read-only" },
12 };
src/core/conversations.ts +89 −11
@@ -1,8 +1,9 @@
11 /**
2 * A person's conversation with the forge: one per person, stored turn by turn
3 * in the database so it reads back after a restart. Every call takes the
4 * person's id and answers only for their own conversation; another person's
5 * conversation is `not_found`. Plain data in, plain data out, no authz beyond
2 * A person's conversations with the forge, stored turn by turn in the
3 * database so they read back after a restart. A person has any number: each
4 * has an id (its URL), a title they may change, and may be archived. Every
5 * call takes the person's id and answers only for their own conversation;
6 * another person's conversation is `not_found`. Plain data in, plain data out, no authz beyond
67 * that ownership.
78 */
89 import type { Database } from "bun:sqlite";
@@ -25,8 +26,14 @@ export interface Conversation {
2526 readonly claudeSessionId: string;
2627 readonly createdAt: string;
2728 readonly updatedAt: string;
29 readonly title: string;
30 /** When it was put away; null while it is in the list. */
31 readonly archivedAt: string | null;
2832 }
2933
34 /** Longest title kept, in characters; longer is refused, not cut. */
35 export const TITLE_MAX = 80;
36
3037 export interface Turn {
3138 readonly id: string;
3239 readonly conversationId: string;
@@ -45,6 +52,8 @@ interface ConversationRow {
4552 claude_session_id: string;
4653 created_at: string;
4754 updated_at: string;
55 title: string;
56 archived_at: string | null;
4857 }
4958
5059 interface TurnRow {
@@ -63,6 +72,8 @@ const conversationOf = (r: ConversationRow): Conversation => ({
6372 claudeSessionId: r.claude_session_id,
6473 createdAt: r.created_at,
6574 updatedAt: r.updated_at,
75 title: r.title,
76 archivedAt: r.archived_at,
6677 });
6778
6879 const turnOf = (r: TurnRow): Turn => ({
@@ -75,18 +86,85 @@ const turnOf = (r: TurnRow): Turn => ({
7586 failed: r.failed === 1,
7687 });
7788
78 /** The person's conversation, made on first use. */
79 export function openConversation(db: Database, userId: string): Conversation {
89 /** Most conversations a person holds, archived ones included; past it, New is refused. */
90 export const CONVERSATIONS_MAX = 100;
91
92 /** What every door says when New is refused. */
93 export const TOO_MANY_WORDS = `you hold ${CONVERSATIONS_MAX} conversations, the most there can be; keep talking in one of them`;
94
95 /** Start a new conversation at a person's request: refused past `CONVERSATIONS_MAX`. */
96 export function createConversation(db: Database, userId: string): Result<Conversation, "too_many"> {
97 const held = db.query("SELECT COUNT(*) AS n FROM conversation WHERE user_id = ?1").get(userId) as { n: number };
98 return held.n >= CONVERSATIONS_MAX ? err("too_many") : ok(newConversation(db, userId));
99 }
100
101 /** Start a new, empty conversation. */
102 export function newConversation(db: Database, userId: string): Conversation {
80103 const now = new Date().toISOString();
104 const row: ConversationRow = { id: id(), user_id: userId, claude_session_id: "", created_at: now, updated_at: now, title: "", archived_at: null };
81105 db.query(
82 "INSERT OR IGNORE INTO conversation (id, user_id, claude_session_id, created_at, updated_at) VALUES (?1,?2,'',?3,?3)",
83 ).run(id(), userId, now);
84 const row = db
85 .query("SELECT * FROM conversation WHERE user_id = ?1")
86 .get(userId) as ConversationRow;
106 "INSERT INTO conversation (id, user_id, claude_session_id, created_at, updated_at) VALUES (?1,?2,'',?3,?3)",
outdated

No cap on how many conversations a person holds, and this list is LIMIT 200, so stopTurn silently misses anything past it. Cap creation (newConversation callers: page, API, MCP) and refuse past the cap.

107 ).run(row.id, userId, now);
87108 return conversationOf(row);
88109 }
89110
111 /**
112 * Where a message with no conversation named goes: the person's most recently
113 * active conversation that is not archived, made on first use.
114 */
115 export function openConversation(db: Database, userId: string): Conversation {
116 const row = db
117 .query("SELECT * FROM conversation WHERE user_id = ?1 AND archived_at IS NULL ORDER BY updated_at DESC, rowid DESC LIMIT 1")
118 .get(userId) as ConversationRow | null;
119 return row === null ? newConversation(db, userId) : conversationOf(row);
120 }
121
122 /** One of the person's conversations by id; another person's is nothing. */
123 export function getConversation(db: Database, userId: string, conversationId: string): Conversation | undefined {
124 const row = db
125 .query("SELECT * FROM conversation WHERE id = ?1 AND user_id = ?2")
126 .get(conversationId, userId) as ConversationRow | null;
127 return row === null ? undefined : conversationOf(row);
128 }
129
130 /** The person's conversations, newest activity first; `archived` picks the put-away ones instead. */
131 export function listConversations(db: Database, userId: string, opts: { readonly archived?: boolean } = {}): Conversation[] {
132 const rows = db
133 .query(
134 `SELECT * FROM conversation WHERE user_id = ?1 AND archived_at IS ${opts.archived === true ? "NOT" : ""} NULL ORDER BY updated_at DESC, rowid DESC LIMIT 200`,
135 )
136 .all(userId) as ConversationRow[];
137 return rows.map(conversationOf);
138 }
139
140 /** Give a conversation a title (1 to `TITLE_MAX` characters, no line breaks); an empty one clears it. */
141 export function renameConversation(
142 db: Database,
143 userId: string,
144 conversationId: string,
145 title: string,
146 ): Result<Conversation, "not_found" | "bad_title"> {
147 const clean = title.trim();
148 if (clean.length > TITLE_MAX || /[\u0000-\u001f\u007f]/.test(clean)) return err("bad_title");
149 const changed = db.query("UPDATE conversation SET title = ?3 WHERE id = ?1 AND user_id = ?2").run(conversationId, userId, clean).changes;
150 const found = changed === 0 ? undefined : getConversation(db, userId, conversationId);
151 return found === undefined ? err("not_found") : ok(found);
152 }
153
154 /** Put a conversation away, or bring it back (`archived` false). It keeps its turns and its URL. */
155 export function archiveConversation(
156 db: Database,
157 userId: string,
158 conversationId: string,
159 archived: boolean,
160 ): Result<Conversation, "not_found"> {
161 const changed = db
162 .query("UPDATE conversation SET archived_at = ?3 WHERE id = ?1 AND user_id = ?2")
163 .run(conversationId, userId, archived ? new Date().toISOString() : null).changes;
164 const found = changed === 0 ? undefined : getConversation(db, userId, conversationId);
165 return found === undefined ? err("not_found") : ok(found);
166 }
167
90168 const owned = (db: Database, userId: string, conversationId: string): boolean =>
91169 db
92170 .query("SELECT 1 FROM conversation WHERE id = ?1 AND user_id = ?2")
src/core/migration-pins/20261103120000-conversations-many.pin added +1
@@ -0,0 +1,1 @@
1 75aae926b6621fe4ee663d1bc8b85e2970f1e95b3ff51bb79e5b0bf113fbedc8
src/core/migrations/20261103120000-conversations-many.ts added +26
@@ -0,0 +1,26 @@
1 // Many conversations a person (#8814): the one-per-person UNIQUE goes, and a
2 // conversation gains a title and an archived mark. SQLite cannot drop a
3 // UNIQUE in place, so the table is copied; its turns and runs are held aside
4 // first because dropping the parent would cascade them away.
5 export default `
6 CREATE TEMP TABLE keep_turn AS SELECT * FROM conversation_turn ORDER BY rowid;
7 CREATE TEMP TABLE keep_run AS SELECT * FROM conversation_run;
8 CREATE TABLE conversation_next (
9 id TEXT PRIMARY KEY,
10 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
11 claude_session_id TEXT NOT NULL DEFAULT '',
12 created_at TEXT NOT NULL,
13 updated_at TEXT NOT NULL,
14 title TEXT NOT NULL DEFAULT '',
15 archived_at TEXT
16 );
17 INSERT INTO conversation_next (id, user_id, claude_session_id, created_at, updated_at)
18 SELECT id, user_id, claude_session_id, created_at, updated_at FROM conversation;
19 DROP TABLE conversation;
20 ALTER TABLE conversation_next RENAME TO conversation;
21 CREATE INDEX conversation_by_person ON conversation (user_id, updated_at);
22 INSERT INTO conversation_turn SELECT * FROM keep_turn ORDER BY rowid;
23 INSERT INTO conversation_run SELECT * FROM keep_run;
24 DROP TABLE keep_turn;
25 DROP TABLE keep_run;
26 `;
src/crew/conversation.ts +24 −18
@@ -19,7 +19,7 @@ import { chmodSync, mkdirSync } from "node:fs";
1919 import { join } from "node:path";
2020 import type { App } from "../app.ts";
2121 import { dailyLeft } from "../core/account_ceiling.ts";
22 import { appendTurn, lastExchange, listTurns, openConversation, removeTurn, restoreTurns, setAsideFrom, setClaudeSession, type Conversation } from "../core/conversations.ts";
22 import { appendTurn, getConversation, lastExchange, listTurns, openConversation, removeTurn, restoreTurns, setAsideFrom, setClaudeSession, type Conversation } from "../core/conversations.ts";
2323 import { carryWrites, forgetWrites, unended } from "../core/conversation_writes.ts";
2424 import { cancelHeld, WORDS_MAX } from "../core/fence.ts";
2525 import { thinkingOf } from "../core/talk_work.ts";
@@ -74,7 +74,8 @@ export const configureConversation = (app: App, options: ConversationOptions): v
7474 export const conversationOptions = (app: App): ConversationOptions | undefined => configured.get(app);
7575
7676 /** Whether a turn of this person's conversation is running now. */
77 export const turnRunning = (app: App, userId: string): boolean => live.has(openConversation(app.db, userId).id);
77 export const turnRunning = (app: App, userId: string, conversationId?: string): boolean =>
78 live.has(conversationId ?? openConversation(app.db, userId).id);
7879
7980 /** The one line the person sees when a restart cut their answer short. */
8081 export const RESUMED_LINE = "The forge restarted while I was answering; I am picking it up where I stopped.";
@@ -101,7 +102,7 @@ const RESUME_PROMPT =
101102 export const STOPPED_LINE = "Stopped.";
102103
103104 /** Stops for the turns running, by conversation id. */
104 const stoppers = new Map<string, { runId: string; stop: () => void }>();
105 const stoppers = new Map<string, { runId: string; userId: string; stop: () => void }>();
105106
106107 /**
107108 * Stop the person's running turn: the agent's process group ends (and every
@@ -109,13 +110,16 @@ const stoppers = new Map<string, { runId: string; stop: () => void }>();
109110 * Confirm is cancelled, never applied. False when no turn runs.
110111 */
111112 export function stopTurn(app: App, userId: string): boolean {
112 const conversation = openConversation(app.db, userId);
113 const stop = stoppers.get(conversation.id)?.stop;
114 if (stop === undefined) return false;
115 // Cancelled first: no Confirm may land while the process is going down.
116 cancelHeld(app.db, `conversation:${conversation.id}`);
117 stop();
118 return true;
113 let stopped = false;
114 // Every turn the person has running, whichever conversation it is in.
115 for (const [conversationId, running] of stoppers) {
116 if (running.userId !== userId) continue;
117 // Cancelled first: no Confirm may land while the process is going down.
118 cancelHeld(app.db, `conversation:${conversationId}`);
outdated

Stop only covers the first 200 per list, and does N queries. Find the person's running conversation ids directly (stoppers keyed by conversation id, checked for ownership) and add a two-conversation test.

119 running.stop();
120 stopped = true;
121 }
122 return stopped;
119123 }
120124
121125 /** Turns with a session listening, by conversation id: the run id a message is steered to. */
@@ -191,7 +195,7 @@ export function mcpConfig(localUrl: string): string {
191195 });
192196 }
193197
194 export type SayRefusal = "unauthorized" | "empty" | "too_long" | "no_account" | "resting" | "busy";
198 export type SayRefusal = "not_found" | "unauthorized" | "empty" | "too_long" | "no_account" | "resting" | "busy";
195199
196200 export interface Said {
197201 /** `started` a new turn, or `steered` one already running. */
@@ -201,12 +205,13 @@ export interface Said {
201205 }
202206
203207 /** Store a person's message and answer it: steer the turn that runs, or start one. */
204 export function say(app: App, options: ConversationOptions, userId: string, text: string): Result<Said, SayRefusal> {
208 export function say(app: App, options: ConversationOptions, userId: string, text: string, conversationId?: string): Result<Said, SayRefusal> {
205209 const user = getUserById(app.db, userId);
206210 if (user === undefined) return err("unauthorized");
207211 if (text.trim() === "") return err("empty");
208212 if (text.length > WORDS_MAX) return err("too_long");
209 const conversation = openConversation(app.db, userId);
213 const conversation = conversationId === undefined ? openConversation(app.db, userId) : getConversation(app.db, userId, conversationId);
214 if (conversation === undefined) return err("not_found");
210215 const stored = appendTurn(app.db, userId, conversation.id, { role: "person", text });
211216 if (!stored.ok) return err("too_long");
212217 const running = live.get(conversation.id);
@@ -233,10 +238,11 @@ export type RedoRefusal = SayRefusal | "running" | "nothing";
233238 * starts a fresh session whose context is the turns that still stand. Refused
234239 * while a turn runs, or when the last exchange is not what the action is for.
235240 */
236 export function redo(app: App, options: ConversationOptions, userId: string, how: RedoHow, text = ""): Result<Said, RedoRefusal> {
241 export function redo(app: App, options: ConversationOptions, userId: string, how: RedoHow, text = "", conversationId?: string): Result<Said, RedoRefusal> {
237242 const user = getUserById(app.db, userId);
238243 if (user === undefined) return err("unauthorized");
239 const conversation = openConversation(app.db, userId);
244 const conversation = conversationId === undefined ? openConversation(app.db, userId) : getConversation(app.db, userId, conversationId);
245 if (conversation === undefined) return err("not_found");
240246 if (live.has(conversation.id)) return err("running");
241247 const { person, after } = lastExchange(app.db, userId, conversation.id);
242248 if (person === undefined) return err("nothing");
@@ -287,8 +293,8 @@ export function resumeInterrupted(app: App, options: ConversationOptions): Promi
287293 carryWrites(app.db, `conversation:${row.conversation_id}`);
288294 app.db.query("UPDATE conversation_run SET state = 'failed', finished_at = ?2 WHERE id = ?1").run(row.id, new Date().toISOString());
289295 if (row.resumes >= 1) continue;
290 const conversation = openConversation(app.db, row.user_id);
291 if (conversation.id !== row.conversation_id) continue;
296 const conversation = getConversation(app.db, row.user_id, row.conversation_id);
297 if (conversation === undefined) continue;
292298 appendTurn(app.db, row.user_id, conversation.id, { role: "agent", text: RESUMED_LINE });
293299 // A write begun and not reported is shown, not retried: the person decides.
294300 if (unknown.length > 0) appendTurn(app.db, row.user_id, conversation.id, { role: "agent", text: unendedLine(unknown) });
@@ -357,7 +363,7 @@ function begin(
357363 .run(runId, conversation.id, userId, subscriptionId, prompt, resumes, resumeSession ?? "", now.toISOString());
358364 live.set(conversation.id, runId);
359365 const stopper = new AbortController();
360 stoppers.set(conversation.id, { runId, stop: () => stopper.abort() });
366 stoppers.set(conversation.id, { runId, userId, stop: () => stopper.abort() });
361367 const signal = AbortSignal.any([options.signal, stopper.signal]);
362368 const put = (role: "agent" | "tool", text: string): void => {
363369 const stored = appendTurn(app.db, userId, conversation.id, { role, text: text.slice(0, 20_000) });
src/http/api/conversation_talk.ts +70 −4
@@ -8,10 +8,23 @@
88 */
99
1010 import { stopTalk, TALK_WORDS, talk } from "../../actions/talk.ts";
11 import { DEFAULT_PAGE, listTurns, MAX_PAGE, openConversation } from "../../core/conversations.ts";
11 import {
12 archiveConversation,
13 createConversation,
14 DEFAULT_PAGE,
15 getConversation,
16 listConversations,
17 listTurns,
18 MAX_PAGE,
19 openConversation,
20 renameConversation,
21 TITLE_MAX,
22 TOO_MANY_WORDS,
23 } from "../../core/conversations.ts";
1224 import { WORDS_MAX } from "../../core/fence.ts";
1325 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1426 import { scopeAllows } from "../../core/tokens.ts";
27 import type { User } from "../../core/users.ts";
1528 import { worksOf } from "../../core/talk_work.ts";
1629 import { turnRunning } from "../../crew/conversation.ts";
1730 import { crossOrigin, type Handler } from "../context.ts";
@@ -41,7 +54,9 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
4154 const text = input["text"];
4255 if (typeof text !== "string" || text.trim() === "" || text.length > WORDS_MAX)
4356 return apiError("invalid_text", 422, `text is a string of 1 to ${WORDS_MAX} characters`);
44 const said = talk(ctx.app, user, text);
57 const named = input["conversation"];
58 if (named !== undefined && (typeof named !== "string" || !ID.test(named))) return apiError("not_found", 404, "no such conversation");
59 const said = talk(ctx.app, user, text, named);
4560 if (!said.ok) {
4661 const [status, words] = TALK_WORDS[said.error];
4762 return json({ error: said.error, message: words }, status, said.error === "rate_limited" || said.error === "busy" ? { "retry-after": "60" } : {});
@@ -63,7 +78,9 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
6378 const user = ctx.auth.user;
6479 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
6580 if (user === undefined) return unauthorized();
66 const conversation = openConversation(ctx.app.db, user.id);
81 const named = ctx.url.searchParams.get("conversation");
82 const conversation = named === null ? openConversation(ctx.app.db, user.id) : getConversation(ctx.app.db, user.id, named);
83 if (conversation === undefined) return apiError("not_found", 404, "no such conversation");
6784 const turns = listTurns(ctx.app.db, user.id, conversation.id, {
6885 limit: turnsLimit(ctx.url.searchParams.get("limit")),
6986 ...(ctx.url.searchParams.get("before") ? { before: ctx.url.searchParams.get("before")! } : {}),
@@ -72,6 +89,55 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
7289 const all = turns.ok ? turns.value : [];
7390 const works = worksOf(ctx.app.db, user.id, conversation.id, all);
7491 const shown = all.map((t) => (t.role === "agent" ? { ...t, work: works.get(t.id) ?? null } : t));
75 return json({ running: turnRunning(ctx.app, user.id), turns: shown });
92 return json({ running: turnRunning(ctx.app, user.id, conversation.id), conversation: conversation.id, turns: shown });
93 });
94
95 router.add("GET", "/api/v1/conversations", (ctx) => {
96 const user = ctx.auth.user;
97 if (user === undefined) return unauthorized();
98 return json({ conversations: listConversations(ctx.app.db, user.id, { archived: ctx.url.searchParams.get("archived") === "1" }) });
99 });
100
101 router.add("POST", "/api/v1/conversations", async (ctx) => {
102 const user = mayChange(ctx);
103 if (user instanceof Response) return user;
104 const input = await boundedBody(ctx.request, 4_000);
105 if (input === "too_large") return apiError("too_large", 413, "at most 4000 bytes");
106 const title = input["title"];
107 if (title !== undefined && typeof title !== "string") return apiError("invalid_title", 422, TITLE_WORDS);
108 const started = createConversation(ctx.app.db, user.id);
109 if (!started.ok) return apiError("too_many", 409, TOO_MANY_WORDS);
110 const made = started.value;
111 if (title === undefined || title.trim() === "") return json({ conversation: made }, 201);
112 const named = renameConversation(ctx.app.db, user.id, made.id, title);
113 return named.ok ? json({ conversation: named.value }, 201) : apiError("invalid_title", 422, TITLE_WORDS);
114 });
115
116 router.add("PATCH", "/api/v1/conversations/:id", async (ctx) => {
117 const user = mayChange(ctx);
118 if (user instanceof Response) return user;
119 const id = ctx.params["id"] ?? "";
120 if (!ID.test(id) || getConversation(ctx.app.db, user.id, id) === undefined) return apiError("not_found", 404, "no such conversation");
121 const input = await boundedBody(ctx.request, 4_000);
122 if (input === "too_large") return apiError("too_large", 413, "at most 4000 bytes");
123 const { title, archived } = input;
124 if (title !== undefined && typeof title !== "string") return apiError("invalid_title", 422, TITLE_WORDS);
125 if (archived !== undefined && typeof archived !== "boolean") return apiError("invalid", 422, "archived is true or false");
126 if (title === undefined && archived === undefined) return apiError("invalid", 422, "send title or archived");
127 if (title !== undefined && !renameConversation(ctx.app.db, user.id, id, title).ok) return apiError("invalid_title", 422, TITLE_WORDS);
128 if (archived !== undefined) archiveConversation(ctx.app.db, user.id, id, archived);
129 return json({ conversation: getConversation(ctx.app.db, user.id, id) });
76130 });
77131 }
132
133 const ID = /^[0-9a-z]{1,40}$/;
134 const TITLE_WORDS = `title is text of at most ${TITLE_MAX} characters, on one line`;
135
136 /** The person a change is for: signed in, same-origin, and not on a read-only token. */
137 function mayChange(ctx: Parameters<Handler>[0]): User | Response {
138 const user = ctx.auth.user;
139 if (user === undefined) return unauthorized();
140 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden();
141 if (ctx.auth.via === "token" && !scopeAllows(ctx.auth.scope ?? "ro", "rw")) return forbidden();
142 return user;
143 }
src/http/mcp/tools/say.ts +31 −4
@@ -1,32 +1,59 @@
11 import { mayView } from "../../../core/sealed.ts";
22 import { addCommentThrough } from "../../../actions/issues.ts";
33 import { getIssue } from "../../../core/issues.ts";
4 import { archiveConversation, createConversation, getConversation, listConversations, renameConversation, TOO_MANY_WORDS } from "../../../core/conversations.ts";
45 import { talk, TALK_WORDS } from "../../../actions/talk.ts";
56 import { WORDS_MAX } from "../../../core/fence.ts";
67 import { good, bad, type Tool, str, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
78
89 export const tool: Tool = {
910 name: "say",
10 doc: "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`",
11 doc: "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 | new | rename | archive | restore manages them (`title` for rename and new)",
1112 description:
12 "Say something on an issue or pull; with no repo, to the forge's own agent.",
13 "Say something on an issue or pull; with no repo, to the forge's own agent, and manage its conversations (action).",
1314 inputSchema: {
1415 type: "object",
1516 properties: {
1617 repo: REPO_ARG,
1718 number: { type: "integer", minimum: 1 },
1819 text: { type: "string", maxLength: 8000 },
20 conversation: { type: "string" },
21 action: { type: "string", enum: ["list", "new", "rename", "archive", "restore"] },
22 title: { type: "string", maxLength: 80 },
1923 },
20 required: ["text"],
2124 },
2225 writes: true,
2326 async run(ctx, user, args) {
2427 if (args["repo"] === undefined && args["number"] === undefined) {
2528 // The forge's own agent never wakes itself: its via token is refused.
2629 if (ctx.auth.through !== undefined) return bad("forbidden", "the forge's agent cannot start its own turn");
30 const db = ctx.app.db;
31 const action = args["action"];
32 if (action === "list") return good({ conversations: listConversations(db, user.id).map(({ id, title, updatedAt }) => ({ id, title, updatedAt })) });
33 if (action === "new") {
34 const started = createConversation(db, user.id);
35 if (!started.ok) return bad("too_many", TOO_MANY_WORDS);
36 const made = started.value;
37 const title = str(args["title"]);
38 if (title !== "" && !renameConversation(db, user.id, made.id, title).ok) return bad("invalid_title", "title is up to 80 characters, on one line");
39 return good({ conversation: made.id, says: "Started; send text with this conversation to speak in it. It opens at /talk/" + made.id + "." });
40 }
41 if (action !== undefined) {
42 const target = getConversation(db, user.id, str(args["conversation"]));
43 if (target === undefined) return bad("not_found", "no such conversation of yours");
outdated

rename without a title quietly clears the title (str(undefined) is empty). Require a title for rename.

44 if (action === "rename") {
45 if (typeof args["title"] !== "string") return bad("invalid_title", "rename needs a title");
46 const named = renameConversation(db, user.id, target.id, args["title"]);
47 return named.ok ? good({ says: "Renamed." }) : bad("invalid_title", "title is up to 80 characters, on one line");
48 }
49 if (action !== "archive" && action !== "restore") return bad("invalid", "action is list, new, rename, archive or restore");
50 archiveConversation(db, user.id, target.id, action === "archive");
51 return good({ says: action === "archive" ? "Archived." : "Restored." });
52 }
2753 const text = str(args["text"]);
2854 if (text.trim() === "" || text.length > WORDS_MAX) return bad("invalid_text", `text is 1 to ${WORDS_MAX} characters`);
29 const talked = talk(ctx.app, user, text);
55 const named = args["conversation"] === undefined ? undefined : str(args["conversation"]);
56 const talked = talk(ctx.app, user, text, named);
3057 if (!talked.ok) return bad(talked.error, TALK_WORDS[talked.error][1]);
3158 return good({ says: talked.value.how === "steered" ? "Said to the forge's agent, mid-answer." : "The forge's agent is answering; read it in GET /api/v1/conversation/turns." });
3259 }
src/http/server.ts +7 −1
@@ -124,7 +124,7 @@ import {
124124 verifyPage,
125125 themeSubmit,
126126 } from "../web/pages/site.ts";
127 import { talkAgainSend, talkConfirm, talkSend, talkStream, talkView } from "../web/pages/talk.ts";
127 import { talkAgainSend, talkArchive, talkConfirm, talkNew, talkRename, talkSend, talkStream, talkView } from "../web/pages/talk.ts";
128128 import {
129129 recoverFinish,
130130 recoverOptions,
@@ -843,6 +843,12 @@ export function buildRouter(): Router<Handler> {
843843 router.add("GET", "/talk/stream", talkStream);
844844 router.add("POST", "/talk/again/:how", talkAgainSend);
845845 router.add("POST", "/talk/confirm/:id", talkConfirm);
846 router.add("POST", "/talk/new", talkNew);
847 router.add("GET", "/talk/:id", talkView);
848 router.add("POST", "/talk/:id", talkSend);
849 router.add("POST", "/talk/:id/rename", talkRename);
850 router.add("POST", "/talk/:id/archive", talkArchive);
851 router.add("POST", "/talk/:id/again/:how", talkAgainSend);
846852 router.add("POST", "/signin/passkey/options", signinOptions);
847853 router.add("POST", "/signin/passkey", signinPasskey);
848854 router.add("GET", "/recover", recoverPage);
src/tui/forge.ts +9
@@ -50,6 +50,7 @@ import { usageScreen } from "./screens/usage.ts";
5050 import { canScreen } from "./screens/can.ts";
5151 import { modelScreen } from "./screens/model.ts";
5252 import { notifyScreen } from "./screens/notify.ts";
53 import { talkChatsScreen } from "./screens/talk_chats.ts";
5354 import { sshKeysScreen } from "./screens/sshkeys.ts";
5455 import { passkeysScreen } from "./screens/passkeys.ts";
5556 import { confirmsScreen } from "./screens/confirms.ts";
@@ -307,6 +308,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
307308 hint: "what the forge's agent asked to do; y does it once",
308309 run: () => ctx.push(confirmsScreen(session, ctx)),
309310 });
311 // The forge's agent keeps many conversations, as /talk lists them (#8814).
312 if (session.signedIn && session.user?.kind !== "agent")
313 commands.push({
314 id: "conversations",
315 title: "Conversations",
316 hint: "your talks with the forge's agent; n starts one, r renames, x archives",
317 run: () => ctx.push(talkChatsScreen(session, ctx)),
318 });
310319 if (session.signedIn)
311320 commands.push({
312321 id: "ssh-keys",
src/tui/screens/talk_chats.ts added +199
@@ -0,0 +1,199 @@
1 /**
2 * Talk conversations in the terminal (#8814): the same list, New, Rename and
3 * Archive/Restore /talk has, through the same `core/conversations.ts` calls,
4 * so a change here is the next thing a web viewer's list or stream reads.
5 * `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()`.
7 */
8
9 import { TALK_WORDS, talk } from "../../actions/talk.ts";
10 import {
11 archiveConversation,
12 createConversation,
13 listConversations,
14 listTurns,
15 renameConversation,
16 TITLE_MAX,
17 TOO_MANY_WORDS,
18 type Conversation,
19 } from "../../core/conversations.ts";
20 import type { Ctx, Screen } from "../app/app.ts";
21 import { binding } from "../app/keys.ts";
22 import { style } from "../term/style.ts";
23 import { truncate, wrap } from "../term/width.ts";
24 import type { Session } from "../session.ts";
25 import { fill, len, split } from "../ui/layout.ts";
26 import { ListState, Scroll, ago, drawLines, drawList, promptScreen, type ListRow } from "./common.ts";
27
28 const BAD_TITLE = `A title is up to ${TITLE_MAX} characters, on one line.`;
29
30 const WHO: Readonly<Record<string, string>> = { person: "You", agent: "Forge", tool: "Tool", confirm: "Asks" };
31
32 /** One conversation, newest turns last: j/k scroll, s says something in it, r reloads. */
33 function chatScreen(f: Session, ctx: Ctx, chat: Conversation): Screen {
34 const scroll = new Scroll();
35 let note = "";
36 let width = 80;
37 // Opened, and after r, the view sits on the newest turns.
38 let follow = true;
39 const lines = (): { text: string; style: ReturnType<typeof style> }[][] => {
40 const c = ctx.theme.c;
41 const listed = f.user === undefined ? undefined : listTurns(f.app.db, f.user.id, chat.id, { limit: 50 });
42 const turns = listed?.ok ? listed.value : [];
43 if (turns.length === 0) return [[{ text: "Nothing said yet; s says something.", style: style(c.mutedFg, c.bg) }]];
44 return turns.flatMap((t) => [
45 [{ text: `${WHO[t.role] ?? t.role}${t.replaced ? " · replaced" : ""} · ${ago(t.createdAt)}`, style: style(c.mutedFg, c.bg) }],
46 ...t.text.split("\n").flatMap((l) => wrap(l, Math.max(10, width - 2))).map((l) => [{ text: l, style: style(c.fg, c.bg) }]),
47 [],
48 ]);
49 };
50 const screen: Screen = {
51 get title() {
52 return chat.title === "" ? "Untitled conversation" : chat.title;
53 },
54 keys: [binding(["j", "k"], "scroll"), binding(["s"], "say"), binding(["r"], "reload"), binding(["esc"], "back")],
55 render(area, s) {
56 const c = ctx.theme.c;
57 width = area.w;
58 const [head, body] = split(area, "v", [len(1), fill(1)]);
59 const text = note !== "" ? note : `/talk/${chat.id}${chat.archivedAt === null ? "" : " · archived: sending does not bring it back"}`;
60 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
61 const all = lines();
62 if (follow) scroll.to(all.length - body!.h, all.length);
63 drawLines(s, body!, c, scroll, all);
64 },
65 key(e) {
66 if (scroll.key(e, lines().length)) {
67 follow = false;
68 return true;
69 }
70 const user = f.user;
71 if (user === undefined || e.ctrl || e.alt) return false;
72 if (e.key === "esc" || e.key === "q") {
73 ctx.pop();
74 return true;
75 }
76 if (e.key === "r") {
77 note = "";
78 follow = true;
79 ctx.invalidate();
80 return true;
81 }
82 if (e.key === "s") {
83 ctx.push(
84 promptScreen(ctx, screen, {
85 title: "Say",
86 label: "to the forge, in this conversation",
87 onSubmit: (words) => {
88 const said = talk(f.app, user, words, chat.id);
89 if (!said.ok) return TALK_WORDS[said.error][1];
90 note = "Sent; r reloads to see the answer.";
91 ctx.invalidate();
92 return undefined;
93 },
94 }),
95 );
96 return true;
97 }
98 return false;
99 },
100 };
101 return screen;
102 }
103
104 export function talkChatsScreen(f: Session, ctx: Ctx): Screen {
105 const state = new ListState();
106 let archived = false;
107 let note = "";
108 const items = (): Conversation[] => (f.user === undefined ? [] : listConversations(f.app.db, f.user.id, { archived }));
109 const rows = (): ListRow[] =>
110 items().map((c) => ({ title: c.title === "" ? "Untitled" : c.title, secondary: `/talk/${c.id}`, meta: `active ${ago(c.updatedAt)}` }));
111 const say = (text: string): void => {
112 note = text;
113 ctx.invalidate();
114 };
115
116 const screen: Screen = {
117 get title() {
118 return archived ? "Archived conversations" : "Conversations";
119 },
120 keys: [
121 binding(["j", "k"], "move cursor"),
122 binding(["enter"], "open"),
123 binding(["n"], "new"),
124 binding(["r"], "rename"),
125 binding(["x"], "archive or restore"),
126 binding(["a"], "archived"),
127 ],
128 render(area, s) {
129 const c = ctx.theme.c;
130 const [head, body] = split(area, "v", [len(1), fill(1)]);
131 const text =
132 note !== ""
133 ? note
134 : items().length === 0
135 ? archived ? "Nothing archived." : "No conversations yet; n starts one."
136 : archived ? "Archived; x brings one back." : "Your talks with the forge's agent; each opens at its /talk address.";
137 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
138 drawList(s, body!, c, state, rows());
139 },
140 key(e) {
141 if (state.key(e, items().length)) return true;
142 const user = f.user;
143 if (user === undefined || e.ctrl || e.alt) return false;
144 const here = items()[state.index];
145 if (e.key === "a") {
146 archived = !archived;
147 state.index = 0;
148 note = "";
149 ctx.invalidate();
150 return true;
151 }
152 if (e.key === "n") {
153 ctx.push(
154 promptScreen(ctx, screen, {
155 title: "New conversation",
156 label: "a title (optional)",
157 onSubmit: (title) => {
158 const made = createConversation(f.app.db, user.id);
159 if (!made.ok) return TOO_MANY_WORDS;
160 if (title.trim() !== "" && !renameConversation(f.app.db, user.id, made.value.id, title).ok) return BAD_TITLE;
161 archived = false;
162 state.index = 0;
163 say(`Started /talk/${made.value.id}.`);
164 return undefined;
165 },
166 }),
167 );
168 return true;
169 }
170 if (here === undefined) return false;
171 if (e.key === "enter") {
172 ctx.push(chatScreen(f, ctx, here));
173 return true;
174 }
175 if (e.key === "r") {
176 ctx.push(
177 promptScreen(ctx, screen, {
178 title: "Rename conversation",
179 label: "a title (empty clears it)",
180 value: here.title,
181 onSubmit: (title) => {
182 if (!renameConversation(f.app.db, user.id, here.id, title).ok) return BAD_TITLE;
183 say("Renamed.");
184 return undefined;
185 },
186 }),
187 );
188 return true;
189 }
190 if (e.key === "x") {
191 archiveConversation(f.app.db, user.id, here.id, !archived);
192 say(archived ? "Restored." : "Archived.");
193 return true;
194 }
195 return false;
196 },
197 };
198 return screen;
199 }
src/web/pages/talk.ts +153 −33
@@ -17,7 +17,23 @@
1717 import type { Database } from "bun:sqlite";
1818 import { TALK_WORDS, talk, talkAgain } from "../../actions/talk.ts";
1919 import { REFUSED, sayNo, sayYes, waitingConfirms } from "../../actions/conversation_confirms.ts";
20 import { DEFAULT_PAGE, lastExchange, listTurns, MAX_PAGE, openConversation, turnsAfter, type Turn } from "../../core/conversations.ts";
20 import {
21 archiveConversation,
22 type Conversation,
23 DEFAULT_PAGE,
24 lastExchange,
25 getConversation,
26 listConversations,
27 listTurns,
28 MAX_PAGE,
29 createConversation,
30 TOO_MANY_WORDS,
31 openConversation,
32 renameConversation,
33 TITLE_MAX,
34 turnsAfter,
35 type Turn,
36 } from "../../core/conversations.ts";
2137 import { contextOf, contextText, dollars, turnCosts, type Context } from "../../core/conversation_cost.ts";
2238 import { WORDS_MAX } from "../../core/fence.ts";
2339 import { thinkingOf, worksOf, type Work } from "../../core/talk_work.ts";
@@ -27,10 +43,10 @@ import { turnRunning, type RedoHow } from "../../crew/conversation.ts";
2743 import type { Ctx } from "../../http/context.ts";
2844 import { json } from "../../http/respond.ts";
2945 import { eventStream } from "../../http/sse.ts";
30 import { signInFirst, forbiddenPage } from "../chrome.ts";
46 import { signInFirst, forbiddenPage, notFoundPage } from "../chrome.ts";
3147 import { readForm } from "../form.ts";
3248 import { html, type Html } from "../html.ts";
33 import { flashTo, page } from "../layout.ts";
49 import { flashTo, page, redirect } from "../layout.ts";
3450 import { renderMarkdown } from "../markdown.ts";
3551 import { btn, time } from "../ui.ts";
3652 import { talkCss, talkJs } from "./talk_client.ts";
@@ -46,6 +62,12 @@ export const clock = { streamMs: STREAM_MS, running: turnRunning };
4662 const open = new Map<string, number>();
4763 const TURN_ID = /^[0-9a-z]{0,40}$/;
4864 const HERE = "/talk";
65 const CONVERSATION_ID = /^[0-9a-z]{1,40}$/;
66
67 /** What a conversation is called in a list: its title, else the day it began. */
68 const nameOf = (c: Conversation): string => (c.title === "" ? `Chat of ${c.createdAt.slice(0, 10)}` : c.title);
69 /** Where a conversation lives. */
70 const urlOf = (c: Conversation): string => `${HERE}/${c.id}`;
4971
5072 const parse = (text: string): Record<string, unknown> | undefined => {
5173 try {
@@ -87,23 +109,23 @@ const workHtml = (work: Work): Html =>
87109 const SUGGESTIONS = ["What needs my attention?", "What did the crew do today?", "Show me my apps"] as const;
88110
89111 /** Ask again as a form, so it works without the script; the script only enhances it. */
90 const againForm = (how: "regenerate" | "retry", label: string, words: string): Html =>
91 html`<form method="post" action="${HERE}/again/${how}" data-again="${how}">${btn(label, { icon: "sync", label: words })}</form>`;
112 const againForm = (base: string, how: "regenerate" | "retry", label: string, words: string): Html =>
113 html`<form method="post" action="${base}/again/${how}" data-again="${how}">${btn(label, { icon: "sync", label: words })}</form>`;
92114
93115 /**
94116 * What the last exchange offers, by the turn it sits under: Edit under the
95117 * person's last message, and under the last turn Retry when it failed or
96118 * Regenerate when it is a reply. Nothing while a turn runs.
97119 */
98 export function exchangeActs(db: Database, userId: string, conversationId: string, running: boolean): Map<string, Html> {
120 export function exchangeActs(db: Database, userId: string, conversationId: string, running: boolean, base: string = HERE): Map<string, Html> {
99121 const acts = new Map<string, Html>();
100122 if (running) return acts;
101123 const { person, after } = lastExchange(db, userId, conversationId);
102124 if (person === undefined) return acts;
103 acts.set(person.id, html`<a class="btn talk-act" href="${HERE}?edit=1#compose" data-act="edit" aria-label="Edit your last message">Edit</a>`);
125 acts.set(person.id, html`<a class="btn talk-act" href="${base}?edit=1#compose" data-act="edit" aria-label="Edit your last message">Edit</a>`);
104126 const last = after.at(-1);
105 if (last?.failed === true) acts.set(last.id, againForm("retry", "Retry", "Retry the failed turn"));
106 else if (last?.role === "agent") acts.set(last.id, againForm("regenerate", "Regenerate", "Regenerate the last reply"));
127 if (last?.failed === true) acts.set(last.id, againForm(base, "retry", "Retry", "Retry the failed turn"));
128 else if (last?.role === "agent") acts.set(last.id, againForm(base, "regenerate", "Regenerate", "Regenerate the last reply"));
107129 return acts;
108130 }
109131
@@ -159,47 +181,88 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: number
159181 return toolCard(id, call, call.split(/[\s(:{]/, 1)[0] ?? "tool", turn.createdAt, set);
160182 }
161183
162 function talkPage(ctx: Ctx, before: string | undefined, prefill: string, edit: boolean): Response {
184 /** The conversations list, then this one's name with Rename and Archive: each a plain form, so none needs the script. */
185 function chats(ctx: Ctx, conversation: Conversation, showArchived: boolean): Html {
163186 const user = ctx.auth.user!;
164 const conversation = openConversation(ctx.app.db, user.id);
187 const shown = listConversations(ctx.app.db, user.id, { archived: showArchived });
188 const put = listConversations(ctx.app.db, user.id, { archived: !showArchived }).length;
189 const archived = conversation.archivedAt !== null;
190 return html`<nav class="talk-chats" aria-label="Conversations">
191 <div class="bar">
192 <form method="post" action="${HERE}/new">${btn("New", { icon: "plus", label: "New conversation" })}</form>
193 <span class="spacer"></span>
194 ${showArchived
195 ? html`<a class="small" href="${HERE}">Back to conversations</a>`
196 : put > 0
197 ? html`<a class="small" href="${HERE}?archived=1">Archived (${put})</a>`
198 : null}
199 </div>
200 <ul>
201 ${shown.length === 0
202 ? html`<li class="muted small">${showArchived ? "Nothing archived." : "No conversations yet."}</li>`
203 : shown.map((c) => html`<li ${c.id === conversation.id ? html`aria-current="page"` : null}><a href="${urlOf(c)}"><span>${nameOf(c)}</span><span class="muted small">${time(c.updatedAt)}</span></a></li>`)}
204 </ul>
205 </nav>
206 <div class="talk-here bar">
207 <strong>${nameOf(conversation)}${archived ? " (archived)" : ""}</strong>
208 <details>
209 <summary class="small">Rename</summary>
210 <form method="post" action="${urlOf(conversation)}/rename">
211 <input class="input" name="title" value="${conversation.title}" maxlength="${TITLE_MAX}" aria-label="Title" placeholder="Title" />
212 ${btn("Save")}
213 </form>
214 </details>
215 <form method="post" action="${urlOf(conversation)}/archive">
216 <input type="hidden" name="archived" value="${archived ? "0" : "1"}" />
217 ${btn(archived ? "Restore" : "Archive")}
218 </form>
219 </div>`;
220 }
221
222 function talkPage(ctx: Ctx, conversation: Conversation, before: string | undefined, prefill: string, latest: boolean, edit: boolean): Response {
223 const user = ctx.auth.user!;
224 const here = latest ? HERE : urlOf(conversation);
225 const showArchived = latest && ctx.url.searchParams.get("archived") === "1";
165226 const listed = listTurns(ctx.app.db, user.id, conversation.id, {
166227 limit: DEFAULT_PAGE,
167228 ...(before === undefined ? {} : { before }),
168229 });
169230 const turns = listed.ok ? listed.value : [];
170231 const waiting = new Set(waitingConfirms(ctx, user).map((w) => w.id));
171 const running = clock.running(ctx.app, user.id);
232 const running = clock.running(ctx.app, user.id, conversation.id);
172233 const costs = turnCosts(ctx.app.db, conversation.id);
173234 const context = contextOf(ctx.app.db, conversation.id);
174235 const works = worksOf(ctx.app.db, user.id, conversation.id, turns);
175236 // Paging back, the log ends before the newest turn: it does not follow.
176237 const last = turns.at(-1)?.id ?? "";
177 const acts = before === undefined ? exchangeActs(ctx.app.db, user.id, conversation.id, running) : new Map<string, Html>();
238 const acts = before === undefined ? exchangeActs(ctx.app.db, user.id, conversation.id, running, here) : new Map<string, Html>();
178239 // Edit shows the composer holding the last message, posting to Edit instead of Send.
179240 const editing = edit ? lastExchange(ctx.app.db, user.id, conversation.id).person : undefined;
180241 const body = html`<div class="page-head"><h1>Talk</h1></div>
181 <div class="talk" data-talk data-user="${user.id}" data-paged="${before === undefined ? "0" : "1"}" data-running="${running && before === undefined ? "1" : "0"}">
242 ${chats(ctx, conversation, showArchived)}
243 <div class="talk" data-talk data-user="${user.id}" data-c="${conversation.id}" data-here="${here}" data-paged="${before === undefined ? "0" : "1"}" data-running="${running && before === undefined ? "1" : "0"}">
182244 <div>
183245 ${contextLine(context)}
184246 ${turns.length === DEFAULT_PAGE && turns[0] !== undefined
185 ? html`<p class="talk-more small"><a href="${HERE}?before=${turns[0].id}">Earlier</a></p>`
247 ? html`<p class="talk-more small"><a href="${here}?before=${turns[0].id}">Earlier</a></p>`
186248 : null}
187 ${before === undefined ? null : html`<p class="talk-more small"><a href="${HERE}">Latest</a></p>`}
249 ${before === undefined ? null : html`<p class="talk-more small"><a href="${here}">Latest</a></p>`}
188250 <ol class="talk-log" role="log" data-last="${last}" aria-label="Conversation with the forge">
189251 ${turns.length === 0
190252 ? 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.
191 <span class="talk-suggest">${SUGGESTIONS.map((q) => html`<a class="btn" href="${HERE}?q=${encodeURIComponent(q)}" data-suggest="${q}">${q}</a>`)}</span></li>`
253 <span class="talk-suggest">${SUGGESTIONS.map((q) => html`<a class="btn" href="${here}?q=${encodeURIComponent(q)}" data-suggest="${q}">${q}</a>`)}</span></li>`
192254 : turns.map((t) => turnHtml(t, waiting, costs.get(t.id), acts.get(t.id), works.get(t.id)))}
193255 </ol>
194256 <div id="end"></div>
195257 </div>
196 <form class="talk-compose" id="compose" method="post" action="${editing === undefined ? HERE : `${HERE}/again/edit`}" ${editing === undefined ? null : html`data-edit`}>
258 <form class="talk-compose" id="compose" method="post" action="${editing === undefined ? here : `${here}/again/edit`}" ${editing === undefined ? null : html`data-edit`}>
259 ${conversation.archivedAt === null ? null : html`<p class="small muted" data-archived-note>Archived: sending here keeps it archived; Restore puts it back in the list.</p>`}
197260 <p class="talk-status small muted" role="status" aria-live="polite">${running ? "The forge is answering…" : ""}</p>
198261 <textarea class="input" name="text" rows="1" maxlength="${WORDS_MAX}" required placeholder="Talk to the forge" aria-label="Talk to the forge">${editing === undefined ? prefill : editing.text}</textarea>
199262 <div class="bar">
200263 <span class="muted small" data-hint></span>
201264 <span class="spacer"></span>
202 ${editing === undefined ? null : html`<a class="btn" href="${HERE}">Keep as it was</a>`}
265 ${editing === undefined ? null : html`<a class="btn" href="${here}">Keep as it was</a>`}
203266 ${btn(editing === undefined ? "Send" : "Resend", { variant: "primary" })}
204267 </div>
205268 </form>
@@ -207,32 +270,83 @@ function talkPage(ctx: Ctx, before: string | undefined, prefill: string, edit: b
207270 return page({ ctx, title: "Talk", body, styleCss: talkCss, scriptJs: talkJs, description: "Talk to the forge." });
208271 }
209272
210 // GET /talk
273 /** The conversation a request names (`:id`), or the person's latest when it names none; undefined when it is not theirs. */
274 const conversationOf = (ctx: Ctx, user: { readonly id: string }): Conversation | undefined => {
275 const named = ctx.params["id"];
276 if (named === undefined) return openConversation(ctx.app.db, user.id);
277 return CONVERSATION_ID.test(named) ? getConversation(ctx.app.db, user.id, named) : undefined;
278 };
279
280 // GET /talk and GET /talk/:id
211281 export function talkView(ctx: Ctx): Response {
212282 if (ctx.auth.user === undefined) return signInFirst(ctx);
213283 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
214284 const before = ctx.url.searchParams.get("before");
215285 const q = ctx.url.searchParams.get("q");
216 return timePhase(ctx.request, "render", () => talkPage(ctx, before !== null && TURN_ID.test(before) && before !== "" ? before : undefined, q !== null && SUGGESTIONS.some((s) => s === q) ? q : "", ctx.url.searchParams.get("edit") === "1" && before === null));
286 const conversation = conversationOf(ctx, ctx.auth.user);
287 if (conversation === undefined) return notFoundPage(ctx);
288 return timePhase(ctx.request, "render", () =>
289 talkPage(ctx, conversation, before !== null && TURN_ID.test(before) && before !== "" ? before : undefined, q !== null && SUGGESTIONS.some((s) => s === q) ? q : "", ctx.params["id"] === undefined, ctx.url.searchParams.get("edit") === "1" && before === null),
290 );
217291 }
218292
219 // POST /talk — the plain form, for a browser without the script.
293 // POST /talk and POST /talk/:id — the plain form, for a browser without the script.
220294 export async function talkSend(ctx: Ctx): Promise<Response> {
221295 const user = ctx.auth.user;
222296 if (user === undefined) return signInFirst(ctx);
223297 const form = await readForm(ctx, "rw");
224298 if (form instanceof Response) return form;
299 const conversation = conversationOf(ctx, user);
300 if (conversation === undefined) return notFoundPage(ctx);
301 const here = ctx.params["id"] === undefined ? HERE : urlOf(conversation);
225302 const text = form.get("text");
226303 if (typeof text !== "string" || text.trim() === "" || text.length > WORDS_MAX)
227 return flashTo(ctx, `${HERE}#end`, { tone: "danger", message: `Say something, up to ${WORDS_MAX} characters.` });
228 const said = talk(ctx.app, user, text);
229 if (!said.ok) return flashTo(ctx, `${HERE}#end`, { tone: "danger", message: TALK_WORDS[said.error][1] });
230 return flashTo(ctx, `${HERE}#end`, { tone: "success", message: "Sent. Reload to see the answer." });
304 return flashTo(ctx, `${here}#end`, { tone: "danger", message: `Say something, up to ${WORDS_MAX} characters.` });
305 const said = talk(ctx.app, user, text, conversation.id);
306 if (!said.ok) return flashTo(ctx, `${here}#end`, { tone: "danger", message: TALK_WORDS[said.error][1] });
307 return flashTo(ctx, `${here}#end`, { tone: "success", message: "Sent. Reload to see the answer." });
308 }
309
310 // POST /talk/new — an empty conversation, opened at its own URL.
311 export async function talkNew(ctx: Ctx): Promise<Response> {
312 const user = ctx.auth.user;
313 if (user === undefined) return signInFirst(ctx);
314 const form = await readForm(ctx, "rw");
315 if (form instanceof Response) return form;
316 const made = createConversation(ctx.app.db, user.id);
317 if (!made.ok) return flashTo(ctx, HERE, { tone: "danger", message: `Not started: ${TOO_MANY_WORDS}.` });
318 return redirect(urlOf(made.value));
319 }
320
321 // POST /talk/:id/rename — the title from the form; an empty one clears it.
322 export async function talkRename(ctx: Ctx): Promise<Response> {
323 const user = ctx.auth.user;
324 if (user === undefined) return signInFirst(ctx);
325 const form = await readForm(ctx, "rw");
326 if (form instanceof Response) return form;
327 const conversation = conversationOf(ctx, user);
328 if (conversation === undefined) return notFoundPage(ctx);
329 const title = form.get("title");
330 const renamed = renameConversation(ctx.app.db, user.id, conversation.id, typeof title === "string" ? title : "\n");
331 return flashTo(ctx, urlOf(conversation), renamed.ok ? { tone: "success", message: "Renamed." } : { tone: "danger", message: `A title is up to ${TITLE_MAX} characters, on one line.` });
332 }
333
334 // POST /talk/:id/archive — archived=1 puts it away, 0 brings it back.
335 export async function talkArchive(ctx: Ctx): Promise<Response> {
336 const user = ctx.auth.user;
337 if (user === undefined) return signInFirst(ctx);
338 const form = await readForm(ctx, "rw");
339 if (form instanceof Response) return form;
340 const conversation = conversationOf(ctx, user);
341 if (conversation === undefined) return notFoundPage(ctx);
342 const archive = form.get("archived") !== "0";
343 archiveConversation(ctx.app.db, user.id, conversation.id, archive);
344 return flashTo(ctx, archive ? HERE : urlOf(conversation), { tone: "success", message: archive ? "Archived. It is under Archived." : "Restored." });
231345 }
232346
233347 const AGAIN: readonly RedoHow[] = ["edit", "regenerate", "retry"];
234348
235 // POST /talk/again/:how — edit and resend the last message, regenerate the last reply, retry a failed turn.
349 // POST /talk/again/:how and POST /talk/:id/again/:how — edit and resend the last message, regenerate the last reply, retry a failed turn.
236350 export async function talkAgainSend(ctx: Ctx): Promise<Response> {
237351 const user = ctx.auth.user;
238352 if (user === undefined) return signInFirst(ctx);
@@ -241,16 +355,19 @@ export async function talkAgainSend(ctx: Ctx): Promise<Response> {
241355 if (form instanceof Response) return form;
242356 const how = AGAIN.find((h) => h === ctx.params["how"]);
243357 if (how === undefined) return new Response("not found", { status: 404 });
358 const conversation = conversationOf(ctx, user);
359 if (conversation === undefined) return notFoundPage(ctx);
360 const here = ctx.params["id"] === undefined ? HERE : urlOf(conversation);
244361 const text = form.get("text");
245362 const asJson = (ctx.request.headers.get("accept") ?? "").includes("application/json");
246363 let status = 422;
247364 let message = `Say something, up to ${WORDS_MAX} characters.`;
248365 if (how !== "edit" || (typeof text === "string" && text.trim() !== "" && text.length <= WORDS_MAX)) {
249 const said = talkAgain(ctx.app, user, how, typeof text === "string" ? text : "");
250 if (said.ok) return asJson ? json({ ok: true }, 202) : flashTo(ctx, `${HERE}#end`, { tone: "success", message: "Asked again. Reload to see the answer." });
366 const said = talkAgain(ctx.app, user, how, typeof text === "string" ? text : "", conversation.id);
367 if (said.ok) return asJson ? json({ ok: true }, 202) : flashTo(ctx, `${here}#end`, { tone: "success", message: "Asked again. Reload to see the answer." });
251368 [status, message] = TALK_WORDS[said.error];
252369 }
253 return asJson ? json({ ok: false, message }, status) : flashTo(ctx, `${HERE}#end`, { tone: "danger", message });
370 return asJson ? json({ ok: false, message }, status) : flashTo(ctx, `${here}#end`, { tone: "danger", message });
254371 }
255372
256373 // POST /talk/confirm/:id — the person's yes or no, from their own session.
@@ -290,14 +407,17 @@ export function talkStream(ctx: Ctx): Response {
290407 const after = ctx.url.searchParams.get("after") ?? ctx.request.headers.get("last-event-id") ?? "";
291408 if (!TURN_ID.test(after)) return new Response("bad turn id", { status: 400 });
292409 const { app } = ctx;
293 const conversation = openConversation(app.db, user.id);
410 const named = ctx.url.searchParams.get("c");
411 if (named !== null && named !== "" && !CONVERSATION_ID.test(named)) return new Response("bad conversation id", { status: 400 });
412 const conversation = named === null || named === "" ? openConversation(app.db, user.id) : getConversation(app.db, user.id, named);
413 if (conversation === undefined) return new Response("no such conversation", { status: 404 });
294414 let cursor = after;
295415 return eventStream(app, ctx.request, (emit, close) => {
296416 const started = Date.now();
297417 let told = false;
298418 const tick = (): void => {
299419 // Asked before the read: a turn that ends after this look is read whole next time.
300 const running = clock.running(app, user.id);
420 const running = clock.running(app, user.id, conversation.id);
301421 const fresh = turnsAfter(app.db, user.id, conversation.id, cursor);
302422 if (fresh.length > 0) {
303423 const waiting = new Set(waitingConfirms(ctx, user).map((w) => w.id));
@@ -315,7 +435,7 @@ export function talkStream(ctx: Ctx): Response {
315435 emit("done", {
316436 costs,
317437 context: context === undefined ? "" : contextText(context),
318 acts: [...exchangeActs(app.db, user.id, conversation.id, false)].map(([id, act]) => ({ id: `t-${id}`, html: act.text })),
438 acts: [...exchangeActs(app.db, user.id, conversation.id, false, ((c) => (c.id === conversation.id ? HERE : urlOf(conversation)))(openConversation(app.db, user.id)))].map(([id, act]) => ({ id: `t-${id}`, html: act.text })),
319439 });
320440 close();
321441 } else if (Date.now() - started >= clock.streamMs) {
src/web/pages/talk_client.ts +8 −4
@@ -44,6 +44,9 @@ export const talkCss = /* css */ `
4444 .talk-body pre { position: relative; }
4545 .talk-body pre .talk-copy { position: absolute; top: 2px; right: 2px; }
4646 .talk-more { text-align: center; }
47 .talk-chats, .talk-here { margin-bottom: 12px; }
48 .talk-chats li a { display: flex; justify-content: space-between; }
49 .talk-chats [aria-current] { font-weight: 600; }
4750 .talk-replaced { opacity: 0.55; }
4851 .talk-failed form { margin-top: 6px; }
4952 .talk-failed .btn, .talk-act { min-height: 2.75rem; }
@@ -63,6 +66,7 @@ if (root) {
6366 let source = null;
6467 let retry = 0;
6568 const paged = root.dataset.paged === "1";
69 const { c: cid, here } = root.dataset;
6670 const say = (words) => { status.textContent = words; };
6771 const hint = root.querySelector("[data-hint]");
6872 if (hint) hint.textContent = "Enter sends, Shift+Enter adds a line";
@@ -130,7 +134,7 @@ if (root) {
130134 const again = async (how, body) => {
131135 say(how === "edit" ? "Sending…" : "Asking again…");
132136 try {
133 const res = await fetch("/talk/again/" + how, { method: "POST", headers: { accept: "application/json" }, body });
137 const res = await fetch(here + "/again/" + how, { method: "POST", headers: { accept: "application/json" }, body });
134138 const out = await res.json().catch(() => ({}));
135139 if (!res.ok) { say(out.message || "That was not done."); return false; }
136140 stuck = true;
@@ -165,7 +169,7 @@ if (root) {
165169 if (paged) return;
166170 if (source) source.close();
167171 dropActs();
168 source = new EventSource("/talk/stream?after=" + encodeURIComponent(last));
172 source = new EventSource("/talk/stream?c=" + encodeURIComponent(cid) + "&after=" + encodeURIComponent(last));
169173 source.addEventListener("turn", (e) => {
170174 const turn = JSON.parse(e.data);
171175 last = turn.id;
@@ -206,7 +210,7 @@ if (root) {
206210 const res = await fetch("/api/v1/conversation/messages", {
207211 method: "POST",
208212 headers: { "content-type": "application/json" },
209 body: JSON.stringify({ text }),
213 body: JSON.stringify({ text, conversation: cid }),
210214 });
211215 if (!res.ok) {
212216 const body = await res.json().catch(() => ({}));
@@ -217,7 +221,7 @@ if (root) {
217221 grow();
218222 try { localStorage.removeItem(draftKey); } catch (_) {}
219223 stuck = true;
220 if (paged) { location.href = "/talk"; return; }
224 if (paged) { location.href = here; return; }
221225 follow();
222226 } catch (_) {
223227 say("That was not sent: no connection.");
test/conversation-talk.test.ts +19 −1
@@ -19,7 +19,7 @@ import { mintViaToken } from "../src/core/via_token.ts";
1919 import { TALK_PER_MINUTE, talk, talkAgain } from "../src/actions/talk.ts";
2020 import { turnsLimit } from "../src/http/api/conversation_talk.ts";
2121 import { serve, type Servers } from "../src/http/server.ts";
22 import { appendTurn, openConversation } from "../src/core/conversations.ts";
22 import { appendTurn, newConversation, openConversation } from "../src/core/conversations.ts";
2323 import { forgeSshSession } from "../src/tui/ssh.ts";
2424 import { isStop, parseTalkAgain, parseTalkCommand } from "../src/tui/ssh-talk.ts";
2525 import { listTurns } from "../src/core/conversations.ts";
@@ -341,6 +341,24 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
341341 expect(await standing()).toEqual(plain);
342342 expect(talkAgain(app, undefined, "retry").ok).toBe(false);
343343 });
344 test("regenerate acts on the conversation it names, not the latest", async () => {
345 const older = newConversation(app.db, alice());
346 appendTurn(app.db, alice(), older.id, { role: "person", text: "older question" });
347 appendTurn(app.db, alice(), older.id, { role: "agent", text: "older answer" });
348 const newer = newConversation(app.db, alice());
349 appendTurn(app.db, alice(), newer.id, { role: "person", text: "newer question" });
350 appendTurn(app.db, alice(), newer.id, { role: "agent", text: "newer answer" });
351 withBinary(answers("Fresh older answer."));
352 await settled(redo(app, conversationOptions(app)!, alice(), "regenerate", "", older.id));
353 await settle();
354 const text = (id: string) => (listTurns(app.db, alice(), id, { limit: 50 }) as { ok: true; value: { text: string; replaced: boolean }[] }).value;
355 expect(text(older.id).filter((t) => !t.replaced).map((t) => t.text)).toEqual(["older question", "Fresh older answer."]);
356 expect(text(newer.id).map((t) => t.text)).toEqual(["newer question", "newer answer"]);
357 const stranger = redo(app, conversationOptions(app)!, alice(), "regenerate", "", "01zzzzzzzzzzzzzzzzzzzzzzzz");
358 expect(!stranger.ok && stranger.error).toBe("not_found");
359 expect(exchangeActs(app.db, alice(), older.id, false, `/talk/${older.id}`).size).toBe(2);
360 });
361
344362 const post = (path: string, h: Record<string, string>, body = "") =>
345363 fetch(`${servers.url}${path}`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", ...h }, body, redirect: "manual" });
346364 const cookie = () => ({ cookie: `forge_session=${createSession(app.db, alice()).token}` });
test/conversation-turn.test.ts +16 −1
@@ -13,7 +13,7 @@ import { join } from "node:path";
1313 import { createApp, type App } from "../src/app.ts";
1414 import { clearAccountCeiling, daySpent, setAccountCeiling } from "../src/core/account_ceiling.ts";
1515 import { claimDone, completeWrite, recordWrite } from "../src/core/conversation_writes.ts";
16 import { listTurns, openConversation } from "../src/core/conversations.ts";
16 import { listTurns, newConversation, openConversation } from "../src/core/conversations.ts";
1717 import { monthSpent } from "../src/core/model_grant.ts";
1818 import { addSubscription, getSubscription, PLATFORM, setGrants, wakeSubscription } from "../src/core/subscriptions.ts";
1919 import { verifyToken } from "../src/core/tokens.ts";
@@ -515,4 +515,19 @@ sleep 300
515515 expect(alive).toBe(false);
516516 expect(stopTurn(app, u.value.id)).toBe(false);
517517 }, 20_000);
518
519 test("Stop ends the replies running in two conversations, the older one included", async () => {
520 const older = newConversation(app.db, alice.id);
521 const newer = newConversation(app.db, alice.id);
522 const one = say(app, options(stub("two-a", "sess-two-a", "hang")), alice.id, "first", older.id);
523 const two = say(app, options(stub("two-b", "sess-two-b", "hang")), alice.id, "second", newer.id);
524 if (!one.ok || !two.ok || one.value.done === undefined || two.value.done === undefined) throw new Error("not started");
525 expect(turnRunning(app, alice.id, older.id)).toBe(true);
526 expect(turnRunning(app, alice.id, newer.id)).toBe(true);
527 expect(stopTurn(app, alice.id)).toBe(true);
528 await Promise.all([one.value.done, two.value.done]);
529 expect(turnRunning(app, alice.id, older.id)).toBe(false);
530 expect(turnRunning(app, alice.id, newer.id)).toBe(false);
531 expect(stopTurn(app, alice.id)).toBe(false);
532 }, 20_000);
518533 });
test/conversations.test.ts +55
@@ -5,6 +5,12 @@ import { join } from "node:path";
55 import { migrations } from "../src/core/schema.ts";
66 import {
77 appendTurn,
8 archiveConversation,
9 getConversation,
10 listConversations,
11 newConversation,
12 renameConversation,
13 TITLE_MAX,
814 listTurns,
915 MAX_TURN_CHARS,
1016 openConversation,
@@ -130,3 +136,52 @@ describe("conversations", () => {
130136 db.close();
131137 });
132138 });
139
140 describe("many conversations (#8814)", () => {
141 test("new starts another; the list is newest activity first and the latest is where messages go", () => {
142 const db = open("many.db");
143 const a = openConversation(db, "u1");
144 const b = newConversation(db, "u1");
145 expect(b.id).not.toBe(a.id);
146 expect(listConversations(db, "u1").map((c) => c.id)).toEqual([b.id, a.id]);
147 Bun.sleepSync(3);
148 appendTurn(db, "u1", a.id, { role: "person", text: "hi" });
149 expect(listConversations(db, "u1").map((c) => c.id)).toEqual([a.id, b.id]);
150 expect(openConversation(db, "u1").id).toBe(a.id);
151 });
152
153 test("rename keeps a clean title and refuses a long or multi-line one", () => {
154 const db = open("rename.db");
155 const c = openConversation(db, "u1");
156 const named = renameConversation(db, "u1", c.id, " Plan the week ");
157 expect(named.ok && named.value.title).toBe("Plan the week");
158 expect(renameConversation(db, "u1", c.id, "x".repeat(TITLE_MAX + 1))).toEqual({ ok: false, error: "bad_title" });
159 expect(renameConversation(db, "u1", c.id, "a\nb")).toEqual({ ok: false, error: "bad_title" });
160 expect(getConversation(db, "u1", c.id)?.title).toBe("Plan the week");
161 });
162
163 test("archive puts one behind the filter, restore brings it back, turns survive", () => {
164 const db = open("archive.db");
165 const a = openConversation(db, "u1");
166 appendTurn(db, "u1", a.id, { role: "person", text: "keep me" });
167 const b = newConversation(db, "u1");
168 expect(archiveConversation(db, "u1", b.id, true).ok).toBe(true);
169 expect(listConversations(db, "u1").map((c) => c.id)).toEqual([a.id]);
170 expect(listConversations(db, "u1", { archived: true }).map((c) => c.id)).toEqual([b.id]);
171 expect(openConversation(db, "u1").id).toBe(a.id);
172 archiveConversation(db, "u1", a.id, true);
173 expect(openConversation(db, "u1").id).not.toBe(a.id);
174 archiveConversation(db, "u1", a.id, false);
175 expect(listTurns(db, "u1", a.id)).toMatchObject({ ok: true, value: [{ text: "keep me" }] });
176 });
177
178 test("another person's id is not found for every call", () => {
179 const db = open("other.db");
180 const mine = openConversation(db, "u1");
181 expect(getConversation(db, "u2", mine.id)).toBeUndefined();
182 expect(renameConversation(db, "u2", mine.id, "x")).toEqual({ ok: false, error: "not_found" });
183 expect(archiveConversation(db, "u2", mine.id, true)).toEqual({ ok: false, error: "not_found" });
184 expect(listConversations(db, "u2")).toEqual([]);
185 expect(listTurns(db, "u2", mine.id)).toEqual({ ok: false, error: "not_found" });
186 });
187 });
test/palette-roster.test.ts +2
@@ -70,6 +70,7 @@ test("a site-admin person is offered the whole roster", () => {
7070 ["decider", "Decider", "what it closed, deferred and asked you about today"],
7171 ["notify", "Phone notifications", "where the crew reaches your phone; s sets, x turns off"],
7272 ["confirms", "Confirms", "what the forge's agent asked to do; y does it once"],
73 ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"],
7374 ["ssh-keys", "SSH keys", "list, add and remove the keys that sign in as you"],
7475 ["passkeys", "Passkeys", "the passkeys that sign in as you"],
7576 ["account", "Account settings", undefined],
@@ -222,6 +223,7 @@ test("a member person is offered the signed-in roster without the admin entries"
222223 ["decider", "Decider", "what it closed, deferred and asked you about today"],
223224 ["notify", "Phone notifications", "where the crew reaches your phone; s sets, x turns off"],
224225 ["confirms", "Confirms", "what the forge's agent asked to do; y does it once"],
226 ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"],
225227 ["ssh-keys", "SSH keys", "list, add and remove the keys that sign in as you"],
226228 ["passkeys", "Passkeys", "the passkeys that sign in as you"],
227229 ["account", "Account settings", undefined],
test/route-timing-coverage.test.ts +1
@@ -19,6 +19,7 @@ import { seedAdmin } from "./helpers/admin.ts";
1919
2020 /** Routes that answer 200 without a `session` phase → why. */
2121 const UNTIMED: Record<string, string> = {
22 "/api/v1/conversations": "a person's conversation list, one indexed query; no page to phase",
2223 "/metrics": "Prometheus text exposition, scraped by token; not a page read",
2324 };
2425
test/schema-additive.test.ts +11 −1
@@ -71,7 +71,7 @@ describe("migrations are additive across a roll", () => {
7171 expect(inPlay.length).toBeGreaterThan(0);
7272 const offenders = migrationFiles
7373 .filter((m) => inPlay.some((ids) => !ids.has(m.name)))
74 .filter((m) => !(m.name in RETIRED))
74 .filter((m) => !(m.name in RETIRED) && !(m.name in REBUILT))
7575 .map((m) => ({ name: m.name, problems: notAdditive(m.sql) }))
7676 .filter((m) => m.problems.length > 0);
7777 expect(offenders).toEqual([]);
@@ -152,6 +152,16 @@ const RETIRED: Record<string, { readonly drops: readonly string[]; readonly sinc
152152 },
153153 };
154154
155 /**
156 * Migrations that rebuild a table under its own name, in one transaction, with
157 * every column the old release reads kept and only columns added: an old
158 * process sees the same table before and after. SQLite cannot drop a UNIQUE
159 * constraint in place, so a rebuild is the only way to lift one.
160 */
161 const REBUILT: Record<string, string> = {
162 "20261103120000-conversations-many": "conversation loses UNIQUE(user_id) (#8814); same columns, plus title and archived_at",
163 };
164
155165 const src = join(import.meta.dir, "../src");
156166
157167 interface Release {
test/security-floor-routes.test.ts +2
@@ -45,11 +45,13 @@ const ARCH = "needs an archived-home operation id; the seed archives nothing";
4545 const NOW = "the stage is one of check, review, land or live; the seed fills no word with a name it cannot guess";
4646 const GATE = "needs a kept gate log, written only when a full gate runs on land";
4747 const BET = "needs a bet, which the seed does not propose";
48 const TALK = "needs a conversation of the signed-in person; the seed starts none";
4849 const HOOK = "needs a webhook, which the seed does not register";
4950
5051 /** GET patterns the seed cannot fill → why. Requested with a placeholder all the same. */
5152 const UNSEEDED: Record<string, string> = {
5253 "/:owner/-/teams/:team": ORG,
54 "/talk/:id": TALK,
5355 "/:owner/:name/bets/:id": BET,
5456 "/:owner/:name/looks/:env/:commit/:kind.png": LOOK,
5557 "/:owner/:name/milestones/:number/limb/:op": LIMB,
test/talk-conversations.test.ts added +243
@@ -0,0 +1,243 @@
1 /**
2 * Many conversations (#8814): /talk lists them with New, each opens at
3 * /talk/<id>, rename and archive are plain forms, the API and the MCP reach
4 * the same calls, another person's id is a 404, and the migration that
5 * lifted one-per-person keeps the turns it found.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { appendTurn, CONVERSATIONS_MAX, createConversation, listConversations, listTurns, newConversation, openConversation, renameConversation } from "../src/core/conversations.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { migrations } from "../src/core/schema.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { openDb } from "../src/kernel/db.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { tool as sayTool } from "../src/http/mcp/tools/say.ts";
20 import { promote } from "./helpers/members.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22
23 quietLogs();
24
25 let dir: string;
26 let app: App;
27 let servers: Servers;
28 let alice: User;
29 let bob: User;
30
31 const cookie = (u: User) => `forge_session=${createSession(app.db, u.id).token}`;
32 const get = (path: string, u?: User) =>
33 fetch(`${servers.url}${path}`, { redirect: "manual", headers: u ? { cookie: cookie(u) } : {} });
34 const post = (path: string, u: User, form: Record<string, string>) =>
35 fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { origin: servers.url, cookie: cookie(u) }, body: new URLSearchParams(form) });
36 const api = (method: string, path: string, u: User, body?: unknown) =>
37 fetch(`${servers.url}${path}`, {
38 method,
39 redirect: "manual",
40 headers: { origin: servers.url, cookie: cookie(u), "content-type": "application/json" },
41 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
42 });
43
44 beforeAll(async () => {
45 dir = await mkdtemp(join(tmpdir(), "forge-talk-many-"));
46 app = createApp({ dataDir: dir, port: 0 });
47 servers = await serve(app);
48 const mk = async (username: string, first = false) => {
49 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
50 if (!u.ok) throw new Error(u.error);
51 promote(app.db, u.value);
52 return u.value;
53 };
54 alice = await mk("alice", true);
55 bob = await mk("bob");
56 }, 30_000);
57
58 afterAll(async () => {
59 servers.stop();
60 app.close();
61 await rm(dir, { recursive: true, force: true });
62 });
63
64 describe("the page", () => {
65 test("New makes a conversation at its own URL that survives a reload, and the list shows it", async () => {
66 const made = await post("/talk/new", alice, {});
67 expect(made.status).toBe(303);
68 const url = made.headers.get("location")!;
69 expect(url).toMatch(/^\/talk\/[0-9a-z]+$/);
70 const first = await (await get(url, alice)).text();
71 const again = await get(url, alice);
72 expect(again.status).toBe(200);
73 expect(first).toContain(`data-c="${url.slice(6)}"`);
74 expect(await again.text()).toContain(`href="${url}"`);
75 expect((await get("/talk", alice)).status).toBe(200);
76 });
77
78 test("rename shows the title in the list; archive moves it behind the filter; restore brings it back", async () => {
79 const c = newConversation(app.db, alice.id);
80 const renamed = await post(`/talk/${c.id}/rename`, alice, { title: "Weekly <plan>" });
81 expect(renamed.status).toBe(303);
82 const page = await (await get(`/talk/${c.id}`, alice)).text();
83 expect(page).toContain("Weekly &lt;plan&gt;");
84 expect(page).not.toContain("Weekly <plan>");
85 await post(`/talk/${c.id}/archive`, alice, { archived: "1" });
86 const list = await (await get("/talk", alice)).text();
87 expect(list).not.toContain(`href="/talk/${c.id}"`);
88 expect(list).toContain("Archived (");
89 expect(await (await get("/talk?archived=1", alice)).text()).toContain(`href="/talk/${c.id}"`);
90 expect(await (await get(`/talk/${c.id}`, alice)).text()).toContain("sending here keeps it archived");
91 await post(`/talk/${c.id}/archive`, alice, { archived: "0" });
92 expect(await (await get("/talk", alice)).text()).toContain(`href="/talk/${c.id}"`);
93 expect(await (await get(`/talk/${c.id}`, alice)).text()).not.toContain("sending here keeps it archived");
94 });
95
96 test("another person's id answers 404 for view, send, rename, archive and stream", async () => {
97 const mine = newConversation(app.db, alice.id);
98 expect((await get(`/talk/${mine.id}`, bob)).status).toBe(404);
99 expect((await post(`/talk/${mine.id}`, bob, { text: "hi" })).status).toBe(404);
100 expect((await post(`/talk/${mine.id}/rename`, bob, { title: "mine now" })).status).toBe(404);
101 expect((await post(`/talk/${mine.id}/archive`, bob, { archived: "1" })).status).toBe(404);
102 expect((await get(`/talk/stream?c=${mine.id}`, bob)).status).toBe(404);
103 expect((await get("/talk/nope!", bob)).status).toBe(404);
104 expect(listConversations(app.db, alice.id).find((c) => c.id === mine.id)?.title).toBe("");
105 });
106
107 test("signed out is sent to sign in", async () => {
108 expect((await get("/talk/abc")).status).toBe(303);
109 expect((await post("/talk/new", alice, {})).status).toBe(303);
110 });
111 });
112
113 describe("the API", () => {
114 test("list, new, rename, archive; another person's id is 404", async () => {
115 const made = await api("POST", "/api/v1/conversations", alice, { title: "From the API" });
116 expect(made.status).toBe(201);
117 const { conversation } = (await made.json()) as { conversation: { id: string; title: string } };
118 expect(conversation.title).toBe("From the API");
119 const listed = (await (await api("GET", "/api/v1/conversations", alice)).json()) as { conversations: { id: string }[] };
120 expect(listed.conversations.some((c) => c.id === conversation.id)).toBe(true);
121 const patched = await api("PATCH", `/api/v1/conversations/${conversation.id}`, alice, { title: "Renamed", archived: true });
122 expect(patched.status).toBe(200);
123 const after = (await (await api("GET", "/api/v1/conversations?archived=1", alice)).json()) as { conversations: { id: string; title: string }[] };
124 expect(after.conversations.find((c) => c.id === conversation.id)?.title).toBe("Renamed");
125 expect((await api("PATCH", `/api/v1/conversations/${conversation.id}`, bob, { title: "x" })).status).toBe(404);
126 expect((await api("PATCH", `/api/v1/conversations/${conversation.id}`, alice, { title: "x".repeat(81) })).status).toBe(422);
127 expect((await api("GET", `/api/v1/conversation/turns?conversation=${conversation.id}`, bob)).status).toBe(404);
128 expect((await api("GET", `/api/v1/conversation/turns?conversation=${conversation.id}`, alice)).status).toBe(200);
129 expect((await api("POST", "/api/v1/conversation/messages", bob, { text: "hi", conversation: conversation.id })).status).toBe(404);
130 });
131 });
132
133 describe("the MCP", () => {
134 test("say with an action lists, starts, renames and archives, and refuses another person's id", async () => {
135 const ctx = { app, auth: { user: alice, via: "session" } } as never;
136 const run = async (u: User, args: Record<string, unknown>) => {
137 const answer = (await sayTool.run(ctx, u, args)) as { ok: boolean; value?: any; error?: string };
138 return answer.ok ? answer.value : { error: answer.error };
139 };
140 const made = await run(alice, { action: "new", title: "By agent" });
141 expect(made.conversation).toMatch(/^[0-9a-z]+$/);
142 expect((await run(alice, { action: "list" })).conversations.some((c: { id: string }) => c.id === made.conversation)).toBe(true);
143 expect((await run(alice, { action: "rename", conversation: made.conversation, title: "Better" })).says).toBe("Renamed.");
144 expect((await run(alice, { action: "archive", conversation: made.conversation })).says).toBe("Archived.");
145 expect((await run(bob, { action: "archive", conversation: made.conversation })).error).toBe("not_found");
146 });
147 });
148
149 describe("the migration", () => {
150 test("a person's one conversation, its turns and runs come through the table rebuild", () => {
151 const db = openDb(join(dir, "before.db"), migrations.slice(0, -1));
152 db.query("INSERT INTO user (id, username, email, password_hash) VALUES ('u1','u1','u1@x','x')").run();
153 db.query("INSERT INTO conversation (id, user_id, claude_session_id, created_at, updated_at) VALUES ('c1','u1','s','t','t')").run();
154 for (const n of [1, 2, 3]) appendTurn(db, "u1", "c1", { role: "person", text: `t${n}` });
155 db.query("INSERT INTO conversation_run (id, conversation_id, user_id, prompt, started_at) VALUES ('r1','c1','u1','p','t')").run();
156 db.close();
157 const after = openDb(join(dir, "before.db"), migrations);
158 expect(openConversation(after, "u1").id).toBe("c1");
159 const turns = listTurns(after, "u1", "c1");
160 expect(turns.ok && turns.value.map((t) => t.text)).toEqual(["t1", "t2", "t3"]);
161 expect(after.query("SELECT COUNT(*) AS n FROM conversation_run").get()).toEqual({ n: 1 });
162 expect(newConversation(after, "u1").id).not.toBe("c1");
163 after.close();
164 });
165 });
166
167 describe("the mutation checks", () => {
168 test("a cross-origin POST to New, Rename and Archive is refused and changes nothing", async () => {
169 const c = newConversation(app.db, alice.id);
170 const before = listConversations(app.db, alice.id).length;
171 const evil = (path: string, form: Record<string, string>) =>
172 fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { origin: "https://evil.example", cookie: cookie(alice) }, body: new URLSearchParams(form) });
173 expect((await evil("/talk/new", {})).status).toBe(403);
174 expect((await evil(`/talk/${c.id}/rename`, { title: "hijack" })).status).toBe(403);
175 expect((await evil(`/talk/${c.id}/archive`, { archived: "1" })).status).toBe(403);
176 expect(listConversations(app.db, alice.id).length).toBe(before);
177 const kept = listConversations(app.db, alice.id).find((x) => x.id === c.id);
178 expect(kept?.title).toBe("");
179 });
180
181 test("a read-only token is refused on POST and PATCH /api/v1/conversations", async () => {
182 const ro = createToken(app.db, alice.id, "t", "ro").token;
183 const rw = createToken(app.db, alice.id, "t", "rw").token;
184 const c = newConversation(app.db, alice.id);
185 const call = (method: string, path: string, token: string, body: unknown) =>
186 fetch(`${servers.url}${path}`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) });
187 const before = listConversations(app.db, alice.id).length;
188 expect((await call("POST", "/api/v1/conversations", ro, {})).status).toBe(403);
189 expect((await call("PATCH", `/api/v1/conversations/${c.id}`, ro, { archived: true })).status).toBe(403);
190 expect(listConversations(app.db, alice.id).length).toBe(before);
191 expect(listConversations(app.db, alice.id).find((x) => x.id === c.id)?.archivedAt).toBeNull();
192 expect((await call("PATCH", `/api/v1/conversations/${c.id}`, rw, { archived: true })).status).toBe(200);
193 expect((await fetch(`${servers.url}/api/v1/conversations`, { headers: { authorization: `Bearer ${ro}` } })).status).toBe(200);
194 });
195
196 test("GET /talk/stream is the stream, not a conversation called stream", async () => {
197 const answer = await get("/talk/stream", alice);
198 expect(answer.headers.get("content-type")).toContain("text/event-stream");
199 await answer.body?.cancel();
200 });
201 });
202
203 describe("the most a person holds", () => {
204 test("every door refuses past the cap, and the others are untouched", async () => {
205 const carol = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" });
206 if (!carol.ok) throw new Error(carol.error);
207 promote(app.db, carol.value);
208 const c = carol.value;
209 while (listConversations(app.db, c.id).length + listConversations(app.db, c.id, { archived: true }).length < CONVERSATIONS_MAX) {
210 const made = createConversation(app.db, c.id);
211 if (!made.ok) break;
212 }
213 const held = () => (app.db.query("SELECT COUNT(*) AS n FROM conversation WHERE user_id = ?1").get(c.id) as { n: number }).n;
214 expect(held()).toBe(CONVERSATIONS_MAX);
215 const refused = createConversation(app.db, c.id);
216 expect(!refused.ok && refused.error).toBe("too_many");
217 const page = await post("/talk/new", c, {});
218 expect(page.status).toBe(303);
219 expect(page.headers.get("location")).not.toMatch(/^\/talk\/[0-9a-z]{6,}/);
220 const viaApi = await api("POST", "/api/v1/conversations", c, {});
221 expect(viaApi.status).toBe(409);
222 expect(((await viaApi.json()) as { error: string }).error).toBe("too_many");
223 const ctx = { app, auth: { user: c, via: "session" } } as never;
224 const mcp = (await sayTool.run(ctx, c, { action: "new" })) as { ok: boolean; error?: string };
225 expect(mcp.ok).toBe(false);
226 expect(mcp.error).toBe("too_many");
227 expect(held()).toBe(CONVERSATIONS_MAX);
228 // Archiving does not free a place; another person is unaffected.
229 expect(createConversation(app.db, alice.id).ok).toBe(true);
230 });
231 });
232
233 describe("the MCP rename", () => {
234 test("rename needs a title: without one the title is kept", async () => {
235 const ctx = { app, auth: { user: alice, via: "session" } } as never;
236 const made = newConversation(app.db, alice.id);
237 renameConversation(app.db, alice.id, made.id, "Keep me");
238 const answer = (await sayTool.run(ctx, alice, { action: "rename", conversation: made.id })) as { ok: boolean; error?: string };
239 expect(answer.ok).toBe(false);
240 expect(answer.error).toBe("invalid_title");
241 expect(listConversations(app.db, alice.id).find((x) => x.id === made.id)?.title).toBe("Keep me");
242 });
243 });
test/tui-talk-chats.test.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * The terminal's Conversations screen (#8814): list, New, Rename and
3 * Archive/Restore through the calls /talk uses, offered to a signed-in person
4 * and not to an agent, with the cap refusing past it.
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 { createApp, type App } from "../src/app.ts";
11 import { appendTurn, CONVERSATIONS_MAX, createConversation, listConversations, listTurns, renameConversation } from "../src/core/conversations.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { createForgeApp } from "../src/tui/forge.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { settleApp } from "./helpers/tui.ts";
16 import { proveAll } from "./helpers/verified.ts";
17
18 let dir: string;
19 let app: App;
20 let alice: User;
21 let bob: User;
22 const open = [":", "Conversations", "\r"];
23
24 async function drive(user: User, keys: string[]): Promise<string> {
25 const terminal = headlessTerminal(120, 30);
26 const { app: tui } = createForgeApp(
27 app,
28 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
29 { terminal, exitHooks: false },
30 );
31 tui.start();
32 await settleApp(tui);
33 for (const k of keys) {
34 terminal.feed(k);
35 await settleApp(tui);
36 }
37 const text = tui.screen.toText();
38 tui.stop?.();
39 return text;
40 }
41
42 beforeAll(async () => {
43 dir = await mkdtemp(join(tmpdir(), "forge-tui-chats-"));
44 app = createApp({ dataDir: dir, port: 0 });
45 const mk = async (username: string, first = false) => {
46 const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
47 if (!r.ok) throw new Error(r.error);
48 return r.value;
49 };
50 alice = await mk("alice", true);
51 bob = await mk("bob");
52 proveAll(app);
53 });
54 afterAll(async () => {
55 app.db.close();
56 await rm(dir, { recursive: true, force: true });
57 });
58
59 describe("the terminal's conversations screen", () => {
60 test("n starts one with a title, r renames it, x archives it and a brings it back", async () => {
61 const text = await drive(alice, [...open, "n", "Weekly plan", "\r"]);
62 const mine = listConversations(app.db, alice.id);
63 expect(mine.map((c) => c.title)).toEqual(["Weekly plan"]);
64 expect(text).toContain("Weekly plan");
65 expect(text).toContain(`/talk/${mine[0]!.id}`);
66 await drive(alice, [...open, "r", ..."\x7f".repeat(11).split(""), "Renamed", "\r"]);
67 expect(listConversations(app.db, alice.id)[0]!.title).toBe("Renamed");
68 await drive(alice, [...open, "x"]);
69 expect(listConversations(app.db, alice.id)).toEqual([]);
70 const archived = await drive(alice, [...open, "a"]);
71 expect(archived).toContain("Renamed");
72 expect(listConversations(app.db, alice.id, { archived: true }).length).toBe(1);
73 await drive(alice, [...open, "a", "x"]);
74 expect(listConversations(app.db, alice.id).length).toBe(1);
75 });
76
77 test("another person's conversations are not listed", async () => {
78 const text = await drive(bob, open);
79 expect(text).not.toContain("Renamed");
80 expect(text).toContain("No conversations yet");
81 });
82
83 test("Enter opens one: its turns, and s says something in it", async () => {
84 const made = createConversation(app.db, bob.id);
85 if (!made.ok) throw new Error(made.error);
86 renameConversation(app.db, bob.id, made.value.id, "Bob's chat");
87 appendTurn(app.db, bob.id, made.value.id, { role: "person", text: "how is the forge" });
88 appendTurn(app.db, bob.id, made.value.id, { role: "agent", text: "all green today" });
89 const text = await drive(bob, [...open, "\r"]);
90 expect(text).toContain("how is the forge");
91 expect(text).toContain("all green today");
92 expect(text).toContain(`/talk/${made.value.id}`);
93 // The crew is off in this app: talk() refuses, the prompt says why, and nothing is stored.
94 const said = await drive(bob, [...open, "\r", "s", "hello", "\r"]);
95 expect(said).toContain("not running here");
96 const turns = listTurns(app.db, bob.id, made.value.id, { limit: 50 });
97 expect(turns.ok && turns.value.length).toBe(2);
98 });
99
100 test("past the cap, n says so and starts nothing", async () => {
101 while (createConversation(app.db, alice.id).ok) { /* fill */ }
102 const held = (app.db.query("SELECT COUNT(*) AS n FROM conversation WHERE user_id = ?1").get(alice.id) as { n: number }).n;
103 expect(held).toBe(CONVERSATIONS_MAX);
104 renameConversation(app.db, alice.id, listConversations(app.db, alice.id)[0]!.id, "top");
105 const text = await drive(alice, [...open, "n", "one too many", "\r"]);
106 expect(text).toContain("the most there can be");
107 expect((app.db.query("SELECT COUNT(*) AS n FROM conversation WHERE user_id = ?1").get(alice.id) as { n: number }).n).toBe(CONVERSATIONS_MAX);
108 });
109 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs