mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 04:21:24 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A person presses Retry on a stopped task, and the Retry API answers before dispatch runs > - The route answered 202 "accepted" when it saved the request. Admission ran afterwards > - When admission refused the request for a reason another click cannot change, the person saw "accepted", no run started, and the task showed no Retry > - A Retry that is shown must work, or the answer must say clearly why it did not start > - This pull request admits a plain Retry before the route answers (bounded wait) and answers a refusal as a refusal > - The benefit is that the API never reports "accepted" for a Retry that admission refused, and the UI shows the reason ## Linked Issues or Issue Description Refs #21481 (a fix for one cause of the refusal). **What happened?** On a hosted staging instance, two tasks got HTTP 202 `accepted: true` from `POST /api/issues/:id/retry`. No run was created. The tasks then showed a failed state with no Retry button and the wait reason `previous_execution_unverified`. **Expected behavior** The Retry answer either reports a Retry that admission took, or it names the refusal so that the UI can show it. It never reports "accepted" for a request that admission refused. **Steps to reproduce** 1. Stop a task's run so that its outcome is unknown (for example, a recorded provider event in a stopped preparation). 2. Press Retry. 3. See HTTP 202 `accepted: true`, then see that the saved request waits on `previous_execution_unverified` and no run starts. **Paperclip version or commit** `master` at `a48eaaef57`. ## What Changed - `POST /api/issues/:id/retry` runs admission of a plain Retry (not a saved-result finalization, not a connected chat retry) before it answers. It waits at most 5 seconds. If admission takes longer, admission continues after the answer, and the answer stays "accepted" as before. - When admission refused the request for a reason another click cannot change (`heldRetryOffersRetry` is false), the answer is HTTP 200 with `accepted: false` and `refused: { reason, message }`. The message is the same stable text that the task view shows. - The saved request is kept. If its gate clears later (for example, saved-work recovery verifies the files), it still starts by itself. - New `taskRetryRefusal` and `taskRetryWaitMessage` in `server/src/services/task-interruption-presentation.ts`. - UI: `taskRetryNotStartedReason` shows `refused.message`; the API type includes `refused`. - Tests that asserted 202 for a held Retry now assert the refusal answer. ## Verification - Red without the route change, green with it: `cd server && npx vitest run src/services/legacy-preparation-retry-hold.test.ts` (new test: a stopped preparation with a recorded provider event; the route answers 200 with `refused.reason: previous_execution_unverified`, and the saved request stays deferred). - Red without the hook change, green with it: `cd ui && npx vitest run src/hooks/useTaskRetry.test.tsx`. - Updated and passing: `src/services/workspace-recovery-preparation-gates.test.ts` (48), `src/services/workspace-recovery-preparation-proof.test.ts` (53), `src/services/workspace-recovery-preparation-dispatch.test.ts` (25). - Passing unchanged: `src/__tests__/issue-scheduled-retry-routes.test.ts` (34), `src/services/unrecoverable-saved-work-retry.test.ts` (5), `src/services/workspace-recovery-warm-handoff.test.ts` (44), `src/__tests__/heartbeat-native-restart-suspension.test.ts` (115), `src/__tests__/issue-agent-mutation-ownership-routes.test.ts` (229), `src/__tests__/agent-cross-tenant-authz-routes.test.ts` (18). - Not run locally: `src/__tests__/chat-channels.integration.test.ts` (did not finish on the loaded machine). CI covers it. ## Risks - The Retry answer can take up to 5 seconds longer when admission is slow (for example, when the agent's start lock is held). Before, the route answered at once and admitted in the background. - A refused request can still start later by itself when its gate clears. The answer then said "not started", but the task view updates when the run starts. - API change: a refused Retry is now HTTP 200 with `accepted: false` and `refused`. The board UI handles it. Other clients that only check `accepted` see a refusal, which is correct. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, file edits, test execution). ## 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>
151 lines
11 KiB
TypeScript
151 lines
11 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 Retry that admission refused", { requestId: "retry", accepted: false, stale: false,
|
|
refused: { reason: "previous_execution_unverified", message: "Retry can't continue because Paperclip can't confirm that the previous attempt stopped before it started work." } },
|
|
"can't confirm that the previous attempt stopped"],
|
|
["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("sends the move-forward intent from the offer and says plainly when the task already moved on", async () => {
|
|
const presentation = { intentId: null, responsibility: "system" as const, state: "working" as const, canRetry: true,
|
|
retryAction: "move_forward" as const, nextRetryAt: null, userAction: null, sourceRunIds: ["continuation"], observedRunId: "continuation" };
|
|
vi.mocked(issuesApi.retryTask).mockResolvedValue({ requestId: null, accepted: false, stale: false, alreadyMovedOn: true,
|
|
presentation: { ...presentation, canRetry: false, retryAction: undefined } } as Awaited<ReturnType<typeof issuesApi.retryTask>>);
|
|
await render({ ...issue, interruption: presentation } as Issue);
|
|
await act(async () => container.querySelector("button")!.click());
|
|
expect(issuesApi.retryTask).toHaveBeenCalledExactlyOnceWith("task", {
|
|
observedRunId: "continuation", retryAction: "move_forward", idempotencyKey: expect.any(String),
|
|
});
|
|
expect(container.querySelector('[role="alert"]')?.textContent).toContain("already moved on, so nothing new was started");
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|