Files
PaperClipAI/ui/src/lib/browser-tracing/controller.test.ts
T
DottaandClaude Opus 5.5 51c81c537b fix(browser-tracing): end hidden loads, cap timeouts, backfill hard-load API spans, record list view (#21392)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted instances send real-user page-load traces to Honeycomb
(#21156), so we can set page-load SLOs
> - Staging data showed four measurement gaps: 140 of 147 hard loads
were hidden tabs that became 30 s timeouts, a few timeouts lasted about
2 hours after the computer slept, hard loads had no API child spans, and
list views on the tasks page could not be told apart
> - These gaps make every average and percentile wrong, so the data
cannot back an SLO yet
> - This pull request ends hidden loads as `hidden`, caps timeouts at
exactly 30 s and marks suspends, backfills hard-load API spans from
Resource Timing, and records the list view from an allowlist
> - The benefit is page-load numbers that describe what users see, with
no cost on the critical path

## Linked Issues or Issue Description

Refs #21156

**What is the issue?**
Browser page-load tracing records misleading data. A load in a
background tab never paints, so it always ends as a 30 s `timeout`. A
timeout that fires late (after sleep) reports hours. Hard loads have no
API spans because the SDK loads after the page settles. `?view=` is
stripped, so all task list views share one route.

**Steps to reproduce**
Open the all-tasks page in a background tab on a traced instance. The
`page.load` span is `outcome=timeout`, `was_hidden=true`, about 30.4 s
(reproduced locally on master: 30,359 ms and 30,988 ms).

**Expected behavior**
A hidden load is counted separately and ends quickly. A timeout lasts
exactly 30 s. A hard load shows its API requests. The list view is a
dimension.

## What Changed

- `page-load-recorder.ts`: new outcome `hidden`. A load that starts
hidden, or hides before it is ready, ends at the moment the tab hid
(same rule `web-vitals` uses for LCP/FCP). For a hard load, the
controller reads Chromium `visibility-state` entries, so a hide before
tracing started is caught. A redirect while still hidden renames the
hidden span instead of starting a second one.
- `page-load-recorder.ts`: any end observed after start + 30 s is a
`timeout` that ends at exactly start + 30 s.
`paperclip.page.suspended=true` marks an end more than 5 s past the
deadline or a gap of more than 5 s between frames.
- `controller.ts`: a `PerformanceObserver` (`type: resource`, `buffered:
true`) keeps only this origin's `/api/` fetch/XHR entries (max 500)
until the SDK loads. It does not depend on the 250-entry resource
buffer.
- `sdk.ts`: when the SDK loads, it creates `HTTP` child spans under each
`page.load` that started before the SDK, for requests that started in
the load window and before live fetch tracing began (no duplicates). The
name is `HTTP` because Resource Timing has no method (OpenTelemetry's
name for an unknown method). Status comes only from `responseStatus`
when the browser exposes it. The URL goes through the same sanitizer as
live fetch spans and becomes `paperclip.api.area`. Spans carry
`paperclip.api.timing_source=resource_timing`.
- `page-view.ts`: `paperclip.page.view` for `/:companyPrefix/issues`
(values from `TASK_VIEW_KEYS`, `default` when missing) and
`/:companyPrefix/decisions` (values from `ATTENTION_PERSONAL_VIEWS`,
`mine` when missing). Any other value is `other`.
- `span-sanitizer.ts`: allowlist adds `paperclip.page.suspended`,
`paperclip.page.view`, `paperclip.api.timing_source`.
- `doc/browser-performance-tracing.md`: outcome list, the meaning of
"loaded" for hidden tabs, suspend handling, page views, backfilled API
spans, attribute table, and example queries that filter `outcome =
ready`.

## Verification

- Red then green: 17 new tests failed on the old code and
`page-view.test.ts` failed to import; all 50 tests in
`ui/src/lib/browser-tracing` pass after the change.
`PageLoadTracker.test.tsx` passes. `tsc --noEmit` for `ui` passes.
- `pnpm verify` exits 2 (a doc is a global CI input), so CI supplies
broad coverage.
- Real browser (local dev server on an empty isolated instance, stand-in
OTLP collector, headless Chromium, tracing config injected into the
session response):
- Background tab (raw CDP, `Target.createTarget background:true`):
`outcome=hidden`, duration 0 ms. Master: `outcome=timeout`, 30,359 ms.
- Tab covered 400 ms into the load: `outcome=hidden`, 434 ms. Master:
`timeout`, 30,988 ms.
- Hard load of the all-tasks page: `page.load` with 13 to 38 `HTTP`
child spans (areas `companies`, `plugins`, `cli-auth`, and others,
status 200 where exposed), same trace, parent = `page.load`.
  - `?view=mine`: `paperclip.page.view=mine`.
- Leak scan of every exported body: no URL, host, company id, company
prefix, user id, or query text.
- Entry bundle: 3,822,045 → 3,823,991 B raw (+1.9 KB), 1,154,280 →
1,155,097 B gzip (+0.8 KB, 0.07%). Lazy SDK chunk: 84,322 → 85,229 B
raw, 27,304 → 27,630 B gzip.

## Risks

- Low risk. The change is limited to the operator-gated Observability
path on hosted instances; self-hosted installs never start the
controller.
- Behavior shift for dashboards: hidden tabs are now `outcome=hidden`
instead of `timeout`, so timeout rates drop. Queries should filter
`outcome = ready`.
- The observer adds one callback per batch of finished requests while
tracing is on, until the SDK loads. It keeps at most 500 entries.
- Backfilled spans do not join server traces because no `traceparent`
was sent. The docs say so.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, headless Chromium).

## 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 09:19:25 -06:00

225 lines
8.4 KiB
TypeScript

// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { QueryClient } from "@tanstack/react-query";
import type { BrowserTracingConfig } from "@paperclipai/shared";
import type { PageLoadMeasurement } from "./page-load-recorder";
import {
observeApiResources,
resetPageSessionSampleForTest,
SDK_LOAD_DEADLINE_MS,
startBrowserTracingController,
type TracingSdkModule,
} from "./controller";
const config: BrowserTracingConfig = {
tracesUrl: "https://api.honeycomb.io/v1/traces",
ingestKey: "hcaik_test",
serviceName: "paperclip-web",
environment: null,
sampleRate: 1,
};
/**
* The page's clock starts at navigation start. A test process can be older
* than the 30 s page-load timeout, which would turn the hard load (start 0)
* into a timeout, so the clock is restarted for each test.
*/
function restartPageClock() {
const realNow = performance.now.bind(performance);
const origin = realNow();
vi.spyOn(performance, "now").mockImplementation(() => realNow() - origin);
}
describe("startBrowserTracingController", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame"] });
resetPageSessionSampleForTest();
restartPageClock();
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
setVisibility("visible");
});
function setVisibility(state: DocumentVisibilityState) {
Object.defineProperty(document, "visibilityState", { configurable: true, get: () => state });
}
function hangingQueryClient() {
const queryClient = new QueryClient();
void queryClient.fetchQuery({ queryKey: ["hangs"], queryFn: () => new Promise(() => {}) });
return queryClient;
}
function recordingSdk(ended: PageLoadMeasurement[]) {
return vi.fn(async (): Promise<TracingSdkModule> => ({
startTracingSdk: (_config, recorder) => {
recorder.attachSink({ begin: () => {}, end: (m) => ended.push({ ...m }) });
return { forceFlush: async () => {}, shutdown: async () => {} };
},
}));
}
it("ends a hard load in a background tab as hidden instead of a 30 s timeout", async () => {
setVisibility("hidden");
const ended: PageLoadMeasurement[] = [];
const controller = startBrowserTracingController(config, {
queryClient: hangingQueryClient(),
initialPathname: "/PAP/issues",
initialRouteTemplate: "/:companyPrefix/issues",
loadSdk: recordingSdk(ended),
scheduleSdkLoad: () => () => {},
});
await vi.advanceTimersByTimeAsync(SDK_LOAD_DEADLINE_MS);
await vi.waitFor(() => expect(ended).toHaveLength(1));
expect(ended[0]).toMatchObject({ loadType: "hard", outcome: "hidden", startTime: 0, endTime: 0, wasHidden: true });
controller?.stop();
});
it("ends an open load as hidden when the tab hides", async () => {
const ended: PageLoadMeasurement[] = [];
const controller = startBrowserTracingController(config, {
queryClient: hangingQueryClient(),
initialPathname: "/PAP/issues",
initialRouteTemplate: "/:companyPrefix/issues",
loadSdk: recordingSdk(ended),
scheduleSdkLoad: () => () => {},
});
await vi.advanceTimersByTimeAsync(1_000);
setVisibility("hidden");
const hiddenAt = performance.now();
document.dispatchEvent(new Event("visibilitychange"));
await vi.advanceTimersByTimeAsync(SDK_LOAD_DEADLINE_MS);
await vi.waitFor(() => expect(ended).toHaveLength(1));
expect(ended[0]!.outcome).toBe("hidden");
expect(ended[0]!.endTime).toBeGreaterThanOrEqual(hiddenAt);
expect(ended[0]!.endTime).toBeLessThan(hiddenAt + 1_000);
controller?.stop();
});
it("records the all-tasks page view from the URL", async () => {
window.history.replaceState(null, "", "/PAP/issues?view=mine&q=private-search");
const ended: PageLoadMeasurement[] = [];
const controller = startBrowserTracingController(config, {
queryClient: hangingQueryClient(),
initialPathname: "/PAP/issues",
initialRouteTemplate: "/:companyPrefix/issues",
loadSdk: recordingSdk(ended),
scheduleSdkLoad: () => () => {},
});
await vi.advanceTimersByTimeAsync(SDK_LOAD_DEADLINE_MS);
await vi.waitFor(() => expect(ended).toHaveLength(1));
expect(ended[0]!.view).toBe("mine");
controller?.stop();
window.history.replaceState(null, "", "/");
});
it("still loads the SDK and exports a timed-out hard load when the page never settles", async () => {
const queryClient = new QueryClient();
// A request that hangs: its query has no data and is always fetching.
void queryClient.fetchQuery({ queryKey: ["hangs"], queryFn: () => new Promise(() => {}) });
const ended: PageLoadMeasurement[] = [];
const loadSdk = vi.fn(async (): Promise<TracingSdkModule> => ({
startTracingSdk: (_config, recorder) => {
recorder.attachSink({ begin: () => {}, end: (m) => ended.push({ ...m }) });
return { forceFlush: async () => {}, shutdown: async () => {} };
},
}));
const controller = startBrowserTracingController(config, {
queryClient,
initialPathname: "/PAP/issues",
initialRouteTemplate: "/:companyPrefix/issues",
loadSdk,
// The page never settles.
scheduleSdkLoad: () => () => {},
});
await vi.advanceTimersByTimeAsync(SDK_LOAD_DEADLINE_MS - 1);
expect(loadSdk).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(loadSdk).toHaveBeenCalledTimes(1);
await vi.waitFor(() => expect(ended).toHaveLength(1));
expect(ended[0]).toMatchObject({ routeTemplate: "/:companyPrefix/issues", loadType: "hard", outcome: "timeout" });
controller?.stop();
});
it("loads the SDK once when the page settles first", async () => {
let settle: (() => void) | null = null;
const loadSdk = vi.fn(async (): Promise<TracingSdkModule> => ({
startTracingSdk: () => ({ forceFlush: async () => {}, shutdown: async () => {} }),
}));
const controller = startBrowserTracingController(config, {
queryClient: new QueryClient(),
initialPathname: "/",
initialRouteTemplate: "/",
loadSdk,
scheduleSdkLoad: (start) => {
settle = start;
return () => {};
},
});
settle!();
await vi.advanceTimersByTimeAsync(SDK_LOAD_DEADLINE_MS * 2);
expect(loadSdk).toHaveBeenCalledTimes(1);
controller?.stop();
});
});
describe("observeApiResources", () => {
type Listener = (list: { getEntries(): PerformanceEntry[] }) => void;
function fakeObserver() {
const state: { listener: Listener | null; options: PerformanceObserverInit | null; disconnected: boolean } = {
listener: null,
options: null,
disconnected: false,
};
class FakeObserver {
static supportedEntryTypes = ["resource"];
constructor(listener: Listener) {
state.listener = listener;
}
observe(options: PerformanceObserverInit) {
state.options = options;
}
disconnect() {
state.disconnected = true;
}
}
return { state, Observer: FakeObserver as unknown as typeof PerformanceObserver };
}
const entry = (name: string, initiatorType = "fetch") => ({ name, initiatorType, entryType: "resource", startTime: 5 }) as unknown as PerformanceEntry;
it("keeps only this origin's /api/ fetches, including ones already buffered", () => {
const { state, Observer } = fakeObserver();
const collector = observeApiResources("https://acme.paperclip.app", Observer);
expect(state.options).toEqual({ type: "resource", buffered: true });
state.listener!({
getEntries: () => [
entry("https://acme.paperclip.app/api/issues?view=mine"),
entry("https://acme.paperclip.app/api/companies", "xmlhttprequest"),
entry("https://acme.paperclip.app/assets/index.js", "script"),
entry("https://acme.paperclip.app.evil.com/api/issues"),
entry("https://api.honeycomb.io/v1/traces"),
],
});
expect(collector.entries().map((e) => e.name)).toEqual([
"https://acme.paperclip.app/api/issues?view=mine",
"https://acme.paperclip.app/api/companies",
]);
collector.stop();
expect(state.disconnected).toBe(true);
expect(collector.entries()).toEqual([]);
});
it("does nothing where resource timing is unavailable", () => {
const collector = observeApiResources("https://acme.paperclip.app", null);
expect(collector.entries()).toEqual([]);
collector.stop();
});
});