Handle incomplete task policies and preserve review limits (#15593)

Apply the reviewed change for Handle incomplete task policies and preserve review limits.

Validation: local typecheck/build and focused regression tests, passing exact-head CI, Greptile 5/5, and independent source review. The PR records full-suite evidence and any local environment limitations.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-10-08 10:20:32 -07:00
1 parent 3d0e74e743
commit 317ed367d4
13 files changed
+452 -30

No files matched your search

@@ -0,0 +1,70 @@
// @vitest-environment jsdom
import { act, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { issueExecutionPolicySchema, type Issue } from "@paperclipai/shared";
import { describe, expect, it, vi } from "vitest";
import { ExecutionParticipantPicker } from "./ExecutionParticipantPicker";
vi.mock("../api/access", () => ({ accessApi: { listUserDirectory: async () => ({ users: [] }) } }));
vi.mock("../lib/sentry", () => ({ captureBrowserException: vi.fn() }));
vi.mock("@/components/ui/popover", () => ({
Popover: ({ children }: { children: ReactNode }) => <div>{children}</div>,
PopoverTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
PopoverContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
function renderPicker(policy: unknown) {
const container = document.createElement("div");
const root = createRoot(container);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const onUpdate = vi.fn();
const issue = { companyId: "company-fixture", executionPolicy: policy } as Issue;
act(() => root.render(<QueryClientProvider client={client}>
<ExecutionParticipantPicker issue={issue} stageType="review" agents={[]} currentUserId="board-reviewer" onUpdate={onUpdate} />
</QueryClientProvider>));
return { container, onUpdate, cleanup: () => { act(() => root.unmount()); client.clear(); } };
}
describe("ExecutionParticipantPicker", () => {
it("adds a reviewer to a valid policy that omits stages without dropping authorization", () => {
const policy = { authorizationPolicy: { trustPreset: "standard" }, maxReviewRounds: 4 };
const { container, onUpdate, cleanup } = renderPicker(policy);
expect(container.textContent).not.toContain("Execution policy unavailable");
const assign = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "Assign to me");
expect(assign).toBeTruthy();
act(() => assign!.click());
expect(onUpdate).toHaveBeenCalledTimes(1);
const updated = onUpdate.mock.calls[0][0].executionPolicy;
expect(issueExecutionPolicySchema.safeParse(updated).success).toBe(true);
expect(updated).toMatchObject({ ...policy, stages: [{ type: "review", participants: [{ type: "user", userId: "board-reviewer" }] }] });
expect(policy).not.toHaveProperty("stages");
cleanup();
});
it("shows an existing reviewer and preserves other policy settings when that reviewer is removed", () => {
const policy = {
authorizationPolicy: { trustPreset: "standard" }, maxReviewRounds: 4,
stages: [{ type: "review", participants: [{ type: "user", userId: "board-reviewer" }] }],
};
const { container, onUpdate, cleanup } = renderPicker(policy);
expect(container.querySelector("button")?.textContent).toBe("You");
const remove = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "No reviewers");
expect(remove).toBeTruthy();
act(() => remove!.click());
expect(onUpdate).toHaveBeenCalledWith({ executionPolicy: {
mode: "normal", commentRequired: true, stages: [],
authorizationPolicy: policy.authorizationPolicy, maxReviewRounds: 4,
} });
expect(policy.stages[0].participants).toHaveLength(1);
cleanup();
});
it("keeps a malformed policy unavailable and exposes no mutation controls", () => {
const { container, onUpdate, cleanup } = renderPicker({ stages: [{ type: "review", participants: {} }] });
expect(container.textContent).toBe("Execution policy unavailable. Refresh to try again.");
expect(container.querySelector("button")).toBeNull();
expect(onUpdate).not.toHaveBeenCalled();
cleanup();
});
});
@@ -11,6 +11,7 @@ import {
buildExecutionPolicy,
stageParticipantValues,
} from "../lib/issue-execution-policy";
import { useExecutionPolicy } from "../hooks/useExecutionPolicy";
import { cn } from "../lib/utils";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { User, Eye, ShieldCheck } from "lucide-react";
@@ -34,6 +35,7 @@ export function ExecutionParticipantPicker({
}: ExecutionParticipantPickerProps) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
const policyAvailable = useExecutionPolicy(issue.executionPolicy).success;
const reviewerValues = stageParticipantValues(issue.executionPolicy, "review");
const approverValues = stageParticipantValues(issue.executionPolicy, "approval");
@@ -73,6 +75,7 @@ export function ExecutionParticipantPicker({
};
const updatePolicy = (nextValues: string[]) => {
if (!policyAvailable) return;
onUpdate({
executionPolicy: buildExecutionPolicy({
existingPolicy: issue.executionPolicy ?? null,
@@ -92,6 +95,10 @@ export function ExecutionParticipantPicker({
const label = stageType === "review" ? "Reviewers" : "Approvers";
const Icon = stageType === "review" ? Eye : ShieldCheck;
if (!policyAvailable) {
return <span role="status" className="text-xs text-muted-foreground">Execution policy unavailable. Refresh to try again.</span>;
}
return (
<Popover open={open} onOpenChange={(o) => { setOpen(o); if (!o) setSearch(""); }}>
<PopoverTrigger asChild>
+62 -8
View File
@@ -2735,10 +2735,10 @@ describe("IssueProperties", () => {
executionPolicy: createExecutionPolicy({
stages: [
{
id: "review-stage",
id: "00000000-0000-4000-8000-000000000010",
type: "review",
approvalsNeeded: 1,
participants: [{ id: "participant-1", type: "agent", agentId: "agent-1", userId: null }],
participants: [{ id: "00000000-0000-4000-8000-000000000012", type: "agent", agentId: "00000000-0000-4000-8000-000000000013", userId: null }],
},
],
}),
@@ -2767,10 +2767,10 @@ describe("IssueProperties", () => {
executionPolicy: createExecutionPolicy({
stages: [
{
id: "approval-stage",
id: "00000000-0000-4000-8000-000000000011",
type: "approval",
approvalsNeeded: 1,
participants: [{ id: "participant-2", type: "user", agentId: null, userId: "user-1" }],
participants: [{ id: "00000000-0000-4000-8000-000000000014", type: "user", agentId: null, userId: "user-1" }],
},
],
}),
@@ -2793,10 +2793,10 @@ describe("IssueProperties", () => {
executionPolicy: createExecutionPolicy({
stages: [
{
id: "review-stage",
id: "00000000-0000-4000-8000-000000000010",
type: "review",
approvalsNeeded: 1,
participants: [{ id: "participant-1", type: "agent", agentId: "agent-1", userId: null }],
participants: [{ id: "00000000-0000-4000-8000-000000000012", type: "agent", agentId: "00000000-0000-4000-8000-000000000013", userId: null }],
},
],
}),
@@ -2819,10 +2819,10 @@ describe("IssueProperties", () => {
executionPolicy: createExecutionPolicy({
stages: [
{
id: "review-stage",
id: "00000000-0000-4000-8000-000000000010",
type: "review",
approvalsNeeded: 1,
participants: [{ id: "participant-1", type: "agent", agentId: "agent-1", userId: null }],
participants: [{ id: "00000000-0000-4000-8000-000000000012", type: "agent", agentId: "00000000-0000-4000-8000-000000000013", userId: null }],
},
],
}),
@@ -2924,6 +2924,60 @@ describe("IssueProperties", () => {
dateNowSpy.mockRestore();
});
it.each([true, false])("clears a monitor with omitted stages while preserving independent limits (authorization: %s)", async (withAuthorization) => {
const onUpdate = vi.fn();
const executionPolicy = {
...(withAuthorization ? { authorizationPolicy: { trustPreset: "standard" } } : {}),
maxReviewRounds: 4,
monitor: { nextCheckAt: "2099-01-01T12:00:00.000Z", notes: "Check service", scheduledBy: "board" },
} as IssueExecutionPolicy;
const before = structuredClone(executionPolicy);
const root = renderProperties(container, {
issue: createIssue({ executionPolicy }), childIssues: [], onUpdate, inline: true,
});
await flush();
expect(container.textContent).toContain("Reviewers");
expect(container.textContent).not.toContain("Execution policy unavailable");
const monitorTrigger = container.querySelector('[data-testid="monitor-row-trigger"]')?.closest("button");
expect(monitorTrigger).toBeTruthy();
await act(async () => { monitorTrigger!.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
const clearButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "Clear");
expect(clearButton).toBeTruthy();
await act(async () => { clearButton!.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
expect(onUpdate).toHaveBeenCalledWith({ executionPolicy: {
mode: "normal", commentRequired: true, stages: [],
...(withAuthorization ? { authorizationPolicy: before.authorizationPolicy } : {}), maxReviewRounds: 4,
} });
expect(executionPolicy).toEqual(before);
act(() => root.unmount());
});
it.each([
{ stages: {} },
{ stages: [null] },
{ stages: [{ type: "review", participants: {} }] },
{ monitor: { nextCheckAt: {}, notes: {} } },
])("keeps malformed policies unavailable without exposing destructive edits: %j", async (executionPolicy) => {
const onUpdate = vi.fn();
const root = renderProperties(container, {
issue: createIssue({ executionPolicy: executionPolicy as unknown as IssueExecutionPolicy }),
childIssues: [], onUpdate, inline: true,
});
await flush();
expect(container.textContent).toContain("Execution policy unavailable. Refresh to try again.");
expect(container.textContent).toContain("Assignee");
expect(container.textContent).not.toContain("No reviewers");
expect(container.textContent).not.toContain("No approvers");
expect(container.textContent).not.toContain("Run review now");
expect(container.querySelector('[data-testid="monitor-row-trigger"]')).toBeNull();
expect(container.querySelector('input[type="datetime-local"]')).toBeNull();
expect(onUpdate).not.toHaveBeenCalled();
act(() => root.unmount());
});
it("renders scheduled, retrying, due, overdue, cleared, and empty monitor row states", async () => {
// Anchored to a fixed *local* time, not a fixed UTC instant. The row renders
// these in the machine's timezone and labels them "Today" only while they
@@ -47,6 +47,7 @@ import { getRecentProjectIds } from "../../lib/recent-projects";
import { orderItemsBySelectedAndRecent } from "../../lib/recent-selections";
import { formatAssigneeUserLabel, formatUserLabel } from "../../lib/assignees";
import { buildExecutionPolicy, stageParticipantValues } from "../../lib/issue-execution-policy";
import { useExecutionPolicy } from "../../hooks/useExecutionPolicy";
import {
formatMonitorAbsolute,
formatMonitorAbsoluteFull,
@@ -246,6 +247,9 @@ export function IssueProperties({
documentDeepLink,
sidePanelContentOnly = false,
}: IssuePropertiesProps) {
const policyResult = useExecutionPolicy(issue.executionPolicy);
const policyAvailable = policyResult.success;
const executionPolicy = policyResult.success ? policyResult.data : null;
const { selectedCompanyId } = useCompany();
const { isMobile } = useSidebar();
const queryClient = useQueryClient();
@@ -392,9 +396,9 @@ export function IssueProperties({
const [newLabelName, setNewLabelName] = useState("");
// token-extraction: allowlisted — color-picker seed state, persisted into label-create payload; a var() string would break that payload.
const [newLabelColor, setNewLabelColor] = useState("#6366f1");
const [monitorAtInput, setMonitorAtInput] = useState(() => toDateTimeLocalValue(issue.executionPolicy?.monitor?.nextCheckAt));
const [monitorNotesInput, setMonitorNotesInput] = useState(issue.executionPolicy?.monitor?.notes ?? "");
const [monitorServiceInput, setMonitorServiceInput] = useState(issue.executionPolicy?.monitor?.serviceName ?? "");
const [monitorAtInput, setMonitorAtInput] = useState(() => toDateTimeLocalValue(executionPolicy?.monitor?.nextCheckAt));
const [monitorNotesInput, setMonitorNotesInput] = useState(executionPolicy?.monitor?.notes ?? "");
const [monitorServiceInput, setMonitorServiceInput] = useState(executionPolicy?.monitor?.serviceName ?? "");
const [runtimeActionMessage, setRuntimeActionMessage] = useState<string | null>(null);
const [runtimeActionErrorMessage, setRuntimeActionErrorMessage] = useState<string | null>(null);
const [unarchiveErrorMessage, setUnarchiveErrorMessage] = useState<string | null>(null);
@@ -999,6 +1003,7 @@ export function IssueProperties({
applyAssignee(next, track);
};
const updateExecutionPolicy = (nextReviewers: string[], nextApprovers: string[]) => {
if (!policyAvailable) return;
onUpdate({
executionPolicy: buildExecutionPolicy({
existingPolicy: issue.executionPolicy ?? null,
@@ -1073,13 +1078,13 @@ export function IssueProperties({
return `${stageLabel} pending${participantLabel ? ` with ${participantLabel}` : ""}`;
})();
useEffect(() => {
setMonitorAtInput(toDateTimeLocalValue(issue.executionPolicy?.monitor?.nextCheckAt));
setMonitorNotesInput(issue.executionPolicy?.monitor?.notes ?? "");
setMonitorServiceInput(issue.executionPolicy?.monitor?.serviceName ?? "");
setMonitorAtInput(toDateTimeLocalValue(executionPolicy?.monitor?.nextCheckAt));
setMonitorNotesInput(executionPolicy?.monitor?.notes ?? "");
setMonitorServiceInput(executionPolicy?.monitor?.serviceName ?? "");
}, [
issue.executionPolicy?.monitor?.nextCheckAt,
issue.executionPolicy?.monitor?.notes,
issue.executionPolicy?.monitor?.serviceName,
executionPolicy?.monitor?.nextCheckAt,
executionPolicy?.monitor?.notes,
executionPolicy?.monitor?.serviceName,
]);
// Re-sync watchdog editor inputs when the persisted watchdog changes (and reset on close).
useEffect(() => {
@@ -1261,6 +1266,7 @@ export function IssueProperties({
? M | null
: never
: never) => {
if (!policyAvailable) return;
const basePolicy = buildExecutionPolicy({
existingPolicy: issue.executionPolicy ?? null,
reviewerValues,
@@ -1270,8 +1276,10 @@ export function IssueProperties({
onUpdate({ executionPolicy: null });
return;
}
const { monitor: _previousMonitor, ...policyWithoutMonitor } = basePolicy ?? {};
onUpdate({
executionPolicy: {
...policyWithoutMonitor,
mode: basePolicy?.mode ?? issue.executionPolicy?.mode ?? "normal",
commentRequired: true,
stages: basePolicy?.stages ?? [],
@@ -1299,11 +1307,11 @@ export function IssueProperties({
setMonitorOpen(false);
};
const monitorState = issue.executionState?.monitor ?? null;
const monitorNextCheckAt = monitorState?.nextCheckAt ?? issue.monitorNextCheckAt ?? issue.executionPolicy?.monitor?.nextCheckAt ?? null;
const monitorNextCheckAt = monitorState?.nextCheckAt ?? issue.monitorNextCheckAt ?? executionPolicy?.monitor?.nextCheckAt ?? null;
const monitorAttemptCount = issue.monitorAttemptCount ?? monitorState?.attemptCount ?? 0;
const monitorLastTriggeredAt = issue.monitorLastTriggeredAt ?? monitorState?.lastTriggeredAt ?? null;
const monitorServiceName = issue.executionPolicy?.monitor?.serviceName ?? monitorState?.serviceName ?? null;
const monitorNotes = issue.executionPolicy?.monitor?.notes ?? monitorState?.notes ?? null;
const monitorServiceName = executionPolicy?.monitor?.serviceName ?? monitorState?.serviceName ?? null;
const monitorNotes = executionPolicy?.monitor?.notes ?? monitorState?.notes ?? null;
const monitorNow = useMonitorCountdown(monitorNextCheckAt);
const monitorRelative = monitorNextCheckAt ? formatMonitorEta(monitorNextCheckAt, monitorNow) : null;
const monitorIsDueNow = monitorRelative === "due now";
@@ -1585,7 +1593,7 @@ export function IssueProperties({
>
Schedule
</button>
{issue.executionPolicy?.monitor ? (
{executionPolicy?.monitor ? (
<button
type="button"
className="inline-flex items-center rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
@@ -2621,6 +2629,11 @@ export function IssueProperties({
</PropertyRow>
) : null}
{!policyAvailable ? (
<PropertyRow label="Execution policy" wrap>
<span role="status" className="text-sm text-muted-foreground">Execution policy unavailable. Refresh to try again.</span>
</PropertyRow>
) : (<>
<PropertyPicker
inline={inline}
label="Reviewers"
@@ -2658,6 +2671,7 @@ export function IssueProperties({
)}
</PropertyPicker>
{nextRunnableExecutionStage === "approval" && approverValues.length > 0 ? runExecutionButton("approval") : null}
</>)}
{currentExecutionLabel && (
<PropertyRow label="Execution">
@@ -2684,6 +2698,7 @@ export function IssueProperties({
</PropertyPicker>
) : null}
{policyAvailable ? (
<PropertyPicker
inline={inline}
label="Monitor"
@@ -2695,6 +2710,7 @@ export function IssueProperties({
>
{monitorContent}
</PropertyPicker>
) : null}
<PropertyPicker
inline={inline}