diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index b441f43d090..7fff1975155 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -501,6 +501,25 @@ key. Under a proposal's text the tab shows the [advice](memory/writing.md#propos the review shows the same as **Advice**, below the graded runs. The advice decides nothing: both decisions stay in the review. A server that sends no advice shows none. +The Proposals tab's toolbar counts the list, and says so when the list is cut ("the newest +100 of 140 proposals"). For an administrator of the namespace each row has a checkbox, except +a sensitive row and a row whose key another listed proposal holds, which say why and are +decided from their own review. While rows are selected the toolbar holds **Reject…** and +**Accept…**, and each opens a plan before anything is sent: + +- **Reject…** lists every selected row's key, proposer and preview, takes one optional reason + kept on each rejected fact, and rejects the rows as listed. A rejection cannot be undone: a + rejected fact has to be proposed again. +- **Accept…** takes at most 20 rows. Its plan reads each text whole and shows it with format + and bidirectional control characters drawn as code points (`U+202E`), marks a proposal that + lands in Conflicts when accepted, and leaves out, by name, a text it could not read. It + accepts each text under the hash of the read the plan shows. + +The plan then shows how many proposals were decided ("Rejected 37 of 40") and one line for +each one left pending, with the reason: its text changed, someone decided it first, the +reviewer proposed it, or an earlier deletion refuses its text. Decided rows leave the +selection and the rows left pending stay selected. + The **Curator** tab (`?tab=curator`) shows a namespace admin the [curator's report](../architecture/curator.md#the-dashboard-tab), one card per section: **Proposals** (how many wait, how long the oldest has waited, how many were filed and diff --git a/docs/features/memory/writing.md b/docs/features/memory/writing.md index af8309c33ec..ca6970d82e6 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -415,6 +415,16 @@ proposed again. A call decides one pending row of a key, and the tab offers no decision for a key that more than one listed proposal holds. Accepting a proposal that recorded a contradiction while on trial stores it `conflicted`, and it waits on the **Conflicts** tab. +An administrator can also tick rows and decide them in one call. **Reject…** takes any +number of the listed rows: its plan shows each row's key, proposer and preview, takes one +optional reason for all of them, and sends the hashes the list served. **Accept…** takes +at most 20: its plan reads each text whole, shows it with format and bidirectional +control characters drawn as code points, says which proposals land in Conflicts, leaves +out a text it could not read, and sends the hash of each read. A `high` row and a key +that more than one listed proposal holds have no checkbox and are decided from their own +review. The result counts the proposals decided and gives one line for each one left +pending, worded from its `code`, or with its `reason` sentence when the dashboard does +not know the code or the server sends none. Learnings have a review of their own: [learnings review queue](./procedures-and-learnings.md#learnings-review-queue). @@ -423,12 +433,12 @@ Learnings have a review of their own: A decision is three calls: list the proposals, read each chosen text whole, decide with the hashes of those reads. Every surface reaches the same three operations. -| Step | HTTP | CLI | Python | TypeScript | MCP | -| -------------------------- | --------------------------------- | ------------------------------------ | --------------------------------------- | ------------------------------ | ----------------------------- | -| Select the proposals | `POST /v1/memory.proposals` | `loom call memory.proposals` | `agent.client.memory.proposals()` | `loom.memory.proposals()` | `loom_memory_proposals` | -| Plan: read each text whole | `POST /v1/memory.get_by_id` | `loom call memory.get_by_id` | `agent.memory.get_by_id()` | `loom.memory.getById()` | `loom_memory_get_by_id` | -| Apply the decision | `POST /v1/memory.proposal_decide` | `loom call memory.proposal_decide` | `agent.client.memory.proposal_decide()` | `loom.memory.proposalDecide()` | `loom_memory_proposal_decide` | -| Read each key's outcome | `results[].code` | `results[].code` in the printed JSON | `out["results"]` | `out.results` | `results` in the tool result | +| Step | HTTP | CLI | Python | TypeScript | MCP | Dashboard | +| -------------------------- | --------------------------------- | ------------------------------------ | --------------------------------------- | ------------------------------ | ----------------------------- | ------------------------------------------------ | +| Select the proposals | `POST /v1/memory.proposals` | `loom call memory.proposals` | `agent.client.memory.proposals()` | `loom.memory.proposals()` | `loom_memory_proposals` | The row checkboxes of the **Proposals** tab | +| Plan: read each text whole | `POST /v1/memory.get_by_id` | `loom call memory.get_by_id` | `agent.memory.get_by_id()` | `loom.memory.getById()` | `loom_memory_get_by_id` | **Accept…** reads and shows each text | +| Apply the decision | `POST /v1/memory.proposal_decide` | `loom call memory.proposal_decide` | `agent.client.memory.proposal_decide()` | `loom.memory.proposalDecide()` | `loom_memory_proposal_decide` | The plan's **Accept** or **Reject** button | +| Read each key's outcome | `results[].code` | `results[].code` in the printed JSON | `out["results"]` | `out.results` | `results` in the tool result | The result's line for each proposal left pending | An acceptance sends the hash of the full read (`memory.get_by_id`), because the reviewer read the whole text. A rejection sends that hash or the one `memory.proposals` listed diff --git a/frontend/e2e/list-tables.spec.ts b/frontend/e2e/list-tables.spec.ts index 03d9c472df8..75ed8e37661 100644 --- a/frontend/e2e/list-tables.spec.ts +++ b/frontend/e2e/list-tables.spec.ts @@ -254,6 +254,57 @@ test("the review queue loads more and counts what it holds of the total", async await expect(page.getByRole("button", { name: "Load more" })).toHaveCount(0); }); +// Under a finger a proposal's checkbox keeps its 16 px box and takes a 44 px tap, in Click +// UI's cards on a phone and in the table at a tablet's width: a tap 20 px from the box's +// centre on each side ticks or unticks it, and none opens the review. +for (const width of [375, 1024]) { + test.describe(`a touch pointer at ${width} px`, () => { + test.use({ viewport: { width, height: 812 }, hasTouch: true, isMobile: true }); + test("a proposal's checkbox is a 44 px target", async ({ page }) => { + await withRows(page); + await open(page, "/admin/review_queue?tab=proposals"); + const check = page.getByRole("checkbox", { name: "Select alerts/threshold/lane-1" }); + let checked = false; + for (const [dx, dy] of [ + [-20, 0], + [20, 0], + [0, -20], + [0, 20], + ]) { + const box = await check.boundingBox(); + if (!box) throw new Error("the checkbox has no box"); + expect(Math.round(box.width)).toBeLessThan(44); + await page.touchscreen.tap(box.x + box.width / 2 + dx, box.y + box.height / 2 + dy); + checked = !checked; + await expect(check, `a tap ${dx}, ${dy} from the centre`).toBeChecked({ checked }); + } + await expect(page.getByRole("dialog")).toHaveCount(0); + }); + }); +} + +// The panel that takes the focus as the selection bar leaves is the toolbar and the whole +// table, taller than the window on a long list: focusing it scrolls nothing. +test("clearing a proposal selection leaves the page where it was scrolled", async ({ page }) => { + await withRows(page); + const many = Array.from({ length: 40 }, (_, i) => ({ + ...proposal(i % 3), + memory_key: `alerts/threshold/lane-${i}`, + memory_id: `proposal-${i}`, + })); + await page.route("**/v1/memory.proposals", (r) => r.fulfill({ json: { proposals: many, total: many.length } })); + await open(page, "/admin/review_queue?tab=proposals"); + const main = page.locator("main#main"); + expect(await main.evaluate((m) => m.scrollHeight - m.clientHeight)).toBeGreaterThan(0); + await page.getByRole("checkbox", { name: "Select alerts/threshold/lane-1", exact: true }).check(); + const before = await main.evaluate((m) => m.scrollTop); + await page.getByRole("button", { name: "Clear selection" }).click(); + await expect(page.getByRole("button", { name: "Clear selection" })).toHaveCount(0); + const bar = page.getByRole("group", { name: "Proposal count and selection" }); + await expect(bar.locator("xpath=ancestor::div[@tabindex='-1'][1]")).toBeFocused(); + expect(await main.evaluate((m) => m.scrollTop)).toBe(before); +}); + test("repositories page above 50 and not below", async ({ page }) => { const one = codeReposFixture(now)[0]; const many = Array.from({ length: 60 }, (_, i) => ({ diff --git a/frontend/src/api/review.ts b/frontend/src/api/review.ts index cc36225cd36..0172df316e9 100644 --- a/frontend/src/api/review.ts +++ b/frontend/src/api/review.ts @@ -184,6 +184,24 @@ export interface MemoryProposal { advice?: "" | "accept" | "reject"; /** Why, in the server's order and words; absent from a server a release behind. */ advice_reasons?: ProposalAdviceReason[]; + /** The facts it contradicted while on trial: accepted, it waits in Conflicts. */ + conflict_with?: string[]; +} + +/** One key's outcome, the fields of + * `server/memory/api/models_proposals.py::MemoryProposalDecision` the tab reads. */ +export interface ProposalDecision { + memory_key: string; + decided: boolean; + /** The row's status after the call. */ + status: string; + /** Why the key was left as it is, as the server's sentence; "" when decided. */ + reason: string; + /** The same as one word of a closed set; absent from a server a release behind. */ + code?: string; + /** The row decided or judged, which for a key with no pending proposal is the key's + * newest row; "" when the key named none, and absent from a server a release behind. */ + memory_id?: string; } /** How many proposals the Review queue asks for, newest first. */ @@ -209,14 +227,15 @@ export async function listProposals( } /** POST /v1/memory.proposal_decide. `approvedSha256` names, per key, the hash served with - * the text the reviewer read, on either decision; `reason` is kept on a rejected fact. */ + * the text the reviewer read, on either decision; `reason` is kept on each rejected fact. + * The answer holds one result per key. */ export async function decideProposals( id: Scope, keys: string[], decision: "accept" | "reject", approvedSha256: Record = {}, reason = "", -): Promise<{ decided: number; results: { memory_key: string; decided: boolean; status: string; reason: string }[] }> { +): Promise<{ decided: number; results: ProposalDecision[] }> { return post("/v1/memory.proposal_decide", { org: id.org, namespace: id.namespace, diff --git a/frontend/src/styles.css b/frontend/src/styles.css index f602301fc8b..a0229f87b80 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -1474,12 +1474,15 @@ textarea[aria-invalid="true"]:focus-visible { } /* A row's checkbox under a coarse pointer is a 44 px target (WCAG 2.5.8), so a tap beside it selects the row instead of opening it. It reaches into Click UI's checkbox markup - (`[role="checkbox"]`): recheck it when Click UI is upgraded. */ + (`[role="checkbox"]`): recheck it when Click UI is upgraded. `.row-check-cell` is the + Click UI Table cell that holds a row's checkbox. */ @media (pointer: coarse) { - .list-row-leading [role="checkbox"] { + .list-row-leading [role="checkbox"], + .row-check-cell [role="checkbox"] { position: relative; } - .list-row-leading [role="checkbox"]::after { + .list-row-leading [role="checkbox"]::after, + .row-check-cell [role="checkbox"]::after { content: ""; position: absolute; top: 50%; @@ -1488,6 +1491,12 @@ textarea[aria-invalid="true"]:focus-visible { height: var(--spacing-hit); transform: translate(-50%, -50%); } + /* Click UI's cell clips what leaves it, and under 769 px its card clips the cell: the + cell is as tall as the target, which reaches over the next cell's padding. */ + .row-check-cell { + overflow: visible; + padding-block: calc((var(--spacing-hit) - var(--click-checkbox-size-all)) / 2); + } } /* A record inside a narrow pane (the Explorer inspector's facts and hits): CardHorizontal sm, diff --git a/frontend/src/test/opNames.ts b/frontend/src/test/opNames.ts index 2a01747153d..7906e79e1c1 100644 --- a/frontend/src/test/opNames.ts +++ b/frontend/src/test/opNames.ts @@ -8,21 +8,24 @@ import { OP_MIN_ROLE } from "../lib/canCall"; // Vite serves a file outside the project's root under `/@fs/`, URL-encoded, which is not a // path on disk. const onDisk = (rel: string) => decodeURIComponent(new URL(rel, import.meta.url).pathname).replace(/^\/@fs\//, "/"); -const SDK_TREE = onDisk("../../../sdk/typescript"); -const GENERATED_OPS = onDisk("../../../sdk/typescript/src/generated/ops.ts"); -/** The generated op table's source, or null in a frontend-only checkout. A checkout with the - * SDK tree must have the table: a partial list would pass every check that reads it. */ -export async function generatedOpsText(): Promise { +/** The text of `file` in `tree`, a directory named from the repository's root, or null in a + * checkout without that tree (a frontend-only one). A checkout with the tree must have the + * file: without it a check passes against a partial list, or against the test's own copy. */ +export async function repositoryText(tree: string, file: string): Promise { // vitest runs on node; the frontend tsconfig carries no node types, so the module is // reached through a computed specifier, and the cast names the two calls used here. type Fs = { existsSync(p: string): boolean; readFileSync(p: string, enc: "utf8"): string }; const fs = (await import(/* @vite-ignore */ "node:" + "fs")) as Fs; - if (fs.existsSync(GENERATED_OPS)) return fs.readFileSync(GENERATED_OPS, "utf8"); - if (fs.existsSync(SDK_TREE)) throw new Error(`sdk/typescript is here but ${GENERATED_OPS} is not`); + const path = onDisk(`../../../${tree}/${file}`); + if (fs.existsSync(path)) return fs.readFileSync(path, "utf8"); + if (fs.existsSync(onDisk(`../../../${tree}`))) throw new Error(`${tree} is here but ${path} is not`); return null; } +/** The generated op table's source, or null in a frontend-only checkout. */ +export const generatedOpsText = () => repositoryText("sdk/typescript", "src/generated/ops.ts"); + export async function opNames(): Promise<{ names: Set; fromRegistry: boolean }> { const names = new Set(Object.keys(OP_MIN_ROLE).filter((op) => op.includes("."))); const text = await generatedOpsText(); diff --git a/frontend/src/views/admin/Proposals.test.tsx b/frontend/src/views/admin/Proposals.test.tsx index dea501dcda3..f987587f44d 100644 --- a/frontend/src/views/admin/Proposals.test.tsx +++ b/frontend/src/views/admin/Proposals.test.tsx @@ -7,6 +7,7 @@ import type { MemoryById, MemoryProposal } from "../../api"; import { useStore } from "../../lib/state"; import { resetNamespaceRoleCache } from "../../lib/namespaceRole"; import { axeViolations } from "../../test/axe"; +import { repositoryText } from "../../test/opNames"; import { ProposalsPanel } from "./Proposals"; vi.mock("../../components/Toast", () => ({ toast: vi.fn(), toastError: vi.fn(), ToastViewport: () => null })); @@ -256,11 +257,23 @@ describe("ProposalsPanel", () => { expect(toast).toHaveBeenCalledWith("Rejected", "ok"); }); - it("shows a high proposal as sensitive, and says the list is cut", async () => { + it("shows a high proposal as sensitive, and the toolbar says the list is cut", async () => { const high = { ...P, memory_id: "m2", memory_key: "door_code", value_preview: "", sensitivity: "high" as const }; await show([P, high], 140); expect(screen.getByText("sensitive")).toBeInTheDocument(); - expect(screen.getByText("The newest 2 proposals are listed; decide some to see the rest.")).toBeInTheDocument(); + const bar = screen.getByRole("group", { name: "Proposal count and selection" }); + expect(within(bar).getByText("the newest 2 of 140 proposals")).toBeInTheDocument(); + // The count replaces the note under the table. + expect(screen.queryByText(/decide some to see the rest/)).toBeNull(); + }); + + it("the toolbar counts a list that holds every proposal", async () => { + await show([P]); + const bar = screen.getByRole("group", { name: "Proposal count and selection" }); + expect(within(bar).getByText("1 proposal")).toBeInTheDocument(); + cleanup(); + await show([P, { ...P, memory_id: "m2", memory_key: "standup_time" }]); + expect(screen.getByText("2 proposals")).toBeInTheDocument(); }); it("shows the advice badge and reason chips", async () => { @@ -290,8 +303,11 @@ describe("ProposalsPanel", () => { advice_reasons: [{ code: "policy_reject", title: "At the failed-run limit" }], }; await show([advised, blocked, failing]); + // An administrator's row leads with its checkbox cell, which the slice leaves out. const cells = (key: string) => - within(screen.getByRole("button", { name: key }).closest("tr") as HTMLElement).getAllByRole("cell"); + within(screen.getByRole("button", { name: key }).closest("tr") as HTMLElement) + .getAllByRole("cell") + .slice(1); // In the Fact cell, after the preview: the badge, then the reasons in the server's order. const cell = cells("deploy_window")[0]; const inOrder = [ @@ -332,7 +348,8 @@ describe("ProposalsPanel", () => { expect(P.ready).toBe("accept"); expect(screen.queryByText(/ready to accept/i)).toBeNull(); const row = screen.getByRole("button", { name: P.memory_key }).closest("tr") as HTMLElement; - expect(within(row).getAllByRole("cell")[3]).toHaveTextContent(/4 passed · 0 failed$/); + // After the checkbox cell: Fact, Agent, Proposed by, Graded runs. + expect(within(row).getAllByRole("cell")[4]).toHaveTextContent(/4 passed · 0 failed$/); const dialog = await open(); expect(within(dialog).queryByText("Advice")).toBeNull(); expect(within(dialog).queryByText(/ready to accept/i)).toBeNull(); @@ -374,8 +391,11 @@ describe("ProposalsPanel", () => { const { actor: _none, ...unnamed } = { ...P, memory_id: "m2", memory_key: "standup_time" }; await show([{ ...P, actor: "human:bob@example.com" }, unnamed]); expect(screen.getByRole("columnheader", { name: "Proposed by" })).toBeInTheDocument(); + // An administrator's row leads with its checkbox cell, which the slice leaves out. const cells = (key: string) => - within(screen.getByRole("button", { name: key }).closest("tr") as HTMLElement).getAllByRole("cell"); + within(screen.getByRole("button", { name: key }).closest("tr") as HTMLElement) + .getAllByRole("cell") + .slice(1); expect(cells("deploy_window")[2]).toHaveTextContent("bob@example.com"); // The table repeats the column's name in each cell for a narrow screen; nothing follows it. expect(cells("standup_time")[2]).toHaveTextContent(/^Proposed by$/); @@ -664,3 +684,583 @@ describe("ProposalsPanel", () => { expect(await axeViolations(dialog)).toEqual([]); }); }); + +/** A second and a third proposal, each under its own key and its own listed hash. */ +const SECOND: MemoryProposal = { + ...P, + memory_id: "m2", + memory_key: "standup_time", + content_sha256: "b".repeat(64), + actor: "human:bob@example.com", + value_preview: "Standup is at ten", +}; +const THIRD: MemoryProposal = { + ...P, + memory_id: "m3", + memory_key: "rollback_rule", + content_sha256: "c".repeat(64), + value_preview: "Roll back before asking", +}; + +/** Ticks the checkbox of each key. */ +async function pick(...keys: string[]) { + for (const key of keys) await userEvent.click(screen.getByRole("checkbox", { name: `Select ${key}` })); +} + +/** Opens the plan of `decision` over the selection. */ +async function plan(decision: "Reject" | "Accept"): Promise { + await userEvent.click(screen.getByRole("button", { name: `${decision}…` })); + return screen.findByRole("dialog", { name: `${decision} proposals` }); +} + +/** The plan's or the result's item that names `key`. */ +function item(dialog: HTMLElement, key: string): HTMLElement { + return within(dialog).getByText(key).closest("li") as HTMLElement; +} + +/** Each id is read whole as its own text under its own hash, as a full read answers. */ +function readsWhole() { + vi.mocked(api.getMemoryById).mockImplementation(async (_org, id) => { + const p = listed.find((row) => row.memory_id === id) ?? P; + return whole(p, { content_sha256: `read-of-${id}`, value: `The complete text of ${p.memory_key}` }); + }); +} + +/** The codes a decision can answer, from the server's table; the set this build words in a + * checkout without the server. */ +async function serverCodes(): Promise { + const source = await repositoryText("server", "memory/domain/proposal_triage.py"); + if (source === null) + return [ + "not_found", + "not_proposed", + "hash_required", + "changed", + "ambiguous", + "not_independent", + "proposer_unknown", + "value_refused", + ]; + return [...source.matchAll(/^[A-Z_]+ = "([a-z_]+)"$/gm)].map((m) => m[1]); +} + +describe("a batch of proposals", () => { + it("offers no selection to a role that cannot decide", async () => { + // Fails when a checkbox shows for a caller whose batch the server would refuse. + signIn("viewer"); + await show([P, SECOND]); + expect(screen.queryByRole("checkbox")).toBeNull(); + expect(screen.queryByRole("columnheader", { name: "Select" })).toBeNull(); + expect(screen.getAllByRole("columnheader")).toHaveLength(5); + }); + + it("gives an administrator a checkbox per row that is never a tab stop", async () => { + // Fails when a row's checkbox is unnamed, takes a tab stop, or Space does not reach it. + await show([P, SECOND]); + expect(screen.getByRole("columnheader", { name: "Select" })).toBeInTheDocument(); + const boxes = ["deploy_window", "standup_time"].map((key) => + screen.getByRole("checkbox", { name: `Select ${key}` }), + ); + await waitFor(() => expect(boxes.map((box) => box.tabIndex)).toEqual([-1, -1])); + screen.getByRole("button", { name: "standup_time" }).focus(); + await userEvent.keyboard(" "); + expect(boxes[1]).toBeChecked(); + expect(boxes[0]).not.toBeChecked(); + // The selection takes the count's place, in the primitive's words. + const bar = screen.getByRole("group", { name: "Proposal count and selection" }); + expect(within(bar).getAllByText("1 selected").length).toBeGreaterThan(0); + expect(within(bar).getByRole("checkbox", { name: "Select all 2 on this page" })).toBeInTheDocument(); + expect(api.getMemoryById).not.toHaveBeenCalled(); + }); + + it("a shared-key row and a sensitive row take no checkbox, and each says why", async () => { + // Fails when a row the batch cannot name by its listed hash can be selected. + const twin = { ...P, memory_id: "m4", agent: "cursor" }; + const high = { ...P, memory_id: "m5", memory_key: "door_code", value_preview: "", sensitivity: "high" as const }; + await show([P, twin, high, SECOND]); + expect(screen.getAllByRole("checkbox")).toHaveLength(1); + expect(screen.getByRole("checkbox", { name: "Select standup_time" })).toBeInTheDocument(); + const row = (name: string, nth = 0) => screen.getAllByRole("button", { name })[nth].closest("tr") as HTMLElement; + expect(within(row("door_code")).getByText("Sensitive proposals are decided one at a time.")).toBeInTheDocument(); + for (const nth of [0, 1]) + expect(within(row("deploy_window", nth)).getByText(/More than one proposal holds this key/)).toBeInTheDocument(); + expect(within(row("standup_time")).queryByText(/one at a time|More than one proposal/)).toBeNull(); + // Select all takes the one row that can be in a batch. + await pick("standup_time"); + expect(screen.getByRole("checkbox", { name: "Select all 1 on this page" })).toBeChecked(); + }); + + it("the reject plan lists each preview, starts on Cancel and sends the listed hashes", async () => { + // Fails when a rejection is bound to anything but the rows as the list showed them. + await show([P, SECOND, THIRD]); + await pick("deploy_window", "standup_time"); + const dialog = await plan("Reject"); + expect(within(dialog).getByRole("button", { name: "Cancel" })).toHaveFocus(); + expect(item(dialog, "deploy_window")).toHaveTextContent("Deploys run on Tuesdays"); + expect(item(dialog, "deploy_window")).toHaveTextContent("Release Bot bot"); + expect(item(dialog, "standup_time")).toHaveTextContent("Standup is at ten"); + expect(item(dialog, "standup_time")).toHaveTextContent("bob@example.com"); + expect(within(dialog).queryByText("rollback_rule")).toBeNull(); + expect( + within(dialog).getByText("A rejection cannot be undone: a rejected fact has to be proposed again."), + ).toBeInTheDocument(); + const reason = within(dialog).getByRole("textbox", { name: "Reason for rejecting" }); + expect(reason).toHaveAccessibleDescription("Optional. Kept on each rejected fact."); + expect(reason).toHaveAttribute("maxlength", "512"); + await userEvent.type(reason, " Out of date "); + // The plan makes no read: the preview is what the reviewer read. + expect(api.getMemoryById).not.toHaveBeenCalled(); + expect(api.decideProposals).not.toHaveBeenCalled(); + await userEvent.click(within(dialog).getByRole("button", { name: "Reject 2 proposals" })); + await waitFor(() => + expect(api.decideProposals).toHaveBeenCalledWith( + SCOPE, + ["deploy_window", "standup_time"], + "reject", + { deploy_window: P.content_sha256, standup_time: SECOND.content_sha256 }, + "Out of date", + ), + ); + expect(api.decideProposals).toHaveBeenCalledTimes(1); + }); + + it("the accept plan reads each text whole and sends each read's hash", async () => { + // Fails when an acceptance goes out for a text that was not read whole, or under the + // listed hash in place of the read's. + readsWhole(); + await show([P, SECOND, THIRD]); + await pick("deploy_window", "standup_time"); + const dialog = await plan("Accept"); + expect(within(dialog).getByRole("button", { name: "Cancel" })).toHaveFocus(); + expect(await within(dialog).findByText("The complete text of deploy_window")).toBeInTheDocument(); + expect(await within(dialog).findByText("The complete text of standup_time")).toBeInTheDocument(); + expect(item(dialog, "standup_time")).toHaveTextContent("bob@example.com"); + expect(api.getMemoryById).toHaveBeenCalledTimes(2); + expect(api.getMemoryById).toHaveBeenCalledWith("acme", "m1"); + expect(api.getMemoryById).toHaveBeenCalledWith("acme", "m2"); + // The plan shows the key, the proposer and the text: no preview, no advice. + expect(within(dialog).queryByText("Deploys run on Tuesdays")).toBeNull(); + await userEvent.click(within(dialog).getByRole("button", { name: "Accept 2 proposals" })); + await waitFor(() => + expect(api.decideProposals).toHaveBeenCalledWith( + SCOPE, + ["deploy_window", "standup_time"], + "accept", + { deploy_window: "read-of-m1", standup_time: "read-of-m2" }, + "", + ), + ); + }); + + it("holds the acceptance until every text is read", async () => { + // Fails when Accept can be pressed over a text still loading. + let answer: (row: MemoryById) => void = () => {}; + await show([P]); + vi.mocked(api.getMemoryById).mockImplementationOnce(() => new Promise((resolve) => (answer = resolve))); + await pick("deploy_window"); + const dialog = await plan("Accept"); + expect(within(dialog).getByText("Loading full proposal…")).toBeInTheDocument(); + expect(within(dialog).getByRole("button", { name: "Accept 1 proposal" })).toBeDisabled(); + await act(async () => answer(whole(P))); + await within(dialog).findByText("The complete proposal text"); + expect(within(dialog).getByRole("button", { name: "Accept 1 proposal" })).toBeEnabled(); + }); + + it("draws format and bidirectional control characters as code points", async () => { + // Fails when a text is accepted with characters the reviewer could not see, or in an + // order other than the stored one. + vi.mocked(api.getMemoryById).mockResolvedValueOnce( + whole(P, { value: "Pay \u202Eeeyolpme\u202C the\u200B \u2066vendor\u2069\u{E0041}" }), + ); + await show([P]); + await pick("deploy_window"); + const dialog = await plan("Accept"); + const text = await within(dialog).findByText(/^Pay /); + expect(text).toHaveTextContent("Pay U+202Eeeyolpme"); + for (const mark of ["U+202E", "U+202C", "U+200B", "U+2066", "U+2069", "U+E0041"]) + expect(within(text).getByText(mark)).toBeInTheDocument(); + expect(text.textContent).not.toMatch(/\p{Cf}/u); + }); + + it("Accept is unavailable above 20 selected, and Reject takes them all", async () => { + // Fails when more texts than a reviewer reads whole can be accepted in one batch. + const rows = Array.from({ length: 21 }, (_, n) => ({ ...P, memory_id: `m${n}`, memory_key: `fact_${n}` })); + await show(rows); + await pick("fact_0"); + await userEvent.click(screen.getByRole("checkbox", { name: "Select all 21 on this page" })); + const accept = screen.getByRole("button", { name: "Accept…" }); + expect(accept).toHaveAttribute("aria-disabled", "true"); + expect(accept).toHaveAccessibleDescription("Accept at most 20 proposals at a time: each is shown in full."); + await userEvent.click(accept); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(api.getMemoryById).not.toHaveBeenCalled(); + expect(screen.getByRole("button", { name: "Reject…" })).not.toHaveAttribute("aria-disabled"); + // One row fewer is a batch a reviewer reads. + await pick("fact_20"); + expect(screen.getByRole("button", { name: "Accept…" })).not.toHaveAttribute("aria-disabled"); + const dialog = await plan("Reject"); + expect(within(dialog).getByRole("button", { name: "Reject 20 proposals" })).toBeInTheDocument(); + }); + + it("a service administrator selects and rejects, with Accept unavailable", async () => { + // Fails when the batch offers an acceptance the server refuses to a service account. + useStore.setState({ + whoami: { authenticated: true, subject: "agent", roles: ["admin"], is_service_account: true }, + }); + await show([P]); + await pick("deploy_window"); + const accept = screen.getByRole("button", { name: "Accept…" }); + expect(accept).toHaveAttribute("aria-disabled", "true"); + expect(accept).toHaveAccessibleDescription("Acceptance needs an authenticated human administrator."); + expect(screen.getByRole("button", { name: "Reject…" })).not.toHaveAttribute("aria-disabled"); + }); + + it("marks a contradicted proposal in the accept plan", async () => { + // Fails when a reviewer accepts a fact without seeing that it lands in Conflicts. + await show([P, { ...SECOND, conflict_with: ["m9"] }]); + await pick("deploy_window", "standup_time"); + const dialog = await plan("Accept"); + await within(dialog).findAllByText("The complete proposal text"); + expect(within(item(dialog, "standup_time")).getByText("Lands in Conflicts when accepted")).toBeInTheDocument(); + expect(within(item(dialog, "deploy_window")).queryByText("Lands in Conflicts when accepted")).toBeNull(); + }); + + it("leaves an unreadable text out of the acceptance, names it and counts it out", async () => { + // Fails when a text the reviewer could not read is sent, or is dropped without a word. + vi.mocked(api.getMemoryById).mockImplementation(async (_org, id) => { + if (id === "m2") throw new Error("unreachable"); + if (id === "m3") return whole(THIRD, { found: false }); + return whole(P); + }); + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 1, + results: [{ memory_key: "deploy_window", decided: true, status: "active", reason: "", code: "" }], + }); + await show([P, SECOND, THIRD]); + await pick("deploy_window", "standup_time", "rollback_rule"); + const dialog = await plan("Accept"); + await within(dialog).findByText("The complete proposal text"); + expect(item(dialog, "standup_time")).toHaveTextContent("Left out. Could not read the full proposal."); + expect(item(dialog, "rollback_rule")).toHaveTextContent("Left out. This proposal is no longer available."); + await userEvent.click(within(dialog).getByRole("button", { name: "Accept 1 proposal" })); + await waitFor(() => + expect(api.decideProposals).toHaveBeenCalledWith( + SCOPE, + ["deploy_window"], + "accept", + { deploy_window: P.content_sha256 }, + "", + ), + ); + // The result counts what was sent. + expect(await within(dialog).findByText("Accepted 1 of 1")).toBeInTheDocument(); + }); + + it("the result lists each undecided row with its words, and decided rows leave the selection", async () => { + // Fails when a row the server left pending is reported as decided, or reported without + // the reason. + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 1, + results: [ + { memory_key: "deploy_window", decided: true, status: "rejected", reason: "", code: "" }, + { + memory_key: "standup_time", + decided: false, + status: "proposed", + reason: "the text changed since it was read; read it again", + code: "changed", + }, + { + memory_key: "rollback_rule", + decided: false, + status: "active", + reason: "not a proposal (status active)", + code: "not_proposed", + // The proposal's own row, as accepted by someone else. + memory_id: THIRD.memory_id, + }, + ], + }); + const before = useStore.getState().reviewDecisions; + await show([P, SECOND, THIRD]); + vi.mocked(api.listProposals).mockResolvedValue({ proposals: [SECOND], total: 1 }); + await pick("deploy_window", "standup_time", "rollback_rule"); + const dialog = await plan("Reject"); + await userEvent.click(within(dialog).getByRole("button", { name: "Reject 3 proposals" })); + expect(await within(dialog).findByText("Rejected 1 of 3")).toHaveAttribute("role", "status"); + expect(item(dialog, "standup_time")).toHaveTextContent("Changed since you read it. Read it again."); + expect(item(dialog, "rollback_rule")).toHaveTextContent("Already accepted."); + expect(within(dialog).queryByText("deploy_window")).toBeNull(); + // The plan is spent: Close alone, which has the focus. + expect(within(dialog).queryByRole("button", { name: "Cancel" })).toBeNull(); + expect(within(dialog).queryByRole("button", { name: /^Reject/ })).toBeNull(); + const close = within(dialog).getAllByRole("button", { name: "Close" }).at(-1) as HTMLElement; + await waitFor(() => expect(close).toHaveFocus()); + // The sidebar counts again and the list is read again behind the result. + expect(useStore.getState().reviewDecisions).toBe(before + 1); + await waitFor(() => expect(api.listProposals).toHaveBeenCalledTimes(2)); + await userEvent.click(close); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + // The row still pending stays selected, and the focus is back on the button pressed. + expect(screen.getByRole("checkbox", { name: "Select standup_time" })).toBeChecked(); + expect(screen.getAllByText("1 selected").length).toBeGreaterThan(0); + await waitFor(() => expect(screen.getByRole("button", { name: "Reject…" })).toHaveFocus()); + expect(api.decideProposals).toHaveBeenCalledTimes(1); + }); + + it("a decided row leaves the selection before the list is read again", async () => { + // Fails when a decided row stays selected until the list catches up, where a second + // batch would send it. + let answer: (v: Listed) => void = () => {}; + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 1, + results: [ + { memory_key: "deploy_window", decided: true, status: "rejected", reason: "", code: "" }, + { memory_key: "standup_time", decided: false, status: "proposed", reason: "changed", code: "changed" }, + ], + }); + await show([P, SECOND]); + vi.mocked(api.listProposals).mockImplementationOnce(() => new Promise((resolve) => (answer = resolve))); + await pick("deploy_window", "standup_time"); + const dialog = await plan("Reject"); + await userEvent.click(within(dialog).getByRole("button", { name: "Reject 2 proposals" })); + await within(dialog).findByText("Rejected 1 of 2"); + // Behind the open result, so read past the dialog's hiding of the page. + expect(screen.getByRole("checkbox", { name: "Select deploy_window", hidden: true })).not.toBeChecked(); + expect(screen.getByRole("checkbox", { name: "Select standup_time", hidden: true })).toBeChecked(); + await act(async () => answer({ proposals: [SECOND], total: 1 })); + }); + + it("closing a result that decided every row puts the focus on the panel", async () => { + // Fails when the focus is left on a toolbar button that went with the selection. + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 2, + results: [ + { memory_key: "deploy_window", decided: true, status: "active", reason: "", code: "" }, + { memory_key: "standup_time", decided: true, status: "conflicted", reason: "", code: "" }, + ], + }); + await show([P, SECOND]); + vi.mocked(api.listProposals).mockResolvedValue({ proposals: [], total: 0 }); + await pick("deploy_window", "standup_time"); + const dialog = await plan("Accept"); + await within(dialog).findAllByText("The complete proposal text"); + await userEvent.click(within(dialog).getByRole("button", { name: "Accept 2 proposals" })); + expect(await within(dialog).findByText("Accepted 2 of 2")).toBeInTheDocument(); + expect(within(dialog).queryByRole("list")).toBeNull(); + await userEvent.click(within(dialog).getAllByRole("button", { name: "Close" }).at(-1) as HTMLElement); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + expect(await screen.findByText("No proposals")).toBeInTheDocument(); + await waitFor(() => expect(screen.getByText("No proposals").closest("[tabindex='-1']")).toHaveFocus()); + }); + + it.each<[string, () => Promise]>([ + [ + "Enter on Clear", + async () => { + screen.getByRole("button", { name: "Clear selection" }).focus(); + await userEvent.keyboard("{Enter}"); + }, + ], + [ + "Escape from Reject…", + async () => { + screen.getByRole("button", { name: "Reject…" }).focus(); + await userEvent.keyboard("{Escape}"); + }, + ], + [ + "Space on the ticked Select all", + async () => { + screen.getByRole("checkbox", { name: "Select all 2 on this page" }).focus(); + await userEvent.keyboard(" "); + }, + ], + ])("%s empties the selection and puts the focus on the panel", async (_how, empty) => { + // Fails when the focus falls to the page as the selection bar leaves: the count that + // takes its place holds no control. + await show([P, SECOND]); + await pick("deploy_window", "standup_time"); + await empty(); + await waitFor(() => expect(screen.queryByRole("button", { name: "Clear selection" })).toBeNull()); + expect(screen.getByRole("checkbox", { name: "Select deploy_window" })).not.toBeChecked(); + const bar = screen.getByRole("group", { name: "Proposal count and selection" }); + expect(bar.closest("[tabindex='-1']")).toHaveFocus(); + }); + + it("says a proposal was decided only when the result names its own row", async () => { + // Fails when a proposal that is gone is reported as accepted or rejected because + // another row, such as another agent's fact, holds its key. + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 0, + results: [ + { + memory_key: "deploy_window", + decided: false, + status: "active", + reason: "not a proposal (status active)", + code: "not_proposed", + memory_id: "m9", + }, + { + memory_key: "standup_time", + decided: false, + status: "rejected", + reason: "not a proposal (status rejected)", + code: "not_proposed", + memory_id: "", + }, + { + memory_key: "rollback_rule", + decided: false, + status: "conflicted", + reason: "not a proposal (status conflicted)", + code: "not_proposed", + memory_id: "m3", + }, + ], + }); + await show([P, SECOND, THIRD]); + await pick("deploy_window", "standup_time", "rollback_rule"); + const dialog = await plan("Reject"); + await userEvent.click(within(dialog).getByRole("button", { name: "Reject 3 proposals" })); + await within(dialog).findByText("Rejected 0 of 3"); + for (const key of ["deploy_window", "standup_time"]) { + expect(item(dialog, key)).toHaveTextContent("Not a pending proposal."); + expect(item(dialog, key)).not.toHaveTextContent("Already"); + } + expect(item(dialog, "rollback_rule")).toHaveTextContent("Already accepted."); + }); + + it("shows the reason sentence of a server a release behind, and of a code it does not know", async () => { + // Fails when an answer without a code, or with one this build has no words for, shows + // nothing or the wrong words. + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 0, + results: [ + { memory_key: "deploy_window", decided: false, status: "active", reason: "not a proposal (status active)" }, + { + memory_key: "standup_time", + decided: false, + status: "proposed", + reason: "words only a later server knows", + code: "from_a_later_server", + }, + ], + }); + await show([P, SECOND]); + await pick("deploy_window", "standup_time"); + const dialog = await plan("Reject"); + await userEvent.click(within(dialog).getByRole("button", { name: "Reject 2 proposals" })); + expect(await within(dialog).findByText("Rejected 0 of 2")).toBeInTheDocument(); + expect(item(dialog, "deploy_window")).toHaveTextContent("not a proposal (status active)"); + expect(item(dialog, "standup_time")).toHaveTextContent("words only a later server knows"); + }); + + it("words every code the server can answer", async () => { + // Fails when the server gains a code the dashboard shows by the server's sentence. + const codes = await serverCodes(); + expect(codes).toContain("value_refused"); + expect(codes.length).toBeGreaterThanOrEqual(8); + const rows = codes.map((code, n) => ({ ...P, memory_id: `m${n}`, memory_key: `key_${code}` })); + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 0, + results: codes.map((code, n) => ({ + memory_key: `key_${code}`, + decided: false, + status: "rejected", + reason: `the server's sentence for ${code}`, + code, + memory_id: `m${n}`, + })), + }); + await show(rows); + await pick(...rows.map((row) => row.memory_key)); + const dialog = await plan("Reject"); + await userEvent.click(within(dialog).getByRole("button", { name: `Reject ${codes.length} proposals` })); + await within(dialog).findByText(`Rejected 0 of ${codes.length}`); + for (const code of codes) expect(item(dialog, `key_${code}`)).not.toHaveTextContent("the server's sentence"); + expect(item(dialog, "key_value_refused")).toHaveTextContent( + "An earlier deletion refuses this text. Delete the proposal.", + ); + expect(item(dialog, "key_not_proposed")).toHaveTextContent("Already rejected."); + expect(item(dialog, "key_not_independent")).toHaveTextContent( + "You proposed this. Another administrator accepts it.", + ); + }); + + it("a batch that gets no answer keeps the plan open for another try", async () => { + // Fails when a failed call closes the plan, or drops the typed reason. + vi.mocked(api.decideProposals).mockRejectedValueOnce(new Error("no answer")); + await show([P, SECOND]); + vi.mocked(api.listProposals).mockResolvedValue({ proposals: [], total: 0 }); + await pick("deploy_window", "standup_time"); + const dialog = await plan("Reject"); + await userEvent.type(within(dialog).getByRole("textbox", { name: "Reason for rejecting" }), "Out of date"); + await userEvent.click(within(dialog).getByRole("button", { name: "Reject 2 proposals" })); + await waitFor(() => expect(toastError).toHaveBeenCalledWith("Decision failed", expect.any(Error))); + await waitFor(() => expect(within(dialog).getByRole("button", { name: "Reject 2 proposals" })).toBeEnabled()); + expect(within(dialog).getByRole("status")).toBeEmptyDOMElement(); + expect(within(dialog).getByRole("textbox", { name: "Reason for rejecting" })).toHaveValue("Out of date"); + // Nothing is known to be decided, so the list is not read again. + expect(api.listProposals).toHaveBeenCalledTimes(1); + await userEvent.click(within(dialog).getByRole("button", { name: "Reject 2 proposals" })); + await waitFor(() => expect(api.decideProposals).toHaveBeenCalledTimes(2)); + expect(vi.mocked(api.decideProposals).mock.calls[1][4]).toBe("Out of date"); + }); + + it("Cancel sends nothing and keeps the selection", async () => { + // Fails when leaving a plan decides, or clears what the reviewer picked. + await show([P, SECOND]); + await pick("deploy_window", "standup_time"); + const dialog = await plan("Reject"); + await userEvent.type(within(dialog).getByRole("textbox", { name: "Reason for rejecting" }), "Out of date"); + await userEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + expect(api.decideProposals).not.toHaveBeenCalled(); + expect(screen.getByRole("checkbox", { name: "Select deploy_window" })).toBeChecked(); + await waitFor(() => expect(screen.getByRole("button", { name: "Reject…" })).toHaveFocus()); + // The next plan starts empty: a reason typed into one is not carried to another. + const again = await plan("Reject"); + expect(within(again).getByRole("textbox", { name: "Reason for rejecting" })).toHaveValue(""); + }); + + it("a row decided from its own review leaves the selection", async () => { + // Fails when a row rejected from its review stays selected for the next batch. + let answer: (v: Listed) => void = () => {}; + await show([P, SECOND]); + vi.mocked(api.listProposals).mockImplementationOnce(() => new Promise((resolve) => (answer = resolve))); + await pick("deploy_window", "standup_time"); + await open(); + await userEvent.click(screen.getByRole("button", { name: "Reject" })); + // Before the list is read again. + await waitFor(() => expect(screen.getByRole("checkbox", { name: "Select deploy_window" })).not.toBeChecked()); + expect(screen.getByRole("checkbox", { name: "Select standup_time" })).toBeChecked(); + await act(async () => answer({ proposals: [SECOND], total: 1 })); + }); + + it("the open plan has no accessibility violation", async () => { + // Fails on an unnamed control or list, or a field whose hint is not tied to it. + readsWhole(); + await show([P, { ...SECOND, conflict_with: ["m9"] }]); + await pick("deploy_window", "standup_time"); + const reject = await plan("Reject"); + expect(await axeViolations(reject)).toEqual([]); + await userEvent.click(within(reject).getByRole("button", { name: "Cancel" })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + const accept = await plan("Accept"); + await within(accept).findByText("The complete text of standup_time"); + expect(await axeViolations(accept)).toEqual([]); + // The result, too. + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 1, + results: [ + { memory_key: "deploy_window", decided: true, status: "active", reason: "", code: "" }, + { memory_key: "standup_time", decided: false, status: "proposed", reason: "changed", code: "changed" }, + ], + }); + await userEvent.click(within(accept).getByRole("button", { name: "Accept 2 proposals" })); + await within(accept).findByText("Accepted 1 of 2"); + expect(await axeViolations(accept)).toEqual([]); + }); +}); diff --git a/frontend/src/views/admin/Proposals.tsx b/frontend/src/views/admin/Proposals.tsx index fb6f19ad001..b7d26379f63 100644 --- a/frontend/src/views/admin/Proposals.tsx +++ b/frontend/src/views/admin/Proposals.tsx @@ -1,15 +1,25 @@ -import { useEffect, useId, useRef, useState } from "react"; +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { Badge } from "@clickhouse/click-ui/Badge"; import { Button } from "@clickhouse/click-ui/Button"; +import { Checkbox } from "@clickhouse/click-ui/Checkbox"; import { Link } from "@clickhouse/click-ui/Link"; import { Table } from "@clickhouse/click-ui/Table"; import { TextAreaField } from "@clickhouse/click-ui/TextAreaField"; -import { decideProposals, getMemoryById, listProposals, type MemoryProposal, type MemoryById } from "../../api"; +import { + decideProposals, + getMemoryById, + listProposals, + type MemoryProposal, + type MemoryById, + type ProposalDecision, + type Scope, +} from "../../api"; import { setViewParam, urlParam, useIdentity, useStore } from "../../lib/state"; import { useNamespaceRoleRead } from "../../lib/namespaceRole"; import { callReason } from "../../lib/callReason"; import { useAbortableEffect } from "../../lib/hooks"; import { useRowNav } from "../../lib/useRowNav"; +import { useRowSelection } from "../../lib/useRowSelection"; import { actorKind, actorName } from "../../lib/tasks"; import { toast, toastError } from "../../components/Toast"; import { AgentBadge, NameBadge } from "../../components/AgentBadge"; @@ -17,6 +27,7 @@ import { Alert } from "../../components/ui/Alert"; import { Chip } from "../../components/ui/Chip"; import { ListState } from "../../components/ui/ListState"; import { ListTime } from "../../components/ui/ListTime"; +import { ListToolbar } from "../../components/ui/ListToolbar"; import { MetaList, MetaRow } from "../../components/ui/Meta"; import { Unavailable } from "../../components/ui/Unavailable"; import { Modal, ModalFooter } from "../../components/ui/Modal"; @@ -29,25 +40,68 @@ const HEADERS = [ { label: "Graded runs", width: "200px" }, { label: "Written", width: "110px" }, ]; +// For a caller who can decide: the rows lead with their checkbox. +const SELECT_HEADERS = [{ label: Select, width: "40px" }, ...HEADERS]; const SHARED_KEY = "More than one proposal holds this key; a decision names only the key, so it cannot choose between them."; +// The list serves neither the text nor the hash of a sensitive row. +const SENSITIVE_ALONE = "Sensitive proposals are decided one at a time."; // The server keeps at most this much of a rejection's reason. const REASON_MAX = 512; +/** The most proposals one acceptance takes: each is read and shown whole before it is sent. */ +const ACCEPT_MAX = 20; +const ACCEPT_OVER = `Accept at most ${ACCEPT_MAX} proposals at a time: each is shown in full.`; + const ADVICE_TEXT = { accept: "Ready to accept", reject: "Suggest rejecting" } as const; -/** The proposal under review, the complete row once it is read, and why it cannot be shown. */ -interface Review { - proposal: MemoryProposal; +/** The complete row of a proposal once it is read, and why it cannot be shown. */ +interface Read { row?: MemoryById; error?: string; } +/** The proposal under review and its read. */ +interface Review extends Read { + proposal: MemoryProposal; +} + +/** A decision on the selected rows, as the list held them when its plan opened. */ +interface Batch { + decision: "accept" | "reject"; + proposals: MemoryProposal[]; +} + +/** The read behind a review and behind each text of an acceptance: the complete row of + * `proposal`, whose hash goes with the decision on the text it served. */ +async function readProposal(scope: Scope, proposal: MemoryProposal): Promise { + try { + const row = await getMemoryById(scope.org, proposal.memory_id); + const gone = + !row.found || row.namespace !== scope.namespace || row.memory_key !== proposal.memory_key || !row.content_sha256; + return { row, error: gone ? "This proposal is no longer available. Refresh the list." : undefined }; + } catch { + return { error: "Could not read the full proposal. Close and try again." }; + } +} + +/** Why a row is decided from its own review and takes no checkbox; null where it takes one. + * `perKey` counts the listed proposals of each key. */ +function aloneReason(proposal: MemoryProposal, perKey: Map): string | null { + if (proposal.sensitivity === "high") return SENSITIVE_ALONE; + return (perKey.get(proposal.memory_key) ?? 0) > 1 ? SHARED_KEY : null; +} + +/** "1 proposal", "37 proposals". */ +const counted = (n: number) => `${n.toLocaleString()} ${n === 1 ? "proposal" : "proposals"}`; + /** Facts on trial (written with `proposed=true`) and how the runs that relied on each * went: a row's key opens its review, which accepts it to serve it by default or rejects - * it to retire it. The address names the proposal under review (`?key=`). */ + * it to retire it. The address names the proposal under review (`?key=`). A caller who can + * decide ticks rows and rejects or accepts them in one batch, from a plan that shows what + * is sent. */ export function ProposalsPanel() { const identity = useIdentity(); const scope = { org: identity.org, namespace: identity.namespace }; @@ -86,30 +140,8 @@ export function ProposalsPanel() { setReason(""); setReview({ proposal }); setViewParam("key", proposal.memory_key); - try { - const row = await getMemoryById(identity.org, proposal.memory_id); - setReview((current) => - current?.proposal === proposal - ? { - proposal, - row, - error: - !row.found || - row.namespace !== identity.namespace || - row.memory_key !== proposal.memory_key || - !row.content_sha256 - ? "This proposal is no longer available. Refresh the list." - : undefined, - } - : current, - ); - } catch { - setReview((current) => - current?.proposal === proposal - ? { proposal, error: "Could not read the full proposal. Close and try again." } - : current, - ); - } + const read = await readProposal(scope, proposal); + setReview((current) => (current?.proposal === proposal ? { proposal, ...read } : current)); }; const closeReview = () => { setReview(null); @@ -184,6 +216,8 @@ export function ProposalsPanel() { try { const r = await decideProposals(scope, [key], decision, read, reason.trim()); const result = r.results[0]; + // A row decided from its review leaves a selection that held it. + if (r.decided > 0) selection.drop([review.proposal.memory_id]); // The sidebar reads its counts again now, not at its next minute. useStore.setState((s) => ({ reviewDecisions: s.reviewDecisions + 1 })); if (r.decided === 0) @@ -210,13 +244,53 @@ export function ProposalsPanel() { const held = busy || reading; // memory.proposal_decide names a proposal by key and decides the newest row of it, so a // key more than one proposal holds cannot be decided for one of them. - const perKey = new Map(); - for (const p of rows ?? []) perKey.set(p.memory_key, (perKey.get(p.memory_key) ?? 0) + 1); + const perKey = useMemo(() => { + const counts = new Map(); + for (const p of rows ?? []) counts.set(p.memory_key, (counts.get(p.memory_key) ?? 0) + 1); + return counts; + }, [rows]); const shared = review !== null && (perKey.get(review.proposal.memory_key) ?? 0) > 1 ? SHARED_KEY : null; const rejectReason = decideReason ?? shared; const unread = !review?.row || !!review.error; - // The rows are one tab stop; the review over them owns the keys while it is open. - const rowNav = useRowNav({ enabled: review === null && (rows?.length ?? 0) > 0 }); + + // A batch names each row by the hash served with it, so it takes the rows the caller can + // decide whose text and hash the list serves, one per key. Checkboxes show on the same + // condition; the server authorizes the call whatever the page offers. + const canDecide = decideReason === null; + const batchable = useMemo( + () => (canDecide ? (rows ?? []).filter((p) => aloneReason(p, perKey) === null).map((p) => p.memory_id) : []), + [rows, perKey, canDecide], + ); + const inBatch = useMemo(() => new Set(batchable), [batchable]); + const [batch, setBatch] = useState(null); + // Counts the plans opened: each starts with no reason typed, no text read and no result. + const [batchNo, setBatchNo] = useState(0); + // Escape clears the selection only while no dialog is over the list. + const selection = useRowSelection(batchable, { enabled: review === null && batch === null }); + const selected = selection.selected; + // The selection bar leaves with its last row, and the count that takes its place holds no + // control: the focus one of the bar's controls held goes to the panel. The panel holds the + // whole table, so the focus must not scroll it into view. + const selecting = selected.size > 0; + const wasSelecting = useRef(selecting); + useLayoutEffect(() => { + const lost = !document.activeElement || document.activeElement === document.body; + if (wasSelecting.current && !selecting && lost) panel.current?.focus({ preventScroll: true }); + wasSelecting.current = selecting; + }, [selecting]); + const openBatch = (decision: Batch["decision"]) => { + setBatch({ decision, proposals: (rows ?? []).filter((p) => selected.has(p.memory_id)) }); + setBatchNo((n) => n + 1); + }; + const batchAnswered = (decided: string[]) => { + // Decided rows leave the selection at once; the rows left pending stay selected. + selection.drop(decided); + useStore.setState((s) => ({ reviewDecisions: s.reviewDecisions + 1 })); + setReading(true); + setReload((n) => n + 1); + }; + // The rows are one tab stop; the dialog over them owns the keys while it is open. + const rowNav = useRowNav({ enabled: review === null && batch === null && (rows?.length ?? 0) > 0 }); // One wrapper in every state, so the focus a decision gives it survives an empty answer. return ( @@ -243,7 +317,7 @@ export function ProposalsPanel() {

Loading full proposal…

) : (
-            {typeof review.row.value === "string" ? review.row.value : JSON.stringify(review.row.value, null, 2)}
+            {valueText(review.row.value)}
           
)}
@@ -276,6 +350,20 @@ export function ProposalsPanel() { + setBatch(null)} + onCloseAutoFocus={(e) => { + // The selection bar leaves with its last row, and the button pressed with it. + if (selected.size > 0) return; + e.preventDefault(); + panel.current?.focus(); + }} + /> {notice && ( ) : ( -
- : undefined} - size="sm" - headers={HEADERS} - rows={(rows ?? []).map((p) => ({ - id: p.memory_id, - items: [ - { - label: ( -
- !held && void openReview(p)} - > - {p.memory_key} - - {p.sensitivity === "high" ? ( - - ) : ( -
{p.value_preview}
- )} - {hasAdvice(p) && } -
- ), - overflowMode: "wrap", - }, - { label: }, - { label: p.actor ? : null }, - { - label: ( - - {p.graded_passes} passed · {p.graded_fails} failed - - ), - }, - { label: }, - ], - }))} - /> - {rows !== null && total > rows.length && ( -

- The newest {rows.length} proposals are listed; decide some to see the rest. -

- )} - + <> + rows.length + ? `the newest ${rows.length.toLocaleString()} of ${counted(total)}` + : counted(rows.length) + } + selection={ + selecting + ? { + count: selected.size, + onClear: selection.clear, + all: { total: batchable.length, checked: selection.allSelected, onToggle: selection.toggleAll }, + actions: [ + { label: "Reject…", icon: "cross", danger: true, onClick: () => openBatch("reject") }, + { + label: "Accept…", + icon: "check", + reason: acceptReason ?? (selected.size > ACCEPT_MAX ? ACCEPT_OVER : null), + onClick: () => openBatch("accept"), + }, + ], + } + : null + } + > + {null} + +
+
: undefined} + size="sm" + headers={canDecide ? SELECT_HEADERS : HEADERS} + rows={(rows ?? []).map((p) => ({ + id: p.memory_id, + isActive: selected.has(p.memory_id), + items: [ + ...(canDecide + ? [ + { + // The checkbox is a 44 px target under a touch pointer (styles.css). + className: inBatch.has(p.memory_id) ? "row-check-cell" : undefined, + // Never a tab stop: Space on the row's key reaches it. + label: inBatch.has(p.memory_id) ? ( + selection.toggle(p.memory_id, e.shiftKey)} + /> + ) : null, + }, + ] + : []), + { + label: ( +
+ !held && void openReview(p)} + > + {p.memory_key} + + {p.sensitivity === "high" ? ( + + ) : ( +
{p.value_preview}
+ )} + {hasAdvice(p) && } + {canDecide && !inBatch.has(p.memory_id) && ( +
{aloneReason(p, perKey)}
+ )} +
+ ), + overflowMode: "wrap", + }, + { label: }, + { label: p.actor ? : null }, + { + label: ( + + {p.graded_passes} passed · {p.graded_fails} failed + + ), + }, + { label: }, + ], + }))} + /> + + )} ); @@ -385,8 +522,6 @@ function ProposalAdvice({ proposal, className = "" }: { proposal: MemoryProposal * advice on it. */ function ProposalFacts({ proposal, reader }: { proposal: MemoryProposal; reader: string }) { const actor = proposal.actor ?? ""; - // A hint only: the server knows the reviewer's linked identities and decides. - const own = reader !== "" && actor.replace(/^(human|process):/, "").toLowerCase() === reader.toLowerCase(); const graded = proposal.graded_passes + proposal.graded_fails > 0; return ( @@ -395,11 +530,7 @@ function ProposalFacts({ proposal, reader }: { proposal: MemoryProposal; reader: {actor && ( - - - {actorKind(actor) === "human" ? "a person" : "an agent"} - - {own && You proposed this, so another administrator accepts it.} + )} @@ -426,3 +557,294 @@ function ProposalFacts({ proposal, reader }: { proposal: MemoryProposal; reader: ); } + +/** Who proposed it, and whether that is a person or an agent. With `reader`, the line for a + * reviewer who proposed it: a hint only, since the server knows the reviewer's linked + * identities and decides. */ +function Proposer({ actor, reader = "" }: { actor: string; reader?: string }) { + const own = reader !== "" && actor.replace(/^(human|process):/, "").toLowerCase() === reader.toLowerCase(); + return ( + <> + + + {actorKind(actor) === "human" ? "a person" : "an agent"} + + {own && You proposed this, so another administrator accepts it.} + + ); +} + +/** A stored value as the text a reviewer reads. */ +function valueText(value: unknown): string { + return typeof value === "string" ? value : (JSON.stringify(value, null, 2) ?? ""); +} + +// A format character (Unicode category Cf: the bidirectional controls, the zero-width +// characters, the tags). It draws nothing, or reorders the text after it. +const FORMAT = /\p{Cf}/gu; + +/** `text` with each format character drawn as its code point, so a reviewer sees every + * character of a text and reads it in the order it is stored. */ +function VisibleText({ text }: { text: string }) { + const parts: ReactNode[] = []; + let at = 0; + for (const m of text.matchAll(FORMAT)) { + const i = m.index ?? 0; + if (i > at) parts.push(text.slice(at, i)); + const code = (m[0].codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0"); + parts.push( + + {`U+${code}`} + , + ); + at = i + m[0].length; + } + parts.push(text.slice(at)); + return <>{parts}; +} + +// The dashboard's words for each code that leaves a proposal undecided: the closed set of +// `server/memory/domain/proposal_triage.py`. +const UNDECIDED = new Map([ + ["not_found", "No proposal holds this key."], + ["not_proposed", "Not a pending proposal."], + ["hash_required", "Not decided: the request named no text."], + ["changed", "Changed since you read it. Read it again."], + ["ambiguous", "Several proposals of this key hold the same text."], + ["not_independent", "You proposed this. Another administrator accepts it."], + ["proposer_unknown", "No proposer is recorded, so it cannot be accepted. Reject it and propose it again."], + ["value_refused", "An earlier deletion refuses this text. Delete the proposal."], +]); + +/** Why `proposal` was left undecided: the words of its result's code, or the server's + * sentence for a code this build does not know and for a server a release behind, which + * sends none. */ +function undecidedWords(result: ProposalDecision | undefined, proposal: MemoryProposal): string { + // The result names the key's newest row. Only when that is this proposal's own row did + // someone decide it before this call reached it: another row holds the key once the + // proposal is gone. + if (result?.code === "not_proposed" && result.memory_id === proposal.memory_id) { + if (result.status === "active" || result.status === "conflicted") return "Already accepted."; + if (result.status === "rejected") return "Already rejected."; + } + return UNDECIDED.get(result?.code ?? "") ?? (result?.reason || "Not decided."); +} + +/** What a batch's answer left: how many of the proposals sent were decided, and each one + * left pending with the reason. */ +interface BatchResult { + decided: number; + sent: number; + undecided: { key: string; why: string }[]; +} + +// A plan's list scrolls inside the dialog, which stays within the window. +const PLAN_LIST = "max-h-[50vh] divide-y divide-border overflow-y-auto rounded-md border border-border"; + +/** The plan of a batch and, once it is sent, its result. A rejection lists each row as the + * list showed it and is bound to the listed hashes. An acceptance reads each text whole, + * is bound to the hashes of those reads, and leaves out a text it could not read. A plan + * shows the key, the proposer and the text, and nothing else of the row. */ +function BatchDialog({ + batch, + scope, + reader, + onAnswered, + onClose, + onCloseAutoFocus, +}: { + /** Null closes the dialog. The panel mounts one dialog per plan, by its `key`. */ + batch: Batch | null; + scope: Scope; + /** The reviewer's subject, for the hint on a proposal of their own. */ + reader: string; + /** The batch was answered: the ids of the rows it decided. */ + onAnswered: (decided: string[]) => void; + onClose: () => void; + onCloseAutoFocus: (e: Event) => void; +}) { + // The plan this dialog was mounted with: it is drawn until the dialog has closed. + const [plan] = useState(batch); + const accept = plan?.decision === "accept"; + const proposals = plan?.proposals ?? []; + const [reads, setReads] = useState>({}); + const [reason, setReason] = useState(""); + const [busy, setBusy] = useState(false); + const [result, setResult] = useState(null); + const reasonHint = useId(); + const cancel = useRef(null); + const close = useRef(null); + + // An acceptance reads every text whole as its plan opens, through the review's read. + const { org, namespace } = scope; + useEffect(() => { + if (plan?.decision !== "accept") return; + let live = true; + for (const p of plan.proposals) + void readProposal({ org, namespace }, p).then( + (read) => live && setReads((prev) => ({ ...prev, [p.memory_id]: read })), + ); + return () => { + live = false; + }; + }, [plan, org, namespace]); + + const loading = accept && proposals.some((p) => !reads[p.memory_id]); + // What the button counts and the call sends: every row of a rejection, and of an + // acceptance every text but those that could not be read. + const sending = proposals.filter((p) => !(accept && reads[p.memory_id]?.error)); + + const apply = async () => { + if (!plan || busy || loading || sending.length === 0) return; + // A rejection is bound to each row as it was listed, an acceptance to each full read. + const hashes = Object.fromEntries( + sending.map((p) => [p.memory_key, (accept ? reads[p.memory_id]?.row?.content_sha256 : p.content_sha256) ?? ""]), + ); + setBusy(true); + try { + const answer = await decideProposals( + scope, + sending.map((p) => p.memory_key), + plan.decision, + hashes, + reason.trim(), + ); + const byKey = new Map(answer.results.map((one) => [one.memory_key, one])); + const decided = sending.filter((p) => byKey.get(p.memory_key)?.decided); + setResult({ + decided: decided.length, + sent: sending.length, + undecided: sending + .filter((p) => !byKey.get(p.memory_key)?.decided) + .map((p) => ({ key: p.memory_key, why: undecidedWords(byKey.get(p.memory_key), p) })), + }); + onAnswered(decided.map((p) => p.memory_id)); + } catch (e) { + // No answer, so nothing is known to be decided: the plan stays open for another try. + toastError("Decision failed", e); + } finally { + setBusy(false); + } + }; + + // The plan's buttons leave with the plan: Close takes the focus they held. + useEffect(() => { + if (result) close.current?.focus(); + }, [result]); + + const verb = accept ? "Accept" : "Reject"; + return ( + !open && !busy && onClose()} + title={`${verb} proposals`} + description={ + accept ? "Read each complete fact before accepting." : "Each proposal is rejected as the list shows it." + } + className="w-full max-w-[720px]" + // Enter on a plan that has just opened does not send it. + onOpenAutoFocus={(e) => { + e.preventDefault(); + cancel.current?.focus(); + }} + onCloseAutoFocus={onCloseAutoFocus} + > + {/* Mounted with the plan, so the result is said when it lands. */} +

+ {result && `${accept ? "Accepted" : "Rejected"} ${result.decided} of ${result.sent}`} +

+ {result ? ( + result.undecided.length > 0 && ( +
    + {result.undecided.map((left) => ( +
  • + {left.key} + {left.why} +
  • + ))} +
+ ) + ) : ( + <> +
    + {proposals.map((p) => { + const read = reads[p.memory_id]; + return ( +
  • +
    + {p.memory_key} + {p.actor && } + {accept && (p.conflict_with ?? []).length > 0 && ( + + )} +
    + {!accept ? ( +

    {p.value_preview}

    + ) : !read ? ( +

    Loading full proposal…

    + ) : read.error ? ( +

    Left out. {read.error}

    + ) : ( +
    +                      
    +                    
    + )} +
  • + ); + })} +
+ {!accept && ( +
+ +

+ Optional. Kept on each rejected fact. +

+

+ A rejection cannot be undone: a rejected fact has to be proposed again. +

+
+ )} + + )} + + {result ? ( + + ) : ( + <> + + + + )} + +
+ ); +}