Files
PaperClipAI/ui/src/components/IssueLinkQuicklook.test.tsx
T
DottaandPaperclip f554d67377 fix(server): add explicit review verdict policies (#10931)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Issues use `in_review` to request a final decision from an
authorized writer
> - The server rejected an assignee agent that tried to close its own
review, even when the issue had no independent-review rule
> - This rejection stopped the default agent workflow and did not
represent the configured execution-stage rules
> - Paperclip needs an open default and explicit issue-level constraints
for teams that require an independent or human verdict
> - This pull request removes the unconditional rejection and adds
`anyone`, `not_creator`, and `human_only` review policies
> - The benefit is a working default path with opt-in, authenticated
verdict controls

## Linked Issues or Issue Description

Refs #10635, #4429, and #10671.

The related public work covers execution-stage independence,
self-approval fallback behavior, and durable review paths. This change
is distinct. It controls who can resolve an issue review verdict. It
keeps configured execution stages active.

## What Changed

- Added a nullable `review_policy` issue column. Null has the same
meaning as `anyone`. The migration does not backfill existing issues.
- Added shared create, update, response, and compact issue contracts for
`anyone`, `not_creator`, and `human_only`.
- Removed the unconditional agent self-approval rejection for
`in_review` issues.
- Added one reusable verdict-actor check for terminal status changes and
pending interaction accept or reject actions.
- Used the authenticated principal type for `human_only`. Agent keys and
run tokens remain agent principals.
- Used the latest transition into `in_review` to identify the requester
for `not_creator`.
- Added actionable 403 responses that name the policy, the allowed
actor, and the next step.
- Kept the configured execution-stage transition and signoff behavior.
- Added focused contract, helper, status-route, interaction-route, and
execution-stage regression tests.
- Updated the implementation specification for the new issue field.

## Verification

- `pnpm exec vitest run packages/shared/src/validators/issue.test.ts
server/src/__tests__/issue-review-policy.test.ts
server/src/__tests__/issue-stalled-review-decision-routes.test.ts
--reporter=dot` passed: 42 tests.
- `pnpm --filter @paperclipai/shared typecheck` passed.
- `pnpm --filter @paperclipai/db typecheck` passed, including migration
numbering and safety checks.
- `pnpm --filter @paperclipai/server typecheck` passed.
- `pnpm run typecheck:build-gaps` passed across server, CLI, plugin
SDK/examples, plugin wiki, and UI.
- `git diff --check origin/master...HEAD` passed.
- SecurityEngineer review approved the authenticated-principal checks
and accepted policy-relaxation tradeoff with no required changes.
- Greptile reviewed the latest head at 5/5 with zero inline comments or
follow-ups.
- The latest-head GitHub rollup passed build, typecheck,
server/workspace tests, serialized suites, canary, e2e, and external
security checks.

## Risks

- The migration adds one nullable text column. It has no default and no
backfill.
- `not_creator` reads the latest recorded transition into `in_review`.
It denies the verdict when it cannot identify the requester.
- Agents can change or relax `reviewPolicy` when they have issue write
access. This is intentional for this issue-level control.
- Null and `anyone` do not add a database query to the verdict path.
- Configured execution-stage checks still run after the issue-level
policy check.

> This work aligns with the completed "Agent Reviews and Approvals" and
"Enforced Outcomes" roadmap items. It does not add a new roadmap
capability.

## Model Used

- OpenAI Codex, GPT-5. The exact deployment ID and context-window size
are not exposed to the agent. The run used reasoning, repository tools,
code execution, and GitHub CLI access.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-08-05 23:12:41 -05:00

304 lines
10 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { MemoryRouter } from "react-router-dom";
import type { Issue } from "@paperclipai/shared";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IssueLinkQuicklook, QUICKLOOK_CONTENT_CLASS, quicklookAlignOffset } from "./IssueLinkQuicklook";
const mockIssuesApiGet = vi.hoisted(() => vi.fn());
vi.mock("@/api/issues", () => ({
issuesApi: {
get: mockIssuesApiGet,
},
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
function createIssue(overrides: Partial<Issue> = {}): Issue {
return {
id: "issue-1",
identifier: "PAP-1",
companyId: "company-1",
projectId: null,
projectWorkspaceId: null,
goalId: null,
parentId: null,
title: "Quicklook title",
description: "Quicklook description",
status: "todo",
priority: "medium",
reviewPolicy: null,
assigneeAgentId: null,
assigneeUserId: null,
responsibleUserId: null,
createdByAgentId: null,
createdByUserId: null,
issueNumber: 1,
requestDepth: 0,
billingCode: null,
assigneeAdapterOverrides: null,
executionWorkspaceId: null,
executionWorkspacePreference: null,
executionWorkspaceSettings: null,
checkoutRunId: null,
executionRunId: null,
executionAgentNameKey: null,
executionLockedAt: null,
startedAt: null,
completedAt: null,
cancelledAt: null,
hiddenAt: null,
createdAt: new Date("2026-05-01T00:00:00.000Z"),
updatedAt: new Date("2026-05-01T00:00:00.000Z"),
labels: [],
labelIds: [],
myLastTouchAt: null,
lastExternalCommentAt: null,
isUnreadForMe: false,
workMode: "standard",
...overrides,
};
}
describe("IssueLinkQuicklook", () => {
let container: HTMLDivElement;
let root: Root;
let queryClient: QueryClient;
beforeEach(() => {
vi.useFakeTimers();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
mockIssuesApiGet.mockResolvedValue(createIssue());
});
afterEach(() => {
act(() => {
root.unmount();
});
queryClient.clear();
container.remove();
vi.useRealTimers();
vi.clearAllMocks();
});
it("keeps portaled quicklook links mounted until after blur click handling", () => {
const issue = createIssue();
act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<IssueLinkQuicklook
issuePathId="PAP-1"
issuePrefetch={issue}
to="/companies/company-1/issues/PAP-1"
>
PAP-1
</IssueLinkQuicklook>
</MemoryRouter>
</QueryClientProvider>,
);
});
const trigger = container.querySelector("a") as HTMLAnchorElement | null;
expect(trigger).not.toBeNull();
act(() => {
trigger?.focus();
});
expect(document.body.textContent).toContain("Quicklook title");
act(() => {
trigger?.blur();
});
expect(document.body.textContent).toContain("Quicklook title");
act(() => {
vi.runOnlyPendingTimers();
});
expect(document.body.textContent).not.toContain("Quicklook title");
});
// Regression: the quicklook could only be closed by a `mouseleave` on the
// trigger or the card, and no leave event fires when the layout shifts the
// trigger out from under a stationary pointer — expanding a decision row does
// exactly that, stranding the card on screen. A pointer move anywhere clear of
// both boxes now closes it.
function renderQuicklook(issueOverrides: Partial<Issue> = {}) {
act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<IssueLinkQuicklook
issuePathId="PAP-1"
issuePrefetch={createIssue(issueOverrides)}
to="/companies/company-1/issues/PAP-1"
>
PAP-1
</IssueLinkQuicklook>
</MemoryRouter>
</QueryClientProvider>,
);
});
return container.querySelector("a") as HTMLAnchorElement;
}
function movePointerTo(x: number, y: number) {
act(() => {
document.dispatchEvent(new MouseEvent("pointermove", { clientX: x, clientY: y, bubbles: true }));
});
}
it("closes an open quicklook once the pointer moves clear of the trigger and the card", () => {
const trigger = renderQuicklook();
act(() => {
trigger.focus();
});
expect(document.body.textContent).toContain("Quicklook title");
// jsdom reports zero-size rects, so every box sits at the origin; a move far
// from it is unambiguously clear of both the trigger and the card.
act(() => {
trigger.blur();
});
movePointerTo(4000, 4000);
expect(document.body.textContent).not.toContain("Quicklook title");
});
// Regression: Radix returns focus to the trigger when a popover closes, and
// this link opens the quicklook `onFocus` — so dismissing it refocused the
// trigger, which reopened it, and hovering away left the card up for good.
it("does not reopen itself by taking focus back when it closes", () => {
const trigger = renderQuicklook();
act(() => {
trigger.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
vi.advanceTimersByTime(200);
});
expect(document.body.textContent).toContain("Quicklook title");
act(() => {
trigger.dispatchEvent(new MouseEvent("mouseout", { bubbles: true, relatedTarget: document.body }));
vi.runOnlyPendingTimers();
});
expect(document.activeElement).not.toBe(trigger);
expect(document.body.textContent).not.toContain("Quicklook title");
});
it("keeps a focus-opened quicklook up while focus stays on the trigger", () => {
const trigger = renderQuicklook();
act(() => {
trigger.focus();
});
expect(document.body.textContent).toContain("Quicklook title");
// A keyboard user moving the mouse must not dismiss what focus opened.
movePointerTo(4000, 4000);
expect(document.body.textContent).toContain("Quicklook title");
});
// The card is the standard task preview for the whole app, so its rows and
// their order are the contract, not incidental markup.
function openCard(trigger: HTMLAnchorElement) {
act(() => {
trigger.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
vi.advanceTimersByTime(200);
});
return document.querySelector('[data-slot="popover-content"]');
}
it("states identity, then title, then summary", () => {
const card = openCard(
renderQuicklook({
status: "in_review",
// The card reads only `name` off the project; the rest of `Project` is
// irrelevant here, so this stands in for a full record.
project: { id: "project-1", name: "Paperclip App" } as unknown as Issue["project"],
}),
);
const text = card?.textContent ?? "";
expect(text).toContain("PAP-1");
expect(text).toContain("Paperclip App");
expect(text).toContain("Quicklook title");
expect(text).toContain("Quicklook description");
expect(text.indexOf("PAP-1")).toBeLessThan(text.indexOf("Quicklook title"));
expect(text.indexOf("Quicklook title")).toBeLessThan(text.indexOf("Quicklook description"));
});
// Status is the glyph, with no word of its own — so it must survive as the
// glyph's accessible name rather than as shape and colour alone.
it("carries the status on the glyph instead of spending a line on it", () => {
const card = openCard(renderQuicklook({ status: "in_review" }));
const glyph = card?.querySelector('[role="img"]');
expect(glyph?.getAttribute("aria-label")).toBe("In review");
// The status must reach a screen reader but occupy no visible text. Drop
// the glyph (whose <title> counts toward textContent) and the word is gone.
const withoutGlyph = card?.cloneNode(true) as HTMLElement;
withoutGlyph.querySelector('[role="img"]')?.remove();
expect(withoutGlyph.textContent).not.toContain("In review");
expect(withoutGlyph.textContent).not.toContain("in_review");
});
it("shows no separator or project when the task has no project", () => {
const card = openCard(renderQuicklook());
expect(card?.querySelector('[data-testid="quicklook-project"]')).toBeNull();
expect(card?.textContent).not.toContain("·");
});
// Radix aligns box to box, so the card's own padding would leave its text
// inset from the trigger's. The offset cancels the padding in whichever
// direction the card is aligned.
it("offsets the card by its padding so its text lines up with the trigger", () => {
// 12px of `p-3` padding plus the 1px border PopoverContent draws.
expect(quicklookAlignOffset("start")).toBe(-13);
expect(quicklookAlignOffset("end")).toBe(13);
expect(quicklookAlignOffset("center")).toBe(0);
expect(quicklookAlignOffset()).toBe(quicklookAlignOffset("start"));
// The offset only holds while the shell keeps that padding.
expect(QUICKLOOK_CONTENT_CLASS).toContain("p-3");
});
it("truncates a long project name but never the task key or the timestamp", () => {
const card = openCard(
renderQuicklook({
project: { id: "p1", name: "Really loooong project name" } as unknown as Issue["project"],
}),
);
const project = card?.querySelector('[data-testid="quicklook-project"]');
expect(project?.getAttribute("title")).toBe("Really loooong project name");
// The name is the only part allowed to give up width.
expect(project?.querySelector(".truncate")?.textContent).toBe("Really loooong project name");
expect(project?.getAttribute("class")).toContain("min-w-0");
const key = Array.from(card?.querySelectorAll("span") ?? []).find((s) => s.textContent === "PAP-1");
expect(key?.getAttribute("class")).toContain("shrink-0");
});
});