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

A conversation on /talk can be pinned, and pinned conversations stay at the top of the list #14634

Merged opened this

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

Merged

scout/forge:scout/14564-a-conversation-on-talk-can-be-pinned-and → main 4 commits fork 3 threads · 3 unresolved

  • Merged. scout/14564-a-conversation-on-talk-can-be-pinned-and was merged into main as 10146eb.

Review

Sign in to review this change.
9 files changed +222 −6
docs/features/talk.md +1
@@ -42,6 +42,7 @@ A person has any number. `/talk` is their latest, with the list above it (newest
4242 - **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.
4343 - **MCP:** `say` with `action` list | new | rename | archive | restore, and `conversation` to speak in one.
4444 - **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.
45 - **Pin (#14564):** Pin and Unpin on the open conversation (`POST /talk/:id/pin`, owner only, same-origin) keep it at the top of the list under a quiet *Pinned* heading, newest activity first among the pinned. Archiving clears the pin and an archived conversation cannot be pinned. Terminal: `p` in Conversations.

Non-blocking: stale. Pin and Unpin are now on every non-archived row of the list as well as on the open conversation.

4546 - Sending to an archived conversation keeps it archived; the page says so above the composer.
4647
4748 ## Edit, regenerate, retry (#8817)
src/core/conversations.ts +27 −4
@@ -29,6 +29,7 @@ export interface Conversation {
2929 readonly title: string;
3030 /** When it was put away; null while it is in the list. */
3131 readonly archivedAt: string | null;
32 readonly pinnedAt: string | null;
3233 }
3334
3435 /** Longest title kept, in characters; longer is refused, not cut. */
@@ -54,6 +55,7 @@ interface ConversationRow {
5455 updated_at: string;
5556 title: string;
5657 archived_at: string | null;
58 pinned_at: string | null;
5759 }
5860
5961 interface TurnRow {
@@ -74,6 +76,7 @@ const conversationOf = (r: ConversationRow): Conversation => ({
7476 updatedAt: r.updated_at,
7577 title: r.title,
7678 archivedAt: r.archived_at,
79 pinnedAt: r.pinned_at ?? null,
7780 });
7881
7982 const turnOf = (r: TurnRow): Turn => ({
@@ -108,7 +111,7 @@ export function dropConversation(db: Database, userId: string, conversationId: s
108111 /** Start a new, empty conversation. */
109112 export function newConversation(db: Database, userId: string): Conversation {
110113 const now = new Date().toISOString();
111 const row: ConversationRow = { id: id(), user_id: userId, claude_session_id: "", created_at: now, updated_at: now, title: "", archived_at: null };
114 const row: ConversationRow = { id: id(), user_id: userId, claude_session_id: "", created_at: now, updated_at: now, title: "", archived_at: null, pinned_at: null };
112115 db.query(
113116 "INSERT INTO conversation (id, user_id, claude_session_id, created_at, updated_at) VALUES (?1,?2,'',?3,?3)",
114117 ).run(row.id, userId, now);
@@ -134,11 +137,14 @@ export function getConversation(db: Database, userId: string, conversationId: st
134137 return row === null ? undefined : conversationOf(row);
135138 }
136139
137 /** The person's conversations, newest activity first; `archived` picks the put-away ones instead. */
140 /**
141 * The person's conversations, pinned first, then newest activity first; `archived` picks the
142 * put-away ones instead.
143 */
138144 export function listConversations(db: Database, userId: string, opts: { readonly archived?: boolean } = {}): Conversation[] {
139145 const rows = db
140146 .query(
141 `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`,
147 `SELECT * FROM conversation WHERE user_id = ?1 AND archived_at IS ${opts.archived === true ? "NOT" : ""} NULL ORDER BY pinned_at IS NULL, updated_at DESC, rowid DESC LIMIT 200`,
142148 )
143149 .all(userId) as ConversationRow[];
144150 return rows.map(conversationOf);
@@ -166,12 +172,29 @@ export function archiveConversation(
166172 archived: boolean,
167173 ): Result<Conversation, "not_found"> {
168174 const changed = db
169 .query("UPDATE conversation SET archived_at = ?3 WHERE id = ?1 AND user_id = ?2")
175 .query("UPDATE conversation SET archived_at = ?3, pinned_at = CASE WHEN ?3 IS NULL THEN pinned_at ELSE NULL END WHERE id = ?1 AND user_id = ?2")
170176 .run(conversationId, userId, archived ? new Date().toISOString() : null).changes;
171177 const found = changed === 0 ? undefined : getConversation(db, userId, conversationId);
172178 return found === undefined ? err("not_found") : ok(found);
173179 }
174180
181 /**
182 * Keep a conversation at the top of the list, or let it go back (`pinned` false). An archived one
183 * is not pinned.
184 */
185 export function pinConversation(
186 db: Database,
187 userId: string,
188 conversationId: string,
189 pinned: boolean,
190 ): Result<Conversation, "not_found"> {
191 const changed = db
192 .query("UPDATE conversation SET pinned_at = ?3 WHERE id = ?1 AND user_id = ?2 AND archived_at IS NULL")
193 .run(conversationId, userId, pinned ? new Date().toISOString() : null).changes;
194 const found = changed === 0 ? undefined : getConversation(db, userId, conversationId);
195 return found === undefined ? err("not_found") : ok(found);
196 }
197
175198 const owned = (db: Database, userId: string, conversationId: string): boolean =>
176199 db
177200 .query("SELECT 1 FROM conversation WHERE id = ?1 AND user_id = ?2")
src/core/migration-pins/20261120100000-conversation-pinned.pin added +1
@@ -0,0 +1,1 @@
1 9e29eb8efc36dbf4cee92ba6da6b36a5a2f490d9391f9ed0bacb5cf314e4dc3e
src/core/migrations/20261120100000-conversation-pinned.ts added +5
@@ -0,0 +1,5 @@
1 // A conversation the owner keeps at the top of /talk (#14564): when it was pinned; null reads
2 // as not pinned. Additive.
3 export default `
4 ALTER TABLE conversation ADD COLUMN pinned_at TEXT;
5 `;
src/http/server.ts +2 −1
@@ -183,7 +183,7 @@ import {
183183 themeSubmit,
184184 } from "../web/pages/site.ts";
185185 import { talkBuild, talkPublish, talkRestore } from "../web/talk_build.ts";
186 import { talkAgainSend, talkArchive, talkConfirm, talkDownload, talkNew, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView } from "../web/pages/talk.ts";
186 import { talkAgainSend, talkArchive, talkConfirm, talkDownload, talkNew, talkPin, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView } from "../web/pages/talk.ts";
187187 import {
188188 recoverFinish,
189189 recoverOptions,
@@ -1228,6 +1228,7 @@ export function buildRouter(): Router<Handler> {
12281228 router.add("POST", "/talk/:id", talkSend);
12291229 router.add("POST", "/talk/:id/rename", talkRename);
12301230 router.add("POST", "/talk/:id/archive", talkArchive);
1231 router.add("POST", "/talk/:id/pin", talkPin);
12311232 router.add("POST", "/talk/:id/build/restore", talkRestore);
12321233 router.add("POST", "/talk/:id/build/publish", talkPublish);
12331234 router.add("POST", "/talk/:id/again/:how", talkAgainSend);
src/tui/screens/talk_chats.ts +7
@@ -13,6 +13,7 @@ import { pathRefs, refTarget } from "../../text/talk_links.ts";
1313 import { STARTER_PROMPTS, TALK_WORDS, talk } from "../../actions/talk.ts";
1414 import {
1515 archiveConversation,
16 pinConversation,
1617 createConversation,
1718 findConversations,
1819 pageAround,
@@ -253,6 +254,7 @@ export function talkChatsScreen(f: Session, ctx: Ctx): Screen {
253254 binding(["enter"], "open"),
254255 binding(["n"], "new"),
255256 binding(["r"], "rename"),
257 binding(["p"], "pin or unpin"),
256258 binding(["x"], "archive or restore"),
257259 binding(["a"], "archived"),
258260 binding(["d"], "download"),
@@ -349,6 +351,11 @@ export function talkChatsScreen(f: Session, ctx: Ctx): Screen {
349351 ctx.push(downloadScreen(f, ctx, here));
350352 return true;
351353 }
354 if (e.key === "p") {

New terminal behaviour (pin, unpin, archived refusal) has no test; every added behaviour needs one that fails without it. Add a screen test for p.

355 const done = pinConversation(f.app.db, user.id, here.id, here.pinnedAt === null);
356 say(!done.ok ? "Restore it first: an archived conversation is not pinned." : here.pinnedAt === null ? "Pinned." : "Unpinned.");
357 return true;
358 }
352359 if (e.key === "x") {
353360 archiveConversation(f.app.db, user.id, here.id, !archived);
354361 say(archived ? "Restored." : "Archived.");
src/web/pages/talk.ts +40 −1
@@ -34,6 +34,7 @@ import {
3434 createConversation,
3535 TOO_MANY_WORDS,
3636 openConversation,
37 pinConversation,
3738 renameConversation,
3839 TITLE_MAX,
3940 turnsAfter,
@@ -322,7 +323,23 @@ function chats(ctx: Ctx, conversation: Conversation, showArchived: boolean, type
322323 <ul class="list">
323324 ${shown.length === 0
324325 ? html`<li class="muted small">${showArchived ? "Nothing archived." : "No conversations yet."}</li>`
325 : shown.map((c) => row({ href: urlOf(c), title: nameOf(c), meta: html`${time(c.updatedAt)}`, current: c.id === conversation.id }))}
326 : shown.map((c, i) =>
327 html`${i === 0 && c.pinnedAt !== null ? html`<li class="muted small" data-pinned-heading>Pinned</li>` : null}${row({

Principle 7 / issue box 1: rows carry no Pin/Unpin; the button is only on the open conversation. Put a pin post form on each row. The Pinned heading is a hand-rolled li; keep it quiet and consistent with the design system's list headings.

328 href: urlOf(c),
329 title: nameOf(c),
330 meta: html`${time(c.updatedAt)}`,
331 current: c.id === conversation.id,
332 ...(c.archivedAt === null
333 ? {
334 after: html`<form method="post" action="${urlOf(c)}/pin">
335 <input type="hidden" name="pinned" value="${c.pinnedAt === null ? "1" : "0"}" />
336 <input type="hidden" name="back" value="list" />
337 ${btn(c.pinnedAt === null ? "Pin" : "Unpin", { size: "sm", variant: "outline" })}
338 </form>`,
339 }
340 : {}),
341 })}`,
342 )}
326343 </ul>
327344 </nav>
328345 <div class="talk-here bar">
@@ -335,6 +352,12 @@ function chats(ctx: Ctx, conversation: Conversation, showArchived: boolean, type
335352 </form>
336353 </details>
337354 <a class="btn" href="${urlOf(conversation)}.md" download>Download</a>
355 ${archived
356 ? null
357 : html`<form method="post" action="${urlOf(conversation)}/pin">
358 <input type="hidden" name="pinned" value="${conversation.pinnedAt === null ? "1" : "0"}" />
359 ${btn(conversation.pinnedAt === null ? "Pin" : "Unpin")}
360 </form>`}
338361 <form method="post" action="${urlOf(conversation)}/archive">
339362 <input type="hidden" name="archived" value="${archived ? "0" : "1"}" />
340363 ${btn(archived ? "Restore" : "Archive")}
@@ -512,6 +535,22 @@ export async function talkArchive(ctx: Ctx): Promise<Response> {
512535 return flashTo(ctx, archive ? HERE : urlOf(conversation), { tone: "success", message: archive ? "Archived. It is under Archived." : "Restored." });
513536 }
514537
538 // POST /talk/:id/pin — pinned=1 keeps it at the top of the list, 0 lets it go; the list stays as it
539 // was.
540 export async function talkPin(ctx: Ctx): Promise<Response> {
541 const user = ctx.auth.user;
542 if (user === undefined) return signInFirst(ctx);
543 const form = await readForm(ctx, "rw");
544 if (form instanceof Response) return form;
545 const conversation = conversationOf(ctx, user);
546 if (conversation === undefined) return notFoundPage(ctx);
547 const pin = form.get("pinned") !== "0";
548 const to = form.get("back") === "list" ? HERE : urlOf(conversation);
549 const done = pinConversation(ctx.app.db, user.id, conversation.id, pin);
550 if (!done.ok) return flashTo(ctx, to, { tone: "danger", message: "An archived conversation is not pinned; Restore it first." });
551 return flashTo(ctx, to, { tone: "success", message: pin ? "Pinned. It stays at the top." : "Unpinned." });
552 }
553
515554 // GET /talk/:id/download — the conversation as one Markdown file, its owner's alone.
516555 export function talkDownload(ctx: Ctx): Response {
517556 const user = ctx.auth.user;
test/talk-pin.test.ts added +123
@@ -0,0 +1,123 @@
1 /**
2 * Pinning a conversation (#14564): pinned first under a heading, unpin, archive clears it, owner
3 * only.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createConversation, getConversation, listConversations } from "../src/core/conversations.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { promote } from "./helpers/members.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let dir: string;
20 let app: App;
21 let servers: Servers;
22 let alice: User;
23 let bob: User;
24
25 const cookie = (u: User) => `forge_session=${createSession(app.db, u.id).token}`;
26 const post = (path: string, u: User, form: Record<string, string>, origin = servers.url) =>
27 fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { origin, cookie: cookie(u) }, body: new URLSearchParams(form) });
28 const mine = (u: User) => {
29 const r = createConversation(app.db, u.id);
30 if (!r.ok) throw new Error(r.error);
31 return r.value;
32 };
33
34 beforeAll(async () => {
35 dir = await mkdtemp(join(tmpdir(), "forge-talk-pin-"));
36 app = createApp({ dataDir: dir, port: 0 });
37 servers = await serve(app);
38 const mk = async (username: string, first = false) => {
39 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
40 if (!u.ok) throw new Error(u.error);
41 promote(app.db, u.value);
42 return u.value;
43 };
44 alice = await mk("alice", true);
45 bob = await mk("bob");
46 }, 30_000);
47
48 afterAll(async () => {
49 servers.stop();
50 app.close();
51 await rm(dir, { recursive: true, force: true });
52 });
53
54 describe("pin", () => {
55 test("pin moves a conversation to the top under a Pinned heading; unpin puts it back", async () => {
56 const a = mine(alice);
57 const b = mine(alice);
58 const c = mine(alice);
59 const ids = () => listConversations(app.db, alice.id).map((x) => x.id);
60 expect(ids()[0]).toBe(c.id);
61 const res = await post(`/talk/${a.id}/pin`, alice, { pinned: "1" });
62 expect(res.status).toBe(303);
63 expect(ids()[0]).toBe(a.id);
64 const page = await (await fetch(`${servers.url}/talk/${b.id}`, { headers: { cookie: cookie(alice) } })).text();
65 expect(page).toContain("data-pinned-heading");
66 await post(`/talk/${a.id}/pin`, alice, { pinned: "0" });
67 expect(ids()[0]).toBe(c.id);
68 expect(getConversation(app.db, alice.id, a.id)!.pinnedAt).toBeNull();
69 const plain = await (await fetch(`${servers.url}/talk/${b.id}`, { headers: { cookie: cookie(alice) } })).text();
70 expect(plain).not.toContain("data-pinned-heading");
71 });
72
73 test("each row carries its own Pin or Unpin form, and back=list returns to the list", async () => {
74 const a = mine(alice);
75 const b = mine(alice);
76 const page = async () => (await fetch(`${servers.url}/talk/${b.id}`, { headers: { cookie: cookie(alice) } })).text();
77 expect(await page()).toContain(`action="/talk/${a.id}/pin"`);
78 const res = await post(`/talk/${a.id}/pin`, alice, { pinned: "1", back: "list" });
79 expect(res.headers.get("location")).toBe("/talk");
80 expect(await page()).toMatch(new RegExp(`action="/talk/${a.id}/pin">\\s*<input[^>]*value="0"`));
81 const other = await post(`/talk/${a.id}/pin`, alice, { pinned: "0", back: "https://evil.example" });
82 expect(other.headers.get("location")).toBe(`/talk/${a.id}`);
83 });
84
85 test("pinned ones come first, newest first", async () => {
86 const x = mine(alice);
87 const y = mine(alice);
88 await post(`/talk/${x.id}/pin`, alice, { pinned: "1" });
89 await post(`/talk/${y.id}/pin`, alice, { pinned: "1" });
90 app.db.query("UPDATE conversation SET updated_at = '2099-01-01T00:00:00.000Z' WHERE id = ?1").run(x.id);
91 const top = listConversations(app.db, alice.id).slice(0, 2).map((r) => r.id);
92 expect(top).toEqual([x.id, y.id]);
93 });
94
95 test("archive clears the pin, and an archived one cannot be pinned", async () => {
96 const a = mine(alice);
97 await post(`/talk/${a.id}/pin`, alice, { pinned: "1" });
98 await post(`/talk/${a.id}/archive`, alice, { archived: "1" });
99 expect(getConversation(app.db, alice.id, a.id)!.pinnedAt).toBeNull();
100 await post(`/talk/${a.id}/archive`, alice, { archived: "0" });
101 expect(getConversation(app.db, alice.id, a.id)!.pinnedAt).toBeNull();
102 await post(`/talk/${a.id}/archive`, alice, { archived: "1" });
103 await post(`/talk/${a.id}/pin`, alice, { pinned: "1" });
104 expect(getConversation(app.db, alice.id, a.id)!.pinnedAt).toBeNull();
105 });
106
107 test("a cross-origin POST is refused and changes nothing", async () => {
108 const a = mine(alice);
109 const res = await post(`/talk/${a.id}/pin`, alice, { pinned: "1" }, "https://evil.example");
110 expect(res.status).toBeGreaterThanOrEqual(400);
111 expect(getConversation(app.db, alice.id, a.id)!.pinnedAt).toBeNull();
112 });
113
114 test("another person's conversation is refused, and signed out goes to sign in", async () => {
115 const a = mine(alice);
116 const res = await post(`/talk/${a.id}/pin`, bob, { pinned: "1" });
117 expect(res.status).toBe(404);
118 expect(getConversation(app.db, alice.id, a.id)!.pinnedAt).toBeNull();
119 const out = await fetch(`${servers.url}/talk/${a.id}/pin`, { method: "POST", redirect: "manual", headers: { origin: servers.url }, body: new URLSearchParams({ pinned: "1" }) });
120 expect(out.status).not.toBe(200);
121 expect(getConversation(app.db, alice.id, a.id)!.pinnedAt).toBeNull();
122 });
123 });
test/tui-talk-chats.test.ts +16
@@ -79,6 +79,22 @@ describe("the terminal's conversations screen", () => {
7979 expect(listConversations(app.db, alice.id).length).toBe(1);
8080 });
8181
82 test("p on the list pins, unpins, and refuses an archived one (#14564)", async () => {
83 const made = createConversation(app.db, alice.id);
84 if (!made.ok) throw new Error(made.error);
85 const id = made.value.id;
86 const pinned = () => listConversations(app.db, alice.id, { archived: false }).find((c) => c.id === id)!.pinnedAt;
87 expect(await drive(alice, [...open, "p"])).toContain("Pinned.");
88 expect(pinned()).not.toBeNull();
89 expect(await drive(alice, [...open, "p"])).toContain("Unpinned.");
90 expect(pinned()).toBeNull();
91 archiveConversation(app.db, alice.id, id, true);
92 const text = await drive(alice, [...open, "a", "p"]);
93 expect(text).toContain("Restore it first");
94 expect(listConversations(app.db, alice.id, { archived: true }).find((c) => c.id === id)!.pinnedAt).toBeNull();
95 archiveConversation(app.db, alice.id, id, false);
96 });
97
8298 test("another person's conversations are not listed", async () => {
8399 const text = await drive(bob, open);
84100 expect(text).not.toContain("Renamed");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs