Files
PaperClipAI/ui/src/components/IssueScheduledRetryCard.tsx
T
Devin FoleyandPaperclip 06484b3c41 fix: preserve conversation retries through execution cleanup (#15463)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Recovery schedules bounded retries after a provider disconnects.
> - A stopped run can still hold its environment lease while cleanup
runs.
> - Retrying before that lease is released cancels the new run before it
starts and spends another retry.
> - Restoring the task can also send the worker repair instructions from
an already resolved recovery action.
> - This pull request preserves the waiting retry and removes settled
recovery instructions from later wakes.
> - The task can continue after cleanup without an operator repairing
the same incident again.

## Linked Issues or Issue Description

**What happened?**

A legacy conversation run disconnected while it was doing ordinary work.
Its environment cleanup took longer than the retry delay. Two retries
were cancelled before dispatch with `execution_reconciliation_required`.
Those cancellations exhausted the failure budget. After an operator
restored the task, the wake still told the original worker to repair the
runtime and hand the task back to itself.

**Expected behavior**

Cleanup waits preserve the pending attempt. The same retry can continue
after ownership is released, subject to all current gates. Once a
recovery action is resolved or cancelled, subsequent task wakes omit its
repair instructions.

**Steps to reproduce**

1. Fail a legacy conversation run while its environment lease remains in
`pending_cleanup`.
2. Schedule a bounded retry and run promotion before cleanup releases
that lease.
3. Repeat the scheduler sweep. Before this fix, retries promote and then
cancel without starting.
4. Resolve a stranded-task recovery action and build the restored task
wake with that action ID. Before this fix, the wake still includes the
settled repair instructions.

**Paperclip version or commit**

Reproduced with database regressions against `ceabc3bc880` on master.

Related: #15019 restores a skipped assignment handoff after lease
release. #15235 filters stale handoff evidence in the recovery sweep.
This change preserves an existing scheduled conversation retry and
corrects restored wake content. It does not create a new handoff wake.

## What Changed

- Keep an unstarted legacy conversation retry on the same durable row
while prior execution ownership remains active. Recheck after 30 seconds
without increasing retry accounting.
- Return a queued retry to scheduled state if it encounters that hold at
the claim gate. Retain its issue claim and publish the status change.
- Record one local lifecycle diagnostic per blocking run. Remove that
wait marker on promotion.
- Include recovery action metadata only while the referenced action is
active or escalated.
- Return an explicit `waiting` response and the saved schedule when
Retry now meets cleanup. Show the wait inline without a false success or
disabled button.
- Add database, rendered-prompt, route, and UI regressions. Document the
execution and run-log contracts.

## Verification

- Five cleanup and restored-wake regressions fail against the original
production code. The Retry now route and UI regressions also fail before
their correction.
- Related retry, dispatch, stale-queue, and recovery suites: 321 tests
pass across seven files. All ten focused cleanup/restored-wake cases
pass after rebase. The final dispatch adjustment passes all 46 adapter
tests.
- Retry now routes and affected UI suites: all 46 tests pass. The tests
cover repeated clicks, the saved schedule, unchanged accounting,
promotion after release, and no false success or error state.
- `pnpm -r typecheck`, `pnpm build`, `pnpm build-storybook`, and `pnpm
check:token-gates` pass.
- Full local `pnpm test:run` was started and then stopped after the
final commit passed all GitHub CI test shards. No complete local
full-suite result is claimed; CI supplies the complete test result for
the final commit.
- Final head `6f1058a332c039e33c4f002b296d20a5554e760e`: all 55 GitHub
checks are green or intentionally skipped. Apex review is 5/5 after two
reviews, with no unresolved threads. The PR has no merge conflicts.

## Risks

The wait applies only to unstarted legacy conversation retries. Native
runs and non-conversation execution keep their existing recovery rules.
Cleanup must actually release ownership before execution can resume. The
wait does not fix a cleanup service that never finishes. Promotion and
dispatch still enforce cancellation, reassignment, pause, budget, and
reconciliation gates. No schema change is required. The Retry now
response adds a `waiting` outcome; the shared contract and all three UI
controls handle it.

## Model Used

OpenAI Codex based on GPT-6, with repository analysis, tool use, and
local code execution. The runtime does not expose the precise serving
model ID or context window.

## 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 (focused suites; complete
final-head test coverage in CI)
- [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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-07 11:15:49 -07:00

207 lines
7.9 KiB
TypeScript

import { Clock, RotateCcw, AlertCircle, Loader2, CheckCircle2 } from "lucide-react";
import { Link } from "@/lib/router";
import { Button } from "@/components/ui/button";
import { cn, formatDateTime } from "@/lib/utils";
import { formatMonitorOffset } from "@/lib/issue-monitor";
import { formatRetryReason } from "@/lib/runRetryState";
import type { IssueScheduledRetry } from "@paperclipai/shared";
import { useRetryNowMutation, type RetryNowError } from "../hooks/useRetryNowMutation";
import { Badge } from "@/components/ui/badge";
import { InlineBanner } from "@/components/InlineBanner";
const MAX_TURN_CONTINUATION = "max_turns_continuation";
function isContinuationReason(reason: string | null | undefined) {
return reason === MAX_TURN_CONTINUATION;
}
function shortRunId(runId: string | null | undefined) {
return typeof runId === "string" && runId.length >= 8 ? runId.slice(0, 8) : runId ?? "";
}
interface IssueScheduledRetryCardProps {
issueId: string | null | undefined;
scheduledRetry: IssueScheduledRetry | null | undefined;
}
export function IssueScheduledRetryCard({
issueId,
scheduledRetry,
}: IssueScheduledRetryCardProps) {
const retryNow = useRetryNowMutation(issueId);
if (!scheduledRetry || !issueId) return null;
if (scheduledRetry.status !== "scheduled_retry") return null;
if (scheduledRetry.scheduledRetryReason === "workspace_busy") {
return (
<InlineBanner tone="info" icon={Clock} title="Waiting for workspace" className="mb-3">
Another task is using this workspace. Work starts automatically when it is available.
</InlineBanner>
);
}
const continuation = isContinuationReason(scheduledRetry.scheduledRetryReason);
const dueAtIso = scheduledRetry.scheduledRetryAt
? new Date(scheduledRetry.scheduledRetryAt).toISOString()
: null;
const relative = dueAtIso ? formatMonitorOffset(dueAtIso) : null;
const absolute = scheduledRetry.scheduledRetryAt
? formatDateTime(scheduledRetry.scheduledRetryAt)
: null;
const reason = formatRetryReason(scheduledRetry.scheduledRetryReason);
const attempt =
typeof scheduledRetry.scheduledRetryAttempt === "number"
&& Number.isFinite(scheduledRetry.scheduledRetryAttempt)
&& scheduledRetry.scheduledRetryAttempt > 0
? scheduledRetry.scheduledRetryAttempt
: null;
const badgeLabel = continuation ? "Continuation scheduled" : "Retry scheduled";
const titleAction = continuation ? "Automatic continuation" : "Automatic retry";
let titleSuffix: string;
if (relative === "now") {
titleSuffix = "due now";
} else if (relative) {
titleSuffix = relative;
} else {
titleSuffix = "pending schedule";
}
const title = `${titleAction} ${titleSuffix}`;
const helperIdle = continuation
? "Pulls continuation forward immediately"
: "Pulls retry forward immediately";
const isError = retryNow.isError || retryNow.lastError !== null;
const isSuccessTransient = retryNow.isSuccess
&& (retryNow.data?.outcome === "promoted" || retryNow.data?.outcome === "already_promoted");
return (
<div
data-testid="issue-scheduled-retry-card"
className="mb-3 rounded-lg border border-blue-500/30 bg-blue-500/5 px-3 py-3"
>
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2 text-xs">
<Badge variant="outline" className="border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300">
<Clock className="h-3 w-3" aria-hidden="true" />
{badgeLabel}
</Badge>
{attempt !== null ? (
<span className="text-muted-foreground">Attempt {attempt}</span>
) : null}
{reason ? (
<span className="text-muted-foreground">{reason}</span>
) : null}
</div>
<div className="mt-1 text-sm font-medium text-foreground">{title}</div>
{(absolute || scheduledRetry.retryOfRunId) ? (
<div className="mt-0.5 text-xs text-muted-foreground">
{absolute ? <span>{absolute}</span> : null}
{absolute && scheduledRetry.retryOfRunId ? <span>{" · "}</span> : null}
{scheduledRetry.retryOfRunId ? (
<span>
Replaces run{" "}
<Link
to={`/agents/${scheduledRetry.agentId}/runs/${scheduledRetry.retryOfRunId}`}
className="font-mono text-foreground hover:underline"
>
{shortRunId(scheduledRetry.retryOfRunId)}
</Link>
</span>
) : null}
</div>
) : null}
{scheduledRetry.error ? (
<div className="mt-1 text-xs text-muted-foreground">
Last attempt failed: {scheduledRetry.error}{/[.!?]$/.test(scheduledRetry.error.trim()) ? "" : "."} Paperclip will retry automatically.
</div>
) : null}
{isError ? (
<RetryErrorBand
error={retryNow.lastError}
onRetry={() => {
retryNow.reset();
retryNow.mutate();
}}
/>
) : null}
</div>
<div className="flex flex-col items-stretch gap-1 sm:items-end">
<Button
type="button"
variant="outline"
size="sm"
className="shrink-0 shadow-none"
onClick={() => retryNow.mutate()}
disabled={retryNow.isPending || isSuccessTransient}
data-testid="issue-scheduled-retry-card-retry-now"
>
{retryNow.isPending ? (
<span className="inline-flex items-center gap-1.5">
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
Retrying…
</span>
) : isSuccessTransient ? (
<span className="inline-flex items-center gap-1.5">
<CheckCircle2 className="h-3.5 w-3.5" aria-hidden="true" />
{retryNow.data?.outcome === "already_promoted" ? "Already promoted" : "Promoted"}
</span>
) : (
<span className="inline-flex items-center gap-1.5">
<RotateCcw className="h-3.5 w-3.5" aria-hidden="true" />
Retry now
</span>
)}
</Button>
<span className="text-right text-xs text-muted-foreground sm:max-w-(--sz-12rem)">
{retryNow.isPending
? "Promoting scheduled retry"
: isSuccessTransient
? retryNow.data?.outcome === "already_promoted"
? "Already promoted — run starting"
: "Promoted — run starting"
: retryNow.data?.outcome === "waiting" && retryNow.data.scheduledRetry?.runId === scheduledRetry.runId
? retryNow.data.message
: helperIdle}
</span>
</div>
</div>
</div>
);
}
interface RetryErrorBandProps {
error: RetryNowError | null;
onRetry: () => void;
className?: string;
}
export function RetryErrorBand({ error, onRetry, className }: RetryErrorBandProps) {
if (!error) return null;
return (
<div
className={cn(
"mt-2 flex items-start gap-2 rounded-md border border-rose-500/30 bg-rose-500/5 px-2 py-1.5 text-xs text-rose-700 dark:text-rose-300",
className,
)}
role="alert"
data-testid="issue-scheduled-retry-error-band"
>
<AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
<div className="min-w-0 flex-1">
<div className="font-medium">Couldn't retry now</div>
<div className="mt-0.5 text-muted-foreground">{error.message}</div>
</div>
<button
type="button"
onClick={onRetry}
className="shrink-0 font-medium text-rose-700 hover:underline dark:text-rose-300"
>
Try again
</button>
</div>
);
}