Files
PaperClipAI/ui/src/components/ExecutionBlockerNotice.tsx
T
Devin FoleyandPaperclip c41145e72a fix: wait on pending questions and quiet provider holds (#22363)
## Thinking Path

> - Paperclip manages agents and the tasks they work on.
> - Recovery should continue unfinished work when it is eligible.
> - An active unanswered question is a persisted reason to wait for a
person.
> - Treating a later Retry as an answer makes the recovery sweep
repeatedly request continuations that admission refuses.
> - Provider-limit holds also produce one cancellation toast per task,
even though provider work never started.
> - This PR aligns recovery with persisted interaction status and
presents these waits accurately.

## Linked Issues or Issue Description

Refs: #20466. This addresses the question blocker presentation and
automatic recovery loop; it preserves the existing
interaction-resolution policy.

Related work: #19420 schedules provider quota retries, and #21570
handles notices and reply ownership in agent chats. This change concerns
assigned-task reconciliation, task/inbox status, and per-run
cancellation toasts.

**What happened?**

The assigned-work sweep ignored pending interactions whenever a newer
run carried `explicitUserContinuation`. Continuation admission still
refused the pending question, so repeated sweeps recorded unsuccessful
continuation attempts. The task could meanwhile show an older provider
error as its current blocker. Separately, each pre-dispatch
provider-limit hold generated a cancellation toast, and the one-hour
fallback was described as a known reset and promised start time.

**Expected behavior**

Wait quietly while the question remains active under the shared
interaction eligibility rules, then react to the existing resolution
notification. Dismissed or historical ordinary questions remain
answerable without blocking work; governed requests keep their gates.
Show the current question on task and inbox surfaces. Keep provider
failure history, suppress cancellation toasts for expected provider
holds, and describe scheduled availability checks without promising the
provider will accept work.

**Steps to reproduce**

1. Leave an `ask_user_questions` interaction pending with
`supersedeOnUserComment: false`.
2. Create a later failed/interrupted explicit Retry and run
assigned-work reconciliation repeatedly.
3. Observe that the question remains pending while the sweep attempts
fresh continuations.
4. Separately, let an agent with recent provider rate-limit evidence
receive automatic task wakes without a reported reset time.

## What Changed

- Remove inferred question supersession from both assigned-work fact
loading and candidate selection. Use the existing active-interaction
predicate consistently in those reads, fresh-continuation admission, and
the task projection. Cover dismissed/historical ordinary questions,
retained governed gates, repeated checks, idle workers, and the existing
resolution notification.
- Add the `question` interruption action, load active pending question
IDs alongside approvals in one company-scoped query, and show that
blocker on tasks and inbox rows. Preserve a supported manual Retry after
a failed attempt, suppress duplicate actions for saved input, and keep
other current user gates authoritative. This preserves the existing
issue-detail SQL statement budget. Historical run failures remain
intact. Refresh the shared source SDK input pin.
- Suppress cancellation toasts specifically for cancelled
`provider_limit_wait` runs. Label provider retry deadlines as
availability rechecks, retain relative-time formatting, and record
successful scheduling as an informational lifecycle event.
- Document the wait contract in the continuation architecture guide.

## Verification

- Demonstrated failing regressions before the implementation:
continuation loop, task projection, task notice, cancellation toast,
provider deadline wording, and deadline formatting.
- Initial focused Vitest qualification: 642 tests passed across 14
files, using:

  ```sh
  pnpm exec vitest run \

server/src/__tests__/{assigned-work-invariant,assigned-work-recheck-idle,heartbeat-provider-limit-wait,task-interruption-query}.test.ts
\

server/src/services/{task-interruption-presentation,execution-projection,fresh-continuation-fallback,issue-thread-interactions}.test.ts
\
    server/src/services/recovery/assigned-work-invariant.test.ts \

ui/src/{components/ExecutionBlockerNotice.test.tsx,context/LiveUpdatesProvider.test.ts,context/LiveUpdatesProvider.hook.test.tsx,lib/provider-limit-message.test.ts,pages/Inbox.test.tsx}
  ```
- `pnpm --filter @paperclipai/shared typecheck` — passed.
- Review follow-up: 157 tests passed in `assigned-work-invariant`,
`task-interruption-query`, and `fresh-continuation-fallback`; 575 passed
in `task-interruption-query`, `assigned-work-recheck-idle`,
`task-interruption-presentation`, `issue-question-context`,
`issue-thread-interactions`, and `explicit-native-continuation` (the
query file overlaps). The strengthened final
dismissed/historical/governed projection regression also passed
separately.
- Final query-consolidation verification: 157 tests passed across five
files, including the unchanged 64-statement issue-detail census and
mixed approval/question batches:

  ```sh
  pnpm exec vitest run \

server/src/__tests__/{issue-detail-statements,task-interruption-query,assigned-work-invariant,assigned-work-recheck-idle}.test.ts
\
    server/src/services/task-interruption-presentation.test.ts
  ```
- `pnpm --filter @paperclipai/server typecheck` — passed, including test
layers.
- Manual-recovery follow-up: 204 tests passed across seven
projection/recovery/notice suites, and all 104 Inbox tests passed. The
lost-runner integration still starts exactly one run from a manual Retry
and leaves the question unanswered. The saved-decision census verifies
one decision batch query for a 41-task list, with at most three
statements referencing interactions; the overall 64-statement
issue-detail limit remains unchanged.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/ui build` — passed.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed.
- `pnpm verify` — exit 2: broader CI is required for changed global
inputs. Focused tests and package checks supply local evidence; broad CI
remains required.
- `git diff --check` and a local secret/instance-data scan — passed.
- Final CI on `1c16fe7c0d8`: [trusted CI
workflow](https://github.com/paperclipai/paperclip/actions/runs/44650155842)
passed, including all server shards, native-server verification, build,
canary, e2e, release registry, and serialized suites. All PR checks are
complete, with no failures; the branch is conflict-free.
- Greptile reviewed the latest revision, `1c16fe7c0d8`, at 5/5 with no
actionable findings or unresolved review threads.

The focused tests cover genuine provider failures, live work and
terminal tasks, unchanged task locks/retry delivery, preservation of
historical failures, and question resolution waking the affected task
while other active pending questions remain quiet. Review regressions
also cover dismissed/historical ordinary questions retaining Retry and
governed requests retaining their gates. No live task was retried or
answered for validation.

## Risks

- An active pending question now consistently blocks automatic
assigned-work recovery. Shared interaction eligibility determines when
ordinary conversation input becomes deferred or historical; governed
requests retain their authority. Automatic recovery no longer infers
that a newer Retry resolved an active question.
- Manual Retry keeps its existing admission policy and recovery checks.
The question notice preserves that supported action after a failed
attempt without changing approval or credential authority; pending saved
input prevents duplicate actions.
- The shared interruption action gains `question`; the task and inbox
consumers are updated together. The pending-question query returns only
task IDs and uses the existing company/task/status index.
- Provider cooldown policy, quotas, credentials, routing, cancellation
history, and durable retry timing are unchanged. The actual provider can
still return a rate limit at the recheck.
- No migration is required. Existing large owner modules receive small
localized changes; no code file crosses 1,000 lines.

## Model Used

OpenAI `gpt-6.1-sol` through the Codex harness in T3 Code, xhigh
reasoning effort, with code execution and tool use.

## 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 linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
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
- [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-11-19 19:54:15 -08:00

159 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describeError } from "../api/errors";
import type { IssueRelationIssueSummary, TaskInterruptionPresentation } from "@paperclipai/shared";
import { AlertCircle } from "lucide-react";
import { Link } from "@/lib/router";
import { createIssueDetailPath } from "../lib/issueDetailBreadcrumb";
import { Button } from "./ui/button";
import { cn } from "../lib/utils";
import { useSecondTick } from "../hooks/useSecondTick";
import { TaskProjectAccessNotice } from "./TaskProjectAccessNotice";
import { ProviderFailureNotice } from "./ProviderFailureNotice";
import { LockedIssueChip, isLockedIssueStub } from "./LockedIssueChip";
import { PreviousServerStopConfirmation } from "./WorkspaceExportRecovery";
import { issuesApi } from "../api/issues";
const recoveryStepText: Record<NonNullable<TaskInterruptionPresentation["recoveryStep"]>, string> = {
checking_previous_run: "Checking that the previous attempt stopped",
saving_previous_files: "Saving files from the previous attempt",
finishing_recovery: "Finishing recovery of saved work",
};
/** A budget hard stop holds saved work. Only a task that already ran has an
* attempt to report; a task refused before its first run just waits. */
function budgetWaitText(presentation: TaskInterruptionPresentation) {
const wait = "It is waiting for the budget to allow new work. Raise the budget in Costs.";
return presentation.observedRunId || presentation.sourceRunIds.length
? `Couldn’t finish this attempt. Your message is saved. ${wait}`
: `This task has not started. ${wait}`;
}
const isBudgetWait = (presentation: TaskInterruptionPresentation | null | undefined) =>
presentation?.state === "waiting_for_user" && presentation.userAction === "budget";
const blockerAction: Record<string, string> = {
blocked: "Blocked: open it to Retry",
cancelled: "Cancelled: remove or replace it",
done: "Saving its files",
};
/** One ordinary interruption surface. Technical records remain in diagnostics. */
export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimistic, takingLonger, error, className, issueId, companyId, agentName, projectName, blockers }: {
presentation: TaskInterruptionPresentation | null | undefined;
companyId?: string;
blockers?: IssueRelationIssueSummary[];
canRetry: boolean;
onRetry: () => void;
optimistic?: boolean;
takingLonger?: boolean;
error?: Error | null;
className?: string;
issueId?: string;
agentName?: string;
projectName?: string;
}) {
useSecondTick(presentation?.state === "retry_scheduled");
if (presentation?.projectAccess && !optimistic && !takingLonger) return <TaskProjectAccessNotice
access={presentation.projectAccess} issueId={issueId} agentName={agentName} projectName={projectName}
canRetry={canRetry && presentation.canRetry} onRetry={onRetry} error={error} className={className} />;
if (error && !optimistic && !takingLonger) return <div role="alert" className={cn("flex items-center justify-between gap-2 text-sm text-destructive", className)}><span>{describeError(error).body}</span>{canRetry && <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}</div>;
if (takingLonger) return <div role="status" className={cn("flex items-center justify-between gap-2 text-sm text-muted-foreground", className)}><span>Taking longer than usual…</span>{canRetry && <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}</div>;
const step = !optimistic && presentation?.responsibility === "system" && presentation.recoveryStep
&& ["working", "retry_scheduled"].includes(presentation.state) ? recoveryStepText[presentation.recoveryStep] : null;
const seconds = Math.max(0, Math.ceil((Date.parse(presentation?.nextRetryAt ?? "") - Date.now()) / 1000));
const retryIn = `Trying again in ${seconds > 60 ? `${Math.ceil(seconds / 60)}m` : `${seconds}s`}…`;
if (!optimistic && presentation?.state === "waiting_for_user" && presentation.userAction === "question")
return <div role="status" data-testid="task-execution-waiting" className={cn("flex items-center justify-between gap-2 text-sm text-muted-foreground", className)}>
<span>Respond to the pending question to continue.</span>
{canRetry && presentation.canRetry && <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}
</div>;
if (!optimistic && !presentation?.retryWait && presentation?.providerFailure && ["failed", "retry_scheduled", "waiting_for_user"].includes(presentation.state)) {
// Saved-work recovery is what the task waits for, so name it over the
// generic automatic-retry line while keeping the provider explanation.
return <ProviderFailureNotice failure={presentation.providerFailure} className={className}
actions={canRetry && presentation.canRetry ? <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button> : undefined}>
{presentation.state === "retry_scheduled" && <p>{step ? `${step}. ${retryIn}` : "Paperclip will retry automatically."}</p>}
{isBudgetWait(presentation) && <p data-testid="task-execution-waiting">It is waiting for the budget to allow new work. Raise the budget in Costs.</p>}
</ProviderFailureNotice>;
}
if (step && presentation?.state === "working") return <div role="status" aria-label="Task status"
className={cn("text-sm text-muted-foreground", className)}>{`${step}…`}</div>;
if (!optimistic && presentation?.state === "working" && presentation.retryAction === "move_forward" && presentation.canRetry)
return <div role="status" aria-label="Task status" className={cn("flex items-center justify-between gap-3 text-sm text-muted-foreground", className)}>
<span className="min-w-0 flex-1">Waiting for the agent to finish other work. Paperclip continues this task by itself.</span>
{canRetry && <Button variant="outline" size="sm" className="shrink-0" onClick={onRetry} data-testid="task-execution-move-forward">Move it forward now</Button>}
</div>;
// A task that has not started yet names the admission hold it waits for.
if (!optimistic && presentation?.state === "working" && presentation.retryWait) {
const dependencies = presentation.retryWait.reason === "dependency_blocked" ? blockers ?? [] : [];
const unfinished = dependencies.filter(blocker => isLockedIssueStub(blocker) || blocker.status !== "done");
const waitingOn = unfinished.length ? unfinished : dependencies;
return <div role="status" aria-label="Task status" className={cn("text-sm text-muted-foreground", className)}>
<p>{presentation.retryWait.message}</p>
{waitingOn.length ? <ul className="mt-1 space-y-0.5" data-testid="retry-waiting-on">
{waitingOn.map(blocker => isLockedIssueStub(blocker)
? <li key={blocker.id} className="flex min-w-0 items-center gap-2"><LockedIssueChip identifier={blocker.identifier} /></li>
: <li key={blocker.id} className="flex min-w-0 items-center gap-2">
<Link to={createIssueDetailPath(blocker.identifier ?? blocker.id)}
className="font-mono text-xs text-foreground underline-offset-2 hover:underline">
{blocker.identifier ?? "Task"}
</Link>
<span className="min-w-0 truncate">{blocker.title}</span>
<span className="shrink-0 text-xs">{blockerAction[blocker.status] ?? blocker.status.replace(/_/g, " ")}</span>
</li>)}
</ul> : null}
</div>;
}
if (!optimistic && presentation?.userAction === "confirm_run_stopped" && presentation.observedRunId && issueId && companyId) {
const runId = presentation.observedRunId;
return <PreviousServerStopConfirmation key={`${issueId}:${runId}`} runId={runId} formId={runId} issueId={issueId} companyId={companyId}
className={className} confirmStop={stopEvidence => issuesApi.confirmRunStopped(issueId, { runId, stopEvidence })}
copy={{ waiting: presentation.retryWait?.message ?? "Paperclip can't confirm that the previous run stopped. Your message is saved.",
question: "How did you confirm that no agent is still working on this task?",
placeholder: "For example: no codex or claude process for this task is running on the server host.",
resuming: "Starting your Retry…", confirm: "Confirm it stopped" }} />;
}
// Other person-owned decisions have their own card on the task (approval,
// project access, ...). A budget hold has none, so name it here and keep the
// failure visible. The saved attempt starts by itself once the budget allows.
if (!optimistic && presentation && isBudgetWait(presentation)) return (
<div className={cn("pt-4", className)}>
<div role="status" aria-label="Task status" data-testid="task-execution-waiting"
className="flex items-center gap-3 rounded-lg bg-destructive/10 p-4 text-sm text-foreground">
<AlertCircle className="size-5 shrink-0 text-destructive" aria-hidden="true" />
<span className="min-w-0 flex-1">{budgetWaitText(presentation)}</span>
</div>
</div>
);
if (!optimistic && presentation?.userAction === "unblock") return (
<div className={cn("pt-4", className)}>
<div role="status" aria-label="Task status" data-testid="task-execution-waiting"
className="flex items-center justify-between gap-3 rounded-lg bg-destructive/10 p-4 text-sm text-foreground">
<AlertCircle className="size-5 shrink-0 text-destructive" aria-hidden="true" />
<span className="min-w-0 flex-1">The agent stopped and needs your help to continue. Read its last comment, do what it asks, then Retry.</span>
{canRetry && presentation.canRetry && <Button variant="outline" size="sm" className="shrink-0" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}
</div>
</div>
);
if (optimistic || !presentation || presentation.responsibility !== "system" ||
!["failed", "retry_scheduled"].includes(presentation.state)) return null;
return (
<div className={cn(presentation.state === "failed" && "pt-4", className)}>
<div role="status" aria-label="Task status" className={cn(
"flex items-center justify-between gap-3 text-sm",
presentation.state === "failed" ? "rounded-lg bg-destructive/10 p-4 text-foreground" : "text-muted-foreground",
)}>
{presentation.state === "failed" && <AlertCircle className="size-5 shrink-0 text-destructive" aria-hidden="true" />}
<span className="min-w-0 flex-1">{presentation.state === "retry_scheduled"
? step ? `${step}. ${retryIn}`
: presentation.setupFailure ? `${presentation.setupFailure.message}. ${retryIn}` : retryIn
: presentation.retryWait ? presentation.retryWait.message
: presentation.workspaceFailure
? <>Couldn’t prepare the task folders. {presentation.workspaceFailure.message}</>
: presentation.setupFailure
? <>Couldn’t set up the task workspace. {presentation.setupFailure.message}. Fix the command in the project’s workspace settings, then retry.</>
: "Couldn’t finish this attempt. Your message is saved."}</span>
{canRetry && presentation.canRetry && <Button variant="outline" size="sm" className="shrink-0" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}
</div>
</div>
);
}