mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 21:34:48 +01:00
feat(ui): browser page-load tracing to Honeycomb for hosted instances (#21156)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board UI is the main surface. Its load speed is a product requirement. > - The team wants to track page-load times over time and give each metric an owner and an SLO in Honeycomb. > - Server traces show only the server part of a page load. They do not show JavaScript start-up, lazy route code, rendering, or client-side navigation. > - Paperclip is also self-hosted by others. Browser tracing must stay off there, and it must not slow any page. > - This pull request adds real-user browser tracing for hosted Paperclip Cloud instances only. It loads lazily and sends a closed set of attributes. > - The benefit is one `page.load` measurement per page (named by route pattern), plus Web Vitals and API spans that join the server trace, ready for Honeycomb queries and SLOs. ## Linked Issues or Issue Description No public issue exists. Feature description: **Subsystem affected** Board UI (`ui/`), the authenticated session route (`server/src/routes/auth.ts`), and the shared session schema. **Problem or motivation** We cannot measure how long the all-tasks page or a task page takes to load for real users. Server traces stop at the API response. Most navigation is client side, and the standard OpenTelemetry document-load instrumentation does not cover it. Without a per-page browser measurement, no agent can own a page-load SLO. **Proposed solution** The server sends a `browserTracing` config in the authenticated session only when the instance is cloud managed and `PAPERCLIP_BROWSER_TRACES_ENDPOINT` is set. The browser then measures every hard load and client navigation in one shared recorder tied to the router's own route tree. After the page settles, it lazily loads an OpenTelemetry chunk that exports `page.load`, `web_vital.*`, and same-origin `/api/` fetch spans to Honeycomb. An allowlist removes every other attribute before export. **Alternatives considered** `@honeycombio/opentelemetry-web` was the first choice. Its defaults add the full page URL, query string, hash, referrer, and user agent to every span and to the resource, and it bundles log and metric pipelines. We would have to replace its exporter and remove most of its defaults. Plain OpenTelemetry web packages plus `web-vitals` are smaller and send only what we choose. Honeycomb needs only OTLP/HTTP and its ingest-key header. **Roadmap alignment** This is internal hosted-instance observability. It changes no product behavior and no self-hosted behavior. ## What Changed - `server/src/browser-tracing-config.ts`: resolves the browser tracing config. It returns `null` unless `isCloudManagedInstance()` is true and `PAPERCLIP_BROWSER_TRACES_ENDPOINT` is set. It accepts only a Honeycomb ingest key (`hcaik_` prefix), requires `https` (except loopback), and fails closed with one value-free warning on any invalid setting. Optional: `PAPERCLIP_BROWSER_TRACES_INGEST_KEY`, `_SAMPLE_RATE` (default 1), `_SERVICE_NAME` (default `paperclip-web`), `_ENVIRONMENT` (default `SENTRY_ENVIRONMENT`). - `GET /api/auth/get-session` adds `browserTracing` (config or `null`), the same delivery path as the front-end Sentry DSN. The shared `authSessionSchema` has the new optional field `browserTracingConfigSchema`. - `ui/src/lib/browser-tracing/page-load-recorder.ts` and `controller.ts` (main bundle, no OpenTelemetry imports): one `page.load` measurement per hard load (from navigation start) and per client navigation (from the history change). A measurement ends at the first painted frame where no full-page loading state is mounted and either every page-declared content signal is ready or no query without data is fetching. Redirects continue the measurement. A new navigation interrupts it. 30 s times out. The sample decision is made once per page session before any download. - `ui/src/components/PageLoadTracker.tsx`: `App` passes the same `<Route>` tree it renders, so every page is reported by route pattern (for example `/:companyPrefix/issues/:issueId`) with no per-page code. - `usePageContentReady` hook and blocking gates: `PaperclipLoading` (also the route `Suspense` fallback) blocks readiness. The task page uses the existing `issue-detail:navigate→content-paint` point. The plain all-tasks list signals when its first rows render. - `ui/src/lib/browser-tracing/sdk.ts` (lazy chunk, loaded after the page settles): OpenTelemetry web tracer, OTLP/HTTP exporter, fetch instrumentation for this origin's `/api/` only with `traceparent` sent only to this origin, `web-vitals` LCP/INP/CLS, and a context manager that makes the open `page.load` span the parent of its API calls. `span-sanitizer.ts` applies the closed attribute allowlist (no URLs, ids, query strings, status messages, or event attributes). Uncaught errors are not sent because Sentry already reports them. - New `ui` dev dependencies, pinned exactly. Each is needed, and the OpenTelemetry ones are the same versions the server already resolves: - `@opentelemetry/api@1.9.1` (already in the workspace): tracer and context API. - `@opentelemetry/sdk-trace-web@2.10.0`: the browser tracer provider, batch processor, and stack context manager. - `@opentelemetry/instrumentation-fetch@0.221.0`: fetch spans and `traceparent` injection. - `@opentelemetry/resources@2.10.0` (already a server dependency): the resource. - `@opentelemetry/otlp-transformer@0.221.0` (already a server dependency): OTLP JSON serialization for a 60-line `OtlpFetchExporter`. This replaces `@opentelemetry/exporter-trace-otlp-http`, which is a server optional peer: installing it in the workspace made the server's exact-version gate test see it as present. - `web-vitals@6.2.3`: LCP, INP, and CLS. All of them are in the lazy chunk only. The lockfile is not committed: `pr-trusted` rejects lockfile edits in pull requests, CI installs with `--no-frozen-lockfile` after the frozen attempt reports `ERR_PNPM_OUTDATED_LOCKFILE`, and the lockfile bot refreshes it after merge. - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for the three shared files (the session schema is part of the pinned public SDK surface; the contract must live in `packages/shared`). - Docs: new `doc/browser-performance-tracing.md` (enablement, config, key handling, span and attribute list, page-load definitions, example Honeycomb queries and an SLO SLI). Pointers in `doc/observability.md` and the Honeycomb tracing skill. - Two App routing tests mock `PageLoadTracker` because they render `App` without a `QueryClientProvider`. ## Verification - `pnpm verify` returns exit 2 (broader verification required) because docs are global CI inputs. Required CI supplies the broad coverage. - Focused local tests, all pass: - `ui`: `vitest run src/lib/browser-tracing src/components/PageLoadTracker.test.tsx src/components/SentryGate.test.tsx src/api/auth.test.ts src/lib/issue-detail-performance src/pages/IssueDetail src/pages/Issues src/App src/components/CloudAccessGate.test.tsx src/components/IssuesList`: 17 files, 484 tests. - `server`: `browser-tracing-config.test.ts`, `auth-routes.test.ts`, `sentry.test.ts`: 63 passed, 5 skipped. - `packages/shared`: `validators/access.test.ts`: 19 passed. - New tests prove: the SDK module is never imported when the session config is `null`, absent, or signed out, or when the session is not sampled; route templates contain no ids, slugs, or tokens; a client navigation produces a `client` measurement under `/:companyPrefix/issues/:issueId`; `traceparent` goes only to this origin's `/api/` and not to a third-party or non-API URL; exported spans carry only allowlisted attributes. A mutation check (tracker forced on) turned the "never imports" tests red. - Typecheck: `ui` (`pnpm typecheck`), `server` (`pnpm --filter @paperclipai/server typecheck`), and `packages/shared` pass. - Real-browser run: a local dev server with a local OTLP collector and headless Chromium. The self-hosted session returned `browserTracing: null` with the endpoint set, and the page made 0 SDK and 0 collector requests. With a cloud session config injected into the session response, the collector received a hard `page.load` (route `/:companyPrefix/issues`, `ready_signal=idle`), a client `page.load` to `/:companyPrefix/issues/:issueId` (`ready_signal=content`), a back navigation, LCP/INP/CLS spans, and `/api/` fetch spans parented to the open `page.load` span. No task identifier, company id, task title, host, or URL appeared in the exported payload. No third-party request carried `traceparent`. - Bundle size (`ui` production build, initial JavaScript closure of `index.html`): before 3,813,986 B raw / 1,153,991 B gzip; after 3,820,743 B / 1,156,590 B (+6.8 KB raw, +2.6 KB gzip, +0.2%). The lazy SDK chunk is 84 KB raw / 27 KB gzip and is not fetched unless tracing is on and sampled. - Review fixes (each red on the old code, green on the new): the SDK now loads by a 35 s deadline even if the page never settles, so a timed-out hard load is exported (`controller.test.ts`); an agent chat with no saved task uses the idle rule instead of a content gate that never fires (`usePageContentReady.test.tsx`); the sample rate is rounded to exactly 1/N so Honeycomb's `SampleRate` weight matches (`browser-tracing-config.test.ts`). The real-browser run was repeated after the exporter change with the same result. ## Risks - Low risk for self-hosted installs: the server never sends a config, so no tracing code beyond the small recorder runs, and the SDK chunk is never fetched. - On hosted instances the feature is off until an operator sets `PAPERCLIP_BROWSER_TRACES_ENDPOINT` and an ingest key. When on, the controller wraps `history.pushState`/`replaceState` to time navigation starts and restores them on sign-out. - Every signed-in browser can read the ingest key, like the Sentry DSN. Only Honeycomb ingest keys (send-only) are accepted. A collector endpoint can keep the key server-side. - Hard-load API calls happen before the SDK loads, so they have no fetch spans. The hard-load `page.load` span is still recorded. - The browser-to-server trace join needs server tracing. The hosted image does not install the OpenTelemetry server peers today (`CLOUD_BUNDLED_SERVER_DEPS` is `@sentry/node` only). Browser spans work without it. - `ui/src/pages/IssueDetail.tsx` was already over 1,000 lines. This change adds 5 lines there for the task page content signal, next to the existing content-paint measure. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) via Claude Code, with tool use (shell, file edits, local browser automation). Reasoning effort: low. ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
8990e94005
commit
eaef46b60b
35 files changed
+2408
-8
No files matched your search
@@ -19,6 +19,7 @@ replaying tasks, changing credentials, or deploying instrumentation.
|
||||
| --- | --- |
|
||||
| Why is a task slow before, during, or after model execution? | Application workflow below; [runtime setup](references/runtime.md) if spans are absent |
|
||||
| Why does an issue page load slowly? | Request spans plus browser timing, described below |
|
||||
| What is a page's real-user load time or SLO on a hosted instance? | Browser `page.load` spans in [browser performance tracing](../../../doc/browser-performance-tracing.md) |
|
||||
| Which CI jobs or test files delay the whole suite? | [CI profiling](references/ci.md) |
|
||||
| How should a trace be organized so a person can understand it? | Human-readable waterfall guidance below and [trace design](references/trace-design.md) |
|
||||
| Where should a new span go? | Instrumentation guidance below and [Observability contract](../../../doc/observability.md) |
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
# Browser Performance Tracing
|
||||
|
||||
The board UI can send real-user page-load measurements, Core Web Vitals, and
|
||||
API request spans to Honeycomb (or any OTLP/HTTP collector). The data answers
|
||||
questions such as "what is the P95 time to load the all-tasks page?" and can
|
||||
back a Honeycomb SLO with an owner.
|
||||
|
||||
This is part of the operator-gated Observability path (see
|
||||
[observability.md](observability.md) and `rules/data-paths.mdc`). It is not the
|
||||
first-party Telemetry system and adds no Telemetry events.
|
||||
|
||||
## Who gets it
|
||||
|
||||
Browser tracing runs **only on hosted Paperclip Cloud instances** that an
|
||||
operator explicitly configures. It is off by default.
|
||||
|
||||
The server decides, in `server/src/browser-tracing-config.ts`. It sends a
|
||||
`browserTracing` object in the authenticated `GET /api/auth/get-session`
|
||||
response only when both hold:
|
||||
|
||||
1. The instance is cloud managed (`isCloudManagedInstance`: a
|
||||
`PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` or a `PAPERCLIP_MANAGED_CONFIG`
|
||||
document is present).
|
||||
2. `PAPERCLIP_BROWSER_TRACES_ENDPOINT` is set and every setting is valid.
|
||||
|
||||
Otherwise the field is `null`. Self-hosted installs, local development, and
|
||||
tests never satisfy (1). With `null`, or with no session (signed out), the
|
||||
browser never downloads the tracing code: it lives in its own lazily loaded
|
||||
chunk (`ui/src/lib/browser-tracing/sdk.ts`). An invalid setting fails closed:
|
||||
the field is `null` and the server logs one warning naming the variable, never
|
||||
its value.
|
||||
|
||||
## Configuration
|
||||
|
||||
Set these on the hosted server process:
|
||||
|
||||
| Variable | Required | Default | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| `PAPERCLIP_BROWSER_TRACES_ENDPOINT` | yes | — | OTLP/HTTP base URL, for example `https://api.honeycomb.io` (US) or `https://api.eu1.honeycomb.io` (EU). `/v1/traces` is appended unless the path already ends with it. Must be `https` (plain `http` only for a loopback host). |
|
||||
| `PAPERCLIP_BROWSER_TRACES_INGEST_KEY` | for Honeycomb | — | A Honeycomb **ingest** key (prefix `hcaik_`). Sent as `x-honeycomb-team`. Required when the endpoint is a Honeycomb host; optional for a collector you run. Any other key format is refused. |
|
||||
| `PAPERCLIP_BROWSER_TRACES_SAMPLE_RATE` | no | `1` | Fraction of page sessions traced, `0`–`1`, rounded to an exact 1 in N (`0.3` becomes 1/3; `0.75` becomes 1). `0` turns tracing off. |
|
||||
| `PAPERCLIP_BROWSER_TRACES_SERVICE_NAME` | no | `paperclip-web` | `service.name`; in Honeycomb this is the dataset name. |
|
||||
| `PAPERCLIP_BROWSER_TRACES_ENVIRONMENT` | no | `SENTRY_ENVIRONMENT` | `deployment.environment.name`, for example `staging`. |
|
||||
|
||||
### Key handling
|
||||
|
||||
Every signed-in browser can read the key, the same way it can read the
|
||||
front-end Sentry DSN. That is why only a Honeycomb **ingest** key is accepted:
|
||||
it can send events but cannot read data or change the Honeycomb account. Use a
|
||||
key scoped to the environment that should receive browser data, keep it in the
|
||||
hosting secret store, and never commit it. To keep the key out of browsers
|
||||
entirely, point the endpoint at an OTLP collector you run (it adds the key) and
|
||||
leave `PAPERCLIP_BROWSER_TRACES_INGEST_KEY` unset. That collector must allow
|
||||
CORS `POST` from the instance origin with the `content-type` header.
|
||||
|
||||
### Sampling
|
||||
|
||||
The sample decision is made once per page session (one tab load), before the
|
||||
SDK downloads. An unsampled session downloads and sends nothing. A sampled
|
||||
session sends everything, so each trace is complete. When the rate is below 1,
|
||||
every span carries Honeycomb's `SampleRate` attribute (1 in N, for example `4`
|
||||
for `0.25`), so Honeycomb's `COUNT` and percentiles are weighted correctly.
|
||||
|
||||
Volume per sampled session: one `page.load` span per navigation, up to three
|
||||
`web_vital.*` spans per page lifetime, and one span per same-origin `/api/`
|
||||
request made after the SDK loads.
|
||||
|
||||
## Load-speed cost
|
||||
|
||||
Nothing loads on the critical path. The main bundle carries only the
|
||||
measurement code (route matching, readiness checks); on the `ui` build of this
|
||||
change the initial JavaScript grew by about 6.8 KB raw / 2.6 KB gzip (0.2%). The
|
||||
OpenTelemetry SDK, a small OTLP JSON exporter, fetch instrumentation, and
|
||||
`web-vitals` are a separate chunk (about 84 KB raw / 27 KB gzip) fetched only when tracing is on
|
||||
and the session is sampled, and only after the page settles (painted, no query
|
||||
fetching, browser idle; `ui/src/lib/when-page-settles.ts`). If the page never
|
||||
settles (for example a request hangs), the chunk loads 35 seconds after tracing
|
||||
starts anyway, so a hard load that ended as `timeout` is still exported.
|
||||
|
||||
Because the SDK loads after the first page settles, API requests made during
|
||||
the hard load have no fetch spans. The hard load's `page.load` span is still
|
||||
recorded: measurements taken before the SDK loads are buffered and exported
|
||||
when it arrives.
|
||||
|
||||
## What "loaded" means
|
||||
|
||||
Each navigation produces one `page.load` span. It ends at the first animation
|
||||
frame, held for two consecutive frames, in which:
|
||||
|
||||
1. no full-page loading state is mounted (the `PaperclipLoading` spinner, which
|
||||
is also the route `Suspense` fallback), and
|
||||
2. one of:
|
||||
- **Content signal** (`ready_signal = content`): when the page declared a
|
||||
primary-content signal with `usePageContentReady`, every declared signal
|
||||
is ready. The end time is the paint time the page reported.
|
||||
- **Idle signal** (`ready_signal = idle`): otherwise, no React Query query
|
||||
that has no data yet is fetching. Background refetches of data already on
|
||||
screen do not count. The end time is the first such frame.
|
||||
|
||||
The rule lives in one place (`ui/src/lib/browser-tracing/page-load-recorder.ts`)
|
||||
and the route comes from the router's own route tree (`App.tsx` passes the tree
|
||||
it renders to `PageLoadTracker`), so a new page is measured without page code.
|
||||
|
||||
- **Hard load** (`load_type = hard`): starts at navigation start (the
|
||||
document request, time 0) and includes HTML, JavaScript download and start
|
||||
up, authentication, and the page's data and render. Redirects during the load
|
||||
(for example `/` to `/:companyPrefix/dashboard`) keep the same span, reported
|
||||
under the final route.
|
||||
- **Client navigation** (`load_type = client`): starts when the URL path
|
||||
changes in history (a link click, `navigate()`, or back/forward) and includes
|
||||
lazy route code download, data loading, and render. Query-string and hash
|
||||
changes are not navigations. A history replace while a navigation is still
|
||||
open is a redirect and continues it.
|
||||
|
||||
Outcomes: `ready`; `interrupted` (another navigation started first); `timeout`
|
||||
(not ready after 30 seconds). A navigation open when the tab closes is not
|
||||
sent. `was_hidden = true` means the tab was hidden during the measurement;
|
||||
browsers pause rendering in hidden tabs, so exclude these from SLOs.
|
||||
|
||||
Pages with an explicit content signal:
|
||||
|
||||
| Page | Route | Loaded when |
|
||||
| --- | --- | --- |
|
||||
| Task (issue) page | `/:companyPrefix/issues/:issueId` | The conversation content has painted: the same point as the `issue-detail:navigate→content-paint` User Timing measure. |
|
||||
| All-tasks list (plain task list) | `/:companyPrefix/issues` | The first page of task rows has rendered (or the list shows its error state). The combined inbox and coordinator task views use the idle signal. |
|
||||
|
||||
An agent chat with no saved task has no content signal and uses the idle rule.
|
||||
|
||||
To add one, call `usePageContentReady(ready)` in the page component. Use it
|
||||
only when the idle rule is inaccurate for that page.
|
||||
|
||||
## Emitted spans
|
||||
|
||||
All spans pass through an allowlist (`ui/src/lib/browser-tracing/span-sanitizer.ts`)
|
||||
before export. Any other attribute an instrumentation adds, including full
|
||||
URLs, server addresses, status messages, and event attributes, is dropped.
|
||||
|
||||
| Span name | When |
|
||||
| --- | --- |
|
||||
| `page.load` | One per hard load or client navigation. |
|
||||
| `web_vital.lcp`, `web_vital.inp`, `web_vital.cls` | Core Web Vitals, from Google's `web-vitals`, usually reported as the tab hides. Zero duration; the value is an attribute. |
|
||||
| `GET`, `POST`, … | A `fetch` to this origin's `/api/`. Its `traceparent` header joins the server's request span to the same trace. While a `page.load` span is open it is the parent, so one trace shows the navigation, its API calls, and (when server tracing is on) their server spans. |
|
||||
|
||||
Attributes (the complete allowlist):
|
||||
|
||||
| Attribute | On | Values |
|
||||
| --- | --- | --- |
|
||||
| `paperclip.page.route` | all | Route pattern, for example `/:companyPrefix/issues/:issueId`; `(unmatched)` when no route matches. Built only from route definitions, never from the URL. On fetch spans: the route current when the request started. On `web_vital.lcp`: the hard load's route. |
|
||||
| `paperclip.page.load_type` | `page.load` | `hard`, `client` |
|
||||
| `paperclip.page.outcome` | `page.load` | `ready`, `interrupted`, `timeout` |
|
||||
| `paperclip.page.ready_signal` | `page.load` | `content`, `idle`, `none` |
|
||||
| `paperclip.page.was_hidden` | `page.load` | boolean |
|
||||
| `paperclip.page.navigation_type` | hard `page.load` | `navigate`, `reload`, `back_forward`, `prerender` |
|
||||
| `paperclip.page.ttfb_ms`, `paperclip.page.dom_content_loaded_ms`, `paperclip.page.load_event_ms` | hard `page.load` | Navigation Timing milestones, ms from navigation start |
|
||||
| `paperclip.web_vital.name` | `web_vital.*` | `LCP`, `INP`, `CLS` |
|
||||
| `paperclip.web_vital.value` | `web_vital.*` | ms for LCP and INP; unitless for CLS |
|
||||
| `paperclip.web_vital.rating` | `web_vital.*` | `good`, `needs-improvement`, `poor` |
|
||||
| `paperclip.api.area` | fetch | First path segment after `/api/` when it is a fixed word (`issues`, `companies`, …), else `other`. Use the joined server span's route for detail. |
|
||||
| `http.request.method`, `http.response.status_code`, `error.type` | fetch | OpenTelemetry HTTP semantics |
|
||||
| `SampleRate` | all, when sampling | 1-in-N weight |
|
||||
|
||||
Resource: `service.name`, `service.version` (the UI build commit),
|
||||
`deployment.environment.name`.
|
||||
|
||||
Not sent: URLs, paths with ids, query strings, hashes, referrers, user agent,
|
||||
user, company, or task identifiers, titles, or content. Server spans carry no
|
||||
company identifier, so browser spans do not either. Uncaught browser errors are
|
||||
not sent here because Sentry already reports them
|
||||
([observability.md](observability.md#sentry-error-monitoring)).
|
||||
|
||||
Trace headers go only to this origin (`propagateTraceHeaderCorsUrls` is empty),
|
||||
so no third party receives a `traceparent`. Same-origin requests need no CORS
|
||||
change. The server's OpenTelemetry HTTP instrumentation continues the trace
|
||||
when server tracing is enabled ([observability.md](observability.md#enabling-tracing)).
|
||||
|
||||
## Example Honeycomb queries
|
||||
|
||||
Use the `paperclip-web` dataset (or your `service.name`) and the environment
|
||||
that holds browser data. Exclude hidden tabs and unfinished loads.
|
||||
|
||||
**P95 load time of the all-tasks page**
|
||||
|
||||
```text
|
||||
VISUALIZE P95(duration_ms), COUNT
|
||||
WHERE name = page.load
|
||||
paperclip.page.route = /:companyPrefix/issues
|
||||
paperclip.page.outcome = ready
|
||||
paperclip.page.was_hidden = false
|
||||
GROUP BY paperclip.page.load_type
|
||||
```
|
||||
|
||||
**P95 load time of an individual task page**
|
||||
|
||||
```text
|
||||
VISUALIZE P95(duration_ms), COUNT
|
||||
WHERE name = page.load
|
||||
paperclip.page.route = /:companyPrefix/issues/:issueId
|
||||
paperclip.page.outcome = ready
|
||||
paperclip.page.was_hidden = false
|
||||
GROUP BY paperclip.page.load_type
|
||||
```
|
||||
|
||||
Group by `service.version` to compare builds. For a timeout rate, count
|
||||
`paperclip.page.outcome = timeout` against all `page.load` spans for the route.
|
||||
For Web Vitals, `P75(paperclip.web_vital.value)` where
|
||||
`name = web_vital.lcp` (or `inp`, `cls`), grouped by `paperclip.page.route`.
|
||||
|
||||
**SLO.** A Honeycomb SLO needs a boolean SLI as a derived column. For example,
|
||||
"task page loads within 2 s":
|
||||
|
||||
```text
|
||||
IF(AND(EQUALS($name, "page.load"),
|
||||
EQUALS($paperclip.page.route, "/:companyPrefix/issues/:issueId"),
|
||||
EQUALS($paperclip.page.was_hidden, false)),
|
||||
AND(EQUALS($paperclip.page.outcome, "ready"), LTE($duration_ms, 2000)))
|
||||
```
|
||||
|
||||
The expression is null for other events, so they do not count.
|
||||
|
||||
## Verifying a deployment
|
||||
|
||||
1. Set the variables above and deploy. A cloud-managed instance logs nothing on
|
||||
success; an invalid setting logs one `browser tracing is off` warning.
|
||||
2. Sign in, open the browser network panel, and confirm the session response
|
||||
carries `browserTracing`, a `sdk-*.js` chunk loads after the page settles,
|
||||
and a `POST` to `…/v1/traces` returns 200.
|
||||
3. In Honeycomb, query `name = page.load` in the browser dataset for the last
|
||||
10 minutes and check `paperclip.page.route` and `service.version`.
|
||||
@@ -124,6 +124,17 @@ Use Chrome's request waterfall and this mark together to distinguish API wait,
|
||||
request dependencies, and rendering time. A hard-load trace also includes auth,
|
||||
company selection, and JavaScript startup before the task navigation mark.
|
||||
|
||||
## Browser performance tracing
|
||||
|
||||
Hosted Paperclip Cloud instances can also trace the board UI in the browser:
|
||||
a `page.load` span for every hard load and client-side navigation (named by
|
||||
route pattern), Core Web Vitals, and same-origin API request spans whose W3C
|
||||
trace context joins the server spans above. It is off unless the instance is
|
||||
cloud managed and `PAPERCLIP_BROWSER_TRACES_ENDPOINT` is set; self-hosted
|
||||
installs never download the browser SDK. Configuration, the closed attribute
|
||||
allowlist, the page-load definitions, and example queries are in
|
||||
[browser-performance-tracing.md](browser-performance-tracing.md).
|
||||
|
||||
## Enabling tracing
|
||||
|
||||
### 1. Install the OTel peer dependencies
|
||||
|
||||
@@ -2419,6 +2419,7 @@ export {
|
||||
createBoardApiKeySchema,
|
||||
currentUserProfileSchema,
|
||||
authSessionSchema,
|
||||
browserTracingConfigSchema,
|
||||
updateCurrentUserProfileSchema,
|
||||
updateCompanyMemberSchema,
|
||||
updateCompanyMemberWithPermissionsSchema,
|
||||
@@ -2444,6 +2445,7 @@ export {
|
||||
type CreateBoardApiKey,
|
||||
type CurrentUserProfile,
|
||||
type AuthSession,
|
||||
type BrowserTracingConfig,
|
||||
type UpdateCurrentUserProfile,
|
||||
type UpdateCompanyMember,
|
||||
type UpdateCompanyMemberWithPermissions,
|
||||
|
||||
@@ -199,6 +199,23 @@ export const currentUserProfileSchema = z.object({
|
||||
|
||||
export type CurrentUserProfile = z.infer<typeof currentUserProfileSchema>;
|
||||
|
||||
/**
|
||||
* Browser performance tracing settings for a hosted Paperclip Cloud instance.
|
||||
* The server sends a value only when the instance is cloud managed and an
|
||||
* operator configured an endpoint; see `doc/browser-performance-tracing.md`.
|
||||
* `ingestKey` is a Honeycomb ingest-only key (or null for a collector that
|
||||
* needs no key); it is never a configuration key.
|
||||
*/
|
||||
export const browserTracingConfigSchema = z.object({
|
||||
tracesUrl: z.string().url(),
|
||||
ingestKey: z.string().min(1).nullable(),
|
||||
serviceName: z.string().min(1),
|
||||
environment: z.string().min(1).nullable(),
|
||||
sampleRate: z.number().gt(0).max(1),
|
||||
});
|
||||
|
||||
export type BrowserTracingConfig = z.infer<typeof browserTracingConfigSchema>;
|
||||
|
||||
export const authSessionSchema = z.object({
|
||||
session: z.object({
|
||||
id: z.string().min(1),
|
||||
@@ -214,6 +231,9 @@ export const authSessionSchema = z.object({
|
||||
sentryDsn: z.string().min(1).nullable(),
|
||||
// Optional for browser/server version skew; null leaves the SDK default.
|
||||
sentryEnvironment: z.string().nullable().optional(),
|
||||
// Null or absent leaves browser performance tracing off. Optional for
|
||||
// browser/server version skew.
|
||||
browserTracing: browserTracingConfigSchema.nullable().optional(),
|
||||
});
|
||||
|
||||
export type AuthSession = z.infer<typeof authSessionSchema>;
|
||||
|
||||
@@ -774,6 +774,7 @@ export {
|
||||
createBoardApiKeySchema,
|
||||
currentUserProfileSchema,
|
||||
authSessionSchema,
|
||||
browserTracingConfigSchema,
|
||||
updateCurrentUserProfileSchema,
|
||||
updateCompanyMemberSchema,
|
||||
updateCompanyMemberWithPermissionsSchema,
|
||||
@@ -795,6 +796,7 @@ export {
|
||||
type CreateBoardApiKey,
|
||||
type CurrentUserProfile,
|
||||
type AuthSession,
|
||||
type BrowserTracingConfig,
|
||||
type UpdateCurrentUserProfile,
|
||||
type UpdateCompanyMember,
|
||||
type UpdateCompanyMemberWithPermissions,
|
||||
|
||||
@@ -95,6 +95,7 @@ describe("auth routes", () => {
|
||||
user: baseUser,
|
||||
sentryDsn: null,
|
||||
sentryEnvironment: null,
|
||||
browserTracing: null,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { authSessionSchema } from "@paperclipai/shared";
|
||||
import { browserTracesUrl, resolveBrowserTracingConfig } from "../browser-tracing-config.js";
|
||||
|
||||
const cloud = { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token" };
|
||||
const ingestKey = "hcaik_" + "0".repeat(58);
|
||||
|
||||
describe("resolveBrowserTracingConfig", () => {
|
||||
it("is off for a self-hosted instance even with every variable set", () => {
|
||||
expect(resolveBrowserTracingConfig({
|
||||
PAPERCLIP_BROWSER_TRACES_ENDPOINT: "https://api.honeycomb.io",
|
||||
PAPERCLIP_BROWSER_TRACES_INGEST_KEY: ingestKey,
|
||||
})).toBeNull();
|
||||
});
|
||||
|
||||
it("is off for a cloud instance with no endpoint", () => {
|
||||
expect(resolveBrowserTracingConfig({ ...cloud, PAPERCLIP_BROWSER_TRACES_INGEST_KEY: ingestKey })).toBeNull();
|
||||
});
|
||||
|
||||
it("is on for a cloud instance with an endpoint and ingest key, with defaults", () => {
|
||||
const config = resolveBrowserTracingConfig({
|
||||
...cloud,
|
||||
PAPERCLIP_BROWSER_TRACES_ENDPOINT: "https://api.honeycomb.io",
|
||||
PAPERCLIP_BROWSER_TRACES_INGEST_KEY: ingestKey,
|
||||
SENTRY_ENVIRONMENT: "staging",
|
||||
});
|
||||
expect(config).toEqual({
|
||||
tracesUrl: "https://api.honeycomb.io/v1/traces",
|
||||
ingestKey,
|
||||
serviceName: "paperclip-web",
|
||||
environment: "staging",
|
||||
sampleRate: 1,
|
||||
});
|
||||
expect(authSessionSchema.shape.browserTracing.parse(config)).toEqual(config);
|
||||
});
|
||||
|
||||
it("also recognises the managed-config cloud signal", () => {
|
||||
expect(resolveBrowserTracingConfig({
|
||||
PAPERCLIP_MANAGED_CONFIG: "{}",
|
||||
PAPERCLIP_BROWSER_TRACES_ENDPOINT: "https://collector.example.com/otlp",
|
||||
PAPERCLIP_BROWSER_TRACES_SAMPLE_RATE: "0.25",
|
||||
PAPERCLIP_BROWSER_TRACES_SERVICE_NAME: "board",
|
||||
PAPERCLIP_BROWSER_TRACES_ENVIRONMENT: "production",
|
||||
})).toEqual({
|
||||
tracesUrl: "https://collector.example.com/otlp/v1/traces",
|
||||
ingestKey: null,
|
||||
serviceName: "board",
|
||||
environment: "production",
|
||||
sampleRate: 0.25,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a configuration key", { PAPERCLIP_BROWSER_TRACES_INGEST_KEY: "51GYc2configkey00000000" }, "INGEST_KEY is not a Honeycomb ingest key"],
|
||||
["Honeycomb with no key", { PAPERCLIP_BROWSER_TRACES_INGEST_KEY: undefined }, "INGEST_KEY is required"],
|
||||
["plain http", { PAPERCLIP_BROWSER_TRACES_ENDPOINT: "http://api.honeycomb.io" }, "must use https"],
|
||||
["a malformed endpoint", { PAPERCLIP_BROWSER_TRACES_ENDPOINT: "not a url" }, "not a valid URL"],
|
||||
["a malformed sample rate", { PAPERCLIP_BROWSER_TRACES_SAMPLE_RATE: "10%" }, "SAMPLE_RATE must be a number"],
|
||||
["an out-of-range sample rate", { PAPERCLIP_BROWSER_TRACES_SAMPLE_RATE: "2" }, "SAMPLE_RATE must be a number"],
|
||||
])("fails closed with a value-free warning for %s", (_label, override, warning) => {
|
||||
const warn = vi.fn();
|
||||
expect(resolveBrowserTracingConfig({
|
||||
...cloud,
|
||||
PAPERCLIP_BROWSER_TRACES_ENDPOINT: "https://api.honeycomb.io",
|
||||
PAPERCLIP_BROWSER_TRACES_INGEST_KEY: ingestKey,
|
||||
...override,
|
||||
}, warn)).toBeNull();
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
expect(warn.mock.calls[0]![0]).toContain(warning);
|
||||
expect(warn.mock.calls[0]![0]).not.toContain(ingestKey);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["0.3", 1 / 3],
|
||||
["0.75", 1],
|
||||
["0.1", 0.1],
|
||||
["0.25", 0.25],
|
||||
])("rounds sample rate %s to an exact 1-in-N rate so Honeycomb weights stay correct", (raw, expected) => {
|
||||
expect(resolveBrowserTracingConfig({
|
||||
...cloud,
|
||||
PAPERCLIP_BROWSER_TRACES_ENDPOINT: "https://api.honeycomb.io",
|
||||
PAPERCLIP_BROWSER_TRACES_INGEST_KEY: ingestKey,
|
||||
PAPERCLIP_BROWSER_TRACES_SAMPLE_RATE: raw,
|
||||
})?.sampleRate).toBeCloseTo(expected, 12);
|
||||
});
|
||||
|
||||
it("treats a zero sample rate as off", () => {
|
||||
expect(resolveBrowserTracingConfig({
|
||||
...cloud,
|
||||
PAPERCLIP_BROWSER_TRACES_ENDPOINT: "https://api.honeycomb.io",
|
||||
PAPERCLIP_BROWSER_TRACES_INGEST_KEY: ingestKey,
|
||||
PAPERCLIP_BROWSER_TRACES_SAMPLE_RATE: "0",
|
||||
})).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("browserTracesUrl", () => {
|
||||
it("appends the OTLP traces path once and drops query and hash", () => {
|
||||
expect(browserTracesUrl(new URL("https://api.eu1.honeycomb.io/"))).toBe("https://api.eu1.honeycomb.io/v1/traces");
|
||||
expect(browserTracesUrl(new URL("https://collector.example.com/v1/traces?x=1#y"))).toBe("https://collector.example.com/v1/traces");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
// Resolves the browser performance tracing settings that the authenticated
|
||||
// session hands to the board UI. See doc/browser-performance-tracing.md.
|
||||
//
|
||||
// Browser tracing is for hosted Paperclip Cloud instances only. It stays off
|
||||
// (`null`) unless both hold:
|
||||
// 1. the instance is cloud managed (`isCloudManagedInstance`), and
|
||||
// 2. an operator set `PAPERCLIP_BROWSER_TRACES_ENDPOINT`.
|
||||
// Self-hosted installs, local development, and tests never match (1), so the
|
||||
// browser never downloads the tracing SDK there.
|
||||
//
|
||||
// Every invalid setting fails closed: the browser receives `null` and the
|
||||
// server logs one warning naming the variable, never its value.
|
||||
|
||||
import type { BrowserTracingConfig } from "@paperclipai/shared";
|
||||
import { isCloudManagedInstance, type CloudInstanceEnv } from "./services/cloud-instance.js";
|
||||
|
||||
export const BROWSER_TRACES_DEFAULT_SERVICE_NAME = "paperclip-web";
|
||||
export const BROWSER_TRACES_DEFAULT_SAMPLE_RATE = 1;
|
||||
|
||||
/** Honeycomb ingest keys carry this prefix; configuration keys never do. */
|
||||
const HONEYCOMB_INGEST_KEY_PREFIX = "hcaik_";
|
||||
|
||||
export type BrowserTracingWarning = (message: string) => void;
|
||||
|
||||
function normalize(value: string | undefined): string | null {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
function isLoopbackHost(hostname: string): boolean {
|
||||
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
||||
}
|
||||
|
||||
function isHoneycombHost(hostname: string): boolean {
|
||||
return hostname === "honeycomb.io" || hostname.endsWith(".honeycomb.io");
|
||||
}
|
||||
|
||||
/** OTLP/HTTP convention: a base URL gets `/v1/traces` appended. */
|
||||
export function browserTracesUrl(endpoint: URL): string {
|
||||
const url = new URL(endpoint.href);
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
if (!url.pathname.endsWith("/v1/traces")) {
|
||||
url.pathname = `${url.pathname.replace(/\/+$/, "")}/v1/traces`;
|
||||
}
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export function resolveBrowserTracingConfig(
|
||||
env: CloudInstanceEnv = process.env,
|
||||
warn: BrowserTracingWarning = () => {},
|
||||
): BrowserTracingConfig | null {
|
||||
if (!isCloudManagedInstance(env)) return null;
|
||||
|
||||
const rawEndpoint = normalize(env.PAPERCLIP_BROWSER_TRACES_ENDPOINT);
|
||||
if (!rawEndpoint) return null;
|
||||
|
||||
let endpoint: URL;
|
||||
try {
|
||||
endpoint = new URL(rawEndpoint);
|
||||
} catch {
|
||||
warn("PAPERCLIP_BROWSER_TRACES_ENDPOINT is not a valid URL; browser tracing is off");
|
||||
return null;
|
||||
}
|
||||
// A browser on an https page cannot post to plain http (mixed content).
|
||||
if (endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && isLoopbackHost(endpoint.hostname))) {
|
||||
warn("PAPERCLIP_BROWSER_TRACES_ENDPOINT must use https; browser tracing is off");
|
||||
return null;
|
||||
}
|
||||
|
||||
const ingestKey = normalize(env.PAPERCLIP_BROWSER_TRACES_INGEST_KEY);
|
||||
// The key is readable by every signed-in browser, so only an ingest-only
|
||||
// key may ship. A configuration key could change the Honeycomb account.
|
||||
if (ingestKey !== null && !ingestKey.startsWith(HONEYCOMB_INGEST_KEY_PREFIX)) {
|
||||
warn("PAPERCLIP_BROWSER_TRACES_INGEST_KEY is not a Honeycomb ingest key (hcaik_…); browser tracing is off");
|
||||
return null;
|
||||
}
|
||||
if (ingestKey === null && isHoneycombHost(endpoint.hostname)) {
|
||||
warn("PAPERCLIP_BROWSER_TRACES_INGEST_KEY is required to send browser traces to Honeycomb; browser tracing is off");
|
||||
return null;
|
||||
}
|
||||
|
||||
let sampleRate = BROWSER_TRACES_DEFAULT_SAMPLE_RATE;
|
||||
const rawSampleRate = normalize(env.PAPERCLIP_BROWSER_TRACES_SAMPLE_RATE);
|
||||
if (rawSampleRate !== null) {
|
||||
const parsed = Number(rawSampleRate);
|
||||
if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {
|
||||
warn("PAPERCLIP_BROWSER_TRACES_SAMPLE_RATE must be a number from 0 to 1; browser tracing is off");
|
||||
return null;
|
||||
}
|
||||
if (parsed === 0) return null;
|
||||
// Honeycomb weights events by an integer `SampleRate` (1 in N). Sample at
|
||||
// exactly 1/N so weighted counts stay correct: 0.3 becomes 1/3.
|
||||
sampleRate = 1 / Math.max(1, Math.round(1 / parsed));
|
||||
}
|
||||
|
||||
return {
|
||||
tracesUrl: browserTracesUrl(endpoint),
|
||||
ingestKey,
|
||||
serviceName: normalize(env.PAPERCLIP_BROWSER_TRACES_SERVICE_NAME) ?? BROWSER_TRACES_DEFAULT_SERVICE_NAME,
|
||||
environment: normalize(env.PAPERCLIP_BROWSER_TRACES_ENVIRONMENT) ?? normalize(env.SENTRY_ENVIRONMENT),
|
||||
sampleRate,
|
||||
};
|
||||
}
|
||||
|
||||
const warnedMessages = new Set<string>();
|
||||
|
||||
/** Logs each distinct configuration warning once per process. */
|
||||
export function warnOnce(log: (message: string) => void): BrowserTracingWarning {
|
||||
return (message) => {
|
||||
if (warnedMessages.has(message)) return;
|
||||
warnedMessages.add(message);
|
||||
log(message);
|
||||
};
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { unauthorized } from "../errors.js";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { resolveSentryDsns } from "../sentry-dsn.js";
|
||||
import { resolveBrowserTracingConfig, warnOnce } from "../browser-tracing-config.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { loadBoardBootstrap } from "../services/board-bootstrap.js";
|
||||
|
||||
@@ -37,6 +38,8 @@ async function loadCurrentUserProfile(db: Db, userId: string) {
|
||||
});
|
||||
}
|
||||
|
||||
const warnBrowserTracing = warnOnce((message) => logger.warn(message));
|
||||
|
||||
export function authRoutes(db: Db) {
|
||||
const router = Router();
|
||||
|
||||
@@ -67,6 +70,9 @@ export function authRoutes(db: Db) {
|
||||
sentryDsn: resolveSentryDsns().frontend,
|
||||
// Match the server SDK's runtime environment, including in reused images.
|
||||
sentryEnvironment: process.env.SENTRY_ENVIRONMENT || null,
|
||||
// Hosted Paperclip Cloud only; null everywhere else. The ingest key is
|
||||
// ingest-only by construction — see `server/src/browser-tracing-config.ts`.
|
||||
browserTracing: resolveBrowserTracingConfig(process.env, warnBrowserTracing),
|
||||
});
|
||||
res.json({ ...session, ...(boardBootstrap ? { boardBootstrap } : {}) });
|
||||
});
|
||||
|
||||
@@ -268,7 +268,7 @@
|
||||
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
|
||||
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
|
||||
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
|
||||
"packages/shared/src/index.ts": "f9865d8aa6a8a30239e9024ff191c6767857ba5a",
|
||||
"packages/shared/src/index.ts": "64a1b7056e3a6cee88b2a6794d2f32483c10f95c",
|
||||
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
|
||||
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
|
||||
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
|
||||
@@ -438,7 +438,7 @@
|
||||
"packages/shared/src/types/workspace-runtime.ts": "00ab237577d3ea3a1fa946ce6ab6ef8b389b1739",
|
||||
"packages/shared/src/types/workspace-source-verification.ts": "647f5c8817590629439813df5dc63750b316206d",
|
||||
"packages/shared/src/validators/access.test.ts": "0df0e096658a31c4f21462a992e38cf8bd7082b1",
|
||||
"packages/shared/src/validators/access.ts": "03d78d52b9a6f2de08ceb9dfc0c8ffccaad95362",
|
||||
"packages/shared/src/validators/access.ts": "eb1c2ab3cc6616477f6cf68d2745a1d1de16640e",
|
||||
"packages/shared/src/validators/adapter-auth-session.ts": "14cffbd7281265bf3f059bcf1b97739ebe0e1f81",
|
||||
"packages/shared/src/validators/adapter-registry.test.ts": "567c113e50dd0c0d259b095375f8f8f403ffa893",
|
||||
"packages/shared/src/validators/adapter-registry.ts": "6fb9f655d49f774ef7f082bf842f388f1187e545",
|
||||
@@ -481,7 +481,7 @@
|
||||
"packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67",
|
||||
"packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d",
|
||||
"packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b",
|
||||
"packages/shared/src/validators/index.ts": "768aa6d275a34ce08ba5d2efca38d26694dcf92e",
|
||||
"packages/shared/src/validators/index.ts": "a62024f564b768d87e9b8a2869c0b8b9ce92dc09",
|
||||
"packages/shared/src/validators/instance.test.ts": "3faa9593a9a05f74429d9b1d2251906a03e9a903",
|
||||
"packages/shared/src/validators/instance.ts": "d94ffda92ccacd3d9410562e2898410db1a100be",
|
||||
"packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645",
|
||||
|
||||
+7
-1
@@ -85,6 +85,11 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@lexical/rich-text": "0.48.0",
|
||||
"@opentelemetry/api": "1.9.1",
|
||||
"@opentelemetry/instrumentation-fetch": "0.221.0",
|
||||
"@opentelemetry/otlp-transformer": "0.221.0",
|
||||
"@opentelemetry/resources": "2.10.0",
|
||||
"@opentelemetry/sdk-trace-web": "2.10.0",
|
||||
"@paperclipai/plugin-sdk": "workspace:*",
|
||||
"@sentry/browser": "10.71.0",
|
||||
"@storybook/addon-a11y": "10.6.0",
|
||||
@@ -99,7 +104,8 @@
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^7.0.2",
|
||||
"vite": "^8.2.2",
|
||||
"vitest": "^5.0.3"
|
||||
"vitest": "^5.0.3",
|
||||
"web-vitals": "6.2.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.11.0"
|
||||
|
||||
@@ -59,6 +59,9 @@ vi.mock("./components/Layout.production", async () => {
|
||||
});
|
||||
|
||||
// Rendered by <App> outside <Routes> and needs DialogProvider; irrelevant here.
|
||||
// These routing tests render App without a QueryClientProvider.
|
||||
vi.mock("./components/PageLoadTracker", () => ({ PageLoadTracker: () => null }));
|
||||
|
||||
vi.mock("./components/OnboardingWizardVariant", () => ({
|
||||
OnboardingWizardVariant: () => null,
|
||||
}));
|
||||
|
||||
@@ -56,6 +56,9 @@ vi.mock("./components/CasesExperimentalGate", () => ({
|
||||
}));
|
||||
|
||||
// Rendered by <App> outside <Routes> and needs DialogProvider; irrelevant here.
|
||||
// These routing tests render App without a QueryClientProvider.
|
||||
vi.mock("./components/PageLoadTracker", () => ({ PageLoadTracker: () => null }));
|
||||
|
||||
vi.mock("./components/OnboardingWizardVariant", () => ({
|
||||
OnboardingWizardVariant: () => null,
|
||||
}));
|
||||
|
||||
+12
-4
@@ -20,6 +20,7 @@ import { useHiddenSettings } from "./hooks/useHiddenSettings";
|
||||
import { OnboardingWizardVariant } from "./components/OnboardingWizardVariant";
|
||||
import { CloudAccessGate } from "./components/CloudAccessGate";
|
||||
import { ConnectionStatusBanner } from "./components/ConnectionStatusBanner";
|
||||
import { PageLoadTracker } from "./components/PageLoadTracker";
|
||||
import { ShellConfigurationGate } from "./components/ShellConfigurationGate";
|
||||
import { PaperclipLoading } from "./components/AnimatedPaperclipIcon";
|
||||
import { AGENT_FILTER_TABS } from "./lib/agent-filter-tabs";
|
||||
@@ -775,10 +776,10 @@ export function App() {
|
||||
else if (/^\/[^/]+\/(issues|tasks)\/?$/.test(pathname)) void loadIssues().catch(() => undefined);
|
||||
}, [pathname]);
|
||||
|
||||
return (
|
||||
// One route tree for both the router and the page-load measurement, so
|
||||
// every page is measured under its route pattern.
|
||||
const routeTree = (
|
||||
<>
|
||||
<ConnectionStatusBanner />
|
||||
<Suspense fallback={<PaperclipLoading />}><Routes>
|
||||
<Route path="oauth-handoff" element={<PaperclipCloudOAuthHandoffPage />} />
|
||||
<Route path="auth" element={<AuthPage />} />
|
||||
<Route path="board-claim/:token" element={<BoardClaimPage />} />
|
||||
@@ -870,7 +871,14 @@ export function App() {
|
||||
<Route path="*" element={<NotFoundPage scope="global" />} />
|
||||
</Route>
|
||||
</Route>
|
||||
</Routes></Suspense>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ConnectionStatusBanner />
|
||||
<PageLoadTracker routes={routeTree} />
|
||||
<Suspense fallback={<PaperclipLoading />}><Routes>{routeTree}</Routes></Suspense>
|
||||
<OnboardingWizardVariant />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { SVGProps } from "react";
|
||||
import { cn } from "../lib/utils";
|
||||
import { useBlockingPageGate } from "../hooks/usePageContentReady";
|
||||
|
||||
export function AnimatedPaperclipIcon({ className, ...props }: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
@@ -24,6 +25,8 @@ export function AnimatedPaperclipIcon({ className, ...props }: SVGProps<SVGSVGEl
|
||||
|
||||
/** Full-page loading state: a large, centered, gray animated paperclip. */
|
||||
export function PaperclipLoading({ className }: { className?: string }) {
|
||||
// While a full-page loading state is on screen the page has not loaded.
|
||||
useBlockingPageGate();
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { MemoryRouter, Route, Routes, useNavigate } from "react-router-dom";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { BrowserTracingConfig } from "@paperclipai/shared";
|
||||
import type { PageLoadMeasurement, PageLoadRecorder } from "@/lib/browser-tracing/page-load-recorder";
|
||||
import { resetPageSessionSampleForTest } from "@/lib/browser-tracing/controller";
|
||||
import { PageLoadTracker } from "./PageLoadTracker";
|
||||
|
||||
const getSessionMock = vi.hoisted(() => vi.fn());
|
||||
const sdkModuleImported = vi.hoisted(() => vi.fn());
|
||||
const measurements = vi.hoisted(() => ({ begun: [] as PageLoadMeasurement[], ended: [] as PageLoadMeasurement[] }));
|
||||
|
||||
vi.mock("@/api/auth", () => ({
|
||||
authApi: { getSession: () => getSessionMock() },
|
||||
}));
|
||||
|
||||
// Records whether the tracing SDK chunk was ever imported; when it is, a
|
||||
// fake sink stands in for OpenTelemetry.
|
||||
vi.mock("@/lib/browser-tracing/sdk", () => {
|
||||
sdkModuleImported();
|
||||
return {
|
||||
startTracingSdk: (_config: BrowserTracingConfig, recorder: PageLoadRecorder) => {
|
||||
recorder.attachSink({
|
||||
begin: (measurement) => measurements.begun.push({ ...measurement }),
|
||||
end: (measurement) => measurements.ended.push({ ...measurement }),
|
||||
});
|
||||
return { forceFlush: async () => {}, shutdown: async () => {} };
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const config: BrowserTracingConfig = {
|
||||
tracesUrl: "https://api.honeycomb.io/v1/traces",
|
||||
ingestKey: "hcaik_test",
|
||||
serviceName: "paperclip-web",
|
||||
environment: "test",
|
||||
sampleRate: 1,
|
||||
};
|
||||
|
||||
function session(browserTracing?: BrowserTracingConfig | null) {
|
||||
return {
|
||||
session: { id: "s", userId: "u" },
|
||||
user: { id: "u", email: null, name: null, image: null },
|
||||
sentryDsn: null,
|
||||
...(browserTracing === undefined ? {} : { browserTracing }),
|
||||
};
|
||||
}
|
||||
|
||||
let navigateTo: ((path: string) => void) | null = null;
|
||||
function NavigateHandle() {
|
||||
navigateTo = useNavigate();
|
||||
return null;
|
||||
}
|
||||
|
||||
const Page = () => <div>page</div>;
|
||||
const routes = (
|
||||
<>
|
||||
<Route path=":companyPrefix" element={<Page />} />
|
||||
<Route path=":companyPrefix/issues" element={<Page />} />
|
||||
<Route path=":companyPrefix/issues/:issueId" element={<Page />} />
|
||||
</>
|
||||
);
|
||||
|
||||
describe("PageLoadTracker", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root | null = null;
|
||||
let queryClient: QueryClient;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
measurements.begun.length = 0;
|
||||
measurements.ended.length = 0;
|
||||
resetPageSessionSampleForTest();
|
||||
window.history.replaceState(null, "", "/PAP/issues");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
root = null;
|
||||
container.remove();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
async function render(initialPath: string) {
|
||||
root = createRoot(container);
|
||||
await act(async () => {
|
||||
root!.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[initialPath]}>
|
||||
<PageLoadTracker routes={routes} />
|
||||
<NavigateHandle />
|
||||
<Routes>{routes}</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function settle(ms = 400) {
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => window.setTimeout(resolve, ms));
|
||||
});
|
||||
}
|
||||
|
||||
it.each([
|
||||
["the server sends null (self-hosted, local dev, or no endpoint)", session(null)],
|
||||
["an older server omits the field", session()],
|
||||
["the browser is signed out", null],
|
||||
])("never imports the tracing SDK when %s", async (_label, payload) => {
|
||||
getSessionMock.mockResolvedValue(payload);
|
||||
await render("/PAP/issues");
|
||||
await settle();
|
||||
expect(sdkModuleImported).not.toHaveBeenCalled();
|
||||
expect(measurements.begun).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("measures the hard load and a client-side navigation under route templates", async () => {
|
||||
getSessionMock.mockResolvedValue(session(config));
|
||||
await render("/PAP/issues");
|
||||
await vi.waitFor(() => expect(measurements.ended).toHaveLength(1), { timeout: 3000 });
|
||||
expect(sdkModuleImported).toHaveBeenCalledTimes(1);
|
||||
expect(measurements.ended[0]).toMatchObject({
|
||||
routeTemplate: "/:companyPrefix/issues",
|
||||
loadType: "hard",
|
||||
startTime: 0,
|
||||
outcome: "ready",
|
||||
});
|
||||
|
||||
await act(async () => navigateTo!("/PAP/issues/PAP-4242"));
|
||||
await vi.waitFor(() => expect(measurements.ended).toHaveLength(2), { timeout: 3000 });
|
||||
const navigation = measurements.ended[1]!;
|
||||
expect(navigation).toMatchObject({
|
||||
routeTemplate: "/:companyPrefix/issues/:issueId",
|
||||
loadType: "client",
|
||||
outcome: "ready",
|
||||
readySignal: "idle",
|
||||
});
|
||||
expect(navigation.endTime).toBeGreaterThanOrEqual(navigation.startTime);
|
||||
expect(JSON.stringify(measurements)).not.toContain("PAP-4242");
|
||||
});
|
||||
|
||||
it("downloads nothing for an unsampled page session", async () => {
|
||||
vi.spyOn(Math, "random").mockReturnValue(0.9);
|
||||
getSessionMock.mockResolvedValue(session({ ...config, sampleRate: 0.5 }));
|
||||
await render("/PAP/issues");
|
||||
await settle();
|
||||
expect(sdkModuleImported).not.toHaveBeenCalled();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useLocation, useNavigationType } from "react-router-dom";
|
||||
import { authApi } from "@/api/auth";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import {
|
||||
startBrowserTracingController,
|
||||
type BrowserTracingController,
|
||||
} from "@/lib/browser-tracing/controller";
|
||||
import { routeTemplateForElements } from "@/lib/browser-tracing/route-template";
|
||||
|
||||
/**
|
||||
* Browser performance tracing for hosted Paperclip Cloud instances. Renders
|
||||
* nothing.
|
||||
*
|
||||
* It reads the signed-in session, like `SentryGate`. The server sends a
|
||||
* `browserTracing` config only for a cloud-managed instance with an operator
|
||||
* endpoint, so self-hosted installs, local development, and tests never start
|
||||
* the controller and never download the tracing SDK chunk. Sign-out clears the
|
||||
* session and stops tracing.
|
||||
*
|
||||
* `routes` is the same `<Route>` tree that `App` renders, so every page is
|
||||
* measured under its route pattern without per-page code.
|
||||
*/
|
||||
export function PageLoadTracker({ routes }: { routes: ReactNode }) {
|
||||
const queryClient = useQueryClient();
|
||||
const { data: session } = useQuery({
|
||||
queryKey: queryKeys.auth.session,
|
||||
queryFn: () => authApi.getSession(),
|
||||
});
|
||||
const config = session?.browserTracing ?? null;
|
||||
const configKey = config ? JSON.stringify(config) : null;
|
||||
const location = useLocation();
|
||||
const navigationType = useNavigationType();
|
||||
const routesRef = useRef(routes);
|
||||
routesRef.current = routes;
|
||||
const controllerRef = useRef<BrowserTracingController | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!config) return;
|
||||
const pathname = window.location.pathname;
|
||||
const controller = startBrowserTracingController(config, {
|
||||
queryClient,
|
||||
initialPathname: pathname,
|
||||
initialRouteTemplate: routeTemplateForElements(routesRef.current, pathname),
|
||||
});
|
||||
controllerRef.current = controller;
|
||||
return () => {
|
||||
controller?.stop();
|
||||
if (controllerRef.current === controller) controllerRef.current = null;
|
||||
};
|
||||
// Keyed by value: the config object identity changes on every session refetch.
|
||||
}, [configKey, queryClient]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const controller = controllerRef.current;
|
||||
if (!controller) return;
|
||||
controller.onLocationCommitted(
|
||||
location.pathname,
|
||||
navigationType,
|
||||
routeTemplateForElements(routesRef.current, location.pathname),
|
||||
);
|
||||
}, [location.pathname, navigationType]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { readPageContentGates, resetPageContentGatesForTest } from "@/lib/browser-tracing/page-content-gates";
|
||||
import { usePageContentReady } from "./usePageContentReady";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function Probe({ enabled }: { enabled: boolean }) {
|
||||
usePageContentReady(false, null, { enabled });
|
||||
return null;
|
||||
}
|
||||
|
||||
describe("usePageContentReady", () => {
|
||||
afterEach(() => resetPageContentGatesForTest());
|
||||
|
||||
it("registers a pending content gate while enabled and none while disabled", () => {
|
||||
const root = createRoot(document.createElement("div"));
|
||||
act(() => root.render(<Probe enabled />));
|
||||
expect(readPageContentGates()).toMatchObject({ contentCount: 1, pendingContentCount: 1 });
|
||||
// An agent chat with no saved task has no content signal; it must not hold the page open.
|
||||
act(() => root.render(<Probe enabled={false} />));
|
||||
expect(readPageContentGates()).toMatchObject({ contentCount: 0, pendingContentCount: 0 });
|
||||
act(() => root.unmount());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
import {
|
||||
registerPageContentGate,
|
||||
setPageContentGateReady,
|
||||
unregisterPageContentGate,
|
||||
} from "@/lib/browser-tracing/page-content-gates";
|
||||
|
||||
/**
|
||||
* Declares when this page's primary content has rendered, for the page-load
|
||||
* measurement in `doc/browser-performance-tracing.md`.
|
||||
*
|
||||
* Most pages need nothing: a navigation ends when no full-page loading state
|
||||
* is mounted and no query without data is still fetching. Call this hook only
|
||||
* when that generic rule is not accurate for a page. Once a page calls it, the
|
||||
* navigation ends when every mounted caller passes `ready`, at the first paint
|
||||
* after that.
|
||||
*
|
||||
* Pass `paintedAt` (a `performance.now()` value) when the page already records
|
||||
* its own paint time; otherwise the hook waits two animation frames so the
|
||||
* time marks a painted frame. The hook sends nothing itself and costs one map
|
||||
* entry while mounted.
|
||||
*/
|
||||
export function usePageContentReady(
|
||||
ready: boolean,
|
||||
paintedAt?: number | null,
|
||||
{ enabled = true }: { enabled?: boolean } = {},
|
||||
): void {
|
||||
const gateRef = useRef<number | null>(null);
|
||||
|
||||
// `enabled: false` leaves the page on the generic rule, for a surface that
|
||||
// has no content signal in its current state.
|
||||
useLayoutEffect(() => {
|
||||
if (!enabled) return;
|
||||
const id = registerPageContentGate("content");
|
||||
gateRef.current = id;
|
||||
return () => {
|
||||
unregisterPageContentGate(id);
|
||||
gateRef.current = null;
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const id = gateRef.current;
|
||||
if (id === null) return;
|
||||
if (!ready) {
|
||||
setPageContentGateReady(id, null);
|
||||
return;
|
||||
}
|
||||
if (typeof paintedAt === "number") {
|
||||
setPageContentGateReady(id, paintedAt);
|
||||
return;
|
||||
}
|
||||
if (typeof requestAnimationFrame !== "function") {
|
||||
setPageContentGateReady(id, performance.now());
|
||||
return;
|
||||
}
|
||||
let second = 0;
|
||||
const first = requestAnimationFrame(() => {
|
||||
second = requestAnimationFrame(() => setPageContentGateReady(id, performance.now()));
|
||||
});
|
||||
return () => {
|
||||
cancelAnimationFrame(first);
|
||||
cancelAnimationFrame(second);
|
||||
};
|
||||
}, [ready, paintedAt, enabled]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a full-page loading state (spinner, route Suspense fallback) as on
|
||||
* screen. A navigation cannot count as loaded while one is mounted.
|
||||
*/
|
||||
export function useBlockingPageGate(): void {
|
||||
useLayoutEffect(() => {
|
||||
const id = registerPageContentGate("blocking");
|
||||
return () => unregisterPageContentGate(id);
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// @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 {
|
||||
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,
|
||||
};
|
||||
|
||||
describe("startBrowserTracingController", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame"] });
|
||||
resetPageSessionSampleForTest();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
// Starts and stops browser performance tracing for one page session.
|
||||
//
|
||||
// Main-bundle code. It does nothing unless the authenticated session carries a
|
||||
// `browserTracing` config, which the server sends only for a hosted Paperclip
|
||||
// Cloud instance with an operator-set endpoint. When active it:
|
||||
// - decides once per page session whether this session is sampled; an
|
||||
// unsampled session does nothing else and downloads nothing,
|
||||
// - measures the hard load and every client-side navigation
|
||||
// (`page-load-recorder.ts`), and
|
||||
// - after the page settles, downloads the tracing SDK chunk (`sdk.ts`),
|
||||
// which exports the measurements, Web Vitals, and API request spans.
|
||||
// See doc/browser-performance-tracing.md.
|
||||
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import type { BrowserTracingConfig } from "@paperclipai/shared";
|
||||
import { whenPageSettles } from "@/lib/when-page-settles";
|
||||
import { readPageContentGates } from "./page-content-gates";
|
||||
import { createPageLoadRecorder, PAGE_LOAD_TIMEOUT_MS, type PageLoadRecorder } from "./page-load-recorder";
|
||||
|
||||
export type RouterNavigationType = "PUSH" | "POP" | "REPLACE";
|
||||
|
||||
export interface BrowserTracingController {
|
||||
/** Called after React commits a new location. */
|
||||
onLocationCommitted(pathname: string, navigationType: RouterNavigationType, routeTemplate: string): void;
|
||||
stop(): void;
|
||||
}
|
||||
|
||||
export interface TracingSdkHandle {
|
||||
forceFlush(): Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface TracingSdkModule {
|
||||
startTracingSdk(config: BrowserTracingConfig, recorder: PageLoadRecorder): TracingSdkHandle;
|
||||
}
|
||||
|
||||
export interface BrowserTracingControllerOptions {
|
||||
queryClient: QueryClient;
|
||||
initialPathname: string;
|
||||
initialRouteTemplate: string;
|
||||
/** Overridable for tests. */
|
||||
loadSdk?: () => Promise<TracingSdkModule>;
|
||||
random?: () => number;
|
||||
/** Overridable for tests; defaults to waiting until the page settles. */
|
||||
scheduleSdkLoad?: (start: () => void) => () => void;
|
||||
/** Load the SDK by this time even if the page never settles. */
|
||||
sdkLoadDeadlineMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the SDK no later than this, measured from activation. A page whose
|
||||
* requests hang never settles; its hard load then ends as `timeout` at 30 s
|
||||
* after navigation start, and this deadline still exports it.
|
||||
*/
|
||||
export const SDK_LOAD_DEADLINE_MS = PAGE_LOAD_TIMEOUT_MS + 5_000;
|
||||
|
||||
let sessionSampled: boolean | null = null;
|
||||
|
||||
/** One decision per page session, so a sampled session is complete. */
|
||||
export function isPageSessionSampled(sampleRate: number, random: () => number = Math.random): boolean {
|
||||
if (sessionSampled === null) sessionSampled = random() < sampleRate;
|
||||
return sessionSampled;
|
||||
}
|
||||
|
||||
export function resetPageSessionSampleForTest(): void {
|
||||
sessionSampled = null;
|
||||
}
|
||||
|
||||
/** Any query that has no data yet and is fetching is the page's primary data. */
|
||||
export function hasPendingPrimaryData(queryClient: QueryClient): boolean {
|
||||
return queryClient.isFetching({ predicate: (query) => query.state.data === undefined }) > 0;
|
||||
}
|
||||
|
||||
function pathnameOf(url: string | URL | null | undefined): string | null {
|
||||
if (url === null || url === undefined) return null;
|
||||
try {
|
||||
return new URL(String(url), window.location.href).pathname;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* React Router commits a navigation inside a transition, after any lazy route
|
||||
* code has loaded. The history entry changes first, when the user acts, so
|
||||
* the navigation start is taken from the history change.
|
||||
*/
|
||||
function trackHistoryChanges(now: () => number) {
|
||||
let last: { pathname: string; time: number } | null = null;
|
||||
const history = window.history;
|
||||
const originalPush = history.pushState;
|
||||
const originalReplace = history.replaceState;
|
||||
const record = (url: string | URL | null | undefined) => {
|
||||
const pathname = pathnameOf(url);
|
||||
if (pathname) last = { pathname, time: now() };
|
||||
};
|
||||
history.pushState = function pushState(this: History, ...args: Parameters<History["pushState"]>) {
|
||||
record(args[2]);
|
||||
return originalPush.apply(this, args);
|
||||
};
|
||||
history.replaceState = function replaceState(this: History, ...args: Parameters<History["replaceState"]>) {
|
||||
record(args[2]);
|
||||
return originalReplace.apply(this, args);
|
||||
};
|
||||
const onPopState = (event: PopStateEvent) => {
|
||||
last = { pathname: window.location.pathname, time: event.timeStamp || now() };
|
||||
};
|
||||
window.addEventListener("popstate", onPopState);
|
||||
return {
|
||||
takeStart(pathname: string): number | null {
|
||||
const entry = last;
|
||||
last = null;
|
||||
return entry && entry.pathname === pathname ? entry.time : null;
|
||||
},
|
||||
stop() {
|
||||
if (history.pushState !== originalPush) history.pushState = originalPush;
|
||||
if (history.replaceState !== originalReplace) history.replaceState = originalReplace;
|
||||
window.removeEventListener("popstate", onPopState);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function startBrowserTracingController(
|
||||
config: BrowserTracingConfig,
|
||||
options: BrowserTracingControllerOptions,
|
||||
): BrowserTracingController | null {
|
||||
if (!isPageSessionSampled(config.sampleRate, options.random)) return null;
|
||||
|
||||
const now = () => performance.now();
|
||||
const recorder = createPageLoadRecorder({
|
||||
now,
|
||||
requestFrame: (callback) => window.requestAnimationFrame(() => callback()),
|
||||
cancelFrame: (handle) => window.cancelAnimationFrame(handle),
|
||||
setTimer: (callback, ms) => window.setTimeout(callback, ms),
|
||||
clearTimer: (handle) => window.clearTimeout(handle as number),
|
||||
isDocumentHidden: () => document.visibilityState === "hidden",
|
||||
hasPendingPrimaryData: () => hasPendingPrimaryData(options.queryClient),
|
||||
readGates: readPageContentGates,
|
||||
});
|
||||
const history = trackHistoryChanges(now);
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === "hidden") recorder.noteHidden();
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
|
||||
// The hard load started at navigation start (time 0), before this code ran.
|
||||
recorder.begin({ routeTemplate: options.initialRouteTemplate, loadType: "hard", startTime: 0 });
|
||||
let lastPathname = options.initialPathname;
|
||||
|
||||
let stopped = false;
|
||||
let sdk: TracingSdkHandle | null = null;
|
||||
const loadSdk = options.loadSdk ?? (() => import("./sdk"));
|
||||
const schedule = options.scheduleSdkLoad ?? ((start: () => void) => whenPageSettles(options.queryClient, start));
|
||||
let loadStarted = false;
|
||||
let cancelSettled: () => void = () => {};
|
||||
const startLoad = () => {
|
||||
if (loadStarted || stopped) return;
|
||||
loadStarted = true;
|
||||
cancelSettled();
|
||||
window.clearTimeout(deadline);
|
||||
void loadSdk()
|
||||
.then((module) => {
|
||||
if (stopped) return;
|
||||
sdk = module.startTracingSdk(config, recorder);
|
||||
})
|
||||
.catch(() => {
|
||||
// Tracing is optional; a failed chunk load must not affect the page.
|
||||
});
|
||||
};
|
||||
const deadline = window.setTimeout(startLoad, options.sdkLoadDeadlineMs ?? SDK_LOAD_DEADLINE_MS);
|
||||
const cancelSchedule = schedule(startLoad);
|
||||
if (loadStarted) cancelSchedule();
|
||||
else cancelSettled = cancelSchedule;
|
||||
const cancelScheduledLoad = () => {
|
||||
cancelSettled();
|
||||
window.clearTimeout(deadline);
|
||||
};
|
||||
|
||||
return {
|
||||
onLocationCommitted(pathname, navigationType, routeTemplate) {
|
||||
if (stopped || pathname === lastPathname) return;
|
||||
lastPathname = pathname;
|
||||
const start = history.takeStart(pathname);
|
||||
if (navigationType === "REPLACE" && recorder.redirect(routeTemplate)) return;
|
||||
recorder.begin({ routeTemplate, loadType: "client", startTime: start ?? now() });
|
||||
},
|
||||
stop() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
cancelScheduledLoad();
|
||||
history.stop();
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
recorder.stop();
|
||||
void sdk?.shutdown();
|
||||
sdk = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { BasicTracerProvider, InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-web";
|
||||
import { KEEPALIVE_BODY_LIMIT_BYTES, OtlpFetchExporter } from "./otlp-fetch-exporter";
|
||||
|
||||
function finishedSpan() {
|
||||
const memory = new InMemorySpanExporter();
|
||||
const provider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(memory)] });
|
||||
provider.getTracer("t").startSpan("page.load", { attributes: { "paperclip.page.route": "/:companyPrefix/issues" } }).end();
|
||||
return memory.getFinishedSpans();
|
||||
}
|
||||
|
||||
describe("OtlpFetchExporter", () => {
|
||||
it("posts OTLP JSON with the ingest-key header, using keepalive while the tab is hidden", async () => {
|
||||
const fetchMock = vi.fn(async () => new Response("{}", { status: 200 }));
|
||||
const exporter = new OtlpFetchExporter({
|
||||
url: "https://api.honeycomb.io/v1/traces",
|
||||
headers: { "x-honeycomb-team": "hcaik_test" },
|
||||
fetch: fetchMock as unknown as typeof fetch,
|
||||
isPageHidden: () => true,
|
||||
});
|
||||
const result = await new Promise<{ code: number }>((resolve) => exporter.export(finishedSpan(), resolve));
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe("https://api.honeycomb.io/v1/traces");
|
||||
expect(init).toMatchObject({ method: "POST", keepalive: true, credentials: "omit" });
|
||||
expect(init.headers).toEqual({ "content-type": "application/json", "x-honeycomb-team": "hcaik_test" });
|
||||
const body = JSON.parse(new TextDecoder().decode(init.body as Uint8Array));
|
||||
const span = body.resourceSpans[0].scopeSpans[0].spans[0];
|
||||
expect(span.name).toBe("page.load");
|
||||
expect(span.attributes).toEqual([{ key: "paperclip.page.route", value: { stringValue: "/:companyPrefix/issues" } }]);
|
||||
});
|
||||
|
||||
it("reports failure without retrying when the collector rejects or is unreachable", async () => {
|
||||
for (const fetchMock of [vi.fn(async () => new Response("", { status: 401 })), vi.fn(async () => { throw new TypeError("offline"); })]) {
|
||||
const exporter = new OtlpFetchExporter({ url: "https://x.test/v1/traces", headers: {}, fetch: fetchMock as unknown as typeof fetch });
|
||||
const result = await new Promise<{ code: number }>((resolve) => exporter.export(finishedSpan(), resolve));
|
||||
expect(result.code).toBe(1);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
});
|
||||
|
||||
it("splits an oversized hidden-tab batch under the keepalive limit and keeps page.load", async () => {
|
||||
const memory = new InMemorySpanExporter();
|
||||
const provider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(memory)] });
|
||||
const tracer = provider.getTracer("t");
|
||||
for (let i = 0; i < 600; i++) tracer.startSpan("GET", { attributes: { "paperclip.api.area": `issues-${"x".repeat(200)}` } }).end();
|
||||
tracer.startSpan("page.load", { attributes: { "paperclip.page.route": "/:companyPrefix/issues/:issueId" } }).end();
|
||||
const spans = memory.getFinishedSpans();
|
||||
const fetchMock = vi.fn(async () => new Response("{}", { status: 200 }));
|
||||
const exporter = new OtlpFetchExporter({
|
||||
url: "https://x.test/v1/traces", headers: {}, fetch: fetchMock as unknown as typeof fetch, isPageHidden: () => true,
|
||||
});
|
||||
const result = await new Promise<{ code: number }>((resolve) => exporter.export(spans, resolve));
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
const calls = fetchMock.mock.calls as unknown as Array<[string, RequestInit]>;
|
||||
expect(calls.length).toBeGreaterThan(1);
|
||||
let exported = 0;
|
||||
for (const [, init] of calls) {
|
||||
const size = (init.body as Uint8Array).byteLength;
|
||||
expect(size).toBeLessThanOrEqual(KEEPALIVE_BODY_LIMIT_BYTES);
|
||||
exported += JSON.parse(new TextDecoder().decode(init.body as Uint8Array)).resourceSpans[0].scopeSpans[0].spans.length;
|
||||
}
|
||||
expect(exported).toBe(spans.length);
|
||||
// page.load is in the first request, which is always within the keepalive quota.
|
||||
const first = JSON.parse(new TextDecoder().decode(calls[0]![1].body as Uint8Array));
|
||||
expect(first.resourceSpans[0].scopeSpans[0].spans[0].name).toBe("page.load");
|
||||
expect(calls[0]![1].keepalive).toBe(true);
|
||||
});
|
||||
|
||||
it("sends a visible-tab batch in one ordinary request regardless of size", async () => {
|
||||
const fetchMock = vi.fn(async () => new Response("{}", { status: 200 }));
|
||||
const exporter = new OtlpFetchExporter({
|
||||
url: "https://x.test/v1/traces", headers: {}, fetch: fetchMock as unknown as typeof fetch, isPageHidden: () => false,
|
||||
});
|
||||
await new Promise((resolve) => exporter.export(finishedSpan(), resolve));
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].keepalive).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
// A minimal OTLP/HTTP JSON trace exporter for the browser tracing chunk.
|
||||
//
|
||||
// It reuses `@opentelemetry/otlp-transformer` (already a server dependency)
|
||||
// for the wire format and sends with `fetch`. While the tab is hidden it uses
|
||||
// `keepalive` so a batch sent as the tab closes still arrives, split to stay
|
||||
// under the browser's 64 KiB keepalive limit. Export is best effort: a failed batch is
|
||||
// dropped, never retried, so tracing cannot add load to a struggling page.
|
||||
|
||||
import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer";
|
||||
import type { ReadableSpan, SpanExporter } from "@opentelemetry/sdk-trace-web";
|
||||
|
||||
/** `ExportResultCode` from `@opentelemetry/core`: 0 = SUCCESS, 1 = FAILED. */
|
||||
const SUCCESS = 0;
|
||||
const FAILED = 1;
|
||||
|
||||
/**
|
||||
* Browsers reject a keepalive request whose body, together with every other
|
||||
* keepalive body still in flight, exceeds 64 KiB. Stay under it with margin.
|
||||
*/
|
||||
export const KEEPALIVE_BODY_LIMIT_BYTES = 60 * 1024;
|
||||
|
||||
export interface OtlpFetchExporterOptions {
|
||||
url: string;
|
||||
headers: Record<string, string>;
|
||||
/**
|
||||
* The un-instrumented `fetch`, captured before fetch instrumentation is
|
||||
* enabled, so exports never create spans of their own.
|
||||
*/
|
||||
fetch: typeof fetch;
|
||||
/** Overridable for tests. */
|
||||
isPageHidden?: () => boolean;
|
||||
}
|
||||
|
||||
/** Page-load and Web Vital spans go first, so a lost tail costs only API spans. */
|
||||
function priority(span: ReadableSpan): number {
|
||||
return span.name === "page.load" || span.name.startsWith("web_vital.") ? 0 : 1;
|
||||
}
|
||||
|
||||
export class OtlpFetchExporter implements SpanExporter {
|
||||
private readonly pending = new Set<Promise<boolean>>();
|
||||
private keepaliveBytesInFlight = 0;
|
||||
private stopped = false;
|
||||
|
||||
constructor(private readonly options: OtlpFetchExporterOptions) {}
|
||||
|
||||
export(spans: ReadableSpan[], resultCallback: Parameters<SpanExporter["export"]>[1]): void {
|
||||
if (this.stopped || spans.length === 0) {
|
||||
resultCallback({ code: this.stopped ? FAILED : SUCCESS });
|
||||
return;
|
||||
}
|
||||
const ordered = [...spans].sort((a, b) => priority(a) - priority(b));
|
||||
// Keepalive is only needed while the tab is hiding or unloading; a
|
||||
// visible page sends with an ordinary request, which has no size limit.
|
||||
const hidden = (this.options.isPageHidden ?? (() => typeof document !== "undefined" && document.visibilityState === "hidden"))();
|
||||
const bodies = hidden ? this.chunk(ordered) : [this.serialize(ordered)];
|
||||
if (bodies.some((body) => body === null)) {
|
||||
resultCallback({ code: FAILED });
|
||||
return;
|
||||
}
|
||||
void Promise.all((bodies as Uint8Array[]).map((body) => this.send(body, hidden)))
|
||||
.then((results) => resultCallback({ code: results.every(Boolean) ? SUCCESS : FAILED }));
|
||||
}
|
||||
|
||||
private serialize(spans: ReadableSpan[]): Uint8Array | null {
|
||||
try {
|
||||
return JsonTraceSerializer.serializeRequest(spans) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Split into bodies under the keepalive limit, halving until each fits. */
|
||||
private chunk(spans: ReadableSpan[]): Array<Uint8Array | null> {
|
||||
const body = this.serialize(spans);
|
||||
if (!body || body.byteLength <= KEEPALIVE_BODY_LIMIT_BYTES || spans.length === 1) return [body];
|
||||
const middle = Math.ceil(spans.length / 2);
|
||||
return [...this.chunk(spans.slice(0, middle)), ...this.chunk(spans.slice(middle))];
|
||||
}
|
||||
|
||||
private send(body: Uint8Array, hidden: boolean): Promise<boolean> {
|
||||
const keepalive = hidden
|
||||
&& body.byteLength <= KEEPALIVE_BODY_LIMIT_BYTES
|
||||
&& this.keepaliveBytesInFlight + body.byteLength <= KEEPALIVE_BODY_LIMIT_BYTES;
|
||||
if (keepalive) this.keepaliveBytesInFlight += body.byteLength;
|
||||
const request = this.options.fetch(this.options.url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...this.options.headers },
|
||||
body: body as BodyInit,
|
||||
keepalive,
|
||||
credentials: "omit",
|
||||
})
|
||||
.then((response) => response.ok)
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
if (keepalive) this.keepaliveBytesInFlight -= body.byteLength;
|
||||
});
|
||||
this.pending.add(request);
|
||||
void request.finally(() => this.pending.delete(request));
|
||||
return request;
|
||||
}
|
||||
|
||||
async forceFlush(): Promise<void> {
|
||||
await Promise.all(this.pending);
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
this.stopped = true;
|
||||
await this.forceFlush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Readiness gates that tell the page-load recorder when a page has rendered.
|
||||
//
|
||||
// This module is in the main bundle and holds only a small map. It sends
|
||||
// nothing anywhere; the recorder reads it only when browser tracing is active.
|
||||
//
|
||||
// Two kinds of gate exist:
|
||||
// - `blocking`: a full-page loading state is on screen (for example the
|
||||
// `PaperclipLoading` spinner or a route Suspense fallback). The page is not
|
||||
// loaded while any blocking gate is mounted.
|
||||
// - `content`: a page declared its own "primary content painted" signal with
|
||||
// `usePageContentReady`. When a page has one, that signal defines "loaded"
|
||||
// instead of the generic network-idle rule.
|
||||
|
||||
export type PageContentGateKind = "blocking" | "content";
|
||||
|
||||
interface GateState {
|
||||
kind: PageContentGateKind;
|
||||
/** `performance.now()` when the gate became ready, or null while pending. */
|
||||
readyAt: number | null;
|
||||
}
|
||||
|
||||
const gates = new Map<number, GateState>();
|
||||
let nextGateId = 1;
|
||||
|
||||
export function registerPageContentGate(kind: PageContentGateKind): number {
|
||||
const id = nextGateId++;
|
||||
gates.set(id, { kind, readyAt: null });
|
||||
return id;
|
||||
}
|
||||
|
||||
export function setPageContentGateReady(id: number, readyAt: number | null): void {
|
||||
const gate = gates.get(id);
|
||||
if (gate && gate.kind === "content") gate.readyAt = readyAt;
|
||||
}
|
||||
|
||||
export function unregisterPageContentGate(id: number): void {
|
||||
gates.delete(id);
|
||||
}
|
||||
|
||||
export interface PageContentGateSnapshot {
|
||||
blockingCount: number;
|
||||
contentCount: number;
|
||||
pendingContentCount: number;
|
||||
/** Latest `readyAt` among content gates, or null when none are ready. */
|
||||
lastContentReadyAt: number | null;
|
||||
}
|
||||
|
||||
export function readPageContentGates(): PageContentGateSnapshot {
|
||||
let blockingCount = 0;
|
||||
let contentCount = 0;
|
||||
let pendingContentCount = 0;
|
||||
let lastContentReadyAt: number | null = null;
|
||||
for (const gate of gates.values()) {
|
||||
if (gate.kind === "blocking") {
|
||||
blockingCount += 1;
|
||||
continue;
|
||||
}
|
||||
contentCount += 1;
|
||||
if (gate.readyAt === null) pendingContentCount += 1;
|
||||
else if (lastContentReadyAt === null || gate.readyAt > lastContentReadyAt) lastContentReadyAt = gate.readyAt;
|
||||
}
|
||||
return { blockingCount, contentCount, pendingContentCount, lastContentReadyAt };
|
||||
}
|
||||
|
||||
/** Test helper. */
|
||||
export function resetPageContentGatesForTest(): void {
|
||||
gates.clear();
|
||||
nextGateId = 1;
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { PageContentGateSnapshot } from "./page-content-gates";
|
||||
import { createPageLoadRecorder, type PageLoadMeasurement, type PageLoadSink } from "./page-load-recorder";
|
||||
|
||||
function createHarness() {
|
||||
let time = 0;
|
||||
let frames: Array<() => void> = [];
|
||||
const timers = new Map<number, { at: number; callback: () => void }>();
|
||||
let nextTimer = 1;
|
||||
const state = {
|
||||
pendingData: false,
|
||||
hidden: false,
|
||||
gates: { blockingCount: 0, contentCount: 0, pendingContentCount: 0, lastContentReadyAt: null } as PageContentGateSnapshot,
|
||||
};
|
||||
const recorder = createPageLoadRecorder({
|
||||
now: () => time,
|
||||
requestFrame: (callback) => {
|
||||
frames.push(callback);
|
||||
return frames.length;
|
||||
},
|
||||
cancelFrame: () => {
|
||||
frames = [];
|
||||
},
|
||||
setTimer: (callback, ms) => {
|
||||
const id = nextTimer++;
|
||||
timers.set(id, { at: time + ms, callback });
|
||||
return id;
|
||||
},
|
||||
clearTimer: (handle) => {
|
||||
timers.delete(handle as number);
|
||||
},
|
||||
isDocumentHidden: () => state.hidden,
|
||||
hasPendingPrimaryData: () => state.pendingData,
|
||||
readGates: () => state.gates,
|
||||
});
|
||||
const ended: PageLoadMeasurement[] = [];
|
||||
const begun: PageLoadMeasurement[] = [];
|
||||
const sink: PageLoadSink = {
|
||||
begin: (measurement) => begun.push({ ...measurement }),
|
||||
end: (measurement) => ended.push({ ...measurement }),
|
||||
};
|
||||
return {
|
||||
recorder,
|
||||
state,
|
||||
ended,
|
||||
begun,
|
||||
sink,
|
||||
/** Advance one 16 ms animation frame. */
|
||||
frame() {
|
||||
time += 16;
|
||||
const due = frames;
|
||||
frames = [];
|
||||
for (const callback of due) callback();
|
||||
for (const [id, timer] of timers) {
|
||||
if (timer.at <= time) {
|
||||
timers.delete(id);
|
||||
timer.callback();
|
||||
}
|
||||
}
|
||||
},
|
||||
advance(ms: number) {
|
||||
time += ms;
|
||||
for (const [id, timer] of timers) {
|
||||
if (timer.at <= time) {
|
||||
timers.delete(id);
|
||||
timer.callback();
|
||||
}
|
||||
}
|
||||
},
|
||||
get time() {
|
||||
return time;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("createPageLoadRecorder", () => {
|
||||
it("ends a client navigation at the first of two idle frames once primary data has loaded", () => {
|
||||
const harness = createHarness();
|
||||
harness.recorder.attachSink(harness.sink);
|
||||
harness.advance(1000);
|
||||
harness.state.pendingData = true;
|
||||
harness.recorder.begin({ routeTemplate: "/:companyPrefix/issues", loadType: "client", startTime: 990 });
|
||||
expect(harness.begun).toHaveLength(1);
|
||||
|
||||
harness.frame();
|
||||
harness.frame();
|
||||
harness.state.pendingData = false;
|
||||
harness.frame(); // first idle frame, t=1048
|
||||
expect(harness.ended).toHaveLength(0);
|
||||
harness.frame();
|
||||
|
||||
expect(harness.ended).toEqual([expect.objectContaining({
|
||||
routeTemplate: "/:companyPrefix/issues",
|
||||
loadType: "client",
|
||||
startTime: 990,
|
||||
endTime: 1048,
|
||||
outcome: "ready",
|
||||
readySignal: "idle",
|
||||
wasHidden: false,
|
||||
})]);
|
||||
});
|
||||
|
||||
it("waits for blocking gates and uses the content gate paint time when a page declares one", () => {
|
||||
const harness = createHarness();
|
||||
harness.recorder.attachSink(harness.sink);
|
||||
harness.recorder.begin({ routeTemplate: "/:companyPrefix/issues/:issueId", loadType: "client", startTime: 0 });
|
||||
harness.state.gates = { blockingCount: 1, contentCount: 0, pendingContentCount: 0, lastContentReadyAt: null };
|
||||
harness.frame();
|
||||
harness.frame();
|
||||
expect(harness.ended).toHaveLength(0);
|
||||
|
||||
// Network idle alone does not end a page that declared a content gate.
|
||||
harness.state.gates = { blockingCount: 0, contentCount: 1, pendingContentCount: 1, lastContentReadyAt: null };
|
||||
harness.frame();
|
||||
harness.frame();
|
||||
expect(harness.ended).toHaveLength(0);
|
||||
|
||||
harness.state.gates = { blockingCount: 0, contentCount: 1, pendingContentCount: 0, lastContentReadyAt: 70 };
|
||||
harness.frame();
|
||||
harness.frame();
|
||||
expect(harness.ended[0]).toMatchObject({ endTime: 70, outcome: "ready", readySignal: "content" });
|
||||
});
|
||||
|
||||
it("interrupts an open measurement when another navigation starts", () => {
|
||||
const harness = createHarness();
|
||||
harness.recorder.attachSink(harness.sink);
|
||||
harness.state.pendingData = true;
|
||||
harness.recorder.begin({ routeTemplate: "/a", loadType: "client", startTime: 0 });
|
||||
harness.advance(100);
|
||||
harness.recorder.begin({ routeTemplate: "/b", loadType: "client", startTime: 100 });
|
||||
expect(harness.ended[0]).toMatchObject({ routeTemplate: "/a", outcome: "interrupted", endTime: 100 });
|
||||
expect(harness.recorder.open()?.routeTemplate).toBe("/b");
|
||||
});
|
||||
|
||||
it("continues a measurement through a redirect under the new route", () => {
|
||||
const harness = createHarness();
|
||||
harness.recorder.attachSink(harness.sink);
|
||||
harness.state.pendingData = true;
|
||||
harness.recorder.begin({ routeTemplate: "/", loadType: "hard", startTime: 0 });
|
||||
expect(harness.recorder.redirect("/:companyPrefix/dashboard")).toBe(true);
|
||||
harness.state.pendingData = false;
|
||||
harness.frame();
|
||||
harness.frame();
|
||||
expect(harness.ended).toEqual([expect.objectContaining({ routeTemplate: "/:companyPrefix/dashboard", loadType: "hard", startTime: 0 })]);
|
||||
expect(harness.recorder.hardLoadRouteTemplate()).toBe("/:companyPrefix/dashboard");
|
||||
});
|
||||
|
||||
it("times out a page that never finishes loading", () => {
|
||||
const harness = createHarness();
|
||||
harness.recorder.attachSink(harness.sink);
|
||||
harness.state.pendingData = true;
|
||||
harness.recorder.begin({ routeTemplate: "/slow", loadType: "client", startTime: 0 });
|
||||
harness.advance(30_000);
|
||||
expect(harness.ended[0]).toMatchObject({ outcome: "timeout", endTime: 30_000, readySignal: null });
|
||||
});
|
||||
|
||||
it("marks a measurement whose tab was hidden", () => {
|
||||
const harness = createHarness();
|
||||
harness.recorder.attachSink(harness.sink);
|
||||
harness.recorder.begin({ routeTemplate: "/a", loadType: "client", startTime: 0 });
|
||||
harness.recorder.noteHidden();
|
||||
harness.frame();
|
||||
harness.frame();
|
||||
expect(harness.ended[0]).toMatchObject({ wasHidden: true });
|
||||
});
|
||||
|
||||
it("buffers measurements that finish before the SDK attaches and replays them in order", () => {
|
||||
const harness = createHarness();
|
||||
harness.recorder.begin({ routeTemplate: "/hard", loadType: "hard", startTime: 0 });
|
||||
harness.frame();
|
||||
harness.frame();
|
||||
harness.state.pendingData = true;
|
||||
harness.recorder.begin({ routeTemplate: "/open", loadType: "client", startTime: 40 });
|
||||
expect(harness.ended).toHaveLength(0);
|
||||
|
||||
harness.recorder.attachSink(harness.sink);
|
||||
expect(harness.begun.map((m) => m.routeTemplate)).toEqual(["/hard", "/open"]);
|
||||
expect(harness.ended.map((m) => m.routeTemplate)).toEqual(["/hard"]);
|
||||
expect(harness.begun[1]!.endTime).toBeNull();
|
||||
});
|
||||
|
||||
it("does nothing after stop", () => {
|
||||
const harness = createHarness();
|
||||
harness.recorder.attachSink(harness.sink);
|
||||
harness.recorder.stop();
|
||||
harness.recorder.begin({ routeTemplate: "/a", loadType: "client", startTime: 0 });
|
||||
harness.frame();
|
||||
harness.frame();
|
||||
expect(harness.begun).toHaveLength(0);
|
||||
expect(harness.ended).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
// Measures how long each page takes to load, for hard loads and client-side
|
||||
// navigations, and hands finished measurements to the tracing SDK once it has
|
||||
// loaded. The definitions live in doc/browser-performance-tracing.md.
|
||||
//
|
||||
// This module is in the main bundle and imports no OpenTelemetry code. It runs
|
||||
// only when browser tracing is active for this page session.
|
||||
//
|
||||
// A measurement ends at the first animation frame, observed on
|
||||
// `stableFrames` consecutive frames, in which:
|
||||
// 1. no blocking gate (full-page loading state) is mounted, and
|
||||
// 2a. when the page declared content gates: every content gate is ready
|
||||
// (the end time is the latest gate's paint time), otherwise
|
||||
// 2b. no query that has no data yet is fetching (the end time is the first
|
||||
// such frame).
|
||||
// A new navigation interrupts an open one. A measurement that has not ended
|
||||
// after `timeoutMs` ends with outcome `timeout`.
|
||||
|
||||
import type { PageContentGateSnapshot } from "./page-content-gates";
|
||||
|
||||
export type PageLoadType = "hard" | "client";
|
||||
export type PageLoadOutcome = "ready" | "timeout" | "interrupted";
|
||||
export type PageLoadReadySignal = "content" | "idle";
|
||||
|
||||
export interface PageLoadMeasurement {
|
||||
readonly id: number;
|
||||
routeTemplate: string;
|
||||
readonly loadType: PageLoadType;
|
||||
/** `performance.now()` time; 0 for a hard load (navigation start). */
|
||||
readonly startTime: number;
|
||||
endTime: number | null;
|
||||
outcome: PageLoadOutcome | null;
|
||||
readySignal: PageLoadReadySignal | null;
|
||||
/** The tab was hidden at some point during the measurement. */
|
||||
wasHidden: boolean;
|
||||
}
|
||||
|
||||
/** Receives measurements; implemented by the lazily loaded tracing SDK. */
|
||||
export interface PageLoadSink {
|
||||
begin(measurement: PageLoadMeasurement): void;
|
||||
end(measurement: PageLoadMeasurement): void;
|
||||
}
|
||||
|
||||
export interface PageLoadRecorderDeps {
|
||||
now(): number;
|
||||
requestFrame(callback: () => void): number;
|
||||
cancelFrame(handle: number): void;
|
||||
setTimer(callback: () => void, ms: number): unknown;
|
||||
clearTimer(handle: unknown): void;
|
||||
isDocumentHidden(): boolean;
|
||||
hasPendingPrimaryData(): boolean;
|
||||
readGates(): PageContentGateSnapshot;
|
||||
}
|
||||
|
||||
export interface PageLoadRecorderOptions {
|
||||
timeoutMs?: number;
|
||||
stableFrames?: number;
|
||||
/** Finished measurements kept while no sink is attached. */
|
||||
bufferLimit?: number;
|
||||
}
|
||||
|
||||
export interface PageLoadRecorder {
|
||||
begin(input: { routeTemplate: string; loadType: PageLoadType; startTime: number }): PageLoadMeasurement;
|
||||
/**
|
||||
* A redirect (history replace) while a measurement is open continues it
|
||||
* under the new route. Returns false when no measurement is open.
|
||||
*/
|
||||
redirect(routeTemplate: string): boolean;
|
||||
open(): PageLoadMeasurement | null;
|
||||
currentRouteTemplate(): string | null;
|
||||
hardLoadRouteTemplate(): string | null;
|
||||
noteHidden(): void;
|
||||
attachSink(sink: PageLoadSink): void;
|
||||
stop(): void;
|
||||
}
|
||||
|
||||
export const PAGE_LOAD_TIMEOUT_MS = 30_000;
|
||||
|
||||
export function createPageLoadRecorder(
|
||||
deps: PageLoadRecorderDeps,
|
||||
options: PageLoadRecorderOptions = {},
|
||||
): PageLoadRecorder {
|
||||
const timeoutMs = options.timeoutMs ?? PAGE_LOAD_TIMEOUT_MS;
|
||||
const stableFrames = Math.max(1, options.stableFrames ?? 2);
|
||||
const bufferLimit = options.bufferLimit ?? 20;
|
||||
|
||||
let nextId = 1;
|
||||
let current: PageLoadMeasurement | null = null;
|
||||
let latestRoute: string | null = null;
|
||||
let hardLoadRoute: string | null = null;
|
||||
let sink: PageLoadSink | null = null;
|
||||
let stopped = false;
|
||||
let frame: number | null = null;
|
||||
let timer: unknown = null;
|
||||
let streak = 0;
|
||||
let streakStart = 0;
|
||||
const buffered: PageLoadMeasurement[] = [];
|
||||
|
||||
function cancelScheduled() {
|
||||
if (frame !== null) deps.cancelFrame(frame);
|
||||
frame = null;
|
||||
if (timer !== null) deps.clearTimer(timer);
|
||||
timer = null;
|
||||
}
|
||||
|
||||
function finish(measurement: PageLoadMeasurement, outcome: PageLoadOutcome, endTime: number, signal: PageLoadReadySignal | null) {
|
||||
if (current === measurement) {
|
||||
current = null;
|
||||
cancelScheduled();
|
||||
}
|
||||
measurement.outcome = outcome;
|
||||
measurement.readySignal = signal;
|
||||
measurement.endTime = Math.max(measurement.startTime, endTime);
|
||||
if (measurement.loadType === "hard") hardLoadRoute = measurement.routeTemplate;
|
||||
if (sink) {
|
||||
sink.end(measurement);
|
||||
return;
|
||||
}
|
||||
buffered.push(measurement);
|
||||
if (buffered.length > bufferLimit) buffered.shift();
|
||||
}
|
||||
|
||||
function tick() {
|
||||
frame = null;
|
||||
const measurement = current;
|
||||
if (!measurement || stopped) return;
|
||||
if (deps.isDocumentHidden()) measurement.wasHidden = true;
|
||||
|
||||
const gates = deps.readGates();
|
||||
let signal: PageLoadReadySignal | null = null;
|
||||
if (gates.blockingCount === 0) {
|
||||
if (gates.contentCount > 0) {
|
||||
if (gates.pendingContentCount === 0) signal = "content";
|
||||
} else if (!deps.hasPendingPrimaryData()) {
|
||||
signal = "idle";
|
||||
}
|
||||
}
|
||||
|
||||
if (signal === null) {
|
||||
streak = 0;
|
||||
} else {
|
||||
if (streak === 0) streakStart = deps.now();
|
||||
streak += 1;
|
||||
if (streak >= stableFrames) {
|
||||
const endTime = signal === "content" && gates.lastContentReadyAt !== null
|
||||
? gates.lastContentReadyAt
|
||||
: streakStart;
|
||||
finish(measurement, "ready", endTime, signal);
|
||||
return;
|
||||
}
|
||||
}
|
||||
frame = deps.requestFrame(tick);
|
||||
}
|
||||
|
||||
function schedule(measurement: PageLoadMeasurement) {
|
||||
streak = 0;
|
||||
frame = deps.requestFrame(tick);
|
||||
const remaining = Math.max(0, measurement.startTime + timeoutMs - deps.now());
|
||||
timer = deps.setTimer(() => {
|
||||
timer = null;
|
||||
if (current === measurement) finish(measurement, "timeout", deps.now(), null);
|
||||
}, remaining);
|
||||
}
|
||||
|
||||
return {
|
||||
begin({ routeTemplate, loadType, startTime }) {
|
||||
if (current) finish(current, "interrupted", deps.now(), null);
|
||||
const measurement: PageLoadMeasurement = {
|
||||
id: nextId++,
|
||||
routeTemplate,
|
||||
loadType,
|
||||
startTime,
|
||||
endTime: null,
|
||||
outcome: null,
|
||||
readySignal: null,
|
||||
wasHidden: deps.isDocumentHidden(),
|
||||
};
|
||||
latestRoute = routeTemplate;
|
||||
if (stopped) return measurement;
|
||||
current = measurement;
|
||||
sink?.begin(measurement);
|
||||
schedule(measurement);
|
||||
return measurement;
|
||||
},
|
||||
redirect(routeTemplate) {
|
||||
latestRoute = routeTemplate;
|
||||
if (!current) return false;
|
||||
current.routeTemplate = routeTemplate;
|
||||
streak = 0;
|
||||
return true;
|
||||
},
|
||||
open: () => current,
|
||||
currentRouteTemplate: () => latestRoute,
|
||||
hardLoadRouteTemplate: () => hardLoadRoute ?? (current?.loadType === "hard" ? current.routeTemplate : null),
|
||||
noteHidden() {
|
||||
if (current) current.wasHidden = true;
|
||||
},
|
||||
attachSink(next) {
|
||||
if (stopped) return;
|
||||
sink = next;
|
||||
for (const measurement of buffered.splice(0)) {
|
||||
next.begin(measurement);
|
||||
next.end(measurement);
|
||||
}
|
||||
if (current) next.begin(current);
|
||||
},
|
||||
stop() {
|
||||
stopped = true;
|
||||
cancelScheduled();
|
||||
current = null;
|
||||
sink = null;
|
||||
buffered.length = 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Route } from "react-router-dom";
|
||||
import { routeTemplateForElements, UNMATCHED_ROUTE_TEMPLATE } from "./route-template";
|
||||
|
||||
const Page = () => null;
|
||||
|
||||
const routes = (
|
||||
<>
|
||||
<Route path="auth" element={<Page />} />
|
||||
<Route path="invite/:token" element={<Page />} />
|
||||
<Route element={<Page />}>
|
||||
<Route index element={<Page />} />
|
||||
<Route path="issues/:issueId" element={<Page />} />
|
||||
<Route path=":companyPrefix" element={<Page />}>
|
||||
<Route path="issues" element={<Page />} />
|
||||
<Route path="issues/:issueId" element={<Page />} />
|
||||
<Route path="agents/:agentId/runs/:runId" element={<Page />} />
|
||||
<Route path=":pluginRoutePath/*" element={<Page />} />
|
||||
</Route>
|
||||
</Route>
|
||||
</>
|
||||
);
|
||||
|
||||
describe("routeTemplateForElements", () => {
|
||||
it.each([
|
||||
["/PAP/issues", "/:companyPrefix/issues"],
|
||||
["/PAP/issues/PAP-1234", "/:companyPrefix/issues/:issueId"],
|
||||
["/PAP/issues/PAP-1234/", "/:companyPrefix/issues/:issueId"],
|
||||
["/issues/0f6b6d1e-2c4f-4b5e-9f00-123456789abc", "/issues/:issueId"],
|
||||
["/PAP/agents/3e1/runs/77d", "/:companyPrefix/agents/:agentId/runs/:runId"],
|
||||
["/invite/secret-token-value", "/invite/:token"],
|
||||
["/PAP/some-plugin/deep/path/9", "/:companyPrefix/:pluginRoutePath/*"],
|
||||
["/", "/"],
|
||||
])("reports %s as %s", (pathname, template) => {
|
||||
expect(routeTemplateForElements(routes, pathname)).toBe(template);
|
||||
});
|
||||
|
||||
it("never includes ids, slugs, or tokens from the concrete path", () => {
|
||||
const concrete = [
|
||||
"/ACME/issues/ACME-98765",
|
||||
"/invite/tok_abcdef123",
|
||||
"/ACME/agents/agent-uuid-1/runs/run-uuid-2",
|
||||
"/ACME/my-plugin/customer-name/42",
|
||||
];
|
||||
for (const pathname of concrete) {
|
||||
const template = routeTemplateForElements(routes, pathname);
|
||||
for (const part of pathname.split("/").filter(Boolean)) {
|
||||
if (["issues", "invite", "agents", "runs"].includes(part)) continue;
|
||||
expect(template).not.toContain(part);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("reports an unmatched path without echoing it", () => {
|
||||
const narrow = <Route path="auth" element={<Page />} />;
|
||||
expect(routeTemplateForElements(narrow, "/private/PAP-1")).toBe(UNMATCHED_ROUTE_TEMPLATE);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { createRoutesFromChildren, matchRoutes, type RouteObject } from "react-router-dom";
|
||||
|
||||
/** Reported when no route in the tree matches the path. */
|
||||
export const UNMATCHED_ROUTE_TEMPLATE = "(unmatched)";
|
||||
|
||||
/**
|
||||
* The route pattern that renders `pathname`, such as
|
||||
* `/:companyPrefix/issues/:issueId`. It is built only from the `path` props in
|
||||
* the route tree, so it never contains an id, a slug, a query string, or a
|
||||
* hash from the concrete URL. A splat route keeps its `*`.
|
||||
*/
|
||||
export function routeTemplateFor(routes: RouteObject[], pathname: string): string {
|
||||
const matches = matchRoutes(routes, pathname);
|
||||
if (!matches) return UNMATCHED_ROUTE_TEMPLATE;
|
||||
const segments: string[] = [];
|
||||
for (const match of matches) {
|
||||
const path = match.route.path?.replace(/^\/+|\/+$/g, "");
|
||||
if (path) segments.push(path);
|
||||
}
|
||||
return `/${segments.join("/")}`;
|
||||
}
|
||||
|
||||
/** Same as `routeTemplateFor`, from the `<Route>` elements rendered by `<Routes>`. */
|
||||
export function routeTemplateForElements(routeElements: ReactNode, pathname: string): string {
|
||||
return routeTemplateFor(createRoutesFromChildren(routeElements), pathname);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { InMemorySpanExporter } from "@opentelemetry/sdk-trace-web";
|
||||
import type { BrowserTracingConfig } from "@paperclipai/shared";
|
||||
import { createPageLoadRecorder, type PageLoadRecorder } from "./page-load-recorder";
|
||||
import { honeycombSampleRate, nonApiUrlPattern, startTracingSdk } from "./sdk";
|
||||
import { apiAreaFromUrl } from "./span-sanitizer";
|
||||
import type { TracingSdkHandle } from "./controller";
|
||||
|
||||
const config: BrowserTracingConfig = {
|
||||
tracesUrl: "https://api.honeycomb.io/v1/traces",
|
||||
ingestKey: "hcaik_test",
|
||||
serviceName: "paperclip-web",
|
||||
environment: "staging",
|
||||
sampleRate: 0.25,
|
||||
};
|
||||
|
||||
function idleRecorder(): PageLoadRecorder {
|
||||
let frames: Array<() => void> = [];
|
||||
const recorder = createPageLoadRecorder({
|
||||
now: () => performance.now(),
|
||||
requestFrame: (callback) => frames.push(callback),
|
||||
cancelFrame: () => {
|
||||
frames = [];
|
||||
},
|
||||
setTimer: () => 0,
|
||||
clearTimer: () => {},
|
||||
isDocumentHidden: () => false,
|
||||
hasPendingPrimaryData: () => false,
|
||||
readGates: () => ({ blockingCount: 0, contentCount: 0, pendingContentCount: 0, lastContentReadyAt: null }),
|
||||
});
|
||||
(recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames = () => {
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const due = frames;
|
||||
frames = [];
|
||||
for (const callback of due) callback();
|
||||
}
|
||||
};
|
||||
return recorder;
|
||||
}
|
||||
|
||||
describe("startTracingSdk", () => {
|
||||
let exporter: InMemorySpanExporter;
|
||||
let handle: TracingSdkHandle | null = null;
|
||||
const realFetch = globalThis.fetch;
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
exporter = new InMemorySpanExporter();
|
||||
fetchMock = vi.fn(async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } }));
|
||||
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await handle?.shutdown();
|
||||
handle = null;
|
||||
globalThis.fetch = realFetch;
|
||||
});
|
||||
|
||||
it("exports a page.load span with the route template and only allowlisted attributes", async () => {
|
||||
const recorder = idleRecorder();
|
||||
handle = startTracingSdk(config, recorder, { exporter });
|
||||
recorder.begin({ routeTemplate: "/:companyPrefix/issues/:issueId", loadType: "client", startTime: performance.now() });
|
||||
(recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames();
|
||||
await handle.forceFlush();
|
||||
|
||||
const spans = exporter.getFinishedSpans().filter((span) => span.name === "page.load");
|
||||
expect(spans).toHaveLength(1);
|
||||
expect(spans[0]!.attributes).toEqual({
|
||||
"paperclip.page.route": "/:companyPrefix/issues/:issueId",
|
||||
"paperclip.page.load_type": "client",
|
||||
"paperclip.page.outcome": "ready",
|
||||
"paperclip.page.ready_signal": "idle",
|
||||
"paperclip.page.was_hidden": false,
|
||||
SampleRate: 4,
|
||||
});
|
||||
// service.version is the build commit, absent in tests.
|
||||
expect(Object.keys(spans[0]!.resource.attributes).sort()).toEqual([
|
||||
"deployment.environment.name",
|
||||
"service.name",
|
||||
]);
|
||||
expect(spans[0]!.resource.attributes["service.name"]).toBe("paperclip-web");
|
||||
});
|
||||
|
||||
it("propagates trace context only to this origin's API and strips URLs from fetch spans", async () => {
|
||||
const recorder = idleRecorder();
|
||||
recorder.begin({ routeTemplate: "/:companyPrefix/issues/:issueId", loadType: "client", startTime: performance.now() });
|
||||
handle = startTracingSdk(config, recorder, { exporter });
|
||||
|
||||
await fetch(`${window.location.origin}/api/issues/PAP-77?includeComments=true`);
|
||||
await fetch("https://third-party.example.com/api/collect?user=someone");
|
||||
await fetch(`${window.location.origin}/assets/index.js`);
|
||||
|
||||
const headersOf = (call: unknown[]) => new Headers((call[1] as RequestInit | undefined)?.headers);
|
||||
expect(headersOf(fetchMock.mock.calls[0]!).get("traceparent")).toMatch(/^00-[0-9a-f]{32}-[0-9a-f]{16}-01$/);
|
||||
expect(headersOf(fetchMock.mock.calls[1]!).get("traceparent")).toBeNull();
|
||||
expect(headersOf(fetchMock.mock.calls[2]!).get("traceparent")).toBeNull();
|
||||
|
||||
(recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames();
|
||||
// Fetch spans end after the instrumentation's resource-timing wait.
|
||||
await new Promise((resolve) => setTimeout(resolve, 400));
|
||||
await handle.forceFlush();
|
||||
const fetchSpans = exporter.getFinishedSpans().filter((span) => span.name !== "page.load");
|
||||
expect(fetchSpans).toHaveLength(1);
|
||||
const [span] = fetchSpans;
|
||||
expect(span!.name).toBe("GET");
|
||||
expect(span!.attributes).toMatchObject({
|
||||
"http.request.method": "GET",
|
||||
"http.response.status_code": 200,
|
||||
"paperclip.api.area": "issues",
|
||||
"paperclip.page.route": "/:companyPrefix/issues/:issueId",
|
||||
});
|
||||
const serialized = JSON.stringify(span!.attributes);
|
||||
expect(serialized).not.toContain("PAP-77");
|
||||
expect(serialized).not.toContain("includeComments");
|
||||
expect(serialized).not.toContain("://");
|
||||
expect(serialized).not.toContain(window.location.host);
|
||||
expect(span!.attributes["url.full"]).toBeUndefined();
|
||||
// The open navigation is the parent, so the server span joins its trace.
|
||||
const pageSpan = exporter.getFinishedSpans().find((s) => s.name === "page.load");
|
||||
expect(span!.spanContext().traceId).toBe(pageSpan!.spanContext().traceId);
|
||||
expect(span!.parentSpanContext?.spanId).toBe(pageSpan!.spanContext().spanId);
|
||||
const traceparent = headersOf(fetchMock.mock.calls[0]!).get("traceparent")!;
|
||||
expect(traceparent.split("-")[1]).toBe(pageSpan!.spanContext().traceId);
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser tracing helpers", () => {
|
||||
it("ignores every URL outside this origin's API", () => {
|
||||
const pattern = nonApiUrlPattern("https://acme.paperclip.app");
|
||||
expect(pattern.test("https://acme.paperclip.app/api/issues")).toBe(false);
|
||||
expect(pattern.test("https://acme.paperclip.app/assets/a.js")).toBe(true);
|
||||
expect(pattern.test("https://acme.paperclip.app.evil.com/api/issues")).toBe(true);
|
||||
expect(pattern.test("https://api.honeycomb.io/v1/traces")).toBe(true);
|
||||
});
|
||||
|
||||
it("reduces an API URL to its fixed area name", () => {
|
||||
expect(apiAreaFromUrl("https://x.test/api/issues/PAP-1/comments?q=secret")).toBe("issues");
|
||||
expect(apiAreaFromUrl("https://x.test/api/0f6b6d1e-2c4f/thing")).toBe("other");
|
||||
expect(apiAreaFromUrl("https://x.test/assets/a.js")).toBeNull();
|
||||
});
|
||||
|
||||
it("converts a sample ratio to Honeycomb's one-in-N SampleRate", () => {
|
||||
expect(honeycombSampleRate(1)).toBeNull();
|
||||
expect(honeycombSampleRate(0.25)).toBe(4);
|
||||
expect(honeycombSampleRate(0.3)).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
// The browser tracing SDK. Loaded only by `controller.ts` through a dynamic
|
||||
// import, after the page settles, so it is a separate chunk that a self-hosted
|
||||
// install, a signed-out page, or an unsampled session never downloads.
|
||||
//
|
||||
// Plain OpenTelemetry web packages are used rather than
|
||||
// `@honeycombio/opentelemetry-web`: that distribution adds the full page URL,
|
||||
// query string, hash, referrer, and user agent to every span and to the
|
||||
// resource by default, and bundles log and metric pipelines this feature does
|
||||
// not use. Honeycomb needs only OTLP/HTTP plus its ingest-key header.
|
||||
//
|
||||
// Emitted spans (see doc/browser-performance-tracing.md):
|
||||
// page.load one per hard load or client-side navigation
|
||||
// web_vital.lcp|inp|cls Core Web Vitals
|
||||
// GET|POST|… same-origin `/api/` fetches, with W3C trace context
|
||||
// so the server's request span joins the trace
|
||||
|
||||
import { context, propagation, trace, ROOT_CONTEXT, type Context, type Span } from "@opentelemetry/api";
|
||||
import {
|
||||
AlwaysOnSampler,
|
||||
BatchSpanProcessor,
|
||||
StackContextManager,
|
||||
WebTracerProvider,
|
||||
type SpanExporter,
|
||||
type SpanProcessor,
|
||||
} from "@opentelemetry/sdk-trace-web";
|
||||
import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
|
||||
import { resourceFromAttributes } from "@opentelemetry/resources";
|
||||
import { onCLS, onINP, onLCP, type Metric } from "web-vitals";
|
||||
import type { BrowserTracingConfig } from "@paperclipai/shared";
|
||||
import type { TracingSdkHandle } from "./controller";
|
||||
import type { PageLoadMeasurement, PageLoadRecorder } from "./page-load-recorder";
|
||||
import { OtlpFetchExporter } from "./otlp-fetch-exporter";
|
||||
import { SanitizingSpanExporter } from "./span-sanitizer";
|
||||
|
||||
const TRACER_NAME = "paperclip.browser";
|
||||
|
||||
/**
|
||||
* Makes the open page-load span the parent of work started while it is open,
|
||||
* so a navigation's API requests (and through trace context, their server
|
||||
* spans) appear under it in one trace.
|
||||
*/
|
||||
class PageLoadContextManager extends StackContextManager {
|
||||
constructor(private readonly openPageSpan: () => Span | null) {
|
||||
super();
|
||||
}
|
||||
|
||||
override active(): Context {
|
||||
const active = super.active();
|
||||
if (active !== ROOT_CONTEXT) return active;
|
||||
const span = this.openPageSpan();
|
||||
return span ? trace.setSpan(active, span) : active;
|
||||
}
|
||||
}
|
||||
|
||||
/** Escapes a string for use inside a regular expression. */
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/** Matches every URL that is not this origin's `/api/`; those get no span. */
|
||||
export function nonApiUrlPattern(origin: string): RegExp {
|
||||
return new RegExp(`^(?!${escapeRegExp(origin)}/api/)`);
|
||||
}
|
||||
|
||||
function roundMs(value: number): number {
|
||||
return Math.round(value);
|
||||
}
|
||||
|
||||
function navigationTimingAttributes(): Record<string, string | number> {
|
||||
const entry = performance.getEntriesByType?.("navigation")[0] as PerformanceNavigationTiming | undefined;
|
||||
if (!entry) return {};
|
||||
const attributes: Record<string, string | number> = { "paperclip.page.navigation_type": entry.type };
|
||||
if (entry.responseStart > 0) attributes["paperclip.page.ttfb_ms"] = roundMs(entry.responseStart);
|
||||
if (entry.domContentLoadedEventEnd > 0) attributes["paperclip.page.dom_content_loaded_ms"] = roundMs(entry.domContentLoadedEventEnd);
|
||||
if (entry.loadEventEnd > 0) attributes["paperclip.page.load_event_ms"] = roundMs(entry.loadEventEnd);
|
||||
return attributes;
|
||||
}
|
||||
|
||||
export function pageLoadAttributes(measurement: PageLoadMeasurement): Record<string, string | boolean> {
|
||||
return {
|
||||
"paperclip.page.route": measurement.routeTemplate,
|
||||
"paperclip.page.load_type": measurement.loadType,
|
||||
"paperclip.page.outcome": measurement.outcome ?? "interrupted",
|
||||
"paperclip.page.ready_signal": measurement.readySignal ?? "none",
|
||||
"paperclip.page.was_hidden": measurement.wasHidden,
|
||||
};
|
||||
}
|
||||
|
||||
/** Honeycomb weights each event by its `SampleRate` (1 in N). */
|
||||
export function honeycombSampleRate(sampleRate: number): number | null {
|
||||
return sampleRate >= 1 ? null : Math.max(1, Math.round(1 / sampleRate));
|
||||
}
|
||||
|
||||
export interface TracingSdkOptions {
|
||||
/** Replaces the OTLP exporter (tests). Spans are still sanitized. */
|
||||
exporter?: SpanExporter;
|
||||
}
|
||||
|
||||
export function startTracingSdk(
|
||||
config: BrowserTracingConfig,
|
||||
recorder: PageLoadRecorder,
|
||||
options: TracingSdkOptions = {},
|
||||
): TracingSdkHandle {
|
||||
const pageSpans = new Map<number, Span>();
|
||||
let openPageSpan: Span | null = null;
|
||||
let stopped = false;
|
||||
|
||||
// Captured before fetch instrumentation patches `fetch`, so exports are never traced.
|
||||
const uninstrumentedFetch = window.fetch.bind(window);
|
||||
const exporter = new SanitizingSpanExporter(options.exporter ?? new OtlpFetchExporter({
|
||||
url: config.tracesUrl,
|
||||
headers: config.ingestKey ? { "x-honeycomb-team": config.ingestKey } : {},
|
||||
fetch: uninstrumentedFetch,
|
||||
}));
|
||||
|
||||
const sampleRateAttribute = honeycombSampleRate(config.sampleRate);
|
||||
const routeProcessor: SpanProcessor = {
|
||||
onStart(span) {
|
||||
const route = recorder.currentRouteTemplate();
|
||||
if (route && span.attributes["paperclip.page.route"] === undefined) {
|
||||
span.setAttribute("paperclip.page.route", route);
|
||||
}
|
||||
if (sampleRateAttribute !== null) span.setAttribute("SampleRate", sampleRateAttribute);
|
||||
},
|
||||
onEnd() {},
|
||||
forceFlush: () => Promise.resolve(),
|
||||
shutdown: () => Promise.resolve(),
|
||||
};
|
||||
|
||||
const buildCommit = typeof __PAPERCLIP_BUILD_COMMIT__ === "string" ? __PAPERCLIP_BUILD_COMMIT__ : null;
|
||||
const provider = new WebTracerProvider({
|
||||
resource: resourceFromAttributes({
|
||||
"service.name": config.serviceName,
|
||||
...(buildCommit ? { "service.version": buildCommit } : {}),
|
||||
...(config.environment ? { "deployment.environment.name": config.environment } : {}),
|
||||
}),
|
||||
// Sampling is decided once per page session before this chunk loads.
|
||||
sampler: new AlwaysOnSampler(),
|
||||
spanProcessors: [routeProcessor, new BatchSpanProcessor(exporter)],
|
||||
});
|
||||
provider.register({ contextManager: new PageLoadContextManager(() => openPageSpan) });
|
||||
const tracer = provider.getTracer(TRACER_NAME);
|
||||
|
||||
const fetchInstrumentation = new FetchInstrumentation({
|
||||
// Only this origin's API gets spans, and only it receives trace
|
||||
// headers: no third-party origin is listed for propagation.
|
||||
ignoreUrls: [nonApiUrlPattern(window.location.origin)],
|
||||
propagateTraceHeaderCorsUrls: [],
|
||||
clearTimingResources: false,
|
||||
enabled: false,
|
||||
});
|
||||
fetchInstrumentation.setTracerProvider(provider);
|
||||
fetchInstrumentation.enable();
|
||||
|
||||
recorder.attachSink({
|
||||
begin(measurement) {
|
||||
const span = tracer.startSpan("page.load", {
|
||||
root: true,
|
||||
startTime: measurement.startTime,
|
||||
attributes: {
|
||||
"paperclip.page.route": measurement.routeTemplate,
|
||||
"paperclip.page.load_type": measurement.loadType,
|
||||
},
|
||||
});
|
||||
pageSpans.set(measurement.id, span);
|
||||
if (measurement.endTime === null) openPageSpan = span;
|
||||
},
|
||||
end(measurement) {
|
||||
const span = pageSpans.get(measurement.id);
|
||||
if (!span) return;
|
||||
pageSpans.delete(measurement.id);
|
||||
if (openPageSpan === span) openPageSpan = null;
|
||||
span.setAttributes(pageLoadAttributes(measurement));
|
||||
if (measurement.loadType === "hard") span.setAttributes(navigationTimingAttributes());
|
||||
span.end(measurement.endTime ?? performance.now());
|
||||
},
|
||||
});
|
||||
|
||||
const reportVital = (metric: Metric) => {
|
||||
if (stopped) return;
|
||||
const route = (metric.name === "LCP" ? recorder.hardLoadRouteTemplate() : null) ?? recorder.currentRouteTemplate();
|
||||
const time = performance.now();
|
||||
const span = tracer.startSpan(`web_vital.${metric.name.toLowerCase()}`, {
|
||||
root: true,
|
||||
startTime: time,
|
||||
attributes: {
|
||||
"paperclip.web_vital.name": metric.name,
|
||||
"paperclip.web_vital.value": metric.value,
|
||||
"paperclip.web_vital.rating": metric.rating,
|
||||
...(route ? { "paperclip.page.route": route } : {}),
|
||||
},
|
||||
});
|
||||
span.end(time);
|
||||
// Vitals are usually reported as the tab hides; send them before unload.
|
||||
if (document.visibilityState === "hidden") void provider.forceFlush();
|
||||
};
|
||||
onLCP(reportVital);
|
||||
onINP(reportVital);
|
||||
onCLS(reportVital);
|
||||
|
||||
return {
|
||||
forceFlush: () => provider.forceFlush(),
|
||||
async shutdown() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
// Unfinished page loads are dropped, not exported half measured.
|
||||
pageSpans.clear();
|
||||
openPageSpan = null;
|
||||
fetchInstrumentation.disable();
|
||||
await provider.shutdown().catch(() => undefined);
|
||||
trace.disable();
|
||||
context.disable();
|
||||
propagation.disable();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// The closed attribute allowlist for browser spans. Every span passes through
|
||||
// `SanitizingSpanExporter` before it leaves the browser, so an attribute that
|
||||
// an OpenTelemetry instrumentation adds (a full URL, a server address, an
|
||||
// error message) is dropped unless it is listed here. Keep this list and the
|
||||
// table in doc/browser-performance-tracing.md in sync.
|
||||
//
|
||||
// Part of the lazily loaded tracing chunk; the main bundle never imports it.
|
||||
|
||||
import type { ReadableSpan, SpanExporter } from "@opentelemetry/sdk-trace-web";
|
||||
import { resourceFromAttributes, type Resource } from "@opentelemetry/resources";
|
||||
import type { Attributes } from "@opentelemetry/api";
|
||||
|
||||
export const ALLOWED_SPAN_ATTRIBUTES: ReadonlySet<string> = new Set([
|
||||
"paperclip.page.route",
|
||||
"paperclip.page.load_type",
|
||||
"paperclip.page.outcome",
|
||||
"paperclip.page.ready_signal",
|
||||
"paperclip.page.was_hidden",
|
||||
"paperclip.page.navigation_type",
|
||||
"paperclip.page.ttfb_ms",
|
||||
"paperclip.page.dom_content_loaded_ms",
|
||||
"paperclip.page.load_event_ms",
|
||||
"paperclip.web_vital.name",
|
||||
"paperclip.web_vital.value",
|
||||
"paperclip.web_vital.rating",
|
||||
"paperclip.api.area",
|
||||
"http.request.method",
|
||||
"http.response.status_code",
|
||||
"error.type",
|
||||
"SampleRate",
|
||||
]);
|
||||
|
||||
export const ALLOWED_RESOURCE_ATTRIBUTES: ReadonlySet<string> = new Set([
|
||||
"service.name",
|
||||
"service.version",
|
||||
"deployment.environment.name",
|
||||
"telemetry.sdk.name",
|
||||
"telemetry.sdk.language",
|
||||
"telemetry.sdk.version",
|
||||
]);
|
||||
|
||||
const API_AREA_PATTERN = /^[a-z][a-z0-9-]{0,40}$/;
|
||||
|
||||
/**
|
||||
* The first path segment after `/api/` when it is a fixed lowercase word such
|
||||
* as `issues` or `companies`; `other` for anything else. Ids, query strings,
|
||||
* and the rest of the path are never kept. The server span for the same
|
||||
* request carries the exact route pattern.
|
||||
*/
|
||||
export function apiAreaFromUrl(url: string): string | null {
|
||||
let pathname: string;
|
||||
try {
|
||||
pathname = new URL(url).pathname;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!pathname.startsWith("/api/")) return null;
|
||||
const segment = pathname.split("/")[2] ?? "";
|
||||
return API_AREA_PATTERN.test(segment) ? segment : "other";
|
||||
}
|
||||
|
||||
function pickAttributes(source: Attributes, allowed: ReadonlySet<string>): Attributes {
|
||||
const result: Attributes = {};
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
if (allowed.has(key)) result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const sanitizedResources = new WeakMap<Resource, Resource>();
|
||||
|
||||
function sanitizeResource(resource: Resource): Resource {
|
||||
let sanitized = sanitizedResources.get(resource);
|
||||
if (!sanitized) {
|
||||
sanitized = resourceFromAttributes(pickAttributes(resource.attributes, ALLOWED_RESOURCE_ATTRIBUTES));
|
||||
sanitizedResources.set(resource, sanitized);
|
||||
}
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
export function sanitizeSpan(span: ReadableSpan): ReadableSpan {
|
||||
const attributes = pickAttributes(span.attributes, ALLOWED_SPAN_ATTRIBUTES);
|
||||
const url = span.attributes["url.full"];
|
||||
if (typeof url === "string") {
|
||||
const area = apiAreaFromUrl(url);
|
||||
if (area) attributes["paperclip.api.area"] = area;
|
||||
}
|
||||
return {
|
||||
name: span.name,
|
||||
kind: span.kind,
|
||||
spanContext: () => span.spanContext(),
|
||||
parentSpanContext: span.parentSpanContext,
|
||||
startTime: span.startTime,
|
||||
endTime: span.endTime,
|
||||
// A status message can carry a URL or error text; keep only the code.
|
||||
status: { code: span.status.code },
|
||||
attributes,
|
||||
links: [],
|
||||
// Network timing events keep their names and times, never attributes.
|
||||
events: span.events.map((event) => ({ name: event.name, time: event.time, droppedAttributesCount: 0 })),
|
||||
duration: span.duration,
|
||||
ended: span.ended,
|
||||
resource: sanitizeResource(span.resource),
|
||||
instrumentationScope: span.instrumentationScope,
|
||||
droppedAttributesCount: 0,
|
||||
droppedEventsCount: span.droppedEventsCount,
|
||||
droppedLinksCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export class SanitizingSpanExporter implements SpanExporter {
|
||||
constructor(private readonly inner: SpanExporter) {}
|
||||
|
||||
export(spans: ReadableSpan[], resultCallback: Parameters<SpanExporter["export"]>[1]): void {
|
||||
this.inner.export(spans.map(sanitizeSpan), resultCallback);
|
||||
}
|
||||
|
||||
shutdown(): Promise<void> {
|
||||
return this.inner.shutdown();
|
||||
}
|
||||
|
||||
forceFlush(): Promise<void> {
|
||||
return this.inner.forceFlush?.() ?? Promise.resolve();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
export const ISSUE_DETAIL_NAVIGATE_MARK = "issue-detail:navigate";
|
||||
export const ISSUE_DETAIL_HEADER_PAINT_MARK = "issue-detail:header-paint";
|
||||
export const ISSUE_DETAIL_CONTENT_PAINT_MARK = "issue-detail:content-paint";
|
||||
@@ -5,6 +7,24 @@ export const ISSUE_DETAIL_HEADER_MEASURE = "issue-detail:navigate→header-paint
|
||||
export const ISSUE_DETAIL_CONTENT_MEASURE = "issue-detail:navigate→content-paint";
|
||||
|
||||
let issueDetailNavigationGeneration = 0;
|
||||
// The paint time of the current navigation's content, for the page-load
|
||||
// measurement (`usePageContentReady`); null until it paints.
|
||||
let contentPaintedAt: number | null = null;
|
||||
const contentPaintListeners = new Set<() => void>();
|
||||
|
||||
function notifyContentPaint(): void {
|
||||
for (const listener of contentPaintListeners) listener();
|
||||
}
|
||||
|
||||
function subscribeContentPaint(listener: () => void): () => void {
|
||||
contentPaintListeners.add(listener);
|
||||
return () => contentPaintListeners.delete(listener);
|
||||
}
|
||||
|
||||
/** `performance.now()` when the current task's content painted, or null. */
|
||||
export function useIssueDetailContentPaintedAt(): number | null {
|
||||
return useSyncExternalStore(subscribeContentPaint, () => contentPaintedAt, () => null);
|
||||
}
|
||||
const readinessGates = ["issue", "comments", "interactions", "attachments", "work-products", "activity", "linked-runs", "runtime", "plan", "transcripts", "history"] as const;
|
||||
type ReadinessGate = typeof readinessGates[number];
|
||||
const readinessState = new Map<ReadinessGate, boolean>();
|
||||
@@ -22,6 +42,10 @@ function supportsPerformanceMarks(): boolean {
|
||||
|
||||
export function beginIssueDetailNavigation(): void {
|
||||
issueDetailNavigationGeneration += 1;
|
||||
if (contentPaintedAt !== null) {
|
||||
contentPaintedAt = null;
|
||||
notifyContentPaint();
|
||||
}
|
||||
if (!supportsPerformanceMarks()) return;
|
||||
|
||||
performance.clearMarks(ISSUE_DETAIL_NAVIGATE_MARK);
|
||||
@@ -66,6 +90,10 @@ export function scheduleIssueDetailPaintMeasure(
|
||||
}
|
||||
performance.mark(markName);
|
||||
performance.measure(measureName, ISSUE_DETAIL_NAVIGATE_MARK, markName);
|
||||
if (markName === ISSUE_DETAIL_CONTENT_PAINT_MARK) {
|
||||
contentPaintedAt = performance.now();
|
||||
notifyContentPaint();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -162,7 +162,9 @@ import {
|
||||
ISSUE_DETAIL_HEADER_PAINT_MARK,
|
||||
reportIssueDetailWebVitals,
|
||||
scheduleIssueDetailPaintMeasure,
|
||||
useIssueDetailContentPaintedAt,
|
||||
} from "../lib/issue-detail-performance";
|
||||
import { usePageContentReady } from "../hooks/usePageContentReady";
|
||||
import {
|
||||
beginLocalInboxArchive,
|
||||
boundLocalInboxArchive,
|
||||
@@ -3526,6 +3528,11 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
useLayoutEffect(() => {
|
||||
beginIssueDetailNavigation();
|
||||
}, [issueId]);
|
||||
// The task page is loaded when its conversation content has painted: the
|
||||
// same point as the `issue-detail:navigate→content-paint` measure. An agent
|
||||
// chat with no saved task never records that mark, so it uses the generic rule.
|
||||
const contentPaintedAt = useIssueDetailContentPaintedAt();
|
||||
usePageContentReady(contentPaintedAt !== null, contentPaintedAt, { enabled: Boolean(issueId) });
|
||||
|
||||
useEffect(() => {
|
||||
if (!(import.meta.env.DEV || import.meta.env.MODE === "qa")) return;
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
type TaskViewKey,
|
||||
} from "../lib/task-views";
|
||||
import { useUpdateIssueMutation } from "../hooks/useUpdateIssueMutation";
|
||||
import { usePageContentReady } from "../hooks/usePageContentReady";
|
||||
|
||||
const WORKSPACE_FILTER_ISSUE_LIMIT = 1000;
|
||||
const ISSUES_PAGE_SIZE = 100;
|
||||
@@ -313,6 +314,8 @@ function OrganizationIssues({
|
||||
|
||||
const { data: issuePages, isFetchingNextPage, hasNextPage, fetchNextPage } = issuesQuery;
|
||||
const issuesView = useQueryView(issuesQuery);
|
||||
// The task list is loaded once its first page of rows has rendered.
|
||||
usePageContentReady(!selectedCompanyId || (issuesView.kind !== "loading" && issuesView.kind !== "reconnecting"));
|
||||
const issues = useMemo(() => mergeIssuePagesStable(issuePages?.pages ?? []) as Issue[], [issuePages]);
|
||||
const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns, issues), [issues, liveRuns]);
|
||||
const hasMoreServerIssues = syncedSearch.trim().length === 0
|
||||
|
||||
Reference in new issue
Block a user