Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(tauri): add memory recording with correlated telemetry (#7489)
Eric Hayesc5f717027af5
diff --git a/apps/web/src/observability/browser.test.ts b/apps/web/src/observability/browser.test.tsnew file mode 100644index 0000000000..eccf05d872--- /dev/null+++ b/apps/web/src/observability/browser.test.ts@@ -0,0 +1,86 @@+import { Telemetry } from '@macro-inc/observability';+import { beforeEach, expect, it, vi } from 'vitest';+import { initializeBrowserObservability } from './browser';+import { readDesktopDiagnostics } from './desktop';+import { initializeUiOperationTelemetry } from './ui-operation';++vi.mock('@core/util/platform', () => ({+ getPlatform: () => 'desktop',+ isTauri: () => true,+}));+vi.mock('@graphql-cache/rollout-observability', () => ({+ recordBrowserTursoCacheNavigation: vi.fn(),+}));+vi.mock('@macro-inc/observability', () => ({+ Telemetry: { init: vi.fn(), info: vi.fn(), flush: vi.fn(), error: vi.fn() },+}));+vi.mock('@macro-inc/observability/web', () => ({+ createWebTracingProvider: vi.fn(),+}));+vi.mock('@macro-inc/observability/zone', () => ({+ ZoneContextManager: class {},+}));+vi.mock('./ui-operation', () => ({+ initializeUiOperationTelemetry: vi.fn(() => vi.fn()),+}));+vi.mock('./desktop', () => ({+ readDesktopDiagnostics: vi.fn(),+ desktopResourceAttributes: () => ({+ 'service.instance.id': 'launch-1',+ 'macro.recording.id': 'recording-1',+ }),+ createDesktopMemoryRecording: () => ({+ attributes: () => ({}),+ accept: vi.fn(),+ start: vi.fn(),+ dispose: vi.fn(),+ }),+}));++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv('VITE_ENABLE_BROWSER_OTEL', 'false');+ vi.mocked(Telemetry.init).mockImplementation(async (config) => {+ await config.enabled();+ });+});++it('explicit native recording overrides the normal enablement gate and exporter before startup', async () => {+ vi.mocked(readDesktopDiagnostics).mockResolvedValue({+ identity: {+ instanceId: 'launch-1',+ recordingId: 'recording-1',+ tracesUrl: 'http://localhost:4318/v1/traces',+ nativeVersion: '2.5.0',+ os: 'macos',+ hostPid: 1,+ },+ samples: [],+ droppedSamples: 0,+ });+ await initializeBrowserObservability();+ const config = vi.mocked(Telemetry.init).mock.calls[0][0];+ expect(await config.enabled()).toBe(true);+ expect(config.recording).toBe(true);+ expect(initializeUiOperationTelemetry).toHaveBeenCalledOnce();+ expect(config.tracesUrl).toBe('http://localhost:4318/v1/traces');+ expect(config.logsUrl).toBe('http://localhost:4318/v1/logs');+ expect(config.resourceAttributes).toMatchObject({+ 'app.runtime': 'tauri',+ 'service.instance.id': 'launch-1',+ 'macro.recording.id': 'recording-1',+ });+});++it('an older binary without diagnostics still obeys the normal telemetry gate', async () => {+ vi.mocked(readDesktopDiagnostics).mockResolvedValue(undefined);+ await initializeBrowserObservability();+ const config = vi.mocked(Telemetry.init).mock.calls[0][0];+ expect(await config.enabled()).toBe(false);+ expect(config.recording).toBe(false);+ expect(initializeUiOperationTelemetry).not.toHaveBeenCalled();+ expect(config.resourceAttributes).toMatchObject({+ 'app.runtime': 'tauri',+ 'app.platform': 'desktop',+ });+});diff --git a/apps/web/src/observability/browser.ts b/apps/web/src/observability/browser.tsindex 1defce61eb..9f09066782 100644--- a/apps/web/src/observability/browser.ts+++ b/apps/web/src/observability/browser.ts@@ -1,8 +1,14 @@+import { getPlatform, isTauri } from '@core/util/platform';import { recordBrowserTursoCacheNavigation } from '@graphql-cache/rollout-observability';import { Telemetry } from '@macro-inc/observability';import { createWebTracingProvider } from '@macro-inc/observability/web';// This static import loads the zone.js Promise patch before application modules run.import { ZoneContextManager } from '@macro-inc/observability/zone';+import {+ createDesktopMemoryRecording,+ desktopResourceAttributes,+ readDesktopDiagnostics,+} from './desktop';import { initializeUiOperationTelemetry } from './ui-operation';async function browserTelemetryEnabled(hasExporter: boolean): Promise<boolean> {@@ -46,7 +52,12 @@ async function browserTelemetryEnabled(hasExporter: boolean): Promise<boolean> {/** Initialize browser telemetry and its application-level lifecycle hooks. */export async function initializeBrowserObservability(): Promise<void> {let browserEnabled = false;+ const desktop = await readDesktopDiagnostics();+ const recording = desktop?.identity.recordingId+ ? createDesktopMemoryRecording(desktop)+ : undefined;const configuredTracesUrl =+ desktop?.identity.tracesUrl ??import.meta.env.VITE_OTEL_EXPORTER_URL ??(import.meta.hot ? 'http://localhost:8098/i/otlp/v1/traces' : undefined);// Local stacks use a same-origin path; exporters expect an absolute URL.@@ -61,8 +72,18 @@ export async function initializeBrowserObservability(): Promise<void> {tracesUrl,logsUrl: tracesUrl?.replace(/\/v1\/traces\/?$/, '/v1/logs'),contextManager: new ZoneContextManager(),+ resourceAttributes: {+ 'service.version': import.meta.env.__APP_VERSION__,+ 'app.runtime': isTauri() ? 'tauri' : 'browser',+ 'app.platform': getPlatform(),+ ...(desktop && desktopResourceAttributes(desktop)),+ },+ recording: Boolean(recording),+ spanAttributes: recording?.attributes,enabled: async () => {- browserEnabled = await browserTelemetryEnabled(Boolean(tracesUrl));+ browserEnabled = recording+ ? true+ : await browserTelemetryEnabled(Boolean(tracesUrl));return browserEnabled;},};@@ -72,6 +93,15 @@ export async function initializeBrowserObservability(): Promise<void> {tracingProvider: (resource, getUserId) =>createWebTracingProvider(telemetryConfig, resource, getUserId),});+ if (recording && desktop) {+ recording.accept(desktop);+ Telemetry.info('Desktop memory recording enabled', {+ 'macro.recording.id': desktop.identity.recordingId ?? undefined,+ 'service.instance.id': desktop.identity.instanceId,+ });+ void recording.start();+ import.meta.hot?.dispose(() => recording.dispose());+ }recordBrowserTursoCacheNavigation();if (browserEnabled) {const disposeUiTelemetry = initializeUiOperationTelemetry();diff --git a/apps/web/src/observability/desktop.test.ts b/apps/web/src/observability/desktop.test.tsnew file mode 100644index 0000000000..6692c567ab--- /dev/null+++ b/apps/web/src/observability/desktop.test.ts@@ -0,0 +1,151 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ createMemoryRecording,+ type DesktopSnapshot,+ desktopResourceAttributes,+ type MemorySample,+ memoryAttributes,+} from './desktop';++vi.mock('@core/util/platform', () => ({+ getPlatform: () => 'desktop',+ isTauri: () => true,+}));+vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() }));++function sample(sequence = 1): MemorySample {+ return {+ sequence,+ timestampMs: 1000,+ frontendStatus: 'available',+ error: null,+ processes: [+ { pid: 1, role: 'native', residentBytes: 100, footprintBytes: 80 },+ { pid: 2, role: 'web_content', residentBytes: 300, footprintBytes: 250 },+ { pid: 3, role: 'gpu', residentBytes: 50, footprintBytes: 40 },+ ],+ };+}+function snapshot(samples: MemorySample[]): DesktopSnapshot {+ return {+ identity: {+ instanceId: 'launch-1',+ recordingId: 'recording-1',+ tracesUrl: 'http://localhost:4318/v1/traces',+ nativeVersion: '2.5.0',+ os: 'macos',+ hostPid: 1,+ },+ samples,+ droppedSamples: 0,+ };+}++afterEach(() => {+ vi.useRealTimers();+});++describe('desktop recording', () => {+ it('separates native, frontend, and app memory without pretending RSS is footprint', () => {+ expect(memoryAttributes(sample())).toMatchObject({+ 'macro.memory.native.rss_bytes': 100,+ 'macro.memory.native.footprint_bytes': 80,+ 'macro.memory.frontend.footprint_bytes': 290,+ 'macro.memory.app.footprint_bytes': 370,+ });+ const unavailable = {+ ...sample(),+ frontendStatus: 'unavailable' as const,+ processes: sample().processes.slice(0, 1),+ };+ expect(memoryAttributes(unavailable)).not.toHaveProperty(+ 'macro.memory.frontend.footprint_bytes'+ );+ expect(memoryAttributes(unavailable)).not.toHaveProperty(+ 'macro.memory.app.footprint_bytes'+ );+ expect(+ memoryAttributes({ ...sample(), frontendStatus: 'partial' })+ ).not.toHaveProperty('macro.memory.app.footprint_bytes');+ });++ it('correlates launches independently of recordings and tags the native runtime', () => {+ const recorded = snapshot([]);+ expect(desktopResourceAttributes(recorded)).toMatchObject({+ 'app.runtime': 'tauri',+ 'app.platform': 'desktop',+ 'service.instance.id': 'launch-1',+ 'macro.recording.id': 'recording-1',+ 'os.type': 'darwin',+ });+ recorded.identity.recordingId = null;+ expect(desktopResourceAttributes(recorded)).toMatchObject({+ 'macro.recording.enabled': false,+ 'macro.recording.id': undefined,+ });+ });++ it('exports each new sample once, preserves sample times, and expires stale readings', () => {+ vi.useFakeTimers();+ vi.setSystemTime(2000);+ const sink = { recordSample: vi.fn(), warn: vi.fn() };+ const save = vi.fn();+ const recording = createMemoryRecording(vi.fn(), sink, 1, save);+ recording.accept(snapshot([sample(1), sample(2)]));+ recording.accept(snapshot([sample(2)]));+ expect(sink.recordSample).toHaveBeenCalledTimes(1);+ expect(sink.recordSample).toHaveBeenCalledWith(+ 'app.memory.sample',+ expect.any(Object),+ 1000+ );+ expect(save).toHaveBeenCalledWith(2);+ expect(recording.attributes()).toMatchObject({+ 'macro.memory.status': 'current',+ 'macro.memory.sample_age_ms': 1000,+ });+ vi.setSystemTime(7000);+ expect(recording.attributes()).toEqual({+ 'macro.memory.status': 'stale',+ 'macro.memory.sample_age_ms': 6000,+ });+ recording.dispose();+ });++ it('reports buffer loss and stops polling or accepting results after disposal', async () => {+ vi.useFakeTimers();+ let resolve!: (value: DesktopSnapshot) => void;+ const read = vi.fn(+ () =>+ new Promise<DesktopSnapshot>((r) => {+ resolve = r;+ })+ );+ const sink = { recordSample: vi.fn(), warn: vi.fn() };+ const recording = createMemoryRecording(read, sink);+ recording.accept({ ...snapshot([sample(9)]), droppedSamples: 8 });+ expect(sink.warn).toHaveBeenCalledWith(+ 'Native memory recording buffer overflowed',+ { 'macro.memory.dropped_samples': 8 }+ );+ const started = recording.start();+ recording.dispose();+ resolve(snapshot([sample()]));+ await started;+ await vi.advanceTimersByTimeAsync(5000);+ expect(read).toHaveBeenCalledTimes(1);+ expect(sink.recordSample).toHaveBeenCalledTimes(1);+ });++ it('does not report buffer loss for samples already exported before a reload', () => {+ const sink = { recordSample: vi.fn(), warn: vi.fn() };+ const recording = createMemoryRecording(vi.fn(), sink, 10);+ recording.accept({+ ...snapshot([sample(9), sample(10), sample(11)]),+ droppedSamples: 8,+ });+ expect(sink.warn).not.toHaveBeenCalled();+ expect(sink.recordSample).toHaveBeenCalledTimes(1);+ recording.dispose();+ });+});diff --git a/apps/web/src/observability/desktop.ts b/apps/web/src/observability/desktop.tsnew file mode 100644index 0000000000..bb468b0aea--- /dev/null+++ b/apps/web/src/observability/desktop.ts@@ -0,0 +1,230 @@+import { getPlatform, isTauri } from '@core/util/platform';+import { type Attributes, Telemetry } from '@macro-inc/observability';+import { invoke } from '@tauri-apps/api/core';++export type ProcessMemory = {+ pid: number;+ role: 'native' | 'web_content' | 'gpu' | 'network';+ residentBytes: number;+ footprintBytes: number;+};++export type MemorySample = {+ sequence: number;+ timestampMs: number;+ processes: ProcessMemory[];+ frontendStatus: 'available' | 'partial' | 'unavailable';+ error: string | null;+};++export type DesktopSnapshot = {+ identity: {+ instanceId: string;+ recordingId: string | null;+ tracesUrl: string | null;+ nativeVersion: string;+ os: string;+ hostPid: number;+ };+ samples: MemorySample[];+ droppedSamples: number;+};++type SampleSink = {+ recordSample: typeof Telemetry.recordSample;+ warn: typeof Telemetry.warn;+};++/** Preserve missing coverage instead of reporting unavailable memory as zero. */+export function memoryAttributes(sample: MemorySample): Attributes {+ const attributes: Attributes = {+ 'macro.memory.timestamp_ms': sample.timestampMs,+ 'macro.memory.sequence': sample.sequence,+ 'macro.memory.frontend.status': sample.frontendStatus,+ };+ for (const role of ['native', 'web_content', 'gpu', 'network'] as const) {+ const processes = sample.processes.filter(+ (process) => process.role === role+ );+ if (!processes.length) continue;+ attributes[`macro.memory.${role}.rss_bytes`] = processes.reduce(+ (sum, process) => sum + process.residentBytes,+ 0+ );+ attributes[`macro.memory.${role}.footprint_bytes`] = processes.reduce(+ (sum, process) => sum + process.footprintBytes,+ 0+ );+ attributes[`macro.memory.${role}.process_count`] = processes.length;+ attributes[`macro.memory.${role}.pids`] = processes.map(+ (process) => process.pid+ );+ }+ if (sample.frontendStatus !== 'unavailable') {+ attributes['macro.memory.frontend.footprint_bytes'] = sample.processes+ .filter((process) => process.role !== 'native')+ .reduce((sum, process) => sum + process.footprintBytes, 0);+ }+ if (+ sample.frontendStatus === 'available' &&+ sample.processes.some((p) => p.role === 'native')+ ) {+ attributes['macro.memory.app.footprint_bytes'] = sample.processes.reduce(+ (sum, process) => sum + process.footprintBytes,+ 0+ );+ }+ return attributes;+}++export function desktopResourceAttributes(+ snapshot: DesktopSnapshot+): Attributes {+ return {+ 'app.runtime': 'tauri',+ 'app.platform': getPlatform(),+ 'service.instance.id': snapshot.identity.instanceId,+ 'macro.recording.id': snapshot.identity.recordingId ?? undefined,+ 'macro.recording.enabled': snapshot.identity.recordingId !== null,+ 'macro.native.version': snapshot.identity.nativeVersion,+ 'os.type':+ snapshot.identity.os === 'macos' ? 'darwin' : snapshot.identity.os,+ 'macro.native.pid': snapshot.identity.hostPid,+ };+}++/** Native samples keep their original times, including after a webview pause. */+export function createMemoryRecording(+ read: (afterSequence: number) => Promise<DesktopSnapshot>,+ sink: SampleSink,+ initialSequence = 0,+ saveSequence: (sequence: number) => void = () => {}+) {+ let sequence = initialSequence;+ let latest: MemorySample | undefined;+ let disposed = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let pending = false;++ function accept(snapshot: DesktopSnapshot) {+ if (disposed) return;+ // Bootstrap reads the entire native buffer, even when this webview has a+ // saved cursor. Only report samples missing after our own cursor.+ const firstNewSample = snapshot.samples.find(+ (sample) => sample.sequence > sequence+ );+ const droppedSamples = firstNewSample+ ? firstNewSample.sequence - sequence - 1+ : 0;+ if (droppedSamples > 0) {+ sink.warn('Native memory recording buffer overflowed', {+ 'macro.memory.dropped_samples': droppedSamples,+ });+ }+ for (const sample of snapshot.samples) {+ if (sample.sequence <= sequence) continue;+ latest = sample;+ sink.recordSample(+ 'app.memory.sample',+ memoryAttributes(sample),+ sample.timestampMs+ );+ if (sample.error && sample.error !== lastError) {+ sink.warn('Native memory recording has incomplete coverage', {+ 'macro.memory.error': sample.error,+ });+ }+ lastError = sample.error;+ sequence = sample.sequence;+ saveSequence(sequence);+ }+ }+ let lastError: string | null = null;++ async function poll() {+ if (disposed || pending) return;+ pending = true;+ try {+ accept(await read(sequence));+ } catch (error) {+ sink.warn('Unable to read native memory samples', {+ 'error.message': error instanceof Error ? error.message : String(error),+ });+ } finally {+ pending = false;+ if (!disposed) timer = setTimeout(() => void poll(), 1000);+ }+ }++ return {+ accept,+ start: poll,+ attributes(): Attributes {+ if (!latest) return { 'macro.memory.status': 'pending' };+ const age = Math.max(0, Date.now() - latest.timestampMs);+ if (age > 5000) {+ return {+ 'macro.memory.status': 'stale',+ 'macro.memory.sample_age_ms': age,+ };+ }+ return {+ ...memoryAttributes(latest),+ 'macro.memory.status': 'current',+ 'macro.memory.sample_age_ms': age,+ };+ },+ dispose() {+ disposed = true;+ clearTimeout(timer);+ },+ };+}++export async function readDesktopDiagnostics(): Promise<+ DesktopSnapshot | undefined+> {+ if (!isTauri()) return undefined;+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ invoke<DesktopSnapshot>('read_desktop_diagnostics'),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(+ () => reject(new Error('Native diagnostics timed out')),+ 3000+ );+ }),+ ]);+ } catch (error) {+ // Older binaries may receive a newer frontend bundle without this command.+ console.warn('[telemetry] Native diagnostics unavailable', error);+ return undefined;+ } finally {+ clearTimeout(timeout);+ }+}++export function createDesktopMemoryRecording(snapshot: DesktopSnapshot) {+ const key = `macro-memory-sequence:${snapshot.identity.instanceId}`;+ let sequence = 0;+ try {+ const saved = Number(sessionStorage.getItem(key));+ if (Number.isSafeInteger(saved) && saved >= 0) sequence = saved;+ } catch {+ /* Storage may be disabled; telemetry still works. */+ }+ return createMemoryRecording(+ (afterSequence) =>+ invoke<DesktopSnapshot>('read_desktop_diagnostics', { afterSequence }),+ Telemetry,+ sequence,+ (value) => {+ try {+ sessionStorage.setItem(key, String(value));+ } catch {+ /* Best effort. */+ }+ }+ );+}diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex 42ff168631..d46d3c24c3 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -139,6 +139,56 @@ dependencies = ["libc",]+[[package]]+name = "anstream"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"+dependencies = [+ "anstyle",+ "anstyle-parse",+ "anstyle-query",+ "anstyle-wincon",+ "colorchoice",+ "is_terminal_polyfill",+ "utf8parse",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anstyle-parse"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"+dependencies = [+ "utf8parse",+]++[[package]]+name = "anstyle-query"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "anstyle-wincon"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"+dependencies = [+ "anstyle",+ "once_cell_polyfill",+ "windows-sys 0.61.2",+]+[[package]]name = "antithesis_sdk"version = "0.2.9"@@ -195,9 +245,11 @@ dependencies = [name = "app"version = "0.1.0"dependencies = [+ "clap","graphql_cache_plugin","http","jni",+ "libc","log","logger","macro_bundle_updater_plugin",@@ -970,6 +1022,46 @@ dependencies = ["inout",]+[[package]]+name = "clap"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"+dependencies = [+ "anstream",+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]++[[package]]+name = "clap_lex"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"+[[package]]name = "cmake"version = "0.1.58"@@ -988,6 +1080,12 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "colorchoice"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]name = "combine"version = "4.6.7"@@ -1569,7 +1667,7 @@ dependencies = ["libc","option-ext","redox_users",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -1854,7 +1952,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -2241,17 +2339,17 @@ dependencies = [[[package]]name = "generator"-version = "0.8.9"+version = "0.8.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b3b854b0e584ead1a33f18b2fcad7cf7be18b3875c78816b753639aa501513ae"+checksum = "52f04ae4152da20c76fe800fa48659201d5cf627c5149ca0b707b69d7eef6cf9"dependencies = ["cc","cfg-if","libc","log","rustversion",- "windows-link 0.1.3",- "windows-result 0.3.4",+ "windows-link 0.2.1",+ "windows-result 0.4.1",][[package]]@@ -2412,7 +2510,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"dependencies = ["heck 0.4.1",- "proc-macro-crate 2.0.2",+ "proc-macro-crate 2.0.0","proc-macro-error","proc-macro2","quote",@@ -2775,7 +2873,7 @@ dependencies = ["tokio","tower-service","tracing",- "windows-registry",+ "windows-registry 0.6.1",][[package]]@@ -2790,7 +2888,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.61.2",+ "windows-core 0.62.2",][[package]]@@ -3083,7 +3181,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"dependencies = ["hermit-abi","libc",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -3096,6 +3194,12 @@ dependencies = ["once_cell",]+[[package]]+name = "is_terminal_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"+[[package]]name = "item-filter-index"version = "0.1.0"@@ -3729,7 +3833,7 @@ dependencies = ["png 0.18.1","serde","thiserror 2.0.18",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -3950,7 +4054,7 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -4236,6 +4340,12 @@ version = "1.21.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"+[[package]]+name = "once_cell_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]name = "opaque-debug"version = "0.3.1"@@ -4796,11 +4906,10 @@ dependencies = [[[package]]name = "proc-macro-crate"-version = "2.0.2"+version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"+checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8"dependencies = [- "toml_datetime 0.6.3","toml_edit 0.20.2",]@@ -4981,7 +5090,7 @@ dependencies = ["once_cell","socket2","tracing",- "windows-sys 0.60.2",+ "windows-sys 0.59.0",][[package]]@@ -5447,7 +5556,7 @@ dependencies = ["errno","libc","linux-raw-sys",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -5504,7 +5613,7 @@ dependencies = ["security-framework","security-framework-sys","webpki-root-certs",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -6013,7 +6122,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -6362,7 +6471,7 @@ dependencies = ["cfg-expr","heck 0.5.0","pkg-config",- "toml 0.8.2",+ "toml 0.8.23","version-compare",]@@ -6629,7 +6738,7 @@ dependencies = ["thiserror 2.0.18","tracing","url",- "windows-registry",+ "windows-registry 0.5.3","windows-result 0.3.4",]@@ -6979,7 +7088,7 @@ dependencies = ["serde_with","swift-rs","thiserror 2.0.18",- "toml 0.9.12+spec-1.1.0",+ "toml 1.1.2+spec-1.1.0","url","urlpattern 0.6.0","uuid",@@ -7019,7 +7128,7 @@ dependencies = ["getrandom 0.4.2","once_cell","rustix",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -7235,14 +7344,14 @@ dependencies = [[[package]]name = "toml"-version = "0.8.2"+version = "0.8.23"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"dependencies = ["serde","serde_spanned 0.6.9",- "toml_datetime 0.6.3",- "toml_edit 0.20.2",+ "toml_datetime 0.6.11",+ "toml_edit 0.22.27",][[package]]@@ -7277,9 +7386,9 @@ dependencies = [[[package]]name = "toml_datetime"-version = "0.6.3"+version = "0.6.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"dependencies = ["serde",]@@ -7309,7 +7418,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"dependencies = ["indexmap 2.14.0",- "toml_datetime 0.6.3",+ "toml_datetime 0.6.11","winnow 0.5.40",]@@ -7318,12 +7427,23 @@ name = "toml_edit"version = "0.20.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"+dependencies = [+ "indexmap 2.14.0",+ "toml_datetime 0.6.11",+ "winnow 0.5.40",+]++[[package]]+name = "toml_edit"+version = "0.22.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"dependencies = ["indexmap 2.14.0","serde","serde_spanned 0.6.9",- "toml_datetime 0.6.3",- "winnow 0.5.40",+ "toml_datetime 0.6.11",+ "winnow 0.7.15",][[package]]@@ -7490,7 +7610,7 @@ dependencies = ["png 0.18.1","serde","thiserror 2.0.18",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -7684,7 +7804,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"dependencies = ["memoffset","tempfile",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -7877,6 +7997,12 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+[[package]]+name = "utf8parse"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"+[[package]]name = "uuid"version = "1.23.1"@@ -8245,7 +8371,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -8523,6 +8649,17 @@ dependencies = ["windows-strings 0.4.2",]+[[package]]+name = "windows-registry"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"+dependencies = [+ "windows-link 0.2.1",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]+[[package]]name = "windows-result"version = "0.1.2"diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 5c7c82600c..8db8913dd4 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -68,8 +68,12 @@ tauri-plugin-os = "2"[target."cfg(any(target_os = \"macos\", windows, target_os = \"linux\"))".dependencies]+clap = { version = "4", features = ["derive"] }tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }+[target.'cfg(target_os = "macos")'.dependencies]+libc = "0.2"+[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]tauri-plugin-haptics = "2"diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.mdindex 6489434a2d..34fd454f5f 100644--- a/apps/web/tauri/src-tauri/README.md+++ b/apps/web/tauri/src-tauri/README.md@@ -132,3 +132,70 @@ extra routes, or mount native-only UI. Pair those checks with the`MaybeTauriProvider` from `@macro/tauri` to keep native-specific wiringlocalized while rendering everything through the shared `src` entrypoint.++## Desktop memory recording (macOS)++The frontend tags traces and logs with `app.runtime=tauri`, `app.platform`,+`service.instance.id` (a new UUID per native launch), `macro.native.pid`, and+`macro.native.version`. The shared `service.name=web-app` remains unchanged.+Browser sessions instead have `app.runtime=browser`.++Quit an existing Macro instance first, then launch the built **app bundle**:++```sh+open -a /absolute/path/to/macro.app --args --record-memory \+ --otel-traces-url https://macro-prox-prod.macroverse.workers.dev/i/otlp/v1/traces+```++For dev telemetry use `https://macro-prox-dev.macroverse.workers.dev/i/otlp/v1/traces`;+for a local collector use its full HTTP `/v1/traces` URL. The endpoint is required+and applies to this launch only; the corresponding `/v1/logs` endpoint is derived+from it. No collector credentials are embedded in the app. Selecting a telemetry+endpoint does not change which backend the frontend uses.++Recording explicitly enables the frontend OTel SDK regardless of the normal+PostHog/build-time enablement gate and uses an always-on sampler for emitted+frontend spans. This does not override sampling/drop policies in a downstream+collector or backend, or add traces to operations that have no instrumentation.+The title bar shows `Recording <short ID>`; the full `macro.recording.id` and+`service.instance.id` appear in the startup telemetry log. Quit to stop recording.+Launching again creates new IDs. A second launch while Macro is already running+is handled by the existing single-instance plugin and does **not** enable recording+in the running instance. Automatic bundle updates are disabled for a recording+launch so the measured frontend stays on the embedded build.++A native thread samples once per second, retaining at most one hour in memory.+The frontend drains the samples, emits timestamped `app.memory.sample` spans, and+attaches the latest reading to every frontend span at start and at end (the latter+attributes end in `.end`). Readings older than five seconds are tagged `stale` and+are not attached as current memory. Buffer overflow is reported in a telemetry+warning. Reloads reuse the native session; a per-webview sessionStorage cursor+avoids replaying samples already handed to the exporter. Export uses the existing+bounded, best-effort OTel batch transport; this is not a durable local recording,+and abrupt exit, export failures, or buffer overflow can lose telemetry.++Memory fields (bytes):++- `macro.memory.native.{rss_bytes,footprint_bytes}`: Rust host process.+- `macro.memory.web_content.{rss_bytes,footprint_bytes}`: frontend WebContent processes.+- `macro.memory.gpu.*` / `macro.memory.network.*`: attributed WebKit helpers.+- `macro.memory.frontend.footprint_bytes`: sum of measured WebKit helper footprints.+- `macro.memory.app.footprint_bytes`: native + frontend footprint sum, present only+ when the native host and WebContent were measured with no helper-read failures.+- `macro.memory.frontend.status`: `available`, `partial`, or `unavailable`.+- `macro.memory.timestamp_ms` / `sample_age_ms`: native sample time and its age.++These are process memory measurements, not JavaScript heap/allocation profiles.+RSS and macOS physical footprint have different accounting; sums are explicitly+process sums and need not equal Activity Monitor's app total.++macOS sampling uses `proc_pid_rusage`. WebKit helpers are XPC processes, so PPID+alone is insufficient. Attribution resolves the optional private libSystem SPI+`responsibility_get_pid_responsible_for_pid` at runtime and includes only known+WebKit helpers whose responsible PID is this app. If the SPI, permissions, or+attribution are unavailable, frontend coverage is explicitly unavailable. Never+sum every WebKit process on the machine. Launch through `open`/LaunchServices:+executing the binary directly from a terminal may attribute helpers to Terminal.+Memory recording is currently macOS-only; normal runtime identification works on+all Tauri platforms. The private attribution API is a compatibility consideration+for future App Store distribution.diff --git a/apps/web/tauri/src-tauri/src/diagnostics.rs b/apps/web/tauri/src-tauri/src/diagnostics.rsnew file mode 100644index 0000000000..296b832513--- /dev/null+++ b/apps/web/tauri/src-tauri/src/diagnostics.rs@@ -0,0 +1,191 @@+//! Launch-scoped desktop diagnostics. Sampling lives outside the webview so a+//! backgrounded or reloaded frontend cannot stop the memory timeline.++use std::collections::VecDeque;+use std::sync::Mutex;+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use serde::Serialize;+use tauri::Manager;+use uuid::Uuid;++#[cfg(desktop)]+mod launch;+#[cfg(target_os = "macos")]+mod macos;+#[cfg(test)]+mod test;++const SAMPLE_INTERVAL: Duration = Duration::from_secs(1);+// One hour of samples, bounded even if the webview stops consuming them.+const MAX_SAMPLES: usize = 3600;++#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Identity {+ instance_id: String,+ recording_id: Option<String>,+ traces_url: Option<String>,+ native_version: String,+ os: &'static str,+ host_pid: u32,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum ProcessRole {+ Native,+ WebContent,+ Gpu,+ Network,+}++#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ProcessMemory {+ pid: u32,+ role: ProcessRole,+ resident_bytes: u64,+ footprint_bytes: u64,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum FrontendStatus {+ Available,+ Partial,+ Unavailable,+}++#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MemorySample {+ sequence: u64,+ timestamp_ms: u64,+ processes: Vec<ProcessMemory>,+ frontend_status: FrontendStatus,+ error: Option<String>,+}++#[derive(Default)]+struct SampleBuffer {+ sequence: u64,+ samples: VecDeque<MemorySample>,+}++impl SampleBuffer {+ fn push(&mut self, mut sample: MemorySample) {+ self.sequence += 1;+ sample.sequence = self.sequence;+ self.samples.push_back(sample);+ if self.samples.len() > MAX_SAMPLES {+ self.samples.pop_front();+ }+ }++ fn read(&self, after_sequence: u64) -> (Vec<MemorySample>, u64) {+ let dropped = self.samples.front().map_or(0, |sample| {+ sample+ .sequence+ .saturating_sub(after_sequence.saturating_add(1))+ });+ let samples = self+ .samples+ .iter()+ .filter(|sample| sample.sequence > after_sequence)+ .cloned()+ .collect();+ (samples, dropped)+ }+}++pub struct Diagnostics {+ identity: Identity,+ buffer: Mutex<SampleBuffer>,+}++impl Diagnostics {+ pub fn from_launch() -> Self {+ #[cfg(desktop)]+ let (recording_id, traces_url) = launch::configuration();+ #[cfg(mobile)]+ let (recording_id, traces_url) = (None, None);+ Self {+ identity: Identity {+ instance_id: Uuid::new_v4().to_string(),+ recording_id,+ traces_url,+ native_version: String::new(),+ os: std::env::consts::OS,+ host_pid: std::process::id(),+ },+ buffer: Mutex::new(SampleBuffer::default()),+ }+ }++ pub fn is_recording(&self) -> bool {+ self.identity.recording_id.is_some()+ }+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Snapshot {+ identity: Identity,+ samples: Vec<MemorySample>,+ dropped_samples: u64,+}++#[tauri::command]+pub fn read_desktop_diagnostics(+ state: tauri::State<'_, Diagnostics>,+ after_sequence: Option<u64>,+) -> Result<Snapshot, String> {+ let buffer = state.buffer.lock().map_err(|e| e.to_string())?;+ let (samples, dropped_samples) = buffer.read(after_sequence.unwrap_or(0));+ Ok(Snapshot {+ identity: state.identity.clone(),+ samples,+ dropped_samples,+ })+}++pub fn setup<R: tauri::Runtime>(app: &tauri::App<R>, mut diagnostics: Diagnostics) {+ diagnostics.identity.native_version = app.package_info().version.to_string();+ let recording = diagnostics.is_recording();+ if let Some(id) = &diagnostics.identity.recording_id {+ tracing::info!(recording_id = %id, instance_id = %diagnostics.identity.instance_id,+ "Desktop memory recording started");+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.set_title(&format!("Macro — Recording {}", &id[..8]));+ }+ }+ app.manage(diagnostics);+ if !recording {+ return;+ }++ #[cfg(target_os = "macos")]+ {+ let handle = app.handle().clone();+ // Sampling uses blocking OS calls; keep it off both the UI and async threads.+ std::thread::spawn(move || {+ loop {+ let mut sample = macos::sample(std::process::id());+ sample.timestamp_ms = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64;+ let state = handle.state::<Diagnostics>();+ match state.buffer.lock() {+ Ok(mut buffer) => buffer.push(sample),+ Err(error) => {+ tracing::error!(?error, "Memory recording buffer unavailable");+ return;+ }+ }+ std::thread::sleep(SAMPLE_INTERVAL);+ }+ });+ }+}diff --git a/apps/web/tauri/src-tauri/src/diagnostics/launch.rs b/apps/web/tauri/src-tauri/src/diagnostics/launch.rsnew file mode 100644index 0000000000..9191169f9a--- /dev/null+++ b/apps/web/tauri/src-tauri/src/diagnostics/launch.rs@@ -0,0 +1,55 @@+use clap::Parser;+use url::Url;+use uuid::Uuid;++#[derive(Debug, Parser)]+#[command(name = "macro", about = "Macro desktop")]+struct LaunchOptions {+ /// Record app memory and all emitted frontend OTel spans until app exit.+ #[arg(long, requires = "otel_traces_url")]+ record_memory: bool,+ /// Full OTLP HTTP /v1/traces endpoint (no API key needed for the Macro proxy).+ #[arg(long, requires = "record_memory", value_parser = traces_url)]+ otel_traces_url: Option<Url>,+ /// URLs passed by the operating system's deep-link handler.+ urls: Vec<String>,+}++fn traces_url(value: &str) -> Result<Url, String> {+ let url = Url::parse(value).map_err(|e| e.to_string())?;+ if !matches!(url.scheme(), "http" | "https")+ || url.host_str().is_none()+ || !url.path().trim_end_matches('/').ends_with("/v1/traces")+ || !url.username().is_empty()+ || url.password().is_some()+ || url.query().is_some()+ || url.fragment().is_some()+ {+ return Err(+ "expected an http(s) URL ending in /v1/traces, without credentials, query or fragment"+ .into(),+ );+ }+ Ok(url)+}++pub(super) fn configuration() -> (Option<String>, Option<String>) {+ let options = LaunchOptions::parse();+ if options.record_memory && !cfg!(target_os = "macos") {+ use clap::{CommandFactory, error::ErrorKind};+ LaunchOptions::command()+ .error(+ ErrorKind::InvalidValue,+ "memory recording currently supports macOS only",+ )+ .exit();+ }+ (+ options.record_memory.then(|| Uuid::new_v4().to_string()),+ options.otel_traces_url.map(|url| url.to_string()),+ )+}++#[cfg(test)]+#[path = "launch_test.rs"]+mod test;diff --git a/apps/web/tauri/src-tauri/src/diagnostics/launch_test.rs b/apps/web/tauri/src-tauri/src/diagnostics/launch_test.rsnew file mode 100644index 0000000000..69c74e7b35--- /dev/null+++ b/apps/web/tauri/src-tauri/src/diagnostics/launch_test.rs@@ -0,0 +1,39 @@+use super::*;++#[test]+fn normal_and_deep_link_launches_do_not_record() {+ assert!(+ !LaunchOptions::try_parse_from(["macro"])+ .unwrap()+ .record_memory+ );+ let options = LaunchOptions::try_parse_from(["macro", "macro://app/channel/123"]).unwrap();+ assert!(!options.record_memory);+ assert_eq!(options.urls, ["macro://app/channel/123"]);+}++#[test]+fn recording_requires_an_explicit_valid_export_destination() {+ assert!(LaunchOptions::try_parse_from(["macro", "--record-memory"]).is_err());+ for url in [+ "file:///v1/traces",+ "https://user:[email protected]/v1/traces",+ "https://example.com/",+ "https://example.com/v1/traces?token=secret",+ ] {+ assert!(+ LaunchOptions::try_parse_from(["macro", "--record-memory", "--otel-traces-url", url])+ .is_err()+ );+ }+ assert!(+ LaunchOptions::try_parse_from([+ "macro",+ "--record-memory",+ "--otel-traces-url",+ "http://localhost:4318/v1/traces"+ ])+ .unwrap()+ .record_memory+ );+}diff --git a/apps/web/tauri/src-tauri/src/diagnostics/macos.rs b/apps/web/tauri/src-tauri/src/diagnostics/macos.rsnew file mode 100644index 0000000000..5c9871e31f--- /dev/null+++ b/apps/web/tauri/src-tauri/src/diagnostics/macos.rs@@ -0,0 +1,152 @@+//! macOS process memory. WebKit helpers are XPC services, not reliably children+//! of the app. Resolve their responsible app PID rather than matching all WebKit+//! processes or following PPIDs (which would include other apps / miss launchd).++use std::ffi::CStr;+use std::mem::{MaybeUninit, size_of};++use super::{FrontendStatus, MemorySample, ProcessMemory, ProcessRole};++type ResponsiblePid = unsafe extern "C" fn(libc::pid_t) -> libc::pid_t;++fn responsible_pid_api() -> Option<ResponsiblePid> {+ // This macOS SPI is optional, resolved at runtime. If it disappears, report+ // frontend coverage as unavailable; never replace it with process-name guesses.+ // Signature also used by chromium/base/process/process_info_mac.mm.+ let symbol = unsafe {+ libc::dlsym(+ libc::RTLD_DEFAULT,+ c"responsibility_get_pid_responsible_for_pid".as_ptr(),+ )+ };+ if symbol.is_null() {+ None+ } else {+ // SAFETY: the symbol has the C signature above and libSystem stays loaded.+ Some(unsafe { std::mem::transmute::<*mut libc::c_void, ResponsiblePid>(symbol) })+ }+}++fn memory(pid: u32, role: ProcessRole) -> std::io::Result<ProcessMemory> {+ let mut usage = MaybeUninit::<libc::rusage_info_v0>::zeroed();+ // SAFETY: libproc writes the v0 struct into this correctly sized/aligned buffer.+ let result = unsafe {+ libc::proc_pid_rusage(pid as i32, libc::RUSAGE_INFO_V0, usage.as_mut_ptr().cast())+ };+ if result != 0 {+ return Err(std::io::Error::last_os_error());+ }+ // SAFETY: a successful proc_pid_rusage initialized the buffer.+ let usage = unsafe { usage.assume_init() };+ Ok(ProcessMemory {+ pid,+ role,+ resident_bytes: usage.ri_resident_size,+ footprint_bytes: usage.ri_phys_footprint,+ })+}++fn process_ids() -> std::io::Result<Vec<i32>> {+ // SAFETY: null/0 asks libproc for the number of processes.+ let count = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) };+ if count <= 0 {+ return Err(std::io::Error::last_os_error());+ }+ let mut pids = vec![0i32; count as usize + 128];+ // SAFETY: the writable buffer contains the advertised number of bytes.+ let count = unsafe {+ libc::proc_listallpids(+ pids.as_mut_ptr().cast(),+ (pids.len() * size_of::<i32>()) as i32,+ )+ };+ if count <= 0 {+ return Err(std::io::Error::last_os_error());+ }+ if count as usize >= pids.len() {+ return Err(std::io::Error::other(+ "process list changed during sampling",+ ));+ }+ pids.truncate(count as usize);+ Ok(pids)+}++fn webkit_role(pid: i32) -> Option<ProcessRole> {+ let mut path = [0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];+ // SAFETY: path is a writable byte buffer of the specified length.+ let size = unsafe { libc::proc_pidpath(pid, path.as_mut_ptr().cast(), path.len() as u32) };+ if size <= 0 {+ return None;+ }+ let path = CStr::from_bytes_until_nul(&path).ok()?.to_str().ok()?;+ role_for_path(path)+}++pub(super) fn role_for_path(path: &str) -> Option<ProcessRole> {+ let name = path.rsplit('/').next()?;+ if name == "com.apple.WebKit.WebContent" || name.starts_with("com.apple.WebKit.WebContent.") {+ Some(ProcessRole::WebContent)+ } else if name == "com.apple.WebKit.GPU" {+ Some(ProcessRole::Gpu)+ } else if name == "com.apple.WebKit.Networking" {+ Some(ProcessRole::Network)+ } else {+ None+ }+}++pub(super) fn sample(host_pid: u32) -> MemorySample {+ let mut sample = MemorySample {+ sequence: 0,+ timestamp_ms: 0,+ processes: Vec::new(),+ frontend_status: FrontendStatus::Unavailable,+ error: None,+ };+ match memory(host_pid, ProcessRole::Native) {+ Ok(memory) => sample.processes.push(memory),+ Err(error) => sample.error = Some(format!("native memory: {error}")),+ }+ let Some(responsible_pid) = responsible_pid_api() else {+ sample.error = Some("macOS process attribution unavailable".into());+ return sample;+ };+ let pids = match process_ids() {+ Ok(pids) => pids,+ Err(error) => {+ sample.error = Some(format!("process enumeration: {error}"));+ return sample;+ }+ };+ let mut failed = false;+ for pid in pids {+ if pid <= 0 || pid as u32 == host_pid {+ continue;+ }+ let Some(role) = webkit_role(pid) else {+ continue;+ };+ // SAFETY: function pointer was resolved from libSystem with its C signature.+ if unsafe { responsible_pid(pid) } != host_pid as i32 {+ continue;+ }+ match memory(pid as u32, role) {+ Ok(memory) => sample.processes.push(memory),+ Err(_) => failed = true, // Helpers may exit during enumeration.+ }+ }+ let has_frontend = sample+ .processes+ .iter()+ .any(|p| p.role == ProcessRole::WebContent);+ sample.frontend_status = match (has_frontend, failed) {+ (true, false) => FrontendStatus::Available,+ (true, true) => FrontendStatus::Partial,+ (false, _) => FrontendStatus::Unavailable,+ };+ if !has_frontend && sample.error.is_none() {+ sample.error = Some("No attributable WebContent process; launch the .app with open, not the executable from a terminal".into());+ }+ sample+}diff --git a/apps/web/tauri/src-tauri/src/diagnostics/test.rs b/apps/web/tauri/src-tauri/src/diagnostics/test.rsnew file mode 100644index 0000000000..96655f68e2--- /dev/null+++ b/apps/web/tauri/src-tauri/src/diagnostics/test.rs@@ -0,0 +1,76 @@+use super::*;++fn sample() -> MemorySample {+ MemorySample {+ sequence: 0,+ timestamp_ms: 1,+ processes: vec![],+ frontend_status: FrontendStatus::Unavailable,+ error: None,+ }+}++#[test]+fn reads_resume_without_duplicates_and_report_evicted_samples() {+ let mut buffer = SampleBuffer::default();+ for _ in 0..MAX_SAMPLES + 2 {+ buffer.push(sample());+ }+ let (samples, dropped) = buffer.read(0);+ assert_eq!(samples.len(), MAX_SAMPLES);+ assert_eq!(dropped, 2);+ assert_eq!(samples.first().unwrap().sequence, 3);+ let (samples, dropped) = buffer.read(MAX_SAMPLES as u64 + 1);+ assert_eq!(samples.len(), 1);+ assert_eq!(dropped, 0);+ assert_eq!(samples[0].sequence, MAX_SAMPLES as u64 + 2);+ assert!(buffer.read(MAX_SAMPLES as u64 + 2).0.is_empty());+}++#[cfg(target_os = "macos")]+#[test]+fn only_known_webkit_executables_are_classified() {+ assert_eq!(+ macos::role_for_path("/System/Library/com.apple.WebKit.WebContent"),+ Some(ProcessRole::WebContent)+ );+ assert_eq!(+ macos::role_for_path("/System/Library/com.apple.WebKit.WebContent.CaptivePortal"),+ Some(ProcessRole::WebContent)+ );+ assert_eq!(+ macos::role_for_path("/System/Library/com.apple.WebKit.GPU"),+ Some(ProcessRole::Gpu)+ );+ assert_eq!(+ macos::role_for_path("/System/Library/com.apple.WebKit.Networking"),+ Some(ProcessRole::Network)+ );+ assert_eq!(+ macos::role_for_path("/tmp/not-com.apple.WebKit.WebContent"),+ None+ );+}++#[cfg(target_os = "macos")]+#[test]+fn sampler_reports_native_memory_or_an_explicit_error_without_fabricating_frontend_usage() {+ let sample = macos::sample(std::process::id());+ if let Some(native) = sample+ .processes+ .iter()+ .find(|p| p.role == ProcessRole::Native)+ {+ assert!(native.resident_bytes > 0);+ assert!(native.footprint_bytes > 0);+ } else {+ assert!(sample.error.is_some());+ }+ assert_eq!(sample.frontend_status, FrontendStatus::Unavailable);+ assert!(+ sample+ .processes+ .iter()+ .all(|p| p.role == ProcessRole::Native)+ );+}diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex bdd8d27e10..cad88d2b8c 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -34,6 +34,7 @@ use tracing_subscriber::util::SubscriberInitExt;use url::Url;mod device;+mod diagnostics;mod logging;mod share_target;mod staged_upload;@@ -118,6 +119,9 @@ type Type = std::sync::OnceLock<pub fn run() {use tracing_subscriber::EnvFilter;+ let diagnostics = diagnostics::Diagnostics::from_launch();+ let recording = diagnostics.is_recording();+let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| logging::default_filter(cfg!(debug_assertions)));@@ -217,7 +221,7 @@ pub fn run() {// Builds without this feature (just ios-dev, ios-build-no-update)// must never check for or apply OTA bundles on their own; manual// checks from settings still work.- .with_auto_update(cfg!(feature = "auto_apply_update")),+ .with_auto_update(cfg!(feature = "auto_apply_update") && !recording),);#[cfg(mobile)]@@ -258,6 +262,7 @@ pub fn run() {.manage(graphql_cache_plugin::CacheState::default()).manage(IsIpad(is_ipad_device)).invoke_handler(tauri::generate_handler![+ diagnostics::read_desktop_diagnostics,graphql_cache_plugin::commands::graphql_cache_init,graphql_cache_plugin::commands::graphql_cache_current_revision,graphql_cache_plugin::commands::graphql_cache_current_storage_generation,@@ -293,7 +298,8 @@ pub fn run() {flush_launch_deep_link,staged_upload::upload_staged_file_to_presigned_url,])- .setup(|app| {+ .setup(move |app| {+ diagnostics::setup(app, diagnostics);#[cfg(any(target_os = "linux", all(windows, debug_assertions)))]{use tauri_plugin_deep_link::DeepLinkExt;@@ -311,7 +317,7 @@ pub fn run() {.build(tauri::generate_context!()).expect("error while building tauri application").run(move |app_handle, event| match &event {- RunEvent::Ready => {+ RunEvent::Ready if !recording => {#[cfg(feature = "auto_apply_update")]{let app = app_handle.clone();diff --git a/docs/AGENT_GUIDE/observability.md b/docs/AGENT_GUIDE/observability.mdindex a2db542683..aaa05df4bf 100644--- a/docs/AGENT_GUIDE/observability.md+++ b/docs/AGENT_GUIDE/observability.md@@ -137,3 +137,37 @@ prompt passes them:| `action queued behind the turn in flight` | the managing replica | Why the prompt is waiting: the in-flight turn, its action id, and `in_flight_age_secs`. || `recovering a run started elsewhere` | the Cursor service | A mirror or a pre-prompt backfill is about to follow a cursor.com run; `cursor.run.still_running=true` means it will hold the turn gate until that run ends. `finished recovering …` closes it with `elapsed_ms`. || `waiting for the turn gate behind a mirror …` / `acquired the turn gate` / `stopped while waiting …` / `gave up waiting for the turn gate` | the Cursor service, inside `agent.turn` | The prompt is parked behind that mirror, and how the wait ended. |++## Tauri desktop memory recordings++The web frontend keeps `service.name=web-app`; distinguish native windows with+`resource.app.runtime = "tauri"` (`"browser"` for regular tabs). Tauri events carry+`service.instance.id`, a UUID for the native launch. Explicit macOS recordings add+`macro.recording.id`; this remains stable across webview reloads and is shared by+frontend traces, logs, and `app.memory.sample` spans.++Launch instructions and memory field definitions are in the+[Tauri recording guide](../../apps/web/tauri/src-tauri/README.md#desktop-memory-recording-macos).+Quit any existing instance before launching with the recording arguments.+The native title bar shows a shortened recording ID; find the full ID in the+`Desktop memory recording enabled` startup log or any recording span's resources.++TraceQL examples:++```traceql+{ resource.app.runtime = "tauri" && resource.macro.recording.id = "<recording UUID>" }+{ resource.macro.recording.id = "<recording UUID>" && name = "app.memory.sample" }+```++Each action span has its latest memory sample at start and end (`.end` suffix).+Use `macro.memory.web_content.footprint_bytes` for the frontend renderer and+`macro.memory.frontend.footprint_bytes` for the measured WebKit helpers together.+Check `macro.memory.frontend.status` and sample age before interpreting readings.+Missing/unavailable values are not zero. The Rust host is reported separately as+`macro.memory.native.*`. Sample spans retain native timestamps after a webview+pause; sessionStorage avoids duplicate draining on ordinary reloads.++Backend spans join through the existing `traceparent` trace ID; recording resource+attributes belong to the frontend, and are not automatically copied onto backend+services. Correlate complete traces by finding their frontend span. Always-on+client sampling does not override downstream sampling or prevent transport loss.diff --git a/packages/observability/src/config.ts b/packages/observability/src/config.tsindex d74e418644..70345a824a 100644--- a/packages/observability/src/config.ts+++ b/packages/observability/src/config.ts@@ -1,32 +1,38 @@import type {- ContextManager,- AttributeValue as OtelAttributeValue,-} from "@opentelemetry/api";-import type { TelemetryTracingProviderFactory } from "./provider";+ ContextManager,+ AttributeValue as OtelAttributeValue,+} from '@opentelemetry/api';+import type { TelemetryTracingProviderFactory } from './provider';export type Attribute = OtelAttributeValue;export type Attributes = Record<string, Attribute | undefined>;export type LogAttributes = Attributes;export interface TelemetryInitConfig {- serviceName: string;- environment: string;- tracesUrl?: string;- logsUrl?: string;- contextManager?: ContextManager;- tracingProvider?: TelemetryTracingProviderFactory;- enabled: () => Promise<boolean>;+ serviceName: string;+ environment: string;+ tracesUrl?: string;+ logsUrl?: string;+ contextManager?: ContextManager;+ tracingProvider?: TelemetryTracingProviderFactory;+ /** Stable identity shared by this runtime's traces and logs. */+ resourceAttributes?: Attributes;+ /** Snapshot of live diagnostics, read synchronously at span start/end. */+ spanAttributes?: () => Attributes;+ /** Explicit diagnostic recordings capture all emitted spans. */+ recording?: boolean;+ enabled: () => Promise<boolean>;}/** Mutable attributes applied to telemetry created after they change. */export class TelemetryRuntimeConfig {- #userId: string | undefined;+ #userId: string | undefined;- get userId(): string | undefined {- return this.#userId;- }+ get userId(): string | undefined {+ return this.#userId;+ }- setUser(userId: string | undefined): void {- this.#userId = userId;- }+ setUser(userId: string | undefined): void {+ this.#userId = userId;+ }}diff --git a/packages/observability/src/telemetry.ts b/packages/observability/src/telemetry.tsindex a37bfba41d..5790a51523 100644--- a/packages/observability/src/telemetry.ts+++ b/packages/observability/src/telemetry.ts@@ -1,122 +1,133 @@-import { resourceFromAttributes } from "@opentelemetry/resources";-import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";+import { resourceFromAttributes } from '@opentelemetry/resources';+import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';import {- type LogAttributes,- type TelemetryInitConfig,- TelemetryRuntimeConfig,-} from "./config";-import { ATTR_DEPLOYMENT_ENVIRONMENT, CONSOLE_PREFIX } from "./constants";-import { Logging } from "./logging";-import type { Span } from "./span";-import { Tracing } from "./tracing";+ type Attributes,+ type LogAttributes,+ type TelemetryInitConfig,+ TelemetryRuntimeConfig,+} from './config';+import { ATTR_DEPLOYMENT_ENVIRONMENT, CONSOLE_PREFIX } from './constants';+import { Logging } from './logging';+import type { Span } from './span';+import { Tracing } from './tracing';type SpanOperation<T> = (span: Span) => Promise<T>;export class Telemetry {- static readonly #tracing = new Tracing();- static readonly #logging = new Logging();- static #initialization: Promise<void> | undefined;-- private constructor() {}-- static readonly config = new TelemetryRuntimeConfig();-- /** Initialize providers once, after the optional async enablement decision. */- static init(config: TelemetryInitConfig): Promise<void> {- Telemetry.#initialization ??= Telemetry.#initialize(config);- return Telemetry.#initialization;- }-- static span<T>(name: string, operation: SpanOperation<T>): Promise<T>;- static span(name: string): Span;- static span<T>(- name: string,- operation?: SpanOperation<T>,- ): Span | Promise<T> {- return Telemetry.#runSpan(Telemetry.#tracing.span(name), operation);- }-- /**- * Start telemetry whose complete span tree is forbidden from receiving the- * runtime user-id enrichment. Use this for privacy-aggregated subsystem- * metrics whose schema does not permit identity.- */- static anonymousSpan<T>(- name: string,- operation: SpanOperation<T>,- ): Promise<T>;- static anonymousSpan(name: string): Span;- static anonymousSpan<T>(- name: string,- operation?: SpanOperation<T>,- ): Span | Promise<T> {- return Telemetry.#runSpan(- Telemetry.#tracing.anonymousSpan(name),- operation,- );- }-- /** Start an HTTP client span. Callers must end the returned span. */- static clientSpan(name: string): Span {- return Telemetry.#tracing.clientSpan(name);- }-- static debug(message: string, attributes?: LogAttributes): void {- Telemetry.#logging.debug(message, attributes);- }-- static info(message: string, attributes?: LogAttributes): void {- Telemetry.#logging.info(message, attributes);- }-- static warn(message: string, attributes?: LogAttributes): void {- Telemetry.#logging.warn(message, attributes);- }-- static error(error: unknown, attributes?: LogAttributes): void {- Telemetry.#logging.error(error, attributes);- }-- static async flush(): Promise<void> {- await Promise.all([Telemetry.#tracing.flush(), Telemetry.#logging.flush()]);- }-- static async shutdown(): Promise<void> {- await Promise.all([- Telemetry.#tracing.shutdown(),- Telemetry.#logging.shutdown(),- ]);- }-- static #runSpan<T>(- span: Span,- operation?: SpanOperation<T>,- ): Span | Promise<T> {- if (!operation) return span;-- return span.run(async () => {- try {- return await operation(span);- } finally {- span.end();- }- });- }-- static async #initialize(config: TelemetryInitConfig): Promise<void> {- try {- if (!(await config.enabled())) return;- } catch (error) {- console.warn(`${CONSOLE_PREFIX} Failed to resolve enablement`, error);- return;- }-- const resource = resourceFromAttributes({- [ATTR_SERVICE_NAME]: config.serviceName,- [ATTR_DEPLOYMENT_ENVIRONMENT]: config.environment,- });- const getUserId = () => Telemetry.config.userId;- Telemetry.#tracing.init(config, resource, getUserId);- Telemetry.#logging.init(config, resource, getUserId);- }+ static readonly #tracing = new Tracing();+ static readonly #logging = new Logging();+ static #initialization: Promise<void> | undefined;++ private constructor() {}++ static readonly config = new TelemetryRuntimeConfig();++ /** Initialize providers once, after the optional async enablement decision. */+ static init(config: TelemetryInitConfig): Promise<void> {+ Telemetry.#initialization ??= Telemetry.#initialize(config);+ return Telemetry.#initialization;+ }++ static span<T>(name: string, operation: SpanOperation<T>): Promise<T>;+ static span(name: string): Span;+ static span<T>(+ name: string,+ operation?: SpanOperation<T>+ ): Span | Promise<T> {+ return Telemetry.#runSpan(Telemetry.#tracing.span(name), operation);+ }++ /**+ * Start telemetry whose complete span tree is forbidden from receiving the+ * runtime user-id enrichment. Use this for privacy-aggregated subsystem+ * metrics whose schema does not permit identity.+ */+ static anonymousSpan<T>(+ name: string,+ operation: SpanOperation<T>+ ): Promise<T>;+ static anonymousSpan(name: string): Span;+ static anonymousSpan<T>(+ name: string,+ operation?: SpanOperation<T>+ ): Span | Promise<T> {+ return Telemetry.#runSpan(+ Telemetry.#tracing.anonymousSpan(name),+ operation+ );+ }++ /** Start an HTTP client span. Callers must end the returned span. */+ static clientSpan(name: string): Span {+ return Telemetry.#tracing.clientSpan(name);+ }++ /** Record a point-in-time sample; timestamp is Unix time in milliseconds. */+ static recordSample(+ name: string,+ attributes: Attributes,+ timestamp: number+ ): void {+ Telemetry.#tracing.recordSample(name, attributes, timestamp);+ }++ static debug(message: string, attributes?: LogAttributes): void {+ Telemetry.#logging.debug(message, attributes);+ }++ static info(message: string, attributes?: LogAttributes): void {+ Telemetry.#logging.info(message, attributes);+ }++ static warn(message: string, attributes?: LogAttributes): void {+ Telemetry.#logging.warn(message, attributes);+ }++ static error(error: unknown, attributes?: LogAttributes): void {+ Telemetry.#logging.error(error, attributes);+ }++ static async flush(): Promise<void> {+ await Promise.all([Telemetry.#tracing.flush(), Telemetry.#logging.flush()]);+ }++ static async shutdown(): Promise<void> {+ await Promise.all([+ Telemetry.#tracing.shutdown(),+ Telemetry.#logging.shutdown(),+ ]);+ }++ static #runSpan<T>(+ span: Span,+ operation?: SpanOperation<T>+ ): Span | Promise<T> {+ if (!operation) return span;++ return span.run(async () => {+ try {+ return await operation(span);+ } finally {+ span.end();+ }+ });+ }++ static async #initialize(config: TelemetryInitConfig): Promise<void> {+ try {+ if (!(await config.enabled())) return;+ } catch (error) {+ console.warn(`${CONSOLE_PREFIX} Failed to resolve enablement`, error);+ return;+ }++ const resource = resourceFromAttributes({+ ...config.resourceAttributes,+ [ATTR_SERVICE_NAME]: config.serviceName,+ [ATTR_DEPLOYMENT_ENVIRONMENT]: config.environment,+ });+ const getUserId = () => Telemetry.config.userId;+ Telemetry.#tracing.init(config, resource, getUserId);+ Telemetry.#logging.init(config, resource, getUserId);+ }}diff --git a/packages/observability/src/tracing.ts b/packages/observability/src/tracing.tsindex 47b3108658..eeb3510a24 100644--- a/packages/observability/src/tracing.ts+++ b/packages/observability/src/tracing.ts@@ -1,58 +1,68 @@import {- type Context,- context,- ROOT_CONTEXT,- SpanKind,- trace,-} from "@opentelemetry/api";-import type { Resource } from "@opentelemetry/resources";-import type { TelemetryInitConfig } from "./config";-import { INSTRUMENTATION_SCOPE_NAME } from "./constants";-import { suppressUserId } from "./privacy";-import type { TelemetryTracingProvider } from "./provider";-import { type Span, SpanImpl } from "./span";+ type Context,+ context,+ ROOT_CONTEXT,+ SpanKind,+ trace,+} from '@opentelemetry/api';+import type { Resource } from '@opentelemetry/resources';+import type { Attributes, TelemetryInitConfig } from './config';+import { INSTRUMENTATION_SCOPE_NAME } from './constants';+import { suppressUserId } from './privacy';+import type { TelemetryTracingProvider } from './provider';+import { type Span, SpanImpl } from './span';export class Tracing {- #provider: TelemetryTracingProvider | undefined;-- init(- config: TelemetryInitConfig,- resource: Resource,- getUserId: () => string | undefined,- ): void {- this.#provider = config.tracingProvider?.(resource, getUserId);- }-- span(name: string): Span {- return this.#startSpan(name, context.active());- }-- /** Starts a detached root span tree with user enrichment suppressed. */- anonymousSpan(name: string): Span {- return this.#startSpan(name, suppressUserId(ROOT_CONTEXT));- }-- clientSpan(name: string): Span {- return this.#startSpan(name, context.active(), SpanKind.CLIENT);- }-- async flush(): Promise<void> {- await this.#provider?.forceFlush();- }-- async shutdown(): Promise<void> {- await this.#provider?.shutdown();- this.#provider = undefined;- }-- #startSpan(name: string, parent: Context, kind?: SpanKind): Span {- const otelSpan = trace- .getTracer(INSTRUMENTATION_SCOPE_NAME)- .startSpan(name, kind === undefined ? undefined : { kind }, parent);- return new SpanImpl(- otelSpan,- trace.setSpan(parent, otelSpan),- (childName, childParent) => this.#startSpan(childName, childParent),- );- }+ #provider: TelemetryTracingProvider | undefined;++ init(+ config: TelemetryInitConfig,+ resource: Resource,+ getUserId: () => string | undefined+ ): void {+ this.#provider = config.tracingProvider?.(resource, getUserId);+ }++ span(name: string): Span {+ return this.#startSpan(name, context.active());+ }++ /** Starts a detached root span tree with user enrichment suppressed. */+ anonymousSpan(name: string): Span {+ return this.#startSpan(name, suppressUserId(ROOT_CONTEXT));+ }++ clientSpan(name: string): Span {+ return this.#startSpan(name, context.active(), SpanKind.CLIENT);+ }++ /** Export a timestamped measurement without retaining a long-lived span. */+ recordSample(name: string, attributes: Attributes, timestamp: number): void {+ const span = trace+ .getTracer(INSTRUMENTATION_SCOPE_NAME)+ .startSpan(name, { startTime: timestamp, attributes }, ROOT_CONTEXT);+ // Historical samples must win over live onStart enrichment.+ span.setAttributes(attributes);+ span.end(timestamp);+ }++ async flush(): Promise<void> {+ await this.#provider?.forceFlush();+ }++ async shutdown(): Promise<void> {+ await this.#provider?.shutdown();+ this.#provider = undefined;+ }++ #startSpan(name: string, parent: Context, kind?: SpanKind): Span {+ const otelSpan = trace+ .getTracer(INSTRUMENTATION_SCOPE_NAME)+ .startSpan(name, kind === undefined ? undefined : { kind }, parent);+ return new SpanImpl(+ otelSpan,+ trace.setSpan(parent, otelSpan),+ (childName, childParent) => this.#startSpan(childName, childParent)+ );+ }}diff --git a/packages/observability/src/web.test.ts b/packages/observability/src/web.test.tsnew file mode 100644index 0000000000..4b1179f1a0--- /dev/null+++ b/packages/observability/src/web.test.ts@@ -0,0 +1,102 @@+import {+ context,+ propagation,+ ROOT_CONTEXT,+ TraceFlags,+ trace,+} from '@opentelemetry/api';+import { resourceFromAttributes } from '@opentelemetry/resources';+import type { InMemorySpanExporter } from '@opentelemetry/sdk-trace-base';+import { afterEach, expect, test, vi } from 'vitest';+import { Tracing } from './tracing';+import { createWebTracingProvider } from './web';++const exporters: InMemorySpanExporter[] = [];+vi.mock('@opentelemetry/exporter-trace-otlp-http', async () => {+ const { InMemorySpanExporter } = await import(+ '@opentelemetry/sdk-trace-base'+ );+ return {+ OTLPTraceExporter: class extends InMemorySpanExporter {+ constructor() {+ super();+ exporters.push(this);+ }+ },+ };+});++afterEach(() => {+ trace.disable();+ context.disable();+ propagation.disable();+});++test('recording exports even unsampled-parent spans with launch identity and memory at both boundaries', async () => {+ let memory = 100;+ const provider = createWebTracingProvider(+ {+ serviceName: 'web-app',+ environment: 'test',+ enabled: async () => true,+ tracesUrl: 'http://localhost/v1/traces',+ recording: true,+ spanAttributes: () => ({ 'macro.memory.native.rss_bytes': memory }),+ },+ resourceFromAttributes({+ 'app.runtime': 'tauri',+ 'service.instance.id': 'launch-1',+ 'macro.recording.id': 'recording-1',+ }),+ () => 'user-1'+ );+ const parent = trace.setSpanContext(ROOT_CONTEXT, {+ traceId: '11111111111111111111111111111111',+ spanId: '2222222222222222',+ traceFlags: TraceFlags.NONE,+ isRemote: true,+ });+ const span = provider+ .getTracer('test')+ .startSpan('open.document', {}, parent);+ memory = 200;+ span.end();+ await provider.forceFlush();+ const exported = exporters.at(-1)?.getFinishedSpans()[0];+ expect(exported?.resource.attributes).toMatchObject({+ 'app.runtime': 'tauri',+ 'service.instance.id': 'launch-1',+ 'macro.recording.id': 'recording-1',+ });+ expect(exported?.attributes).toMatchObject({+ 'usr.id': 'user-1',+ 'macro.memory.native.rss_bytes': 100,+ 'macro.memory.native.rss_bytes.end': 200,+ });+ await provider.shutdown();+});++test('buffered samples retain their native timestamp and values despite live enrichment', async () => {+ const provider = createWebTracingProvider(+ {+ serviceName: 'web-app',+ environment: 'test',+ enabled: async () => true,+ tracesUrl: 'http://localhost/v1/traces',+ spanAttributes: () => ({ 'macro.memory.native.rss_bytes': 999 }),+ },+ resourceFromAttributes({}),+ () => undefined+ );+ new Tracing().recordSample(+ 'app.memory.sample',+ { 'macro.memory.native.rss_bytes': 123 },+ 1_700_000_000_125+ );+ await provider.forceFlush();+ const sample = exporters.at(-1)?.getFinishedSpans()[0];+ expect(sample?.startTime).toEqual([1_700_000_000, 125_000_000]);+ expect(sample?.endTime).toEqual(sample?.startTime);+ expect(sample?.attributes['macro.memory.native.rss_bytes']).toBe(123);+ await provider.shutdown();+});diff --git a/packages/observability/src/web.ts b/packages/observability/src/web.tsindex e85a8a79cf..82d631c99f 100644--- a/packages/observability/src/web.ts+++ b/packages/observability/src/web.ts@@ -1,44 +1,57 @@-import { W3CTraceContextPropagator } from "@opentelemetry/core";-import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";-import type { Resource } from "@opentelemetry/resources";-import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";-import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";-import type { TelemetryInitConfig } from "./config";-import { ATTR_USER_ID } from "./constants";-import { userIdSuppressed } from "./privacy";-import type { TelemetryTracingProvider } from "./provider";+import { W3CTraceContextPropagator } from '@opentelemetry/core';+import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';+import type { Resource } from '@opentelemetry/resources';+import {+ AlwaysOnSampler,+ BatchSpanProcessor,+} from '@opentelemetry/sdk-trace-base';+import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';+import type { TelemetryInitConfig } from './config';+import { ATTR_USER_ID } from './constants';+import { userIdSuppressed } from './privacy';+import type { TelemetryTracingProvider } from './provider';/** Creates the browser OpenTelemetry provider used by the web application. */export function createWebTracingProvider(- config: TelemetryInitConfig,- resource: Resource,- getUserId: () => string | undefined,+ config: TelemetryInitConfig,+ resource: Resource,+ getUserId: () => string | undefined): TelemetryTracingProvider {- const provider = new WebTracerProvider({- resource,- spanProcessors: [- {- onStart: (span, parentContext) => {- if (userIdSuppressed(parentContext)) return;- const userId = getUserId();- if (userId !== undefined) span.setAttribute(ATTR_USER_ID, userId);- },- onEnd: () => {},- forceFlush: () => Promise.resolve(),- shutdown: () => Promise.resolve(),- },- ...(config.tracesUrl- ? [- new BatchSpanProcessor(- new OTLPTraceExporter({ url: config.tracesUrl }),- ),- ]- : []),- ],- });- provider.register({- ...(config.contextManager && { contextManager: config.contextManager }),- propagator: new W3CTraceContextPropagator(),- });- return provider;+ const provider = new WebTracerProvider({+ resource,+ ...(config.recording && { sampler: new AlwaysOnSampler() }),+ spanProcessors: [+ {+ onStart: (span, parentContext) => {+ span.setAttributes(config.spanAttributes?.() ?? {});+ if (userIdSuppressed(parentContext)) return;+ const userId = getUserId();+ if (userId !== undefined) span.setAttribute(ATTR_USER_ID, userId);+ },+ onEnding: (span) => {+ const attributes = config.spanAttributes?.() ?? {};+ for (const [key, value] of Object.entries(attributes)) {+ if (value !== undefined) span.setAttribute(`${key}.end`, value);+ }+ },+ onEnd: () => {},+ forceFlush: () => Promise.resolve(),+ shutdown: () => Promise.resolve(),+ },+ ...(config.tracesUrl+ ? [+ new BatchSpanProcessor(+ new OTLPTraceExporter({ url: config.tracesUrl }),+ // The native recorder can replay up to 3600 samples after a pause.+ config.recording ? { maxQueueSize: 8192 } : undefined+ ),+ ]+ : []),+ ],+ });+ provider.register({+ ...(config.contextManager && { contextManager: config.contextManager }),+ propagator: new W3CTraceContextPropagator(),+ });+ return provider;}