diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index ab30a1ad78..8d0209f0f8 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1818,8 +1818,7 @@ behind does not check: without `code`, from N-1, is shown by its `reason`. - Build N-1 compares no hash on a rejection, accepts one without it, and rejects the newest row of the key, whichever pending proposal the reviewer read. While both builds - serve, decide a key that several pending proposals hold only once every server is on N; - the dashboard offers no decision for a key that several of the proposals it lists hold. + serve, decide a key that several pending proposals hold only once every server is on N. A page listed oldest first (`order="oldest"`, the dashboard's **Oldest first**) can hold a key's older proposal while the key's newest lies past the page, and nothing on that page shows the key is shared. While both builds serve, reject from the newest order. diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 704dce31a5..0786e7b06e 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -957,10 +957,17 @@ The Proposals tab's toolbar lists the queue **Newest first** or **Oldest first** proposals that waited longest. It counts the list, and says which end it shows when the list is cut ("the oldest 100 of 140 proposals"). A server a release behind lists the newest first only: the toggle goes back to **Newest first** and says the other order is not available. -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: +For an administrator of the namespace each row has a checkbox, except a sensitive row, +which says why and is decided from its own review. Each of several pending proposals under +one key is decided from its own row, in its review or in a batch, and the decision names the +row by the hash of the text read. When another listed proposal of the key lists that hash, +the decision would land on that proposal, or on neither: the review offers no decision and +says why, and an **Accept…** plan leaves the text out. A batch holds one row of a key: +while one proposal of a key is selected, the checkbox of another proposal of that key is +unavailable and says why, and the select-all checkbox takes one row of each key. A link +that names such a key opens none of its proposals and says how many hold it. 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 diff --git a/docs/features/memory/writing.md b/docs/features/memory/writing.md index a39fce65b7..e7fd55599c 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -457,17 +457,21 @@ agent, when the fact was first proposed, its graded runs and the advice above th text, and holds both decisions: the tab supplies the displayed hash when an administrator accepts, and a rejection can carry a reason. A rejection cannot be undone: the fact has to be 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 +A call decides one pending row of a key, and the tab decides each of several pending +proposals of one key from its own row. When another listed proposal of the key lists the +hash of the text a review read, the review offers no decision and says why: the decision +would land on that proposal, or on neither. 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 +out a text it could not read or whose hash another listed proposal of its key lists, and +sends the hash of each read. A `high` row has no checkbox and is decided from its own +review. A batch takes one row of a key: while one proposal of a key is selected, the +checkbox of another proposal of that key is unavailable. +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: @@ -495,6 +499,8 @@ two of them share decides neither. Among several pending proposals of one key a named by the hash `memory.proposals` lists, so a value whose listed and full-read hashes differ, such as an object with a null field, is rejected with the listed hash, answers `changed` to an acceptance, and is accepted once it is the key's only pending proposal. +A full-read hash that another pending proposal of the key lists names that proposal, so +compare it with the key's listed hashes before sending it. A call whose keys hold more pending proposals than `memory_proposals_scan_cap` is refused with a 422 and decides nothing: send fewer keys. The owner's automatic policy names no text, so it rejects a key only while one pending proposal holds it. diff --git a/frontend/src/lib/useRowSelection.test.tsx b/frontend/src/lib/useRowSelection.test.tsx index e364bd4b53..78197883df 100644 --- a/frontend/src/lib/useRowSelection.test.tsx +++ b/frontend/src/lib/useRowSelection.test.tsx @@ -5,8 +5,11 @@ import { useRowSelection } from "./useRowSelection"; const NAMES = ["one", "two", "three", "four", "five"]; -function List({ names = NAMES }: { names?: string[] }) { - const sel = useRowSelection(names); +/** "two" and "three" are one group; every other row is its own. */ +const paired = (name: string) => (name === "three" ? "two" : name); + +function List({ names = NAMES, groupOf }: { names?: string[]; groupOf?: (name: string) => string }) { + const sel = useRowSelection(names, { groupOf }); return ( <> @@ -88,4 +91,38 @@ describe("useRowSelection", () => { rerender(); expect(picked()).toBe("four"); }); + + it("keeps one selected row of a group on a tick and on select-all", async () => { + // Fails when a tick or the select-all checkbox selects two rows of one group, or when + // select-all drops the row of a group that was selected before it. + render(); + const user = userEvent.setup(); + const all = screen.getByLabelText("Select all on this page"); + await user.click(screen.getByLabelText("Select three")); + await user.click(screen.getByLabelText("Select two")); + expect(picked()).toBe("three"); + await user.click(all); + expect(new Set(picked()?.split(","))).toEqual(new Set(["one", "three", "four", "five"])); + // One row of every group is selected, so the next click clears them. + expect(all).toBeChecked(); + await user.click(all); + expect(picked()).toBe(""); + // With none selected, each group gives its first row on the page. + await user.click(all); + expect(picked()).toBe("one,two,four,five"); + }); + + it("a range passes over the other row of a group, and takes the row clicked", async () => { + // Fails when a Shift-click selects two rows of one group, or leaves the clicked row out + // for an unselected row of its group earlier in the range. + render(); + const user = userEvent.setup(); + await user.click(screen.getByLabelText("Select one")); + await user.keyboard("{Shift>}"); + await user.click(screen.getByLabelText("Select three")); + expect(picked()).toBe("one,three"); + await user.click(screen.getByLabelText("Select five")); + await user.keyboard("{/Shift}"); + expect(new Set(picked()?.split(","))).toEqual(new Set(["one", "three", "four", "five"])); + }); }); diff --git a/frontend/src/lib/useRowSelection.ts b/frontend/src/lib/useRowSelection.ts index db31e38913..3a7f579a7a 100644 --- a/frontend/src/lib/useRowSelection.ts +++ b/frontend/src/lib/useRowSelection.ts @@ -7,7 +7,7 @@ export interface RowSelection { /** Toggle one row; with `range` (a Shift-click), select every row from the last one * toggled to this one instead. */ toggle: (key: string, range?: boolean) => void; - /** Every row on the page is selected (and there is one). */ + /** Every row on the page is selected (and there is one); with `groupOf`, one of each group. */ allSelected: boolean; /** Select every row on the page, or clear them all once they are. */ toggleAll: () => void; @@ -16,6 +16,19 @@ export interface RowSelection { drop: (keys: readonly string[]) => void; } +/** The group of a row on a page that names none: the row alone. */ +const alone = (key: string) => key; + +/** Adds each of `more` to `next`, in its order, unless a row of its group is there already. */ +function add(next: Set, more: readonly string[], group: (key: string) => string) { + const held = new Set([...next].map(group)); + for (const key of more) { + if (held.has(group(key))) continue; + held.add(group(key)); + next.add(key); + } +} + /** * The checkbox selection of a list page: one row at a time as Click UI's selectable Table, * plus Loom's own range and clear (Click UI's Table has neither): a Shift-click selects the @@ -24,8 +37,15 @@ export interface RowSelection { * page). `keys` are the page's rows in their order on screen; a selected row that leaves the * page (a new page, a search) leaves the selection, so a bulk action only ever acts on rows * in view. + * + * `groupOf` names a row's group, for a bulk action that takes one row of each: a tick, a + * range and the select-all checkbox pass over a row while another row of its group is + * selected. A range takes the row clicked before any other row of its group. */ -export function useRowSelection(keys: readonly string[], { enabled = true }: { enabled?: boolean } = {}): RowSelection { +export function useRowSelection( + keys: readonly string[], + { enabled = true, groupOf = alone }: { enabled?: boolean; groupOf?: (key: string) => string } = {}, +): RowSelection { const [picked, setPicked] = useState>(new Set()); const onPage = useMemo(() => new Set(keys), [keys]); const selected = useMemo(() => { @@ -41,6 +61,8 @@ export function useRowSelection(keys: readonly string[], { enabled = true }: { e keysRef.current = keys; const selectedRef = useRef(selected); selectedRef.current = selected; + const groupRef = useRef(groupOf); + groupRef.current = groupOf; const anchor = useRef(null); const toggle = useCallback((key: string, range = false) => { @@ -50,11 +72,14 @@ export function useRowSelection(keys: readonly string[], { enabled = true }: { e const to = all.indexOf(key); if (range && from >= 0 && to >= 0) { const [lo, hi] = from < to ? [from, to] : [to, from]; - for (const k of all.slice(lo, hi + 1)) next.add(k); + const group = groupRef.current; + // Of the rows of the clicked row's group, the range holds the clicked one alone. + const span = all.slice(lo, hi + 1).filter((k) => k === key || group(k) !== group(key)); + add(next, span, group); } else if (next.has(key)) { next.delete(key); } else { - next.add(key); + add(next, [key], groupRef.current); } anchor.current = key; setPicked(next); @@ -72,11 +97,16 @@ export function useRowSelection(keys: readonly string[], { enabled = true }: { e setPicked((prev) => new Set([...prev].filter((k) => !out.has(k)))); }, []); - const allSelected = keys.length > 0 && selected.size === keys.length; + // The most rows a selection holds: one of each group. + const most = useMemo(() => new Set(keys.map(groupOf)).size, [keys, groupOf]); + const allSelected = keys.length > 0 && selected.size === most; const toggleAll = useCallback(() => { anchor.current = null; const all = keysRef.current; - setPicked(selectedRef.current.size === all.length ? new Set() : new Set(all)); + const next = new Set(selectedRef.current); + add(next, all, groupRef.current); + // Nothing was left to take: every row that can be selected is, so the click clears them. + setPicked(next.size === selectedRef.current.size ? new Set() : new Set(all.filter((k) => next.has(k)))); }, []); const escape = useMemo(() => ({ Escape: clear }), [clear]); diff --git a/frontend/src/views/admin/Proposals.test.tsx b/frontend/src/views/admin/Proposals.test.tsx index 787a4e5d0f..6a9907bcb7 100644 --- a/frontend/src/views/admin/Proposals.test.tsx +++ b/frontend/src/views/admin/Proposals.test.tsx @@ -59,6 +59,8 @@ const COVERED: MemoryProposal = { ...P, checks: checks() }; /** A reason as the server words it. */ const READY = { code: "policy_ready", title: "Meets the evidence thresholds" }; const SCOPE = { org: "acme", namespace: "team" }; +/** Why a text is not decided while another listed proposal of its key lists its hash. */ +const SAME_TEXT = "Another pending proposal of this key holds this text, so a decision cannot name this one."; const HOME = "/admin/review_queue?tab=proposals"; const address = () => window.location.pathname + window.location.search; @@ -826,23 +828,80 @@ describe("ProposalsPanel", () => { ); }); - it("a key two proposals hold opens with neither decision available", async () => { - const other = { ...P, memory_id: "m2", agent: "cursor" }; - const lone = { ...P, memory_id: "m3", memory_key: "standup_time" }; - await show([P, other, lone]); - expect(screen.getAllByRole("button", { name: "deploy_window" })).toHaveLength(2); + it("a shared key is decided from its row", async () => { + // Fails when the review of a key two proposals hold offers no decision, or sends + // anything but the hash read for the row it opened. + const other = { ...P, memory_id: "m2", agent: "nightly-agent", content_sha256: "d".repeat(64) }; + await show([P, other]); + vi.mocked(api.listProposals).mockResolvedValue({ proposals: [P], total: 1 }); + await userEvent.click(screen.getAllByRole("button", { name: "deploy_window" })[1]); + const dialog = await screen.findByRole("dialog", { name: "Review proposal" }); + await within(dialog).findByText("The complete proposal text"); + expect(api.getMemoryById).toHaveBeenCalledWith("acme", "m2"); + for (const name of ["Reject", "Accept reviewed fact"]) + expect(screen.getByRole("button", { name })).not.toHaveAttribute("aria-disabled"); + await userEvent.click(screen.getByRole("button", { name: "Reject" })); + await waitFor(() => + expect(api.decideProposals).toHaveBeenCalledWith( + SCOPE, + ["deploy_window"], + "reject", + { deploy_window: other.content_sha256 }, + "", + ), + ); + // The key's other proposal is still listed, and is accepted under its own hash. + await waitFor(() => + expect(screen.getByRole("button", { name: "deploy_window" })).not.toHaveAttribute("aria-disabled"), + ); await open(); - // A decision names only the key, so neither of the two can take one; each says why. + await userEvent.click(screen.getByRole("button", { name: "Accept reviewed fact" })); + await waitFor(() => + expect(api.decideProposals).toHaveBeenLastCalledWith( + SCOPE, + ["deploy_window"], + "accept", + { deploy_window: P.content_sha256 }, + "", + ), + ); + }); + + it("offers no decision on a text that another listed proposal of its key lists", async () => { + // Fails when a review sends, for the row it read, the hash the list serves for another + // row of the key: the server decides that row, or neither. + const other = { ...P, memory_id: "m2", agent: "nightly-agent", content_sha256: "d".repeat(64) }; + // The full read of the first row answers the hash listed for the second. + vi.mocked(api.getMemoryById).mockImplementation(async (_org, id) => + id === "m1" ? whole(P, { content_sha256: other.content_sha256 }) : whole(other), + ); + await show([P, other]); + const dialog = await open(); for (const name of ["Reject", "Accept reviewed fact"]) { - const decision = screen.getByRole("button", { name }); - expect(decision).toHaveAttribute("aria-disabled", "true"); - expect(decision).toHaveAccessibleDescription(/More than one proposal holds this key/); - await userEvent.click(decision); + const button = within(dialog).getByRole("button", { name }); + expect(button).toHaveAttribute("aria-disabled", "true"); + expect(button).toHaveAccessibleDescription(SAME_TEXT); + await userEvent.click(button); } expect(api.decideProposals).not.toHaveBeenCalled(); - await userEvent.click(screen.getByRole("button", { name: "Cancel" })); - await open("standup_time"); - expect(screen.getByRole("button", { name: "Reject" })).not.toHaveAttribute("aria-disabled"); + await userEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + // The read of the second row answers its own listed hash, which names it. + await userEvent.click(screen.getAllByRole("button", { name: "deploy_window" })[1]); + await within(await screen.findByRole("dialog", { name: "Review proposal" })).findByText( + "The complete proposal text", + ); + for (const name of ["Reject", "Accept reviewed fact"]) + expect(screen.getByRole("button", { name })).not.toHaveAttribute("aria-disabled"); + await userEvent.click(screen.getByRole("button", { name: "Reject" })); + await waitFor(() => + expect(api.decideProposals).toHaveBeenCalledWith( + SCOPE, + ["deploy_window"], + "reject", + { deploy_window: other.content_sha256 }, + "", + ), + ); }); it("opening a proposal writes its key to the address and closing drops it", async () => { @@ -909,7 +968,8 @@ describe("ProposalsPanel", () => { expect(screen.getByRole("table", { name: "Proposals" }).closest("[tabindex='-1']")).toHaveFocus(); }); - it("a key several proposals hold says how many and opens no dialog", async () => { + it("a link to a shared key shows the notice", async () => { + // Fails when a link that names a key, and no row of it, opens one of the key's proposals. const other = { ...P, memory_id: "m2", agent: "cursor" }; showLinked("deploy_window", [P, other], { proposals: [P, other], total: 2 }); await notice("2 pending proposals hold this key, so this link opens none of them."); @@ -1007,6 +1067,12 @@ const THIRD: MemoryProposal = { value_preview: "Roll back before asking", }; +/** Another pending proposal under the key of `P`, with its own listed hash. */ +const TWIN: MemoryProposal = { ...P, memory_id: "m4", agent: "nightly-agent", content_sha256: "d".repeat(64) }; + +/** The checkboxes of the rows under the key of `P`, in the list's order. */ +const siblings = () => screen.getAllByRole("checkbox", { name: "Select deploy_window" }); + /** 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}` })); @@ -1079,21 +1145,87 @@ describe("a batch of proposals", () => { expect(api.getMemoryById).not.toHaveBeenCalled(); }); - it("a shared-key row and a sensitive row take no checkbox, and each says why", async () => { + it("a sensitive row takes no checkbox and 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; + await show([P, high, SECOND]); + expect(screen.getAllByRole("checkbox")).toHaveLength(2); + const row = (name: string) => screen.getByRole("button", { name }).closest("tr") as HTMLElement; + expect(within(row("door_code")).queryByRole("checkbox")).toBeNull(); 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(); + expect(within(row("standup_time")).queryByText(/one at a time/)).toBeNull(); + // Select all takes the rows that can be in a batch. + await pick("deploy_window", "standup_time"); + expect(screen.getByRole("checkbox", { name: "Select all 2 on this page" })).toBeChecked(); + }); + + it("the sibling of a selected row cannot be selected", async () => { + // Fails when two rows of one key enter one batch: by a tick, by Space on the row's key + // or by Select all. + const why = "Another proposal of this key is selected; decide them one batch at a time."; + await show([P, TWIN, SECOND]); + vi.mocked(api.listProposals).mockResolvedValue({ proposals: [P, TWIN, SECOND], total: 3 }); + expect(siblings()).toHaveLength(2); + for (const box of siblings()) expect(box).toBeEnabled(); + expect(screen.queryByText(why)).toBeNull(); + await userEvent.click(siblings()[1]); + expect(siblings()[1]).toBeChecked(); + // The row above holds the same key: its checkbox says why it takes no tick. + expect(siblings()[0]).toBeDisabled(); + expect(siblings()[0]).toHaveAccessibleDescription(why); + const first = screen.getAllByRole("button", { name: "deploy_window" })[0]; + expect(within(first.closest("tr") as HTMLElement).getByText(why)).toBeInTheDocument(); + await userEvent.click(siblings()[0]); + first.focus(); + await userEvent.keyboard(" "); + expect(siblings()[0]).not.toBeChecked(); + // Select all takes one row of each key, and keeps the row already selected. + const all = screen.getByRole("checkbox", { name: "Select all 2 on this page" }); + await userEvent.click(all); + expect(all).toBeChecked(); + expect(siblings()[0]).not.toBeChecked(); + expect(screen.getByRole("checkbox", { name: "Select standup_time" })).toBeChecked(); + // The plan holds one row of the key, under that row's listed hash. + const dialog = await plan("Reject"); + expect(within(dialog).getAllByText("deploy_window")).toHaveLength(1); + 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: TWIN.content_sha256, standup_time: SECOND.content_sha256 }, + "", + ), + ); + }); + + it("a Shift-click over the sibling of a selected row leaves it out", async () => { + // Fails when a range takes both rows of a key. + await show([P, TWIN, SECOND]); + await userEvent.click(siblings()[0]); + const user = userEvent.setup(); + await user.keyboard("{Shift>}"); + await user.click(screen.getByRole("checkbox", { name: "Select standup_time" })); + await user.keyboard("{/Shift}"); + expect(screen.getByRole("checkbox", { name: "Select standup_time" })).toBeChecked(); + expect(siblings()[0]).toBeChecked(); + expect(siblings()[1]).not.toBeChecked(); + expect(siblings()[1]).toBeDisabled(); + expect(screen.getAllByText("2 selected").length).toBeGreaterThan(0); + }); + + it("unticking a row gives its sibling's checkbox back", async () => { + // Fails when a row stays unavailable after the selected row of its key is unticked. + await show([P, TWIN]); + await userEvent.click(siblings()[0]); + expect(siblings()[1]).toBeDisabled(); + await userEvent.click(siblings()[0]); + expect(siblings()[1]).toBeEnabled(); + expect(siblings()[1]).toHaveAccessibleDescription(""); + await userEvent.click(siblings()[1]); + expect(siblings()[1]).toBeChecked(); + expect(siblings()[0]).toBeDisabled(); }); it("the reject plan lists each preview, starts on Cancel and sends the listed hashes", async () => { @@ -1262,6 +1394,30 @@ describe("a batch of proposals", () => { expect(await within(dialog).findByText("Accepted 1 of 1")).toBeInTheDocument(); }); + it("leaves out of the acceptance a text that another listed proposal of its key lists", async () => { + // Fails when an acceptance sends, for a row it read, the hash the list serves for an + // unselected row of the key: the server accepts that row, or neither. + vi.mocked(api.getMemoryById).mockImplementation(async (_org, id) => + id === "m1" ? whole(P, { content_sha256: TWIN.content_sha256 }) : whole(SECOND, { value: "Standup is at ten" }), + ); + await show([P, TWIN, SECOND]); + await userEvent.click(siblings()[0]); + await pick("standup_time"); + const dialog = await plan("Accept"); + await within(dialog).findByText("Standup is at ten"); + expect(item(dialog, "deploy_window")).toHaveTextContent(`Left out. ${SAME_TEXT}`); + await userEvent.click(within(dialog).getByRole("button", { name: "Accept 1 proposal" })); + await waitFor(() => + expect(api.decideProposals).toHaveBeenCalledWith( + SCOPE, + ["standup_time"], + "accept", + { standup_time: SECOND.content_sha256 }, + "", + ), + ); + }); + 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. diff --git a/frontend/src/views/admin/Proposals.tsx b/frontend/src/views/admin/Proposals.tsx index a5e7ab24fe..6e72cebd55 100644 --- a/frontend/src/views/admin/Proposals.tsx +++ b/frontend/src/views/admin/Proposals.tsx @@ -1,4 +1,4 @@ -import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { useCallback, 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 { ButtonGroup } from "@clickhouse/click-ui/ButtonGroup"; @@ -49,10 +49,13 @@ const HEADERS = [ // 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."; +// A decision takes one pending row per key and call. +const SIBLING_SELECTED = "Another proposal of this key is selected; decide them one batch at a time."; +// Among several pending rows of a key the server names one by the hash the list serves, +// and a review and an acceptance send the hash of the full read. +const SAME_TEXT = "Another pending proposal of this key holds this text, so a decision cannot name this one."; // The server keeps at most this much of a rejection's reason. const REASON_MAX = 512; @@ -82,10 +85,23 @@ interface Review extends Read { proposal: MemoryProposal; } -/** A decision on the selected rows, as the list held them when its plan opened. */ +/** A decision on the selected rows, as the list held them when its plan opened, and every + * row the list held then. */ interface Batch { decision: "accept" | "reject"; proposals: MemoryProposal[]; + listed: MemoryProposal[]; +} + +/** Whether a row of `listed` other than `proposal` holds its key and lists `sha`, the hash + * of the full read of `proposal`: a decision sent with it lands on that row, or on neither. */ +function listedElsewhere(listed: MemoryProposal[], proposal: MemoryProposal, sha: string | undefined): boolean { + return ( + !!sha && + listed.some( + (p) => p.memory_id !== proposal.memory_id && p.memory_key === proposal.memory_key && p.content_sha256 === sha, + ) + ); } /** The read behind a review and behind each text of an acceptance: the complete row of @@ -101,13 +117,6 @@ async function readProposal(scope: Scope, proposal: MemoryProposal): Promise): 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"}`; @@ -264,8 +273,15 @@ export function ProposalsPanel() { [identity.org, identity.namespace, linked], ); + // Why the review holds no decision on the text it read: another listed row of the key + // lists the hash that would be sent. + const sameText = + review && !review.error && listedElsewhere(rows ?? [], review.proposal, review.row?.content_sha256) + ? SAME_TEXT + : null; + const decide = async (decision: "accept" | "reject") => { - if (!review?.row?.content_sha256) return; + if (!review?.row?.content_sha256 || sameText) return; const key = review.proposal.memory_key; // The hash served with the text on screen goes with either decision. const read = { [key]: review.row.content_sha256 }; @@ -299,15 +315,6 @@ export function ProposalsPanel() { setReload((n) => n + 1); }; 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 = 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; // A required suite whose results, read for the text under review, are not satisfied: // the server refuses that accept. Before the read answers, and when it fails, Accept // stays available and the server decides. @@ -316,20 +323,39 @@ export function ProposalsPanel() { const unread = !review?.row || !!review.error; // 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. + // decide whose text and hash the list serves. 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], + // The key of each row a batch can take, by the row's id. + const batchKeys = useMemo( + () => + new Map( + (canDecide ? (rows ?? []) : []).filter((p) => p.sensitivity !== "high").map((p) => [p.memory_id, p.memory_key]), + ), + [rows, canDecide], ); - const inBatch = useMemo(() => new Set(batchable), [batchable]); + const batchable = useMemo(() => [...batchKeys.keys()], [batchKeys]); + const keyOf = useCallback((id: string) => batchKeys.get(id) ?? id, [batchKeys]); 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); + // A decision takes one pending row per key and call, so a batch holds one row per key. // Escape clears the selection only while no dialog is over the list. - const selection = useRowSelection(batchable, { enabled: review === null && batch === null }); + const selection = useRowSelection(batchable, { enabled: review === null && batch === null, groupOf: keyOf }); const selected = selection.selected; + // Why a row takes no tick, by its id: a sensitive row has no checkbox, and a row's + // checkbox is unavailable while another row of its key is selected. The words stand + // under the row's key, where the checkbox is described by them. + const untickable = useMemo(() => { + const taken = new Set([...selected].map(keyOf)); + const why = new Map(); + for (const p of canDecide ? (rows ?? []) : []) { + if (p.sensitivity === "high") why.set(p.memory_id, SENSITIVE_ALONE); + else if (!selected.has(p.memory_id) && taken.has(p.memory_key)) why.set(p.memory_id, SIBLING_SELECTED); + } + return why; + }, [rows, canDecide, selected, keyOf]); + const whyId = useId(); // The bar stays over the skeleton, the rows and a failed read; an empty answer takes it away. const barShown = !!error || rows?.length !== 0; // What last took the focus inside the panel: once it is off the page, it left with the focus. @@ -356,7 +382,7 @@ export function ProposalsPanel() { wasSelecting.current = selecting; }, [selecting, barShown]); const openBatch = (decision: Batch["decision"]) => { - setBatch({ decision, proposals: (rows ?? []).filter((p) => selected.has(p.memory_id)) }); + setBatch({ decision, proposals: (rows ?? []).filter((p) => selected.has(p.memory_id)), listed: rows ?? [] }); setBatchNo((n) => n + 1); }; const batchAnswered = (decided: string[]) => { @@ -420,7 +446,7 @@ export function ProposalsPanel() { label="Reason for rejecting" value={reason} onChange={setReason} - disabled={busy || rejectReason !== null} + disabled={busy || decideReason !== null} maxLength={REASON_MAX} rows={2} aria-describedby={reasonHint} @@ -433,12 +459,12 @@ export function ProposalsPanel() { - + - + @@ -500,7 +526,11 @@ export function ProposalsPanel() { ? { count: selected.size, onClear: selection.clear, - all: { total: batchable.length, checked: selection.allSelected, onToggle: selection.toggleAll }, + all: { + total: new Set(batchKeys.values()).size, + checked: selection.allSelected, + onToggle: selection.toggleAll, + }, actions: [ { label: "Reject…", icon: "cross", danger: true, onClick: () => openBatch("reject") }, { @@ -546,12 +576,14 @@ export function ProposalsPanel() { ? [ { // The checkbox is a 44 px target under a touch pointer (styles.css). - className: inBatch.has(p.memory_id) ? "row-check-cell" : undefined, + className: batchKeys.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) ? ( + label: batchKeys.has(p.memory_id) ? ( selection.toggle(p.memory_id, e.shiftKey)} /> ) : null, @@ -580,8 +612,10 @@ export function ProposalsPanel() {
{p.value_preview}
)} {hasAdvice(p) && } - {canDecide && !inBatch.has(p.memory_id) && ( -
{aloneReason(p, perKey)}
+ {untickable.has(p.memory_id) && ( +
+ {untickable.get(p.memory_id)} +
)} @@ -797,8 +831,9 @@ const PLAN_LIST = "max-h-[50vh] divide-y divide-border overflow-y-auto rounded-m /** 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. */ + * is bound to the hashes of those reads, and leaves out a text it could not read or whose + * hash another listed row of its key lists. A plan shows the key, the proposer and the + * text, and nothing else of the row. */ function BatchDialog({ batch, scope, @@ -829,15 +864,17 @@ function BatchDialog({ const cancel = useRef(null); const close = useRef(null); - // An acceptance reads every text whole as its plan opens, through the review's read. + // An acceptance reads every text whole as its plan opens, through the review's read. A + // text whose hash another listed row of its key lists is left out like one not 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 })), - ); + void readProposal({ org, namespace }, p).then((read) => { + const error = read.error ?? (listedElsewhere(plan.listed, p, read.row?.content_sha256) ? SAME_TEXT : undefined); + if (live) setReads((prev) => ({ ...prev, [p.memory_id]: { ...read, error } })); + }); return () => { live = false; }; @@ -845,7 +882,7 @@ function BatchDialog({ 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. + // acceptance every text but those left out. const sending = proposals.filter((p) => !(accept && reads[p.memory_id]?.error)); const apply = async () => {