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(observability): retain native reload diagnostics (#8434)
Peter Chinmana0f0fc2e7093
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex f1981554c3..ccd939e8df 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -131,7 +131,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.- Keep desktop model and effort controls separate: the model selector opens the catalog and the speedometer opens the runtime's advertised slider stops; retain the mobile effort sheet.- Passive PR mentions must not retry initial GitHub status failures on remount; preserve confirmed status through refetch errors and keep pending data reads out of their parent Suspense boundary.- Keep native booking exit navigation in the route shell, outside page loading boundaries, and use the router so the native hash route stays intact.-- Diagnose native full reloads with `native_webview_started` and native launch/termination/update counters; termination coverage is iOS/macOS only, and a pageview alone also includes SPA navigation. See `tauri/src-tauri/README.md`.+- Diagnose native full reloads with `native_webview_started`, `native_diagnostic_recovered`, and the shared `frontend_instance_id`; use `reloadApp(reason)` for frontend reloads and keep breadcrumbs content-free. See `tauri/src-tauri/README.md`.- Inline agent steps reuse the session code-execution query for live SDK operationnames; completed step snapshots come from the shared fold of the tool receipt.- All API/network calls live in service-clients.diff --git a/apps/web/biome.jsonc b/apps/web/biome.jsoncindex 6c0e8c1cff..086f6e4bbe 100644--- a/apps/web/biome.jsonc+++ b/apps/web/biome.jsonc@@ -19,6 +19,8 @@"src/lib/service-clients/**/generated/**",// graphql-codegen output; regenerated wholesale by `bun gen-graphql`"!src/lib/service-clients/service-storage/graphql/generated",+ // Specta output; native diagnostic_wire_types tests check exact drift.+ "!src/observability/generated","!src/lib/filesystem","!packages/_app-mobile","**/generated/tools",diff --git a/apps/web/docs/ios-releases.md b/apps/web/docs/ios-releases.mdindex eae22a8841..e799d18360 100644--- a/apps/web/docs/ios-releases.md+++ b/apps/web/docs/ios-releases.md@@ -1,5 +1,10 @@# iOS releases and breaking Tauri changes+Native reload history and UIKit memory-warning diagnostics require an App Store+binary update. Their IPC is optional: OTA-only clients retain frontend reload+markers and instance IDs, with missing native coverage explicitly reported.+See [reload diagnostics](../tauri/src-tauri/README.md#diagnosing-unexpected-webview-reloads).+(The Android counterpart — `android-update`, `Android Native Check`, GooglePlay as the source of truth — is described in `docs/development/android.md`.)diff --git a/apps/web/src/features/block-ai/ai-block.tsx b/apps/web/src/features/block-ai/ai-block.tsxindex d5b5a9cf20..52bef9f70f 100644--- a/apps/web/src/features/block-ai/ai-block.tsx+++ b/apps/web/src/features/block-ai/ai-block.tsx@@ -1,3 +1,4 @@+import { reloadApp } from '@app/observability/reload';/*** The `.ai` block: app chrome (header, file menu, sharing) around the* Illustrator editor, wired to the worker engine, document storage, and@@ -110,7 +111,7 @@ function AiHost(props: {message:'This file was replaced by a newer version (an upload or an AI edit). Reload to edit the latest version.',action: 'Reload',- onAction: () => window.location.reload(),+ onAction: () => reloadApp('user_recovery'),}: props.notice;onMount(() => {diff --git a/apps/web/src/features/block-fig/fig-block.tsx b/apps/web/src/features/block-fig/fig-block.tsxindex f496157412..da3c4f2c6f 100644--- a/apps/web/src/features/block-fig/fig-block.tsx+++ b/apps/web/src/features/block-fig/fig-block.tsx@@ -1,3 +1,4 @@+import { reloadApp } from '@app/observability/reload';/*** The `.fig` block: app chrome (header, file menu, sharing) around the* viewer, wired to the worker engine and document storage.@@ -131,7 +132,7 @@ function FigHost(props: {message:'This design was replaced by a newer file (an upload or an AI edit). Reload to edit the latest version.',action: 'Reload',- onAction: () => window.location.reload(),+ onAction: () => reloadApp('user_recovery'),}: props.notice;onMount(() => {diff --git a/apps/web/src/features/block-psd/psd-block.tsx b/apps/web/src/features/block-psd/psd-block.tsxindex 929c2147bf..3baa0677ba 100644--- a/apps/web/src/features/block-psd/psd-block.tsx+++ b/apps/web/src/features/block-psd/psd-block.tsx@@ -1,3 +1,4 @@+import { reloadApp } from '@app/observability/reload';/*** The Photoshop block: app chrome (header, file menu, sharing) around the* editor, wired to the worker engine, live collaboration, and document@@ -114,7 +115,7 @@ function PsdHost(props: {message:'This document was replaced by a newer file (an upload or an AI edit). Reload to edit the latest version.',action: 'Reload',- onAction: () => window.location.reload(),+ onAction: () => reloadApp('user_recovery'),}: props.notice;onMount(() => {diff --git a/apps/web/src/lib/analytics/analytics.test.ts b/apps/web/src/lib/analytics/analytics.test.tsindex 4d9cb1cf4c..d66f8901fe 100644--- a/apps/web/src/lib/analytics/analytics.test.ts+++ b/apps/web/src/lib/analytics/analytics.test.ts@@ -142,6 +142,23 @@ describe('Meta pixel platform support', () => {});describe('PostHog exception frames', () => {+ it('overwrites persisted document identity on automatic events, including after reset', async () => {+ vi.stubEnv('VITE_POSTHOG_API_KEY', 'test-key');+ const { analytics } = await import('./analytics');+ const { frontendInstanceId } = await import(+ '@app/observability/frontend-instance'+ );+ const beforeSend = mocks.init.mock.calls[0][1].before_send;+ for (const event of ['$pageview', '$exception']) {+ analytics.reset();+ expect(+ beforeSend({+ event,+ properties: { frontend_instance_id: 'old-document' },+ }).properties.frontend_instance_id+ ).toBe(frontendInstanceId);+ }+ });async function beforeSendException(value: string, filenames: string[]) {vi.stubEnv('VITE_POSTHOG_API_KEY', 'test-key');await import('./analytics');diff --git a/apps/web/src/lib/analytics/analytics.ts b/apps/web/src/lib/analytics/analytics.tsindex 79bb1f344f..6fe54878fa 100644--- a/apps/web/src/lib/analytics/analytics.ts+++ b/apps/web/src/lib/analytics/analytics.ts@@ -7,6 +7,7 @@ import {initializeGoogleAnalytics,initializeMetaPixel,} from '@app/lib/analytics/providers';+import { frontendInstanceId } from '@app/observability/frontend-instance';import { DEV_MODE_ENV, PROD_MODE_ENV } from '@core/constant/featureFlags';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { getPlatform, isTauri } from '@core/util/platform';@@ -150,6 +151,7 @@ const initializePosthog = (instance: PostHog) => {if (isPrivateCallPage()) return null;if (cr) {cr.properties = redactLinkTokenProperties(cr.properties);+ cr.properties.frontend_instance_id = frontendInstanceId;if (cr.$set) cr.$set = redactLinkTokenProperties(cr.$set);if (cr.$set_once) {cr.$set_once = redactLinkTokenProperties(cr.$set_once);diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.tsindex 39e5173b39..b53f544c52 100644--- a/apps/web/src/lib/core/auth/logout.ts+++ b/apps/web/src/lib/core/auth/logout.ts@@ -1,5 +1,7 @@import { clearMcpAuthAttempts } from '@app/features/settings/mcp-auth-attempt';import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { clearNativeDiagnostics } from '@app/observability/native-diagnostics';+import { reloadApp } from '@app/observability/reload';import { SERVER_HOSTS } from '@core/constant/servers';import { clearPipedreamCallbacks } from '@core/pipedream/connect-callback';import { syncLoginStorage } from '@core/util/cookies';@@ -46,6 +48,7 @@ const unauthenticatedUserInfo: UserInfoData = {};export async function clearLocalAuthSession() {+ await clearNativeDiagnostics();clearPipedreamCallbacks();document.cookie ='login=false; expires=Thu, 01 Jan 1970 00:00:00 UTC; max-age=0; path=/; SameSite=Lax';@@ -137,7 +140,7 @@ export function useLogout() {navigate('/login');// Native login reuses this WebView. End the document lifetime so queued// editor callbacks can never adopt the next account's draft session.- window.location.reload();+ reloadApp('logout');} else {window.location.href = SERVER_HOSTS['auth-logout'];}diff --git a/apps/web/src/lib/core/util/reloadForNewerBuild.ts b/apps/web/src/lib/core/util/reloadForNewerBuild.tsindex c867998c5e..937b51016b 100644--- a/apps/web/src/lib/core/util/reloadForNewerBuild.ts+++ b/apps/web/src/lib/core/util/reloadForNewerBuild.ts@@ -1,3 +1,5 @@+import type { ReloadReason } from '@app/observability/generated/native-diagnostics';+import { reloadApp } from '@app/observability/reload';import { toast } from '@core/component/Toast/Toast';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { createSignal } from 'solid-js';@@ -10,7 +12,7 @@ export interface ReloadPage {isOffline(): boolean;/** Whether focus is in a text field that holds text a reload would lose. */isEditingText(): boolean;- reload(): void;+ reload(reason: ReloadReason): void;/** Runs `callback` each time the page is hidden or comes back online. */onHiddenOrOnline(callback: () => void): void;/** Offers the user a reload now; `build` is the newer build, when known. */@@ -44,7 +46,7 @@ const browserPage: ReloadPage = {: focused?.textContent;return Boolean(text?.trim());},- reload: () => window.location.reload(),+ reload: reloadApp,onHiddenOrOnline(callback) {// Run a task later: a page being unloaded also turns hidden, and its// timers never run, so leaving the app never becomes a reload.@@ -110,11 +112,11 @@ export function reloadForNewerBuild(holds.size === 0 &&!page.isEditingText()) {- page.reload();+ page.reload('cache_replaced_automatic');}};page.onHiddenOrOnline(reloadIfIdle);- page.promptReload(() => page.reload(), build);+ page.promptReload(() => page.reload('update_accepted'), build);reloadIfIdle();}@@ -128,7 +130,7 @@ export function promptReloadForFailedLoad(): void {reloadForNewerBuild();const current = pendingWebUpdate();setPendingWebUpdate({- reload: current?.reload ?? (() => window.location.reload()),+ reload: () => reloadApp('failed_load_recovery'),build: current?.build,failedLoads: (current?.failedLoads ?? 0) + 1,});diff --git a/apps/web/src/observability/browser.test.ts b/apps/web/src/observability/browser.test.tsindex c6e33dc028..7913365e98 100644--- a/apps/web/src/observability/browser.test.ts+++ b/apps/web/src/observability/browser.test.ts@@ -2,6 +2,7 @@ import { Telemetry } from '@macro-inc/observability';import { beforeEach, expect, it, vi } from 'vitest';import { initializeBrowserObservability } from './browser';import { readDesktopDiagnostics } from './desktop';+import { frontendInstanceId } from './frontend-instance';import { initializeUiOperationTelemetry } from './ui-operation';const startupSpan = vi.hoisted(() => ({@@ -78,9 +79,14 @@ it('explicit native recording overrides the normal enablement gate and exporterexpect(config.logsUrl).toBe('http://localhost:4318/v1/logs');expect(config.resourceAttributes).toMatchObject({'app.runtime': 'tauri',+ frontend_instance_id: frontendInstanceId,'service.instance.id': 'launch-1','macro.recording.id': 'recording-1',});+ expect(config.spanAttributes?.()).toMatchObject({+ frontend_instance_id: frontendInstanceId,+ native_instance_id: 'launch-1',+ });expect(Telemetry.span).toHaveBeenCalledWith('native.webview.start');expect(startupSpan.setAttr).toHaveBeenCalledWith('native_instance_id',diff --git a/apps/web/src/observability/browser.ts b/apps/web/src/observability/browser.tsindex 4ad0ff4fef..42e5157253 100644--- a/apps/web/src/observability/browser.ts+++ b/apps/web/src/observability/browser.ts@@ -11,6 +11,8 @@ import {desktopResourceAttributes,readDesktopDiagnostics,} from './desktop';+import { frontendInstanceId } from './frontend-instance';+import { startNativeDiagnostics } from './native-diagnostics';import { recordNativeWebviewStart } from './native-lifecycle';import { initializeUiOperationTelemetry } from './ui-operation';@@ -56,6 +58,8 @@ async function browserTelemetryEnabled(hasExporter: boolean): Promise<boolean> {export async function initializeBrowserObservability(): Promise<void> {let browserEnabled = false;const desktop = await readDesktopDiagnostics();+ const disposeNativeDiagnostics = startNativeDiagnostics(desktop);+ import.meta.hot?.dispose(disposeNativeDiagnostics);const recording = desktop?.identity.recordingId? createDesktopMemoryRecording(desktop): undefined;@@ -77,12 +81,17 @@ export async function initializeBrowserObservability(): Promise<void> {contextManager: new ZoneContextManager(),resourceAttributes: {'service.version': import.meta.env.__APP_VERSION__,+ frontend_instance_id: frontendInstanceId,'app.runtime': isTauri() ? 'tauri' : 'browser','app.platform': getPlatform(),...(desktop && desktopResourceAttributes(desktop)),},recording: Boolean(recording),- spanAttributes: recording?.attributes,+ spanAttributes: () => ({+ ...recording?.attributes(),+ frontend_instance_id: frontendInstanceId,+ native_instance_id: desktop?.identity.instanceId,+ }),enabled: async () => {browserEnabled = recording? truediff --git a/apps/web/src/observability/desktop.ts b/apps/web/src/observability/desktop.tsindex fdfef859b7..7cbd2293c7 100644--- a/apps/web/src/observability/desktop.ts+++ b/apps/web/src/observability/desktop.ts@@ -2,6 +2,8 @@ import { fireAndForget } from '@core/util/fireAndForget';import { getPlatform, isTauri } from '@core/util/platform';import { type Attributes, Telemetry } from '@macro-inc/observability';import { invoke } from '@tauri-apps/api/core';+import type { BundleReloadDiagnostics } from './generated/bundle-reloads';+import type { EventSnapshot } from './generated/native-diagnostics';export type ProcessMemory = {pid: number;@@ -34,10 +36,12 @@ export type DesktopSnapshot = {terminations: number;lastTerminationMs: number | null;};- bundleReloads?: {- dispatches: number;- lastSource: string | null;- } | null;+ bundleReloads?:+ | (Pick<BundleReloadDiagnostics, 'dispatches' | 'lastSource'> &+ Partial<BundleReloadDiagnostics>)+ | null;+ /** Absent on older native binaries; also gates the diagnostic write command. */+ recentEvents?: EventSnapshot;};type SampleSink = {@@ -94,6 +98,7 @@ export function desktopResourceAttributes('app.runtime': 'tauri','app.platform': getPlatform(),'service.instance.id': snapshot.identity.instanceId,+ native_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,diff --git a/apps/web/src/observability/frontend-instance.ts b/apps/web/src/observability/frontend-instance.tsnew file mode 100644index 0000000000..df1c54f72b--- /dev/null+++ b/apps/web/src/observability/frontend-instance.ts@@ -0,0 +1,2 @@+/** One identity per document, shared by automatic analytics and OTLP signals. */+export const frontendInstanceId = crypto.randomUUID();diff --git a/apps/web/src/observability/generated/bundle-reloads.ts b/apps/web/src/observability/generated/bundle-reloads.tsnew file mode 100644index 0000000000..1850a752e7--- /dev/null+++ b/apps/web/src/observability/generated/bundle-reloads.ts@@ -0,0 +1,8 @@+// This file has been generated by Specta. Do not edit this file manually.+/** Launch-scoped reload dispatches, retained across replacement documents. */+export type BundleReloadDiagnostics = {+ dispatches: number,+ lastSource: string | null,+ lastReloadId: string | null,+ lastDispatchMs: number | null,+};diff --git a/apps/web/src/observability/generated/native-diagnostics.ts b/apps/web/src/observability/generated/native-diagnostics.tsnew file mode 100644index 0000000000..911cffdee1--- /dev/null+++ b/apps/web/src/observability/generated/native-diagnostics.ts@@ -0,0 +1,26 @@+// This file has been generated by Specta. Do not edit this file manually.+export type DiagnosticEvent = {+ sequence: number,+ timestampMs: number,+ frontendInstanceId: string | null,+ event: Event,+};++export type Event = FrontendEvent | NativeEvent;++export type EventSnapshot = {+ events: DiagnosticEvent[],+ currentFrontendInstanceId: string | null,+ heartbeat: DiagnosticEvent | null,+ dropped: number,+ memoryWarningReporting: boolean,+};++/** Closed schema: never accept arbitrary text, URLs, or message content. */+export type FrontendEvent = { kind: "started"; previous_instance_id: string | null } | { kind: "heartbeat"; visible: boolean; online: boolean } | { kind: "visibility"; visible: boolean } | { kind: "connectivity"; online: boolean } | { kind: "reload_requested"; reload_id: string; reason: ReloadReason } |+/** Clears identifiers before another account can take over the WebView. */+{ kind: "account_cleared" };++export type NativeEvent = { kind: "foreground" } | { kind: "background" } | { kind: "memory_warning" } | { kind: "web_content_terminated" };++export type ReloadReason = "cache_replaced_automatic" | "update_accepted" | "failed_load_recovery" | "user_recovery" | "logout";diff --git a/apps/web/src/observability/native-diagnostics.test.ts b/apps/web/src/observability/native-diagnostics.test.tsnew file mode 100644index 0000000000..cfa6a457da--- /dev/null+++ b/apps/web/src/observability/native-diagnostics.test.ts@@ -0,0 +1,184 @@+import { invoke } from '@tauri-apps/api/core';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { DesktopSnapshot } from './desktop';++vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() }));+vi.mock('@core/util/platform', () => ({ isTauri: () => true }));++const snapshot: DesktopSnapshot = {+ identity: {+ instanceId: 'launch',+ nativeVersion: '2.5',+ os: 'ios',+ hostPid: 1,+ recordingId: null,+ tracesUrl: null,+ },+ samples: [],+ droppedSamples: 0,+ recentEvents: {+ events: [],+ currentFrontendInstanceId: null,+ heartbeat: null,+ dropped: 0,+ memoryWarningReporting: true,+ },+};+let dispose: (() => void) | undefined;++beforeEach(() => {+ sessionStorage.clear();+ vi.resetModules();+ vi.mocked(invoke).mockReset().mockResolvedValue(undefined);+ vi.useFakeTimers();+});+afterEach(() => {+ dispose?.();+ dispose = undefined;+ vi.useRealTimers();+});++it.each([undefined, { ...snapshot, recentEvents: undefined }])(+ 'does not send unsupported commands without the new native capability',+ async (olderSnapshot) => {+ const diagnostics = await import('./native-diagnostics');+ diagnostics.recordNativeDiagnostic({ kind: 'visibility', visible: true });+ dispose = diagnostics.startNativeDiagnostics(olderSnapshot);+ await diagnostics.sendNativeDiagnostic({+ kind: 'visibility',+ visible: false,+ });+ expect(invoke).not.toHaveBeenCalled();+ }+);++it('bounds a hung bridge and keeps reload and logout usable', async () => {+ const diagnostics = await import('./native-diagnostics');+ dispose = diagnostics.startNativeDiagnostics(snapshot);+ await vi.advanceTimersByTimeAsync(0);+ vi.mocked(invoke)+ .mockClear()+ .mockImplementation(() => new Promise(() => {}));+ const write = diagnostics.sendNativeDiagnostic({+ kind: 'visibility',+ visible: false,+ });+ await vi.advanceTimersByTimeAsync(250);+ await write;+ const reload = diagnostics.sendNativeDiagnostic({+ kind: 'reload_requested',+ reload_id: crypto.randomUUID(),+ reason: 'user_recovery',+ });+ await vi.advanceTimersByTimeAsync(250);+ await reload;+ const clearing = diagnostics.clearNativeDiagnostics();+ expect(sessionStorage.getItem('macro-native-diagnostic-document')).toBeNull();+ await vi.advanceTimersByTimeAsync(250);+ await clearing;+ expect(invoke).toHaveBeenCalledTimes(3);+ expect(invoke).toHaveBeenNthCalledWith(+ 2,+ 'record_frontend_diagnostic',+ expect.objectContaining({+ event: expect.objectContaining({ kind: 'reload_requested' }),+ })+ );+});++it('bounds cumulative timeouts even when successful writes occur between them', async () => {+ const diagnostics = await import('./native-diagnostics');+ dispose = diagnostics.startNativeDiagnostics(snapshot);+ dispose();+ await vi.advanceTimersByTimeAsync(0);+ vi.mocked(invoke).mockClear();+ for (let index = 0; index < 3; index++) {+ vi.mocked(invoke).mockImplementationOnce(() => new Promise(() => {}));+ const write = diagnostics.sendNativeDiagnostic({+ kind: 'visibility',+ visible: true,+ });+ await vi.advanceTimersByTimeAsync(250);+ await write;+ await diagnostics.sendNativeDiagnostic({+ kind: 'connectivity',+ online: true,+ });+ }+ // Three hung invocations, with a successful write after each except the last.+ expect(invoke).toHaveBeenCalledTimes(5);+ await diagnostics.sendNativeDiagnostic({+ kind: 'visibility',+ visible: false,+ });+ expect(invoke).toHaveBeenCalledTimes(5);+ await diagnostics.clearNativeDiagnostics();+ expect(invoke).toHaveBeenCalledTimes(6);+});++it('disables diagnostics immediately when native rejects an invocation', async () => {+ const diagnostics = await import('./native-diagnostics');+ dispose = diagnostics.startNativeDiagnostics(snapshot);+ await vi.advanceTimersByTimeAsync(0);+ vi.mocked(invoke).mockClear().mockRejectedValue(new Error('bridge gone'));+ await diagnostics.sendNativeDiagnostic({+ kind: 'visibility',+ visible: false,+ });+ await diagnostics.sendNativeDiagnostic({+ kind: 'connectivity',+ online: false,+ });+ expect(invoke).toHaveBeenCalledOnce();+});++it('clears native history before retiring callbacks from the signed-out document', async () => {+ const diagnostics = await import('./native-diagnostics');+ dispose = diagnostics.startNativeDiagnostics(snapshot);+ await diagnostics.clearNativeDiagnostics();+ vi.mocked(invoke).mockClear();+ await diagnostics.sendNativeDiagnostic({+ kind: 'visibility',+ visible: true,+ });+ await vi.advanceTimersByTimeAsync(10_000);+ expect(invoke).not.toHaveBeenCalled();+ await diagnostics.sendNativeDiagnostic({+ kind: 'reload_requested',+ reload_id: crypto.randomUUID(),+ reason: 'logout',+ });+ expect(invoke).toHaveBeenCalledOnce();+});++it('still clears the previous document if logout happens during startup', async () => {+ const diagnostics = await import('./native-diagnostics');+ await diagnostics.clearNativeDiagnostics();+ dispose = diagnostics.startNativeDiagnostics(snapshot);+ expect(invoke).toHaveBeenNthCalledWith(+ 1,+ 'record_frontend_diagnostic',+ expect.objectContaining({+ event: { kind: 'started', previous_instance_id: null },+ })+ );+ expect(invoke).toHaveBeenNthCalledWith(+ 2,+ 'record_frontend_diagnostic',+ expect.objectContaining({ event: { kind: 'account_cleared' } })+ );+});++it('does not recover an old account after native clearing fails', async () => {+ sessionStorage.setItem('macro-native-diagnostic-document', 'launch:previous');+ const diagnostics = await import('./native-diagnostics');+ dispose = diagnostics.startNativeDiagnostics(snapshot);+ expect(diagnostics.recoverableNativeFrontend()).toBe('previous');+ vi.mocked(invoke).mockRejectedValue(new Error('bridge gone'));+ await diagnostics.clearNativeDiagnostics();+ dispose();+ vi.resetModules();+ const replacement = await import('./native-diagnostics');+ dispose = replacement.startNativeDiagnostics(snapshot);+ expect(replacement.recoverableNativeFrontend()).toBeUndefined();+});diff --git a/apps/web/src/observability/native-diagnostics.ts b/apps/web/src/observability/native-diagnostics.tsnew file mode 100644index 0000000000..ab44216afb--- /dev/null+++ b/apps/web/src/observability/native-diagnostics.ts@@ -0,0 +1,150 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { isTauri } from '@core/util/platform';+import { invoke } from '@tauri-apps/api/core';+import type { DesktopSnapshot } from './desktop';+import { frontendInstanceId } from './frontend-instance';+import type { FrontendEvent } from './generated/native-diagnostics';++// Document-owned diagnostics, never application state. Older native binaries+// advertise no recentEvents field and receive no new command invocations.+let supported: boolean | undefined;+let capable = false;+let retired = false;+const LEASE = 'macro-native-diagnostic-document';+const MAX_PENDING_DIAGNOSTICS = 32;+const MAX_DIAGNOSTIC_TIMEOUTS = 3;+let previousFrontend: string | undefined;+const pending: FrontendEvent[] = [];+let inFlight = 0;+let timeouts = 0;++export function nativeDiagnosticsRetired(): boolean {+ return retired;+}++export function recoverableNativeFrontend(): string | undefined {+ return previousFrontend;+}++/** Best effort, bounded IPC; a stuck bridge must never accumulate promises. */+export async function sendNativeDiagnostic(+ event: FrontendEvent+): Promise<void> {+ if (+ !isTauri() ||+ (retired &&+ !['reload_requested', 'account_cleared', 'started'].includes(event.kind))+ )+ return;+ if (supported === undefined) {+ if (pending.length < MAX_PENDING_DIAGNOSTICS) pending.push(event);+ return;+ }+ const clearing = event.kind === 'account_cleared' && capable;+ // A timed-out invoke may still be pending in the bridge. Keep it charged+ // against the document's budget even after the caller stops waiting.+ if (+ (!supported || inFlight + timeouts >= MAX_PENDING_DIAGNOSTICS) &&+ !clearing+ )+ return;+ inFlight++;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ invoke('record_frontend_diagnostic', { frontendInstanceId, event }),+ new Promise<void>((resolve) => {+ timer = setTimeout(() => {+ timeouts++;+ if (timeouts >= MAX_DIAGNOSTIC_TIMEOUTS) supported = false;+ resolve();+ }, 250);+ }),+ ]);+ } catch {+ // A rejected native command disables diagnostics immediately for this document.+ supported = false;+ } finally {+ clearTimeout(timer);+ inFlight--;+ }+}++export function recordNativeDiagnostic(event: FrontendEvent): void {+ fireAndForget(sendNativeDiagnostic(event), 'native-diagnostics');+}++/** Await before clearing auth, then reject late callbacks from the old account. */+export async function clearNativeDiagnostics(): Promise<void> {+ previousFrontend = undefined;+ try {+ sessionStorage.removeItem(LEASE);+ } catch {+ /* Replay requires a readable lease. */+ }+ pending.length = 0;+ const clearing = sendNativeDiagnostic({ kind: 'account_cleared' });+ retired = true;+ await clearing;+}++export function startNativeDiagnostics(+ snapshot: DesktopSnapshot | undefined+): () => void {+ supported = snapshot?.recentEvents !== undefined;+ capable = supported;+ if (!supported) {+ pending.length = 0;+ return () => {};+ }+ const nativeId = snapshot?.identity.instanceId;+ try {+ const lease = sessionStorage.getItem(LEASE)?.split(':');+ previousFrontend = lease && lease[0] === nativeId ? lease[1] : undefined;+ if (!retired)+ sessionStorage.setItem(LEASE, `${nativeId}:${frontendInstanceId}`);+ } catch {+ // No proof that these entries belong to this signed-in session: don't export them.+ previousFrontend = undefined;+ }+ recordNativeDiagnostic({+ kind: 'started',+ previous_instance_id:+ snapshot?.recentEvents?.currentFrontendInstanceId ?? null,+ });+ if (retired) {+ pending.length = 0;+ recordNativeDiagnostic({ kind: 'account_cleared' });+ return () => {};+ }+ for (const event of pending.splice(0)) recordNativeDiagnostic(event);+ const heartbeat = () =>+ recordNativeDiagnostic({+ kind: 'heartbeat',+ visible: document.visibilityState === 'visible',+ online: navigator.onLine,+ });+ const visibility = () => {+ recordNativeDiagnostic({+ kind: 'visibility',+ visible: document.visibilityState === 'visible',+ });+ heartbeat();+ };+ const connectivity = () =>+ recordNativeDiagnostic({ kind: 'connectivity', online: navigator.onLine });+ document.addEventListener('visibilitychange', visibility);+ window.addEventListener('online', connectivity);+ window.addEventListener('offline', connectivity);+ heartbeat();+ const timer = setInterval(() => {+ // Background timer throttling is expected, not evidence of a hung frontend.+ if (document.visibilityState === 'visible') heartbeat();+ }, 5000);+ return () => {+ clearInterval(timer);+ document.removeEventListener('visibilitychange', visibility);+ window.removeEventListener('online', connectivity);+ window.removeEventListener('offline', connectivity);+ };+}diff --git a/apps/web/src/observability/native-lifecycle.test.ts b/apps/web/src/observability/native-lifecycle.test.tsindex d3ef592162..a7d959efac 100644--- a/apps/web/src/observability/native-lifecycle.test.ts+++ b/apps/web/src/observability/native-lifecycle.test.ts@@ -1,9 +1,15 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { recordNativeWebviewStart } from './native-lifecycle';+import type { DesktopSnapshot } from './desktop';+import { frontendInstanceId } from './frontend-instance';+import {+ recordNativeWebviewStart,+ reportRecoveredEvents,+} from './native-lifecycle';const telemetry = vi.hoisted(() => ({track: vi.fn(),register: vi.fn(),+ recordSample: vi.fn(),span: { setAttr: vi.fn(), end: vi.fn() },}));vi.mock('@app/lib/analytics', () => ({@@ -13,13 +19,78 @@ vi.mock('@app/lib/analytics', () => ({},}));vi.mock('@macro-inc/observability', () => ({- Telemetry: { span: () => telemetry.span },+ Telemetry: {+ span: () => telemetry.span,+ recordSample: telemetry.recordSample,+ },}));afterEach(() => {document.head.querySelector('meta[name="macro-bundle-build"]')?.remove();vi.restoreAllMocks();vi.clearAllMocks();+ sessionStorage.clear();+});++it('replays a previous document once with original identity/time in sequence order', () => {+ const visibility = {+ sequence: 1,+ timestampMs: 100,+ frontendInstanceId: 'previous',+ event: { kind: 'visibility' as const, visible: true },+ };+ const snapshot: DesktopSnapshot = {+ identity: {+ instanceId: 'host',+ nativeVersion: '2.5',+ os: 'ios',+ hostPid: 1,+ recordingId: null,+ tracesUrl: null,+ },+ samples: [],+ droppedSamples: 0,+ recentEvents: {+ currentFrontendInstanceId: 'previous',+ events: [+ visibility,+ {+ sequence: 3,+ timestampMs: 300,+ frontendInstanceId: 'previous',+ event: { kind: 'web_content_terminated' },+ },+ ],+ heartbeat: {+ sequence: 2,+ timestampMs: 200,+ frontendInstanceId: 'previous',+ event: {+ kind: 'heartbeat',+ visible: true,+ online: false,+ },+ },+ dropped: 0,+ memoryWarningReporting: true,+ },+ };+ reportRecoveredEvents(snapshot, 'previous');+ reportRecoveredEvents(snapshot, 'previous');+ expect(telemetry.recordSample).toHaveBeenCalledTimes(3);+ expect(telemetry.recordSample).toHaveBeenNthCalledWith(+ 2,+ 'native.diagnostic.recovered',+ expect.objectContaining({+ source_frontend_instance_id: 'previous',+ recovered_by_frontend_instance_id: frontendInstanceId,+ native_event_id: 'host:2',+ visible: true,+ online: false,+ }),+ 200+ );+ expect(telemetry.track).toHaveBeenCalledTimes(3);});describe('native WebView startup diagnostics', () => {diff --git a/apps/web/src/observability/native-lifecycle.ts b/apps/web/src/observability/native-lifecycle.tsindex f69ae81154..9414a594d4 100644--- a/apps/web/src/observability/native-lifecycle.ts+++ b/apps/web/src/observability/native-lifecycle.ts@@ -1,6 +1,12 @@import { analytics } from '@app/lib/analytics';import { Telemetry } from '@macro-inc/observability';import type { DesktopSnapshot } from './desktop';+import { frontendInstanceId } from './frontend-instance';+import {+ nativeDiagnosticsRetired,+ recoverableNativeFrontend,+} from './native-diagnostics';+import { consumeReloadIntent } from './reload';/** Called once per document, including recovery after a WebContent termination. */export function recordNativeWebviewStart(@@ -17,6 +23,7 @@ export function recordNativeWebviewStart(? snapshot.webContent: undefined;const attributes = {+ frontend_instance_id: frontendInstanceId,native_instance_id: snapshot?.identity.instanceId,native_version: snapshot?.identity.nativeVersion,native_diagnostics_available: snapshot !== undefined,@@ -26,6 +33,14 @@ export function recordNativeWebviewStart(native_bundle_reload_dispatches: snapshot?.bundleReloads?.dispatches,native_bundle_reload_last_source:snapshot?.bundleReloads?.lastSource ?? undefined,+ native_bundle_reload_last_id:+ snapshot?.bundleReloads?.lastReloadId ?? undefined,+ native_bundle_reload_last_dispatch_ms:+ snapshot?.bundleReloads?.lastDispatchMs ?? undefined,+ native_breadcrumbs_available: snapshot?.recentEvents !== undefined,+ native_memory_warning_reporting_available:+ snapshot?.recentEvents?.memoryWarningReporting ?? false,+ native_breadcrumbs_dropped: snapshot?.recentEvents?.dropped,loaded_bundle_build: bundleBuild ?? undefined,web_version: import.meta.env.__APP_VERSION__,navigation_type:@@ -36,10 +51,65 @@ export function recordNativeWebviewStart(// Include the native launch and termination count on subsequent exceptions.// These are runtime identifiers, not account data.analytics.posthog.register(attributes);- analytics.track('native_webview_started', attributes);+ const startupAttributes = { ...attributes, ...consumeReloadIntent() };+ analytics.track('native_webview_started', startupAttributes);const span = Telemetry.span('native.webview.start');- for (const [key, value] of Object.entries(attributes)) {+ for (const [key, value] of Object.entries(startupAttributes)) {if (value !== undefined) span.setAttr(key, value);}span.end();+ if (snapshot && !nativeDiagnosticsRetired())+ reportRecoveredEvents(snapshot, recoverableNativeFrontend());+}++/** Recovered entries retain source identity/time; current signals identify their uploader. */+export function reportRecoveredEvents(+ snapshot: DesktopSnapshot,+ previousFrontend: string | undefined+) {+ const recent = snapshot.recentEvents;+ if (!recent || !previousFrontend) return;+ const key = 'macro-native-diagnostic-cursor';+ let after = 0;+ try {+ const saved = sessionStorage.getItem(key)?.split(':');+ if (saved?.[0] === snapshot.identity.instanceId) {+ const sequence = Number(saved[1]);+ if (Number.isSafeInteger(sequence) && sequence >= 0) after = sequence;+ }+ } catch {+ /* Recovery still works without session storage; duplicates retain event IDs. */+ }+ let latest = after;+ const entries = [+ ...recent.events,+ ...(recent.heartbeat ? [recent.heartbeat] : []),+ ].sort((a, b) => a.sequence - b.sequence);+ for (const entry of entries) {+ if (entry.frontendInstanceId !== previousFrontend) continue;+ if (entry.sequence <= after) continue;+ const attributes = {+ ...Object.fromEntries(+ Object.entries(entry.event).filter(([, value]) => value !== null)+ ),+ native_instance_id: snapshot.identity.instanceId,+ native_event_id: `${snapshot.identity.instanceId}:${entry.sequence}`,+ source_frontend_instance_id: entry.frontendInstanceId ?? undefined,+ recovered_by_frontend_instance_id: frontendInstanceId,+ native_event_timestamp_ms: entry.timestampMs,+ native_event_sequence: entry.sequence,+ };+ analytics.track('native_diagnostic_recovered', attributes);+ Telemetry.recordSample(+ 'native.diagnostic.recovered',+ attributes,+ entry.timestampMs+ );+ latest = entry.sequence;+ }+ try {+ sessionStorage.setItem(key, `${snapshot.identity.instanceId}:${latest}`);+ } catch {+ /* Stable event IDs permit deduplication after storage loss. */+ }}diff --git a/apps/web/src/observability/reload.test.ts b/apps/web/src/observability/reload.test.tsnew file mode 100644index 0000000000..b0445dca87--- /dev/null+++ b/apps/web/src/observability/reload.test.ts@@ -0,0 +1,77 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { sendNativeDiagnostic } from './native-diagnostics';++vi.mock('./native-diagnostics', () => ({ sendNativeDiagnostic: vi.fn() }));+const reload = vi.fn();+beforeEach(() => {+ vi.resetModules();+ vi.mocked(sendNativeDiagnostic).mockReset().mockResolvedValue(undefined);+ reload.mockClear();+ sessionStorage.clear();+ vi.stubGlobal('window', { location: { reload } });+});+afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++it('persists intent before native IPC and reloads only after acknowledgement', async () => {+ let acknowledge: (() => void) | undefined;+ vi.mocked(sendNativeDiagnostic).mockImplementation(+ () =>+ new Promise((resolve) => {+ acknowledge = resolve;+ })+ );+ const app = await import('./reload');+ app.reloadApp('user_recovery');+ app.reloadApp('logout');+ expect(reload).not.toHaveBeenCalled();+ expect(sendNativeDiagnostic).toHaveBeenCalledOnce();+ const intent = app.consumeReloadIntent();+ expect(intent).toMatchObject({ requested_reload_reason: 'user_recovery' });+ expect(intent?.requested_reload_id).toHaveLength(36);+ expect(app.consumeReloadIntent()).toBeUndefined();+ acknowledge?.();+ await Promise.resolve();+ expect(reload).toHaveBeenCalledOnce();+});++it('telemetry or storage failure cannot prevent the requested reload', async () => {+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('unavailable');+ });+ vi.mocked(sendNativeDiagnostic).mockRejectedValue(new Error('bridge gone'));+ const app = await import('./reload');+ app.reloadApp('update_accepted');+ await Promise.resolve();+ expect(reload).toHaveBeenCalledOnce();+});++it('does not attribute an old or malformed marker to a later startup', async () => {+ const app = await import('./reload');+ sessionStorage.setItem(+ 'macro-pending-reload',+ JSON.stringify({+ reason: 'user_recovery',+ reloadId: crypto.randomUUID(),+ frontendInstanceId: crypto.randomUUID(),+ timestampMs: 1,+ })+ );+ expect(app.consumeReloadIntent(31 * 60_000)).toBeUndefined();+ sessionStorage.setItem('macro-pending-reload', '{');+ expect(app.consumeReloadIntent()).toBeUndefined();+});++it('does not delay an automatic reload beyond the synchronous idle decision', async () => {+ vi.mocked(sendNativeDiagnostic).mockImplementation(+ () => new Promise(() => {})+ );+ const app = await import('./reload');+ app.reloadApp('cache_replaced_automatic');+ expect(reload).toHaveBeenCalledOnce();+ expect(app.consumeReloadIntent()?.requested_reload_reason).toBe(+ 'cache_replaced_automatic'+ );+});diff --git a/apps/web/src/observability/reload.ts b/apps/web/src/observability/reload.tsnew file mode 100644index 0000000000..69e0508902--- /dev/null+++ b/apps/web/src/observability/reload.ts@@ -0,0 +1,90 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { frontendInstanceId } from './frontend-instance';+import type { ReloadReason } from './generated/native-diagnostics';+import { sendNativeDiagnostic } from './native-diagnostics';++const KEY = 'macro-pending-reload';+const REASONS = [+ 'cache_replaced_automatic',+ 'update_accepted',+ 'failed_load_recovery',+ 'user_recovery',+ 'logout',+] satisfies ReloadReason[];+let requested = false;++/** Record intent before unloading; native acknowledgement is capped at 250ms. */+export function reloadApp(reason: ReloadReason): void {+ if (requested) return;+ requested = true;+ const reloadId = crypto.randomUUID();+ try {+ sessionStorage.setItem(+ KEY,+ JSON.stringify({+ reloadId,+ reason,+ frontendInstanceId,+ timestampMs: Date.now(),+ })+ );+ } catch {+ /* Storage restrictions must not prevent recovery. */+ }+ fireAndForget(reloadAfterRecording(reloadId, reason), 'app-reload');+}++async function reloadAfterRecording(reloadId: string, reason: ReloadReason) {+ try {+ const recording = sendNativeDiagnostic({+ kind: 'reload_requested',+ reload_id: reloadId,+ reason,+ });+ // The idle decision was just made synchronously. Waiting could let the+ // user foreground the app or start held work before an automatic reload.+ if (reason === 'cache_replaced_automatic') {+ fireAndForget(recording, 'automatic-reload-diagnostic');+ } else {+ await recording;+ }+ } finally {+ window.location.reload();+ }+}++/** Consume once; this is reload intent, never proof the request caused a crash. */+export function consumeReloadIntent(now = Date.now()) {+ try {+ const saved = sessionStorage.getItem(KEY);+ sessionStorage.removeItem(KEY);+ if (!saved) return undefined;+ const value: unknown = JSON.parse(saved);+ if (+ !value ||+ typeof value !== 'object' ||+ !('reason' in value) ||+ !REASONS.some((reason) => reason === value.reason) ||+ !('reloadId' in value) ||+ typeof value.reloadId !== 'string' ||+ value.reloadId.length !== 36 ||+ !('frontendInstanceId' in value) ||+ typeof value.frontendInstanceId !== 'string' ||+ value.frontendInstanceId.length !== 36 ||+ !('timestampMs' in value) ||+ typeof value.timestampMs !== 'number' ||+ !Number.isFinite(value.timestampMs) ||+ now < value.timestampMs ||+ now - value.timestampMs > 30 * 60_000+ )+ return undefined;+ return {+ requested_reload_id: value.reloadId,+ requested_reload_reason: String(value.reason),+ requested_reload_timestamp_ms: value.timestampMs,+ requested_reload_frontend_instance_id: value.frontendInstanceId,+ };+ } catch {+ return undefined;+ }+}diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex fe07994a61..4fbf4b6482 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -2,6 +2,12 @@# It is not intended for manual editing.version = 4+[[package]]+name = "Inflector"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"+[[package]]name = "adler2"version = "2.0.1"@@ -262,6 +268,7 @@ dependencies = ["objc2 0.5.2","objc2 0.6.4","objc2-foundation",+ "objc2-ui-kit","objc2-user-notifications","reqwest","rootcause",@@ -269,6 +276,9 @@ dependencies = ["serde","serde_json","serde_qs",+ "specta",+ "specta-serde",+ "specta-typescript","staged_upload_constants","tauri","tauri-build",@@ -3676,6 +3686,9 @@ dependencies = ["serde","serde_json","sha2",+ "specta",+ "specta-serde",+ "specta-typescript","strum 0.27.2","tauri","tauri-plugin-device-info",@@ -3683,6 +3696,7 @@ dependencies = ["tokio","tracing","url",+ "uuid","zip 6.0.0",]@@ -6285,6 +6299,48 @@ dependencies = ["system-deps",]+[[package]]+name = "specta"+version = "2.0.0-rc.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38f9a30cbcbb7011f1da7d73483983bf838af123883e45f2b36ed76328df9c50"+dependencies = [+ "rustc_version",+ "specta-macros",+ "uuid",+]++[[package]]+name = "specta-macros"+version = "2.0.0-rc.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ce14957ecc2897f1f848b8255b6531d13ddf49cbcf506b7c2c9fb1d005593bb"+dependencies = [+ "Inflector",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "specta-serde"+version = "0.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee8a72b755ddb8949fd8f17c5db43f0e8a806ea587d9bc602ee3f73240c00029"+dependencies = [+ "specta",+ "specta-macros",+]++[[package]]+name = "specta-typescript"+version = "0.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "639404ee95557f2f8b7e4cb773ffefd45304c7ab8ba21ac83b69051595e083c0"+dependencies = [+ "specta",+]+[[package]]name = "spin"version = "0.9.8"diff --git a/apps/web/tauri/macro_bundle_updater_plugin/Cargo.toml b/apps/web/tauri/macro_bundle_updater_plugin/Cargo.tomlindex 9644a53a67..8f5c79b671 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/Cargo.toml+++ b/apps/web/tauri/macro_bundle_updater_plugin/Cargo.toml@@ -20,6 +20,7 @@ tokio = { workspace = true, features = ["fs", "macros", "sync", "time"] }tracing = { workspace = true }url = { workspace = true }zip = "6"+uuid = { version = "1.18.1", features = ["v4"] }[target.'cfg(target_os = "ios")'.dependencies]objc2 = "0.5"@@ -29,4 +30,7 @@ jni = "0.21"ndk-context = "0.1"[dev-dependencies]+specta = { version = "=2.0.0-rc.25", features = ["derive"] }+specta-serde = "=0.0.12"+specta-typescript = "=0.0.12"tokio = { workspace = true, features = ["macros", "rt"] }diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rsindex a41d906664..be4c9e3b21 100644--- a/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs@@ -27,12 +27,44 @@ pub type PluginService = Service<FileSystem>;const EVENT_NAME: &str = "bundle-update-status";const WIFI_RETRY_INTERVAL: Duration = Duration::from_secs(30);+#[test]+fn diagnostic_wire_types() {+ let generated = specta_typescript::Typescript::default()+ .export(+ &specta::Types::default().register::<BundleReloadDiagnostics>(),+ specta_serde::Format,+ )+ .expect("export bundle reload types");+ let generated = generated+ .lines()+ .map(str::trim_end)+ .collect::<Vec<_>>()+ .join("\n")+ + "\n";+ let output = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../src/observability/generated/bundle-reloads.ts");+ if std::env::var_os("UPDATE_NATIVE_DIAGNOSTIC_TYPES").is_some() {+ std::fs::create_dir_all(output.parent().expect("generated directory"))+ .expect("create directory");+ std::fs::write(&output, &generated).expect("write types");+ }+ assert_eq!(+ std::fs::read_to_string(output).expect("generated types"),+ generated+ );+}+/// Launch-scoped reload dispatches, retained across replacement documents.#[derive(Clone, Default, Serialize)]+#[cfg_attr(test, derive(specta::Type))]#[serde(rename_all = "camelCase")]pub struct BundleReloadDiagnostics {+ #[cfg_attr(test, specta(type = specta_typescript::Number))]dispatches: u64,last_source: Option<&'static str>,+ last_reload_id: Option<String>,+ #[cfg_attr(test, specta(type = Option<specta_typescript::Number>))]+ last_dispatch_ms: Option<u64>,}/// Read reload evidence without waiting for the updater's async service lock.@@ -50,6 +82,13 @@ fn record_reload_dispatch<R: Runtime>(app: &tauri::AppHandle<R>, source: &'stati{diagnostics.dispatches += 1;diagnostics.last_source = Some(source);+ diagnostics.last_reload_id = Some(uuid::Uuid::new_v4().to_string());+ diagnostics.last_dispatch_ms = Some(+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64,+ );}tracing::info!(source, "Dispatching bundle update WebView reload");}diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 2aaaff9a50..ff116421cf 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -19,6 +19,9 @@ tauri-build = { version = "2.3.1", features = [] }[dev-dependencies]tauri = { workspace = true, features = ["test"] }+specta = { version = "=2.0.0-rc.25", features = ["derive", "uuid"] }+specta-serde = "=0.0.12"+specta-typescript = "=0.0.12"[features]# Automatic OTA bundle updates: check on launch/resume, apply cached bundles at@@ -60,7 +63,7 @@ tracing = { workspace = true }tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }url = { workspace = true }urlencoding = "2.1.3"-uuid = { version = "1.18.1", features = ["v4"] }+uuid = { version = "1.18.1", features = ["v4", "serde"] }# system notifications for when the app is opentauri-plugin-notification = "2"# push notifications for mobile (when app is closed)@@ -130,4 +133,9 @@ tauri-plugin-pasteboard = { path = "../pasteboard_plugin" }tauri-plugin-photo-library = { path = "../photo_library_plugin" }# Used to call NSFileManager from Rust to get the App Group container path.# This version is already in the dependency tree via wry/tao.-objc2 = "0.5"+objc2-legacy = { package = "objc2", version = "0.5" }+# Modern generated Foundation/UIKit bindings for memory-warning observation.+objc2 = "0.6"+block2 = "0.6"+objc2-ui-kit = { version = "0.3", default-features = false, features = ["std", "UIApplication"] }+objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSNotification", "NSOperation", "NSString", "block2"] }diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.mdindex 55c1e89a90..9cb69a1ed7 100644--- a/apps/web/tauri/src-tauri/README.md+++ b/apps/web/tauri/src-tauri/README.md@@ -55,6 +55,71 @@ the native evidence before reloading. It does not establish why WebKit terminateare needed for that distinction. Native counters require a full app release,while the frontend remains compatible with older binaries.+`frontend_instance_id` is generated once per document and attached to every+PostHog event (including automatic exceptions/pageviews) and OTel resource.+`native_instance_id` joins both systems to the host launch. A new frontend ID+with the same native ID establishes a document replacement; SPA navigation+keeps both. OTel export still obeys the existing browser telemetry gate.++Frontend reloads go through `reloadApp(reason)`: automatic cache replacement,+accepted update, failed-load recovery, user recovery, or logout. It saves a+one-shot session-storage marker and asks native to record the request before+reloading, waiting at most 250ms for user-requested reloads. Automatic idle+reloads keep their synchronous timing and send native evidence best effort.+An individual diagnostic IPC timeout stops waiting for that event; three+cumulative timeouts disable further writes for the document. Timed-out requests+remain charged against the 32-request budget because the native invocation may+still be pending.+A native command rejection disables writes immediately. Logout cleanup can+bypass the budget, with the same 250ms wait limit.+The next native startup reports+`requested_reload_*`; stale markers older than 30 minutes are discarded. Native+bundle reload dispatches have their own `native_bundle_reload_last_id` and+`native_bundle_reload_last_dispatch_ms`. These are evidence of intent/dispatch,+not proof of the cause of a termination.++New binaries retain 128 diagnostic events and a separate latest frontend+heartbeat in native memory. Events+cover native foreground/background, WebContent termination, iOS memory warnings,+frontend visibility/connectivity, and explicit reload requests. Keep reload+diagnostics at document/native lifecycle boundaries; UI mount state and streamed+text changes do not establish a reload cause and should not generate native IPC.+The schema accepts no message text, URLs, or content identifiers.+Heartbeats record visibility and connectivity every five seconds while visible+and at visibility transitions; background throttling is expected. They provide+a last-known responsive timestamp, not proof of a hang or its cause.+Heartbeats cannot evict history. Logout clears history and rejects late callbacks.+Recovery also requires a session-storage lease matching the previous document;+logout deletes it before awaiting native IPC. A missing/blocked lease suppresses+replay, so even a failed native clear cannot export the previous account's history.++After replacement, `native_diagnostic_recovered` PostHog events and+`native.diagnostic.recovered` OTel samples report the buffered evidence.+`source_frontend_instance_id` identifies the old document,+`recovered_by_frontend_instance_id` the uploader, and+`native_event_timestamp_ms` the original observation time. OTel samples use that+original timestamp; PostHog captures recovery now and retains the observation+timestamp as a property. Session storage avoids repeated exports; stable+`native_event_id` values permit deduplication if storage is lost. Export is best+effort, not a server-acknowledged delivery queue. The buffer survives WebContent+replacement but not host termination, and a full ring reports dropped events.++UIKit memory warnings support a memory-pressure hypothesis but are not a WebKit+kill reason. No warning does not rule out memory-related termination. Native+history and memory warnings require a rebuilt app; older binaries report+unavailable coverage and receive no periodic diagnostic commands. These additions+are optional and do not raise the minimum native build for OTA bundles.++The new wire types are generated from Rust (Specta is a dev dependency). After+editing the contract, run from the repository root with the development native+environment configured:++```sh+UPDATE_NATIVE_DIAGNOSTIC_TYPES=1 cargo test --manifest-path apps/web/tauri/Cargo.toml --locked -p app -p macro_bundle_updater_plugin --lib --no-default-features diagnostic_wire_types+```++The same tests without that environment variable check for drift.+## Running in development```shdiff --git a/apps/web/tauri/src-tauri/src/device.rs b/apps/web/tauri/src-tauri/src/device.rsindex 56f874cf7a..d6db688ad8 100644--- a/apps/web/tauri/src-tauri/src/device.rs+++ b/apps/web/tauri/src-tauri/src/device.rs@@ -14,7 +14,7 @@ pub(crate) struct IsIpad(pub(crate) bool);/// `UIUserInterfaceIdiomPad`, from `<UIKit/UIDevice.h>`.#[cfg(target_os = "ios")]-const UI_USER_INTERFACE_IDIOM_PAD: objc2::ffi::NSInteger = 1;+const UI_USER_INTERFACE_IDIOM_PAD: objc2_legacy::ffi::NSInteger = 1;/// Reads `[[UIDevice currentDevice] userInterfaceIdiom]`, excluding iOS apps/// running on an Apple Silicon Mac (which also report the iPad idiom).@@ -27,9 +27,9 @@ const UI_USER_INTERFACE_IDIOM_PAD: objc2::ffi::NSInteger = 1;/// silently become `.phone`, making this return `false` with no compile error.#[cfg(target_os = "ios")]pub(crate) fn detect_is_ipad() -> bool {- use objc2::ffi::NSInteger;- use objc2::runtime::{AnyObject, Bool};- use objc2::{class, msg_send};+ use objc2_legacy::ffi::NSInteger;+ use objc2_legacy::runtime::{AnyObject, Bool};+ use objc2_legacy::{class, msg_send};// SAFETY: `+[UIDevice currentDevice]`, `-[UIDevice userInterfaceIdiom]`,// `+[NSProcessInfo processInfo]` and `-[NSProcessInfo isiOSAppOnMac]` alldiff --git a/apps/web/tauri/src-tauri/src/diagnostics.rs b/apps/web/tauri/src-tauri/src/diagnostics.rsindex 2b53eb70c7..3c8415aff3 100644--- a/apps/web/tauri/src-tauri/src/diagnostics.rs+++ b/apps/web/tauri/src-tauri/src/diagnostics.rs@@ -9,6 +9,9 @@ use serde::Serialize;use tauri::Manager;use uuid::Uuid;+pub mod events;+#[cfg(target_os = "ios")]+mod ios;#[cfg(desktop)]mod launch;#[cfg(target_os = "macos")]@@ -117,6 +120,7 @@ pub struct Diagnostics {identity: Identity,buffer: Mutex<SampleBuffer>,web_content: Mutex<WebContentDiagnostics>,+ events: Mutex<events::EventBuffer>,}impl Diagnostics {@@ -136,6 +140,7 @@ impl Diagnostics {},buffer: Mutex::new(SampleBuffer::default()),web_content: Mutex::new(WebContentDiagnostics::default()),+ events: Mutex::new(events::EventBuffer::default()),}}@@ -145,6 +150,7 @@ impl Diagnostics {/// Retain process termination evidence outside the WebView being reloaded.pub fn record_web_content_termination(&self) -> Result<(), String> {+ self.record_native_event(events::NativeEvent::WebContentTerminated);let mut web_content = self.web_content.lock().map_err(|e| e.to_string())?;web_content.record_termination(SystemTime::now()@@ -154,6 +160,33 @@ impl Diagnostics {);Ok(())}++ pub fn record_native_event(&self, event: events::NativeEvent) {+ if let Ok(mut buffer) = self.events.lock() {+ buffer.native(event, timestamp_ms());+ }+ }+}++fn timestamp_ms() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64+}++#[tauri::command]+pub fn record_frontend_diagnostic(+ state: tauri::State<'_, Diagnostics>,+ frontend_instance_id: Uuid,+ event: events::FrontendEvent,+) -> Result<(), String> {+ state.events.lock().map_err(|e| e.to_string())?.frontend(+ frontend_instance_id,+ event,+ timestamp_ms(),+ );+ Ok(())}#[derive(Serialize)]@@ -164,6 +197,7 @@ pub struct Snapshot {dropped_samples: u64,web_content: WebContentDiagnostics,bundle_reloads: Option<macro_bundle_updater_plugin::inbound::plugin::BundleReloadDiagnostics>,+ recent_events: events::EventSnapshot,}#[tauri::command]@@ -182,6 +216,7 @@ pub fn read_desktop_diagnostics<R: tauri::Runtime>(bundle_reloads: macro_bundle_updater_plugin::inbound::plugin::bundle_reload_diagnostics(&app_handle,),+ recent_events: state.events.lock().map_err(|e| e.to_string())?.snapshot(),})}@@ -196,6 +231,8 @@ pub fn setup<R: tauri::Runtime>(app: &tauri::App<R>, mut diagnostics: Diagnostic}}app.manage(diagnostics);+ #[cfg(target_os = "ios")]+ ios::observe_memory_warnings(app.handle().clone());if !recording {return;}diff --git a/apps/web/tauri/src-tauri/src/diagnostics/events.rs b/apps/web/tauri/src-tauri/src/diagnostics/events.rsnew file mode 100644index 0000000000..1d26a58253--- /dev/null+++ b/apps/web/tauri/src-tauri/src/diagnostics/events.rs@@ -0,0 +1,178 @@+//! Small, content-free history owned by the host, independent of WebContent.++use std::collections::VecDeque;++use serde::{Deserialize, Serialize};+use uuid::Uuid;++const CAPACITY: usize = 128;++#[derive(Clone, Debug, Deserialize, Serialize)]+#[cfg_attr(test, derive(specta::Type))]+#[serde(rename_all = "snake_case")]+pub enum ReloadReason {+ CacheReplacedAutomatic,+ UpdateAccepted,+ FailedLoadRecovery,+ UserRecovery,+ Logout,+}++/// Closed schema: never accept arbitrary text, URLs, or message content.+#[derive(Clone, Debug, Deserialize, Serialize)]+#[cfg_attr(test, derive(specta::Type))]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum FrontendEvent {+ Started {+ previous_instance_id: Option<Uuid>,+ },+ Heartbeat {+ visible: bool,+ online: bool,+ },+ Visibility {+ visible: bool,+ },+ Connectivity {+ online: bool,+ },+ ReloadRequested {+ reload_id: Uuid,+ reason: ReloadReason,+ },+ /// Clears identifiers before another account can take over the WebView.+ AccountCleared,+}++#[derive(Clone, Debug, Serialize)]+#[cfg_attr(test, derive(specta::Type))]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum NativeEvent {+ #[cfg(any(mobile, test))]+ Foreground,+ #[cfg(any(mobile, test))]+ Background,+ #[cfg(any(target_os = "ios", test))]+ MemoryWarning,+ WebContentTerminated,+}++#[derive(Clone, Debug, Serialize)]+#[cfg_attr(test, derive(specta::Type))]+#[serde(untagged)]+pub enum Event {+ Frontend(FrontendEvent),+ Native(NativeEvent),+}++#[derive(Clone, Debug, Serialize)]+#[cfg_attr(test, derive(specta::Type))]+#[serde(rename_all = "camelCase")]+pub struct DiagnosticEvent {+ pub sequence: u32,+ // Milliseconds since epoch fit exactly in a JavaScript number.+ #[cfg_attr(test, specta(type = specta_typescript::Number))]+ pub timestamp_ms: u64,+ pub frontend_instance_id: Option<Uuid>,+ pub event: Event,+}++#[derive(Clone, Default, Serialize)]+#[cfg_attr(test, derive(specta::Type))]+#[serde(rename_all = "camelCase")]+pub struct EventSnapshot {+ pub events: Vec<DiagnosticEvent>,+ pub current_frontend_instance_id: Option<Uuid>,+ pub heartbeat: Option<DiagnosticEvent>,+ pub dropped: u32,+ pub memory_warning_reporting: bool,+}++#[derive(Default)]+pub struct EventBuffer {+ sequence: u32,+ events: VecDeque<DiagnosticEvent>,+ heartbeat: Option<DiagnosticEvent>,+ frontend: Option<Uuid>,+ retired_frontend: Option<Uuid>,+ dropped: u32,+}++impl EventBuffer {+ pub fn frontend(&mut self, id: Uuid, event: FrontendEvent, timestamp_ms: u64) {+ if self.retired_frontend == Some(id)+ && !matches!(event, FrontendEvent::ReloadRequested { .. })+ {+ return;+ }+ if let FrontendEvent::Started {+ previous_instance_id,+ } = &event+ {+ // Compare against the snapshot read by this document. A delayed+ // start from a replaced document cannot reclaim the buffer.+ if self.frontend == Some(id) || *previous_instance_id != self.frontend {+ return;+ }+ self.frontend = Some(id);+ self.heartbeat = None;+ } else if self.frontend != Some(id) {+ // A delayed IPC from the replaced document cannot overwrite its successor.+ return;+ }+ if matches!(event, FrontendEvent::AccountCleared) {+ self.events.clear();+ self.heartbeat = None;+ self.retired_frontend = Some(id);+ self.dropped = 0;+ }+ let heartbeat = matches!(event, FrontendEvent::Heartbeat { .. });+ let entry = self.entry(Some(id), Event::Frontend(event), timestamp_ms);+ if heartbeat {+ self.heartbeat = Some(entry);+ } else {+ self.push(entry);+ }+ }++ pub fn native(&mut self, event: NativeEvent, timestamp_ms: u64) {+ let entry = self.entry(self.frontend, Event::Native(event), timestamp_ms);+ self.push(entry);+ }++ fn entry(+ &mut self,+ frontend_instance_id: Option<Uuid>,+ event: Event,+ timestamp_ms: u64,+ ) -> DiagnosticEvent {+ self.sequence = self.sequence.saturating_add(1);+ DiagnosticEvent {+ sequence: self.sequence,+ timestamp_ms,+ frontend_instance_id,+ event,+ }+ }++ fn push(&mut self, entry: DiagnosticEvent) {+ if self.events.len() == CAPACITY {+ self.events.pop_front();+ self.dropped = self.dropped.saturating_add(1);+ }+ self.events.push_back(entry);+ }++ pub fn snapshot(&self) -> EventSnapshot {+ EventSnapshot {+ events: self.events.iter().cloned().collect(),+ current_frontend_instance_id: self.frontend,+ heartbeat: self.heartbeat.clone(),+ dropped: self.dropped,+ memory_warning_reporting: cfg!(target_os = "ios"),+ }+ }+}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/src-tauri/src/diagnostics/events/test.rs b/apps/web/tauri/src-tauri/src/diagnostics/events/test.rsnew file mode 100644index 0000000000..dba56b752b--- /dev/null+++ b/apps/web/tauri/src-tauri/src/diagnostics/events/test.rs@@ -0,0 +1,169 @@+use super::*;++#[test]+fn a_delayed_start_cannot_reclaim_a_newer_document() {+ let mut buffer = EventBuffer::default();+ let old = Uuid::new_v4();+ let next = Uuid::new_v4();+ buffer.frontend(+ old,+ FrontendEvent::Started {+ previous_instance_id: None,+ },+ 1,+ );+ buffer.frontend(+ next,+ FrontendEvent::Started {+ previous_instance_id: Some(old),+ },+ 2,+ );+ buffer.frontend(+ old,+ FrontendEvent::Started {+ previous_instance_id: None,+ },+ 3,+ );+ buffer.native(NativeEvent::Foreground, 4);+ assert_eq!(buffer.snapshot().current_frontend_instance_id, Some(next));+ assert_eq!(buffer.snapshot().events.len(), 3);+}++#[test]+fn heartbeats_do_not_evict_events_and_history_is_bounded() {+ let mut buffer = EventBuffer::default();+ let id = Uuid::new_v4();+ buffer.frontend(+ id,+ FrontendEvent::Started {+ previous_instance_id: None,+ },+ 1,+ );+ for time in 2..300 {+ buffer.frontend(+ id,+ FrontendEvent::Heartbeat {+ visible: true,+ online: true,+ },+ time,+ );+ }+ assert_eq!(buffer.snapshot().events.len(), 1);+ assert_eq!(+ buffer.snapshot().heartbeat.map(|event| event.timestamp_ms),+ Some(299)+ );+ for time in 300..500 {+ buffer.native(NativeEvent::MemoryWarning, time);+ }+ let snapshot = buffer.snapshot();+ assert_eq!(snapshot.events.len(), CAPACITY);+ assert_eq!(snapshot.dropped, 73);+ assert_eq!(+ snapshot.events.first().map(|event| event.timestamp_ms),+ Some(372)+ );+}++#[test]+fn logout_erases_identifiers_and_ignores_late_callbacks() {+ let mut buffer = EventBuffer::default();+ let old = Uuid::new_v4();+ let next = Uuid::new_v4();+ buffer.frontend(+ old,+ FrontendEvent::Started {+ previous_instance_id: None,+ },+ 1,+ );+ buffer.frontend(old, FrontendEvent::Visibility { visible: true }, 2);+ buffer.frontend(old, FrontendEvent::AccountCleared, 3);+ buffer.frontend(old, FrontendEvent::Visibility { visible: true }, 4);+ assert_eq!(buffer.snapshot().events.len(), 1);+ buffer.frontend(+ next,+ FrontendEvent::Started {+ previous_instance_id: Some(old),+ },+ 5,+ );+ buffer.frontend(old, FrontendEvent::Visibility { visible: false }, 6);+ assert_eq!(buffer.snapshot().events.len(), 2);+ buffer.native(NativeEvent::WebContentTerminated, 7);+ assert_eq!(+ buffer+ .snapshot()+ .events+ .last()+ .and_then(|event| event.frontend_instance_id),+ Some(next)+ );+}++#[test]+fn native_events_and_previous_heartbeat_survive_until_next_document_reads_them() {+ let mut buffer = EventBuffer::default();+ let old = Uuid::new_v4();+ buffer.frontend(+ old,+ FrontendEvent::Started {+ previous_instance_id: None,+ },+ 1,+ );+ buffer.frontend(+ old,+ FrontendEvent::Heartbeat {+ visible: true,+ online: true,+ },+ 2,+ );+ buffer.native(NativeEvent::Background, 3);+ buffer.native(NativeEvent::MemoryWarning, 4);+ buffer.native(NativeEvent::WebContentTerminated, 5);+ let recovery = buffer.snapshot();+ buffer.frontend(+ Uuid::new_v4(),+ FrontendEvent::Started {+ previous_instance_id: Some(old),+ },+ 6,+ );+ assert_eq!(recovery.events.len(), 4);+ assert_eq!(recovery.heartbeat.map(|event| event.timestamp_ms), Some(2));+ assert!(buffer.snapshot().heartbeat.is_none());+}++/// UPDATE_NATIVE_DIAGNOSTIC_TYPES=1 cargo test ... diagnostic_wire_types+#[test]+fn diagnostic_wire_types() {+ let generated = specta_typescript::Typescript::default()+ .export(+ &specta::Types::default().register::<EventSnapshot>(),+ specta_serde::Format,+ )+ .expect("export diagnostic wire types");+ let generated = generated+ .lines()+ .map(str::trim_end)+ .collect::<Vec<_>>()+ .join("\n")+ + "\n";+ let output = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../src/observability/generated/native-diagnostics.ts");+ if std::env::var_os("UPDATE_NATIVE_DIAGNOSTIC_TYPES").is_some() {+ std::fs::create_dir_all(output.parent().expect("generated directory"))+ .expect("create directory");+ std::fs::write(&output, &generated).expect("write types");+ }+ assert_eq!(+ std::fs::read_to_string(output).expect("generated types"),+ generated+ );+}diff --git a/apps/web/tauri/src-tauri/src/diagnostics/ios.rs b/apps/web/tauri/src-tauri/src/diagnostics/ios.rsnew file mode 100644index 0000000000..d735866fde--- /dev/null+++ b/apps/web/tauri/src-tauri/src/diagnostics/ios.rs@@ -0,0 +1,35 @@+//! UIKit sends this warning to the host even when WebContent is unresponsive.++use std::{cell::RefCell, ptr::NonNull};++use block2::RcBlock;+use objc2::{rc::Retained, runtime::ProtocolObject};+use objc2_foundation::{NSNotification, NSNotificationCenter, NSObjectProtocol};+use objc2_ui_kit::UIApplicationDidReceiveMemoryWarningNotification;+use tauri::Manager;++use super::{Diagnostics, events::NativeEvent};++thread_local! {+ // Registration is installed once on the UI thread and retained for the host lifetime.+ static OBSERVER: RefCell<Option<Retained<ProtocolObject<dyn NSObjectProtocol>>>> = const { RefCell::new(None) };+}++pub fn observe_memory_warnings<R: tauri::Runtime>(app: tauri::AppHandle<R>) {+ let callback = RcBlock::new(move |_: NonNull<NSNotification>| {+ if let Some(state) = app.try_state::<Diagnostics>() {+ state.record_native_event(NativeEvent::MemoryWarning);+ }+ });+ // SAFETY: No object filter or operation queue. The callback captures only+ // the Send + Sync AppHandle and uses the diagnostic buffer's mutex.+ let observer = unsafe {+ NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(+ Some(UIApplicationDidReceiveMemoryWarningNotification),+ None,+ None,+ &callback,+ )+ };+ OBSERVER.with(|slot| *slot.borrow_mut() = Some(observer));+}diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex 4f07902628..42d5b8ff6b 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -357,6 +357,7 @@ pub fn run_with(builder: tauri::Builder<AppRuntime>) {desktop_update::get_native_update_status,desktop_update::restart_native_update,diagnostics::read_desktop_diagnostics,+ diagnostics::record_frontend_diagnostic,#[cfg(target_os = "linux")]linux_notification::send_linux_notification,#[cfg(target_os = "linux")]@@ -480,6 +481,9 @@ pub fn run_with(builder: tauri::Builder<AppRuntime>) {..} => {tracing::debug!(window_label = %label, "mobile window resumed");+ if let Some(state) = app_handle.try_state::<diagnostics::Diagnostics>() {+ state.record_native_event(diagnostics::events::NativeEvent::Foreground);+ }let app = app_handle.clone();tauri::async_runtime::spawn(async move {if let Err(e) = retry_waiting_for_wifi(&app).await {@@ -509,6 +513,15 @@ pub fn run_with(builder: tauri::Builder<AppRuntime>) {});}}+ #[cfg(mobile)]+ RunEvent::WindowEvent {+ event: tauri::WindowEvent::Suspended,+ ..+ } => {+ if let Some(state) = app_handle.try_state::<diagnostics::Diagnostics>() {+ state.record_native_event(diagnostics::events::NativeEvent::Background);+ }+ }#[cfg(desktop)]RunEvent::ExitRequested { api, .. } => {window_state::save(app_handle);diff --git a/apps/web/tauri/src-tauri/src/share_target/ios.rs b/apps/web/tauri/src-tauri/src/share_target/ios.rsindex 82dcd6027a..fec6848b80 100644--- a/apps/web/tauri/src-tauri/src/share_target/ios.rs+++ b/apps/web/tauri/src-tauri/src/share_target/ios.rs@@ -23,9 +23,9 @@ struct ShareFilesReadyPayload {/// exchange files between the Share Extension and the main app./// Calls NSFileManager directly via the objc2 runtime — no FFI to main.mm needed.fn ios_app_group_container_path() -> Option<String> {- use objc2::rc::autoreleasepool;- use objc2::runtime::AnyObject;- use objc2::{class, msg_send};+ use objc2_legacy::rc::autoreleasepool;+ use objc2_legacy::runtime::AnyObject;+ use objc2_legacy::{class, msg_send};use std::ffi::{CStr, CString};use std::os::raw::c_char;diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.jsonindex ca3ad03159..c6908f4741 100644--- a/apps/web/tauri/src-tauri/tauri.android.conf.json+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json@@ -2,7 +2,7 @@"version": "2.5.0","bundle": {"android": {- "versionCode": 11+ "versionCode": 12}},"$schema": "https://schema.tauri.app/config/2",