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>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-13 12:54:45 -06:00
1 parent 8aaf983151
commit e5158293c5
5 files changed
+254 -1

No files matched your search

+12
View File
@@ -61,6 +61,18 @@ navigation start to the first Mine row (two frames after mount) over
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.
`shell-read-waves.spec.ts` hard loads Mine with every API response delayed
300 ms and counts the shell and inbox reads that used to repeat about 1.5–2.5 s
after load (session, health, company list, agents, inbox dismissals, user
directory, approvals, execution workspaces). With the saved query cache
(`paperclip:query-cache:v1:<user>:<company>`, primed by one earlier visit in
the same browser context) each read happens at most once and the live socket
opens once. Without it, the socket's catch-up read may repeat reads that
answered before the subscription, but never the session or health read. The
fixture (`returning-visit-fixture.ts`) is a company with 24 Mine tasks and
three pending board approvals, retained in
`test-results/collections/mine-returning-visit-fixture.json`.
`recent-task-open.spec.ts` covers opening a task from the sidebar's Recents.
It gives eight fixture tasks twelve saved comments each and seeds them as the
account's Recents. An idle Projects page must make exactly one
@@ -0,0 +1,129 @@
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;
};
@@ -0,0 +1,54 @@
import { expect, test } from "@playwright/test";
import { freshContext, minePath, observeMineLoad, returningVisitFixture, savedQueryCache, type ReturningVisitFixture } from "./returning-visit-fixture";
// A hard load of Mine used to repeat about eight shell and inbox reads 1.5–2.5 s
// after load. With the saved query cache, the restored session has no session
// id; when the server answered with one, the live-updates socket reconnected,
// and that reconnect refreshed every active query, session and health included.
// Every API response is delayed 300 ms so the socket opens while reads are in
// flight, as on a busy hosted instance.
let fixture: ReturningVisitFixture;
test.beforeAll(async ({ request }) => {
test.setTimeout(120_000);
fixture = await returningVisitFixture(request);
});
test("a returning visit makes each shell read at most once and keeps one live socket", async ({ browser, baseURL }) => {
const storageState = await savedQueryCache(browser, baseURL, fixture);
const context = await freshContext(browser, baseURL, storageState);
try {
const page = await context.newPage();
const sockets: string[] = [];
page.on("websocket", socket => { if (socket.url().includes("/events/ws")) sockets.push(socket.url()); });
const { rowsAt, shellReadCounts } = await observeMineLoad(page, 300);
await page.goto(minePath(fixture));
await rowsAt();
await page.waitForTimeout(5_000);
const counts = shellReadCounts();
// The restored session is verified exactly once; that read is what used to reconnect the socket.
expect(counts["auth/get-session"], JSON.stringify(counts)).toBe(1);
expect(Object.entries(counts).filter(([, count]) => count > 1), JSON.stringify(counts)).toEqual([]);
expect(sockets, "The verified session reconnected the live socket").toHaveLength(1);
} finally { await context.close(); }
});
// Without a saved cache the socket can open only after the company list has
// answered, so the catch-up read that covers events between a read and the
// subscription may repeat reads that answered first. It never repeats the
// session or health read, and the socket is opened once.
test("a first visit never repeats the session or health read", async ({ browser, baseURL }) => {
const context = await freshContext(browser, baseURL);
try {
const page = await context.newPage();
const sockets: string[] = [];
page.on("websocket", socket => { if (socket.url().includes("/events/ws")) sockets.push(socket.url()); });
const { rowsAt, shellReadCounts } = await observeMineLoad(page, 300);
await page.goto(minePath(fixture));
await rowsAt();
await page.waitForTimeout(5_000);
const counts = shellReadCounts();
expect({ session: counts["auth/get-session"], health: counts.health }, JSON.stringify(counts)).toEqual({ session: 1, health: 1 });
expect(Object.entries(counts).filter(([, count]) => count > 2), JSON.stringify(counts)).toEqual([]);
expect(sockets).toHaveLength(1);
} finally { await context.close(); }
});
@@ -357,6 +357,40 @@ describe("LiveUpdatesProvider connection recovery", () => {
expect(pollRead).toHaveBeenCalledTimes(afterOpen);
});
// A session restored from the saved query cache has no session id. Its first
// verified read is the same sign-in, so the socket stays open and nothing is
// refetched. Before, the new id reconnected the socket, and that open
// refreshed every active query, session and health included.
it("keeps the socket when the restored session is verified for the same user", async () => {
vi.stubGlobal("WebSocket", Socket);
client.setQueryData(queryKeys.auth.session, { user: { id: "viewer" }, session: { userId: "viewer" } });
await renderPolling();
expect(Socket.instances).toHaveLength(1);
await act(async () => Socket.instances[0].onopen?.());
expect(container.textContent).toBe("connected");
const invalidate = vi.spyOn(client, "invalidateQueries");
await act(async () => client.setQueryData(queryKeys.auth.session, { user: { id: "viewer" }, session: { id: "session", userId: "viewer" } }));
await act(async () => vi.advanceTimersByTimeAsync(1));
expect(Socket.instances).toHaveLength(1);
expect(container.textContent).toBe("connected");
expect(invalidate).not.toHaveBeenCalled();
// A later replacement session still needs a new connection.
await act(async () => client.setQueryData(queryKeys.auth.session, { user: { id: "viewer" }, session: { id: "replacement", userId: "viewer" } }));
await act(async () => vi.advanceTimersByTimeAsync(1));
expect(Socket.instances).toHaveLength(2);
});
it("reconnects when the verified session belongs to another user", async () => {
vi.stubGlobal("WebSocket", Socket);
client.setQueryData(queryKeys.auth.session, { user: { id: "viewer" }, session: { userId: "viewer" } });
await renderPolling();
await act(async () => Socket.instances[0].onopen?.());
await act(async () => client.setQueryData(queryKeys.auth.session, { user: { id: "other" }, session: { id: "other-session", userId: "other" } }));
await act(async () => vi.advanceTimersByTimeAsync(1));
expect(Socket.instances).toHaveLength(2);
expect(container.textContent).toBe("fallback");
});
it.each(["DEMO-1", "issue-1"])("discovers and finishes runs with cache key %s on an unfocused non-task route", async queryRef => {
vi.stubGlobal("WebSocket", Socket);
vi.spyOn(document, "hasFocus").mockReturnValue(false);
+25 -1
View File
@@ -2374,6 +2374,7 @@ export const __liveUpdatesTestUtils = {
readRunLiveStatusPatchFromPayload,
resolveLiveCompanyId,
canUseLiveSession,
nextSocketAuthScope,
shouldDeferIssueRefetchForVisibleAgentActivity,
shouldDeferVisibleIssueCommentActivity,
shouldSuppressActivityToastForVisibleIssue,
@@ -2381,6 +2382,24 @@ export const __liveUpdatesTestUtils = {
shouldSuppressAgentStatusToastForVisibleIssue,
};
type SocketAuthScope = { userId: string | null; sessionId: string | null; key: string };
/**
* The socket's sign-in scope. A new key closes the socket, opens another and
* refreshes every active query, because events are not replayed.
*
* A session restored from the saved query cache carries the user but no
* session id. Its first verified read adds the id for the same user. That is
* the same sign-in, so the key stays and the open socket is kept. A
* different user, or a different session id once one is known, still
* reconnects.
*/
function nextSocketAuthScope(previous: SocketAuthScope | null, userId: string | null, sessionId: string | null): SocketAuthScope {
if (previous && previous.userId === userId && previous.sessionId === sessionId) return previous;
if (previous && userId !== null && previous.userId === userId && previous.sessionId === null) return { ...previous, sessionId };
return { userId, sessionId, key: sessionId ?? userId ?? "signed_out" };
}
function canUseLiveSession(sessionStatus: string, hasSession: boolean, deploymentMode?: string) {
return sessionStatus === "success" && (hasSession || deploymentMode === "local_trusted");
}
@@ -2408,7 +2427,12 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) {
const { data: health } = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get });
const currentUserId = session?.user?.id ?? session?.session?.userId ??
(health?.deploymentMode === "local_trusted" ? "local-board" : null);
const socketAuthKey = session?.session?.id ?? currentUserId ?? "signed_out";
const sessionId = session?.session?.id ?? null;
const [socketAuth, setSocketAuth] = useState(() => nextSocketAuthScope(null, currentUserId, sessionId));
const nextSocketAuth = nextSocketAuthScope(socketAuth, currentUserId, sessionId);
// Adjust state during render: the scope depends on the previous scope.
if (nextSocketAuth !== socketAuth) setSocketAuth(nextSocketAuth);
const socketAuthKey = nextSocketAuth.key;
const [connectedScopeKey, setConnectedScopeKey] = useState<string | null>(null);
const liveCompanyId = resolveLiveCompanyId(selectedCompanyId, selectedCompany?.id ?? null);
const socketScopeKey = JSON.stringify([liveCompanyId, socketAuthKey]);