diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 6f82c8688b..a89547c4d3 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -97,6 +97,18 @@ The left rail groups pages into Memory, Activity and Sources. Every page has its | **Repositories** | `/repositories` | Indexed code repositories, each with Health, Explore, PR packs and Access tabs, and the org's trackers; a branch's admin re-indexes it after one of its commits. An opened repository lists its documents and their sources, each with its last sync; a source's name opens its settings, sync state and the documents it wrote (`knowledge.source.inspect`), and a caller with the role the [sources table](knowledge.md#document-sources) names adds, checks, syncs, rotates and retires a source there. See [code index](code-index/overview.md) and [tracker](tracker/overview.md). | | **Settings** | `/settings` | **Tokens** (one form for every token: what it reads, where it saves, its expiry; the setup for each MCP client or a script; the list, with what each token reads); **Memory** (`?tab=memory`: patterns never to save, each with a sweep of the memories it already matches, seeding memory from a document, and the webhooks that receive its memory changes and their deliveries); **Structure** (`?tab=structure`, on a memory namespace: the record schemas, each one's records and disagreements with the record each disagreement superseded, the profile schema, the graph ontology and the categories; an admin registers and approves schemas, sets or clears the profile schema and accepts and adds ontology terms, a writer adds categories); and **Models & keys** for a platform admin. | +In the Memory group, **Review queue** (`/admin/review_queue`) is a stable rail entry for +every caller who may view review work on a memory namespace (any role that reaches +`conflicts.list` or `memory.proposals`, both viewer-level), so Review stays reachable when +its queue is empty or a count fails — the phone's More sheet lists the same entry. Its badge +counts review items waiting for a person, open conflicts plus pending proposals, read as +bounded server-side counts (`count_only`, no row bodies, uncapped by any page size), labeled +per kind for screen readers; when only proposals wait, the entry links straight to the +Proposals tab (`?tab=proposals`). Inside the queue, the Conflicts and Proposals tabs carry +their own counts, and a proposal-only queue opens on Proposals. A count whose read fails is +shown as unknown — never as zero. The same URL also resolves as an admin-drawer entry that +appears on its own while something waits. + Three views are reached from elsewhere rather than the rail: **Namespaces in your org** (`/spaces`, the namespaces you manage and the org's public namespaces to join, with each one's [guide](namespaces-and-sharing.md#a-namespaces-guide) summary, and the guide itself for @@ -435,25 +447,27 @@ Admins of the current namespace get a drawer with the Review and Observe groups; platform admins also get Access, and platform admins Deployment. A viewer never sees an entry that would answer 403. -| Group | Page | URL | What it is for | -| ------- | ---------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Review | **Review queue** | `/admin/review_queue` | Conflicts (pairs of memories that disagree, each with a suggested decision on request, except a sensitive one), learnings proposed for promotion, memories Loom retired on its own (Auto-resolved, each with an Undo), exceptions (the allowlist of pairs that may coexist), proposals (facts on trial, accepted or rejected), and duplicate memories and documents with the namespace-wide repairs. Shown in the drawer only while a conflict waits or Loom retired a memory in the last 30 days; the URL always resolves. See [conflicts and refusal](memory/conflicts-and-refusal.md). | -| Review | **Guardrails** | `/admin/guardrails` | Blacklist patterns: content Loom should never store, each with a sweep that deletes the stored memories it already matches; for an org admin, the org's and the namespace's extraction rules and the org's model-call switch. | -| Review | **Policies** | `/admin/policies` | History policy rules, a dry run of a hypothetical call, and the decision ledger. | -| Observe | **Health** | `/admin/health` | Worker status and how agents in the namespace spend their calls; the namespace's memory report, search gates and recent extractions; an admin's repairs (apply expiry, re-embed, remove an extractor's facts, roll back, snapshot and restore); an org admin's projection failures, retried or dismissed. | -| Observe | **Audit log** | `/admin/activity` | The audit feed, one readable line per event; the Erasures tab lists erasures with each one's details and, by role, erases or exports one namespace or one user; the Exposure tab shows which readers read the namespace's memories and one user's owner report. | -| Observe | **Flow** | `/flow` | Read-only: where memories flow — writes and recalls, cross-namespace reach, producer and consumer agents, memberships; collections and repositories are listed apart from the namespaces. | -| Observe | **Usage** | `/admin/usage` | LLM and embedding cost by day, operation, agent or user, the namespace's daily cap, and on **Coding agents** the coding agents' own model spend. | -| Observe | **Agents** | `/admin/agents` | Which clients connected in a window (`agents.connected`); confirms a new MCP connection works. A namespace admin can forget every memory one agent holds there. | -| Access | **Users** | `/admin/users` | Org and platform admins only: every subject, their grants (namespaces, collections and repositories) and roles, last activity, and releasing a namespace whose owner lost their password. | - -Badges draw attention without a rail entry: the Review queue appears with its conflict -count, or with no count when there is no open conflict but Loom retired a memory on its -own in the last 30 days (the Auto-resolved tab), Usage warns when the namespace is over +| Group | Page | URL | What it is for | +| ------- | ---------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Review | **Review queue** | `/admin/review_queue` | Conflicts (pairs of memories that disagree, each with a suggested decision on request, except a sensitive one), learnings proposed for promotion, memories Loom retired on its own (Auto-resolved, each with an Undo), exceptions (the allowlist of pairs that may coexist), proposals (facts on trial, accepted or rejected), and duplicate memories and documents with the namespace-wide repairs. Also a stable rail entry in the Memory group for anyone who may view review work; in the drawer it additionally appears on its own while a review item waits or Loom retired a memory in the last 30 days. The URL always resolves, and `?tab=` names the category to open. See [conflicts and refusal](memory/conflicts-and-refusal.md). | +| Review | **Guardrails** | `/admin/guardrails` | Blacklist patterns: content Loom should never store, each with a sweep that deletes the stored memories it already matches; for an org admin, the org's and the namespace's extraction rules and the org's model-call switch. | +| Review | **Policies** | `/admin/policies` | History policy rules, a dry run of a hypothetical call, and the decision ledger. | +| Observe | **Health** | `/admin/health` | Worker status and how agents in the namespace spend their calls; the namespace's memory report, search gates and recent extractions; an admin's repairs (apply expiry, re-embed, remove an extractor's facts, roll back, snapshot and restore); an org admin's projection failures, retried or dismissed. | +| Observe | **Audit log** | `/admin/activity` | The audit feed, one readable line per event; the Erasures tab lists erasures with each one's details and, by role, erases or exports one namespace or one user; the Exposure tab shows which readers read the namespace's memories and one user's owner report. | +| Observe | **Flow** | `/flow` | Read-only: where memories flow — writes and recalls, cross-namespace reach, producer and consumer agents, memberships; collections and repositories are listed apart from the namespaces. | +| Observe | **Usage** | `/admin/usage` | LLM and embedding cost by day, operation, agent or user, the namespace's daily cap, and on **Coding agents** the coding agents' own model spend. | +| Observe | **Agents** | `/admin/agents` | Which clients connected in a window (`agents.connected`); confirms a new MCP connection works. A namespace admin can forget every memory one agent holds there. | +| Access | **Users** | `/admin/users` | Org and platform admins only: every subject, their grants (namespaces, collections and repositories) and roles, last activity, and releasing a namespace whose owner lost their password. | + +Badges draw attention on their entries: the Review queue appears with its review-item +count — open conflicts plus pending proposals, a partial count labeled "at least" — or +with no count when nothing waits but Loom retired a memory on its own in the last 30 days +(the Auto-resolved tab), Usage warns when the namespace is over its 24-hour cap, Agents counts clients new in the last 24 hours. The header carries a task bell (triage and blocked-on-person items) and a pending-approvals bell (grant requests the -person can decide). The phone's More sheet lists the same admin entries with the same badges; a -badge whose read fails is hidden. +person can decide). The phone's More sheet lists the same entries with the same badges; a +badge whose read fails is hidden, and a remembered badge answer is cached per org, +namespace, principal and role, so it never crosses an account or permission boundary. ## Operations the dashboard uses diff --git a/docs/reference/operations/memory.md b/docs/reference/operations/memory.md index 97e81689b2..eeb860a237 100644 --- a/docs/reference/operations/memory.md +++ b/docs/reference/operations/memory.md @@ -1564,11 +1564,12 @@ List facts on trial (written with memory.set proposed=true) with the graded runs | `tags` | `list[str]` | *(computed)* | Only proposals carrying any of these tags; empty = no tag filter. | | `only` | `Literal['', 'ready']` | `''` | `ready` keeps only proposals the policy thresholds would decide now (accept or reject); "" lists every proposal. | | `limit` | `int` | `50` | At most this many proposals returned, newest first. | +| `count_only` | `bool` | `False` | A badge or a tab count needs the number, not the rows. | | Output field | Type | Meaning | | --- | --- | --- | | `proposals` | `list[MemoryProposal]` | The proposals in scope, newest first, with graded counts and `ready`. | -| `total` | `int` | Proposals in scope before `only` and `limit`. | +| `total` | `int` | Proposals in scope before `only` and `limit` — on a listing, capped by the scan cap; on a `count_only` call, the full uncapped in-scope count. | | `policy` | `ProposalPolicy` | The namespace's proposal policy: `mode` (manual / auto) and thresholds. | ## `memory.provenance` diff --git a/frontend/e2e/navigation.spec.ts b/frontend/e2e/navigation.spec.ts index 506b1418b2..93abd4eaa2 100644 --- a/frontend/e2e/navigation.spec.ts +++ b/frontend/e2e/navigation.spec.ts @@ -30,7 +30,9 @@ test("the collapsed rail reads the review-queue and agents counts in the link na await page.route("**/v1/conflicts.list", (r) => r.fulfill({ json: { rows: [], total: 3 } })); await page.route("**/v1/agents.connected", (r) => r.fulfill({ json: { new_count: 2 } })); await page.goto("/memories"); - await expect(page.getByRole("link", { name: "Review queue, 3" })).toBeVisible(); + // The rail shows the Review queue twice — its stable Memory entry and the admin entry + // when items wait — so the count is read from the first of them. + await expect(page.getByRole("link", { name: "Review queue, 3" }).first()).toBeVisible(); await expect(page.getByRole("link", { name: "Agents, 2" })).toBeVisible(); }); diff --git a/frontend/e2e/route-budget.spec.ts b/frontend/e2e/route-budget.spec.ts index 5f76ca21af..c93df4d9b7 100644 --- a/frontend/e2e/route-budget.spec.ts +++ b/frontend/e2e/route-budget.spec.ts @@ -11,10 +11,11 @@ test.beforeAll(({ browser }, testInfo) => warmUp(browser, testInfo)); const LCP_BUDGET_MS = 2000; const LONG_TASK_BUDGET_MS = 1500; -// Every route reads at most 12 times, the sidebar's Auto-resolved audit.list included -// (Settings, Conversations, Tasks, Review queue and Usage). The budget is that ceiling -// plus one read of headroom, so a second new read on any route fails here. -const CALL_BUDGET = 13; +// Every route reads at most 13 times, the sidebar's Auto-resolved audit.list and pending +// proposal count included (Settings, Conversations, Tasks, Review queue and Usage). The +// budget is that ceiling plus one read of headroom, so a second new read on any route +// fails here. +const CALL_BUDGET = 14; const ROUTES: Array<[string, string]> = [ ["Memories", "/memories"], diff --git a/frontend/e2e/shell-layout.spec.ts b/frontend/e2e/shell-layout.spec.ts index 64fefb54bd..3fbc4b938b 100644 --- a/frontend/e2e/shell-layout.spec.ts +++ b/frontend/e2e/shell-layout.spec.ts @@ -27,7 +27,12 @@ for (const width of [1400, 375]) { const current = page.locator( "main [aria-current='page'], main [role='tab'][aria-selected='true'], main [aria-label='Show the documents of']", ); - const tab = (await current.count()) > 0 ? (await current.first().textContent())?.trim() : undefined; + // A tab that carries a count reads "Conflicts (2)"; the document title names the + // tab without the count, so the expected title strips it. + const tab = + (await current.count()) > 0 + ? (await current.first().textContent())?.trim().replace(/\s*\(\d+\)$/, "") + : undefined; await expect(page).toHaveTitle(tab && tab !== h1 ? `${tab} · ${h1} · Loom` : `${h1} · Loom`); // Click UI draws an icon, a badge and an ellipsis as a
: none sits in a

. const blocksInText = await page.evaluate(() => diff --git a/frontend/src/App.boot.test.tsx b/frontend/src/App.boot.test.tsx index 51294a7a53..bcc49c11fb 100644 --- a/frontend/src/App.boot.test.tsx +++ b/frontend/src/App.boot.test.tsx @@ -596,7 +596,10 @@ describe("a link's namespace", () => { expect(calls.some((c) => c.body?.namespace === "group-b-shared")).toBe(false); expect( calls.filter((c) => c.path.startsWith("memory.")).map((c) => ({ path: c.path, namespace: c.body?.namespace })), - ).toEqual([{ path: "memory.auto_retirements", namespace: NS }]); + ).toEqual([ + { path: "memory.proposals", namespace: NS }, + { path: "memory.auto_retirements", namespace: NS }, + ]); expect(localStorage.getItem("loom_namespace_v1")).toBe(NS); expect(savedDefault()).toBe(false); // Continue: the page the link asked for, on the namespace the picker shows. @@ -642,7 +645,10 @@ describe("a link's namespace", () => { expect(calls.some((c) => c.body?.namespace === "joined")).toBe(false); expect( calls.filter((c) => c.path.startsWith("memory.")).map((c) => ({ path: c.path, namespace: c.body?.namespace })), - ).toEqual([{ path: "memory.auto_retirements", namespace: NS }]); + ).toEqual([ + { path: "memory.proposals", namespace: NS }, + { path: "memory.auto_retirements", namespace: NS }, + ]); }); it("when the membership read fails, a reload still opens the saved pick: the server answers its reads", async () => { diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f72cb6ce7c..18442e2ea3 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -48,8 +48,6 @@ import { Sidebar } from "./layout/Sidebar"; import { Header } from "./layout/Header"; import { MobileNav } from "./layout/MobileNav"; import { ToastViewport, toast, toastError } from "./components/Toast"; -import { ConfirmViewport } from "./components/ConfirmDialog"; -import { PendingRequestBanner } from "./components/PendingRequestBanner"; import { assistantAddress, assistantPopstate, @@ -116,6 +114,13 @@ const ProfileSectionDialog = lazy(() => ); const TokenGate = lazy(() => import("./flows/TokenGate").then((m) => ({ default: m.TokenGate }))); const LinkTokenConfirm = lazy(() => import("./flows/TokenGate").then((m) => ({ default: m.LinkTokenConfirm }))); +// The confirm dialog and the pending-request banner open on demand, not at boot, so their +// chunks load on the first open, not with the shell (keeps the index chunk inside its +// bundle budget). +const ConfirmViewport = lazy(() => import("./components/ConfirmDialog").then((m) => ({ default: m.ConfirmViewport }))); +const PendingRequestBanner = lazy(() => + import("./components/PendingRequestBanner").then((m) => ({ default: m.PendingRequestBanner })), +); // The expired-session card's chunk is fetched as the app loads, from the build that served // it: it shows on a long-lived tab, the one most likely to predate a deploy, and a chunk // first asked for then would be gone and its stale-chunk reload would lose the page. @@ -580,7 +585,9 @@ export default function App() { location.reload()} reason={gateReason} ssoAsked={ssoAsked} /> - + + + ); } @@ -634,7 +641,9 @@ export default function App() { - + + + {/* Keyed by view so each navigation replays the fade-in, and the no-access page is a page of its own: leaving it mounts the view afresh, never under the hidden old page. `h-full` @@ -699,7 +708,9 @@ export default function App() { ) : null } /> - + + +

); } diff --git a/frontend/src/api/review.test.ts b/frontend/src/api/review.test.ts index cf9438b762..65de76292c 100644 --- a/frontend/src/api/review.test.ts +++ b/frontend/src/api/review.test.ts @@ -1,5 +1,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { collapseMemoryDuplicates, consolidateMemories, listMemoryDuplicates, listProposals } from "./review"; +import { + collapseMemoryDuplicates, + consolidateMemories, + countPendingProposals, + listMemoryDuplicates, + listProposals, +} from "./review"; afterEach(() => { vi.unstubAllGlobals(); @@ -30,3 +36,23 @@ describe("review requests", () => { expect(sent.get("memory.proposals")).toMatchObject({ ...scope, limit: 100 }); }); }); + +describe("the pending-proposal count", () => { + it("asks for a bounded server-side count (count_only, one row's worth of shape), not a page of bodies", async () => { + const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => Response.json({ total: 7 })); + vi.stubGlobal("fetch", fetchMock); + const n = await countPendingProposals(scope); + expect(n).toBe(7); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe("/v1/memory.proposals"); + expect(JSON.parse(String(init?.body))).toMatchObject({ ...scope, limit: 1, count_only: true }); + }); + + it("answers null — unknown, never a false zero — when the answer carries no number", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async () => Response.json({})), + ); + expect(await countPendingProposals(scope)).toBeNull(); + }); +}); diff --git a/frontend/src/api/review.ts b/frontend/src/api/review.ts index 274bc73fb7..208ddbfa00 100644 --- a/frontend/src/api/review.ts +++ b/frontend/src/api/review.ts @@ -186,6 +186,20 @@ export async function listProposals( ); } +/** The pending proposals of the namespace — one bounded server-side `count()` + * (`count_only`), no row bodies and no scan cap, so the number matches the whole + * authorized queue, not the first page. Accepted and rejected proposals are not + * pending and never counted. `null` when the answer carries no number: unknown, + * never a false zero. */ +export async function countPendingProposals(id: Scope, opts: RequestOpts = {}): Promise { + const r = await post<{ total?: number | null }>( + "/v1/memory.proposals", + { org: id.org, namespace: id.namespace, limit: 1, count_only: true }, + opts.signal, + ); + return typeof r.total === "number" ? r.total : null; +} + export async function decideProposals( id: Scope, keys: string[], diff --git a/frontend/src/callBudget.test.tsx b/frontend/src/callBudget.test.tsx index aa163f413a..5610cacee2 100644 --- a/frontend/src/callBudget.test.tsx +++ b/frontend/src/callBudget.test.tsx @@ -188,6 +188,8 @@ const BUDGET: Record JSX.Element; view: View; allow: Rec // The task inbox bell asks for counts once per two minutes. allow: { "/v1/conflicts.list": 1, + // One bounded count (count_only, no rows): pending proposals in the Review queue's badge. + "/v1/memory.proposals": 1, // Fifty retirement records: whether the Review queue's Auto-resolved tab has anything. "/v1/memory.auto_retirements": 1, "/v1/cost.budget_status": 1, diff --git a/frontend/src/layout/Header.tsx b/frontend/src/layout/Header.tsx index b97d9b7a86..4c8f6cf72b 100644 --- a/frontend/src/layout/Header.tsx +++ b/frontend/src/layout/Header.tsx @@ -19,8 +19,12 @@ const AddDocumentDialog = lazy(() => ); const loadHeaderSearch = () => import("../components/HeaderSearch"); const HeaderSearch = lazy(() => loadHeaderSearch().then((m) => ({ default: m.HeaderSearch }))); -import { PendingApprovalsBell } from "../components/PendingApprovalsBell"; -import { TaskInboxBell } from "../components/TaskInboxBell"; +// The bells poll on an interval and open their lists on click, so their chunks load with +// the header's paint, not into the boot chunk (keeps the index chunk inside its budget). +const PendingApprovalsBell = lazy(() => + import("../components/PendingApprovalsBell").then((m) => ({ default: m.PendingApprovalsBell })), +); +const TaskInboxBell = lazy(() => import("../components/TaskInboxBell").then((m) => ({ default: m.TaskInboxBell }))); import { IconButton } from "../components/IconButton"; import { Unavailable } from "../components/ui"; import { Tip } from "../components/ui/Tooltip"; @@ -182,10 +186,14 @@ export function Header() { {/* Pending-approvals bell: surfaces grant requests on namespaces the user is admin of. Counts updated every 30s. */} - + + + {/* Task inbox bell: review items and blocked tasks in this namespace's inboxes. One task.counts call per two minutes. */} - + + + {whoami && ( { - // The sheet shows the rail's own groups; the two primary tabs are left out of theirs, - // and Settings closes the list. An unlabelled rail group (Profile) joins the first - // labelled one on the phone rather than heading a one-item group of its own. + // The sheet shows the rail's own groups — including the Review queue entry the rail + // adds for a caller who may view review work, so the phone exposes the same entry; + // the two primary tabs are left out of theirs, and Settings closes the list. An + // unlabelled rail group (Profile) joins the first labelled one on the phone rather + // than heading a one-item group of its own. const groups: Array<{ group: string; items: NavItem[] }> = []; let carry: NavItem[] = []; - for (const g of RAIL_GROUPS) { + for (const g of railGroups(whoami, mine, namespace, badges)) { const items = [...carry, ...g.items.filter((m) => !PRIMARY_IDS.includes(m.id))]; if (!g.label) { carry = items; @@ -48,7 +50,7 @@ export function mobileMoreItems( * out), then every route the sidebar has, in its groups. */ export default function MoreSheet({ onClose }: { onClose: () => void }) { const view = useStore((s) => s.view); - const setView = useStore((s) => s.setView); + const navigate = useStore((s) => s.navigate); const whoami = useStore((s) => s.whoami); const myNamespaces = useStore((s) => s.myNamespaces); const namespace = useStore((s) => s.identity?.namespace ?? ""); @@ -109,17 +111,19 @@ export default function MoreSheet({ onClose }: { onClose: () => void }) {
{g.items.map((m) => { const active = view === m.id || (m.id === "setup" && view === "connected-accounts"); + const href = m.query ? `${viewHref(m.id)}?${new URLSearchParams(m.query).toString()}` : viewHref(m.id); return ( { if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; e.preventDefault(); - setView(m.id); + navigate(m.id, m.query ? { query: m.query } : {}); onClose(); }} aria-current={active ? "page" : undefined} + aria-label={m.badgeLabel ? `${m.label}, ${m.badgeLabel}` : undefined} className={`flex flex-col items-center justify-center gap-1.5 py-3 rounded-sm transition-colors no-underline hover:no-underline text-text ${ active ? `${ACTIVE} font-medium` : "bg-surface-2 hover:bg-surface-3" }`} diff --git a/frontend/src/layout/Sidebar.nav.test.ts b/frontend/src/layout/Sidebar.nav.test.ts index d82bf5239b..a9ab5a1d50 100644 --- a/frontend/src/layout/Sidebar.nav.test.ts +++ b/frontend/src/layout/Sidebar.nav.test.ts @@ -1,19 +1,22 @@ import { describe, expect, it } from "vitest"; -import type { MyNamespaceEntry } from "../api"; +import type { MyNamespaceEntry, WhoAmI } from "../api"; import { ADMIN_BASE, ADMIN_GROUPS, MAIN, RAIL_GROUPS, SETTINGS_ITEM, + adminItems, groupAdminItems, isDrawerView, operatorItems, + railGroups, + reviewNavItem, scopeHint, type NavItem, } from "./Sidebar"; import { mobileMoreItems } from "./MobileMore"; -import { ALL_VIEWS } from "../lib/state"; +import { ALL_VIEWS, type AdminBadges } from "../lib/state"; import { must } from "../test/must"; // Flow (route id "sharing") is an operator's view of the whole namespace — it lives in @@ -140,3 +143,107 @@ describe("operator entries", () => { expect(isDrawerView("admin:settings")).toBe(true); }); }); + +describe("the Review queue's stable rail entry", () => { + const badges = (conflicts: number | null, pendingProposals: number | null): AdminBadges => ({ + conflicts, + pendingProposals, + autoResolved: false, + overCap: false, + newAgents: 0, + }); + + it("sits in the Memory group for any role that may view review work, whatever the counts", () => { + for (const who of [admin, writer, { ...writer, roles: ["VIEWER"] } as WhoAmI]) { + for (const role of ["admin", "writer", "viewer"] as const) { + const groups = railGroups(who, [row(role)], NS, null); + expect(groups.map((g) => g.label)).toEqual([null, "Memory", "Activity", "Sources"]); + expect(groups[1].items.map((i) => i.id)).toEqual(["memories", "knowledge", "sessions", "admin:review_queue"]); + } + } + // The static arrays the phone's primary tabs read are unchanged. + expect(MAIN.map((m) => m.id)).not.toContain("admin:review_queue"); + }); + + it("is absent when the role is unknown, and on a non-memory namespace", () => { + expect(railGroups(writer, null, NS, null).flatMap((g) => g.items.map((i) => i.id))).not.toContain( + "admin:review_queue", + ); + expect(railGroups(writer, [row("writer")], "", null).flatMap((g) => g.items.map((i) => i.id))).not.toContain( + "admin:review_queue", + ); + // A collection name is not a memory namespace. + expect( + railGroups(writer, [row("writer")], "collection:docs", null).flatMap((g) => g.items.map((i) => i.id)), + ).not.toContain("admin:review_queue"); + }); + + it("the phone's More sheet gets the same entry, in its Memory group, badge and all", () => { + const sheet = mobileMoreItems(writer, [row("viewer")], NS, badges(1, 2)); + const memory = sheet.find((g) => g.group === "Memory"); + const review = memory?.items.find((i) => i.id === "admin:review_queue"); + expect(review).toMatchObject({ badge: 3, badgeLabel: "3 items to review: 1 conflict, 2 pending proposals" }); + expect(sheet.find((g) => g.group === "Admin")).toBeUndefined(); + }); + + it("a proposal-only count links straight to the proposals tab", () => { + const item = reviewNavItem(writer, [row("writer")], NS, badges(0, 3)); + expect(item).toMatchObject({ + id: "admin:review_queue", + badge: 3, + badgeLabel: "3 items to review: 3 pending proposals", + query: { tab: "proposals" }, + }); + // Conflicts present: the plain queue link, no tab override. + expect(reviewNavItem(writer, [row("writer")], NS, badges(2, 3))?.query).toBeUndefined(); + // A failed count is unknown: no badge number, no tab override, entry still there. + const partial = reviewNavItem(writer, [row("writer")], NS, badges(null, 3)); + expect(partial?.badge).toBe(3); + expect(partial?.badgeLabel).toBe("at least 3 items to review: 3 pending proposals"); + expect(partial?.query).toBeUndefined(); + expect(reviewNavItem(writer, [row("writer")], NS, null)).toMatchObject({ id: "admin:review_queue" }); + }); +}); + +describe("adminItems counts pending proposals toward the Review queue", () => { + const badges = (conflicts: number | null, pendingProposals: number | null, autoResolved = false): AdminBadges => ({ + conflicts, + pendingProposals, + autoResolved, + overCap: false, + newAgents: 0, + }); + + it("leads with the Review entry for pending proposals alone, badge and label per kind", () => { + const items = adminItems(admin, [row("admin")], NS, badges(0, 3)); + expect(items[0]).toMatchObject({ + id: "admin:review_queue", + badge: 3, + badgeLabel: "3 items to review: 3 pending proposals", + query: { tab: "proposals" }, + }); + }); + + it("adds conflicts and proposals into one labeled count", () => { + const items = adminItems(admin, [row("admin")], NS, badges(2, 3)); + expect(items[0]?.badge).toBe(5); + expect(items[0]?.badgeLabel).toBe("5 items to review: 2 conflicts, 3 pending proposals"); + expect(items[0]?.query).toBeUndefined(); + }); + + it("a failed count makes the sum partial, labeled 'at least', never a false zero", () => { + const items = adminItems(admin, [row("admin")], NS, badges(2, null)); + expect(items[0]?.badge).toBe(2); + expect(items[0]?.badgeLabel).toBe("at least 2 items to review: 2 conflicts"); + // Both failed: no badge, but the entry still appears only via auto-resolution; with + // nothing known and nothing auto-resolved, no entry. + expect(adminItems(admin, [row("admin")], NS, badges(null, null))).not.toContainEqual( + expect.objectContaining({ id: "admin:review_queue" }), + ); + }); + + it("auto-resolved history alone still surfaces the entry, without a number", () => { + const items = adminItems(admin, [row("admin")], NS, badges(0, 0, true)); + expect(items[0]).toMatchObject({ id: "admin:review_queue", badge: undefined, badgeLabel: undefined }); + }); +}); diff --git a/frontend/src/layout/Sidebar.test.tsx b/frontend/src/layout/Sidebar.test.tsx index 442887684c..d61c620883 100644 --- a/frontend/src/layout/Sidebar.test.tsx +++ b/frontend/src/layout/Sidebar.test.tsx @@ -10,7 +10,7 @@ async function painted(): Promise { } import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { MyNamespaceEntry, WhoAmI } from "../api"; -import { useStore, viewHref } from "../lib/state"; +import { useStore, viewHref, badgeCacheKey } from "../lib/state"; import { Sidebar } from "./Sidebar"; import { MobileNav } from "./MobileNav"; import { invalidateShared } from "../lib/sharedReads"; @@ -24,6 +24,7 @@ vi.mock("../api", async (importOriginal) => { return { ...actual, countConflicts: vi.fn(async () => 0), + countPendingProposals: vi.fn(async () => 0), // The badge asks for a number, no rows getBudgetStatus: vi.fn(async () => ({ over_cap: false })), countNewAgents: vi.fn(async () => 0), // The badge asks for a number }; @@ -33,7 +34,7 @@ vi.mock("../api/audit", async (importOriginal) => ({ ...(await importOriginal()), hasAutoResolved: vi.fn(async () => false), })); -import { getBudgetStatus, countConflicts, countNewAgents } from "../api"; +import { getBudgetStatus, countConflicts, countNewAgents, countPendingProposals } from "../api"; import { hasAutoResolved } from "../api/audit"; const row = (namespace: string, role: MyNamespaceEntry["role"]): MyNamespaceEntry => ({ @@ -64,6 +65,14 @@ const viewer: WhoAmI = { namespaces: ["team-a"], }; +// The rail's Memory group, and the Admin drawer's container: with a stable rail Review +// entry, "Review queue" can name a link in either, so the tests say which they mean. (The +// nav landmark holds both, so it cannot serve as the rail's scope.) +const memoryGroup = () => screen.getByText("Memory").parentElement as HTMLElement; +const drawerBox = () => screen.getByRole("button", { name: /Admin/ }).parentElement as HTMLElement; +/** The session-cache key the sidebar writes for the seeded principal and role. */ +const teamAKey = (role: string | null = "admin") => badgeCacheKey("dev", "team-a", viewer.subject, role); + describe("Sidebar admin drawer", () => { beforeEach(() => { invalidateShared(); // the budget read is shared with the Usage page @@ -76,14 +85,18 @@ describe("Sidebar admin drawer", () => { useStore.setState({ whoami: null, myNamespaces: null, identity: null }); }); - it("is hidden for a viewer, and none of the admin polls fire", async () => { + it("is hidden for a viewer, and none of the admin polls fire — but the rail still offers Review", async () => { seed(viewer, [row("team-a", "viewer")]); render(); expect(screen.getByText("Memories")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: /Admin/ })).not.toBeInTheDocument(); + // The stable rail entry: a caller who may view review work reaches it even with an + // empty queue and no badge polls. + expect(screen.getByRole("link", { name: /Review queue/ })).toBeInTheDocument(); // Let any effect that would have polled run. await painted(); expect(countConflicts).not.toHaveBeenCalled(); + expect(countPendingProposals).not.toHaveBeenCalled(); expect(getBudgetStatus).not.toHaveBeenCalled(); expect(countNewAgents).not.toHaveBeenCalled(); expect(hasAutoResolved).not.toHaveBeenCalled(); @@ -95,6 +108,7 @@ describe("Sidebar admin drawer", () => { expect(screen.getByRole("button", { name: /Admin/ })).toBeInTheDocument(); await painted(); expect(countConflicts).toHaveBeenCalledTimes(1); + expect(countPendingProposals).toHaveBeenCalledTimes(1); expect(getBudgetStatus).toHaveBeenCalledTimes(1); }); @@ -113,17 +127,22 @@ describe("Sidebar admin drawer", () => { render(); await painted(); expect(countConflicts).not.toHaveBeenCalled(); + expect(countPendingProposals).not.toHaveBeenCalled(); expect(getBudgetStatus).not.toHaveBeenCalled(); expect(countNewAgents).not.toHaveBeenCalled(); }); - it("a viewer whose list_mine failed (unknown role) polls nothing", async () => { + it("a viewer whose list_mine failed (unknown role) polls nothing and sees no rail Review entry", async () => { seed(viewer, null); render(); await painted(); expect(countConflicts).not.toHaveBeenCalled(); + expect(countPendingProposals).not.toHaveBeenCalled(); expect(getBudgetStatus).not.toHaveBeenCalled(); expect(countNewAgents).not.toHaveBeenCalled(); + // An unknown role may not view review work, so the stable entry stays hidden rather + // than pointing at reads that would 403. + expect(screen.queryByRole("link", { name: /Review queue/ })).not.toBeInTheDocument(); }); it("an admin claim polls even when list_mine failed", async () => { @@ -131,6 +150,7 @@ describe("Sidebar admin drawer", () => { render(); await painted(); expect(countConflicts).toHaveBeenCalledTimes(1); + expect(countPendingProposals).toHaveBeenCalledTimes(1); expect(getBudgetStatus).toHaveBeenCalledTimes(1); expect(countNewAgents).toHaveBeenCalledTimes(1); }); @@ -157,8 +177,10 @@ describe("Sidebar admin drawer", () => { expect(countNewAgents).toHaveBeenCalledTimes(2); expect(countNewAgents).toHaveBeenLastCalledWith(expect.objectContaining({ namespace: "team-b" })); expect(screen.getByRole("link", { name: /Agents/ })).toHaveTextContent("1"); - const cached: unknown = JSON.parse(sessionStorage.getItem("loom_badge_v1:badges:dev/team-b") ?? "null"); - expect(cached).toMatchObject({ v: { newAgents: 1 } }); + const cached: unknown = JSON.parse( + sessionStorage.getItem(`loom_badge_v1:${badgeCacheKey("dev", "team-b", admin.subject, "admin")}`) ?? "null", + ); + expect(cached).toMatchObject({ v: { newAgents: 1, pendingProposals: 0 } }); }); it("a switch to a namespace that is not polled clears the previous namespace's badges", async () => { @@ -168,21 +190,23 @@ describe("Sidebar admin drawer", () => { useStore.setState({ view: "admin:health" }); render(); await painted(); - expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("4"); + expect(within(drawerBox()).getByRole("link", { name: /Review queue/ })).toHaveTextContent("4"); // team-b's role is unknown (list_mine failed): the drawer stays (fail-open) but nothing - // is polled, so nothing from team-a may stay on it. + // is polled, so nothing from team-a may stay on it, and the rail entry goes too (an + // unknown role may not view review work). act(() => useStore.setState({ identity: { org: "dev", namespace: "team-b", agent: "loom-ui" }, myNamespaces: null }), ); await painted(); expect(screen.getByRole("button", { name: /Admin/ })).toBeInTheDocument(); + expect(within(drawerBox()).queryByRole("link", { name: /Review queue/ })).not.toBeInTheDocument(); expect(screen.queryByRole("link", { name: /Review queue/ })).not.toBeInTheDocument(); expect(countConflicts).toHaveBeenCalledTimes(1); }); // With no open conflict, the queue's Auto-resolved tab still has something to show: - // the entry appears, with no count, so it is reachable without its URL. - it("shows the Review queue when Loom recently retired a memory on its own", async () => { + // the drawer's entry appears, with no count, so it is reachable without its URL. + it("shows the Review queue in the drawer when Loom recently retired a memory on its own", async () => { sessionStorage.clear(); vi.mocked(hasAutoResolved).mockResolvedValueOnce(true); seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); @@ -190,17 +214,22 @@ describe("Sidebar admin drawer", () => { render(); await painted(); expect(hasAutoResolved).toHaveBeenCalledWith({ org: "dev", namespace: "team-a" }); - expect(screen.getByRole("link", { name: /Review queue/ })).not.toHaveTextContent(/\d/); + expect(within(drawerBox()).getByRole("link", { name: /Review queue/ })).not.toHaveTextContent(/\d/); }); - it("hides the Review queue with no open conflict and no recent auto-resolution", async () => { + it("keeps the rail's Review queue entry with no open conflict and no recent auto-resolution, and hides the drawer's", async () => { sessionStorage.clear(); seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); useStore.setState({ view: "admin:health" }); render(); await painted(); expect(hasAutoResolved).toHaveBeenCalledTimes(1); - expect(screen.queryByRole("link", { name: /Review queue/ })).not.toBeInTheDocument(); + // The drawer's auto-appearing entry stays hidden, but the stable rail entry remains: + // Review is reachable even when its queue is empty. + expect(within(drawerBox()).queryByRole("link", { name: /Review queue/ })).not.toBeInTheDocument(); + const railReview = within(memoryGroup()).getByRole("link", { name: /Review queue/ }); + expect(railReview).not.toHaveTextContent(/\d/); + expect(railReview).toHaveAttribute("href", viewHref("admin:review_queue")); }); it("is shown for a platform admin regardless of grants, with the Users entry", async () => { @@ -268,13 +297,20 @@ describe("the admin list on every width", () => { it("redraws the open sheet when a new badge answer lands", async () => { seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); - useStore.setState({ adminBadges: { conflicts: 3, autoResolved: false, overCap: false, newAgents: 0 } }); + useStore.setState({ + adminBadges: { conflicts: 3, pendingProposals: null, autoResolved: false, overCap: false, newAgents: 0 }, + }); render(); await userEvent.setup().click(screen.getByRole("button", { name: "More" })); const sheet = await screen.findByRole("dialog", { name: "More" }); - const review = () => within(sheet).getByRole("link", { name: /Review queue/ }); + const admin = within(sheet).getByRole("navigation", { name: "Admin" }); + const review = () => within(admin).getByRole("link", { name: /Review queue/ }); expect(review()).toHaveTextContent("3"); - act(() => useStore.setState({ adminBadges: { conflicts: 5, autoResolved: false, overCap: false, newAgents: 0 } })); + act(() => + useStore.setState({ + adminBadges: { conflicts: 5, pendingProposals: null, autoResolved: false, overCap: false, newAgents: 0 }, + }), + ); expect(review()).toHaveTextContent("5"); }); @@ -300,17 +336,21 @@ describe("the admin list on every width", () => { useStore.setState({ view: "admin:health" }); render(); await painted(); - expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("3"); + expect(within(drawerBox()).getByRole("link", { name: /Review queue/ })).toHaveTextContent("3"); act(() => useStore.setState({ identity: { org: "other", namespace: "team-a", agent: "loom-ui" } })); - expect(screen.queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(within(drawerBox()).queryByRole("link", { name: /Review queue/ })).toBeNull(); await painted(); expect(countConflicts).toHaveBeenLastCalledWith({ org: "other", namespace: "team-a" }); - expect(screen.queryByRole("link", { name: /Review queue/ })).toBeNull(); + // The drawer's badge is gone; the stable rail entry remains, without a number. + expect(within(drawerBox()).queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(within(memoryGroup()).getByRole("link", { name: /Review queue/ })).not.toHaveTextContent(/\d/); }); it("draws Usage's warning dot and the Agents count on the More sheet", async () => { seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); - useStore.setState({ adminBadges: { conflicts: null, autoResolved: false, overCap: true, newAgents: 2 } }); + useStore.setState({ + adminBadges: { conflicts: null, pendingProposals: null, autoResolved: false, overCap: true, newAgents: 2 }, + }); render(); await userEvent.setup().click(screen.getByRole("button", { name: "More" })); const sheet = await screen.findByRole("dialog", { name: "More" }); @@ -330,21 +370,29 @@ describe("the admin list on every width", () => { unmount(); await act(async () => settle(3)); expect(useStore.getState().adminBadges).toBeNull(); - expect(sessionStorage.getItem("loom_badge_v1:badges:dev/team-a")).toBeNull(); + expect(sessionStorage.getItem(`loom_badge_v1:${teamAKey()}`)).toBeNull(); }); it("hides a badge whose read fails, though the session remembered one", async () => { sessionStorage.setItem( - "loom_badge_v1:badges:dev/team-a", - JSON.stringify({ at: Date.now(), v: { conflicts: 3, autoResolved: false, overCap: false, newAgents: 0 } }), + `loom_badge_v1:${teamAKey()}`, + JSON.stringify({ + at: Date.now(), + v: { conflicts: 3, pendingProposals: 1, autoResolved: false, overCap: false, newAgents: 0 }, + }), ); vi.mocked(countConflicts).mockRejectedValueOnce(new Error("offline")); + vi.mocked(countPendingProposals).mockRejectedValueOnce(new Error("offline")); seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); useStore.setState({ view: "admin:health" }); render(); - expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("3"); + // The remembered answer shows at once: 3 conflicts + 1 proposal = 4 review items. + expect(within(drawerBox()).getByRole("link", { name: /Review queue/ })).toHaveTextContent("4"); await painted(); - expect(screen.queryByRole("link", { name: /Review queue/ })).toBeNull(); + // Both reads failed: the drawer's auto-appearing entry goes, and the rail's stable + // entry stays without a number — a failed count is unknown, never a false zero. + expect(within(drawerBox()).queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(within(memoryGroup()).getByRole("link", { name: /Review queue/ })).not.toHaveTextContent(/\d/); }); it("shows the reads' answers together, once the slowest settles", async () => { @@ -355,11 +403,76 @@ describe("the admin list on every width", () => { useStore.setState({ view: "admin:health" }); render(); await painted(); - expect(screen.queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(within(drawerBox()).queryByRole("link", { name: /Review queue/ })).toBeNull(); await act(async () => settle(2)); - expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("3"); + expect(within(drawerBox()).getByRole("link", { name: /Review queue/ })).toHaveTextContent("3"); expect(screen.getByRole("link", { name: /Agents/ })).toHaveTextContent("2"); }); + + // Pending proposals are review items too: they surface the Review queue and count in + // its badge, next to conflicts, with a label that says what the number counts. + it("counts pending proposals in the Review queue badge, labeled per kind", async () => { + sessionStorage.clear(); + vi.mocked(countConflicts).mockResolvedValueOnce(2); + vi.mocked(countPendingProposals).mockResolvedValueOnce(3); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + const link = within(drawerBox()).getByRole("link", { name: /Review queue/ }); + expect(link).toHaveTextContent("5"); + expect(link).toHaveAccessibleName(/5 items to review: 2 conflicts, 3 pending proposals/); + // The rail entry carries the same count and label. + const railLink = within(memoryGroup()).getByRole("link", { name: /Review queue/ }); + expect(railLink).toHaveTextContent("5"); + expect(railLink).toHaveAccessibleName(/5 items to review/); + }); + + it("surfaces a proposal-only queue and links straight to its pending proposals", async () => { + sessionStorage.clear(); + vi.mocked(countConflicts).mockResolvedValueOnce(0); + vi.mocked(countPendingProposals).mockResolvedValueOnce(4); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + const link = within(drawerBox()).getByRole("link", { name: /Review queue/ }); + expect(link).toHaveTextContent("4"); + expect(link).toHaveAccessibleName(/4 items to review: 4 pending proposals/); + expect(link).toHaveAttribute("href", `${viewHref("admin:review_queue")}?tab=proposals`); + expect(within(memoryGroup()).getByRole("link", { name: /Review queue/ })).toHaveAttribute( + "href", + `${viewHref("admin:review_queue")}?tab=proposals`, + ); + }); + + it("a partial count is labeled 'at least', never a false total", async () => { + sessionStorage.clear(); + vi.mocked(countConflicts).mockResolvedValueOnce(2); + vi.mocked(countPendingProposals).mockRejectedValueOnce(new Error("offline")); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + const link = within(drawerBox()).getByRole("link", { name: /Review queue/ }); + expect(link).toHaveTextContent("2"); + expect(link).toHaveAccessibleName(/at least 2 items to review: 2 conflicts/); + }); + + it("the badge cache key carries org, namespace, principal and role", async () => { + sessionStorage.clear(); + vi.mocked(countConflicts).mockResolvedValueOnce(3); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + render(); + await painted(); + expect(sessionStorage.getItem(`loom_badge_v1:${teamAKey("admin")}`)).not.toBeNull(); + // Another principal on the same namespace is another cache entry. + expect( + sessionStorage.getItem(`loom_badge_v1:${badgeCacheKey("dev", "team-a", "someone-else", "admin")}`), + ).toBeNull(); + // Another role is another entry (a permission boundary). + expect(sessionStorage.getItem(`loom_badge_v1:${teamAKey("viewer")}`)).toBeNull(); + }); }); describe("Sidebar collapsed rail", () => { diff --git a/frontend/src/layout/Sidebar.tsx b/frontend/src/layout/Sidebar.tsx index 895b548275..db5660af09 100644 --- a/frontend/src/layout/Sidebar.tsx +++ b/frontend/src/layout/Sidebar.tsx @@ -3,10 +3,23 @@ import { Badge } from "@clickhouse/click-ui/Badge"; import { Icon, type IconName } from "@clickhouse/click-ui/Icon"; import { IconButton } from "../components/IconButton"; import { Tip } from "../components/ui/Tooltip"; -import { useStore, viewHref, type AdminBadges, type View } from "../lib/state"; -import { countConflicts, countNewAgents, type MyNamespaceEntry, type WhoAmI } from "../api"; +import { + useStore, + viewHref, + badgeCacheKey, + reviewBadgeLabel, + reviewCount, + type AdminBadges, + type View, +} from "../lib/state"; +import { countNewAgents, type MyNamespaceEntry, type WhoAmI } from "../api"; import { readSession, useAfterPaint, writeSession } from "../lib/afterPaint"; -import { sharedBudgetStatus, sharedHasAutoResolved } from "../lib/sharedReads"; +import { + sharedBudgetStatus, + sharedConflictsCount, + sharedHasAutoResolved, + sharedPendingProposalsCount, +} from "../lib/sharedReads"; import { hasOrgAdminClaim, hasPlatformAdminClaim, isNamespaceAdmin } from "../lib/role"; import { roleOnNamespace } from "../lib/namespaceRole"; import { canCall } from "../lib/canCall"; @@ -62,6 +75,13 @@ export interface NavItem { // differently from a neutral count (review queue). Number >= 999 // collapses to a dot rather than a numeric label. badgeTone?: "default" | "warn" | "accent"; + /** What the badge number counts, read to screen readers with the label ("3 items to + * review: 2 conflicts, 1 pending proposal") — a bare number on a nav entry says + * nothing about what waits. */ + badgeLabel?: string; + /** Query the destination opens on (`?tab=proposals` for a proposal-only queue), so a + * deep link, cmd-click and a plain click all land on the same category. */ + query?: Record; } // The rail is three labelled groups around the questions a user brings — what does my AI @@ -226,22 +246,80 @@ export function adminItems( return { ...item, badge: badges.newAgents, badgeTone: "accent" }; return item; }); - const open = !!badges?.conflicts; + // The Review entry appears when any review item waits: open conflicts or pending + // proposals (the badge counts both), or a recent auto-resolution (icon only, no + // number — retired history is not review work waiting for a person). + const { total } = reviewCount(badges); + const open = total > 0; if (!open && !badges?.autoResolved) return items; - // Open conflicts warn with their count; recent auto-resolutions alone use the - // Auto-resolved tab's icon, no number. const review: NavItem = { id: "admin:review_queue", label: "Review queue", icon: open ? "warning" : "flash", - badge: badges?.conflicts || undefined, + badge: open ? total : undefined, + badgeLabel: open ? reviewBadgeLabel(badges) : undefined, + // A proposal-only queue links straight to its pending proposals, so an empty + // Conflicts tab does not look like an empty queue. + ...(open && (badges?.conflicts ?? 0) === 0 && (badges?.pendingProposals ?? 0) > 0 + ? { query: { tab: "proposals" } } + : {}), }; return [review, ...items]; } +/** The Review queue entry in the ordinary Memory rail, for a caller authorized to view + * review work — every role that reaches `conflicts.list` or `memory.proposals` does + * (both VIEWER on the server, so backend roles are unchanged). A memory namespace + * only: a code or tracker namespace has no review queue. An unknown role shows + * nothing rather than an entry whose reads would 403. The entry is stable — it does + * not wait for a badge count, and a failed count leaves it in place without a + * number. */ +export function reviewNavItem( + whoami: WhoAmI | null, + mine: MyNamespaceEntry[] | null, + namespace: string, + badges: AdminBadges | null, +): NavItem | null { + if (!isMemoryNamespace(namespace, mine)) return null; + const role = roleOnNamespace(whoami, mine, namespace); + if (!role) return null; + if (!canCall("conflicts.list", role, whoami) && !canCall("memory.proposals", role, whoami)) return null; + const { total } = reviewCount(badges); + const proposalOnly = + badges !== null && + badges.conflicts != null && + badges.pendingProposals != null && + badges.conflicts === 0 && + badges.pendingProposals > 0; + return { + id: "admin:review_queue", + label: "Review queue", + icon: total > 0 ? "warning" : "question", + scope: "namespace", + badge: total > 0 ? total : undefined, + badgeLabel: total > 0 ? reviewBadgeLabel(badges) : undefined, + ...(proposalOnly ? { query: { tab: "proposals" } } : {}), + }; +} + +/** The rail groups with the Review queue entry in the Memory group when the caller may + * view review work. The sidebar and the phone's More sheet both render this, so the + * same entry — and its count — appears on desktop and mobile. */ +export function railGroups( + whoami: WhoAmI | null, + mine: MyNamespaceEntry[] | null, + namespace: string, + badges: AdminBadges | null, +): NavGroup[] { + const review = reviewNavItem(whoami, mine, namespace, badges); + if (!review) return RAIL_GROUPS; + return RAIL_GROUPS.map((g) => (g.label === "Memory" ? { ...g, items: [...g.items, review] } : g)); +} + export function Sidebar() { const view = useStore((s) => s.view); const setView = useStore((s) => s.setView); + const navigate = useStore((s) => s.navigate); const identity = useStore((s) => s.identity); const collapsed = useStore((s) => s.sidebarCollapsed); const toggleSidebar = useStore((s) => s.toggleSidebar); @@ -276,7 +354,9 @@ export function Sidebar() { // first paint, on idle — a badge number is not what the person is waiting for — and the // last answer is remembered for the session, so a full reload shows the badges at once // from it and refreshes them behind. - const badgeKey = identity ? `badges:${identity.org}/${identity.namespace}` : ""; + // The cache key carries the principal and the role as well as the scope: a remembered + // count never crosses an org, namespace, account or permission boundary. + const badgeKey = identity ? badgeCacheKey(identity.org, identity.namespace, whoami?.subject, roleHere) : ""; // A badge belongs to one namespace: on a switch, show the new namespace's remembered // answer or nothing — never the previous namespace's numbers — and make its first read // ask agents.connected, so no tick carries the old count into the new cache key. @@ -290,12 +370,19 @@ export function Sidebar() { let cancelled = false; const fetch_ = async () => { const tasks: Promise[] = []; - const next: AdminBadges = { conflicts: null, autoResolved: false, overCap: false, newAgents: 0 }; + const next: AdminBadges = { + conflicts: null, + pendingProposals: null, + autoResolved: false, + overCap: false, + newAgents: 0, + }; if (canCall("conflicts.list", roleHere, whoami)) { tasks.push( // The badge asks for the number, not 100 rows with their values (33 MB per tick - // on a large namespace). - countConflicts({ org: identity.org, namespace: identity.namespace }) + // on a large namespace). Shared with the Review queue's tab count — one read + // per question per page. + sharedConflictsCount({ org: identity.org, namespace: identity.namespace }) .then((n) => { next.conflicts = n; }) @@ -304,6 +391,21 @@ export function Sidebar() { }), ); } + // Pending proposals count toward the review badge too: one bounded server-side + // count (`count_only`, no rows, uncapped), so the number matches the whole queue. + // A failed read leaves `null` — unknown, never a false zero. Shared with the + // Review queue's per-kind count. + if (canCall("memory.proposals", roleHere, whoami)) { + tasks.push( + sharedPendingProposalsCount({ org: identity.org, namespace: identity.namespace }) + .then((n) => { + next.pendingProposals = n; + }) + .catch(() => { + /* unknown */ + }), + ); + } // The Review queue shows the Auto-resolved tab only to a role that reaches both. if (canCall("memory.auto_retirements", roleHere, whoami) && canCall("audit.list", roleHere, whoami)) { tasks.push( @@ -411,7 +513,7 @@ export function Sidebar() { {/* Main nav — anchors so cmd-click opens in a new tab. Padded, not margined, so the scroll box leaves room for the first and last items' focus ring. */}
@@ -483,7 +585,7 @@ export function Sidebar() { item={item} active={view === item.id} collapsed={true} - onActivate={() => setView(item.id)} + onActivate={() => navigate(item.id, item.query ? { query: item.query } : {})} /> ))} @@ -552,9 +654,10 @@ function NavBtn({ const hintId = useId(); // Anchor (not button) so cmd/ctrl-click opens the view in a new tab, // middle-click works, and "Copy link" gives a usable URL. + const href = item.query ? `${viewHref(item.id)}?${new URLSearchParams(item.query).toString()}` : viewHref(item.id); const anchor = ( { if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; e.preventDefault(); @@ -571,6 +674,8 @@ function NavBtn({ {hint} )} + {/* What the badge counts, read with the label; the number alone says nothing. */} + {item.badgeLabel && {item.badgeLabel}}