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(desktop): browser-style tabs in the title bar (#8514)

Eric Hayes8de2cc7af401
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 7d76123074..8461682ce7 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -260,6 +260,7 @@ the user's newest account for that app from the last fifteen minutes.
- 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`.
+- Desktop tabs (`components/app/tab-layout`, macOS + `enable-desktop-tabs`) hold one split layout per tab over the router's `layoutSnapshot`/`restoreLayout`; only the active tab is live, and the strip renders in the title bar's center slot. Cmd+click becomes a background tab through `openInNewTabMiddleware`, so tab operations must disarm the intent tracker before navigating. Tabs are not draggable. See the tabs section of `docs/agent-guide/navigation.md` at the repository root.
- 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.
- Preserve focused chrome editors during deferred split insertion/removal autofocus; explicit return-focus commands may still focus the pane.
diff --git a/apps/web/src/components/app/DesktopTitleBar.tsx b/apps/web/src/components/app/DesktopTitleBar.tsx
index 7a119d2404..7595ec50cf 100644
--- a/apps/web/src/components/app/DesktopTitleBar.tsx
+++ b/apps/web/src/components/app/DesktopTitleBar.tsx
@@ -1,6 +1,7 @@
import { LIST_VIEW_ID } from '@app/constants/list-views';
import { globalSplitManager } from '@app/signal/splitLayout';
import { splitBackInterceptor } from '@components/app/split-layout/back-interceptor';
+import { DesktopTabStrip } from '@components/app/tab-layout/DesktopTabStrip';
import { TOKENS } from '@core/hotkey/tokens';
import CaretLeftIcon from '@icon/system/regular/caret-left.svg';
import CaretRightIcon from '@icon/system/regular/caret-right.svg';
@@ -41,6 +42,12 @@ export function DesktopTitleBar() {
<CaretRightIcon class="size-4" />
</Button>
</div>
+ <div
+ data-tauri-drag-region
+ class="flex h-full min-w-0 flex-1 items-center"
+ >
+ <DesktopTabStrip />
+ </div>
<Show when={globalSplitManager()}>
{(manager) => (
<Button
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index d5060d232c..4f6da83c90 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -2,6 +2,7 @@ import { CreateContextProvider } from '@app/features/command/context/create-cont
import { useSplitRouter } from '@app/lib/split-router';
import { setGlobalSplitManager } from '@app/signal/splitLayout';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
+import { DesktopTabsController } from '@components/app/tab-layout/DesktopTabsController';
import { Resize } from '@core/component/Resize';
import { useIsAuthenticated, useUserId } from '@core/context/user';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
@@ -51,6 +52,7 @@ export function SplitLayoutProvider(props: ParentProps) {
return (
<SplitLayoutContext.Provider value={{ manager: splitManager }}>
<CreateContextProvider focusedPaneId={splitManager.activeSplitId}>
+ <DesktopTabsController router={router} manager={splitManager} />
{props.children}
</CreateContextProvider>
</SplitLayoutContext.Provider>
diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
index e6002846ec..d72b803c7f 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
@@ -33,6 +33,7 @@ import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
+import { openInNewTabMiddleware } from '@components/app/tab-layout/open-in-tab-middleware';
import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';
import { match } from 'ts-pattern';
import { decodeLegacyPair } from './legacy-route';
@@ -279,6 +280,9 @@ export function createAppSplitRouterMiddleware(
state: AppMiddlewareState
): readonly SplitRouterMiddleware[] {
return [
+ // First: a cmd+click becomes a tab with the proposed entry as-is; legacy
+ // redirects still run when that tab is activated.
+ openInNewTabMiddleware,
(context) => redirectLegacyRoutes(context, state),
redirectLegacyCrmPipeline,
migrateLegacySearch,
diff --git a/apps/web/src/components/app/tab-layout/DesktopTabStrip.tsx b/apps/web/src/components/app/tab-layout/DesktopTabStrip.tsx
new file mode 100644
index 0000000000..9023782380
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/DesktopTabStrip.tsx
@@ -0,0 +1,102 @@
+import { t } from '@app/lib/i18n';
+import { globalTabManager } from '@app/signal/tabLayout';
+import { TOKENS } from '@core/hotkey/tokens';
+import PlusIcon from '@icon/system/regular/plus.svg';
+import SquareSplitIcon from '@icon/system/regular/square-split-horizontal.svg';
+import XIcon from '@icon/system/regular/x.svg';
+import { Button, cn, Tooltip } from '@ui';
+import { For, Show } from 'solid-js';
+import type { DesktopTab, TabManager } from './tab-manager';
+
+function TabItem(props: { tabManager: TabManager; tab: DesktopTab }) {
+ const title = () => props.tabManager.tabTitle(props.tab) ?? t('tabs.newTab');
+ const active = () => props.tabManager.activeTabId() === props.tab.id;
+ const paneCount = () => props.tabManager.tabPaneCount(props.tab);
+ const closable = () => props.tabManager.tabs().length > 1;
+
+ return (
+ <div
+ role="tab"
+ aria-selected={active()}
+ class={cn(
+ 'group flex h-7 min-w-9 max-w-44 flex-initial basis-40 items-center gap-1 rounded-md pl-2 pr-1 text-xs select-none',
+ active()
+ ? 'bg-active text-ink'
+ : 'text-ink-muted not-touch:hover:bg-hover not-touch:hover:text-ink'
+ )}
+ onClick={() => props.tabManager.activateTab(props.tab.id)}
+ onAuxClick={(event) => {
+ if (event.button === 1 && closable()) {
+ props.tabManager.closeTab(props.tab.id);
+ }
+ }}
+ >
+ <Show when={paneCount() > 1}>
+ <Tooltip label={t('tabs.splitCount', { count: paneCount() })} as="span">
+ <span class="flex shrink-0 items-center gap-0.5 text-2xs text-ink-extra-muted">
+ <SquareSplitIcon class="size-3.5" />
+ {paneCount()}
+ </span>
+ </Tooltip>
+ </Show>
+ <Tooltip label={title()} as="span" class="min-w-0 flex-1">
+ <span class="block truncate">{title()}</span>
+ </Tooltip>
+ <Show when={closable()}>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ label={t('tabs.closeTab')}
+ noTouchResize
+ class={cn(
+ 'shrink-0',
+ !active() && 'invisible not-touch:group-hover:visible'
+ )}
+ onClick={(event) => {
+ event.stopPropagation();
+ props.tabManager.closeTab(props.tab.id);
+ }}
+ >
+ <XIcon />
+ </Button>
+ </Show>
+ </div>
+ );
+}
+
+/**
+ * The browser-style tab strip in the title bar's center slot. Renders nothing
+ * until the tab manager exists (desktop tabs enabled and a user signed in).
+ */
+export function DesktopTabStrip() {
+ return (
+ <Show when={globalTabManager()}>
+ {(tabManager) => (
+ <div
+ data-desktop-tab-strip
+ class="flex h-full min-w-0 flex-1 items-center gap-1 px-2"
+ >
+ <div
+ role="tablist"
+ aria-label={t('tabs.tablist')}
+ class="flex min-w-0 items-center gap-1 overflow-hidden"
+ >
+ <For each={tabManager().tabs()}>
+ {(tab) => <TabItem tabManager={tabManager()} tab={tab} />}
+ </For>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label={t('tabs.newTab')}
+ hotkey={TOKENS.tabs.new}
+ onClick={() => tabManager().newTab()}
+ >
+ <PlusIcon class="size-4" />
+ </Button>
+ <div data-tauri-drag-region class="h-full min-w-4 flex-1" />
+ </div>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/components/app/tab-layout/DesktopTabsController.tsx b/apps/web/src/components/app/tab-layout/DesktopTabsController.tsx
new file mode 100644
index 0000000000..de90852b45
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/DesktopTabsController.tsx
@@ -0,0 +1,111 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { t } from '@app/lib/i18n';
+import type { SplitRouter } from '@app/lib/split-router';
+import { setGlobalTabManager } from '@app/signal/tabLayout';
+import type { SplitManager } from '@components/app/split-layout/layoutManager';
+import { enableDesktopTabs } from '@core/constant/featureFlags';
+import { useUserId } from '@core/context/user';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+import { TOKENS } from '@core/hotkey/tokens';
+import { isPlatform } from '@core/util/platform';
+import { type as osType } from '@tauri-apps/plugin-os';
+import { onCleanup, Show } from 'solid-js';
+import { installOpenInNewTabIntentTracker } from './open-in-tab-intent';
+import { createTabManager, type TabManager } from './tab-manager';
+
+/** Whether this build can show desktop tabs; the flag still decides per user. */
+export function desktopTabsSupported(): boolean {
+ return isPlatform('desktop') && osType() === 'macos';
+}
+
+function registerTabHotkeys(tabManager: TabManager) {
+ registerHotkey({
+ hotkeyToken: TOKENS.tabs.new,
+ hotkey: 'cmd+t',
+ scopeId: 'global',
+ description: () => t('tabs.newTab'),
+ keyDownHandler: () => {
+ tabManager.newTab();
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.tabs.close,
+ hotkey: 'shift+cmd+w',
+ scopeId: 'global',
+ description: () => t('tabs.closeTab'),
+ condition: () => tabManager.tabs().length > 1,
+ keyDownHandler: () => {
+ tabManager.closeTab(tabManager.activeTabId());
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.tabs.next,
+ hotkey: 'ctrl+tab',
+ scopeId: 'global',
+ description: () => t('tabs.nextTab'),
+ condition: () => tabManager.tabs().length > 1,
+ keyDownHandler: () => {
+ tabManager.activateNextTab(1);
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.tabs.previous,
+ hotkey: 'ctrl+shift+tab',
+ scopeId: 'global',
+ description: () => t('tabs.previousTab'),
+ condition: () => tabManager.tabs().length > 1,
+ keyDownHandler: () => {
+ tabManager.activateNextTab(-1);
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+}
+
+function TabsOwner(props: {
+ router: SplitRouter;
+ manager: SplitManager;
+ userId: string;
+}) {
+ const tabManager = createTabManager({
+ router: props.router,
+ manager: props.manager,
+ userId: props.userId,
+ });
+ setGlobalTabManager(tabManager);
+ onCleanup(() => setGlobalTabManager(undefined));
+ onCleanup(installOpenInNewTabIntentTracker());
+ registerTabHotkeys(tabManager);
+
+ return null;
+}
+
+/**
+ * Owns the desktop tab manager while tabs are enabled. Mounted by the split
+ * layout provider; tab state is per user and resets on account changes.
+ */
+export function DesktopTabsController(props: {
+ router: SplitRouter;
+ manager: SplitManager;
+}) {
+ const flag = useFeatureFlag(enableDesktopTabs);
+ const userId = useUserId();
+ const enabled = () => desktopTabsSupported() && flag().enabled;
+
+ return (
+ <Show when={enabled() ? userId() : undefined} keyed>
+ {(uid) => (
+ <TabsOwner router={props.router} manager={props.manager} userId={uid} />
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/components/app/tab-layout/open-in-tab-intent.ts b/apps/web/src/components/app/tab-layout/open-in-tab-intent.ts
new file mode 100644
index 0000000000..d4812a2838
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/open-in-tab-intent.ts
@@ -0,0 +1,86 @@
+import { IS_MAC } from '@core/constant/isMac';
+
+export type OpenInNewTabIntent = {
+ /** Cmd+shift+click switches to the new tab; plain cmd+click stays. */
+ activate: boolean;
+};
+
+/**
+ * Remembers that the last click carried the open-in-new-tab modifier
+ * (cmd on macOS, ctrl elsewhere). The router middleware consumes it when a
+ * navigation starts, so any click-driven navigation can become a new tab
+ * without threading the event through every call site.
+ */
+let armed: { intent: OpenInNewTabIntent; expires: number } | undefined;
+/** A pointerdown happened and its trailing click has not arrived yet. */
+let awaitingGestureClick = false;
+/** The current press gesture's intent was already consumed. */
+let pressConsumed = false;
+
+/** Long enough for a navigation that follows the click, short enough that an
+ * unrelated later navigation cannot pick it up. */
+const INTENT_EXPIRY_MS = 800;
+
+function arm(event: MouseEvent) {
+ const isGestureClick = event.type === 'click' && awaitingGestureClick;
+ if (event.type === 'pointerdown') {
+ awaitingGestureClick = true;
+ pressConsumed = false;
+ } else if (isGestureClick) {
+ awaitingGestureClick = false;
+ }
+
+ const modifier = IS_MAC ? event.metaKey : event.ctrlKey;
+ if (!modifier || event.button !== 0) {
+ return;
+ }
+
+ // Some surfaces navigate on the press and ignore the click (sidebar list
+ // rows). The press's intent is consumed then, and that gesture's trailing
+ // click must not re-arm, or a stale intent would hijack whatever
+ // navigation happens next. Only the matching pointer gesture's click is
+ // held back; a keyboard-generated click has no pointerdown and still arms.
+ if (isGestureClick && pressConsumed) {
+ return;
+ }
+
+ const target = event.target;
+ if (target instanceof Element && target.closest('[data-desktop-tab-strip]')) {
+ return;
+ }
+
+ armed = {
+ intent: { activate: event.shiftKey },
+ expires: performance.now() + INTENT_EXPIRY_MS,
+ };
+}
+
+/** One-shot read; stale intents are dropped. */
+export function consumeOpenInNewTabIntent(): OpenInNewTabIntent | undefined {
+ const current = armed;
+ armed = undefined;
+ if (!current || performance.now() > current.expires) return;
+
+ pressConsumed = true;
+ return current.intent;
+}
+
+/** Tab operations call this before navigating so they can't hijack themselves. */
+export function disarmOpenInNewTabIntent(): void {
+ armed = undefined;
+}
+
+export function installOpenInNewTabIntentTracker(): () => void {
+ // Capture phase: some surfaces navigate from mousedown handlers, others on
+ // click, and both may stop propagation.
+ window.addEventListener('pointerdown', arm, { capture: true });
+ window.addEventListener('click', arm, { capture: true });
+
+ return () => {
+ window.removeEventListener('pointerdown', arm, { capture: true });
+ window.removeEventListener('click', arm, { capture: true });
+ armed = undefined;
+ awaitingGestureClick = false;
+ pressConsumed = false;
+ };
+}
diff --git a/apps/web/src/components/app/tab-layout/open-in-tab-middleware.ts b/apps/web/src/components/app/tab-layout/open-in-tab-middleware.ts
new file mode 100644
index 0000000000..398bdd5e41
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/open-in-tab-middleware.ts
@@ -0,0 +1,23 @@
+import type { SplitRouterMiddleware } from '@app/lib/split-router';
+import { globalTabManager } from '@app/signal/tabLayout';
+import { consumeOpenInNewTabIntent } from './open-in-tab-intent';
+
+/**
+ * Cmd+click (ctrl elsewhere) opens the destination in a new desktop tab
+ * instead of navigating. Runs for every pane navigation, so it covers
+ * mentions, lists, buttons, and links without touching their handlers; it
+ * does nothing when tabs are off or the last click carried no modifier.
+ */
+export const openInNewTabMiddleware: SplitRouterMiddleware = (context) => {
+ if (context.cause !== 'navigate') return;
+
+ const tabManager = globalTabManager();
+ if (!tabManager) return;
+
+ const intent = consumeOpenInNewTabIntent();
+ if (!intent) return;
+
+ tabManager.openEntryInNewTab(context.to, intent);
+
+ return context.cancel();
+};
diff --git a/apps/web/src/components/app/tab-layout/tab-manager.ts b/apps/web/src/components/app/tab-layout/tab-manager.ts
new file mode 100644
index 0000000000..f0ab6cfe28
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/tab-manager.ts
@@ -0,0 +1,310 @@
+import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
+import type { Entry, LayoutSnapshot, SplitRouter } from '@app/lib/split-router';
+import type {
+ SplitId,
+ SplitManager,
+} from '@components/app/split-layout/layoutManager';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
+import { batch, createEffect, createSignal, untrack } from 'solid-js';
+import { disarmOpenInNewTabIntent } from './open-in-tab-intent';
+import { readPersistedTabs, writePersistedTabs } from './tab-persistence';
+
+export type DesktopTabId = string & { readonly DesktopTabId: unique symbol };
+
+/** How an inactive tab comes back: a kept capture, or a saved URL. */
+type StoredLayout =
+ | {
+ kind: 'snapshot';
+ layout: LayoutSnapshot;
+ activeSplit: SplitId | undefined;
+ href: string;
+ }
+ | { kind: 'url'; url: string };
+
+export type DesktopTab = {
+ readonly id: DesktopTabId;
+ /** Frozen at deactivation; the active tab renders live values instead. */
+ readonly title: string | undefined;
+ readonly paneCount: number;
+ readonly stored: StoredLayout;
+};
+
+const newTabId = () => crypto.randomUUID() as DesktopTabId;
+
+const SURFACE = 'desktop-tabs';
+
+function newUrlTab(url: string): DesktopTab {
+ return {
+ id: newTabId(),
+ title: undefined,
+ paneCount: 1,
+ stored: { kind: 'url', url },
+ };
+}
+
+/** What the tab layer needs from the split layout manager. */
+export type TabLayoutHost = Pick<
+ SplitManager,
+ 'tabTitle' | 'activeSplitId' | 'getSplit' | 'splits' | 'activateSplit'
+>;
+
+export type TabManagerOptions = {
+ router: SplitRouter;
+ manager: TabLayoutHost;
+ userId: string;
+};
+
+export type TabManager = ReturnType<typeof createTabManager>;
+
+/**
+ * Browser-style tabs over the split layout. Only the active tab is live; the
+ * others hold a layout capture (or a saved URL) and restore through the
+ * router, so switching runs leave guards and keeps pane histories.
+ */
+export function createTabManager(options: TabManagerOptions) {
+ const { router, manager, userId } = options;
+
+ const persisted = readPersistedTabs(userId);
+ const initialTabs: readonly DesktopTab[] = persisted
+ ? persisted.tabs.map((tab) => ({
+ id: newTabId(),
+ title: tab.title,
+ paneCount: tab.paneCount,
+ stored: { kind: 'url', url: tab.url },
+ }))
+ : [newUrlTab(DEFAULT_ROUTE)];
+ const initialActive =
+ initialTabs[Math.min(persisted?.active ?? 0, initialTabs.length - 1)]!;
+
+ const [tabs, setTabs] = createSignal<readonly DesktopTab[]>(initialTabs);
+ const [activeTabId, setActiveTabId] = createSignal(initialActive.id);
+ // Tab operations swap the whole layout; one at a time keeps them coherent.
+ let switching = false;
+
+ const findTab = (id: DesktopTabId) => tabs().find((tab) => tab.id === id);
+ const activeIndex = () => tabs().findIndex((tab) => tab.id === activeTabId());
+
+ /** The active tab with the live layout frozen in, ready to be stored. */
+ const captureActiveTab = (): DesktopTab | undefined => {
+ const current = findTab(activeTabId());
+ if (!current) return;
+
+ const layout = router.layoutSnapshot();
+ if (layout.panes.length === 0) return current;
+
+ return {
+ ...current,
+ title: manager.tabTitle() ?? current.title,
+ paneCount: layout.panes.length,
+ stored: {
+ kind: 'snapshot',
+ layout,
+ activeSplit: manager.activeSplitId(),
+ href: router.layoutHref(layout),
+ },
+ };
+ };
+
+ const storedHref = (tab: DesktopTab): string =>
+ tab.stored.kind === 'url' ? tab.stored.url : tab.stored.href;
+
+ /** Brings a stored tab's layout up; false when a leave guard refused. */
+ const show = async (tab: DesktopTab): Promise<boolean> => {
+ disarmOpenInNewTabIntent();
+ const result =
+ tab.stored.kind === 'snapshot'
+ ? await router.restoreLayout(tab.stored.layout)
+ : await router.navigate(tab.stored.url);
+
+ return result.status !== 'cancelled';
+ };
+
+ const focusStoredSplit = (tab: DesktopTab) => {
+ const stored = tab.stored.kind === 'snapshot' ? tab.stored : undefined;
+ const target =
+ stored?.activeSplit !== undefined && manager.getSplit(stored.activeSplit)
+ ? stored.activeSplit
+ : untrack(manager.splits)[0]?.id;
+ if (target) manager.activateSplit(target);
+ };
+
+ async function activateTab(id: DesktopTabId): Promise<void> {
+ if (switching || id === untrack(activeTabId)) return;
+ const target = untrack(() => findTab(id));
+ if (!target) return;
+
+ switching = true;
+ const span = Telemetry.span('tabs.switch');
+ try {
+ span.setAttr('tabs.count', untrack(tabs).length);
+ span.setAttr('tabs.target_pane_count', target.paneCount);
+ const previous = untrack(captureActiveTab);
+ const shown = await show(target);
+ span.setAttr('tabs.outcome', shown ? 'committed' : 'cancelled');
+ if (!shown) return;
+
+ batch(() => {
+ if (previous) {
+ setTabs((list) =>
+ list.map((tab) => (tab.id === previous.id ? previous : tab))
+ );
+ }
+ setActiveTabId(id);
+ });
+ focusStoredSplit(target);
+ } finally {
+ switching = false;
+ span.end();
+ }
+ }
+
+ async function closeActiveTab(
+ id: DesktopTabId,
+ neighbor: DesktopTabId
+ ): Promise<void> {
+ if (switching) return;
+ const target = untrack(() => findTab(neighbor));
+ if (!target) return;
+
+ switching = true;
+ try {
+ // Restoring the neighbor removes this tab's panes, so its leave
+ // guards (unsaved changes) decide whether the close happens.
+ const shown = await show(target);
+ if (!shown) return;
+
+ batch(() => {
+ setTabs((list) => list.filter((tab) => tab.id !== id));
+ setActiveTabId(neighbor);
+ });
+ focusStoredSplit(target);
+ } finally {
+ switching = false;
+ }
+ }
+
+ const insertTab = (tab: DesktopTab, index: number) => {
+ setTabs((list) => {
+ const next = [...list];
+ next.splice(Math.max(0, Math.min(index, next.length)), 0, tab);
+ return next;
+ });
+ };
+
+ // Keep the saved tabs current: the active tab persists its live layout URL.
+ createEffect(() => {
+ const list = tabs();
+ const active = activeTabId();
+ // Track the live layout so in-tab navigation refreshes the saved URL.
+ router.panes().forEach((pane) => router.entry(pane));
+ const activeTitle = manager.tabTitle();
+ const livePaneCount = router.panes().length;
+ const liveUrl = untrack(() => router.layoutHref(router.layoutSnapshot()));
+
+ writePersistedTabs(userId, {
+ version: 1,
+ active: Math.max(
+ 0,
+ list.findIndex((tab) => tab.id === active)
+ ),
+ tabs: list.map((tab) => {
+ const isActive = tab.id === active;
+ return {
+ title: isActive ? (activeTitle ?? tab.title) : tab.title,
+ paneCount:
+ isActive && livePaneCount > 0 ? livePaneCount : tab.paneCount,
+ url: isActive && livePaneCount > 0 ? liveUrl : storedHref(tab),
+ };
+ }),
+ });
+ });
+
+ return {
+ tabs,
+ activeTabId,
+
+ /** Live title for the strip: the active tab reads the layout manager.
+ * Undefined when the tab has no title yet; the strip renders the
+ * translated placeholder. */
+ tabTitle(tab: DesktopTab): string | undefined {
+ const live = tab.id === activeTabId() ? manager.tabTitle() : undefined;
+ return live ?? tab.title;
+ },
+
+ /** Live pane count for the strip's split indicator. */
+ tabPaneCount(tab: DesktopTab): number {
+ if (tab.id !== activeTabId()) return tab.paneCount;
+ const live = router.panes().length;
+ return live > 0 ? live : tab.paneCount;
+ },
+
+ activateTab(id: DesktopTabId): void {
+ fireAndForget(activateTab(id), SURFACE);
+ },
+
+ closeTab(id: DesktopTabId): void {
+ const list = untrack(tabs);
+ if (list.length <= 1) return;
+ const index = list.findIndex((tab) => tab.id === id);
+ if (index < 0) return;
+
+ if (id !== untrack(activeTabId)) {
+ setTabs((current) => current.filter((tab) => tab.id !== id));
+ return;
+ }
+
+ const neighbor = list[index + 1] ?? list[index - 1];
+ if (!neighbor) return;
+ fireAndForget(closeActiveTab(id, neighbor.id), SURFACE);
+ },
+
+ /** The + button and cmd+T: a fresh tab on the default view. */
+ newTab(options: { activate?: boolean } = {}): void {
+ const tab = newUrlTab(DEFAULT_ROUTE);
+ insertTab(tab, untrack(tabs).length);
+ if (options.activate !== false) {
+ fireAndForget(activateTab(tab.id), SURFACE);
+ }
+ },
+
+ /** Cmd+click: the destination opens as a tab beside the active one. */
+ openEntryInNewTab(entry: Entry, options: { activate: boolean }): void {
+ const layout: LayoutSnapshot = {
+ panes: [{ pane: router.createPaneId(), entries: [entry], index: 0 }],
+ };
+ const tab: DesktopTab = {
+ id: newTabId(),
+ // No stored title until the tab is activated and gets a live one;
+ // the strip renders its translated placeholder meanwhile (i18n.md
+ // bans deriving display text from English route ids).
+ title: undefined,
+ paneCount: 1,
+ stored: {
+ kind: 'snapshot',
+ layout,
+ activeSplit: undefined,
+ href: router.layoutHref(layout),
+ },
+ };
+ const span = Telemetry.span('tabs.open');
+ span.setAttr('tabs.activate', options.activate);
+ span.setAttr('tabs.count', untrack(tabs).length + 1);
+ span.end();
+
+ insertTab(tab, untrack(activeIndex) + 1);
+ if (options.activate) {
+ // The intercepted navigation is still settling; activate after it.
+ queueMicrotask(() => fireAndForget(activateTab(tab.id), SURFACE));
+ }
+ },
+
+ activateNextTab(step: 1 | -1): void {
+ const list = untrack(tabs);
+ if (list.length <= 1) return;
+ const index = untrack(activeIndex);
+ const next = list[(index + step + list.length) % list.length];
+ if (next) fireAndForget(activateTab(next.id), SURFACE);
+ },
+ };
+}
diff --git a/apps/web/src/components/app/tab-layout/tab-persistence.ts b/apps/web/src/components/app/tab-layout/tab-persistence.ts
new file mode 100644
index 0000000000..c70ae8e744
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/tab-persistence.ts
@@ -0,0 +1,40 @@
+import { createUserScopedStorage } from '@core/util/userScopedStorage';
+import { z } from 'zod';
+
+// Not makePersistedState: the canonical tab state (live layout, capture
+// objects) differs from the saved projection (URLs), so the manager derives
+// what to write instead of persisting a signal one-to-one.
+
+const persistedTabSchema = z.object({
+ title: z.string().optional(),
+ paneCount: z.number().int().min(1),
+ url: z.string().min(1),
+});
+
+const persistedTabsSchema = z.object({
+ version: z.literal(1),
+ active: z.number().int().min(0),
+ tabs: z.array(persistedTabSchema).min(1),
+});
+
+export type PersistedTabs = z.infer<typeof persistedTabsSchema>;
+
+const storage = createUserScopedStorage('macro:desktop:tabs');
+
+export function readPersistedTabs(userId: string): PersistedTabs | undefined {
+ const raw = storage.read(userId);
+ if (!raw) return;
+
+ try {
+ const parsed = persistedTabsSchema.safeParse(JSON.parse(raw));
+ if (!parsed.success) return;
+
+ return parsed.data;
+ } catch {
+ return;
+ }
+}
+
+export function writePersistedTabs(userId: string, value: PersistedTabs) {
+ storage.write(userId, JSON.stringify(value));
+}
diff --git a/apps/web/src/components/app/tab-layout/tests/open-in-tab-intent.test.ts b/apps/web/src/components/app/tab-layout/tests/open-in-tab-intent.test.ts
new file mode 100644
index 0000000000..66e0c13c4a
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/tests/open-in-tab-intent.test.ts
@@ -0,0 +1,120 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ consumeOpenInNewTabIntent,
+ disarmOpenInNewTabIntent,
+ installOpenInNewTabIntentTracker,
+} from '../open-in-tab-intent';
+
+// IS_MAC is false under jsdom, so the modifier is ctrl.
+function press(options: { ctrl?: boolean; shift?: boolean } = {}) {
+ document.body.dispatchEvent(
+ new MouseEvent('pointerdown', {
+ bubbles: true,
+ button: 0,
+ ctrlKey: options.ctrl ?? true,
+ shiftKey: options.shift ?? false,
+ })
+ );
+}
+
+function click(options: { ctrl?: boolean; shift?: boolean } = {}) {
+ document.body.dispatchEvent(
+ new MouseEvent('click', {
+ bubbles: true,
+ button: 0,
+ ctrlKey: options.ctrl ?? true,
+ shiftKey: options.shift ?? false,
+ })
+ );
+}
+
+let uninstall: () => void;
+
+beforeEach(() => {
+ uninstall = installOpenInNewTabIntentTracker();
+});
+
+afterEach(() => {
+ uninstall();
+ vi.restoreAllMocks();
+});
+
+describe('open-in-new-tab intent', () => {
+ it('a ctrl+click arms once and consuming is one-shot', () => {
+ press();
+ click();
+ expect(consumeOpenInNewTabIntent()).toEqual({ activate: false });
+ expect(consumeOpenInNewTabIntent()).toBeUndefined();
+ });
+
+ it('shift asks for the new tab to be activated', () => {
+ press({ shift: true });
+ click({ shift: true });
+ expect(consumeOpenInNewTabIntent()).toEqual({ activate: true });
+ });
+
+ it('a click without the modifier does not arm', () => {
+ press({ ctrl: false });
+ click({ ctrl: false });
+ expect(consumeOpenInNewTabIntent()).toBeUndefined();
+ });
+
+ it('the trailing click cannot re-arm a gesture whose press was consumed', () => {
+ // Sidebar list rows navigate on the press and ignore the click
+ // (list-nav.tsx): the middleware consumes between the two events.
+ press();
+ expect(consumeOpenInNewTabIntent()).toEqual({ activate: false });
+
+ click();
+ expect(consumeOpenInNewTabIntent()).toBeUndefined();
+ });
+
+ it('a new press after a consumed gesture arms again', () => {
+ press();
+ expect(consumeOpenInNewTabIntent()).toEqual({ activate: false });
+ click();
+
+ press();
+ click();
+ expect(consumeOpenInNewTabIntent()).toEqual({ activate: false });
+ });
+
+ it('a keyboard-generated click after a consumed press gesture still arms', () => {
+ // Press gesture: navigate on the press, trailing click suppressed.
+ press();
+ expect(consumeOpenInNewTabIntent()).toEqual({ activate: false });
+ click();
+ expect(consumeOpenInNewTabIntent()).toBeUndefined();
+
+ // A click with no pointerdown (keyboard activation) is a new intent.
+ click();
+ expect(consumeOpenInNewTabIntent()).toEqual({ activate: false });
+ });
+
+ it('disarm clears a pending intent', () => {
+ press();
+ click();
+ disarmOpenInNewTabIntent();
+ expect(consumeOpenInNewTabIntent()).toBeUndefined();
+ });
+
+ it('an intent expires', () => {
+ const now = vi.spyOn(performance, 'now');
+ now.mockReturnValue(1_000);
+ press();
+ click();
+ now.mockReturnValue(2_000);
+ expect(consumeOpenInNewTabIntent()).toBeUndefined();
+ });
+
+ it('clicks inside the tab strip never arm', () => {
+ const strip = document.createElement('div');
+ strip.setAttribute('data-desktop-tab-strip', '');
+ document.body.appendChild(strip);
+ strip.dispatchEvent(
+ new MouseEvent('click', { bubbles: true, button: 0, ctrlKey: true })
+ );
+ expect(consumeOpenInNewTabIntent()).toBeUndefined();
+ strip.remove();
+ });
+});
diff --git a/apps/web/src/components/app/tab-layout/tests/tab-manager.test.ts b/apps/web/src/components/app/tab-layout/tests/tab-manager.test.ts
new file mode 100644
index 0000000000..98a9ee0709
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/tests/tab-manager.test.ts
@@ -0,0 +1,175 @@
+import {
+ createMemoryHistory,
+ createMemoryPaneStore,
+ createSplitRouter,
+ type Entry,
+ type PaneId,
+ type SplitRouter,
+} from '@app/lib/split-router';
+import {
+ appRoutes,
+ createTestPolicy,
+} from '@app/lib/split-router/tests/fixtures';
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createTabManager, type TabLayoutHost } from '../tab-manager';
+
+const fakeHost = (): TabLayoutHost => ({
+ tabTitle: () => undefined,
+ activeSplitId: () => undefined,
+ getSplit: () => undefined,
+ splits: () => [],
+ activateSplit: () => {},
+});
+
+function setup(url: string, userId = `user-${Math.random()}`) {
+ const history = createMemoryHistory(url);
+ let created = 0;
+ const { router, tabManager, dispose } = createRoot((dispose) => {
+ const router = createSplitRouter({
+ routes: appRoutes,
+ history,
+ paneStore: createMemoryPaneStore<Entry>(),
+ policy: createTestPolicy().policy,
+ createPaneId: () => `pane-${++created}` as PaneId,
+ });
+ const tabManager = createTabManager({
+ router,
+ manager: fakeHost(),
+ userId,
+ });
+ return { router, tabManager, dispose };
+ });
+ return {
+ router,
+ tabManager,
+ history,
+ userId,
+ dispose: () => {
+ router.dispose();
+ dispose();
+ },
+ };
+}
+
+async function flush(router: SplitRouter) {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await router.settled();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+const routeIds = (router: SplitRouter) =>
+ router.panes().map((pane) =>
+ router
+ .entry(pane)
+ ?.location.route.matches.map((match) => match.id)
+ .filter((id) => id !== 'app')
+ );
+
+let cleanup: (() => void) | undefined;
+const track = <T extends { dispose: () => void }>(context: T) => {
+ cleanup = context.dispose;
+ return context;
+};
+
+afterEach(() => {
+ cleanup?.();
+ cleanup = undefined;
+});
+
+describe('desktop tab manager', () => {
+ it('starts with one tab holding the default view', () => {
+ const { tabManager } = track(setup('/mail/t1'));
+ expect(tabManager.tabs()).toHaveLength(1);
+ expect(tabManager.activeTabId()).toBe(tabManager.tabs()[0]!.id);
+ });
+
+ it('newTab opens the default view and switching back restores the layout and its history', async () => {
+ const { router, tabManager } = track(setup('/mail/t1'));
+ const [first] = tabManager.tabs();
+
+ tabManager.newTab();
+ await flush(router);
+ expect(tabManager.tabs()).toHaveLength(2);
+ const second = tabManager.tabs()[1]!;
+ expect(tabManager.activeTabId()).toBe(second.id);
+ expect(routeIds(router)).toEqual([['home']]);
+
+ // Navigate within the second tab so it has pane history.
+ await router.navigatePane(router.panes()[0]!, '/drive');
+ expect(routeIds(router)).toEqual([['drive']]);
+
+ tabManager.activateTab(first!.id);
+ await flush(router);
+ expect(tabManager.activeTabId()).toBe(first!.id);
+ expect(routeIds(router)).toEqual([['mail', 'mail-thread']]);
+
+ // The second tab kept its in-tab history across the switch away.
+ tabManager.activateTab(second.id);
+ await flush(router);
+ expect(routeIds(router)).toEqual([['drive']]);
+ expect(router.canGo(router.panes()[0]!, -1)).toBe(true);
+ });
+
+ it('closing the active tab activates its neighbor and restores it', async () => {
+ const { router, tabManager } = track(setup('/mail/t1'));
+ const [first] = tabManager.tabs();
+ tabManager.newTab();
+ await flush(router);
+
+ tabManager.closeTab(tabManager.activeTabId());
+ await flush(router);
+ expect(tabManager.tabs()).toHaveLength(1);
+ expect(tabManager.activeTabId()).toBe(first!.id);
+ expect(routeIds(router)).toEqual([['mail', 'mail-thread']]);
+ });
+
+ it('never closes the last tab', () => {
+ const { tabManager } = track(setup('/home'));
+ tabManager.closeTab(tabManager.activeTabId());
+ expect(tabManager.tabs()).toHaveLength(1);
+ });
+
+ it('openEntryInNewTab without activation leaves the layout alone', async () => {
+ const { router, tabManager } = track(setup('/mail/t1'));
+ const entry = router.entry(router.panes()[0]!)!;
+
+ tabManager.openEntryInNewTab(entry, { activate: false });
+ await flush(router);
+ expect(tabManager.tabs()).toHaveLength(2);
+ expect(tabManager.activeTabId()).toBe(tabManager.tabs()[0]!.id);
+ expect(routeIds(router)).toEqual([['mail', 'mail-thread']]);
+
+ // No stored English title; the strip renders its translated placeholder
+ // until the tab is activated and gets a live title.
+ const background = tabManager.tabs()[1]!;
+ expect(background.title).toBeUndefined();
+ expect(tabManager.tabTitle(background)).toBeUndefined();
+
+ tabManager.activateTab(tabManager.tabs()[1]!.id);
+ await flush(router);
+ expect(routeIds(router)).toEqual([['mail', 'mail-thread']]);
+ });
+
+ it('persists tabs per user and restores them on the next start', async () => {
+ const userId = 'user-persistence';
+ const { router, tabManager, dispose } = setup('/mail/t1', userId);
+ tabManager.newTab();
+ await flush(router);
+ await router.navigatePane(router.panes()[0]!, '/drive');
+ await flush(router);
+ dispose();
+
+ const second = track(setup('/drive', userId));
+ expect(second.tabManager.tabs()).toHaveLength(2);
+ // The second tab was active when the first session ended.
+ expect(second.tabManager.activeTabId()).toBe(
+ second.tabManager.tabs()[1]!.id
+ );
+ const storedFirst = second.tabManager.tabs()[0]!;
+ expect(storedFirst.stored).toMatchObject({
+ kind: 'url',
+ url: '/mail/t1',
+ });
+ });
+});
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 30ca6da503..c0739b56c9 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -150,6 +150,13 @@ export const PROD_MODE_ENV = import.meta.env.MODE === 'production';
const onInDev = DEV_MODE_ENV || undefined;
+/** Browser-style tabs in the macOS desktop title bar; each tab holds a split layout. */
+export const enableDesktopTabs = defineFlag({
+ key: 'enable-desktop-tabs',
+ env: 'ENABLE_DESKTOP_TABS',
+ default: onInDev,
+});
+
// Leave the production PostHog flag disabled until archive-import rollout.
export const enableSlackArchiveImport = defineFlag({
key: 'enable-slack-archive-import',
diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.ts
index d091ec5e72..3e7c6f4fd2 100644
--- a/apps/web/src/lib/core/hotkey/tokens.ts
+++ b/apps/web/src/lib/core/hotkey/tokens.ts
@@ -116,6 +116,14 @@ export const TOKENS = {
zoomReset: 'global.zoomReset',
},
+ // desktop tabs
+ tabs: {
+ new: 'tabs.new',
+ close: 'tabs.close',
+ next: 'tabs.next',
+ previous: 'tabs.previous',
+ },
+
// sidebar navigation
sidebar: {
goToLeader: 'sidebar.goToLeader',
diff --git a/apps/web/src/lib/i18n/locales/en.ts b/apps/web/src/lib/i18n/locales/en.ts
index 0d72346d07..951e978a63 100644
--- a/apps/web/src/lib/i18n/locales/en.ts
+++ b/apps/web/src/lib/i18n/locales/en.ts
@@ -10,6 +10,7 @@ import nav from './en/nav';
import settingsLanguage from './en/settings-language';
import settingsNav from './en/settings-nav';
import splitMenu from './en/split-menu';
+import tabs from './en/tabs';
import viewMenus from './en/view-menus';
/**
@@ -29,5 +30,6 @@ export default {
settingsLanguage,
settingsNav,
splitMenu,
+ tabs,
viewMenus,
};
diff --git a/apps/web/src/lib/i18n/locales/en/tabs.ts b/apps/web/src/lib/i18n/locales/en/tabs.ts
new file mode 100644
index 0000000000..6a03c4a8aa
--- /dev/null
+++ b/apps/web/src/lib/i18n/locales/en/tabs.ts
@@ -0,0 +1,12 @@
+export default {
+ // Title bar tab strip.
+ tablist: 'Tabs',
+ newTab: 'New Tab',
+ closeTab: 'Close Tab',
+ nextTab: 'Next Tab',
+ previousTab: 'Previous Tab',
+ splitCount: {
+ one: '{{count}} split',
+ other: '{{count}} splits',
+ },
+};
diff --git a/apps/web/src/lib/signals/tabLayout.ts b/apps/web/src/lib/signals/tabLayout.ts
new file mode 100644
index 0000000000..f5df2aed43
--- /dev/null
+++ b/apps/web/src/lib/signals/tabLayout.ts
@@ -0,0 +1,10 @@
+import type { TabManager } from '@components/app/tab-layout/tab-manager';
+import { createSignal } from 'solid-js';
+
+/**
+ * The desktop tab manager, set while tabs are enabled (macOS desktop app).
+ * Published globally like `globalSplitManager`, because the title bar, global
+ * hotkeys, and the router middleware live outside the owning provider.
+ */
+export const [globalTabManager, setGlobalTabManager] =
+ createSignal<TabManager>();
diff --git a/apps/web/src/lib/split-router/index.ts b/apps/web/src/lib/split-router/index.ts
index 3c93781203..7885eb8289 100644
--- a/apps/web/src/lib/split-router/index.ts
+++ b/apps/web/src/lib/split-router/index.ts
@@ -22,6 +22,11 @@ export type {
} from './panes/types';
export type { ClaimHolder } from './router/claims';
export { createSplitRouter } from './router/create-router';
+export type {
+ LayoutPane,
+ LayoutSnapshot,
+ RestoreLayoutOptions,
+} from './router/layout';
export { PANE_LEVEL } from './router/leave-guards';
export type {
SplitRouterMiddleware,
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 c70d4bb394..fa24f7b373 100644
--- a/apps/web/src/lib/split-router/router/create-router.ts
+++ b/apps/web/src/lib/split-router/router/create-router.ts
@@ -9,6 +9,7 @@ import type {
} from '../routes/types';
import { UNCANCELLABLE } from '../utils';
import { createClaims } from './claims';
+import { createLayout } from './layout';
import { createLeaveGuards } from './leave-guards';
import { createPaneList } from './pane-list';
import { createPaneNavigation } from './pane-navigation';
@@ -89,6 +90,8 @@ export function createSplitRouter(options: SplitRouterOptions) {
navigation: paneNavigation,
});
+ const layout = createLayout({ routes, panes, url, runner });
+
const disconnect = urlNavigation.connect();
const matches = (pane: PaneId): RouteMatchInfo[] => {
@@ -151,6 +154,10 @@ export function createSplitRouter(options: SplitRouterOptions) {
matches,
preload,
href: url.href,
+ layoutSnapshot: layout.snapshot,
+ restoreLayout: layout.restore,
+ layoutHref: layout.href,
+ createPaneId: panes.createPaneId,
activatePane: panes.activate,
registerGuard: guards.register,
settled: runner.settled,
diff --git a/apps/web/src/lib/split-router/router/layout.ts b/apps/web/src/lib/split-router/router/layout.ts
new file mode 100644
index 0000000000..b195fbfcf1
--- /dev/null
+++ b/apps/web/src/lib/split-router/router/layout.ts
@@ -0,0 +1,133 @@
+import { batch, untrack } from 'solid-js';
+import { type ChangedPane, changedPanes } from '../panes/diff';
+import type { PaneId } from '../panes/types';
+import { encodePanes, formatLocation } from '../routes/codec';
+import type { SplitRoutesManifest } from '../routes/manifest';
+import type { Entry } from '../routes/types';
+import type { MaybePromise } from '../utils';
+import { sameVisit } from './entries';
+import type { Runner } from './runner';
+import {
+ CANCELLED_RESULT,
+ type Navigation,
+ type NavigationResult,
+ type PaneTarget,
+ type RouterPanes,
+} from './types';
+import type { Url } from './url';
+
+/** One pane in a captured layout: its full history and cursor. */
+export type LayoutPane = {
+ pane: PaneId;
+ entries: readonly Entry[];
+ index: number;
+};
+
+/** A whole layout: every open pane with its history, in order. */
+export type LayoutSnapshot = {
+ panes: readonly LayoutPane[];
+};
+
+export type RestoreLayoutOptions = {
+ replace?: boolean;
+};
+
+const shownEntry = (pane: LayoutPane): Entry => pane.entries[pane.index]!;
+
+function toTarget(change: ChangedPane<Entry>): PaneTarget {
+ if (change.kind === 'change') {
+ return { pane: change.pane, from: change.from, to: change.to };
+ }
+
+ return { pane: change.pane, to: change.entry };
+}
+
+/**
+ * Capturing the open panes as plain data and bringing a capture back, so a
+ * host can keep several layouts (such as window tabs) and swap between them
+ * without losing any pane's back/forward history.
+ */
+export function createLayout(options: {
+ routes: SplitRoutesManifest;
+ panes: RouterPanes;
+ url: Url;
+ runner: Runner;
+}) {
+ const { routes, panes, url, runner } = options;
+
+ /** The open panes with their histories; entries are shared, not copied. */
+ const snapshot = (): LayoutSnapshot => ({
+ panes: untrack(panes.ids).flatMap((pane) => {
+ const stored = untrack(() => panes.read(pane));
+ if (!stored) return [];
+
+ return [{ pane, entries: stored.entries, index: stored.index }];
+ }),
+ });
+
+ /**
+ * Makes the captured layout the open panes in one guarded navigation: leave
+ * guards run for removed and changed panes, and each restored pane gets its
+ * captured history back. A pane already showing its entry stays mounted.
+ */
+ const restore = (
+ layout: LayoutSnapshot,
+ restoreOptions: RestoreLayoutOptions = {}
+ ): MaybePromise<NavigationResult> => {
+ if (layout.panes.length === 0) return CANCELLED_RESULT;
+
+ const incoming = layout.panes.map((pane) => ({
+ paneId: pane.pane,
+ entry: shownEntry(pane),
+ }));
+ const diff = panes.diff(incoming, { same: sameVisit });
+
+ const apply = (entries: readonly Entry[]): NavigationResult => {
+ batch(() => {
+ panes.applyDiff(diff, entries);
+
+ // Put each captured history back; the shown entry may have been
+ // amended by middleware, so the live one replaces it at the cursor.
+ layout.panes.forEach((pane, position) => {
+ const landed = diff.panes[position]!.pane;
+ const current = untrack(() => panes.current(landed));
+ if (!current) return;
+
+ const history = [...pane.entries];
+ history[pane.index] = current;
+ panes.commit(landed, {
+ type: 'reset',
+ entries: history,
+ index: pane.index,
+ });
+ });
+ });
+ url.write(restoreOptions.replace ? 'replace' : 'push');
+
+ const [first] = diff.panes;
+
+ return { status: 'committed', pane: first!.pane };
+ };
+
+ const navigation: Navigation = {
+ cause: 'navigate',
+ targets: changedPanes(diff).map(toTarget),
+ removed: diff.removed,
+ apply,
+ };
+
+ return runner.startUrl(navigation, false);
+ };
+
+ /** The mount-relative URL a captured layout shows, for saving or sharing. */
+ const href = (layout: LayoutSnapshot): string => {
+ const shown = layout.panes.map((pane) => ({
+ paneId: pane.pane,
+ entry: shownEntry(pane),
+ }));
+
+ return formatLocation(encodePanes(routes, shown, untrack(url.lastKnown)));
+ };
+
+ return { snapshot, restore, href };
+}
diff --git a/apps/web/src/lib/split-router/tests/layout.test.ts b/apps/web/src/lib/split-router/tests/layout.test.ts
new file mode 100644
index 0000000000..15131d2e4a
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/layout.test.ts
@@ -0,0 +1,124 @@
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createMemoryHistory } from '../history/memory';
+import { createMemoryPaneStore } from '../panes/memory-store';
+import { createSplitRouter } from '../router/create-router';
+import { PANE_LEVEL } from '../router/leave-guards';
+import type { Entry, PaneId } from '../routes/types';
+import { appRoutes, createTestPolicy } from './fixtures';
+
+function setup(url: string) {
+ const history = createMemoryHistory(url);
+ const paneStore = createMemoryPaneStore<Entry>();
+ let created = 0;
+ const { router, dispose } = createRoot((dispose) => ({
+ router: createSplitRouter({
+ routes: appRoutes,
+ history,
+ paneStore,
+ policy: createTestPolicy().policy,
+ createPaneId: () => `pane-${++created}` as PaneId,
+ }),
+ dispose,
+ }));
+ return {
+ router,
+ history,
+ paneStore,
+ pane: (index: number) => router.panes()[index]!,
+ dispose: () => {
+ router.dispose();
+ dispose();
+ },
+ };
+}
+
+const routeIds = (entry: Entry | undefined) =>
+ entry?.location.route.matches
+ .map((match) => match.id)
+ .filter((id) => id !== 'app');
+
+let cleanup: (() => void) | undefined;
+const track = <T extends { dispose: () => void }>(context: T) => {
+ cleanup = context.dispose;
+ return context;
+};
+
+afterEach(() => {
+ cleanup?.();
+ cleanup = undefined;
+});
+
+describe('layout snapshot and restore', () => {
+ it('restores a captured layout with every pane history and the URL', async () => {
+ const { router, history, paneStore, pane } = track(setup('/home/~/drive'));
+ await router.navigatePane(pane(0), '/mail/t1');
+ const captured = router.layoutSnapshot();
+ expect(captured.panes.map((item) => item.pane)).toEqual([
+ 'pane-1',
+ 'pane-2',
+ ]);
+ expect(captured.panes[0]).toMatchObject({ index: 1 });
+
+ await router.navigate('/mail');
+ expect(router.panes()).toEqual(['pane-1']);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);
+
+ const result = await router.restoreLayout(captured);
+ expect(result.status).toBe('committed');
+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail', 'mail-thread']);
+ expect(routeIds(router.entry(pane(1)))).toEqual(['drive']);
+
+ expect(history.entries().at(-1)?.path).toBe('/mail/t1/~/drive');
+
+ // The first pane can still go back through its captured history.
+ expect(paneStore.read(pane(0))?.entries).toHaveLength(2);
+ expect(router.canGo(pane(0), -1)).toBe(true);
+ await router.navigatePane(pane(0), -1);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ });
+
+ it('keeps a pane already showing its entry mounted across a restore', async () => {
+ const { router, pane } = track(setup('/home/~/drive'));
+ const captured = router.layoutSnapshot();
+ const home = router.entry(pane(0));
+
+ const result = await router.restoreLayout(captured);
+ expect(result.status).toBe('committed');
+ expect(router.entry(pane(0))).toBe(home);
+ });
+
+ it('a leave guard on a pane the restore removes can refuse it', async () => {
+ const { router, pane } = track(setup('/home'));
+ const captured = router.layoutSnapshot();
+ await router.navigate('/mail/~/drive');
+ expect(router.panes()).toHaveLength(2);
+
+ const stop = router.registerGuard(pane(1), PANE_LEVEL, () => false);
+ const result = await router.restoreLayout(captured);
+ expect(result.status).toBe('cancelled');
+ expect(router.panes()).toHaveLength(2);
+ stop();
+
+ const retried = await router.restoreLayout(captured);
+ expect(retried.status).toBe('committed');
+ expect(router.panes()).toHaveLength(1);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ });
+
+ it('restoring an empty capture is cancelled', async () => {
+ const { router } = track(setup('/home'));
+ const result = await router.restoreLayout({ panes: [] });
+ expect(result.status).toBe('cancelled');
+ });
+
+ it('layoutHref encodes the captured panes, not the open ones', async () => {
+ const { router } = track(setup('/home/~/drive'));
+ const captured = router.layoutSnapshot();
+ await router.navigate('/mail/t1');
+
+ expect(router.layoutHref(captured)).toBe('/home/~/drive');
+ expect(router.layoutHref(router.layoutSnapshot())).toBe('/mail/t1');
+ });
+});
diff --git a/docs/agent-guide/media/desktop-tabs/restored-tabs.png b/docs/agent-guide/media/desktop-tabs/restored-tabs.png
new file mode 100644
index 0000000000..91fb4ccca4
Binary files /dev/null and b/docs/agent-guide/media/desktop-tabs/restored-tabs.png differ
diff --git a/docs/agent-guide/media/desktop-tabs/three-split-tab.png b/docs/agent-guide/media/desktop-tabs/three-split-tab.png
new file mode 100644
index 0000000000..959800b651
Binary files /dev/null and b/docs/agent-guide/media/desktop-tabs/three-split-tab.png differ
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index fd6da51d85..df63b8754f 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -12,6 +12,24 @@ workspace. The top-right split icon opens another Home split, even
when Home is already open, and is disabled when there is no room for a new split.
Its tooltip is “New Split” and displays the registered new-split shortcut (`\`).
+## Desktop tabs (macOS, `enable-desktop-tabs` flag)
+
+The title bar's center holds browser-style tabs; each tab is a whole split
+layout. Only the active tab's layout is mounted — switching tabs swaps every
+split through the router, preserving each split's back/forward history and
+running unsaved-changes guards. A tab holding more than one split shows a
+split icon with the count. The strip's `+` button (and `Cmd+T`) opens a tab on
+Home; the `X` or a middle click closes one (the last tab cannot close;
+`Shift+Cmd+W` closes the active tab); `Ctrl+Tab` / `Ctrl+Shift+Tab` cycle.
+Cmd+click (Ctrl elsewhere) on anything that navigates opens the destination in
+a background tab; adding Shift also switches to it. Tabs are not draggable.
+Tabs persist per user and restore on launch. In the browser and on other
+platforms the strip does not render.
+
+Reference captures (browser fixture with the desktop gates forced):
+[a three-split tab beside a second tab](media/desktop-tabs/three-split-tab.png)
+and [tabs restored after a reload](media/desktop-tabs/restored-tabs.png).
+
After native bundle updates, verify that Home and channel details load without
an update toast on every launch. Relative bundled assets such as Loro's WASM
must load through the webview, not native HTTP. A `vite:preloadError` with