Files
PaperClipAI/ui/src/pages/apps/TailscaleConnector.test.tsx
T
Dotta 0731cd3afc perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Pull-request CI checks run on every commit before maintainers can
merge code
> - PR #22679 cut PR CI from 15–30+ minutes down toward 4.5–5.5 minutes
on 4-core runners
> - Remaining wall-clock bottlenecks sit in unsharded `workspaces-b`,
serial typecheck preparation, E2E server/UI startup, fixed Vitest worker
caps, and remaining soak and duplicated UI tests
> - This pull request adds Phase 2 optimizations across server soak
triage, typecheck DAG overlap, E2E fast boot and shard balance, dynamic
CPU-aware workers, pure-Node workspace link preflight, UI pruning, and
permanent test-budget enforcement
> - The benefit is ordinary feature PRs finish in ~3.1–3.8 minutes on
4-core runners and scale automatically to ~2.0–3.0 minutes on 8-core
runners while keeping core invariants and nightly coverage intact

## Linked Issues or Issue Description

Refs #22679

**Problem Statement**
After #22679 landed, several PR lanes still took 4.5–6 minutes on 4-core
runners (`general-workspaces-b` ran unsharded, `Typecheck + Release
Registry` waited on a serial server build before starting UI and
test-program checks, E2E shards paid full `cli onboard` + minified UI
build overhead, and Vitest worker counts did not scale with runner CPU
count).

**Proposed Solution**
Split `general-workspaces-b` across two duration-balanced shards,
overlap typecheck preparation tasks behind a shared runner-vendor node,
replace E2E `onboard` with a direct template-PG boot + unminified inline
UI build, scale Vitest/Playwright/Typecheck workers dynamically by CPU
and RAM, replace `tsx` in workspace-link preflight with pure Node, prune
redundant mocked UI tests and additional real-clock server soak suites
(still run on `master`, `release-verify`, `cloud-readiness`, and
`PAPERCLIP_CI_FULL=1`), and add a permanent test-budget policy check.

**Expected Benefit**
Brings ordinary PR CI wall-clock down to ~3.1–3.8 minutes on 4-core
runners (and ~2.0–3.0 minutes on 8-core runners) with automated
guardrails against future test-time regressions.

## What Changed

- **Server soak triage & permanent test-budget guardrail
(`scripts/ci/nightly-only-suites.json`, `rules/test-budget.mdc`,
`.greptile/files.json`, `scripts/check-test-budget.mjs`,
`scripts/check-test-budget.test.mjs`,
`.github/workflows/pr-trusted.yml`):** Expanded the PR-excluded
soak/heavy-integration manifest to 568 genuine heavy suites (preserving
100% of company isolation, authz, checkout, approval, budget,
activity-log, security, telemetry, and serialized suites on every PR)
and wired `node scripts/check-test-budget.mjs` into the `policy` job.
- **Typecheck DAG overlap & CPU/RAM scaling
(`scripts/ci-typecheck-lane.mjs`, `scripts/typecheck-test-programs.mjs`,
`scripts/__tests__/ci-typecheck-lane.test.mjs`,
`scripts/typecheck-test-programs.test.mjs`):** Moved `build server
without type checks` and `check server runtime assets` out of serial
`prepare` into parallel DAG nodes behind `prepare runner vendor`, added
`computeResourceProfile` scaling across 2/4/8-core runners, and added
missing UI/Runner consumer routing inputs (`packages/paperclip-runner/`
for `@paperclipai/ui`, `packages/adapter-utils/` for Runner test
programs).
- **E2E fast boot, dynamic workers & 8-shard rebalance
(`tests/e2e/start-e2e-server.ts`, `tests/e2e/playwright.config.ts`,
`scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Added direct throwaway
template-PG boot (`fsync=off`), unminified inline Vite fallback build,
dynamic parallel workers (`min(4, floor(cpus/2))`), empirical `1.5x`
parallel speedup weighting across 8 shards, targeted trims to slowest
E2E specs, and hashed workspace `package.json` manifests into the
`e2e-ui-dist-v2` cache key.
- **Dynamic Vitest workers, 2-shard `workspaces-b`, and pure-Node
preflight (`scripts/ci/vitest-workers.mjs`,
`scripts/ci/workspaces-b-shard.mjs`,
`scripts/ensure-workspace-package-links.mjs`,
`scripts/ci-dependency-cache.mjs`,
`packages/db/src/test-embedded-postgres.ts`,
`.github/ci-task-matrix.json`,
`.github/actions/setup-ci-dependencies/action.yml`, `package.json`):**
Scaled Vitest workers dynamically (`4→7` general, `3→5` serialized) with
`max_connections=300` before PostgreSQL start, split
`general-workspaces-b` into 2 duration-weighted shards
(backward-compatible unsharded for release workflows), replaced `tsx`
workspace-link preflight with pure Node (~29× faster), and parallelized
`ci-dependency-cache.mjs` child queries.
- **UI Vitest worker scaling, fake timers & E2E-duplicated suite pruning
(`ui/vitest.config.ts`, 4 `maps/` files, and UI test suites):** Scaled
UI `maxWorkers` dynamically, converted real-clock sleeps in kept suites
to fake timers, removed 34 E2E-duplicated mocked jsdom suites, and
updated corresponding `maps/` prose references.

## Verification

- `node --test .github/scripts/tests/ci-plan.test.mjs
.github/scripts/tests/ci-dependency-cache.test.mjs
.github/scripts/tests/pr-dependency-cache.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/__tests__/e2e-shard.test.mjs scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs`: **160/160 PASS**
- `node scripts/check-test-budget.mjs`: **PASS** (`568` nightly suites
validated)
- `node scripts/check-maps.mjs`: **PASS** (`35 areas, 192 capability
IDs`)
- `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter
@paperclipai/db typecheck`: **PASS**
- Live CI verification runs on the new `pr-trusted.yml@master` (from
#22679) with `profile-ci` enabled to export the full job/step/file
waterfall to Honeycomb `paperclip-ci`.

## Risks

- Medium CI scope: touches workflow matrix partitioning, E2E startup,
and test runners; does not change production app runtime behavior.
- All PR-demoted soak suites continue to execute on `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and
`PAPERCLIP_CI_FULL=1`.
- All new `policy` and `setup-ci-dependencies` commands keep
file-existence guards so reruns of older PR branches continue to work.

## Model Used

- Google Gemini (Antigravity swarm orchestrating specialized worker
agents with shell, file editing, and test execution tools) and Anthropic
Claude Opus (verification and optimization sub-agents).

## 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
2026-11-24 10:53:19 -06:00

235 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, describe, expect, it, vi } from "vitest";
import { TailscaleConnector, TailscaleConnectorCard } from "./TailscaleConnector";
import { ApiError } from "@/api/client";
import { shouldRetryRequest } from "@/lib/query-client";
import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
const fixture = vi.hoisted(() => ({ companyId: "company-1", search: "", navigate: vi.fn(), access: vi.fn(), list: vi.fn(), connect: vi.fn(), deviceLogin: vi.fn(), disconnect: vi.fn(), breadcrumbs: vi.fn() }));
vi.mock("@/api/access", () => ({ accessApi: { getCurrentBoardAccess: fixture.access } }));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: { list: fixture.list, connect: fixture.connect, deviceLogin: fixture.deviceLogin, disconnect: fixture.disconnect } }));
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: fixture.companyId }) }));
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: fixture.breadcrumbs }) }));
vi.mock("./AppLogo", () => ({ AppLogo: () => null }));
vi.mock("@/lib/router", () => ({ Link: ({ to, children, ...props }: { to: string; children: React.ReactNode }) => <a href={to} {...props}>{children}</a>, useSearchParams: () => [new URLSearchParams(fixture.search)] }));
vi.mock("@/lib/browserNavigation", () => ({ navigateTopLevel: (url: string) => fixture.navigate(url) }));
const connected = { id: "tailnet-1", companyId: "company-1", name: "Home tailnet", status: "connected" };
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
const render = () => flushSync(() => root.render(<QueryClientProvider client={client}><TailscaleConnector /></QueryClientProvider>));
async function settle() {
for (let i = 0; i < 6; i++) await new Promise(resolve => setTimeout(resolve, 0));
}
function button(label: string) {
const result = [...container.querySelectorAll("button")].find(element => element.textContent === label);
expect(result).toBeDefined();
return result!;
}
describe("Tailscale network connector", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(window, "open").mockReturnValue(null);
fixture.deviceLogin.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() + 600_000).toISOString() });
fixture.companyId = "company-1";
fixture.search = "";
window.sessionStorage.clear();
fixture.access.mockResolvedValue({ source: "session", isInstanceAdmin: true, companyIds: ["company-1", "company-2"] });
fixture.list.mockResolvedValue([connected]);
fixture.connect.mockImplementation(() => new Promise(() => {}));
fixture.disconnect.mockResolvedValue({ ...connected, status: "disconnected" });
container = document.createElement("div");document.body.append(container);
root = createRoot(container);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => { flushSync(() => root.unmount());client.clear();container.remove();vi.unstubAllGlobals(); });
it("does not offer setup or request tailnets to a company member without instance-admin rights", async () => {
fixture.access.mockResolvedValue({ source: "session", isInstanceAdmin: false, companyIds: ["company-1"] });
flushSync(() => root.render(<QueryClientProvider client={client}><TailscaleConnectorCard onNavigate={vi.fn()} /></QueryClientProvider>));
await settle();
expect(fixture.list).not.toHaveBeenCalled();
expect(container.querySelector("button")).toBeNull();
render();await settle();
expect(container.textContent).toContain("instance administrator");
expect(container.querySelector("button")).toBeNull();
expect(fixture.list).not.toHaveBeenCalled();
});
it("waits for management access before requesting network data", async () => {
fixture.access.mockImplementationOnce(() => new Promise(() => {}));
render();await settle();
expect(container.textContent).toContain("Checking Tailscale management access");
expect(fixture.list).not.toHaveBeenCalled();
expect(fixture.connect).not.toHaveBeenCalled();
});
it("allows a local implicit board to manage its network", async () => {
fixture.access.mockResolvedValue({ source: "local_implicit", isInstanceAdmin: false });
render();await settle();
expect(fixture.list).toHaveBeenCalledWith("company-1");
expect(button("Connect Tailscale Network").disabled).toBe(false);
});
it("reuses an approved tailnet and links to an ordinary SSH environment", async () => {
render();await settle();
expect(fixture.list).toHaveBeenCalledWith("company-1");
expect(container.textContent).toContain("Home tailnet");
expect(container.textContent).toContain("any harness supported");
expect(replayLeaks("Home tailnet", container)).toEqual({ rendered: true, recorded: false });
expect(container.textContent).not.toContain("Claude");
expect(container.querySelector('a[href="/company/settings/instance/environments/new?tailscale_connection=tailnet-1"]')?.textContent).toBe("Create SSH environment");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("starts device sign-in from Connectors only when the user clicks Connect", async () => {
render();await settle();
flushSync(() => button("Connect Tailscale Network").click());await settle();
expect(fixture.connect).toHaveBeenCalledWith("company-1", undefined);
expect(button("Connecting…").disabled).toBe(true);
});
it("reconnects the existing connection instead of creating another record", async () => {
fixture.list.mockResolvedValue([{ ...connected, status: "disconnected" }]);
render();await settle();
flushSync(() => button("Reconnect Home tailnet").click());await settle();
expect(fixture.connect).toHaveBeenCalledWith("company-1", "tailnet-1");
});
it("keeps the connector open and offers a sign-in link when popups are blocked", async () => {
fixture.connect.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() + 600_000).toISOString() });
render();await settle();
flushSync(() => button("Connect Tailscale Network").click());await settle();
expect(window.open).toHaveBeenCalledWith("about:blank", "_blank");
expect(fixture.navigate).not.toHaveBeenCalled();
expect(fixture.deviceLogin).toHaveBeenCalledWith("company-1", "tailnet-1");
expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')?.textContent).toBe("Continue to Tailscale");
expect(button("Cancel sign-in")).toBeDefined();
});
it("shows administrator approval separately from sign-in", async () => {
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
fixture.deviceLogin.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, needsApproval: true, expiresAt: new Date(Date.now() + 600_000).toISOString() });
render();await settle();
expect(container.textContent).toContain("Tailscale administrator");
expect(container.querySelector('a[href="https://login.tailscale.com/admin/machines"]')).not.toBeNull();
});
it("recovers a transient sign-in status failure using the shared retry policy", async () => {
client.setDefaultOptions({ queries: { retry: shouldRetryRequest, retryDelay: 0 } });
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
fixture.deviceLogin.mockRejectedValueOnce(new ApiError("Unavailable", 503, {}));
render();await settle();
expect(fixture.deviceLogin).toHaveBeenCalledTimes(2);
expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')).not.toBeNull();
expect(container.querySelector('[role="alert"]')).toBeNull();
});
it("does not automatically retry a denied sign-in status request", async () => {
client.setDefaultOptions({ queries: { retry: shouldRetryRequest, retryDelay: 0 } });
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
fixture.deviceLogin.mockRejectedValue(new ApiError("Forbidden", 403, {}));
render();await settle();
expect(fixture.deviceLogin).toHaveBeenCalledOnce();
expect(container.querySelector('[role="alert"]')).not.toBeNull();
expect(button("Check again")).toBeDefined();
});
it("shows the connected network when the server confirms enrollment", async () => {
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
fixture.deviceLogin.mockResolvedValue({ connection: connected, expiresAt: null });
render();await settle();
expect(container.textContent).toContain("Create SSH environment");
expect(container.textContent).not.toContain("Cancel sign-in");
});
it("does not open a late sign-in response after changing companies", async () => {
let complete!: (value: unknown) => void;
fixture.connect.mockImplementation(() => new Promise(resolve => { complete = resolve; }));
const assign = vi.fn();
vi.spyOn(window, "open").mockReturnValue({ opener: null, closed: false, location: { assign }, focus: vi.fn(), close: vi.fn() } as unknown as Window);
fixture.list.mockImplementation(async id => id === "company-1" ? [connected] : []);
render();await settle();
flushSync(() => button("Connect Tailscale Network").click());await settle();
fixture.companyId = "company-2";render();await settle();
complete({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() + 600_000).toISOString() });
await settle();
expect(assign).not.toHaveBeenCalled();
expect(container.textContent).not.toContain("Home tailnet");
});
it("stops polling and gives a recovery action when the sign-in deadline passes", async () => {
fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]);
fixture.deviceLogin.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() - 1).toISOString() });
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval"] });
try {
render();
for (let i = 0; i < 6; i++) {
await Promise.resolve();
await vi.advanceTimersByTimeAsync(1);
}
expect(container.textContent).toContain("Sign-in expired");
expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')).toBeNull();
await vi.advanceTimersByTimeAsync(2100);
expect(fixture.deviceLogin).toHaveBeenCalledOnce();
expect(button("Cancel sign-in")).toBeDefined();
} finally {
vi.useRealTimers();
}
});
it.each(["cancelled", "failed"])("explains %s consent and retries the same saved connection", async outcome => {
fixture.search = `tailscale_connection=tailnet-1&tailscale_error=${outcome}`;
fixture.list.mockResolvedValue([{ ...connected, status: "pending" }]);
render();await settle();
expect(container.querySelector('[role="alert"]')?.textContent).toContain(outcome === "cancelled" ? "was canceled" : "could not be completed");
flushSync(() => button("Try again").click());await settle();
expect(fixture.connect).toHaveBeenCalledExactlyOnceWith("company-1", "tailnet-1");
});
it("does not offer a saved-connection retry for a connection outside the current company", async () => {
fixture.search = "tailscale_connection=foreign-connection&tailscale_error=cancelled";
render();await settle();
expect([...container.querySelectorAll("button")].some(element => element.textContent === "Try again")).toBe(false);
expect(fixture.connect).not.toHaveBeenCalled();
});
it("does not display untrusted error text from the return URL", async () => {
fixture.search = new URLSearchParams({ tailscale_connection: "tailnet-1", tailscale_error: "untrusted-provider-error<script>" }).toString();
render();await settle();
expect(container.textContent).not.toContain("untrusted-provider-error");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("refreshes connector status after a deliberate disconnect", async () => {
fixture.list.mockResolvedValueOnce([connected]).mockResolvedValue([{ ...connected, status: "disconnected" }]);
render();await settle();
flushSync(() => button("Disconnect Home tailnet").click());await settle();
expect(fixture.disconnect).toHaveBeenCalledWith("company-1", "tailnet-1");
expect(container.textContent).toContain("Disconnected");
expect(container.textContent).not.toContain("Create SSH environment");
});
it("reports access failure without presenting a usable connection or starting sign-in", async () => {
fixture.list.mockRejectedValue(new ApiError("Instance admin access required", 403, { error: "forbidden" }));
render();await settle();
expect(container.querySelector('[role="alert"]')).not.toBeNull();
expect(button("Connect Tailscale Network").disabled).toBe(true);
expect(container.textContent).not.toContain("Home tailnet");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("does not retain another company's tailnets when the organization changes", async () => {
fixture.list.mockImplementation(async companyId => companyId === "company-1" ? [connected] : []);
render();await settle();
expect(container.textContent).toContain("Home tailnet");
fixture.companyId = "company-2";render();await settle();
expect(container.textContent).not.toContain("Home tailnet");
expect(fixture.list).toHaveBeenCalledWith("company-2");
});
});