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(navigation): resume app views within the session (#8593)

dev-rbbbb78bb2c0ed
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 23e52b5716..441eb14c94 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -180,13 +180,14 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
- 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.
- Key mobile name-result history ordering and scroll anchors by the other participant for one-to-one DMs, preserving a person's position when their conversation is created; keep group DMs keyed by channel.
- Keep mobile Search history lightweight: save query/category/mode, account-scoped item anchors, and at most 200 ordering IDs per mode; never save row objects or virtualizer caches. Restore from current sources with at most three additional pages, fall back when an anchor disappears, and stop restoration on user interaction or scope changes. Dock navigation starts a fresh search session; cached rows belong to the source, not history.
-- 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.
+- Release per-history-entry state when its router entry is replaced, pruned, or closed; retain only the latest per-view session snapshot and the latest split event outside reachable Back/Forward history.
- 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 item anchors after responsive row measurement and disable browser scroll anchoring so layout changes cannot override restoration.
- Reserve the safe area plus the category row above mobile Search, and only the safe area above Channels; their hidden split headers must not add another blank strip.
- Follow [mobile layout and chrome](../../.agents/rules/web/mobile.md#layout-and-chrome) for full-frame views and record tabs; verify their first controls below the navigation with a nonzero safe area on phones and tablets.
- Keep split chrome portal targets reactive so cached views can mount before their header, and clear a retiring header's targets only while it still owns them.
+- Opt views into session restoration with `split-layout/view-restoration` and set `resume: true` on ordinary layout navigation; publish captured state only through the leave guard's `onCommit`, keep explicit links and new splits fresh, and reuse entry-state captors rather than hidden mounted views.
- Let `ViewShell.TopBar` own split close and navigation controls; do not add a second split close button inside Agents headers or their preview `headerLeading`.
- Show only the Recent conversation feed in mobile Channels, without view tabs or a persisted mobile tab selection; render its rows with Home's touch row (`ChannelCardLayout` and `InboxDivider`) and pin at most six channel favorites above it.
- Mount the mobile search input before focusing it inside the dock tap; keep navigation in that handler so focus does not trigger a second navigation or lose iOS keyboard activation.
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsx
index fafc744960..ba8a127092 100644
--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx
+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx
@@ -148,6 +148,7 @@ const SIDEBAR_LINKS = [
},
] satisfies SidebarItem[];
+// Global view switches restore session context; explicit split opens stay fresh.
type OpenWithSplitFn = ReturnType<typeof useSplitLayout>['openWithSplit'];
export function sidebarContent(
@@ -162,9 +163,8 @@ export function sidebarContent(
}
/**
- * Navigate to a sidebar view by pushing a fresh entry into the active split.
- * Holding shift opens it in a new split. Use in-app back/forward to return to
- * prior entries.
+ * Navigate through the layout, resuming only views that opted into retention.
+ * Holding shift opens a fresh view in a new split.
*/
export function navigateToSidebarView(args: {
viewId: SidebarItem['id'];
@@ -172,14 +172,18 @@ export function navigateToSidebarView(args: {
shiftKey: boolean;
openWithSplit: OpenWithSplitFn;
referredFrom?: ReferredFrom;
+ onApplied?: () => void;
}): SplitHandle | undefined {
- const { viewId, params, shiftKey, openWithSplit, referredFrom } = args;
+ const { viewId, params, shiftKey, openWithSplit, referredFrom, onApplied } =
+ args;
return openWithSplit(sidebarContent(viewId, params), {
preferNewSplit: shiftKey,
+ resume: !shiftKey,
mergeHistory: false,
allowDuplicate: viewId !== 'calendar',
referredFrom,
+ onApplied,
}).split;
}
@@ -321,6 +325,14 @@ export const GoToHotkeys = () => {
params: link.params,
shiftKey: !!e?.shiftKey,
openWithSplit,
+ onApplied:
+ link.id === 'search'
+ ? () => {
+ const split = globalSplitManager()?.activeSplit();
+ if (split?.content().id === 'search')
+ requestSearchFocus(split.id);
+ }
+ : undefined,
});
if (link.id === 'search' && handle) {
requestSearchFocus(handle.id);
diff --git a/apps/web/src/components/app/mobile/use-mobile-nav.ts b/apps/web/src/components/app/mobile/use-mobile-nav.ts
index 2393e46fb0..bf88baf640 100644
--- a/apps/web/src/components/app/mobile/use-mobile-nav.ts
+++ b/apps/web/src/components/app/mobile/use-mobile-nav.ts
@@ -90,12 +90,14 @@ export function useMobileNavNavigate(): (id: MobileDockNavId) => void {
if (isNativeMobilePlatform()) {
const routeState: MobileSearchRouteState | undefined =
id === 'search' ? { sessionId: crypto.randomUUID() } : undefined;
- replaceAllSplits(content, { routeState });
+ // Search taps intentionally start a new search session.
+ replaceAllSplits(content, { routeState, resume: id !== 'search' });
return;
}
const fgContent = globalSplitManager()?.activeSplit()?.content();
const isOnNavView = fgContent?.type === 'component';
openWithSplit(content, {
+ resume: id !== 'search',
mergeHistory: isOnNavView,
// Route through the router so an existing pane receives the default tab.
search: id === 'documents' || id === 'reviews' ? {} : undefined,
diff --git a/apps/web/src/components/app/sidebar-next/search-bar-button.test.tsx b/apps/web/src/components/app/sidebar-next/search-bar-button.test.tsx
index fe780082f7..a385acfd41 100644
--- a/apps/web/src/components/app/sidebar-next/search-bar-button.test.tsx
+++ b/apps/web/src/components/app/sidebar-next/search-bar-button.test.tsx
@@ -38,7 +38,7 @@ vi.mock('@app/signal/splitLayout', () => ({
vi.mock('@components/app/app-sidebar/sidebar', () => ({
navigateToSidebarView: mocks.navigate,
}));
-vi.mock('@components/app/split-layout/layout', () => ({
+vi.mock('../split-layout/layout', () => ({
useSplitLayout: () => ({ openWithSplit: vi.fn() }),
}));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
diff --git a/apps/web/src/components/app/sidebar-next/search-bar-button.tsx b/apps/web/src/components/app/sidebar-next/search-bar-button.tsx
index 0a19084f88..4feeb9f04c 100644
--- a/apps/web/src/components/app/sidebar-next/search-bar-button.tsx
+++ b/apps/web/src/components/app/sidebar-next/search-bar-button.tsx
@@ -2,14 +2,14 @@ import { requestSearchFocus } from '@app/features/next-soup/soup-view/search-con
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { globalSplitManager } from '@app/signal/splitLayout';
import { navigateToSidebarView } from '@components/app/app-sidebar/sidebar';
-import { useSplitLayout } from '@components/app/split-layout/layout';
import { TOKENS } from '@core/hotkey/tokens';
import { SidebarSearchMenu } from '../app-sidebar/sidebar-search-menu';
+import { useSplitLayout } from '../split-layout/layout';
/** Search and command-menu discovery in the compact rail. */
export const SearchRailButton = () => {
const analytics = useAnalytics();
- const layout = useSplitLayout();
+ const { openWithSplit } = useSplitLayout();
const openSearch = (newSplit: boolean) => {
analytics.track('sidebar_click', { view: 'search' });
@@ -31,8 +31,12 @@ export const SearchRailButton = () => {
split = navigateToSidebarView({
viewId: 'search',
shiftKey: newSplit,
- openWithSplit: layout.openWithSplit,
+ openWithSplit,
referredFrom: 'sidebar',
+ onApplied: () => {
+ const active = globalSplitManager()?.activeSplit();
+ if (active?.content().id === 'search') requestSearchFocus(active.id);
+ },
});
if (split) requestSearchFocus(split.id);
globalSplitManager()?.returnFocus();
diff --git a/apps/web/src/components/app/split-layout/README.md b/apps/web/src/components/app/split-layout/README.md
index 1aaf0cc9da..8c9f93da0b 100644
--- a/apps/web/src/components/app/split-layout/README.md
+++ b/apps/web/src/components/app/split-layout/README.md
@@ -1,5 +1,34 @@
Split layout should support an arbitrary number of vertical splits.
+## Opt-in view restoration
+
+`SplitLayoutProvider` owns a memory-only, account-scoped view-state store.
+A view opts in by calling `useViewRestoration()` in its stable route component.
+The default key comes from the current router location, with Agents conversations
+normalized to `agents`; pass an explicit key to override that grouping.
+
+The hook captures its current location, route state, and entry-state slices in
+`useBeforeLeave`. It stages the snapshot with the navigation's `onCommit`
+callback, so a refused, cancelled, failed, or superseded navigation cannot replace
+the saved snapshot. Solid cleanup only unregisters the hook; it never saves state.
+
+Ordinary rail, Go To, and mobile dock navigation sets `resume: true` on the existing
+layout actions. Only opted-in views resume. A mounted view can supply its current
+state directly, and the last focused instance wins when several splits show a view.
+Explicit links and new-split actions stay fresh. Native dock navigation still
+resets the pane stack, and dock Search starts a fresh session. Reload, sign-out,
+and account changes retire the saved state. Views still unmount normally.
+
+Views retain local context through `useEntryState` or `registerEntryStateCaptor`.
+These slices restore through both pane Back/Forward and opted-in app switches;
+route/schema state stays separate. Restores use the existing router, including
+leave guards, middleware, URL updates, and single-owner content claims.
+
+Resolve restoration keys and initial entry-state slices from the current router
+entry, not the layout mirror: an outlet can mount before the mirror updates.
+
+The remaining notes below describe the original split layout.
+
SplitLayoutRouter is responsible for handling the routing of the splits.
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index ff7f00fd2d..d5060d232c 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -3,6 +3,7 @@ import { useSplitRouter } from '@app/lib/split-router';
import { setGlobalSplitManager } from '@app/signal/splitLayout';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
import { Resize } from '@core/component/Resize';
+import { useIsAuthenticated, useUserId } from '@core/context/user';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { tabTitleSignal } from '@core/signal/tabTitle';
@@ -34,12 +35,15 @@ import { createSplitFocusTracker } from './splitFocusTracker';
export function SplitLayoutProvider(props: ParentProps) {
const router = useSplitRouter();
const blockOrchestrator = useGlobalBlockOrchestrator();
+ const userId = useUserId();
+ const authenticated = useIsAuthenticated();
const splitManager = createSplitLayout(blockOrchestrator, {
router,
toLocation: (content) => resolveContentLocation(router.routes, content),
toContent: splitContentFromLocation,
stacked: isNativeMobilePlatform,
+ sessionKey: () => (authenticated() === false ? undefined : userId()),
});
createEffect(() => setGlobalSplitManager(splitManager));
onCleanup(() => setGlobalSplitManager(undefined));
diff --git a/apps/web/src/components/app/split-layout/entry-state.ts b/apps/web/src/components/app/split-layout/entry-state.ts
index 4ef475a745..6e096f9e8a 100644
--- a/apps/web/src/components/app/split-layout/entry-state.ts
+++ b/apps/web/src/components/app/split-layout/entry-state.ts
@@ -5,7 +5,7 @@ import {
type Setter,
untrack,
} from 'solid-js';
-import type { EntryState, NavigationCause } from './layoutManager';
+import type { NavigationCause } from './layoutManager';
import { useSplitPanelOrThrow } from './layoutUtils';
export type UseEntryStateOptions<T> = {
@@ -22,7 +22,8 @@ export type UseEntryStateOptions<T> = {
* Returns a signal whose initial value is read from the current split entry's
* `state[key]` slot (if present) or from `options.default`. The signal value
* is captured back into the entry just before any navigation away (back,
- * forward, replace, push), so it round-trips correctly across back/forward.
+ * forward, replace, push). It restores on back/forward and when app navigation
+ * resumes a view that opted in with `useViewRestoration`.
*
* Slice keys are flat and shared across the split's entry state blob — use a
* dotted namespace convention (e.g. `'search.text'`, `'soup.scroll'`).
@@ -37,7 +38,7 @@ export function useEntryState<T>(
const handle = panel.handle;
const persisted = untrack(() => {
- const blob = (handle.content() as { state?: EntryState }).state;
+ const blob = handle.currentEntryState();
return blob && key in blob ? (blob[key] as T) : undefined;
});
const initial = persisted !== undefined ? persisted : options.default;
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.ts
index 1f33a4014f..8a8ad413c7 100644
--- a/apps/web/src/components/app/split-layout/layoutManager.ts
+++ b/apps/web/src/components/app/split-layout/layoutManager.ts
@@ -25,6 +25,7 @@ import type {
} from '@core/orchestrator';
import { useFocusLock } from '@core/util/createControlledOpenSignal';
import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
import {
type Accessor,
batch,
@@ -48,6 +49,7 @@ import {
createContentInstanceRegistry,
} from './contentInstanceRegistry';
import { DEFAULT_SPLIT_MIN_WIDTH } from './splitContentSizing';
+import { createViewState, type ViewState } from './view-state';
/** Checked on every route change in a pane, so entry state is captured before the pane moves. */
const ENTRY_STATE_GUARD_DEPTH = Number.MAX_SAFE_INTEGER;
@@ -80,7 +82,7 @@ type SplitKey = `${BlockName | BlockAlias | 'component'}:${string}`;
/**
* Per-entry runtime state, opaque at the layout-manager level.
* Owned by components via `useEntryState`. Survives back/forward within a
- * split's history. Does not contribute to entry identity.
+ * split's history and can be supplied on fresh entries. Does not contribute to entry identity.
*/
export type EntryState = Record<string, unknown>;
@@ -178,6 +180,8 @@ export type ReferredFrom =
| null;
export type ReplaceAllSplitsOptions = {
+ /** Resume a view that opted into layout-owned session state. */
+ resume?: boolean;
referredFrom?: ReferredFrom;
/** Router state validated by the destination route, separate from runtime EntryState. */
routeState?: unknown;
@@ -201,8 +205,12 @@ export type CreateNewSplitOptions = {
};
export type OpenWithSplitOptions = {
+ /** Resume an opted-in view; explicit new-split actions stay fresh. */
+ resume?: boolean;
/** Route-owned targets must pass through middleware and content claims before opening. */
search?: Record<string, SplitSearchUpdate>;
+ /** Schema-validated route state, separate from opaque runtime EntryState. */
+ routeState?: unknown;
/** Runs after a cooperating navigator applies or reuses its destination. */
onApplied?: () => void;
mergeHistory?: boolean;
@@ -307,9 +315,12 @@ export type SplitLayoutOptions = {
* behind moves it to the front.
*/
stacked?: () => boolean;
+ /** Changing the session retires retained snapshots and ownership of existing entries. */
+ sessionKey?: Accessor<string | undefined>;
};
export type SplitManager = {
+ readonly viewState: ViewState;
/** Whether the router has loaded the URL, so route-owned opens can run. */
readonly contentNavigationReady: Accessor<boolean>;
/** Changes when route-owned navigation becomes available. */
@@ -601,6 +612,10 @@ export function createSplitLayout(
popovers: new Map(),
});
const [lastEvent, setLastEvent] = createSignal<SplitEventWithType>();
+ const viewState = createViewState({
+ activeOwner: () => state.activeSplitId,
+ sessionKey: options.sessionKey,
+ });
const contentInstances = createContentInstanceRegistry();
const unregisterContentInstances = contentInstances.register(() => [
@@ -1049,9 +1064,13 @@ export function createSplitLayout(
/** Mirrors a pane's new current entry onto its split, creating the split when the pane is new. */
function applyEntry(id: SplitId, entry: Entry, arrival: PaneArrival) {
+ viewState.observe(entry);
const deliversParams = arrival === 'fresh' || arrival === 'replace';
- const content = contentOfEntry(entry, deliversParams);
const meta = metaOf(entry);
+ if (meta.entryState && !entryStates.has(entry.id)) {
+ entryStates.set(entry.id, meta.entryState);
+ }
+ const content = contentOfEntry(entry, deliversParams);
const referredFrom = deliversParams ? meta.referredFrom : undefined;
const split = findSplitById(id);
@@ -1107,6 +1126,7 @@ export function createSplitLayout(
const front = state.splits.at(-1);
if (stacked() && state.activeSplitId === id && front) {
setState('activeSplitId', front.id);
+ viewState.activate(front.id);
}
dispatchEvent(SplitEvent.Remove, { splitId: id, splitIndex: index });
});
@@ -1136,6 +1156,7 @@ export function createSplitLayout(
setState('spotlightId', undefined);
}
setState('activeSplitId', id);
+ viewState.activate(id);
}
/** Stacked panes bring a pane behind the front forward; the panes that were in front of it stay, behind it. */
@@ -1290,12 +1311,10 @@ export function createSplitLayout(
captureCurrentEntryState(live);
},
currentEntryState: () => {
- const live = s();
- if (!live) return undefined;
- // Read through the store getter so callers see the latest captured
- // state (mirrored from history into split.content on capture).
- const c = live.content as { state?: EntryState };
- return c.state;
+ const entry = router.entry(paneOf(currentSplit.id));
+ if (!entry) return;
+ // The outlet can mount before applyEntry mirrors the router entry.
+ return entryStates.get(entry.id) ?? metaOf(entry).entryState;
},
updateCurrentEntry: (updater) =>
updateCurrentEntry(currentSplit.id, updater),
@@ -1415,7 +1434,10 @@ export function createSplitLayout(
router.history(pane)?.entries.map((entry) => entry.id)
);
for (const entryId of entryIds) {
- if (!retained.has(entryId)) entryStates.delete(entryId);
+ if (!retained.has(entryId)) {
+ entryStates.delete(entryId);
+ viewState.forget(entryId);
+ }
}
entryIds = retained;
});
@@ -1439,7 +1461,10 @@ export function createSplitLayout(
onCleanup(() => {
unregisterGuard();
- for (const entryId of entryIds) entryStates.delete(entryId);
+ for (const entryId of entryIds) {
+ entryStates.delete(entryId);
+ viewState.forget(entryId);
+ }
untrack(() => dropSplit(id));
});
@@ -1548,7 +1573,7 @@ export function createSplitLayout(
}
}
- /** An open that carries search: the router merges it and checks claims as it lands. */
+ /** Route-owned search and state pass through the router and its content claims. */
function openThroughRouter(
content: SplitContent,
options: OpenWithSplitOptions
@@ -1566,6 +1591,7 @@ export function createSplitLayout(
replace: options.mergeHistory,
search: options.search,
allowDuplicate: options.allowDuplicate,
+ ...(options.routeState !== undefined && { state: options.routeState }),
};
const wantsNewPane = stacked()
? !options.mergeHistory
@@ -1590,12 +1616,52 @@ export function createSplitLayout(
});
}
+ /** Resolve a retained entry before the destination mounts, never by redirecting after mount. */
+ function resumeView(
+ content: SplitContent
+ ): { content: SplitContent; routeState: unknown } | undefined {
+ const span = Telemetry.span('navigation.view.resume');
+ span.setAttr('view.id', content.id);
+ try {
+ const snapshot =
+ content.type === 'component' ? viewState.get(content.id) : undefined;
+ span.setAttr('view.restored', snapshot !== undefined);
+ if (!snapshot) return;
+ const restored = toContent(snapshot.location);
+ if (restored.type !== 'component') return;
+ return {
+ content: {
+ ...restored,
+ params: snapshot.params,
+ preserveParams: snapshot.preserveParams,
+ state: snapshot.entryState,
+ entryMetadata: snapshot.location,
+ },
+ routeState: snapshot.routeState,
+ };
+ } finally {
+ span.end();
+ }
+ }
+
function openWithSplit(
content: SplitContent,
options: OpenWithSplitOptions = {}
): OpenSplitResult {
const sourceOwner = options.handle?.id;
- if (options.search) {
+ if (options.resume && !options.preferNewSplit) {
+ const restored = resumeView(content);
+ if (restored) {
+ content = restored.content;
+ options = {
+ ...options,
+ search: options.search ?? {},
+ allowDuplicate: false,
+ routeState: options.routeState ?? restored.routeState,
+ };
+ }
+ }
+ if (options.search || options.routeState !== undefined) {
openThroughRouter(content, options);
return { status: 'navigating', sourceOwner };
}
@@ -1694,6 +1760,16 @@ export function createSplitLayout(
content: SplitContent,
options: ReplaceAllSplitsOptions = {}
): SplitHandle | undefined {
+ if (options.resume) {
+ const restored = resumeView(content);
+ if (restored) {
+ content = restored.content;
+ options = {
+ ...options,
+ routeState: options.routeState ?? restored.routeState,
+ };
+ }
+ }
if (
!canOpenContent(content, getSplitByContent(content.type, content.id)?.id)
) {
@@ -1737,6 +1813,7 @@ export function createSplitLayout(
const getVisibleSplits = () => state.splits.filter(onScreen);
return {
+ viewState,
splits: () => state.splits,
findOpenView,
registerOpenViews: contentInstances.register,
diff --git a/apps/web/src/components/app/split-layout/tests/view-restoration.test.tsx b/apps/web/src/components/app/split-layout/tests/view-restoration.test.tsx
new file mode 100644
index 0000000000..2955c27c82
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/tests/view-restoration.test.tsx
@@ -0,0 +1,520 @@
+import {
+ createMemoryHistory,
+ createMemoryPaneStore,
+ createSplitRouter,
+ type Entry,
+ SplitRouter,
+ type SplitRouterMiddleware,
+ type SplitRoutes,
+} from '@app/lib/split-router';
+import { SplitRouterProvider } from '@app/lib/split-router/solid/context';
+import { paneRoute } from '@app/routes/app-route';
+import {
+ agentsRoute,
+ agentsViewRoute,
+ appRoute,
+ calendarSplitRoute,
+ channelDetailRoute,
+ channelsSplitRoute,
+ driveSplitRoute,
+ driveTabRoute,
+ homeSplitRoute,
+ notFoundRoute,
+ searchRoute,
+} from '@app/routes/routes';
+import type { BlockOrchestrator } from '@core/orchestrator';
+import { cleanup, render } from '@solidjs/testing-library';
+import { createSignal, For, type Setter, Show } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SplitLayoutContext } from '../context';
+import { useEntryState } from '../entry-state';
+import { createSplitLayout, type SplitManager } from '../layoutManager';
+import { createAppPanePolicy } from '../split-router/app-pane-policy';
+import {
+ resolveContentLocation,
+ splitContentFromLocation,
+} from '../split-router/legacy-route';
+import { useViewRestoration } from '../view-restoration';
+
+const mocks = vi.hoisted(() => ({
+ manager: undefined as SplitManager | undefined,
+ account: (): string | undefined => 'account-one',
+ selection: (): string[] => [],
+ setSelection: undefined as Setter<string[]> | undefined,
+ retaining: (): boolean => true,
+}));
+
+vi.mock('../layoutUtils', async () => {
+ const { usePane } = await import('@app/lib/split-router');
+ return {
+ useSplitPanelOrThrow() {
+ const pane = usePane()();
+ const manager = mocks.manager;
+ const id = manager
+ ?.splits()
+ .find((split) => split.id.toString() === pane.toString())?.id;
+ const handle = id && manager?.getSplit(id);
+ if (!handle) throw new Error('Missing test split');
+ return { handle };
+ },
+ };
+});
+vi.mock('../componentRegistry', () => ({
+ resolveComponent: () => ({ element: () => null, initialMeta: {} }),
+}));
+vi.mock('@core/constant/allBlocks', () => ({
+ isBlockAlias: () => false,
+ resolveBlockAlias: (type: string) => type,
+}));
+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(),
+}));
+
+function RememberedView() {
+ useViewRestoration();
+ const [selection, setSelection] = useEntryState<string[]>('view.selection', {
+ default: [],
+ });
+ mocks.selection = selection;
+ mocks.setSelection = setSelection;
+ return null;
+}
+
+function AuthenticatedView() {
+ return (
+ <Show when={mocks.account() && mocks.retaining()}>
+ <RememberedView />
+ </Show>
+ );
+}
+
+function setup(
+ url = '/channels/channel-one',
+ options: {
+ stacked?: boolean;
+ retainChannels?: boolean;
+ account?: string | null;
+ middleware?: readonly SplitRouterMiddleware[];
+ } = {}
+) {
+ let router!: ReturnType<typeof createSplitRouter>;
+ let manager!: SplitManager;
+ const [account, setAccount] = createSignal<string | undefined>(
+ options.account === null ? undefined : (options.account ?? 'account-one')
+ );
+ mocks.account = account;
+ const [retaining, setRetaining] = createSignal(true);
+ mocks.retaining = retaining;
+ render(() => {
+ const routes: SplitRoutes = {
+ definitions: [
+ {
+ ...appRoute,
+ component: () => <SplitRouter.Outlet />,
+ children: [
+ homeSplitRoute,
+ { ...agentsRoute, component: AuthenticatedView },
+ { ...agentsViewRoute, component: AuthenticatedView },
+ { ...calendarSplitRoute, component: AuthenticatedView },
+ {
+ ...channelsSplitRoute,
+ component:
+ options.retainChannels === false
+ ? () => null
+ : AuthenticatedView,
+ children: [channelDetailRoute],
+ },
+ {
+ ...driveSplitRoute,
+ component: AuthenticatedView,
+ children: [driveTabRoute],
+ },
+ { ...searchRoute, component: AuthenticatedView },
+ notFoundRoute,
+ ],
+ },
+ ],
+ defaultRoute: () => paneRoute({ id: 'view-home', params: {} }),
+ };
+ router = createSplitRouter({
+ routes,
+ history: createMemoryHistory(url),
+ paneStore: createMemoryPaneStore<Entry>(),
+ middleware: options.middleware,
+ policy: createAppPanePolicy({
+ manager: () => manager,
+ toContent: splitContentFromLocation,
+ defaultLocation: () => ({ route: routes.defaultRoute() }),
+ stacked: () => options.stacked ?? false,
+ }),
+ });
+ const orchestrator = {
+ isBlockMounted: () => false,
+ createBlockInstance: vi.fn(),
+ } as unknown as BlockOrchestrator;
+ manager = createSplitLayout(orchestrator, {
+ router,
+ toLocation: (content) => resolveContentLocation(router.routes, content),
+ toContent: splitContentFromLocation,
+ stacked: () => options.stacked ?? false,
+ sessionKey: account,
+ });
+ mocks.manager = manager;
+ return (
+ <SplitRouterProvider router={router}>
+ <SplitLayoutContext.Provider value={{ manager }}>
+ <For each={router.panes()}>
+ {(pane) => <SplitRouter.Outlet pane={pane} />}
+ </For>
+ </SplitLayoutContext.Provider>
+ </SplitRouterProvider>
+ );
+ });
+ return { router, manager, setAccount, setRetaining };
+}
+
+afterEach(() => {
+ cleanup();
+ mocks.manager = undefined;
+ mocks.setSelection = undefined;
+});
+
+describe('opt-in view restoration', () => {
+ it('restores nested location, search, and UI state through existing layout navigation', async () => {
+ const { router, manager } = setup();
+ const pane = router.panes()[0]!;
+ await router.updateSearch(pane, 'channels', { tab: ['unread'] });
+ mocks.setSelection?.(['message-one']);
+ manager.openWithSplit({ type: 'component', id: 'home' }, { resume: true });
+ await router.settled();
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.location.route.matches.at(-1)).toMatchObject({
+ id: 'channels-channel',
+ params: { channelId: 'channel-one' },
+ });
+ expect(router.entry(pane)?.location.search).toEqual({
+ channels: { tab: ['unread'] },
+ });
+ expect(mocks.selection()).toEqual(['message-one']);
+ expect(manager.activeSplit()?.canGoBack()).toBe(true);
+ });
+
+ it('does not retain a view without the hook', async () => {
+ const { router, manager } = setup('/channels/channel-one', {
+ retainChannels: false,
+ });
+ const pane = router.panes()[0]!;
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.location.route.matches.at(-1)?.id).toBe(
+ 'view-channels'
+ );
+ });
+
+ it('captures direct departures but keeps explicit links and new splits fresh', async () => {
+ const { router, manager } = setup();
+ const pane = router.panes()[0]!;
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(
+ router.entry(pane)?.location.route.matches.at(-1)?.params.channelId
+ ).toBe('channel-one');
+ await router.navigatePane(pane, '/channels/channel-two');
+ expect(
+ router.entry(pane)?.location.route.matches.at(-1)?.params.channelId
+ ).toBe('channel-two');
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true, preferNewSplit: true, allowDuplicate: true }
+ );
+ await router.settled();
+ expect(
+ router.entry(router.panes()[1]!)?.location.route.matches.at(-1)?.id
+ ).toBe('view-channels');
+ });
+
+ it('retains a closed detail as the root, not the previous detail', async () => {
+ const { router, manager } = setup();
+ const pane = router.panes()[0]!;
+ await router.navigatePane(pane, '/channels');
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.location.route.matches.at(-1)?.id).toBe(
+ 'view-channels'
+ );
+ });
+
+ it('keeps route schema state separate from runtime state', async () => {
+ const { router, manager } = setup('/drive/recent');
+ const pane = router.panes()[0]!;
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'documents' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.location.route.matches.at(-1)?.params.tab).toBe(
+ 'recent'
+ );
+ await router.navigatePane(pane, '/search', {
+ state: { sessionId: 'search-one' },
+ });
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'search' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.state).toEqual({ sessionId: 'search-one' });
+ });
+
+ it('resumes Calendar focus and Agents conversations with the same hook', async () => {
+ const { router, manager } = setup('/calendar/month');
+ const pane = router.panes()[0]!;
+ await router.updateSearch(pane, 'calendar', { eventId: ['event-one'] });
+ await router.navigatePane(pane, '/agents/session-one');
+ manager.openWithSplit(
+ { type: 'component', id: 'calendar' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(
+ router.entry(pane)?.location.route.matches.at(-1)?.params.period
+ ).toBe('dayGridMonth');
+ expect(router.entry(pane)?.location.search?.calendar?.eventId).toEqual([
+ 'event-one',
+ ]);
+ manager.openWithSplit(
+ { type: 'component', id: 'agents' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.location.route.matches.at(-1)?.params.id).toBe(
+ 'session-one'
+ );
+ });
+
+ it('resumes a live native view before replacing its pane stack', async () => {
+ const { router, manager } = setup('/channels/channel-one', {
+ stacked: true,
+ });
+ mocks.setSelection?.(['message-one']);
+ manager.openWithSplit(
+ { type: 'component', id: 'home' },
+ { preferNewSplit: true }
+ );
+ await router.settled();
+ const oldPanes = [...router.panes()];
+ manager.replaceAllSplits(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.panes()).toHaveLength(1);
+ const pane = router.panes()[0]!;
+ expect(
+ router.entry(pane)?.location.route.matches.at(-1)?.params.channelId
+ ).toBe('channel-one');
+ expect(mocks.selection()).toEqual(['message-one']);
+ expect(oldPanes.some((oldPane) => !router.panes().includes(oldPane))).toBe(
+ true
+ );
+ });
+
+ it('prefers the last focused view over another live instance', async () => {
+ const { router, manager } = setup();
+ const firstPane = router.panes()[0]!;
+ await router.open('/channels/channel-two', { newPane: true });
+ const firstSplit = manager
+ .splits()
+ .find((split) => split.id.toString() === firstPane.toString())!;
+ manager.activateSplit(firstSplit.id);
+ await router.navigatePane(firstPane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(
+ router.entry(firstPane)?.location.route.matches.at(-1)?.params.channelId
+ ).toBe('channel-one');
+ });
+
+ it('retains an opted-in view when its pane closes', async () => {
+ const { router, manager } = setup();
+ const pane = router.panes()[0]!;
+ await router.open('/home', { newPane: true });
+ await router.remove(pane);
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(
+ router.entry(router.panes()[0]!)?.location.route.matches.at(-1)?.params
+ .channelId
+ ).toBe('channel-one');
+ });
+
+ it('never publishes a snapshot when a later guard refuses navigation', async () => {
+ const { router, manager, setRetaining } = setup();
+ const pane = router.panes()[0]!;
+ router.registerGuard(pane, Number.MAX_SAFE_INTEGER, () => false);
+ const previous = router.entry(pane);
+ await router.navigatePane(pane, '/home');
+ expect(router.entry(pane)).toBe(previous);
+ setRetaining(false);
+ expect(manager.viewState.get('channels')).toBeUndefined();
+ });
+
+ it('never publishes a snapshot when middleware cancels navigation', async () => {
+ const { router, manager, setRetaining } = setup('/channels/channel-one', {
+ middleware: [
+ ({ to, cancel }) =>
+ to.location.route.matches.at(-1)?.id === 'view-home'
+ ? cancel()
+ : undefined,
+ ],
+ });
+ const pane = router.panes()[0]!;
+ const previous = router.entry(pane);
+ await router.navigatePane(pane, '/home');
+ expect(router.entry(pane)).toBe(previous);
+ setRetaining(false);
+ expect(manager.viewState.get('channels')).toBeUndefined();
+ });
+
+ it('discards a staged snapshot if the account changes before commit', async () => {
+ const entered = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const { router, manager, setAccount } = setup('/channels/channel-one', {
+ middleware: [
+ ({ to }) => {
+ if (to.location.route.matches.at(-1)?.id !== 'view-home') return;
+ entered.resolve();
+ return release.promise;
+ },
+ ],
+ });
+ const pane = router.panes()[0]!;
+ const pending = router.navigatePane(pane, '/home');
+ await entered.promise;
+ setAccount('account-two');
+ release.resolve();
+ await pending;
+ expect(manager.viewState.get('channels')).toBeUndefined();
+ });
+
+ it('keeps an initial URL eligible after authentication resolves', async () => {
+ const { router, manager, setAccount } = setup('/channels/channel-one', {
+ account: null,
+ });
+ const pane = router.panes()[0]!;
+ setAccount('account-one');
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(
+ router.entry(pane)?.location.route.matches.at(-1)?.params.channelId
+ ).toBe('channel-one');
+ });
+
+ it('does not share retained or live entries across account changes', async () => {
+ const { router, manager, setAccount } = setup();
+ const pane = router.panes()[0]!;
+ setAccount('account-two');
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.location.route.matches.at(-1)?.id).toBe(
+ 'view-channels'
+ );
+ });
+
+ it('keeps rewritten entries owned by their original account', async () => {
+ const { router, manager, setAccount } = setup();
+ const pane = router.panes()[0]!;
+ const entryId = router.entry(pane)?.id;
+ setAccount('account-two');
+ await router.updateSearch(
+ pane,
+ 'channels',
+ { tab: ['unread'] },
+ { history: 'replace' }
+ );
+ expect(router.entry(pane)?.id).toBe(entryId);
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.location.route.matches.at(-1)?.id).toBe(
+ 'view-channels'
+ );
+ });
+
+ it('retains new entries after an account change without remounting the view', async () => {
+ const { router, manager, setAccount } = setup();
+ const pane = router.panes()[0]!;
+ setAccount('account-two');
+ await router.navigatePane(pane, '/channels/channel-two');
+ await router.navigatePane(pane, '/home');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(
+ router.entry(pane)?.location.route.matches.at(-1)?.params.channelId
+ ).toBe('channel-two');
+ });
+
+ it('clears a saved snapshot on sign-out', async () => {
+ const { router, manager, setAccount } = setup();
+ const pane = router.panes()[0]!;
+ await router.navigatePane(pane, '/home');
+ expect(manager.viewState.get('channels')).toBeDefined();
+ setAccount(undefined);
+ expect(manager.viewState.get('channels')).toBeUndefined();
+ setAccount('account-one');
+ manager.openWithSplit(
+ { type: 'component', id: 'channels' },
+ { resume: true }
+ );
+ await router.settled();
+ expect(router.entry(pane)?.location.route.matches.at(-1)?.id).toBe(
+ 'view-channels'
+ );
+ });
+});
diff --git a/apps/web/src/components/app/split-layout/view-restoration.ts b/apps/web/src/components/app/split-layout/view-restoration.ts
new file mode 100644
index 0000000000..fcd4cc262e
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/view-restoration.ts
@@ -0,0 +1,56 @@
+import { parseAgentsRoute } from '@app/features/agents-view/core/route';
+import {
+ type Entry,
+ useBeforeLeave,
+ usePane,
+ useSplitRouter,
+} from '@app/lib/split-router';
+import { onCleanup, untrack, useContext } from 'solid-js';
+import { SplitLayoutContext } from './context';
+import { useSplitPanelOrThrow } from './layoutUtils';
+import { splitContentFromLocation } from './split-router/legacy-route';
+import type { RetainedViewState } from './view-state';
+
+/** Opt this view into resuming its last location and captured entry-state slices. */
+export function useViewRestoration(key?: string): void {
+ const layout = useContext(SplitLayoutContext);
+ if (!layout) throw new Error('View restoration requires SplitLayoutProvider');
+ const { handle } = useSplitPanelOrThrow();
+ const pane = usePane();
+ const router = useSplitRouter();
+ const entry = () => router.entry(pane());
+ const viewId =
+ key ??
+ untrack(() => {
+ const current = entry();
+ if (!current) throw new Error('View restoration requires a router entry');
+ const content = splitContentFromLocation(current.location);
+ return parseAgentsRoute(content.id) ? 'agents' : content.id;
+ });
+
+ function capture(entry: Entry): RetainedViewState | undefined {
+ const content = handle.content();
+ if (content.type !== 'component') return;
+ handle.captureEntryState();
+ return {
+ location: entry.location,
+ routeState: entry.state,
+ entryState: handle.currentEntryState(),
+ params: content.preserveParams ? content.params : undefined,
+ preserveParams: content.preserveParams,
+ };
+ }
+
+ const retention = layout.manager.viewState.register(
+ viewId,
+ handle.id,
+ entry,
+ capture
+ );
+ onCleanup(retention.dispose);
+ useBeforeLeave(({ from, onCommit }) => {
+ const publish = retention.remember(from);
+ if (publish) onCommit(publish);
+ return true;
+ });
+}
diff --git a/apps/web/src/components/app/split-layout/view-state.ts b/apps/web/src/components/app/split-layout/view-state.ts
new file mode 100644
index 0000000000..dd675b4052
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/view-state.ts
@@ -0,0 +1,150 @@
+import type { Entry, SplitLocation } from '@app/lib/split-router';
+import {
+ type Accessor,
+ createComputed,
+ on,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+import type { EntryState } from './layoutManager';
+
+export type RetainedViewState = {
+ location: SplitLocation;
+ routeState: unknown;
+ entryState: EntryState | undefined;
+ params?: Record<string, unknown>;
+ preserveParams?: boolean;
+};
+
+/** Layout-owned, memory-only state for views that explicitly register retention. */
+export function createViewState(options: {
+ activeOwner: Accessor<string | undefined>;
+ sessionKey?: Accessor<string | undefined>;
+}) {
+ type Source = {
+ key: string;
+ owner: string;
+ order: number;
+ capture: (entry: Entry) => RetainedViewState | undefined;
+ entry: Accessor<Entry | undefined>;
+ };
+ const sources = new Set<Source>();
+ const saved = new Map<
+ string,
+ { snapshot: RetainedViewState; order: number }
+ >();
+ const entryOwners = new Map<
+ string,
+ { generation: number; sessionKey: string | undefined }
+ >();
+ let generation = 0;
+ let order = 0;
+
+ function clear() {
+ generation += 1;
+ saved.clear();
+ }
+
+ if (options.sessionKey) {
+ createComputed(on(options.sessionKey, clear, { defer: true }));
+ }
+ onCleanup(() => {
+ clear();
+ sources.clear();
+ entryOwners.clear();
+ });
+
+ const authenticated = () =>
+ !options.sessionKey || options.sessionKey() !== undefined;
+
+ function observe(entry: Entry) {
+ let owner = entryOwners.get(entry.id);
+ if (!owner) {
+ owner = { generation, sessionKey: options.sessionKey?.() };
+ entryOwners.set(entry.id, owner);
+ }
+ return owner;
+ }
+
+ function currentEntry(entry: Entry) {
+ const owner = observe(entry);
+ const sessionKey = options.sessionKey?.();
+ // An initial URL can arrive before authentication identifies its owner.
+ if (
+ options.sessionKey &&
+ owner.sessionKey === undefined &&
+ sessionKey !== undefined
+ ) {
+ owner.generation = generation;
+ owner.sessionKey = sessionKey;
+ }
+ return owner.generation === generation;
+ }
+
+ function register(
+ key: string,
+ owner: string,
+ entry: Source['entry'],
+ capture: Source['capture']
+ ) {
+ const source: Source = {
+ key,
+ owner,
+ capture,
+ order: untrack(options.activeOwner) === owner ? ++order : 0,
+ entry,
+ };
+ sources.add(source);
+
+ return {
+ /** Capture now; the router calls the returned publisher only after commit. */
+ remember(entry: Entry): (() => void) | undefined {
+ if (!authenticated() || !currentEntry(entry)) return;
+ const capturedGeneration = generation;
+ const snapshot = capture(entry);
+ if (!snapshot) return;
+ const capturedOrder = source.order;
+ return () => {
+ if (!authenticated() || capturedGeneration !== generation) return;
+ const previous = saved.get(key);
+ if (!previous || capturedOrder >= previous.order) {
+ saved.set(key, { snapshot, order: capturedOrder });
+ }
+ };
+ },
+ dispose: () => sources.delete(source),
+ };
+ }
+
+ return {
+ register,
+ observe,
+ forget: (entryId: string) => entryOwners.delete(entryId),
+ /** A live opted-in view can resume without first leaving or unmounting. */
+ get(key: string): RetainedViewState | undefined {
+ if (!authenticated()) return;
+ let snapshot = saved.get(key)?.snapshot;
+ let newest = saved.get(key)?.order ?? -1;
+ for (const source of sources) {
+ if (source.key !== key || source.order < newest) continue;
+ const entry = source.entry();
+ if (!entry || !currentEntry(entry)) continue;
+ const live = source.capture(entry);
+ if (!live) continue;
+ snapshot = live;
+ newest = source.order;
+ }
+ return snapshot;
+ },
+ activate(owner: string) {
+ if (!authenticated()) return;
+ for (const source of sources) {
+ if (source.owner === owner) {
+ source.order = ++order;
+ }
+ }
+ },
+ };
+}
+
+export type ViewState = ReturnType<typeof createViewState>;
diff --git a/apps/web/src/features/agents-view/route-views.test.tsx b/apps/web/src/features/agents-view/route-views.test.tsx
index 07e7d1bc67..a31b254650 100644
--- a/apps/web/src/features/agents-view/route-views.test.tsx
+++ b/apps/web/src/features/agents-view/route-views.test.tsx
@@ -33,6 +33,9 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
},
}),
}));
+vi.mock('@components/app/split-layout/view-restoration', () => ({
+ useViewRestoration: () => {},
+}));
vi.mock('@components/app/split-layout/split-router/app-route-shell', () => ({
withAuth: (view: unknown) => view,
usePageViewTracking: () => {},
diff --git a/apps/web/src/features/agents-view/route-views.tsx b/apps/web/src/features/agents-view/route-views.tsx
index bdddac662b..79c0f06002 100644
--- a/apps/web/src/features/agents-view/route-views.tsx
+++ b/apps/web/src/features/agents-view/route-views.tsx
@@ -7,6 +7,7 @@ import {
usePageViewTracking,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { enableChatV3Agents } from '@core/constant/featureFlags';
import { useUserContext } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -85,6 +86,7 @@ function LegacyAgentsView() {
export const AgentsRouteView = withAuth(() => {
const panel = useSplitPanelOrThrow();
+ useViewRestoration();
const route = () => {
const content = panel.handle.content();
if (content.type === 'component' && content.id === 'routines') return;
diff --git a/apps/web/src/features/calendar-view/route-views.tsx b/apps/web/src/features/calendar-view/route-views.tsx
index 5251935e42..57b9e0e5d4 100644
--- a/apps/web/src/features/calendar-view/route-views.tsx
+++ b/apps/web/src/features/calendar-view/route-views.tsx
@@ -1,5 +1,6 @@
import { calendarSplitRoute } from '@app/routes/routes';
import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { lazy } from 'solid-js';
import { CalendarViewSkeleton } from './calendar-view-skeleton';
@@ -7,7 +8,7 @@ const CalendarView = lazy(async () => ({
default: (await import('./calendar-view')).CalendarView,
}));
-export const CalendarRouteView = withAuth(
- () => <CalendarView route={calendarSplitRoute} />,
- CalendarViewSkeleton
-);
+export const CalendarRouteView = withAuth(() => {
+ useViewRestoration();
+ return <CalendarView route={calendarSplitRoute} />;
+}, CalendarViewSkeleton);
diff --git a/apps/web/src/features/channels-view/route-views.tsx b/apps/web/src/features/channels-view/route-views.tsx
index 8bbd8587d1..a6dccc287f 100644
--- a/apps/web/src/features/channels-view/route-views.tsx
+++ b/apps/web/src/features/channels-view/route-views.tsx
@@ -6,6 +6,7 @@ import {
RedirectSplit,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { Show } from 'solid-js';
import { channelsSearch } from './channels-route';
import { ChannelsView } from './channels-view';
@@ -29,6 +30,7 @@ function ChannelsLegacyRouteView() {
}
export const ChannelsRouteView = withAuth(() => {
+ useViewRestoration();
const params = useParams<{ channelId?: string }>();
const detailRequested = () => typeof params.channelId === 'string';
diff --git a/apps/web/src/features/crm/route-views.test.tsx b/apps/web/src/features/crm/route-views.test.tsx
index 4993bdd8aa..f944c2916a 100644
--- a/apps/web/src/features/crm/route-views.test.tsx
+++ b/apps/web/src/features/crm/route-views.test.tsx
@@ -15,6 +15,9 @@ vi.mock('@components/app/split-layout/split-router/app-route-shell', () => ({
usePageViewTracking: () => {},
RedirectSplit: () => null,
}));
+vi.mock('@components/app/split-layout/view-restoration', () => ({
+ useViewRestoration: () => {},
+}));
vi.mock('@core/constant/featureFlags', () => ({
enableCrm: 'crm',
isFeatureEnabled: () => true,
diff --git a/apps/web/src/features/crm/route-views.tsx b/apps/web/src/features/crm/route-views.tsx
index 4d51636edd..06927b42b8 100644
--- a/apps/web/src/features/crm/route-views.tsx
+++ b/apps/web/src/features/crm/route-views.tsx
@@ -3,6 +3,7 @@ import {
usePageViewTracking,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { enableCrm, isFeatureEnabled } from '@core/constant/featureFlags';
import { useLocation } from '@solidjs/router';
import { createEffect, createMemo, lazy, on } from 'solid-js';
@@ -21,6 +22,7 @@ const Crm = lazy(async () => ({
export const CompaniesRouteView = withAuth(() => {
if (!isFeatureEnabled(enableCrm))
return <RedirectSplit to={{ type: 'component', id: 'home' }} />;
+ useViewRestoration();
usePageViewTracking('companies');
const route = createCrmRoute();
const crmView = new URLSearchParams(window.location.search).get(
diff --git a/apps/web/src/features/drive-view/route-views.test.tsx b/apps/web/src/features/drive-view/route-views.test.tsx
index bc4e3b1622..8694703609 100644
--- a/apps/web/src/features/drive-view/route-views.test.tsx
+++ b/apps/web/src/features/drive-view/route-views.test.tsx
@@ -13,6 +13,9 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
handle: { content: () => ({ type: 'component', params: {} }) },
}),
}));
+vi.mock('@components/app/split-layout/view-restoration', () => ({
+ useViewRestoration: () => {},
+}));
vi.mock('@app/lib/analytics/analytics-context', () => ({
useAnalytics: () => ({ pageView: vi.fn(), track: vi.fn() }),
}));
diff --git a/apps/web/src/features/drive-view/route-views.tsx b/apps/web/src/features/drive-view/route-views.tsx
index 4c801f95f7..50004cd37f 100644
--- a/apps/web/src/features/drive-view/route-views.tsx
+++ b/apps/web/src/features/drive-view/route-views.tsx
@@ -6,6 +6,7 @@ import {
AppView,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { useIsAuthenticated } from '@core/auth';
import { lazy, Show } from 'solid-js';
import {
@@ -20,6 +21,7 @@ const DriveCallDetail = lazy(async () => ({
}));
const AuthenticatedDriveRouteView = withAuth(() => {
+ useViewRestoration();
const panel = useSplitPanelOrThrow();
const props = (): DriveViewProps => {
const content = panel.handle.content();
diff --git a/apps/web/src/features/email-view/route-views.tsx b/apps/web/src/features/email-view/route-views.tsx
index f0f12969b3..990931ad39 100644
--- a/apps/web/src/features/email-view/route-views.tsx
+++ b/apps/web/src/features/email-view/route-views.tsx
@@ -5,6 +5,7 @@ import {
RedirectSplit,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { Show } from 'solid-js';
import { URL_PARAMS as EMAIL_URL_PARAMS } from '../email-thread/core/location';
import { emailDetailSearch } from './email-route';
@@ -28,6 +29,7 @@ function MailLegacyRouteView() {
}
export const MailRouteView = withAuth(() => {
+ useViewRestoration();
const params = useParams<{ threadId?: string }>();
const detailRequested = () => typeof params.threadId === 'string';
diff --git a/apps/web/src/features/home/route-views.tsx b/apps/web/src/features/home/route-views.tsx
index 1ccdb8f8a6..abe9e7da63 100644
--- a/apps/web/src/features/home/route-views.tsx
+++ b/apps/web/src/features/home/route-views.tsx
@@ -8,6 +8,7 @@ import {
RedirectSplit,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { Show } from 'solid-js';
import {
homeCalendarLegacyTarget,
@@ -48,6 +49,7 @@ function HomeLegacyRouteView() {
}
export const HomeRouteView = withAuth(() => {
+ useViewRestoration();
const params = useParams<HomeDetailParams>();
const detailRequested = () =>
homeDetailParamsFromRoute(params) !== undefined ||
diff --git a/apps/web/src/features/next-soup/route-views.tsx b/apps/web/src/features/next-soup/route-views.tsx
index 1225a0dc0f..85c447a84c 100644
--- a/apps/web/src/features/next-soup/route-views.tsx
+++ b/apps/web/src/features/next-soup/route-views.tsx
@@ -6,6 +6,7 @@ import {
usePageViewTracking,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { useUserContext } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { lazy, Show } from 'solid-js';
@@ -30,6 +31,7 @@ const SoupView = lazy(async () => ({
}));
function TrackedRecentView() {
+ useViewRestoration();
usePageViewTracking('recent');
const preset = getViewPreset('recent');
return (
@@ -61,11 +63,13 @@ export const RecentRouteView = withAuth(() => {
});
export const CallsRouteView = withAuth(() => {
+ useViewRestoration();
usePageViewTracking('calls');
return <CallsView />;
});
export const FoldersRouteView = withAuth(() => {
+ useViewRestoration();
usePageViewTracking('folders');
const user = useUserContext();
const preset = getViewPreset('folders', undefined, {
@@ -90,6 +94,7 @@ type SearchRouteViewParams = {
};
export const SearchRouteView = withAuth(() => {
+ useViewRestoration();
const panel = useSplitPanelOrThrow();
const params = (): SearchRouteViewParams => {
const content = panel.handle.content();
diff --git a/apps/web/src/features/reviews-view/route-views.tsx b/apps/web/src/features/reviews-view/route-views.tsx
index 074f8a847e..e9353c1dbf 100644
--- a/apps/web/src/features/reviews-view/route-views.tsx
+++ b/apps/web/src/features/reviews-view/route-views.tsx
@@ -5,6 +5,7 @@ import {
usePageViewTracking,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { enableTasksReviews } from '@core/constant/featureFlags';
import { lazy, onMount, Show } from 'solid-js';
import { ReviewsViewSkeleton } from './reviews-view-skeleton';
@@ -27,6 +28,7 @@ function DisabledReviewsRoute() {
}
function TrackedReviewsView() {
+ useViewRestoration();
usePageViewTracking('reviews');
return <ReviewsView />;
}
diff --git a/apps/web/src/features/tasks-view/route-views.tsx b/apps/web/src/features/tasks-view/route-views.tsx
index 2bd81046cc..dfb2d10be4 100644
--- a/apps/web/src/features/tasks-view/route-views.tsx
+++ b/apps/web/src/features/tasks-view/route-views.tsx
@@ -23,6 +23,7 @@ import {
RedirectSplit,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
+import { useViewRestoration } from '@components/app/split-layout/view-restoration';
import { LoadingBlock } from '@core/component/LoadingBlock';
import { enableProjects } from '@core/constant/featureFlags';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -43,6 +44,7 @@ function TasksLegacyRouteView() {
}
export const TasksRouteView = withAuth(() => {
+ useViewRestoration();
const params = useParams<{ taskId?: string; projectId?: string }>();
return (
<AppView
diff --git a/apps/web/src/lib/split-router/README.md b/apps/web/src/lib/split-router/README.md
new file mode 100644
index 0000000000..5cc31bf9c2
--- /dev/null
+++ b/apps/web/src/lib/split-router/README.md
@@ -0,0 +1,21 @@
+# SplitRouter leave guards
+
+`useBeforeLeave` runs when a navigation leaves the registering route, closes its
+pane, or changes an explicitly watched search namespace. Returning `false` keeps
+the current destination. Solid cleanup only unregisters the guard.
+
+Use `context.onCommit(callback)` to stage a synchronous side effect that must run
+only after the navigation commits. Capture outgoing state while the guard runs;
+the callback runs after the new panes and URL are applied, when the outgoing
+component can already be disposed.
+
+Callbacks belong to the navigation, not the guard phase or the mounted component.
+Refusal, cancellation, supersession, disposal, and failed application discard all
+staged callbacks. Unchanged navigation and activation of another content owner do
+not publish callbacks. Late registration after the guard phase ends is ignored.
+A throwing callback is logged without changing the successful navigation result
+or preventing later callbacks from running.
+
+Preload and middleware errors that the router recovers from still allow commit
+callbacks when navigation commits. Host-leave permission checks cannot confirm
+that the host actually navigates, so their `onCommit` registration is a no-op.
diff --git a/apps/web/src/lib/split-router/router/create-router.ts b/apps/web/src/lib/split-router/router/create-router.ts
index c11ae9f6c0..c70d4bb394 100644
--- a/apps/web/src/lib/split-router/router/create-router.ts
+++ b/apps/web/src/lib/split-router/router/create-router.ts
@@ -48,7 +48,8 @@ export function createSplitRouter(options: SplitRouterOptions) {
};
const runner = createRunner({
- phases: (waiting) => createPhaseScopes(phaseOptions, waiting),
+ phases: (waiting, onCommit) =>
+ createPhaseScopes(phaseOptions, waiting, onCommit),
live: () => untrack(panes.ids),
});
diff --git a/apps/web/src/lib/split-router/router/phases.ts b/apps/web/src/lib/split-router/router/phases.ts
index dd863b6336..415b84476d 100644
--- a/apps/web/src/lib/split-router/router/phases.ts
+++ b/apps/web/src/lib/split-router/router/phases.ts
@@ -24,6 +24,7 @@ import {
import { runMiddleware, type SplitRouterMiddleware } from './middleware';
import { preloadLocation, withinBudget } from './preload';
import type { Event as RunEvent, Running, State as RunState } from './run';
+import type { RegisterCommitCallback } from './runner';
import type { Navigation, PaneTarget } from './types';
type Report = (event: RunEvent) => void;
@@ -115,17 +116,31 @@ export function createPhaseScopes(
current(pane: PaneId): Entry | undefined;
preloadBudgetMs: number;
},
- waiting: (state: Running) => void
+ waiting: (state: Running) => void,
+ registerCommit: RegisterCommitCallback
): PhaseScopes {
const { routes, guards } = options;
+ const onCommit =
+ ({ navigation, signal }: RunContext) =>
+ (callback: () => void) => {
+ if (!signal.aborted) registerCommit(navigation, callback);
+ };
+
const targetChecks = ({ navigation, signal }: RunContext): Check[] =>
navigation.targets.flatMap(({ pane, from, to }) => {
if (!from) return [];
const depth = firstChangedDepth(routes, from, to);
- const context = { pane, from, to, cause: navigation.cause, signal };
+ const context = {
+ pane,
+ from,
+ to,
+ cause: navigation.cause,
+ signal,
+ onCommit: onCommit({ navigation, signal }),
+ };
return checksFor(guards.select(pane, depth, context), context);
});
@@ -137,7 +152,13 @@ export function createPhaseScopes(
const from = options.current(pane);
if (!from) return [];
- const context = { pane, from, cause: navigation.cause, signal };
+ const context = {
+ pane,
+ from,
+ cause: navigation.cause,
+ signal,
+ onCommit: onCommit({ navigation, signal }),
+ };
return checksFor(guards.select(pane, PANE_LEVEL), context);
});
diff --git a/apps/web/src/lib/split-router/router/runner.ts b/apps/web/src/lib/split-router/router/runner.ts
index b1cd0e5eec..6c75e64240 100644
--- a/apps/web/src/lib/split-router/router/runner.ts
+++ b/apps/web/src/lib/split-router/router/runner.ts
@@ -53,6 +53,11 @@ type PaneRun = { pane: PaneId; machine: Run };
type Settle = (result: NavigationResult) => void;
+export type RegisterCommitCallback = (
+ navigation: Navigation,
+ callback: () => void
+) => void;
+
const URL_KEY = '@url';
/** What each pane, and the URL navigation run, has in flight. */
@@ -133,12 +138,18 @@ export type Runner = ReturnType<typeof createRunner>;
*/
export function createRunner(options: {
/** Phase work for a run; `waiting` hears when a phase goes async. */
- phases(waiting: (state: Running) => void): MachineScopes<RunState, RunEvent>;
+ phases(
+ waiting: (state: Running) => void,
+ onCommit: RegisterCommitCallback
+ ): MachineScopes<RunState, RunEvent>;
/** Panes still open; runs of the others are dropped once idle. */
live(): readonly PaneId[];
}) {
const inFlight = createInFlight();
- const settlers = new WeakMap<Navigation, Settle>();
+ const settlers = new WeakMap<
+ Navigation,
+ { settle: Settle; callbacks: (() => void)[] }
+ >();
const outstanding = new Set<Promise<unknown>>();
const waiters: (() => void)[] = [];
const paneRuns: PaneRun[] = [];
@@ -159,9 +170,12 @@ export function createRunner(options: {
const deferred = Promise.withResolvers<NavigationResult>();
let result: NavigationResult | undefined;
- settlers.set(navigation, (value) => {
- result = value;
- deferred.resolve(value);
+ settlers.set(navigation, {
+ settle(value) {
+ result = value;
+ deferred.resolve(value);
+ },
+ callbacks: [],
});
fireAndForget(track(deferred.promise), 'split-router');
begin();
@@ -172,7 +186,11 @@ export function createRunner(options: {
const settle = (navigation: Navigation, result: NavigationResult) => {
const settler = settlers.get(navigation);
settlers.delete(navigation);
- settler?.(result);
+ settler?.settle(result);
+ };
+
+ const onCommit: RegisterCommitCallback = (navigation, callback) => {
+ settlers.get(navigation)?.callbacks.push(callback);
};
const isOpen = () => {
@@ -201,7 +219,19 @@ export function createRunner(options: {
committing += 1;
try {
- return navigation.apply(entries);
+ const result = navigation.apply(entries);
+ const callbacks = settlers.get(navigation)?.callbacks.splice(0) ?? [];
+ if (result.status === 'committed') {
+ for (const callback of callbacks) {
+ if (disposed) break;
+ try {
+ callback();
+ } catch (error) {
+ console.error('Split router commit callback failed', error);
+ }
+ }
+ }
+ return result;
} catch (error) {
console.error('Split router could not commit a navigation', error);
return CANCELLED_RESULT;
@@ -216,7 +246,10 @@ export function createRunner(options: {
key: string,
execute: (command: RunCommand) => void
): Run => {
- const scopes = options.phases((state) => inFlight.show(key, state));
+ const scopes = options.phases(
+ (state) => inFlight.show(key, state),
+ onCommit
+ );
const machine = createMachine<RunState, RunEvent, RunCommand>({
initial: IDLE,
def: runDef,
diff --git a/apps/web/src/lib/split-router/router/types.ts b/apps/web/src/lib/split-router/router/types.ts
index 3dd526fa28..567b515781 100644
--- a/apps/web/src/lib/split-router/router/types.ts
+++ b/apps/web/src/lib/split-router/router/types.ts
@@ -94,6 +94,12 @@ export type LeaveGuardContext = {
to?: Entry;
cause: NavigationCause;
signal: AbortSignal;
+ /**
+ * Runs a synchronous callback once after this router navigation commits.
+ * Cancelled, unchanged, and owner-activation results discard the callback.
+ * Register while this guard is active. Host-leave checks never run callbacks.
+ */
+ onCommit(callback: () => void): void;
};
export type LeaveGuard = (context: LeaveGuardContext) => MaybePromise<boolean>;
diff --git a/apps/web/src/lib/split-router/router/url-navigation.ts b/apps/web/src/lib/split-router/router/url-navigation.ts
index 2079d2d843..dd47ed2c97 100644
--- a/apps/web/src/lib/split-router/router/url-navigation.ts
+++ b/apps/web/src/lib/split-router/router/url-navigation.ts
@@ -210,6 +210,8 @@ export function createUrlNavigation(options: {
from,
cause: 'external' as const,
signal: UNCANCELLABLE,
+ // The host only asks permission; the router cannot observe its commit.
+ onCommit: () => {},
};
return checksFor(guards.select(pane, PANE_LEVEL), context);
diff --git a/apps/web/src/lib/split-router/solid/use-before-leave.ts b/apps/web/src/lib/split-router/solid/use-before-leave.ts
index 9286954179..86ae50a303 100644
--- a/apps/web/src/lib/split-router/solid/use-before-leave.ts
+++ b/apps/web/src/lib/split-router/solid/use-before-leave.ts
@@ -6,6 +6,7 @@ import { usePaneContext, useSplitRouter } from './context';
* Runs before a navigation would unmount this view or close its pane.
* Opt into search namespaces to also protect updates that keep this view mounted.
* Return false, or a Promise of false, to keep the pane where it is.
+ * Stage commit-only side effects with context.onCommit; cleanup is not a commit.
*/
export function useBeforeLeave(
guard: LeaveGuard,
diff --git a/apps/web/src/lib/split-router/tests/commit-callbacks.test.ts b/apps/web/src/lib/split-router/tests/commit-callbacks.test.ts
new file mode 100644
index 0000000000..df36be340d
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/commit-callbacks.test.ts
@@ -0,0 +1,331 @@
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createMemoryHistory } from '../history/memory';
+import { createSolidRouterHistory } from '../history/solid-router';
+import { createMemoryPaneStore } from '../panes/memory-store';
+import { createSplitRouter } from '../router/create-router';
+import type { LeaveGuardContext, SplitRouterOptions } from '../router/types';
+import { defineRoute } from '../routes/define';
+import type { Entry } from '../routes/types';
+import { createFakeSolidRouter } from './fake-solid-router';
+import { appRoute, appRoutes, createTestPolicy, mailRoute } from './fixtures';
+
+const disposers: (() => void)[] = [];
+
+function setup(url = '/home', overrides: Partial<SplitRouterOptions> = {}) {
+ const history = createMemoryHistory(url);
+ const { router, dispose } = createRoot((dispose) => ({
+ router: createSplitRouter({
+ routes: appRoutes,
+ history,
+ paneStore: createMemoryPaneStore<Entry>(),
+ policy: createTestPolicy().policy,
+ ...overrides,
+ }),
+ dispose,
+ }));
+ disposers.push(() => {
+ router.dispose();
+ dispose();
+ });
+ return { router, history, pane: router.panes()[0]! };
+}
+
+afterEach(() => {
+ for (const dispose of disposers.splice(0)) dispose();
+ vi.restoreAllMocks();
+});
+
+describe('leave guard commit callbacks', () => {
+ it('publishes once after middleware and the destination and URL commit', async () => {
+ const release = Promise.withResolvers<void>();
+ const { router, history, pane } = setup('/home', {
+ middleware: [
+ ({ path }) => (path === '/mail' ? release.promise : undefined),
+ ],
+ });
+ const published: { path: string; route: string | undefined }[] = [];
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(() => {
+ published.push({
+ path: history.read().path,
+ route: router.entry(pane)?.location.route.matches.at(-1)?.id,
+ });
+ });
+ return true;
+ });
+ const navigation = router.navigatePane(pane, '/mail');
+ expect(published).toEqual([]);
+ release.resolve();
+ expect(await navigation).toMatchObject({ status: 'committed' });
+ expect(published).toEqual([{ path: '/mail', route: 'mail' }]);
+ await router.settled();
+ expect(published).toEqual([{ path: '/mail', route: 'mail' }]);
+ });
+
+ it('discards every callback when a later guard refuses', async () => {
+ const { router, pane } = setup();
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(publish);
+ return true;
+ });
+ router.registerGuard(pane, 1, () => false);
+ expect(await router.navigatePane(pane, '/mail')).toEqual({
+ status: 'cancelled',
+ });
+ expect(publish).not.toHaveBeenCalled();
+ });
+
+ it('discards staged callbacks when middleware cancels', async () => {
+ const { router, pane } = setup('/home', {
+ middleware: [
+ ({ path, cancel }) => (path === '/mail' ? cancel() : undefined),
+ ],
+ });
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(publish);
+ return true;
+ });
+ expect(await router.navigatePane(pane, '/mail')).toEqual({
+ status: 'cancelled',
+ });
+ expect(publish).not.toHaveBeenCalled();
+ });
+
+ it('publishes when a middleware failure permits navigation to commit', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { router, pane } = setup('/home', {
+ middleware: [
+ ({ path }) => {
+ if (path === '/mail') throw new Error('Middleware failed');
+ },
+ ],
+ });
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(publish);
+ return true;
+ });
+ expect(await router.navigatePane(pane, '/mail')).toMatchObject({
+ status: 'committed',
+ });
+ expect(publish).toHaveBeenCalledOnce();
+ });
+
+ it('discards staged callbacks when applying navigation fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { router, history, pane } = setup();
+ vi.spyOn(history, 'write').mockImplementationOnce(() => {
+ throw new Error('History write failed');
+ });
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(publish);
+ return true;
+ });
+ expect(await router.navigatePane(pane, '/mail')).toEqual({
+ status: 'cancelled',
+ });
+ expect(publish).not.toHaveBeenCalled();
+ expect(await router.navigatePane(pane, '/drive')).toMatchObject({
+ status: 'committed',
+ });
+ expect(publish).toHaveBeenCalledOnce();
+ });
+
+ it('still publishes when a failed preload permits navigation to commit', async () => {
+ const failingMail = defineRoute({
+ ...mailRoute,
+ preload: () => Promise.reject(new Error('Preload failed')),
+ });
+ const { router, pane } = setup('/home', {
+ routes: {
+ ...appRoutes,
+ definitions: [
+ {
+ ...appRoute,
+ children: appRoute.children.map((route) =>
+ route.id === mailRoute.id ? failingMail : route
+ ),
+ },
+ ],
+ },
+ });
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(publish);
+ return true;
+ });
+ expect(await router.navigatePane(pane, '/mail')).toMatchObject({
+ status: 'committed',
+ });
+ expect(publish).toHaveBeenCalledOnce();
+ });
+
+ it('ignores early and late registrations from a superseded guard', async () => {
+ const release = Promise.withResolvers<boolean>();
+ const finished = Promise.withResolvers<void>();
+ const { router, pane } = setup();
+ const publishStale = vi.fn();
+ const publishCurrent = vi.fn();
+ router.registerGuard(pane, 1, async ({ to, onCommit }) => {
+ if (to?.location.route.matches.at(-1)?.id === 'mail') {
+ onCommit(publishStale);
+ const allowed = await release.promise;
+ onCommit(publishStale);
+ finished.resolve();
+ return allowed;
+ }
+ onCommit(publishCurrent);
+ return true;
+ });
+ const superseded = router.navigatePane(pane, '/mail');
+ expect(await router.navigatePane(pane, '/drive')).toMatchObject({
+ status: 'committed',
+ });
+ expect(await superseded).toEqual({ status: 'cancelled' });
+ release.resolve(true);
+ await finished.promise;
+ expect(publishStale).not.toHaveBeenCalled();
+ expect(publishCurrent).toHaveBeenCalledOnce();
+ });
+
+ it('discards callbacks after disposal even when the guard resolves later', async () => {
+ const release = Promise.withResolvers<boolean>();
+ const finished = Promise.withResolvers<void>();
+ const { router, pane } = setup();
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, async ({ onCommit }) => {
+ onCommit(publish);
+ const allowed = await release.promise;
+ onCommit(publish);
+ finished.resolve();
+ return allowed;
+ });
+ const navigation = router.navigatePane(pane, '/mail');
+ router.dispose();
+ expect(await navigation).toEqual({ status: 'cancelled' });
+ release.resolve(true);
+ await finished.promise;
+ expect(publish).not.toHaveBeenCalled();
+ });
+
+ it('does not publish when another pane owns the requested detail', async () => {
+ const { router, pane } = setup('/home/~/drive/md/document-one');
+ const publish = vi.fn();
+ const original = router.entry(pane);
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(publish);
+ return true;
+ });
+ expect(
+ await router.navigatePane(pane, '/drive/md/document-one')
+ ).toMatchObject({ status: 'activated' });
+ expect(router.entry(pane)).toBe(original);
+ expect(publish).not.toHaveBeenCalled();
+ });
+
+ it('does not run leave callbacks for unchanged navigation', async () => {
+ const { router, pane } = setup();
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(publish);
+ return true;
+ });
+ expect(await router.navigatePane(pane, '/home')).toMatchObject({
+ status: 'unchanged',
+ });
+ expect(publish).not.toHaveBeenCalled();
+ });
+
+ it('publishes pane removal callbacks after the pane disappears', async () => {
+ const { router, pane } = setup('/home/~/mail');
+ const published: boolean[] = [];
+ const destinations: (Entry | undefined)[] = [];
+ router.registerGuard(pane, 1, ({ to, onCommit }) => {
+ destinations.push(to);
+ onCommit(() => published.push(router.panes().includes(pane)));
+ return true;
+ });
+ expect(await router.remove(pane)).toBe(true);
+ expect(destinations).toEqual([undefined]);
+ expect(published).toEqual([false]);
+ });
+
+ it('discards callbacks from all panes when a whole-window navigation is refused', async () => {
+ const { router, pane } = setup('/home/~/mail');
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(publish);
+ return true;
+ });
+ router.registerGuard(router.panes()[1]!, 1, () => false);
+ expect(await router.navigate('/drive')).toEqual({ status: 'cancelled' });
+ expect(publish).not.toHaveBeenCalled();
+ expect(router.panes()).toHaveLength(2);
+ });
+
+ it('contains callback errors without cancelling the commit or skipping later callbacks', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { router, pane } = setup();
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(() => {
+ throw new Error('Capture publication failed');
+ });
+ onCommit(publish);
+ return true;
+ });
+ expect(await router.navigatePane(pane, '/mail')).toMatchObject({
+ status: 'committed',
+ });
+ expect(error).toHaveBeenCalledWith(
+ 'Split router commit callback failed',
+ expect.any(Error)
+ );
+ expect(publish).toHaveBeenCalledOnce();
+ expect(router.entry(pane)?.location.route.matches.at(-1)?.id).toBe('mail');
+ });
+
+ it('stops remaining callbacks when a callback disposes the router', async () => {
+ const { router, pane } = setup();
+ const publish = vi.fn();
+ router.registerGuard(pane, 1, ({ onCommit }) => {
+ onCommit(router.dispose);
+ onCommit(publish);
+ return true;
+ });
+ expect(await router.navigatePane(pane, '/mail')).toMatchObject({
+ status: 'committed',
+ });
+ expect(publish).not.toHaveBeenCalled();
+ });
+
+ it('never publishes callbacks from host-leave permission checks', async () => {
+ const solid = createFakeSolidRouter('/app/home');
+ const { router, pane } = setup('/home', {
+ history: createSolidRouterHistory({
+ location: solid.location,
+ navigate: solid.navigate,
+ base: '/app',
+ beforeLeave: solid.beforeLeave,
+ landedPath: solid.landed,
+ }),
+ });
+ const publish = vi.fn();
+ const guard = vi.fn(({ onCommit }: LeaveGuardContext) => {
+ onCommit(publish);
+ return true;
+ });
+ router.registerGuard(pane, 1, guard);
+ solid.leave('/outside-app');
+ expect(guard).toHaveBeenCalledOnce();
+ expect(publish).not.toHaveBeenCalled();
+ expect(await router.navigatePane(pane, '/mail')).toMatchObject({
+ status: 'committed',
+ });
+ expect(publish).toHaveBeenCalledOnce();
+ });
+});
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index be51039d94..2dafe88f31 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -33,6 +33,10 @@ omits the key. A pipeline has its own path, `/app/companies/pipeline/<uuid>`;
older `sN.crm.tab=pipeline:<uuid>` URLs and shared `crmView` links that show a
pipeline redirect there. Choosing Companies, People, an activity tab, a pipeline,
or a list updates the URL, and browser Back and Forward restore it.
+Ordinary sidebar and Go To navigation also resumes Customers' last location and
+captured entry state within the current account session, including an open
+pipeline or record. Direct links and new-split actions keep their requested
+destination; reload and account changes clear the remembered location.
The four activity tabs show CRM-linked content, not the whole app: Tasks and
Calls require a Companies or Contacts reference; Notes are linked Markdown
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 9dd634b6b0..d4b089b502 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -426,6 +426,22 @@ cancels that navigation without adding a duplicate history step.
A later ordinary rail press also cancels a new split still preloading from the
active split's earlier Shift-press. Already-open splits and pending work from
other splits remain intact.
+
+Ordinary rail, More-menu, and Go To shortcut navigation resumes opted-in apps'
+last locations during the current session, including nested details, tabs,
+filters, and local state registered with the split entry (such as scroll or
+selection). Views opt in with `useViewRestoration()`; views without the hook keep
+ordinary navigation behavior. The mobile dock uses the same memory; Search taps
+still start a fresh search. Memory is account-scoped and clears on reload,
+sign-out, or account changes. A leave guard stages each snapshot, but only a
+committed navigation saves it; refusal, cancellation, failure, and supersession
+leave the saved snapshot unchanged. Direct links and explicit Shift/open-in-split
+actions keep their requested destination. Closing a detail before switching apps
+remembers the list, not the closed detail. Views unmount normally; this is not a
+keep-alive cache for editors or other transient UI.
+Verify Chat → open channel → Calendar → Chat restores the same channel, then
+repeat with a filtered list and a nested Drive item. Check mobile dock switching,
+split Back/Forward, refused leave guards, explicit links, and account changes.
Verify rapid app presses, returning to the currently shown app while another app
loads, split focus changes, closing a split, and split Back/Forward. The last
requested destination must win, and a later return to an earlier view must not