mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 21:35:36 +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>
327 lines
13 KiB
TypeScript
327 lines
13 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import {
|
|
createTenantSessionRecoveryCoordinator,
|
|
tenantSessionRecovery,
|
|
} from "@/lib/tenant-session-recovery";
|
|
import { api, detachInflightGet } from "./client";
|
|
import { toolsApi } from "./tools";
|
|
import { museInvitationsApi } from "./museInvitations";
|
|
|
|
interface Deferred<T> {
|
|
promise: Promise<T>;
|
|
resolve: (value: T) => void;
|
|
reject: (reason?: unknown) => void;
|
|
}
|
|
|
|
function deferred<T>(): Deferred<T> {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (reason?: unknown) => void;
|
|
const promise = new Promise<T>((res, rej) => {
|
|
resolve = res;
|
|
reject = rej;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
|
|
function jsonResponse(body: unknown) {
|
|
return { ok: true, status: 200, json: async () => body } as unknown as Response;
|
|
}
|
|
|
|
function errorResponse(body: unknown, status = 401) {
|
|
return { ok: false, status, json: async () => body } as unknown as Response;
|
|
}
|
|
|
|
const fetchMock = vi.fn();
|
|
|
|
beforeEach(() => {
|
|
fetchMock.mockReset();
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
describe("tenant-session recovery", () => {
|
|
it("loads anonymous Dot consent despite concurrent protected background probes", async () => {
|
|
const reload = vi.fn();
|
|
const requestId = `pcmcp_request_${"a".repeat(43)}`;
|
|
const recovery = createTenantSessionRecoveryCoordinator(reload, () => `/dot-connect/${requestId}`);
|
|
vi.spyOn(tenantSessionRecovery, "recoverIfNeeded").mockImplementation(recovery.recoverIfNeeded);
|
|
fetchMock.mockImplementation((url: string) => Promise.resolve(
|
|
url.includes("/dot-mcp/requests/")
|
|
? jsonResponse({ id: requestId, agentConnection: true })
|
|
: errorResponse({ error: "tenant_session_required" }),
|
|
));
|
|
|
|
const background = api.get("/health");
|
|
const consent = api.get(`/dot-mcp/requests/${requestId}`);
|
|
await expect(background).rejects.toMatchObject({ status: 401 });
|
|
await expect(consent).resolves.toEqual({ id: requestId, agentConnection: true });
|
|
expect(reload).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps concurrent failures pending and schedules one top-level reload", async () => {
|
|
const reload = vi.fn();
|
|
const recovery = createTenantSessionRecoveryCoordinator(reload);
|
|
vi.spyOn(tenantSessionRecovery, "recoverIfNeeded").mockImplementation(recovery.recoverIfNeeded);
|
|
fetchMock.mockResolvedValue(errorResponse({ error: "tenant_session_required" }));
|
|
|
|
const first = api.post("/tenant-session-a", { value: 1 });
|
|
const second = api.post("/tenant-session-b", { value: 2 });
|
|
|
|
await vi.waitFor(() => {
|
|
expect(tenantSessionRecovery.recoverIfNeeded).toHaveBeenCalledTimes(2);
|
|
expect(reload).toHaveBeenCalledTimes(1);
|
|
});
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
|
|
let settled = false;
|
|
void Promise.all([first, second]).then(
|
|
() => { settled = true; },
|
|
() => { settled = true; },
|
|
);
|
|
await Promise.resolve();
|
|
expect(settled).toBe(false);
|
|
});
|
|
|
|
it("preserves ApiError handling for an unrelated 401", async () => {
|
|
fetchMock.mockResolvedValue(errorResponse({ error: "unauthorized" }));
|
|
|
|
await expect(api.get("/ordinary-401")).rejects.toMatchObject({
|
|
name: "ApiError",
|
|
status: 401,
|
|
code: "unauthorized",
|
|
message: "Your session has ended. Sign in again to continue.",
|
|
});
|
|
|
|
fetchMock.mockResolvedValue(jsonResponse({ recovered: true }));
|
|
await expect(api.get("/ordinary-401")).resolves.toEqual({ recovered: true });
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
});
|
|
});
|
|
|
|
describe("in-tab GET coalescing", () => {
|
|
it("keeps fresh validation reads separate from older and concurrent requests", async () => {
|
|
const old = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(old.promise).mockResolvedValue(jsonResponse({ title: "Current C" }));
|
|
const stale = api.get("/fresh-validation");
|
|
const first = api.get("/fresh-validation", { cache: "no-store", fresh: true });
|
|
const second = api.get("/fresh-validation", { cache: "no-store", fresh: true });
|
|
const joined = api.get("/fresh-validation");
|
|
expect(fetchMock).toHaveBeenCalledTimes(3);
|
|
expect(fetchMock.mock.calls[1][1]).toMatchObject({ cache: "no-store" });
|
|
await expect(first).resolves.toEqual({ title: "Current C" });
|
|
await expect(second).resolves.toEqual({ title: "Current C" });
|
|
old.resolve(jsonResponse({ title: "Old A" }));
|
|
await expect(stale).resolves.toEqual({ title: "Old A" });
|
|
await expect(joined).resolves.toEqual({ title: "Old A" });
|
|
});
|
|
|
|
it("times out a caller without cancelling another and starts a fresh fetch on retry", async () => {
|
|
vi.useFakeTimers();
|
|
const first = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(first.promise);
|
|
const survivorController = new AbortController();
|
|
const survivor = api.get("/deadline-shared", { signal: survivorController.signal });
|
|
const timed = api.get("/deadline-shared", { timeoutMs: 100 }).catch(error => error);
|
|
const sharedSignal = fetchMock.mock.calls[0][1].signal as AbortSignal;
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(await timed).toMatchObject({ status: 408, body: { error: "TIMEOUT" } });
|
|
expect(sharedSignal.aborted).toBe(false);
|
|
fetchMock.mockResolvedValueOnce(jsonResponse({ fresh: true }));
|
|
await expect(api.get("/deadline-shared", { timeoutMs: 100 })).resolves.toEqual({ fresh: true });
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
survivorController.abort();
|
|
await expect(survivor).rejects.toMatchObject({ name: "AbortError" });
|
|
expect(sharedSignal.aborted).toBe(true);
|
|
first.resolve(jsonResponse({ stale: true }));
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("bounds response-body reads and aborts the last caller's fetch", async () => {
|
|
vi.useFakeTimers();
|
|
const body = deferred<unknown>();
|
|
fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => body.promise });
|
|
const result = api.get("/deadline-body", { timeoutMs: 100 }).catch(error => error);
|
|
const signal = fetchMock.mock.calls[0][1].signal as AbortSignal;
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(await result).toMatchObject({ status: 408 });
|
|
expect(signal.aborted).toBe(true);
|
|
body.resolve({ tooLate: true });
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("clears a successful or cancelled caller's deadline", async () => {
|
|
vi.useFakeTimers();
|
|
fetchMock.mockResolvedValueOnce(jsonResponse({ ok: true }));
|
|
await expect(api.get("/deadline-success", { timeoutMs: 100 })).resolves.toEqual({ ok: true });
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
const controller = new AbortController();
|
|
fetchMock.mockReturnValueOnce(deferred<Response>().promise);
|
|
const result = api.get("/deadline-cancel", { signal: controller.signal, timeoutMs: 100 });
|
|
controller.abort();
|
|
await expect(result).rejects.toMatchObject({ name: "AbortError" });
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("shares one underlying fetch for identical in-flight GETs", async () => {
|
|
const d = deferred<Response>();
|
|
fetchMock.mockReturnValue(d.promise);
|
|
|
|
const p1 = api.get("/coalesce-a");
|
|
const p2 = api.get("/coalesce-a");
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
|
|
d.resolve(jsonResponse({ value: 1 }));
|
|
expect(await p1).toEqual({ value: 1 });
|
|
expect(await p2).toEqual({ value: 1 });
|
|
});
|
|
|
|
it("issues a fresh fetch after the previous one settles", async () => {
|
|
fetchMock.mockResolvedValue(jsonResponse({ value: "x" }));
|
|
await api.get("/coalesce-b");
|
|
await api.get("/coalesce-b");
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("does not coalesce different paths", async () => {
|
|
fetchMock.mockReturnValue(deferred<Response>().promise);
|
|
const c1 = new AbortController();
|
|
const c2 = new AbortController();
|
|
const p1 = api.get("/path-1", { signal: c1.signal });
|
|
const p2 = api.get("/path-2", { signal: c2.signal });
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
// Clean up the never-settling shared entries so the module map does not leak.
|
|
c1.abort();
|
|
c2.abort();
|
|
await expect(p1).rejects.toMatchObject({ name: "AbortError" });
|
|
await expect(p2).rejects.toMatchObject({ name: "AbortError" });
|
|
});
|
|
|
|
it("stops later callers joining a detached in-flight GET", async () => {
|
|
// A GET issued under one account's session must not answer a caller that
|
|
// runs after the account changed.
|
|
const first = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(first.promise);
|
|
const previousAccount = api.get("/detach-me");
|
|
|
|
detachInflightGet("/detach-me");
|
|
|
|
const second = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(second.promise);
|
|
const currentAccount = api.get("/detach-me");
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
|
|
// Each caller gets its own response, not the other's.
|
|
first.resolve(jsonResponse({ companies: ["previous"] }));
|
|
second.resolve(jsonResponse({ companies: ["current"] }));
|
|
expect(await previousAccount).toEqual({ companies: ["previous"] });
|
|
expect(await currentAccount).toEqual({ companies: ["current"] });
|
|
});
|
|
|
|
it("never coalesces mutations", async () => {
|
|
fetchMock.mockResolvedValue(jsonResponse({ ok: true }));
|
|
await Promise.all([api.post("/mutate", { a: 1 }), api.post("/mutate", { a: 1 })]);
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
});
|
|
});
|
|
|
|
describe("per-caller abort semantics", () => {
|
|
it("aborting one caller rejects only that caller, not the shared fetch", async () => {
|
|
const d = deferred<Response>();
|
|
let sharedSignal: AbortSignal | undefined;
|
|
fetchMock.mockImplementation((_url: string, init: RequestInit) => {
|
|
sharedSignal = init.signal ?? undefined;
|
|
return d.promise;
|
|
});
|
|
|
|
const c1 = new AbortController();
|
|
const c2 = new AbortController();
|
|
const p1 = api.get("/abort-a", { signal: c1.signal });
|
|
const p2 = api.get("/abort-a", { signal: c2.signal });
|
|
|
|
c1.abort();
|
|
await expect(p1).rejects.toMatchObject({ name: "AbortError" });
|
|
// The shared fetch is still alive because caller 2 has not aborted.
|
|
expect(sharedSignal?.aborted).toBe(false);
|
|
|
|
d.resolve(jsonResponse({ value: 2 }));
|
|
expect(await p2).toEqual({ value: 2 });
|
|
});
|
|
|
|
it("aborts the shared fetch after all callers cancel and permits a fresh request", async () => {
|
|
const d = deferred<Response>();
|
|
let sharedSignal: AbortSignal | undefined;
|
|
fetchMock.mockImplementation((_url: string, init: RequestInit) => {
|
|
sharedSignal = init.signal ?? undefined;
|
|
return d.promise;
|
|
});
|
|
|
|
const c1 = new AbortController();
|
|
const c2 = new AbortController();
|
|
const p1 = api.get("/abort-b", { signal: c1.signal });
|
|
const p2 = api.get("/abort-b", { signal: c2.signal });
|
|
|
|
c1.abort();
|
|
c2.abort();
|
|
await expect(p1).rejects.toMatchObject({ name: "AbortError" });
|
|
await expect(p2).rejects.toMatchObject({ name: "AbortError" });
|
|
expect(sharedSignal?.aborted).toBe(true);
|
|
|
|
fetchMock.mockResolvedValueOnce(jsonResponse({ value: "fresh" }));
|
|
const fresh = api.get("/abort-b");
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
expect(await fresh).toEqual({ value: "fresh" });
|
|
});
|
|
|
|
it("rejects immediately if the caller signal is already aborted", async () => {
|
|
const controller = new AbortController();
|
|
controller.abort();
|
|
await expect(api.get("/already-aborted", { signal: controller.signal })).rejects.toMatchObject({
|
|
name: "AbortError",
|
|
});
|
|
expect(fetchMock).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
|
|
describe("managed-account request isolation", () => {
|
|
it("does not share a previous viewing user's pending account response", async () => {
|
|
const previous = deferred<Response>();
|
|
const current = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(previous.promise).mockReturnValueOnce(current.promise);
|
|
const previousUser = toolsApi.listAggregatorApps("shared-gateway");
|
|
const currentUser = toolsApi.listAggregatorApps("shared-gateway");
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
expect(fetchMock.mock.calls.every(([, options]) => options.cache === "no-store")).toBe(true);
|
|
current.resolve(jsonResponse({ apps: ["current-user-account"] }));
|
|
previous.resolve(jsonResponse({ apps: ["previous-user-account"] }));
|
|
expect(await currentUser).toEqual({ apps: ["current-user-account"] });
|
|
expect(await previousUser).toEqual({ apps: ["previous-user-account"] });
|
|
});
|
|
});
|
|
|
|
describe("Muse operator request isolation", () => {
|
|
it.each([
|
|
["invitation resume", () => museInvitationsApi.resume("company")],
|
|
["connection evidence", () => museInvitationsApi.connection("company", "agent")],
|
|
] as const)("does not join the previous operator's %s request", async (_name, read) => {
|
|
const previous = deferred<Response>();
|
|
const current = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(previous.promise).mockReturnValueOnce(current.promise);
|
|
const previousOperator = read();
|
|
const currentOperator = read();
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
expect(fetchMock.mock.calls.every(([, options]) => options.cache === "no-store")).toBe(true);
|
|
current.resolve(jsonResponse({ operator: "current" }));
|
|
previous.resolve(jsonResponse({ operator: "previous" }));
|
|
expect(await currentOperator).toEqual({ operator: "current" });
|
|
expect(await previousOperator).toEqual({ operator: "previous" });
|
|
});
|
|
});
|