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..6195980a43 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -533,6 +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. +- **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/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/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/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/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 new file mode 100644 index 0000000000..848caa4fab --- /dev/null +++ b/src/bundled/threads/README.md @@ -0,0 +1,13 @@ +# Named threads + +Find the threads that matter by their titles, across every channel you have joined. + +## Getting started + +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. 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 && ( +