Files
PaperClipAI/ui/src/hooks/useTaskRetry.test.tsx
T
DottaandClaude Opus 5.5 ef2b8d5324 fix(issues): make every Retry start work or say why (#20283)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - When a task's run fails, the board recovers it with a Retry button,
so that button must either start work or say why it did not
> - An audit of every Retry-type button found three gaps. The task Retry
shown during a scheduled retry's countdown returned "accepted" but
changed nothing. A stale Retry looked like success in the Inbox. "Retry
now" skipped the task's read and change checks, so a member who cannot
see a private task could start its retry
> - This pull request makes the task Retry start a scheduled retry
immediately, makes every Retry that did not start work say why, and
gives "Retry now" the same authorization as the task Retry
> - The benefit is that no Retry click silently does nothing

## Linked Issues or Issue Description

Refs #19831. The board reported a dead Retry button. A read-only audit
of every Retry button confirmed:
- **Task Retry during a scheduled retry was a no-op.**
`TaskInterruptionPresentation.canRetry` is true in `retry_scheduled`, so
`ExecutionBlockerNotice` shows Retry. `requestTaskRetry` treats
`scheduled_retry` as busy and inserts a `coalesced` wake pointing at
that run. `resumeTaskRetry` reads only `deferred_issue_execution`, and
dispatch uses coalesced user wakes only to carry comments. Nothing
promoted the run: the API answered 202 `accepted: true` and the
countdown did not change.
- **A stale Retry looked like success.** `accepted: false, stale: true`
comes back as HTTP 200. The Inbox ignored `accepted` and opened the task
as if work had started. The task page showed no reason.
- **"Retry now" checked less than the task Retry.** It ran only
`assertBoard` and `getAccessibleResource`, skipping
`assertIssueReadAllowed` and `issue:mutate`. A company member who cannot
read a private task could promote that task's scheduled retry.
- **"Retry now" said nothing for some outcomes.** It toasted only
`promoted` and `gate_suppressed`.

## What Changed

- `server/src/services/task-retry.ts`: when the Retry coalesces into the
task's latest run and that run is `scheduled_retry` (with no other Retry
already active), the receipt returns `scheduledRetryRunId`.
- `server/src/routes/issues.ts`:
- `POST /issues/:id/retry` then promotes that run through the existing
`retryScheduledRetryNow`, the same path "Retry now" uses. It logs
`issue.scheduled_retry_retry_now` with `source: "task_retry"` and
returns `scheduledRetry: { outcome, message }`.
- `POST /issues/:id/scheduled-retry/retry-now` now runs
`assertIssueReadAllowed` and `decideIssueAccess("issue:mutate")`,
matching `/retry`. A private task the member cannot read now answers
404.
- `ui/src/hooks/useTaskRetry.ts`: new `taskRetryNotStartedReason`. When
a Retry did not start work (stale, or a scheduled retry that is
gate-suppressed, waiting, or gone), the hook returns that reason as its
error. `ExecutionBlockerNotice` and `StalledDependencyNotice` already
display it.
- `ui/src/pages/Inbox.tsx`: a task Retry that did not start work shows
the reason in the error toast and does not navigate.
- `ui/src/hooks/useRetryNowMutation.ts` and
`IssueScheduledRetryCard.tsx`: every "Retry now" outcome now shows its
headline and message, including `no_scheduled_retry` on the card.
- `ui/src/api/issues.ts`: `retryTask`'s response type includes
`scheduledRetry`.

## Verification

Red/green (each new test fails against master and passes with this PR):
- `server/src/__tests__/issue-scheduled-retry-routes.test.ts`:
- "starts a scheduled retry now when the task Retry is clicked during
its countdown": 202 with `scheduledRetry.outcome: "promoted"`, the same
run becomes `queued`, and no second retry run is created.
- "refuses Retry now on a private task the member cannot see, like the
task Retry": on master "Retry now" answers 200 `promoted`; now both
routes answer 404 and the run stays `scheduled_retry`.
- The seed now adds the board user's membership, which the stricter
route needs. All 33 tests pass.
- `ui/src/hooks/useTaskRetry.test.tsx`: a replaced attempt, a gate-held
scheduled retry and a waiting scheduled retry each show their reason; a
promoted one shows nothing extra.
- `ui/src/pages/Inbox.test.tsx`: an Inbox Retry that did not start work
(stale, or gate-held) toasts the reason and does not navigate.
- `ui/src/components/IssueScheduledRetryCard.test.tsx`: "explains when
there was no scheduled retry left to start".

Other Retry buttons: the chat failed-run Retry already reports stopped
and failed retries (`agents.test.ts`). Agent lifecycle "Retry now" and
cost "Retry accounting" start no task work and already surface their API
errors.

Regression and static checks:
- UI: 7 files, 168 passed. Server: task-retry and scheduled-retry
suites, 149 passed. `issue-agent-mutation-ownership-routes.test.ts`
passed.
- `maintenance-server-routes.test.ts` "assembled maintenance server
production wiring" fails identically on master on this Mac
(`ensure-build-deps`).
- `tsc --noEmit` passes for `server` and `ui/src`. `pnpm
check:token-gates` is clean.

## Risks

- A task Retry during a scheduled retry now starts the run immediately,
through the existing "Retry now" promotion gates (pause, budget, cleanup
waits). A gate that holds it is reported, not bypassed.
- "Retry now" is stricter: a member without read or change access to the
task gets 404 or 403, as on `/retry`.
- No schema change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:25:21 -06:00

135 lines
9.5 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Issue } from "@paperclipai/shared";
import { useTaskRetry } from "./useTaskRetry";
import { ExecutionBlockerNotice } from "../components/ExecutionBlockerNotice";
import { ApiError } from "../api/client";
import { issuesApi } from "../api/issues";
import { queryKeys } from "../lib/queryKeys";
vi.mock("../api/issues", () => ({ issuesApi: { retryTask: vi.fn() } }));
const issue = { id: "task", interruption: { observedRunId: "failed-run" } } as Issue;
function View({ task = issue }: { task?: Issue }) {
const retry = useTaskRetry(task);
return <><button onClick={retry.retry}>Retry</button>{retry.optimistic && <span>Thinking</span>}{retry.takingLonger && <span>Taking longer than usual…</span>}{retry.error && <ExecutionBlockerNotice
presentation={{ intentId: "intent", responsibility: "system", state: "failed", canRetry: true,
nextRetryAt: null, userAction: null, sourceRunIds: ["failed-run"], observedRunId: "failed-run" }}
canRetry onRetry={retry.retry} error={retry.error} />}</>;
}
describe("optimistic task Retry", () => {
let container: HTMLDivElement, root: Root, client: QueryClient;
beforeEach(() => {
vi.clearAllMocks(); container = document.createElement("div"); document.body.append(container); root = createRoot(container);
client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
});
afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); vi.useRealTimers(); });
async function render(task = issue) { await act(async () => root.render(<QueryClientProvider client={client}><View task={task} /></QueryClientProvider>)); }
it("shows the saved-work continuation path after normal Retry is definitively denied", async () => {
const message = "This attempt already recorded a result. Send a new message on the task to continue from the saved work.";
vi.mocked(issuesApi.retryTask).mockRejectedValue(new ApiError(message, 409,
{ error: message, details: { code: "chat_failed_run_retry_not_authorized", reason: "accepted_result_without_new_input" } }));
await render();
await act(async () => container.querySelector("button")!.click());
expect(issuesApi.retryTask).toHaveBeenCalledExactlyOnceWith("task", {
observedRunId: "failed-run", idempotencyKey: expect.any(String),
});
expect(container.querySelector('[role="alert"]')?.textContent).toContain(message);
expect(container.textContent).not.toContain("Thinking");
expect(container.textContent).not.toContain("Taking longer");
});
it.each([
["a replaced attempt", { requestId: null, accepted: false, stale: true }, "already replaced, so Retry did not start new work"],
["a scheduled retry held by a gate", { requestId: "retry", accepted: true, stale: false,
scheduledRetry: { outcome: "gate_suppressed" as const, message: "The company budget is paused." } }, "The company budget is paused."],
["a scheduled retry still waiting", { requestId: "retry", accepted: true, stale: false,
scheduledRetry: { outcome: "waiting" as const, message: "The retry is waiting for the workspace." } }, "waiting for the workspace"],
])("shows why Retry did not start work for %s", async (_label, result, reason) => {
const presentation = { intentId: "intent", responsibility: "system" as const, state: "retry_scheduled" as const,
canRetry: true, nextRetryAt: null, userAction: null, sourceRunIds: ["failed-run"], observedRunId: "failed-run" };
vi.mocked(issuesApi.retryTask).mockResolvedValue({ ...result, presentation } as Awaited<ReturnType<typeof issuesApi.retryTask>>);
const waiting = { ...issue, interruption: presentation } as Issue;
await render(waiting);
await act(async () => container.querySelector("button")!.click());
expect(container.querySelector('[role="alert"]')?.textContent).toContain(reason);
expect(container.textContent).not.toContain("Thinking");
await render({ ...waiting, interruption: { ...presentation, state: "working", canRetry: false } } as Issue);
expect(container.querySelector('[role="alert"]')).toBeNull();
});
it("shows nothing extra when Retry promoted the scheduled run", async () => {
vi.mocked(issuesApi.retryTask).mockResolvedValue({ requestId: "retry", accepted: true, stale: false,
scheduledRetry: { outcome: "promoted", message: "Retry promoted" }, presentation: null });
await render();
await act(async () => container.querySelector("button")!.click());
expect(container.querySelector('[role="alert"]')).toBeNull();
});
it("refreshes the inspected file recovery after an accepted Retry", async () => {
vi.mocked(issuesApi.retryTask).mockResolvedValue({ requestId: "retry", accepted: true, stale: false,
observedRunId: "failed-run", presentation: null } as Awaited<ReturnType<typeof issuesApi.retryTask>>);
const key = queryKeys.issues.recoveryActions("task", "hold", "failed-run");
client.setQueryData(key, { active: null, actions: [] });
await render();
await act(async () => container.querySelector("button")!.click());
expect(client.getQueryState(key)?.isInvalidated).toBe(true);
});
it("paints Thinking before admission resolves and shares the same request across double clicks", async () => {
let settle!: (value: Awaited<ReturnType<typeof issuesApi.retryTask>>) => void;
vi.mocked(issuesApi.retryTask).mockImplementation(() => new Promise(resolve => { settle = resolve; }));
await render();
await act(async () => container.querySelector("button")!.click());
expect(container.textContent).toContain("Thinking");
const request = vi.mocked(issuesApi.retryTask).mock.calls[0][1];
await act(async () => container.querySelector("button")!.click());
expect(vi.mocked(issuesApi.retryTask).mock.calls[1][1]).toEqual(request);
await act(async () => { settle({ requestId: "intent", accepted: true, stale: false, presentation: null }); });
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
expect(container.textContent).not.toContain("Thinking");
});
it("reconciles an unknown admission with the original idempotency key after ten seconds", async () => {
vi.useFakeTimers(); vi.mocked(issuesApi.retryTask).mockImplementation(() => new Promise(() => {}));
await render(); await act(async () => container.querySelector("button")!.click());
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
expect(container.textContent).toContain("Taking longer than usual…");
expect(issuesApi.retryTask).toHaveBeenCalledTimes(2);
expect(vi.mocked(issuesApi.retryTask).mock.calls[1]).toEqual(vi.mocked(issuesApi.retryTask).mock.calls[0]);
});
it("does not let an old task response settle a newer task's optimistic request", async () => {
const settlements: Array<(value: Awaited<ReturnType<typeof issuesApi.retryTask>>) => void> = [];
vi.mocked(issuesApi.retryTask).mockImplementation(() => new Promise(resolve => settlements.push(resolve)));
await render(); await act(async () => container.querySelector("button")!.click());
await render({ ...issue, id: "other-task" }); await act(async () => container.querySelector("button")!.click());
await act(async () => settlements[0]({ requestId: "old", accepted: true, stale: false, presentation: null }));
expect(container.textContent).toContain("Thinking");
});
it.each(["id", "identifier"])("reads a deferred Retry reason on the %s route and stops checking once explained", async route => {
vi.useFakeTimers();
const presentation = { intentId: "intent", responsibility: "system" as const, state: "failed" as const,
canRetry: true, nextRetryAt: null, userAction: null, sourceRunIds: ["failed-run"], observedRunId: "failed-run" };
let saved = { ...issue, identifier: "RTA-1", interruption: presentation } as Issue;
const queryFn = vi.fn(async () => saved);
const detailKey = queryKeys.issues.detail(route === "identifier" ? saved.identifier! : issue.id);
client.setQueryData(detailKey, saved);
function Observed() {
const { data } = useQuery({ queryKey: detailKey, queryFn, staleTime: Infinity });
const retry = useTaskRetry(data);
return <ExecutionBlockerNotice presentation={data?.interruption} canRetry onRetry={retry.retry}
optimistic={retry.optimistic} takingLonger={retry.takingLonger} error={retry.error} />;
}
vi.mocked(issuesApi.retryTask).mockResolvedValue({ requestId: "intent", accepted: true, stale: false, presentation });
await act(async () => root.render(<QueryClientProvider client={client}><Observed /></QueryClientProvider>));
await act(async () => container.querySelector("button")!.click());
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
saved = { ...saved, interruption: { ...presentation, retryWait: {
reason: "remote_cleanup", message: "Retry is waiting for the previous environment to stop. Your message is saved.",
} } };
await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
expect(container.textContent).toContain(saved.interruption!.retryWait!.message);
const reads = queryFn.mock.calls.length;
await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
expect(queryFn).toHaveBeenCalledTimes(reads);
expect(issuesApi.retryTask).toHaveBeenCalledTimes(1);
});
});