mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 12:33:05 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The control plane must preserve saved work before it admits another attempt. > - Retained-file recovery already has an authorized API and a bounded worker. > - The task UI hid that operation when workspace repair blocked execution. > - The run inspector could check source identity but could not request preservation. > - This pull request exposes that existing operation with its exact source binding. > - The worker still owns file verification, stop receipts, and execution release. ## Linked Issues or Issue Description Refs #18678 and #18803 for the existing retained-source and continuation contracts. **What happened?** A failed native run could leave an active, system-owned export recovery action. The task showed a generic Retry control. Its workspace repair gate correctly refused another provider turn. The run inspector offered only read-only source inspection. The authorized file-preservation API had no production UI caller. **Expected behavior** An authorized board operator can request preservation of the exact retained files. The UI keeps the repair hold until the server records verified preservation. A lost response must keep the same request identity. **Steps to reproduce** 1. Use an active retained-export action whose workspace recovery is blocked and retryable. 2. Open its source task while `workspaceRepairRequired` is true. 3. Open the exact failed run and inspect recovery. 4. Before this change, neither surface can request the existing file-preservation operation. **Paperclip version or commit** The focused regression fails on master `1f55073f96b2485f49f98ee8c261aa14ec2f79ac` before the production UI edits. I checked the roadmap and searched open public PRs for this UI repair. No duplicate was found. This is a repair to the existing recovery capability. ## What Changed - Add Recover saved files to the existing task recovery area and exact-run inspector. Reuse the current board task-mutation access check and the existing `recoverWorkspace` API. - Read the exact action, run, company, task, and source observation again before sending. Refuse changed, retired, foreign, unverified, or non-retryable sources. - Save one account-scoped request before POST. Keep its key through a lost response and reload. Reconcile with GET before an explicit resend. Use a new key only after an explicit click and a fresh, confirmed exhausted attempt; do not resend automatically. - Show queued, recovering, blocked, and verified receipt states separately. A request acknowledgement does not mark files saved or resolve the task hold. Hide generic Retry for native export holds. Keep the existing Retry path for legacy restoration. - Cover both mounted surfaces and negative access, source, account, persistence, duplicate-click, and lost-response cases. Update the existing design guidance and correct the affected run-detail recipe only. ## Verification - RED: the new component regression fails with `missing Recover saved files` before production changes. The original failure is retained. - GREEN: 265 tests pass across `WorkspaceExportRecovery.control.test.tsx`, `WorkspaceExportRecovery.test.tsx`, `RunWorkspaceRecoverySurface.test.tsx`, and the full `IssueDetail.test.tsx` suite. - Review RED/GREEN: the prior UI reused the failed key after a confirmed exhausted attempt. A focused regression now proves a different key for an explicit new attempt, while the lost-response controls still prove key reuse. Mounted task controls prove that verified native preservation stays available, unverified or stale native sources never offer generic Retry, and viewers cannot mutate. A separate RED against the exact prior UI proves the lost legacy control. Its GREEN clicks the existing legacy Retry API while the workspace hold remains active. - Full UI TypeScript check passes: `node scripts/run-tsc.mjs -p ui/tsconfig.json --noEmit`. - `node scripts/check-token-gates.mjs`, `node scripts/check-maps.mjs`, and `git diff --check` pass. The map check proves structure only. - One early legacy test probe used an unsigned fixture and a readonly array; those setup failures are retained. The corrected same-user fixture proves the source RED and GREEN. The first test command used an unnamed project filter and stopped before loading tests. The corrected package configuration produced the recorded RED. One initial storage fault probe did not intercept jsdom's storage method; the corrected prototype fault proves that unavailable storage sends no POST. - Dependencies use Node 24.22.2 and a frozen pnpm 9.15.4 install with scripts disabled. The maintained shared and SDK prerequisite builds pass on this base. No dependency or lockfile changes are included. - A later Paperclip Review follow-up found the plain-HTTP UUID gap. Its focused regression fails before POST with the prior direct call, then passes with the existing UUID helper. The same storage, lost-response, retry and source controls remain green. - Original full CI `41715060582` fails two Cloud-auth task-entry browser checks at their existing heading assertion. The retained original artifacts show a late task pane (one already contains the heading; one still shows Loading conversation). The cause remains unproven. No auth, fixture, timeout or assertion change is included. Fresh Greptile is 5/5 with zero open threads and Paperclip Review passes on the UUID fix head. Current full CI `41720068249` attempt 1 failed. Three workers were terminated by AWS Spot capacity loss. The CLI startup and dense-ZIP checks also timed out at their unchanged deadlines. The CLI/shared input trees match a previous passing CI job, and the dense-ZIP case passes one focused local check. The CLI timeout cause remains unknown. The coordinator requested one bounded recheck. Attempt 2 succeeds on the same source, with all current checks green. No source, fixture, timeout or assertion changed for that recheck. The worker issued no retry. This pass does not establish the original CLI timeout cause. - Full recursive typecheck, repository tests, and application build were not run locally under the bounded UI verification scope. Full CI is requested. - No live preservation request, provider turn, deployment, or sandbox cleanup was performed for this repair. Original saved-file recovery remains unverified until rollout and real acceptance. ## Risks The client access check is a display guard. The existing server authorization and physical source, ownership, stop, and snapshot checks remain authoritative. Unavailable browser storage blocks the request before POST. A failed acknowledgement retains the request for its owner. The UI never calls task Retry, recovery resolution, reconstruction, provider execution, or destructive cleanup. The existing worker retains its bounded recovery policy and may finish the saved result after real preservation. ## Model Used OpenAI Codex, GPT-6 family, with repository inspection, code editing, and test execution. The exact runtime model ID and context-window size are not exposed to this agent. ## 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>
262 lines
14 KiB
TypeScript
262 lines
14 KiB
TypeScript
// @vitest-environment jsdom
|
|
import { act } from "react";
|
|
import { createRoot, type Root } from "react-dom/client";
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { IssueRecoveryAction } from "@paperclipai/shared";
|
|
import { queryKeys } from "../lib/queryKeys";
|
|
import { WorkspaceExportRecovery } from "./WorkspaceExportRecovery";
|
|
|
|
const api = vi.hoisted(() => ({ inspect: vi.fn(), recover: vi.fn() }));
|
|
vi.mock("../api/issues", () => ({ issuesApi: { recoveryActions: api.inspect, recoverWorkspace: api.recover } }));
|
|
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
const action = {
|
|
id: "action-1", companyId: "company-1", sourceIssueId: "issue-1",
|
|
cause: "native_workspace_sync_out_retry_exhausted", kind: "active_run_watchdog",
|
|
status: "active", ownerType: "system", wakePolicy: null,
|
|
evidence: { runId: "run-1", workspaceRecovery: {
|
|
schema: "paperclip.workspace-recovery.v1", runId: "run-1", status: "blocked",
|
|
stage: "restoring_files", attempt: 6, requestIds: [], retryable: true,
|
|
}, systemRecovery: { state: "exhausted", preservationOperationIds: [] } },
|
|
} as unknown as IssueRecoveryAction;
|
|
|
|
function inspection(value = action) {
|
|
return { active: value, actions: [value], sourceInspection: {
|
|
schema: "paperclip.workspace-source-inspection.v1", actionId: value.id, runId: "run-1",
|
|
status: "verified", scope: "recorded_source_identity", observedAt: "2026-11-03T12:00:00Z",
|
|
} };
|
|
}
|
|
|
|
describe("governed retained-file recovery", () => {
|
|
let root: Root, container: HTMLDivElement, client: QueryClient;
|
|
beforeEach(() => {
|
|
vi.resetAllMocks(); localStorage.clear();
|
|
api.inspect.mockResolvedValue(inspection());
|
|
api.recover.mockResolvedValue({ actionId: action.id, status: "queued" });
|
|
client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity }, mutations: { retry: false } } });
|
|
client.setQueryData(queryKeys.auth.session, { user: { id: "board-1" } });
|
|
client.setQueryData(queryKeys.access.currentBoardAccess, {
|
|
userId: "board-1", companyIds: ["company-1"], source: "session", isInstanceAdmin: false,
|
|
memberships: [{ companyId: "company-1", membershipRole: "operator", status: "active" }],
|
|
});
|
|
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
|
|
});
|
|
afterEach(async () => {
|
|
await act(async () => root.unmount()); container.remove(); client.clear(); localStorage.clear();
|
|
vi.restoreAllMocks();
|
|
});
|
|
async function mount(value: IssueRecoveryAction | null = action) {
|
|
const props = { action: value, issueId: "issue-1", companyId: "company-1" };
|
|
await act(async () => root.render(<QueryClientProvider client={client}>
|
|
<WorkspaceExportRecovery {...props} />
|
|
</QueryClientProvider>));
|
|
await settle();
|
|
}
|
|
async function settle() {
|
|
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
|
|
}
|
|
function button(label: string) { return [...container.querySelectorAll("button")].find(b => b.textContent === label); }
|
|
async function click(label: string) {
|
|
const target = button(label); expect(target, `missing ${label}`).toBeDefined();
|
|
await act(async () => target!.click()); await settle();
|
|
}
|
|
|
|
it("offers the existing preservation operation for a stopped, exhausted system-owned export", async () => {
|
|
await mount();
|
|
await click("Recover saved files");
|
|
expect(api.inspect).toHaveBeenCalledWith("issue-1", { runId: "run-1", actionId: "action-1" });
|
|
expect(api.recover).toHaveBeenCalledTimes(1);
|
|
expect(api.recover).toHaveBeenCalledWith("issue-1", {
|
|
actionId: "action-1", runId: "run-1", idempotencyKey: expect.any(String),
|
|
});
|
|
expect(container.textContent).toContain("queued");
|
|
expect(container.textContent).not.toContain("Saved files recovered");
|
|
});
|
|
|
|
it("requests file preservation on plain HTTP without crypto.randomUUID", async () => {
|
|
const originalCrypto = globalThis.crypto;
|
|
vi.stubGlobal("crypto", { getRandomValues: originalCrypto.getRandomValues.bind(originalCrypto) });
|
|
try {
|
|
await mount(); await click("Recover saved files");
|
|
expect(api.recover).toHaveBeenCalledExactlyOnceWith("issue-1", {
|
|
actionId: "action-1", runId: "run-1", idempotencyKey: expect.stringMatching(
|
|
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/),
|
|
});
|
|
expect(container.textContent).not.toContain("Saved files recovered");
|
|
} finally { vi.unstubAllGlobals(); }
|
|
});
|
|
|
|
it.each(["viewer", "suspended", "foreign-company", "other-account"])("does not offer mutation with %s access", async kind => {
|
|
client.setQueryData(queryKeys.access.currentBoardAccess, {
|
|
userId: kind === "other-account" ? "board-2" : "board-1", source: "session", isInstanceAdmin: false,
|
|
companyIds: kind === "foreign-company" ? ["company-2"] : ["company-1"],
|
|
memberships: [{ companyId: kind === "foreign-company" ? "company-2" : "company-1",
|
|
membershipRole: kind === "viewer" ? "viewer" : "operator", status: kind === "suspended" ? "suspended" : "active" }],
|
|
});
|
|
await mount();
|
|
expect(button("Recover saved files")).toBeUndefined();
|
|
expect(api.inspect).not.toHaveBeenCalled();
|
|
expect(api.recover).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["resolved", "cancelled", "foreign-company", "foreign-task", "unsafe-archive"])("does not offer a %s source", async kind => {
|
|
await mount({ ...action, ...(kind === "foreign-company" ? { companyId: "company-2" }
|
|
: kind === "foreign-task" ? { sourceIssueId: "issue-2" }
|
|
: kind === "unsafe-archive" ? { cause: "native_workspace_sync_out_unsafe_archive" }
|
|
: { status: kind }) } as IssueRecoveryAction);
|
|
expect(button("Recover saved files")).toBeUndefined();
|
|
expect(api.recover).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a source/action/run binding that changed after the control was rendered", async () => {
|
|
api.inspect.mockResolvedValueOnce(inspection()).mockResolvedValueOnce({
|
|
...inspection(), sourceInspection: { ...inspection().sourceInspection, runId: "foreign-run" },
|
|
});
|
|
await mount(); await click("Recover saved files");
|
|
expect(api.recover).not.toHaveBeenCalled();
|
|
expect(container.textContent).toContain("File recovery changed");
|
|
});
|
|
|
|
it("does not offer an unverified source", async () => {
|
|
api.inspect.mockResolvedValue({ ...inspection(), sourceInspection: {
|
|
...inspection().sourceInspection, status: "blocked", failureCode: "source_binding_invalid",
|
|
} });
|
|
await mount();
|
|
expect(button("Recover saved files")).toBeUndefined();
|
|
expect(container.textContent).toContain("source is unavailable or has changed");
|
|
});
|
|
|
|
it("persists the exact request before POST and prevents a double click", async () => {
|
|
let finish!: (value: unknown) => void;
|
|
api.recover.mockImplementation((_issue, body) => {
|
|
expect(localStorage.getItem("workspace-file-recovery:company-1:issue-1:action-1:run-1:board-1")).toContain(body.idempotencyKey);
|
|
return new Promise(resolve => { finish = resolve; });
|
|
});
|
|
await mount();
|
|
const target = button("Recover saved files")!;
|
|
await act(async () => { target.click(); target.click(); }); await settle();
|
|
expect(api.recover).toHaveBeenCalledTimes(1);
|
|
await act(async () => finish({ actionId: action.id, status: "queued" })); await settle();
|
|
expect(button("Recover saved files")).toBeUndefined();
|
|
expect(container.textContent).not.toContain("Saved files recovered");
|
|
});
|
|
|
|
it("reconciles a lost accepted response through GET without another POST", async () => {
|
|
let current = action;
|
|
api.inspect.mockImplementation(async () => inspection(current));
|
|
api.recover.mockImplementation(async (_issue, body) => {
|
|
current = { ...action, evidence: { ...action.evidence, workspaceRecovery: {
|
|
...(action.evidence.workspaceRecovery as object), status: "queued", requestIds: [body.idempotencyKey],
|
|
} } };
|
|
throw Object.assign(new Error("Network reply lost"), { status: 503 });
|
|
});
|
|
await mount(); await click("Recover saved files");
|
|
expect(container.textContent).toContain("could not be confirmed");
|
|
await click("Check file recovery status");
|
|
expect(api.recover).toHaveBeenCalledTimes(1);
|
|
expect(container.textContent).toContain("Recovering saved files");
|
|
expect(container.textContent).not.toContain("could not be confirmed");
|
|
expect(button("Recover saved files")).toBeUndefined();
|
|
});
|
|
|
|
it("reuses the stored key after remount and a GET that has no acceptance receipt", async () => {
|
|
api.recover.mockRejectedValueOnce(Object.assign(new Error("Network unavailable"), { status: 503 }));
|
|
await mount(); await click("Recover saved files");
|
|
const first = api.recover.mock.calls[0][1].idempotencyKey;
|
|
await act(async () => root.render(null));
|
|
await mount();
|
|
expect(button("Recover saved files")).toBeUndefined();
|
|
await click("Check file recovery status");
|
|
await click("Recover saved files");
|
|
expect(api.recover).toHaveBeenCalledTimes(2);
|
|
expect(api.recover.mock.calls[1][1].idempotencyKey).toBe(first);
|
|
});
|
|
|
|
it("does not POST when durable storage is unavailable", async () => {
|
|
vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("storage denied"); });
|
|
await mount(); await click("Recover saved files");
|
|
expect(api.recover).not.toHaveBeenCalled();
|
|
expect(container.textContent).toContain("No request was sent");
|
|
});
|
|
|
|
it("does not send an old account's request after a source read completes", async () => {
|
|
let finish!: (value: unknown) => void;
|
|
api.inspect.mockResolvedValueOnce(inspection()).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
|
|
await mount(); await click("Recover saved files");
|
|
await act(async () => client.setQueryData(queryKeys.auth.session, { user: { id: "board-2" } }));
|
|
await act(async () => finish(inspection())); await settle();
|
|
expect(api.recover).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("shows a confirmed blocked attempt as failed preservation, not queued or recovered", async () => {
|
|
let current = action;
|
|
api.inspect.mockImplementation(async () => inspection(current));
|
|
api.recover.mockImplementation(async (_issue, body) => {
|
|
current = { ...action, evidence: { ...action.evidence, workspaceRecovery: {
|
|
...(action.evidence.workspaceRecovery as object), requestIds: [body.idempotencyKey],
|
|
} } };
|
|
return { actionId: action.id, status: "queued" };
|
|
});
|
|
await mount(); await click("Recover saved files");
|
|
expect(container.textContent).toContain("File recovery has not finished");
|
|
expect(container.textContent).not.toContain("File recovery is queued");
|
|
expect(container.textContent).not.toContain("Saved files recovered");
|
|
expect(api.recover).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("offers a new explicit request only after the prior accepted attempt is confirmed exhausted", async () => {
|
|
let current = action;
|
|
const accepted: string[] = [];
|
|
api.inspect.mockImplementation(async () => inspection(current));
|
|
api.recover.mockImplementation(async (_issue, body) => {
|
|
accepted.push(body.idempotencyKey);
|
|
current = { ...action, evidence: { ...action.evidence, workspaceRecovery: {
|
|
...(action.evidence.workspaceRecovery as object), requestIds: [...accepted],
|
|
} } };
|
|
return { actionId: action.id, status: "queued" };
|
|
});
|
|
await mount(); await click("Recover saved files");
|
|
expect(container.textContent).toContain("File recovery has not finished");
|
|
expect(api.recover).toHaveBeenCalledTimes(1);
|
|
await click("Try file recovery again");
|
|
expect(api.recover).toHaveBeenCalledTimes(2);
|
|
expect(accepted[1]).not.toBe(accepted[0]);
|
|
expect(container.textContent).not.toContain("Saved files recovered");
|
|
});
|
|
|
|
it("does not replace the confirmed failed key if another recovery is active at the fresh read", async () => {
|
|
let current = action;
|
|
api.inspect.mockImplementation(async () => inspection(current));
|
|
api.recover.mockImplementation(async (_issue, body) => {
|
|
current = { ...action, evidence: { ...action.evidence, workspaceRecovery: {
|
|
...(action.evidence.workspaceRecovery as object), requestIds: [body.idempotencyKey],
|
|
} } };
|
|
return { actionId: action.id, status: "queued" };
|
|
});
|
|
await mount(); await click("Recover saved files");
|
|
const previous = api.recover.mock.calls[0][1].idempotencyKey;
|
|
current = { ...current, evidence: { ...current.evidence, workspaceRecovery: {
|
|
...(current.evidence.workspaceRecovery as object), status: "recovering",
|
|
} } };
|
|
await click("Try file recovery again");
|
|
expect(api.recover).toHaveBeenCalledTimes(1);
|
|
expect(localStorage.getItem("workspace-file-recovery:company-1:issue-1:action-1:run-1:board-1")).toContain(previous);
|
|
});
|
|
|
|
it("only reports recovered files after the durable preservation receipt is present", async () => {
|
|
const recovered = { ...action, evidence: { ...action.evidence, workspaceRecovery: {
|
|
...(action.evidence.workspaceRecovery as object), status: "recovered",
|
|
}, systemRecovery: { state: "complete", preservationOperationIds: [] } } };
|
|
api.inspect.mockResolvedValue(inspection(recovered)); await mount();
|
|
expect(container.textContent).not.toContain("Saved files recovered");
|
|
api.inspect.mockResolvedValue(inspection({ ...recovered, evidence: { ...recovered.evidence,
|
|
systemRecovery: { state: "complete", preservationOperationIds: ["host-preservation-operation"] },
|
|
} }));
|
|
await act(async () => client.invalidateQueries({ queryKey: queryKeys.issues.recoveryActions("issue-1", "action-1", "run-1") }));
|
|
await settle();
|
|
expect(container.textContent).toContain("Saved files recovered");
|
|
expect(api.recover).not.toHaveBeenCalled();
|
|
});
|
|
});
|