From 582ba3d50004685002667c9057c1bb408fe3c5b8 Mon Sep 17 00:00:00 2001 From: Laura Thiel Date: Sun, 15 Nov 2026 16:24:14 +0100 Subject: [PATCH 1/5] feat(account): save pinned conversations on the account --- apps/server/src/app/auth.test.ts | 96 ++++++++++++++++++++ apps/server/src/contract/user-preferences.ts | 23 +++++ 2 files changed, 119 insertions(+) diff --git a/apps/server/src/app/auth.test.ts b/apps/server/src/app/auth.test.ts index 994eba9c..d9969dcd 100644 --- a/apps/server/src/app/auth.test.ts +++ b/apps/server/src/app/auth.test.ts @@ -162,3 +162,99 @@ test("closed sign-up needs an open invite, which works once", async () => { accounts.close(); } }); + +const ORIGIN = "http://localhost:7337"; + +/** Calls an auth endpoint as a client does: over HTTP, with the account's bearer token. */ +const authRequest = ( + accounts: Awaited>, + token: string, + path: string, + body?: unknown, +) => + accounts.auth.handler( + new Request(`${ORIGIN}/api/auth/${path}`, { + method: body === undefined ? "GET" : "POST", + headers: { + authorization: `Bearer ${token}`, + "content-type": "application/json", + origin: ORIGIN, + }, + body: body === undefined ? null : JSON.stringify(body), + }), + ); + +const pinsOf = async ( + accounts: Awaited>, + token: string, +) => { + const session = (await ( + await authRequest(accounts, token, "get-session") + ).json()) as { user: { pinnedConversations?: unknown } }; + + return session.user.pinnedConversations; +}; + +test("a new account has no pins", async () => { + const accounts = await createAuth( + mkdtempSync(join(tmpdir(), "auth-")), + ORIGIN, + ); + + try { + const { token } = await signUp(accounts, "pins@example.com"); + + expect(await pinsOf(accounts, token!)).toEqual([]); + } finally { + accounts.close(); + } +}); + +test("saves pins in order", async () => { + const accounts = await createAuth( + mkdtempSync(join(tmpdir(), "auth-")), + ORIGIN, + ); + + try { + const { token } = await signUp(accounts, "pins@example.com"); + const saved = await authRequest(accounts, token!, "update-user", { + pinnedConversations: ["group:g1", "agent:b1"], + }); + + expect(saved.status).toBe(200); + expect(await pinsOf(accounts, token!)).toEqual(["group:g1", "agent:b1"]); + } finally { + accounts.close(); + } +}); + +test("rejects more than nine pins, duplicates, and malformed keys", async () => { + const accounts = await createAuth( + mkdtempSync(join(tmpdir(), "auth-")), + ORIGIN, + ); + + try { + const { token } = await signUp(accounts, "pins@example.com"); + await authRequest(accounts, token!, "update-user", { + pinnedConversations: ["agent:kept"], + }); + const tooMany = Array.from({ length: 10 }, (_, index) => `agent:${index}`); + + for (const pinnedConversations of [ + tooMany, + ["agent:a", "agent:a"], + ["bot:a"], + ]) { + const response = await authRequest(accounts, token!, "update-user", { + pinnedConversations, + }); + + expect(response.status).toBe(400); + } + expect(await pinsOf(accounts, token!)).toEqual(["agent:kept"]); + } finally { + accounts.close(); + } +}); diff --git a/apps/server/src/contract/user-preferences.ts b/apps/server/src/contract/user-preferences.ts index c2685b77..284100cf 100644 --- a/apps/server/src/contract/user-preferences.ts +++ b/apps/server/src/contract/user-preferences.ts @@ -5,6 +5,20 @@ export const THEMES = ["system", "light", "dark"] as const; export type Theme = (typeof THEMES)[number]; +/** Messages allows nine pins: three rows of three. */ +export const MAX_PINS = 9; + +/** A pinned conversation: `agent:` or `group:`. */ +export const pinKey = z.string().regex(/^(agent|group):\S+$/); + +/** The pinned conversations in order, first pin first. */ +export const pinnedConversations = z + .array(pinKey) + .max(MAX_PINS) + .refine((keys) => new Set(keys).size === keys.length, { + message: "A conversation is pinned once", + }); + /** Per-person settings stored as columns on Better Auth's user table and returned with the session. */ export const userPreferenceFields = { theme: { @@ -14,4 +28,13 @@ export const userPreferenceFields = { input: true, validator: { input: z.enum(THEMES) }, }, + pinnedConversations: { + // Not "string[]": SQLite stores that as TEXT, which Better Auth then reports as a type mismatch + // on every start. "json" is also TEXT, and comes back as the array. + type: "json", + required: false, + defaultValue: [], + input: true, + validator: { input: pinnedConversations }, + }, } satisfies Record; From 011faabe1583f32ea2374697decb8e6d36449d7a Mon Sep 17 00:00:00 2001 From: Laura Thiel Date: Sun, 15 Nov 2026 16:27:47 +0100 Subject: [PATCH 2/5] feat(events): send pinned conversation changes on /v1/events --- CHANGELOG.md | 1 + apps/server/src/app/api.test.ts | 14 +++++ apps/server/src/app/auth.test.ts | 20 ++++++++ apps/server/src/app/auth.ts | 48 ++++++++++++++++-- apps/server/src/app/multi-user.test.ts | 62 +++++++++++++++++++++++ apps/server/src/app/server.ts | 11 +++- apps/server/src/app/tenant.ts | 4 ++ apps/server/src/bots/bot-activity-api.ts | 29 +++++++---- apps/server/src/bots/bots.ts | 14 ++++- apps/server/src/contract/api-contract.ts | 3 +- apps/server/src/contract/api-responses.ts | 13 +++++ openapi/openapi.json | 22 +++++++- openapi/pins-event.schema.json | 18 +++++++ 13 files changed, 240 insertions(+), 19 deletions(-) create mode 100644 openapi/pins-event.schema.json diff --git a/CHANGELOG.md b/CHANGELOG.md index ecc5f80d..7434c12b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Pinned conversations are saved on the account, so every app shows the same pins in the same order. The session returns them as `pinnedConversations`, `update-user` saves the whole list (up to nine `agent:` or `group:` keys), and `/v1/events` sends a `pins` event to the account's open apps when they change. - Bots may stay quiet after automations. A scheduled or event automation, and a succeeded script automation's result, tell the bot it can react with 👍 instead of replying when the run found nothing the owner needs, unless the automation asks for a message every time. A reaction sends no notification. Results of failed, timed-out, and interrupted script runs don't carry the note. - Push notifications wait at least three seconds after enqueue and are suppressed on every device when the reply was seen or its bot or group chat is active in a focused web tab. Request cards count as seen only after their content loads and appears in the viewport. Browser notifications and unread counters are unchanged. - Breaking: independent chat views and explicit reply acknowledgements replace the device-presence endpoint. Existing Apple and Android clients still register for and receive pushes, but must adopt the new attention API before their foreground chats suppress pushes on other devices. diff --git a/apps/server/src/app/api.test.ts b/apps/server/src/app/api.test.ts index a986e75e..4c703d19 100644 --- a/apps/server/src/app/api.test.ts +++ b/apps/server/src/app/api.test.ts @@ -737,6 +737,20 @@ describe("HTTP API for bots, chats, and activity", () => { ); }); + test("/v1/events sends pins as their own event", async () => { + const { app, service } = setup(); + + const response: Response = await req(app, "/v1/events"); + const reader = response.body!.getReader(); + service.announce({ type: "pins", pinnedConversations: ["group:g1"] }); + const text = await readUntil(reader, '"group:g1"'); + expect(text).toContain( + 'event: pins\ndata: {"pinnedConversations":["group:g1"]}', + ); + expect(text).not.toContain('event: activity\ndata: {"type":"pins"'); + await reader.cancel(); + }); + test("streams server-wide activity", async () => { const { app } = setup(); diff --git a/apps/server/src/app/auth.test.ts b/apps/server/src/app/auth.test.ts index d9969dcd..07152c24 100644 --- a/apps/server/src/app/auth.test.ts +++ b/apps/server/src/app/auth.test.ts @@ -258,3 +258,23 @@ test("rejects more than nine pins, duplicates, and malformed keys", async () => accounts.close(); } }); + +test("updating pins tells the account's listener", async () => { + const calls: [string, string[]][] = []; + const accounts = await createAuth( + mkdtempSync(join(tmpdir(), "auth-")), + ORIGIN, + { onPinsChanged: (userId, pins) => calls.push([userId, pins]) }, + ); + + try { + const { token, user } = await signUp(accounts, "pins@example.com"); + await authRequest(accounts, token!, "update-user", { + pinnedConversations: ["agent:b1"], + }); + + expect(calls).toEqual([[user.id, ["agent:b1"]]]); + } finally { + accounts.close(); + } +}); diff --git a/apps/server/src/app/auth.ts b/apps/server/src/app/auth.ts index 9b1d67f9..33a53eb7 100644 --- a/apps/server/src/app/auth.ts +++ b/apps/server/src/app/auth.ts @@ -1,3 +1,4 @@ +import { z } from "@hono/zod-openapi"; import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import { randomBytes, randomUUID } from "node:crypto"; import { join } from "node:path"; @@ -19,7 +20,10 @@ import { getMigrations } from "better-auth/db/migration"; import { eq } from "drizzle-orm"; import { drizzle } from "drizzle-orm/bun-sqlite"; import { authUsers } from "./auth-schema"; -import { userPreferenceFields } from "../contract/user-preferences"; +import { + pinnedConversations, + userPreferenceFields, +} from "../contract/user-preferences"; import { INVITE_HEADER, invites, type Invites } from "./invites"; import { serverSettingsStore, @@ -117,9 +121,38 @@ function signUpGate() { type SignUpGate = ReturnType; -const userDatabaseHooks = (gate: SignUpGate) => +/** What the server does when an account changes, beyond saving it. */ +export type AccountHooks = { + /** Every saved account update, with the pins it now has: a theme change reports unchanged pins. */ + onPinsChanged?: (userId: string, pins: string[]) => void; +}; + +/** The pins on a saved user row: Better Auth hands hooks the stored JSON text, not the array. */ +const storedPins = z + .string() + .transform((text, context) => { + try { + return pinnedConversations.parse(JSON.parse(text)); + } catch { + context.addIssue({ code: "custom", message: "Unreadable pins" }); + + return z.NEVER; + } + }) + .or(pinnedConversations) + .catch([]); + +const userDatabaseHooks = (gate: SignUpGate, hooks: AccountHooks) => ({ user: { + update: { + async after(user) { + hooks.onPinsChanged?.( + user.id, + storedPins.parse(user["pinnedConversations"]), + ); + }, + }, create: { // Every way to create a user passes here: the gate for closed sign-up and the first admin. async before(user, context) { @@ -209,6 +242,7 @@ function authOptions( baseURL: string, secretPath: string, gate: SignUpGate, + hooks: AccountHooks, ) { const passkeyOrigin = passkeyOriginFor(baseURL); @@ -222,7 +256,7 @@ function authOptions( session: { cookieCache: { enabled: false } }, rateLimit: { enabled: true, storage: "database" }, user: { additionalFields: userPreferenceFields }, - databaseHooks: userDatabaseHooks(gate), + databaseHooks: userDatabaseHooks(gate, hooks), plugins: [ bearer(), admin(), @@ -237,7 +271,11 @@ function authOptions( } satisfies BetterAuthOptions; } -export async function createAuth(dataDir: string, baseURL: string) { +export async function createAuth( + dataDir: string, + baseURL: string, + hooks: AccountHooks = {}, +) { const secretPath = join(dataDir, ".auth-secret"); if (!existsSync(secretPath)) @@ -249,7 +287,7 @@ export async function createAuth(dataDir: string, baseURL: string) { const database = new Database(join(dataDir, "auth.sqlite")); database.run("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;"); const gate = signUpGate(); - const options = authOptions(database, baseURL, secretPath, gate); + const options = authOptions(database, baseURL, secretPath, gate, hooks); try { const { runMigrations } = await getMigrations(options); diff --git a/apps/server/src/app/multi-user.test.ts b/apps/server/src/app/multi-user.test.ts index a09f54a0..62eb8293 100644 --- a/apps/server/src/app/multi-user.test.ts +++ b/apps/server/src/app/multi-user.test.ts @@ -731,3 +731,65 @@ test.serial( } }, ); + +/** Reads a stream until `text` arrives or `ms` pass, and returns what it saw. */ +async function readFor( + reader: ReadableStreamDefaultReader, + text: string, + ms: number, +) { + const decoder = new TextDecoder(); + const deadline = Date.now() + ms; + let seen = ""; + + while (!seen.includes(text) && Date.now() < deadline) { + const next = await Promise.race([ + reader.read(), + Bun.sleep(deadline - Date.now()).then(() => undefined), + ]); + + if (!next || next.done) break; + seen += decoder.decode(next.value, { stream: true }); + } + + return seen; +} + +test.serial("pins reach only their own account", async () => { + const dataDir = mkdtempSync(join(tmpdir(), "crumble-multi-user-")); + let running: Awaited> | undefined; + + try { + running = await startServer({ dataDir, port: 0 }); + const first = await signUp(running, `first-${crypto.randomUUID()}`); + const second = await signUp(running, `second-${crypto.randomUUID()}`); + const open = async (headers: Record) => + ( + await fetch(new URL("/v1/events", running!.server.url), { headers }) + ).body!.getReader(); + const firstEvents = await open(first); + const secondEvents = await open(second); + + const saved = await fetch( + new URL("/api/auth/update-user", running.server.url), + { + method: "POST", + headers: { ...json(first), origin: running.server.url.origin }, + body: JSON.stringify({ pinnedConversations: ["agent:b1"] }), + }, + ); + + expect(saved.status).toBe(200); + const firstSaw = await readFor(firstEvents, '"agent:b1"', 5_000); + expect(firstSaw).toContain("event: pins"); + expect(firstSaw).toContain('{"pinnedConversations":["agent:b1"]}'); + expect(await readFor(secondEvents, "event: pins", 1_000)).not.toContain( + "event: pins", + ); + await firstEvents.cancel(); + await secondEvents.cancel(); + } finally { + await running?.close(); + rmSync(dataDir, { recursive: true, force: true }); + } +}); diff --git a/apps/server/src/app/server.ts b/apps/server/src/app/server.ts index bb5a3229..f6c0f11f 100644 --- a/apps/server/src/app/server.ts +++ b/apps/server/src/app/server.ts @@ -225,6 +225,13 @@ function tenantPool(pool: { rmSync(accountDir(dataDir, userId), { recursive: true, force: true }); }, restore: (accounts: Accounts) => restoreTenants(dataDir, accounts, tenant), + /** Only an account that is running has streams to tell; this never starts one. */ + announcePins: (userId: string, pins: string[]) => { + void tenants + .get(userId) + ?.then((context) => context.announcePins(pins)) + .catch(() => {}); + }, outdatedWorkspaces: () => outdatedWorkspaces(tenants), close: () => closeTenants(tenants.values()), }; @@ -408,7 +415,9 @@ async function connectAccounts( dataDir: string, origin: string, ) { - state.identity = await createAuth(dataDir, origin); + state.identity = await createAuth(dataDir, origin, { + onPinsChanged: pool.announcePins, + }); state.admin = adminAPI({ accounts: state.identity, origin: () => origin, diff --git a/apps/server/src/app/tenant.ts b/apps/server/src/app/tenant.ts index 5b7851e7..cce48449 100644 --- a/apps/server/src/app/tenant.ts +++ b/apps/server/src/app/tenant.ts @@ -118,6 +118,8 @@ export type TenantRuntime = { workspaces: Workspaces | undefined; /** Deletes every bot's workspace, for an account being removed. A failure is logged, so it never rejects. */ removeWorkspaces: () => Promise; + /** Tells the account's open /v1/events streams that its pinned conversations changed. */ + announcePins: (pins: string[]) => void; close: () => Promise; }; @@ -431,6 +433,8 @@ export async function createTenant( workspaces, removeWorkspaces: () => account.runPromise(removeAccountWorkspaces(workspaces)), + announcePins: (pins) => + service.announce({ type: "pins", pinnedConversations: pins }), close: () => account.dispose(), }; }), diff --git a/apps/server/src/bots/bot-activity-api.ts b/apps/server/src/bots/bot-activity-api.ts index 796fc352..2dade344 100644 --- a/apps/server/src/bots/bot-activity-api.ts +++ b/apps/server/src/bots/bot-activity-api.ts @@ -5,20 +5,31 @@ import { sendHeartbeat, streamEvents } from "../shared/event-stream"; import { canonicalReplyEvent } from "../contract/reply-event"; import type { Activity, BotsAccess } from "./bots"; +/** The SSE event an activity is sent as, and its data. Learned and pins events are their own event names. */ +function activityFrame(data: Activity, serverId: string) { + switch (data.type) { + case "reply": + return { event: "activity", data: canonicalReplyEvent(data, serverId) }; + case "learned": + return { event: "learned", data }; + case "pins": + return { + event: "pins", + data: { pinnedConversations: data.pinnedConversations }, + }; + case "chat-preview": + return { event: "activity", data }; + } +} + /** Writes one activity as the event the clients expect, canonicalized so replies match the push payload. */ const activitySender = (serverId: string, stream: SSEStreamingApi, close: () => void) => - (data: Activity) => { - const canonical = - data.type === "reply" ? canonicalReplyEvent(data, serverId) : data; + (activity: Activity) => { + const { event, data } = activityFrame(activity, serverId); if (!stream.aborted) - stream - .writeSSE({ - event: data.type === "learned" ? "learned" : "activity", - data: JSON.stringify(canonical), - }) - .catch(close); + stream.writeSSE({ event, data: JSON.stringify(data) }).catch(close); }; export function registerBotActivityRoutes(options: { diff --git a/apps/server/src/bots/bots.ts b/apps/server/src/bots/bots.ts index fcfdc564..a0a4332e 100644 --- a/apps/server/src/bots/bots.ts +++ b/apps/server/src/bots/bots.ts @@ -47,7 +47,17 @@ export type LearnedActivity = { createdAt: string; }; -export type Activity = ReplyActivity | ChatPreviewActivity | LearnedActivity; +/** The account's pinned conversations changed; the whole list, first pin first. */ +export type PinsActivity = { + type: "pins"; + pinnedConversations: string[]; +}; + +export type Activity = + | ReplyActivity + | ChatPreviewActivity + | LearnedActivity + | PinsActivity; type ReferencedMessage = TranscriptMessage & { replyReferences: ReplyReference[]; @@ -98,7 +108,7 @@ export class Bots extends Context.Service< answer: JobAnswer, ) => Effect.Effect; readonly announce: ( - event: ReplyActivity | LearnedActivity, + event: ReplyActivity | LearnedActivity | PinsActivity, ) => Effect.Effect; readonly snapshot: ( conversationId: string, diff --git a/apps/server/src/contract/api-contract.ts b/apps/server/src/contract/api-contract.ts index bd9a5f30..37c0ae9c 100644 --- a/apps/server/src/contract/api-contract.ts +++ b/apps/server/src/contract/api-contract.ts @@ -985,10 +985,11 @@ export const routes = { "x-sse-events": { activity: { $ref: "#/components/schemas/ActivityEvent" }, learned: { $ref: "#/components/schemas/LearnedEvent" }, + pins: { $ref: "#/components/schemas/PinsEvent" }, heartbeat: { $ref: "#/components/schemas/HeartbeatEvent" }, }, description: - "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Current chat previews replay on connection; finished replies and learned events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", + "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Each pins event carries a PinsEvent: the account's pinned conversations after a change, which the session also returns. Current chat previews replay on connection; finished replies, learned events, and pins events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", responses: { 200: { description: "SSE stream, not a JSON array", diff --git a/apps/server/src/contract/api-responses.ts b/apps/server/src/contract/api-responses.ts index 7d81f7df..95b74822 100644 --- a/apps/server/src/contract/api-responses.ts +++ b/apps/server/src/contract/api-responses.ts @@ -24,6 +24,7 @@ import { SKILL_STATES } from "./skills"; import { avatarDefinitionSchema } from "./avatar"; import { replyEvent } from "./reply-event"; import { replyReference } from "./push"; +import { pinnedConversations } from "./user-preferences"; import { voiceCallCancelEvent, voiceCallEvent, @@ -1228,6 +1229,13 @@ export const activityEvent = z .discriminatedUnion("type", [replyEvent, chatPreviewEvent]) .openapi("ActivityEvent"); +export const pinsEvent = z + .object({ pinnedConversations }) + .openapi("PinsEvent", { + description: + "The account's pinned conversations changed, sent as the `pins` event on /v1/events with the whole list, first pin first. Not replayed: read the session on connect.", + }); + export const heartbeatEvent = z.object({}).openapi("HeartbeatEvent"); export const eventSchemas: { @@ -1252,6 +1260,11 @@ export const eventSchemas: { component: "LearnedEvent", artifact: "learned-event.schema.json", }, + { + schema: pinsEvent, + component: "PinsEvent", + artifact: "pins-event.schema.json", + }, { schema: chatSnapshotResponse, artifact: "chat-snapshot.schema.json" }, { schema: groupChatSnapshotResponse, diff --git a/openapi/openapi.json b/openapi/openapi.json index e11d3196..27b530f2 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -213,6 +213,23 @@ ], "description": "A bot's review of one of its turns changed its skills or memory, sent as the `learned` event on /v1/events. Clients show a short notice in the bot chat and link to the change record." }, + "PinsEvent": { + "type": "object", + "properties": { + "pinnedConversations": { + "type": "array", + "items": { + "type": "string", + "pattern": "^(agent|group):\\S+$" + }, + "maxItems": 9 + } + }, + "required": [ + "pinnedConversations" + ], + "description": "The account's pinned conversations changed, sent as the `pins` event on /v1/events with the whole list, first pin first. Not replayed: read the session on connect." + }, "VoiceGatewayConfigEvent": { "type": "object", "properties": { @@ -17134,11 +17151,14 @@ "learned": { "$ref": "#/components/schemas/LearnedEvent" }, + "pins": { + "$ref": "#/components/schemas/PinsEvent" + }, "heartbeat": { "$ref": "#/components/schemas/HeartbeatEvent" } }, - "description": "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Current chat previews replay on connection; finished replies and learned events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", + "description": "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Each pins event carries a PinsEvent: the account's pinned conversations after a change, which the session also returns. Current chat previews replay on connection; finished replies, learned events, and pins events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", "security": [ { "BearerAuth": [] diff --git a/openapi/pins-event.schema.json b/openapi/pins-event.schema.json new file mode 100644 index 00000000..0b582652 --- /dev/null +++ b/openapi/pins-event.schema.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "pinnedConversations": { + "maxItems": 9, + "type": "array", + "items": { + "type": "string", + "pattern": "^(agent|group):\\S+$" + } + } + }, + "required": [ + "pinnedConversations" + ], + "additionalProperties": true +} From 6f933b8741ac2ae9fc17cf5c911109abf961251a Mon Sep 17 00:00:00 2001 From: Laura Thiel Date: Sun, 15 Nov 2026 16:34:19 +0100 Subject: [PATCH 3/5] feat(web): pin conversations in the sidebar --- CHANGELOG.md | 2 +- apps/docs/content/clients/web.md | 19 +-- apps/web/app/activity-stream.ts | 17 ++- apps/web/app/shell.tsx | 233 +++++++++++++++++++++++++++---- apps/web/lib/pins.dom.test.tsx | 228 ++++++++++++++++++++++++++++++ apps/web/lib/pins.ts | 113 +++++++++++++++ 6 files changed, 571 insertions(+), 41 deletions(-) create mode 100644 apps/web/lib/pins.dom.test.tsx create mode 100644 apps/web/lib/pins.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7434c12b..80e3bae6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- Pinned conversations are saved on the account, so every app shows the same pins in the same order. The session returns them as `pinnedConversations`, `update-user` saves the whole list (up to nine `agent:` or `group:` keys), and `/v1/events` sends a `pins` event to the account's open apps when they change. +- Pinned conversations are saved on the account, so every app shows the same pins in the same order. The session returns them as `pinnedConversations`, `update-user` saves the whole list (up to nine `agent:` or `group:` keys), and `/v1/events` sends a `pins` event to the account's open apps when they change. On the web, pin or unpin a bot chat or group chat from its **More** menu in the sidebar, and drag pins in the **Pinned** section to reorder them. - Bots may stay quiet after automations. A scheduled or event automation, and a succeeded script automation's result, tell the bot it can react with 👍 instead of replying when the run found nothing the owner needs, unless the automation asks for a message every time. A reaction sends no notification. Results of failed, timed-out, and interrupted script runs don't carry the note. - Push notifications wait at least three seconds after enqueue and are suppressed on every device when the reply was seen or its bot or group chat is active in a focused web tab. Request cards count as seen only after their content loads and appears in the viewport. Browser notifications and unread counters are unchanged. - Breaking: independent chat views and explicit reply acknowledgements replace the device-presence endpoint. Existing Apple and Android clients still register for and receive pushes, but must adopt the new attention API before their foreground chats suppress pushes on other devices. diff --git a/apps/docs/content/clients/web.md b/apps/docs/content/clients/web.md index df00e81d..4b326bb1 100644 --- a/apps/docs/content/clients/web.md +++ b/apps/docs/content/clients/web.md @@ -12,15 +12,16 @@ Sign in with the account you created when you ## Sidebar -| Section | What's there | -| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| **Bots** | Each bot's chat, with its jobs and desktop. | -| **Group chats** | Chats with several bots. | -| **Memory** | Every bot's memories and your shared memories. Edit or delete them here. | -| **Automations** | Every automation with its schedule, next run, and status, plus a **Runs** tab with recent runs. | -| **Activity** | Everything bots did, by day. Filter by kind or bot, and revert a change to a skill or memory. | -| **Theme** | System, Light, or Dark. The choice is saved to your account, so your other devices use it too. | -| **Settings** | Providers, web search, credentials, logins, the judge and vision models, MCP integrations, skills, notifications, passkeys, and sign-out. | +| Section | What's there | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Pinned** | Up to nine bot chats and group chats. Pin or unpin one from its **More** menu, and drag pins to reorder them. Your other apps show the same pins. | +| **Bots** | Each bot's chat, with its jobs and desktop. | +| **Group chats** | Chats with several bots. | +| **Memory** | Every bot's memories and your shared memories. Edit or delete them here. | +| **Automations** | Every automation with its schedule, next run, and status, plus a **Runs** tab with recent runs. | +| **Activity** | Everything bots did, by day. Filter by kind or bot, and revert a change to a skill or memory. | +| **Theme** | System, Light, or Dark. The choice is saved to your account, so your other devices use it too. | +| **Settings** | Providers, web search, credentials, logins, the judge and vision models, MCP integrations, skills, notifications, passkeys, and sign-out. | Press `⌘K`, or `Ctrl+K`, or select **Search** in the sidebar to open the command palette. It jumps to a bot, group chat, workspace page, or settings diff --git a/apps/web/app/activity-stream.ts b/apps/web/app/activity-stream.ts index 32d5da92..ae60943a 100644 --- a/apps/web/app/activity-stream.ts +++ b/apps/web/app/activity-stream.ts @@ -1,5 +1,9 @@ import { useSyncExternalStore } from "react"; -import { activityEvent } from "@crumble/server/contract/api-responses"; +import { + activityEvent, + pinsEvent, +} from "@crumble/server/contract/api-responses"; +import { authClient } from "@/lib/auth-client"; import { type Bot, botsQuery, invalidateBots } from "@/features/bots/api"; import { groupChatQuery, invalidateGroups } from "@/features/group-chats/api"; import { chatQuery } from "@/features/chat/api"; @@ -64,13 +68,22 @@ export function followActivity(links: ChatLinks, signal: AbortSignal) { { onStatus: report, onOpen: () => { - // Bots and groups may have changed while the stream was down. + // Bots, groups, and pins may have changed while the stream was down. if (connections++ > 0) { void invalidateBots(); void invalidateGroups(); + authClient.$store.notify("$sessionSignal"); } }, onEvent: (name, data) => { + if (name === "pins") { + // Checked against the contract, but the session is what the sidebar reads. + pinsEvent.parse(JSON.parse(data)); + authClient.$store.notify("$sessionSignal"); + + return; + } + if (name !== "activity") return; const event = activityEvent.parse(JSON.parse(data)); diff --git a/apps/web/app/shell.tsx b/apps/web/app/shell.tsx index f66d936d..d59f3336 100644 --- a/apps/web/app/shell.tsx +++ b/apps/web/app/shell.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { type ComponentProps, useEffect, useRef, useState } from "react"; import { useQuery, type UseQueryResult } from "@tanstack/react-query"; import { Link, @@ -8,7 +8,14 @@ import { useRouterState, Outlet, } from "@tanstack/react-router"; -import { IconPlus, IconSearch, IconSettings } from "@tabler/icons-react"; +import { + IconDots, + IconPin, + IconPinnedOff, + IconPlus, + IconSearch, + IconSettings, +} from "@tabler/icons-react"; import { Sidebar, SidebarContent, @@ -20,6 +27,7 @@ import { SidebarHeader, SidebarInset, SidebarMenu, + SidebarMenuAction, SidebarMenuButton, SidebarMenuItem, SidebarMenuSkeleton, @@ -30,6 +38,7 @@ import { import { DropdownMenu, DropdownMenuContent, + DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger, @@ -51,6 +60,7 @@ import { useTheme, } from "@/lib/theme"; import { resetSession, signedOut } from "@/lib/session"; +import { botPin, groupPin, type Pins, usePins } from "@/lib/pins"; import { botStatusLine, isBusy, useWorking } from "@/features/bot-chat/working"; import { followActivity, useConnectionStatus } from "./activity-stream"; import { markSeen, useUnreadCount } from "@/lib/notifications"; @@ -158,6 +168,7 @@ export function Shell() { const bots = useQuery(botsQuery); const groups = useQuery(groupsQuery); const [paletteOpen, setPaletteOpen] = useState(false); + const pins = usePins(bots.data, groups.data); useResetOnUserChange(session.data?.user.id); useFollowActivity(); useDocumentTitle(bots.data, groups.data); @@ -175,8 +186,9 @@ export function Shell() { setPaletteOpen(true)} /> - - + + + @@ -194,7 +206,140 @@ export function Shell() { ); } -function BotsSection({ bots }: { bots: UseQueryResult }) { +type DragProps = Pick< + ComponentProps<"li">, + "draggable" | "onDragStart" | "onDragOver" | "onDrop" | "onDragEnd" +>; + +function PinnedSection({ + pins, + bots, + groups, +}: { + pins: Pins; + bots: Bot[] | undefined; + groups: GroupChat[] | undefined; +}) { + const matchRoute = useMatchRoute(); + const dragged = useRef(null); + + if (pins.pinned.length === 0) return null; + + const botsById = new Map(bots?.map((bot) => [bot.id, bot])); + const botsByPin = new Map(bots?.map((bot) => [botPin(bot.id), bot])); + + const groupsByPin = new Map( + groups?.map((group) => [groupPin(group.id), group]), + ); + + const drag = (key: string): DragProps => ({ + draggable: true, + onDragStart: (event) => { + dragged.current = key; + event.dataTransfer.effectAllowed = "move"; + }, + onDragOver: (event) => { + if (!dragged.current || dragged.current === key) return; + + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + }, + onDrop: (event) => { + event.preventDefault(); + + if (dragged.current) pins.move(dragged.current, key); + + dragged.current = null; + }, + onDragEnd: () => { + dragged.current = null; + }, + }); + + return ( + + Pinned + + + {pins.pinned.map((key) => { + const bot = botsByPin.get(key); + const group = groupsByPin.get(key); + + if (bot) + return ( + + ); + + return ( + group && ( + + ) + ); + })} + + + + ); +} + +function PinAction({ + conversation, + pins, +}: { + conversation: string; + pins: Pins; +}) { + if (!pins.ready) return null; + + const pinned = pins.isPinned(conversation); + + return ( + + } + > + + + + + pinned ? pins.unpin(conversation) : pins.pin(conversation) + } + > + {pinned ? : } + {pinned ? "Unpin" : "Pin"} + + + + ); +} + +function BotsSection({ + bots, + pins, +}: { + bots: UseQueryResult; + pins: Pins; +}) { const matchRoute = useMatchRoute(); return ( @@ -212,19 +357,22 @@ function BotsSection({ bots }: { bots: UseQueryResult }) { ))} - {bots.data?.map((bot) => ( - - ))} + {bots.data + ?.filter((bot) => !pins.isPinned(botPin(bot.id))) + .map((bot) => ( + + ))} {bots.data?.length === 0 && (

No bots yet

)} @@ -240,9 +388,11 @@ function BotsSection({ bots }: { bots: UseQueryResult }) { function GroupsSection({ bots, groups, + pins, }: { bots: Bot[] | undefined; groups: GroupChat[] | undefined; + pins: Pins; }) { const byId = new Map(bots?.map((bot) => [bot.id, bot])); const canGroup = (bots?.length ?? 0) >= MIN_GROUP_MEMBERS; @@ -261,13 +411,16 @@ function GroupsSection({ )} - {groups?.map((group) => ( - - ))} + {groups + ?.filter((group) => !pins.isPinned(groupPin(group.id))) + .map((group) => ( + + ))} {groups?.length === 0 && (

{canGroup @@ -281,11 +434,21 @@ function GroupsSection({ ); } -function GroupRow({ group, members }: { group: GroupChat; members: Bot[] }) { +function GroupRow({ + group, + members, + pins, + drag, +}: { + group: GroupChat; + members: Bot[]; + pins: Pins; + drag?: DragProps; +}) { const matchRoute = useMatchRoute(); return ( - + + ); } @@ -430,11 +594,21 @@ function ConnectionStatus() { ); } -function BotRow({ bot, active }: { bot: Bot; active: boolean }) { +function BotRow({ + bot, + active, + pins, + drag, +}: { + bot: Bot; + active: boolean; + pins: Pins; + drag?: DragProps; +}) { const working = isBusy(useWorking(bot.id)); return ( - + + ); } diff --git a/apps/web/lib/pins.dom.test.tsx b/apps/web/lib/pins.dom.test.tsx new file mode 100644 index 00000000..4be39934 --- /dev/null +++ b/apps/web/lib/pins.dom.test.tsx @@ -0,0 +1,228 @@ +import { afterAll, beforeAll, beforeEach, expect, spyOn, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { z } from "zod"; +import { settle, waitFor } from "@/test/wait-for"; +import type { Pins } from "./pins"; + +type Conversation = { id: string }; + +const window = new Window({ url: "http://localhost" }); +const globals = Object.getOwnPropertyDescriptors(globalThis); + +const values = { + window, + document: window.document, + HTMLElement: window.HTMLElement, + Element: window.Element, + Node: window.Node, + MutationObserver: window.MutationObserver, + getComputedStyle: window.getComputedStyle.bind(window), + Event: window.Event, + IS_REACT_ACT_ENVIRONMENT: true, + requestAnimationFrame: window.requestAnimationFrame.bind(window), + cancelAnimationFrame: window.cancelAnimationFrame.bind(window), +}; + +/** The account's list on the stub server, and every list written to it. */ +let stored: string[] = []; +let written: string[][] = []; +let failWrites = false; +let release = () => {}; +let pins: Pins | undefined; +let root: Root; +let notifySession: () => void; + +let renderPins: ( + bots?: Conversation[], + groups?: Conversation[], +) => Promise; + +let fetch: ReturnType; + +const removedListeners = spyOn(window, "removeEventListener"); + +const stubServer = () => + spyOn(globalThis, "fetch").mockImplementation( + Object.assign( + async (input: RequestInfo | URL, init?: RequestInit) => { + const path = input instanceof Request ? input.url : input.toString(); + + if (path.endsWith("/update-user")) { + const body = z + .object({ pinnedConversations: z.array(z.string()) }) + .parse(JSON.parse(z.string().parse(init?.body))); + + written.push(body.pinnedConversations); + + if (failWrites) { + await new Promise((resolve) => { + release = resolve; + }); + + return new Response("Unavailable", { status: 503 }); + } + + stored = body.pinnedConversations; + + return Response.json({ status: true }); + } + + if (path.endsWith("/get-session")) + return Response.json({ + session: { id: "s", userId: "u" }, + user: { id: "u", pinnedConversations: stored }, + }); + + return Response.json(null); + }, + { preconnect: globalThis.fetch.preconnect }, + ), + ); + +const bots = [{ id: "a" }, { id: "b" }]; +const groups = [{ id: "g" }]; + +const current = () => { + if (!pins) throw new Error("usePins has not rendered"); + + return pins; +}; + +const shows = (keys: string[]) => () => + JSON.stringify(current().pinned) === JSON.stringify(keys); + +/** Loads `keys` as the session's list and waits for the hook to show `expected`. */ +async function load(keys: string[], expected = keys) { + stored = keys; + await act(async () => notifySession()); + await waitFor(shows(expected), `pins ${expected.join(",")}`); + written = []; +} + +beforeAll(async () => { + fetch = stubServer(); + + for (const [key, value] of Object.entries(values)) + Object.defineProperty(globalThis, key, { configurable: true, value }); + + const { createRoot } = await import("react-dom/client"); + const { usePins } = await import("./pins"); + const { authClient } = await import("./auth-client"); + const container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + notifySession = () => authClient.$store.notify("$sessionSignal"); + + function Harness(props: { + bots: Conversation[] | undefined; + groups: Conversation[] | undefined; + }) { + pins = usePins(props.bots, props.groups); + + return null; + } + + renderPins = async (nextBots, nextGroups) => { + await act(async () => + root.render(), + ); + }; +}); + +beforeEach(async () => { + failWrites = false; + await renderPins(bots, groups); +}); + +afterAll(async () => { + await act(async () => root.unmount()); + // The auth client stops a second after its last consumer, and needs the window to. + await waitFor( + () => removedListeners.mock.calls.some(([type]) => type === "storage"), + "the session store to stop", + ); + fetch.mockRestore(); + + for (const key of Object.keys(values)) { + if (globals[key]) Object.defineProperty(globalThis, key, globals[key]); + else Reflect.deleteProperty(globalThis, key); + } + + window.close(); +}); + +test("pin adds the conversation at the end", async () => { + await load(["group:g"]); + await act(async () => current().pin("agent:a")); + expect(current().pinned).toEqual(["group:g", "agent:a"]); + await waitFor(() => stored.length === 2, "the write"); + expect(written).toEqual([["group:g", "agent:a"]]); + await settle(); + expect(current().pinned).toEqual(["group:g", "agent:a"]); +}); + +test("unpin removes the conversation", async () => { + await load(["agent:a", "group:g"]); + await act(async () => current().unpin("agent:a")); + expect(current().pinned).toEqual(["group:g"]); + await waitFor(() => written.length === 1, "the write"); + expect(written).toEqual([["group:g"]]); +}); + +test("move puts the conversation at the target's place", async () => { + await load(["agent:a", "agent:b", "group:g"]); + await act(async () => current().move("agent:a", "group:g")); + expect(current().pinned).toEqual(["agent:b", "group:g", "agent:a"]); + await act(async () => current().move("agent:a", "agent:b")); + expect(current().pinned).toEqual(["agent:a", "agent:b", "group:g"]); + await waitFor(shows(["agent:a", "agent:b", "group:g"]), "the saved order"); + await waitFor(() => stored[0] === "agent:a", "the last write"); + expect(written.at(-1)).toEqual(["agent:a", "agent:b", "group:g"]); +}); + +test("a write drops pins for conversations that are gone", async () => { + await load(["agent:gone", "agent:a"], ["agent:a"]); + await act(async () => current().pin("group:g")); + await waitFor(() => written.length === 1, "the write"); + expect(written).toEqual([["agent:a", "group:g"]]); +}); + +test("a tenth pin is refused", async () => { + const many = Array.from({ length: 10 }, (_, index) => ({ id: `${index}` })); + await renderPins(many, groups); + + const nine = many.slice(0, 9).map(({ id }) => `agent:${id}`); + await load(nine); + expect(current().canPin("agent:9")).toBe(false); + await act(async () => current().pin("agent:9")); + await settle(); + expect(written).toEqual([]); + expect(current().pinned).toEqual(nine); +}); + +test("changes wait until bots and groups have loaded", async () => { + await load(["agent:a"]); + await renderPins(bots, undefined); + expect(current().ready).toBe(false); + expect(current().canPin("agent:b")).toBe(false); + await act(async () => { + current().pin("agent:b"); + current().unpin("agent:a"); + }); + await settle(); + expect(written).toEqual([]); + expect(stored).toEqual(["agent:a"]); +}); + +test("a failed write rolls back to the session's list", async () => { + await load(["agent:a"]); + failWrites = true; + await act(async () => current().pin("agent:b")); + await waitFor(() => written.length === 1, "the write"); + expect(current().pinned).toEqual(["agent:a", "agent:b"]); + await act(async () => release()); + await waitFor(shows(["agent:a"]), "the rollback"); + expect(written).toEqual([["agent:a", "agent:b"]]); +}); diff --git a/apps/web/lib/pins.ts b/apps/web/lib/pins.ts new file mode 100644 index 00000000..5d4f63ea --- /dev/null +++ b/apps/web/lib/pins.ts @@ -0,0 +1,113 @@ +import { useRef, useState } from "react"; +import { + MAX_PINS, + pinnedConversations, +} from "@crumble/server/contract/user-preferences"; +import { authClient } from "@/lib/auth-client"; + +type Conversation = { id: string }; + +export const botPin = (id: string) => `agent:${id}`; + +export const groupPin = (id: string) => `group:${id}`; + +const savedPins = pinnedConversations.catch([]); + +export type Pins = { + /** The pinned conversations that exist, first pin first. */ + pinned: string[]; + /** False until the bots and groups load; until then every change is refused. */ + ready: boolean; + isPinned: (key: string) => boolean; + canPin: (key: string) => boolean; + pin: (key: string) => void; + unpin: (key: string) => void; + move: (key: string, target: string) => void; +}; + +/** + * The account's pinned conversations. Changes show at once and save the whole + * list, one write at a time; afterwards the session's list takes over again, + * which also rolls back a failed write. + */ +export function usePins( + bots: Conversation[] | undefined, + groups: Conversation[] | undefined, +): Pins { + const session = authClient.useSession(); + const [wanted, setWanted] = useState(null); + + const writes = useRef<{ next: string[] | null; running: boolean }>({ + next: null, + running: false, + }); + + const { refetch } = session; + + // A list filtered to conversations that haven't loaded would wipe every pin. + const ready = bots !== undefined && groups !== undefined; + + const existing = new Set([ + ...(bots ?? []).map(({ id }) => botPin(id)), + ...(groups ?? []).map(({ id }) => groupPin(id)), + ]); + + const pinned = ( + wanted ?? savedPins.parse(session.data?.user.pinnedConversations) + ).filter((key) => existing.has(key)); + + async function save() { + const queue = writes.current; + queue.running = true; + + while (queue.next) { + while (queue.next) { + const pinnedConversations = queue.next; + queue.next = null; + + // The session is read once every write is done, so it can't show an older list in between. + await authClient + .updateUser({ pinnedConversations }, { disableSignal: true }) + .catch(() => null); + } + + await refetch().catch(() => null); + } + + queue.running = false; + setWanted(null); + } + + function change(next: string[]) { + setWanted(next); + writes.current.next = next; + + if (!writes.current.running) void save(); + } + + const isPinned = (key: string) => pinned.includes(key); + + const canPin = (key: string) => + ready && existing.has(key) && !isPinned(key) && pinned.length < MAX_PINS; + + return { + pinned, + ready, + isPinned, + canPin, + pin: (key) => { + if (canPin(key)) change([...pinned, key]); + }, + unpin: (key) => { + if (ready && isPinned(key)) change(pinned.filter((each) => each !== key)); + }, + move: (key, target) => { + if (!ready || key === target || !isPinned(key) || !isPinned(target)) + return; + + const next = pinned.filter((each) => each !== key); + next.splice(pinned.indexOf(target), 0, key); + change(next); + }, + }; +} From 8d758e34d0007003a533e28848c1df387c58131f Mon Sep 17 00:00:00 2001 From: Laura Thiel Date: Sun, 15 Nov 2026 16:37:46 +0100 Subject: [PATCH 4/5] fix(web): wait for the session's pins before changing them --- apps/web/lib/pins.dom.test.tsx | 20 +++++++++++++++++++- apps/web/lib/pins.ts | 9 +++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/apps/web/lib/pins.dom.test.tsx b/apps/web/lib/pins.dom.test.tsx index 4be39934..74583d98 100644 --- a/apps/web/lib/pins.dom.test.tsx +++ b/apps/web/lib/pins.dom.test.tsx @@ -29,6 +29,10 @@ const values = { let stored: string[] = []; let written: string[][] = []; let failWrites = false; + +/** Answers sessions without a pins list, as before it loads or from an older server. */ +let omitPins = false; + let release = () => {}; let pins: Pins | undefined; let root: Root; @@ -72,7 +76,9 @@ const stubServer = () => if (path.endsWith("/get-session")) return Response.json({ session: { id: "s", userId: "u" }, - user: { id: "u", pinnedConversations: stored }, + user: omitPins + ? { id: "u" } + : { id: "u", pinnedConversations: stored }, }); return Response.json(null); @@ -133,6 +139,7 @@ beforeAll(async () => { beforeEach(async () => { failWrites = false; + omitPins = false; await renderPins(bots, groups); }); @@ -226,3 +233,14 @@ test("a failed write rolls back to the session's list", async () => { await waitFor(shows(["agent:a"]), "the rollback"); expect(written).toEqual([["agent:a", "agent:b"]]); }); + +test("changes wait until the session's list has loaded", async () => { + await load(["agent:a"]); + omitPins = true; + await act(async () => notifySession()); + await waitFor(() => !current().ready, "the list to go"); + await act(async () => current().pin("agent:b")); + await settle(); + expect(written).toEqual([]); + expect(stored).toEqual(["agent:a"]); +}); diff --git a/apps/web/lib/pins.ts b/apps/web/lib/pins.ts index 5d4f63ea..6dd4abd8 100644 --- a/apps/web/lib/pins.ts +++ b/apps/web/lib/pins.ts @@ -44,8 +44,13 @@ export function usePins( const { refetch } = session; - // A list filtered to conversations that haven't loaded would wipe every pin. - const ready = bots !== undefined && groups !== undefined; + // A list filtered to conversations that haven't loaded would wipe every pin, and so would one + // written before the session's list arrives. A server too old to keep pins never sends one. + const ready = + bots !== undefined && + groups !== undefined && + pinnedConversations.safeParse(session.data?.user.pinnedConversations) + .success; const existing = new Set([ ...(bots ?? []).map(({ id }) => botPin(id)), From f71a1e21b0de16e08e4ff16a0feca11b91c189f2 Mon Sep 17 00:00:00 2001 From: Laura Thiel Date: Sun, 15 Nov 2026 16:40:03 +0100 Subject: [PATCH 5/5] fix(account): read pins of accounts from before pins as none --- apps/server/src/app/auth.test.ts | 17 +++++++++++++++++ apps/server/src/contract/user-preferences.ts | 3 +++ 2 files changed, 20 insertions(+) diff --git a/apps/server/src/app/auth.test.ts b/apps/server/src/app/auth.test.ts index 07152c24..861f8d91 100644 --- a/apps/server/src/app/auth.test.ts +++ b/apps/server/src/app/auth.test.ts @@ -278,3 +278,20 @@ test("updating pins tells the account's listener", async () => { accounts.close(); } }); + +test("an account from before pins reads as no pins", async () => { + const dataDir = mkdtempSync(join(tmpdir(), "auth-")); + const accounts = await createAuth(dataDir, ORIGIN); + + try { + const { token } = await signUp(accounts, "older@example.com"); + // Accounts made before the column existed have NULL there, not the default. + const database = new Database(join(dataDir, "auth.sqlite")); + database.run('update user set "pinnedConversations" = NULL'); + database.close(); + + expect(await pinsOf(accounts, token!)).toEqual([]); + } finally { + accounts.close(); + } +}); diff --git a/apps/server/src/contract/user-preferences.ts b/apps/server/src/contract/user-preferences.ts index 284100cf..1af100dc 100644 --- a/apps/server/src/contract/user-preferences.ts +++ b/apps/server/src/contract/user-preferences.ts @@ -36,5 +36,8 @@ export const userPreferenceFields = { defaultValue: [], input: true, validator: { input: pinnedConversations }, + // Accounts from before this field hold NULL, not the default; they have no pins yet. Clients + // read a missing field as a server too old to keep pins, so NULL must not look like that. + transform: { output: (value) => value ?? [] }, }, } satisfies Record;