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.

fix(navigation): release obsolete view state and diagnose native reloads (#8533)

Peter Chinman828570e8f052
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index f13fab5577..ffc3db6675 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -119,6 +119,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
- Mobile dock search owns transient category/mode state in `features/command/mobile`; reuse the shared entity source and explicit full-text adapter rather than overlaying the dock query on view tabs or saved facets. See `docs/agent-guide/search.md` at the repository root.
- Include known Macro users in typed All/People name searches without requiring a DM or CRM contact; resolve a matching person to their existing one-to-one DM while preserving name/email matching.
- Keep mobile search sessions, result order, loaded rows, and scroll state with their Search history entry; preserve order before opening a result so viewedAt updates cannot move it on Back. Refresh row data in place and append later pages. Scope saved rows and scroll measurements to their account and reset result adapters/scrollers on account changes. Query/category changes rerank; a fresh dock search supplies a new session ID in Search's route state, including when reusing a native pane.
+- Release saved entry state when its router entry is replaced, pruned, or closed; retain only the latest split event so obsolete payloads cannot keep result lists alive. Preserve snapshots for entries still reachable through Back/Forward.
- Keep Quick Access cache availability reactive to the GraphQL rollout flag; it can arrive after the provider mounts, and email has no legacy source fallback.
- Virtualize mobile name results like desktop Command Menu; local Quick Access sources are unbounded, and mounting them all stalls iOS keyboard focus during layout. Load additional search pages near the scroll end instead of reserving a paging bar.
- Reconcile mobile full-text rows by entity ID so appending a page preserves DOM rows and scroll position; restore after responsive row measurement and disable browser scroll anchoring so layout changes cannot override the saved history offset.
@@ -134,7 +135,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. 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. 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`.
- 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
new file mode 100644
index 0000000000..a2bb46a682
--- /dev/null
+++ b/apps/web/docs/native-reload-diagnostics.md
@@ -0,0 +1,34 @@
+# Frontend checkpoints for native reloads
+
+The frontend also saves one content-free document checkpoint in session storage,
+including on older binaries. It updates at startup, router commits, visibility
+changes, `pagehide`, and same-document bfcache restoration; there is no polling or native
+IPC. The next startup's `previous_document_*` properties report the last recorded
+visibility and whether `pagehide` was observed, including its `persisted` bit.
+Navigation checkpoints include commit, pane, history-entry, and saved-entry-state
+counts. Commits in one JavaScript turn coalesce into one checkpoint after pane
+cleanup; these are not click counts. No routes, result rows, or entry IDs are
+stored. Counts can reveal growing retained navigation state, but do not measure
+WebContent memory or establish a memory-related termination.
+Missing, malformed, future, or more-than-24-hour-old checkpoints report unavailable
+coverage. Logout clears the checkpoint and stops its listeners. A document that
+has lost checkpoint ownership cannot overwrite its successor's data.
+If that older document resumes from bfcache, it invalidates the checkpoint so
+the next startup reports unknown instead of attributing its exit to a successor.
+These are last-observed lifecycle signals: missing `pagehide` supports an abrupt
+exit hypothesis but does not prove a crash, and `persisted` is bfcache intent,
+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
+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.
+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.
+
+For native buffers, reload markers, termination counters, and binary-release
+requirements, see [native reload diagnostics](../tauri/src-tauri/README.md#diagnosing-unexpected-webview-reloads).
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.ts
index e7b6ea3342..1f33a4014f 100644
--- a/apps/web/src/components/app/split-layout/layoutManager.ts
+++ b/apps/web/src/components/app/split-layout/layoutManager.ts
@@ -10,6 +10,7 @@ import type {
SplitRouter,
SplitSearchUpdate,
} from '@app/lib/split-router';
+import { trackNavigationLifecycle } from '@app/observability/navigation-lifecycle';
import type {
BlockAlias,
BlockAliasContext,
@@ -267,9 +268,7 @@ export type SplitEventWithType =
| ({
type: SplitEvent.ContentChange;
} & SplitEventPayload[SplitEvent.ContentChange])
- | ({
- type: SplitEvent.ReturnFocus;
- } & SplitEventPayload[SplitEvent.ReturnFocus]);
+ | { type: SplitEvent.ReturnFocus };
/**
* If a split layout helper passes and aliased block type, make sure to wrap
@@ -323,7 +322,7 @@ export type SplitManager = {
readonly activeSplitId: Accessor<SplitId | undefined>;
readonly activeSplit: Accessor<SplitHandle | undefined>;
readonly lastActiveSplitId: Accessor<SplitId | undefined>;
- readonly events: Accessor<SplitEventWithType>;
+ readonly events: Accessor<SplitEventWithType | undefined>;
readonly resizeContext: Accessor<ResizeZoneCtx | undefined>;
// methods
@@ -583,7 +582,6 @@ export function createSplitLayout(
activeSplitId: SplitId | undefined;
lastActiveSplitId: SplitId | undefined;
spotlightId: SplitId | undefined;
- events: SplitEventWithType[];
popovers: Map<
string,
{
@@ -600,9 +598,9 @@ export function createSplitLayout(
activeSplitId: undefined,
lastActiveSplitId: undefined,
spotlightId: undefined,
- events: [],
popovers: new Map(),
});
+ const [lastEvent, setLastEvent] = createSignal<SplitEventWithType>();
const contentInstances = createContentInstanceRegistry();
const unregisterContentInstances = contentInstances.register(() => [
@@ -720,10 +718,9 @@ export function createSplitLayout(
type: SplitEvent,
payload: SplitEventPayload[SplitEvent]
) {
- setState('events', (prev) => [
- ...prev,
- { type, ...payload } as SplitEventWithType,
- ]);
+ // Consumers read only the latest event. Keeping older payloads retains
+ // the departed views' params and captured state for the whole document.
+ setLastEvent({ type, ...payload } as SplitEventWithType);
}
const findSplitById = (id: SplitId) => state.splits.find((s) => s.id === id);
@@ -1411,6 +1408,17 @@ export function createSplitLayout(
// The router owns each pane's history; splits mirror what its panes show.
const paneSplits = mapArray(router.panes, (pane) => {
const id = splitOf(pane);
+ let entryIds = new Set<string>();
+
+ createComputed(() => {
+ const retained = new Set(
+ router.history(pane)?.entries.map((entry) => entry.id)
+ );
+ for (const entryId of entryIds) {
+ if (!retained.has(entryId)) entryStates.delete(entryId);
+ }
+ entryIds = retained;
+ });
createComputed(() => {
const entry = router.entry(pane);
@@ -1431,6 +1439,7 @@ export function createSplitLayout(
onCleanup(() => {
unregisterGuard();
+ for (const entryId of entryIds) entryStates.delete(entryId);
untrack(() => dropSplit(id));
});
@@ -1442,7 +1451,7 @@ export function createSplitLayout(
untrack(() => orderSplits(ids));
});
- const lastEvent = createMemo(() => state.events[state.events.length - 1]);
+ trackNavigationLifecycle(router, () => entryStates.size);
const tabTitle = () => {
if (state.activeSplitId === undefined) return undefined;
diff --git a/apps/web/src/components/app/split-layout/splitFocusTracker.ts b/apps/web/src/components/app/split-layout/splitFocusTracker.ts
index 57ff0ab5bb..d99a6a08d0 100644
--- a/apps/web/src/components/app/split-layout/splitFocusTracker.ts
+++ b/apps/web/src/components/app/split-layout/splitFocusTracker.ts
@@ -169,6 +169,7 @@ export function createSplitFocusTracker(props: {
on(
() => props.splitManager.events(),
(newEvent) => {
+ if (!newEvent) return;
if (focusTimeout) {
clearTimeout(focusTimeout);
}
diff --git a/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts b/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts
index d4e5c2fe44..7a3d89385f 100644
--- a/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts
+++ b/apps/web/src/components/app/split-layout/tests/stacked-panes.test.ts
@@ -9,6 +9,10 @@ import {
type SplitRoutes,
} from '@app/lib/split-router';
import { firstChangedDepth } from '@app/lib/split-router/routes/queries';
+import {
+ clearDocumentLifecycle,
+ startDocumentLifecycle,
+} from '@app/observability/document-lifecycle';
import { paneRoute } from '@app/routes/app-route';
import {
appRoute,
@@ -150,6 +154,7 @@ function setup(url: string, stacked = true) {
}
afterEach(() => {
+ clearDocumentLifecycle();
cleanup();
SearchState.close();
dispose?.();
@@ -157,6 +162,74 @@ afterEach(() => {
});
describe('stacked panes', () => {
+ it('releases saved state when entries are replaced and panes are removed', async () => {
+ startDocumentLifecycle();
+ const { manager, router } = setup('/search');
+ const pane = router.panes()[0]!;
+ for (let index = 0; index < 100; index++) {
+ const handle = manager.activeSplit()!;
+ const stop = handle.registerEntryStateCaptor('rows', () => [index]);
+ handle.captureEntryState();
+ await router.navigatePane(
+ pane,
+ index % 2 === 0 ? '/settings' : '/search',
+ { replace: true }
+ );
+ stop();
+ }
+ await Promise.resolve();
+ expect(
+ JSON.parse(sessionStorage.getItem('macro-document-lifecycle')!).navigation
+ ).toMatchObject({
+ paneCount: 1,
+ historyEntryCount: 1,
+ savedEntryStateCount: 0,
+ });
+ const handle = manager.activeSplit()!;
+ handle.registerEntryStateCaptor('rows', () => ['retained until close']);
+ handle.captureEntryState();
+ manager.openWithSplit(documents);
+ await router.remove(pane);
+ await Promise.resolve();
+
+ expect(
+ JSON.parse(sessionStorage.getItem('macro-document-lifecycle')!).navigation
+ ).toMatchObject({
+ paneCount: 1,
+ historyEntryCount: 1,
+ savedEntryStateCount: 0,
+ });
+ });
+
+ it('keeps reachable snapshots and releases a discarded forward branch', async () => {
+ startDocumentLifecycle();
+ const { manager, router } = setup('/search');
+ const pane = router.panes()[0]!;
+ const handle = manager.activeSplit()!;
+ const stopSearch = handle.registerEntryStateCaptor('rows', () => [
+ 'search',
+ ]);
+ await router.navigatePane(pane, '/settings');
+ stopSearch();
+ const stopSettings = handle.registerEntryStateCaptor('rows', () => [
+ 'settings',
+ ]);
+ handle.goBack();
+ stopSettings();
+ expect(handle.currentEntryState()?.rows).toEqual(['search']);
+ handle.goForward();
+ expect(handle.currentEntryState()?.rows).toEqual(['settings']);
+ handle.goBack();
+ await router.navigatePane(pane, '/drive');
+ await Promise.resolve();
+ expect(handle.canGoForward()).toBe(false);
+ expect(
+ JSON.parse(sessionStorage.getItem('macro-document-lifecycle')!).navigation
+ ).toMatchObject({ historyEntryCount: 2, savedEntryStateCount: 1 });
+ handle.goBack();
+ expect(handle.currentEntryState()?.rows).toEqual(['search']);
+ });
+
it('restores search after a second entity evicts its mounted pane', () => {
const { manager, stack, router } = setup('/search');
const handle = manager.activeSplit()!;
diff --git a/apps/web/src/observability/browser.test.ts b/apps/web/src/observability/browser.test.ts
index 7913365e98..b87eeb5969 100644
--- a/apps/web/src/observability/browser.test.ts
+++ b/apps/web/src/observability/browser.test.ts
@@ -1,7 +1,8 @@
import { Telemetry } from '@macro-inc/observability';
-import { beforeEach, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { initializeBrowserObservability } from './browser';
import { readDesktopDiagnostics } from './desktop';
+import { clearDocumentLifecycle } from './document-lifecycle';
import { frontendInstanceId } from './frontend-instance';
import { initializeUiOperationTelemetry } from './ui-operation';
@@ -57,6 +58,8 @@ beforeEach(() => {
});
});
+afterEach(clearDocumentLifecycle);
+
it('explicit native recording overrides the normal enablement gate and exporter before startup', async () => {
vi.mocked(readDesktopDiagnostics).mockResolvedValue({
identity: {
@@ -132,6 +135,15 @@ it('drops browser and extension noise from window errors but reports app errors'
});
it('an older binary without diagnostics still obeys the normal telemetry gate', async () => {
+ sessionStorage.setItem(
+ 'macro-document-lifecycle',
+ JSON.stringify({
+ frontendInstanceId: '11111111-1111-4111-8111-111111111111',
+ startedAtMs: Date.now() - 1000,
+ updatedAtMs: Date.now() - 1000,
+ visible: true,
+ })
+ );
vi.mocked(readDesktopDiagnostics).mockResolvedValue(undefined);
await initializeBrowserObservability();
const config = vi.mocked(Telemetry.init).mock.calls[0][0];
@@ -142,4 +154,44 @@ it('an older binary without diagnostics still obeys the normal telemetry gate',
'app.runtime': 'tauri',
'app.platform': 'desktop',
});
+ expect(startupSpan.setAttr).toHaveBeenCalledWith(
+ 'previous_document_checkpoint_available',
+ true
+ );
+ expect(startupSpan.setAttr).toHaveBeenCalledWith(
+ 'previous_document_pagehide_observed',
+ false
+ );
+});
+
+it('revokes the previous document identity if logout happens while telemetry initializes', async () => {
+ sessionStorage.setItem(
+ 'macro-document-lifecycle',
+ JSON.stringify({
+ frontendInstanceId: '11111111-1111-4111-8111-111111111111',
+ startedAtMs: Date.now() - 1000,
+ updatedAtMs: Date.now() - 1000,
+ visible: true,
+ })
+ );
+ vi.mocked(readDesktopDiagnostics).mockResolvedValue(undefined);
+ const reached = Promise.withResolvers<void>();
+ const resume = Promise.withResolvers<void>();
+ vi.mocked(Telemetry.init).mockImplementation(async () => {
+ reached.resolve();
+ await resume.promise;
+ });
+ const initializing = initializeBrowserObservability();
+ await reached.promise;
+ clearDocumentLifecycle();
+ resume.resolve();
+ await initializing;
+ expect(startupSpan.setAttr).toHaveBeenCalledWith(
+ 'previous_document_checkpoint_available',
+ false
+ );
+ expect(startupSpan.setAttr).not.toHaveBeenCalledWith(
+ 'previous_document_instance_id',
+ expect.anything()
+ );
});
diff --git a/apps/web/src/observability/browser.ts b/apps/web/src/observability/browser.ts
index 42e5157253..8be393d0c6 100644
--- a/apps/web/src/observability/browser.ts
+++ b/apps/web/src/observability/browser.ts
@@ -11,6 +11,7 @@ import {
desktopResourceAttributes,
readDesktopDiagnostics,
} from './desktop';
+import { startDocumentLifecycle } from './document-lifecycle';
import { frontendInstanceId } from './frontend-instance';
import { startNativeDiagnostics } from './native-diagnostics';
import { recordNativeWebviewStart } from './native-lifecycle';
@@ -56,6 +57,8 @@ async function browserTelemetryEnabled(hasExporter: boolean): Promise<boolean> {
/** Initialize browser telemetry and its application-level lifecycle hooks. */
export async function initializeBrowserObservability(): Promise<void> {
+ const lifecycle = isTauri() ? startDocumentLifecycle() : undefined;
+ import.meta.hot?.dispose(() => lifecycle?.dispose());
let browserEnabled = false;
const desktop = await readDesktopDiagnostics();
const disposeNativeDiagnostics = startNativeDiagnostics(desktop);
@@ -105,7 +108,7 @@ export async function initializeBrowserObservability(): Promise<void> {
tracingProvider: (resource, getUserId) =>
createWebTracingProvider(telemetryConfig, resource, getUserId),
});
- if (isTauri()) recordNativeWebviewStart(desktop);
+ if (isTauri()) recordNativeWebviewStart(desktop, lifecycle?.attributes);
if (recording && desktop) {
recording.accept(desktop);
Telemetry.info('Desktop memory recording enabled', {
diff --git a/apps/web/src/observability/document-lifecycle.test.ts b/apps/web/src/observability/document-lifecycle.test.ts
new file mode 100644
index 0000000000..0d19cfb08d
--- /dev/null
+++ b/apps/web/src/observability/document-lifecycle.test.ts
@@ -0,0 +1,243 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import {
+ clearDocumentLifecycle,
+ recordDocumentNavigation,
+ startDocumentLifecycle,
+} from './document-lifecycle';
+import { frontendInstanceId } from './frontend-instance';
+
+const key = 'macro-document-lifecycle';
+const previousId = '11111111-1111-4111-8111-111111111111';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(100_000);
+ sessionStorage.clear();
+});
+
+afterEach(() => {
+ clearDocumentLifecycle();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+it('recovers the last checkpoint after a document disappears without pagehide', () => {
+ sessionStorage.setItem(
+ key,
+ JSON.stringify({
+ frontendInstanceId: previousId,
+ startedAtMs: 80_000,
+ updatedAtMs: 90_000,
+ visible: true,
+ })
+ );
+ const { attributes } = startDocumentLifecycle();
+ expect(attributes).toMatchObject({
+ previous_document_checkpoint_available: true,
+ previous_document_instance_id: previousId,
+ previous_document_visible: true,
+ previous_document_pagehide_observed: false,
+ });
+ expect(JSON.parse(sessionStorage.getItem(key)!)).toMatchObject({
+ frontendInstanceId,
+ });
+});
+
+it('records visibility and orderly pagehide locally without timers or network calls', () => {
+ startDocumentLifecycle();
+ vi.setSystemTime(101_000);
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+ document.dispatchEvent(new Event('visibilitychange'));
+ window.dispatchEvent(
+ new PageTransitionEvent('pagehide', { persisted: false })
+ );
+ expect(JSON.parse(sessionStorage.getItem(key)!)).toMatchObject({
+ visible: false,
+ updatedAtMs: 101_000,
+ pagehide: { atMs: 101_000, persisted: false },
+ });
+});
+
+it('clears the old pagehide marker when the same document returns from bfcache', () => {
+ startDocumentLifecycle();
+ window.dispatchEvent(
+ new PageTransitionEvent('pagehide', { persisted: true })
+ );
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ expect(JSON.parse(sessionStorage.getItem(key)!)).not.toHaveProperty(
+ 'pagehide'
+ );
+});
+
+it('does not let an old document overwrite its replacement', () => {
+ startDocumentLifecycle();
+ const replacement = JSON.stringify({
+ frontendInstanceId: previousId,
+ startedAtMs: 100_000,
+ updatedAtMs: 100_000,
+ visible: true,
+ });
+ sessionStorage.setItem(key, replacement);
+ window.dispatchEvent(new PageTransitionEvent('pagehide'));
+ document.dispatchEvent(new Event('visibilitychange'));
+ expect(sessionStorage.getItem(key)).toBe(replacement);
+});
+
+it('invalidates another document checkpoint when an older page resumes from bfcache', () => {
+ startDocumentLifecycle();
+ sessionStorage.setItem(
+ key,
+ JSON.stringify({
+ frontendInstanceId: previousId,
+ startedAtMs: 100_000,
+ updatedAtMs: 100_000,
+ visible: true,
+ })
+ );
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ expect(sessionStorage.getItem(key)).toBeNull();
+ expect(
+ startDocumentLifecycle().attributes.previous_document_checkpoint_available
+ ).toBe(false);
+});
+
+it('logout removes the checkpoint and prevents callbacks from recreating it', () => {
+ sessionStorage.setItem(
+ key,
+ JSON.stringify({
+ frontendInstanceId: previousId,
+ startedAtMs: 80_000,
+ updatedAtMs: 90_000,
+ visible: true,
+ })
+ );
+ const lifecycle = startDocumentLifecycle();
+ expect(lifecycle.attributes.previous_document_checkpoint_available).toBe(
+ true
+ );
+ clearDocumentLifecycle();
+ recordDocumentNavigation({
+ paneCount: 1,
+ historyEntryCount: 8,
+ savedEntryStateCount: 7,
+ });
+ expect(lifecycle.attributes.previous_document_checkpoint_available).toBe(
+ false
+ );
+ document.dispatchEvent(new Event('visibilitychange'));
+ window.dispatchEvent(new PageTransitionEvent('pagehide'));
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ expect(sessionStorage.getItem(key)).toBeNull();
+ expect(
+ startDocumentLifecycle().attributes.previous_document_checkpoint_available
+ ).toBe(false);
+});
+
+it('recovers navigation counts without saving route or result content', () => {
+ const first = startDocumentLifecycle();
+ recordDocumentNavigation({
+ paneCount: 2,
+ historyEntryCount: 15,
+ savedEntryStateCount: 4,
+ });
+ recordDocumentNavigation({
+ paneCount: 1,
+ historyEntryCount: 2,
+ savedEntryStateCount: 1,
+ });
+ const saved = JSON.parse(sessionStorage.getItem(key)!);
+ expect(saved.navigation).toEqual({
+ commits: 2,
+ paneCount: 1,
+ historyEntryCount: 2,
+ savedEntryStateCount: 1,
+ });
+ first.dispose();
+ sessionStorage.setItem(
+ key,
+ JSON.stringify({ ...saved, frontendInstanceId: previousId })
+ );
+ expect(startDocumentLifecycle().attributes).toMatchObject({
+ previous_document_navigation_commits: 2,
+ previous_document_pane_count: 1,
+ previous_document_history_entry_count: 2,
+ previous_document_saved_entry_state_count: 1,
+ });
+});
+
+it('an old disposer cannot stop navigation checkpoints for its successor', () => {
+ const first = startDocumentLifecycle();
+ startDocumentLifecycle();
+ first.dispose();
+ recordDocumentNavigation({
+ paneCount: 1,
+ historyEntryCount: 1,
+ savedEntryStateCount: 0,
+ });
+ expect(JSON.parse(sessionStorage.getItem(key)!).navigation?.commits).toBe(1);
+});
+
+it.each([
+ 'invalid json',
+ JSON.stringify({
+ frontendInstanceId: 'not-an-id',
+ startedAtMs: 0,
+ updatedAtMs: 0,
+ visible: true,
+ }),
+ JSON.stringify({
+ frontendInstanceId: previousId,
+ startedAtMs: 110_000,
+ updatedAtMs: 110_000,
+ visible: true,
+ }),
+ JSON.stringify({
+ frontendInstanceId: previousId,
+ startedAtMs: 90_000,
+ updatedAtMs: 80_000,
+ visible: true,
+ }),
+])('reports malformed or future checkpoints as unavailable: %s', (saved) => {
+ sessionStorage.setItem(key, saved);
+ expect(startDocumentLifecycle().attributes).toMatchObject({
+ previous_document_checkpoint_available: false,
+ previous_document_pagehide_observed: undefined,
+ });
+});
+
+it('expires stale checkpoints instead of correlating them to a later incident', () => {
+ sessionStorage.setItem(
+ key,
+ JSON.stringify({
+ frontendInstanceId: previousId,
+ startedAtMs: 0,
+ updatedAtMs: 0,
+ visible: true,
+ })
+ );
+ vi.setSystemTime(25 * 60 * 60_000);
+ expect(
+ startDocumentLifecycle().attributes.previous_document_checkpoint_available
+ ).toBe(false);
+});
+
+it('tolerates unavailable session storage', () => {
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('blocked');
+ });
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('blocked');
+ });
+ expect(
+ startDocumentLifecycle().attributes.previous_document_checkpoint_available
+ ).toBe(false);
+ expect(() =>
+ window.dispatchEvent(new PageTransitionEvent('pagehide'))
+ ).not.toThrow();
+});
diff --git a/apps/web/src/observability/document-lifecycle.ts b/apps/web/src/observability/document-lifecycle.ts
new file mode 100644
index 0000000000..9ee3db1329
--- /dev/null
+++ b/apps/web/src/observability/document-lifecycle.ts
@@ -0,0 +1,159 @@
+import { z } from 'zod';
+import { frontendInstanceId } from './frontend-instance';
+
+const KEY = 'macro-document-lifecycle';
+const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
+const navigationSchema = z.object({
+ commits: count,
+ paneCount: count,
+ historyEntryCount: count,
+ savedEntryStateCount: count,
+});
+type NavigationSnapshot = Omit<z.infer<typeof navigationSchema>, 'commits'>;
+const checkpointSchema = z.object({
+ frontendInstanceId: z.uuid(),
+ startedAtMs: z.number().int().nonnegative(),
+ updatedAtMs: z.number().int().nonnegative(),
+ visible: z.boolean(),
+ navigation: navigationSchema.optional(),
+ pagehide: z
+ .object({ atMs: z.number().int().nonnegative(), persisted: z.boolean() })
+ .optional(),
+});
+
+// Document-owned diagnostics only; no account, URL, or content state.
+let stopCurrent: (() => void) | undefined;
+let recordNavigation: ((snapshot: NavigationSnapshot) => void) | undefined;
+
+/** Counts only: never pass routes, entry ids, or captured view state. */
+export function recordDocumentNavigation(snapshot: NavigationSnapshot): void {
+ recordNavigation?.(snapshot);
+}
+
+function readCheckpoint() {
+ try {
+ const parsed = checkpointSchema.safeParse(
+ JSON.parse(sessionStorage.getItem(KEY) ?? 'null')
+ );
+ return parsed.success ? parsed.data : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Runs on old binaries too. No timers, native IPC, or unload-time network export. */
+export function startDocumentLifecycle() {
+ stopCurrent?.();
+ const now = Date.now();
+ const saved = readCheckpoint();
+ let previous =
+ saved &&
+ saved.frontendInstanceId !== frontendInstanceId &&
+ saved.startedAtMs <= saved.updatedAtMs &&
+ saved.updatedAtMs <= now &&
+ (!saved.pagehide ||
+ (saved.pagehide.atMs >= saved.startedAtMs &&
+ saved.pagehide.atMs <= saved.updatedAtMs)) &&
+ now - saved.updatedAtMs <= 24 * 60 * 60_000
+ ? saved
+ : undefined;
+ const checkpoint: z.infer<typeof checkpointSchema> = {
+ frontendInstanceId,
+ startedAtMs: now,
+ updatedAtMs: now,
+ visible: document.visibilityState === 'visible',
+ };
+ let active = true;
+ const write = () => {
+ try {
+ sessionStorage.setItem(KEY, JSON.stringify(checkpoint));
+ } catch {
+ // Storage restrictions must not affect the app.
+ }
+ };
+ const update = () => {
+ // Logout or a replacement document revokes this document's ownership.
+ if (!active || readCheckpoint()?.frontendInstanceId !== frontendInstanceId)
+ return;
+ checkpoint.updatedAtMs = Date.now();
+ checkpoint.visible = document.visibilityState === 'visible';
+ write();
+ };
+ const hide = (event: PageTransitionEvent) => {
+ checkpoint.pagehide = { atMs: Date.now(), persisted: event.persisted };
+ update();
+ };
+ const show = (event: PageTransitionEvent) => {
+ if (!active || !event.persisted) return;
+ if (readCheckpoint()?.frontendInstanceId !== frontendInstanceId) {
+ // A cached document resumed after another document/account owned the
+ // checkpoint. Report unknown next time rather than attributing its exit
+ // to that other document or reclaiming the old identity.
+ clearDocumentLifecycle();
+ return;
+ }
+ checkpoint.pagehide = undefined;
+ update();
+ };
+ const navigation = (snapshot: NavigationSnapshot) => {
+ checkpoint.navigation = {
+ commits: Math.min(
+ (checkpoint.navigation?.commits ?? 0) + 1,
+ Number.MAX_SAFE_INTEGER
+ ),
+ paneCount: snapshot.paneCount,
+ historyEntryCount: snapshot.historyEntryCount,
+ savedEntryStateCount: snapshot.savedEntryStateCount,
+ };
+ update();
+ };
+ recordNavigation = navigation;
+ write();
+ document.addEventListener('visibilitychange', update);
+ window.addEventListener('pagehide', hide);
+ window.addEventListener('pageshow', show);
+ const dispose = () => {
+ active = false;
+ previous = undefined;
+ if (recordNavigation === navigation) recordNavigation = undefined;
+ document.removeEventListener('visibilitychange', update);
+ window.removeEventListener('pagehide', hide);
+ window.removeEventListener('pageshow', show);
+ };
+ stopCurrent = dispose;
+
+ return {
+ dispose,
+ get attributes() {
+ return {
+ previous_document_checkpoint_available: previous !== undefined,
+ previous_document_instance_id: previous?.frontendInstanceId,
+ previous_document_started_at_ms: previous?.startedAtMs,
+ previous_document_checkpoint_at_ms: previous?.updatedAtMs,
+ previous_document_visible: previous?.visible,
+ previous_document_pagehide_observed: previous
+ ? previous.pagehide !== undefined
+ : undefined,
+ previous_document_pagehide_at_ms: previous?.pagehide?.atMs,
+ previous_document_pagehide_persisted: previous?.pagehide?.persisted,
+ previous_document_navigation_commits: previous?.navigation?.commits,
+ previous_document_pane_count: previous?.navigation?.paneCount,
+ previous_document_history_entry_count:
+ previous?.navigation?.historyEntryCount,
+ previous_document_saved_entry_state_count:
+ previous?.navigation?.savedEntryStateCount,
+ };
+ },
+ };
+}
+
+/** Prevent a late lifecycle callback from relinking a signed-out document. */
+export function clearDocumentLifecycle(): void {
+ stopCurrent?.();
+ stopCurrent = undefined;
+ try {
+ sessionStorage.removeItem(KEY);
+ } catch {
+ // Best effort, matching the native diagnostic lease.
+ }
+}
diff --git a/apps/web/src/observability/native-diagnostics.ts b/apps/web/src/observability/native-diagnostics.ts
index ab44216afb..94f49eeaf9 100644
--- a/apps/web/src/observability/native-diagnostics.ts
+++ b/apps/web/src/observability/native-diagnostics.ts
@@ -2,6 +2,7 @@ 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 { clearDocumentLifecycle } from './document-lifecycle';
import { frontendInstanceId } from './frontend-instance';
import type { FrontendEvent } from './generated/native-diagnostics';
@@ -76,6 +77,7 @@ export function recordNativeDiagnostic(event: FrontendEvent): void {
/** Await before clearing auth, then reject late callbacks from the old account. */
export async function clearNativeDiagnostics(): Promise<void> {
+ clearDocumentLifecycle();
previousFrontend = undefined;
try {
sessionStorage.removeItem(LEASE);
diff --git a/apps/web/src/observability/native-lifecycle.ts b/apps/web/src/observability/native-lifecycle.ts
index 9414a594d4..9bd2e8c121 100644
--- a/apps/web/src/observability/native-lifecycle.ts
+++ b/apps/web/src/observability/native-lifecycle.ts
@@ -1,5 +1,5 @@
import { analytics } from '@app/lib/analytics';
-import { Telemetry } from '@macro-inc/observability';
+import { type Attributes, Telemetry } from '@macro-inc/observability';
import type { DesktopSnapshot } from './desktop';
import { frontendInstanceId } from './frontend-instance';
import {
@@ -10,7 +10,8 @@ import { consumeReloadIntent } from './reload';
/** Called once per document, including recovery after a WebContent termination. */
export function recordNativeWebviewStart(
- snapshot: DesktopSnapshot | undefined
+ snapshot: DesktopSnapshot | undefined,
+ documentLifecycle?: Attributes
) {
const bundleBuild = document
.querySelector('meta[name="macro-bundle-build"]')
@@ -51,7 +52,11 @@ export function recordNativeWebviewStart(
// Include the native launch and termination count on subsequent exceptions.
// These are runtime identifiers, not account data.
analytics.posthog.register(attributes);
- const startupAttributes = { ...attributes, ...consumeReloadIntent() };
+ const startupAttributes = {
+ ...attributes,
+ ...documentLifecycle,
+ ...consumeReloadIntent(),
+ };
analytics.track('native_webview_started', startupAttributes);
const span = Telemetry.span('native.webview.start');
for (const [key, value] of Object.entries(startupAttributes)) {
diff --git a/apps/web/src/observability/navigation-lifecycle.ts b/apps/web/src/observability/navigation-lifecycle.ts
new file mode 100644
index 0000000000..53805e419a
--- /dev/null
+++ b/apps/web/src/observability/navigation-lifecycle.ts
@@ -0,0 +1,39 @@
+import type { SplitRouter } from '@app/lib/split-router';
+import { createEffect, on, onCleanup } from 'solid-js';
+import { recordDocumentNavigation } from './document-lifecycle';
+
+/** One small local checkpoint after a router commit, with no IPC or export. */
+export function trackNavigationLifecycle(
+ router: SplitRouter,
+ savedEntryStateCount: () => number
+): void {
+ let disposed = false;
+ let queued = false;
+ onCleanup(() => {
+ disposed = true;
+ });
+ createEffect(
+ on(
+ () => router.panes().map((pane) => router.history(pane)),
+ () => {
+ if (queued) return;
+ queued = true;
+ // Let every pane finish pruning its saved state before counting it.
+ queueMicrotask(() => {
+ queued = false;
+ if (disposed) return;
+ const panes = router.panes();
+ recordDocumentNavigation({
+ paneCount: panes.length,
+ historyEntryCount: panes.reduce(
+ (count, pane) =>
+ count + (router.history(pane)?.entries.length ?? 0),
+ 0
+ ),
+ savedEntryStateCount: savedEntryStateCount(),
+ });
+ });
+ }
+ )
+ );
+}
diff --git a/docs/agent-guide/search.md b/docs/agent-guide/search.md
index 0449ada790..2d46a3f49a 100644
--- a/docs/agent-guide/search.md
+++ b/docs/agent-guide/search.md
@@ -52,6 +52,8 @@ Native search captures its state when covered: it retains mounted results while
it is among the front two panes, and restores them after deeper navigation evicts
it. A remounted history entry immediately restores its loaded results,
virtualizer measurements and offset (or the full-text scroller's offset).
+Snapshots are released when their history entry is removed or replaced, or its
+pane closes; entries still reachable with Back/Forward retain their snapshots.
Refreshing sources rebuild the loaded window and update matching rows in place;
new pages append without reordering saved rows. A saved row missing from an
incomplete source page remains until it is found or pagination exhausts.