mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-10 01:50:13 +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>
390 lines
14 KiB
TypeScript
390 lines
14 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { createElement } from "react";
|
|
import { flushSync } from "react-dom";
|
|
import { createRoot } from "react-dom/client";
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import type {
|
|
ToolCatalogEntry,
|
|
ToolConnection,
|
|
ToolProfileEntry,
|
|
ToolProfileSummary,
|
|
ToolProfileWithDetails,
|
|
} from "@paperclipai/shared";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
const navigate = vi.hoisted(() => vi.fn());
|
|
const setSearchParams = vi.hoisted(() => vi.fn());
|
|
const api = vi.hoisted(() => ({
|
|
getProfileNewTools: vi.fn(),
|
|
reviewProfileNewTools: vi.fn(),
|
|
updateProfile: vi.fn(),
|
|
duplicateProfile: vi.fn(),
|
|
deleteProfile: vi.fn(),
|
|
unbindProfile: vi.fn(),
|
|
}));
|
|
const profilesData = vi.hoisted(() => ({ current: {} as Record<string, unknown> }));
|
|
|
|
vi.mock("@/lib/router", () => ({
|
|
useNavigate: () => navigate,
|
|
useSearchParams: () => [new URLSearchParams(), setSearchParams],
|
|
Link: ({ to, children }: { to: string; children: unknown }) => createElement("a", { href: to }, children as never),
|
|
}));
|
|
vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ pushToast: vi.fn() }) }));
|
|
vi.mock("@/api/tools", () => ({ toolsApi: api }));
|
|
vi.mock("./useProfilesData", () => ({ useProfilesData: () => profilesData.current }));
|
|
|
|
import { ApiError } from "@/api/client";
|
|
import { ProfileDetail } from "./ProfileDetail";
|
|
|
|
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
function summary(partial: Partial<ToolProfileSummary> = {}): ToolProfileSummary {
|
|
return {
|
|
accessMode: "selected",
|
|
allowedToolCount: 1,
|
|
allowedApplicationCount: 1,
|
|
excludedToolCount: 0,
|
|
totalToolCount: 2,
|
|
assignmentCount: 1,
|
|
appliesToAgentCount: 1,
|
|
isCompanyDefault: false,
|
|
...partial,
|
|
};
|
|
}
|
|
|
|
function entry(partial: Partial<ToolProfileEntry>): ToolProfileEntry {
|
|
return {
|
|
id: partial.id ?? "entry-1",
|
|
companyId: "c1",
|
|
profileId: "p1",
|
|
selectorType: "application",
|
|
effect: "include",
|
|
applicationId: "app-gmail",
|
|
connectionId: null,
|
|
catalogEntryId: null,
|
|
toolName: null,
|
|
riskLevel: null,
|
|
conditions: null,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
...partial,
|
|
};
|
|
}
|
|
|
|
function profile(partial: Partial<ToolProfileWithDetails> & { id?: string; name?: string } = {}): ToolProfileWithDetails {
|
|
return {
|
|
id: partial.id ?? "p1",
|
|
companyId: "c1",
|
|
profileKey: "everyday",
|
|
name: partial.name ?? "Everyday work",
|
|
description: "Routine work tools.",
|
|
status: "active",
|
|
defaultAction: "deny",
|
|
newToolsReviewedAt: null,
|
|
metadata: null,
|
|
createdAt: new Date("2026-06-10T00:00:00Z"),
|
|
updatedAt: new Date("2026-06-11T00:00:00Z"),
|
|
entries: [entry({})],
|
|
bindings: [
|
|
{
|
|
id: "b1",
|
|
companyId: "c1",
|
|
profileId: "p1",
|
|
targetType: "agent",
|
|
targetId: "a1",
|
|
priority: 0,
|
|
metadata: null,
|
|
createdByAgentId: null,
|
|
createdByUserId: null,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
],
|
|
summary: summary(),
|
|
...partial,
|
|
} as ToolProfileWithDetails;
|
|
}
|
|
|
|
function tool(partial: Partial<ToolCatalogEntry>): ToolCatalogEntry {
|
|
return {
|
|
id: partial.id ?? "t1",
|
|
companyId: "c1",
|
|
applicationId: "app-gmail",
|
|
connectionId: "conn-gmail",
|
|
entryKind: "tool",
|
|
toolName: "gmail.read",
|
|
title: "Read mail",
|
|
description: null,
|
|
inputSchema: null,
|
|
outputSchema: null,
|
|
annotations: null,
|
|
riskLevel: "read",
|
|
isReadOnly: true,
|
|
isWrite: false,
|
|
isDestructive: false,
|
|
status: "active",
|
|
addedAt: new Date(),
|
|
version: null,
|
|
schemaHash: null,
|
|
firstSeenAt: new Date(),
|
|
lastSeenAt: new Date(),
|
|
reviewedAt: null,
|
|
reviewedByAgentId: null,
|
|
reviewedByUserId: null,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
...partial,
|
|
} as ToolCatalogEntry;
|
|
}
|
|
|
|
function newTool(partial: Record<string, unknown> = {}) {
|
|
return {
|
|
catalogEntryId: partial.catalogEntryId ?? "new-1",
|
|
applicationId: "app-gmail",
|
|
applicationName: "Gmail",
|
|
connectionId: "conn-gmail",
|
|
connectionName: "Gmail",
|
|
toolName: partial.toolName ?? "gmail.send",
|
|
title: partial.title ?? "Send mail",
|
|
description: partial.description ?? "Send a message from Gmail.",
|
|
capability: partial.capability ?? "write",
|
|
riskLevel: partial.riskLevel ?? "write",
|
|
addedAt: partial.addedAt ?? new Date("2026-05-28T00:00:00Z"),
|
|
firstSeenAt: partial.firstSeenAt ?? new Date("2026-05-28T00:00:00Z"),
|
|
};
|
|
}
|
|
|
|
function setData(profiles: ToolProfileWithDetails[], catalog: ToolCatalogEntry[] = [tool({})], connections: Partial<ToolConnection>[] = []) {
|
|
profilesData.current = {
|
|
profiles: { isLoading: false, isError: false, data: { profiles }, refetch: vi.fn() },
|
|
connections: { data: { connections: [{ id: "conn-gmail", name: "Gmail", status: "active", healthStatus: "ok", ...connections[0] }] } },
|
|
catalog,
|
|
maps: {
|
|
applicationsById: new Map([["app-gmail", "Gmail"]]),
|
|
connectionsById: new Map([["conn-gmail", "Gmail"]]),
|
|
agentsById: new Map([["a1", "Sage"]]),
|
|
projectsById: new Map(),
|
|
routinesById: new Map(),
|
|
},
|
|
};
|
|
}
|
|
|
|
function setNativeValue(el: HTMLInputElement | HTMLTextAreaElement, value: string) {
|
|
const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
|
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
|
|
setter?.call(el, value);
|
|
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
}
|
|
|
|
describe("ProfileDetail", () => {
|
|
let container: HTMLDivElement;
|
|
let root: ReturnType<typeof createRoot>;
|
|
|
|
beforeEach(() => {
|
|
container = document.createElement("div");
|
|
document.body.appendChild(container);
|
|
root = createRoot(container);
|
|
api.getProfileNewTools.mockResolvedValue({ profileId: "p1", reviewedAt: null, pendingCount: 0, tools: [] });
|
|
api.reviewProfileNewTools.mockResolvedValue({ reviewedAt: new Date(), allowedCount: 0, keptBlockedCount: 0, entriesCreated: [], reviewedCatalogEntryIds: [], profile: profile() });
|
|
api.updateProfile.mockResolvedValue(profile());
|
|
api.duplicateProfile.mockResolvedValue(profile({ id: "copy", name: "Copy" }));
|
|
api.deleteProfile.mockResolvedValue({ deleted: true });
|
|
});
|
|
|
|
afterEach(() => {
|
|
flushSync(() => root.unmount());
|
|
container.remove();
|
|
vi.clearAllMocks();
|
|
document.body.innerHTML = "";
|
|
});
|
|
|
|
async function render() {
|
|
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
flushSync(() => {
|
|
root.render(
|
|
<QueryClientProvider client={client}>
|
|
<ProfileDetail companyId="c1" profileId="p1" />
|
|
</QueryClientProvider>,
|
|
);
|
|
});
|
|
await Promise.resolve();
|
|
}
|
|
|
|
it("renders detail sections with resolved allowed tools and assignments", async () => {
|
|
setData([profile()]);
|
|
await render();
|
|
|
|
expect(container.textContent).toContain("Everyday work");
|
|
expect(container.textContent).toContain("What it allows");
|
|
expect(container.textContent).toContain("Read mail");
|
|
expect(container.textContent).toContain("added by rule: all Gmail");
|
|
expect(container.textContent).toContain("Who has it");
|
|
expect(container.textContent).toContain("Sage");
|
|
expect(container.textContent).toContain("New tools that appear later");
|
|
});
|
|
|
|
it("keeps the loaded profile visible when a refetch fails transiently", async () => {
|
|
setData([profile()]);
|
|
profilesData.current.profiles = {
|
|
...(profilesData.current.profiles as Record<string, unknown>),
|
|
status: "success",
|
|
fetchStatus: "idle",
|
|
error: new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }),
|
|
};
|
|
await render();
|
|
|
|
expect(container.textContent).toContain("Everyday work");
|
|
expect(container.textContent).toContain("What it allows");
|
|
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
|
|
expect(container.textContent).not.toContain("Paperclip is restarting.");
|
|
});
|
|
|
|
it("shows readable copy and a Retry button for a real error", async () => {
|
|
const refetch = vi.fn();
|
|
setData([]);
|
|
profilesData.current.profiles = {
|
|
isLoading: false,
|
|
status: "error",
|
|
fetchStatus: "idle",
|
|
data: undefined,
|
|
error: new ApiError("Boom", 500, { error: "Boom" }),
|
|
refetch,
|
|
};
|
|
await render();
|
|
|
|
expect(container.querySelector('[data-query-view="error"]')).not.toBeNull();
|
|
expect(container.textContent).toContain("Couldn't load the profile");
|
|
expect(container.textContent).not.toContain("Profile not found");
|
|
|
|
const retry = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Retry"));
|
|
expect(retry, "Retry button").toBeTruthy();
|
|
flushSync(() => {
|
|
retry?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
expect(refetch).toHaveBeenCalled();
|
|
});
|
|
|
|
it("shows degraded app rows and the 0-tools warning state", async () => {
|
|
setData([profile()], [tool({})], [
|
|
{ status: "disabled", healthStatus: "error" },
|
|
]);
|
|
await render();
|
|
|
|
expect(container.textContent).toContain("Gmail is disconnected");
|
|
expect(container.textContent).toContain("Reconnect");
|
|
});
|
|
|
|
it("shows the 0-tools and unassigned warning states", async () => {
|
|
setData([profile({ summary: summary({ allowedToolCount: 0, assignmentCount: 0, appliesToAgentCount: 0 }), entries: [], bindings: [] })], [tool({})]);
|
|
await render();
|
|
|
|
expect(container.textContent).toContain("allows 0 tools");
|
|
expect(container.textContent).toContain("Not assigned yet");
|
|
expect(container.textContent).toContain("Assign this profile before it changes access.");
|
|
});
|
|
|
|
it("shows pending new tools and submits per-tool review decisions", async () => {
|
|
const tools = [
|
|
newTool({ catalogEntryId: "new-send", toolName: "gmail.send", title: "Send mail" }),
|
|
newTool({ catalogEntryId: "new-label", toolName: "gmail.label", title: "Manage labels", capability: "write", riskLevel: "write" }),
|
|
newTool({ catalogEntryId: "new-delete", toolName: "gmail.delete", title: "Delete mail", capability: "destructive", riskLevel: "destructive" }),
|
|
];
|
|
api.getProfileNewTools.mockResolvedValue({ profileId: "p1", reviewedAt: null, pendingCount: 3, tools });
|
|
setData([profile({ newToolsPendingCount: 3 })]);
|
|
await render();
|
|
|
|
await Promise.resolve();
|
|
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
|
expect(container.textContent).toContain("Gmail added 3 new tools since your last review");
|
|
|
|
const review = [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Review");
|
|
flushSync(() => {
|
|
review?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
await Promise.resolve();
|
|
|
|
expect(document.body.textContent).toContain("Send mail");
|
|
expect(document.body.textContent).toContain("Keep blocked");
|
|
|
|
const firstAllow = document.body.querySelector('input[name="review-new-send"][type="radio"]') as HTMLInputElement;
|
|
flushSync(() => {
|
|
firstAllow.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
await Promise.resolve();
|
|
|
|
const submit = [...document.body.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Submit review");
|
|
flushSync(() => {
|
|
submit?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
await Promise.resolve();
|
|
|
|
expect(api.reviewProfileNewTools).toHaveBeenCalledWith("p1", {
|
|
decisions: [
|
|
{ catalogEntryId: "new-send", decision: "allow" },
|
|
{ catalogEntryId: "new-label", decision: "keep_blocked" },
|
|
{ catalogEntryId: "new-delete", decision: "keep_blocked" },
|
|
],
|
|
});
|
|
});
|
|
|
|
it("shows recently auto-added tools in the source column", async () => {
|
|
const recent = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000);
|
|
setData([profile({ defaultAction: "allow" })], [tool({ addedAt: recent, firstSeenAt: recent })]);
|
|
await render();
|
|
|
|
expect(container.textContent).toContain("added automatically");
|
|
});
|
|
|
|
it("validates duplicate profile names in the edit dialog", async () => {
|
|
setData([profile(), profile({ id: "p2", name: "Existing name" })]);
|
|
await render();
|
|
|
|
const edit = [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Edit");
|
|
flushSync(() => {
|
|
edit?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
await Promise.resolve();
|
|
const input = document.body.querySelector("#edit-profile-name") as HTMLInputElement;
|
|
flushSync(() => {
|
|
setNativeValue(input, "Existing name");
|
|
});
|
|
await Promise.resolve();
|
|
|
|
expect(document.body.textContent).toContain("Another profile already uses this name.");
|
|
});
|
|
|
|
it("shows archive and delete confirmation copy", async () => {
|
|
setData([profile({ summary: summary({ assignmentCount: 2, appliesToAgentCount: 2, isCompanyDefault: true }) })]);
|
|
await render();
|
|
|
|
const archive = [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Archive");
|
|
flushSync(() => {
|
|
archive?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
await Promise.resolve();
|
|
expect(document.body.textContent).toContain("This profile stops applying to 2 agents");
|
|
|
|
flushSync(() => {
|
|
document.body.querySelector('[role="dialog"] button')?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Escape" }));
|
|
});
|
|
await Promise.resolve();
|
|
});
|
|
|
|
it("blocks company-default delete from the detail dialog before the API call", async () => {
|
|
setData([profile({ summary: summary({ assignmentCount: 0, isCompanyDefault: true }) })]);
|
|
await render();
|
|
|
|
const deleteButton = [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Delete");
|
|
flushSync(() => {
|
|
deleteButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
});
|
|
await Promise.resolve();
|
|
|
|
expect(document.body.textContent).toContain("Reassign the organization default to another profile before deleting it.");
|
|
const dialogDelete = [...document.body.querySelectorAll('[role="dialog"] button')].find((b) => b.textContent?.trim() === "Delete") as HTMLButtonElement | undefined;
|
|
expect(dialogDelete?.disabled).toBe(true);
|
|
expect(api.deleteProfile).not.toHaveBeenCalled();
|
|
});
|
|
});
|