mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 18:35:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Hosted Paperclip Cloud records browser sessions with PostHog session replay > - Replay masked all text and showed only an allowlist of chrome, so most replays showed only stars > - The team cannot see how people use the board, and the allowlist needed a review for each new label > - The owner decided to show text by default and mask only marked customer content, the way PostHog normally works > - This pull request flips the default, removes the allowlist, and marks every surface that can show connected-account content > - The benefit is readable replays, while Google user data and Slack data stay masked ## Linked Issues or Issue Description **Subsystem affected** Hosted Cloud browser analytics: PostHog session replay in the board UI (`ui/src/lib/analytics/`). **Problem or motivation** Replay masked every text node. Only sidebar items and opt-in components showed text. Replays were almost unreadable. Each new label needed an `analyticsChrome` opt-in and an allowlist review. **Proposed solution** Record text as it is. Mask text only inside `ph-mask` (customer content), `ph-no-capture` (secrets, blocked) and editable content. Add `ANALYTICS_MASK_CLASS` to every surface that can show connected-account content (Gmail, Calendar, Drive and Docs, Slack) or other free-form text from agents or customers. **Alternatives considered** Keep "mask all" and grow the allowlist. This needs a review for each label and still hides most of the board. ## What Changed - `privacy.ts`: `ANALYTICS_MASK_TEXT_SELECTOR` is now `.ph-mask, .ph-no-capture, [contenteditable]:not([contenteditable="false"])`. rrweb masks a text node only when its parent or an ancestor matches the selector. Removed `maskReplayText`, `isReplayTextRevealed`, `ANALYTICS_UNMASK_ATTRIBUTE` and `ANALYTICS_UNMASK_PROPS`. - `product-analytics.ts`: removed `maskTextFn`, so rrweb uses its default star masking. `maskAllInputs`, `blockClass`, `maskAttributeFn`, `mask_all_text` and `mask_all_element_attributes` do not change. - Removed the `analyticsChrome` prop from `Button`, `Label`, `TabsTrigger`, `EmptyState` and `SidebarNavItem`, and from all sidebar call sites. - Added `ANALYTICS_MASK_CLASS` to the content element (not the chrome) of these surfaces: - Link preview cards, task quicklook description, external object pills and rows, related-work titles. - Email message cards and email send intents. - Connected account names and email addresses (Browse, Connections, app detail headers, app sidebar, connection choice list, connection access and repair cards), GitHub login and repositories, Slack workspace names, chat channel and linked user labels. - Inbox and decision rows (subject and detail), obligation evidence, Needs You notes and receipts, decision options and result summaries, and the interaction card roots (questions, options, answers, tool action requests, suggested tasks). - Approval payloads, action card input and reason, recovery card headline, evidence and options, run ledger retry detail, interrupt handoff previews. - Run transcripts, run failure details and run events on the agent page. - Search result snippets, toast bodies, voice and call transcripts, case summary, files and fields, attachment previews, artifact previews (text, tables, patches and documents). - Replaced `unmask-allowlist.test.ts` with `replay-masking.test.tsx`. It checks that unmarked chrome records as it is, that each marker masks, that a rendered voice transcript and run transcript mask, that each surface above has the class, and that autocapture records no element text. Updated `privacy.test.ts`, `shared-chrome.test.tsx` and `product-analytics.test.ts`. - Updated `doc/cloud-browser-analytics.md`: new default, marker classes, masked surfaces, and residual risk. ## Verification - `pnpm exec vitest run src/lib/analytics` in `ui/`: 83 tests pass. - Vitest for the 48 test files next to the changed components: 994 tests pass. - `tsc --noEmit -p ui/tsconfig.json`: no new errors (only the existing generated Storybook catalog errors). - `pnpm verify` exits 2 because a doc is a global CI input. Required CI supplies the broad coverage. - Manual: I ran an isolated local instance with a Cloud-like browser analytics config. `PAPERCLIP_POSTHOG_HOST` pointed to a local capture server, not PostHog. I opened a task page in headless Chromium, hovered a GitHub pull request link, and decoded the captured `/s/` replay payloads: - Clear text: sidebar (`New task`, `Chat`, `Tasks`, `Inbox`, `More`), breadcrumb, task title `Quarterly launch checklist`, `REP-1`, the Connectors promo heading and button. - Masked (stars only): the markdown task body, the chat comment, the link preview card (pull request title, author, URL, status), and the company menu. - Marker strings in the body, comment and preview never appeared in clear text in any payload. - The page `<title>` (task title and company name) is in the replay head. This is accepted residual risk. ## Risks - Text that is not marked is now recorded. Task titles, agent names, project names, company names, routine names, artifact and document titles, and activity rows are visible in replays. The owner accepted this. An agent can copy email or Slack text into a task title. - A new surface that shows connected-account content without `ANALYTICS_MASK_CLASS` is recorded until somebody marks it. `replay-masking.test.tsx` and the doc list the marked surfaces. - The masking options in `posthog.init` take precedence over the PostHog project masking settings (posthog-js 1.450), so a dashboard change cannot unmask content. Keep the project settings empty to avoid a console warning. - Some masked areas also mask nearby fixed labels (for example the interaction card buttons). This is safe. - Analytics is off on self-hosted and local installs, so they see no change. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code execution in Claude Code. ## 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 either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [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 any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
415 lines
26 KiB
TypeScript
415 lines
26 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";
|
|
import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils";
|
|
|
|
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("blocks the device code being confirmed from session replay", async () => {
|
|
const page = setup(true);
|
|
try {
|
|
await vi.waitFor(() => expect(page.container.textContent).toContain("Confirm this matches the code shown by your assistant"));
|
|
expect(isBlockedFromReplay("MIST-YPED", page.container)).toBe(true);
|
|
} finally { page.cleanup(); }
|
|
});
|
|
|
|
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(); }
|
|
});
|