diff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.md index e5ef11d0..48caa80f 100644 --- a/apps/web/CLAUDE.md +++ b/apps/web/CLAUDE.md @@ -17,6 +17,7 @@ bun run generate-routes # tsr generate — regenerates routeTree.gen.ts - Outside it: `index.tsx` (a redirect into the workspace; the public pages live in `apps/site`, see `docs/domains/deployment.md`), `login.tsx`, `choose-organization.tsx` (the workspace chooser for a link such as `/:org/settings`; see `docs/domains/authentication.md`), `accept-invite/$invitationId.tsx`, `no-access.tsx`, `device.tsx` (approves a CLI login) and `cli/` (the install scripts and binary downloads). - Server routes: `api/auth/$.ts` (better-auth), `api/login.ts`, `api/mcp-login.ts`, `api/github/setup.ts`, `api/slack/callback.ts`, `api/files/$.ts`, `api/assistant/stream.ts`, `api/mcp/$orgSlug.ts`, `[.]well-known/oauth-*.ts`, `api/v1/projects` + `api/v1/time-entries` (cookie-authed REST reads), and `api/v1/{meta,me,session}`, `api/v1/me/devices` (the mobile app's phone, see `docs/domains/mobile.md`) + `api/v1/orgs/$orgSlug/*` (the CLI's API). `api/v1/openapi[.]json.ts` serves the OpenAPI document that `lib/openapi.ts` builds, and `api-docs.tsx` renders it with Scalar. **A new `api/v1` route needs an entry in `OPERATIONS`** — `lib/openapi.test.ts` fails until the two lists match, and each response schema there is checked against its `@farmer/core/api` type at compile time. That API takes two bearer credentials — a device-flow session token and a personal API token (`fmr_…`, Preferences → API tokens, `components/api-tokens-settings.tsx`); `docs/domains/api-tokens.md` has the rules, including the read-only 403 in `serve` and the `session` scheme that lets `/api-docs` send requests as the signed-in reader (`?org=` on the OpenAPI route; never add CORS headers to `api/v1`). All of that auth lives in `server/api-auth.ts` — deliberately NOT `server/auth.ts`, see the client-bundle rule below. - `reports.tsx` is the shell. Its four tabs — Time, Overtime, Tracking (`compliance`) and Absence — are declared in `components/reports/search.ts` and live in `components/reports/`. `periodSearch` there is shared with the project page. +- `src/client.tsx` — the custom client entry that TanStack Start picks up by name. It is the default entry plus an `onRecoverableError` that captures hydration errors in PostHog (see `docs/domains/deployment.md`). - `src/server/` — thin `createServerFn` wrappers, one file per aggregate, mirroring `services/`. **Auth is attached via middleware** (`sessionMiddleware` / `orgMiddleware` / `orgAdminMiddleware` from `server/auth.ts`), read from the handler's `context` — never by calling `requireOrgContext()` inline, so the protection is part of the function's declared shape. `auth.ts` itself is the only place the bare helpers are called, because route `beforeLoad`s need them. `orgMiddleware` re-checks membership inside its `.server()` callback rather than in a shared helper: a top-level function body in `auth.ts` ships to the browser, so a deferred `import("@farmer/core/services")` there becomes a real client chunk. - `src/queries/` — TanStack Query `queryOptions` factories, one per aggregate; loaders prefetch, components read via `useSuspenseQuery`. **Every key names its organization**: factories take the slug first (`timeEntriesRangeQuery(orgSlug, from, to)`) and spread their root from `queryKeys(orgSlug)` in `queries/keys.ts`; invalidations name the same root. Components get the slug from `useOrgSlug()`, loaders from `params.orgSlug`. Never write a bare `queryKey: ["…"]` literal and never drop the org — an org-blind key is an answer from the previous workspace. Server functions are deliberately NOT generated from a shared declaration — see `docs/adr/0001-no-server-function-generator.md`. - `src/components/ui/` — shadcn on **Base UI** (`@base-ui/react`), not Radix (`components.json` style is `base-nova`). Composition uses the `render` prop, not `asChild`. The project picker (grouped by client) and task picker (grouped by `taskGroup`) are in `components/pickers/`. The task picker leaves out the tasks the person switched off (`pickers/your-tasks.tsx`, also Preferences → Your tasks), search included, except the task already chosen and Recent; its grouped list ends in Edit list. diff --git a/apps/web/src/client.tsx b/apps/web/src/client.tsx new file mode 100644 index 00000000..bf93056e --- /dev/null +++ b/apps/web/src/client.tsx @@ -0,0 +1,42 @@ +import { StartClient } from "@tanstack/react-start/client"; +import posthog from "posthog-js"; +import { StrictMode, startTransition } from "react"; +import { type HydrationOptions, hydrateRoot } from "react-dom/client"; + +const TRANSLATED = ["translated-ltr", "translated-rtl"]; + +/** + * Report an error that React recovered from, such as a hydration mismatch + * (React error #418). The production message names no component, so the + * event holds the component stack. Chrome's page translation edits the DOM + * and the `lang` attribute, so the event says if it was on. + * + * Not `reportError`: React's default handler calls it, and the `error` event + * that it fires is already captured by posthog-js. This handler replaces + * the default, so each error is captured one time. + */ +const onRecoverableError: NonNullable< + HydrationOptions["onRecoverableError"] +> = (error, errorInfo) => { + if (posthog.__loaded) { + const classes = document.documentElement.classList; + posthog.captureException(error, { + react_component_stack: errorInfo.componentStack, + html_lang: document.documentElement.lang, + html_translated: TRANSLATED.some((name) => classes.contains(name)), + pathname: location.pathname, + }); + } + console.error(error); +}; + +// The default entry of TanStack Start, plus `onRecoverableError`. +startTransition(() => { + hydrateRoot( + document, + + + , + { onRecoverableError }, + ); +}); diff --git a/apps/web/src/lib/capture-failure.test.ts b/apps/web/src/lib/capture-failure.test.ts index 8080dfe4..77701311 100644 --- a/apps/web/src/lib/capture-failure.test.ts +++ b/apps/web/src/lib/capture-failure.test.ts @@ -1,12 +1,17 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; -import { captureFailure } from "./capture-failure"; +import { PostHog } from "posthog-node"; + +import { captureFailure, SLOW_SERVER_FN_MS } from "./capture-failure"; +import * as posthogServer from "./posthog-server"; + +const META = { id: "abc", name: "fn", filename: "file.ts" }; const run = (error: Error) => captureFailure( { next: () => Promise.reject(error), - serverFnMeta: { name: "fn", filename: "file.ts" }, + serverFnMeta: META, }, // No request here: the capture fails, and the error must still come out. () => { @@ -26,3 +31,121 @@ describe("captureFailure", () => { expect(await run(error).catch((e) => e)).toBe(error); }); }); + +describe("slow server functions", () => { + const client = new PostHog("test-token", { disabled: true }); + const capture = spyOn(client, "capture").mockImplementation(() => {}); + + /** Run a call that takes `ms` on a fake clock, with the request `headers`. */ + const call = async (ms: number, headers: Headers, fails = false) => { + let clock = 0; + const now = spyOn(performance, "now").mockImplementation(() => clock); + try { + await captureFailure( + { + next: () => { + clock += ms; + return fails ? Promise.reject(new Error("x")) : Promise.resolve(1); + }, + serverFnMeta: META, + }, + () => headers, + ).catch(() => {}); + } finally { + now.mockRestore(); + } + }; + + const events = () => capture.mock.calls.map(([message]) => message); + + /** The report is a background task: wait until PostHog got an event of + * this duration. Reports run in call order, so earlier ones are in. */ + const waitForEventOf = async (durationMs: number) => { + const deadline = Date.now() + 5000; + while ( + !events().some((e) => e.properties?.duration_ms === durationMs) && + Date.now() < deadline + ) { + await Bun.sleep(5); + } + return events(); + }; + + const withClient = async (run: () => Promise) => { + capture.mockClear(); + const getClient = spyOn(posthogServer, "getPostHogClient").mockReturnValue( + client, + ); + try { + await run(); + } finally { + getClient.mockRestore(); + } + }; + + test("a fast call sends nothing and a slow call sends one event", () => + withClient(async () => { + await call(SLOW_SERVER_FN_MS - 1, new Headers()); + await call(SLOW_SERVER_FN_MS, new Headers()); + const sent = await waitForEventOf(SLOW_SERVER_FN_MS); + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + event: "server_fn_slow", + properties: { + server_fn_id: "abc", + server_fn_name: "fn", + duration_ms: SLOW_SERVER_FN_MS, + threw: false, + }, + }); + })); + + test("a slow call that throws is reported as one that threw", () => + withClient(async () => { + await call(SLOW_SERVER_FN_MS, new Headers(), true); + const sent = await waitForEventOf(SLOW_SERVER_FN_MS); + expect(sent).toMatchObject([{ properties: { threw: true } }]); + })); + + /** A call that ends after `endMs` real time; the pending mark is `markMs`. */ + const lateCall = async (markMs: number, endMs: number, headers: Headers) => { + await captureFailure( + { + next: () => Bun.sleep(endMs).then(() => 1), + serverFnMeta: META, + }, + () => headers, + markMs, + ); + }; + + test("a call still pending at the mark sends one pending event", () => + withClient(async () => { + await lateCall(10, 60, new Headers()); + const sent = await waitForEventOf(10); + // The finish of the same call sends no second event. + await Bun.sleep(50); + expect(events()).toHaveLength(1); + expect(sent[0]).toMatchObject({ + event: "server_fn_slow", + properties: { server_fn_id: "abc", duration_ms: 10, pending: true }, + }); + })); + + test("a call that ends before the mark sends no pending event", () => + withClient(async () => { + await lateCall(50, 1, new Headers()); + await Bun.sleep(100); + expect(events()).toHaveLength(0); + })); + + test("two slow calls of one request send one event", () => + withClient(async () => { + const headers = new Headers(); + await call(SLOW_SERVER_FN_MS, headers); + await call(SLOW_SERVER_FN_MS, headers); + // Another request gets its own event. + await call(2 * SLOW_SERVER_FN_MS, new Headers()); + expect(await waitForEventOf(2 * SLOW_SERVER_FN_MS)).toHaveLength(2); + })); +}); diff --git a/apps/web/src/lib/capture-failure.ts b/apps/web/src/lib/capture-failure.ts index f4a7d11d..2eb76e3c 100644 --- a/apps/web/src/lib/capture-failure.ts +++ b/apps/web/src/lib/capture-failure.ts @@ -1,3 +1,5 @@ +import type { ServerFnCall } from "./posthog-api"; + /** * Send the unexpected failure of a server function to PostHog error tracking. * @@ -6,7 +8,10 @@ * it: it runs after the throw and is never awaited. A failure of the capture * is logged and dropped. Only a fault is captured: see `isServerFnFault`. The * person is read from the session because the middleware runs before - * `orgMiddleware`, so it has no `ctx`. + * `orgMiddleware`, so it has no `ctx`. A call that takes `SLOW_SERVER_FN_MS` + * or more is reported in the same way, as a `server_fn_slow` event, also + * when it throws. A call still pending at `PENDING_SERVER_FN_MS` is reported + * then, with `pending: true`, and not again when it ends. * * `start.ts` reaches this module with a deferred `import()` inside the * middleware callback, which TanStack strips from the client bundle. A static @@ -18,34 +23,69 @@ export const captureFailure = async ( serverFnMeta, }: { next: () => Promise; - serverFnMeta: { name: string; filename: string }; + serverFnMeta: { id: string; name: string; filename: string }; }, readHeaders: () => Headers, + pendingMs: number = PENDING_SERVER_FN_MS, ): Promise => { + const start = performance.now(); + let error: Error | null = null; + let threw = false; + let pendingReported = false; + // A call that never ends sends no report from `finally`, so report it here. + const timer = setTimeout(() => { + pendingReported = true; + reportInBackground( + { error: null, threw: false, slowMs: pendingMs, pending: true }, + serverFnMeta, + readHeaders, + ); + }, pendingMs); + timer.unref(); try { return await next(); - } catch (error) { - if (error instanceof Error) { - reportInBackground(error, serverFnMeta, readHeaders); - } - throw error; + } catch (thrown) { + threw = true; + if (thrown instanceof Error) error = thrown; + throw thrown; + } finally { + clearTimeout(timer); + const durationMs = performance.now() - start; + reportInBackground( + { + error, + threw, + slowMs: + !pendingReported && durationMs >= SLOW_SERVER_FN_MS + ? durationMs + : null, + pending: false, + }, + serverFnMeta, + readHeaders, + ); } }; +/** A call at or over this duration is sent as a `server_fn_slow` event. */ +export const SLOW_SERVER_FN_MS = 1000; + +/** A call still pending at this mark is sent as a `server_fn_slow` event. */ +export const PENDING_SERVER_FN_MS = 10_000; + const reportInBackground = ( - error: Error, - meta: { name: string; filename: string }, + call: ServerFnCall, + meta: { id: string; name: string; filename: string }, readHeaders: () => Headers, ): void => { + if (!call.error && call.slowMs === null) return; const fail = (captureError: Error) => console.error("server function capture failed", captureError); try { // Read at once, while the request context is current. const headers = readHeaders(); void import("./posthog-api") - .then(({ reportServerFnError }) => - reportServerFnError(error, headers, meta), - ) + .then(({ reportServerFnCall }) => reportServerFnCall(headers, meta, call)) .catch(fail); } catch (captureError) { console.error("server function capture failed", captureError); diff --git a/apps/web/src/lib/posthog-api.ts b/apps/web/src/lib/posthog-api.ts index fdaab16b..9661892c 100644 --- a/apps/web/src/lib/posthog-api.ts +++ b/apps/web/src/lib/posthog-api.ts @@ -184,29 +184,111 @@ export const claimServerFnError = (error: Error): boolean => { return true; }; +export type ServerFnCall = { + /** The error that the call threw, if it is an `Error`. */ + error: Error | null; + /** The duration of a call at or over the slow threshold, else null. */ + slowMs: number | null; + threw: boolean; + /** The call had not ended when it was reported. */ + pending: boolean; +}; + +const slowReported = new WeakSet(); + +/** The error, when this call is the first to report it and it is a fault. */ +const claimFault = async (error: Error | null): Promise => { + if (!error || !claimServerFnError(error)) return null; + return (await isServerFnFault(error)) ? error : null; +}; + +/** The duration, when this request has not sent a slow event yet. */ +const claimSlow = (headers: Headers, slowMs: number | null): number | null => { + if (slowMs === null || slowReported.has(headers)) return null; + slowReported.add(headers); + return slowMs; +}; + +const sessionPerson = async (headers: Headers) => { + const { auth } = await import("@farmer/core/auth"); + const session = await auth.api.getSession({ headers }).catch(() => null); + return { + userId: session?.user.id ?? null, + organizationId: session?.session.activeOrganizationId ?? null, + }; +}; + /** - * Report the error of a server function, if it is a fault. + * Report a server function call: its error, if it is a fault, and its + * duration, if it is slow. * * The caller does not await this: a metric must not delay the answer, and - * the session lookup is one more query on a pool that may be the fault. The - * claim comes first and runs before any `await`, so the inner and the outer - * middleware of a nested call cannot both pass it. `headers` are read by the - * caller, while the request context is still current. + * the session lookup is one more query on a pool that may be the fault, so + * it runs one time for both reports and only when one of them is due. The + * claims come first and run before any `await`, so the inner and the outer + * middleware of a nested call cannot both pass them. A request sends one + * slow event: its `headers` are the same object in a nested call. `headers` + * are read by the caller, while the request context is still current. */ -export const reportServerFnError = async ( - error: Error, +export const reportServerFnCall = async ( headers: Headers, - fn: { name: string; filename: string }, + fn: { id: string; name: string; filename: string }, + call: ServerFnCall, ): Promise => { - if (!claimServerFnError(error)) return; - if (!(await isServerFnFault(error))) return; - const { auth } = await import("@farmer/core/auth"); - const session = await auth.api.getSession({ headers }).catch(() => null); - captureServerFnFailure(error, { - userId: session?.user.id ?? null, - organizationId: session?.session.activeOrganizationId ?? null, - fn: fn.name, - file: fn.filename, + // Both claims start before the first `await`. + const pendingFault = claimFault(call.error); + const slowMs = claimSlow(headers, call.slowMs); + const fault = await pendingFault; + if (!fault && slowMs === null) return; + const person = await sessionPerson(headers); + if (fault) { + captureServerFnFailure(fault, { + ...person, + fn: fn.name, + file: fn.filename, + }); + } + if (slowMs !== null) { + captureSlowServerFn({ + ...person, + id: fn.id, + fn: fn.name, + file: fn.filename, + durationMs: slowMs, + threw: call.threw, + pending: call.pending, + }); + } +}; + +/** A server function that took long. The properties name the function, + * never its input. */ +export const captureSlowServerFn = (ctx: { + userId: string | null; + organizationId: string | null; + id: string; + fn: string; + file: string; + durationMs: number; + threw: boolean; + pending: boolean; +}): void => { + const properties = { + organization_id: ctx.organizationId, + server_fn_id: ctx.id, + server_fn_name: ctx.fn, + server_fn_file: ctx.file, + duration_ms: Math.round(ctx.durationMs), + threw: ctx.threw, + pending: ctx.pending, + }; + getPostHogClient()?.capture({ + distinctId: ctx.userId ?? "server-fn-anonymous", + event: "server_fn_slow", + // No person to attach to: do not mint a profile for the bucket id. + properties: ctx.userId + ? properties + : { ...properties, $process_person_profile: false }, }); }; diff --git a/apps/web/src/lib/posthog-client.test.ts b/apps/web/src/lib/posthog-client.test.ts new file mode 100644 index 00000000..59fe9b35 --- /dev/null +++ b/apps/web/src/lib/posthog-client.test.ts @@ -0,0 +1,80 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; + +import posthog from "posthog-js"; + +import { fetchReportingNetworkErrors, watchUnload } from "./posthog-client"; + +describe("fetchReportingNetworkErrors", () => { + const capture = spyOn(posthog, "capture").mockImplementation(() => undefined); + + beforeEach(() => { + capture.mockClear(); + posthog.__loaded = true; + }); + afterEach(() => { + posthog.__loaded = false; + }); + + const callWith = (base: () => Promise) => + fetchReportingNetworkErrors( + "abc", + base, + )("/_serverFn/abc").then( + (response) => response, + (error: Error) => error, + ); + + test("a fetch that rejects sends one event and rethrows the same error", async () => { + const error = new TypeError("NetworkError when attempting to fetch"); + + expect(await callWith(() => Promise.reject(error))).toBe(error); + expect(capture).toHaveBeenCalledTimes(1); + expect(capture.mock.calls[0]?.[0]).toBe("server_fn_network_error"); + expect(capture.mock.calls[0]?.[1]).toMatchObject({ server_fn_id: "abc" }); + }); + + // A TypeError that a handler threw on the server comes back the same way: + // as an answer that TanStack turns into an error after the fetch resolved. + test("an error answer is returned and sends nothing", async () => { + const answer = new Response("Bad gateway", { status: 502 }); + + expect(await callWith(() => Promise.resolve(answer))).toBe(answer); + expect(capture).not.toHaveBeenCalled(); + }); + + test("a rejection after the caller aborted sends nothing", async () => { + const error = new TypeError("Load failed"); + const controller = new AbortController(); + controller.abort(); + const base = () => Promise.reject(error); + + const result = await fetchReportingNetworkErrors("abc", base)( + "/_serverFn/abc", + { signal: controller.signal }, + ).catch((e: Error) => e); + + expect(result).toBe(error); + expect(capture).not.toHaveBeenCalled(); + }); + + test("a rejection while the page unloads sends nothing until pageshow", async () => { + const page = new EventTarget(); + watchUnload(page); + const error = new TypeError("NetworkError when attempting to fetch"); + + page.dispatchEvent(new Event("pagehide")); + expect(await callWith(() => Promise.reject(error))).toBe(error); + expect(capture).not.toHaveBeenCalled(); + + page.dispatchEvent(new Event("pageshow")); + expect(await callWith(() => Promise.reject(error))).toBe(error); + expect(capture).toHaveBeenCalledTimes(1); + }); + + test("an aborted fetch sends nothing", async () => { + const abort = new DOMException("aborted", "AbortError"); + + expect(await callWith(() => Promise.reject(abort))).toBe(abort); + expect(capture).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/lib/posthog-client.ts b/apps/web/src/lib/posthog-client.ts index cbcccb9d..724c611e 100644 --- a/apps/web/src/lib/posthog-client.ts +++ b/apps/web/src/lib/posthog-client.ts @@ -44,6 +44,16 @@ export function startPostHog({ capture_unhandled_rejections: true, capture_console_errors: false, }, + // A client value wins over the project's remote setting, so vitals are + // on here for every project. The default attribution (INP and LCP) names + // the element behind a slow metric. CLS stays out, because its + // attribution keeps detached DOM nodes and can leak memory in an SPA. + // Soft navigations make each router change its own measurement + // (Chrome only; other browsers measure the page load). + capture_performance: { + web_vitals: true, + __preview_web_vitals_soft_navs: true, + }, before_send: (event) => event && isResizeObserverLoop(event) ? null : event, debug: import.meta.env.DEV, @@ -56,3 +66,57 @@ export function startPostHog({ } return posthog; } + +// Firefox and Safari reject an in-flight fetch with a `TypeError` on unload. +let unloading = false; +export function watchUnload(target: EventTarget): void { + target.addEventListener("pagehide", () => { + unloading = true; + }); + // A page that returns from the back/forward cache is alive again. + target.addEventListener("pageshow", () => { + unloading = false; + }); +} +if (globalThis.window) watchUnload(globalThis.window); + +/** The call signature of `fetch`, as TanStack's `CustomFetch` has it. */ +type FetchFn = (...args: Parameters) => ReturnType; + +/** + * A `fetch` that reports a server function call that got no answer. + * + * `fetch` rejects with a `TypeError` when the network fails (Firefox: + * "NetworkError when attempting to fetch resource", Chrome: "Failed to + * fetch"). The error has no URL, so the event names the function by its id, + * which the server build maps to a name. It wraps the `fetch` itself, not + * the call of the function: a `TypeError` that a handler threw on the server, + * and a non-2xx answer, are not network failures. The event is a plain + * event, not an exception, because the same rejection can reach the + * unhandled-rejection capture too. The error is rethrown unchanged. + */ +export function fetchReportingNetworkErrors( + serverFnId: string, + baseFetch: FetchFn = globalThis.fetch, +): FetchFn { + return async (input, init) => { + try { + return await baseFetch(input, init); + } catch (error) { + if ( + error instanceof TypeError && + posthog.__loaded && + !unloading && + !(init?.signal ?? (input instanceof Request ? input.signal : null)) + ?.aborted + ) { + posthog.capture("server_fn_network_error", { + server_fn_id: serverFnId, + message: error.message, + online: navigator.onLine, + }); + } + throw error; + } + }; +} diff --git a/apps/web/src/start.ts b/apps/web/src/start.ts index 4a5500d9..fe0c095e 100644 --- a/apps/web/src/start.ts +++ b/apps/web/src/start.ts @@ -4,6 +4,8 @@ import { createStart, } from "@tanstack/react-start"; +import { fetchReportingNetworkErrors } from "./lib/posthog-client"; + /** * Bring the instance's settings up to date before any handler reads one. * @@ -72,8 +74,11 @@ const passThrough = ({ next }: { next: () => Promise }) => next(); // Both server-only imports stay inside this callback: TanStack strips it from // the client bundle, and a top-level import is not stripped. -const captureFailureMiddleware = createMiddleware({ type: "function" }).server( - async (args) => { +const captureFailureMiddleware = createMiddleware({ type: "function" }) + .client(({ next, serverFnMeta, fetch }) => + next({ fetch: fetchReportingNetworkErrors(serverFnMeta.id, fetch) }), + ) + .server(async (args) => { // A failed import must not fail the call: the call then runs uncaptured. const modules = await Promise.all([ import("@tanstack/react-start/server"), @@ -85,8 +90,7 @@ const captureFailureMiddleware = createMiddleware({ type: "function" }).server( if (!modules) return passThrough(args); const [{ getRequestHeaders }, { captureFailure }] = modules; return captureFailure(args, getRequestHeaders); - }, -); + }); export const startInstance = createStart(() => ({ requestMiddleware: [csrfMiddleware, instanceSettingsMiddleware], diff --git a/docs/domains/deployment.md b/docs/domains/deployment.md index 1a7a82cf..b79e1abc 100644 --- a/docs/domains/deployment.md +++ b/docs/domains/deployment.md @@ -28,7 +28,9 @@ Each job is env-gated by `_ENABLED` / `_INTERVAL_MINUTES`; the full **Impersonation is not configured here.** The platform admin role — who may become any user in any workspace — is a database value, granted to the instance's first account and passed on from inside the product. There is no environment variable for it, deliberately; see `docs/domains/authentication.md`. -**PostHog's BROWSER half is the part that catches people out.** `POSTHOG_PROJECT_TOKEN` and `POSTHOG_HOST` are instance settings, not `VITE_` variables: `vite build` runs inside the Docker image, so a `VITE_` value could only ever be what CI was given. The server reads them per request (`lib/posthog-server.ts`, one client kept per token and host and rebuilt when either changes, null when either is missing) and `routes/__root.tsx` writes the pair into the inline `` script beside the theme, for the browser to read back off `window`. Not through `getPublicAppConfig`, which is a server FUNCTION: the root route has no loader to call one from, and `RootDocument` is the `shellComponent`, which renders on the error and not-found paths where no loader has run. `POSTHOG_AI_CAPTURE_CONTENT` (default `false`) is the one switch for whether an agent's content — the assistant's prompts and answers, and the MCP server's tool arguments and results — leaves the process at all. The metadata goes either way and is what the dashboards are built on; the content is a customer's timesheet, so on a multi-tenant deployment sending it is a decision an operator makes rather than inherits. Six adapters read that one client and nothing else does: `lib/posthog-ai.ts` (the assistant's turns), `lib/posthog-mcp.ts` (the MCP server's requests), `lib/posthog-api.ts` (the REST API's requests and failures, and the faults of server functions), `lib/posthog-jobs.ts` (a failure a background job caught and went on from, through `jobs/job-failures.ts`; the standalone worker installs no sink), `lib/posthog-impersonation.ts` (the impersonation ledger, see `docs/domains/authentication.md`) and the `capture` calls in `server/*.ts` (what a person did in the browser). +**PostHog's BROWSER half is the part that catches people out.** `POSTHOG_PROJECT_TOKEN` and `POSTHOG_HOST` are instance settings, not `VITE_` variables: `vite build` runs inside the Docker image, so a `VITE_` value could only ever be what CI was given. The server reads them per request (`lib/posthog-server.ts`, one client kept per token and host and rebuilt when either changes, null when either is missing) and `routes/__root.tsx` writes the pair into the inline `` script beside the theme, for the browser to read back off `window`. Not through `getPublicAppConfig`, which is a server FUNCTION: the root route has no loader to call one from, and `RootDocument` is the `shellComponent`, which renders on the error and not-found paths where no loader has run. `POSTHOG_AI_CAPTURE_CONTENT` (default `false`) is the one switch for whether an agent's content — the assistant's prompts and answers, and the MCP server's tool arguments and results — leaves the process at all. The metadata goes either way and is what the dashboards are built on; the content is a customer's timesheet, so on a multi-tenant deployment sending it is a decision an operator makes rather than inherits. Six adapters read that one client and nothing else does: `lib/posthog-ai.ts` (the assistant's turns), `lib/posthog-mcp.ts` (the MCP server's requests), `lib/posthog-api.ts` (the REST API's requests and failures, and the faults of server functions), `lib/posthog-jobs.ts` (a failure a background job caught and went on from, through `jobs/job-failures.ts`; the standalone worker installs no sink), `lib/posthog-impersonation.ts` (the impersonation ledger, see `docs/domains/authentication.md`) and the `capture` calls in `server/*.ts` (what a person did in the browser). `lib/posthog-api.ts` also sends `server_fn_slow` for a server function that takes `SLOW_SERVER_FN_MS` (1 second) or more, whether it threw or not. + +**The browser sends diagnostics too.** `lib/posthog-client.ts` turns on web vitals with attribution and soft navigations (`capture_performance`), and the client value wins over the project's remote setting. The proxy forwards the lazy `/static/web-vitals*.js` script as any other `/static/` path. `src/client.tsx` replaces TanStack Start's default client entry to capture the errors that React recovers from (a hydration mismatch, React error #418) with the component stack, the page language and whether Chrome's page translation was on. The function middleware in `start.ts` also sends a `server_fn_network_error` event when the browser's `fetch` of a server function fails before any answer. **The browser does not talk to PostHog directly.** It sends its events to `/api/k7v2q9` on the app's own origin. The server route `routes/api/k7v2q9/$.ts` forwards them to `POSTHOG_HOST`, and forwards `/static/` and `/array/` paths to the PostHog assets host. An ad blocker that blocks the PostHog domains then does not drop the events. The prefix is a fixed random word on purpose: block lists match words such as "ingest". The proxy is a route, not code in `server.ts`, so it reads fresh instance settings. It forwards only the paths that posthog-js requests, with a 10 second timeout and a 5 MB body limit, because a self-hosted `POSTHOG_HOST` can be on a private network. PostHog takes the GeoIP address from the request, so the route sends the client address as `X-Forwarded-For`. Set `TRUSTED_IP_HEADER`, or every event has the address of the proxy in front of the app.