From b64ddc9825072e2bab415246c7fc886a4c07acb4 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Tue, 27 Oct 2026 01:53:07 +0000 Subject: [PATCH 1/2] stewards: sidebar redesign with two-line effort rows, four glyphs and Blocked / In flight sections (BB-76) --- plugins/stewards/DESIGN.md | 111 +++--- plugins/stewards/README.md | 65 ++-- plugins/stewards/app.test.tsx | 254 ++++--------- plugins/stewards/app.tsx | 348 +++++++++++------- plugins/stewards/server.test.ts | 44 ++- plugins/stewards/server.ts | 36 +- plugins/stewards/sidebar-app.test.tsx | 491 ++++++++++++++++++-------- plugins/stewards/sidebar.test.ts | 171 ++++++++- plugins/stewards/sidebar.ts | 172 ++++++++- 9 files changed, 1133 insertions(+), 559 deletions(-) diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index d7592ea9..59efc344 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -1438,25 +1438,50 @@ A **lesson** makes the answer a record and, for most of them, lands it. An opt-in replacement for bb's own sidebar list, registered through the exclusive `experimental_threadList` slot (`plugins/stewards/app.tsx`). One -project dropdown 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. - -**Title-first rows (BB-48).** A row is the status glyph, the title, and — for -a stewarded effort — the binding key only when the title does not already name -it, plus the held and blocked badges. The title wins: it takes the available -width and truncates last, while the meta shrinks and truncates first. A key -shown is shortened (a pull request `acme/web#612` as `#612`, a ticket as its -own key) and the full key stays on the row's `title` attribute. The stage -leaves the row — the board still groups by stage, but a row no longer repeats -it — and the chevron no longer carries a child count, so only the chevron -signals children. A child row's worker/reviewer label is a small muted `W`/`R` -tag. One-off threads no longer share In flight: they sit in a collapsed -**Threads** row below it, so In flight counts stewarded efforts only. -`buildSidebar` returns `efforts`, `threads` and `watches` separately, and the -split is unit tested in `sidebar.test.ts`. +project dropdown in the live view; the sections top to bottom are **Blocked** +(needs-you rows first, then blocked), **In flight** (running before quiet), +**Threads** (one-off threads, collapsed), **Monitors** (the `ops`, Dependabot +and Sentry bindings, collapsed), **Recently ended** (collapsed), 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. + +**Two-line effort rows and the four glyphs (BB-76).** An effort row is two +lines. Line one is the glyph, the entity key in bold, and the title, which +takes the available width and truncates last; the key prefix is stripped from +the steward thread's title (titled `: `, or `<Review key>: +<title>`), so the key and title are not repeated. Line two is the kind +(`ticket`, `pull request`, `review`, `ops`), the entity's own phase when it has +one (omitted for ops), and the status phrase. A row that needs you adds its +prompt and one-click actions under line two, in the same row, with no tinted +callout box. + +The glyph is one of four shapes, in precedence order `you › blocked › running › +quiet`: a solid yellow dot when it waits on you, an empty red ring when +blocked, a blue ring that pulses slowly while a worker or reviewer runs, and +an empty grey ring when quiet. The pulse is CSS only and stops under +`prefers-reduced-motion`. One-off threads use the same four glyphs — yellow +when unread, blue animated while their agent runs, grey otherwise — except a +draft, which keeps bb's own `ThreadStatusGlyph`. The project steward footer +row is the grey ring. + +**The status phrase (BB-76).** First match wins: `needs you`; `blocked on +<blockedOn>`; `held behind <holdBehind keys>` when `holdBehind` is non-empty, +else `on hold`; `stuck` for an open stuck escalation; `waiting on +<nextAction>` when the status actor is `other` (an external wait is a block); +`N worker(s) running` counting only workers whose worker-table status is +`running`; the newest deployment watch's state (`deploying`, `deployed`, +`deploy failed`); the status `nextAction`; otherwise `no report yet`. The +phrase's colour follows the glyph's. `sidebar.ts` derives `state`, `section` +and `phrase` as pure functions and sorts by the section rules; `sidebar.test.ts` +covers every rule and the precedence. + +**Sections.** Blocked holds the needs-you (yellow) and blocked (red) efforts, +whether stewarded or `ops`; a blocked `ops` binding leaves Monitors for +Blocked. In flight holds the rest of the stewarded, non-ops efforts, running +before quiet, then by recency. Pinned rows stay first within their section. +`buildSidebar` returns `blocked`, `efforts`, `threads` and `monitors` +separately, and the split is unit tested in `sidebar.test.ts`. **Grouping is the steward relationship, not the thread tree.** A worker belongs to its binding through the plugin's `workers` table and a reviewer @@ -1467,37 +1492,35 @@ 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 Needs you block and the count badge (BB-46).** The sidebar is where the -user already looks, so what waits on them is shown there, not only on the -Stewards page. The project dropdown carries each project's count in its option -label and the summed count in a pill beside it. Above In flight, a **Needs you** -block lists one row per item -with the entity key (opening the entity), one line of text, and **Details**, -which opens the board at that project. A question's or `decide` item's fixed -`choices` are not rendered here: the board carries the full question, its -context and the choices, so a truncated one-line row never asks the user to -pick blind. An `approve-pr` row carries the page's actions — **Open the pull -request** (`navigate.openUrl` on the item's `url`), **Approve** +**The inline needs-you actions and the picker count (BB-46, BB-76).** The +sidebar is where the user already looks, so what waits on them is shown there, +not only on the Stewards page. An effort that needs you appears once, at the +top of **Blocked**, with a yellow dot; under its line two it shows the +question or need's text and its one-click actions, the same RPC calls the old +block made. A fixed-choice question answers through +`stewardsAnswerQuestion { choice }`, a `decide` need through +`stewardsNeedAction { action: "choose", choice }`; an `approve-pr` row carries +**Open PR** (`navigate.openUrl` on the item's `url`), **Approve** (`stewardsNeedAction { action: "approve" }`, no confirmation, the server's -refusal shown in the row) and **Details** (the board at that project) — and -its text wraps instead of truncating, so the repository, number and title are -readable before the click. A `merge` row adds **Merge** -(`stewardsNeedAction { action: "merge" }`, the lane gate re-checked -server-side) beside **Open the pull request** and **Details**. Every other -row's page button is **Details** too: a row without choices, or a -`provide-secret` item, opens the Stewards page at that project, where the -free-text answer and the secret form live. The block adds no write path the -page does not already make. +refusal shown in the row) and **Details** (the board at that project); a +`merge` row swaps **Merge** for **Approve** (the lane gate re-checked +server-side). Every other row's page button is **Details**, opening the +Stewards page at that project, where the free-text answer and the secret form +live. The inline block adds no write path the page does not already make. The +project dropdown carries each project's count in its option label, and that +count is the number of yellow effort rows, so the picker and the sections +cannot disagree. `stewardsSidebar` carries, per project, +`needs: { count, items }` with the board's row shapes, each tagged +`question`/`withUser`/`need` and carrying the binding's entity key as +`bindingKey` so a row owns its item; the effort row filters the items by that +key. A project-level question with no binding has no effort row and stays on +the Stewards page. **One source of truth.** `server.ts`'s `needsYou(projectId, { actionableOnly })` builds the board's `questions`, `withUser` and `needs` lists in one place; the board calls it unfiltered, the sidebar calls it with `actionableOnly`, and `bb stewards needs` prints it, so the surfaces cannot drift and a non-actionable -need is on the page but not in the sidebar's count or items. `stewardsSidebar` -carries, per project, -`needs: { count, items }` with the same row shapes, each tagged -`question`/`withUser`/`need` so the app knows how to render the row and which -one-click action it carries. +need is on the page but not in the sidebar's items. **Realtime, not the poll.** The store takes an optional `onNeedsYouChange(projectId)` callback, wired in `server.ts` to diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 760f3af1..81cfd552 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -370,9 +370,42 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. ## 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 project dropdown, -in-flight efforts grouped by the steward relationship, and collapsed Watches -and Recently ended rows. BB-45 makes it switchable from where you are. +exclusive `experimental_threadList` slot: one project dropdown, two-line +effort rows with the four glyphs, and the **Blocked**, **In flight**, +**Threads**, **Monitors** and **Recently ended** sections. BB-45 makes it +switchable from where you are. + +**The row and the glyphs (BB-76).** An effort row is two lines: the glyph, the +entity key in bold and the title on line one; the kind (`ticket`, `pull +request`, `review`, `ops`), the entity's phase when it has one, and the status +phrase on line two. A row that needs you adds its prompt and one-click actions +under line two, in the same row. The glyph is one of four, in precedence order +`you › blocked › running › quiet`: a solid yellow dot when it waits on you, an +empty red ring when blocked, a blue ring that pulses slowly while a worker or +reviewer runs (CSS only, off under `prefers-reduced-motion`), and an empty grey +ring when quiet. One-off threads use the same four glyphs — yellow when unread, +blue animated while their agent runs, grey otherwise — except a draft, which +keeps bb's own glyph. An `ops` binding that needs you or is blocked moves from +Monitors into Blocked. + +**The needs-you items and the picker count (BB-46).** The project dropdown +shows each project's count in its option label, counting the yellow effort +rows. A needs-you effort shows the question or need's text and its one-click +actions inline under line two: a fixed-choice question answers through +`stewardsAnswerQuestion`, a `decide` need through `stewardsNeedAction +{ action: "choose" }`, an `approve-pr` row carries **Open PR** / **Approve** / +**Details**, a `merge` row **Open PR** / **Merge** / **Details**, and every +other row opens the Stewards page with **Details**. The actions make the same +RPC calls the board does, the server's refusal is shown in the row, and the +row refetches on success. The items come from `stewardsSidebar` and each +carries the binding's entity key as `bindingKey`, so a row owns its item; a +project-level question with no binding has no row and stays on the Stewards +page. The plugin publishes `needs-you-changed { projectId }` on its realtime +channel whenever a question is opened or answered, an escalation is filed with +or forwarded to the user or resolved, a need is filed, updated or closed, or a +binding ends or reopens — including from a steward's own tools — so every open +sidebar and the board page refresh within seconds. The half-minute poll stays +as the fallback. **The footer toggle.** A `ShieldCheck` icon in the sidebar footer (next to Settings) opens a small panel above the footer row with a **Stewards @@ -398,32 +431,6 @@ 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.) -**The Needs you block and the picker badge (BB-46).** The project dropdown -shows each project's count in its option label and the summed count in a small -pill beside it. Above **In flight**, a **Needs you** block lists one row per -item: the entity key opens the entity, one line of what, and **Details**, which -opens the Stewards page at that project. A question's or `decide` item's fixed -`choices` are not rendered here: the page shows the full question, its context -and the choices, so a one-line row never asks the user to pick blind. An -`approve-pr` row carries the page's three actions: **Open the pull request** -opens the item's `url`, **Approve** makes the page's one-click approval -(`stewardsNeedAction { action: "approve" }`, no confirmation, the server's -refusal shown in the row), and **Details** opens the Stewards page at that -project; its text wraps so the repository, number and title are readable. A -`merge` row adds **Merge** (`stewardsNeedAction { action: "merge" }`, the gate -re-checked server-side) beside **Open the pull request** and **Details**. Every -other row's page button is **Details** too: a row without choices, or a -`provide-secret` item, opens the Stewards page at that project. The block and -the board page read one server function -(`needsYou`), so the sidebar and the page can never disagree; a -non-actionable need is on the page but not in the sidebar. The count and the -items come from `stewardsSidebar`; the plugin publishes -`needs-you-changed { projectId }` on its realtime channel whenever a question -is opened or answered, an escalation is filed with or forwarded to the user -or resolved, a need is filed, updated or closed, or a binding ends or reopens -— including from a steward's own tools — so every open sidebar and the board -page refresh within seconds. The half-minute poll stays as the fallback. - **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 diff --git a/plugins/stewards/app.test.tsx b/plugins/stewards/app.test.tsx index 07959a41..8f6eb445 100644 --- a/plugins/stewards/app.test.tsx +++ b/plugins/stewards/app.test.tsx @@ -358,76 +358,96 @@ describe("the sidebar-footer toggle (BB-45)", () => { }); }); -// BB-46: the sidebar's "Needs you" block, fed by the -// `stewardsSidebar` call and refreshed over the realtime channel. +// BB-46/BB-76: the sidebar's picker counts the yellow effort rows and refreshes +// over the realtime channel; the needs-you items themselves live inline on the +// effort row (covered in sidebar-app.test.tsx). const sidebarProjects = [ { id: "p1", name: "Acme", isPersonal: false, href: "/projects/p1", settingsHref: "/projects/p1/settings" }, { id: "p2", name: "Beta", isPersonal: false, href: "/projects/p2", settingsHref: "/projects/p2/settings" }, ]; -const sidebarData = (p1Needs: { count: number; items: unknown[] }, p2Needs: { count: number; items: unknown[] } = { count: 0, items: [] }) => ({ +const sidebarThread = (id: string, projectId = "p1") => ({ + id, + projectId, + title: id, + titleFallback: null, + displayTitle: 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/${projectId}/threads/${id}`, + isHidden: false, + environment: null, + host: null, + createdAt: 0, + updatedAt: 0, + lastReadAt: null, + latestAttentionAt: 0, +}); + +const sidebarBinding = (over: Record<string, unknown>) => ({ + key: "ENG-1", + kind: "ticket", + stage: null, + phase: null, + hold: null, + holdBehind: [], + blockedOn: null, + needsUser: false, + stuck: false, + status: null, + deployment: null, + advancedAt: null, + workers: [], + reviewers: [], + ...over, +}); + +const sidebarData = (over: { p1?: Record<string, unknown>; p2?: Record<string, unknown> } = {}) => ({ projects: [ - { projectId: "p1", name: "Acme", projectStewardThreadId: null, needs: p1Needs, bindings: [], ended: [] }, - { projectId: "p2", name: "Beta", projectStewardThreadId: null, needs: p2Needs, bindings: [], ended: [] }, + { projectId: "p1", name: "Acme", projectStewardThreadId: null, needs: { count: 0, items: [] }, bindings: [], ended: [], ...over.p1 }, + { projectId: "p2", name: "Beta", projectStewardThreadId: null, needs: { count: 0, items: [] }, bindings: [], ended: [], ...over.p2 }, ], }); -describe("the stewards sidebar's needs you block (BB-46)", () => { - const questionItem = (over: Record<string, unknown> = {}) => ({ - type: "question", - id: "qst_1", - question: "Which approach?", - context: null, - choices: [], - key: "ENG-12", - url: "https://linear.app/acme/issue/ENG-12", - escalationId: null, - createdAt: 1_000, - ...over, - }); - const needItem = (over: Record<string, unknown> = {}) => ({ - type: "need", - id: "need_1", - bindingId: "bnd_1", - key: "ENG-12", - kind: "decide", - url: null, - entityUrl: "https://linear.app/acme/issue/ENG-12", - escalationId: null, - choices: [], - lessonId: null, - what: "Hold or start?", - how: null, - destination: null, - threadId: null, - createdAt: 1_000, - actionable: true, - why: null, - ...over, - }); - - const renderSidebar = async (rpc: Record<string, unknown>, props: Record<string, unknown> = {}): Promise<RenderedSlot> => { +describe("the stewards sidebar's picker counts and refresh (BB-46)", () => { + const renderSidebar = async (rpc: Record<string, unknown>, props: Record<string, unknown> = {}, threads: unknown[] = []): Promise<RenderedSlot> => { const captured = await loadApp(); const list = captured.threadLists[0]!; return renderSlot(list, { activeThreadId: null, activeProjectId: "p1", isCompactViewport: false, onNavigate: () => {}, searchQuery: "", ...props } as never, { - sidebarThreads: { projects: sidebarProjects, threads: [] }, + sidebarThreads: { projects: sidebarProjects, threads }, rpc, } as never); }; - it("does not render a summed count badge beside the picker", async () => { - const slot = await renderSidebar({ stewardsSidebar: () => sidebarData({ count: 2, items: [questionItem()] }) }); - await waitFor(() => expect(slot.getByLabelText("Project")).toBeTruthy()); - await waitFor(() => expect(slot.getByRole("option", { name: "Acme (2)" })).toBeTruthy()); - expect(slot.queryByLabelText("2 waiting on you")).toBeNull(); - expect(slot.getByRole("option", { name: "Beta" })).toBeTruthy(); - slot.lifecycle.unmount(); - }); - - it.each([false, true])("shows per-project counts in its options and no summed badge (compact=%s)", async (isCompactViewport) => { + it("counts the yellow effort rows per project, with no summed badge beside the picker", async () => { const slot = await renderSidebar( - { stewardsSidebar: () => sidebarData({ count: 2, items: [questionItem(), needItem()] }, { count: 1, items: [needItem({ id: "need_2" })] }) }, - { isCompactViewport }, + { + stewardsSidebar: () => + sidebarData({ + p1: { bindings: [sidebarBinding({ key: "ENG-1", threadId: "thr_a", needsUser: true }), sidebarBinding({ key: "ENG-2", threadId: "thr_b", needsUser: true })], needs: { count: 9, items: [] } }, + p2: { bindings: [sidebarBinding({ key: "ENG-3", threadId: "thr_c", needsUser: true })] }, + }), + }, + {}, + [sidebarThread("thr_a"), sidebarThread("thr_b"), sidebarThread("thr_c", "p2")], ); await waitFor(() => expect(slot.getByRole("option", { name: "Acme (2)" })).toBeTruthy()); expect(slot.getByRole("option", { name: "Beta (1)" })).toBeTruthy(); @@ -436,7 +456,7 @@ describe("the stewards sidebar's needs you block (BB-46)", () => { }); it("sizes the picker and the New thread button as h-8 controls", async () => { - const slot = await renderSidebar({ stewardsSidebar: () => sidebarData({ count: 2, items: [questionItem()] }) }); + const slot = await renderSidebar({ stewardsSidebar: () => sidebarData() }); const select = await waitFor(() => slot.getByLabelText("Project")); expect(select.className).toContain("h-8"); const button = slot.getByRole("button", { name: "New thread" }); @@ -445,136 +465,12 @@ describe("the stewards sidebar's needs you block (BB-46)", () => { slot.lifecycle.unmount(); }); - it("renders only Details for a question with choices, never the choices", async () => { - const slot = await renderSidebar({ - stewardsSidebar: () => sidebarData({ count: 1, items: [questionItem({ choices: ["Merge", "Close"] })] }), - stewardsAnswerQuestion: () => ({ ok: true, message: "closed" }), - }); - await waitFor(() => expect(slot.getByRole("button", { name: "Details" })).toBeTruthy()); - expect(slot.queryByRole("button", { name: "Merge" })).toBeNull(); - expect(slot.queryByRole("button", { name: "Close" })).toBeNull(); - fireEvent.click(slot.getByRole("button", { name: "Details" })); - await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "toPluginPanel", path: "board", options: { subPath: "p1" } })); - expect(slot.inspection.rpcCalls.some((c) => c.method === "stewardsAnswerQuestion")).toBe(false); - slot.lifecycle.unmount(); - }); - - it("renders only Details for a decide need with choices, never the choices", async () => { - const slot = await renderSidebar({ - stewardsSidebar: () => sidebarData({ count: 1, items: [needItem({ choices: ["Hold", "Start"] })] }), - stewardsNeedAction: () => ({ ok: true, message: "done" }), - }); - await waitFor(() => expect(slot.getByRole("button", { name: "Details" })).toBeTruthy()); - expect(slot.queryByRole("button", { name: "Hold" })).toBeNull(); - expect(slot.queryByRole("button", { name: "Start" })).toBeNull(); - fireEvent.click(slot.getByRole("button", { name: "Details" })); - await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "toPluginPanel", path: "board", options: { subPath: "p1" } })); - expect(slot.inspection.rpcCalls.some((c) => c.method === "stewardsNeedAction")).toBe(false); - slot.lifecycle.unmount(); - }); - - it("offers Merge, Open the pull request and Details on a merge row, and sends the merge action", async () => { - const url = "https://github.com/bitcomplete/bb-gate/pull/17"; - const slot = await renderSidebar({ - stewardsSidebar: () => sidebarData({ count: 1, items: [needItem({ kind: "merge", url })] }), - stewardsNeedAction: () => ({ ok: true, message: "merged" }), - }); - await waitFor(() => expect(slot.getByRole("button", { name: "Merge" })).toBeTruthy()); - expect(slot.getByRole("button", { name: "Open the pull request" })).toBeTruthy(); - expect(slot.getByRole("button", { name: "Details" })).toBeTruthy(); - fireEvent.click(slot.getByRole("button", { name: "Merge" })); - await waitFor(() => expect(slot.inspection.rpcCalls).toContainEqual({ method: "stewardsNeedAction", input: { needId: "need_1", action: "merge", note: null, choice: null } })); - slot.lifecycle.unmount(); - }); - - it("opens the board for a row without choices, under a Details label", async () => { - const slot = await renderSidebar({ stewardsSidebar: () => sidebarData({ count: 1, items: [needItem({ kind: "configure", choices: [] })] }) }); - await waitFor(() => expect(slot.getByRole("button", { name: "Details" })).toBeTruthy()); - expect(slot.queryByRole("button", { name: "Open" })).toBeNull(); - fireEvent.click(slot.getByRole("button", { name: "Details" })); - await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "toPluginPanel", path: "board", options: { subPath: "p1" } })); - slot.lifecycle.unmount(); - }); - - it("offers Open the pull request, Approve and Details on an approve-pr row, with wrapped text", async () => { - const slot = await renderSidebar({ - stewardsSidebar: () => sidebarData({ count: 1, items: [needItem({ kind: "approve-pr", url: "https://github.com/bitcomplete/bb-gate/pull/17", what: "Approve bitcomplete/bb-gate#17" })] }), - }); - await waitFor(() => expect(slot.getByRole("button", { name: "Open the pull request" })).toBeTruthy()); - expect(slot.getByRole("button", { name: "Approve" })).toBeTruthy(); - expect(slot.getByRole("button", { name: "Details" })).toBeTruthy(); - const text = slot.getByText("Approve bitcomplete/bb-gate#17"); - expect(text.className).not.toContain("truncate"); - expect(text.className).toContain("break-words"); - slot.lifecycle.unmount(); - }); - - it("opens the pull request's url from the row and makes no RPC", async () => { - const url = "https://github.com/bitcomplete/bb-gate/pull/17"; - const slot = await renderSidebar({ - stewardsSidebar: () => sidebarData({ count: 1, items: [needItem({ kind: "approve-pr", url })] }), - stewardsNeedAction: () => ({ ok: true, message: "done" }), - }); - fireEvent.click(await waitFor(() => slot.getByRole("button", { name: "Open the pull request" }))); - await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "openUrl", url })); - expect(slot.inspection.rpcCalls.some((c) => c.method === "stewardsNeedAction")).toBe(false); - slot.lifecycle.unmount(); - }); - - it("sends the approve action with no note or choice, and refetches on success", async () => { - let calls = 0; - const slot = await renderSidebar({ - stewardsSidebar: () => { - calls += 1; - return sidebarData({ count: 1, items: [needItem({ kind: "approve-pr", url: "https://github.com/bitcomplete/bb-gate/pull/17" })] }); - }, - stewardsNeedAction: () => ({ ok: true, message: "approved" }), - }); - fireEvent.click(await waitFor(() => slot.getByRole("button", { name: "Approve" }))); - await waitFor(() => expect(slot.inspection.rpcCalls).toContainEqual({ method: "stewardsNeedAction", input: { needId: "need_1", action: "approve", note: null, choice: null } })); - await waitFor(() => expect(calls).toBe(2)); - slot.lifecycle.unmount(); - }); - - it("shows the server's refusal in the row and re-enables the buttons", async () => { - const slot = await renderSidebar({ - stewardsSidebar: () => sidebarData({ count: 1, items: [needItem({ kind: "approve-pr", url: "https://github.com/bitcomplete/bb-gate/pull/17" })] }), - stewardsNeedAction: () => ({ ok: false, message: "the owner must approve first" }), - }); - fireEvent.click(await waitFor(() => slot.getByRole("button", { name: "Approve" }))); - await waitFor(() => expect(slot.getByText("the owner must approve first")).toBeTruthy()); - expect((slot.getByRole("button", { name: "Approve" }) as HTMLButtonElement).disabled).toBe(false); - slot.lifecycle.unmount(); - }); - - it("opens the board at the project from Details on an approve-pr row", async () => { - const slot = await renderSidebar({ - stewardsSidebar: () => sidebarData({ count: 1, items: [needItem({ kind: "approve-pr", url: "https://github.com/bitcomplete/bb-gate/pull/17" })] }), - }); - fireEvent.click(await waitFor(() => slot.getByRole("button", { name: "Details" }))); - await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "toPluginPanel", path: "board", options: { subPath: "p1" } })); - slot.lifecycle.unmount(); - }); - - it("labels the page button Details on every other row, with no Open label", async () => { - const items = [ - needItem({ id: "need_secret", kind: "provide-secret", choices: [] }), - needItem({ id: "need_config", kind: "configure", choices: [] }), - needItem({ id: "need_decide", kind: "decide", choices: [] }), - questionItem({ id: "qst_1", choices: [] }), - ]; - const slot = await renderSidebar({ stewardsSidebar: () => sidebarData({ count: items.length, items }) }); - await waitFor(() => expect(slot.getAllByRole("button", { name: "Details" })).toHaveLength(4)); - expect(slot.queryByRole("button", { name: "Open" })).toBeNull(); - slot.lifecycle.unmount(); - }); - it("refetches on a realtime event for a shown project and ignores an unknown one", async () => { let calls = 0; const slot = await renderSidebar({ stewardsSidebar: () => { calls += 1; - return sidebarData({ count: 0, items: [] }); + return sidebarData(); }, }); await waitFor(() => expect(calls).toBe(1)); diff --git a/plugins/stewards/app.tsx b/plugins/stewards/app.tsx index 524b3d17..2445b688 100644 --- a/plugins/stewards/app.tsx +++ b/plugins/stewards/app.tsx @@ -27,7 +27,7 @@ import { } from "@get-bb/plugin-sdk/app"; import type { rpcContract } from "./server"; import { NEEDS_YOU_CHANGED } from "./channels.js"; -import { buildSidebar, isBusy, type SidebarChild, type SidebarChildRole, type SidebarEffort } from "./sidebar.js"; +import { buildSidebar, effortTitle, isBusy, type SidebarChild, type SidebarChildRole, type SidebarEffort, type SidebarEffortState } from "./sidebar.js"; import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY, stewardsThreadListId } from "./sidebar-provider.js"; type Client = ReturnType<typeof useRpc<typeof rpcContract>>; @@ -851,10 +851,11 @@ 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 project dropdown, 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. +// exclusive `experimental_threadList` slot. One project dropdown, two-line +// effort rows with the four glyphs in the Blocked / In flight / Threads / +// Monitors / Recently ended sections, 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. /** The live fields bb's thread actions read, from a sidebar row. */ function actionTarget(t: PluginSidebarThread): PluginThreadActionTarget { @@ -881,14 +882,43 @@ function shortBindingKey(key: string): string { return pull === null ? key : `#${pull[1]}`; } -const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +/** The effort's kind, spelled out for line two. */ +function kindLabel(kind: string | null): string { + if (kind === "pr") return "pull request"; + if (kind === "ticket") return "ticket"; + if (kind === "review") return "review"; + if (kind === "ops") return "ops"; + return kind ?? "thread"; +} + +/** The phrase's colour follows the glyph's (BB-76): yellow, red, blue, muted. */ +function phraseClass(state: SidebarEffortState): string { + if (state === "you") return "text-amber-600 dark:text-amber-500"; + if (state === "blocked") return "text-destructive"; + if (state === "running") return "text-blue-600 dark:text-blue-400"; + return "text-muted-foreground"; +} -/** Whether the title names the key as a whole token, so `#612` is not swallowed by `#6123`. */ -function titleNamesKey(title: string, key: string): boolean { - return new RegExp(`${escapeRegExp(key)}(?!\\d)`).test(title); +/** + * The four glyphs, in precedence order (BB-76): a solid yellow dot when it + * waits on you, an empty red ring when blocked, a blue ring that pulses slowly + * while a worker or agent runs, an empty grey ring when quiet. The pulse is + * CSS only and stops under `prefers-reduced-motion`. + */ +function StewardGlyph({ kind }: { kind: SidebarEffortState }) { + if (kind === "you") return <span data-steward-glyph="you" aria-hidden="true" className="size-2.5 shrink-0 rounded-full bg-amber-400" />; + const border = kind === "blocked" ? "border-red-500" : kind === "running" ? "border-blue-500" : "border-muted-foreground/50"; + return <span data-steward-glyph={kind} aria-hidden="true" className={`size-2.5 shrink-0 rounded-full border-2 ${border}${kind === "running" ? " motion-safe:animate-pulse" : ""}`} />; } -/** One thread row: bb's glyph, title and context menu, expanding into its children. */ +/** A one-off thread's glyph: yellow when unread, blue animated while its agent runs, grey otherwise. */ +function oneOffGlyph(thread: PluginSidebarThread): SidebarEffortState { + if (thread.isUnread || thread.indicator === "unread-success" || thread.indicator === "unread-error") return "you"; + if (isBusy(thread.status)) return "running"; + return "quiet"; +} + +/** One thread row: a glyph, title and context menu, expanding into its children. */ function SidebarThreadRow({ thread, role, @@ -898,6 +928,7 @@ function SidebarThreadRow({ onNavigate, meta, titleAttr, + glyph, }: { thread: PluginSidebarThread; role: SidebarChildRole; @@ -908,6 +939,8 @@ function SidebarThreadRow({ meta?: ReactNode; /** The full binding key, kept on the row's `title` attribute when the row is an effort. */ titleAttr?: string; + /** The four-glyph component for a one-off thread or the project steward row; drafts keep bb's glyph. */ + glyph?: SidebarEffortState; }) { const navigate = useBbNavigate(); const rowStatus = useSidebarThreadRowStatus(thread.id); @@ -916,6 +949,7 @@ function SidebarThreadRow({ // 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 useStewardGlyph = glyph !== undefined && indicator !== "draft" && indicator !== "working-draft"; const count = countThreads(children); return ( <li className="flex flex-col"> @@ -938,7 +972,7 @@ function SidebarThreadRow({ (none, dot, spinner) or its width. The spinner at size="compact" is the widest, so size-4 is the slot. */} <span data-sidebar-status-slot="" className="flex size-4 shrink-0 items-center justify-center"> - <ThreadStatusGlyph indicator={indicator} rowStatus={rowStatus} size="compact" /> + {useStewardGlyph ? <StewardGlyph kind={glyph!} /> : <ThreadStatusGlyph indicator={indicator} rowStatus={rowStatus} size="compact" />} </span> <a href={thread.href} @@ -973,25 +1007,158 @@ function SidebarThreadRow({ ); } -/** One effort's root row, title-first: the shortened key only when the title omits it, and the held/blocked badges. */ -function SidebarEffortRow({ effort, byId, onNavigate }: { effort: SidebarEffort; byId: ReadonlyMap<string, PluginSidebarThread>; onNavigate: () => void }) { +/** + * The inline "needs you" block under an effort row's line two (BB-76): the + * question or need's text, then its one-click actions, exactly the RPC calls + * the old Needs you block made. A fixed-choice question answers through + * `stewardsAnswerQuestion`, a `decide` need through `stewardsNeedAction + * choose`; an approve-pr or merge keeps its Open PR / Approve|Merge buttons; + * everything else opens the board. + */ +function SidebarInlineNeed({ item, onChanged, onOpenBoard }: { item: SidebarNeedItem; onChanged: () => void; onOpenBoard: () => void }) { + const rpc = useRpc<typeof rpcContract>(); + const navigate = useBbNavigate(); + const [state, setState] = useState<"idle" | "running" | { error: string }>("idle"); + const text = item.type === "need" ? item.what : item.question; + const isApprovePr = item.type === "need" && item.kind === "approve-pr"; + const isMerge = item.type === "need" && item.kind === "merge"; + const choices = item.type === "question" ? item.choices : item.type === "need" && item.kind === "decide" ? item.choices : []; + const run = (call: Promise<{ ok: boolean; message: string }>) => { + setState("running"); + call.then( + (r) => { + if (!r.ok) return setState({ error: r.message }); + onChanged(); + }, + (e: unknown) => setState({ error: message(e) }), + ); + }; + const answer = (choice: string) => run(rpc.call("stewardsAnswerQuestion", { questionId: item.id, answer: null, choice })); + const choose = (choice: string) => run(rpc.call("stewardsNeedAction", { needId: item.id, action: "choose", note: null, choice })); + const approve = () => run(rpc.call("stewardsNeedAction", { needId: item.id, action: "approve", note: null, choice: null })); + const merge = () => run(rpc.call("stewardsNeedAction", { needId: item.id, action: "merge", note: null, choice: null })); + const button = "rounded-md border border-input px-2 py-0.5 text-[11px] hover:bg-state-hover disabled:opacity-50"; + return ( + <div className="flex flex-col gap-1"> + <p className="min-w-0 break-words text-[11px] text-muted-foreground">{text}</p> + <div className="flex flex-wrap items-center gap-1"> + {choices.length > 0 ? ( + choices.map((choice) => ( + <button key={choice} type="button" disabled={state === "running"} className={button} onClick={() => (item.type === "question" ? answer(choice) : choose(choice))}> + {choice} + </button> + )) + ) : isApprovePr || isMerge ? ( + <> + {item.url !== null ? ( + <button type="button" className={button} onClick={() => navigate.openUrl(item.url!)}> + Open PR + </button> + ) : null} + <button type="button" disabled={state === "running"} className={button} onClick={isApprovePr ? approve : merge}> + {isApprovePr ? "Approve" : "Merge"} + </button> + </> + ) : null} + <button type="button" className={button} onClick={onOpenBoard}> + Details + </button> + {typeof state === "object" ? <span className="text-[11px] text-destructive">{state.error}</span> : null} + </div> + </div> + ); +} + +/** + * One effort's root row, two lines (BB-76): glyph, entity key and title on + * line one; kind, phase and status phrase on line two; a needs-you row adds + * its prompt and actions under that, in the same row. + */ +function SidebarEffortRow({ + effort, + needs, + byId, + onNavigate, + onChanged, + onOpenBoard, +}: { + effort: SidebarEffort; + needs: readonly SidebarNeedItem[]; + byId: ReadonlyMap<string, PluginSidebarThread>; + onNavigate: () => void; + onChanged: () => void; + onOpenBoard: () => void; +}) { const root = byId.get(effort.rootThreadId); + const navigate = useBbNavigate(); + const [open, setOpen] = useState(false); if (root === undefined) return null; const key = effort.bindingKey; const displayKey = key === null ? null : shortBindingKey(key); - // The title wins: a steward is titled after its binding, so showing the key again is noise. - const keyInTitle = key !== null && displayKey !== null && (titleNamesKey(root.displayTitle, key) || titleNamesKey(root.displayTitle, displayKey)); - const showKey = displayKey !== null && !keyInTitle; - const badges = effort.hold !== null || effort.blockedOn !== null; - const meta = - !showKey && !badges ? null : ( - <span className="flex min-w-0 shrink items-center gap-1 text-[11px] text-muted-foreground"> - {showKey ? <span className="min-w-0 truncate font-medium">{displayKey}</span> : null} - {effort.hold !== null ? <Badge tone="warn">held</Badge> : null} - {effort.blockedOn !== null ? <Badge tone="bad">blocked</Badge> : null} - </span> - ); - return <SidebarThreadRow thread={root} role="thread" children={effort.children} depth={0} byId={byId} onNavigate={onNavigate} meta={meta} titleAttr={key ?? undefined} />; + const title = effortTitle(root.displayTitle, key); + const count = countThreads(effort.children); + const mine = needs.filter((item) => item.bindingKey !== null && item.bindingKey === key); + return ( + <li className="flex flex-col"> + <ThreadActionsContextMenu thread={actionTarget(root)}> + <div className="flex flex-col rounded-md py-0.5 pr-1 hover:bg-state-hover" style={{ paddingLeft: "4px" }} title={key ?? undefined}> + <div className="flex items-center gap-1"> + {count > 0 ? ( + <button + type="button" + aria-label={`${open ? "Collapse" : "Expand"} ${root.displayTitle}`} + aria-expanded={open} + className="flex size-4 shrink-0 items-center justify-center text-muted-foreground" + onClick={() => setOpen((v) => !v)} + > + <Icon name={open ? "ChevronDown" : "ChevronRight"} className="size-3.5" /> + </button> + ) : ( + <span className="flex size-4 shrink-0 items-center justify-center" /> + )} + <span data-sidebar-status-slot="" className="flex size-4 shrink-0 items-center justify-center"> + <StewardGlyph kind={effort.state} /> + </span> + <a + href={root.href} + className="flex min-w-0 flex-1 items-baseline gap-1 text-sm" + onClick={(e) => { + e.preventDefault(); + navigate.toThread(root.id); + onNavigate(); + }} + > + {displayKey !== null ? <span className="shrink-0 font-semibold">{displayKey}</span> : null} + <span className="min-w-0 truncate">{title}</span> + </a> + </div> + <p className="text-[11px] text-muted-foreground" style={{ paddingLeft: "36px" }} data-sidebar-line-two=""> + {kindLabel(effort.kind)} + {effort.phase !== null ? ` · ${effort.phase}` : ""} + {" · "} + <span className={phraseClass(effort.state)}>{effort.phrase}</span> + </p> + </div> + </ThreadActionsContextMenu> + {mine.length > 0 ? ( + <div className="flex flex-col gap-1 pb-1" style={{ paddingLeft: "40px" }}> + {mine.map((item) => ( + <SidebarInlineNeed key={`${item.type}:${item.id}`} item={item} onChanged={onChanged} onOpenBoard={onOpenBoard} /> + ))} + </div> + ) : null} + {open && effort.children.length > 0 ? ( + <ul className="flex flex-col"> + {effort.children.map((c) => { + const child = byId.get(c.threadId); + return child === undefined ? null : ( + <SidebarThreadRow key={c.threadId} thread={child} role={c.role} children={c.children} depth={1} byId={byId} onNavigate={onNavigate} /> + ); + })} + </ul> + ) : null} + </li> + ); } function SidebarSection({ title, count, children }: { title: string; count: number; children: ReactNode }) { @@ -1062,98 +1229,6 @@ function ProjectTabs({ tabs, counts, activeId, onPick, onNewThread }: { tabs: Ar ); } -/** - * One item in the sidebar's "Needs you" block: the key, one line of text, and - * Details, which opens the board at the project. The board carries the full - * question, its context and its choices, so a `question` or `decide` row does - * not render them here. An `approve-pr` or `merge` row keeps its one-click - * button — the server re-checks the gate before acting — beside Open the pull - * request; every other row opens the page. - */ -function SidebarNeedRow({ item, onChanged, onOpenBoard }: { item: SidebarNeedItem; onChanged: () => void; onOpenBoard: () => void }) { - const rpc = useRpc<typeof rpcContract>(); - const navigate = useBbNavigate(); - const [state, setState] = useState<"idle" | "running" | { error: string }>("idle"); - const text = item.type === "need" ? item.what : item.question; - const entityUrl = item.type === "need" ? item.entityUrl : item.url; - const prUrl = item.url; - // approve-pr and merge are the mechanical items the server verifies before - // acting; every other row opens the page. - const isApprovePr = item.type === "need" && item.kind === "approve-pr"; - const isMerge = item.type === "need" && item.kind === "merge"; - const run = (call: Promise<{ ok: boolean; message: string }>) => { - setState("running"); - call.then( - (r) => { - if (!r.ok) return setState({ error: r.message }); - onChanged(); - }, - (e: unknown) => setState({ error: message(e) }), - ); - }; - const approve = () => run(rpc.call("stewardsNeedAction", { needId: item.id, action: "approve", note: null, choice: null })); - const merge = () => run(rpc.call("stewardsNeedAction", { needId: item.id, action: "merge", note: null, choice: null })); - return ( - <li className="flex flex-col gap-1 px-2 py-1.5"> - <p className="flex flex-wrap items-center gap-2"> - {item.key !== null ? <EntityLink entityKey={item.key} url={entityUrl} /> : null} - {item.type === "withUser" ? <Badge tone="bad">{item.kind === "approval" ? "approval request" : `${item.kind} escalation`}</Badge> : null} - {item.type === "need" ? <Badge tone="bad">{item.kind}</Badge> : null} - </p> - <p className={isApprovePr ? "min-w-0 break-words" : "min-w-0 truncate"}>{text}</p> - <div className="flex flex-wrap items-center gap-1"> - {isApprovePr || isMerge ? ( - <> - {prUrl !== null ? ( - <button - type="button" - className="rounded-md border border-input px-2 py-0.5 text-[11px] hover:bg-state-hover" - onClick={() => navigate.openUrl(prUrl)} - > - Open the pull request - </button> - ) : null} - <button - type="button" - disabled={state === "running"} - className="rounded-md border border-input px-2 py-0.5 text-[11px] hover:bg-state-hover disabled:opacity-50" - onClick={isApprovePr ? approve : merge} - > - {isApprovePr ? "Approve" : "Merge"} - </button> - <button type="button" className="rounded-md border border-input px-2 py-0.5 text-[11px] hover:bg-state-hover" onClick={onOpenBoard}> - Details - </button> - </> - ) : ( - <button type="button" className="rounded-md border border-input px-2 py-0.5 text-[11px] hover:bg-state-hover" onClick={onOpenBoard}> - Details - </button> - )} - {typeof state === "object" ? <span className="text-destructive">{state.error}</span> : null} - </div> - </li> - ); -} - -/** The sidebar's "Needs you" block: the board's waiting items, above In flight. */ -function SidebarNeedsSection({ projectId, needs, onChanged }: { projectId: string; needs: SidebarNeeds; onChanged: () => void }) { - const navigate = useBbNavigate(); - return ( - <SidebarSection title="Needs you" count={needs.count}> - {needs.items.length === 0 ? ( - <p className="px-2 py-1 text-muted-foreground">Nothing is waiting on you.</p> - ) : ( - <ul className="flex flex-col"> - {needs.items.map((item) => ( - <SidebarNeedRow key={`${item.type}:${item.id}`} item={item} onChanged={onChanged} onOpenBoard={() => navigate.toPluginPanel(BOARD_PATH, { subPath: encodeURIComponent(projectId) })} /> - ))} - </ul> - )} - </SidebarSection> - ); -} - function StewardsSidebar({ activeProjectId, onNavigate }: PluginThreadListProps) { const rpc = useRpc<typeof rpcContract>(); const navigate = useBbNavigate(); @@ -1161,7 +1236,8 @@ function StewardsSidebar({ activeProjectId, onNavigate }: PluginThreadListProps) const { data, error, refetch } = usePolled(useCallback(() => rpc.call("stewardsSidebar", null), [rpc])); const tabs = useMemo(() => buildSidebar({ projects, threads, data: data?.projects ?? [] }), [projects, threads, data]); const needsByProject = useMemo(() => new Map((data?.projects ?? []).map((p) => [p.projectId, p.needs] as const)), [data]); - const counts = useMemo(() => new Map(tabs.map((t) => [t.projectId, needsByProject.get(t.projectId)?.count ?? 0] as const)), [tabs, needsByProject]); + // The picker counts the yellow rows, so the pill and the sections cannot disagree (BB-76). + const counts = useMemo(() => new Map(tabs.map((t) => [t.projectId, t.blocked.filter((e) => e.state === "you").length] as const)), [tabs]); // A steward's question or item updates the badge and block within seconds; // the half-minute poll stays the fallback. Only a project this sidebar shows // triggers a refetch. @@ -1189,6 +1265,10 @@ function StewardsSidebar({ activeProjectId, onNavigate }: PluginThreadListProps) if (active !== null) navigate.toCompose({ projectId: active.projectId }); onNavigate(); }; + const openBoard = () => { + if (active !== null) navigate.toPluginPanel(BOARD_PATH, { subPath: encodeURIComponent(active.projectId) }); + }; + const needItems = activeNeeds?.items ?? []; return ( <div className="flex h-full flex-col text-sm"> <ProjectTabs tabs={tabs} counts={counts} activeId={active?.projectId ?? null} onPick={setPicked} onNewThread={openNewThread} /> @@ -1198,14 +1278,22 @@ function StewardsSidebar({ activeProjectId, onNavigate }: PluginThreadListProps) <p className="p-3 text-muted-foreground">No projects yet.</p> ) : ( <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-1"> - {activeNeeds !== undefined ? <SidebarNeedsSection projectId={active.projectId} needs={activeNeeds} onChanged={refetch} /> : null} + {active.blocked.length > 0 ? ( + <SidebarSection title="Blocked" count={active.blocked.length}> + <ul className="flex flex-col"> + {active.blocked.map((e) => ( + <SidebarEffortRow key={e.key} effort={e} needs={needItems} byId={byId} onNavigate={onNavigate} onChanged={refetch} onOpenBoard={openBoard} /> + ))} + </ul> + </SidebarSection> + ) : null} <SidebarSection title="In flight" count={active.efforts.length}> {active.efforts.length === 0 ? ( <p className="px-2 py-1 text-muted-foreground">Nothing in flight.</p> ) : ( <ul className="flex flex-col"> {active.efforts.map((e) => ( - <SidebarEffortRow key={e.key} effort={e} byId={byId} onNavigate={onNavigate} /> + <SidebarEffortRow key={e.key} effort={e} needs={needItems} byId={byId} onNavigate={onNavigate} onChanged={refetch} onOpenBoard={openBoard} /> ))} </ul> )} @@ -1213,17 +1301,20 @@ function StewardsSidebar({ activeProjectId, onNavigate }: PluginThreadListProps) {active.threads.length > 0 ? ( <SidebarCollapsible title="Threads" count={active.threads.length}> <ul className="flex flex-col"> - {active.threads.map((e) => ( - <SidebarEffortRow key={e.key} effort={e} byId={byId} onNavigate={onNavigate} /> - ))} + {active.threads.map((e) => { + const t = byId.get(e.rootThreadId); + return t === undefined ? null : ( + <SidebarThreadRow key={e.key} thread={t} role="thread" children={e.children} depth={0} byId={byId} onNavigate={onNavigate} glyph={oneOffGlyph(t)} /> + ); + })} </ul> </SidebarCollapsible> ) : null} - {active.watches.length > 0 ? ( - <SidebarCollapsible title="Watches" count={active.watches.length}> + {active.monitors.length > 0 ? ( + <SidebarCollapsible title="Monitors" count={active.monitors.length}> <ul className="flex flex-col"> - {active.watches.map((e) => ( - <SidebarEffortRow key={e.key} effort={e} byId={byId} onNavigate={onNavigate} /> + {active.monitors.map((e) => ( + <SidebarEffortRow key={e.key} effort={e} needs={needItems} byId={byId} onNavigate={onNavigate} onChanged={refetch} onOpenBoard={openBoard} /> ))} </ul> </SidebarCollapsible> @@ -1264,6 +1355,7 @@ function StewardsSidebar({ activeProjectId, onNavigate }: PluginThreadListProps) depth={0} byId={byId} onNavigate={onNavigate} + glyph="quiet" meta={<span className="shrink-0 text-[10px] uppercase text-muted-foreground">project steward</span>} /> </div> diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index fd06a3e8..b8e0a4d3 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -3193,14 +3193,20 @@ describe("the stewards sidebar call", () => { key: string; kind: string; stage: string | null; + phase: string | null; threadId: string | null; hold: string | null; + holdBehind: string[]; blockedOn: string | null; needsUser: boolean; + stuck: boolean; + status: { actor: string; nextAction: string; at: number } | null; + deployment: string | null; advancedAt: number | null; - workers: Array<{ threadId: string; title: string }>; + workers: Array<{ threadId: string; title: string; status: string }>; reviewers: Array<{ threadId: string; workerThreadId: string }>; }>; + needs: { count: number; items: Array<{ type: string; id: string; bindingKey: string | null }> }; ended: Array<{ key: string; kind: string; threadId: string | null; title: string | null; endedAt: number }>; }>; }; @@ -3228,6 +3234,42 @@ describe("the stewards sidebar call", () => { expect(result.projects[0]!.ended).toEqual([]); }); + it("carries phase, status, holdBehind, stuck, deployment, worker status and a needs item's bindingKey (BB-76)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + const steward = t.spawns[1]!.id; + await t.created("thr_w1", steward, "Implement retry"); + t.hooks.store.setWorker("thr_w1", "running", null); + const at = t.now(); + t.hooks.store.patch(b.id, { + phase: "In Review", + hold: "a freeze", + holdBehind: ["ENG-9"], + status: { phase: "review", summary: "Waiting on the vendor", nextAction: "the vendor", actor: "other", blockedOn: null, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at }, + deployments: { + "acme/web#7": { key: "acme/web#7", state: "deployed", mergeSha: null, repo: "acme/web", environment: "production", deploymentId: null, deploymentState: null, ref: null, sha: null, url: null, at, deadlineAt: null, note: null, workflowRuns: [] }, + }, + }); + // An open `stuck` escalation is a block (BB-76). + t.hooks.store.escalate({ bindingId: b.id, kind: "stuck", question: "Stuck", meanwhile: "Waiting", route: "project", recommendation: null, projectId: "p1" }); + const q = t.hooks.store.ask({ projectId: "p1", bindingId: b.id, escalationId: null, question: "Which option?", context: null }); + + const result = (await t.harness.callRpc("stewardsSidebar", null)) as Sidebar; + const binding = result.projects[0]!.bindings.find((x) => x.key === "ENG-12")!; + expect(binding).toMatchObject({ + phase: "In Review", + hold: "a freeze", + holdBehind: ["ENG-9"], + stuck: true, + status: { actor: "other", nextAction: "the vendor", at }, + deployment: "deployed", + workers: [{ threadId: "thr_w1", title: "Implement retry", status: "running" }], + }); + expect(result.projects[0]!.needs.items).toContainEqual(expect.objectContaining({ type: "question", id: q.id, bindingKey: "ENG-12" })); + }); + 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" })); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index a92adc50..9222c6a7 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -73,7 +73,7 @@ import { type Source, type WorkflowRun, } from "./source-contract.js"; -import { allDeployed, applyDeployment, applyDeploymentRead, applyWorkflowRun, awaitingOnRepo, deploymentLines, deploymentReportSchema, matchesWorkflow, recordMerged, reportDeployment, timeOut, timeoutsDue } from "./deploy.js"; +import { DEPLOY_STATES, allDeployed, applyDeployment, applyDeploymentRead, applyWorkflowRun, awaitingOnRepo, deploymentLines, deploymentReportSchema, matchesWorkflow, recordMerged, reportDeployment, timeOut, timeoutsDue } from "./deploy.js"; import { ACTORS, MIGRATIONS, ESCALATED_NEED_KINDS, 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, type Worker } from "./store.js"; import { hasLessonAnchor, planLessonTransitions, planValidations, retiredLessonAnchor, withLessonAnchor } from "./lessons.js"; import { AFTER_THE_FACT_RATIONALE_WHY, REPEAT_RATIONALE_WHY, ROUTINE_RATIONALE_WHY, clusterKey, routineRationaleWanted } from "./rationale.js"; @@ -271,9 +271,9 @@ const needViewSchema = z.object({ }); /** One "needs you" item in the sidebar, tagged so the app knows which write it makes. */ const sidebarNeedsItemSchema = z.discriminatedUnion("type", [ - questionViewSchema.extend({ type: z.literal("question") }), - withUserViewSchema.extend({ type: z.literal("withUser") }), - needViewSchema.extend({ type: z.literal("need") }), + questionViewSchema.extend({ type: z.literal("question"), /** The binding's entity key, so a row owns its item (BB-76); null for a project-level question. */ bindingKey: z.string().nullable() }), + withUserViewSchema.extend({ type: z.literal("withUser"), bindingKey: z.string() }), + needViewSchema.extend({ type: z.literal("need"), bindingKey: z.string() }), ]); /** The steward's own surface for the app and the CLI. Cross-plugin methods are in source-contract.ts. */ @@ -447,12 +447,23 @@ export const rpcContract = defineRpcContract({ key: z.string(), kind: z.string(), stage: z.string().nullable(), + /** The entity's own phase, for line two; null when the binding has none (ops). */ + phase: z.string().nullable(), threadId: z.string().nullable(), hold: z.string().nullable(), + /** Entity keys this hold waits behind, for `held behind <keys>`. */ + holdBehind: z.array(z.string()), blockedOn: z.string().nullable(), needsUser: z.boolean(), + /** An open `stuck` escalation: the row is blocked (BB-76). */ + stuck: z.boolean(), + /** The status report's actor, next action and timestamp; null with no report. */ + status: z.object({ actor: z.string(), nextAction: z.string(), at: z.number() }).nullable(), + /** The newest deployment watch's state, or null with none (BB-76). */ + deployment: z.enum(DEPLOY_STATES).nullable(), advancedAt: z.number().nullable(), - workers: z.array(z.object({ threadId: z.string(), title: z.string() })), + /** Every worker, running or not, with the plugin's own status so the row counts running ones. */ + workers: z.array(z.object({ threadId: z.string(), title: z.string(), status: z.string() })), /** Reviewer threads, each under the worker it reviews. */ reviewers: z.array(z.object({ threadId: z.string(), workerThreadId: z.string() })), }), @@ -4552,23 +4563,30 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P needs: { count: questions.length + withUser.length + needs.length, items: [ - ...questions.map((q) => ({ type: "question" as const, ...q })), - ...withUser.map((w) => ({ type: "withUser" as const, ...w })), - ...needs.map((n) => ({ type: "need" as const, ...n })), + ...questions.map((q) => ({ type: "question" as const, ...q, bindingKey: q.key })), + ...withUser.map((w) => ({ type: "withUser" as const, ...w, bindingKey: w.key })), + ...needs.map((n) => ({ type: "need" as const, ...n, bindingKey: n.key })), ], }, bindings: all .filter((b) => b.endedAt === null) .map((b) => { - const workers = store.workers(b.id).map((w) => ({ threadId: w.threadId, title: w.title })); + const workers = store.workers(b.id).map((w) => ({ threadId: w.threadId, title: w.title, status: w.status })); + // The newest deployment watch, whatever its state (BB-76); the row shows `merged` as deploying too. + const newestDeployment = Object.values(b.deployments).sort((x, y) => y.at - x.at)[0] ?? null; return { key: b.entityKey, kind: b.kind, stage: b.stage, + phase: b.phase, threadId: b.threadId, hold: b.hold, + holdBehind: b.holdBehind, blockedOn: b.status?.blockedOn ?? null, needsUser: needsUser(b), + stuck: store.openEscalations(b.id).some((x) => x.kind === "stuck"), + status: b.status === null ? null : { actor: b.status.actor, nextAction: b.status.nextAction, at: b.status.at }, + deployment: newestDeployment === null ? null : newestDeployment.state, advancedAt: b.advancedAt, workers, reviewers: workers.flatMap((w) => (reviewersByWorker.get(w.threadId) ?? []).map((threadId) => ({ threadId, workerThreadId: w.threadId }))), diff --git a/plugins/stewards/sidebar-app.test.tsx b/plugins/stewards/sidebar-app.test.tsx index 5f99bb18..150a2c21 100644 --- a/plugins/stewards/sidebar-app.test.tsx +++ b/plugins/stewards/sidebar-app.test.tsx @@ -1,7 +1,7 @@ // @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. +// BB-44/BB-76: the stewards sidebar thread list renders one tab per project, +// two-line effort rows with the four glyphs, inline needs-you actions, and the +// Blocked / In flight / Threads / Monitors / Recently ended sections. 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"; @@ -48,12 +48,13 @@ const projects = [ { id: "personal", name: "Personal", isPersonal: true, href: "/projects/personal", settingsHref: "/projects/personal/settings" }, ]; -const sidebarData = (over: { bindings?: unknown[]; ended?: unknown[]; projectStewardThreadId?: string | null } = {}) => ({ +const sidebarData = (over: { bindings?: unknown[]; ended?: unknown[]; needs?: unknown; projectStewardThreadId?: string | null } = {}) => ({ projects: [ { projectId: "p1", name: "Acme", projectStewardThreadId: over.projectStewardThreadId ?? null, + needs: over.needs ?? { count: 0, items: [] }, bindings: over.bindings ?? [], ended: over.ended ?? [], }, @@ -64,16 +65,77 @@ const binding = (over: Record<string, unknown> = {}) => ({ key: "ENG-1", kind: "ticket", stage: "build", + phase: null, threadId: "thr_steward", hold: null, + holdBehind: [], blockedOn: null, needsUser: false, + stuck: false, + status: null, + deployment: null, advancedAt: null, workers: [], reviewers: [], ...over, }); +const questionItem = (over: Record<string, unknown> = {}) => ({ + type: "question", + id: "qst_1", + question: "Stack or hold?", + context: null, + choices: [], + key: "ENG-1", + bindingKey: "ENG-1", + url: null, + escalationId: null, + createdAt: 0, + rationaleWanted: null, + ...over, +}); + +const needItem = (over: Record<string, unknown> = {}) => ({ + type: "need", + id: "need_1", + bindingId: "b1", + key: "ENG-1", + bindingKey: "ENG-1", + kind: "approve-pr", + url: "https://github.com/acme/web/pull/1", + entityUrl: "https://github.com/acme/web/pull/1", + escalationId: null, + choices: [], + lessonId: null, + what: "Approve the pull request", + how: null, + destination: null, + threadId: null, + createdAt: 0, + actionable: true, + why: null, + ...over, +}); + +const withUserItem = (over: Record<string, unknown> = {}) => ({ + type: "withUser", + id: "esc_1", + kind: "blocked", + question: "Need cluster access", + recommendation: null, + key: "ENG-1", + bindingKey: "ENG-1", + url: null, + threadId: null, + createdAt: 0, + rationaleWanted: null, + ...over, +}); + +const lineTwo = (slot: RenderedSlot, title: string): string => slot.getByText(title).closest("li")!.querySelector("[data-sidebar-line-two]")!.textContent ?? ""; + +const glyphOf = (slot: RenderedSlot, title: string): string | null => slot.getByText(title).closest("li")!.querySelector("[data-steward-glyph]")?.getAttribute("data-steward-glyph") ?? null; + let app: CapturedPluginApp | null = null; const loadApp = async () => { app ??= await loadPluginApp(() => import("./app.js")); @@ -97,62 +159,45 @@ describe("the stewards sidebar list (BB-44)", () => { expect(captured.threadLists[0]).toMatchObject({ id: "sidebar", title: "Stewards" }); }); - it("shows a tab per live project and a title-first row with the shortened key and badges", async () => { + it("shows a tab per live project and a two-line effort row with key, title, kind, phase and phrase", 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, + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { + stewardsSidebar: () => sidebarData({ bindings: [binding({ phase: "In Review", status: { actor: "steward", nextAction: "wait for the review", at: 1 } })] }), + } as never, }); await waitFor(() => expect(slot.getByRole("option", { name: "Acme" })).toBeTruthy()); expect(slot.getByRole("option", { name: "Personal" })).toBeTruthy(); await waitFor(() => expect(slot.getByText("Fix login")).toBeTruthy()); - // The title does not name the key, so the key shows; the stage does not. + // Line one: the shortened key and the title, the key stripped from the title. expect(slot.getByText("ENG-1")).toBeTruthy(); - expect(slot.queryByText("build")).toBeNull(); - expect(slot.getByText("held")).toBeTruthy(); - // The full key stays on the row's title attribute. expect(slot.container.querySelector('[title="ENG-1"]')).not.toBeNull(); + // Line two: kind, phase, phrase; no stage text anywhere. + expect(lineTwo(slot, "Fix login")).toBe("ticket · In Review · wait for the review"); + expect(slot.queryByText("build")).toBeNull(); slot.lifecycle.unmount(); }); - it("drops the key when the title already names it, and keeps no stage text", async () => { - const slot = await renderSidebar({ - sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Review acme/web#612: Read dashboard metrics" })] }, - rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ key: "acme/web#612", stage: "review" })] }) } as never, - }); - await waitFor(() => expect(slot.getByText("Review acme/web#612: Read dashboard metrics")).toBeTruthy()); - expect(slot.queryByText("#612", { exact: true })).toBeNull(); - expect(slot.queryByText("review", { exact: true })).toBeNull(); - expect(slot.container.querySelector('[title="acme/web#612"]')).not.toBeNull(); - slot.lifecycle.unmount(); - }); - - it("shortens a pull-request key to #N when the title omits it", async () => { + it("shortens a pull-request key to #N and spells out the kind", async () => { const slot = await renderSidebar({ - sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Fix login" })] }, - rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ key: "acme/web#612" })] }) } as never, + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "acme/web#612: Read dashboard metrics" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ key: "acme/web#612", kind: "pr", phase: "open" })] }) } as never, }); await waitFor(() => expect(slot.getByText("#612")).toBeTruthy()); expect(slot.queryByText("acme/web#612", { exact: true })).toBeNull(); - expect(slot.container.querySelector('[title="acme/web#612"]')).not.toBeNull(); - slot.lifecycle.unmount(); - }); - - it("does not swallow a key into a longer number in the title", async () => { - const slot = await renderSidebar({ - sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Fix login #6123" })] }, - rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ key: "acme/web#612" })] }) } as never, - }); - await waitFor(() => expect(slot.getByText("#612", { exact: true })).toBeTruthy()); + expect(lineTwo(slot, "Read dashboard metrics")).toBe("pull request · open · no report yet"); slot.lifecycle.unmount(); }); - it("renders held and blocked badges without a stage", async () => { + it("shows kind only for an ops binding, with no phase", async () => { const slot = await renderSidebar({ - sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Fix login" })] }, - rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ hold: "waiting", blockedOn: "a review" })] }) } as never, + sidebarThreads: { projects, threads: [thread({ id: "thr_ops", displayTitle: "Ops watch: acme/web" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ key: "acme/web", kind: "ops", stage: null, threadId: "thr_ops", status: { actor: "steward", nextAction: "watching", at: 1 } })] }) } as never, }); - await waitFor(() => expect(slot.getByText("held")).toBeTruthy()); - expect(slot.getByText("blocked")).toBeTruthy(); + const monitors = await waitFor(() => slot.getByRole("button", { name: /Monitors/u })); + fireEvent.click(monitors); + await waitFor(() => expect(slot.getByText("Ops watch: acme/web")).toBeTruthy()); + expect(lineTwo(slot, "Ops watch: acme/web")).toBe("ops · watching"); slot.lifecycle.unmount(); }); @@ -160,132 +205,34 @@ describe("the stewards sidebar list (BB-44)", () => { const slot = await renderSidebar({ sidebarThreads: { projects, - threads: [thread({ id: "thr_steward", displayTitle: "Fix login" }), thread({ id: "thr_worker", displayTitle: "Implement retry" })], + threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" }), thread({ id: "thr_worker", displayTitle: "Implement retry" })], }, - rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ workers: [{ threadId: "thr_worker", title: "Implement retry" }] })] }) } as never, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ workers: [{ threadId: "thr_worker", title: "Implement retry", status: "running" }] })] }) } as never, }); - const expand = await waitFor(() => slot.getByRole("button", { name: "Expand Fix login" })); + const expand = await waitFor(() => slot.getByRole("button", { name: "Expand ENG-1: Fix login" })); expect(expand.textContent).toBe(""); fireEvent.click(expand); await waitFor(() => expect(slot.getByText("Implement retry")).toBeTruthy()); - expect(slot.getByRole("button", { name: "Collapse Fix login" })).toBeTruthy(); - slot.lifecycle.unmount(); - }); - - it("puts every row's status glyph in the same fixed-width slot so titles line up", async () => { - const slot = await renderSidebar({ - sidebarThreads: { - projects, - threads: [ - thread({ id: "thr_none", displayTitle: "No indicator" }), - thread({ id: "thr_dot", displayTitle: "Dot indicator", indicator: "unread-success" }), - thread({ id: "thr_spinner", displayTitle: "Spinner indicator", indicator: "runtime" }), - ], - }, - rpc: { stewardsSidebar: () => sidebarData() } as never, - }); - // One-off threads live in the collapsed Threads section. - const threadsToggle = await waitFor(() => slot.getByRole("button", { name: /Threads/u })); - fireEvent.click(threadsToggle); - await waitFor(() => expect(slot.getByText("No indicator")).toBeTruthy()); - - const rows = ["No indicator", "Dot indicator", "Spinner indicator"].map((title) => { - const anchor = slot.getByText(title).closest("a")!; - const wrapper = anchor.previousElementSibling as HTMLElement; - return { anchor, wrapper }; - }); - - // Every indicator, including none, occupies the same slot classes, and the - // title anchor is the element right after it. - for (const { anchor, wrapper } of rows) { - expect(wrapper.dataset.sidebarStatusSlot).toBe(""); - expect(wrapper.classList.contains("flex")).toBe(true); - expect(wrapper.classList.contains("size-4")).toBe(true); - expect(wrapper.classList.contains("shrink-0")).toBe(true); - expect(wrapper.classList.contains("items-center")).toBe(true); - expect(wrapper.classList.contains("justify-center")).toBe(true); - expect(anchor.previousElementSibling).toBe(wrapper); - } - // None has no glyph; the dot and the spinner render inside the slot. - expect(rows[0]!.wrapper.querySelector("[data-thread-status-glyph]")).toBeNull(); - expect(rows[1]!.wrapper.querySelector('[data-thread-status-glyph="unread-success"]')).not.toBeNull(); - expect(rows[2]!.wrapper.querySelector('[data-thread-status-glyph="runtime"]')).not.toBeNull(); - slot.lifecycle.unmount(); - }); - - it("keeps the chevron slot the same width as the leaf slot", async () => { - const slot = await renderSidebar({ - sidebarThreads: { - projects, - threads: [ - thread({ id: "thr_parent", displayTitle: "With children" }), - thread({ id: "thr_worker", displayTitle: "A worker" }), - thread({ id: "thr_leaf", displayTitle: "Leaf binding" }), - ], - }, - rpc: { - stewardsSidebar: () => - sidebarData({ - bindings: [ - binding({ key: "ENG-1", threadId: "thr_parent", workers: [{ threadId: "thr_worker", title: "A worker" }] }), - binding({ key: "ENG-2", threadId: "thr_leaf" }), - ], - }), - } as never, - }); - await waitFor(() => expect(slot.getByText("With children")).toBeTruthy()); - expect(slot.getByText("Leaf binding")).toBeTruthy(); - - const chevronSlot = (title: string): HTMLElement => { - const anchor = slot.getByText(title).closest("a")!; - return anchor.previousElementSibling!.previousElementSibling as HTMLElement; - }; - // The 14px expand icon and the empty leaf placeholder both sit in a size-4 - // slot, so at equal depth the title starts at the same x either way. - const parentSlot = chevronSlot("With children"); - const leafSlot = chevronSlot("Leaf binding"); - expect(parentSlot.tagName).toBe("BUTTON"); - expect(parentSlot.classList.contains("size-4")).toBe(true); - expect(parentSlot.classList.contains("shrink-0")).toBe(true); - expect(leafSlot.tagName).toBe("SPAN"); - expect(leafSlot.classList.contains("size-4")).toBe(true); - expect(leafSlot.classList.contains("shrink-0")).toBe(true); - slot.lifecycle.unmount(); - }); - - it("keeps one-off threads out of In flight, in a collapsed Threads section", async () => { - const slot = await renderSidebar({ - sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Fix login" }), thread({ id: "thr_oneoff", displayTitle: "My notes" })] }, - rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding()] }) } as never, - }); - await waitFor(() => expect(slot.getByText("Fix login")).toBeTruthy()); - const inFlight = slot.getByRole("heading", { name: /In flight/u }); - expect(inFlight.textContent).toContain("1"); - const threads = slot.getByRole("button", { name: /Threads/u }); - expect(threads.textContent).toContain("1"); - // Collapsed by default: the one-off's title is not rendered until it is opened. - expect(slot.queryByText("My notes")).toBeNull(); - fireEvent.click(threads); - await waitFor(() => expect(slot.getByText("My notes")).toBeTruthy()); + expect(slot.getByRole("button", { name: "Collapse ENG-1: Fix login" })).toBeTruthy(); slot.lifecycle.unmount(); }); - it("shows workers and reviewers only when the effort is expanded, as muted glyph tags", async () => { + it("shows workers and reviewers only when the effort is expanded, as muted W/R tags", 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" })], + threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: 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" }] })], + bindings: [binding({ workers: [{ threadId: "thr_worker", title: "Implement retry", status: "running" }], reviewers: [{ threadId: "thr_reviewer", workerThreadId: "thr_worker" }] })], }), } as never, }); await waitFor(() => expect(slot.getByText("Fix login")).toBeTruthy()); expect(slot.queryByText("Implement retry")).toBeNull(); - fireEvent.click(slot.getByRole("button", { name: /Expand Fix login/u })); + fireEvent.click(slot.getByRole("button", { name: /Expand ENG-1: Fix login/u })); await waitFor(() => expect(slot.getByText("Implement retry")).toBeTruthy()); expect(slot.getByTitle("worker").textContent).toBe("W"); fireEvent.click(slot.getByRole("button", { name: /Expand Implement retry/u })); @@ -296,7 +243,7 @@ describe("the stewards sidebar list (BB-44)", () => { 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" })] }, + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: 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, @@ -309,7 +256,7 @@ describe("the stewards sidebar list (BB-44)", () => { slot.lifecycle.unmount(); }); - it("collapses Watches and Recently ended until opened", async () => { + it("collapses Monitors and Recently ended until opened", async () => { const slot = await renderSidebar({ sidebarThreads: { projects, threads: [thread({ id: "thr_steward" }), thread({ id: "thr_ops" })] }, rpc: { @@ -320,10 +267,10 @@ describe("the stewards sidebar list (BB-44)", () => { }), } as never, }); - await waitFor(() => expect(slot.getByRole("button", { name: /Watches/u })).toBeTruthy()); + await waitFor(() => expect(slot.getByRole("button", { name: /Monitors/u })).toBeTruthy()); expect(slot.queryByText("acme/web")).toBeNull(); expect(slot.queryByText("Old work")).toBeNull(); - fireEvent.click(slot.getByRole("button", { name: /Watches/u })); + fireEvent.click(slot.getByRole("button", { name: /Monitors/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()); @@ -391,7 +338,7 @@ describe("the stewards sidebar list (BB-44)", () => { const onNavigate = vi.fn(); const slot = await renderSidebar( { - sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "Fix login" })] }, + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding()] }) } as never, }, { onNavigate }, @@ -403,3 +350,243 @@ describe("the stewards sidebar list (BB-44)", () => { slot.lifecycle.unmount(); }); }); + +describe("the stewards sidebar sections, glyphs and phrases (BB-76)", () => { + it("puts a needs-you effort at the top of Blocked with a yellow dot and its phrase, not in In flight", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ needsUser: true, phase: "In Review" })] }) } as never, + }); + await waitFor(() => expect(slot.getByRole("heading", { name: /Blocked/u })).toBeTruthy()); + expect(lineTwo(slot, "Fix login")).toBe("ticket · In Review · needs you"); + expect(glyphOf(slot, "Fix login")).toBe("you"); + // The picker counts the yellow rows. + expect(slot.getByRole("option", { name: "Acme (1)" })).toBeTruthy(); + // No separate Needs you section remains. + expect(slot.queryByRole("heading", { name: /Needs you/u })).toBeNull(); + // The In flight section is empty. + expect(slot.getByRole("heading", { name: /In flight/u }).textContent).toContain("0"); + slot.lifecycle.unmount(); + }); + + it("puts a blocked effort in Blocked with a red ring and the rule's phrase", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ blockedOn: "bb-gate#88", phase: "In Progress" })] }) } as never, + }); + await waitFor(() => expect(slot.getByText("Fix login")).toBeTruthy()); + expect(lineTwo(slot, "Fix login")).toBe("ticket · In Progress · blocked on bb-gate#88"); + expect(glyphOf(slot, "Fix login")).toBe("blocked"); + expect(slot.getByRole("heading", { name: /In flight/u }).textContent).toContain("0"); + slot.lifecycle.unmount(); + }); + + it("shows held-behind, stuck and waiting-on-others as blocked", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_a", displayTitle: "ENG-1: A" }), thread({ id: "thr_b", displayTitle: "ENG-2: B" }), thread({ id: "thr_c", displayTitle: "ENG-3: C" })] }, + rpc: { + stewardsSidebar: () => + sidebarData({ + bindings: [ + binding({ key: "ENG-1", threadId: "thr_a", hold: "a freeze", holdBehind: ["ENG-9"] }), + binding({ key: "ENG-2", threadId: "thr_b", stuck: true }), + binding({ key: "ENG-3", threadId: "thr_c", status: { actor: "other", nextAction: "the vendor", at: 1 } }), + ], + }), + } as never, + }); + await waitFor(() => expect(slot.getByText("A")).toBeTruthy()); + expect(lineTwo(slot, "A")).toContain("held behind ENG-9"); + expect(lineTwo(slot, "B")).toContain("stuck"); + expect(lineTwo(slot, "C")).toContain("waiting on the vendor"); + expect(glyphOf(slot, "A")).toBe("blocked"); + expect(glyphOf(slot, "B")).toBe("blocked"); + expect(glyphOf(slot, "C")).toBe("blocked"); + slot.lifecycle.unmount(); + }); + + it("shows a running effort in In flight with a blue animated ring and a running-worker count", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { + stewardsSidebar: () => + sidebarData({ + bindings: [ + binding({ + phase: "In Review", + workers: [ + { threadId: "thr_w1", title: "w1", status: "running" }, + { threadId: "thr_w2", title: "w2", status: "running" }, + { threadId: "thr_w3", title: "w3", status: "finished" }, + ], + }), + ], + }), + } as never, + }); + await waitFor(() => expect(slot.getByText("Fix login")).toBeTruthy()); + expect(lineTwo(slot, "Fix login")).toBe("ticket · In Review · 2 workers running"); + expect(glyphOf(slot, "Fix login")).toBe("running"); + const glyph = slot.container.querySelector('[data-steward-glyph="running"]')!; + expect(glyph.className).toContain("motion-safe:animate-pulse"); + slot.lifecycle.unmount(); + }); + + it("shows a quiet effort in In flight with a grey ring and the next action", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ status: { actor: "steward", nextAction: "wait for CI", at: 1 } })] }) } as never, + }); + await waitFor(() => expect(slot.getByText("Fix login")).toBeTruthy()); + expect(lineTwo(slot, "Fix login")).toBe("ticket · wait for CI"); + expect(glyphOf(slot, "Fix login")).toBe("quiet"); + slot.lifecycle.unmount(); + }); + + it("shows a deployment watch's state as the phrase", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ deployment: "deployed" })] }) } as never, + }); + await waitFor(() => expect(slot.getByText("Fix login")).toBeTruthy()); + expect(lineTwo(slot, "Fix login")).toBe("ticket · deployed"); + expect(glyphOf(slot, "Fix login")).toBe("quiet"); + slot.lifecycle.unmount(); + }); + + it("shows yellow, blue and grey one-off thread glyphs, keeping bb's draft glyph", async () => { + const slot = await renderSidebar({ + sidebarThreads: { + projects, + threads: [ + thread({ id: "thr_unread", displayTitle: "Unread reply", indicator: "unread-success" }), + thread({ id: "thr_running", displayTitle: "Running agent", status: "active" }), + thread({ id: "thr_quiet", displayTitle: "Read and idle" }), + thread({ id: "thr_draft", displayTitle: "Has a draft", indicator: "draft" }), + ], + }, + rpc: { stewardsSidebar: () => sidebarData() } as never, + }); + fireEvent.click(await waitFor(() => slot.getByRole("button", { name: /Threads/u }))); + await waitFor(() => expect(slot.getByText("Unread reply")).toBeTruthy()); + expect(glyphOf(slot, "Unread reply")).toBe("you"); + expect(glyphOf(slot, "Running agent")).toBe("running"); + expect(glyphOf(slot, "Read and idle")).toBe("quiet"); + // A draft keeps bb's own glyph, not the four-glyph component. + expect(glyphOf(slot, "Has a draft")).toBeNull(); + expect(slot.container.querySelector('[data-thread-status-glyph="draft"]')).not.toBeNull(); + slot.lifecycle.unmount(); + }); + + it("keeps an ops binding out of Monitors when it is blocked, and shows it in Blocked", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_ops", displayTitle: "Ops watch: acme/web" })] }, + rpc: { stewardsSidebar: () => sidebarData({ bindings: [binding({ key: "acme/web", kind: "ops", stage: null, threadId: "thr_ops", blockedOn: "a rotation" })] }) } as never, + }); + await waitFor(() => expect(slot.getByRole("heading", { name: /Blocked/u })).toBeTruthy()); + expect(slot.getByText("Ops watch: acme/web")).toBeTruthy(); + expect(glyphOf(slot, "Ops watch: acme/web")).toBe("blocked"); + expect(slot.queryByRole("button", { name: /Monitors/u })).toBeNull(); + slot.lifecycle.unmount(); + }); + + it("gives the project steward footer row a grey ring", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_p", displayTitle: "Acme project steward" })] }, + rpc: { stewardsSidebar: () => sidebarData({ projectStewardThreadId: "thr_p" }) } as never, + }); + await waitFor(() => expect(slot.getByText("Acme project steward")).toBeTruthy()); + expect(glyphOf(slot, "Acme project steward")).toBe("quiet"); + slot.lifecycle.unmount(); + }); +}); + +describe("the inline needs-you actions (BB-76)", () => { + it("renders a fixed-choice question's buttons and answers through stewardsAnswerQuestion", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { + stewardsSidebar: () => + sidebarData({ + bindings: [binding({ needsUser: true })], + needs: { count: 1, items: [questionItem({ choices: ["Stack", "Hold"], question: "Stacked on BB-57. Merge order?" })] }, + }), + stewardsAnswerQuestion: () => ({ ok: true, message: "closed" }), + } as never, + }); + await waitFor(() => expect(slot.getByText("Stacked on BB-57. Merge order?")).toBeTruthy()); + fireEvent.click(slot.getByRole("button", { name: "Stack" })); + await waitFor(() => expect(slot.inspection.rpcCalls).toContainEqual({ method: "stewardsAnswerQuestion", input: { questionId: "qst_1", answer: null, choice: "Stack" } })); + expect(slot.getByRole("button", { name: "Details" })).toBeTruthy(); + slot.lifecycle.unmount(); + }); + + it("renders a decide need's choices and sends them through stewardsNeedAction choose", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { + stewardsSidebar: () => + sidebarData({ + bindings: [binding({ needsUser: true })], + needs: { count: 1, items: [needItem({ kind: "decide", choices: ["Merge", "Close"], what: "Merge or close?" })] }, + }), + stewardsNeedAction: () => ({ ok: true, message: "done" }), + } as never, + }); + await waitFor(() => expect(slot.getByText("Merge or close?")).toBeTruthy()); + fireEvent.click(slot.getByRole("button", { name: "Merge" })); + await waitFor(() => expect(slot.inspection.rpcCalls).toContainEqual({ method: "stewardsNeedAction", input: { needId: "need_1", action: "choose", note: null, choice: "Merge" } })); + slot.lifecycle.unmount(); + }); + + it("renders an approve-pr need's Open PR / Approve / Details and approves in one click", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { + stewardsSidebar: () => sidebarData({ bindings: [binding({ needsUser: true })], needs: { count: 1, items: [needItem()] } }), + stewardsNeedAction: () => ({ ok: true, message: "done" }), + } as never, + }); + await waitFor(() => expect(slot.getByText("Approve the pull request")).toBeTruthy()); + fireEvent.click(slot.getByRole("button", { name: "Approve" })); + await waitFor(() => expect(slot.inspection.rpcCalls).toContainEqual({ method: "stewardsNeedAction", input: { needId: "need_1", action: "approve", note: null, choice: null } })); + fireEvent.click(slot.getByRole("button", { name: "Open PR" })); + await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "openUrl", url: "https://github.com/acme/web/pull/1" })); + slot.lifecycle.unmount(); + }); + + it("renders a with-user escalation with Details only", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { + stewardsSidebar: () => sidebarData({ bindings: [binding({ needsUser: true })], needs: { count: 1, items: [withUserItem()] } }), + } as never, + }); + await waitFor(() => expect(slot.getByText("Need cluster access")).toBeTruthy()); + expect(slot.getByRole("button", { name: "Details" })).toBeTruthy(); + expect(slot.queryByRole("button", { name: "Approve" })).toBeNull(); + slot.lifecycle.unmount(); + }); + + it("refetches after an action so the row updates without a reload", async () => { + let calls = 0; + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { + stewardsSidebar: () => { + calls += 1; + return sidebarData({ + bindings: [binding({ needsUser: calls === 1 })], + needs: calls === 1 ? { count: 1, items: [questionItem({ choices: ["Stack", "Hold"] })] } : { count: 0, items: [] }, + }); + }, + stewardsAnswerQuestion: () => ({ ok: true, message: "closed" }), + } as never, + }); + await waitFor(() => expect(slot.getByRole("button", { name: "Stack" })).toBeTruthy()); + fireEvent.click(slot.getByRole("button", { name: "Stack" })); + await waitFor(() => expect(slot.queryByRole("button", { name: "Stack" })).toBeNull()); + expect(calls).toBeGreaterThan(1); + slot.lifecycle.unmount(); + }); +}); diff --git a/plugins/stewards/sidebar.test.ts b/plugins/stewards/sidebar.test.ts index b238b049..e5acc527 100644 --- a/plugins/stewards/sidebar.test.ts +++ b/plugins/stewards/sidebar.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { buildSidebar, compareEfforts, isBusy, type SidebarEffort, type SidebarLiveProject, type SidebarLiveThread, type SidebarProjectData } from "./sidebar.js"; +import { buildSidebar, compareBlocked, compareEfforts, compareInflight, deploymentPhrase, effortPhrase, effortSection, effortState, effortTitle, isBusy, type SidebarEffort, type SidebarLiveProject, type SidebarLiveThread, type SidebarProjectData } from "./sidebar.js"; const thread = (over: Partial<SidebarLiveThread> & { id: string }): SidebarLiveThread => ({ projectId: "p1", @@ -17,9 +17,14 @@ const project = (over: Partial<SidebarLiveProject> & { id: string }): SidebarLiv const binding = (over: Partial<SidebarProjectData["bindings"][number]> & { key: string; threadId: string }): SidebarProjectData["bindings"][number] => ({ kind: "ticket", stage: "build", + phase: null, hold: null, + holdBehind: [], blockedOn: null, needsUser: false, + stuck: false, + status: null, + deployment: null, advancedAt: null, workers: [], reviewers: [], @@ -40,12 +45,23 @@ const effort = (over: Partial<SidebarEffort> & { key: string }): SidebarEffort = title: over.key, kind: null, stage: null, + phase: null, hold: null, + holdBehind: [], blockedOn: null, needsUser: false, + stuck: false, + statusActor: null, + statusNextAction: null, + statusAt: null, + deployment: null, + runningWorkers: 0, pinned: false, busy: false, recency: 0, + state: "quiet", + section: "inflight", + phrase: "", children: [], ...over, }); @@ -55,7 +71,7 @@ describe("stewards sidebar grouping", () => { 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" }] })] })], + data: [data({ projectId: "p1", bindings: [binding({ key: "ENG-1", threadId: "thr_steward", workers: [{ threadId: "thr_worker", title: "Implement", status: "running" }] })] })], }); expect(tabs[0]!.efforts).toHaveLength(1); expect(tabs[0]!.efforts[0]!.children).toMatchObject([{ threadId: "thr_worker", role: "worker" }]); @@ -68,7 +84,7 @@ describe("stewards sidebar grouping", () => { 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" }] })], + bindings: [binding({ key: "ENG-1", threadId: "thr_steward", workers: [{ threadId: "thr_worker", title: "Implement", status: "running" }], reviewers: [{ threadId: "thr_reviewer", workerThreadId: "thr_worker" }] })], }), ], }); @@ -98,7 +114,7 @@ describe("stewards sidebar grouping", () => { expect(tabs[0]!.threads[0]!.children).toMatchObject([{ threadId: "thr_child", role: "thread", children: [{ threadId: "thr_fork", role: "thread" }] }]); }); - it("returns stewarded efforts, one-off threads and ops watches as separate lists", () => { + it("returns stewarded efforts, one-off threads and ops monitors as separate lists", () => { const tabs = buildSidebar({ projects: [project({ id: "p1" })], threads: [thread({ id: "thr_steward" }), thread({ id: "thr_ops" }), thread({ id: "thr_oneoff" })], @@ -111,7 +127,7 @@ describe("stewards sidebar grouping", () => { }); expect(tabs[0]!.efforts.map((e) => e.key)).toEqual(["ENG-1"]); expect(tabs[0]!.threads.map((e) => e.key)).toEqual(["thread:thr_oneoff"]); - expect(tabs[0]!.watches.map((e) => e.key)).toEqual(["acme/web"]); + expect(tabs[0]!.monitors.map((e) => e.key)).toEqual(["acme/web"]); }); it("skips a binding whose steward thread is not in the live view", () => { @@ -134,7 +150,7 @@ describe("stewards sidebar grouping", () => { expect(tabs[1]!.isPersonal).toBe(true); }); - it("groups ops bindings under watches, not in flight", () => { + it("groups quiet ops bindings under monitors, not in flight", () => { const tabs = buildSidebar({ projects: [project({ id: "p1" })], threads: [thread({ id: "thr_ticket" }), thread({ id: "thr_ops" })], @@ -146,7 +162,41 @@ describe("stewards sidebar grouping", () => { ], }); expect(tabs[0]!.efforts.map((e) => e.key)).toEqual(["ENG-1"]); - expect(tabs[0]!.watches.map((e) => e.key)).toEqual(["acme/web"]); + expect(tabs[0]!.monitors.map((e) => e.key)).toEqual(["acme/web"]); + }); + + it("moves a blocked or needs-you ops binding into blocked, out of monitors", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_ops_blocked" }), thread({ id: "thr_ops_you" }), thread({ id: "thr_ops_quiet" })], + data: [ + data({ + projectId: "p1", + bindings: [ + binding({ key: "acme/sentry", threadId: "thr_ops_blocked", kind: "ops", stage: null, blockedOn: "a rotation" }), + binding({ key: "acme/deps", threadId: "thr_ops_you", kind: "ops", stage: null, needsUser: true }), + binding({ key: "acme/ns", threadId: "thr_ops_quiet", kind: "ops", stage: null }), + ], + }), + ], + }); + expect(tabs[0]!.monitors.map((e) => e.key)).toEqual(["acme/ns"]); + expect(tabs[0]!.blocked.map((e) => e.key)).toEqual(["acme/deps", "acme/sentry"]); + }); + + it("keeps a blocked non-ops effort out of in flight", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_steward" }), thread({ id: "thr_ok" })], + data: [ + data({ + projectId: "p1", + bindings: [binding({ key: "ENG-1", threadId: "thr_steward", hold: "a freeze", holdBehind: ["ENG-9"] }), binding({ key: "ENG-2", threadId: "thr_ok" })], + }), + ], + }); + expect(tabs[0]!.blocked.map((e) => e.key)).toEqual(["ENG-1"]); + expect(tabs[0]!.efforts.map((e) => e.key)).toEqual(["ENG-2"]); }); }); @@ -166,7 +216,7 @@ describe("stewards sidebar ordering", () => { expect(["idle", "finished", "failed"].some(isBusy)).toBe(false); }); - it("orders a tab's threads and watches with the same comparator", () => { + it("orders a tab's threads and monitors 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 })], @@ -174,4 +224,109 @@ describe("stewards sidebar ordering", () => { }); expect(tabs[0]!.threads.map((e) => e.rootThreadId)).toEqual(["thr_busy", "thr_quiet"]); }); + + it("orders blocked: pinned, then needs-you (yellow) before red, then recency", () => { + const you = effort({ key: "you", needsUser: true, state: "you", recency: 1 }); + const blockedOld = effort({ key: "blocked-old", blockedOn: "x", state: "blocked", recency: 5 }); + const blockedNew = effort({ key: "blocked-new", blockedOn: "y", state: "blocked", recency: 50 }); + const pinned = effort({ key: "pinned", pinned: true, blockedOn: "z", state: "blocked", recency: 0 }); + const ordered = [blockedOld, you, pinned, blockedNew].sort(compareBlocked).map((e) => e.key); + expect(ordered).toEqual(["pinned", "you", "blocked-new", "blocked-old"]); + }); + + it("orders in flight: pinned, then running before quiet, then recency", () => { + const runningOld = effort({ key: "running-old", runningWorkers: 1, state: "running", recency: 1 }); + const quietNew = effort({ key: "quiet-new", recency: 99 }); + const pinned = effort({ key: "pinned", pinned: true, recency: 0 }); + const ordered = [quietNew, runningOld, pinned].sort(compareInflight).map((e) => e.key); + expect(ordered).toEqual(["pinned", "running-old", "quiet-new"]); + }); +}); + +describe("stewards sidebar state, section and phrase (BB-76)", () => { + it("takes the state in precedence order: you › blocked › running › quiet", () => { + // A running effort that also needs you is yellow. + expect(effortState(effort({ key: "a", needsUser: true, blockedOn: "x", runningWorkers: 1 }))).toBe("you"); + expect(effortState(effort({ key: "b", blockedOn: "x", runningWorkers: 1 }))).toBe("blocked"); + expect(effortState(effort({ key: "c", runningWorkers: 1 }))).toBe("running"); + expect(effortState(effort({ key: "d" }))).toBe("quiet"); + }); + + it("treats each block signal as blocked: blockedOn, hold, stuck, and actor = other", () => { + expect(effortState(effort({ key: "a", blockedOn: "a review" }))).toBe("blocked"); + expect(effortState(effort({ key: "b", hold: "a freeze" }))).toBe("blocked"); + expect(effortState(effort({ key: "c", stuck: true }))).toBe("blocked"); + expect(effortState(effort({ key: "d", statusActor: "other", statusNextAction: "the vendor" }))).toBe("blocked"); + }); + + it("counts a busy thread or a running worker as running", () => { + expect(effortState(effort({ key: "a", busy: true }))).toBe("running"); + expect(effortState(effort({ key: "b", runningWorkers: 2 }))).toBe("running"); + }); + + it("puts needs-you and blocked in the blocked section, ops in monitors, the rest in flight", () => { + expect(effortSection(effort({ key: "a", needsUser: true, state: "you" }))).toBe("blocked"); + expect(effortSection(effort({ key: "b", blockedOn: "x", state: "blocked" }))).toBe("blocked"); + expect(effortSection(effort({ key: "c", kind: "ops", state: "quiet" }))).toBe("monitors"); + expect(effortSection(effort({ key: "d", kind: "ticket", state: "running" }))).toBe("inflight"); + }); + + it("phrases every rule, first match wins", () => { + // 1. needs you + expect(effortPhrase(effort({ key: "a", needsUser: true, blockedOn: "x" }))).toBe("needs you"); + // 2. blockedOn + expect(effortPhrase(effort({ key: "b", blockedOn: "bb-gate#88" }))).toBe("blocked on bb-gate#88"); + // 3. hold + expect(effortPhrase(effort({ key: "c", hold: "a freeze", holdBehind: ["BB-57", "BB-61"] }))).toBe("held behind BB-57, BB-61"); + expect(effortPhrase(effort({ key: "d", hold: "a freeze" }))).toBe("on hold"); + // 4. stuck + expect(effortPhrase(effort({ key: "e", stuck: true }))).toBe("stuck"); + // 5. actor = other + expect(effortPhrase(effort({ key: "f", statusActor: "other", statusNextAction: "an owner LGTM" }))).toBe("waiting on an owner LGTM"); + // 6. running workers + expect(effortPhrase(effort({ key: "g", runningWorkers: 2 }))).toBe("2 workers running"); + expect(effortPhrase(effort({ key: "h", runningWorkers: 1 }))).toBe("1 worker running"); + // 7. deployment + expect(effortPhrase(effort({ key: "i", deployment: "merged" }))).toBe("deploying"); + expect(effortPhrase(effort({ key: "j", deployment: "deployed" }))).toBe("deployed"); + expect(effortPhrase(effort({ key: "k", deployment: "failed" }))).toBe("deploy failed"); + // 8. nextAction + expect(effortPhrase(effort({ key: "l", statusNextAction: "wait for the review" }))).toBe("wait for the review"); + // 9. no report + expect(effortPhrase(effort({ key: "m" }))).toBe("no report yet"); + }); + + it("phrases a deployment watch's state", () => { + expect(deploymentPhrase("merged")).toBe("deploying"); + expect(deploymentPhrase("deploying")).toBe("deploying"); + expect(deploymentPhrase("deployed")).toBe("deployed"); + expect(deploymentPhrase("failed")).toBe("deploy failed"); + }); + + it("strips the key prefix so line one shows the key and title without repeating it", () => { + expect(effortTitle("ENG-1: Fix login", "ENG-1")).toBe("Fix login"); + expect(effortTitle("Review acme/web#612: Read metrics", "acme/web#612")).toBe("Read metrics"); + expect(effortTitle("A title that keeps its words", "ENG-1")).toBe("A title that keeps its words"); + expect(effortTitle("Any title", null)).toBe("Any title"); + }); + + it("derives state, section and phrase for every effort a tab builds", () => { + const tabs = buildSidebar({ + projects: [project({ id: "p1" })], + threads: [thread({ id: "thr_you" }), thread({ id: "thr_run" }), thread({ id: "thr_ops" })], + data: [ + data({ + projectId: "p1", + bindings: [ + binding({ key: "ENG-1", threadId: "thr_you", needsUser: true }), + binding({ key: "ENG-2", threadId: "thr_run", workers: [{ threadId: "thr_w", title: "w", status: "running" }] }), + binding({ key: "acme/web", threadId: "thr_ops", kind: "ops", stage: null }), + ], + }), + ], + }); + expect(tabs[0]!.blocked.map((e) => `${e.key}:${e.state}:${e.phrase}`)).toEqual(["ENG-1:you:needs you"]); + expect(tabs[0]!.efforts.map((e) => `${e.key}:${e.state}`)).toEqual(["ENG-2:running"]); + expect(tabs[0]!.monitors.map((e) => `${e.key}:${e.state}:${e.phrase}`)).toEqual(["acme/web:quiet:no report yet"]); + }); }); diff --git a/plugins/stewards/sidebar.ts b/plugins/stewards/sidebar.ts index 7fec6e0e..b71fb936 100644 --- a/plugins/stewards/sidebar.ts +++ b/plugins/stewards/sidebar.ts @@ -1,7 +1,7 @@ // 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. +// the `stewardsSidebar` RPC result, grouping threads into efforts, deriving each +// effort's state / section / phrase, 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 @@ -10,15 +10,27 @@ // for a pre-BB-23 worker whose parent is its steward (BB-23 removed that link, // so it is a fallback, never the rule). +import type { DeployState } from "./deploy.js"; + /** A binding as `stewardsSidebar` reports it. */ export interface SidebarBinding { key: string; kind: string; stage: string | null; + /** The entity's own state, as the playbook's `phases` table names it; null when the binding has none. */ + phase: string | null; threadId: string | null; hold: string | null; + /** Entity keys this hold waits behind. */ + holdBehind: string[]; blockedOn: string | null; needsUser: boolean; + /** An open `stuck` escalation (BB-76): an external wait is a block. */ + stuck: boolean; + /** The status report's actor, next action and timestamp, or null with no report. */ + status: { actor: string; nextAction: string; at: number } | null; + /** The state of the newest deployment watch, or null with none (BB-76). */ + deployment: DeployState | null; advancedAt: number | null; workers: SidebarWorker[]; reviewers: SidebarReviewer[]; @@ -27,6 +39,8 @@ export interface SidebarBinding { export interface SidebarWorker { threadId: string; title: string; + /** The plugin's own worker status, so the running count is of running workers. */ + status: string; } export interface SidebarReviewer { @@ -78,6 +92,12 @@ export interface SidebarChild { children: SidebarChild[]; } +/** The four glyphs, in precedence order: you › blocked › running › quiet. */ +export type SidebarEffortState = "you" | "blocked" | "running" | "quiet"; + +/** Which section an effort belongs to. `ops` bindings are `monitors` unless they need you or are blocked. */ +export type SidebarSection = "blocked" | "inflight" | "monitors"; + /** 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:<id>` for a one-off. */ @@ -88,13 +108,29 @@ export interface SidebarEffort { title: string; kind: string | null; stage: string | null; + /** The entity's own phase, shown on line two; null for ops and one-off threads. */ + phase: string | null; hold: string | null; + holdBehind: string[]; blockedOn: string | null; needsUser: boolean; + stuck: boolean; + statusActor: string | null; + statusNextAction: string | null; + statusAt: number | null; + deployment: DeployState | null; + /** How many of the binding's workers are running (worker-table status). */ + runningWorkers: number; pinned: boolean; busy: boolean; /** The most recent activity anywhere in the effort, epoch ms. */ recency: number; + /** Derived: the glyph. */ + state: SidebarEffortState; + /** Derived: the section it sits in. */ + section: SidebarSection; + /** Derived: line two's status phrase. */ + phrase: string; children: SidebarChild[]; } @@ -102,12 +138,14 @@ export interface SidebarTab { projectId: string; name: string; isPersonal: boolean; - /** In-flight stewarded efforts, ordered. `ops` bindings are in `watches`, one-off threads in `threads`. */ + /** Needs-you (yellow) then blocked (red) efforts: stewarded and ops. */ + blocked: SidebarEffort[]; + /** In-flight stewarded efforts, running before quiet. `ops` bindings are in `monitors`, one-off threads in `threads`. */ efforts: SidebarEffort[]; /** One-off threads (no steward binding), ordered. */ threads: SidebarEffort[]; - /** `ops`, Dependabot and Sentry bindings, grouped in a collapsed row. */ - watches: SidebarEffort[]; + /** `ops`, Dependabot and Sentry bindings that are neither waiting on you nor blocked. */ + monitors: SidebarEffort[]; projectStewardThreadId: string | null; ended: SidebarEnded[]; } @@ -119,6 +157,74 @@ export const isBusy = (status: string): boolean => BUSY.has(status); const parentOf = (t: Pick<SidebarLiveThread, "parentThreadId" | "lifecycleOwnerThreadId">): string | null => t.parentThreadId ?? t.lifecycleOwnerThreadId; +/** Whether a worker or reviewer thread is running: the binding is in flight, not quiet. */ +export const isRunning = (e: Pick<SidebarEffort, "busy" | "runningWorkers">): boolean => e.busy || e.runningWorkers > 0; + +/** + * The effort's glyph, first match wins (BB-76): + * needs you › blocked › running › quiet. An external wait (`actor = other`) + * is a block, and a running effort that also needs you is yellow. + */ +export function effortState(e: SidebarEffort): SidebarEffortState { + if (e.needsUser) return "you"; + if (e.blockedOn !== null || e.hold !== null || e.stuck || e.statusActor === "other") return "blocked"; + if (isRunning(e)) return "running"; + return "quiet"; +} + +/** The section the effort sits in: blocked (you or red), monitors for a quiet/running `ops`, else in flight. */ +export function effortSection(e: SidebarEffort): SidebarSection { + if (e.state === "you" || e.state === "blocked") return "blocked"; + return e.kind === "ops" ? "monitors" : "inflight"; +} + +/** A deployment watch's state, in words: the three the row shows. */ +export function deploymentPhrase(state: DeployState): string { + if (state === "deployed") return "deployed"; + if (state === "failed") return "deploy failed"; + return "deploying"; +} + +/** + * Line two's status phrase, first match wins (BB-76): + * needs you › blockedOn › hold › stuck › actor=other › running › deployment › nextAction › no report. + */ +export function effortPhrase(e: SidebarEffort): string { + if (e.needsUser) return "needs you"; + if (e.blockedOn !== null) return `blocked on ${e.blockedOn}`; + if (e.hold !== null) return e.holdBehind.length > 0 ? `held behind ${e.holdBehind.join(", ")}` : "on hold"; + if (e.stuck) return "stuck"; + if (e.statusActor === "other") return `waiting on ${e.statusNextAction ?? "the other party"}`; + if (isRunning(e)) { + const n = e.runningWorkers; + return `${n} worker${n === 1 ? "" : "s"} running`; + } + if (e.deployment !== null) return deploymentPhrase(e.deployment); + if (e.statusNextAction !== null) return e.statusNextAction; + return "no report yet"; +} + +/** Fill in the derived fields. Grouping calls this once the effort's children are attached. */ +function derive(e: SidebarEffort): SidebarEffort { + e.state = effortState(e); + e.section = effortSection(e); + e.phrase = effortPhrase(e); + return e; +} + +/** + * The title with the key prefix stripped, so line one can show the key and the + * title without repeating it. Steward threads are titled `<key>: <title>`, and + * a review `<Review key>: <title>`; the key is shown separately either way. + */ +export function effortTitle(displayTitle: string, key: string | null): string { + if (key === null) return displayTitle; + for (const prefix of [`Review ${key}: `, `${key}: `]) { + if (displayTitle.startsWith(prefix)) return displayTitle.slice(prefix.length); + } + return displayTitle; +} + /** * bb's precedence for its own list: pinned first, then threads that need the * user, then busy threads (`starting` / `active` / `stopping`), then most @@ -132,6 +238,26 @@ export function compareEfforts(a: SidebarEffort, b: SidebarEffort): number { return a.title.localeCompare(b.title); } +/** Blocked: pinned first, then needs-you (yellow) before red, then by recency. */ +export function compareBlocked(a: SidebarEffort, b: SidebarEffort): number { + if (a.pinned !== b.pinned) return a.pinned ? -1 : 1; + const aYou = a.state === "you" ? 0 : 1; + const bYou = b.state === "you" ? 0 : 1; + if (aYou !== bYou) return aYou - bYou; + if (b.recency !== a.recency) return b.recency - a.recency; + return a.title.localeCompare(b.title); +} + +/** In flight: pinned first, then running (blue) before quiet (grey), then by recency. */ +export function compareInflight(a: SidebarEffort, b: SidebarEffort): number { + if (a.pinned !== b.pinned) return a.pinned ? -1 : 1; + const aRun = a.state === "running" ? 0 : 1; + const bRun = b.state === "running" ? 0 : 1; + if (aRun !== bRun) return aRun - bRun; + 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[]; @@ -177,12 +303,23 @@ function buildTab(project: SidebarLiveProject, data: SidebarProjectData | undefi title: root.displayTitle, kind: b.kind, stage: b.stage, + phase: b.phase, hold: b.hold, + holdBehind: b.holdBehind, blockedOn: b.blockedOn, needsUser: b.needsUser, + stuck: b.stuck, + statusActor: b.status?.actor ?? null, + statusNextAction: b.status?.nextAction ?? null, + statusAt: b.status?.at ?? null, + deployment: b.deployment, + runningWorkers: b.workers.filter((w) => w.status === "running").length, pinned: root.isPinned, busy: isBusy(root.status), recency: root.updatedAt, + state: "quiet", + section: "inflight", + phrase: "", children: [], }; const byThread = new Map<string, SidebarChild>(); @@ -212,6 +349,7 @@ function buildTab(project: SidebarLiveProject, data: SidebarProjectData | undefi byThread.set(thread.id, child); touch(effort, thread); } + derive(effort); } // The fallback the RPC records do not cover: a pre-BB-23 worker whose parent @@ -236,6 +374,8 @@ function buildTab(project: SidebarLiveProject, data: SidebarProjectData | undefi changed = true; } } + // A fallback child can flip busy after the effort was derived. + for (const effort of efforts) derive(effort); // One-off efforts: everything left, treed by parent / lifecycle owner. const remaining = threads.filter((t) => !claimed.has(t.id) && t.id !== stewardThreadId); @@ -260,12 +400,23 @@ function buildTab(project: SidebarLiveProject, data: SidebarProjectData | undefi title: root.displayTitle, kind: null, stage: null, + phase: null, hold: null, + holdBehind: [], blockedOn: null, needsUser: false, + stuck: false, + statusActor: null, + statusNextAction: null, + statusAt: null, + deployment: null, + runningWorkers: 0, pinned: root.isPinned, busy: isBusy(root.status), recency: root.updatedAt, + state: "quiet", + section: "inflight", + phrase: "", children: [], }; const visit = (t: SidebarLiveThread): SidebarChild => { @@ -273,16 +424,19 @@ function buildTab(project: SidebarLiveProject, data: SidebarProjectData | undefi 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); + efforts.push(derive(effort)); } + const nonOps = efforts.filter((e) => e.bindingKey !== null && e.kind !== "ops"); + const ops = efforts.filter((e) => e.kind === "ops"); return { projectId: project.id, name: project.name, isPersonal: project.isPersonal, - efforts: efforts.filter((e) => e.bindingKey !== null && e.kind !== "ops").sort(compareEfforts), + blocked: [...nonOps, ...ops].filter((e) => e.section === "blocked").sort(compareBlocked), + efforts: nonOps.filter((e) => e.section === "inflight").sort(compareInflight), threads: efforts.filter((e) => e.bindingKey === null).sort(compareEfforts), - watches: efforts.filter((e) => e.kind === "ops").sort(compareEfforts), + monitors: ops.filter((e) => e.section === "monitors").sort(compareEfforts), projectStewardThreadId: stewardThreadId, ended: data?.ended ?? [], }; From c43d50d24270a2b43ec88ba72acafc588c6cefba Mon Sep 17 00:00:00 2001 From: Dylan Trotter <dylan@bitcomplete.io> Date: Tue, 27 Oct 2026 02:01:51 +0000 Subject: [PATCH 2/2] stewards: fall through the running phrase when no worker runs, and cover the inline refusal (BB-76) --- plugins/stewards/DESIGN.md | 3 ++- plugins/stewards/sidebar-app.test.tsx | 14 ++++++++++++++ plugins/stewards/sidebar.test.ts | 3 +++ plugins/stewards/sidebar.ts | 5 ++++- 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 59efc344..744e8464 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -1470,7 +1470,8 @@ row is the grey ring. else `on hold`; `stuck` for an open stuck escalation; `waiting on <nextAction>` when the status actor is `other` (an external wait is a block); `N worker(s) running` counting only workers whose worker-table status is -`running`; the newest deployment watch's state (`deploying`, `deployed`, +`running` (a busy steward or reviewer with no running worker falls through, +rather than reading `0 workers running`); the newest deployment watch's state (`deploying`, `deployed`, `deploy failed`); the status `nextAction`; otherwise `no report yet`. The phrase's colour follows the glyph's. `sidebar.ts` derives `state`, `section` and `phrase` as pure functions and sorts by the section rules; `sidebar.test.ts` diff --git a/plugins/stewards/sidebar-app.test.tsx b/plugins/stewards/sidebar-app.test.tsx index 150a2c21..9ce11424 100644 --- a/plugins/stewards/sidebar-app.test.tsx +++ b/plugins/stewards/sidebar-app.test.tsx @@ -568,6 +568,20 @@ describe("the inline needs-you actions (BB-76)", () => { slot.lifecycle.unmount(); }); + it("shows the server's refusal in the row and re-enables the buttons", async () => { + const slot = await renderSidebar({ + sidebarThreads: { projects, threads: [thread({ id: "thr_steward", displayTitle: "ENG-1: Fix login" })] }, + rpc: { + stewardsSidebar: () => sidebarData({ bindings: [binding({ needsUser: true })], needs: { count: 1, items: [needItem()] } }), + stewardsNeedAction: () => ({ ok: false, message: "the owner must approve first" }), + } as never, + }); + fireEvent.click(await waitFor(() => slot.getByRole("button", { name: "Approve" }))); + await waitFor(() => expect(slot.getByText("the owner must approve first")).toBeTruthy()); + expect((slot.getByRole("button", { name: "Approve" }) as HTMLButtonElement).disabled).toBe(false); + slot.lifecycle.unmount(); + }); + it("refetches after an action so the row updates without a reload", async () => { let calls = 0; const slot = await renderSidebar({ diff --git a/plugins/stewards/sidebar.test.ts b/plugins/stewards/sidebar.test.ts index e5acc527..e78ce060 100644 --- a/plugins/stewards/sidebar.test.ts +++ b/plugins/stewards/sidebar.test.ts @@ -286,6 +286,9 @@ describe("stewards sidebar state, section and phrase (BB-76)", () => { // 6. running workers expect(effortPhrase(effort({ key: "g", runningWorkers: 2 }))).toBe("2 workers running"); expect(effortPhrase(effort({ key: "h", runningWorkers: 1 }))).toBe("1 worker running"); + // A busy steward or reviewer with no running worker falls through, not "0 workers running". + expect(effortPhrase(effort({ key: "g2", busy: true, statusNextAction: "a reviewer is checking" }))).toBe("a reviewer is checking"); + expect(effortPhrase(effort({ key: "g3", busy: true }))).toBe("no report yet"); // 7. deployment expect(effortPhrase(effort({ key: "i", deployment: "merged" }))).toBe("deploying"); expect(effortPhrase(effort({ key: "j", deployment: "deployed" }))).toBe("deployed"); diff --git a/plugins/stewards/sidebar.ts b/plugins/stewards/sidebar.ts index b71fb936..1cbc40fe 100644 --- a/plugins/stewards/sidebar.ts +++ b/plugins/stewards/sidebar.ts @@ -195,7 +195,10 @@ export function effortPhrase(e: SidebarEffort): string { if (e.hold !== null) return e.holdBehind.length > 0 ? `held behind ${e.holdBehind.join(", ")}` : "on hold"; if (e.stuck) return "stuck"; if (e.statusActor === "other") return `waiting on ${e.statusNextAction ?? "the other party"}`; - if (isRunning(e)) { + // A running worker or reviewer paints the blue ring, but the count is of + // running workers: a busy steward or reviewer with no running worker falls + // through rather than reading "0 workers running". + if (e.runningWorkers > 0) { const n = e.runningWorkers; return `${n} worker${n === 1 ? "" : "s"} running`; }