Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(diagnostics): report which page a desktop hang happened on (MUL-5345) (#5989)
Naiyuan Qing38b08acf0097
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex c99b5462e8..396e9f60a5 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -442,11 +442,11 @@ function createWindow(): BrowserWindow {dialog.showMessageBox(window, options),),getDiagnosticContext: () => {+ // No `windowUrl`: it is an absolute install path (`/Users/<name>/...`+ // when installed per-user) and the bucketed route below already says+ // which page the window was on, which is the part we can act on.const routeContext = rendererRouteContexts.get(window.webContents);- return {- windowUrl: window.webContents.getURL(),- ...(routeContext ? { desktopRoute: routeContext } : {}),- };+ return routeContext ? { desktopRoute: routeContext } : {};},// Only persist in production: a true hang/crash can't report itself, so we// write a breadcrumb and the next renderer boot flushes it to PostHog. Dev@@ -528,11 +528,11 @@ function createIssueWindow(context: IssueWindowContext): void {dialog.showMessageBox(window, options),),getDiagnosticContext: () => {+ // No `windowUrl`: it is an absolute install path (`/Users/<name>/...`+ // when installed per-user) and the bucketed route below already says+ // which page the window was on, which is the part we can act on.const routeContext = rendererRouteContexts.get(window.webContents);- return {- windowUrl: window.webContents.getURL(),- ...(routeContext ? { desktopRoute: routeContext } : {}),- };+ return routeContext ? { desktopRoute: routeContext } : {};},persistBreadcrumb: is.dev? undefineddiff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex e4aef2b415..a981ca5c5c 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -22,6 +22,8 @@ import { createDesktopLocaleAdapter } from "./platform/i18n-adapter";import { captureEvent } from "@multica/core/analytics";import { RESOURCES } from "@multica/views/locales";import { DesktopClientUsageReporter } from "./platform/client-usage-reporter";+import { DiagnosticRouteReporter } from "./platform/diagnostic-route-reporter";+import { buildFreezeEventProps } from "./freeze-flush";// BCP-47 region tags for the <html lang> attribute, mirroring// apps/web/app/layout.tsx HTML_LANG. index.html ships a static lang="en";@@ -381,16 +383,10 @@ export default function App() {useEffect(() => {const last = window.desktopAPI.getLastFreeze();if (!last) return;- const crashed = last.kind === "render-process-gone";- captureEvent(crashed ? "client_crash" : "client_unresponsive", {- // Spread context FIRST so our explicit fields below always win — a- // future context key (e.g. its own `source`) must not silently override.- ...last.context,- source: crashed ? "render-process-gone" : "main-unresponsive",- recovered: false,- breadcrumb_ts: last.ts,- crashed_version: last.version,- });+ captureEvent(+ last.kind === "render-process-gone" ? "client_crash" : "client_unresponsive",+ buildFreezeEventProps(last),+ );}, []);// Stable identity reference so downstream effects (WS reconnect) don't@@ -453,6 +449,7 @@ export default function App() {localeAdapter={localeAdapter}><DesktopAuthSessionBridge />+ {windowContext.kind === "main" && <DiagnosticRouteReporter />}{windowContext.kind === "main" && (<DesktopClientUsageReporterapiUrl={runtimeConfigResult.config.apiUrl}diff --git a/apps/desktop/src/renderer/src/freeze-flush.test.ts b/apps/desktop/src/renderer/src/freeze-flush.test.tsnew file mode 100644index 0000000000..738c5677ba--- /dev/null+++ b/apps/desktop/src/renderer/src/freeze-flush.test.ts@@ -0,0 +1,107 @@+/**+ * MUL-5345 — a hang report has to say which page it happened on, and must not+ * say anything else about the user.+ *+ * The props used to be built by spreading the whole breadcrumb context, which+ * shipped the workspace slug, the tab id and the absolute window URL. Building+ * them by whitelist is what keeps that from coming back the next time the+ * context grows a field.+ */+import { describe, expect, it } from "vitest";++import { buildFreezeEventProps } from "./freeze-flush";+import type { FreezeBreadcrumb } from "../../shared/freeze-breadcrumb";++const hang: FreezeBreadcrumb = {+ kind: "unresponsive",+ ts: 1_700_000_000_000,+ version: "0.4.11",+ context: {+ desktopRoute: {+ surface: "tab",+ path: "/:slug/issues",+ reportedAt: "2026-07-27T00:00:00.000Z",+ },+ },+};++describe("buildFreezeEventProps", () => {+ it("reports the bucketed route at the top level, like the in-thread watchdog", () => {+ expect(buildFreezeEventProps(hang)).toEqual({+ source: "main-unresponsive",+ recovered: false,+ breadcrumb_ts: hang.ts,+ crashed_version: "0.4.11",+ path: "/:slug/issues",+ surface: "tab",+ });+ });++ it("drops workspace slug, tab id and window url if a context still carries them", () => {+ const leaky: FreezeBreadcrumb = {+ ...hang,+ context: {+ windowUrl: "file:///Users/someone/Applications/Multica.app/index.html",+ desktopRoute: {+ surface: "tab",+ path: "/:slug/issues",+ workspaceSlug: "acme",+ tabId: "tab-1",+ reportedAt: "2026-07-27T00:00:00.000Z",+ },+ },+ };++ const props = buildFreezeEventProps(leaky);++ const serialized = JSON.stringify(props);+ expect(serialized).not.toContain("acme");+ expect(serialized).not.toContain("tab-1");+ expect(serialized).not.toContain("someone");+ expect(props).not.toHaveProperty("workspaceSlug");+ expect(props).not.toHaveProperty("tabId");+ expect(props).not.toHaveProperty("windowUrl");+ });++ it("drops an unknown context key rather than forwarding it", () => {+ const props = buildFreezeEventProps({+ ...hang,+ context: { ...hang.context, somethingAddedLater: "raw-value" },+ });++ expect(JSON.stringify(props)).not.toContain("raw-value");+ });++ it("cannot have its own fields overridden by the context", () => {+ const props = buildFreezeEventProps({+ ...hang,+ context: { ...hang.context, source: "spoofed", recovered: true },+ });++ expect(props.source).toBe("main-unresponsive");+ expect(props.recovered).toBe(false);+ });++ it("keeps the crash reason as two scalars", () => {+ const props = buildFreezeEventProps({+ ...hang,+ kind: "render-process-gone",+ context: { details: { reason: "oom", exitCode: 5 } },+ });++ expect(props).toMatchObject({+ source: "render-process-gone",+ crash_reason: "oom",+ crash_exit_code: 5,+ });+ });++ it("survives a breadcrumb with no context at all", () => {+ expect(buildFreezeEventProps({ ...hang, context: {} })).toEqual({+ source: "main-unresponsive",+ recovered: false,+ breadcrumb_ts: hang.ts,+ crashed_version: "0.4.11",+ });+ });+});diff --git a/apps/desktop/src/renderer/src/freeze-flush.ts b/apps/desktop/src/renderer/src/freeze-flush.tsnew file mode 100644index 0000000000..77e0a5bc96--- /dev/null+++ b/apps/desktop/src/renderer/src/freeze-flush.ts@@ -0,0 +1,55 @@+import type { FreezeBreadcrumb } from "../../shared/freeze-breadcrumb";++// Turning a breadcrumb the previous session left behind into event properties.+//+// The breadcrumb context is assembled in the main process and can grow a field+// at any time, so props are built by explicit whitelist here rather than by+// spreading it: an unknown key is dropped, not forwarded. That matters because+// this context is the one place a raw identifier could reach telemetry.++/**+ * Build the event properties for a pending freeze/crash breadcrumb, field by+ * field. Anything not named here does not ship.+ */+export function buildFreezeEventProps(+ breadcrumb: FreezeBreadcrumb,+): Record<string, unknown> {+ const crashed = breadcrumb.kind === "render-process-gone";+ const context = (breadcrumb.context ?? {}) as Record<string, unknown>;++ return {+ source: crashed ? "render-process-gone" : "main-unresponsive",+ recovered: false,+ breadcrumb_ts: breadcrumb.ts,+ crashed_version: breadcrumb.version,+ ...routeProps(context.desktopRoute),+ ...crashProps(context.details),+ };+}++/**+ * `path` is flattened to the top level under the same name the in-thread+ * watchdog uses, so both hang sources group in one query. The value arrives+ * already bucketed to a template and carries no slug or resource id — see+ * renderer-route-context.+ */+function routeProps(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== "object") return {};+ const route = value as Record<string, unknown>;+ return {+ ...(typeof route.path === "string" ? { path: route.path } : {}),+ ...(typeof route.surface === "string" ? { surface: route.surface } : {}),+ };+}++/** Electron's render-process-gone details: two scalars, nothing else. */+function crashProps(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== "object") return {};+ const details = value as Record<string, unknown>;+ return {+ ...(typeof details.reason === "string" ? { crash_reason: details.reason } : {}),+ ...(typeof details.exitCode === "number"+ ? { crash_exit_code: details.exitCode }+ : {}),+ };+}diff --git a/apps/desktop/src/renderer/src/platform/diagnostic-route-reporter.test.tsx b/apps/desktop/src/renderer/src/platform/diagnostic-route-reporter.test.tsxnew file mode 100644index 0000000000..bb71399fa8--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/diagnostic-route-reporter.test.tsx@@ -0,0 +1,133 @@+/**+ * MUL-5345 — the main window must publish which page it is showing.+ *+ * This reporting existed once and was deleted with the PostHog $pageview+ * cleanup (MUL-4127), which left the main process reading a route it was never+ * sent: every field hang report came back with only the asar `index.html` URL.+ * Nothing failed loudly, so these tests pin both consumers — the IPC push to+ * main (the only party alive during a true hang) and the in-renderer+ * diagnostic context the freeze watchdog reads.+ */+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import { render } from "@testing-library/react";++const authState = { user: null as { id: string } | null };+const overlayState = { overlay: null as { type: string } | null };+const tabState = {+ slug: null as string | null,+ tabId: null as string | null,+ url: null as string | null,+};++vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (s: typeof authState) => unknown) => selector(authState),+}));++vi.mock("@/stores/window-overlay-store", () => ({+ useWindowOverlayStore: (selector: (s: typeof overlayState) => unknown) =>+ selector(overlayState),+}));++vi.mock("@/stores/tab-store", () => ({+ useActiveTabIdentity: () => ({ slug: tabState.slug, tabId: tabState.tabId }),+ useActiveTabUrl: () => tabState.url,+}));++import { DiagnosticRouteReporter } from "./diagnostic-route-reporter";+import { getDiagnosticRoute, resetDiagnosticContext } from "@multica/core/diagnostics";++const setRendererRouteContext = vi.fn();++beforeEach(() => {+ setRendererRouteContext.mockClear();+ authState.user = { id: "u-1" };+ overlayState.overlay = null;+ tabState.slug = "acme";+ tabState.tabId = "tab-1";+ tabState.url = "/acme/issues";+ Object.defineProperty(window, "desktopAPI", {+ configurable: true,+ value: { setRendererRouteContext },+ });+});++afterEach(() => {+ resetDiagnosticContext();+});++describe("DiagnosticRouteReporter", () => {+ it("pushes the bucketed tab route to main", () => {+ render(<DiagnosticRouteReporter />);++ expect(setRendererRouteContext).toHaveBeenCalledWith({+ surface: "tab",+ path: "/:slug/issues",+ });+ });++ it("never sends the workspace slug or tab id — this payload reaches telemetry", () => {+ render(<DiagnosticRouteReporter />);++ const sent = JSON.stringify(setRendererRouteContext.mock.calls);+ expect(sent).not.toContain("acme");+ expect(sent).not.toContain("tab-1");+ });++ it("publishes the same route to the in-renderer freeze watchdog", () => {+ render(<DiagnosticRouteReporter />);++ expect(getDiagnosticRoute()).toBe("/:slug/issues");+ });++ it("keeps the issue id out of telemetry", () => {+ tabState.url = "/acme/issues/8db920bc-f982-4d38-95f3-56ec43cbefa8";++ render(<DiagnosticRouteReporter />);++ expect(getDiagnosticRoute()).toBe("/:slug/issues/:id");+ });++ it("reports the login surface before a user exists", () => {+ authState.user = null;++ render(<DiagnosticRouteReporter />);++ expect(setRendererRouteContext).toHaveBeenCalledWith({+ surface: "login",+ path: "/login",+ });+ });++ it("reports an overlay, which is window state rather than a tab route", () => {+ overlayState.overlay = { type: "onboarding" };++ render(<DiagnosticRouteReporter />);++ expect(setRendererRouteContext).toHaveBeenCalledWith({+ surface: "overlay",+ path: "/onboarding",+ });+ });++ it("does not re-send an unchanged context", () => {+ const { rerender } = render(<DiagnosticRouteReporter />);+ expect(setRendererRouteContext).toHaveBeenCalledTimes(1);++ rerender(<DiagnosticRouteReporter />);++ expect(setRendererRouteContext).toHaveBeenCalledTimes(1);+ });++ it("re-reports when the tab navigates to another page", () => {+ const { rerender } = render(<DiagnosticRouteReporter />);+ tabState.url = "/acme/inbox";++ rerender(<DiagnosticRouteReporter />);++ expect(setRendererRouteContext).toHaveBeenLastCalledWith({+ surface: "tab",+ path: "/:slug/inbox",+ });+ expect(getDiagnosticRoute()).toBe("/:slug/inbox");+ });+});diff --git a/apps/desktop/src/renderer/src/platform/diagnostic-route-reporter.tsx b/apps/desktop/src/renderer/src/platform/diagnostic-route-reporter.tsxnew file mode 100644index 0000000000..b21216c1d8--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/diagnostic-route-reporter.tsx@@ -0,0 +1,107 @@+import { useEffect, useRef } from "react";+import { bucketDiagnosticPath, setDiagnosticRoute } from "@multica/core/diagnostics";+import { useAuthStore } from "@multica/core/auth";+import { useActiveTabIdentity, useActiveTabUrl } from "@/stores/tab-store";+import {+ useWindowOverlayStore,+ type WindowOverlay,+} from "@/stores/window-overlay-store";+import type { RendererRouteContextInput } from "../../../shared/renderer-route-context";++/**+ * Publishes which page this window is showing, for freeze diagnostics.+ *+ * Two consumers, because a freeze can be observed from two places:+ *+ * - The main process, via IPC. It is the only party still alive during a+ * true hang, and it cannot ask a blocked renderer anything — so the route+ * has to already be there when the hang starts.+ * - The in-renderer freeze watchdog, via the shared diagnostic context.+ * `location.pathname` is the packaged index.html path here (this window+ * runs a memory router), so without this the watchdog has no route at all.+ *+ * Desktop has three layers that can own the visible page: the logged-out+ * `/login` state, window overlays (onboarding, new-workspace, invite — these+ * are overlay state, not tab routes), and otherwise the active tab's path.+ *+ * Paths are bucketed to route templates before publishing, so telemetry+ * carries `/:slug/issues/:id` rather than a workspace slug and issue id.+ */+export function DiagnosticRouteReporter() {+ const user = useAuthStore((s) => s.user);+ const overlay = useWindowOverlayStore((s) => s.overlay);+ // The slug decides whether a workspace is mounted at all; it is never sent.+ const { slug: activeWorkspaceSlug } = useActiveTabIdentity();+ // The tab url carries search/hash too; bucketing drops both, so telemetry+ // never sees a filter value or an anchor.+ const activeTabUrl = useActiveTabUrl();++ // Last payload pushed to main, so a re-render doesn't re-send an identical+ // context.+ const lastSentRef = useRef<string | null>(null);++ useEffect(() => {+ const surface = resolveSurface({+ user,+ overlay,+ activeWorkspaceSlug,+ activeTabUrl,+ });+ setDiagnosticRoute(surface.path);++ // Only the bucketed template travels. The slug and tab id stay in this+ // process: they identify a workspace and a session, and this payload ends+ // up in telemetry.+ const context: RendererRouteContextInput = {+ surface: surface.kind,+ path: surface.path,+ };+ send(context, lastSentRef);+ }, [user, overlay, activeWorkspaceSlug, activeTabUrl]);++ return null;+}++function send(+ context: RendererRouteContextInput,+ lastSentRef: { current: string | null },+) {+ const serialized = JSON.stringify(context);+ if (serialized === lastSentRef.current) return;+ lastSentRef.current = serialized;+ window.desktopAPI.setRendererRouteContext(context);+}++function resolveSurface({+ user,+ overlay,+ activeWorkspaceSlug,+ activeTabUrl,+}: {+ user: unknown;+ overlay: WindowOverlay | null;+ activeWorkspaceSlug: string | null;+ activeTabUrl: string | null;+}): { kind: RendererRouteContextInput["surface"]; path: string } {+ if (!user) return { kind: "login", path: "/login" };+ if (overlay) {+ return { kind: "overlay", path: bucketDiagnosticPath(overlayPath(overlay)) };+ }+ if (activeWorkspaceSlug && activeTabUrl) {+ return { kind: "tab", path: bucketDiagnosticPath(activeTabUrl) };+ }+ return { kind: "tab", path: "/" };+}++function overlayPath(overlay: WindowOverlay): string {+ switch (overlay.type) {+ case "new-workspace":+ return "/workspaces/new";+ case "onboarding":+ return "/onboarding";+ case "invite":+ return `/invite/${overlay.invitationId}`;+ case "invitations":+ return "/invitations";+ }+}diff --git a/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx b/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsxindex 57a3f51775..7b25c13315 100644--- a/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx@@ -1,6 +1,9 @@import { useEffect, useMemo } from "react";import { useLocation, useNavigate } from "react-router-dom";-import { useCurrentWorkspace } from "@multica/core/paths";+import {+ bucketDiagnosticPath,+ setDiagnosticRoute,+} from "@multica/core/diagnostics";import {NavigationProvider,type NavigationAdapter,@@ -56,17 +59,22 @@ export function IssueWindowNavigationProvider({}) {const location = useLocation();const navigate = useNavigate();- const workspace = useCurrentWorkspace();const runtimeConfig = window.desktopAPI.runtimeConfig;const currentPath = `${location.pathname}${location.search}${location.hash}`;useEffect(() => {+ // Both freeze observers need the route: main for a hang this window never+ // returns from, the in-renderer watchdog for one it survives (its+ // `location.pathname` is the packaged index.html path).+ // Bucketed template only — this payload ends up in a freeze report, so the+ // workspace slug and the issue id must not travel with it.+ const bucketed = bucketDiagnosticPath(currentPath);+ setDiagnosticRoute(bucketed);window.desktopAPI.setRendererRouteContext({surface: "tab",- path: currentPath,- ...(workspace?.slug ? { workspaceSlug: workspace.slug } : {}),+ path: bucketed,});- }, [currentPath, workspace?.slug]);+ }, [currentPath]);useContentLinkHandler(navigate, runtimeConfig);diff --git a/apps/desktop/src/shared/renderer-route-context.test.ts b/apps/desktop/src/shared/renderer-route-context.test.tsnew file mode 100644index 0000000000..42c5d1c110--- /dev/null+++ b/apps/desktop/src/shared/renderer-route-context.test.ts@@ -0,0 +1,69 @@+/**+ * This context is attached to freeze/crash reports, which leave the machine.+ * The sanitizer is the last checkpoint before a renderer-supplied payload is+ * stored for that purpose, so it must construct the result explicitly rather+ * than pass through whatever it was handed — including from a renderer build+ * older than this one, which still sends `workspaceSlug` / `tabId`.+ */+import { describe, expect, it } from "vitest";++import { sanitizeRendererRouteContext } from "./renderer-route-context";++const reportedAt = new Date("2026-07-27T00:00:00.000Z");++describe("sanitizeRendererRouteContext", () => {+ it("keeps the bucketed route", () => {+ expect(+ sanitizeRendererRouteContext({ surface: "tab", path: "/:slug/issues" }, reportedAt),+ ).toEqual({+ surface: "tab",+ path: "/:slug/issues",+ reportedAt: "2026-07-27T00:00:00.000Z",+ });+ });++ it("drops raw identifiers a stale renderer still sends", () => {+ const sanitized = sanitizeRendererRouteContext(+ {+ surface: "tab",+ path: "/:slug/issues",+ workspaceSlug: "acme",+ tabId: "tab-1",+ issueId: "MUL-5345",+ },+ reportedAt,+ );++ expect(JSON.stringify(sanitized)).not.toContain("acme");+ expect(sanitized).not.toHaveProperty("workspaceSlug");+ expect(sanitized).not.toHaveProperty("tabId");+ expect(sanitized).not.toHaveProperty("issueId");+ });++ it("rejects a payload with an unknown surface", () => {+ expect(+ sanitizeRendererRouteContext({ surface: "browser", path: "/x" }, reportedAt),+ ).toBeNull();+ });++ it("rejects a payload with no usable path", () => {+ expect(+ sanitizeRendererRouteContext({ surface: "tab", path: " " }, reportedAt),+ ).toBeNull();+ expect(sanitizeRendererRouteContext({ surface: "tab" }, reportedAt)).toBeNull();+ });++ it("rejects non-object input", () => {+ expect(sanitizeRendererRouteContext(null, reportedAt)).toBeNull();+ expect(sanitizeRendererRouteContext("tab", reportedAt)).toBeNull();+ });++ it("bounds string length so one payload can't bloat every report", () => {+ const sanitized = sanitizeRendererRouteContext(+ { surface: "tab", path: "/".padEnd(5_000, "x") },+ reportedAt,+ );++ expect(sanitized?.path.length).toBe(512);+ });+});diff --git a/apps/desktop/src/shared/renderer-route-context.ts b/apps/desktop/src/shared/renderer-route-context.tsindex 47887fd981..d64f7ad8e7 100644--- a/apps/desktop/src/shared/renderer-route-context.ts+++ b/apps/desktop/src/shared/renderer-route-context.ts@@ -2,11 +2,15 @@ export const RENDERER_ROUTE_CONTEXT_CHANNEL = "renderer:route-context";export type RendererRouteSurface = "login" | "overlay" | "tab";+// This context exists only to be attached to a freeze/crash report, and those+// reports leave the machine. Every field here must therefore be safe to ship:+// route TEMPLATES (`/:slug/issues/:id`), never a workspace slug, tab id, or any+// other raw identifier. Keeping the raw values out at the source is what makes+// the egress side impossible to get wrong.export type RendererRouteContextInput = {surface: RendererRouteSurface;+ /** Bucketed route template. Must not contain slugs or resource ids. */path: string;- workspaceSlug?: string;- tabId?: string;};export type RendererRouteContext = RendererRouteContextInput & {@@ -27,14 +31,11 @@ export function sanitizeRendererRouteContext(const path = sanitizeString(input.path);if (!path) return null;- const workspaceSlug = sanitizeString(input.workspaceSlug);- const tabId = sanitizeString(input.tabId);-+ // Explicit construction, not a spread of `input`: an unknown key sent by a+ // renderer (a stale build, a future field) must never survive into a report.return {surface: input.surface,path,- ...(workspaceSlug ? { workspaceSlug } : {}),- ...(tabId ? { tabId } : {}),reportedAt: reportedAt.toISOString(),};}diff --git a/packages/core/diagnostics/diagnostic-context.test.ts b/packages/core/diagnostics/diagnostic-context.test.tsnew file mode 100644index 0000000000..8625fc1dec--- /dev/null+++ b/packages/core/diagnostics/diagnostic-context.test.ts@@ -0,0 +1,163 @@+import { afterEach, describe, expect, it } from "vitest";++import {+ bucketDiagnosticPath,+ getDiagnosticRoute,+ resetDiagnosticContext,+ setDiagnosticRoute,+} from "./diagnostic-context";+import { paths } from "../paths";++afterEach(() => {+ resetDiagnosticContext();+});++describe("diagnostic route", () => {+ it("holds the published route", () => {+ setDiagnosticRoute("/:slug/issues");+ expect(getDiagnosticRoute()).toBe("/:slug/issues");+ });++ it("treats empty and whitespace values as absent", () => {+ setDiagnosticRoute(" ");+ expect(getDiagnosticRoute()).toBeNull();+ });++ it("clears on null, so a window that leaves a route stops claiming it", () => {+ setDiagnosticRoute("/:slug/issues");+ setDiagnosticRoute(null);+ expect(getDiagnosticRoute()).toBeNull();+ });+});++describe("bucketDiagnosticPath", () => {+ it("replaces the workspace slug", () => {+ expect(bucketDiagnosticPath("/acme/issues")).toBe("/:slug/issues");+ });++ it("templates every workspace detail route", () => {+ expect(bucketDiagnosticPath("/acme/issues/MUL-5345")).toBe("/:slug/issues/:id");+ expect(bucketDiagnosticPath("/acme/projects/p1")).toBe("/:slug/projects/:id");+ expect(bucketDiagnosticPath("/acme/autopilots/ap-7")).toBe("/:slug/autopilots/:id");+ expect(bucketDiagnosticPath("/acme/agents/agt_9")).toBe("/:slug/agents/:id");+ expect(bucketDiagnosticPath("/acme/members/m-3")).toBe("/:slug/members/:id");+ expect(bucketDiagnosticPath("/acme/squads/sq.4")).toBe("/:slug/squads/:id");+ expect(bucketDiagnosticPath("/acme/runtimes/machine-1")).toBe("/:slug/runtimes/:id");+ expect(bucketDiagnosticPath("/acme/skills/skl_123")).toBe("/:slug/skills/:id");+ expect(bucketDiagnosticPath("/acme/attachments/att-8/preview")).toBe(+ "/:slug/attachments/:id/preview",+ );+ expect(bucketDiagnosticPath("/acme/runtimes/machine-1/runtime/rt-2")).toBe(+ "/:slug/runtimes/:id/runtime/:runtimeId",+ );+ });++ // The previous implementation guessed from the shape of a segment, so any id+ // that was not a UUID, an issue key or digits travelled to telemetry intact.+ it("templates ids that look nothing like ids", () => {+ for (const [path, expected] of [+ ["/acme/projects/p1", "/:slug/projects/:id"],+ ["/acme/skills/skl_123", "/:slug/skills/:id"],+ ["/acme/agents/my-favourite-agent", "/:slug/agents/:id"],+ ["/acme/squads/Platform Team", "/:slug/squads/:id"],+ ["/acme/issues/new", "/:slug/issues/:id"],+ ] as const) {+ expect(bucketDiagnosticPath(path)).toBe(expected);+ }+ });++ // paths.ts URL-encodes every id, so an id containing a slash or a space+ // arrives as one already-escaped segment.+ it("templates percent-encoded ids without splitting them", () => {+ expect(bucketDiagnosticPath("/acme/runtimes/machine%2Fruntime")).toBe(+ "/:slug/runtimes/:id",+ );+ expect(+ bucketDiagnosticPath("/acme/runtimes/machine%2Fruntime/runtime/runtime%20one"),+ ).toBe("/:slug/runtimes/:id/runtime/:runtimeId");+ expect(bucketDiagnosticPath("/my%20workspace/skills/a%2Fb")).toBe(+ "/:slug/skills/:id",+ );+ });++ it("keeps static segments that share a slot with an id", () => {+ expect(bucketDiagnosticPath("/acme/agents/new")).toBe("/:slug/agents/new");+ expect(bucketDiagnosticPath("/acme/agents")).toBe("/:slug/agents");+ });++ it("keeps pre-workspace routes intact", () => {+ expect(bucketDiagnosticPath("/login")).toBe("/login");+ expect(bucketDiagnosticPath("/workspaces/new")).toBe("/workspaces/new");+ expect(bucketDiagnosticPath("/invitations")).toBe("/invitations");+ expect(bucketDiagnosticPath("/auth/callback")).toBe("/auth/callback");+ });++ it("templates the invitation id", () => {+ expect(bucketDiagnosticPath("/invite/8db920bc-f982-4d38-95f3-56ec43cbefa8")).toBe(+ "/invite/:id",+ );+ expect(bucketDiagnosticPath("/invite/plain-token")).toBe("/invite/:id");+ });++ it("drops query string and hash — they can carry resource ids", () => {+ expect(bucketDiagnosticPath("/acme/issues?issue=MUL-1#comment-3")).toBe(+ "/:slug/issues",+ );+ });++ it("normalizes the root and a bare workspace path", () => {+ expect(bucketDiagnosticPath("/")).toBe("/");+ expect(bucketDiagnosticPath("/acme")).toBe("/:slug");+ });++ // A route we do not know is exactly the case where an id cannot be told from+ // a page name, so nothing from it travels.+ it("masks an unknown route instead of passing segments through", () => {+ expect(bucketDiagnosticPath("/acme/issues/MUL-1/secret-tab")).toBe(+ "/:slug/issues/*",+ );+ expect(bucketDiagnosticPath("/acme/not-a-section/raw-value")).toBe("/:slug/*");+ expect(bucketDiagnosticPath("/login/raw-value")).toBe("/login/*");+ });+});++// Bucketing is only safe while it knows every route. This walks the real path+// builders rather than a copy of them, so adding a route to paths.ts without+// adding it here fails CI instead of shipping a raw id.+describe("route coverage stays in step with paths.ts", () => {+ const SLUG = "workspace-slug-value";+ const RAW_ID = "raw-identifier-value";+ const RAW_SECOND_ID = "second-raw-identifier-value";++ function buildAll(): string[] {+ const scoped = paths.workspace(SLUG) as Record<string, (...args: string[]) => string>;+ const global = {+ login: paths.login,+ newWorkspace: paths.newWorkspace,+ invite: paths.invite,+ invitations: paths.invitations,+ onboarding: paths.onboarding,+ authCallback: paths.authCallback,+ root: paths.root,+ } as Record<string, (...args: string[]) => string>;++ return [...Object.values(scoped), ...Object.values(global)].map((build) =>+ build(RAW_ID, RAW_SECOND_ID),+ );+ }++ it("never lets a slug or an id through, for any builder", () => {+ for (const built of buildAll()) {+ const bucketed = bucketDiagnosticPath(built);+ expect(bucketed, `leaked from ${built}`).not.toContain(SLUG);+ expect(bucketed, `leaked from ${built}`).not.toContain(RAW_ID);+ expect(bucketed, `leaked from ${built}`).not.toContain(RAW_SECOND_ID);+ }+ });++ it("recognizes every builder — no builder falls back to the mask", () => {+ for (const built of buildAll()) {+ expect(bucketDiagnosticPath(built), `unrecognized: ${built}`).not.toContain("*");+ }+ });+});diff --git a/packages/core/diagnostics/diagnostic-context.ts b/packages/core/diagnostics/diagnostic-context.tsnew file mode 100644index 0000000000..42fb016513--- /dev/null+++ b/packages/core/diagnostics/diagnostic-context.ts@@ -0,0 +1,167 @@+// Where the app thinks it is — the one field a freeze report is useless+// without.+//+// Desktop runs a memory router, so `location.pathname` in the renderer is the+// packaged `index.html` file path and can never identify the visible page. The+// desktop shell publishes its bucketed route here; the freeze watchdog reads it+// so an in-thread freeze event carries a real route. Web sets nothing and keeps+// using `location.pathname`.++let route: string | null = null;++/** Longest route we keep; these are our own short templates. */+const MAX_ROUTE_LENGTH = 256;++/**+ * Publish the current app route, already bucketed to a template — see+ * `bucketDiagnosticPath`. Pass null when leaving a known route.+ */+export function setDiagnosticRoute(next: string | null): void {+ if (typeof next !== "string") {+ route = null;+ return;+ }+ const trimmed = next.trim();+ route = trimmed ? trimmed.slice(0, MAX_ROUTE_LENGTH) : null;+}++export function getDiagnosticRoute(): string | null {+ return route;+}++/** Test seam: drop state so cases don't leak into each other. */+export function resetDiagnosticContext(): void {+ route = null;+}++// The known route shapes, mirroring `packages/core/paths/paths.ts` (the single+// path builder every navigation goes through) and the routers that consume it.+// Bucketing matches against these STRUCTURALLY: a `:param` slot is whatever+// occupies that position, whether it is a UUID, an issue key, `p1`, `skl_123`+// or a percent-encoded string.+//+// Guessing from the shape of a segment instead would leak every id that does+// not look like an id — project, skill, agent, runtime and attachment ids are+// all arbitrary strings. `paths.ts` also URL-encodes them, so an id containing+// a slash arrives as one already-escaped segment and must not be mistaken for+// two path segments.+//+// A route added to `paths.ts` without being added here is not a leak: an+// unmatched path is masked below rather than passed through. The parity test in+// diagnostic-context.test.ts walks the real builders and fails when one is+// missing, so this list cannot silently fall behind.+type RoutePattern = readonly string[];++const WORKSPACE_ROUTES: readonly RoutePattern[] = [+ ["issues"],+ ["issues", ":id"],+ ["projects"],+ ["projects", ":id"],+ ["autopilots"],+ ["autopilots", ":id"],+ ["agents"],+ ["agents", "new"],+ ["agents", ":id"],+ ["members", ":id"],+ ["squads"],+ ["squads", ":id"],+ ["inbox"],+ ["chat"],+ ["my-issues"],+ ["usage"],+ ["billing"],+ ["runtimes"],+ ["runtimes", ":id"],+ ["runtimes", ":id", "runtime", ":runtimeId"],+ ["skills"],+ ["skills", ":id"],+ ["settings"],+ ["attachments", ":id", "preview"],+];++const GLOBAL_ROUTES: readonly RoutePattern[] = [+ ["login"],+ ["signup"],+ ["logout"],+ ["workspaces", "new"],+ ["invite", ":id"],+ ["invitations"],+ ["onboarding"],+ ["auth", "callback"],+];++const WORKSPACE_SECTIONS = new Set(WORKSPACE_ROUTES.map((route) => route[0]!));+const GLOBAL_SECTIONS = new Set(GLOBAL_ROUTES.map((route) => route[0]!));++/**+ * Collapse a concrete path to its route template: `/acme/issues/MUL-12` becomes+ * `/:slug/issues/:id`. Diagnostics only need to know which screen the user was+ * on, and a template keeps workspace slugs and resource ids out of telemetry+ * while making the field groupable in one query.+ *+ * A path that matches no known route is masked with `*` rather than reported —+ * an unrecognized segment is exactly the case where we cannot tell an id from a+ * page name, so it never travels.+ */+export function bucketDiagnosticPath(path: string): string {+ const [pathname = ""] = path.split(/[?#]/);+ const segments = pathname.split("/").filter(Boolean);+ if (segments.length === 0) return "/";++ const globalRoute = matchRoute(segments, GLOBAL_ROUTES);+ if (globalRoute) return `/${globalRoute.join("/")}`;++ // Reserved slugs mean a known global section can never also be a workspace,+ // so an unmatched path under one keeps its section and masks the rest.+ const first = segments[0]!;+ if (GLOBAL_SECTIONS.has(first)) return `/${first}/*`;++ // Everything else is workspace-scoped; the leading segment is the slug.+ const rest = segments.slice(1);+ if (rest.length === 0) return "/:slug";++ const scoped = matchRoute(rest, WORKSPACE_ROUTES);+ if (scoped) return `/:slug/${scoped.join("/")}`;++ const section = rest[0]!;+ return WORKSPACE_SECTIONS.has(section)+ ? `/:slug/${section}/*`+ : "/:slug/*";+}++/**+ * Find the route this path follows. A `:param` slot accepts any single segment;+ * every other slot must match literally. When several patterns fit, the most+ * literal one wins, so `/agents/new` is the create page rather than an agent+ * whose id happens to be "new".+ */+function matchRoute(+ segments: readonly string[],+ patterns: readonly RoutePattern[],+): RoutePattern | null {+ let best: RoutePattern | null = null;+ let bestLiterals = -1;++ for (const pattern of patterns) {+ if (pattern.length !== segments.length) continue;++ let literals = 0;+ let matches = true;+ for (let i = 0; i < pattern.length; i += 1) {+ const slot = pattern[i]!;+ if (slot.startsWith(":")) continue;+ if (slot !== segments[i]) {+ matches = false;+ break;+ }+ literals += 1;+ }++ if (matches && literals > bestLiterals) {+ best = pattern;+ bestLiterals = literals;+ }+ }++ return best;+}diff --git a/packages/core/diagnostics/freeze-watchdog.test.ts b/packages/core/diagnostics/freeze-watchdog.test.tsindex 77b5aad437..b264753d09 100644--- a/packages/core/diagnostics/freeze-watchdog.test.ts+++ b/packages/core/diagnostics/freeze-watchdog.test.ts@@ -26,9 +26,11 @@ function fireLongTask(duration: number) {async function load() {vi.resetModules();const mod = await import("./freeze-watchdog");+ const { setDiagnosticRoute } = await import("./diagnostic-context");const { captureEvent } = await import("../analytics");return {installFreezeWatchdog: mod.installFreezeWatchdog,+ setDiagnosticRoute,captureEvent: captureEvent as unknown as ReturnType<typeof vi.fn>,};}@@ -63,6 +65,35 @@ describe("installFreezeWatchdog", () => {});});+ // Desktop runs a memory router, so `location.pathname` there is the packaged+ // index.html path and identifies no page at all. The shell publishes its real+ // route instead; web publishes nothing and keeps the URL.+ it("prefers the published diagnostic route over location.pathname", async () => {+ const { installFreezeWatchdog, setDiagnosticRoute, captureEvent } = await load();+ setDiagnosticRoute("/:slug/issues/:id");+ installFreezeWatchdog();++ fireLongTask(2300);++ expect(captureEvent).toHaveBeenCalledWith("client_unresponsive", {+ source: "longtask",+ duration_ms: 2300,+ path: "/:slug/issues/:id",+ });+ });++ it("falls back to location.pathname when no route was published (web)", async () => {+ const { installFreezeWatchdog, captureEvent } = await load();+ installFreezeWatchdog();++ fireLongTask(2300);++ expect(captureEvent).toHaveBeenCalledWith(+ "client_unresponsive",+ expect.objectContaining({ path: "/acme/issues" }),+ );+ });+it("ignores blocks below the threshold (normal render cost)", async () => {const { installFreezeWatchdog, captureEvent } = await load();installFreezeWatchdog();diff --git a/packages/core/diagnostics/freeze-watchdog.ts b/packages/core/diagnostics/freeze-watchdog.tsindex 4d632d5866..1e8c331ad5 100644--- a/packages/core/diagnostics/freeze-watchdog.ts+++ b/packages/core/diagnostics/freeze-watchdog.ts@@ -18,6 +18,7 @@// platform branch here.import { captureEvent } from "../analytics";+import { getDiagnosticRoute } from "./diagnostic-context";// 2s is well above the normal switch/render cost (measured 50–600ms) and just// under Electron's renderer-hang threshold, so an event here means "the user@@ -59,7 +60,7 @@ export function installFreezeWatchdog(): void {captureEvent("client_unresponsive", {source: "longtask",duration_ms: Math.round(entry.duration),- path: typeof location !== "undefined" ? location.pathname : undefined,+ path: resolveDiagnosticPath(),});}});@@ -70,3 +71,17 @@ export function installFreezeWatchdog(): void {// longtask entry type unsupported on this engine — nothing else to do.}}++/**+ * Which page the freeze happened on.+ *+ * The desktop shell publishes its memory-router route, because+ * `location.pathname` there is the packaged `index.html` path and identifies+ * nothing. Web publishes no route and falls back to the real URL, which is+ * already the right answer.+ */+function resolveDiagnosticPath(): string | undefined {+ const route = getDiagnosticRoute();+ if (route) return route;+ return typeof location !== "undefined" ? location.pathname : undefined;+}diff --git a/packages/core/diagnostics/index.ts b/packages/core/diagnostics/index.tsnew file mode 100644index 0000000000..36b80ab28c--- /dev/null+++ b/packages/core/diagnostics/index.ts@@ -0,0 +1,7 @@+export { installFreezeWatchdog } from "./freeze-watchdog";+export {+ bucketDiagnosticPath,+ getDiagnosticRoute,+ resetDiagnosticContext,+ setDiagnosticRoute,+} from "./diagnostic-context";diff --git a/packages/core/package.json b/packages/core/package.jsonindex 0d05477e6a..55de94551a 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -115,6 +115,7 @@"./platform": "./platform/index.ts","./shortcuts": "./shortcuts/index.ts","./analytics": "./analytics/index.ts",+ "./diagnostics": "./diagnostics/index.ts","./client-usage": "./client-usage/index.ts","./i18n": "./i18n/index.ts","./i18n/react": "./i18n/react.ts",