diff --git a/crates/plugin-manager/src/lib.rs b/crates/plugin-manager/src/lib.rs index d0adc67712..b149259f50 100644 --- a/crates/plugin-manager/src/lib.rs +++ b/crates/plugin-manager/src/lib.rs @@ -542,6 +542,8 @@ pub fn bundled_manifests() -> Vec { "../../../src/bundled/changesets/manifest.json" )) .expect("changesets manifest"), + serde_json::from_str(include_str!("../../../src/bundled/threads/manifest.json")) + .expect("threads manifest"), ] } /// New bundles must opt in to the default-on policy. @@ -564,6 +566,7 @@ fn enabled_by_default(id: &str) -> bool { | "buzz.watching" | "buzz.pairing" | "buzz.inbox" + | "buzz.threads" | "buzz.repos" | "buzz.agents" | "buzz.claude-code" diff --git a/docs/buzz-help.md b/docs/buzz-help.md index fd35b457de..b20604ee3f 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -533,6 +533,12 @@ and are asked to sign in again in Buzz. New reactions from updated clients appear; older unaddressed reactions are not backfilled. While Buzz is visible, a live reaction briefly replaces the Activity bell with its emoji for three seconds. Further reactions during that hold do not change the icon; history loading does not trigger it. +- **Thread titles** are shared, channel-visible names for threads. A titled thread shows its title under + its first message in the channel (choose it to open the thread) and on its thread tab. Renaming a thread + tab sets the shared title. If it can't be saved, the tab shows the current title again and an error says why, + with Retry; if someone else changed the title first, rename the tab again to replace theirs. + Agents and the `buzz threads title` CLI also set titles, and Buzz 0.x shows the same titles; they are not + searchable. Provided by the optional Named threads plugin, on by default. - **New messages** marks the first known unread incoming channel message when you enter. Once established, the divider stays in place for that visit as you read, reveal another message, or receive new messages. In a channel with more diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index bd529c3f90..7c6b31da10 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -1367,7 +1367,7 @@ contracts with their own layout and local navigation. **Channels is the only required bundled plugin.** Todos, Usage, Reminders, Workflows, Changesets, Shared compute, Charts and File viewer are off by default for fresh installs. Bestie, Feedback, Diff viewer, Identity Naming, Agent Activity, Terminal, Links, GitHub, Inbox, -Repositories, Agents, Claude, Codex, Builderlab, +Named threads, Repositories, Agents, Claude, Codex, Builderlab, Membership, and Moderation are on by default, but optional. Both browser and native catalogs declare that policy. diff --git a/src/bundled/channels/useConversationTabs.titles.test.tsx b/src/bundled/channels/useConversationTabs.titles.test.tsx new file mode 100644 index 0000000000..09463d41c3 --- /dev/null +++ b/src/bundled/channels/useConversationTabs.titles.test.tsx @@ -0,0 +1,390 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { + enableThreadTitles, + threadTitleStore, +} from "../../features/messages/thread-title-store"; +import { titleRevision } from "../../features/messages/thread-titles"; +import type { Panels } from "../../features/panels/service"; +import type { ReadFilter, RelayEvent } from "../../features/relay/events"; +import { PublishRejected } from "../../features/relay/outbox"; +import type { RelayData } from "../../features/relay/service"; +import type { RelaySession } from "../../features/relay/session"; +import { channelTabs, useChannelTabState } from "./useChannelTabState"; +import { useConversationTabs } from "./useConversationTabs"; + +const toasts = vi.hoisted(() => ({ + notify: vi.fn< + ( + title: string, + tone: string, + action?: { label: string; onClick(): void }, + ) => string + >(() => ""), +})); +vi.mock("../../shared/design-system/ui/Toast", () => ({ + useToastNotification: () => toasts.notify, +})); + +// The Named threads plugin turns shared titles on while it runs. +let disable: (() => void) | undefined; +beforeEach(() => { + disable = enableThreadTitles(); + toasts.notify.mockClear(); +}); +afterEach(() => { + cleanup(); + disable?.(); +}); + +const ALPHA = "11111111-1111-4111-8111-111111111111"; +const ROOT = "a".repeat(64); +const TAB = `thread:${ALPHA}:${ROOT}`; + +async function harness({ + title, + publish = vi.fn(async () => ""), +}: { + title?: string; + publish?: (event: RelayEvent) => Promise; +} = {}) { + const heads: RelayEvent[] = []; + if (title) { + const template = await titleRevision(ALPHA, ROOT, { op: "create" }, title); + heads.push({ + ...template, + id: "e1", + pubkey: "f".repeat(64), + sig: "", + } as unknown as RelayEvent); + } + const snapshotRead = vi.fn(async (filters: readonly ReadFilter[]) => { + const [filter] = filters; + return heads.filter((head) => + head.tags.some(([k, v]) => + filter?.["#d"] ? k === "d" && v === filter["#d"][0] : k === "h", + ), + ); + }); + const channels = [{ id: ALPHA, name: "alpha" }]; + const writer = { + sign: vi.fn(async (t: { tags: string[][]; content: string }) => ({ + ...t, + kind: 45010, + created_at: 1, + id: "new", + pubkey: "f".repeat(64), + sig: "", + })), + publish, + }; + const writerTaken = vi.fn(); + const session = { + viewer: "viewer", + snapshotRead, + // Counted: only a shared title write takes the writer. + get configArtifactWriter() { + writerTaken(); + return writer; + }, + artifacts: { follow: () => () => {} }, + channels: { + list: () => ({ status: "ready", channels }), + ensureList: () => () => {}, + subscribeList: () => () => {}, + window: () => ({ + rows: [{ id: ROOT, content: "Original message" }], + }), + }, + } as unknown as RelaySession; + const available: never[] = []; + const panels = { + snapshot: () => available, + subscribe: () => () => {}, + } as unknown as Panels; + const relay = { + snapshot: () => ({ status: "ready", session }), + } as unknown as RelayData; + const h = renderHook(() => { + const state = useChannelTabState(session, ALPHA); + const workspace = useConversationTabs({ + profiles: new Map(), + state, + relay, + session, + panels, + current: channels[0], + channels, + scope: "scope:viewer", + conversationIcon: () => null, + leadingIds: [], + continuingVisit: true, + isLive: () => true, + openLink: () => false, + }); + return { state, workspace }; + }); + act(() => h.result.current.state.openThreadTab(ALPHA, ROOT, ROOT)); + const item = () => + h.result.current.workspace.items.find((tab) => tab.id === TAB) as + | { label: string; rename?: (name: string) => void } + | undefined; + const localName = () => + ( + h.result.current.state.tabs.find((tab) => tab.id === TAB) as + | { name?: string } + | undefined + )?.name; + return { + session, + heads, + publish, + snapshotRead, + writerTaken, + item, + localName, + }; +} + +it("labels a thread tab with its local name, then its shared title, then its text", async () => { + const h = await harness({ title: "Launch plan" }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => { + channelTabs(h.session).rename(ALPHA, ROOT, "Mine"); + }); + expect(h.item()?.label).toBe("Mine"); + act(() => { + channelTabs(h.session).rename(ALPHA, ROOT, ""); + }); + expect(h.item()?.label).toBe("Launch plan"); + expect(h.publish).not.toHaveBeenCalled(); +}); + +it("renaming a thread tab publishes the shared title and drops the local name", async () => { + const h = await harness(); + await waitFor(() => expect(h.snapshotRead).toHaveBeenCalled()); + expect(h.item()?.label).toBe("Original message"); + act(() => h.item()?.rename?.(" Launch plan ")); + // The typed name shows while the write is in flight. + expect(h.item()?.label).toBe("Launch plan"); + await waitFor(() => expect(h.localName()).toBeFalsy()); + expect(h.item()?.label).toBe("Launch plan"); + const [signed] = vi.mocked(h.publish).mock.calls[0] ?? []; + expect(signed?.tags).toContainEqual(["op", "create"]); + expect(signed?.tags).toContainEqual(["title", "Launch plan"]); +}); + +it("renaming against a titled thread updates it from the shown revision", async () => { + const h = await harness({ title: "Launch plan" }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => h.item()?.rename?.("Ship plan")); + await waitFor(() => expect(h.publish).toHaveBeenCalled()); + const [signed] = vi.mocked(h.publish).mock.calls[0] ?? []; + expect(signed?.tags).toContainEqual(["op", "update"]); + expect(signed?.tags).toContainEqual(["prev", "e1"]); + await waitFor(() => expect(h.localName()).toBeFalsy()); + expect(h.item()?.label).toBe("Ship plan"); +}); + +it("a failed shared write drops the typed name and offers a retry", async () => { + const publish = vi.fn(async (_event: RelayEvent): Promise => { + throw new PublishRejected("Rejected", "restricted: not a member"); + }); + const h = await harness({ title: "Launch plan", publish }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => h.item()?.rename?.("Ship plan")); + expect(h.item()?.label).toBe("Ship plan"); + await waitFor(() => expect(toasts.notify).toHaveBeenCalledOnce()); + const [message, tone, action] = toasts.notify.mock.calls[0] ?? []; + expect(message).toMatch(/^Couldn’t save the thread title\./); + expect(tone).toBe("error"); + expect(action?.label).toBe("Retry"); + // The local name can't hide the shared title once the write failed. + expect(h.localName()).toBeFalsy(); + expect(h.item()?.label).toBe("Launch plan"); + // Retry writes the same name again, and this time it lands. + publish.mockResolvedValueOnce(""); + act(() => action?.onClick()); + expect(h.item()?.label).toBe("Ship plan"); + await waitFor(() => expect(publish).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(h.localName()).toBeFalsy()); + expect(h.item()?.label).toBe("Ship plan"); + expect(publish.mock.calls[1]?.[0].tags).toContainEqual([ + "title", + "Ship plan", + ]); +}); + +it("Retry keeps the revision it was typed over, and a conflict offers none", async () => { + const publish = vi.fn(async (_event: RelayEvent): Promise => { + throw new PublishRejected("Rejected", "relay unavailable"); + }); + const h = await harness({ title: "Launch plan", publish }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => h.item()?.rename?.("Ship plan")); + await waitFor(() => expect(toasts.notify).toHaveBeenCalledOnce()); + const retry = toasts.notify.mock.calls[0]?.[2]; + // Meanwhile someone else retitles the thread, and this client sees it. + const theirs = await titleRevision( + ALPHA, + ROOT, + { op: "update", prev: "e1" }, + "Their plan", + ); + const head = { ...theirs, id: "e2", pubkey: "", sig: "" }; + h.heads.splice(0, 1, head as unknown as RelayEvent); + act(() => + threadTitleStore(h.session).apply(ALPHA, ROOT, { + title: "Their plan", + channel: ALPHA, + root: ROOT, + revision: "e2", + updatedAt: 2, + }), + ); + // Retry still expects e1, so it conflicts instead of replacing their title. + act(() => retry?.onClick()); + await waitFor(() => expect(toasts.notify).toHaveBeenCalledTimes(2)); + const [message, , action] = toasts.notify.mock.calls[1] ?? []; + expect(message).toMatch(/Someone else changed this thread/); + expect(action).toBeUndefined(); + expect(publish).toHaveBeenCalledOnce(); + expect(h.localName()).toBeFalsy(); + expect(h.item()?.label).toBe("Their plan"); +}); + +it("an older failure's Retry does nothing after a newer rename", async () => { + const publish = vi.fn(async (_event: RelayEvent): Promise => { + throw new PublishRejected("Rejected", "relay unavailable"); + }); + const h = await harness({ title: "Launch plan", publish }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => h.item()?.rename?.("Ship plan")); + await waitFor(() => expect(toasts.notify).toHaveBeenCalledOnce()); + const stale = toasts.notify.mock.calls[0]?.[2]; + publish.mockResolvedValueOnce(""); + act(() => h.item()?.rename?.("Final plan")); + await waitFor(() => expect(h.localName()).toBeFalsy()); + expect(h.item()?.label).toBe("Final plan"); + act(() => stale?.onClick()); + expect(h.item()?.label).toBe("Final plan"); + expect(publish).toHaveBeenCalledTimes(2); +}); + +it("a failed rename's Retry does nothing once titles are off or the tab was renamed", async () => { + const publish = vi.fn(async (_event: RelayEvent): Promise => { + throw new PublishRejected("Rejected", "relay unavailable"); + }); + const h = await harness({ title: "Launch plan", publish }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + const fail = async (name: string) => { + const before = toasts.notify.mock.calls.length; + act(() => h.item()?.rename?.(name)); + await waitFor(() => + expect(toasts.notify).toHaveBeenCalledTimes(before + 1), + ); + return toasts.notify.mock.calls[before]?.[2]; + }; + publish.mockResolvedValue(""); + publish.mockRejectedValueOnce(new Error("relay unavailable")); + // Shared titles switched off: Retry publishes nothing. + const whileOff = await fail("Ship plan"); + act(() => disable?.()); + act(() => whileOff?.onClick()); + // A local rename while off, then back on: the old Retry stays retired. + act(() => h.item()?.rename?.("Mine")); + act(() => { + disable = enableThreadTitles(); + }); + act(() => whileOff?.onClick()); + expect(h.localName()).toBe("Mine"); + // A blank rename retires it too. + act(() => h.item()?.rename?.("")); + publish.mockRejectedValueOnce(new Error("relay unavailable")); + const beforeBlank = await fail("Ship plan"); + act(() => h.item()?.rename?.("")); + act(() => beforeBlank?.onClick()); + expect(publish).toHaveBeenCalledTimes(2); + expect(h.localName()).toBeFalsy(); +}); + +it("a rejected name leaves a pending rename's rollback in place", async () => { + let reject: (cause: Error) => void = () => {}; + const publish = vi.fn( + (_event: RelayEvent) => + new Promise((_, fail) => { + reject = fail; + }), + ); + const h = await harness({ title: "Launch plan", publish }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => h.item()?.rename?.("Ship plan")); + await waitFor(() => expect(publish).toHaveBeenCalledOnce()); + act(() => h.item()?.rename?.("x".repeat(513))); + expect(toasts.notify).toHaveBeenCalledWith( + "Titles can be at most 512 bytes.", + "error", + ); + expect(h.item()?.label).toBe("Ship plan"); + act(() => reject(new Error("relay unavailable"))); + await waitFor(() => expect(toasts.notify).toHaveBeenCalledTimes(2)); + expect(toasts.notify.mock.calls[1]?.[2]?.label).toBe("Retry"); + expect(h.localName()).toBeFalsy(); + expect(h.item()?.label).toBe("Launch plan"); +}); + +it("a name over the byte limit says so and changes nothing", async () => { + const h = await harness({ title: "Launch plan" }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => h.item()?.rename?.("x".repeat(513))); + expect(toasts.notify).toHaveBeenCalledWith( + "Titles can be at most 512 bytes.", + "error", + ); + expect(h.localName()).toBeFalsy(); + expect(h.item()?.label).toBe("Launch plan"); + expect(h.publish).not.toHaveBeenCalled(); +}); + +it("an empty rename clears only the local name, never the shared title", async () => { + const h = await harness({ title: "Launch plan" }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => { + channelTabs(h.session).rename(ALPHA, ROOT, "Mine"); + }); + act(() => h.item()?.rename?.("")); + expect(h.localName()).toBeFalsy(); + expect(h.item()?.label).toBe("Launch plan"); + expect(h.publish).not.toHaveBeenCalled(); +}); + +it("with shared titles off, a tab shows no shared title and renames stay local", async () => { + disable?.(); + const h = await harness({ title: "Launch plan" }); + expect(h.item()?.label).toBe("Original message"); + act(() => h.item()?.rename?.("Mine")); + expect(h.localName()).toBe("Mine"); + expect(h.item()?.label).toBe("Mine"); + // A shared write takes the writer as it starts, before any await. + expect(h.writerTaken).not.toHaveBeenCalled(); + expect(h.snapshotRead).not.toHaveBeenCalled(); + expect(h.publish).not.toHaveBeenCalled(); +}); + +it("follows shared titles being switched off and on while a tab is open", async () => { + const h = await harness({ title: "Launch plan" }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => disable?.()); + expect(h.item()?.label).toBe("Original message"); + act(() => h.item()?.rename?.("Mine")); + expect(h.localName()).toBe("Mine"); + expect(h.writerTaken).not.toHaveBeenCalled(); + act(() => h.item()?.rename?.("")); + act(() => { + disable = enableThreadTitles(); + }); + await waitFor(() => expect(h.item()?.label).toBe("Launch plan")); + act(() => h.item()?.rename?.("Ship plan")); + await waitFor(() => expect(h.publish).toHaveBeenCalledTimes(1)); +}); diff --git a/src/bundled/channels/useConversationTabs.tsx b/src/bundled/channels/useConversationTabs.tsx index 33a817f242..72c30a3aa3 100644 --- a/src/bundled/channels/useConversationTabs.tsx +++ b/src/bundled/channels/useConversationTabs.tsx @@ -21,6 +21,17 @@ import { import { useTabDrag } from "../../features/panels/useTabDrag"; import { PanelCard } from "../../features/panels/PanelCard"; import type { MessageLinkOrigin } from "../../features/messages/MessageRow"; +import { + threadTitlesEnabled, + threadTitleStore, + useThreadTitles, +} from "../../features/messages/thread-title-store"; +import { + activityKey, + normalizeTitle, + TitleConflict, + writeTitle, +} from "../../features/messages/thread-titles"; import { BrowserIcon, MessageReplyIcon, @@ -48,6 +59,7 @@ import { type TabPane, type useChannelTabState, } from "./useChannelTabState"; +import { useToastNotification } from "../../shared/design-system/ui/Toast"; import styles from "./Channels.module.css"; import tabStyles from "./ChannelTabs.module.css"; @@ -773,10 +785,18 @@ export function useConversationTabs({ linkedThread.current(channelId, messageId, rootId), [], ); - // Several open threads stay distinguishable by their original message. + // A device-local name wins, then the thread's shared title. Several open + // threads stay distinguishable by their original message. + const sharedTitles = useThreadTitles(queries).titles; + const notify = useToastNotification(); + // The latest shared rename per tab: an older write's outcome or Retry + // must not undo a newer one. + const renames = useRef(new Map()); function threadLabel(tab: Extract, name?: string) { if (tab.name) return tab.name; const rootId = rootOfTab(tab); + const shared = sharedTitles?.get(activityKey(tab.channelId, rootId)); + if (shared) return shared.title; const root = queries.channels .window(tab.channelId) .rows.find((row) => row.id === rootId); @@ -788,6 +808,83 @@ export function useConversationTabs({ .slice(0, 80); return text || (name ? `Thread · ${name}` : "Thread"); } + // With shared titles on, renaming a thread tab names the thread for + // everyone. The typed name shows on this tab until the write lands. A failed + // write drops it, so it can't hide the shared title, and says so. A blank + // name only drops the local one. + function renameThread(tab: Extract, name: string) { + // Any accepted rename, local or shared, retires an earlier rename's + // pending outcome and Retry; a rejected one leaves them alone. + const bump = () => { + const id = (renames.current.get(tab.id) ?? 0) + 1; + renames.current.set(tab.id, id); + return id; + }; + if (!threadTitlesEnabled()) { + bump(); + return tabState.renameTab(tab.id, name); + } + const rootId = rootOfTab(tab); + const read = queries.snapshotRead; + const writer = queries.configArtifactWriter; + let desired: string | undefined; + try { + desired = normalizeTitle(name); + } catch (cause) { + notify(cause instanceof Error ? cause.message : String(cause), "error"); + return; + } + if (!desired || !read || !writer) { + bump(); + return tabState.renameTab(tab.id, desired ?? ""); + } + const store = threadTitleStore(queries); + // Retry writes against the revision this rename was typed over, so it + // can never replace a title someone else set meanwhile. + const expected = store.get(tab.channelId, rootId)?.revision; + const save = () => { + const id = bump(); + const latest = () => renames.current.get(tab.id) === id; + tabState.renameTab(tab.id, desired); + writeTitle( + read, + writer, + { channel: tab.channelId, root: rootId, revision: expected }, + desired, + AbortSignal.timeout(20_000), + ).then( + (revision) => { + if (revision) + store.apply(tab.channelId, rootId, { + title: desired, + channel: tab.channelId, + root: rootId.toLowerCase(), + revision, + updatedAt: Math.floor(Date.now() / 1000), + }); + if (latest()) tabState.renameTab(tab.id, ""); + }, + (cause) => { + if (!latest()) return; + tabState.renameTab(tab.id, ""); + const reason = cause instanceof Error ? cause.message : String(cause); + // After a conflict the tab shows the current title; renaming again + // writes over that one. + notify( + `Couldn’t save the thread title. ${reason}`, + "error", + cause instanceof TitleConflict + ? undefined + : { + label: "Retry", + onClick: () => latest() && threadTitlesEnabled() && save(), + }, + ); + }, + ); + }; + save(); + } // The current conversation's own threads are already in its channel. function openInChannel(tab: Tab, target: ChannelSummary | undefined) { return target && navigation && viewer && tab.channelId !== currentId @@ -848,7 +945,7 @@ export function useConversationTabs({ ...(tab.kind === "thread" && { attentionRequest: tab.attentionRequest, move: (delta: -1 | 1) => moveBy(tab, delta), - rename: (name: string) => tabState.renameTab(tab.id, name), + rename: (name: string) => renameThread(tab, name), }), ...(openChannel && { actions: [{ label: "Open in channel", run: openChannel }], diff --git a/src/bundled/index.ts b/src/bundled/index.ts index d49af2cd6d..a5f7c6d4da 100644 --- a/src/bundled/index.ts +++ b/src/bundled/index.ts @@ -54,6 +54,8 @@ import usageManifest from "./usage/manifest.json"; import * as usage from "./usage"; import inboxManifest from "./inbox/manifest.json"; import * as inbox from "./inbox"; +import threadsManifest from "./threads/manifest.json"; +import * as threads from "./threads"; import focusManifest from "./focus/manifest.json"; import * as focus from "./focus"; import remindersManifest from "./reminders/manifest.json"; @@ -208,6 +210,11 @@ export const bundledPlugins: readonly BundledPlugin[] = [ module: inbox, enabledByDefault: true, }, + { + manifest: { ...threadsManifest, apiVersion: 1 }, + module: threads, + enabledByDefault: true, + }, { manifest: { ...remindersManifest, apiVersion: 1 }, module: reminders, diff --git a/src/bundled/threads/README.md b/src/bundled/threads/README.md new file mode 100644 index 0000000000..31e8ab51ea --- /dev/null +++ b/src/bundled/threads/README.md @@ -0,0 +1,10 @@ +# Named threads + +See a thread's title wherever the thread shows. + +## Getting started + +1. A titled thread shows its title under its first message in the channel. Choose the title to open the thread. +2. An open thread's tab shows its title. Rename the tab to set the title for everyone in the channel. + +Titles are shared with everyone in the channel. The `buzz` CLI sets them with `buzz threads title set`, and Buzz 0.x shows the same titles. diff --git a/src/bundled/threads/TitleAccessory.test.tsx b/src/bundled/threads/TitleAccessory.test.tsx new file mode 100644 index 0000000000..267b7f21b1 --- /dev/null +++ b/src/bundled/threads/TitleAccessory.test.tsx @@ -0,0 +1,86 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { cleanup, render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import type { ComposerAccessoryProps } from "../../features/conversation/contracts"; +import { enableThreadTitles } from "../../features/messages/thread-title-store"; +import { titleRevision } from "../../features/messages/thread-titles"; +import type { ChannelMessage } from "../../features/relay/contracts"; +import type { RelaySession } from "../../features/relay/session"; +import { TitleAccessory } from "./TitleAccessory"; + +let disable: (() => void) | undefined; +beforeEach(() => { + disable = enableThreadTitles(); +}); +afterEach(() => { + cleanup(); + disable?.(); +}); + +const ALPHA = "11111111-1111-4111-8111-111111111111"; +const ROOT = "a".repeat(64); + +async function session() { + const template = await titleRevision( + ALPHA, + ROOT, + { op: "create" }, + "Launch plan", + ); + return { + snapshotRead: async () => [{ ...template, id: "e1", pubkey: "", sig: "" }], + artifacts: { follow: () => () => {} }, + channels: { + list: () => ({ status: "ready", channels: [{ id: ALPHA }] }), + ensureList: () => () => {}, + subscribeList: () => () => {}, + }, + } as unknown as RelaySession; +} + +const props = ( + s: RelaySession, + message: Partial, + openThread?: () => boolean, +) => + ({ + session: s, + scope: "scope", + channelId: ALPHA, + message: { id: ROOT, channelId: ALPHA, ...message } as ChannelMessage, + openThread, + canOpen: () => false, + open: () => false, + }) satisfies ComposerAccessoryProps; + +it("shows a thread root's title and opens the thread", async () => { + const s = await session(); + const openThread = vi.fn(() => true); + render(); + await userEvent.click( + await screen.findByRole("button", { name: "Open thread: Launch plan" }), + ); + expect(openThread).toHaveBeenCalledOnce(); +}); + +it("shows nothing on replies, untitled roots or where the thread can't open", async () => { + const s = await session(); + const open = () => true; + const { rerender } = render(); + // Loaded: the titled root that can open shows it. + await screen.findByRole("button", { name: "Open thread: Launch plan" }); + for (const message of [ + { threadRootId: "b".repeat(64) }, + { id: "c".repeat(64) }, + ]) { + rerender(); + expect(screen.queryByRole("button")).not.toBeInTheDocument(); + } + rerender(); + expect(screen.queryByRole("button")).not.toBeInTheDocument(); + // A root that names itself as its thread root is still the root. + rerender(); + expect(screen.getByRole("button")).toHaveTextContent("Launch plan"); +}); diff --git a/src/bundled/threads/TitleAccessory.tsx b/src/bundled/threads/TitleAccessory.tsx new file mode 100644 index 0000000000..e92f1398dd --- /dev/null +++ b/src/bundled/threads/TitleAccessory.tsx @@ -0,0 +1,36 @@ +import type { ComposerAccessoryProps } from "../../features/conversation/contracts"; +import { useThreadTitle } from "../../features/messages/thread-title-store"; +import { MessageReplyIcon } from "../../shared/design-system/icons"; +import { Button } from "../../shared/design-system/ui/Button"; + +/** A thread root's shared title on its timeline row; choosing it opens the + * thread. Nothing inside the thread, where its tab already carries the name. */ +export function TitleAccessory({ + session, + channelId, + message, + openThread, +}: ComposerAccessoryProps) { + const root = + message && (!message.threadRootId || message.threadRootId === message.id) + ? message.id + : ""; + const title = useThreadTitle(session, channelId, root); + if (!root || !title || !openThread) return null; + return ( + + ); +} diff --git a/src/bundled/threads/index.test.ts b/src/bundled/threads/index.test.ts new file mode 100644 index 0000000000..65517e19d6 --- /dev/null +++ b/src/bundled/threads/index.test.ts @@ -0,0 +1,21 @@ +import { expect, it, vi } from "vitest"; +import { threadTitlesEnabled } from "../../features/messages/thread-title-store"; +import { apply } from "./index"; +import manifest from "./manifest.json"; + +it("turns shared titles on while it runs and registers the timeline title", () => { + const conversation = { registerAccessory: vi.fn() }; + const effects: (() => () => void)[] = []; + const effect = (run: () => () => void) => effects.push(run); + apply({ conversation, effect } as unknown as Parameters[0]); + expect(threadTitlesEnabled()).toBe(false); + const stop = effects[0]?.(); + expect(threadTitlesEnabled()).toBe(true); + stop?.(); + expect(threadTitlesEnabled()).toBe(false); + expect(conversation.registerAccessory.mock.calls[0]?.[0]).toMatchObject({ + id: "thread-title", + placement: "message", + }); + expect(manifest).not.toHaveProperty("host"); +}); diff --git a/src/bundled/threads/index.tsx b/src/bundled/threads/index.tsx new file mode 100644 index 0000000000..0b59a34602 --- /dev/null +++ b/src/bundled/threads/index.tsx @@ -0,0 +1,14 @@ +import { enableThreadTitles } from "../../features/messages/thread-title-store"; +import type { PluginModule } from "../../plugins/api"; +import { TitleAccessory } from "./TitleAccessory"; + +export const inject = ["conversation"]; +export const apply: PluginModule["apply"] = (ctx) => { + ctx.effect(() => enableThreadTitles()); + ctx.conversation.registerAccessory({ + id: "thread-title", + title: "Thread title", + placement: "message", + component: TitleAccessory, + }); +}; diff --git a/src/bundled/threads/manifest.json b/src/bundled/threads/manifest.json new file mode 100644 index 0000000000..3c81e9c4a1 --- /dev/null +++ b/src/bundled/threads/manifest.json @@ -0,0 +1,7 @@ +{ + "id": "buzz.threads", + "name": "Named threads", + "apiVersion": 1, + "description": "Show and rename shared thread titles in channels and on thread tabs. Titles are shared with everyone in the channel, including agents.", + "discovery": { "category": "communication", "tags": ["messaging"] } +} diff --git a/src/features/messages/thread-title-store.test.ts b/src/features/messages/thread-title-store.test.ts new file mode 100644 index 0000000000..66925740f6 --- /dev/null +++ b/src/features/messages/thread-title-store.test.ts @@ -0,0 +1,226 @@ +import { describe, expect, it, vi } from "vitest"; +import type { ReadFilter, RelayEvent } from "../relay/events"; +import type { RelaySession } from "../relay/session"; +import { + enableThreadTitles, + retryDelay, + threadTitlesEnabled, + threadTitleStore, +} from "./thread-title-store"; +import { titleRevision } from "./thread-titles"; + +const ALPHA = "11111111-1111-4111-8111-111111111111"; +const BETA = "22222222-2222-4222-8222-222222222222"; +const ROOT = "a".repeat(64); + +async function head(id: string, text: string, channel = ALPHA, root = ROOT) { + const template = await titleRevision(channel, root, { op: "create" }, text); + return { ...template, id, pubkey: "f".repeat(64), sig: "" } as RelayEvent; +} + +function fixture(heads: RelayEvent[]) { + const relay = { heads, channels: [ALPHA] }; + const listListeners = new Set<() => void>(); + const follow: { + ids?: readonly string[]; + listener?: ((events: readonly RelayEvent[]) => void) | undefined; + } = {}; + const snapshotRead = vi.fn(async (filters: readonly ReadFilter[]) => + relay.heads.filter((h) => + h.tags.some( + ([k, v]) => k === "h" && filters[0]?.["#h"]?.includes(v ?? ""), + ), + ), + ); + const session = { + snapshotRead, + artifacts: { + follow: vi.fn( + (ids: readonly string[], listener: typeof follow.listener) => { + follow.ids = ids; + follow.listener = listener; + return () => { + follow.listener = undefined; + }; + }, + ), + }, + channels: { + list: () => ({ + status: "ready", + channels: relay.channels.map((id) => ({ id })), + }), + ensureList: () => () => {}, + subscribeList: (listener: () => void) => { + listListeners.add(listener); + return () => listListeners.delete(listener); + }, + }, + } as unknown as RelaySession; + const changeList = (channels: string[]) => { + relay.channels = channels; + for (const listener of listListeners) listener(); + }; + return { session, relay, follow, snapshotRead, changeList }; +} + +describe("thread title store", () => { + it("is one store per session and reads nothing until someone subscribes", async () => { + const f = fixture([await head("e1", "Launch plan")]); + const store = threadTitleStore(f.session); + expect(threadTitleStore(f.session)).toBe(store); + expect(f.snapshotRead).not.toHaveBeenCalled(); + const stop = store.subscribe(() => {}); + await vi.waitFor(() => + expect(store.get(ALPHA, ROOT.toUpperCase())?.title).toBe("Launch plan"), + ); + expect(f.follow.ids).toEqual([ALPHA]); + stop(); + expect(f.follow.listener).toBeUndefined(); + }); + + it("re-reads a channel a live revision names, and drops a cleared title", async () => { + const f = fixture([await head("e1", "Launch plan")]); + const store = threadTitleStore(f.session); + const seen = vi.fn(); + const stop = store.subscribe(seen); + await vi.waitFor(() => expect(store.get(ALPHA, ROOT)).toBeDefined()); + const renamed = await head("e2", "Ship plan"); + f.relay.heads = [renamed]; + f.follow.listener?.([renamed]); + await vi.waitFor(() => + expect(store.get(ALPHA, ROOT)?.title).toBe("Ship plan"), + ); + const cleared = await titleRevision(ALPHA, ROOT, { + op: "delete", + prev: "e2", + }); + f.relay.heads = []; + f.follow.listener?.([ + { ...cleared, id: "e3", pubkey: "", sig: "" } as unknown as RelayEvent, + ]); + await vi.waitFor(() => expect(store.get(ALPHA, ROOT)).toBeUndefined()); + expect(f.snapshotRead).toHaveBeenCalledTimes(3); + stop(); + }); + + it("follows and reads again when the joined channels change, not on a same-set refresh", async () => { + const f = fixture([ + await head("e1", "Launch plan"), + await head("e2", "Bug triage", BETA, "b".repeat(64)), + ]); + const store = threadTitleStore(f.session); + const stop = store.subscribe(() => {}); + await vi.waitFor(() => expect(store.get(ALPHA, ROOT)).toBeDefined()); + f.changeList([ALPHA]); + expect(f.snapshotRead).toHaveBeenCalledTimes(1); + f.changeList([BETA, ALPHA]); + await vi.waitFor(() => + expect(store.get(BETA, "b".repeat(64))?.title).toBe("Bug triage"), + ); + expect(f.follow.ids).toEqual([ALPHA, BETA]); + // Leaving a channel drops its titles at once. + f.changeList([BETA]); + expect(store.get(ALPHA, ROOT)).toBeUndefined(); + stop(); + }); + + it("reports a failed read and retries it after a backoff", async () => { + // Only timers are faked: reads settle through real crypto and promises. + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const random = vi.spyOn(Math, "random").mockReturnValue(0.5); + const tick = () => new Promise((resolve) => setImmediate(resolve)); + const until = async (done: () => boolean) => { + for (let i = 0; i < 100 && !done(); i++) await tick(); + expect(done()).toBe(true); + }; + // A live revision is checked against its derived id before it marks a + // channel stale; wait for that hash, then for the store to act on it. + const digest = vi.spyOn(crypto.subtle, "digest"); + try { + const f = fixture([await head("e1", "Launch plan")]); + const live = async (event: RelayEvent) => { + const before = digest.mock.results.length; + f.follow.listener?.([event]); + await until(() => digest.mock.results.length > before); + await digest.mock.results.at(-1)?.value; + await tick(); + }; + f.snapshotRead.mockRejectedValueOnce(new Error("Relay offline")); + const store = threadTitleStore(f.session); + const stop = store.subscribe(() => {}); + await until(() => store.snapshot().error === "Relay offline"); + expect(store.snapshot().titles?.size).toBe(0); + // A live change in a failed channel waits for the backoff too. + const renamed = await head("e2", "Launch plan"); + await live(renamed); + vi.advanceTimersByTime(4_999); + await tick(); + expect(f.snapshotRead).toHaveBeenCalledTimes(1); + // The second failure waits twice as long, even when a live change + // arrived while that read was pending. + let fail: (cause: Error) => void = () => {}; + f.snapshotRead.mockImplementationOnce( + () => new Promise((_, reject) => (fail = reject)), + ); + vi.advanceTimersByTime(1); + await until(() => f.snapshotRead.mock.calls.length === 2); + await live(renamed); + fail(new Error("Still offline")); + await until(() => store.snapshot().error === "Still offline"); + vi.advanceTimersByTime(300); + await tick(); + expect(f.snapshotRead).toHaveBeenCalledTimes(2); + vi.advanceTimersByTime(9_699); + await tick(); + expect(f.snapshotRead).toHaveBeenCalledTimes(2); + vi.advanceTimersByTime(1); + await until(() => store.get(ALPHA, ROOT)?.title === "Launch plan"); + expect(store.snapshot().error).toBeUndefined(); + expect(f.snapshotRead.mock.calls[2]?.[0][0]?.["#h"]).toEqual([ALPHA]); + // Leaving stops a pending retry. + f.snapshotRead.mockRejectedValueOnce(new Error("Offline again")); + f.changeList([ALPHA, BETA]); + await until(() => store.snapshot().error === "Offline again"); + stop(); + vi.advanceTimersByTime(60_000); + await tick(); + expect(f.snapshotRead).toHaveBeenCalledTimes(4); + } finally { + digest.mockRestore(); + random.mockRestore(); + vi.useRealTimers(); + } + }); + + it("spreads and caps the retry delay", () => { + expect(retryDelay(1, () => 0)).toBe(2_500); + expect(retryDelay(1, () => 0.5)).toBe(5_000); + expect(retryDelay(3, () => 0.5)).toBe(20_000); + expect(retryDelay(30, () => 0.5)).toBe(300_000); + expect(retryDelay(30, () => 0.999)).toBeLessThan(450_000); + }); + + it("is empty and inert without a snapshot reader", () => { + const f = fixture([]); + const session = { ...f.session, snapshotRead: undefined } as RelaySession; + const store = threadTitleStore(session); + const stop = store.subscribe(() => {}); + expect(store.snapshot().titles?.size).toBe(0); + expect(f.session.artifacts.follow).not.toHaveBeenCalled(); + stop(); + }); +}); + +describe("shared title switch", () => { + it("stays on while any enabler is live, so a late dispose of a replaced plugin can't turn it off", () => { + expect(threadTitlesEnabled()).toBe(false); + const first = enableThreadTitles(); + const second = enableThreadTitles(); + first(); + first(); + expect(threadTitlesEnabled()).toBe(true); + second(); + expect(threadTitlesEnabled()).toBe(false); + }); +}); diff --git a/src/features/messages/thread-title-store.ts b/src/features/messages/thread-title-store.ts new file mode 100644 index 0000000000..7cbd8bfbdc --- /dev/null +++ b/src/features/messages/thread-title-store.ts @@ -0,0 +1,293 @@ +// One live set of shared thread titles per relay session, read by the channel +// timeline and thread tabs. The relay's current read is the only authority: +// a live title revision only marks its channel stale, and a debounced read of +// the stale channels replaces their titles. NIP-AR orders revisions by `prev`, +// not by time, so live events are never applied as-is. +// +// Relay reads per session: ceil(joined/100) current reads when the first +// reader subscribes and whenever the joined set changes, then one read per +// burst of title changes. A failed read is retried after a jittered delay that +// doubles up to a cap. Following adds no subscriptions: the live routes +// already carry the joined channels. +import { useSyncExternalStore } from "react"; +import type { RelaySession } from "../relay/session"; +import { + activityKey, + readTitles, + staleChannels, + type ThreadTitle, +} from "./thread-titles"; + +/** A burst of title changes waits this long, then reads its channels once. */ +const TITLE_DEBOUNCE_MS = 300; +/** A failed read waits this long, doubling per failure up to the cap. */ +const RETRY_BASE_MS = 5_000; +const RETRY_CAP_MS = 5 * 60_000; +/** Spread to [0.5, 1.5) of the delay, so clients that failed together don't + * retry together. */ +export const retryDelay = (failures: number, random = Math.random) => + Math.min(RETRY_BASE_MS * 2 ** (failures - 1), RETRY_CAP_MS) * + (0.5 + random()); + +export type ThreadTitles = Readonly<{ + /** By activityKey(channel, root); undefined until the first read settles. */ + titles: ReadonlyMap | undefined; + /** Some channel had more titles than one read returns. */ + partial: boolean; + error?: string | undefined; +}>; + +export type ThreadTitleStore = Readonly<{ + snapshot(): ThreadTitles; + subscribe(listener: () => void): () => void; + get(channelId: string, rootId: string): ThreadTitle | undefined; + /** A write this client made, shown before the relay's echo is re-read. */ + apply( + channelId: string, + rootId: string, + title: ThreadTitle | undefined, + ): void; +}>; + +type Session = Pick; + +const stores = new WeakMap(); + +export function threadTitleStore(session: Session): ThreadTitleStore { + let store = stores.get(session); + if (!store) { + store = createStore(session); + stores.set(session, store); + } + return store; +} + +// Shared titles are on only while a plugin that offers them runs (it calls +// enableThreadTitles in an effect). A host plugin such as Channels can't see +// another plugin's state, so the switch lives here: while it is off, nothing +// reads titles and thread tabs keep device-local names. +let enabled = 0; +const switchListeners = new Set<() => void>(); +const flip = (by: number) => { + enabled += by; + for (const listener of [...switchListeners]) listener(); +}; + +/** Turns shared titles on; the returned disposer turns them off again. */ +export function enableThreadTitles() { + let on = true; + flip(1); + return () => { + if (!on) return; + on = false; + flip(-1); + }; +} + +export const threadTitlesEnabled = () => enabled > 0; + +const subscribeSwitch = (listener: () => void) => { + switchListeners.add(listener); + return () => { + switchListeners.delete(listener); + }; +}; + +const NONE: ThreadTitles = { titles: new Map(), partial: false }; +const off = () => NONE; +const idle = () => () => {}; + +/** No titles, and no relay reads, while shared titles are off. */ +export function useThreadTitles(session: Session) { + const store = threadTitleStore(session); + const on = useSyncExternalStore( + subscribeSwitch, + threadTitlesEnabled, + threadTitlesEnabled, + ); + return useSyncExternalStore( + on ? store.subscribe : idle, + on ? store.snapshot : off, + on ? store.snapshot : off, + ); +} + +/** One thread's title. A row rerenders only when its own title changes. */ +export function useThreadTitle( + session: Session, + channelId: string, + rootId: string, +) { + const store = threadTitleStore(session); + const on = useSyncExternalStore( + subscribeSwitch, + threadTitlesEnabled, + threadTitlesEnabled, + ); + const get = () => (on ? store.get(channelId, rootId) : undefined); + return useSyncExternalStore(on ? store.subscribe : idle, get, get); +} + +function createStore(session: Session): ThreadTitleStore { + const listeners = new Set<() => void>(); + let state: ThreadTitles = { titles: undefined, partial: false }; + const set = (next: Partial) => { + state = { ...state, ...next }; + for (const listener of [...listeners]) listener(); + }; + /** The joined channels being followed, sorted and joined; undefined while stopped. */ + let channelKey: string | undefined; + let stopRun: (() => void) | undefined; + let stopList: (() => void) | undefined; + + // Follows `ids` and reads them all, replacing every title. + const start = (ids: readonly string[]) => { + stopRun?.(); + const read = session.snapshotRead; + const joined = new Set(ids); + if (state.titles) + set({ + titles: new Map( + [...state.titles].filter(([, t]) => joined.has(t.channel)), + ), + }); + if (!read || !ids.length) { + stopRun = undefined; + return set({ titles: new Map(), partial: false, error: undefined }); + } + const controller = new AbortController(); + const { signal } = controller; + const stale = new Set(); + let timer: ReturnType | undefined; + let retry: ReturnType | undefined; + let failures = 0; + const failed = new Set(); + let reading = false; + let partial = new Set(); + const run = (channels: readonly string[], first: boolean) => { + reading = true; + readTitles(read, channels, signal) + .then((found) => { + if (signal.aborted) return; + const titles = new Map( + first + ? [] + : [...(state.titles ?? [])].filter( + ([, t]) => !channels.includes(t.channel), + ), + ); + for (const t of found.titles) + titles.set(activityKey(t.channel, t.root), t); + partial = new Set( + first ? [] : [...partial].filter((c) => !channels.includes(c)), + ); + if (found.partial) for (const c of channels) partial.add(c); + for (const c of channels) failed.delete(c); + if (!failed.size) failures = 0; + set({ titles, partial: partial.size > 0, error: undefined }); + }) + .catch((cause) => { + if (signal.aborted) return; + // Failed channels wait for the backoff, even when live changes + // mark them stale meanwhile. + for (const c of channels) { + failed.add(c); + stale.delete(c); + } + failures += 1; + clearTimeout(retry); + retry = setTimeout(() => { + for (const c of failed) stale.add(c); + failed.clear(); + flush(); + }, retryDelay(failures)); + set({ + ...(!state.titles && { titles: new Map() }), + error: cause instanceof Error ? cause.message : String(cause), + }); + }) + .finally(() => { + reading = false; + // Channels that changed during this read get one follow-up read. + if (!signal.aborted && stale.size) flush(); + }); + }; + const flush = () => { + clearTimeout(timer); + timer = undefined; + if (reading) return; + const channels = [...stale]; + stale.clear(); + if (channels.length) run(channels, false); + }; + const stopFollow = session.artifacts.follow(ids, (events) => { + void staleChannels(events, joined).then((changed) => { + if (signal.aborted || !changed.size) return; + for (const channel of changed) + if (!failed.has(channel)) stale.add(channel); + if (!stale.size) return; + if (reading) return; + clearTimeout(timer); + timer = setTimeout(flush, TITLE_DEBOUNCE_MS); + }); + }); + run(ids, true); + stopRun = () => { + controller.abort(); + clearTimeout(timer); + clearTimeout(retry); + stopFollow(); + }; + }; + + // Restarts when the joined set changes; a background list refresh with the + // same channels reads nothing. + const sync = () => { + const list = session.channels.list(); + if (list.status === "error") + return set({ + ...(!state.titles && { titles: new Map() }), + error: list.error || "Couldn't load your channels.", + }); + if (list.status !== "ready" && !list.channels.length) return; + const ids = [...new Set(list.channels.map((c) => c.id))].sort(); + const key = ids.join(","); + if (key === channelKey) return; + channelKey = key; + start(ids); + }; + + const open = () => { + // Without a snapshot reader there is nothing to read or follow. + if (!session.snapshotRead) return set({ titles: new Map() }); + session.channels.ensureList(); + stopList = session.channels.subscribeList(sync); + sync(); + }; + const close = () => { + stopList?.(); + stopRun?.(); + stopList = stopRun = channelKey = undefined; + }; + + return { + snapshot: () => state, + subscribe(listener) { + listeners.add(listener); + if (listeners.size === 1) open(); + return () => { + if (!listeners.delete(listener) || listeners.size) return; + close(); + }; + }, + get: (channelId, rootId) => + state.titles?.get(activityKey(channelId, rootId.toLowerCase())), + apply(channelId, rootId, title) { + const titles = new Map(state.titles); + const key = activityKey(channelId, rootId.toLowerCase()); + if (title) titles.set(key, title); + else titles.delete(key); + set({ titles }); + }, + }; +} diff --git a/src/features/messages/thread-titles.test.ts b/src/features/messages/thread-titles.test.ts new file mode 100644 index 0000000000..65ec49ff4f --- /dev/null +++ b/src/features/messages/thread-titles.test.ts @@ -0,0 +1,362 @@ +import { describe, expect, it, vi } from "vitest"; +import { PublishRejected } from "../relay/outbox"; +import type { ReadFilter, RelayEvent } from "../relay/events"; +import type { RelayWriter } from "../relay/transport"; +import { + normalizeTitle, + parseTitle, + planTitle, + readTitles, + staleChannels, + type ThreadTitle, + threadTitleId, + TitleConflict, + titleRevision, + writeTitle, +} from "./thread-titles"; + +// The 0.x SDK's test vector (`buzz_sdk::thread_title`, id_is_uuidv5_of_type_and_root_hex). +const ROOT = "a".repeat(64); +const ROOT_ID = "0d943738-f875-5089-91fe-135fe16d0f72"; +const CHANNEL = "11111111-1111-4111-8111-111111111111"; +const OTHER = "22222222-2222-4222-8222-222222222222"; + +const event = ( + id: string, + tags: string[][], + content = "", + created_at = 100, +): RelayEvent => + ({ + id, + pubkey: "f".repeat(64), + kind: 45010, + created_at, + content, + tags, + sig: "", + }) as unknown as RelayEvent; +async function titleEvent( + id: string, + title: string, + { root = ROOT, channel = CHANNEL, created_at = 100 } = {}, +) { + const template = await titleRevision(channel, root, { op: "create" }, title); + return event(id, template.tags, title, created_at); +} + +describe("convention", () => { + it("derives the same d as the SDK, whatever the root's case", async () => { + expect(await threadTitleId(ROOT)).toBe(ROOT_ID); + expect(await threadTitleId(ROOT.toUpperCase())).toBe(ROOT_ID); + }); + + it("trims titles, treats blank as clearing and bounds UTF-8 bytes", () => { + expect(normalizeTitle(" Spaced ")).toBe("Spaced"); + expect(normalizeTitle(" ")).toBeUndefined(); + expect(normalizeTitle("é".repeat(256))).toBe("é".repeat(256)); + expect(() => normalizeTitle("é".repeat(257))).toThrow("512 bytes"); + // A typed title is one line of plain text, too. + expect(normalizeTitle(" Launch\n\tplan\u202e ")).toBe("Launch plan"); + expect(normalizeTitle("\u2066\u200f")).toBeUndefined(); + }); + + it("plans the SDK's lifecycle", () => { + const live = { id: "h", deleted: false, title: "x" }; + const gone = { id: "h", deleted: true }; + expect(planTitle(undefined, "x")).toEqual({ op: "create" }); + expect(planTitle(undefined)).toEqual({ op: "unchanged" }); + expect(planTitle(live, "x")).toEqual({ op: "unchanged" }); + expect(planTitle(live, "y")).toEqual({ op: "update", prev: "h" }); + expect(planTitle(live)).toEqual({ op: "delete", prev: "h" }); + expect(planTitle(gone, "y")).toEqual({ op: "restore", prev: "h" }); + expect(planTitle(gone)).toEqual({ op: "unchanged" }); + }); + + it("builds revisions with the SDK's tags and content", async () => { + const prev = "b".repeat(64); + const base = [ + ["ar", "1"], + ["d", ROOT_ID], + ["h", CHANNEL], + ["type", "buzz.thread-title"], + ]; + const upper = ROOT.toUpperCase(); + expect( + await titleRevision(CHANNEL, upper, { op: "create" }, "Release"), + ).toMatchObject({ + kind: 45010, + content: "Release", + tags: [...base, ["op", "create"], ["root", ROOT], ["title", "Release"]], + }); + for (const op of ["update", "restore"] as const) + expect( + await titleRevision(CHANNEL, ROOT, { op, prev }, "Renamed"), + ).toMatchObject({ + content: "Renamed", + tags: [ + ...base, + ["op", op], + ["root", ROOT], + ["prev", prev], + ["title", "Renamed"], + ], + }); + const cleared = await titleRevision(CHANNEL, ROOT, { op: "delete", prev }); + expect(cleared).toMatchObject({ + content: "", + tags: [...base, ["op", "delete"], ["root", ROOT], ["prev", prev]], + }); + await expect( + titleRevision(CHANNEL, ROOT, { op: "update", prev }), + ).rejects.toThrow("title is required"); + expect(parseTitle(event("x", cleared.tags))).toBeUndefined(); + }); + + it("parses live titles only", async () => { + expect(parseTitle(await titleEvent("e1", "Release", {}))).toEqual({ + title: "Release", + channel: CHANNEL, + root: ROOT, + revision: "e1", + updatedAt: 100, + }); + expect( + parseTitle( + event("e2", [ + ["type", "buzz.task"], + ["title", "x"], + ["h", CHANNEL], + ["root", ROOT], + ]), + ), + ).toBeUndefined(); + }); + + it("makes another writer's title safe to show", async () => { + const shown = async (title: string) => + parseTitle(await titleEvent("e1", title))?.title; + // Line breaks, controls and separators become one space; bidi + // formatting (overrides, isolates, marks) is removed. + expect(await shown("Launch\r\n\n plan\u0000\u2028done")).toBe( + "Launch plan done", + ); + expect(await shown("\u202eevil\u202c \u2067x\u2069\u200e\u061c")).toBe( + "evil x", + ); + // Emoji sequences keep their joiners. + expect(await shown("👩‍💻 plan")).toBe("👩‍💻 plan"); + // Over the byte limit is cut at a code point boundary, not rejected. + const long = await shown(`${"a".repeat(511)}😀tail`); + expect(long).toBe("a".repeat(511)); + expect(await shown(`${"é".repeat(300)}`)).toBe("é".repeat(256)); + // Nothing left to show is no title. + expect(await shown("\u202e\n\u2066 ")).toBeUndefined(); + }); +}); + +describe("reads", () => { + it("reads titles in batches of 100 channels, keeping only derived ids in asked channels", async () => { + const channels = Array.from( + { length: 101 }, + (_, i) => `${String(i).padStart(8, "0")}-1111-4111-8111-111111111111`, + ); + const good = await titleEvent("e1", "Good", { channel: channels[0] }); + const forged = event( + "e2", + good.tags.map(([k, v]) => + k === "d" ? ["d", OTHER] : [k ?? "", v ?? ""], + ), + "Forged", + ); + const elsewhere = await titleEvent("e3", "Elsewhere", { + root: "c".repeat(64), + channel: OTHER, + }); + const read = vi.fn(async (filters: readonly ReadFilter[]) => + filters[0]?.["#h"]?.includes(channels[0] ?? "") + ? [good, forged, elsewhere] + : [], + ); + const result = await readTitles( + read, + channels, + new AbortController().signal, + ); + expect(result).toEqual({ + titles: [expect.objectContaining({ title: "Good", revision: "e1" })], + partial: false, + }); + expect(read.mock.calls.map(([[filter]]) => filter)).toEqual([ + { + kinds: [45010], + "#h": channels.slice(0, 100), + "#type": ["buzz.thread-title"], + artifact: "current", + limit: 500, + }, + expect.objectContaining({ "#h": channels.slice(100) }), + ]); + }); + + it("reports a read that fills its page as partial", async () => { + const full = await Promise.all( + Array.from({ length: 500 }, (_, i) => + titleEvent(`e${i}`, `Title ${i}`, { + root: i.toString(16).padStart(64, "0"), + }), + ), + ); + const result = await readTitles( + async () => full, + [CHANNEL], + new AbortController().signal, + ); + expect(result.partial).toBe(true); + expect(result.titles).toHaveLength(500); + const under = await readTitles( + async () => full.slice(1), + [CHANNEL], + new AbortController().signal, + ); + expect(under.partial).toBe(false); + }); +}); + +describe("writes", () => { + const current: ThreadTitle = { + title: "Old", + channel: CHANNEL, + root: ROOT, + revision: "e1", + updatedAt: 100, + }; + function fixture(head: RelayEvent | undefined, publish = vi.fn()) { + const read = vi.fn(async () => (head ? [head] : [])); + const writer: RelayWriter = { + sign: vi.fn(async (template) => + event("new", template.tags, template.content), + ), + publish, + }; + return { read, writer, publish }; + } + + it("renames against the shown revision with a strong head read", async () => { + const f = fixture(await titleEvent("e1", "Old")); + const signal = new AbortController().signal; + await expect( + writeTitle(f.read, f.writer, current, "New", signal), + ).resolves.toBe("new"); + expect(f.read).toHaveBeenCalledWith( + [ + { + kinds: [45010], + "#h": [CHANNEL], + "#d": [ROOT_ID], + limit: 1, + consistency: "strong", + }, + ], + { signal }, + ); + const [signed] = f.publish.mock.calls[0] ?? []; + expect(signed.tags).toContainEqual(["op", "update"]); + expect(signed.tags).toContainEqual(["prev", "e1"]); + }); + + it("clears with a delete and writes nothing when unchanged", async () => { + const f = fixture(await titleEvent("e1", "Old")); + const signal = new AbortController().signal; + await expect( + writeTitle(f.read, f.writer, current, undefined, signal), + ).resolves.toBeUndefined(); + expect(f.publish.mock.calls[0]?.[0].tags).toContainEqual(["op", "delete"]); + f.publish.mockClear(); + await expect( + writeTitle(f.read, f.writer, current, "Old", signal), + ).resolves.toBe("e1"); + expect(f.publish).not.toHaveBeenCalled(); + }); + + it("names an untitled thread with create, and a cleared one with restore", async () => { + const signal = new AbortController().signal; + const untitled = { channel: CHANNEL, root: ROOT }; + const fresh = fixture(undefined); + await expect( + writeTitle(fresh.read, fresh.writer, untitled, "New", signal), + ).resolves.toBe("new"); + expect(fresh.publish.mock.calls[0]?.[0].tags).toContainEqual([ + "op", + "create", + ]); + const deletion = await titleRevision(CHANNEL, ROOT, { + op: "delete", + prev: "e1", + }); + const cleared = fixture(event("e2", deletion.tags)); + await expect( + writeTitle(cleared.read, cleared.writer, untitled, "New", signal), + ).resolves.toBe("new"); + const tags = cleared.publish.mock.calls[0]?.[0].tags; + expect(tags).toContainEqual(["op", "restore"]); + expect(tags).toContainEqual(["prev", "e2"]); + // Expecting no title while one is live is a conflict. + const taken = fixture(await titleEvent("e1", "Theirs")); + await expect( + writeTitle(taken.read, taken.writer, untitled, "New", signal), + ).rejects.toBeInstanceOf(TitleConflict); + expect(taken.publish).not.toHaveBeenCalled(); + }); + + it("reports a conflict when the head moved or a CAS race is lost", async () => { + const signal = new AbortController().signal; + const moved = fixture(await titleEvent("e9", "Theirs")); + await expect( + writeTitle(moved.read, moved.writer, current, "New", signal), + ).rejects.toBeInstanceOf(TitleConflict); + expect(moved.publish).not.toHaveBeenCalled(); + await expect( + writeTitle(fixture(undefined).read, moved.writer, current, "New", signal), + ).rejects.toBeInstanceOf(TitleConflict); + const lost = fixture( + await titleEvent("e1", "Old"), + vi.fn(async () => { + throw new PublishRejected( + "Rejected", + "conflict: artifact head changed", + ); + }), + ); + await expect( + writeTitle(lost.read, lost.writer, current, "New", signal), + ).rejects.toBeInstanceOf(TitleConflict); + const denied = fixture( + await titleEvent("e1", "Old"), + vi.fn(async () => { + throw new PublishRejected("Rejected", "restricted: not a member"); + }), + ); + await expect( + writeTitle(denied.read, denied.writer, current, "New", signal), + ).rejects.toThrow("restricted: not a member"); + }); +}); + +describe("live updates", () => { + it("marks only the channels of checked title revisions stale", async () => { + const good = await titleEvent("e1", "Good"); + const forged = event( + "e2", + (await titleEvent("e2", "Forged", { channel: OTHER })).tags.map( + ([k, v]) => (k === "d" ? ["d", "x"] : [k ?? "", v ?? ""]), + ), + ); + const elsewhere = await titleEvent("e3", "x", { + channel: "33333333-3333-4333-8333-333333333333", + }); + expect( + await staleChannels([good, forged, elsewhere], new Set([CHANNEL, OTHER])), + ).toEqual(new Set([CHANNEL])); + }); +}); diff --git a/src/features/messages/thread-titles.ts b/src/features/messages/thread-titles.ts new file mode 100644 index 0000000000..3c0f05ee19 --- /dev/null +++ b/src/features/messages/thread-titles.ts @@ -0,0 +1,281 @@ +// Shared thread titles: NIP-AR artifacts (kind 45010) in the thread's channel. +// Mirrors `buzz_sdk::thread_title` in Buzz 0.x, so titles set by the `buzz` +// CLI, agents and 0.x desktops show here and titles set here show there: +// - `type` = THREAD_TITLE_TYPE; `d` = UUIDv5(THREAD_TITLE_NAMESPACE, +// ":"), so a thread has at most one title. +// - tags `h` = channel, `root` = thread root, `title`; `content` = the title. +// - Clearing is a soft `delete`; setting a cleared title is a `restore`. +import { + ARTIFACT_KIND, + artifactOp, + deliver, + readHead, + type SnapshotRead, + uuidv5, +} from "../agents/agent-config-artifacts"; +import type { EventData, RelayEvent } from "../relay/events"; +import type { RelayWriter } from "../relay/transport"; + +export const THREAD_TITLE_TYPE = "buzz.thread-title"; +export const THREAD_TITLE_NAMESPACE = "2039f9bf-c754-483e-a7cf-56f1ec0e4abe"; +export const MAX_THREAD_TITLE_BYTES = 512; +/** Channels or roots named by one read; the relay caps artifact predicates at 256. */ +const BATCH = 100; +/** The session reader's page cap. */ +const PAGE = 500; + +export const threadTitleId = (root: string) => + uuidv5(THREAD_TITLE_NAMESPACE, `${THREAD_TITLE_TYPE}:${root.toLowerCase()}`); + +// A title is one line of plain text shown inside other people's rows: no +// control or line-separator characters, and no bidi formatting characters, +// which could reorder the row's text around it. +const BREAKS = /[\p{Cc}\u2028\u2029]/gu; +const BIDI = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu; + +/** One line: breaks and controls become spaces, bidi formatting goes, runs + * of whitespace collapse, and the ends are trimmed. */ +export function cleanTitle(title: string) { + return title + .replace(BIDI, "") + .replace(BREAKS, " ") + .replace(/\s+/g, " ") + .trim(); +} + +const bytes = (text: string) => new TextEncoder().encode(text).length; + +/** Cleaned title, or undefined when blank (clearing is its own operation). */ +export function normalizeTitle(title: string) { + const cleaned = cleanTitle(title); + if (!cleaned) return undefined; + if (bytes(cleaned) > MAX_THREAD_TITLE_BYTES) + throw new Error(`Titles can be at most ${MAX_THREAD_TITLE_BYTES} bytes.`); + return cleaned; +} + +/** A title as another client published it, made safe to show: cleaned, and + * cut to the byte limit at a code point boundary. */ +export function displayTitle(title: string) { + const cleaned = cleanTitle(title); + if (bytes(cleaned) <= MAX_THREAD_TITLE_BYTES) return cleaned || undefined; + let out = ""; + let used = 0; + for (const char of cleaned) { + used += bytes(char); + if (used > MAX_THREAD_TITLE_BYTES) break; + out += char; + } + return out.trimEnd() || undefined; +} + +const tag = (event: EventData, name: string) => + event.tags.find((t) => t[0] === name)?.[1]; + +export type ThreadTitle = Readonly<{ + title: string; + channel: string; + root: string; + /** Current revision id: the next write's `prev`. */ + revision: string; + updatedAt: number; +}>; + +/** A live title, or undefined for other types, deletions or malformed events. + * Writers other than this client aren't bound by normalizeTitle, so the title + * is made safe to show here, for every consumer. */ +export function parseTitle(event: EventData): ThreadTitle | undefined { + const [raw, channel, root] = ["title", "h", "root"].map((t) => tag(event, t)); + const title = raw && displayTitle(raw); + if ( + event.kind !== ARTIFACT_KIND || + tag(event, "type") !== THREAD_TITLE_TYPE || + artifactOp(event) === "delete" || + !title || + !channel || + !root + ) + return undefined; + return { + title, + channel, + root, + revision: event.id, + updatedAt: event.created_at, + }; +} + +/** Titles are kept per channel and root. */ +export const activityKey = (channel: string, root: string) => + `${channel} ${root}`; + +/** Channels a live title revision may have changed: those of revisions + * passing readTitles' checks. Only a fresh current read says what changed; + * NIP-AR orders revisions by `prev`, not by time. */ +export async function staleChannels( + events: readonly EventData[], + channels: ReadonlySet, +) { + const stale = new Set(); + for (const event of events) { + const root = tag(event, "root"); + const channel = tag(event, "h"); + if ( + event.kind === ARTIFACT_KIND && + tag(event, "type") === THREAD_TITLE_TYPE && + root && + channel && + channels.has(channel) && + tag(event, "d") === (await threadTitleId(root)) + ) + stale.add(channel); + } + return stale; +} + +export type Head = Readonly<{ + id: string; + deleted: boolean; + title?: string | undefined; +}>; +export type Plan = + | Readonly<{ op: "create" }> + | Readonly<{ op: "update" | "restore" | "delete"; prev: string }> + | Readonly<{ op: "unchanged" }>; + +/** What a write must do given the head; `desired` undefined clears. */ +export function planTitle(head: Head | undefined, desired?: string): Plan { + if (!head) return desired ? { op: "create" } : { op: "unchanged" }; + if (desired === undefined) + return head.deleted ? { op: "unchanged" } : { op: "delete", prev: head.id }; + if (head.deleted) return { op: "restore", prev: head.id }; + return head.title === desired + ? { op: "unchanged" } + : { op: "update", prev: head.id }; +} + +/** The unsigned revision for `plan`, as `build_thread_title_revision` builds it. */ +export async function titleRevision( + channel: string, + root: string, + plan: Exclude, + title?: string, +) { + const lower = root.toLowerCase(); + if (plan.op !== "delete" && !title) + throw new Error("A title is required for this operation"); + const text = plan.op === "delete" ? "" : (title ?? ""); + return { + kind: ARTIFACT_KIND, + created_at: Math.floor(Date.now() / 1000), + content: text, + tags: [ + ["ar", "1"], + ["d", await threadTitleId(lower)], + ["h", channel], + ["type", THREAD_TITLE_TYPE], + ["op", plan.op], + ["root", lower], + ...("prev" in plan ? [["prev", plan.prev]] : []), + ...(text ? [["title", text]] : []), + ], + }; +} + +/** Live titles in `channels`. A title counts only when its `d` is derived + * from its root and its channel is one asked for. */ +export async function readTitles( + read: SnapshotRead, + channels: readonly string[], + signal: AbortSignal, +) { + const titles: ThreadTitle[] = []; + let partial = false; + for (let at = 0; at < channels.length; at += BATCH) { + const batch = channels.slice(at, at + BATCH); + const events = await read( + [ + { + kinds: [ARTIFACT_KIND], + "#h": batch, + "#type": [THREAD_TITLE_TYPE], + artifact: "current", + limit: PAGE, + }, + ], + { signal }, + ); + partial ||= events.length >= PAGE; + for (const event of events) { + const title = parseTitle(event); + if ( + title && + batch.includes(title.channel) && + tag(event, "d") === (await threadTitleId(title.root)) + ) + titles.push({ ...title, root: title.root.toLowerCase() }); + } + } + return { titles, partial }; +} + +export class TitleConflict extends Error { + constructor() { + super( + "Someone else changed this thread's title. Refresh to see the current one.", + ); + } +} + +/** Where a write goes and the live revision the writer last saw: undefined + * when the thread had no title. */ +export type TitleTarget = Readonly<{ + channel: string; + root: string; + revision?: string | undefined; +}>; + +/** Names (`desired`) or clears (undefined) a thread's title, provided its + * live head is still `expected.revision`. A lost race is a conflict, never + * retried: with an expected revision, a retry could only find the same + * change. Resolves to the new live revision, or undefined once cleared. */ +export async function writeTitle( + read: SnapshotRead, + writer: RelayWriter, + expected: TitleTarget, + desired: string | undefined, + signal: AbortSignal, +) { + const event = await readHead( + read, + expected.channel, + await threadTitleId(expected.root), + signal, + ); + const head = event && { + id: event.id, + deleted: artifactOp(event) === "delete", + title: tag(event, "title"), + }; + const live = head && !head.deleted ? head.id : undefined; + if (live !== expected.revision) throw new TitleConflict(); + const plan = planTitle(head, desired); + if (plan.op === "unchanged") return live; + const signed: RelayEvent = await writer.sign( + await titleRevision(expected.channel, expected.root, plan, desired), + signal, + ); + const delivery = await deliver(writer, signed, signal); + if (delivery.status === "refused") { + if ( + /artifact head changed|artifact identity is taken/.test(delivery.message) + ) + throw new TitleConflict(); + throw new Error(delivery.message); + } + if (delivery.status === "uncertain") + throw new Error( + `The title may not have saved (${delivery.message}). Refresh to check.`, + ); + return desired === undefined ? undefined : signed.id; +}