From 0d22f49fe3a1423055726704d3994a182b59aa1c Mon Sep 17 00:00:00 2001 From: Jeff Hedlund Date: Mon, 16 Nov 2026 14:46:57 -0500 Subject: [PATCH 1/5] feat(threads): show shared thread titles in channels and on thread tabs Read and write the shared thread titles Buzz 0.x, agents and the `buzz` CLI already set (NIP-AR kind 45010, type `buzz.thread-title`): a titled thread shows its title under its first message in the channel and on its thread tab, and renaming a thread tab sets the title for everyone in the channel. A rename that can't be saved stays on that tab on this device. One title store per relay session reads joined channels' current titles and re-reads only channels a live title revision touched. Writes compare against the revision last seen and report a conflict rather than overwriting. Provided by a new optional Named threads plugin (`buzz.threads`), on by default. While it is off, nothing reads titles and renaming a thread tab stays device-local, as on main. Channels can't see another plugin's state, so the plugin turns titles on through a counted switch in the title store (`enableThreadTitles`, from a `ctx.effect`); counting keeps titles on when a reloaded plugin's old instance is disposed after the new one starts. Part of #3455. Co-authored-by: Engineer Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jeff Hedlund --- crates/plugin-manager/src/lib.rs | 3 + docs/buzz-help.md | 5 + docs/plugin-architecture.md | 2 +- .../useConversationTabs.titles.test.tsx | 225 +++++++++++++ src/bundled/channels/useConversationTabs.tsx | 68 +++- src/bundled/index.ts | 7 + src/bundled/threads/README.md | 10 + src/bundled/threads/TitleAccessory.test.tsx | 86 +++++ src/bundled/threads/TitleAccessory.tsx | 32 ++ src/bundled/threads/index.test.ts | 21 ++ src/bundled/threads/index.tsx | 14 + src/bundled/threads/manifest.json | 7 + .../messages/thread-title-store.test.ts | 163 +++++++++ src/features/messages/thread-title-store.ts | 264 +++++++++++++++ src/features/messages/thread-titles.test.ts | 315 ++++++++++++++++++ src/features/messages/thread-titles.ts | 247 ++++++++++++++ 16 files changed, 1466 insertions(+), 3 deletions(-) create mode 100644 src/bundled/channels/useConversationTabs.titles.test.tsx create mode 100644 src/bundled/threads/README.md create mode 100644 src/bundled/threads/TitleAccessory.test.tsx create mode 100644 src/bundled/threads/TitleAccessory.tsx create mode 100644 src/bundled/threads/index.test.ts create mode 100644 src/bundled/threads/index.tsx create mode 100644 src/bundled/threads/manifest.json create mode 100644 src/features/messages/thread-title-store.test.ts create mode 100644 src/features/messages/thread-title-store.ts create mode 100644 src/features/messages/thread-titles.test.ts create mode 100644 src/features/messages/thread-titles.ts 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..7e3ba790f0 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -533,6 +533,11 @@ 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 that can't be saved, the name stays on that tab on this device only. + 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..1f3e44494d --- /dev/null +++ b/src/bundled/channels/useConversationTabs.titles.test.tsx @@ -0,0 +1,225 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { enableThreadTitles } 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"; + +// The Named threads plugin turns shared titles on while it runs. +let disable: (() => void) | undefined; +beforeEach(() => { + disable = enableThreadTitles(); +}); +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, 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("keeps the typed name on the tab when the shared write fails", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const h = await harness({ + publish: vi.fn(async () => { + throw new PublishRejected("Rejected", "restricted: not a member"); + }), + }); + await waitFor(() => expect(h.snapshotRead).toHaveBeenCalled()); + act(() => h.item()?.rename?.("Launch plan")); + await waitFor(() => expect(warn).toHaveBeenCalled()); + expect(h.localName()).toBe("Launch plan"); + expect(h.item()?.label).toBe("Launch plan"); + // Over the byte limit never reaches the relay and stays local too. + const long = "x".repeat(513); + act(() => h.item()?.rename?.(long)); + expect(h.localName()).toBe(long); + expect(h.publish).toHaveBeenCalledTimes(1); + warn.mockRestore(); +}); + +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..d1b4576110 100644 --- a/src/bundled/channels/useConversationTabs.tsx +++ b/src/bundled/channels/useConversationTabs.tsx @@ -21,6 +21,16 @@ 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, + writeTitle, +} from "../../features/messages/thread-titles"; import { BrowserIcon, MessageReplyIcon, @@ -773,10 +783,14 @@ 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; 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 +802,56 @@ 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, and + // stays there if it fails. A blank name only drops the local one. + function renameThread(tab: Extract, name: string) { + if (!threadTitlesEnabled()) 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 { + return tabState.renameTab(tab.id, name); + } + if (!desired) return tabState.renameTab(tab.id, ""); + if (!read || !writer) return tabState.renameTab(tab.id, desired); + const store = threadTitleStore(queries); + const title = desired; + tabState.renameTab(tab.id, title); + writeTitle( + read, + writer, + { + channel: tab.channelId, + root: rootId, + revision: store.get(tab.channelId, rootId)?.revision, + }, + title, + AbortSignal.timeout(20_000), + ).then( + (revision) => { + if (revision) + store.apply(tab.channelId, rootId, { + title, + channel: tab.channelId, + root: rootId.toLowerCase(), + revision, + updatedAt: Math.floor(Date.now() / 1000), + }); + tabState.renameTab(tab.id, ""); + }, + (cause) => { + console.warn( + "Couldn't save the thread title; kept it on this tab", + cause, + ); + tabState.renameTab(tab.id, title); + }, + ); + } // 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 +912,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..11a4eaedff --- /dev/null +++ b/src/bundled/threads/TitleAccessory.tsx @@ -0,0 +1,32 @@ +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..b67e1a0d85 --- /dev/null +++ b/src/features/messages/thread-title-store.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it, vi } from "vitest"; +import type { ReadFilter, RelayEvent } from "../relay/events"; +import type { RelaySession } from "../relay/session"; +import { + enableThreadTitles, + 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("keeps the titles it has and reports a failed re-read", async () => { + const f = fixture([await head("e1", "Launch plan")]); + const store = threadTitleStore(f.session); + const stop = store.subscribe(() => {}); + await vi.waitFor(() => expect(store.get(ALPHA, ROOT)).toBeDefined()); + f.snapshotRead.mockRejectedValueOnce(new Error("Relay offline")); + store.refresh(); + await vi.waitFor(() => + expect(store.snapshot().error).toBe("Relay offline"), + ); + expect(store.get(ALPHA, ROOT)?.title).toBe("Launch plan"); + stop(); + }); + + 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..85188740cf --- /dev/null +++ b/src/features/messages/thread-title-store.ts @@ -0,0 +1,264 @@ +// 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. 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; + +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; + /** Reads every joined channel again. */ + refresh(): void; + /** 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, + ); +} + +export function useThreadTitle( + session: Session, + channelId: string, + rootId: string, +) { + return useThreadTitles(session).titles?.get( + activityKey(channelId, rootId.toLowerCase()), + ); +} + +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 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); + set({ titles, partial: partial.size > 0, error: undefined }); + }) + .catch((cause) => { + if (signal.aborted) return; + 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(); + 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) stale.add(channel); + if (reading) return; + clearTimeout(timer); + timer = setTimeout(flush, TITLE_DEBOUNCE_MS); + }); + }); + run(ids, true); + stopRun = () => { + controller.abort(); + clearTimeout(timer); + 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())), + refresh() { + if (!listeners.size) return; + close(); + open(); + }, + 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..ca6b5e228d --- /dev/null +++ b/src/features/messages/thread-titles.test.ts @@ -0,0 +1,315 @@ +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"); + }); + + 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(); + }); +}); + +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) }), + ]); + }); +}); + +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..5c05e1eec9 --- /dev/null +++ b/src/features/messages/thread-titles.ts @@ -0,0 +1,247 @@ +// 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()}`); + +/** Trimmed title, or undefined when blank (clearing is its own operation). */ +export function normalizeTitle(title: string) { + const trimmed = title.trim(); + if (!trimmed) return undefined; + if (new TextEncoder().encode(trimmed).length > MAX_THREAD_TITLE_BYTES) + throw new Error(`Titles can be at most ${MAX_THREAD_TITLE_BYTES} bytes.`); + return trimmed; +} + +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. */ +export function parseTitle(event: EventData): ThreadTitle | undefined { + const [title, channel, root] = ["title", "h", "root"].map((t) => + tag(event, t), + ); + 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; +} From e2c917785d356f746c15ee2b20949b49852c8bb1 Mon Sep 17 00:00:00 2001 From: Jeff Hedlund Date: Tue, 17 Nov 2026 22:21:53 -0500 Subject: [PATCH 2/5] fix(threads): make shared titles safe to show and surface failed renames - parseTitle cleans every title it reads: line breaks and controls become a space, bidi formatting characters are removed, and anything over 512 bytes is cut at a code point boundary. Typed titles get the same cleaning. - The timeline row keeps a title to one line, with the full title on hover. - A failed tab rename drops the typed name, so it can't hide the shared title, and shows an error toast with Retry. A name over the limit says so and changes nothing. - A failed title read is retried after a jittered delay that doubles up to five minutes, instead of waiting for the channel list to change. - useThreadTitle reads one key, so a title change rerenders only its row. - Drop the store's unused refresh(). Co-authored-by: Engineer Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jeff Hedlund --- .../useConversationTabs.titles.test.tsx | 68 ++++++++++++++----- src/bundled/channels/useConversationTabs.tsx | 23 ++++--- src/bundled/threads/TitleAccessory.tsx | 6 +- .../messages/thread-title-store.test.ts | 64 +++++++++++++---- src/features/messages/thread-title-store.ts | 43 +++++++++--- src/features/messages/thread-titles.test.ts | 47 +++++++++++++ src/features/messages/thread-titles.ts | 52 +++++++++++--- 7 files changed, 246 insertions(+), 57 deletions(-) diff --git a/src/bundled/channels/useConversationTabs.titles.test.tsx b/src/bundled/channels/useConversationTabs.titles.test.tsx index 1f3e44494d..f11c21dbca 100644 --- a/src/bundled/channels/useConversationTabs.titles.test.tsx +++ b/src/bundled/channels/useConversationTabs.titles.test.tsx @@ -11,10 +11,24 @@ 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(); @@ -162,24 +176,46 @@ it("renaming against a titled thread updates it from the shown revision", async expect(h.item()?.label).toBe("Ship plan"); }); -it("keeps the typed name on the tab when the shared write fails", async () => { - const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const h = await harness({ - publish: vi.fn(async () => { - throw new PublishRejected("Rejected", "restricted: not a member"); - }), +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"); }); - await waitFor(() => expect(h.snapshotRead).toHaveBeenCalled()); - act(() => h.item()?.rename?.("Launch plan")); - await waitFor(() => expect(warn).toHaveBeenCalled()); - expect(h.localName()).toBe("Launch plan"); + 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"); - // Over the byte limit never reaches the relay and stays local too. - const long = "x".repeat(513); - act(() => h.item()?.rename?.(long)); - expect(h.localName()).toBe(long); - expect(h.publish).toHaveBeenCalledTimes(1); - warn.mockRestore(); + // 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("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 () => { diff --git a/src/bundled/channels/useConversationTabs.tsx b/src/bundled/channels/useConversationTabs.tsx index d1b4576110..d8d758b875 100644 --- a/src/bundled/channels/useConversationTabs.tsx +++ b/src/bundled/channels/useConversationTabs.tsx @@ -58,6 +58,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"; @@ -786,6 +787,7 @@ export function useConversationTabs({ // 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(); function threadLabel(tab: Extract, name?: string) { if (tab.name) return tab.name; const rootId = rootOfTab(tab); @@ -803,8 +805,9 @@ export function useConversationTabs({ 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, and - // stays there if it fails. A blank name only drops the local one. + // 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 with a + // retry. A blank name only drops the local one. function renameThread(tab: Extract, name: string) { if (!threadTitlesEnabled()) return tabState.renameTab(tab.id, name); const rootId = rootOfTab(tab); @@ -813,8 +816,9 @@ export function useConversationTabs({ let desired: string | undefined; try { desired = normalizeTitle(name); - } catch { - return tabState.renameTab(tab.id, name); + } catch (cause) { + notify(cause instanceof Error ? cause.message : String(cause), "error"); + return; } if (!desired) return tabState.renameTab(tab.id, ""); if (!read || !writer) return tabState.renameTab(tab.id, desired); @@ -844,11 +848,12 @@ export function useConversationTabs({ tabState.renameTab(tab.id, ""); }, (cause) => { - console.warn( - "Couldn't save the thread title; kept it on this tab", - cause, - ); - tabState.renameTab(tab.id, title); + tabState.renameTab(tab.id, ""); + const reason = cause instanceof Error ? cause.message : String(cause); + notify(`Couldn’t save the thread title. ${reason}`, "error", { + label: "Retry", + onClick: () => renameThread(tab, title), + }); }, ); } diff --git a/src/bundled/threads/TitleAccessory.tsx b/src/bundled/threads/TitleAccessory.tsx index 11a4eaedff..e92f1398dd 100644 --- a/src/bundled/threads/TitleAccessory.tsx +++ b/src/bundled/threads/TitleAccessory.tsx @@ -23,10 +23,14 @@ export function TitleAccessory({ size="sm" data-thread-title="" aria-label={`Open thread: ${title.title}`} + title={title.title} onClick={() => openThread()} >