mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
## 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
665 lines
28 KiB
TypeScript
665 lines
28 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { act, useEffect } from "react";
|
|
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 type { Company } from "@paperclipai/shared";
|
|
import { queryKeys } from "../lib/queryKeys";
|
|
import {
|
|
CompanyProvider,
|
|
resolveBootstrapCompanySelection,
|
|
shouldClearStoredCompanySelection,
|
|
useCompany,
|
|
} from "./CompanyContext";
|
|
|
|
const mockCompaniesApi = vi.hoisted(() => ({
|
|
list: vi.fn(),
|
|
create: vi.fn(),
|
|
detachInflightList: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../api/companies", () => ({
|
|
companiesApi: mockCompaniesApi,
|
|
}));
|
|
|
|
const mockAuthApi = vi.hoisted(() => ({
|
|
getSession: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../api/auth", () => ({
|
|
authApi: mockAuthApi,
|
|
}));
|
|
|
|
function sessionFor(userId: string) {
|
|
return {
|
|
session: { id: `session-${userId}`, userId },
|
|
user: { id: userId, name: "Example", email: `${userId}@example.com`, image: null },
|
|
};
|
|
}
|
|
|
|
const activeCompany = { id: "company-1" };
|
|
const secondActiveCompany = { id: "company-2" };
|
|
const archivedCompany = { id: "archived-company" };
|
|
|
|
function makeCompany(id: string): Company {
|
|
return {
|
|
id,
|
|
name: "Paperclip",
|
|
description: null,
|
|
status: "active",
|
|
pauseReason: null,
|
|
pausedAt: null,
|
|
issuePrefix: "PAP",
|
|
issueCounter: 1,
|
|
budgetMonthlyCents: 0,
|
|
spentMonthlyCents: 0,
|
|
defaultResponsibleUserId: null,
|
|
defaultDecisionOwnerUserId: null,
|
|
budgetOwnerUserId: null,
|
|
requireBoardApprovalForNewAgents: false,
|
|
interactionResolverGovernance: {},
|
|
feedbackDataSharingEnabled: false,
|
|
feedbackDataSharingConsentAt: null,
|
|
feedbackDataSharingConsentByUserId: null,
|
|
feedbackDataSharingTermsVersion: null,
|
|
logoAssetId: null,
|
|
logoUrl: null,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
};
|
|
}
|
|
|
|
async function flushReact() {
|
|
await act(async () => {
|
|
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
|
});
|
|
}
|
|
|
|
let captured: ReturnType<typeof useCompany> | null = null;
|
|
|
|
function Probe({ onSelectedCompanyId }: { onSelectedCompanyId: (companyId: string | null) => void }) {
|
|
const company = useCompany();
|
|
captured = company;
|
|
const { selectedCompanyId } = company;
|
|
useEffect(() => {
|
|
onSelectedCompanyId(selectedCompanyId);
|
|
}, [onSelectedCompanyId, selectedCompanyId]);
|
|
return <div data-selected-company-id={selectedCompanyId ?? ""} />;
|
|
}
|
|
|
|
describe("resolveBootstrapCompanySelection", () => {
|
|
it("boots the addressed company before the remembered company", () => {
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [activeCompany, secondActiveCompany], sidebarCompanies: [activeCompany, secondActiveCompany],
|
|
selectedCompanyId: null, storedCompanyId: activeCompany.id, routeCompanyId: secondActiveCompany.id,
|
|
})).toBe(secondActiveCompany.id);
|
|
});
|
|
|
|
it("retains a manual selection and does not bootstrap into an archived route", () => {
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [activeCompany, secondActiveCompany], sidebarCompanies: [activeCompany, secondActiveCompany],
|
|
selectedCompanyId: activeCompany.id, storedCompanyId: activeCompany.id, routeCompanyId: secondActiveCompany.id,
|
|
})).toBe(activeCompany.id);
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [activeCompany, archivedCompany], sidebarCompanies: [activeCompany],
|
|
selectedCompanyId: null, storedCompanyId: activeCompany.id, routeCompanyId: archivedCompany.id,
|
|
})).toBe(activeCompany.id);
|
|
});
|
|
|
|
it("does not expose a stale stored company id before companies load", () => {
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [],
|
|
sidebarCompanies: [],
|
|
selectedCompanyId: null,
|
|
storedCompanyId: "stale-company",
|
|
})).toBeNull();
|
|
});
|
|
|
|
it("replaces a stale stored company id with the first loaded company", () => {
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [activeCompany],
|
|
sidebarCompanies: [activeCompany],
|
|
selectedCompanyId: null,
|
|
storedCompanyId: "stale-company",
|
|
})).toBe("company-1");
|
|
});
|
|
|
|
it("keeps a valid selected company ahead of stored bootstrap state", () => {
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [activeCompany],
|
|
sidebarCompanies: [activeCompany],
|
|
selectedCompanyId: "company-1",
|
|
storedCompanyId: "stale-company",
|
|
})).toBe("company-1");
|
|
});
|
|
|
|
it("keeps a valid stored company id instead of falling back to the first company", () => {
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [activeCompany, secondActiveCompany],
|
|
sidebarCompanies: [activeCompany, secondActiveCompany],
|
|
selectedCompanyId: null,
|
|
storedCompanyId: "company-2",
|
|
})).toBe("company-2");
|
|
});
|
|
|
|
it("uses selectable sidebar companies before archived companies", () => {
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [archivedCompany, activeCompany],
|
|
sidebarCompanies: [activeCompany],
|
|
selectedCompanyId: null,
|
|
storedCompanyId: "archived-company",
|
|
})).toBe("company-1");
|
|
});
|
|
|
|
it("keeps an explicitly selected archived company that still exists", () => {
|
|
// The Layout route-sync selects the company the URL names, archived
|
|
// included. Vetoing that selection here re-selected an active company,
|
|
// the route-sync selected the archived one again, and the two effects
|
|
// ping-ponged until React threw #185 and unmounted the app.
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [archivedCompany, activeCompany],
|
|
sidebarCompanies: [activeCompany],
|
|
selectedCompanyId: "archived-company",
|
|
storedCompanyId: null,
|
|
})).toBe("archived-company");
|
|
});
|
|
|
|
it("still replaces a selected company that no longer exists at all", () => {
|
|
expect(resolveBootstrapCompanySelection({
|
|
companies: [activeCompany],
|
|
sidebarCompanies: [activeCompany],
|
|
selectedCompanyId: "deleted-company",
|
|
storedCompanyId: null,
|
|
})).toBe("company-1");
|
|
});
|
|
});
|
|
|
|
describe("shouldClearStoredCompanySelection", () => {
|
|
it("does not clear the stored company selection during an unauthorized company list response", () => {
|
|
expect(shouldClearStoredCompanySelection({
|
|
companies: [],
|
|
isLoading: false,
|
|
unauthorized: true,
|
|
errored: false,
|
|
})).toBe(false);
|
|
});
|
|
|
|
it("clears the stored company selection when an authorized company list is empty", () => {
|
|
expect(shouldClearStoredCompanySelection({
|
|
companies: [],
|
|
isLoading: false,
|
|
unauthorized: false,
|
|
errored: false,
|
|
})).toBe(true);
|
|
});
|
|
|
|
it("does not clear the stored company selection when the request failed", () => {
|
|
// `companiesListQueryOptions` sets `retry: false`, and a failure before any
|
|
// success leaves `data` undefined — which the provider defaults to an empty
|
|
// list. That is indistinguishable from "asked, and owns nothing", so
|
|
// without this a single failed request on a cold load would drop the
|
|
// customer's stored company.
|
|
expect(shouldClearStoredCompanySelection({
|
|
companies: [],
|
|
isLoading: false,
|
|
unauthorized: false,
|
|
errored: true,
|
|
})).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("CompanyProvider", () => {
|
|
let container: HTMLDivElement;
|
|
let root: Root;
|
|
let queryClient: QueryClient;
|
|
|
|
beforeEach(() => {
|
|
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
|
captured = null;
|
|
localStorage.clear();
|
|
container = document.createElement("div");
|
|
document.body.appendChild(container);
|
|
root = createRoot(container);
|
|
queryClient = new QueryClient({
|
|
defaultOptions: {
|
|
queries: { retry: false, retryDelay: 0 },
|
|
},
|
|
});
|
|
mockAuthApi.getSession.mockResolvedValue(null);
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
queryClient.clear();
|
|
container.remove();
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
it("seeds navigation from the session and preserves ordinary company invalidation", async () => {
|
|
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: 30_000 } });
|
|
mockAuthApi.getSession.mockResolvedValue({ ...sessionFor("one"), boardBootstrap: {
|
|
userId: "one", companies: [makeCompany("bootstrap-company")],
|
|
boardAccess: { userId: "one", isInstanceAdmin: false, companyIds: ["bootstrap-company"] },
|
|
} });
|
|
await act(() => root.render(<QueryClientProvider client={queryClient}><CompanyProvider>
|
|
<Probe onSelectedCompanyId={() => {}} />
|
|
</CompanyProvider></QueryClientProvider>));
|
|
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("bootstrap-company"));
|
|
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
|
expect(queryClient.getQueryData(queryKeys.companies.list("one"))).toMatchObject({ companies: [{ id: "bootstrap-company" }] });
|
|
mockCompaniesApi.list.mockResolvedValue([makeCompany("fresh-company")]);
|
|
await act(() => queryClient.invalidateQueries({ queryKey: queryKeys.companies.all }));
|
|
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("fresh-company"));
|
|
expect(mockCompaniesApi.list).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("never exposes the previous account's selection while a new bootstrap is ready", async () => {
|
|
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: 30_000 } });
|
|
const boot = (userId: string) => ({ ...sessionFor(userId), boardBootstrap: {
|
|
userId, companies: [makeCompany(`company-${userId}`)],
|
|
boardAccess: { userId, isInstanceAdmin: false, companyIds: [`company-${userId}`] },
|
|
} });
|
|
mockAuthApi.getSession.mockResolvedValue(boot("one"));
|
|
const snapshots: Array<{ selected: string | null; company: string | undefined }> = [];
|
|
function AccountProbe() {
|
|
const current = useCompany();
|
|
snapshots.push({ selected: current.selectedCompanyId, company: current.companies[0]?.id });
|
|
return null;
|
|
}
|
|
await act(() => root.render(<QueryClientProvider client={queryClient}><CompanyProvider><AccountProbe /></CompanyProvider></QueryClientProvider>));
|
|
await vi.waitFor(() => expect(snapshots.at(-1)?.selected).toBe("company-one"));
|
|
await act(() => { queryClient.setQueryData(queryKeys.auth.session, boot("two")); });
|
|
await vi.waitFor(() => expect(snapshots.at(-1)?.selected).toBe("company-two"));
|
|
expect(snapshots.filter(value => value.company === "company-two").some(value => value.selected === "company-one")).toBe(false);
|
|
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("replaces a returning account's cached companies with its revoked session snapshot once", async () => {
|
|
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } });
|
|
const boot = (userId: string, ids: string[]) => ({ ...sessionFor(userId), boardBootstrap: {
|
|
userId, companies: ids.map(makeCompany),
|
|
boardAccess: { userId, isInstanceAdmin: false, companyIds: ids },
|
|
} });
|
|
const seen: Array<{ selected: string | null; companies: string[] }> = [];
|
|
function AccountProbe() {
|
|
const current = useCompany();
|
|
seen.push({ selected: current.selectedCompanyId, companies: current.companies.map(company => company.id) });
|
|
return null;
|
|
}
|
|
mockAuthApi.getSession.mockResolvedValue(boot("one", ["revoked-company"]));
|
|
await act(() => root.render(<QueryClientProvider client={queryClient}><CompanyProvider><AccountProbe /></CompanyProvider></QueryClientProvider>));
|
|
await vi.waitFor(() => expect(seen.at(-1)?.selected).toBe("revoked-company"));
|
|
await act(() => { queryClient.setQueryData(queryKeys.auth.session, boot("two", ["company-two"])); });
|
|
await vi.waitFor(() => expect(seen.at(-1)?.selected).toBe("company-two"));
|
|
const returningAt = seen.length;
|
|
await act(() => { queryClient.setQueryData(queryKeys.auth.session, boot("one", [])); });
|
|
await vi.waitFor(() => expect(seen.at(-1)).toEqual({ selected: null, companies: [] }));
|
|
expect(seen.slice(returningAt).some(value => value.companies.includes("revoked-company"))).toBe(false);
|
|
expect(queryClient.getQueryData(queryKeys.companies.list("one"))).toEqual({ companies: [], unauthorized: false });
|
|
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
|
|
|
// The session seed must not overwrite a later authoritative read.
|
|
mockCompaniesApi.list.mockResolvedValue([makeCompany("new-membership")]);
|
|
await act(() => queryClient.invalidateQueries({ queryKey: queryKeys.companies.all }));
|
|
await vi.waitFor(() => expect(seen.at(-1)?.selected).toBe("new-membership"));
|
|
expect(mockCompaniesApi.list).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("reseeds a collected bootstrap query and restores ordinary reads after remount", async () => {
|
|
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: Infinity, gcTime: 0 } });
|
|
const bootstrap = {
|
|
userId: "one", companies: [makeCompany("bootstrap-company")],
|
|
boardAccess: { userId: "one", isInstanceAdmin: false, companyIds: ["bootstrap-company"] },
|
|
};
|
|
mockAuthApi.getSession.mockResolvedValue({ ...sessionFor("one"), boardBootstrap: bootstrap });
|
|
const render = (mounted: boolean) => root.render(<QueryClientProvider client={queryClient}>
|
|
{mounted ? <CompanyProvider><Probe onSelectedCompanyId={() => {}} /></CompanyProvider> : null}
|
|
</QueryClientProvider>);
|
|
await act(() => render(true));
|
|
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("bootstrap-company"));
|
|
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
|
await act(() => render(false));
|
|
await vi.waitFor(() => expect(queryClient.getQueryState(queryKeys.companies.list("one"))).toBeUndefined());
|
|
captured = null;
|
|
await act(() => render(true));
|
|
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("bootstrap-company"));
|
|
|
|
mockCompaniesApi.list.mockResolvedValue([makeCompany("ordinary-reader-company")]);
|
|
await act(() => queryClient.invalidateQueries({ queryKey: queryKeys.companies.all }));
|
|
await vi.waitFor(() => expect(mockCompaniesApi.list).toHaveBeenCalledOnce());
|
|
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("ordinary-reader-company"));
|
|
expect(queryClient.getQueryData(queryKeys.companies.list("one"))).toMatchObject({ companies: [{ id: "ordinary-reader-company" }] });
|
|
});
|
|
|
|
it("publishes the URL company without first exposing the remembered company", async () => {
|
|
const previousUrl = window.location.href;
|
|
window.history.replaceState(null, "", "/TWO/issues");
|
|
localStorage.setItem("paperclip.selectedCompanyId", "company-1");
|
|
queryClient.setQueryData(queryKeys.auth.session, null);
|
|
queryClient.setQueryData(queryKeys.companies.list(null), {
|
|
companies: [{ ...makeCompany("company-1"), issuePrefix: "ONE" }, { ...makeCompany("company-2"), issuePrefix: "TWO" }],
|
|
unauthorized: false,
|
|
});
|
|
mockCompaniesApi.list.mockImplementation(() => new Promise(() => {}));
|
|
const seen: Array<string | null> = [];
|
|
try {
|
|
await act(async () => root.render(<QueryClientProvider client={queryClient}><CompanyProvider>
|
|
<Probe onSelectedCompanyId={id => seen.push(id)} />
|
|
</CompanyProvider></QueryClientProvider>));
|
|
expect(seen.filter(Boolean)).toEqual(["company-2"]);
|
|
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-2");
|
|
} finally {
|
|
window.history.replaceState(null, "", previousUrl);
|
|
}
|
|
});
|
|
|
|
it("keeps the stored company when the company request fails", async () => {
|
|
// The seam the predicate test above cannot reach: the provider defaults a
|
|
// failed request to an empty list, so the effect has to be told the
|
|
// request errored or it reads that as "asked, and owns nothing" and clears
|
|
// the customer's stored company.
|
|
localStorage.setItem("paperclip.selectedCompanyId", "company-a");
|
|
mockCompaniesApi.list.mockRejectedValue(new Error("companies unavailable"));
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<CompanyProvider>
|
|
<Probe onSelectedCompanyId={() => {}} />
|
|
</CompanyProvider>
|
|
</QueryClientProvider>,
|
|
);
|
|
});
|
|
await act(async () => {
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
});
|
|
|
|
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-a");
|
|
});
|
|
|
|
it("does not expose a stale stored company id before companies load", async () => {
|
|
localStorage.setItem("paperclip.selectedCompanyId", "stale-company");
|
|
mockCompaniesApi.list.mockImplementation(() => new Promise(() => {}));
|
|
const seen: Array<string | null> = [];
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<CompanyProvider>
|
|
<Probe onSelectedCompanyId={(companyId) => seen.push(companyId)} />
|
|
</CompanyProvider>
|
|
</QueryClientProvider>,
|
|
);
|
|
});
|
|
|
|
expect(seen).toEqual([null]);
|
|
});
|
|
|
|
it("replaces a stale stored company id with the first loaded company", async () => {
|
|
localStorage.setItem("paperclip.selectedCompanyId", "stale-company");
|
|
// Signed out, and *known* to be: the list is keyed by account, so it cannot
|
|
// resolve before the session does. Seeding the answer is how this test says
|
|
// the account lookup has already happened.
|
|
queryClient.setQueryData(queryKeys.auth.session, null);
|
|
queryClient.setQueryData(queryKeys.companies.list(null), {
|
|
companies: [makeCompany("company-1")],
|
|
unauthorized: false,
|
|
});
|
|
mockCompaniesApi.list.mockImplementation(() => new Promise(() => {}));
|
|
const seen: Array<string | null> = [];
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<CompanyProvider>
|
|
<Probe onSelectedCompanyId={(companyId) => seen.push(companyId)} />
|
|
</CompanyProvider>
|
|
</QueryClientProvider>,
|
|
);
|
|
});
|
|
|
|
expect(seen).toEqual([null, "company-1"]);
|
|
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-1");
|
|
});
|
|
|
|
// The `["companies"]` cache entry is shared app-wide and carries no account
|
|
// identity, so it survives a change of account in this tab. Cached data is
|
|
// served whether or not it is stale, so freshness cannot stand in for
|
|
// "belongs to the account signed in now".
|
|
describe("when the account changes in this tab", () => {
|
|
async function bootWithFirstAccount(seen: Array<string | null>) {
|
|
mockAuthApi.getSession.mockResolvedValue(sessionFor("user-1"));
|
|
queryClient.setQueryData(queryKeys.companies.list("user-1"), {
|
|
companies: [makeCompany("company-1")],
|
|
unauthorized: false,
|
|
});
|
|
mockCompaniesApi.list.mockImplementation(() => new Promise(() => {}));
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<CompanyProvider>
|
|
<Probe onSelectedCompanyId={(companyId) => seen.push(companyId)} />
|
|
</CompanyProvider>
|
|
</QueryClientProvider>,
|
|
);
|
|
});
|
|
await flushReact();
|
|
|
|
expect(seen).toEqual([null, "company-1"]);
|
|
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-1");
|
|
}
|
|
|
|
it("drops the previous account's selection and re-reads the list", async () => {
|
|
const seen: Array<string | null> = [];
|
|
await bootWithFirstAccount(seen);
|
|
|
|
let resolveSecondList: ((companies: Company[]) => void) | null = null;
|
|
mockCompaniesApi.list.mockImplementation(
|
|
() =>
|
|
new Promise<Company[]>((resolve) => {
|
|
resolveSecondList = resolve;
|
|
}),
|
|
);
|
|
|
|
await act(async () => {
|
|
queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2"));
|
|
});
|
|
await flushReact();
|
|
|
|
// Nothing from the previous account is exposed while the new list loads.
|
|
expect(seen).toEqual([null, "company-1", null]);
|
|
expect(queryClient.getQueryData(queryKeys.companies.list("user-2"))).toBeUndefined();
|
|
// The previous account's entry may still sit in the cache; keying by
|
|
// account is what makes that harmless, since nothing reads it now.
|
|
expect(queryClient.getQueryData(queryKeys.companies.list("user-1"))).toMatchObject({
|
|
companies: [{ id: "company-1" }],
|
|
});
|
|
expect(resolveSecondList).not.toBeNull();
|
|
// The replacement fetch must not be coalesced into a `/companies` request
|
|
// issued under the previous session.
|
|
expect(mockCompaniesApi.detachInflightList).toHaveBeenCalled();
|
|
|
|
await act(async () => {
|
|
resolveSecondList?.([makeCompany("company-2")]);
|
|
await Promise.resolve();
|
|
});
|
|
await flushReact();
|
|
|
|
expect(seen).toEqual([null, "company-1", null, "company-2"]);
|
|
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-2");
|
|
});
|
|
|
|
// The replacement fetch is the only thing standing between the account
|
|
// change and a usable app: the cache entry has already been removed, so a
|
|
// failure here leaves the tab with no list and no selection. It must not
|
|
// also leave it with no way out.
|
|
it("recovers the list when the replacement fetch fails and is retried", async () => {
|
|
const seen: Array<string | null> = [];
|
|
await bootWithFirstAccount(seen);
|
|
|
|
mockCompaniesApi.list.mockRejectedValue(new Error("network down"));
|
|
|
|
await act(async () => {
|
|
queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2"));
|
|
});
|
|
await flushReact();
|
|
// Past the bounded retries, so the failure has actually settled.
|
|
await vi.waitFor(() => {
|
|
expect(captured?.companyListUnavailable).toBe(true);
|
|
});
|
|
await flushReact();
|
|
|
|
// The previous account's company is gone and nothing took its place.
|
|
expect(seen).toEqual([null, "company-1", null]);
|
|
// Reported as unavailable, not as an account that owns nothing. Without
|
|
// this the switcher renders "No companies", which is a false claim.
|
|
expect(captured?.companyListUnavailable).toBe(true);
|
|
expect(captured?.companies).toEqual([]);
|
|
|
|
// The recovery path actually recovers.
|
|
mockCompaniesApi.list.mockResolvedValue([makeCompany("company-2")]);
|
|
await act(async () => {
|
|
await captured?.retryCompanies();
|
|
});
|
|
await flushReact();
|
|
|
|
expect(captured?.companyListUnavailable).toBe(false);
|
|
expect(seen).toEqual([null, "company-1", null, "company-2"]);
|
|
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-2");
|
|
});
|
|
|
|
// A transient blip must not need the customer to notice and click anything.
|
|
// Nothing configures a retry — the second attempt is the observer's own,
|
|
// issued when it rebinds to a fresh query after the removal above. This
|
|
// pins that, so the recovery affordance stays reserved for real outages
|
|
// rather than becoming the only way back from a one-off blip.
|
|
it("rides out a single failed replacement request without help", async () => {
|
|
const seen: Array<string | null> = [];
|
|
await bootWithFirstAccount(seen);
|
|
|
|
mockCompaniesApi.list
|
|
.mockRejectedValueOnce(new Error("blip"))
|
|
.mockResolvedValue([makeCompany("company-2")]);
|
|
|
|
await act(async () => {
|
|
queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2"));
|
|
});
|
|
await flushReact();
|
|
await vi.waitFor(() => {
|
|
expect(seen).toEqual([null, "company-1", null, "company-2"]);
|
|
});
|
|
await flushReact();
|
|
|
|
expect(captured?.companyListUnavailable).toBe(false);
|
|
});
|
|
|
|
// The failure flag must not outlive the failure. A later success — a focus
|
|
// refetch, an invalidation from anywhere — settles the question, including
|
|
// when the honest answer is an empty list. Otherwise an account that owns
|
|
// nothing reads as "couldn't load", behind a retry that cannot change it.
|
|
it("stops reporting the list as unavailable once any fetch succeeds", async () => {
|
|
const seen: Array<string | null> = [];
|
|
await bootWithFirstAccount(seen);
|
|
|
|
mockCompaniesApi.list.mockRejectedValue(new Error("network down"));
|
|
await act(async () => {
|
|
queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2"));
|
|
});
|
|
await flushReact();
|
|
await vi.waitFor(() => {
|
|
expect(captured?.companyListUnavailable).toBe(true);
|
|
});
|
|
await flushReact();
|
|
|
|
// This account genuinely owns no companies, and the request says so.
|
|
mockCompaniesApi.list.mockResolvedValue([]);
|
|
await act(async () => {
|
|
await queryClient.refetchQueries({ queryKey: queryKeys.companies.list("user-2") });
|
|
});
|
|
await flushReact();
|
|
|
|
expect(captured?.companies).toEqual([]);
|
|
expect(captured?.companyListUnavailable).toBe(false);
|
|
});
|
|
|
|
// The guarantee the account-keyed entry buys, stated directly: a list sitting
|
|
// in the cache for another account is not merely distrusted, it is not
|
|
// reachable. No gate, no freshness check, no refetch stands between the two —
|
|
// they are different entries.
|
|
it("cannot read another account's cached list at all", async () => {
|
|
const seen: Array<string | null> = [];
|
|
await bootWithFirstAccount(seen);
|
|
|
|
// user-2's list is slow. If the entries were shared, the cached user-1
|
|
// list would answer in the meantime — which is the whole bug.
|
|
mockCompaniesApi.list.mockImplementation(() => new Promise(() => {}));
|
|
|
|
await act(async () => {
|
|
queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2"));
|
|
});
|
|
await flushReact();
|
|
|
|
expect(captured?.companies).toEqual([]);
|
|
expect(captured?.selectedCompanyId).toBeNull();
|
|
expect(captured?.loading).toBe(true);
|
|
// Still cached, still keyed to whom it belongs, still unread.
|
|
expect(queryClient.getQueryData(queryKeys.companies.list("user-1"))).toMatchObject({
|
|
companies: [{ id: "company-1" }],
|
|
});
|
|
});
|
|
|
|
// A session request that failed answers nothing. Keying the list to
|
|
// `anonymous` on that basis would write an authenticated response — the
|
|
// request still carries the cookie — into the entry every signed-out reader
|
|
// trusts, which is the original bug rebuilt for anonymous.
|
|
//
|
|
// Cold cache on purpose: after a prior success React Query retains the old
|
|
// session `data` through a failed refetch, so the identity survives anyway
|
|
// and the bug does not show. It needs a session that never answered.
|
|
it("does not treat a never-answered session as a signed-out session", async () => {
|
|
mockAuthApi.getSession.mockRejectedValue(new Error("network down"));
|
|
localStorage.setItem("paperclip.selectedCompanyId", "company-1");
|
|
mockCompaniesApi.list.mockResolvedValue([makeCompany("company-1")]);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<CompanyProvider>
|
|
<Probe onSelectedCompanyId={() => undefined} />
|
|
</CompanyProvider>
|
|
</QueryClientProvider>,
|
|
);
|
|
});
|
|
await flushReact();
|
|
await flushReact();
|
|
|
|
// Nothing asked for a list it could not attribute, and nothing landed in
|
|
// the anonymous entry.
|
|
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
|
expect(queryClient.getQueryData(queryKeys.companies.list(null))).toBeUndefined();
|
|
// And the stored company survives: unavailable is not "owns nothing".
|
|
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-1");
|
|
});
|
|
|
|
it("leaves the selection alone when the same account is observed again", async () => {
|
|
const seen: Array<string | null> = [];
|
|
await bootWithFirstAccount(seen);
|
|
const listCallsAfterBoot = mockCompaniesApi.list.mock.calls.length;
|
|
|
|
// A session refetch returns an equal-but-new object for the same account.
|
|
await act(async () => {
|
|
queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-1"));
|
|
});
|
|
await flushReact();
|
|
|
|
expect(seen).toEqual([null, "company-1"]);
|
|
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-1");
|
|
expect(mockCompaniesApi.list.mock.calls.length).toBe(listCallsAfterBoot);
|
|
});
|
|
});
|
|
});
|