mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +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>
238 lines
14 KiB
TypeScript
238 lines
14 KiB
TypeScript
// @vitest-environment jsdom
|
|
import { flushSync } from "react-dom";
|
|
import { createRoot, type Root } from "react-dom/client";
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
|
import type { ComponentProps } from "react";
|
|
import type { AiManagedConnectionSummary } from "@paperclipai/shared";
|
|
import { AiConnectionField, aiProviderForAdapter } from "./AiConnectionField";
|
|
import { ApiError } from "@/api/client";
|
|
import type { AiConnectionCredentialStep } from "./AiConnectionCredentialStep";
|
|
|
|
const mocks = vi.hoisted(() => ({ list: vi.fn(), setDefault: vi.fn() }));
|
|
let credentialProps: ComponentProps<typeof AiConnectionCredentialStep> | undefined;
|
|
vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: mocks }));
|
|
vi.mock("./AiConnectionCredentialStep", () => ({
|
|
AiConnectionCredentialStep: (props: ComponentProps<typeof AiConnectionCredentialStep>) => {
|
|
credentialProps = props;
|
|
return <div>Provider sign-in</div>;
|
|
},
|
|
}));
|
|
vi.mock("./AiProviderSetup", () => ({ AiProviderSetup: () => <div>Advanced provider setup</div> }));
|
|
vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null }));
|
|
|
|
let root: Root;
|
|
let container: HTMLDivElement;
|
|
let client: QueryClient;
|
|
const onChange = vi.fn();
|
|
const account = (overrides: Partial<AiManagedConnectionSummary> = {}): AiManagedConnectionSummary => ({
|
|
id: "old-connection", grantId: "old-grant", companyId: "company",
|
|
provider: "anthropic", method: "subscription", name: "My Claude",
|
|
ownership: "personal", ownerUserId: "owner", isDefault: true,
|
|
status: "needs_attention", ...overrides,
|
|
});
|
|
async function settle() {
|
|
for (let i = 0; i < 5; i++) {
|
|
await new Promise(resolve => setTimeout(resolve, 0));
|
|
flushSync(() => {});
|
|
}
|
|
}
|
|
async function mount(connections: AiManagedConnectionSummary[], canManageConnections = true, preferAdvanced = false) {
|
|
mocks.list.mockResolvedValue({ currentUserId: "owner", connections, canManageConnections });
|
|
flushSync(() => root.render(<QueryClientProvider client={client}>
|
|
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="claude_local"
|
|
preferAdvanced={preferAdvanced}
|
|
value={{ provider: "anthropic", method: "subscription", mode: "responsible_user" }} onChange={onChange} />
|
|
</QueryClientProvider>));
|
|
await settle();
|
|
}
|
|
async function click(label: string) {
|
|
if (label === "Connect another account") {
|
|
const trigger = document.querySelector('[role="combobox"][aria-label="Connection"]')!;
|
|
flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
|
|
await settle();
|
|
const option = Array.from(document.querySelectorAll<HTMLElement>('[role="option"]')).find(item => item.textContent?.includes("Connect an account"));
|
|
expect(option).toBeDefined();
|
|
flushSync(() => option!.click());
|
|
await settle();
|
|
return;
|
|
}
|
|
const button = Array.from(document.querySelectorAll("button")).find(item => item.textContent === label);
|
|
expect(button, `Missing button: ${label}`).toBeDefined();
|
|
flushSync(() => button!.click());
|
|
}
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
credentialProps = undefined;
|
|
mocks.setDefault.mockResolvedValue({});
|
|
container = document.createElement("div");
|
|
document.body.append(container);
|
|
root = createRoot(container);
|
|
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
|
});
|
|
afterEach(() => { flushSync(() => root.unmount()); client.clear(); container.remove(); });
|
|
|
|
it("reconnects the unavailable personal default in place", async () => {
|
|
await mount([account()]);
|
|
await click("Reconnect account");
|
|
expect(credentialProps).toMatchObject({ connectionId: "old-connection", initialMethod: "subscription", fixedMethod: true });
|
|
credentialProps!.onComplete({ connectionId: "old-connection", grantId: "old-grant", method: "subscription" });
|
|
await settle();
|
|
expect(mocks.setDefault).not.toHaveBeenCalled();
|
|
expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "subscription", mode: "responsible_user" });
|
|
});
|
|
|
|
it("identifies duplicate-named accounts before adopting the exact personal grant", async () => {
|
|
const personal = account({ id: "00000000-0000-4000-8000-000000000001", grantId: "00000000-0000-4000-8000-000000000002", provider: "openai", method: "api_key", name: "OpenAI", ownerName: "Avery", status: "connected", isDefault: false });
|
|
const shared = account({ id: "00000000-0000-4000-8000-000000000003", grantId: "00000000-0000-4000-8000-000000000004", provider: "openai", method: "subscription", name: "OpenAI", accountLabel: "engineering@example.test", ownership: "shared", ownerUserId: undefined, status: "connected", isDefault: false });
|
|
const sharedKey = account({ id: "00000000-0000-4000-8000-000000000005", grantId: "00000000-0000-4000-8000-000000000006", provider: "openai", method: "api_key", name: "OpenAI", ownerName: "Engineering", ownership: "shared", ownerUserId: undefined, status: "connected", isDefault: false });
|
|
const unavailable = account({ id: "expired-account", grantId: "expired-grant", provider: "openai", method: "api_key", name: "Expired account", ownerName: "Avery" });
|
|
mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [shared, personal, sharedKey, unavailable], canManageConnections: true });
|
|
flushSync(() => root.render(<QueryClientProvider client={client}>
|
|
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="codex_local" legacy onChange={onChange} />
|
|
</QueryClientProvider>));
|
|
await settle();
|
|
await click("Choose a managed connection");
|
|
const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
|
|
flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
|
|
await settle();
|
|
const choices = [...document.querySelectorAll<HTMLElement>('[role="option"]')];
|
|
expect(choices.map(choice => choice.textContent)).toContain("OpenAI · API key · Personal · Avery");
|
|
expect(choices.map(choice => choice.textContent)).toContain("OpenAI · ChatGPT subscription · Company shared · engineering@example.test");
|
|
expect(choices.map(choice => choice.textContent)).toContain("OpenAI · API key · Company shared · Engineering");
|
|
expect(choices.find(choice => choice.textContent?.includes("Expired account"))?.getAttribute("aria-disabled")).toBe("true");
|
|
flushSync(() => choices.find(choice => choice.textContent === "OpenAI · API key · Personal · Avery")!.click());
|
|
await settle();
|
|
expect(document.querySelector('[role="dialog"]')?.textContent).toContain("OpenAI · API key · Personal · Avery");
|
|
expect(onChange).not.toHaveBeenCalled();
|
|
await click("Use this binding when saved");
|
|
expect(onChange).toHaveBeenCalledExactlyOnceWith({ provider: "openai", method: "api_key", mode: "delegated", connectionId: personal.id, grantId: personal.grantId });
|
|
});
|
|
|
|
it("opens provider setup directly when connecting from the advanced mode", async () => {
|
|
await mount([], true, true);
|
|
await click("Connect another account");
|
|
expect(document.body.textContent).toContain("Advanced provider setup");
|
|
expect(credentialProps).toBeUndefined();
|
|
});
|
|
|
|
it("selects the returned new grant and actual method before adopting the personal default", async () => {
|
|
await mount([account()]);
|
|
await click("Connect another account");
|
|
expect(document.body.textContent).toContain("default");
|
|
expect(credentialProps).toMatchObject({ connectionId: undefined, allAgents: true });
|
|
let resolveDefault!: () => void;
|
|
mocks.setDefault.mockImplementation(() => new Promise<void>(resolve => { resolveDefault = resolve; }));
|
|
credentialProps!.onComplete({ connectionId: "new-connection", grantId: "new-grant", method: "api_key" });
|
|
await settle();
|
|
expect(mocks.setDefault).toHaveBeenCalledWith("company", "new-grant");
|
|
expect(onChange).not.toHaveBeenCalled();
|
|
resolveDefault();
|
|
await settle();
|
|
expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "api_key", mode: "responsible_user" });
|
|
});
|
|
|
|
it("lets the owner limit a new personal connection to this agent", async () => {
|
|
await mount([]);
|
|
await click("Connect another account");
|
|
const checkbox = document.querySelector<HTMLButtonElement>('[role="checkbox"]')!;
|
|
expect(checkbox).not.toBeNull();
|
|
expect(checkbox.getAttribute("aria-checked")).toBe("true");
|
|
flushSync(() => checkbox.click());
|
|
expect(credentialProps).toMatchObject({ allAgents: false, agentIds: ["agent"] });
|
|
});
|
|
|
|
it("keeps default-update failures visible and retries without another provider login", async () => {
|
|
await mount([account()]);
|
|
await click("Connect another account");
|
|
mocks.setDefault.mockRejectedValueOnce(new Error("Default update failed"));
|
|
credentialProps!.onComplete({ connectionId: "new-connection", grantId: "new-grant", method: "api_key" });
|
|
await settle();
|
|
expect(document.body.textContent).toContain("Default update failed");
|
|
expect(onChange).not.toHaveBeenCalled();
|
|
await click("Retry default selection");
|
|
await settle();
|
|
expect(mocks.setDefault).toHaveBeenCalledTimes(2);
|
|
expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "api_key", mode: "responsible_user" });
|
|
});
|
|
|
|
it("does not offer reconnection for a healthy default or another owner's account", async () => {
|
|
await mount([account({ status: "connected" }), account({ id: "someone-else", ownerUserId: "other" })]);
|
|
expect(document.body.textContent).not.toContain("Reconnect account");
|
|
});
|
|
|
|
it("keeps an ordinary member's new connection scoped to the current agent by default", async () => {
|
|
await mount([], false);
|
|
expect(document.body.textContent).toContain("You have no default account");
|
|
await click("Connect another account");
|
|
expect(document.querySelector<HTMLButtonElement>('[role="checkbox"]')!.disabled).toBe(true);
|
|
expect(credentialProps).toMatchObject({ allAgents: false, agentIds: ["agent"] });
|
|
});
|
|
|
|
it("uses the server's connection-manager permission for company-wide access", async () => {
|
|
await mount([], true);
|
|
await click("Connect another account");
|
|
expect(credentialProps).toMatchObject({ allAgents: true });
|
|
});
|
|
|
|
it("offers Pi account selection before choosing its required model", async () => {
|
|
mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [], canManageConnections: true });
|
|
expect(aiProviderForAdapter("pi_local")).toBe("openrouter");
|
|
flushSync(() => root.render(<QueryClientProvider client={client}>
|
|
<AiConnectionField companyId="company" agentId="agent" agentName="Pi" adapterType="pi_local" model=""
|
|
value={{ provider: "openrouter", method: "api_key", mode: "responsible_user" }} onChange={onChange} />
|
|
</QueryClientProvider>));
|
|
await settle();
|
|
expect(document.querySelector('[role="combobox"][aria-label="Connection"]')).not.toBeNull();
|
|
expect(container.textContent).not.toContain("does not support the current harness");
|
|
await click("Connect another account");
|
|
expect(document.body.textContent).toContain("Advanced provider setup");
|
|
});
|
|
|
|
it.each(["openai", "anthropic", "google", "openrouter"] as const)("keeps a matching saved Pi %s API-key account selectable", async provider => {
|
|
const saved = account({ provider, method: "api_key", name: "Pi provider account", accountLabel: "avery@example.test", status: "connected" });
|
|
mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [saved], canManageConnections: true });
|
|
flushSync(() => root.render(<QueryClientProvider client={client}>
|
|
<AiConnectionField companyId="company" agentId="agent" agentName="Pi" adapterType="pi_local" model={`${provider}/provider-model`}
|
|
value={{ provider, method: "api_key", mode: "delegated", connectionId: saved.id, grantId: saved.grantId }} onChange={onChange} />
|
|
</QueryClientProvider>));
|
|
await settle();
|
|
expect(container.textContent).toContain("Pi provider account");
|
|
expect(container.textContent).not.toContain("incompatible");
|
|
expect(container.textContent).not.toContain("does not support");
|
|
const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
|
|
expect(trigger.getAttribute("title")).toBe("Pi provider account · API key · Personal · avery@example.test");
|
|
flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
|
|
await settle();
|
|
const choice = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(node => node.textContent?.includes("Pi provider account"));
|
|
expect(choice).toBeDefined();
|
|
expect(choice?.getAttribute("aria-disabled")).not.toBe("true");
|
|
});
|
|
|
|
it("keeps loaded connections usable when a refetch fails during an outage", async () => {
|
|
await mount([account()]);
|
|
expect(document.body.textContent).toContain("Reconnect account");
|
|
mocks.list.mockRejectedValue(new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }));
|
|
await client.invalidateQueries();
|
|
await settle();
|
|
expect(document.body.textContent).toContain("Reconnect account");
|
|
expect(document.body.textContent).not.toContain("Retry connections");
|
|
expect(document.body.textContent).not.toContain("Paperclip is restarting.");
|
|
expect(document.querySelector('[data-query-view="error"]')).toBeNull();
|
|
});
|
|
|
|
it("shows readable copy with a retry when connections cannot be loaded", async () => {
|
|
mocks.list.mockRejectedValueOnce(new ApiError("Request failed: 500", 500, { error: "internal_error" }));
|
|
await mount([account()]);
|
|
const alerts = Array.from(document.querySelectorAll('[role="alert"]')).map(node => node.textContent).join(" ");
|
|
expect(alerts).toContain("An unexpected error occurred");
|
|
expect(document.body.textContent).not.toContain("internal_error");
|
|
expect(document.body.textContent).not.toContain("Request failed: 500");
|
|
expect(document.body.textContent).not.toContain("Reconnect account");
|
|
await click("Retry connections");
|
|
await settle();
|
|
expect(mocks.list).toHaveBeenCalledTimes(2);
|
|
expect(document.body.textContent).toContain("Reconnect account");
|
|
expect(document.body.textContent).not.toContain("Retry connections");
|
|
});
|