mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 12:33:05 +01:00
## Thinking Path > - Paperclip lets people manage agent work through the board. > - The board reads task, agent, settings, plugin, and run data from the server. > - A deploy can interrupt those reads after content is already visible. > - Local error branches can replace that content with an error or show raw codes. > - This pull request moves the remaining reads to the shared recovery behavior. > - The query-error guard prevents new local error patterns from returning. ## Linked Issues or Issue Description **What happened?** Loaded lists, settings, task panels, and manual reads could clear their content or show errors during a server restart. Some reads also disabled the shared retry policy. **Expected behavior** Keep loaded content during a temporary failure. Show the shared connection banner. Retry reads after recovery. Replace content after a real access denial or missing resource, with readable copy. **Steps to reproduce** Open a task, settings page, or run log. Return 503 with `tenant_app_unavailable` from the API. Restore the API and check that content refreshes. Repeat with 403 and 404 to check the failure state. Related merged work: Refs #15754, Refs #15772, Refs #17960. This change covers remaining reads and enforcement. Browser persistence and the outage browser suite follow separately. ## What Changed - Repair an existing PostgreSQL deadline fixture at UTC boundaries. A daily cap defers a heartbeat until both its original interval and the next UTC day allow it. Keep the counted run in its seeded day and cover noon, just before midnight and the first second after midnight with explicit clocks and real PostgreSQL. Production scheduling is unchanged. - Integrate the saved list, settings, shell, task, and manual-read recovery changes against current master. Preserve the current task, Inbox, and run-log structure. - Add `useResilientFetch` for component-local reads. Preserve loaded data, cancel stale requests, and retry through the shared connectivity policy. Keep browser and pairing capabilities in memory. - Retain run log chunks across stream changes and catch up after recovery without duplicate chunks or stalled requests. - Keep genuine authorization and missing-resource failures visible. Translate known single-word codes such as `forbidden`. Show known skills and disconnected-app failures before sibling loading states. Keep Retry bound to its failed request. - Make the query-error guard enforce by default and run it in the CI policy job. Document the narrow exceptions and the read recovery contract. - Invalidate pending OAuth discovery when the operator leaves setup or its context changes. Keep reserved-popup cleanup bound to the current attempt. ## Verification - Current read head `09d1db29dea` is merge-ready: all 59 check runs are completed (54 successful, three skipped, two neutral), the legacy Snyk status is successful, and both required `ci / verify` and `ci / e2e` gates pass. Greptile Apex reviewed this exact head at 5/5 with no unresolved threads; the branch has no merge conflicts. The current CI run is `41748339602`. - Current read head `09d1db29dea` includes master `683fa4725e9`. The latest change touches only the existing server deadline test fixture. Application source remains the previously verified `86376fa751e` revision: all 60 affected skills/disconnected-app tests and both application UI typechecks passed, along with token gates and the enforcing query-error guard. Those UI suites were not repeated for this test-only repair. - The fixture repair passes all seven deadline integration cases and the complete server typecheck, including the server test layer. The old assertion deterministically fails at 23:59:06.888 UTC; its one-second-old run also fails the first-second-of-day probe. The corrected fixture passes noon and both midnight probes. The permanent three-case coverage uses seeded 2099 clocks. - Twelve new regressions fail against the previous implementation. Both skills variants and disconnected-app pages show either request's 403 or 429 while the sibling pauses or remains fetching. Permission failures stay visible. Retry stays usable for its failed request and recovers independently. An initial test-fixture query-key typo was corrected before the passing run. The finding is replied to and resolved. Greptile reviewed prior application revision `86376fa751e` at 5/5 with no new actionable findings or unresolved threads. The current test-only head has now received its own Apex 5/5 review with no unresolved threads, and its CI is successful as recorded above. - The preceding OAuth fix passed all 237 setup tests on both application branches. Its ten regressions prove that Back, Cancel, unmount, or context changes retire initial discovery without creating a connection, caching old identities, navigating an abandoned popup, or closing a newer attempt. - Earlier master integration `e992f770339` passed all 309 tests across eight affected Slack, recovery, retry, submission and task files, plus UI typecheck, token gates, enforcing query-error scan and seven guard tests. The integration preserves Slack workspace reconnect and shared recovery, readable execution errors, source-inspection company scoping, and current submission behavior. Newly inherited retained-file recovery controls keep cached data through transient failures and hide it after definitive denial. - The preceding cache head `97c0bc3966f` passed 1,038 focused cache/write/editor/account/task/API tests. All 22 built-UI outage/write/loading cases passed in 4.7 minutes on exact browser head `b7deaaee5da`, with strict checking of all three specs. The latest skills/app rendering fix is covered by its affected component suites; those broader cases were not repeated for this separate read path. - Historical broader UI, CLI and build results and unresolved aggregate server/DB/adapter failures remain in the PR discussion. Interrupted CI runs were audited and recorded separately; they are not counted as passes. Controlled local outages do not prove hosted authentication or a real Cloud restart/deploy. Real hosted acceptance remains required after merge and deployment. Commands for the latest fix: ```sh pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanySkills.test.tsx src/pages/apps/AppNotConnected.test.tsx pnpm --filter @paperclipai/ui typecheck pnpm check:token-gates node scripts/check-query-error-rendering.mjs --enforce --summary ``` ## Risks This migration touches many read surfaces. The main risks are initial loading, request cancellation, retained authorization state, and run-log paging. The tests cover those states. There are no server, schema, dependency, or API contract changes. The follow-up browser suite and hosted deploy acceptance are required before release acceptance. Recovered commits retain their original authors. If squash-merging, preserve `Co-Authored-By: Bender (Fable) <bender@agents.paperclip.ing>` and the Paperclip trailer. ## Model Used OpenAI `gpt-6.1-sol` through Codex, with xhigh reasoning effort, tool use, and code execution. The context window size is not exposed. Saved source commits keep their original authorship. ## 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 described the issue in-PR following the bug report 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 - [x] The affected local tests pass; broader limitations are recorded above - [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 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: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Bender (Fable) <bender@agents.paperclip.ing> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
290 lines
15 KiB
TypeScript
290 lines
15 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 { ApiError } from "../api/client";
|
|
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.each(["access", "source"])("retains loaded recovery controls through a transient %s refresh failure", async kind => {
|
|
await mount();
|
|
const key = kind === "access" ? queryKeys.access.currentBoardAccess
|
|
: queryKeys.issues.recoveryActions("issue-1", "action-1", "run-1");
|
|
await act(async () => {
|
|
await client.fetchQuery({ queryKey: key, staleTime: 0, queryFn: async () => { throw new ApiError("Restarting", 503, { error: "tenant_app_unavailable" }); }, retry: false }).catch(() => {});
|
|
});
|
|
await settle();
|
|
expect(button("Recover saved files")).toBeDefined();
|
|
expect(container.querySelector('[role="alert"]')).toBeNull();
|
|
expect(container.textContent).not.toContain("tenant_app_unavailable");
|
|
expect(api.recover).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["access", "source"])("hides cached recovery controls after definitive %s denial", async kind => {
|
|
await mount();
|
|
const key = kind === "access" ? queryKeys.access.currentBoardAccess
|
|
: queryKeys.issues.recoveryActions("issue-1", "action-1", "run-1");
|
|
await act(async () => {
|
|
await client.fetchQuery({ queryKey: key, staleTime: 0, queryFn: async () => { throw new ApiError("Forbidden", 403, null); }, retry: false }).catch(() => {});
|
|
});
|
|
await settle();
|
|
expect(button("Recover saved files")).toBeUndefined();
|
|
expect(container.querySelector('[role="alert"]')).not.toBeNull();
|
|
expect(api.recover).not.toHaveBeenCalled();
|
|
});
|
|
|
|
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();
|
|
});
|
|
});
|