From 0d22f49fe3a1423055726704d3994a182b59aa1c Mon Sep 17 00:00:00 2001 From: Jeff Hedlund Date: Mon, 16 Nov 2026 14:46:57 -0500 Subject: [PATCH 1/2] 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 c3dd20558e03ba48d7d1a6a1215a9fffca9cfe29 Mon Sep 17 00:00:00 2001 From: Jeff Hedlund Date: Mon, 16 Nov 2026 14:50:45 -0500 Subject: [PATCH 2/2] feat(threads): add a Threads page listing titled threads A Threads page (below Activity in the Messages sidebar, Cmd/Ctrl+Shift+H) lists titled threads across joined channels, newest reply or title change first. Rows open the thread, can be filtered by channel, and rename or clear a title in place; a stale revision reports a conflict instead of overwriting. Rows also show unread replies in threads you follow (Mark read clears them) and how long agents have been working in a thread, from the session's existing thread-activity and agent-activity state; the sidebar entry shows a dot or a working count. Reply times come from one `#e` read per titled thread when it first appears, then live replies (including reconnect replay), so reopening the page reads nothing. It stops, and forgets what it read, when the plugin is switched off. A read that fills its page reads again the roots it left out. Part of #3455. Co-authored-by: Engineer Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jeff Hedlund --- docs/buzz-help.md | 19 +- src/app/shell/presentation.ts | 3 + src/bundled/navigation-owner.test.ts | 1 + src/bundled/threads/README.md | 11 +- src/bundled/threads/Threads.module.css | 114 +++ src/bundled/threads/ThreadsBadge.tsx | 49 ++ src/bundled/threads/ThreadsPage.test.tsx | 743 ++++++++++++++++++ src/bundled/threads/ThreadsPage.tsx | 465 +++++++++++ src/bundled/threads/icon.png | Bin 0 -> 23428 bytes src/bundled/threads/index.test.ts | 42 +- src/bundled/threads/index.tsx | 36 +- src/bundled/threads/manifest.json | 2 +- src/bundled/threads/thread-signals.test.tsx | 168 ++++ src/bundled/threads/thread-signals.ts | 132 ++++ .../messages/thread-activity-store.ts | 154 ++++ src/features/messages/thread-title-store.ts | 14 +- src/features/messages/thread-titles.test.ts | 146 ++++ src/features/messages/thread-titles.ts | 89 ++- src/features/relay/unread.test.ts | 21 + 19 files changed, 2183 insertions(+), 26 deletions(-) create mode 100644 src/bundled/threads/Threads.module.css create mode 100644 src/bundled/threads/ThreadsBadge.tsx create mode 100644 src/bundled/threads/ThreadsPage.test.tsx create mode 100644 src/bundled/threads/ThreadsPage.tsx create mode 100644 src/bundled/threads/icon.png create mode 100644 src/bundled/threads/thread-signals.test.tsx create mode 100644 src/bundled/threads/thread-signals.ts create mode 100644 src/features/messages/thread-activity-store.ts diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 7e3ba790f0..6195980a43 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -533,11 +533,20 @@ 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. +- **Threads** (below Activity in the Messages sidebar, or Cmd/Ctrl+Shift+H) lists threads that have a + title in channels you have joined, most recent reply or title change first. Choose one to open the thread, + or narrow the list with the channel menu; the **×** beside it shows all channels again. **Rename** edits a + title in place (Enter saves, Escape cancels); saving it empty removes the title for everyone. If someone + else changed the title first, nothing is overwritten: refresh and try again. + A thread you follow shows its unread reply count (**Mark read** clears it), and a thread with an agent + working in it shows how long it has been working. + The sidebar's Threads entry shows a dot while a named thread is unread, or how many have agents working. Titles are shared, + channel-visible data that agents and the `buzz threads title` CLI also set, and Buzz 0.x shows the same + titles; they are not searchable. 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. Title changes and new replies update the + list, which stays loaded while you use other pages; **Refresh** reads it again. 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/src/app/shell/presentation.ts b/src/app/shell/presentation.ts index 6c4d84085d..d082204489 100644 --- a/src/app/shell/presentation.ts +++ b/src/app/shell/presentation.ts @@ -6,6 +6,7 @@ import { NoteIcon, GearIcon, LightningIcon, + MessageReplyIcon, RobotIcon, SendIcon, } from "../../shared/design-system/icons/index"; @@ -23,6 +24,7 @@ export const shellPresentation = { const bundledOrder = [ "buzz.channels/channels", "buzz.inbox/inbox", + "buzz.threads/threads", "buzz.drafts-and-sent/drafts-sent", "buzz.reminders/reminders", "buzz.bestie/bestie", @@ -54,6 +56,7 @@ export function orderPages( const bundledIcons = new Map([ ["buzz.inbox/inbox", BellIcon], + ["buzz.threads/threads", MessageReplyIcon], ["buzz.drafts-and-sent/drafts-sent", SendIcon], ["buzz.reminders/reminders", AlarmIcon], ["buzz.agents/agents", RobotIcon], diff --git a/src/bundled/navigation-owner.test.ts b/src/bundled/navigation-owner.test.ts index 964da081b0..2d87052631 100644 --- a/src/bundled/navigation-owner.test.ts +++ b/src/bundled/navigation-owner.test.ts @@ -47,6 +47,7 @@ it("gives every bundled page to the app whose navigation lists it", async () => // Pages listed in the Messages sidebar keep Messages selected. "buzz.drafts-and-sent/drafts-sent": messages, "buzz.inbox/inbox": messages, + "buzz.threads/threads": messages, // Dock apps own themselves. "buzz.bestie/bestie": "buzz.bestie/bestie", "buzz.reminders/reminders": "buzz.reminders/reminders", diff --git a/src/bundled/threads/README.md b/src/bundled/threads/README.md index 31e8ab51ea..848caa4fab 100644 --- a/src/bundled/threads/README.md +++ b/src/bundled/threads/README.md @@ -1,10 +1,13 @@ # Named threads -See a thread's title wherever the thread shows. +Find the threads that matter by their titles, across every channel you have joined. ## 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. +1. Open **Threads** from the navigation, or press Cmd+Shift+H (Ctrl+Shift+H on Windows and Linux). +2. Threads with a title are listed newest activity first. Choose one to open it beside its channel. +3. Use the channel menu to show one channel's threads, and the **×** beside it to show all of them again. +4. Rows show unread replies in threads you follow (choose **Mark read** to clear them) and how long an agent has been working in a thread. The sidebar's Threads entry shows a dot while a named thread is unread, or how many have agents working. +5. Choose **Rename** to edit a title in place: press Enter to save or Escape to cancel. Save it empty to remove the title. -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. +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. A titled thread also shows its title under its first message in the channel and on its thread tab; renaming a thread tab sets the shared title. The list updates as titles change and replies arrive. diff --git a/src/bundled/threads/Threads.module.css b/src/bundled/threads/Threads.module.css new file mode 100644 index 0000000000..da2edd78a3 --- /dev/null +++ b/src/bundled/threads/Threads.module.css @@ -0,0 +1,114 @@ +.page { + display: flex; + flex-direction: column; + height: 100%; + min-height: 0; +} + +.toolbar { + display: flex; + align-items: center; + gap: var(--space-1); + flex: none; + padding: var(--space-2) var(--space-row-gap); +} + +.notice { + margin: 0; + padding: var(--space-2) var(--space-row-gap); +} + +.scroller { + flex: 1; + min-height: 0; + overflow: auto; + padding: var(--space-2) var(--space-row-gap); +} + +.list { + list-style: none; + margin: 0; + padding: 0; +} + +.row { + min-width: 0; +} + +.label { + display: flex; + flex-direction: column; + min-width: 0; +} + +.actions { + display: flex; + flex: none; + align-self: center; + margin-inline-end: var(--space-control-inset); +} + +/* As the channel list marks unread: read titles in the quieter navigation + ink, unread ones in the unread ink at the heavier weight. */ +.title { + color: var(--text-navigation); +} + +.title[data-unread] { + color: var(--text-navigation-unread); + font-weight: var(--type-weight-semibold); +} + +.unreadDot { + display: block; + flex-shrink: 0; + width: 0.5rem; + height: 0.5rem; + border-radius: 50%; + background: var(--affordance-prominent-mark); +} + +.signals { + display: inline-flex; + align-items: center; + gap: var(--space-1); +} + +.working { + display: inline-flex; + align-items: center; + gap: var(--space-1); + color: var(--text-subtle); +} + +.badgeWorking { + display: inline-flex; + align-items: center; + gap: var(--space-1); + color: var(--text-subtle); + font-variant-numeric: tabular-nums; +} + +.badgeDot { + display: block; + width: 0.375rem; + height: 0.375rem; + border-radius: 50%; + background: var(--affordance-prominent-mark); +} + +/* Row actions show on row hover or keyboard focus (not any focus: a clicked + button keeps focus, which would leave them shown), always without hover. */ +.row [data-reveal] { + opacity: 0; +} + +:is(.row:hover, .row:has(:focus-visible)) [data-reveal] { + opacity: 1; +} + +@media (hover: none) { + .row [data-reveal] { + opacity: 1; + } +} diff --git a/src/bundled/threads/ThreadsBadge.tsx b/src/bundled/threads/ThreadsBadge.tsx new file mode 100644 index 0000000000..b09f37c24a --- /dev/null +++ b/src/bundled/threads/ThreadsBadge.tsx @@ -0,0 +1,49 @@ +import { useMemo } from "react"; +import { useThreadTitles } from "../../features/messages/thread-title-store"; +import { useRelayConnection } from "../../features/relay/react"; +import type { RelayData } from "../../features/relay/service"; +import type { RelaySession } from "../../features/relay/session"; +import { TypingDots } from "../../shared/design-system/ui/TypingDots"; +import styles from "./Threads.module.css"; +import { useThreadSignals } from "./thread-signals"; + +/** The sidebar entry's mark: how many titled threads have an agent working, + * else a dot while one is unread. Live with the page closed. */ +export function ThreadsBadge({ relay }: { relay: RelayData }) { + const connection = useRelayConnection(relay); + return connection.status === "ready" ? ( + + ) : null; +} + +export function SessionBadge({ session }: { session: RelaySession }) { + const { titles } = useThreadTitles(session); + const channels = useMemo( + () => [...new Set([...(titles?.values() ?? [])].map((t) => t.channel))], + [titles], + ); + const { unread, working } = useThreadSignals(session, channels); + if (!titles) return null; + const busy = [...working.keys()].filter((key) => titles.has(key)).length; + if (busy) + return ( + + + {busy} + + ); + const unreadThreads = [...unread.keys()].filter((key) => + titles.has(key), + ).length; + return unreadThreads ? ( + + ) : null; +} diff --git a/src/bundled/threads/ThreadsPage.test.tsx b/src/bundled/threads/ThreadsPage.test.tsx new file mode 100644 index 0000000000..78ac71b5e7 --- /dev/null +++ b/src/bundled/threads/ThreadsPage.test.tsx @@ -0,0 +1,743 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { + act, + cleanup, + render, + screen, + waitFor, + within, +} from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import type { Navigation } from "../../features/navigation/controller"; +import type { ReadFilter, RelayEvent } from "../../features/relay/events"; +import type { RelaySession } from "../../features/relay/session"; +import { enableThreadTitles } from "../../features/messages/thread-title-store"; +import { titleRevision } from "../../features/messages/thread-titles"; +import { ThreadsView } from "./ThreadsPage"; + +const ALPHA = "11111111-1111-4111-8111-111111111111"; +const BETA = "22222222-2222-4222-8222-222222222222"; +const scope = { + viewer: "f".repeat(64), + communityOrigin: "https://example.org", +}; +const event = ( + id: string, + tags: string[][], + content: string, + created_at: number, +) => + ({ + id, + pubkey: scope.viewer, + kind: 45010, + created_at, + content, + tags, + sig: "", + }) as unknown as RelayEvent; +async function title( + id: string, + text: string, + root: string, + channel: string, + at: number, +) { + const template = await titleRevision(channel, root, { op: "create" }, text); + return event(id, template.tags, text, at); +} + +const reply = (id: string, channel: string, root: string, at: number) => ({ + ...event( + id, + [ + ["h", channel], + ["e", root, "", "reply"], + ], + "hi", + at, + ), + kind: 9, +}); + +async function fixture({ + empty = false, + writable = true, + hold, + holdActivity, +}: { + empty?: boolean; + writable?: boolean; + hold?: Promise; + /** Holds every reply read open until it resolves. */ + holdActivity?: Promise; +} = {}) { + const now = Math.floor(Date.now() / 1000); + // The relay's current heads and stored replies; a test changes them as the + // relay would. + const relay = { + heads: [] as RelayEvent[], + replies: [reply("r1", ALPHA, "a".repeat(64), now - 10)] as RelayEvent[], + }; + const titles = empty + ? [] + : [ + await title("e1", "Launch plan", "a".repeat(64), ALPHA, now - 500), + await title("e2", "Bug triage", "b".repeat(64), BETA, now - 400), + await title("e3", "Retro notes", "c".repeat(64), ALPHA, now - 300), + ]; + const publish = vi.fn(async () => ""); + relay.heads = titles; + const snapshotRead = vi.fn(async (filters: readonly ReadFilter[]) => { + const [filter] = filters; + // A head read names one `d`. + if (filter?.["#d"]) + return relay.heads.filter((t) => + t.tags.some(([k, v]) => k === "d" && v === filter["#d"]?.[0]), + ); + // The first list read can be held open; it answers with the heads it + // started with, as a relay would. + const heads = relay.heads; + if (hold && snapshotRead.mock.calls.length === 1) await hold; + return heads.filter((t) => + t.tags.some(([k, v]) => k === "h" && filter?.["#h"]?.includes(v ?? "")), + ); + }); + // A newer reply moves Launch plan to the top. + const read = vi.fn(async (filters: readonly ReadFilter[]) => { + await holdActivity; + return relay.replies.filter((r) => + r.tags.some( + ([k, v]) => k === "e" && filters[0]?.["#e"]?.includes(v ?? ""), + ), + ); + }); + const list = { + status: "ready", + channels: [ + { id: ALPHA, name: "alpha" }, + { id: BETA, name: "beta" }, + ], + }; + const live: { + titles?: ((events: readonly RelayEvent[]) => void) | undefined; + events?: + | ((batch: { events: readonly RelayEvent[]; replay?: boolean }) => void) + | undefined; + replay?: boolean | undefined; + followed?: readonly string[]; + } = {}; + // Thread unread and agent activity, as the session projects them. + const signals = { + unread: new Map(), + agents: { + status: "listening", + turns: [], + typing: [], + local: [], + } as Record, + listeners: new Set<() => void>(), + emit() { + for (const listener of [...signals.listeners]) listener(); + }, + }; + const prepareThreadRead = vi.fn( + (channel: string, root: string) => async () => { + signals.unread.set( + channel, + (signals.unread.get(channel) ?? []).filter((t) => t.rootId !== root), + ); + signals.emit(); + return { status: "saved" }; + }, + ); + const session = { + unread: { + activity: (channelId: string) => ({ + channelId, + items: (signals.unread.get(channelId) ?? []).map((t) => ({ + ...t, + channelId, + })), + }), + subscribeActivity: (_: string, listener: () => void) => { + signals.listeners.add(listener); + return () => signals.listeners.delete(listener); + }, + prepareThreadRead, + }, + agentActivity: { + snapshot: () => signals.agents, + subscribe: (listener: () => void) => { + signals.listeners.add(listener); + return () => signals.listeners.delete(listener); + }, + }, + artifacts: { + follow: vi.fn((ids: readonly string[], listener: typeof live.titles) => { + live.followed = ids; + live.titles = listener; + return () => { + live.titles = undefined; + }; + }), + }, + subscribeLive: vi.fn( + (listener: typeof live.events, options?: { replay?: boolean }) => { + live.events = listener; + live.replay = options?.replay; + return () => { + live.events = undefined; + }; + }, + ), + channels: { + ensureList: () => () => {}, + subscribeList: () => () => {}, + list: () => list, + }, + snapshotRead, + read, + configArtifactWriter: writable + ? { + sign: vi.fn(async (t: { tags: string[][]; content: string }) => + event("new", t.tags, t.content, now), + ), + publish, + } + : undefined, + } as unknown as RelaySession; + const open = vi.fn(async () => ({ status: "opened" })); + const mount = () => + render( + , + ); + const view = mount(); + return { + publish, + open, + snapshotRead, + read, + live, + now, + relay, + view, + mount, + signals, + prepareThreadRead, + }; +} +const rows = async () => + within(await screen.findByRole("list", { name: "Named threads" })) + .queryAllByRole("listitem") + .map((item) => item.textContent?.split("·")[0]?.trim()); + +let disable: (() => void) | undefined; +beforeEach(() => { + disable = enableThreadTitles(); + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + disable?.(); +}); + +it("lists titles newest activity first with their channel, and opens the thread root", async () => { + const f = await fixture(); + expect(await rows()).toEqual([ + "Launch planalpha", + "Retro notesalpha", + "Bug triagebeta", + ]); + await userEvent.click(screen.getByRole("button", { name: /^Launch plan/ })); + expect(f.open).toHaveBeenCalledWith({ + version: 1, + kind: "conversation", + scope, + channelId: ALPHA, + messageId: "a".repeat(64), + threadRootId: "a".repeat(64), + }); +}); + +it("filters by channel", async () => { + await fixture(); + await rows(); + await userEvent.click(screen.getByRole("combobox", { name: "Channel" })); + await userEvent.click(await screen.findByRole("option", { name: "beta" })); + await waitFor(async () => expect(await rows()).toEqual(["Bug triagebeta"])); +}); + +it("offers a clear-filter button only while a channel is chosen", async () => { + await fixture(); + await rows(); + expect( + screen.queryByRole("button", { name: "Show all channels" }), + ).not.toBeInTheDocument(); + await userEvent.click(screen.getByRole("combobox", { name: "Channel" })); + await userEvent.click(await screen.findByRole("option", { name: "alpha" })); + await waitFor(async () => expect(await rows()).toHaveLength(2)); + await userEvent.click( + screen.getByRole("button", { name: "Show all channels" }), + ); + expect(await rows()).toHaveLength(3); + expect(screen.getByRole("combobox", { name: "Channel" })).toHaveFocus(); + expect( + screen.queryByRole("button", { name: "Show all channels" }), + ).not.toBeInTheDocument(); +}); + +it("draws rows by title time before any reply read returns, then reorders", async () => { + let release = () => {}; + const holdActivity = new Promise((resolve) => { + release = resolve; + }); + const f = await fixture({ holdActivity }); + try { + await waitFor(() => expect(f.read).toHaveBeenCalled()); + expect(await rows()).toEqual([ + "Retro notesalpha", + "Bug triagebeta", + "Launch planalpha", + ]); + } finally { + release(); + } + await waitFor(async () => expect((await rows())[0]).toBe("Launch planalpha")); +}); + +it("takes a reply missed while disconnected from the reconnect replay", async () => { + const f = await fixture(); + await waitFor(async () => expect((await rows())[0]).toBe("Launch planalpha")); + await waitFor(() => expect(f.read).toHaveBeenCalledTimes(2)); + expect(f.live.replay).toBe(true); + f.view.unmount(); + // After a reconnect, the route replays a reply sent while offline. + act(() => + f.live.events?.({ + events: [reply("r8", ALPHA, "c".repeat(64), f.now)], + replay: true, + }), + ); + f.mount(); + expect((await rows())[0]).toBe("Retro notesalpha"); + expect(f.read).toHaveBeenCalledTimes(2); +}); + +it("reopens with no relay reads and keeps replies that arrived while closed", async () => { + const f = await fixture(); + await waitFor(async () => expect((await rows())[0]).toBe("Launch planalpha")); + await waitFor(() => expect(f.read).toHaveBeenCalledTimes(2)); + const titleReads = f.snapshotRead.mock.calls.length; + f.view.unmount(); + // Bug triage gets a newer reply while the page is closed. + act(() => + f.live.events?.({ + events: [reply("r9", BETA, "b".repeat(64), f.now)], + }), + ); + f.mount(); + expect(await rows()).toEqual([ + "Bug triagebeta", + "Launch planalpha", + "Retro notesalpha", + ]); + expect(f.snapshotRead).toHaveBeenCalledTimes(titleReads); + expect(f.read).toHaveBeenCalledTimes(2); +}); + +it("lets go of titles and live replies once shared titles are switched off", async () => { + const f = await fixture(); + await waitFor(async () => expect((await rows())[0]).toBe("Launch planalpha")); + // As when Named threads is turned off: the page goes, and so does the + // session-long reply tracking that outlives it. + f.view.unmount(); + expect(f.live.events).toBeDefined(); + act(() => disable?.()); + expect(f.live.events).toBeUndefined(); + expect(f.live.titles).toBeUndefined(); + // Turned on again, the page reads titles and replies afresh. + act(() => { + disable = enableThreadTitles(); + }); + f.mount(); + await waitFor(async () => expect((await rows())[0]).toBe("Launch planalpha")); + expect(f.live.events).toBeDefined(); + expect(f.read).toHaveBeenCalledTimes(4); +}); + +it("renames inline with Enter and cancels with Escape", async () => { + const f = await fixture(); + await rows(); + await userEvent.click( + screen.getByRole("button", { name: "Rename Bug triage" }), + ); + await userEvent.keyboard("{Escape}"); + expect(f.publish).not.toHaveBeenCalled(); + await userEvent.click( + screen.getByRole("button", { name: "Rename Bug triage" }), + ); + const field = screen.getByRole("textbox", { name: "Title for Bug triage" }); + await userEvent.clear(field); + await userEvent.type(field, " Bugs {Enter}"); + expect( + await screen.findByRole("button", { name: /^Bugs/ }), + ).toBeInTheDocument(); + const [signed] = f.publish.mock.calls[0] as unknown as [RelayEvent]; + expect(signed.tags).toContainEqual(["op", "update"]); + expect(signed.tags).toContainEqual(["prev", "e2"]); + expect(signed.tags).toContainEqual(["title", "Bugs"]); + expect(f.publish).toHaveBeenCalledTimes(1); +}); + +it("clears a title saved blank with a soft delete and removes its row", async () => { + const f = await fixture(); + await rows(); + expect( + screen.queryByRole("button", { name: /^Clear title/ }), + ).not.toBeInTheDocument(); + await userEvent.click( + screen.getByRole("button", { name: "Rename Retro notes" }), + ); + await userEvent.clear( + screen.getByRole("textbox", { name: "Title for Retro notes" }), + ); + await userEvent.keyboard("{Enter}"); + await waitFor(async () => + expect(await rows()).toEqual(["Launch planalpha", "Bug triagebeta"]), + ); + const [signed] = f.publish.mock.calls[0] as unknown as [RelayEvent]; + expect(signed.tags).toContainEqual(["op", "delete"]); + expect(signed.content).toBe(""); +}); + +it("reports a title someone else changed instead of overwriting it", async () => { + const f = await fixture(); + await rows(); + // The head is now another revision. + f.snapshotRead.mockImplementationOnce(async () => [ + await title("e9", "Theirs", "a".repeat(64), ALPHA, 1), + ]); + await userEvent.click( + screen.getByRole("button", { name: "Rename Launch plan" }), + ); + await userEvent.type( + screen.getByRole("textbox", { name: "Title for Launch plan" }), + " v2{Enter}", + ); + expect(await screen.findByRole("alert")).toHaveTextContent( + "Someone else changed this thread's title", + ); + expect(f.publish).not.toHaveBeenCalled(); + expect(await rows()).toHaveLength(3); +}); + +it("shows an empty state when no thread has a title, and no edit actions without a writer", async () => { + await fixture({ empty: true }); + expect(await screen.findByText("No named threads")).toBeInTheDocument(); + cleanup(); + await fixture({ writable: false }); + await rows(); + expect( + screen.queryByRole("button", { name: /^Rename/ }), + ).not.toBeInTheDocument(); +}); + +it("moves a locally renamed old thread to the top with a fresh time", async () => { + await fixture(); + expect(await rows()).toEqual([ + "Launch planalpha", + "Retro notesalpha", + "Bug triagebeta", + ]); + await userEvent.click( + screen.getByRole("button", { name: "Rename Bug triage" }), + ); + const field = screen.getByRole("textbox", { name: "Title for Bug triage" }); + await userEvent.clear(field); + await userEvent.type(field, "Bugs{Enter}"); + await waitFor(async () => + expect(await rows()).toEqual([ + "Bugsbeta", + "Launch planalpha", + "Retro notesalpha", + ]), + ); + expect(screen.getByRole("button", { name: /^Bugs/ })).toHaveTextContent( + "beta · just now", + ); +}); + +it("takes titles from the relay's current read, not live event order", async () => { + const f = await fixture(); + await rows(); + expect(f.live.followed).toEqual([ALPHA, BETA]); + const reads = f.snapshotRead.mock.calls.length; + // NIP-AR orders revisions by `prev`: the head e5 is older than the e4 it + // replaces, and a newest-first replay delivers e5 before e4. + const b = "b".repeat(64); + const e4 = await title("e4", "Bug board", b, BETA, f.now - 5); + const e5 = await title("e5", "Bug list", b, BETA, f.now - 50); + f.relay.heads = f.relay.heads.map((head) => (head.id === "e2" ? e5 : head)); + act(() => f.live.titles?.([e5, e4])); + await waitFor(async () => + expect(await rows()).toEqual([ + "Launch planalpha", + "Bug listbeta", + "Retro notesalpha", + ]), + ); + // One read for the burst, of the stale channel only. + expect(f.snapshotRead.mock.calls.slice(reads)).toEqual([ + [[expect.objectContaining({ "#h": [BETA] })], expect.anything()], + ]); + // A clear followed by its same-second predecessor: the relay has no head. + const c = "c".repeat(64); + const cleared = await titleRevision(ALPHA, c, { op: "delete", prev: "e3" }); + f.relay.heads = f.relay.heads.filter((head) => head.id !== "e3"); + const predecessor = await title("e3", "Retro notes", c, ALPHA, f.now - 300); + act(() => + f.live.titles?.([event("e6", cleared.tags, "", f.now - 300), predecessor]), + ); + await waitFor(async () => + expect(await rows()).toEqual(["Launch planalpha", "Bug listbeta"]), + ); + // A revision whose `d` is not derived from its root changes nothing. + const forged = ( + await title("e7", "Forged", "d".repeat(64), ALPHA, f.now) + ).tags.map(([k, v]) => (k === "d" ? ["d", "x"] : [k ?? "", v ?? ""])); + const before = f.snapshotRead.mock.calls.length; + act(() => f.live.titles?.([event("e7", forged, "Forged", f.now)])); + // A reply is the completion barrier: it lands after the forged revision. + act(() => + f.live.events?.({ events: [reply("r2", BETA, "b".repeat(64), f.now)] }), + ); + await waitFor(async () => + expect(await rows()).toEqual(["Bug listbeta", "Launch planalpha"]), + ); + expect(f.snapshotRead.mock.calls.length).toBe(before); +}); + +it("keeps a rename and a reply that arrive while the first read is open", async () => { + let release = () => {}; + const hold = new Promise((resolve) => { + release = resolve; + }); + const f = await fixture({ hold }); + try { + await waitFor(() => expect(f.snapshotRead).toHaveBeenCalledTimes(1)); + const b = "b".repeat(64); + const renamed = await title("e4", "Bug board", b, BETA, f.now - 5); + f.relay.heads = f.relay.heads.map((head) => + head.id === "e2" ? renamed : head, + ); + act(() => f.live.titles?.([renamed])); + // The relay stores the reply before it is delivered live. + const late = reply("r2", ALPHA, "c".repeat(64), f.now); + f.relay.replies.push(late); + act(() => f.live.events?.({ events: [late] })); + // Both are pending until the read settles; no read starts meanwhile. + expect(f.snapshotRead).toHaveBeenCalledTimes(1); + } finally { + release(); + } + await waitFor(async () => + expect(await rows()).toEqual([ + "Retro notesalpha", + "Bug boardbeta", + "Launch planalpha", + ]), + ); + expect(f.snapshotRead).toHaveBeenCalledTimes(2); +}); + +it("clears a failed automatic re-read's error once a later one succeeds", async () => { + const f = await fixture(); + await rows(); + const b = "b".repeat(64); + const renamed = await title("e4", "Bug board", b, BETA, f.now - 5); + f.snapshotRead.mockRejectedValueOnce(new Error("Relay offline")); + act(() => f.live.titles?.([renamed])); + expect(await screen.findByRole("alert")).toHaveTextContent("Relay offline"); + f.relay.heads = f.relay.heads.map((head) => + head.id === "e2" ? renamed : head, + ); + act(() => f.live.titles?.([renamed])); + await waitFor(async () => expect(await rows()).toContain("Bug boardbeta")); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); +}); + +it("reads a restored thread's replies again, even when its successor is older", async () => { + const f = await fixture(); + await rows(); + const a = "a".repeat(64); + const historyReads = () => + f.read.mock.calls.filter(([[filter]]) => filter?.["#e"]?.includes(a)) + .length; + expect(historyReads()).toBe(1); + // Cleared: the relay has no head for the thread. + const cleared = await titleRevision(ALPHA, a, { op: "delete", prev: "e1" }); + f.relay.heads = f.relay.heads.filter((head) => head.id !== "e1"); + act(() => f.live.titles?.([event("e8", cleared.tags, "", f.now - 2)])); + await waitFor(async () => + expect(await rows()).toEqual(["Retro notesalpha", "Bug triagebeta"]), + ); + // Restored by a successor stamped before its reply at now - 10. + const restored = await title("e9", "Launch plan", a, ALPHA, f.now - 600); + f.relay.heads = [...f.relay.heads, restored]; + act(() => f.live.titles?.([restored])); + await waitFor(async () => + expect(await rows()).toEqual([ + "Launch planalpha", + "Retro notesalpha", + "Bug triagebeta", + ]), + ); + expect(historyReads()).toBe(2); +}); + +const A = "a".repeat(64); +const B = "b".repeat(64); + +it("shows unread replies on a row, and Mark read clears them", async () => { + const f = await fixture(); + await rows(); + act(() => { + f.signals.unread.set(BETA, [{ rootId: B, unreadCount: 3 }]); + f.signals.emit(); + }); + expect( + await screen.findByRole("img", { name: "3 unread replies" }), + ).toBeInTheDocument(); + await userEvent.click( + screen.getByRole("button", { name: "Mark Bug triage read" }), + ); + expect(f.prepareThreadRead).toHaveBeenCalledWith(BETA, B); + await waitFor(() => + expect( + screen.queryByRole("img", { name: /unread repl/ }), + ).not.toBeInTheDocument(), + ); + expect( + screen.queryByRole("button", { name: "Mark Bug triage read" }), + ).not.toBeInTheDocument(); +}); + +it("shows how long agents have been working in a thread, then clears it", async () => { + const f = await fixture(); + await rows(); + act(() => { + f.signals.agents = { + status: "listening", + turns: [ + // Channel-level work is the channel's. + { + agent: "x", + channelId: ALPHA, + state: "working", + turnId: "t0", + timestamp: 1, + }, + ], + typing: [], + local: [ + { + agent: "y", + channelId: ALPHA, + threadRootId: A, + thread: true, + messageId: "m", + state: "working", + startedAt: Date.now() - 65_000, + }, + ], + }; + f.signals.emit(); + }); + expect( + await screen.findByRole("img", { + name: /^An agent is working for 1m \d+s$/, + }), + ).toBeInTheDocument(); + expect(screen.getAllByRole("img", { name: /working/ })).toHaveLength(1); + act(() => { + f.signals.agents = { + status: "listening", + turns: [], + typing: [], + local: [], + }; + f.signals.emit(); + }); + await waitFor(() => + expect( + screen.queryByRole("img", { name: /working/ }), + ).not.toBeInTheDocument(), + ); +}); + +it("loads a thread root unread state hasn't seen before marking the thread read", async () => { + const f = await fixture(); + await rows(); + act(() => { + f.signals.unread.set(BETA, [{ rootId: B, unreadCount: 2 }]); + f.signals.emit(); + }); + // As the session's unread state does for a root it holds no evidence of. + f.prepareThreadRead.mockImplementationOnce(() => { + throw new Error("Verified readable message evidence unavailable"); + }); + await userEvent.click( + await screen.findByRole("button", { name: "Mark Bug triage read" }), + ); + await waitFor(() => + expect( + screen.queryByRole("img", { name: /unread repl/ }), + ).not.toBeInTheDocument(), + ); + expect(f.read).toHaveBeenCalledWith( + [{ ids: [B], "#h": [BETA], limit: 1 }], + expect.anything(), + ); + expect(f.prepareThreadRead).toHaveBeenCalledTimes(2); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); +}); + +it("orders row actions Rename, Mark read and reveals them on hover or focus", async () => { + const f = await fixture(); + await rows(); + act(() => { + f.signals.unread.set(ALPHA, [{ rootId: A, unreadCount: 1 }]); + f.signals.emit(); + }); + const read = await screen.findByRole("button", { + name: "Mark Launch plan read", + }); + const row = read.closest("li") as HTMLElement; + expect( + within(row) + .getAllByRole("button") + .slice(1) + .map((button) => button.getAttribute("aria-label")), + ).toEqual(["Rename Launch plan", "Mark Launch plan read"]); + const reveal = (name: string) => + within(row) + .getByRole("button", { name }) + .parentElement?.hasAttribute("data-reveal"); + expect(reveal("Mark Launch plan read")).toBe(true); + expect(reveal("Rename Launch plan")).toBe(true); +}); diff --git a/src/bundled/threads/ThreadsPage.tsx b/src/bundled/threads/ThreadsPage.tsx new file mode 100644 index 0000000000..cc7fd139b4 --- /dev/null +++ b/src/bundled/threads/ThreadsPage.tsx @@ -0,0 +1,465 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import type { Navigation } from "../../features/navigation/controller"; +import type { NavigationScope } from "../../features/navigation/targets"; +import { useChannelList, useRelayConnection } from "../../features/relay/react"; +import type { RelayData } from "../../features/relay/service"; +import type { RelaySession } from "../../features/relay/session"; +import { + ArrowsClockwiseIcon, + ChecksIcon, + MessageReplyIcon, + PencilSimpleIcon, + XIcon, +} from "../../shared/design-system/icons"; +import { CountBadge } from "../../shared/design-system/ui/CountBadge"; +import { TypingDots } from "../../shared/design-system/ui/TypingDots"; +import { EmptyState } from "../../shared/design-system/ui/EmptyState"; +import { FullPageSurface } from "../../shared/design-system/ui/FullPageSurface"; +import { IconButton } from "../../shared/design-system/ui/IconButton"; +import { Input } from "../../shared/design-system/ui/Input"; +import { LoadingRegion } from "../../shared/design-system/ui/LoadingRegion"; +import { + NavigationCard, + NavigationItem, +} from "../../shared/design-system/ui/NavigationItem"; +import { + PanelHeader, + PanelHeaderLabel, +} from "../../shared/design-system/ui/PanelHeader"; +import { Select } from "../../shared/design-system/ui/Select"; +import { relativeTimestamp } from "../../shared/relative-timestamp"; +import { + threadActivityStore, + useThreadActivity, +} from "../../features/messages/thread-activity-store"; +import { + threadTitleStore, + useThreadTitles, +} from "../../features/messages/thread-title-store"; +import { + activityKey, + normalizeTitle, + type Row, + writeTitle, +} from "../../features/messages/thread-titles"; +import styles from "./Threads.module.css"; +import { useThreadSignals, workingDuration } from "./thread-signals"; + +const ALL = ""; + +export function ThreadsPage({ + relay, + navigator, +}: { + relay: RelayData; + navigator: Navigation; +}) { + const connection = useRelayConnection(relay); + const { viewer, scope } = connection; + return ( +
+ + {connection.status === "ready" && + viewer && + scope?.endsWith(`:${viewer}`) ? ( + + ) : ( +
+
+

+ {connection.status === "connecting" + ? "Connecting…" + : "Choose a community to see its threads."} +

+
+ )} +
+
+ ); +} + +function Header({ onRefresh }: { onRefresh?: () => void }) { + return ( + } + /> + } + actions={ + onRefresh && ( +