Files
PaperClipAI/ui/src/pages/McpConnect.test.tsx
T
a3313f6944 fix(ui): complete read recovery and enforce query error rendering (#18822)
## 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>
2026-11-04 14:07:18 -08:00

406 lines
25 KiB
TypeScript

// @vitest-environment jsdom
import type { ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { beforeEach, expect, it, vi } from "vitest";
import { api } from "../api/client";
import { McpConnectPage, McpDevicePage } from "./McpConnect";
const route = vi.hoisted(() => ({ id: "request-one", companyId: null as string | null, unavailable: false, canWrite: true, requestedWrite: true, requestedConfigure: false, agentConnection: false, requiresSignIn: false, clientName: "Assistant", clientOrigin: null as string | null, setupUrl: "https://my.paperclip.app/orgs/new", reverseCompanies: false, hideFirst: false }));
vi.mock("@/lib/router", () => ({
useParams: () => ({ id: route.id }),
Link: ({ children, to }: { children: ReactNode; to: string }) => <a href={to}>{children}</a>,
}));
vi.mock("@/components/CompanyPatternIcon", () => ({
CompanyPatternIcon: ({ companyName, logoUrl }: { companyName: string; logoUrl?: string | null }) => <img alt={`${companyName} logo`} src={logoUrl ?? undefined} />,
}));
vi.mock("../api/client", () => ({ api: {
get: vi.fn(async () => ({
id: route.id, clientName: route.clientName, clientOrigin: route.clientOrigin, redirectOrigin: "https://assistant.example.test",
requestedWrite: route.requestedWrite, requestedConfigure: route.requestedConfigure, agentConnection: route.agentConnection, offlineAccess: true, requiresSignIn: route.requiresSignIn, requestedCompanyId: route.companyId,
companies: route.unavailable ? [] : [
{ id: route.companyId ?? "company-one", name: "Acme Research", logoUrl: "/api/assets/acme-logo/content", canWrite: route.canWrite },
...(!route.companyId ? [{ id: "company-two", name: "Design Partners", logoUrl: null, canWrite: true }] : []),
].filter(item => !route.hideFirst || item.id !== "company-one").sort((a, b) => route.reverseCompanies ? b.id.localeCompare(a.id) : a.id.localeCompare(b.id)), setupUrl: route.setupUrl,
})),
post: vi.fn(() => new Promise(() => {})),
} }));
beforeEach(() => {
Object.assign(route, { id: "request-one", companyId: null, unavailable: false, canWrite: true, requestedWrite: true, requestedConfigure: false, agentConnection: false, requiresSignIn: false, clientName: "Assistant", clientOrigin: null, setupUrl: "https://my.paperclip.app/orgs/new", reverseCompanies: false, hideFirst: false });
vi.clearAllMocks();
});
function setup(device = false, agentPairingOnly = false) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
const render = () => flushSync(() => root.render(<QueryClientProvider client={client}>{device ? <McpDevicePage initialCode="MIST-YPED" /> : <McpConnectPage agentPairingOnly={agentPairingOnly} />}</QueryClientProvider>));
render();
return {
client, container, render,
connect: () => Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Connect organization")!,
checkbox: () => container.querySelector('[role="checkbox"]') as HTMLButtonElement,
cleanup: () => { flushSync(() => root.unmount()); container.remove(); client.clear(); },
};
}
it("lets a person correct an invalid device code without reloading", async () => {
vi.mocked(api.get).mockRejectedValueOnce(new Error("Invalid code"));
const page = setup(true);
try {
await vi.waitFor(() => expect(page.container.textContent).toContain("Invalid code"));
const edit = Array.from(page.container.querySelectorAll("button")).find(item => item.textContent === "Enter a different code")!;
flushSync(() => edit.click());
expect(page.container.querySelector<HTMLInputElement>("#device-code")?.value).toBe("MIST-YPED");
expect(page.container.querySelector("form")).not.toBeNull();
expect(api.post).not.toHaveBeenCalled();
} finally { page.cleanup(); }
});
it.each([false, true])("lets Dot use the operator pairing capability without signing into a board account (dedicated=%s)", async dedicated => {
Object.assign(route, { agentConnection: true, requiresSignIn: true });
vi.mocked(api.post).mockImplementationOnce(async () => ({ company: { id: "company-one", name: "Dot Test Drive" }, agent: { id: "agent-one", name: "Dot" }, permissions: "Assigned work only", accessDuration: "Ongoing until revoked", pairingExpiresAt: new Date(Date.now() + 60000).toISOString() }) as never);
const page = setup(false, dedicated);
try {
await vi.waitFor(() => expect(page.container.querySelector("#dot-pairing-code")).not.toBeNull());
const input = page.container.querySelector<HTMLInputElement>("#dot-pairing-code")!;
expect(input.type).toBe("password");
const connect = Array.from(page.container.querySelectorAll("button")).find(button => button.textContent === "Allow agent connection")!;
expect(connect.disabled).toBe(true);
flushSync(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "x".repeat(32));
input.dispatchEvent(new Event("input", { bubbles: true }));
});
await vi.waitFor(() => expect(page.container.textContent).toContain("Dot Test Drive"));
expect(page.container.textContent).toContain("Assigned work only");
expect(page.container.textContent).toContain("Ongoing until revoked");
expect(connect.disabled).toBe(false);
flushSync(() => connect.click());
await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith(`${dedicated ? "/dot-mcp" : "/mcp"}/requests/request-one/dot-pairing`, { pairingCode: "x".repeat(32) }));
} finally { page.cleanup(); }
});
it("keeps approval disabled while replacing a code and ignores an older preview response", async () => {
Object.assign(route, { agentConnection: true, requiresSignIn: true });
let resolveOld!: (value: unknown) => void;
let resolveCurrent!: (value: unknown) => void;
vi.mocked(api.post).mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; }) as never)
.mockImplementationOnce(() => new Promise(resolve => { resolveCurrent = resolve; }) as never);
const page = setup();
try {
await vi.waitFor(() => expect(page.container.querySelector("#dot-pairing-code")).not.toBeNull());
const input = page.container.querySelector<HTMLInputElement>("#dot-pairing-code")!;
const connect = Array.from(page.container.querySelectorAll("button")).find(button => button.textContent === "Allow agent connection")!;
const enter = (value: string) => flushSync(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
enter("x".repeat(32));
await vi.waitFor(() => expect(resolveOld).toBeTypeOf("function"));
enter("y".repeat(32));
expect(connect.disabled).toBe(true);
await vi.waitFor(() => expect(resolveCurrent).toBeTypeOf("function"));
resolveCurrent({ company: { id: "current", name: "Current company" }, agent: { id: "agent", name: "Dot" }, permissions: "Assigned work", accessDuration: "Until revoked" });
await vi.waitFor(() => expect(connect.disabled).toBe(false));
resolveOld({ company: { id: "old", name: "Old company" }, agent: { id: "other", name: "Other agent" }, permissions: "Other work", accessDuration: "Until revoked" });
await new Promise(resolve => setTimeout(resolve, 20));
expect(page.container.textContent).toContain("Current company");
expect(page.container.textContent).not.toContain("Old company");
enter("");
expect(connect.disabled).toBe(true);
expect(page.container.textContent).not.toContain("Current company");
} finally { page.cleanup(); }
});
it("does not offer Dot pairing-code approval on a personal connection", async () => {
const page = setup();
try {
await vi.waitFor(() => expect(page.container.querySelector("h1")).not.toBeNull());
expect(page.container.querySelector("#dot-pairing-code")).toBeNull();
} finally { page.cleanup(); }
});
it("identifies the receiving app and registered callback origin before approval", async () => {
route.companyId = "company-one";
route.clientName = "Claude";
route.clientOrigin = "https://claude.ai";
const page = setup();
try {
await vi.waitFor(() => expect(page.container.querySelector("h1")?.textContent).toBe("Connect Claude to Paperclip"));
expect(page.container.textContent).toContain("https://claude.ai");
expect(page.container.textContent).toContain("https://assistant.example.test");
expect(page.container.querySelector('img[src^="https://assistant.example.test"]')).toBeNull();
expect(page.container.textContent).not.toContain("Access for");
expect(page.container.querySelector('img[src="/brands/claude-color.svg"]')).not.toBeNull();
expect(page.container.querySelector('a[href="https://my.paperclip.app/orgs/new"]')).toBeNull();
expect(page.connect().disabled).toBe(false);
// Registration metadata is text, never an executable link or verified-app badge.
expect(page.container.querySelector('a[href="https://assistant.example.test"]')).toBeNull();
} finally { page.cleanup(); }
});
it("defaults eligible writes on and preserves opt-out across organization changes and refetch", async () => {
const page = setup();
try {
await vi.waitFor(() => expect(page.container.querySelector('input[type="radio"]')).not.toBeNull());
expect(page.connect().disabled).toBe(false);
expect((page.container.querySelector('input[value="company-one"]') as HTMLInputElement).checked).toBe(true);
expect(page.checkbox().getAttribute("aria-checked")).toBe("true");
expect(api.post).not.toHaveBeenCalled();
expect(page.container.querySelector("h1")?.textContent).toBe("Connect your assistant to Paperclip");
flushSync(() => page.checkbox().click());
flushSync(() => (page.container.querySelector('input[value="company-two"]') as HTMLInputElement).click());
expect(page.checkbox().getAttribute("aria-checked")).toBe("false");
flushSync(() => (page.container.querySelector('input[value="company-one"]') as HTMLInputElement).click());
expect(page.checkbox().getAttribute("aria-checked")).toBe("false");
await page.client.invalidateQueries({ queryKey: ["mcp-request", route.id] });
expect(page.checkbox().getAttribute("aria-checked")).toBe("false");
flushSync(() => page.connect().click());
await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith("/mcp/requests/request-one/consent", { decision: "approve", companyId: "company-one", allowWrites: false, allowConfiguration: false }));
route.id = "request-two";
page.render();
await vi.waitFor(() => expect(page.container.querySelector('input[type="radio"]')).not.toBeNull());
expect((page.container.querySelector('input[type="radio"]') as HTMLInputElement).checked).toBe(true);
expect(page.connect().disabled).toBe(false);
expect(page.checkbox().getAttribute("aria-checked")).toBe("true");
} finally { page.cleanup(); }
});
it("keeps hosted organization identity fixed and defaults each new request to eligible write access", async () => {
route.companyId = "company-one";
const page = setup();
try {
await vi.waitFor(() => expect(page.container.textContent).toContain("Acme Research"));
expect(page.container.querySelector('input[type="radio"]')).toBeNull();
expect(page.container.querySelector('img[alt="Acme Research logo"]')?.getAttribute("src")).toBe("/api/assets/acme-logo/content");
expect(page.checkbox().getAttribute("aria-checked")).toBe("true");
flushSync(() => page.checkbox().click());
expect(page.checkbox().getAttribute("aria-checked")).toBe("false");
route.id = "hosted-two";
route.companyId = "company-two";
page.render();
await vi.waitFor(() => expect(page.container.textContent).toContain("Acme Research"));
expect(page.checkbox().getAttribute("aria-checked")).toBe("true");
route.canWrite = false;
await page.client.invalidateQueries({ queryKey: ["mcp-request", route.id] });
await vi.waitFor(() => expect(page.checkbox().disabled).toBe(true));
expect(page.checkbox().getAttribute("aria-checked")).toBe("false");
// Losing membership never turns a fixed hosted organization into a picker.
route.unavailable = true;
await page.client.invalidateQueries({ queryKey: ["mcp-request", route.id] });
await vi.waitFor(() => expect(page.container.textContent).toContain("selected organization is no longer available"));
expect(page.container.querySelector('input[type="radio"]')).toBeNull();
expect(page.connect().disabled).toBe(true);
expect(Array.from(page.container.querySelectorAll("button")).find(item => item.textContent === "Cancel")!.disabled).toBe(false);
} finally { page.cleanup(); }
});
it.each([
{ requestedWrite: true, canWrite: true, allowWrites: true },
{ requestedWrite: true, canWrite: false, allowWrites: false },
{ requestedWrite: false, canWrite: true, allowWrites: false },
])("submits only allowed requested access: %j", async ({ requestedWrite, canWrite, allowWrites }) => {
Object.assign(route, { companyId: "company-one", requestedWrite, canWrite });
const page = setup();
try {
await vi.waitFor(() => expect(page.container.textContent).toContain("Acme Research"));
if (requestedWrite) {
expect(page.checkbox().getAttribute("aria-checked")).toBe(String(allowWrites));
expect(page.checkbox().disabled).toBe(!canWrite);
} else expect(page.checkbox()).toBeNull();
flushSync(() => page.connect().click());
await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith("/mcp/requests/request-one/consent", { decision: "approve", companyId: "company-one", allowWrites, allowConfiguration: false }));
} finally { page.cleanup(); }
});
it("pins the default organization across refetches and never falls back after it disappears", async () => {
const page = setup();
try {
await vi.waitFor(() => expect(page.container.querySelector<HTMLInputElement>('input[value="company-one"]')?.checked).toBe(true));
route.reverseCompanies = true;
await page.client.invalidateQueries({ queryKey: ["mcp-request", route.id] });
await vi.waitFor(() => expect(page.container.querySelector('input[type="radio"]')?.getAttribute("value")).toBe("company-two"));
expect(page.container.querySelector<HTMLInputElement>('input[value="company-one"]')?.checked).toBe(true);
route.hideFirst = true;
await page.client.invalidateQueries({ queryKey: ["mcp-request", route.id] });
await vi.waitFor(() => expect(page.connect().disabled).toBe(true));
expect(page.container.querySelector<HTMLInputElement>('input[value="company-two"]')?.checked).toBe(false);
expect(page.checkbox().getAttribute("aria-checked")).toBe("false");
expect(page.container.textContent).not.toContain("Create a hosted organization");
expect(api.post).not.toHaveBeenCalled();
} finally { page.cleanup(); }
});
it("denies without granting default work or configuration access", async () => {
route.requestedConfigure = true;
const page = setup();
try {
await vi.waitFor(() => expect(page.checkbox()?.getAttribute("aria-checked")).toBe("true"));
flushSync(() => Array.from(page.container.querySelectorAll("button")).find(button => button.textContent === "Cancel")!.click());
await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith("/mcp/requests/request-one/consent", { decision: "deny", companyId: "company-one", allowWrites: false, allowConfiguration: false }));
} finally { page.cleanup(); }
});
it.each([false, true])("explains Dot agent consent and requires an operator in both browser and device flows (device=%s)", async device => {
Object.assign(route, { companyId: "company-one", agentConnection: true, canWrite: false });
const page = setup(device);
const connect = () => Array.from(page.container.querySelectorAll("button")).find(button => button.textContent === "Connect Dot agent")!;
try {
await vi.waitFor(() => expect(page.container.textContent).toContain("Connect Dot as a Paperclip agent"));
expect(page.container.textContent).not.toContain("Read all of your Paperclip data");
expect(page.checkbox()).toBeNull();
expect(connect().disabled).toBe(true);
route.canWrite = true;
await page.client.invalidateQueries({ queryKey: [device ? "mcp-device" : "mcp-request", device ? "MIST-YPED" : route.id] });
await vi.waitFor(() => expect(connect().disabled).toBe(false));
flushSync(() => connect().click());
await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith(device ? "/mcp/device/consent" : "/mcp/requests/request-one/consent", {
decision: "approve", companyId: "company-one", allowWrites: false, allowConfiguration: false, ...(device ? { userCode: "MIST-YPED" } : {}),
}));
} finally { page.cleanup(); }
});
it("does not fetch client-selected favicons or trust names for branding", async () => {
route.clientName = "Claude";
route.clientOrigin = "https://unrecognized.example.test";
const page = setup();
try {
await vi.waitFor(() => expect(page.container.textContent).toContain(route.clientOrigin));
expect(page.container.textContent).toContain("https://assistant.example.test");
expect(page.container.querySelector('img[src^="https://"]')).toBeNull();
expect(page.container.querySelector('img[src="/brands/claude-color.svg"]')).toBeNull();
expect(api.post).not.toHaveBeenCalled();
} finally { page.cleanup(); }
});
it.each([
{ device: false, optOut: false },
{ device: false, optOut: true },
{ device: true, optOut: false },
{ device: true, optOut: true },
])("uses one write choice for requested work and configuration access: %j", async ({ device, optOut }) => {
route.requestedConfigure = true;
const page = setup(device);
try {
await vi.waitFor(() => expect(page.checkbox()?.getAttribute("aria-checked")).toBe("true"));
expect(page.container.querySelectorAll('[role="checkbox"]')).toHaveLength(1);
expect(page.container.textContent).toContain("Write all of your Paperclip data");
expect(page.container.textContent).not.toContain("Allow configuring");
if (optOut) flushSync(() => page.checkbox().click());
flushSync(() => page.connect().click());
await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith(
device ? "/mcp/device/consent" : "/mcp/requests/request-one/consent",
{ decision: "approve", companyId: "company-one", allowWrites: !optOut, allowConfiguration: !optOut, ...(device ? { userCode: "MIST-YPED" } : {}) },
));
} finally { page.cleanup(); }
});
it.each([
{ requestedWrite: false, canWrite: true, enabled: true },
{ requestedWrite: true, canWrite: false, enabled: false },
])("keeps one write choice for configuration-only requests and viewer restrictions: %j", async ({ requestedWrite, canWrite, enabled }) => {
Object.assign(route, { requestedWrite, requestedConfigure: true, canWrite });
const page = setup();
try {
await vi.waitFor(() => expect(page.checkbox()?.getAttribute("aria-checked")).toBe(String(enabled)));
expect(page.container.querySelectorAll('[role="checkbox"]')).toHaveLength(1);
expect(page.checkbox().disabled).toBe(!canWrite);
flushSync(() => page.connect().click());
await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ allowWrites: false, allowConfiguration: enabled })));
} finally { page.cleanup(); }
});
it("shows the fixed Grok agent and authorizing person before granting a Cursor client access", async () => {
Object.assign(route, { agentConnection: true, requiresSignIn: true, clientName: "Cursor", clientOrigin: "https://www.cursor.com" });
vi.mocked(api.post).mockImplementationOnce(async () => ({ providerKind: "grok_bot", authorizingPerson: "Test Operator",
company: { id: "company-one", name: "Acme Research" }, agent: { id: "agent-grok", name: "Night Shift" },
permissions: "Work as this agent. Execution requires a current task-bound session.", accessDuration: "Ongoing until revoked",
pairingExpiresAt: new Date(Date.now() + 60_000).toISOString() }) as never);
const page = setup(false, true);
try {
await vi.waitFor(() => expect(page.container.querySelector("#dot-pairing-code")).not.toBeNull());
const input = page.container.querySelector<HTMLInputElement>("#dot-pairing-code")!;
const connect = [...page.container.querySelectorAll("button")].find(button => button.textContent === "Allow agent connection")!;
expect(connect.disabled).toBe(true);
expect(page.container.textContent).not.toContain("Connect Dot");
flushSync(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "g".repeat(32));
input.dispatchEvent(new Event("input", { bubbles: true }));
});
await vi.waitFor(() => expect(page.container.textContent).toContain("Allow this connection to work as Night Shift in Acme Research."));
expect(page.container.textContent).toContain("Test Operator");
expect(page.container.textContent).toContain("current task-bound session");
expect(page.container.querySelector("h1")?.textContent).toBe("Connect Cursor to Paperclip");
expect(api.post).toHaveBeenCalledTimes(1);
expect(api.post).toHaveBeenCalledWith("/dot-mcp/requests/request-one/dot-pairing/preview", { pairingCode: "g".repeat(32) }, expect.objectContaining({ signal: expect.any(AbortSignal) }));
flushSync(() => connect.click());
await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith("/dot-mcp/requests/request-one/dot-pairing", { pairingCode: "g".repeat(32) }));
} finally { page.cleanup(); }
});
// --- Disconnect handling ---------------------------------------------------------
// The API client is mocked above, so build errors structurally; `classifyError` reads `status`.
const apiError = (message: string, status: number) => Object.assign(new Error(message), { name: "ApiError", status, body: { error: message } });
const unavailable = () => apiError("tenant_app_unavailable", 503);
it("shows readable copy without Retry when the request is gone, and keeps the device-code escape hatch", async () => {
vi.mocked(api.get).mockRejectedValueOnce(apiError("Connection request not found", 404));
const page = setup(true);
try {
await vi.waitFor(() => expect(page.container.querySelector('[data-query-view="error"]')).not.toBeNull());
const alert = page.container.querySelector('[data-query-view="error"]')!;
expect(alert.textContent).toContain("Connection request not found");
expect(alert.textContent).not.toContain("tenant_app_unavailable");
expect(alert.querySelector("button")).toBeNull();
expect(page.container.textContent).toContain("Start a new connection from your assistant.");
expect(Array.from(page.container.querySelectorAll("button")).some(item => item.textContent === "Enter a different code")).toBe(true);
} finally { page.cleanup(); }
});
it("keeps the loaded request on screen when a refetch fails transiently", async () => {
const page = setup();
try {
await vi.waitFor(() => expect(page.container.querySelector('input[type="radio"]')).not.toBeNull());
vi.mocked(api.get).mockRejectedValueOnce(unavailable());
await page.client.refetchQueries({ queryKey: ["mcp-request", route.id] });
await vi.waitFor(() => expect(page.client.getQueryState(["mcp-request", route.id])?.status).toBe("error"));
page.render();
expect(page.container.querySelector('input[type="radio"]')).not.toBeNull();
expect(page.container.querySelector('[data-query-view="error"]')).toBeNull();
expect(page.container.textContent).not.toContain("tenant_app_unavailable");
expect(page.connect().disabled).toBe(false);
} finally { page.cleanup(); }
});
it("explains a rejected pairing code in readable copy and clears it when the code changes", async () => {
Object.assign(route, { agentConnection: true, requiresSignIn: true });
vi.mocked(api.post).mockImplementationOnce(async () => { throw apiError("This pairing code has expired.", 400); });
const page = setup();
try {
await vi.waitFor(() => expect(page.container.querySelector("#dot-pairing-code")).not.toBeNull());
const input = page.container.querySelector<HTMLInputElement>("#dot-pairing-code")!;
const connect = Array.from(page.container.querySelectorAll("button")).find(button => button.textContent === "Allow agent connection")!;
const enter = (value: string) => flushSync(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
enter("x".repeat(32));
await vi.waitFor(() => expect(page.container.querySelector('[data-query-view="error"]')).not.toBeNull());
expect(page.container.querySelector('[data-query-view="error"]')?.textContent).toContain("This pairing code has expired.");
expect(connect.disabled).toBe(true);
vi.mocked(api.post).mockImplementationOnce(async () => ({ company: { id: "company-one", name: "Dot Test Drive" }, agent: { id: "agent-one", name: "Dot" }, permissions: "Assigned work only", accessDuration: "Ongoing until revoked" }) as never);
enter("y".repeat(32));
expect(page.container.querySelector('[data-query-view="error"]')).toBeNull();
await vi.waitFor(() => expect(page.container.textContent).toContain("Dot Test Drive"));
expect(connect.disabled).toBe(false);
} finally { page.cleanup(); }
});