mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 20:12:20 +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>
112 lines
5.8 KiB
TypeScript
112 lines
5.8 KiB
TypeScript
import { useEffect, useRef, useState } from "react";
|
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import type { Issue } from "@paperclipai/shared";
|
|
import { ApiError } from "../api/client";
|
|
import { issuesApi } from "../api/issues";
|
|
import { queryKeys } from "../lib/queryKeys";
|
|
import { createUuid } from "../lib/uuid";
|
|
|
|
type RetryRequest = { issueId: string; identifier?: string | null; idempotencyKey: string; observedRunId: string | null;
|
|
retryAction?: "move_forward" };
|
|
type RetryResult = Awaited<ReturnType<typeof issuesApi.retryTask>>;
|
|
|
|
export const STALE_TASK_RETRY_MESSAGE = "This attempt was already replaced, so Retry did not start new work. The task now shows its current state.";
|
|
|
|
export const ALREADY_MOVED_ON_MESSAGE = "The task already moved on, so nothing new was started. It now shows its current state.";
|
|
|
|
export function taskRetryNotStartedReason(result: RetryResult): string | null {
|
|
if (!result.accepted && result.refused) return result.refused.message;
|
|
if (!result.accepted && result.alreadyMovedOn) return ALREADY_MOVED_ON_MESSAGE;
|
|
if (!result.accepted) return STALE_TASK_RETRY_MESSAGE;
|
|
const outcome = result.scheduledRetry?.outcome;
|
|
if (outcome && outcome !== "promoted" && outcome !== "already_promoted") return result.scheduledRetry!.message;
|
|
return null;
|
|
}
|
|
|
|
export function useTaskRetry(issue: Issue | undefined) {
|
|
const queryClient = useQueryClient();
|
|
const request = useRef<RetryRequest | null>(null);
|
|
const [optimistic, setOptimistic] = useState(false);
|
|
const [takingLonger, setTakingLonger] = useState(false);
|
|
const [reconcile, setReconcile] = useState<{ refs: string[]; sourceRunId: string | null } | null>(null);
|
|
const [notStarted, setNotStarted] = useState<{ error: Error; state: string | null; observedRunId: string | null } | null>(null);
|
|
const mutation = useMutation({
|
|
mutationFn: ({ issueId, identifier: _identifier, ...body }: RetryRequest) =>
|
|
issuesApi.retryTask(issueId, body),
|
|
onSuccess: async (result, variables) => {
|
|
const isCurrent = request.current?.idempotencyKey === variables.idempotencyKey;
|
|
if (isCurrent) request.current = null;
|
|
const refs = [...new Set([variables.issueId, variables.identifier].filter((ref): ref is string => Boolean(ref)))];
|
|
if (isCurrent && result.accepted) setReconcile({ refs, sourceRunId: variables.observedRunId });
|
|
if (isCurrent) {
|
|
const reason = taskRetryNotStartedReason(result);
|
|
setNotStarted(reason ? { error: new Error(reason), state: result.presentation?.state ?? null,
|
|
observedRunId: result.presentation?.observedRunId ?? null } : null);
|
|
}
|
|
{
|
|
for (const ref of refs) queryClient.setQueryData<Issue>(queryKeys.issues.detail(ref), current =>
|
|
current ? { ...current, interruption: result.presentation } : current);
|
|
// Retry can queue retained-file recovery; refresh its inspected state too.
|
|
await Promise.all(refs.flatMap(ref => [queryKeys.issues.detail(ref), queryKeys.issues.runs(ref),
|
|
queryKeys.issues.liveRuns(ref), queryKeys.issues.activeRun(ref),
|
|
queryKeys.issues.allRecoveryActions(ref)]).map(queryKey =>
|
|
queryClient.invalidateQueries({ queryKey })));
|
|
}
|
|
if (isCurrent && !request.current) { setOptimistic(false); setTakingLonger(false); }
|
|
},
|
|
onError: (error, variables) => {
|
|
if (request.current?.idempotencyKey !== variables.idempotencyKey) return;
|
|
if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
|
|
request.current = null;
|
|
setOptimistic(false);
|
|
setTakingLonger(false);
|
|
} else {
|
|
setTakingLonger(true);
|
|
}
|
|
},
|
|
});
|
|
useEffect(() => {
|
|
if (!reconcile || !issue || !reconcile.refs.includes(issue.id) || issue.interruption?.retryWait ||
|
|
issue.interruption?.observedRunId !== reconcile.sourceRunId) return;
|
|
// Dispatch follows the committed HTTP receipt. Read its admission reason
|
|
// after that handoff, including the existing ten-second presentation grace.
|
|
// These bounded reads end with this click; idle tasks do not poll.
|
|
const timers = [1_000, 10_000].map(delay => window.setTimeout(() => {
|
|
for (const ref of reconcile.refs) void queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(ref) });
|
|
}, delay));
|
|
return () => timers.forEach(timer => window.clearTimeout(timer));
|
|
}, [reconcile, issue?.id, issue?.interruption?.observedRunId, issue?.interruption?.retryWait, queryClient]);
|
|
useEffect(() => {
|
|
if (!optimistic) return;
|
|
const timer = window.setTimeout(() => {
|
|
setTakingLonger(true);
|
|
// Reconcile the identical durable request after a lost response. This
|
|
// creates neither a second generation nor a second optimistic tail.
|
|
if (request.current) mutation.mutate(request.current);
|
|
}, 10_000);
|
|
return () => window.clearTimeout(timer);
|
|
}, [optimistic]);
|
|
useEffect(() => {
|
|
request.current = null;
|
|
setOptimistic(false);
|
|
setTakingLonger(false);
|
|
setReconcile(null);
|
|
setNotStarted(null);
|
|
mutation.reset();
|
|
}, [issue?.id]);
|
|
return { retry: () => {
|
|
if (!issue) return;
|
|
setReconcile(null);
|
|
setNotStarted(null);
|
|
mutation.reset();
|
|
request.current ??= { issueId: issue.id, identifier: issue.identifier, idempotencyKey: createUuid(),
|
|
observedRunId: issue.interruption?.observedRunId ?? issue.executionBlocker?.runId ?? null,
|
|
...(issue.interruption?.retryAction === "move_forward" ? { retryAction: "move_forward" as const } : {}) };
|
|
setOptimistic(true);
|
|
setTakingLonger(false);
|
|
mutation.mutate(request.current);
|
|
}, optimistic, takingLonger, error: mutation.error ?? (notStarted
|
|
&& (issue?.interruption?.state ?? null) === notStarted.state
|
|
&& (issue?.interruption?.observedRunId ?? null) === notStarted.observedRunId ? notStarted.error : null) };
|
|
}
|