From 490d97bf1e11a9d711e221990c0a5be114b327c1 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:29:56 -0600 Subject: [PATCH] test(perf): guard Mine against waiting on the company-wide workspace list (#20419) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > Follows #20388 (merged as 50df9a19b9). This PR adds only test and fixture files. It changes no product code. ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Mine inbox (`/:companyPrefix/issues?view=mine`) is the first page an operator opens > - On an instance with 8,758 execution workspaces, Mine took about 13 s to show rows. It loaded every workspace in the company (`execution-workspaces?summary=true`, 2.5 MB) and kept all rows hidden until that read finished > - #20388 fixes this. Mine now reads only the workspaces its rows reference (`ids` filter), and waits for them only when the rows show workspace data > - The collections perf suite did not catch the regression. Its fixture has almost no execution workspaces, and it has no check on the workspace read > - This pull request adds a workspace-scale fixture and a spec that fails if Mine requests the company-wide list again, or if Mine rows wait for the workspace read when no workspace data is shown > - The benefit is a regression guard that fails on `master` before #20388 and passes with it ## Linked Issues or Issue Description Refs #20388 **What happened?** The collections perf suite could not detect that Mine waited on a company-wide execution-workspace list. The fixture had no workspace scale, and no assertion covered the workspace request or the reveal gate. **What did you expect?** A browser check that fails when Mine requests the unfiltered workspace list, or when Mine rows wait on a workspace read that does not change what the rows show. **Steps to reproduce** Run `tests/perf/collections` against `master` UI assets on a company with thousands of execution workspaces. All existing checks pass, although Mine requests the full list and holds rows for it. ## What Changed - `tests/perf/collections/workspace-fixture.ts` (new): a retained company with 6,000 execution workspaces. 4,000 of them belong to finished tasks. 12 Mine tasks each run in their own isolated workspace. Mine tasks come from the API. The API cannot create execution workspaces, so the bulk rows go to the disposable instance database directly (same pattern as `tests/e2e/legacy-failure-continuation.spec.ts`). The database URL comes from `PAPERCLIP_CONFIG` or `PAPERCLIP_COLLECTION_PERF_DATABASE_URL`, loopback only. The fixture uses the existing retain/404 rule. - `tests/perf/collections/mine-workspaces.spec.ts` (new), cold load of `/:prefix/issues?view=mine`: 1. Mine requests only `ids`-filtered `execution-workspaces?summary=true` reads, and only for the workspaces its rows reference. No unfiltered read. 2. With the Workspace column off and no workspace grouping, all Mine rows appear while every workspace read is held. 3. With the Workspace column on, each row shows its isolated workspace name. 4. Records cold time from navigation start to the first Mine row (two frames after mount, as in `measure-mine-context.ts`) over at least 5 runs. It attaches the samples and the median. It is not a budget. - `tests/perf/collections/README.md`: documents the fixture, its database prerequisite, and the checks. ## Verification Local disposable instance (`onboard --yes --run`, `local_trusted`, embedded PostgreSQL, `PAPERCLIP_UI_DEV_MIDDLEWARE=false`, production UI builds). Both arms used the same server (this branch) and the same database. Only the UI assets changed, so this is a UI comparison. The `master` UI does not send `ids`. ```sh PAPERCLIP_CONFIG=/config.json PAPERCLIP_COLLECTION_PERF_BASE_URL=http://127.0.0.1:3219 \ pnpm exec playwright test --config tests/perf/collections/playwright.config.ts mine-workspaces.spec.ts ``` **Fails on `origin/master` UI at 5858cef8f9 (before #20388 merged):** ``` ✘ 1 Mine reads only the execution workspaces its rows reference Error: Mine requested the company-wide list of 6000 workspaces + "/api/companies//execution-workspaces?summary=true", ✘ 2 Mine rows appear while workspace reads are pending when no workspace data is shown Error: Mine rows waited for the workspace read expect(locator).toBeVisible() failed … timeout 15000ms ✓ 3 the Workspace column resolves each Mine row's isolated workspace name ✓ 4 records cold time to Mine rows 2 failed, 2 passed ``` **Passes on this branch (#20388 UI):** ``` ✓ 1 Mine reads only the execution workspaces its rows reference ✓ 2 Mine rows appear while workspace reads are pending when no workspace data is shown ✓ 3 the Workspace column resolves each Mine row's isolated workspace name ✓ 4 records cold time to Mine rows 4 passed ``` **Cold time to first Mine row, 5 runs each, fresh browser contexts, 1440×900:** | Scenario | `master` UI median (samples) | This branch median (samples) | | --- | --- | --- | | Native loopback, no interception | 472 ms (461, 466, 472, 483, 523) | 425 ms (406, 417, 425, 429, 998) | | Workspace reads delayed 3,000 ms (diagnostic, intercepted) | 3,523 ms (3488–3539) | 546 ms (471–1754) | On this fixture the unfiltered list is 1.55 MB but returns in about 40 ms on loopback. The filtered read is 3.2 KB in about 4 ms. So native loopback timing does not separate the arms. The delayed scenario shows the dependency: on `master`, rows wait for the full workspace delay. No hard time budget is added. The suite has no CI timing convention, and the structural assertions are the guard. **CI status of this suite:** `tests/perf/collections` runs in no GitHub workflow. It is a manual suite against a disposable local instance (see its README). The new spec runs the same way as the existing specs: same directory, same `playwright.config.ts`, no new config. The Vitest checks in #20388 (`ui/src/pages/Inbox.test.tsx`) remain the CI guard for the reveal rule. **Full collections suite on this branch:** 19 passed, 5 failed. The 5 failures are existing cases (`startup-regressions`: two partial-source cases and two 429 cases; `startup`: "Coordinator Inbox retains aggregate Mine reads when Streamlined UI is disabled"). They fail the same way on the `origin/master` UI with the new spec excluded. This PR does not cause them. `pnpm verify`: exit 2 (README is a global CI input), so required CI supplies broad coverage. `tsc -p tests/tsconfig.playwright.json` passes (the CI typecheck project that covers `tests/perf`). ## Risks - Low risk. Test and fixture files only. - The fixture writes rows straight to the database. It needs `PAPERCLIP_CONFIG` or `PAPERCLIP_COLLECTION_PERF_DATABASE_URL`, and refuses non-loopback databases. Without either variable the spec fails with a clear message. - The timing case changes the real `enableIsolatedWorkspaces` instance setting and restores it in `finally`. - Seeding 6,000 workspaces takes about 10 s on the first run. Later runs reuse the retained fixture. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, Playwright runs). Extended reasoning on. ## 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 --- tests/perf/collections/README.md | 20 +++ .../perf/collections/mine-workspaces.spec.ts | 143 ++++++++++++++++++ tests/perf/collections/workspace-fixture.ts | 132 ++++++++++++++++ 3 files changed, 295 insertions(+) create mode 100644 tests/perf/collections/mine-workspaces.spec.ts create mode 100644 tests/perf/collections/workspace-fixture.ts diff --git a/tests/perf/collections/README.md b/tests/perf/collections/README.md index 1b675f08be7..25a2e875003 100644 --- a/tests/perf/collections/README.md +++ b/tests/perf/collections/README.md @@ -41,6 +41,26 @@ They allow 45 seconds for its bounded retry window before exercising manual Retry. Other cases keep the normal short assertion timeout. Timing samples do not accelerate the browser clock. +`mine-workspaces.spec.ts` guards Mine against waiting on a company-wide +execution-workspace list. Its fixture (`workspace-fixture.ts`) adds a company +with 6,000 execution workspaces, 4,000 of them created for finished tasks, and +12 Mine tasks that each run in their own isolated workspace. The API cannot +create execution workspaces, so this fixture writes those rows to the instance +database. Set `PAPERCLIP_CONFIG` to the disposable instance's `config.json` +(embedded PostgreSQL), or `PAPERCLIP_COLLECTION_PERF_DATABASE_URL` to its +loopback database. The fixture is retained in +`test-results/collections/workspace-fixture.json` with the same 404 rule as the +main fixture. The spec routes isolated workspaces on for its own pages. It +checks that Mine requests only `ids`-filtered workspace summaries for the +workspaces its rows reference, that rows appear while those reads are held when +neither the Workspace column nor workspace grouping is active, and that the +Workspace column still shows each row's workspace name. Its timing case turns on +the real isolated-workspaces setting, restores it, and records cold time from +navigation start to the first Mine row (two frames after mount) over +`PAPERCLIP_COLLECTION_PERF_TIMING_RUNS` runs (default and minimum 5). It records +a native scenario without request interception and a separate diagnostic scenario that delays +workspace reads by 3 seconds. The timings are attached evidence, not budgets. + Run these focused browser checks before the full collection suite: ```sh diff --git a/tests/perf/collections/mine-workspaces.spec.ts b/tests/perf/collections/mine-workspaces.spec.ts new file mode 100644 index 00000000000..8b9b6709e01 --- /dev/null +++ b/tests/perf/collections/mine-workspaces.spec.ts @@ -0,0 +1,143 @@ +import { expect, test, type Page } from "@playwright/test"; +import { isolatedWorkspaceSettings, workspaceFixture, WORKSPACE_COUNT, type WorkspaceFixture } from "./workspace-fixture"; + +// Mine must not wait on a company-wide execution-workspace list. With thousands +// of workspaces that list was megabytes and seconds long, and Mine held every +// row hidden until it finished. These checks run against a company with +// WORKSPACE_COUNT workspaces and Mine rows that each reference their own. +let fixture: WorkspaceFixture; +test.beforeAll(async ({ request }) => { + test.setTimeout(300_000); + fixture = await workspaceFixture(request); +}); + +const workspaceListPath = () => `/api/companies/${fixture.company.id}/execution-workspaces`; +const minePage = () => `/${fixture.company.issuePrefix}/issues?view=mine`; +const mineLink = (page: Page, identifier: string) => page.locator(`[data-inbox-issue-link][href$="/${identifier}"]`); +const mineRow = (page: Page, identifier: string) => page.locator("[data-inbox-item]", { has: mineLink(page, identifier) }); +const showWorkspaceColumn = (page: Page) => page.addInitScript(() => { + localStorage.setItem("paperclip:inbox:issue-columns", JSON.stringify(["status", "id", "workspace", "updated"])); +}); +function recordWorkspaceReads(page: Page) { + const reads: URL[] = []; + page.on("request", request => { + const url = new URL(request.url()); + if (url.pathname === workspaceListPath()) reads.push(url); + }); + return reads; +} +function holdWorkspaceReads(page: Page) { + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + let pending = 0; + const ready = page.route(url => url.pathname === workspaceListPath(), async route => { + pending += 1; + await held; + await route.continue(); + }); + return { ready, release, pending: () => pending }; +} + +test("Mine reads only the execution workspaces its rows reference", async ({ page }) => { + await isolatedWorkspaceSettings(page); + const reads = recordWorkspaceReads(page); + await page.goto(minePage()); + for (const row of fixture.mine) await expect(mineLink(page, row.identifier)).toBeVisible(); + await expect.poll(() => reads.length).toBeGreaterThan(0); + // Late reads (background refetches) must follow the same rule. + await page.waitForTimeout(1_000); + const unfiltered = reads.filter(url => !url.searchParams.has("ids")).map(url => `${url.pathname}${url.search}`); + expect(unfiltered, `Mine requested the company-wide list of ${WORKSPACE_COUNT} workspaces`).toEqual([]); + const expected = fixture.mine.map(row => row.workspaceId).sort(); + expect([...new Set(reads.flatMap(url => url.searchParams.get("ids")!.split(",")))].sort()).toEqual(expected); + for (const url of reads) { + expect(url.searchParams.get("summary")).toBe("true"); + expect(url.searchParams.get("ids")!.split(",").every(id => expected.includes(id))).toBe(true); + } +}); + +test("Mine rows appear while workspace reads are pending when no workspace data is shown", async ({ page }) => { + await isolatedWorkspaceSettings(page); + const hold = holdWorkspaceReads(page); + await hold.ready; + try { + await page.goto(minePage()); + for (const row of fixture.mine) { + await expect(mineLink(page, row.identifier), "Mine rows waited for the workspace read").toBeVisible({ timeout: 15_000 }); + } + expect(hold.pending()).toBeGreaterThan(0); + } finally { hold.release(); } +}); + +test("the Workspace column resolves each Mine row's isolated workspace name", async ({ page }) => { + await isolatedWorkspaceSettings(page); + await showWorkspaceColumn(page); + await page.goto(minePage()); + for (const row of fixture.mine) await expect(mineRow(page, row.identifier)).toContainText(row.workspaceName); +}); + +// Cold time to first Mine row, from navigation start (two frames after the +// first row mounts, as in measure-mine-context.ts), in fresh browser contexts +// with the real instance setting. The native scenario uses no request +// interception. The delayed scenario holds every workspace read for +// WORKSPACE_DELAY_MS and is diagnostic evidence only: it shows whether rows wait +// on that read. Neither is a budget; the structural checks above are the guard. +const WORKSPACE_DELAY_MS = 3_000; +type Sample = { timeToRowsMs: number; workspaceReads: string[] }; +const median = (values: number[]) => { + const sorted = [...values].sort((a, b) => a - b); + const middle = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; +}; + +test("records cold time to Mine rows", async ({ browser, request, baseURL }, testInfo) => { + const runs = Number(process.env.PAPERCLIP_COLLECTION_PERF_TIMING_RUNS ?? 5); + expect(Number.isInteger(runs) && runs >= 5, "Record at least five samples").toBe(true); + test.setTimeout(60_000 + runs * 60_000); + const settingsUrl = "/api/instance/settings/experimental"; + const original = await (await request.get(settingsUrl)).json() as { enableIsolatedWorkspaces: boolean }; + const enable = await request.patch(settingsUrl, { data: { enableIsolatedWorkspaces: true } }); + expect(enable.ok(), await enable.text()).toBeTruthy(); + const sample = async (delayMs: number): Promise => { + const context = await browser.newContext({ baseURL, serviceWorkers: "block", viewport: { width: 1440, height: 900 } }); + try { + const page = await context.newPage(); + const reads = recordWorkspaceReads(page); + if (delayMs > 0) await page.route(url => url.pathname === workspaceListPath(), async route => { + await new Promise(resolve => setTimeout(resolve, delayMs)); + await route.continue(); + }); + await page.addInitScript(() => { + const state = window as unknown as { __mineRowsAt: number | null }; + state.__mineRowsAt = null; + const observer = new MutationObserver(() => { + if (!document.querySelector("[data-inbox-item]")) return; + observer.disconnect(); + requestAnimationFrame(() => requestAnimationFrame(() => { state.__mineRowsAt = performance.now(); })); + }); + observer.observe(document, { subtree: true, childList: true }); + }); + await page.goto(minePage()); + await page.waitForFunction(() => (window as unknown as { __mineRowsAt: number | null }).__mineRowsAt !== null, null, { timeout: 30_000 }); + const timeToRowsMs = Math.round(await page.evaluate(() => (window as unknown as { __mineRowsAt: number }).__mineRowsAt)); + await expect(mineLink(page, fixture.mine[0]!.identifier)).toBeVisible(); + return { timeToRowsMs, workspaceReads: reads.map(url => url.search) }; + } finally { await context.close(); } + }; + const scenarios = [ + { name: "native loopback, no interception", delayMs: 0, samples: [] as Sample[] }, + { name: `workspace reads delayed ${WORKSPACE_DELAY_MS} ms (diagnostic, intercepted)`, delayMs: WORKSPACE_DELAY_MS, samples: [] as Sample[] }, + ]; + try { + for (const scenario of scenarios) for (let run = 0; run < runs; run++) scenario.samples.push(await sample(scenario.delayMs)); + } finally { + const restore = await request.patch(settingsUrl, { data: { enableIsolatedWorkspaces: original.enableIsolatedWorkspaces } }); + expect(restore.ok(), await restore.text()).toBeTruthy(); + } + const report = scenarios.map(({ name, samples }) => { + const times = samples.map(entry => entry.timeToRowsMs); + console.log(`Mine cold time to rows, ${name}: median ${median(times)} ms over ${runs} runs (${[...times].sort((a, b) => a - b).join(", ")} ms)`); + return { scenario: name, workspaces: WORKSPACE_COUNT, mineRows: fixture.mine.length, medianMs: median(times), samples }; + }); + await testInfo.attach("mine-workspace-scale-timing", { contentType: "application/json", body: Buffer.from(JSON.stringify(report, null, 2)) }); +}); diff --git a/tests/perf/collections/workspace-fixture.ts b/tests/perf/collections/workspace-fixture.ts new file mode 100644 index 00000000000..c811f6606b0 --- /dev/null +++ b/tests/perf/collections/workspace-fixture.ts @@ -0,0 +1,132 @@ +import { randomUUID } from "node:crypto"; +import fs from "node:fs/promises"; +import path from "node:path"; +import { expect, type APIRequestContext, type Page } from "@playwright/test"; +import { sql } from "../../../server/node_modules/drizzle-orm/index.js"; +import { closeRegisteredClients, createDb, executionWorkspaces, issues, projects } from "../../../packages/db/src/index.js"; + +// A company shaped like a long-lived instance: thousands of execution +// workspaces, most of them created for (now finished) tasks, and a few Mine +// rows that each run in their own isolated workspace. The API has no route to +// create execution workspaces, so the bulk rows are written to the disposable +// instance database directly. Mine rows are created through the API so Mine +// selects them exactly as it selects any board-created task. +export const WORKSPACE_COUNT = 6_000; +export const LINKED_WORKSPACE_COUNT = 4_000; +export const MINE_ROW_COUNT = 12; +export type WorkspaceFixture = { + company: { id: string; issuePrefix: string }; + mine: Array<{ id: string; identifier: string; workspaceId: string; workspaceName: string }>; +}; +export const workspaceFixturePath = "test-results/collections/workspace-fixture.json"; +const LOOPBACK_HOSTS = ["127.0.0.1", "localhost", "[::1]", "::1"]; + +async function databaseUrl() { + let url = process.env.PAPERCLIP_COLLECTION_PERF_DATABASE_URL; + if (!url && process.env.PAPERCLIP_CONFIG) { + const config = JSON.parse(await fs.readFile(process.env.PAPERCLIP_CONFIG, "utf8")); + url = config.database.mode === "postgres" ? config.database.connectionString + : `postgres://paperclip:paperclip@127.0.0.1:${(await fs.readFile( + path.join(config.database.embeddedPostgresDataDir, "postmaster.pid"), "utf8")).split("\n")[3]}/paperclip`; + } + if (!url) { + throw new Error("Workspace-scale checks seed execution workspaces directly. Set PAPERCLIP_COLLECTION_PERF_DATABASE_URL " + + "to the disposable instance database, or PAPERCLIP_CONFIG to its config.json."); + } + if (!LOOPBACK_HOSTS.includes(new URL(url).hostname)) throw new Error("Workspace-scale seeding only supports a loopback database."); + return url; +} + +async function seed(request: APIRequestContext): Promise { + const created = await request.post("/api/companies", { data: { name: "Mine workspace scale fixture" } }); + expect(created.ok(), await created.text()).toBeTruthy(); + const company = await created.json() as { id: string; issuePrefix: string }; + const preference = await request.put(`/api/companies/${company.id}/workspace-preferences/me`, { + data: { coordinatorWorkspaceEnabled: true }, + }); + expect(preference.ok(), await preference.text()).toBeTruthy(); + const mineTasks: Array<{ id: string; identifier: string; issueNumber: number }> = []; + for (let index = 0; index < MINE_ROW_COUNT; index++) { + const response = await request.post(`/api/companies/${company.id}/issues`, { data: { + title: `Workspace-scale Mine task ${index}`, status: "todo", + } }); + expect(response.ok(), await response.text()).toBeTruthy(); + mineTasks.push(await response.json()); + } + + const url = await databaseUrl(); + const db = createDb(url); + try { + const projectId = randomUUID(); + await db.insert(projects).values({ id: projectId, companyId: company.id, name: "Workspace scale project", status: "in_progress" }); + const firstNumber = Math.max(...mineTasks.map(task => task.issueNumber)) + 1; + const now = Date.now(); + // Finished tasks, each with the workspace it ran in. The remaining + // workspaces have no source task (reused, imported or orphaned). + const sourceTasks = Array.from({ length: LINKED_WORKSPACE_COUNT }, (_, index) => ({ + id: randomUUID(), companyId: company.id, projectId, title: `Finished workspace task ${index}`, status: "done", + issueNumber: firstNumber + index, identifier: `${company.issuePrefix}-${firstNumber + index}`, + createdAt: new Date(now - (index + 60) * 60_000), updatedAt: new Date(now - (index + 60) * 60_000), + })); + const workspace = (index: number, sourceIssueId: string | null, name = `scale-ws-${index}`) => ({ + id: randomUUID(), companyId: company.id, projectId, sourceIssueId, mode: "isolated_workspace", strategyType: "git_worktree", + providerType: "git_worktree", name, status: index % 3 === 0 ? "idle" : "archived", cwd: `/tmp/collections-perf/${name}`, + branchName: `perf/${name}`, lastUsedAt: new Date(now - (index + 60) * 60_000), + metadata: sourceIssueId ? { _issuePrivacySources: { [sourceIssueId]: true } } : null, + }); + const bulk = Array.from({ length: WORKSPACE_COUNT - MINE_ROW_COUNT }, (_, index) => + workspace(index, sourceTasks[index]?.id ?? null)); + const mineWorkspaces = mineTasks.map((task, index) => ({ + ...workspace(index, task.id, `mine-isolated-${index}`), status: "active", lastUsedAt: new Date(now - index * 1_000), + })); + for (let index = 0; index < sourceTasks.length; index += 500) await db.insert(issues).values(sourceTasks.slice(index, index + 500)); + const allWorkspaces = [...mineWorkspaces, ...bulk]; + for (let index = 0; index < allWorkspaces.length; index += 500) { + await db.insert(executionWorkspaces).values(allWorkspaces.slice(index, index + 500)); + } + await db.execute(sql`update issues set execution_workspace_id = w.id + from execution_workspaces w where w.source_issue_id = issues.id and w.company_id = ${company.id}`); + await db.execute(sql`update companies set issue_counter = ${firstNumber + LINKED_WORKSPACE_COUNT - 1} where id = ${company.id}`); + await db.execute(sql`analyze issues`); + await db.execute(sql`analyze execution_workspaces`); + const [counts] = await db.execute(sql`select + (select count(*)::int from execution_workspaces where company_id = ${company.id}) as workspaces, + (select count(*)::int from issues where company_id = ${company.id} and execution_workspace_id is not null) as linked`) as unknown as Array<{ workspaces: number; linked: number }>; + expect(counts).toEqual({ workspaces: WORKSPACE_COUNT, linked: LINKED_WORKSPACE_COUNT + MINE_ROW_COUNT }); + return { + company: { id: company.id, issuePrefix: company.issuePrefix }, + mine: mineTasks.map((task, index) => ({ + id: task.id, identifier: task.identifier, workspaceId: mineWorkspaces[index]!.id, workspaceName: mineWorkspaces[index]!.name, + })), + }; + } finally { + await closeRegisteredClients(url); + } +} + +// Retained like the main collection fixture: reused while its company exists, +// replaced only when the company is gone (404). Other errors fail. +export async function workspaceFixture(request: APIRequestContext): Promise { + const saved = await fs.readFile(workspaceFixturePath, "utf8").then(JSON.parse).catch(error => { + if (error.code !== "ENOENT") throw error; + return null; + }) as WorkspaceFixture | null; + if (saved) { + const existing = await request.get(`/api/companies/${saved.company.id}`); + if (existing.ok()) return saved; + expect(existing.status(), await existing.text()).toBe(404); + } + const fixture = await seed(request); + await fs.mkdir(path.dirname(workspaceFixturePath), { recursive: true }); + await fs.writeFile(workspaceFixturePath, JSON.stringify(fixture)); + return fixture; +} + +// Turns on isolated workspaces for this page only, so other specs keep the +// instance's real feature settings. +export async function isolatedWorkspaceSettings(page: Page) { + await page.route("**/api/instance/settings/experimental", async route => { + const response = await route.fetch(); + await route.fulfill({ json: { ...await response.json(), enableIsolatedWorkspaces: true } }); + }); +}