Skip to content

The open-source app everyone uses to manage agents at work

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

Devin Foley317ed367d4e7
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index 53ea15d19a..50e1034572 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -174,6 +174,16 @@ checkout, including a non-primary checkout. Changing projects clears the
previous worktree choice. Switching from reuse to a new worktree or the project
workspace restores the project default checkout. Task creation uses the selected company and has
no separate heading or settings control.
+
+Task execution-policy controls apply the shared schema defaults when stages or
+participants are omitted. An invalid policy shows an unavailable notice and
+disables policy edits while leaving other task properties usable. Refresh to
+retry. Optional browser error monitoring reports only a fixed field category,
+once per mounted control; it never includes the policy or task identifiers.
+Edits in the reviewer and monitor controls retain an explicitly configured
+review-round limit when the last reviewer or monitor is removed, so adding a
+reviewer later uses the saved limit.
+
Fresh tasks start with an empty request and the last task assignee chosen in that
company, including a human. If that assignee is unavailable, the CEO is the
default, or the first eligible agent when the company has no CEO. Explicit launch
diff --git a/server/src/__tests__/issue-execution-policy-persistence.test.ts b/server/src/__tests__/issue-execution-policy-persistence.test.ts
new file mode 100644
index 0000000000..743c248efc
--- /dev/null
+++ b/server/src/__tests__/issue-execution-policy-persistence.test.ts
@@ -0,0 +1,45 @@
+import { randomUUID } from "node:crypto";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { companies, createDb, issues } from "@paperclipai/db";
+import { buildExecutionPolicy } from "../../../ui/src/lib/issue-execution-policy.ts";
+import { normalizeIssueExecutionPolicy } from "../services/issue-execution-policy.js";
+import { issueService } from "../services/issues.js";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+
+const support = await getEmbeddedPostgresTestSupport();
+(support.supported ? describe : describe.skip)("edited execution policy persistence", () => {
+ let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
+ let db: ReturnType<typeof createDb>;
+ beforeAll(async () => {
+ temporary = await startEmbeddedPostgresTestDatabase("paperclip-policy-persistence-");
+ db = createDb(temporary.connectionString);
+ }, 30_000);
+ afterAll(async () => { await temporary?.cleanup(); });
+
+ it.each(["reviewer", "monitor"] as const)("retains the independent review limit after removing the last %s", async (removed) => {
+ const companyId = randomUUID();
+ const issueId = randomUUID();
+ const original = normalizeIssueExecutionPolicy({
+ maxReviewRounds: 4,
+ ...(removed === "monitor"
+ ? { monitor: { nextCheckAt: "2099-01-01T00:00:00.000Z" } }
+ : { stages: [{ type: "review", participants: [{ type: "user", userId: "board-reviewer" }] }] }),
+ });
+ await db.insert(companies).values({ id: companyId, name: "Policy fixture", issuePrefix: `P${companyId.slice(0, 6)}` });
+ await db.insert(issues).values({ id: issueId, companyId, title: "Review limit fixture", executionPolicy: original });
+ const edited = buildExecutionPolicy({ existingPolicy: original, reviewerValues: [], approverValues: [] })!;
+ // The monitor editor removes this key after building the unchanged stages.
+ const { monitor: _removedMonitor, ...withoutMonitor } = edited;
+ const normalized = normalizeIssueExecutionPolicy(removed === "monitor" ? withoutMonitor : edited);
+ const service = issueService(db);
+ await service.update(issueId, { executionPolicy: normalized, companyGuard: companyId });
+ const saved = await service.getById(issueId);
+ expect(saved?.executionPolicy).toEqual({ mode: "normal", commentRequired: true, stages: [], maxReviewRounds: 4 });
+
+ const restored = normalizeIssueExecutionPolicy(buildExecutionPolicy({
+ existingPolicy: saved?.executionPolicy,
+ reviewerValues: ["user:board-reviewer"], approverValues: [],
+ }));
+ expect(restored).toMatchObject({ maxReviewRounds: 4, stages: [{ type: "review" }] });
+ });
+});
diff --git a/server/src/__tests__/issue-execution-policy.test.ts b/server/src/__tests__/issue-execution-policy.test.ts
index 8b9d560191..c49890ba0b 100644
--- a/server/src/__tests__/issue-execution-policy.test.ts
+++ b/server/src/__tests__/issue-execution-policy.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { applyIssueExecutionPolicyTransition, normalizeIssueExecutionPolicy, parseIssueExecutionState } from "../services/issue-execution-policy.ts";
import type { IssueExecutionPolicy, IssueExecutionState } from "@paperclipai/shared";
+import { buildExecutionPolicy } from "../../../ui/src/lib/issue-execution-policy.ts";
const coderAgentId = "11111111-1111-4111-8111-111111111111";
const qaAgentId = "22222222-2222-4222-8222-222222222222";
@@ -43,6 +44,23 @@ describe("normalizeIssueExecutionPolicy", () => {
expect(normalizeIssueExecutionPolicy({ stages: [] })).toBeNull();
});
+ it("retains an independent review limit through removing and restoring the last reviewer", () => {
+ const original = normalizeIssueExecutionPolicy({
+ maxReviewRounds: 4,
+ stages: [{ type: "review", participants: [{ type: "agent", agentId: qaAgentId }] }],
+ });
+ const edited = buildExecutionPolicy({ existingPolicy: original, reviewerValues: [], approverValues: [] });
+ const saved = normalizeIssueExecutionPolicy(edited);
+ expect(saved).toEqual({ mode: "normal", commentRequired: true, stages: [], maxReviewRounds: 4 });
+ expect(applyIssueExecutionPolicyTransition({
+ issue: { status: "in_progress", assigneeAgentId: coderAgentId },
+ policy: saved, requestedStatus: "done", requestedAssigneePatch: {}, actor: { agentId: coderAgentId },
+ })).toEqual({ patch: {} });
+ expect(normalizeIssueExecutionPolicy(buildExecutionPolicy({
+ existingPolicy: saved, reviewerValues: [`agent:${qaAgentId}`], approverValues: [],
+ }))).toMatchObject({ maxReviewRounds: 4, stages: [{ type: "review" }] });
+ });
+
it("throws when all participants are invalid (missing agentId)", () => {
expect(() =>
normalizeIssueExecutionPolicy({
diff --git a/server/src/services/issue-execution-policy.ts b/server/src/services/issue-execution-policy.ts
index 859dc5fe1e..ed38f91fb9 100644
--- a/server/src/services/issue-execution-policy.ts
+++ b/server/src/services/issue-execution-policy.ts
@@ -401,7 +401,8 @@ export function normalizeIssueExecutionPolicy(input: unknown): IssueExecutionPol
const reviewPreset = parsed.data.reviewPreset;
const authorizationPolicy = parsed.data.authorizationPolicy;
- if (stages.length === 0 && !monitor && !reviewPreset && !authorizationPolicy) return null;
+ if (stages.length === 0 && !monitor && !reviewPreset && !authorizationPolicy
+ && parsed.data.maxReviewRounds == null) return null;
return {
mode: parsed.data.mode ?? "normal",
diff --git a/ui/src/components/ExecutionParticipantPicker.test.tsx b/ui/src/components/ExecutionParticipantPicker.test.tsx
new file mode 100644
index 0000000000..98fa99a5aa
--- /dev/null
+++ b/ui/src/components/ExecutionParticipantPicker.test.tsx
@@ -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();
+ });
+});
diff --git a/ui/src/components/ExecutionParticipantPicker.tsx b/ui/src/components/ExecutionParticipantPicker.tsx
index b13d60748f..b5aba28216 100644
--- a/ui/src/components/ExecutionParticipantPicker.tsx
+++ b/ui/src/components/ExecutionParticipantPicker.tsx
@@ -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>
diff --git a/ui/src/components/IssueProperties.test.tsx b/ui/src/components/IssueProperties.test.tsx
index 683acb658e..dd19e8712b 100644
--- a/ui/src/components/IssueProperties.test.tsx
+++ b/ui/src/components/IssueProperties.test.tsx
@@ -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
diff --git a/ui/src/components/issue-properties/IssueProperties.tsx b/ui/src/components/issue-properties/IssueProperties.tsx
index db6de10d24..2b00c76aba 100644
--- a/ui/src/components/issue-properties/IssueProperties.tsx
+++ b/ui/src/components/issue-properties/IssueProperties.tsx
@@ -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}
diff --git a/ui/src/hooks/useExecutionPolicy.test.tsx b/ui/src/hooks/useExecutionPolicy.test.tsx
new file mode 100644
index 0000000000..74076b8432
--- /dev/null
+++ b/ui/src/hooks/useExecutionPolicy.test.tsx
@@ -0,0 +1,49 @@
+// @vitest-environment jsdom
+import { StrictMode, act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useExecutionPolicy } from "./useExecutionPolicy";
+
+const capture = vi.hoisted(() => vi.fn());
+vi.mock("../lib/sentry", () => ({ captureBrowserException: capture }));
+
+function Policy({ value }: { value: unknown }) {
+ const result = useExecutionPolicy(value);
+ return <span>{result.success ? "available" : "unavailable"}</span>;
+}
+
+afterEach(() => capture.mockClear());
+
+describe("execution policy diagnostics", () => {
+ it("normalizes valid omissions quietly", () => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ act(() => root.render(<StrictMode><Policy value={{ monitor: { nextCheckAt: "2099-01-01T00:00:00Z" } }} /></StrictMode>));
+ expect(container.textContent).toBe("available");
+ expect(capture).not.toHaveBeenCalled();
+ act(() => root.unmount());
+ });
+
+ it("reports only a closed category once despite repeated rendering and refreshed objects", () => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ const invalid = { stages: "synthetic-private-value", taskId: "synthetic-task-id", monitor: { notes: "synthetic-notes" } };
+ act(() => root.render(<StrictMode><Policy value={invalid} /></StrictMode>));
+ act(() => root.render(<StrictMode><Policy value={structuredClone(invalid)} /></StrictMode>));
+ expect(container.textContent).toBe("unavailable");
+ expect(capture).toHaveBeenCalledTimes(1);
+ const [error, details] = capture.mock.calls[0];
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toBe("Invalid task execution policy (stages)");
+ expect(error.cause).toBeUndefined();
+ expect(details).toBeUndefined();
+ expect(Object.keys(error)).toEqual([]);
+ expect(error.stack).not.toContain("synthetic-");
+
+ act(() => root.render(<StrictMode><Policy value={{ stages: [] }} /></StrictMode>));
+ expect(container.textContent).toBe("available");
+ act(() => root.render(<StrictMode><Policy value={invalid} /></StrictMode>));
+ expect(capture).toHaveBeenCalledTimes(1);
+ act(() => root.unmount());
+ });
+});
diff --git a/ui/src/hooks/useExecutionPolicy.ts b/ui/src/hooks/useExecutionPolicy.ts
new file mode 100644
index 0000000000..5ffcf02f54
--- /dev/null
+++ b/ui/src/hooks/useExecutionPolicy.ts
@@ -0,0 +1,23 @@
+import { useEffect, useMemo, useRef } from "react";
+import { readExecutionPolicy } from "../lib/issue-execution-policy";
+import { captureBrowserException } from "../lib/sentry";
+
+/** Keep an invalid policy visible without crashing the task or enabling edits. */
+export function useExecutionPolicy(value: unknown) {
+ const result = useMemo(() => readExecutionPolicy(value), [value]);
+ const reported = useRef(false);
+ useEffect(() => {
+ if (result.success || reported.current) return;
+ reported.current = true;
+ // Schema diagnostics can contain the original data. Report only a closed
+ // field category, once per mounted component, through the existing gate.
+ const field = result.error.issues[0]?.path[0];
+ const category = field === "stages" ? "stages"
+ : field === "monitor" ? "monitor"
+ : field === "authorizationPolicy" ? "authorization"
+ : field === "reviewPreset" ? "review_preset"
+ : "policy";
+ captureBrowserException(new Error(`Invalid task execution policy (${category})`));
+ }, [result]);
+ return result;
+}
diff --git a/ui/src/lib/issue-execution-policy.test.ts b/ui/src/lib/issue-execution-policy.test.ts
index 83fe0a1b0f..4b16adb2ef 100644
--- a/ui/src/lib/issue-execution-policy.test.ts
+++ b/ui/src/lib/issue-execution-policy.test.ts
@@ -1,9 +1,40 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { issueExecutionPolicySchema } from "@paperclipai/shared";
-import { buildExecutionPolicy } from "./issue-execution-policy";
+import { issueExecutionPolicySchema, type IssueExecutionPolicy } from "@paperclipai/shared";
+import { buildExecutionPolicy, stageParticipantValues } from "./issue-execution-policy";
const AGENT_ID = "00000000-0000-4000-8000-000000000001";
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+const STAGE_ID = "00000000-0000-4000-8000-000000000002";
+const PARTICIPANT_ID = "00000000-0000-4000-8000-000000000003";
+
+describe("reading execution policy defaults", () => {
+ it.each([
+ {},
+ { authorizationPolicy: { trustPreset: "standard" } },
+ { monitor: { nextCheckAt: "2099-01-01T00:00:00.000Z" } },
+ { stages: [{ type: "review" }] },
+ ])("reads schema-valid omitted collections without changing the input: %j", (input) => {
+ expect(issueExecutionPolicySchema.safeParse(input).success).toBe(true);
+ const before = structuredClone(input);
+ expect(stageParticipantValues(input as IssueExecutionPolicy, "review")).toEqual([]);
+ expect(stageParticipantValues(input as IssueExecutionPolicy, "approval")).toEqual([]);
+ expect(input).toEqual(before);
+ });
+
+ it("retains configured reviewers when an unrelated stage omits participants", () => {
+ const policy = {
+ stages: [
+ { type: "approval" },
+ { id: STAGE_ID, type: "review", participants: [
+ { id: PARTICIPANT_ID, type: "agent", agentId: AGENT_ID },
+ { type: "user", userId: "board-reviewer" },
+ ] },
+ ],
+ } as IssueExecutionPolicy;
+ expect(stageParticipantValues(policy, "review")).toEqual([`agent:${AGENT_ID}`, "user:board-reviewer"]);
+ expect(stageParticipantValues(policy, "approval")).toEqual([]);
+ });
+});
describe("buildExecutionPolicy", () => {
afterEach(() => {
@@ -36,4 +67,73 @@ describe("buildExecutionPolicy", () => {
expect(stage.participants[0]?.id).toMatch(UUID_PATTERN);
}
});
+
+ it("adds reviewers to a policy with omitted stages and retains other policy fields", () => {
+ const existingPolicy = {
+ authorizationPolicy: { trustPreset: "standard" },
+ maxReviewRounds: 4,
+ monitor: { nextCheckAt: "2099-01-01T00:00:00.000Z" },
+ } as IssueExecutionPolicy;
+ const before = structuredClone(existingPolicy);
+ const policy = buildExecutionPolicy({ existingPolicy, reviewerValues: [`agent:${AGENT_ID}`], approverValues: [] });
+ expect(issueExecutionPolicySchema.safeParse(policy).success).toBe(true);
+ expect(policy).toMatchObject(before);
+ expect(stageParticipantValues(policy, "review")).toEqual([`agent:${AGENT_ID}`]);
+ expect(existingPolicy).toEqual(before);
+ });
+
+ it("keeps stage and participant identities and governance fields when editing reviewers", () => {
+ const existingPolicy: IssueExecutionPolicy = {
+ mode: "normal", commentRequired: true, maxReviewRounds: 4,
+ authorizationPolicy: { trustPreset: "standard" },
+ stages: [{ id: STAGE_ID, type: "review", approvalsNeeded: 1, participants: [
+ { id: PARTICIPANT_ID, type: "agent", agentId: AGENT_ID, userId: null },
+ ] }],
+ };
+ const policy = buildExecutionPolicy({
+ existingPolicy, reviewerValues: [`agent:${AGENT_ID}`, "user:board-reviewer"], approverValues: [],
+ });
+ expect(policy).toMatchObject({
+ authorizationPolicy: existingPolicy.authorizationPolicy,
+ maxReviewRounds: 4,
+ stages: [{ id: STAGE_ID, participants: [
+ existingPolicy.stages[0].participants[0],
+ { type: "user", userId: "board-reviewer" },
+ ] }],
+ });
+ expect(issueExecutionPolicySchema.safeParse(policy).success).toBe(true);
+ });
+
+ it("does not remove authorization settings when the last reviewer is removed", () => {
+ const existingPolicy = {
+ mode: "normal", commentRequired: true, stages: [],
+ authorizationPolicy: { trustPreset: "standard" },
+ } as IssueExecutionPolicy;
+ expect(buildExecutionPolicy({ existingPolicy, reviewerValues: [], approverValues: [] }))
+ .toEqual(existingPolicy);
+ });
+
+ it.each([
+ { maxReviewRounds: 4 },
+ { maxReviewRounds: 4, stages: [{ id: STAGE_ID, type: "review", participants: [
+ { id: PARTICIPANT_ID, type: "user", userId: "board-reviewer" },
+ ] }] },
+ ])("retains an independent review-round limit when no participants remain: %j", (existingPolicy) => {
+ expect(buildExecutionPolicy({ existingPolicy: existingPolicy as IssueExecutionPolicy, reviewerValues: [], approverValues: [] }))
+ .toEqual({ mode: "normal", commentRequired: true, stages: [], maxReviewRounds: 4 });
+ });
+
+ it("still clears a policy with no participants, monitor, or other settings", () => {
+ expect(buildExecutionPolicy({
+ existingPolicy: { mode: "normal", commentRequired: true, stages: [] },
+ reviewerValues: [], approverValues: [],
+ })).toBeNull();
+ });
+
+ it.each([{ stages: {} }, { stages: [null] }, { stages: [{ type: "review", participants: {} }] }])(
+ "refuses to manufacture a replacement for a malformed policy: %j", (input) => {
+ expect(() => buildExecutionPolicy({ existingPolicy: input as unknown as IssueExecutionPolicy,
+ reviewerValues: [], approverValues: [] })).toThrow();
+ },
+ );
});
diff --git a/ui/src/lib/issue-execution-policy.ts b/ui/src/lib/issue-execution-policy.ts
index 83a1d3d3cb..7d38e723c8 100644
--- a/ui/src/lib/issue-execution-policy.ts
+++ b/ui/src/lib/issue-execution-policy.ts
@@ -1,8 +1,15 @@
import type { IssueExecutionPolicy, IssueExecutionStageParticipant, IssueExecutionStagePrincipal } from "@paperclipai/shared";
+import { issueExecutionPolicySchema } from "@paperclipai/shared";
import { parseAssigneeValue } from "./assignees";
import { createUuid as newId } from "./uuid";
type StageType = "review" | "approval";
+const nullablePolicySchema = issueExecutionPolicySchema.nullable();
+
+/** Apply wire-format defaults without treating an invalid policy as no policy. */
+export function readExecutionPolicy(policy: unknown) {
+ return nullablePolicySchema.safeParse(policy ?? null);
+}
function principalKey(principal: IssueExecutionStagePrincipal | IssueExecutionStageParticipant) {
return principal.type === "agent" ? `agent:${principal.agentId}` : `user:${principal.userId}`;
@@ -24,12 +31,14 @@ export function selectionValueFromPrincipal(principal: IssueExecutionStagePrinci
}
export function stageParticipantValues(policy: IssueExecutionPolicy | null | undefined, stageType: StageType): string[] {
- const stage = policy?.stages.find((candidate) => candidate.type === stageType);
+ const parsed = readExecutionPolicy(policy);
+ if (!parsed.success) return [];
+ const stage = parsed.data?.stages.find((candidate) => candidate.type === stageType);
return stage?.participants.map((participant) => selectionValueFromPrincipal(participant)) ?? [];
}
function mergeParticipants(
- existing: IssueExecutionStageParticipant[] | undefined,
+ existing: Array<IssueExecutionStagePrincipal & { id?: string }> | undefined,
values: string[],
): IssueExecutionStageParticipant[] {
const existingByKey = new Map((existing ?? []).map((participant) => [principalKey(participant), participant]));
@@ -54,11 +63,14 @@ export function buildExecutionPolicy(input: {
reviewerValues: string[];
approverValues: string[];
}): IssueExecutionPolicy | null {
- const mode = input.existingPolicy?.mode ?? "normal";
+ const parsed = readExecutionPolicy(input.existingPolicy);
+ if (!parsed.success) throw new Error("Execution policy is unavailable");
+ const existingPolicy = parsed.data;
+ const mode = existingPolicy?.mode ?? "normal";
const stages: IssueExecutionPolicy["stages"] = [];
const monitor = input.existingPolicy?.monitor ?? null;
- const existingReviewStage = input.existingPolicy?.stages.find((stage) => stage.type === "review");
+ const existingReviewStage = existingPolicy?.stages.find((stage) => stage.type === "review");
const reviewParticipants = mergeParticipants(existingReviewStage?.participants, input.reviewerValues);
if (reviewParticipants.length > 0) {
stages.push({
@@ -69,7 +81,7 @@ export function buildExecutionPolicy(input: {
});
}
- const existingApprovalStage = input.existingPolicy?.stages.find((stage) => stage.type === "approval");
+ const existingApprovalStage = existingPolicy?.stages.find((stage) => stage.type === "approval");
const approvalParticipants = mergeParticipants(existingApprovalStage?.participants, input.approverValues);
if (approvalParticipants.length > 0) {
stages.push({
@@ -80,9 +92,11 @@ export function buildExecutionPolicy(input: {
});
}
- if (stages.length === 0 && !monitor) return null;
+ if (stages.length === 0 && !monitor && !existingPolicy?.authorizationPolicy
+ && !existingPolicy?.reviewPreset && existingPolicy?.maxReviewRounds == null) return null;
return {
+ ...input.existingPolicy,
mode,
commentRequired: true,
stages,
diff --git a/ui/storybook/stories/issue-management.stories.tsx b/ui/storybook/stories/issue-management.stories.tsx
index 3e1a67abb0..1939c5b3bf 100644
--- a/ui/storybook/stories/issue-management.stories.tsx
+++ b/ui/storybook/stories/issue-management.stories.tsx
@@ -891,6 +891,21 @@ type Story = StoryObj<typeof meta>;
export const FullSurfaceMatrix: Story = {};
+export const IssuePropertiesUnavailablePolicy: Story = {
+ name: "IssueProperties - unavailable execution policy",
+ render: () => (
+ <StorybookData>
+ <div className="paperclip-story p-6">
+ <IssueProperties
+ issue={{ ...primaryIssue, executionPolicy: { stages: {} } as unknown as Issue["executionPolicy"] }}
+ onUpdate={() => undefined}
+ inline
+ />
+ </div>
+ </StorybookData>
+ ),
+};
+
export const IssuePropertiesLongValuesDesktop: Story = {
name: "IssueProperties - long values desktop pane",
render: () => <IssuePropertiesLongValuePane />,