Files
PaperClipAI/tests/perf/collections/returning-visit-fixture.ts
T
DottaandClaude Opus 5.5 e5158293c5 perf(ui): keep the live socket when a cached session is verified (#20591)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The board UI keeps one live-updates WebSocket per company and saves
a copy of its query cache in `localStorage` so a returning visit can
paint from it
> - On a returning hard load of the Mine inbox, about eight shell and
inbox reads ran a second time 1.5–2.5 s after load (session, health,
company list, agents, inbox dismissals, user directory, approvals,
execution workspaces)
> - The cause is the socket's sign-in key. A session restored from the
saved cache has the user but no session id. The first session read adds
the id, the key changes, the socket closes and opens again, and that
second open refreshes every active query, session and health included
> - This pull request keeps the socket when the verified session belongs
to the same user as the restored one
> - The benefit is one read of each shell request per returning load and
one socket instead of two, with no change to the catch-up read that
covers the gap before the first subscription

## Linked Issues or Issue Description

**What happened?**
A returning hard load of `/:companyPrefix/issues?view=mine` sent
`auth/get-session`, `health`, `companies?scope=accessible`, agents,
inbox-dismissals, user-directory, approvals and execution-workspaces
twice. The second copy started about 1.5–2.5 s after load on the hosted
staging instance.

**Steps to reproduce**
1. Open Mine once so the app saves its query cache.
2. Reload the page.
3. Watch the network panel. The live-updates socket opens, closes, opens
again, and the reads above repeat.

**Expected behavior**
Each read runs once. The socket opens once.

Related: #20398 (socket reconcile skips settings and preferences),
#20407 and #20419 (Mine reveal and its perf guard).

## What Changed

- `ui/src/context/LiveUpdatesProvider.tsx`: the socket auth key comes
from `nextSocketAuthScope`. When the previous scope has the same user
and no session id, the first known session id is adopted without a new
key. A different user, or a different session id once one is known,
still produces a new key and a new connection.
- `ui/src/context/LiveUpdatesProvider.recovery.test.tsx`: two tests. A
restored session (no id) verified for the same user keeps the socket and
invalidates nothing; a later replacement session still reconnects. A
verified session for another user reconnects.
- `tests/perf/collections/shell-read-waves.spec.ts` and
`returning-visit-fixture.ts`: browser checks on a production build with
every API response delayed 300 ms. With a saved cache, each of the eight
reads runs at most once and the socket opens once. Without a saved
cache, session and health run once, no read runs more than twice, and
the socket opens once.
- `tests/perf/collections/README.md`: documents the new spec and
fixture.

## Verification

- `cd ui && pnpm exec vitest run src/context/`: 16 files, 286 tests
pass. The new same-user test fails on `master` (socket count 2) and
passes with this change.
- Browser check on a disposable local instance (production UI build,
`local_trusted`, embedded PostgreSQL, Chromium headless, 1440×900, API
+300 ms):
`PAPERCLIP_COLLECTION_PERF_BASE_URL=http://127.0.0.1:<port> pnpm exec
playwright test --config tests/perf/collections/playwright.config.ts
shell-read-waves.spec.ts`
- `master` build (`99edcd28a7`): returning visit fails with
`{"auth/get-session":2,"health":1,"companies?scope=accessible":2,"agents":2,"inbox-dismissals":1,"user-directory":1,"approvals":1,"execution-workspaces":0}`.
  - This branch: both tests pass; every count is 1 and one socket opens.
- Timing evidence (same instance, 5 fresh contexts per arm, API +300 ms,
host load average about 20; `mine-returning-visit.spec.ts` timing case
from the companion Mine PR). Duplicate shell reads are summed over the 5
loads:

| Build | Saved cache: time to rows, median (range) | Saved cache:
duplicate shell reads | Cleared cache: median (range) | Cleared cache:
duplicate shell reads |
  | --- | --- | --- | --- | --- |
| `master` | 1028 ms (906–3011) | 5 (session ×2 each load) | 1502 ms
(1423–1592) | 5 (company list ×2, the catch-up) |
| This PR | 895 ms (880–930) | 0 | 1364 ms (1328–1408) | 5 (company list
×2, the catch-up) |

The time difference is small and inside host noise; the claim here is
the removed reads and the single socket. On the busier hosted instance
the second wave was larger (about eight reads), because more reads have
answered before the session read returns.
- Review follow-up (8e6e77dd4c): the scope is held in state instead of a
ref written during render, and the browser check requires exactly one
session read. Re-run after that commit: provider tests pass and
`shell-read-waves.spec.ts` passes twice.
- `pnpm verify` selected broader coverage (exit 2) because the perf
fixture is a global CI input. Required CI supplies that coverage.
- `pnpm check:token-gates`: clean.
- Not run: the full local Vitest suite, browser suites outside
`tests/perf/collections`, the hosted staging page.

## Risks

- Low risk. The socket keeps its connection only for the same user. The
cookie that opened it is the one the verified session read used.
Sign-out still drops the session, so the socket closes.
- If the cached copy and the verified session name different users, the
key changes as before, the socket reconnects, and the persisted cache
clears the old account's data as before.
- The initial catch-up read after the first socket open is unchanged. On
a first visit the company list can still be read twice, because the
socket can only subscribe after that list answers.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, Playwright). Standard context window,
reasoning enabled.

## 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>
2026-11-13 12:54:45 -06:00

130 lines
7.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from "node:fs/promises";
import { expect, type APIRequestContext, type Browser, type BrowserContext, type Page } from "@playwright/test";
// A company with Mine tasks and pending board approvals, for hard loads of
// Mine with and without the saved query cache
// (`paperclip:query-cache:v1:<user>:<company>`). Retained in
// test-results/collections with the same 404 rule as the other fixtures.
export type ReturningVisitFixture = {
company: { id: string; issuePrefix: string };
tasks: Array<{ id: string; identifier: string }>;
approvalIds: string[];
};
const fixturePath = "test-results/collections/mine-returning-visit-fixture.json";
const TASK_COUNT = 24;
const APPROVAL_COUNT = 3;
export async function returningVisitFixture(request: APIRequestContext): Promise<ReturningVisitFixture> {
const saved = await fs.readFile(fixturePath, "utf8").then(text => JSON.parse(text) as ReturningVisitFixture).catch(error => {
if (error.code !== "ENOENT") throw error;
return 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 created = await request.post("/api/companies", { data: { name: "Mine returning visit fixture" } });
expect(created.ok(), await created.text()).toBeTruthy();
const company = await created.json() as ReturningVisitFixture["company"];
const tasks: ReturningVisitFixture["tasks"] = [];
for (let index = 0; index < TASK_COUNT; index++) {
const response = await request.post(`/api/companies/${company.id}/issues`, { data: { title: `Returning visit task ${index}`, status: "todo" } });
expect(response.ok(), await response.text()).toBeTruthy();
const task = await response.json();
tasks.push({ id: task.id, identifier: task.identifier });
}
const approvalIds: string[] = [];
for (let index = 0; index < APPROVAL_COUNT; index++) {
const response = await request.post(`/api/companies/${company.id}/approvals`, { data: {
type: "request_board_approval", payload: { title: `Returning visit approval ${index}`, summary: "Synthetic decision context." },
} });
expect(response.ok(), await response.text()).toBeTruthy();
approvalIds.push((await response.json()).id);
}
const fixture = { company, tasks, approvalIds };
await fs.mkdir("test-results/collections", { recursive: true });
await fs.writeFile(fixturePath, JSON.stringify(fixture));
return fixture;
}
export const minePath = (fixture: ReturningVisitFixture) => `/${fixture.company.issuePrefix}/issues?view=mine`;
export const firstMineRow = (page: Page) => page.locator("[data-inbox-issue-link]").first();
export type StorageState = Awaited<ReturnType<BrowserContext["storageState"]>>;
export const freshContext = (browser: Browser, baseURL: string | undefined, storageState?: StorageState) =>
browser.newContext({ baseURL, serviceWorkers: "block", viewport: { width: 1440, height: 900 }, storageState });
/** Visits Mine once and returns the browser storage that visit saved, including the query cache. */
export async function savedQueryCache(browser: Browser, baseURL: string | undefined, fixture: ReturningVisitFixture): Promise<StorageState> {
const context = await freshContext(browser, baseURL);
try {
const page = await context.newPage();
await page.goto(minePath(fixture));
await expect(firstMineRow(page)).toBeVisible({ timeout: 30_000 });
await page.waitForFunction((companyId) => Object.keys(localStorage).some(key => key.startsWith("paperclip:query-cache:v1:")
&& key.endsWith(`:${encodeURIComponent(companyId)}`) && (localStorage.getItem(key) ?? "").includes("mine-context")),
fixture.company.id, { timeout: 15_000 });
// Let the debounced writer settle after the last background read.
await page.waitForTimeout(1_500);
await page.evaluate(() => window.dispatchEvent(new Event("pagehide")));
return await context.storageState();
} finally { await context.close(); }
}
/** Shell and inbox reads that a hard load of Mine used to repeat about 1.5–2.5 s after load. */
export const SHELL_READS: ReadonlyArray<readonly [string, (url: URL) => boolean]> = [
["auth/get-session", url => url.pathname === "/api/auth/get-session"],
["health", url => url.pathname === "/api/health"],
["companies?scope=accessible", url => url.pathname === "/api/companies" && url.searchParams.get("scope") === "accessible"],
["agents", url => /^\/api\/companies\/[^/]+\/agents$/.test(url.pathname)],
["inbox-dismissals", url => /^\/api\/companies\/[^/]+\/inbox-dismissals$/.test(url.pathname)],
["user-directory", url => /^\/api\/companies\/[^/]+\/user-directory$/.test(url.pathname)],
["approvals", url => /^\/api\/companies\/[^/]+\/approvals$/.test(url.pathname)],
["execution-workspaces", url => /^\/api\/companies\/[^/]+\/execution-workspaces$/.test(url.pathname)],
];
export type ApiRead = { path: string; startedAt: number; finishedAt: number | null };
/**
* Delays every API response by `delayMs`, records each read, and marks the
* first Mine row (two frames after it mounts) in page time.
*/
export async function observeMineLoad(page: Page, delayMs: number) {
const reads: ApiRead[] = [];
await page.route(url => url.pathname.startsWith("/api/"), async route => {
const url = new URL(route.request().url());
reads.push({ path: `${url.pathname}${url.search}`, startedAt: Date.now(), finishedAt: null });
if (delayMs > 0) await new Promise(resolve => setTimeout(resolve, delayMs));
// A closed page aborts outstanding routes; that read never finished.
await route.continue().catch(() => {});
});
page.on("requestfinished", request => {
const url = new URL(request.url());
const read = reads.find(entry => entry.finishedAt === null && entry.path === `${url.pathname}${url.search}`);
if (read) read.finishedAt = Date.now();
});
await page.addInitScript(() => {
const state = window as unknown as { __mineRowsAt: number | null };
state.__mineRowsAt = null;
const observer = new MutationObserver(() => {
if (!document.querySelector("[data-inbox-issue-link]")) return;
observer.disconnect();
requestAnimationFrame(() => requestAnimationFrame(() => { state.__mineRowsAt = performance.timeOrigin + performance.now(); }));
});
observer.observe(document, { subtree: true, childList: true });
});
const rowsAt = async () => {
await page.waitForFunction(() => (window as unknown as { __mineRowsAt: number | null }).__mineRowsAt !== null, null, { timeout: 30_000 });
return await page.evaluate(() => (window as unknown as { __mineRowsAt: number }).__mineRowsAt);
};
const shellReadCounts = () => Object.fromEntries(SHELL_READS.map(([name, matches]) => [name,
reads.filter(read => matches(new URL(read.path, "http://local"))).length])) as Record<string, number>;
return { reads, rowsAt, shellReadCounts };
}
export 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;
};