Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(observability): name what a terminated iOS web view was opening (#8513)

teocf3f50c979e2
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index a7aa5a0879..b9ae13a0fa 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -147,7 +147,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`, `native_diagnostic_recovered`, and the shared `frontend_instance_id`; use `reloadApp(reason)` for frontend reloads and keep breadcrumbs content-free. Treat `previous_document_*` checkpoints as last-observed lifecycle evidence, never a crash verdict; clear them on logout. See [frontend checkpoints](docs/native-reload-diagnostics.md) and `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. Treat `previous_document_*` checkpoints as last-observed lifecycle evidence, never a crash verdict; clear them on logout. `previous_document_last_*` comes from the native navigation breadcrumb (route and entity type, never ids). See [frontend checkpoints](docs/native-reload-diagnostics.md) and `tauri/src-tauri/README.md`.
- Inline agent steps reuse the session code-execution query for live SDK operation
names; 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/docs/native-reload-diagnostics.md b/apps/web/docs/native-reload-diagnostics.md
index a2bb46a682..9d01a8e891 100644
--- a/apps/web/docs/native-reload-diagnostics.md
+++ b/apps/web/docs/native-reload-diagnostics.md
@@ -21,11 +21,15 @@ not proof a document was later restored. This checkpoint cannot identify why
WebKit terminated; correlate it with the native counters and device diagnostics.
When investigating a repeat, compare the native launch ID, termination counter,
-reload request/dispatch markers, and the recovered heartbeat/lifecycle events.
-The same native launch with a larger termination counter confirms WebContent
+reload request/dispatch markers, and the recovered heartbeat/lifecycle events. On new binaries,
+`previous_document_last_*` names the route and entity type the document was
+navigating to. The same native launch with a larger termination counter confirms WebContent
recovery. A memory warning supports pressure but does not identify the kill reason.
-For the OS reason, obtain the incident's iPhone Analytics Data report: a matching
-WebKit WebContent crash report or JetsamEvent, including its process and timestamp.
+For the OS reason, obtain the incident's iPhone Analytics Data report (Settings →
+Privacy & Security → Analytics & Improvements → Analytics Data): a matching
+`com.apple.WebKit.WebContent-…` crash report, or a `JetsamEvent-…` listing
+`com.apple.WebKit.WebContent` as killed, near the termination timestamp. On
+macOS, use Console → Crash Reports.
Do not use the host app's memory footprint as the renderer's memory footprint;
WebContent runs in a separate process. A change in native launch ID alone cannot
distinguish a crash, OS termination, or the user relaunching the app.
diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
index 4d78269f0e..e6002846ec 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
@@ -27,6 +27,7 @@ import {
type SplitRouterMiddlewareContext,
type SplitRouterMiddlewareResult,
} from '@app/lib/split-router';
+import { recordNavigationBreadcrumb } from '@app/observability/navigation-breadcrumb';
import { paneRootMatch } from '@app/routes/app-route';
import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
@@ -281,5 +282,7 @@ export function createAppSplitRouterMiddleware(
(context) => redirectLegacyRoutes(context, state),
redirectLegacyCrmPipeline,
migrateLegacySearch,
+ // Last, so it records the entry that remains after every redirect.
+ recordNavigationBreadcrumb,
];
}
diff --git a/apps/web/src/observability/generated/native-diagnostics.ts b/apps/web/src/observability/generated/native-diagnostics.ts
index 911cffdee1..cfb68b6573 100644
--- a/apps/web/src/observability/generated/native-diagnostics.ts
+++ b/apps/web/src/observability/generated/native-diagnostics.ts
@@ -1,4 +1,7 @@
// This file has been generated by Specta. Do not edit this file manually.
+/** A route id or entity type defined in app code, never user text. */
+export type CodeName = string;
+
export type DiagnosticEvent = {
sequence: number,
timestampMs: number,
@@ -18,9 +21,16 @@ export type EventSnapshot = {
/** 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 } |
+/**
+ * A pane started navigating; recorded before the destination loads so a
+ * termination while it loads still names it.
+ */
+{ kind: "navigated"; cause: NavigationCause; route: CodeName; from_route: CodeName | null; entity_type: CodeName | null } |
/** 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 NavigationCause = "initial" | "external" | "navigate" | "history" | "search";
+
export type ReloadReason = "cache_replaced_automatic" | "update_accepted" | "failed_load_recovery" | "user_recovery" | "logout";
diff --git a/apps/web/src/observability/native-lifecycle.test.ts b/apps/web/src/observability/native-lifecycle.test.ts
index a7d959efac..1a6d489f59 100644
--- a/apps/web/src/observability/native-lifecycle.test.ts
+++ b/apps/web/src/observability/native-lifecycle.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import type { DesktopSnapshot } from './desktop';
import { frontendInstanceId } from './frontend-instance';
import {
+ previousDocumentAttributes,
recordNativeWebviewStart,
reportRecoveredEvents,
} from './native-lifecycle';
@@ -159,6 +160,90 @@ describe('native WebView startup diagnostics', () => {
expect(telemetry.span.end).toHaveBeenCalledOnce();
});
+ it('names what the terminated document last opened and its last memory warning', () => {
+ const snapshot: DesktopSnapshot = {
+ identity: {
+ instanceId: 'host',
+ nativeVersion: '2.5',
+ os: 'ios',
+ hostPid: 1,
+ recordingId: null,
+ tracesUrl: null,
+ },
+ samples: [],
+ droppedSamples: 0,
+ recentEvents: {
+ currentFrontendInstanceId: 'previous',
+ events: [
+ {
+ sequence: 1,
+ timestampMs: 100,
+ frontendInstanceId: 'previous',
+ event: {
+ kind: 'navigated',
+ cause: 'navigate',
+ route: 'view-search',
+ from_route: 'view-home',
+ entity_type: null,
+ },
+ },
+ {
+ sequence: 2,
+ timestampMs: 200,
+ frontendInstanceId: 'previous',
+ event: {
+ kind: 'navigated',
+ cause: 'navigate',
+ route: 'legacy-content',
+ from_route: 'view-search',
+ entity_type: 'channel',
+ },
+ },
+ {
+ sequence: 3,
+ timestampMs: 250,
+ frontendInstanceId: 'previous',
+ event: { kind: 'memory_warning' },
+ },
+ {
+ sequence: 4,
+ timestampMs: 300,
+ frontendInstanceId: 'previous',
+ event: { kind: 'web_content_terminated' },
+ },
+ {
+ sequence: 5,
+ timestampMs: 400,
+ frontendInstanceId: 'older',
+ event: {
+ kind: 'navigated',
+ cause: 'history',
+ route: 'agents',
+ from_route: null,
+ entity_type: null,
+ },
+ },
+ ],
+ heartbeat: null,
+ dropped: 0,
+ memoryWarningReporting: true,
+ },
+ };
+ expect(previousDocumentAttributes(snapshot, 'previous')).toEqual({
+ previous_document_last_route: 'legacy-content',
+ previous_document_last_from_route: 'view-search',
+ previous_document_last_entity_type: 'channel',
+ previous_document_last_navigation_cause: 'navigate',
+ previous_document_last_navigation_at_ms: 200,
+ previous_document_last_memory_warning_at_ms: 250,
+ });
+ expect(
+ Object.values(previousDocumentAttributes(snapshot, undefined)).every(
+ (value) => value === undefined
+ )
+ ).toBe(true);
+ });
+
it('reports missing native support as unknown, rather than zero terminations', () => {
vi.spyOn(performance, 'getEntriesByType').mockReturnValue([]);
recordNativeWebviewStart(undefined);
diff --git a/apps/web/src/observability/native-lifecycle.ts b/apps/web/src/observability/native-lifecycle.ts
index 0762e7b7da..edc9c60bb9 100644
--- a/apps/web/src/observability/native-lifecycle.ts
+++ b/apps/web/src/observability/native-lifecycle.ts
@@ -56,6 +56,7 @@ export function recordNativeWebviewStart(
...attributes,
...documentLifecycle,
...consumeReloadIntent(),
+ ...previousDocumentAttributes(snapshot, recoverableNativeFrontend()),
};
analytics.track('native_webview_started', startupAttributes);
const span = Telemetry.span('native.webview.start');
@@ -67,6 +68,34 @@ export function recordNativeWebviewStart(
reportRecoveredEvents(snapshot, recoverableNativeFrontend());
}
+/** What the document this one replaced last opened, and its last memory warning. */
+export function previousDocumentAttributes(
+ snapshot: DesktopSnapshot | undefined,
+ previousFrontend: string | undefined
+) {
+ const events =
+ snapshot?.recentEvents?.events.filter(
+ (entry) =>
+ previousFrontend !== undefined &&
+ entry.frontendInstanceId === previousFrontend
+ ) ?? [];
+ // Events are in sequence order; findLast is missing before iOS 15.4.
+ const latest = (kind: string) =>
+ [...events].reverse().find((entry) => entry.event.kind === kind);
+ const navigation = latest('navigated');
+ const breadcrumb =
+ navigation?.event.kind === 'navigated' ? navigation.event : undefined;
+ return {
+ previous_document_last_route: breadcrumb?.route,
+ previous_document_last_from_route: breadcrumb?.from_route ?? undefined,
+ previous_document_last_entity_type: breadcrumb?.entity_type ?? undefined,
+ previous_document_last_navigation_cause: breadcrumb?.cause,
+ previous_document_last_navigation_at_ms: navigation?.timestampMs,
+ previous_document_last_memory_warning_at_ms:
+ latest('memory_warning')?.timestampMs,
+ };
+}
+
/** Recovered entries retain source identity/time; current signals identify their uploader. */
export function reportRecoveredEvents(
snapshot: DesktopSnapshot,
diff --git a/apps/web/src/observability/navigation-breadcrumb.test.ts b/apps/web/src/observability/navigation-breadcrumb.test.ts
new file mode 100644
index 0000000000..1295094e5e
--- /dev/null
+++ b/apps/web/src/observability/navigation-breadcrumb.test.ts
@@ -0,0 +1,99 @@
+import {
+ createRoutesManifest,
+ decodePane,
+ type Entry,
+ type SplitRoutes,
+} from '@app/lib/split-router';
+import { paneRoute } from '@app/routes/app-route';
+import {
+ agentsRoute,
+ appRoute,
+ legacyContentRoute,
+ notFoundRoute,
+ searchRoute,
+} from '@app/routes/routes';
+import { describe, expect, it, vi } from 'vitest';
+import { navigationBreadcrumb } from './navigation-breadcrumb';
+
+vi.mock('@components/app/split-layout/componentRegistry', () => ({
+ resolveComponent: vi.fn(() => ({ type: 'mock-component' })),
+}));
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+
+const routes = createRoutesManifest({
+ definitions: [
+ {
+ ...appRoute,
+ children: [searchRoute, agentsRoute, legacyContentRoute, notFoundRoute],
+ },
+ ],
+ defaultRoute: () => paneRoute({ id: searchRoute.id, params: {} }),
+} satisfies SplitRoutes);
+
+const entry = (path: string): Entry => {
+ const route = decodePane(routes, path.split('/').filter(Boolean));
+ if (!route) throw new Error(`no route for ${path}`);
+ return { id: path, location: { route } };
+};
+
+describe('navigation breadcrumbs', () => {
+ it('names a DM opened from Search by route and block type', () => {
+ expect(
+ navigationBreadcrumb({
+ routes,
+ from: entry('search'),
+ to: entry('channel/0196a706-e489-7f6f-92ed-1a1440c62fd1'),
+ cause: 'navigate',
+ })
+ ).toEqual({
+ kind: 'navigated',
+ cause: 'navigate',
+ route: 'legacy-content',
+ from_route: 'view-search',
+ entity_type: 'channel',
+ });
+ });
+
+ it('takes the type of a non-block claim from its namespace', () => {
+ expect(
+ navigationBreadcrumb({
+ routes,
+ from: undefined,
+ to: entry('agents/01a1609c-18a6-7077-a7ee-60c97d9ba8f9'),
+ cause: 'external',
+ })
+ ).toMatchObject({
+ route: 'agents',
+ from_route: null,
+ entity_type: 'agent',
+ });
+ });
+
+ it('reports no entity for views and unrecognised ids', () => {
+ expect(
+ navigationBreadcrumb({
+ routes,
+ from: undefined,
+ to: entry('search'),
+ cause: 'initial',
+ })
+ ).toMatchObject({ route: 'view-search', entity_type: null });
+ expect(
+ navigationBreadcrumb({
+ routes,
+ from: undefined,
+ to: entry('agents/not-a-uuid'),
+ cause: 'navigate',
+ })
+ ).toMatchObject({ route: 'agents', entity_type: null });
+ });
+});
diff --git a/apps/web/src/observability/navigation-breadcrumb.ts b/apps/web/src/observability/navigation-breadcrumb.ts
new file mode 100644
index 0000000000..6b506e328d
--- /dev/null
+++ b/apps/web/src/observability/navigation-breadcrumb.ts
@@ -0,0 +1,67 @@
+import {
+ claimOf,
+ isSafeName,
+ type SplitRouterMiddlewareContext,
+} from '@app/lib/split-router';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { isTauri } from '@core/util/platform';
+import { Telemetry } from '@macro-inc/observability';
+import type { FrontendEvent } from './generated/native-diagnostics';
+import { recordNativeDiagnostic } from './native-diagnostics';
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+type Navigated = Extract<FrontendEvent, { kind: 'navigated' }>;
+
+/** The native schema rejects the whole event on one bad field, which also
+ * disables diagnostics for the document, so drop anything it would refuse. */
+function codeName(value: string | undefined): string | null {
+ return value !== undefined && isSafeName(value) ? value : null;
+}
+
+/** The type of entity a route claims; views such as Search claim no entity. */
+function claimedEntityType(claim: string | undefined): string | null {
+ const [namespace, ...rest] = claim?.split(':') ?? [];
+ const [type, id] =
+ namespace === 'block'
+ ? [rest[0], rest.slice(1).join(':')]
+ : [namespace, rest.join(':')];
+ return UUID.test(id ?? '') ? codeName(type) : null;
+}
+
+export function navigationBreadcrumb({
+ routes,
+ from,
+ to,
+ cause,
+}: Pick<SplitRouterMiddlewareContext, 'routes' | 'from' | 'to' | 'cause'>):
+ | Navigated
+ | undefined {
+ const route = codeName(to.location.route.matches.at(-1)?.id);
+ if (!route) return;
+ return {
+ kind: 'navigated',
+ cause,
+ route,
+ from_route: codeName(from?.location.route.matches.at(-1)?.id),
+ entity_type: claimedEntityType(claimOf(routes, to.location.route)),
+ };
+}
+
+/**
+ * Records where a pane is going in the native host before the destination
+ * loads, and flushes telemetry still queued in this document, so both survive
+ * a WebContent termination while it loads. Never changes the navigation.
+ */
+export function recordNavigationBreadcrumb(
+ context: SplitRouterMiddlewareContext
+): undefined {
+ if (!isTauri()) return;
+ try {
+ const breadcrumb = navigationBreadcrumb(context);
+ if (breadcrumb) recordNativeDiagnostic(breadcrumb);
+ } catch (error) {
+ Telemetry.error(error, { surface: 'navigation-breadcrumb' });
+ }
+ fireAndForget(Telemetry.flush(), 'navigation-telemetry-flush');
+}
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 5c82e78b59..37c635172e 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -84,10 +84,31 @@ 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.
+frontend visibility/connectivity, explicit reload requests, and pane
+navigations. Keep reload diagnostics at document/native lifecycle boundaries and
+pane navigation; 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.
+
+The last split-router middleware records `navigated` when a pane starts
+navigating, before its destination loads: the navigation cause, the destination
+and previous route ids, and the claimed entity type (`channel`, `md`, `agent`, …)
+when the route claims an entity by UUID. Native rejects anything but code-defined
+names, and the frontend drops a value it would reject, since a rejected command
+disables diagnostics for the document. The entity's id is deliberately absent;
+the restored URL on `native_webview_started` usually carries it. Each navigation
+in the native app also flushes queued OTel spans, so the work leading up to an
+open is exported before a termination while it loads.
+
+From this buffer, `native_webview_started` names the replaced document's last
+navigation: `previous_document_last_route`, `previous_document_last_from_route`,
+`previous_document_last_entity_type`, `previous_document_last_navigation_cause`,
+and `previous_document_last_navigation_at_ms`, plus
+`previous_document_last_memory_warning_at_ms` for its last iOS memory warning.
+Compare those timestamps with `native_last_termination_ms`. They need the same
+recovery lease as replay below. The other `previous_document_*` fields come from
+the session-storage [frontend checkpoint](../../docs/native-reload-diagnostics.md),
+which also covers older binaries but records counts, not routes.
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.
diff --git a/apps/web/tauri/src-tauri/src/diagnostics/events.rs b/apps/web/tauri/src-tauri/src/diagnostics/events.rs
index 1d26a58253..19c48fef57 100644
--- a/apps/web/tauri/src-tauri/src/diagnostics/events.rs
+++ b/apps/web/tauri/src-tauri/src/diagnostics/events.rs
@@ -18,6 +18,47 @@ pub enum ReloadReason {
Logout,
}
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[cfg_attr(test, derive(specta::Type))]
+#[serde(rename_all = "snake_case")]
+pub enum NavigationCause {
+ Initial,
+ External,
+ Navigate,
+ History,
+ Search,
+}
+
+/// A route id or entity type defined in app code, never user text.
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[cfg_attr(test, derive(specta::Type))]
+#[serde(try_from = "String", into = "String")]
+pub struct CodeName(String);
+
+impl From<CodeName> for String {
+ fn from(name: CodeName) -> Self {
+ name.0
+ }
+}
+
+impl TryFrom<String> for CodeName {
+ type Error = &'static str;
+
+ fn try_from(value: String) -> Result<Self, Self::Error> {
+ let mut chars = value.chars();
+ let valid = value.len() <= 64
+ && chars
+ .next()
+ .is_some_and(|first| first.is_ascii_alphabetic())
+ && chars.all(|next| next.is_ascii_alphanumeric() || next == '-' || next == '_');
+ if valid {
+ Ok(Self(value))
+ } else {
+ Err("expected a code-defined name")
+ }
+ }
+}
+
/// Closed schema: never accept arbitrary text, URLs, or message content.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(specta::Type))]
@@ -40,6 +81,14 @@ pub enum FrontendEvent {
reload_id: Uuid,
reason: ReloadReason,
},
+ /// A pane started navigating; recorded before the destination loads so a
+ /// termination while it loads still names it.
+ Navigated {
+ cause: NavigationCause,
+ route: CodeName,
+ from_route: Option<CodeName>,
+ entity_type: Option<CodeName>,
+ },
/// Clears identifiers before another account can take over the WebView.
AccountCleared,
}
diff --git a/apps/web/tauri/src-tauri/src/diagnostics/events/test.rs b/apps/web/tauri/src-tauri/src/diagnostics/events/test.rs
index dba56b752b..50ce0b5b13 100644
--- a/apps/web/tauri/src-tauri/src/diagnostics/events/test.rs
+++ b/apps/web/tauri/src-tauri/src/diagnostics/events/test.rs
@@ -140,6 +140,45 @@ fn native_events_and_previous_heartbeat_survive_until_next_document_reads_them()
assert!(buffer.snapshot().heartbeat.is_none());
}
+#[test]
+fn navigation_breadcrumbs_accept_only_code_defined_names() {
+ let accepted: FrontendEvent = serde_json::from_value(serde_json::json!({
+ "kind": "navigated",
+ "cause": "external",
+ "route": "legacy-content",
+ "from_route": "view-search",
+ "entity_type": "channel",
+ }))
+ .expect("code-defined navigation");
+ assert!(matches!(
+ accepted,
+ FrontendEvent::Navigated {
+ entity_type: Some(_),
+ ..
+ }
+ ));
+
+ for (field, value) in [
+ ("route", "/search/~/channel/hello world"),
+ ("entity_type", "Julia's DM"),
+ ("from_route", ""),
+ ("route", "0196a706-e489-7f6f-92ed-1a1440c62fd1"),
+ ] {
+ let mut event = serde_json::json!({
+ "kind": "navigated",
+ "cause": "navigate",
+ "route": "view-search",
+ "from_route": null,
+ "entity_type": null,
+ });
+ event[field] = serde_json::Value::from(value);
+ assert!(
+ serde_json::from_value::<FrontendEvent>(event).is_err(),
+ "{field} accepted {value:?}"
+ );
+ }
+}
+
/// UPDATE_NATIVE_DIAGNOSTIC_TYPES=1 cargo test ... diagnostic_wire_types
#[test]
fn diagnostic_wire_types() {