packages/ui of iterate/private at fd6fe9d2f647d32bd610e1a3564d5e79167b576e
ui release builder, 2026-11-27 06:56 UTC · b22794d07c154c8c27875d3fe8c4eb4c948d469b · parent 203f7da
13 files changed
- M browser-entries.ts
- M package.json
- M registry.json
- M src/apps/document.test.tsx
- M src/apps/document.tsx
- M src/apps/providers.tsx
- M src/apps/server.test.ts
- M src/apps/server.ts
- M src/components/app-shell.tsx
- D src/components/not-recorded.tsx
- D src/components/posthog-replay.test.tsx
- D src/components/posthog.tsx
- M src/components/route-defaults.tsx
M browser-entries.ts
@@ -146,7 +146,6 @@ { name: "vendor-yjs", test: /node_modules[\\/](yjs|lib0|y-protocols|y-codemirror\.next)[\\/]/ }, // Atomic's live preview holds CodeMirror state fields and facets: one copy, beside CodeMirror's { name: "vendor-atomic", test: /node_modules[\\/]@atomic-editor[\\/]/ }, - { name: "vendor-posthog", test: /node_modules[\\/]posthog-js[\\/]/ }, // Prettier's browser build, which prettifies a script in the Agents app's Script tab // (lib/format-script.ts): only a page that shows a script loads it { name: "vendor-prettier", test: /node_modules[\\/]prettier[\\/]/ },
M package.json
@@ -110,9 +110,7 @@ "./components/log-in-with-iterate": "./dist/components/log-in-with-iterate.mjs", "./components/mcp-connect": "./dist/components/mcp-connect.mjs", "./components/mind-app-shell": "./dist/components/mind-app-shell.mjs", - "./components/not-recorded": "./dist/components/not-recorded.mjs", "./components/page-tools": "./dist/components/page-tools.mjs", - "./components/posthog": "./dist/components/posthog.mjs", "./components/reconnecting-mark": "./dist/components/reconnecting-mark.mjs", "./components/repo-ide/repo-ide": "./dist/components/repo-ide/repo-ide.mjs", "./components/route-defaults": "./dist/components/route-defaults.mjs", @@ -181,7 +179,6 @@ "./chunks/vendor-db": "./dist/chunks/vendor-db.mjs", "./chunks/vendor-yjs": "./dist/chunks/vendor-yjs.mjs", "./chunks/vendor-atomic": "./dist/chunks/vendor-atomic.mjs", - "./chunks/vendor-posthog": "./dist/chunks/vendor-posthog.mjs", "./chunks/vendor-prettier": "./dist/chunks/vendor-prettier.mjs", "./chunks/vendor-icons": "./dist/chunks/vendor-icons.mjs", "./chunks/ui-base": "./dist/chunks/ui-base.mjs", @@ -275,7 +272,6 @@ "lucide-react": "catalog:", "next-themes": "^0.4.6", "postcss": "8.5.28", - "posthog-js": "catalog:", "prettier": "3.9.9", "react": "catalog:", "react-dom": "catalog:",
M registry.json
@@ -378,7 +378,6 @@ "dropdown-menu", "iterate/packages/iterate-logo", "iterate/packages/plain-left-click", - "iterate/packages/posthog", "iterate/packages/saved-log-tail", "sidebar", "skeleton" @@ -1298,20 +1297,6 @@ ] }, { - "name": "not-recorded", - "type": "registry:component", - "description": "A block PostHog's session replay never records, for a secret shown on screen.", - "dependencies": [ - "cn" - ], - "files": [ - { - "path": "src/components/not-recorded.tsx", - "type": "registry:component" - } - ] - }, - { "name": "context-path-text", "type": "registry:component", "description": "A context path as one plain path from the root, in the fixed-width face; a short line keeps its end.", @@ -1389,21 +1374,6 @@ ] }, { - "name": "posthog", - "type": "registry:component", - "description": "PostHog in the browser: init, identity and exception capture, with secrets redacted from URLs.", - "dependencies": [ - "iterate", - "posthog-js" - ], - "files": [ - { - "path": "src/components/posthog.tsx", - "type": "registry:component" - } - ] - }, - { "name": "mind-app-shell", "type": "registry:component", "description": "The app shell for a page inside one mind, with its breadcrumb, and the frame it shows while the page loads.", @@ -1685,7 +1655,6 @@ ], "registryDependencies": [ "button", - "iterate/packages/posthog", "spinner" ], "files": [
M src/apps/document.test.tsx
@@ -16,14 +16,14 @@ test("a root loader that fails still renders the document: the head the root names, the failure and a retry", async () => { const root = createRootRoute({ - loader: (): { posthogProjectKey: string | null } => { + loader: (): null => { throw new Error("the deployment's configuration could not be read"); }, head: () => appHead({ title: "Agents", stylesheet: "/assets/styles.css" }), shellComponent: ({ children }) => ( <AppDocumentShell icon="/client-logo.svg">{children}</AppDocumentShell> ), - component: () => <AppRoot posthogProjectKey={root.useLoaderData().posthogProjectKey} />, + component: AppRoot, }); const router = createAppRouter({ routeTree: root, @@ -42,7 +42,7 @@ }); test("a mind whose first read fails keeps the app's frame, and says which mind and what failed, with a retry", async () => { - const root = createRootRoute({ component: () => <AppRoot posthogProjectKey={null} /> }); + const root = createRootRoute({ component: AppRoot }); const mind = createRoute({ getParentRoute: () => root, path: "minds/$mind",
M src/apps/document.tsx
@@ -29,9 +29,9 @@ /** Every app's root route `component`, inside `AppDocumentShell`: the app's providers around its * pages. */ -export function AppRoot(props: { posthogProjectKey: string | null }) { +export function AppRoot() { return ( - <AppProviders posthogApiKey={props.posthogProjectKey || undefined}> + <AppProviders> <Outlet /> </AppProviders> ); @@ -39,14 +39,10 @@ /** The document and the providers in one root `component`: for an app outside this repo that * names no `shellComponent` yet. Its root loader's failure renders no document. */ -export function AppDocument(props: { - icon: string; - posthogProjectKey: string | null; - basePath?: string; -}) { +export function AppDocument(props: { icon: string; basePath?: string }) { return ( <AppDocumentShell icon={props.icon} basePath={props.basePath}> - <AppRoot posthogProjectKey={props.posthogProjectKey} /> + <AppRoot /> </AppDocumentShell> ); }
M src/apps/providers.tsx
@@ -1,13 +1,9 @@ import type { ReactNode } from "react"; -import { initPosthog } from "#/components/posthog.tsx"; import { Toaster } from "#/components/ui/sonner.tsx"; import { TooltipProvider } from "#/components/ui/tooltip.tsx"; -/** Every client app's root providers. PostHog starts when the app has a key (envs.ts hands one to - * prd only). */ -export function AppProviders(props: { children: ReactNode; posthogApiKey?: string }) { - initPosthog(props.posthogApiKey); - +/** Every client app's root providers. */ +export function AppProviders(props: { children: ReactNode }) { return ( // Base UI tooltips are intended to share a provider; setting delay=0 // here makes hover tooltips feel immediate across the app.
M src/apps/server.test.ts
@@ -1,5 +1,5 @@ -// Which part of an app's Worker answers a request (appServerEntry): its health check, the PostHog -// proxy, the app's own routes, the sign-in gate, the assets and the pages. +// Which part of an app's Worker answers a request (appServerEntry): its health check, +// the app's own routes, the sign-in gate, the assets and the pages. // The gate's own behaviour is iterate/app-server's (app-server.test.ts). import { env } from "cloudflare:workers"; import { expect, test, vi } from "vitest"; @@ -12,12 +12,6 @@ path: "/healthz", owns: "*", expected: "ok", - }, - { - name: "PostHog's files come from PostHog through /e/, before the app's own routes", - path: "/e/static/array.js", - owns: "*", - expected: "fetched https://eu-assets.i.posthog.com/static/array.js", }, { name: "the app's own routes answer before the gate",
M src/apps/server.ts
@@ -1,7 +1,6 @@ // server.ts — EVERY APP'S WORKER (dash, agents, notes, voice, admin): its src/server.ts, Start's // server entry, is `appServerEntry(handler, { … })` with only what the app does differently. import { env } from "cloudflare:workers"; -import { proxyPosthogRequest } from "@iterate-com/shared/posthog"; import { startAppConfigOf, type StartAppConfig } from "@iterate-com/shared/start-app-config"; import { appAuth } from "iterate/app-server"; import type { BrowserSession } from "iterate/app-session"; @@ -13,7 +12,7 @@ ASSETS: Fetcher; BROWSER_SESSION: DurableObjectNamespace<BrowserSession>; /** THE APP'S CONFIGURATION, JSON (@iterate-com/shared/start-app-config): its platform, the - * other apps' origins, our own zones and its PostHog key — from envs.ts (startAppWorkerConfig) */ + * other apps' origins and our own zones — from envs.ts (startAppWorkerConfig) */ ITERATE_APP: string; } } @@ -50,9 +49,6 @@ const config = startAppConfigOf(env); const url = new URL(request.url); if (url.pathname === "/healthz") return new Response("ok"); - // posthog-js's `api_host` (packages/ui posthog.tsx): PostHog EU through our own origin - if (url.pathname.startsWith("/e/")) - return proxyPosthogRequest({ request, proxyPrefix: "/e" }); const own = await app.before?.(request, config); if (own) return own; if (!app.proxied) {
M src/components/app-shell.tsx
@@ -71,7 +71,6 @@ useSidebar, } from "#/components/ui/sidebar.tsx"; import { Skeleton } from "#/components/ui/skeleton.tsx"; -import { resetPosthog } from "#/components/posthog.tsx"; import { wipeSavedLogTails } from "#/lib/saved-log-tail.ts"; /** Nothing to subscribe to: the cookie has no change event, and `SidebarProvider` reads @@ -831,7 +830,6 @@ <DropdownMenuGroup> <DropdownMenuItem onClick={() => { - resetPosthog(); // the next member of this browser sees none of this one's saved rows void wipeSavedLogTails().then(() => logout.current?.requestSubmit()); }}
D src/components/not-recorded.tsx
@@ -1,10 +0,0 @@ -import type { ComponentProps } from "react"; -import { cn } from "cn"; - -/** A block PostHog never captures, for a secret on screen such as a personal access token or an - * invite link shown once. `ph-no-capture` is PostHog's class for sensitive content outside a form - * field (https://posthog.com/docs/session-replay/privacy, "Other elements"): session replay draws - * an empty box of the same size in its place, and autocapture skips anything inside it. */ -export function NotRecorded({ className, ...props }: ComponentProps<"div">) { - return <div {...props} className={cn("ph-no-capture", className)} />; -}
D src/components/posthog-replay.test.tsx
@@ -1,136 +0,0 @@ -// @vitest-environment jsdom -// What PostHog would receive from a page, with the apps' own options (posthog.tsx -// `posthogInitOptions`) run by posthog-js itself: its full bundle and the session recorder it -// lazy-loads in a browser (`/e/static/lazy-recorder.js`, the same file). The page is React's, with -// a controlled field, so the value attribute React syncs reaches the recorder as it does in the -// apps. A last `before_send` keeps each event here and drops it, so nothing leaves the test. -import "posthog-js/dist/lazy-recorder.js"; -import { gunzipSync } from "node:zlib"; -import { posthog } from "posthog-js/dist/module.full.js"; -import type { CaptureResult } from "posthog-js"; -import { act, useState } from "react"; -import { createRoot } from "react-dom/client"; -import { expect, test, vi } from "vitest"; -import { NotRecorded } from "./not-recorded.tsx"; -import { posthogInitOptions } from "./posthog.tsx"; -import { Input } from "#/components/ui/input.tsx"; -import { Textarea } from "#/components/ui/textarea.tsx"; - -test("a replay masks what is typed and leaves out a NotRecorded block, and no event carries an invitation token", async () => { - const token = "phc_aaaaabbbbbccccc111112222233333aaaaabbbbbccc"; - // an invitation link's page: its URL holds the token - history.replaceState(null, "", "/invitations/FAKE-invite-token"); - // posthog-js's preloaded remote config (what `/e/array/<token>/config.js` sets): record replays and autocapture - Object.assign(window, { - _POSTHOG_REMOTE_CONFIG: { - [token]: { config: { sessionRecording: { endpoint: "/s/" }, autocapture_opt_out: false } }, - }, - }); - Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); - const root = createRoot(document.body.appendChild(document.createElement("div"))); - await act(() => root.render(<Page />)); - - const captured: CaptureResult[] = []; - const options = posthogInitOptions(); - posthog.init(token, { - ...options, - advanced_disable_flags: true, - before_send: [ - options.before_send, - (event) => { - if (event) captured.push(event); - return null; - }, - ], - }); - await vi.waitFor(() => expect(posthog.sessionRecording).toMatchObject({ status: "active" })); - - // types as a person does: the value through the DOM's own setter, so React's onChange sees it - await type(document.querySelector<HTMLInputElement>("#plain")!, "FAKE-typed"); - // rrweb records a textarea's value on its own path, so it gets its own field - await type(document.querySelector<HTMLTextAreaElement>("#area")!, "FAKE-area-typed"); - for (const selector of ["#visible", "#minted", "[role=status] a"]) - document.querySelector<HTMLElement>(selector)!.click(); - // the person joins and lands on the organization: `$prev_pageview_*` names the invitation page - history.pushState(null, "", "/organizations/org_FAKE"); - await vi.waitFor(() => - expect(captured.filter((event) => event.event === "$pageview")).toHaveLength(2), - ); - posthog.identify("user_FAKE"); - // the recorder flushes its buffer on unload, synchronously - window.dispatchEvent(new Event("beforeunload")); - - const replay = JSON.stringify( - captured.filter((event) => event.event === "$snapshot").map(inflate), - ); - const autocapture = JSON.stringify(captured.filter((event) => event.event === "$autocapture")); - const everything = JSON.stringify(captured.map(inflate)); - // the replay and autocapture work: the field is there, with what was typed as asterisks - expect(replay).toContain('"id":"plain"'); - expect(replay).toContain(`"text":"${"*".repeat("FAKE-typed".length)}"`); - expect(replay).toContain('"id":"area"'); - expect(replay).toContain(`"value":"${"*".repeat("FAKE-area-typed".length)}"`); - expect(autocapture).toContain("Visible button"); - // no secret reaches PostHog, in the replay or in any event - for (const secret of [ - "FAKE-typed", - "FAKE-area-typed", - "itk_FAKE_shown_once", - "FAKE-invite-token", - ]) - expect(everything).not.toContain(secret); - // a NotRecorded block is left out, not just masked: an empty box in the replay, no autocapture - expect(replay).not.toContain('"id":"minted"'); - expect(autocapture).not.toContain("minted"); - expect(autocapture).not.toContain("Allow"); - // the page URLs PostHog records name the route, not the token - expect(captured.filter((event) => event.event === "$pageview")).toMatchObject([ - { properties: { $pathname: "/invitations/:token" } }, - { properties: { $pathname: "/organizations/org_FAKE" } }, - ]); - expect(captured.find((event) => event.event === "$identify")).toMatchObject({ - $set_once: { $initial_current_url: expect.stringMatching(/\/invitations\/:token$/) }, - }); - expect(replay).toMatch(/"href":"http:\/\/[^"]+\/invitations\/:token"/); -}); - -function Page() { - const [plain, setPlain] = useState(""); - const [area, setArea] = useState(""); - return ( - <form> - <Input id="plain" value={plain} onChange={(event) => setPlain(event.target.value)} /> - <Textarea id="area" value={area} onChange={(event) => setArea(event.target.value)} /> - <NotRecorded role="status"> - <code id="minted">itk_FAKE_shown_once</code> - <a - href="/.auth/login?next=%2Finvitations%2FFAKE-invite-token" - onClick={(event) => event.preventDefault()} - > - Allow - </a> - </NotRecorded> - <button type="button" id="visible"> - Visible button - </button> - </form> - ); -} - -async function type(field: HTMLInputElement | HTMLTextAreaElement, text: string) { - await act(async () => { - Object.getOwnPropertyDescriptor(Object.getPrototypeOf(field), "value")!.set!.call(field, text); - field.dispatchEvent(new Event("input", { bubbles: true })); - field.dispatchEvent(new Event("change", { bubbles: true })); - }); -} - -/** posthog-js gzips a full snapshot's data and a mutation's fields into latin1 strings. */ -function inflate(value: unknown): unknown { - if (typeof value === "string" && value.startsWith("\u001f\u008b")) - return inflate(JSON.parse(gunzipSync(Buffer.from(value, "latin1")).toString("utf8"))); - if (Array.isArray(value)) return value.map(inflate); - if (value instanceof Object) - return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, inflate(entry)])); - return value; -}
D src/components/posthog.tsx
@@ -1,139 +0,0 @@ -import { useEffect } from "react"; -import type { PostHogConfig } from "posthog-js"; -import type { Principal } from "iterate/principal"; - -// posthog-js only ever runs in the browser; the SSR branch keeps it out of the -// server bundle. -const loadPosthog = import.meta.env.SSR ? null : () => import("posthog-js"); - -export type PosthogProperties = Record<string, boolean | number | string>; - -export interface PosthogGroup { - type: string; - key: string; - properties: PosthogProperties; -} - -// Only a deployment that should report is given a key (envs.ts: prd), so an initialized SDK sends. -// `api_host` is the page's own `/e` proxy (proxyPosthogRequest in @iterate-com/shared/posthog). -// `defaults` sets the rest: pageviews on history changes, page leaves, identified-only person -// profiles, no URL hashes. -// -// Session replay keeps PostHog's privacy defaults (https://posthog.com/docs/session-replay/privacy): -// every input is masked, and a `ph-no-capture` element (`NotRecorded`) is not recorded. Masking is -// the PostHog project's setting, so nothing here sets it. The two additions are PostHog's own -// guidance for a secret in a URL: an invitation link's token is redacted from the page URLs a replay -// records (`maskCapturedNetworkRequestFn`, same page, "URL redaction") and from every event -// (`before_send`, https://posthog.com/docs/libraries/js/usage#redacting-information-in-events). -// That function replaces posthog-js's own scrubbing of request bodies, so headers and bodies are -// never recorded (https://posthog.com/docs/session-replay/network-recording). -export function posthogInitOptions() { - return { - api_host: "/e", - ui_host: "https://eu.posthog.com", - defaults: "2026-08-30", - capture_exceptions: true, - strict_script_versioning: true, - session_recording: { - maskCapturedNetworkRequestFn: (request) => ({ - ...request, - name: redactSecretPaths(request.name), - }), - recordHeaders: false, - recordBody: false, - }, - before_send: (event) => event && redactSecretPathsIn(event), - } satisfies Partial<PostHogConfig>; -} - -/** `text` with the secret in each URL path that carries one replaced by its route parameter: - * `/invitations/<token>` (the Dash's invitation link, which joins its organization) becomes - * `/invitations/:token`, URL-encoded too (`?next=%2Finvitations%2F<token>`, the Dash's step-up - * link). A new route whose path holds a secret adds its pattern here. */ -function redactSecretPaths(text: string) { - return text.replace(/((?:\/|%2F)invitations(?:\/|%2F))[^/?#&"'\s%]+/gi, "$1:token"); -} - -/** `value` with `redactSecretPaths` applied to every string and object key in it, except a replay - * batch's `$snapshot_data`: its payloads are gzipped, and `maskCapturedNetworkRequestFn` already - * redacted the URLs in them. The casts are safe: each branch rebuilds the value it was given with - * strings in place of strings, which TypeScript cannot follow through `Object.fromEntries`. */ -function redactSecretPathsIn<T>(value: T): T { - if (typeof value === "string") return redactSecretPaths(value) as T; - if (Array.isArray(value)) return value.map(redactSecretPathsIn) as T; - if (value && typeof value === "object" && !(value instanceof Date)) - return Object.fromEntries( - Object.entries(value).map(([key, entry]) => [ - redactSecretPaths(key), - key === "$snapshot_data" ? entry : redactSecretPathsIn(entry), - ]), - ) as T; - return value; -} - -let posthogInitStarted = false; -let posthogClientPromise: Promise<import("posthog-js").PostHog> | undefined; - -/** - * Once-per-app-load PostHog initialization. Nothing in our apps reads the - * PostHog React context, so there is no provider: autocapture, session replay, - * feature flags, surveys, and exception capture all run through `init`. This - * would run at module scope per React's guidance for app - * initialization, but the api key only arrives with loader data — so the - * once-guard lives here at module scope and the first render with config in - * hand kicks it off. Idempotent, so safe to call during render. - */ -export function initPosthog(apiKey: string | null | undefined) { - if (posthogInitStarted || !loadPosthog || !apiKey) return; - posthogInitStarted = true; - const clientPromise = loadPosthog().then((posthogModule) => { - posthogModule.default.init(apiKey, posthogInitOptions()); - return posthogModule.default; - }); - posthogClientPromise = clientPromise; - void clientPromise.catch((error: unknown) => { - if (posthogClientPromise === clientPromise) { - posthogInitStarted = false; - posthogClientPromise = undefined; - } - console.error("PostHog browser SDK failed to load", error); - }); -} - -function withPosthogClient(action: (client: import("posthog-js").PostHog) => void) { - const clientPromise = posthogClientPromise; - if (!clientPromise) return; - void clientPromise.then(action, () => undefined); -} - -const NO_GROUPS: PosthogGroup[] = []; - -/** PostHog: the person is the platform user id — the same person in every app — and `groups` are - * the caller's (memoized: a new array re-runs the effect). Following PostHog's guide, a different - * signed-in user resets first, so the two are never merged; identify and group skip what they - * already sent. A platform admin signed in as someone (`impersonatedBy`) is the admin: the clicks - * are theirs, never the person's. */ -export function usePosthogIdentity(principal: Principal, groups: PosthogGroup[] = NO_GROUPS) { - const { actor, email } = principal.impersonatedBy || principal; - useEffect(() => { - withPosthogClient((client) => { - const identified = client.get_property("$user_id"); - if (typeof identified === "string" && identified !== actor) client.reset(); - client.identify(actor, email ? { email } : undefined); - const types = new Set(groups.map((group) => group.type)); - if (Object.keys(client.getGroups()).some((type) => !types.has(type))) client.resetGroups(); - for (const group of groups) client.group(group.type, group.key, group.properties); - }); - }, [actor, email, groups]); -} - -/** Sign-out: the next person on this browser starts anonymous (PostHog's guide: reset on logout). */ -export function resetPosthog() { - withPosthogClient((client) => client.reset()); -} - -/** An error a route's error screen caught: React never lets it reach `window.onerror`, so - * `capture_exceptions` alone would miss it. */ -export function capturePosthogException(error: unknown) { - withPosthogClient((client) => client.captureException(error)); -}
M src/components/route-defaults.tsx
@@ -1,7 +1,6 @@ -import { useEffect, type ReactNode } from "react"; +import type { ReactNode } from "react"; import { useRouter } from "@tanstack/react-router"; import { Button } from "#/components/ui/button.tsx"; -import { capturePosthogException } from "#/components/posthog.tsx"; import { Spinner } from "#/components/ui/spinner.tsx"; export function DefaultPendingComponent() { @@ -49,7 +48,6 @@ }: ErrorFallbackProps) { const router = useRouter(); const message = error instanceof Error ? error.message : "An unexpected error occurred"; - useEffect(() => capturePosthogException(error), [error]); return ( <div className="flex min-h-screen flex-col items-center justify-center gap-4 p-4 text-center">