diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 8d0e99ce2a4..21bc3c40b41 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -447,7 +447,7 @@ 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 | **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. In the drawer for every admin of a memory namespace, even when empty; it counts open conflicts plus pending proposals. 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. | @@ -457,12 +457,17 @@ entry that would answer 403. | 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. | -The Admin button shows the number of open conflicts while its drawer is closed. The -Review queue appears with its conflict count, or with no count when 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 +The Admin button shows the Review queue's count while its drawer is closed. That count is the +review items waiting: open conflicts plus pending proposals, both from the one +`conflicts.list` count the badge reads (`count_only` answers `total` and `proposals`). A +decision in the Proposals tab reads the count again at once, counted fresh rather than from a +replica's minute-long cache, which only the replica that took the decision drops. The fresh +count reads with sequential consistency, and a count of the decided namespace read before the +decision that returns after it is not cached. The minute's polls read the cache. When the queue's own count finds +proposals waiting and no open conflict, the queue opens on Proposals. 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. ## Operations the dashboard uses diff --git a/docs/reference/operations/conflicts.md b/docs/reference/operations/conflicts.md index 25d369595f6..90a5610443b 100644 --- a/docs/reference/operations/conflicts.md +++ b/docs/reference/operations/conflicts.md @@ -55,7 +55,7 @@ List unresolved conflicts where two memories contradict each other. | `namespace` | `str` | required | The namespace the op reads or writes. | | `limit` | `int` | `50` | At most this many rows, 1-500, newest version first. | | `before_version` | `int \| None` | `None` | Keyset cursor — pass previous response's earliest version to paginate. | -| `count_only` | `bool` | `False` | A badge needs the number, not the rows. | +| `count_only` | `bool` | `False` | A badge needs the numbers, not the rows. | | `fresh` | `bool` | `False` | With count_only, count now instead of reading the minute-long cache; default off. | | `keys_only` | `bool` | `False` | The Memories view marks cards that have a conflict and needs only the keys. | | `fields` | `list[str] \| None` | `None` | The output fields the caller reads (a whitelist resolved against the row model; an unknown name is a 422); unset, every field. | @@ -65,6 +65,7 @@ List unresolved conflicts where two memories contradict each other. | `rows` | `list[_ConflictRow]` | Conflicted memories, newest version first; empty on a `count_only` or `keys_only` call. | | `next_before_version` | `int \| None` | Pass as `before_version` for the next page; null on the last page. | | `total` | `int \| None` | The live conflicted count for the namespace; set on a count_only call. | +| `proposals` | `int \| None` | The pending proposals in the same scope, from the same read; set on a count_only call. | | `keys` | `list[str] \| None` | The conflicted memory keys of the namespace; set on a keys_only call. | ## `conflicts.propose_revision` diff --git a/docs/reference/operations/memory.md b/docs/reference/operations/memory.md index b58505f7288..2806993d08e 100644 --- a/docs/reference/operations/memory.md +++ b/docs/reference/operations/memory.md @@ -1566,11 +1566,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` | Answer `total`, the exact number of pending proposals that match prefix and tags, and the namespace's `policy`, with no proposal or graded count read; default off. | | 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`, up to the scan cap; exact with `count_only`. | | `policy` | `ProposalPolicy` | The namespace's proposal policy: `mode` (manual / auto) and thresholds. | ## `memory.provenance` diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 7261bfa9ae3..03638b843ec 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -1037,18 +1037,24 @@ export async function listConflicts( return post("/v1/conflicts.list", body, opts.signal); } -/** The namespace's conflicted count. `fresh` counts now instead of answering from the - * replica's minute-long cache (the review queue; the sidebar badge takes the cache). */ -export async function countConflicts( +/** The namespace's Review queue counts from one read: `total` conflicted and `proposals` + * pending (absent from a server that does not count them). `fresh` counts now instead of + * answering from the replica's minute-long cache (the review queue, and the sidebar's read + * after a decision; its minute polls take the cache). */ +export function countReview( id: Pick, opts: RequestOpts & { fresh?: boolean } = {}, -): Promise { - const r = await post<{ total?: number | null }>( +): Promise { + return post( "/v1/conflicts.list", - { org: id.org, namespace: id.namespace, count_only: true, ...(opts.fresh ? { fresh: true } : {}) }, + { org: id.org, namespace: id.namespace, count_only: true, fresh: opts.fresh }, opts.signal, ); - return r.total ?? 0; +} + +export interface ReviewCounts { + total?: number | null; + proposals?: number | null; } /** The conflicted memory keys of a namespace, for the cards' chips diff --git a/frontend/src/layout/Sidebar.test.tsx b/frontend/src/layout/Sidebar.test.tsx index 7a04fb2c9f1..67d39954c63 100644 --- a/frontend/src/layout/Sidebar.test.tsx +++ b/frontend/src/layout/Sidebar.test.tsx @@ -9,7 +9,7 @@ async function painted(): Promise { }); } import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { MyNamespaceEntry, WhoAmI } from "../api"; +import type { MyNamespaceEntry, ReviewCounts, WhoAmI } from "../api"; import { useStore, viewHref } from "../lib/state"; import { Sidebar } from "./Sidebar"; import { MobileNav } from "./MobileNav"; @@ -23,7 +23,7 @@ vi.mock("../api", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - countConflicts: vi.fn(async () => 0), + countReview: vi.fn(async () => ({ total: 0, proposals: 0 })), getBudgetStatus: vi.fn(async () => ({ over_cap: false })), countNewAgents: vi.fn(async () => 0), // The badge asks for a number }; @@ -33,7 +33,7 @@ vi.mock("../api/audit", async (importOriginal) => ({ ...(await importOriginal()), hasAutoResolved: vi.fn(async () => false), })); -import { getBudgetStatus, countConflicts, countNewAgents } from "../api"; +import { getBudgetStatus, countNewAgents, countReview } from "../api"; import { hasAutoResolved } from "../api/audit"; const row = (namespace: string, role: MyNamespaceEntry["role"]): MyNamespaceEntry => ({ @@ -83,7 +83,7 @@ describe("Sidebar admin drawer", () => { expect(screen.queryByRole("button", { name: /Admin/ })).not.toBeInTheDocument(); // Let any effect that would have polled run. await painted(); - expect(countConflicts).not.toHaveBeenCalled(); + expect(countReview).not.toHaveBeenCalled(); expect(getBudgetStatus).not.toHaveBeenCalled(); expect(countNewAgents).not.toHaveBeenCalled(); expect(hasAutoResolved).not.toHaveBeenCalled(); @@ -94,7 +94,7 @@ describe("Sidebar admin drawer", () => { render(); expect(screen.getByRole("button", { name: /Admin/ })).toBeInTheDocument(); await painted(); - expect(countConflicts).toHaveBeenCalledTimes(1); + expect(countReview).toHaveBeenCalledTimes(1); expect(getBudgetStatus).toHaveBeenCalledTimes(1); }); @@ -112,7 +112,7 @@ describe("Sidebar admin drawer", () => { seed(viewer, []); render(); await painted(); - expect(countConflicts).not.toHaveBeenCalled(); + expect(countReview).not.toHaveBeenCalled(); expect(getBudgetStatus).not.toHaveBeenCalled(); expect(countNewAgents).not.toHaveBeenCalled(); }); @@ -121,7 +121,7 @@ describe("Sidebar admin drawer", () => { seed(viewer, null); render(); await painted(); - expect(countConflicts).not.toHaveBeenCalled(); + expect(countReview).not.toHaveBeenCalled(); expect(getBudgetStatus).not.toHaveBeenCalled(); expect(countNewAgents).not.toHaveBeenCalled(); }); @@ -130,7 +130,7 @@ describe("Sidebar admin drawer", () => { seed({ ...viewer, roles: ["ADMIN"] }, null); render(); await painted(); - expect(countConflicts).toHaveBeenCalledTimes(1); + expect(countReview).toHaveBeenCalledTimes(1); expect(getBudgetStatus).toHaveBeenCalledTimes(1); expect(countNewAgents).toHaveBeenCalledTimes(1); }); @@ -163,7 +163,7 @@ describe("Sidebar admin drawer", () => { it("a switch to a namespace that is not polled clears the previous namespace's badges", async () => { sessionStorage.clear(); - vi.mocked(countConflicts).mockResolvedValueOnce(4); + vi.mocked(countReview).mockResolvedValueOnce({ total: 4, proposals: 0 }); seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); useStore.setState({ view: "admin:health" }); render(); @@ -176,8 +176,8 @@ describe("Sidebar admin drawer", () => { ); await painted(); expect(screen.getByRole("button", { name: /Admin/ })).toBeInTheDocument(); - expect(screen.queryByRole("link", { name: /Review queue/ })).not.toBeInTheDocument(); - expect(countConflicts).toHaveBeenCalledTimes(1); + expect(screen.getByRole("link", { name: /Review queue/ })).not.toHaveTextContent(/\d/); + expect(countReview).toHaveBeenCalledTimes(1); }); // With no open conflict, the queue's Auto-resolved tab still has something to show: @@ -193,14 +193,177 @@ describe("Sidebar admin drawer", () => { expect(screen.getByRole("link", { name: /Review queue/ })).not.toHaveTextContent(/\d/); }); - it("hides the Review queue with no open conflict and no recent auto-resolution", async () => { + // An empty queue stays reachable: the entry is listed with no number. + it("lists the Review queue with nothing pending, with no count", 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(); + expect(screen.getByRole("link", { name: "Review queue" })).not.toHaveTextContent(/\d/); + }); + + // The count is the review items waiting, open conflicts plus pending proposals, from one read. + it("counts pending proposals with the open conflicts", async () => { + sessionStorage.clear(); + vi.mocked(countReview).mockResolvedValueOnce({ total: 2, proposals: 3 }); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + expect(countReview).toHaveBeenCalledTimes(1); + expect(countReview).toHaveBeenCalledWith({ org: "dev", namespace: "team-a" }, { fresh: false }); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("5"); + }); + + it("shows proposals waiting alone, with no open conflict", async () => { + sessionStorage.clear(); + vi.mocked(countReview).mockResolvedValueOnce({ total: 0, proposals: 1 }); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("1"); + }); + + // A server that does not count proposals answers the conflicts alone. + it("counts the open conflicts when the answer has no proposals count", async () => { + sessionStorage.clear(); + vi.mocked(countReview).mockResolvedValueOnce({ total: 2 }); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("2"); + }); + + // A decision reads the counts again for the namespace shown, and an answer read before + // the decision is dropped even when it lands after the new one. + it("reads the counts again after a Review queue decision and drops the earlier answer", async () => { + sessionStorage.clear(); + let before: (r: ReviewCounts) => void = () => {}; + vi.mocked(countReview) + .mockReturnValueOnce(new Promise((r) => (before = r))) + .mockResolvedValueOnce({ total: 0, proposals: 1 }); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + act(() => useStore.setState((s) => ({ reviewDecisions: s.reviewDecisions + 1 }))); + await painted(); + expect(countReview).toHaveBeenCalledTimes(2); + expect(countReview).toHaveBeenLastCalledWith({ org: "dev", namespace: "team-a" }, { fresh: true }); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("1"); + await act(async () => before({ total: 0, proposals: 2 })); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("1"); + }); + + // A decision made in team-a that lands after a switch to team-b reads team-b's counts + // again and leaves them as read, with nothing taken off. + it("reads the namespace shown again after a decision made in another one", async () => { + sessionStorage.clear(); + vi.mocked(countReview) + .mockResolvedValueOnce({ total: 0, proposals: 3 }) + .mockResolvedValueOnce({ total: 1, proposals: 1 }) + .mockResolvedValueOnce({ total: 1, proposals: 1 }); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin"), row("team-b", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("3"); + act(() => useStore.setState({ identity: { org: "dev", namespace: "team-b", agent: "loom-ui" } })); + await painted(); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("2"); + act(() => useStore.setState((s) => ({ reviewDecisions: s.reviewDecisions + 1 }))); + await painted(); + expect(countReview).toHaveBeenCalledTimes(3); + expect(countReview).toHaveBeenLastCalledWith({ org: "dev", namespace: "team-b" }, { fresh: true }); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("2"); + }); + + // A decision drops only the deciding replica's cached count: the read it starts counts + // fresh, and the minute's polls after it read the cache again. + it("counts fresh after a decision and from the cache on the minute's polls", async () => { + const intervals = vi.spyOn(globalThis, "setInterval"); + try { + sessionStorage.clear(); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + act(() => useStore.setState((s) => ({ reviewDecisions: s.reviewDecisions + 1 }))); + await painted(); + const [minute] = intervals.mock.calls.filter(([, ms]) => ms === 60_000).pop() ?? []; + act(() => (minute as () => void)()); + await painted(); + const id = { org: "dev", namespace: "team-a" }; + expect(vi.mocked(countReview).mock.calls).toEqual([ + [id, { fresh: false }], + [id, { fresh: true }], + [id, { fresh: false }], + ]); + } finally { + intervals.mockRestore(); + } + }); + + // A fresh read cut off by a re-run never shows its answer, so the next read counts fresh. + it("counts fresh again when the read after a decision is cut off", async () => { + sessionStorage.clear(); + let cutOff: (r: ReviewCounts) => void = () => {}; + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + vi.mocked(countReview).mockReturnValueOnce(new Promise((r) => (cutOff = r))); + act(() => useStore.setState((s) => ({ reviewDecisions: s.reviewDecisions + 1 }))); + await painted(); + act(() => useStore.setState((s) => ({ whoami: { ...(s.whoami as WhoAmI) } }))); + await painted(); + await act(async () => cutOff({ total: 0, proposals: 0 })); + const id = { org: "dev", namespace: "team-a" }; + expect(vi.mocked(countReview).mock.calls).toEqual([ + [id, { fresh: false }], + [id, { fresh: true }], + [id, { fresh: true }], + ]); + }); + + // A refused fresh read shows no count, so the decision waits for the next fresh read. + it("counts fresh again after a refused read until a count is shown", async () => { + sessionStorage.clear(); + vi.mocked(countReview).mockResolvedValueOnce({ total: 0, proposals: 1 }); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + useStore.setState({ view: "admin:health" }); + render(); + await painted(); + expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("1"); + vi.mocked(countReview).mockRejectedValueOnce(new Error("refused")); + act(() => useStore.setState((s) => ({ reviewDecisions: s.reviewDecisions + 1 }))); + await painted(); + act(() => useStore.setState((s) => ({ whoami: { ...(s.whoami as WhoAmI) } }))); + await painted(); + expect(screen.getByRole("link", { name: /Review queue/ })).not.toHaveTextContent("1"); + act(() => useStore.setState((s) => ({ whoami: { ...(s.whoami as WhoAmI) } }))); + await painted(); + const id = { org: "dev", namespace: "team-a" }; + expect(vi.mocked(countReview).mock.calls).toEqual([ + [id, { fresh: false }], + [id, { fresh: true }], + [id, { fresh: true }], + [id, { fresh: false }], + ]); + }); + + // Closed, the Admin button carries the queue's count and says what it counts. + it("names the review count on the closed Admin button", async () => { + sessionStorage.clear(); + vi.mocked(countReview).mockResolvedValueOnce({ total: 0, proposals: 2 }); + seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); + render(); + await painted(); + expect(screen.getByRole("button", { name: "Admin, 2 to review" })).toBeInTheDocument(); }); it("is shown for a platform admin regardless of grants, with the Users entry", async () => { @@ -231,7 +394,7 @@ describe("the admin list on every width", () => { }); it("is the same on the phone's More sheet: the drawer's entries in its order, Review queue and its count included", async () => { - vi.mocked(countConflicts).mockResolvedValueOnce(3); + vi.mocked(countReview).mockResolvedValueOnce({ total: 3, proposals: 0 }); seed({ ...viewer, roles: ["PLATFORM_ADMIN"] }, [row("team-a", "admin")]); useStore.setState({ view: "admin:health" }); render(); @@ -253,7 +416,7 @@ describe("the admin list on every width", () => { }); it("keeps the sheet's Review queue past the badge cache's minute: the sheet reads the store", async () => { - vi.mocked(countConflicts).mockResolvedValueOnce(3); + vi.mocked(countReview).mockResolvedValueOnce({ total: 3, proposals: 0 }); seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); render(); await painted(); @@ -279,7 +442,7 @@ describe("the admin list on every width", () => { }); it("drops the previous namespace's Review queue from the open sheet on a namespace switch", async () => { - vi.mocked(countConflicts).mockResolvedValueOnce(3); + vi.mocked(countReview).mockResolvedValueOnce({ total: 3, proposals: 0 }); seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin"), row("team-b", "admin")]); render(); await painted(); @@ -289,23 +452,23 @@ describe("the admin list on every width", () => { const admin = () => within(sheet).getByRole("navigation", { name: "Review" }); expect(within(admin()).getByRole("link", { name: /Review queue/ })).toHaveTextContent("3"); act(() => useStore.setState({ identity: { org: "dev", namespace: "team-b", agent: "loom-ui" } })); - expect(within(admin()).queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(within(admin()).getByRole("link", { name: /Review queue/ })).not.toHaveTextContent("3"); await painted(); - expect(within(admin()).queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(within(admin()).getByRole("link", { name: /Review queue/ })).not.toHaveTextContent("3"); }); it("shows no badge from the other org after an org switch", async () => { - vi.mocked(countConflicts).mockResolvedValueOnce(3); + vi.mocked(countReview).mockResolvedValueOnce({ total: 3, proposals: 0 }); seed({ ...viewer, roles: ["PLATFORM_ADMIN"] }, null); useStore.setState({ view: "admin:health" }); render(); await painted(); expect(screen.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(screen.getByRole("link", { name: /Review queue/ })).not.toHaveTextContent("3"); await painted(); - expect(countConflicts).toHaveBeenLastCalledWith({ org: "other", namespace: "team-a" }); - expect(screen.queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(countReview).toHaveBeenLastCalledWith({ org: "other", namespace: "team-a" }, { fresh: false }); + expect(screen.getByRole("link", { name: /Review queue/ })).not.toHaveTextContent("3"); }); it("draws Usage's warning dot and the Agents count on the More sheet", async () => { @@ -321,14 +484,14 @@ describe("the admin list on every width", () => { }); it("writes nothing once unmounted while a read is out", async () => { - let settle: (n: number) => void = () => {}; - vi.mocked(countConflicts).mockReturnValueOnce(new Promise((r) => (settle = r))); + let settle: (r: ReviewCounts) => void = () => {}; + vi.mocked(countReview).mockReturnValueOnce(new Promise((r) => (settle = r))); seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); const { unmount } = render(); await painted(); - expect(countConflicts).toHaveBeenCalledTimes(1); + expect(countReview).toHaveBeenCalledTimes(1); unmount(); - await act(async () => settle(3)); + await act(async () => settle({ total: 3, proposals: 0 })); expect(useStore.getState().adminBadges).toBeNull(); expect(sessionStorage.getItem("loom_badge_v1:badges:dev/team-a")).toBeNull(); }); @@ -338,24 +501,24 @@ describe("the admin list on every width", () => { "loom_badge_v1:badges:dev/team-a", JSON.stringify({ at: Date.now(), v: { conflicts: 3, autoResolved: false, overCap: false, newAgents: 0 } }), ); - vi.mocked(countConflicts).mockRejectedValueOnce(new Error("offline")); + vi.mocked(countReview).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"); await painted(); - expect(screen.queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(screen.getByRole("link", { name: "Review queue" })).not.toHaveTextContent(/\d/); }); it("shows the reads' answers together, once the slowest settles", async () => { let settle: (n: number) => void = () => {}; vi.mocked(countNewAgents).mockReturnValueOnce(new Promise((r) => (settle = r))); - vi.mocked(countConflicts).mockResolvedValueOnce(3); + vi.mocked(countReview).mockResolvedValueOnce({ total: 3, proposals: 0 }); seed({ ...viewer, roles: ["WRITER"] }, [row("team-a", "admin")]); useStore.setState({ view: "admin:health" }); render(); await painted(); - expect(screen.queryByRole("link", { name: /Review queue/ })).toBeNull(); + expect(screen.getByRole("link", { name: /Review queue/ })).not.toHaveTextContent("3"); await act(async () => settle(2)); expect(screen.getByRole("link", { name: /Review queue/ })).toHaveTextContent("3"); expect(screen.getByRole("link", { name: /Agents/ })).toHaveTextContent("2"); diff --git a/frontend/src/layout/Sidebar.tsx b/frontend/src/layout/Sidebar.tsx index 1a3c53b916f..045c5443c8b 100644 --- a/frontend/src/layout/Sidebar.tsx +++ b/frontend/src/layout/Sidebar.tsx @@ -4,7 +4,7 @@ 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 { countNewAgents, countReview, type MyNamespaceEntry, type WhoAmI } from "../api"; import { readSession, useAfterPaint, writeSession } from "../lib/afterPaint"; import { sharedBudgetStatus, sharedHasAutoResolved } from "../lib/sharedReads"; import { hasOrgAdminClaim, hasPlatformAdminClaim, isNamespaceAdmin } from "../lib/role"; @@ -74,11 +74,8 @@ export const MAIN: NavItem[] = RAIL_GROUPS.flatMap((g) => g.items); export const SETTINGS_ITEM: NavItem = { id: "setup", label: "Settings", icon: "gear", scope: "namespace" }; export const DOCS_ITEM: NavItem = { id: "help", label: "Documentation", icon: "book" }; -// Admin drawer items. Review queue is HIDDEN by default — it's a -// usually-empty surface (conflicts/learnings only appear on -// multi-writer namespaces) and a permanent rail entry advertising -// emptiness is noise. The route stays resolvable for deep links; when there's actually -// something to review the entry slides in automatically via the badge logic below. +// Admin drawer items. Review queue is added by `adminItems` for an admin of a memory +// namespace, so it can be found with nothing pending or after a failed count. // // Badges are layered on at render time by `adminItems` so the // labels can come straight from the const while count / warning @@ -180,15 +177,15 @@ export function adminItems( return { ...item, badge: badges.newAgents, badgeTone: "accent" }; return item; }); - const open = !!badges?.conflicts; - 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. + if (!isMemoryNamespace(namespace, mine)) return items; + const conflicts = badges?.conflicts; + // The Review queue counts the review items waiting: open conflicts plus pending proposals. const review: NavItem = { id: "admin:review_queue", label: "Review queue", - icon: open ? "warning" : "flash", - badge: badges?.conflicts || undefined, + // Open conflicts warn; otherwise the entry shows the Auto-resolved tab's icon. + icon: conflicts ? "warning" : "flash", + badge: (conflicts ?? 0) + (badges?.proposals ?? 0), }; return [review, ...items]; } @@ -207,6 +204,10 @@ export function Sidebar() { // Lean notification surface: badge admin items that have actionable state right now. The // answer is kept in the store, where the phone's More sheet reads it too. const badges = useStore((s) => s.adminBadges); + // A Review queue decision reads the badges again for the namespace shown now, and drops + // an answer still in flight from before it. + const decisions = useStore((s) => s.reviewDecisions); + const decisionsCounted = useRef(decisions); const agentsTick = useRef(0); const whoami = useStore((s) => s.whoami); @@ -218,16 +219,17 @@ export function Sidebar() { // principal on a jwt-only namespace has no user row, so its list_mine is empty or // fails; polling on "unknown" would fire conflicts.list + cost.budget_status every 30 s // into AUTH_INSUFFICIENT. Unknown does not poll. - const roleHere = roleOnNamespace(whoami, myNamespaces, identity?.namespace ?? ""); - // The badges count conflicts, budget and agents of the memory plane; a code index or a - // tracker namespace has none, so its admin is not polled for them either. - const pollsBadges = roleHere === "admin" && isMemoryNamespace(identity?.namespace ?? "", myNamespaces); + const namespaceHere = identity?.namespace ?? ""; + const roleHere = roleOnNamespace(whoami, myNamespaces, namespaceHere); + // The badges count conflicts, proposals, budget and agents of the memory plane; a code + // index or a tracker namespace has none, so its admin is not polled for them either. + const pollsBadges = roleHere === "admin" && isMemoryNamespace(namespaceHere, myNamespaces); - const visibleAdmin = adminItems(whoami, myNamespaces, identity?.namespace ?? "", badges); - const conflicts = visibleAdmin.find((item) => item.id === "admin:review_queue")?.badge; + const visibleAdmin = adminItems(whoami, myNamespaces, namespaceHere, badges); + const pending = visibleAdmin.find((item) => item.id === "admin:review_queue")?.badge; - // Fetch conflict count + recent auto-resolutions + budget + agents activity on identity - // change and refresh every 60s. All four are fail-quiet — a missing + // Fetch the conflict and proposal counts + recent auto-resolutions + budget + agents activity + // on identity change and refresh every 60s. All four are fail-quiet — a missing // backend op just leaves its badge hidden. Only for a known admin of this // namespace: otherwise a viewer-only token draws AUTH_INSUFFICIENT 403s on every page // load, and a token-only principal through the fail-open gate. Each call also passes @@ -252,11 +254,16 @@ export function Sidebar() { const next: AdminBadges = { conflicts: 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 }) - .then((n) => { - next.conflicts = n; + // The badge asks for the numbers, not 100 rows with their values (33 MB per tick + // on a large namespace). The same read counts the pending proposals. A decision drops + // only its own replica's cache, so the first read after one counts fresh. + countReview( + { org: identity.org, namespace: identity.namespace }, + { fresh: decisionsCounted.current !== decisions }, + ) + .then((r) => { + next.conflicts = r.total ?? 0; + next.proposals = r.proposals; }) .catch(() => { /* hide */ @@ -310,6 +317,8 @@ export function Sidebar() { // One answer once every read settles: a failed read hides its badge. await Promise.allSettled(tasks); if (cancelled) return; + // Counted once a count is shown: a read cut off by a re-run or refused leaves the next one fresh. + if (next.conflicts !== null) decisionsCounted.current = decisions; useStore.setState({ adminBadges: next }); writeSession(badgeKey, next); }; @@ -336,7 +345,7 @@ export function Sidebar() { clearInterval(id); document.removeEventListener("visibilitychange", onVisible); }; - }, [identity, pollsBadges, roleHere, whoami, badgeKey]); + }, [identity, pollsBadges, roleHere, whoami, badgeKey, decisions]); return (