mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-24 01:41:42 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A stopped run can leave useful files in its original sandbox. > - The server keeps that sandbox when it cannot confirm file copyback. > - The task can then save new user input but offers no safe way to recover the files. > - A retry of the old agent turn can repeat work that already finished. > - This pull request recovers files through the existing workspace owner and delivers only saved human input. > - The user can recover a task without certifying infrastructure facts or losing completed work. ## Linked Issues or Issue Description Refs #16883 and #16835 for publication receipts and verified process termination. Related: #16478 clears stale holds after copyback already succeeded. This change performs the missing export and records its proof. #16901 manages the main GitHub response comment and does not perform workspace repair. **What happened?** A failed run retained its workspace. A later user message stayed saved behind a file-repair hold. The task asked the user to verify process termination and file recovery but offered no repair control. Sending a message could show an optimistic Working state and move the task to Todo before admission succeeded. **Expected behavior** The harness should recover the original files when it can prove ownership and termination. It should preserve newer edits and completed operations. Only waiting user input may start another turn. Missing evidence must keep the source held with a specific explanation. **Steps to reproduce** 1. Interrupt a sandbox run before workspace finalization succeeds. 2. Retain its exact allocation and save a user follow-up. 3. Observe the file-repair hold and missing end-user repair path. ## What Changed - Add source-bound background recovery for native and legacy runs. An accepted native result is not required. - Share the physical copyback lock and durable owner. Resume only the exact stopped allocation, export files, verify persistence and obtain a fresh stop receipt. - Persist retry limits and idempotent requests on the existing recovery record. Limit each server to two background exports. Add an indexed candidate scan and a separate cleanup obligation. - Add a task-editor recovery endpoint. Deny agents and viewers. Reject caller-supplied stop or repair claims. - Deliver waiting human input once through ordinary admission. Preserve pause, approval, budget and assignment gates. Require historical conversational-adapter evidence for legacy-to-Runner continuation. - Include exact GitHub publication receipts in continuation context. Preserve unknown effects and the original failed run. - Show observed recovery progress, a transient-failure retry action and specific service blockers. Keep saved messages visible. Suppress false startup feedback and implicit Todo promotion behind a file hold. Hide unavailable workspace links. - Update execution semantics, capability maps and production-component stories. ## Verification - Red: the original read model failed the new recovery-progress assertion; the other 23 checks in that file passed. - Passed: recovery regressions with 28 cases with real PostgreSQL, files, tar and Git operations. Lifecycle provider calls are controlled test boundaries. Coverage includes native/legacy export, concurrent owners, rollback after export, interrupted archive export with a new database connection, lost replies, historical discovery, durable retry limits, separate cleanup and saved-input delivery. The actual candidate query uses its partial index with 3,000 unrelated history rows. A first automatic repair can bind verified old-controller stop proof without an accepted native result. Review also reproduced and fixed export-only continuation and cleanup lost after a committed repair. Cleanup remains discoverable without waiting input and after task reconciliation. - Passed: two GitHub integration cases verify that continuation context carries the existing publication receipt and does not write another response. Company and task boundaries are checked. - Passed: 293 continuation, workspace-sync, platform-receipt and OpenAPI checks. After file repair, actual dispatch retains pause, cancellation, approval, real budget-policy and assignment gates. - Passed: 174 route checks, including editor admission, agent/viewer denial and rejection of fabricated repair claims. - Passed: 351 task detail, workspace properties and comment-reopen checks after updating the new read boundaries and asynchronous workspace-link expectations. Two new route cases keep held tasks Blocked when a comment is saved. - Passed: 265 task-thread and recovery-notice checks. The broader continuation suite also passed; its new legacy migration case first exposed a gap that the focused recovery suite now covers. - Passed after rebase: `pnpm -r typecheck` and `pnpm build`. The later master merge adds an unrelated permission migration; recovery migration generation and safety checks passed after the merge. - Passed: token gates, module boundaries, map structure and migration checks. The recovery index is migration 0360 after current master. - Browser: inspected the production recovery component and its retry-to-queued transition with fixture data. The first dev dependency load failed; a reload after optimization resolved it. This is UI evidence, not a live provider recovery claim. - Every test shard passed on final commit `bbbc09efb4`. The older local `pnpm test:run` was stopped after the complete CI test matrix passed. Local full typecheck and production build passed. The first CI build compiled and booted, then lost its runner during the clean public npm-install check. An isolated retry passed the build, production boot and clean public npm-install verification. - Greptile reviewed final commit `bbbc09efb4` at 5/5. All review threads are resolved. - The change is not deployed. Hosted recovery remains unverified until the served revision includes this change. ## Risks - Recovery crosses process, provider and persistence boundaries. Missing or mismatched ownership, stop, descriptor or file evidence keeps the hold. It never selects a replacement allocation or silently starts over. - File recovery does not certify external action outcomes or authorize replay. New input still uses normal execution admission. - Historical sources without sufficient durable evidence can remain blocked. Destructive reconstruction stays separate. - The index migration is idempotent. It changes no task data. Snapshot pruning follows repository policy. ## Model Used OpenAI Codex, `gpt-6.1-sol`, with code execution and browser tools. `gpt-6-astra` assisted earlier investigation. The runtime does not expose the context-window size. ## 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 - [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>
356 lines
24 KiB
TypeScript
356 lines
24 KiB
TypeScript
// @vitest-environment jsdom
|
||
import { act, type AnchorHTMLAttributes } from "react";
|
||
import { createRoot, type Root } from "react-dom/client";
|
||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||
import { ExecutionBlockerNotice } from "./ExecutionBlockerNotice";
|
||
import { agentsApi } from "../api/agents";
|
||
import { activityApi } from "../api/activity";
|
||
import { issuesApi } from "../api/issues";
|
||
import { queryKeys } from "../lib/queryKeys";
|
||
vi.mock("../lib/router", () => ({
|
||
Link: ({ to, ...props }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => <a href={to} {...props} />,
|
||
}));
|
||
vi.mock("../api/agents", () => ({ agentsApi: { retryFailedRun: vi.fn() } }));
|
||
vi.mock("../api/activity", () => ({ activityApi: { runsForIssue: vi.fn() } }));
|
||
vi.mock("../api/issues", () => ({ issuesApi: { recoveryActions: vi.fn(), listAttachments: vi.fn(), reconstructWorkspace: vi.fn(), recoverWorkspace: vi.fn() } }));
|
||
|
||
describe("stopped task recovery notice", () => {
|
||
let root: Root;
|
||
let container: HTMLDivElement;
|
||
let client: QueryClient;
|
||
const onRetried = vi.fn();
|
||
beforeEach(async () => {
|
||
vi.clearAllMocks();
|
||
vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [] });
|
||
vi.mocked(issuesApi.listAttachments).mockResolvedValue([]);
|
||
container = document.createElement("div"); document.body.append(container);
|
||
root = createRoot(container);
|
||
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||
vi.mocked(activityApi.runsForIssue).mockResolvedValue([{ runId: "failed-run", agentId: "agent", status: "failed" }] as never);
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause: "legacy_execution_requires_reconciliation",
|
||
nextAction: "Automatic recovery stopped. Recorded work is preserved; actions with unverified outcomes will not be repeated.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
});
|
||
afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });
|
||
it.each(["queued", "recovering", "blocked"] as const)("shows observed workspace recovery state: %s", async status => {
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" canRecover onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause: "native_continuation_requires_reconciliation",
|
||
nextAction: "Recover the retained source", workspaceRepairRequired: true, savedMessageCount: 1,
|
||
workspaceRecovery: { status, stage: "restoring_files", canRetry: status === "blocked",
|
||
message: "Recovery couldn’t finish. Your message is saved." },
|
||
}} />
|
||
</QueryClientProvider>));
|
||
expect(container.textContent).not.toContain("operator attention");
|
||
if (status === "blocked") {
|
||
expect(container.textContent).toContain("Recovery couldn’t finish");
|
||
vi.mocked(issuesApi.recoverWorkspace).mockResolvedValue({ actionId: "recovery", status: "queued" });
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
expect(issuesApi.recoverWorkspace).toHaveBeenCalledWith("task", expect.objectContaining({ actionId: "recovery", runId: "failed-run", idempotencyKey: expect.any(String) }));
|
||
expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();
|
||
} else {
|
||
expect(container.textContent).toContain("Recovering saved work…");
|
||
expect(container.textContent).toContain("Your message is saved and will continue after recovery.");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
}
|
||
});
|
||
it("keeps the recovery guidance and an inspection link alongside Retry", () => {
|
||
const notice = container.querySelector('[role="status"][aria-label="Task recovery"]')!;
|
||
expect(notice.textContent).toContain("Recorded work is preserved");
|
||
expect(notice.textContent).toContain("Retry");
|
||
expect(notice.classList.contains("task-context-notice")).toBe(true);
|
||
expect(notice.querySelector("a")?.getAttribute("href")).toBe("/agents/agent/runs/failed-run");
|
||
});
|
||
it.each([false, true])("explains cancelled runs and saved input; continue eligibility %s", async canContinue => {
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",
|
||
cause: "legacy_execution_requires_reconciliation", runStatus: "cancelled",
|
||
runError: "Provider cancelled execution", savedMessageCount: 2, canContinue,
|
||
nextAction: canContinue ? "Verify provider shutdown before continuing."
|
||
: "Inspect the run before sending a new message to request continuation.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
expect(container.textContent).toContain("Provider cancelled execution");
|
||
expect(container.textContent).toContain("2 saved messages are waiting");
|
||
expect(container.querySelector("a")?.getAttribute("href")).toContain("cancelled-run");
|
||
expect(container.querySelector("button")?.textContent ?? null).toBe(canContinue ? "Continue" : null);
|
||
if (!canContinue) expect(container.textContent).toContain("sending a new message to request continuation");
|
||
if (canContinue) {
|
||
vi.mocked(agentsApi.retryFailedRun).mockResolvedValue({} as never);
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
expect(agentsApi.retryFailedRun).toHaveBeenCalledWith("agent", "cancelled-run", "company");
|
||
}
|
||
});
|
||
it("keeps removed-chat guidance without suggesting a message to an unavailable destination", async () => {
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",
|
||
cause: "legacy_execution_requires_reconciliation", runStatus: "cancelled", canContinue: false,
|
||
nextAction: "This chat connection was removed. Inspect the stopped run and create a new task to continue the work.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
expect(container.textContent).toContain("create a new task");
|
||
expect(container.textContent).not.toContain("sending a new message");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
expect(container.querySelector("a")?.textContent).toBe("Inspect run");
|
||
});
|
||
it("keeps the required next action for other reconciliation causes", async () => {
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause: "action_outcome_unknown",
|
||
nextAction: "Verify the external action outcome before continuing.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
expect(container.textContent).toContain("Verify the external action outcome before continuing.");
|
||
expect(container.textContent).not.toContain("Automatic recovery of this task stopped.");
|
||
});
|
||
it.each(["native_continuation_requires_reconciliation", "native_session_cleanup_quarantined"])("links to the source run instead of offering a retry rejected by %s", async (cause) => {
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent",
|
||
cause,
|
||
nextAction: "Inspect the original failure and reconcile the previous execution before continuing.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
expect(container.textContent).toContain("Work paused.");
|
||
expect(container.textContent).not.toContain("Retry");
|
||
const link = container.querySelector("a")!;
|
||
expect(link.textContent).toBe("Inspect run");
|
||
expect(link.getAttribute("href")).toBe("/agents/agent/runs/failed-run");
|
||
expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();
|
||
});
|
||
it("keeps workspace repair guidance and inspection without offering the legacy Retry fallback", async () => {
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{
|
||
recoveryActionId: "repair", runId: "failed-run", agentId: "agent", cause: "legacy_execution_requires_reconciliation",
|
||
workspaceRepairRequired: true, canRecordWorkspaceRepair: true, canRetry: false, canContinue: false,
|
||
nextAction: "The original sandbox is retained. Recover the missing files and record workspace repair evidence.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
expect(container.textContent).toContain("Paperclip must recover the saved workspace");
|
||
// The hold also covers unsafe archives and local runs, so the notice must not promise retries or a kept sandbox.
|
||
expect(container.textContent).not.toContain("retrying");
|
||
expect(container.textContent).not.toContain("no work is lost");
|
||
expect(container.textContent).not.toContain("record workspace repair evidence");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
expect(container.querySelector("textarea, input")).toBeNull();
|
||
expect(container.querySelector("a")?.textContent).toBe("Inspect run");
|
||
expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it.each([false, true])("preserves source reconstruction and its queued state: %s", async pending => {
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" canManage issueStatus="blocked" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause: "native_workspace_sync_out_unrecoverable",
|
||
workspaceRepairRequired: true, canReconstructWorkspace: !pending, workspaceReconstructionPending: pending,
|
||
workspaceRecoveryStatusVersion: 1, nextAction: pending ? "Continuation from saved sources is queued and waiting for execution checks." : "Inspect surviving source attachments.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
expect(container.textContent).toContain(pending ? "Continuation queued." : "Continue from saved sources");
|
||
expect(container.textContent).not.toContain(pending ? "Work paused." : "recovered workspace files");
|
||
expect(container.querySelector("summary")?.closest("details")?.open).toBe(false);
|
||
expect(issuesApi.reconstructWorkspace).not.toHaveBeenCalled();
|
||
if (pending) {
|
||
expect(container.querySelector("textarea")).toBeNull();
|
||
expect(issuesApi.listAttachments).not.toHaveBeenCalled();
|
||
}
|
||
});
|
||
|
||
it.each(["running", "missed", "wrong-run", "replay-blocked", "delegated"])("uses observed recovery liveness, including for readers: %s", async state => {
|
||
const action = { id: "recovery", kind: "active_run_watchdog", status: "active", ownerType: "agent",
|
||
evidence: { runId: state === "wrong-run" ? "other-run" : "failed-run",
|
||
automaticRecovery: { replay: state === "replay-blocked" ? "blocked" : "held" } },
|
||
attemptCount: 1, maxAttempts: 3, outcome: state === "delegated" ? "delegated" : null,
|
||
wakePolicy: state === "delegated" ? null : { kind: "resume_native_run", runId: "failed-run", attempt: 1, maxAttempts: 3, notBefore: "2020-01-01T00:00:00Z" },
|
||
nativeRunActivity: state === "missed" ? null : { runId: "failed-run", status: "running" },
|
||
};
|
||
vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: action, actions: [action] } as never);
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="live-task" issueStatus="blocked" canManage={false} onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", workspaceRepairRequired: true,
|
||
cause: "native_continuation_requires_reconciliation", nextAction: "Operator inspection is required.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(Boolean(container.querySelector('[aria-label="Task recovery"]'))).toBe(state !== "running");
|
||
});
|
||
|
||
it("retries the exact failed run and refreshes the task", async () => {
|
||
vi.mocked(agentsApi.retryFailedRun).mockResolvedValue({} as never);
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(agentsApi.retryFailedRun).toHaveBeenCalledWith("agent", "failed-run", "company");
|
||
expect(onRetried).toHaveBeenCalledOnce();
|
||
});
|
||
|
||
it("reveals a missed retry when every recovery poll returns identical data", async () => {
|
||
vi.useFakeTimers();
|
||
vi.setSystemTime(new Date("2026-10-18T00:00:00Z"));
|
||
try {
|
||
const action = { id: "recovery", kind: "active_run_watchdog", status: "active", ownerType: "agent", outcome: null,
|
||
evidence: { runId: "failed-run" }, attemptCount: 1, maxAttempts: 3,
|
||
wakePolicy: { kind: "resume_native_run", runId: "failed-run", attempt: 1, maxAttempts: 3,
|
||
notBefore: "2026-10-18T00:00:10Z" }, nativeRunActivity: null };
|
||
const response = { active: action, actions: [action] };
|
||
vi.mocked(issuesApi.recoveryActions).mockResolvedValue(response as never);
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="expiry-task" issueStatus="blocked" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent",
|
||
cause: "native_continuation_requires_reconciliation", nextAction: "Inspect the missed recovery.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
|
||
expect(container.querySelector('[aria-label="Task recovery"]')).toBeNull();
|
||
const before = vi.mocked(issuesApi.recoveryActions).mock.calls.length;
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(41_000); });
|
||
expect(vi.mocked(issuesApi.recoveryActions).mock.calls.length).toBeGreaterThan(before);
|
||
expect(container.querySelector('[aria-label="Task recovery"]')).not.toBeNull();
|
||
expect(container.textContent).toContain("Inspect the missed recovery.");
|
||
} finally { vi.useRealTimers(); }
|
||
});
|
||
|
||
it("shows a recovery refresh error instead of trusting cached activity", async () => {
|
||
const action = { id: "recovery", kind: "active_run_watchdog", status: "active", ownerType: "agent", outcome: null,
|
||
evidence: { runId: "failed-run" }, attemptCount: 1, maxAttempts: 3,
|
||
wakePolicy: { kind: "resume_native_run", runId: "failed-run" },
|
||
nativeRunActivity: { runId: "failed-run", status: "running", workspaceOperationId: null } };
|
||
vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: action, actions: [action] } as never);
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="read-error-task" issueStatus="blocked" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent",
|
||
cause: "native_continuation_requires_reconciliation", nextAction: "Inspect the current run.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(container.querySelector('[aria-label="Task recovery"]')).toBeNull();
|
||
vi.mocked(issuesApi.recoveryActions).mockRejectedValue(new Error("Recovery service unavailable"));
|
||
await act(async () => { await client.refetchQueries({ queryKey: queryKeys.issues.recoveryActions("read-error-task", "recovery", "failed-run") }); });
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Recovery service unavailable");
|
||
expect(container.textContent).toContain("Inspect the current run.");
|
||
});
|
||
|
||
it.each([
|
||
"The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.",
|
||
"The selected model is not supported by the current ChatGPT connection. Choose a supported model or a compatible AI connection.",
|
||
])("shows the model rejection and repair action without expanding run logs: %s", async (runError) => {
|
||
vi.mocked(activityApi.runsForIssue).mockResolvedValue([{ runId: "model-run", agentId: "agent",
|
||
status: "failed", errorCode: "native_provider_model_rejected" }] as never);
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="model-task" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "model-run", agentId: "agent",
|
||
cause: "native_continuation_requires_reconciliation", canRetry: true,
|
||
runError,
|
||
nextAction: "Inspect the original failure before continuing.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(container.textContent).toContain("Model unavailable.");
|
||
expect(container.textContent).toContain(runError);
|
||
expect(container.textContent).toContain("clear the task's model override, then retry");
|
||
expect(container.textContent).toContain("Inspect the original failure before continuing.");
|
||
expect(container.querySelector("button")?.textContent).toBe("Retry");
|
||
});
|
||
|
||
it.each(["native_continuation_requires_reconciliation", "uncertain_external_action"])("offers Retry for a server-admitted native failure: %s", async cause => {
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause,
|
||
canRetry: true,
|
||
nextAction: "Automatic recovery stopped. Try again or send a new message to continue.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
const button = container.querySelector<HTMLButtonElement>("button");
|
||
expect(button?.textContent).toBe("Retry");
|
||
vi.mocked(agentsApi.retryFailedRun).mockResolvedValue({} as never);
|
||
await act(async () => button!.click());
|
||
expect(agentsApi.retryFailedRun).toHaveBeenCalledWith("agent", "failed-run", "company");
|
||
});
|
||
it("shows a failed Retry in the same container and allows another attempt", async () => {
|
||
vi.mocked(agentsApi.retryFailedRun).mockRejectedValue(new Error("Environment cleanup is still running."));
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toBe("Environment cleanup is still running.");
|
||
expect(container.querySelector<HTMLButtonElement>("button")!.disabled).toBe(false);
|
||
expect(onRetried).not.toHaveBeenCalled();
|
||
});
|
||
it("shows a settled hold's decision even when there is no active recovery action", async () => {
|
||
vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [{
|
||
id: "recovery", status: "resolved", resolutionNote: "The last tool outcome could not be verified.",
|
||
evidence: { runId: "cancelled-run", automaticRecovery: { replay: "blocked" } },
|
||
}] as never });
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent", runStatus: "cancelled",
|
||
cause: "legacy_execution_requires_reconciliation", nextAction: "Send a new message after inspecting the run.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(issuesApi.recoveryActions).toHaveBeenCalledWith("task");
|
||
expect(container.querySelector("details")?.textContent).toContain("The last tool outcome could not be verified.");
|
||
expect(container.querySelector("details")?.textContent).toContain("stopped automatic retries");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();
|
||
});
|
||
it("does not show a different run's historical recovery decision", async () => {
|
||
vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [{
|
||
id: "recovery", status: "resolved", resolutionNote: "Old decision",
|
||
evidence: { runId: "another-run", automaticRecovery: { replay: "blocked" } },
|
||
}] as never });
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",
|
||
cause: "legacy_execution_requires_reconciliation", nextAction: "Inspect the current run.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(container.querySelector("details")).toBeNull();
|
||
expect(container.textContent).not.toContain("Old decision");
|
||
});
|
||
it("reports a recovery history read failure without hiding the current guidance", async () => {
|
||
vi.mocked(issuesApi.recoveryActions).mockRejectedValue(new Error("History unavailable"));
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",
|
||
cause: "legacy_execution_requires_reconciliation", nextAction: "Inspect the current run.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("History unavailable");
|
||
expect(container.textContent).toContain("Inspect the current run.");
|
||
});
|
||
it("refreshes a decision while the same stopped run remains open", async () => {
|
||
vi.mocked(issuesApi.recoveryActions).mockClear();
|
||
vi.useFakeTimers();
|
||
try {
|
||
const action = { id: "recovery", status: "active", resolutionNote: "Inspection pending", evidence: { runId: "cancelled-run" } };
|
||
vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [action] } as never);
|
||
await act(async () => root.render(<QueryClientProvider client={client}>
|
||
<ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{
|
||
recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",
|
||
cause: "legacy_execution_requires_reconciliation", nextAction: "Inspect the current run.",
|
||
}} />
|
||
</QueryClientProvider>));
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
|
||
expect(container.textContent).toContain("Inspection pending");
|
||
vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [{ ...action,
|
||
status: "resolved", resolutionNote: "Preserved work; automatic replay stopped", evidence: {
|
||
runId: "cancelled-run", automaticRecovery: { replay: "blocked" },
|
||
},
|
||
}] } as never);
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(5_001); });
|
||
expect(issuesApi.recoveryActions).toHaveBeenCalledTimes(2);
|
||
expect(container.textContent).toContain("Preserved work; automatic replay stopped");
|
||
expect(container.textContent).not.toContain("Inspection pending");
|
||
} finally {
|
||
vi.useRealTimers();
|
||
}
|
||
});
|
||
});
|