diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 224e4f2f..178f5c3c 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -1245,6 +1245,53 @@ A **lesson** makes the answer a record and, for most of them, lands it. closes the record, not the file. A boundary lesson is undone the same way once the user has merged it. +## 21. The sidebar thread list + +An opt-in replacement for bb's own sidebar list, registered through the +exclusive `experimental_threadList` slot (`plugins/stewards/app.tsx`). One tab +per project in the live view; in-flight efforts grouped by the steward +relationship; a collapsed Watches row for `ops`, Dependabot and Sentry +bindings; a collapsed Recently ended row; and the project steward demoted to +one small row at the bottom. Every row carries bb's own thread actions +context menu, so archive, pin, rename, split and delete still work. + +**Grouping is the steward relationship, not the thread tree.** A worker +belongs to its binding through the plugin's `workers` table and a reviewer +through the worker the RPC names, so BB-23's removal of the parent link cannot +break it. The thread tree is used only for one-off threads, which have nothing +else, and as a fallback for a pre-BB-23 worker whose parent is its steward. +The pure grouping and ordering live in `sidebar.ts` and are unit tested; the +component joins them to `experimental_useSidebarThreads` and polls +`stewardsSidebar` on the board's half-minute visibility-aware cadence. + +**The default provider, checked (BB-44 criterion 1).** With +`sidebar.threadListProvider` unset it is `__automatic__`, which bb resolves to +"the first installed thread list plugin other than the bundled +`thread-list/thread-list`". Registering the slot therefore makes the stewards +list active on every client that has not pinned a provider, and +`bb settings ui get sidebar.threadListProvider` on the dev server reads +`__automatic__`. **The guard was needed:** without it the list would win by +default. On load the plugin (`server.ts`, `pinSidebarThreadListProvider`) +reads the preference and, when it is unset or `__automatic__`, sets it to +`thread-list/thread-list`; an explicit value is left alone, and a failure is +logged, never thrown. `bb.onInstall` is not usable here — it does not run for +plugins baked into the `bb-server` image — so the pin is on load. BB-44 and +BB-45 are one landing; BB-44 must not land alone. + +**The footer toggle (BB-45).** `app.tsx` registers a +`experimental_sidebarFooter` disclosure (`id: "sidebar"`, `icon: +"ShieldCheck"`): a switch that writes the same preference. On sets +`/sidebar`, the id BB-44 registers; off sets +`thread-list/thread-list`. It lists the preference when the disclosure opens +and, on an HTTP 409 revision conflict, re-lists and retries once with the +fresh revision. `__automatic__` (or a missing entry) reads as on, because it +means the stewards list is the effective provider until the pin makes the +choice explicit. The preference is server-synced, so a flip is per server: +every window of one bb server shows the same list. Each developer has their +own server behind bb-gate, so it is per developer in practice. + +The "Needs you" block and the tab badge are a separate ticket. + ## Known limits - **Multi-repo projects only.** A bb project whose source is a single diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 4a4daab1..6382ca9c 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -297,6 +297,45 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. put its own binding on hold for this, but only its parent or the project steward lifts a hold. +## The sidebar thread list and its toggle + +BB-44 registers a replacement for bb's own sidebar thread list through the +exclusive `experimental_threadList` slot: one tab per stewarded project, +in-flight efforts grouped by the steward relationship, and collapsed Watches +and Recently ended rows. BB-45 makes it switchable from where you are. + +**The footer toggle.** A `ShieldCheck` icon in the sidebar footer (next to +Settings) opens a small panel above the footer row with a **Stewards +sidebar** switch and one line of help. On writes `sidebar.threadListProvider` += `stewards/sidebar` (the list BB-44 registers); off writes it back to bb's +own `thread-list/thread-list`. The sidebar's list swaps without a reload. The +footer is host-rendered and stays in place under either list, so the icon is +reachable in both states. Hide it like any footer item through bb's footer +preferences (Settings → Appearance → Sidebar → footer items, or +`sidebar.hiddenFooterItems`). + +**The Appearance page alternative.** The same choice is Settings → Appearance +→ Sidebar → the thread-list provider; the toggle is a shortcut to it, not a +second setting. Both write the one UI preference. + +**The default-provider pin.** bb resolves an unset (`__automatic__`) +provider to the first installed thread list other than the bundled +`thread-list/thread-list` — the stewards list — so without a guard BB-44 +would change everyone's sidebar the moment it landed. On load the plugin +reads the preference and, when it is unset or `__automatic__`, sets it to +`thread-list/thread-list`. An explicit value, including `stewards/sidebar`, +is left alone. The write is best-effort: a failure is logged and the sidebar +keeps working. (`bb.onInstall` is not usable here; it does not run for +plugins baked into the `bb-server` image.) + +**Per client or per server?** Checked on a dev server: the preference is +**server-synced**, so a flip is per server, not per browser. Every open +window of that bb server shows the same list, and the choice survives a +reload. `bb settings ui get sidebar.threadListProvider` — a different client — +sees the value the toggle wrote, and bb tells the other clients the preference +changed. Each developer has their own server behind bb-gate, so in practice +the choice is per developer. + ## Configuration In the project's `.bb` (the multi-repo project repo), read from committed diff --git a/plugins/stewards/app.test.tsx b/plugins/stewards/app.test.tsx index 032aaa93..998f2421 100644 --- a/plugins/stewards/app.test.tsx +++ b/plugins/stewards/app.test.tsx @@ -2,7 +2,7 @@ // BB-20: the Stewards page renders a decide item or question with fixed // choices as one button per choice plus Other…, and a text-only one with // Answer rather than Done. -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { fireEvent, waitFor } from "@testing-library/react"; import { loadPluginApp, renderSlot, type CapturedPluginApp, type RenderedSlot } from "@get-bb/plugin-sdk/testing/app"; @@ -179,3 +179,105 @@ describe("the Stewards page's need links (BB-29)", () => { slot.lifecycle.unmount(); }); }); + +// BB-45: the sidebar-footer disclosure writes the `sidebar.threadListProvider` +// UI preference, so the stewards list BB-44 registers can be turned on and off +// from the footer instead of Settings → Appearance. +describe("the sidebar-footer toggle (BB-45)", () => { + type UiPrefEntry = { value: string; revision: number }; + type SetArgs = { key: string; value: string; expectedRevision: number }; + + /** A `uiPreferences.list()` answer with just the one preference the toggle reads. */ + const listed = (entry: UiPrefEntry | null) => ({ preferences: entry === null ? {} : { "sidebar.threadListProvider": entry } }) as never; + + const renderToggle = async (options: { entry: UiPrefEntry | null; set: (args: SetArgs) => Promise }) => { + const captured = await loadApp(); + const item = captured.experimentalSidebarFooterItems[0]!; + if (item.kind !== "disclosure") throw new Error("the sidebar footer item is not a disclosure"); + const list = vi.fn(async () => listed(options.entry)); + const set = vi.fn(options.set); + const slot = renderSlot({ component: item.component }, { dismiss: () => {} }, { pluginId: "stewards", sdk: { system: { uiPreferences: { list, set } } } as never }); + return { slot, set }; + }; + + const echo = async (args: SetArgs) => ({ key: args.key, value: args.value, revision: args.expectedRevision + 1 }); + + it("registers one footer disclosure under the Stewards sidebar label", async () => { + const captured = await loadApp(); + expect(captured.experimentalSidebarFooterItems).toHaveLength(1); + expect(captured.experimentalSidebarFooterItems[0]).toMatchObject({ kind: "disclosure", id: "sidebar", label: "Stewards sidebar", icon: "ShieldCheck" }); + }); + + it("shows the switch off for bb's list and on for the stewards list", async () => { + const off = await renderToggle({ entry: { value: "thread-list/thread-list", revision: 7 }, set: echo }); + const offSwitch = await waitFor(() => off.slot.getByRole("switch", { name: "Stewards sidebar" })); + expect(offSwitch.getAttribute("aria-checked")).toBe("false"); + off.slot.lifecycle.unmount(); + + const on = await renderToggle({ entry: { value: "stewards/sidebar", revision: 7 }, set: echo }); + const onSwitch = await waitFor(() => on.slot.getByRole("switch", { name: "Stewards sidebar" })); + expect(onSwitch.getAttribute("aria-checked")).toBe("true"); + on.slot.lifecycle.unmount(); + }); + + it("reads an unpinned provider as on, the effective stewards list", async () => { + for (const entry of [null, { value: "__automatic__", revision: 0 }]) { + const { slot } = await renderToggle({ entry, set: echo }); + const toggle = await waitFor(() => slot.getByRole("switch", { name: "Stewards sidebar" })); + expect(toggle.getAttribute("aria-checked")).toBe("true"); + slot.lifecycle.unmount(); + } + }); + + it("turns the stewards list on with the stewards list id and the listed revision", async () => { + const { slot, set } = await renderToggle({ entry: { value: "thread-list/thread-list", revision: 7 }, set: echo }); + fireEvent.click(await waitFor(() => slot.getByRole("switch", { name: "Stewards sidebar" }))); + await waitFor(() => expect(set).toHaveBeenCalledTimes(1)); + expect(set.mock.calls[0]![0]).toEqual({ key: "sidebar.threadListProvider", value: "stewards/sidebar", expectedRevision: 7 }); + await waitFor(() => expect(slot.getByRole("switch", { name: "Stewards sidebar" }).getAttribute("aria-checked")).toBe("true")); + slot.lifecycle.unmount(); + }); + + it("turns the stewards list off by setting bb's own list", async () => { + const { slot, set } = await renderToggle({ entry: { value: "stewards/sidebar", revision: 3 }, set: echo }); + fireEvent.click(await waitFor(() => slot.getByRole("switch", { name: "Stewards sidebar" }))); + await waitFor(() => expect(set).toHaveBeenCalledTimes(1)); + expect(set.mock.calls[0]![0]).toEqual({ key: "sidebar.threadListProvider", value: "thread-list/thread-list", expectedRevision: 3 }); + await waitFor(() => expect(slot.getByRole("switch", { name: "Stewards sidebar" }).getAttribute("aria-checked")).toBe("false")); + slot.lifecycle.unmount(); + }); + + it("re-lists and retries once when the set hits a revision conflict", async () => { + let sets = 0; + let lists = 0; + const captured = await loadApp(); + const item = captured.experimentalSidebarFooterItems[0]!; + if (item.kind !== "disclosure") throw new Error("the sidebar footer item is not a disclosure"); + const slot = renderSlot({ component: item.component }, { dismiss: () => {} }, { + pluginId: "stewards", + sdk: { + system: { + uiPreferences: { + list: async () => { + lists += 1; + return listed({ value: "thread-list/thread-list", revision: lists === 1 ? 7 : 9 }); + }, + set: async (args: SetArgs) => { + sets += 1; + if (sets === 1) throw Object.assign(new Error("revision conflict"), { status: 409 }); + return { key: args.key, value: args.value, revision: args.expectedRevision + 1 }; + }, + }, + }, + } as never, + }); + fireEvent.click(await waitFor(() => slot.getByRole("switch", { name: "Stewards sidebar" }))); + await waitFor(() => expect(sets).toBe(2)); + expect(slot.inspection.sdkCalls.filter((c) => c.method === "system.uiPreferences.set")).toEqual([ + { method: "system.uiPreferences.set", args: [{ key: "sidebar.threadListProvider", value: "stewards/sidebar", expectedRevision: 7 }] }, + { method: "system.uiPreferences.set", args: [{ key: "sidebar.threadListProvider", value: "stewards/sidebar", expectedRevision: 9 }] }, + ]); + expect(lists).toBe(2); + slot.lifecycle.unmount(); + }); +}); diff --git a/plugins/stewards/app.tsx b/plugins/stewards/app.tsx index 1d57de7d..35087820 100644 --- a/plugins/stewards/app.tsx +++ b/plugins/stewards/app.tsx @@ -5,9 +5,28 @@ // stewarded and whether their configuration is healthy, then every open // steward and where it stands. Steering stays with the project steward and // the CLI. -import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; -import { Markdown, definePluginApp, experimental_Icon as Icon, useBbNavigate, useRpc } from "@get-bb/plugin-sdk/app"; +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { + Markdown, + ThreadTitle, + definePluginApp, + experimental_Icon as Icon, + experimental_ThreadActionsContextMenu as ThreadActionsContextMenu, + experimental_ThreadStatusGlyph as ThreadStatusGlyph, + experimental_usePluginId, + experimental_useSidebarThreads, + useBbNavigate, + useRpc, + useSdk, + useSidebarThreadDraft, + useSidebarThreadRowStatus, + type PluginSidebarThread, + type PluginThreadActionTarget, + type PluginThreadListProps, +} from "@get-bb/plugin-sdk/app"; import type { rpcContract } from "./server"; +import { buildSidebar, isBusy, type SidebarChild, type SidebarChildRole, type SidebarEffort } from "./sidebar.js"; +import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY, stewardsThreadListId } from "./sidebar-provider.js"; type Client = ReturnType>; type Overview = Awaited> extends infer R ? Extract : never; @@ -772,6 +791,381 @@ function InFlightRow({ steward: s, now }: { steward: Board["stewards"][number]; ); } +// ---- The sidebar thread list ------------------------------------------------------------------- +// +// The opt-in replacement for bb's sidebar list, registered through the +// exclusive `experimental_threadList` slot. One tab per project, in-flight +// efforts grouped by the steward relationship, collapsed Watches and Recently +// ended rows, and a demoted project-steward row. Every row carries bb's own +// thread actions context menu, so nothing bb's rows can do is lost. + +/** Past this many projects the tabs become a picker, as on a compact viewport. */ +const SIDEBAR_TAB_LIMIT = 5; + +/** The live fields bb's thread actions read, from a sidebar row. */ +function actionTarget(t: PluginSidebarThread): PluginThreadActionTarget { + return { + id: t.id, + projectId: t.projectId, + parentThreadId: t.parentThreadId, + archivedAt: t.archivedAt, + pinnedAt: t.pinnedAt, + sectionId: t.sectionId, + isUnread: t.isUnread, + status: t.status, + environment: t.environment === null || t.environment.id === null ? null : { id: t.environment.id, path: t.environment.path }, + }; +} + +function countThreads(children: readonly SidebarChild[]): number { + return children.reduce((n, c) => n + 1 + countThreads(c.children), 0); +} + +/** One thread row: bb's glyph, title and context menu, expanding into its children. */ +function SidebarThreadRow({ + thread, + role, + children, + depth, + byId, + onNavigate, + meta, +}: { + thread: PluginSidebarThread; + role: SidebarChildRole; + children: readonly SidebarChild[]; + depth: number; + byId: ReadonlyMap; + onNavigate: () => void; + meta?: ReactNode; +}) { + const navigate = useBbNavigate(); + const rowStatus = useSidebarThreadRowStatus(thread.id); + const draft = useSidebarThreadDraft(thread.id); + const [open, setOpen] = useState(false); + // The array-wide indicator never reports a draft; the row folds in the + // client-local one, as bb's own row does. + const indicator = draft.hasUnsubmittedDraft && thread.indicator === "none" ? (isBusy(thread.status) ? "working-draft" : "draft") : thread.indicator; + const count = countThreads(children); + return ( +
  • + +
    + {count > 0 ? ( + + ) : ( + + )} + + { + e.preventDefault(); + navigate.toThread(thread.id); + onNavigate(); + }} + > + + + {role === "worker" || role === "reviewer" ? {role} : null} + {meta} +
    +
    + {open && children.length > 0 ? ( +
      + {children.map((c) => { + const child = byId.get(c.threadId); + return child === undefined ? null : ( + + ); + })} +
    + ) : null} +
  • + ); +} + +/** One effort's root row, with the binding's key, stage and held/blocked badges. */ +function SidebarEffortRow({ effort, byId, onNavigate }: { effort: SidebarEffort; byId: ReadonlyMap; onNavigate: () => void }) { + const root = byId.get(effort.rootThreadId); + if (root === undefined) return null; + const meta = + effort.bindingKey === null ? null : ( + + {effort.bindingKey} + {effort.stage !== null ? {effort.stage} : null} + {effort.hold !== null ? held : null} + {effort.blockedOn !== null ? blocked : null} + + ); + return ; +} + +function SidebarSection({ title, count, children }: { title: string; count: number; children: ReactNode }) { + return ( +
    +

    + {title} {count} +

    + {children} +
    + ); +} + +function SidebarCollapsible({ title, count, children }: { title: string; count: number; children: ReactNode }) { + const [open, setOpen] = useState(false); + return ( +
    + + {open ? children : null} +
    + ); +} + +function ProjectTabs({ tabs, activeId, compact, onPick }: { tabs: Array<{ projectId: string; name: string }>; activeId: string | null; compact: boolean; onPick: (projectId: string) => void }) { + if (compact || tabs.length > SIDEBAR_TAB_LIMIT) { + return ( +
    + +
    + ); + } + return ( +
    + {tabs.map((t) => ( + + ))} +
    + ); +} + +function StewardsSidebar({ activeProjectId, isCompactViewport, onNavigate }: PluginThreadListProps) { + const rpc = useRpc(); + const { status, threads, projects } = experimental_useSidebarThreads(); + const { data, error } = usePolled(useCallback(() => rpc.call("stewardsSidebar", null), [rpc])); + const tabs = useMemo(() => buildSidebar({ projects, threads, data: data?.projects ?? [] }), [projects, threads, data]); + const byId = useMemo(() => new Map(threads.map((t) => [t.id, t] as const)), [threads]); + const [picked, setPicked] = useState(null); + // The active tab follows the route; a pick only lasts until the route moves. + useEffect(() => setPicked(null), [activeProjectId]); + const wanted = picked ?? activeProjectId; + const active = tabs.find((t) => t.projectId === wanted) ?? tabs[0] ?? null; + const now = Date.now(); + return ( +
    + + {status === "loading" && data === null ? ( +

    Loading…

    + ) : active === null ? ( +

    No projects yet.

    + ) : ( +
    + + {active.efforts.length === 0 ? ( +

    Nothing in flight.

    + ) : ( +
      + {active.efforts.map((e) => ( + + ))} +
    + )} +
    + {active.watches.length > 0 ? ( + +
      + {active.watches.map((e) => ( + + ))} +
    +
    + ) : null} + {active.ended.length > 0 ? ( + +
      + {active.ended.map((e) => { + const t = e.threadId === null ? undefined : byId.get(e.threadId); + return t === undefined ? ( +
    • + {e.key} + {e.title ?? ""} + {ago(e.endedAt, now)} +
    • + ) : ( + {ago(e.endedAt, now)}} + /> + ); + })} +
    +
    + ) : null} + {active.projectStewardThreadId !== null && byId.has(active.projectStewardThreadId) ? ( +
    + project steward} + /> +
    + ) : null} +
    + )} + {error !== null ?

    Refresh failed: {error}

    : null} +
    + ); +} + +// ---- The sidebar-footer toggle ----------------------------------------------------------------- +// +// BB-45: an icon in the sidebar footer that opens a small panel above the +// footer row with a switch for the stewards list BB-44 registers. The footer +// is host-rendered and stays in place under either list, so the toggle is +// reachable in both states. The preference it writes is the one Settings → +// Appearance → Sidebar sets; the value is the plugin id plus the `sidebar` +// slot id BB-44 registers. + +/** bb answers a stale `expectedRevision` with HTTP 409. */ +function isRevisionConflict(error: unknown): boolean { + const status = typeof error === "object" && error !== null && "status" in error ? (error as { status?: unknown }).status : null; + return status === 409 || /\bHTTP\s*409\b/u.test(String(error)); +} + +type ThreadListProviderState = { status: "loading" } | { status: "ready"; on: boolean; revision: number } | { status: "error"; message: string }; + +/** + * The disclosure's body: a switch that writes `sidebar.threadListProvider`. + * The preference is read when the disclosure opens (the component mounts) and + * again after a conflict. `__automatic__` (the value while nothing is pinned) + * means bb picks the stewards list, so it reads as on until the load-time pin + * has made the choice explicit. + */ +function SidebarToggle() { + const sdk = useSdk(); + const pluginId = experimental_usePluginId(); + const onId = stewardsThreadListId(pluginId); + const [state, setState] = useState({ status: "loading" }); + const [busy, setBusy] = useState(false); + + const read = useCallback(async (): Promise<{ on: boolean; revision: number }> => { + const { preferences } = await sdk.system.uiPreferences.list(); + const entry = preferences[THREAD_LIST_PROVIDER_KEY]; + const value = entry?.value; + return { on: value === onId || value === undefined || value === AUTOMATIC_THREAD_LIST_PROVIDER, revision: entry?.revision ?? 0 }; + }, [sdk, onId]); + + useEffect(() => { + let live = true; + read().then( + (next) => { + if (live) setState({ status: "ready", ...next }); + }, + (error: unknown) => { + if (live) setState({ status: "error", message: message(error) }); + }, + ); + return () => { + live = false; + }; + }, [read]); + + const flip = useCallback(async () => { + if (state.status !== "ready" || busy) return; + const next = !state.on; + const value = next ? onId : BUILTIN_THREAD_LIST_ID; + setBusy(true); + try { + let revision: number; + try { + revision = (await sdk.system.uiPreferences.set({ key: THREAD_LIST_PROVIDER_KEY, value, expectedRevision: state.revision })).revision; + } catch (error) { + // Another window changed the preference between our list and our set: + // re-list and retry once with the fresh revision. Anything else is a + // real failure. + if (!isRevisionConflict(error)) throw error; + const fresh = await read(); + revision = (await sdk.system.uiPreferences.set({ key: THREAD_LIST_PROVIDER_KEY, value, expectedRevision: fresh.revision })).revision; + } + setState({ status: "ready", on: next, revision }); + } catch (error) { + setState({ status: "error", message: message(error) }); + } finally { + setBusy(false); + } + }, [state, busy, onId, read, sdk]); + + const on = state.status === "ready" && state.on; + return ( +
    +
    + Stewards sidebar + +
    +

    Show the stewards list of threads grouped by project and effort. Off shows bb's own list.

    + {state.status === "error" ?

    Could not change the sidebar: {state.message}

    : null} +
    + ); +} + export default definePluginApp((app) => { app.slots.navPanel({ id: "board", @@ -780,6 +1174,23 @@ export default definePluginApp((app) => { path: BOARD_PATH, component: BoardPage, }); + // The exclusive sidebar slot: while this plugin is enabled and no provider is + // pinned, this list replaces bb's own (see DESIGN.md, "The sidebar thread list"). + app.slots.experimental_threadList({ + id: "sidebar", + title: "Stewards", + description: "Threads grouped by project and in-flight effort, with stages, workers and reviewers.", + component: StewardsSidebar, + }); + // The footer disclosure that writes the provider preference, so the list + // above can be turned on and off without Settings → Appearance. + app.experimental_sidebarFooter.register({ + kind: "disclosure", + id: "sidebar", + label: "Stewards sidebar", + icon: "ShieldCheck", + component: SidebarToggle, + }); app.slots.settingsSection({ id: "status", title: "Status", diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 0ad45f72..70c88cc5 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -37,6 +37,10 @@ function world() { /** Each thread's latest context window reading, as bb reports it. */ const usage = new Map(); const metadata = new Map>(); + /** The fake server's UI preferences, keyed by preference key. */ + const uiPreferences = new Map([["sidebar.threadListProvider", { value: "__automatic__", revision: 0 }]]); + /** Every `system.uiPreferences.set` the plugin made, for the load-time pin's tests. */ + const uiPreferencesWrites: Array<{ key: string; value: unknown; expectedRevision: number }> = []; const spawns: Array & { id: string }> = []; const sends: Array<{ threadId: string; text: string }> = []; const userTurns: Array<{ threadId: string; text: string }> = []; @@ -224,13 +228,34 @@ function world() { : userTurns.filter((t) => t.threadId === threadId).map((t, i) => ({ id: `e${i}`, seq: i, threadId, createdAt: now, scope: "thread", type: "client/turn/start", data: { initiator: "user", request: { method: "turn/start", params: { input: [{ type: "text", text: t.text }] } } } })), }, }, + system: { + uiPreferences: { + list: async () => ({ preferences: Object.fromEntries([...uiPreferences].map(([key, entry]) => [key, { ...entry }])) }), + set: async (args: { key: string; value: unknown; expectedRevision: number }) => { + const current = uiPreferences.get(args.key); + if (current !== undefined && current.revision !== args.expectedRevision) throw Object.assign(new Error(`revision conflict for ${args.key}`), { status: 409 }); + const next = { value: args.value, revision: (current?.revision ?? 0) + 1 }; + uiPreferences.set(args.key, next); + uiPreferencesWrites.push({ ...args }); + return { key: args.key, ...next }; + }, + }, + }, }; let now = Date.parse("2026-10-14T15:00:00Z"); - return { files, writes, fileContents, repos, entities, dependabotAlerts, rpcCalls, mergeGuidanceCalls, setMergeGuidanceResult: (value: typeof mergeGuidanceResult) => { mergeGuidanceResult = value; }, threads, sections, usage, metadata, spawns, sends, userTurns, githubComments, githubMerges, githubFiles, github, sdk, now: () => now, advance: (ms: number) => (now += ms) }; + return { files, writes, fileContents, repos, entities, dependabotAlerts, rpcCalls, mergeGuidanceCalls, setMergeGuidanceResult: (value: typeof mergeGuidanceResult) => { mergeGuidanceResult = value; }, threads, sections, usage, metadata, spawns, sends, userTurns, githubComments, githubMerges, githubFiles, github, sdk, uiPreferences, uiPreferencesWrites, now: () => now, advance: (ms: number) => (now += ms) }; } -async function setup(extra: Partial = {}, settings: Record = {}) { +async function setup(extra: Partial = {}, settings: Record = {}, seedProvider?: string | null | "fail-list" | "fail-set") { const w = world(); + if (seedProvider === null) w.uiPreferences.delete("sidebar.threadListProvider"); + else if (seedProvider === "fail-list") w.sdk.system.uiPreferences.list = async () => { + throw new Error("the preferences store is down"); + }; + else if (seedProvider === "fail-set") w.sdk.system.uiPreferences.set = async () => { + throw new Error("the preferences store is down"); + }; + else if (seedProvider !== undefined) w.uiPreferences.set("sidebar.threadListProvider", { value: seedProvider, revision: 4 }); const { bb, harness } = createFakePluginHost({ pluginId: "stewards", sdk: w.sdk as never, agentSkillIds: ["stewards"], settings }); await createStewardsPlugin({ now: w.now, timing: { debounceMs: 1, nightlyStaggerMs: 0 }, github: w.github, ...extra })(bb); const hooks = testHooks.get("stewards")!; @@ -2460,6 +2485,65 @@ describe("questions to the user", () => { }); }); +describe("the stewards sidebar call", () => { + type Sidebar = { + projects: Array<{ + projectId: string; + name: string; + projectStewardThreadId: string | null; + bindings: Array<{ + key: string; + kind: string; + stage: string | null; + threadId: string | null; + hold: string | null; + blockedOn: string | null; + needsUser: boolean; + advancedAt: number | null; + workers: Array<{ threadId: string; title: string }>; + reviewers: Array<{ threadId: string; workerThreadId: string }>; + }>; + ended: Array<{ key: string; kind: string; threadId: string | null; title: string | null; endedAt: number }>; + }>; + }; + + it("returns every stewarded project's bindings, workers and reviewers, the project steward and what ended", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; + await t.created("thr_w1", steward, "Implement retry"); + await t.created("thr_r1", "thr_w1", "Review the pull request"); + + const result = (await t.harness.callRpc("stewardsSidebar", null)) as Sidebar; + expect(result.projects).toMatchObject([{ projectId: "p1", name: "Acme", projectStewardThreadId: project }]); + expect(result.projects[0]!.bindings).toMatchObject([ + { + key: "ENG-12", + kind: "ticket", + threadId: steward, + needsUser: false, + workers: [{ threadId: "thr_w1", title: "Implement retry" }], + reviewers: [{ threadId: "thr_r1", workerThreadId: "thr_w1" }], + }, + ]); + expect(result.projects[0]!.ended).toEqual([]); + }); + + it("lists an ended binding in `ended` and drops it from the bindings", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const binding = t.hooks.store.find("ENG-12")!; + t.hooks.store.patch(binding.id, { endedAt: t.now(), endReason: "merged" }); + + const result = (await t.harness.callRpc("stewardsSidebar", null)) as Sidebar; + expect(result.projects[0]!.bindings).toEqual([]); + expect(result.projects[0]!.ended).toMatchObject([{ key: "ENG-12", kind: "ticket" }]); + expect(result.projects[0]!.ended[0]!.endedAt).toBe(t.now()); + }); +}); + describe("needs you items", () => { const client = { experimental_caller: { kind: "client" } } as const; const met = { checklist: [1, 2, 3, 4].map((item) => ({ item, met: true })), substantial: true }; @@ -4754,3 +4838,34 @@ describe("steward-spawned threads and the sidebar (BB-39)", () => { expect(instructions()).not.toContain("--section"); }); }); + +// BB-45: BB-44's dev-server check found that an unset `sidebar.threadListProvider` +// resolves to the stewards list, so the plugin pins bb's own list on load and +// leaves any explicit choice alone. +describe("the load-time sidebar thread-list pin (BB-45)", () => { + it("pins bb's own list when the preference is unset or automatic", async () => { + const unset = await setup({}, {}, null); + expect(unset.uiPreferences.get("sidebar.threadListProvider")).toMatchObject({ value: "thread-list/thread-list" }); + expect(unset.uiPreferencesWrites).toEqual([{ key: "sidebar.threadListProvider", value: "thread-list/thread-list", expectedRevision: 0 }]); + + const automatic = await setup({}, {}, "__automatic__"); + expect(automatic.uiPreferences.get("sidebar.threadListProvider")).toMatchObject({ value: "thread-list/thread-list" }); + expect(automatic.uiPreferencesWrites).toEqual([{ key: "sidebar.threadListProvider", value: "thread-list/thread-list", expectedRevision: 4 }]); + }); + + it("leaves an explicit provider alone, including the stewards list", async () => { + for (const value of ["thread-list/thread-list", "stewards/sidebar"]) { + const t = await setup({}, {}, value); + expect(t.uiPreferences.get("sidebar.threadListProvider")).toEqual({ value, revision: 4 }); + expect(t.uiPreferencesWrites).toEqual([]); + } + }); + + it("logs and carries on when the preference cannot be read or written", async () => { + for (const seed of ["fail-list", "fail-set"] as const) { + const t = await setup({}, {}, seed); + expect(t.uiPreferences.get("sidebar.threadListProvider")).toEqual({ value: "__automatic__", revision: 0 }); + expect(t.harness.logEntries.some((entry) => entry.level === "warn" && entry.message.includes("could not pin the sidebar thread list"))).toBe(true); + } + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index fbcd1407..3c75726c 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -71,6 +71,7 @@ import { import { ACTORS, MIGRATIONS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store } from "./store.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { allPullsMerged, conflictsOf, normalizeTouches } from "./schedule.js"; +import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY } from "./sidebar-provider.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; import { PROJECT_STEWARD_INTRO, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerQuestion, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; @@ -146,6 +147,35 @@ export interface StewardsDeps { } const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error)); + +/** + * BB-45: pin bb's own sidebar thread list for clients that have not opted in. + * + * BB-44 registers the stewards list through the exclusive + * `experimental_threadList` slot, and bb resolves an unset (`__automatic__`) + * provider to the first installed list other than the bundled + * `thread-list/thread-list` — the stewards list. Without this pin the sidebar + * would change for everyone the moment BB-44 lands. Set the preference to the + * bundled list on load; an explicit value (including the stewards list the + * footer toggle writes) is left alone. `bb.onInstall` does not run for plugins + * baked into the `bb-server` image, so this runs on load. Best-effort: a + * failure is logged and the sidebar keeps working. + */ +export async function pinSidebarThreadListProvider(bb: BbPluginApi): Promise { + try { + const { preferences } = await bb.sdk.system.uiPreferences.list(); + const entry = preferences[THREAD_LIST_PROVIDER_KEY]; + if (entry !== undefined && entry.value !== AUTOMATIC_THREAD_LIST_PROVIDER) return; + await bb.sdk.system.uiPreferences.set({ + key: THREAD_LIST_PROVIDER_KEY, + value: BUILTIN_THREAD_LIST_ID, + expectedRevision: entry?.revision ?? 0, + }); + bb.log.info(`stewards: pinned the sidebar thread list to ${BUILTIN_THREAD_LIST_ID}; the footer toggle switches it to ${STEWARDS_PLUGIN_ID}/sidebar`); + } catch (error) { + bb.log.warn(`stewards: could not pin the sidebar thread list: ${errorMessage(error)}`); + } +} const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max)}… (${text.length - max} more characters)`); const iso = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/u, "Z"); const lc = (s: string | null | undefined) => (s ?? "").toLowerCase(); @@ -341,6 +371,37 @@ export const rpcContract = defineRpcContract({ .nullable(), }), }, + // The sidebar thread list's one call: every stewarded project's bindings, + // their workers and known reviewers, the project steward, and what ended. + // One call for all projects, so a replaced sidebar does not refetch per tab. + stewardsSidebar: { + input: z.null(), + output: z.object({ + projects: z.array( + z.object({ + projectId: z.string(), + name: z.string(), + projectStewardThreadId: z.string().nullable(), + bindings: z.array( + z.object({ + key: z.string(), + kind: z.string(), + stage: z.string().nullable(), + threadId: z.string().nullable(), + hold: z.string().nullable(), + blockedOn: z.string().nullable(), + needsUser: z.boolean(), + advancedAt: z.number().nullable(), + workers: z.array(z.object({ threadId: z.string(), title: z.string() })), + /** Reviewer threads, each under the worker it reviews. */ + reviewers: z.array(z.object({ threadId: z.string(), workerThreadId: z.string() })), + }), + ), + ended: z.array(z.object({ key: z.string(), kind: z.string(), threadId: z.string().nullable(), title: z.string().nullable(), endedAt: z.number() })), + }), + ), + }), + }, // The user closes a question from the page, with or without an answer, or // picks one of its fixed choices. stewardsAnswerQuestion: { @@ -3529,6 +3590,57 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }, }; }, + // The sidebar's one call: every stewarded project's bindings, their + // workers, and the reviewers known under them. One `threads.list` per + // worker finds the reviewers; everything else is the store's own records. + async stewardsSidebar() { + const named = new Map((await bb.sdk.projects.list()).map((p) => [p.id, p.name] as const)); + const projects = projectIds((await stewardedProjects()).map((c) => c.projectId)) + .map((projectId) => ({ projectId, name: named.get(projectId) ?? projectId })) + .sort((a, b) => a.name.localeCompare(b.name)); + const workerIds = [ + ...new Set(projects.flatMap((p) => store.all(p.projectId).filter((b) => b.endedAt === null).flatMap((b) => store.workers(b.id).map((w) => w.threadId)))), + ]; + const reviewersByWorker = new Map(); + await Promise.all( + workerIds.map(async (workerId) => { + const children = await bb.sdk.threads.list({ parentThreadId: workerId, includeHidden: true }).catch(() => []); + reviewersByWorker.set(workerId, children.map((c) => c.id)); + }), + ); + return { + projects: projects.map(({ projectId, name }) => { + const all = store.all(projectId); + const ended = all + .filter((b) => b.endedAt !== null && b.endedAt >= now() - ENDED_ON_BOARD_MS) + .sort((a, b) => b.endedAt! - a.endedAt!) + .slice(0, 30); + return { + projectId, + name, + projectStewardThreadId: store.project(projectId).threadId, + bindings: all + .filter((b) => b.endedAt === null) + .map((b) => { + const workers = store.workers(b.id).map((w) => ({ threadId: w.threadId, title: w.title })); + return { + key: b.entityKey, + kind: b.kind, + stage: b.stage, + threadId: b.threadId, + hold: b.hold, + blockedOn: b.status?.blockedOn ?? null, + needsUser: needsUser(b), + advancedAt: b.advancedAt, + workers, + reviewers: workers.flatMap((w) => (reviewersByWorker.get(w.threadId) ?? []).map((threadId) => ({ threadId, workerThreadId: w.threadId }))), + }; + }), + ended: ended.map((b) => ({ key: b.entityKey, kind: b.kind, threadId: b.threadId, title: b.title, endedAt: b.endedAt! })), + }; + }), + }; + }, async stewardsAnswerQuestion({ questionId, answer, choice }, { experimental_caller: caller }) { if (caller.kind !== "client") throw new Error("questions are closed by the user, from the stewards page"); const q = store.question(questionId); @@ -5449,6 +5561,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P tagged.clear(); kept.clear(); }; + await pinSidebarThreadListProvider(bb); testHooks.set(bb.pluginId, { sweep, store, db, settings, forgetTags, nightlyPass: (projectId: string, night: string) => loadConfig(projectId, true).then((c) => (c === null ? undefined : nightlyPass(c, night, true))), settle: () => Promise.all([...chains.values()]).then(() => undefined), sentryDoorbell: onSentryDoorbell, sentryLeases }); }; } diff --git a/plugins/stewards/sidebar-app.test.tsx b/plugins/stewards/sidebar-app.test.tsx new file mode 100644 index 00000000..64792a58 --- /dev/null +++ b/plugins/stewards/sidebar-app.test.tsx @@ -0,0 +1,216 @@ +// @vitest-environment jsdom +// BB-44: the stewards sidebar thread list renders one tab per project, efforts +// grouped by the steward relationship, collapsed Watches and Recently ended +// rows, and bb's thread actions context menu on every row. +import { afterEach, describe, expect, it, vi } from "vitest"; +import { fireEvent, waitFor } from "@testing-library/react"; +import { loadPluginApp, renderSlot, type CapturedPluginApp, type RenderedSlot } from "@get-bb/plugin-sdk/testing/app"; +import type { PluginSidebarThread } from "@get-bb/plugin-sdk/app"; + +const thread = (over: Partial & { id: string }): PluginSidebarThread => ({ + projectId: "p1", + title: over.id, + titleFallback: null, + displayTitle: over.id, + parentThreadId: null, + lifecycleOwnerThreadId: null, + sourceThreadId: null, + sectionId: null, + originKind: null, + originPluginId: null, + providerId: "pi", + status: "idle", + runtimeStatus: "idle", + queuedWork: "none", + hasPendingInteraction: false, + activity: { workflows: 0, backgroundAgents: 0, backgroundCommands: 0, planMode: 0, goals: 0 }, + indicator: "none", + indicatorLabel: null, + isUnread: false, + isPinned: false, + pinnedAt: null, + pinSortKey: null, + isArchived: false, + archivedAt: null, + href: `/projects/p1/threads/${over.id}`, + isHidden: false, + environment: null, + host: null, + createdAt: 0, + updatedAt: 0, + lastReadAt: null, + latestAttentionAt: 0, + ...over, +}); + +const projects = [ + { id: "p1", name: "Acme", isPersonal: false, href: "/projects/p1", settingsHref: "/projects/p1/settings" }, + { id: "personal", name: "Personal", isPersonal: true, href: "/projects/personal", settingsHref: "/projects/personal/settings" }, +]; + +const sidebarData = (over: { bindings?: unknown[]; ended?: unknown[]; projectStewardThreadId?: string | null } = {}) => ({ + projects: [ + { + projectId: "p1", + name: "Acme", + projectStewardThreadId: over.projectStewardThreadId ?? null, + bindings: over.bindings ?? [], + ended: over.ended ?? [], + }, + ], +}); + +const binding = (over: Record = {}) => ({ + key: "ENG-1", + kind: "ticket", + stage: "build", + threadId: "thr_steward", + hold: null, + blockedOn: null, + needsUser: false, + advancedAt: null, + workers: [], + reviewers: [], + ...over, +}); + +let app: CapturedPluginApp | null = null; +const loadApp = async () => { + app ??= await loadPluginApp(() => import("./app.js")); + return app; +}; + +const renderSidebar = async (options: Parameters[2] = {}, props: Record = {}): Promise => { + const captured = await loadApp(); + const list = captured.threadLists[0]!; + return renderSlot(list, { activeThreadId: null, activeProjectId: "p1", isCompactViewport: false, onNavigate: () => {}, searchQuery: "", ...props }, options); +}; + +afterEach(() => { + app = null; +}); + +describe("the stewards sidebar list (BB-44)", () => { + it("registers exactly one sidebar thread list under the Stewards title", async () => { + const captured = await loadApp(); + expect(captured.threadLists).toHaveLength(1); + expect(captured.threadLists[0]).toMatchObject({ id: "sidebar", title: "Stewards" }); + }); + + it("shows a tab per live project and the active project's effort with its key, stage and badges", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Fix login" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ hold: "billing freeze" })] }) } as never, + }); + await waitFor(() => expect(slot.getByRole("tab", { name: "Acme" })).toBeTruthy()); + expect(slot.getByRole("tab", { name: "Personal" })).toBeTruthy(); + await waitFor(() => expect(slot.getByText("ENG-1")).toBeTruthy()); + expect(slot.getByText("build")).toBeTruthy(); + expect(slot.getByText("held")).toBeTruthy(); + slot.lifecycle.unmount(); + }); + + it("shows workers and reviewers only when the effort is expanded", async () => { + const slot = await renderSidebar({ + sidebarThreads: { + projects, + threads: [thread({ id: "thr_steward", displayTitle: "Fix login" }), thread({ id: "thr_worker", displayTitle: "Implement retry" }), thread({ id: "thr_reviewer", displayTitle: "Review the PR", parentThreadId: "thr_worker" })], + }, + rpc: { + stewardsSidebar: () => + sidebarData({ + bindings: [binding({ workers: [{ threadId: "thr_worker", title: "Implement retry" }], reviewers: [{ threadId: "thr_reviewer", workerThreadId: "thr_worker" }] })], + }), + } as never, + }); + await waitFor(() => expect(slot.getByText("ENG-1")).toBeTruthy()); + expect(slot.queryByText("Implement retry")).toBeNull(); + fireEvent.click(slot.getByRole("button", { name: /Expand Fix login/u })); + await waitFor(() => expect(slot.getByText("Implement retry")).toBeTruthy()); + expect(slot.getByText("worker")).toBeTruthy(); + fireEvent.click(slot.getByRole("button", { name: /Expand Implement retry/u })); + await waitFor(() => expect(slot.getByText("Review the PR")).toBeTruthy()); + expect(slot.getByText("reviewer")).toBeTruthy(); + slot.lifecycle.unmount(); + }); + + it("wraps every row in bb's thread actions context menu", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Fix login" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding()] }) } as never, + threadActions: () => + [{ key: "archive", pluginId: "thread-list", group: "4_lifecycle", action: { label: "Archive", icon: "Archive", run: () => {} } }] as never, + }); + await waitFor(() => expect(slot.getByText("ENG-1")).toBeTruthy()); + const menu = slot.container.querySelector('[data-testid="bb-thread-actions-context-menu"][data-thread-id="thr_steward"]'); + expect(menu).not.toBeNull(); + fireEvent.contextMenu(menu!); + await waitFor(() => expect(slot.getByRole("menuitem", { name: "Archive" })).toBeTruthy()); + slot.lifecycle.unmount(); + }); + + it("collapses Watches and Recently ended until opened", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward" }), thread({ id: "thr_ops" })] }, + rpc: { + stewardsSidebar: () => + sidebarData({ + bindings: [binding(), binding({ key: "acme/web", kind: "ops", stage: null, threadId: "thr_ops" })], + ended: [{ key: "ENG-0", kind: "ticket", threadId: null, title: "Old work", endedAt: 1_000 }], + }), + } as never, + }); + await waitFor(() => expect(slot.getByRole("button", { name: /Watches/u })).toBeTruthy()); + expect(slot.queryByText("acme/web")).toBeNull(); + expect(slot.queryByText("Old work")).toBeNull(); + fireEvent.click(slot.getByRole("button", { name: /Watches/u })); + await waitFor(() => expect(slot.getByText("acme/web")).toBeTruthy()); + fireEvent.click(slot.getByRole("button", { name: /Recently ended/u })); + await waitFor(() => expect(slot.getByText("Old work")).toBeTruthy()); + slot.lifecycle.unmount(); + }); + + it("renders a project picker on a compact viewport", async () => { + const slot = await renderSidebar( + { + sidebarThreads: { projects, threads: [] }, + rpc: { stewardsSidebar: () => sidebarData() } as never, + }, + { isCompactViewport: true }, + ); + await waitFor(() => expect(slot.getByLabelText("Project")).toBeTruthy()); + expect(slot.queryByRole("tab")).toBeNull(); + slot.lifecycle.unmount(); + }); + + it("follows activeProjectId for the active tab and switches on pick", async () => { + const slot = await renderSidebar( + { + sidebarThreads: { projects, threads: [thread({ id: "thr_personal", projectId: "personal", displayTitle: "My notes" })] }, + rpc: { stewardsSidebar: () => sidebarData() } as never, + }, + { activeProjectId: "personal" }, + ); + await waitFor(() => expect(slot.getByRole("tab", { name: "Personal" }).getAttribute("aria-selected")).toBe("true")); + expect(slot.getByText("My notes")).toBeTruthy(); + fireEvent.click(slot.getByRole("tab", { name: "Acme" })); + await waitFor(() => expect(slot.getByRole("tab", { name: "Acme" }).getAttribute("aria-selected")).toBe("true")); + slot.lifecycle.unmount(); + }); + + it("navigates to the row's thread and calls onNavigate", async () => { + const onNavigate = vi.fn(); + const slot = await renderSidebar( + { + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Fix login" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding()] }) } as never, + }, + { onNavigate }, + ); + await waitFor(() => expect(slot.getByText("Fix login")).toBeTruthy()); + fireEvent.click(slot.getByText("Fix login")); + await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "toThread", threadId: "thr_steward" })); + expect(onNavigate).toHaveBeenCalled(); + slot.lifecycle.unmount(); + }); +}); diff --git a/plugins/stewards/sidebar-provider.ts b/plugins/stewards/sidebar-provider.ts new file mode 100644 index 00000000..90361114 --- /dev/null +++ b/plugins/stewards/sidebar-provider.ts @@ -0,0 +1,14 @@ +// The `sidebar.threadListProvider` preference values, shared by the client +// footer toggle (`app.tsx`) and the server-side default pin (`server.ts`). +// Its own module so the app bundle imports only these strings, never server +// code (BB-45). + +/** The UI preference that picks the sidebar thread list. */ +export const THREAD_LIST_PROVIDER_KEY = "sidebar.threadListProvider"; +/** bb's bundled thread list; pinning to it leaves the sidebar as it was. */ +export const BUILTIN_THREAD_LIST_ID = "thread-list/thread-list"; +/** What `sidebar.threadListProvider` reads while nothing is pinned. */ +export const AUTOMATIC_THREAD_LIST_PROVIDER = "__automatic__"; + +/** The value that turns the stewards list on: the plugin id plus BB-44's slot id. */ +export const stewardsThreadListId = (pluginId: string): string => `${pluginId}/sidebar`; diff --git a/plugins/stewards/sidebar.test.ts b/plugins/stewards/sidebar.test.ts new file mode 100644 index 00000000..6927201d --- /dev/null +++ b/plugins/stewards/sidebar.test.ts @@ -0,0 +1,159 @@ +import { describe, expect, it } from "vitest"; +import { buildSidebar, compareEfforts, isBusy, type SidebarEffort, type SidebarLiveProject, type SidebarLiveThread, type SidebarProjectData } from "./sidebar.js"; + +const thread = (over: Partial & { id: string }): SidebarLiveThread => ({ + projectId: "p1", + displayTitle: over.id, + parentThreadId: null, + lifecycleOwnerThreadId: null, + status: "idle", + isPinned: false, + updatedAt: 0, + ...over, +}); + +const project = (over: Partial & { id: string }): SidebarLiveProject => ({ name: over.id, isPersonal: false, ...over }); + +const binding = (over: Partial & { key: string; threadId: string }): SidebarProjectData["bindings"][number] => ({ + kind: "ticket", + stage: "build", + hold: null, + blockedOn: null, + needsUser: false, + advancedAt: null, + workers: [], + reviewers: [], + ...over, +}); + +const data = (over: Partial & { projectId: string }): SidebarProjectData => ({ + name: over.projectId, + projectStewardThreadId: null, + bindings: [], + ended: [], + ...over, +}); + +const effort = (over: Partial & { key: string }): SidebarEffort => ({ + bindingKey: null, + rootThreadId: over.key, + title: over.key, + kind: null, + stage: null, + hold: null, + blockedOn: null, + needsUser: false, + pinned: false, + busy: false, + recency: 0, + children: [], + ...over, +}); + +describe("stewards sidebar grouping", () => { + it("puts a worker with no parent or lifecycle owner under its binding through the workers table", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_steward" }), thread({ id: "thr_worker" })], + data: [data({ projectId: "p1", bindings: [binding({ key: "ENG-1", threadId: "thr_steward", workers: [{ threadId: "thr_worker", title: "Implement" }] })] })], + }); + expect(tabs[0]!.efforts).toHaveLength(1); + expect(tabs[0]!.efforts[0]!.children).toMatchObject([{ threadId: "thr_worker", role: "worker" }]); + }); + + it("puts a reviewer under its worker, not at the effort root", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_steward" }), thread({ id: "thr_worker" }), thread({ id: "thr_reviewer", parentThreadId: "thr_worker" })], + data: [ + data({ + projectId: "p1", + bindings: [binding({ key: "ENG-1", threadId: "thr_steward", workers: [{ threadId: "thr_worker", title: "Implement" }], reviewers: [{ threadId: "thr_reviewer", workerThreadId: "thr_worker" }] })], + }), + ], + }); + const workers = tabs[0]!.efforts[0]!.children; + expect(workers).toHaveLength(1); + expect(workers[0]!.children).toMatchObject([{ threadId: "thr_reviewer", role: "reviewer" }]); + }); + + it("lands a pre-BB-23 worker whose parent is the steward with the steward, even with no workers record", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_steward" }), thread({ id: "thr_old_worker", parentThreadId: "thr_steward" })], + data: [data({ projectId: "p1", bindings: [binding({ key: "ENG-1", threadId: "thr_steward" })] })], + }); + expect(tabs[0]!.efforts[0]!.children).toMatchObject([{ threadId: "thr_old_worker", role: "worker" }]); + }); + + it("trees a one-off thread's forks and children from the thread tree", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_root" }), thread({ id: "thr_child", parentThreadId: "thr_root" }), thread({ id: "thr_fork", lifecycleOwnerThreadId: "thr_child" })], + data: [data({ projectId: "p1" })], + }); + expect(tabs[0]!.efforts).toHaveLength(1); + expect(tabs[0]!.efforts[0]).toMatchObject({ rootThreadId: "thr_root", key: "thread:thr_root" }); + expect(tabs[0]!.efforts[0]!.children).toMatchObject([{ threadId: "thr_child", role: "thread", children: [{ threadId: "thr_fork", role: "thread" }] }]); + }); + + it("skips a binding whose steward thread is not in the live view", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_other" })], + data: [data({ projectId: "p1", bindings: [binding({ key: "ENG-1", threadId: "thr_archived" })] })], + }); + expect(tabs[0]!.efforts.map((e) => e.key)).toEqual(["thread:thr_other"]); + }); + + it("gives every live project a tab, stewarded or not, including the personal project", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" }), project({ id: "personal", isPersonal: true })], + threads: [], + data: [data({ projectId: "p1" })], + }); + expect(tabs.map((t) => t.projectId)).toEqual(["p1", "personal"]); + expect(tabs[1]!.isPersonal).toBe(true); + }); + + it("groups ops bindings under watches, not in flight", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_ticket" }), thread({ id: "thr_ops" })], + data: [ + data({ + projectId: "p1", + bindings: [binding({ key: "ENG-1", threadId: "thr_ticket" }), binding({ key: "acme/web", threadId: "thr_ops", kind: "ops", stage: null })], + }), + ], + }); + expect(tabs[0]!.efforts.map((e) => e.key)).toEqual(["ENG-1"]); + expect(tabs[0]!.watches.map((e) => e.key)).toEqual(["acme/web"]); + }); +}); + +describe("stewards sidebar ordering", () => { + it("orders pinned, then needsUser, then busy, then most recent activity", () => { + const pinned = effort({ key: "pinned", pinned: true, recency: 1 }); + const needs = effort({ key: "needs", needsUser: true, recency: 2 }); + const busy = effort({ key: "busy", busy: true, recency: 3 }); + const recent = effort({ key: "recent", recency: 100 }); + const old = effort({ key: "old", recency: 10 }); + const ordered = [old, recent, busy, needs, pinned].sort(compareEfforts).map((e) => e.key); + expect(ordered).toEqual(["pinned", "needs", "busy", "recent", "old"]); + }); + + it("counts starting, active and stopping as busy, and nothing else", () => { + expect(["starting", "active", "stopping"].every(isBusy)).toBe(true); + expect(["idle", "finished", "failed"].some(isBusy)).toBe(false); + }); + + it("orders a tab's efforts and watches with the same comparator", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_quiet", updatedAt: 5 }), thread({ id: "thr_busy", status: "active", updatedAt: 1 })], + data: [data({ projectId: "p1" })], + }); + expect(tabs[0]!.efforts.map((e) => e.rootThreadId)).toEqual(["thr_busy", "thr_quiet"]); + }); +}); diff --git a/plugins/stewards/sidebar.ts b/plugins/stewards/sidebar.ts new file mode 100644 index 00000000..efe6fea8 --- /dev/null +++ b/plugins/stewards/sidebar.ts @@ -0,0 +1,286 @@ +// The sidebar thread list's pure core: joining the host's live thread view to +// the `stewardsSidebar` RPC result, grouping threads into efforts, and ordering +// them. No React and no SDK, so the component and its tests share exactly this +// code. +// +// Grouping comes from the steward relationship, not the thread tree. A worker +// belongs to its binding through the plugin's `workers` table, which the RPC +// carries; a reviewer through its worker, which the RPC names. The thread tree +// is used only for one-off threads, which have nothing else, and as a fallback +// for a pre-BB-23 worker whose parent is its steward (BB-23 removed that link, +// so it is a fallback, never the rule). + +/** A binding as `stewardsSidebar` reports it. */ +export interface SidebarBinding { + key: string; + kind: string; + stage: string | null; + threadId: string | null; + hold: string | null; + blockedOn: string | null; + needsUser: boolean; + advancedAt: number | null; + workers: SidebarWorker[]; + reviewers: SidebarReviewer[]; +} + +export interface SidebarWorker { + threadId: string; + title: string; +} + +export interface SidebarReviewer { + threadId: string; + workerThreadId: string; +} + +export interface SidebarEnded { + key: string; + kind: string; + threadId: string | null; + title: string | null; + endedAt: number; +} + +export interface SidebarProjectData { + projectId: string; + name: string; + projectStewardThreadId: string | null; + bindings: SidebarBinding[]; + ended: SidebarEnded[]; +} + +/** The live-view fields grouping reads (`experimental_useSidebarThreads`). */ +export interface SidebarLiveThread { + id: string; + projectId: string; + displayTitle: string; + parentThreadId: string | null; + lifecycleOwnerThreadId: string | null; + status: string; + isPinned: boolean; + updatedAt: number; +} + +export interface SidebarLiveProject { + id: string; + name: string; + isPersonal: boolean; +} + +export type SidebarChildRole = "worker" | "reviewer" | "thread"; + +/** One thread under an effort: a worker, its reviewer, or a one-off's fork/child. */ +export interface SidebarChild { + threadId: string; + title: string; + role: SidebarChildRole; + children: SidebarChild[]; +} + +/** One effort: a root thread and the threads that belong to it. */ +export interface SidebarEffort { + /** Stable identity: the binding key for a stewarded effort, `thread:` for a one-off. */ + key: string; + /** The binding key, or null for a one-off thread. */ + bindingKey: string | null; + rootThreadId: string; + title: string; + kind: string | null; + stage: string | null; + hold: string | null; + blockedOn: string | null; + needsUser: boolean; + pinned: boolean; + busy: boolean; + /** The most recent activity anywhere in the effort, epoch ms. */ + recency: number; + children: SidebarChild[]; +} + +export interface SidebarTab { + projectId: string; + name: string; + isPersonal: boolean; + /** In-flight efforts, ordered. `ops` bindings are in `watches`, not here. */ + efforts: SidebarEffort[]; + /** `ops`, Dependabot and Sentry bindings, grouped in a collapsed row. */ + watches: SidebarEffort[]; + projectStewardThreadId: string | null; + ended: SidebarEnded[]; +} + +const BUSY = new Set(["starting", "active", "stopping"]); + +/** bb's own list counts these as busy. */ +export const isBusy = (status: string): boolean => BUSY.has(status); + +const parentOf = (t: Pick): string | null => t.parentThreadId ?? t.lifecycleOwnerThreadId; + +/** + * bb's precedence for its own list: pinned first, then threads that need the + * user, then busy threads (`starting` / `active` / `stopping`), then most + * recent activity. The tie-break by title keeps the order stable. + */ +export function compareEfforts(a: SidebarEffort, b: SidebarEffort): number { + if (a.pinned !== b.pinned) return a.pinned ? -1 : 1; + if (a.needsUser !== b.needsUser) return a.needsUser ? -1 : 1; + if (a.busy !== b.busy) return a.busy ? -1 : 1; + if (b.recency !== a.recency) return b.recency - a.recency; + return a.title.localeCompare(b.title); +} + +/** Every live project gets a tab; a project with no stewards still gets its one-off threads. */ +export function buildSidebar(input: { + projects: readonly SidebarLiveProject[]; + threads: readonly SidebarLiveThread[]; + data: readonly SidebarProjectData[]; +}): SidebarTab[] { + const dataByProject = new Map(input.data.map((d) => [d.projectId, d] as const)); + const threadsByProject = new Map(); + for (const t of input.threads) { + const list = threadsByProject.get(t.projectId) ?? []; + list.push(t); + threadsByProject.set(t.projectId, list); + } + return input.projects.map((project) => buildTab(project, dataByProject.get(project.id), threadsByProject.get(project.id) ?? [])); +} + +function buildTab(project: SidebarLiveProject, data: SidebarProjectData | undefined, threads: readonly SidebarLiveThread[]): SidebarTab { + const byId = new Map(threads.map((t) => [t.id, t] as const)); + const bindings = data?.bindings ?? []; + const stewardThreadId = data?.projectStewardThreadId ?? null; + + // Where a claimed thread sits: the effort it belongs to and its own child row. + const index = new Map }>(); + const roleByThread = new Map(); + const claimed = new Set(); + const efforts: SidebarEffort[] = []; + + const touch = (effort: SidebarEffort, t: SidebarLiveThread): void => { + if (t.updatedAt > effort.recency) effort.recency = t.updatedAt; + if (isBusy(t.status)) effort.busy = true; + }; + + for (const b of bindings) { + const root = b.threadId === null ? undefined : byId.get(b.threadId); + // A binding whose steward thread is not in the live view (archived) is skipped. + if (root === undefined) continue; + claimed.add(root.id); + roleByThread.set(root.id, "steward"); + const effort: SidebarEffort = { + key: b.key, + bindingKey: b.key, + rootThreadId: root.id, + title: root.displayTitle, + kind: b.kind, + stage: b.stage, + hold: b.hold, + blockedOn: b.blockedOn, + needsUser: b.needsUser, + pinned: root.isPinned, + busy: isBusy(root.status), + recency: root.updatedAt, + children: [], + }; + const byThread = new Map(); + index.set(root.id, { effort, byThread }); + efforts.push(effort); + + // Workers from the plugin's own table: the binding relationship, whatever + // the thread's parent or lifecycle owner says. + for (const w of b.workers) { + const thread = byId.get(w.threadId); + if (thread === undefined) continue; + claimed.add(thread.id); + roleByThread.set(thread.id, "worker"); + const child: SidebarChild = { threadId: thread.id, title: thread.displayTitle, role: "worker", children: [] }; + effort.children.push(child); + byThread.set(thread.id, child); + touch(effort, thread); + } + // Reviewers, each under the worker the RPC names. + for (const r of b.reviewers) { + const thread = byId.get(r.threadId); + if (thread === undefined) continue; + claimed.add(thread.id); + roleByThread.set(thread.id, "reviewer"); + const child: SidebarChild = { threadId: thread.id, title: thread.displayTitle, role: "reviewer", children: [] }; + (byThread.get(r.workerThreadId)?.children ?? effort.children).push(child); + byThread.set(thread.id, child); + touch(effort, thread); + } + } + + // The fallback the RPC records do not cover: a pre-BB-23 worker whose parent + // is its steward, and anything else a claimed thread owns. Run to a fixed + // point so a child of a fallback-attached thread lands too. + for (let changed = true; changed; ) { + changed = false; + for (const t of threads) { + if (claimed.has(t.id) || t.id === stewardThreadId) continue; + const parent = parentOf(t); + const holder = parent === null ? undefined : index.get(parent); + if (holder === undefined) continue; + claimed.add(t.id); + const parentRole = roleByThread.get(parent!) ?? "steward"; + const role: SidebarChildRole = parentRole === "steward" ? "worker" : parentRole === "worker" ? "reviewer" : "thread"; + roleByThread.set(t.id, role); + const child: SidebarChild = { threadId: t.id, title: t.displayTitle, role, children: [] }; + (holder.byThread.get(parent!)?.children ?? holder.effort.children).push(child); + holder.byThread.set(t.id, child); + index.set(t.id, holder); + touch(holder.effort, t); + changed = true; + } + } + + // One-off efforts: everything left, treed by parent / lifecycle owner. + const remaining = threads.filter((t) => !claimed.has(t.id) && t.id !== stewardThreadId); + const remainingById = new Map(remaining.map((t) => [t.id, t] as const)); + const childrenByParent = new Map(); + for (const t of remaining) { + const parent = parentOf(t); + if (parent === null || !remainingById.has(parent)) continue; + const list = childrenByParent.get(parent) ?? []; + list.push(t); + childrenByParent.set(parent, list); + } + const roots = remaining.filter((t) => { + const parent = parentOf(t); + return parent === null || !remainingById.has(parent); + }); + for (const root of roots) { + const effort: SidebarEffort = { + key: `thread:${root.id}`, + bindingKey: null, + rootThreadId: root.id, + title: root.displayTitle, + kind: null, + stage: null, + hold: null, + blockedOn: null, + needsUser: false, + pinned: root.isPinned, + busy: isBusy(root.status), + recency: root.updatedAt, + children: [], + }; + const visit = (t: SidebarLiveThread): SidebarChild => { + touch(effort, t); + return { threadId: t.id, title: t.displayTitle, role: "thread", children: (childrenByParent.get(t.id) ?? []).map(visit) }; + }; + effort.children = (childrenByParent.get(root.id) ?? []).map(visit); + efforts.push(effort); + } + + return { + projectId: project.id, + name: project.name, + isPersonal: project.isPersonal, + efforts: efforts.filter((e) => e.kind !== "ops").sort(compareEfforts), + watches: efforts.filter((e) => e.kind === "ops").sort(compareEfforts), + projectStewardThreadId: stewardThreadId, + ended: data?.ended ?? [], + }; +}