🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(desktop): support split tab views (#18004)
Arvin Xu280ec0d59908
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.jsonindex 06dadf883a0..fdfa4922534 100644--- a/locales/en-US/electron.json+++ b/locales/en-US/electron.json@@ -120,9 +120,12 @@"tab.closeLeftTabs": "Close Tabs to the Left","tab.closeOtherTabs": "Close Other Tabs","tab.closeRightTabs": "Close Tabs to the Right",+ "tab.closeSplitView": "Close Split View","tab.newTab": "New Tab",+ "tab.openInSplitView": "Open in Split View","tab.overflow": "{{count}} more tabs","tab.pin": "Pin Tab",+ "tab.resizeSplitView": "Resize Split View","tab.running": "Agent is running","tab.unpin": "Unpin Tab","tab.unread": "New message",diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex 882c052a689..90f923ca6a8 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -12,6 +12,8 @@"features.claudeCodeSdk.title": "Claude Code SDK Runtime","features.codexAppServer.desc": "Run Codex sessions through the local app-server instead of one-shot CLI processes. Enables token streaming and native turn control.","features.codexAppServer.title": "Codex App Server Runtime",+ "features.desktopSplitView.desc": "Show two desktop tabs side by side, with independent navigation and a resizable divider.",+ "features.desktopSplitView.title": "Split Tab View","features.groupChat.desc": "Enable multi-agent group chat coordination.","features.groupChat.title": "Group Chat (Multi-Agent)","features.heteroSessionImport.desc": "Add an \"Import Local Agent Sessions\" entry to the topic list menu: scan local Claude Code / Codex CLI transcripts and import them as topics, with incremental sync on re-import.",diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.jsonindex 834d85a9b51..031a18ab87c 100644--- a/locales/zh-CN/electron.json+++ b/locales/zh-CN/electron.json@@ -120,9 +120,12 @@"tab.closeLeftTabs": "关闭左侧标签页","tab.closeOtherTabs": "关闭其他标签页","tab.closeRightTabs": "关闭右侧标签页",+ "tab.closeSplitView": "关闭分栏","tab.newTab": "新建标签页",+ "tab.openInSplitView": "在右侧分栏打开","tab.overflow": "另有 {{count}} 个标签页","tab.pin": "固定标签页",+ "tab.resizeSplitView": "调整分栏宽度","tab.running": "智能体运行中","tab.unpin": "取消固定","tab.unread": "新消息",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex 9ce3be17e27..ba90c6b79c5 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -12,6 +12,8 @@"features.claudeCodeSdk.title": "Claude Code SDK 运行时","features.codexAppServer.desc": "通过本地 App Server 运行 Codex 会话,替代一次性的 CLI 进程,提供 Token 流式输出与原生 Turn 控制。","features.codexAppServer.title": "Codex App Server 运行时",+ "features.desktopSplitView.desc": "在桌面端并排显示两个标签页,支持独立导航和拖拽调整分栏宽度。",+ "features.desktopSplitView.title": "标签页分栏","features.groupChat.desc": "启用多代理协同群聊功能。","features.groupChat.title": "群聊(多代理)","features.heteroSessionImport.desc": "在话题列表菜单中新增「导入本地 Agent 会话」入口:扫描本地 Claude Code / Codex CLI 的会话记录并导入为话题,重复导入时增量同步新消息。",diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.tsindex cc720200606..ed3cca0e9ae 100644--- a/packages/locales/src/default/electron.ts+++ b/packages/locales/src/default/electron.ts@@ -46,9 +46,12 @@ export default {'tab.closeLeftTabs': 'Close Tabs to the Left','tab.closeOtherTabs': 'Close Other Tabs','tab.closeRightTabs': 'Close Tabs to the Right',+ 'tab.closeSplitView': 'Close Split View','tab.newTab': 'New Tab',+ 'tab.openInSplitView': 'Open in Split View','tab.overflow': '{{count}} more tabs','tab.pin': 'Pin Tab',+ 'tab.resizeSplitView': 'Resize Split View','tab.running': 'Agent is running','tab.unpin': 'Unpin Tab','tab.unread': 'New message',diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex dc82fbc36aa..cb3fd512b8c 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -19,6 +19,9 @@ export default {'features.codexAppServer.desc':'Run Codex sessions through the local app-server instead of one-shot CLI processes. Enables token streaming and native turn control.','features.codexAppServer.title': 'Codex App Server Runtime',+ 'features.desktopSplitView.desc':+ 'Show two desktop tabs side by side, with independent navigation and a resizable divider.',+ 'features.desktopSplitView.title': 'Split Tab View','features.heteroSessionImport.desc':'Add an "Import Local Agent Sessions" entry to the topic list menu: scan local Claude Code / Codex CLI transcripts and import them as topics, with incremental sync on re-import.','features.heteroSessionImport.title': 'Local Agent Session Import',diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex fae0cc5a17e..e1c1c3fd59f 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -169,6 +169,10 @@ export const UserLabSchema = z.object({* run Codex hetero sessions through codex app-server instead of one-shot CLI spawn*/enableCodexAppServer: z.boolean().optional(),+ /**+ * enable displaying two desktop tabs side by side+ */+ enableDesktopSplitView: z.boolean().optional(),/*** one-click import of local Claude Code / Codex CLI sessions as topics (desktop only)*/diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex 85eb30ad416..8ec80518a13 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -19,6 +19,7 @@ import {import { memo, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useConversationStore } from '@/features/Conversation/store';import { openAddWorkingDirModal } from '@/features/WorkingDirectory';import {resolveAgentWorkingDirectorySource,@@ -283,6 +284,7 @@ interface WorkingDirectoryPickerProps {* runs in when nothing is picked is never invisible.*/const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) => {+ const topicId = useConversationStore((s) => s.context.topicId);const { t } = useTranslation('device');const [open, setOpen] = useState(false);const [search, setSearch] = useState('');@@ -310,10 +312,10 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =const recents = useMemo(() => rawRecents.filter(isValidWorkingDirEntry), [rawRecents]);const rawDeviceDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(targetDeviceId));const deviceDefaultCwd = getWorkingDirectoryPathString(rawDeviceDefaultCwd);- const rawTopicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);+ const rawTopicWorkingDirectory = useChatStore(topicSelectors.getTopicWorkingDirectory(topicId));const topicWorkingDirectory = getWorkingDirectoryPathString(rawTopicWorkingDirectory);- const topicWorkingDirectoryConfig = useChatStore(- (s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,+ const topicWorkingDirectoryConfig = useChatStore((s) =>+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata?.workingDirectoryConfig : undefined,);const rawLegacyAgentWorkingDirectory = useAgentStore((s) => s.localAgentWorkingDirectoryMap[agentId],@@ -348,7 +350,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =legacyAgentWorkingDirectory);- const { clear, commit } = useCommitWorkingDirectory(agentId);+ const { clear, commit } = useCommitWorkingDirectory(agentId, topicId);const clearDeviceDefaultCwd = useDeviceStore((s) => s.clearDeviceDefaultCwd);const removeDeviceWorkingDir = useDeviceStore((s) => s.removeDeviceWorkingDir);const updateDeviceCwd = useDeviceStore((s) => s.updateDeviceCwd);diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex 258c7f0a2d4..bd6df06b391 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -69,7 +69,7 @@ const toAgentWorkingDirConfig = (entry: WorkingDirEntry): WorkingDirConfig => ({* per-cwd), so warn before the reset and clear the stale session id as part of* the same metadata write — same as the legacy pickers.*/-export const useCommitWorkingDirectory = (agentId: string) => {+export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string | null) => {const { t } = useTranslation(['plugin', 'chat']);// The RAW shared config — every write below spreads it back into@@ -93,9 +93,10 @@ export const useCommitWorkingDirectory = (agentId: string) => {(s) => s.localAgentWorkingDirectoryMap[agentId],);- const activeTopicId = useChatStore((s) => s.activeTopicId);+ const globalActiveTopicId = useChatStore((s) => s.activeTopicId);+ const activeTopicId = routeTopicId === undefined ? globalActiveTopicId : routeTopicId;const activeTopic = useChatStore((s) =>- s.activeTopicId ? topicSelectors.getTopicById(s.activeTopicId)(s) : undefined,+ activeTopicId ? topicSelectors.getTopicById(activeTopicId)(s) : undefined,);const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);diff --git a/src/features/Electron/TabHost/TabHost.test.ts b/src/features/Electron/TabHost/TabHost.test.tsindex 0d3d5779cb7..5a4b90a3fe8 100644--- a/src/features/Electron/TabHost/TabHost.test.ts+++ b/src/features/Electron/TabHost/TabHost.test.ts@@ -1,4 +1,4 @@-import { act, cleanup, render, screen } from '@testing-library/react';+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import React from 'react';import { createMemoryRouter, Outlet, RouterProvider, useParams } from 'react-router';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';import { useElectronStore } from '@/store/electron';import { initialState } from '@/store/electron/initialState';+import { useUserStore } from '@/store/user';import { MAX_LIVE_TAB_ROUTERS } from './resolveLiveTabIds';import TabHost from './TabHost';@@ -29,6 +30,7 @@ interface Creation {}let created: Creation[];+const initialUserState = useUserStore.getState();const createTestRouter = (url: string): TabRouter => {const router = createMemoryRouter(@@ -82,11 +84,19 @@ beforeEach(() => {window.localStorage.clear();resetTabRouterManager();setStore([], null);+ useUserStore.setState({+ isUserStateInit: true,+ preference: {+ ...initialUserState.preference,+ lab: { ...initialUserState.preference.lab, enableDesktopSplitView: true },+ },+ });});afterEach(() => {cleanup();resetTabRouterManager();+ useUserStore.setState(initialUserState, true);});describe('TabHost', () => {@@ -157,6 +167,67 @@ describe('TabHost', () => {expect(slotB.style.display).toBe('');});+ it('keeps both split panes visible and moves focus without hiding either router', async () => {+ const tabs = [+ { id: 'a', lastVisited: 2, url: '/item/a' },+ { id: 'b', lastVisited: 1, url: '/item/b' },+ ];+ useElectronStore.setState({+ ...initialState,+ activeTabId: 'a',+ splitView: { primaryTabId: 'a', ratio: 0.5, secondaryTabId: 'b' },+ tabs,+ });++ renderHost();++ const slotA = (await screen.findByTestId('param-a')).parentElement!;+ const slotB = (await screen.findByTestId('param-b')).parentElement!;+ expect(slotA.style.display).toBe('');+ expect(slotB.style.display).toBe('');+ expect(slotA).toHaveAttribute('data-pane', 'primary');+ expect(slotB).toHaveAttribute('data-pane', 'secondary');++ act(() => {+ slotB.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));+ });++ expect(useElectronStore.getState().activeTabId).toBe('b');+ expect(slotA.style.display).toBe('');+ expect(slotB.style.display).toBe('');++ act(() => {+ useElectronStore.setState({ activeTabId: 'a' });+ slotB.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));+ });++ expect(useElectronStore.getState().activeTabId).toBe('b');+ });++ it('collapses a persisted split when the alpha lab is disabled', async () => {+ useUserStore.setState({+ preference: {+ ...initialUserState.preference,+ lab: { ...initialUserState.preference.lab, enableDesktopSplitView: false },+ },+ });+ useElectronStore.setState({+ ...initialState,+ activeTabId: 'a',+ splitView: { primaryTabId: 'a', ratio: 0.5, secondaryTabId: 'b' },+ tabs: [+ { id: 'a', lastVisited: 2, url: '/item/a' },+ { id: 'b', lastVisited: 1, url: '/item/b' },+ ],+ });++ renderHost();++ expect(await screen.findByTestId('param-a')).toBeVisible();+ expect(screen.getByTestId('param-b').parentElement).toHaveStyle({ display: 'none' });+ await waitFor(() => expect(useElectronStore.getState().splitView).toBeNull());+ });+it('disposes a router evicted past the LRU cap and recreates it fresh when reactivated', async () => {const baseTabs: TabItem[] = Array.from({ length: MAX_LIVE_TAB_ROUTERS }, (_, index) => ({id: `t${index}`,diff --git a/src/features/Electron/TabHost/TabHost.tsx b/src/features/Electron/TabHost/TabHost.tsxindex 285efbd1bc0..9b850cf9d56 100644--- a/src/features/Electron/TabHost/TabHost.tsx+++ b/src/features/Electron/TabHost/TabHost.tsx@@ -1,11 +1,22 @@'use client';-import { Activity, type CSSProperties, useEffect, useMemo } from 'react';+import { createStaticStyles } from 'antd-style';+import {+ Activity,+ type CSSProperties,+ type KeyboardEvent,+ type PointerEvent,+ useEffect,+ useMemo,+} from 'react';+import { useTranslation } from 'react-i18next';import { UNSAFE_LocationContext } from 'react-router';import { RouterProvider } from 'react-router/dom';import { createTabRouter } from '@/spa/router/tabRouter';import { useElectronStore } from '@/store/electron';+import { useUserStore } from '@/store/user';+import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors';import { MAX_LIVE_TAB_ROUTERS, resolveLiveTabIds } from './resolveLiveTabIds';import { TabIdContext } from './TabIdContext';@@ -25,13 +36,75 @@ const rootStyle: CSSProperties = { blockSize: '100%', inlineSize: '100%', positiconst slotStyle: CSSProperties = { inset: 0, position: 'absolute' };const hiddenSlotStyle: CSSProperties = { ...slotStyle, display: 'none' };+const styles = createStaticStyles(({ css, cssVar }) => ({+ divider: css`+ cursor: col-resize;++ position: absolute;+ z-index: 10;+ inset-block: 0;+ transform: translateX(-50%);++ width: 8px;++ &::after {+ content: '';++ position: absolute;+ inset-block: 0;+ inset-inline-start: 50%;+ transform: translateX(-50%);++ width: 1px;++ background: ${cssVar.colorBorderSecondary};++ transition:+ background 150ms ease,+ width 150ms ease;+ }++ &:hover::after,+ &:focus-visible::after {+ width: 2px;+ background: ${cssVar.colorPrimary};+ }+ `,+ pane: css`+ overflow: hidden;+ min-width: 0;+ `,+}));+const TabHost = ({ createRouter = createTabRouter }: TabHostProps) => {+ const { t } = useTranslation('electron');const tabs = useElectronStore((s) => s.tabs);const activeTabId = useElectronStore((s) => s.activeTabId);+ const splitView = useElectronStore((s) => s.splitView);+ const isPreferenceInit = useUserStore(preferenceSelectors.isPreferenceInit);+ const splitViewEnabled = useUserStore(labPreferSelectors.enableDesktopSplitView);+ const closeSplitView = useElectronStore((s) => s.closeSplitView);+ const focusTabPane = useElectronStore((s) => s.focusTabPane);+ const setSplitRatio = useElectronStore((s) => s.setSplitRatio);+ const effectiveSplitView = isPreferenceInit && splitViewEnabled ? splitView : null;++ const visibleTabIds = useMemo(+ () =>+ effectiveSplitView+ ? [effectiveSplitView.primaryTabId, effectiveSplitView.secondaryTabId]+ : activeTabId+ ? [activeTabId]+ : [],+ [activeTabId, effectiveSplitView],+ );++ useEffect(() => {+ if (isPreferenceInit && !splitViewEnabled && splitView) closeSplitView();+ }, [closeSplitView, isPreferenceInit, splitView, splitViewEnabled]);const liveIds = useMemo(- () => resolveLiveTabIds(tabs, activeTabId, MAX_LIVE_TAB_ROUTERS),- [tabs, activeTabId],+ () => resolveLiveTabIds(tabs, activeTabId, MAX_LIVE_TAB_ROUTERS, visibleTabIds),+ [tabs, activeTabId, visibleTabIds],);useEffect(() => {@@ -47,19 +120,51 @@ const TabHost = ({ createRouter = createTabRouter }: TabHostProps) => {}, [liveIds]);const liveSet = new Set(liveIds);+ const visibleSet = new Set(visibleTabIds);++ const handleDividerPointerMove = (event: PointerEvent<HTMLDivElement>) => {+ if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;+ const bounds = event.currentTarget.parentElement?.getBoundingClientRect();+ if (!bounds?.width) return;+ setSplitRatio((event.clientX - bounds.left) / bounds.width);+ };++ const handleDividerKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (!effectiveSplitView) return;+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;+ event.preventDefault();+ setSplitRatio(effectiveSplitView.ratio + (event.key === 'ArrowLeft' ? -0.05 : 0.05));+ };return (<div style={rootStyle}>{tabs.filter((tab) => liveSet.has(tab.id)).map((tab) => {- const isActive = tab.id === activeTabId;+ const isVisible = visibleSet.has(tab.id);+ const isPrimary = effectiveSplitView?.primaryTabId === tab.id;+ const paneStyle: CSSProperties = effectiveSplitView+ ? isPrimary+ ? { ...slotStyle, right: 'auto', width: `${effectiveSplitView.ratio * 100}%` }+ : {+ ...slotStyle,+ left: 'auto',+ width: `${(1 - effectiveSplitView.ratio) * 100}%`,+ }+ : slotStyle;return (- <Activity key={tab.id} mode={isActive ? 'visible' : 'hidden'} name={`Tab:${tab.id}`}>+ <Activity key={tab.id} mode={isVisible ? 'visible' : 'hidden'} name={`Tab:${tab.id}`}>{/* Activity preserves state but doesn't visually hide the DOM in this Reactversion, so force-hide the inactive slot (mirrors home/_layout). */}- <div style={isActive ? slotStyle : hiddenSlotStyle}>+ <div+ className={styles.pane}+ data-focused={tab.id === activeTabId ? 'true' : undefined}+ data-pane={effectiveSplitView ? (isPrimary ? 'primary' : 'secondary') : 'single'}+ style={isVisible ? paneStyle : hiddenSlotStyle}+ onFocusCapture={() => focusTabPane(tab.id)}+ onPointerDownCapture={() => focusTabPane(tab.id)}+ ><TabIdContext value={tab.id}>{/* react-router forbids a data <RouterProvider> inside another Router(useInRouterContext invariant). Reset LocationContext so each per-tab@@ -73,6 +178,23 @@ const TabHost = ({ createRouter = createTabRouter }: TabHostProps) => {</Activity>);})}+ {effectiveSplitView && (+ <div+ aria-label={t('tab.resizeSplitView')}+ aria-orientation="vertical"+ aria-valuemax={75}+ aria-valuemin={25}+ aria-valuenow={Math.round(effectiveSplitView.ratio * 100)}+ className={styles.divider}+ role="separator"+ style={{ left: `${effectiveSplitView.ratio * 100}%` }}+ tabIndex={0}+ onDoubleClick={() => setSplitRatio(0.5)}+ onKeyDown={handleDividerKeyDown}+ onPointerDown={(event) => event.currentTarget.setPointerCapture(event.pointerId)}+ onPointerMove={handleDividerPointerMove}+ />+ )}</div>);};diff --git a/src/features/Electron/TabHost/TabLocationReporter.tsx b/src/features/Electron/TabHost/TabLocationReporter.tsxindex dcdb642c950..9f19461242c 100644--- a/src/features/Electron/TabHost/TabLocationReporter.tsx+++ b/src/features/Electron/TabHost/TabLocationReporter.tsx@@ -15,9 +15,15 @@ const TabLocationReporter = () => {useEffect(() => {if (!tabId) return;- // `<Activity mode="hidden">` tears down effects in hidden trees, so only the- // active tab reaches here; the active-id check is belt-and-braces.- if (useElectronStore.getState().activeTabId !== tabId) return;+ // `<Activity mode="hidden">` tears down effects in hidden trees. In split view both+ // pane routers stay visible, so either one may report navigation even when keyboard+ // focus currently belongs to the other pane.+ const { activeTabId, splitView } = useElectronStore.getState();+ const isVisible =+ activeTabId === tabId ||+ splitView?.primaryTabId === tabId ||+ splitView?.secondaryTabId === tabId;+ if (!isVisible) return;// A hidden tree also loses `RouterProvider`'s subscription, and remounting it// only reconnects — it never replays what was missed. So a backgrounddiff --git a/src/features/Electron/TabHost/resolveLiveTabIds.test.ts b/src/features/Electron/TabHost/resolveLiveTabIds.test.tsindex 2e68b84b849..98b5d235273 100644--- a/src/features/Electron/TabHost/resolveLiveTabIds.test.ts+++ b/src/features/Electron/TabHost/resolveLiveTabIds.test.ts@@ -43,6 +43,12 @@ describe('resolveLiveTabIds', () => {expect(resolveLiveTabIds([tab('a', 1)], null, 0)).toEqual([]);});+ it('retains both visible split panes even when one is older than the LRU cap', () => {+ const tabs = [tab('left', 1), tab('recent', 3), tab('right', 2)];++ expect(resolveLiveTabIds(tabs, 'right', 2, ['left', 'right'])).toEqual(['left', 'right']);+ });+it('exposes the default cap', () => {expect(MAX_LIVE_TAB_ROUTERS).toBe(3);});diff --git a/src/features/Electron/TabHost/resolveLiveTabIds.ts b/src/features/Electron/TabHost/resolveLiveTabIds.tsindex 84173e6bbd6..92b7e24792a 100644--- a/src/features/Electron/TabHost/resolveLiveTabIds.ts+++ b/src/features/Electron/TabHost/resolveLiveTabIds.ts@@ -6,10 +6,16 @@ export const resolveLiveTabIds = (tabs: Pick<TabItem, 'id' | 'lastVisited'>[],activeTabId: string | null,cap: number,+ retainedTabIds: string[] = [],): string[] => {const hasActive = activeTabId !== null && tabs.some((tab) => tab.id === activeTabId);+ const existingIds = new Set(tabs.map((tab) => tab.id));- if (cap <= 0) return hasActive ? [activeTabId!] : [];+ if (cap <= 0) {+ const retained = new Set(retainedTabIds.filter((id) => existingIds.has(id)));+ if (hasActive) retained.add(activeTabId);+ return tabs.filter((tab) => retained.has(tab.id)).map((tab) => tab.id);+ }const ranked = tabs.map((tab, index) => ({ id: tab.id, index, lastVisited: tab.lastVisited }))@@ -17,6 +23,9 @@ export const resolveLiveTabIds = (const live = new Set<string>();if (hasActive) live.add(activeTabId!);+ for (const id of retainedTabIds) {+ if (existingIds.has(id)) live.add(id);+ }for (const entry of ranked) {if (live.size >= cap) break;diff --git a/src/features/Electron/titlebar/TabBar/TabItem.tsx b/src/features/Electron/titlebar/TabBar/TabItem.tsxindex 9dbdc194f4a..959d5c58d8f 100644--- a/src/features/Electron/titlebar/TabBar/TabItem.tsx+++ b/src/features/Electron/titlebar/TabBar/TabItem.tsx@@ -45,14 +45,18 @@ interface TabItemProps {enterX: number;index: number;isActive: boolean;+ isSplitVisible: boolean;item: ResolvedTab;onActivate: (id: string, url: string) => void;onClose: (id: string) => void;onCloseLeft: (id: string) => void;onCloseOthers: (id: string) => void;onCloseRight: (id: string) => void;+ onCloseSplitView: () => void;+ onOpenInSplitView: (id: string) => void;onTogglePin: (id: string) => void;pinnedCount: number;+ splitViewEnabled: boolean;tier: TabTier;totalCount: number;width: number;@@ -63,8 +67,10 @@ const TabItem = memo<TabItemProps>(({item,isActive,+ isSplitVisible,index,pinnedCount,+ splitViewEnabled,tier,totalCount,width,@@ -75,6 +81,8 @@ const TabItem = memo<TabItemProps>(onCloseOthers,onCloseLeft,onCloseRight,+ onCloseSplitView,+ onOpenInSplitView,onTogglePin,}) => {const styles = useStyles;@@ -163,13 +171,17 @@ const TabItem = memo<TabItemProps>(buildTabContextMenuItems({id,index,+ inSplitView: isSplitVisible,onClose,onCloseLeft,onCloseOthers,onCloseRight,+ onCloseSplitView,+ onOpenInSplitView,onTogglePin,pinned,pinnedCount,+ splitViewEnabled,t,totalCount,}),@@ -180,10 +192,14 @@ const TabItem = memo<TabItemProps>(totalCount,pinned,pinnedCount,+ splitViewEnabled,+ isSplitVisible,onClose,onCloseOthers,onCloseLeft,onCloseRight,+ onCloseSplitView,+ onOpenInSplitView,onTogglePin,],);@@ -215,6 +231,7 @@ const TabItem = memo<TabItemProps>(electronStylish.nodrag,styles.tab,pinned && styles.tabPinned,+ isSplitVisible && !isActive && styles.tabSplitVisible,isActive && styles.tabActive,isDragging && styles.tabDragging,)}diff --git a/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap b/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snapindex e4006e75230..1f0053abef4 100644--- a/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap+++ b/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap@@ -7,16 +7,21 @@ exports[`tab context menu ownership > goes native on macOS desktop (plain string"label": "tab.pin","type": "normal",},+ {+ "id": "1",+ "label": "tab.openInSplitView",+ "type": "normal",+ },{"type": "separator",},{- "id": "2",+ "id": "3","label": "tab.closeCurrentTab","type": "normal",},{- "id": "3",+ "id": "4","label": "tab.closeOtherTabs","type": "normal",},@@ -24,12 +29,12 @@ exports[`tab context menu ownership > goes native on macOS desktop (plain string"type": "separator",},{- "id": "5",+ "id": "6","label": "tab.closeLeftTabs","type": "normal",},{- "id": "6",+ "id": "7","label": "tab.closeRightTabs","type": "normal",},diff --git a/src/features/Electron/titlebar/TabBar/index.tsx b/src/features/Electron/titlebar/TabBar/index.tsxindex debf4c34556..a1ddcee1676 100644--- a/src/features/Electron/titlebar/TabBar/index.tsx+++ b/src/features/Electron/titlebar/TabBar/index.tsx@@ -27,6 +27,8 @@ import { useRegisterDesktopTabHotkeys } from '@/hooks/useHotkeys/desktopTabScopeimport { usePermission } from '@/hooks/usePermission';import { electronSystemService } from '@/services/electron/system';import { useElectronStore } from '@/store/electron';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import { electronStylish } from '@/styles/electron';import { useResolvedTabs } from './hooks/useResolvedTabs';@@ -59,6 +61,8 @@ const TabBar = () => {const { allowed: canCreate, reason } = usePermission('create_content');const [stripWidth, stripRef] = useStripWidth();const { tabs, activeTabId } = useResolvedTabs();+ const splitView = useElectronStore((s) => s.splitView);+ const splitViewEnabled = useUserStore(labPreferSelectors.enableDesktopSplitView);const activateTab = useElectronStore((s) => s.activateTab);const addNewTab = useElectronStore((s) => s.addNewTab);const removeTab = useElectronStore((s) => s.removeTab);@@ -68,6 +72,8 @@ const TabBar = () => {const reorderTabs = useElectronStore((s) => s.reorderTabs);const pinTab = useElectronStore((s) => s.pinTab);const unpinTab = useElectronStore((s) => s.unpinTab);+ const closeSplitView = useElectronStore((s) => s.closeSplitView);+ const openTabInSplitView = useElectronStore((s) => s.openTabInSplitView);const sensors = useSensors(// Require a small drag distance so a plain click still activates the tab.@@ -246,15 +252,22 @@ const TabBar = () => {item={tab}key={placement.id}pinnedCount={pinnedTabs.length}+ splitViewEnabled={splitViewEnabled}tier={resolveTabTier(placement.width)}totalCount={tabs.length}width={placement.width}x={placement.x}+ isSplitVisible={+ splitView?.primaryTabId === placement.id ||+ splitView?.secondaryTabId === placement.id+ }onActivate={handleActivate}onClose={handleClose}onCloseLeft={handleCloseLeft}onCloseOthers={handleCloseOthers}onCloseRight={handleCloseRight}+ onCloseSplitView={closeSplitView}+ onOpenInSplitView={openTabInSplitView}onTogglePin={handleTogglePin}/>);diff --git a/src/features/Electron/titlebar/TabBar/styles.ts b/src/features/Electron/titlebar/TabBar/styles.tsindex 85e8b42393c..aa72c7ec454 100644--- a/src/features/Electron/titlebar/TabBar/styles.ts+++ b/src/features/Electron/titlebar/TabBar/styles.ts@@ -175,6 +175,21 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({background-color: ${cssVar.colorFillTertiary};}`,+ tabSplitVisible: css`+ &::after {+ content: '';++ position: absolute;+ inset-block-end: 1px;+ inset-inline: 8px;++ height: 1px;+ border-radius: 1px;++ opacity: 0.65;+ background: ${cssVar.colorPrimary};+ }+ `,overflowButton: css`cursor: default;diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.tsindex d3684559ce6..bb4fd415b8f 100644--- a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts@@ -9,13 +9,17 @@ const build = (index: number, totalCount: number, pinned = false, pinnedCount =buildTabContextMenuItems({id: 'tab-1',index,+ inSplitView: false,onClose: vi.fn(),onCloseLeft: vi.fn(),onCloseOthers: vi.fn(),onCloseRight: vi.fn(),+ onCloseSplitView: vi.fn(),+ onOpenInSplitView: vi.fn(),onTogglePin: vi.fn(),pinned,pinnedCount,+ splitViewEnabled: true,t: (key) => key,totalCount,});@@ -59,6 +63,62 @@ describe('pin entry', () => {});});+describe('split view entry', () => {+ it('hides split view while the alpha lab is disabled', () => {+ const items = buildTabContextMenuItems({+ id: 'tab-1',+ inSplitView: false,+ index: 0,+ onClose: vi.fn(),+ onCloseLeft: vi.fn(),+ onCloseOthers: vi.fn(),+ onCloseRight: vi.fn(),+ onCloseSplitView: vi.fn(),+ onOpenInSplitView: vi.fn(),+ onTogglePin: vi.fn(),+ pinned: false,+ pinnedCount: 0,+ splitViewEnabled: false,+ t: (key) => key,+ totalCount: 2,+ });++ expect(items.some((item) => item && 'key' in item && item.key === 'openInSplitView')).toBe(+ false,+ );+ });++ it('offers opening a tab in split view', () => {+ const items = build(0, 2);+ const entry = items.find((item) => !!item && 'key' in item && item.key === 'openInSplitView');++ expect(entry && 'label' in entry ? entry.label : undefined).toBe('tab.openInSplitView');+ });++ it('offers closing split view for a tab already shown in a pane', () => {+ const items = buildTabContextMenuItems({+ id: 'tab-1',+ inSplitView: true,+ index: 0,+ onClose: vi.fn(),+ onCloseLeft: vi.fn(),+ onCloseOthers: vi.fn(),+ onCloseRight: vi.fn(),+ onCloseSplitView: vi.fn(),+ onOpenInSplitView: vi.fn(),+ onTogglePin: vi.fn(),+ pinned: false,+ pinnedCount: 0,+ splitViewEnabled: true,+ t: (key) => key,+ totalCount: 2,+ });+ const entry = items.find((item) => !!item && 'key' in item && item.key === 'closeSplitView');++ expect(entry && 'label' in entry ? entry.label : undefined).toBe('tab.closeSplitView');+ });+});+describe('bulk close entries reflect what pinning spares', () => {it('disables closing others when every other tab is pinned', () => {expect(isDisabled(build(2, 3, false, 2), 'closeOtherTabs')).toBe(true);diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.tsindex e9b4a069ec2..68c6207274b 100644--- a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts@@ -5,19 +5,25 @@ type TabContextMenuLabelKey =| 'tab.closeLeftTabs'| 'tab.closeOtherTabs'| 'tab.closeRightTabs'+ | 'tab.closeSplitView'+ | 'tab.openInSplitView'| 'tab.pin'| 'tab.unpin';interface TabContextMenuParams {id: string;index: number;+ inSplitView: boolean;onClose: (id: string) => void;onCloseLeft: (id: string) => void;onCloseOthers: (id: string) => void;onCloseRight: (id: string) => void;+ onCloseSplitView: () => void;+ onOpenInSplitView: (id: string) => void;onTogglePin: (id: string) => void;pinned: boolean;pinnedCount: number;+ splitViewEnabled: boolean;t: (key: TabContextMenuLabelKey) => string;totalCount: number;}@@ -28,13 +34,17 @@ interface TabContextMenuParams {export const buildTabContextMenuItems = ({id,index,+ inSplitView,onClose,onCloseLeft,onCloseOthers,onCloseRight,+ onCloseSplitView,+ onOpenInSplitView,onTogglePin,pinned,pinnedCount,+ splitViewEnabled,t,totalCount,}: TabContextMenuParams): GenericItemType[] => {@@ -48,6 +58,13 @@ export const buildTabContextMenuItems = ({label: pinned ? t('tab.unpin') : t('tab.pin'),onClick: () => onTogglePin(id),},+ splitViewEnabled || inSplitView+ ? {+ key: inSplitView ? 'closeSplitView' : 'openInSplitView',+ label: t(inSplitView ? 'tab.closeSplitView' : 'tab.openInSplitView'),+ onClick: () => (inSplitView ? onCloseSplitView() : onOpenInSplitView(id)),+ }+ : null,{ type: 'divider' },{disabled: totalCount === 1,diff --git a/src/features/Settings/labs/index.test.tsx b/src/features/Settings/labs/index.test.tsxindex 7af5571cdab..a7cc16d94c2 100644--- a/src/features/Settings/labs/index.test.tsx+++ b/src/features/Settings/labs/index.test.tsx@@ -135,6 +135,13 @@ describe('Labs settings page', () => {expect(screen.getByText('features.messageTextSelectionActions.title')).toBeDefined();});+ it('renders the desktop split view as an alpha lab toggle', () => {+ renderPage();++ const splitView = screen.getByText('features.desktopSplitView.title');+ expect(within(splitView).getByText('stage.alpha.label')).toBeDefined();+ });+it('renders the OAuth Apps lab toggle', () => {renderPage();@@ -158,8 +165,8 @@ describe('Labs settings page', () => {const alphaTags = screen.getAllByText('stage.alpha.label');const betaTags = screen.getAllByText('stage.beta.label');- // Every toggle carries exactly one stage tag (6 general + 5 desktop).- expect(alphaTags.length + betaTags.length).toBe(11);+ // Every toggle carries exactly one stage tag (6 general + 6 desktop).+ expect(alphaTags.length + betaTags.length).toBe(12);});it('marks internal-testing experiments as alpha and usable ones as beta', () => {diff --git a/src/features/Settings/labs/index.tsx b/src/features/Settings/labs/index.tsxindex 2d1b575976d..c2b90395b3b 100644--- a/src/features/Settings/labs/index.tsx+++ b/src/features/Settings/labs/index.tsx@@ -64,6 +64,7 @@ const LabsForm = memo(() => {enableImessage,enableClaudeCodeSdk,enableCodexAppServer,+ enableDesktopSplitView,enableHeteroSessionImport,enableMessageTextSelectionActions,enableOAuthApps,@@ -81,6 +82,7 @@ const LabsForm = memo(() => {labPreferSelectors.enableImessage(s),labPreferSelectors.enableClaudeCodeSdk(s),labPreferSelectors.enableCodexAppServer(s),+ labPreferSelectors.enableDesktopSplitView(s),labPreferSelectors.enableHeteroSessionImport(s),labPreferSelectors.enableMessageTextSelectionActions(s),labPreferSelectors.enableOAuthApps(s),@@ -172,6 +174,13 @@ const LabsForm = memo(() => {// Desktop-only experiments: local agent runtimes, iMessage bridge, and the// in-app browser (renderer-retained Electron webviews).const desktopItems: LabToggle[] = [+ {+ checked: enableDesktopSplitView,+ desc: tLabs('features.desktopSplitView.desc'),+ flag: 'enableDesktopSplitView',+ stage: 'alpha',+ title: tLabs('features.desktopSplitView.title'),+ },{checked: enableImessage,desc: tLabs('features.imessage.desc'),diff --git a/src/features/TopicComment/TopicCommentButton.tsx b/src/features/TopicComment/TopicCommentButton.tsxindex 29340cfe70c..63effe91080 100644--- a/src/features/TopicComment/TopicCommentButton.tsx+++ b/src/features/TopicComment/TopicCommentButton.tsx@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { DESKTOP_HEADER_ICON_SMALL_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';+import { useAgentContext } from '@/features/Conversation/useAgentContext';import { useChatStore } from '@/store/chat';import { usePrefetchTopicCommentsOnTopicLoad, useTopicCommentSummary } from './hooks';@@ -13,7 +14,7 @@ import { usePrefetchTopicCommentsOnTopicLoad, useTopicCommentSummary } from './hconst TopicCommentButton = memo<{ mobile?: boolean }>(({ mobile }) => {const { t } = useTranslation('chat');const workspaceId = useActiveWorkspaceId();- const topicId = useChatStore((s) => s.activeTopicId);+ const { topicId } = useAgentContext();const openTopicComments = useChatStore((s) => s.openTopicComments);const { data } = useTopicCommentSummary(workspaceId ? topicId : undefined);usePrefetchTopicCommentsOnTopicLoad(workspaceId ? topicId : undefined);diff --git a/src/hooks/useEffectiveWorkingDirectory.test.ts b/src/hooks/useEffectiveWorkingDirectory.test.tsindex a1ff30a327b..d3aa5cfc9ba 100644--- a/src/hooks/useEffectiveWorkingDirectory.test.ts+++ b/src/hooks/useEffectiveWorkingDirectory.test.ts@@ -36,6 +36,9 @@ vi.mock('@/store/chat/selectors', () => ({currentTopicMetadata: (s: { topicMetadata?: object }) => s.topicMetadata,currentTopicWorkingDirectory: (s: { topicWorkingDirectory?: string }) =>s.topicWorkingDirectory,+ getTopicById: () => (s: { topicMetadata?: object }) => ({ metadata: s.topicMetadata }),+ getTopicWorkingDirectory: (id?: string | null) => (s: { topicWorkingDirectory?: string }) =>+ id === null ? undefined : s.topicWorkingDirectory,},}));vi.mock('@/store/device', () => ({@@ -138,6 +141,38 @@ describe('useEffectiveWorkingDirectory', () => {expect(result.current).toBe('/repo/topic-project');});+ it('resolves a route-scoped topic override', () => {+ setupStores({+ agencyConfig: { workingDirByDevice: { 'device-A': '/repo/project' } },+ topicWorkingDirectory: '/repo/split-pane-topic',+ });++ const { result } = renderHook(() =>+ useEffectiveWorkingDirectory('agent-1', {+ homeFallback: false,+ topicId: 'topic-in-split-pane',+ }),+ );++ expect(result.current).toBe('/repo/split-pane-topic');+ });++ it('does not inherit the active topic directory for a new-topic pane', () => {+ setupStores({+ agencyConfig: { workingDirByDevice: { 'device-A': '/repo/agent-default' } },+ topicWorkingDirectory: '/repo/other-pane-topic',+ });++ const { result } = renderHook(() =>+ useEffectiveWorkingDirectory('agent-1', {+ homeFallback: false,+ topicId: null,+ }),+ );++ expect(result.current).toBe('/repo/agent-default');+ });+it('keeps the device default cwd with homeFallback disabled', () => {setupStores({ deviceDefaultCwd: '/repo/device-default' });diff --git a/src/hooks/useEffectiveWorkingDirectory.ts b/src/hooks/useEffectiveWorkingDirectory.tsindex bfa1504d08d..f3bf27e932b 100644--- a/src/hooks/useEffectiveWorkingDirectory.ts+++ b/src/hooks/useEffectiveWorkingDirectory.ts@@ -24,6 +24,7 @@ interface UseEffectiveWorkingDirectoryOptions {* @default true*/homeFallback?: boolean;+ topicId?: string | null;}/**@@ -39,7 +40,7 @@ interface UseEffectiveWorkingDirectoryOptions {*/export const useEffectiveWorkingDirectory = (agentId?: string,- { homeFallback = true }: UseEffectiveWorkingDirectoryOptions = {},+ { homeFallback = true, topicId }: UseEffectiveWorkingDirectoryOptions = {},): string | undefined => {// Self-populate the device store (SWR dedupes by key across all callers).// Devices live behind an authed lambda procedure, so only fetch once signed in@@ -54,9 +55,11 @@ export const useEffectiveWorkingDirectory = (const legacyAgentWorkingDirectory = useAgentStore((s) =>agentId ? s.localAgentWorkingDirectoryMap[agentId] : undefined,);- const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);- const topicWorkingDirectoryConfig = useChatStore(- (s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,+ const topicWorkingDirectory = useChatStore(topicSelectors.getTopicWorkingDirectory(topicId));+ const topicWorkingDirectoryConfig = useChatStore((s) =>+ topicId+ ? topicSelectors.getTopicById(topicId)(s)?.metadata?.workingDirectoryConfig+ : topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.tsindex 5eba3c9d629..b1ed4022195 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts@@ -1 +1,4 @@+// Electron projects route state through the single ActiveConversationBridge,+// which follows activeTabId. Keeping this hook inert prevents every visible+// split-pane router from subscribing to and rewriting the global conversation.export const useChatRouteSync = () => {};diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsxindex cfc9ecd69a0..f4ec0cd1a20 100644--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx@@ -29,6 +29,10 @@ vi.mock('@/const/version', () => ({isDesktop: true,}));+vi.mock('@/features/Conversation/useAgentContext', () => ({+ useAgentContext: () => ({ agentId: 'agent-1', topicId: 'topic-1' }),+}));+vi.mock('@lobehub/ui', () => ({Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,@@ -58,8 +62,8 @@ vi.mock('react-router', () => ({vi.mock('@/store/chat/selectors', () => ({topicSelectors: {- currentActiveTopic: (state: Record<string, unknown>) => state.activeTopic,- currentTopicWorkingDirectory: (state: Record<string, unknown>) => state.workingDirectory,+ getTopicById: (id: string) => (state: { topics: Record<string, unknown> }) => state.topics[id],+ getTopicWorkingDirectory: () => (state: Record<string, unknown>) => state.workingDirectory,},}));@@ -67,12 +71,19 @@ vi.mock('@/store/chat', () => ({useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>selector({activeAgentId: 'agent-1',- activeTopic: {- favorite: false,- id: 'topic-1',- title: 'Topic 1',- updatedAt: '2026-05-27T00:15:00.000Z',- userId: 'user-1',+ activeTopicId: 'topic-other-pane',+ topics: {+ 'topic-1': {+ favorite: false,+ id: 'topic-1',+ title: 'Topic 1',+ updatedAt: '2026-05-27T00:15:00.000Z',+ userId: 'user-1',+ },+ 'topic-other-pane': {+ id: 'topic-other-pane',+ title: 'Other pane topic',+ },},autoRenameTopicTitle: autoRenameTopicTitleMock,favoriteTopic: favoriteTopicMock,diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsxindex 73e388a5b09..c40351225c5 100644--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx@@ -24,6 +24,7 @@ import { useAuthorInfo } from '@/business/client/hooks/useAuthorInfo';import { openRenameModal } from '@/components/RenameModal';import { DOCUMENT_HISTORY_QUERY_LIST_LIMIT } from '@/const/documentHistory';import { isDesktop } from '@/const/version';+import { useAgentContext } from '@/features/Conversation/useAgentContext';import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';import { openDocumentCompareModal } from '@/features/PageEditor/History/CompareModal';import { formatHistoryAbsoluteTime } from '@/features/PageEditor/History/formatHistoryDate';@@ -76,9 +77,11 @@ export const useMenu = (): { menuHeader?: ReactNode; menuItems: () => DropdownIt]);const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);- const activeAgentId = useChatStore((s) => s.activeAgentId);- const activeTopic = useChatStore(topicSelectors.currentActiveTopic);- const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);+ const { agentId: activeAgentId, topicId: routeTopicId } = useAgentContext();+ const activeTopic = useChatStore((s) =>+ routeTopicId ? topicSelectors.getTopicById(routeTopicId)(s) : undefined,+ );+ const workingDirectory = useChatStore(topicSelectors.getTopicWorkingDirectory(routeTopicId));const [autoRenameTopicTitle, favoriteTopic, removeTopic, updateTopicTitle] = useChatStore((s) => [s.autoRenameTopicTitle,s.favoriteTopic,diff --git a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsxindex 55f83cff11a..6a9fba260d7 100644--- a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx@@ -55,13 +55,12 @@ vi.mock('@/features/ShareModal', () => ({}),}));-vi.mock('@/hooks/usePermission', () => ({- usePermission: () => ({ allowed: mocks.permission.allowed, reason: mocks.permission.reason }),+vi.mock('@/features/Conversation/useAgentContext', () => ({+ useAgentContext: () => ({ topicId: mocks.activeTopicId }),}));-vi.mock('@/store/chat', () => ({- useChatStore: (selector: (state: { activeTopicId?: string }) => unknown) =>- selector({ activeTopicId: mocks.activeTopicId }),+vi.mock('@/hooks/usePermission', () => ({+ usePermission: () => ({ allowed: mocks.permission.allowed, reason: mocks.permission.reason }),}));vi.mock('@/store/serverConfig', () => ({diff --git a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.tsxindex 79040010d78..8e168e3bc1b 100644--- a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.tsx@@ -7,10 +7,10 @@ import { useTranslation } from 'react-i18next';import { withSuspense } from '@/components/withSuspense';import { DESKTOP_HEADER_ICON_SMALL_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';+import { useAgentContext } from '@/features/Conversation/useAgentContext';import { useShareModal } from '@/features/ShareModal';import { LazySharePopover as SharePopover } from '@/features/SharePopover/lazy';import { usePermission } from '@/hooks/usePermission';-import { useChatStore } from '@/store/chat';import { useServerConfigStore } from '@/store/serverConfig';import { serverConfigSelectors } from '@/store/serverConfig/selectors';@@ -23,12 +23,12 @@ interface ShareButtonProps {const ShareButton = memo<ShareButtonProps>(({ mobile, setOpen, open }) => {const { openShareModal } = useShareModal({ open, setOpen });const { t } = useTranslation('common');- const activeTopicId = useChatStore((s) => s.activeTopicId);+ const { topicId } = useAgentContext();const enableTopicLinkShare = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);const { allowed: canShare, reason } = usePermission('edit_own_content');// Hide share button when no topic exists (no messages sent yet)- if (!activeTopicId) return null;+ if (!topicId) return null;const iconButton = (<ActionIcondiff --git a/src/routes/(main)/agent/features/Conversation/Header/Tags/FolderTag.tsx b/src/routes/(main)/agent/features/Conversation/Header/Tags/FolderTag.tsxdeleted file mode 100644index bf14a432a67..00000000000--- a/src/routes/(main)/agent/features/Conversation/Header/Tags/FolderTag.tsx+++ /dev/null@@ -1,57 +0,0 @@-import { Tooltip } from '@lobehub/ui';-import { createStaticStyles, cssVar } from 'antd-style';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { isDesktop } from '@/const/version';-import { localFileService } from '@/services/electron/localFileService';-import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/selectors';--const styles = createStaticStyles(({ css }) => ({- chip: css`- cursor: pointer;-- overflow: hidden;- display: inline-block;-- min-width: 0;- max-width: 200px;-- font-size: 13px;- color: ${cssVar.colorTextTertiary};- text-overflow: ellipsis;- white-space: nowrap;-- transition: color 0.2s;-- &:hover {- color: ${cssVar.colorText};- }- `,-}));--const FolderTag = memo(() => {- const { t } = useTranslation('tool');-- const topicBoundDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);-- if (!isDesktop || !topicBoundDirectory) return null;- const handleOpen = () => {- void localFileService.openLocalFolder({ isDirectory: true, path: topicBoundDirectory });- };-- const displayName = topicBoundDirectory.split('/').findLast(Boolean) || topicBoundDirectory;-- return (- <Tooltip title={`${topicBoundDirectory} · ${t('localFiles.openFolder')}`}>- <span className={styles.chip} onClick={handleOpen}>- {displayName}- </span>- </Tooltip>- );-});--FolderTag.displayName = 'TopicFolderTag';--export default FolderTag;diff --git a/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsxindex 27ba9a5fa18..ee2530d1ef7 100644--- a/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx@@ -3,24 +3,26 @@ import { cssVar } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { useAgentContext } from '@/features/Conversation/useAgentContext';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { useSessionStore } from '@/store/session';import { sessionSelectors } from '@/store/session/selectors';-import FolderTag from './FolderTag';import MemberCountTag from './MemberCountTag';import ThreadSwitcher from './ThreadSwitcher';const TitleTags = memo(() => {const { t } = useTranslation(['topic', 'chat']);- const activeThreadId = useChatStore((s) => s.activeThreadId);+ const { threadId, topicId } = useAgentContext();const threadTitle = useChatStore((s) =>- s.activeThreadId && s.activeTopicId- ? s.threadMaps[s.activeTopicId]?.find((thread) => thread.id === s.activeThreadId)?.title+ threadId && topicId+ ? s.threadMaps[topicId]?.find((thread) => thread.id === threadId)?.title: undefined,);- const topicTitle = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.title);+ const topicTitle = useChatStore((s) =>+ topicId ? topicSelectors.getTopicById(topicId)(s)?.title : undefined,+ );const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);if (isGroupSession) {@@ -36,7 +38,7 @@ const TitleTags = memo(() => {return (<Flexbox allowShrink horizontal align={'center'} gap={6} style={{ marginLeft: 8, minWidth: 0 }}>- {activeThreadId ? (+ {threadId ? (<><spanstyle={{@@ -64,22 +66,19 @@ const TitleTags = memo(() => {<ThreadSwitcher title={fallbackThreadTitle} /></>) : (- <>- <span- style={{- color: cssVar.colorText,- fontSize: 14,- fontWeight: 600,- minWidth: 0,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- }}- >- {fallbackTopicTitle}- </span>- <FolderTag />- </>+ <span+ style={{+ color: cssVar.colorText,+ fontSize: 14,+ fontWeight: 600,+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {fallbackTopicTitle}+ </span>)}</Flexbox>);diff --git a/src/routes/(main)/agent/features/Conversation/Header/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/index.tsxindex 1ccba8eb7ec..16344fbc2c5 100644--- a/src/routes/(main)/agent/features/Conversation/Header/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/index.tsx@@ -1,17 +1,18 @@'use client';-import { Flexbox } from '@lobehub/ui';+import { Avatar, Flexbox } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';import { memo } from 'react';import { AgentMigrationBadge, useAgentTransferJob } from '@/features/AgentTransferMigration';+import { useAgentContext } from '@/features/Conversation/useAgentContext';import NavHeader from '@/features/NavHeader';import OpenInAppButton from '@/features/OpenInAppButton';import TopicCommentButton from '@/features/TopicComment/TopicCommentButton';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';import { useAgentStore } from '@/store/agent';-import { chatConfigByIdSelectors } from '@/store/agent/selectors';-import { useChatStore } from '@/store/chat';+import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import { useElectronStore } from '@/store/electron';import HeaderActions from './HeaderActions';import ShareButton from './ShareButton';@@ -125,12 +126,17 @@ const headerStyles = createStaticStyles(({ css }) => ({}));const Header = memo(() => {- const agentId = useChatStore((s) => s.activeAgentId);+ const { agentId, topicId } = useAgentContext();// No home/desktop fallback: the IDE button should only show up once the user// explicitly picked a working directory (topic / agent / device default).const workingDirectory = useEffectiveWorkingDirectory(agentId || undefined, {homeFallback: false,+ topicId,});+ const splitView = useElectronStore((s) => s.splitView);+ const agentMeta = useAgentStore((s) =>+ agentId ? agentSelectors.getAgentMetaById(agentId)(s) : undefined,+ );const isLocalSystemEnabled = useAgentStore((s) =>agentId ? chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(s) : false,);@@ -150,6 +156,17 @@ const Header = memo(() => {className={headerStyles.leftContent}gap={4}>+ {splitView && agentMeta && (+ <Avatar+ alt={agentMeta.title}+ avatar={agentMeta.avatar}+ background={agentMeta.backgroundColor}+ shape={'square'}+ size={24}+ style={{ flex: 'none', marginInlineStart: 8 }}+ title={agentMeta.title}+ />+ )}<Tags /><HeaderActions /></Flexbox>diff --git a/src/routes/(main)/agent/features/Conversation/index.tsx b/src/routes/(main)/agent/features/Conversation/index.tsxindex 5514bf5cdd8..79127f5036d 100644--- a/src/routes/(main)/agent/features/Conversation/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/index.tsx@@ -5,13 +5,14 @@ import React, { memo, Suspense, useCallback } from 'react';import DragUploadZone, { type DroppedLocalPath, useUploadFiles } from '@/components/DragUploadZone';import Loading from '@/components/Loading/BrandTextLoading';import { insertLocalPathTags } from '@/features/ChatInput/InputEditor/insertLocalFileTags';+import { useAgentContext } from '@/features/Conversation/useAgentContext';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';import { useAgentStore } from '@/store/agent';import {- agentChatConfigSelectors,- agentSelectors,+ agentByIdSelectors,builtinAgentSelectors,+ chatConfigByIdSelectors,} from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -25,11 +26,13 @@ const wrapperStyle: React.CSSProperties = {};const ChatConversation = memo(() => {- const agentId = useAgentStore((s) => s.activeAgentId || '');- const model = useAgentStore(agentSelectors.currentAgentModel);- const provider = useAgentStore(agentSelectors.currentAgentModelProvider);- const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);- const isLocalSystemEnabled = useAgentStore(agentChatConfigSelectors.isLocalSystemEnabled);+ const { agentId, topicId } = useAgentContext();+ const model = useAgentStore(agentByIdSelectors.getAgentModelById(agentId));+ const provider = useAgentStore(agentByIdSelectors.getAgentModelProviderById(agentId));+ const isHeterogeneous = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));+ const isLocalSystemEnabled = useAgentStore(+ chatConfigByIdSelectors.isLocalSystemEnabledById(agentId),+ );// Drag-drop upload bypasses the (view-only-disabled) input editor, so the// drop zone itself follows the same per-resource General-access rules as the@@ -43,7 +46,7 @@ const ChatConversation = memo(() => {const { canUseResource } = useResourceAccess('agent', gatedResourceId);const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });- const workingDirectory = useEffectiveWorkingDirectory(agentId);+ const workingDirectory = useEffectiveWorkingDirectory(agentId, { topicId });const enableLocalPathReference =isDesktop && !!workingDirectory && (isHeterogeneous || isLocalSystemEnabled);diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.tsindex 80dc568d4e2..610874cb85d 100644--- a/src/store/chat/slices/topic/selectors.test.ts+++ b/src/store/chat/slices/topic/selectors.test.ts@@ -213,6 +213,25 @@ describe('topicSelectors', () => {const topic = topicSelectors.getTopicById('topic1')(state);expect(topic).toEqual(topicItems[0]);});++ it('should find a topic loaded under another agent for split desktop panes', () => {+ const backgroundTopic = { id: 'background-topic', name: 'Background topic' };+ const state = merge(initialStore, {+ activeAgentId: 'focused-agent',+ topicDataMap: {+ ...createTopicDataMap('focused-agent'),+ [topicMapKey({ agentId: 'background-agent' })]: {+ currentPage: 0,+ hasMore: false,+ items: [backgroundTopic],+ pageSize: 20,+ total: 1,+ },+ },+ });++ expect(topicSelectors.getTopicById('background-topic')(state)).toEqual(backgroundTopic);+ });});describe('getTopicWorkingDirectory', () => {@@ -245,7 +264,10 @@ describe('topicSelectors', () => {it('falls back to the active topic when no id is given', () => {expect(topicSelectors.getTopicWorkingDirectory()(wdState)).toBe('/project-a');- expect(topicSelectors.getTopicWorkingDirectory(null)(wdState)).toBe('/project-a');+ });++ it('treats an explicit null as a new-topic route without a directory', () => {+ expect(topicSelectors.getTopicWorkingDirectory(null)(wdState)).toBeUndefined();});it('returns undefined for an unknown topic id', () => {diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex 49930369854..49828e382f8 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -56,8 +56,19 @@ const currentTopicCount = (s: ChatStoreState): number => currentTopicData(s)?.toconst getTopicById =(id: string) =>- (s: ChatStoreState): ChatTopic | undefined =>- currentTopics(s)?.find((topic) => topic.id === id); // Don't filter here, need to access all topics by ID+ (s: ChatStoreState): ChatTopic | undefined => {+ const currentTopic = currentTopics(s)?.find((topic) => topic.id === id);+ if (currentTopic) return currentTopic;++ // Multiple desktop tab routers can render topics from different agents at+ // the same time. The global activeAgentId only describes the focused tab,+ // so fall back to the other already-loaded agent buckets for background+ // panes. Topic ids are globally unique.+ for (const topicData of Object.values(s.topicDataMap)) {+ const topic = topicData.items.find((item) => item.id === id);+ if (topic) return topic;+ }+ };/*** Get topics by specific agentId (for AgentBuilder scenarios where agentId differs from activeAgentId)@@ -133,8 +144,9 @@ const extractTopicWorkingDirectory = (topic: ChatTopic | undefined): string | un};/**- * Get a topic's working directory by id, falling back to the active topic when- * no id is given. Prefer the explicit-id form for async work (e.g. a streaming+ * Get a topic's working directory by id, falling back to the active topic only+ * when the argument is omitted. An explicit null represents a new-topic route+ * and therefore has no topic-level directory. Prefer the explicit-id form for async work (e.g. a streaming* tool call): the executing topic is captured at request time, so reading the* *active* topic here would return the wrong project if the user switched topics* mid-stream.@@ -142,7 +154,9 @@ const extractTopicWorkingDirectory = (topic: ChatTopic | undefined): string | unconst getTopicWorkingDirectory =(id?: string | null) =>(s: ChatStoreState): string | undefined =>- extractTopicWorkingDirectory(id ? getTopicById(id)(s) : currentActiveTopic(s));+ id === null+ ? undefined+ : extractTopicWorkingDirectory(id ? getTopicById(id)(s) : currentActiveTopic(s));/*** Get current active topic's working directory.diff --git a/src/store/electron/actions/__tests__/tabPages.test.ts b/src/store/electron/actions/__tests__/tabPages.test.tsindex 0ff34976503..9e41bf98c7e 100644--- a/src/store/electron/actions/__tests__/tabPages.test.ts+++ b/src/store/electron/actions/__tests__/tabPages.test.ts@@ -176,6 +176,78 @@ describe('tabPages actions', () => {});});+ describe('split view', () => {+ const seed = () => {+ const { result } = renderHook(() => useElectronStore());+ const tabs = [buildTab('/left'), buildTab('/right'), buildTab('/third')];++ act(() => {+ useElectronStore.setState({ activeTabId: '/left', splitView: null, tabs });+ });+ return result;+ };++ it('opens another tab in the secondary pane and focuses it', () => {+ const result = seed();++ act(() => {+ result.current.openTabInSplitView('/right');+ });++ expect(result.current.activeTabId).toBe('/right');+ expect(result.current.splitView).toEqual({+ primaryTabId: '/left',+ ratio: 0.5,+ secondaryTabId: '/right',+ });+ });++ it('duplicates the active tab so each pane owns an independent router', () => {+ const result = seed();+ let secondaryTabId: string | null = null;++ act(() => {+ secondaryTabId = result.current.openTabInSplitView('/left');+ });++ expect(secondaryTabId).not.toBe('/left');+ expect(result.current.tabs).toHaveLength(4);+ expect(result.current.tabs.at(-1)?.url).toBe('/left');+ expect(result.current.splitView?.secondaryTabId).toBe(secondaryTabId);+ });++ it('replaces the focused pane when a third tab is activated', () => {+ const result = seed();+ act(() => result.current.openTabInSplitView('/right'));+ act(() => result.current.focusTabPane('/left'));+ act(() => result.current.activateTab('/third'));++ expect(result.current.splitView).toMatchObject({+ primaryTabId: '/third',+ secondaryTabId: '/right',+ });+ expect(result.current.activeTabId).toBe('/third');+ });++ it('collapses to the remaining pane when one visible tab closes', () => {+ const result = seed();+ act(() => result.current.openTabInSplitView('/right'));+ act(() => result.current.removeTab('/right'));++ expect(result.current.splitView).toBeNull();+ expect(result.current.activeTabId).toBe('/left');+ });++ it('clamps the divider ratio to usable pane widths', () => {+ const result = seed();+ act(() => result.current.openTabInSplitView('/right'));+ act(() => result.current.setSplitRatio(0.9));+ expect(result.current.splitView?.ratio).toBe(0.75);+ act(() => result.current.setSplitRatio(0.1));+ expect(result.current.splitView?.ratio).toBe(0.25);+ });+ });+describe('updateTab', () => {it('drops cached data when the tab navigates to a different page but keeps the id stable', () => {const { result } = renderHook(() => useElectronStore());diff --git a/src/store/electron/actions/tabPages.ts b/src/store/electron/actions/tabPages.tsindex d1121cd0046..31dfc4d2ed0 100644--- a/src/store/electron/actions/tabPages.ts+++ b/src/store/electron/actions/tabPages.ts@@ -24,14 +24,22 @@ const generateTabId = (): string => `tab_${nanoid(8)}`;export interface TabPagesState {activeTabId: string | null;activeTabScope: TabScope;+ splitView: SplitViewState | null;tabs: TabItem[];}+export interface SplitViewState {+ primaryTabId: string;+ ratio: number;+ secondaryTabId: string;+}+// ======== Initial State ======== //export const tabPagesInitialState: TabPagesState = {activeTabScope: PERSONAL_TAB_SCOPE,activeTabId: null,+ splitView: null,tabs: [],};@@ -52,10 +60,18 @@ export class TabPagesActionImpl {}activateTab = (id: string): void => {- const { tabs } = this.#get();+ const { activeTabId, splitView, tabs } = this.#get();if (!tabs.some((t) => t.id === id)) return;- this.#set({ activeTabId: id, tabs: this.#touch(tabs, id) }, false, 'activateTab');+ this.#set(+ {+ activeTabId: id,+ splitView: this.#replaceFocusedPane(splitView, activeTabId, id),+ tabs: this.#touch(tabs, id),+ },+ false,+ 'activateTab',+ );this.#persist();};@@ -66,12 +82,7 @@ export class TabPagesActionImpl {if (existing) {if (activate) {- this.#set(- { activeTabId: existing.id, tabs: this.#touch(tabs, existing.id) },- false,- 'activateExistingTab',- );- this.#persist();+ this.activateTab(existing.id);}return existing.id;}@@ -90,6 +101,72 @@ export class TabPagesActionImpl {return tabs.find((t) => t.id === activeTabId) ?? null;};+ closeSplitView = (): void => {+ if (!this.#get().splitView) return;+ this.#set({ splitView: null }, false, 'closeSplitView');+ };++ focusTabPane = (id: string): void => {+ const { splitView, tabs } = this.#get();+ if (!splitView) return;+ if (id !== splitView.primaryTabId && id !== splitView.secondaryTabId) return;++ this.#set({ activeTabId: id, tabs: this.#touch(tabs, id) }, false, 'focusTabPane');+ this.#persist();+ };++ openTabInSplitView = (id: string): string | null => {+ const { activeTabId, splitView, tabs } = this.#get();+ const target = tabs.find((tab) => tab.id === id);+ if (!target || !activeTabId) return null;++ const primaryTabId = splitView?.primaryTabId ?? activeTabId;+ if (splitView?.secondaryTabId === id) {+ this.focusTabPane(id);+ return id;+ }++ const now = Date.now();+ const shouldDuplicate = id === primaryTabId;+ const secondaryTabId = shouldDuplicate ? generateTabId() : id;+ const nextTabs = shouldDuplicate+ ? [+ ...tabs,+ {+ ...target,+ id: secondaryTabId,+ lastVisited: now,+ pinned: false,+ },+ ]+ : this.#touch(tabs, id);++ this.#set(+ {+ activeTabId: secondaryTabId,+ splitView: {+ primaryTabId,+ ratio: splitView?.ratio ?? 0.5,+ secondaryTabId,+ },+ tabs: nextTabs,+ },+ false,+ 'openTabInSplitView',+ );+ this.#persist();+ return secondaryTabId;+ };++ setSplitRatio = (ratio: number): void => {+ const { splitView } = this.#get();+ if (!splitView) return;++ const nextRatio = Math.min(0.75, Math.max(0.25, ratio));+ if (nextRatio === splitView.ratio) return;+ this.#set({ splitView: { ...splitView, ratio: nextRatio } }, false, 'setSplitRatio');+ };+loadTabs = (url = '/'): void => {this.#loadScope(resolveTabScope(url), true);};@@ -112,8 +189,15 @@ export class TabPagesActionImpl {}}+ const reconciled = this.#reconcileSplitView(newTabs, newActiveId);+ newActiveId = reconciled.activeTabId;+this.#set(- { activeTabId: newActiveId, tabs: this.#touch(newTabs, newActiveId) },+ {+ activeTabId: newActiveId,+ splitView: reconciled.splitView,+ tabs: this.#touch(newTabs, newActiveId),+ },false,'removeTab',);@@ -252,9 +336,17 @@ export class TabPagesActionImpl {const newTabs = tabs.filter((tab, index) => tab.pinned || keep(tab, index));if (newTabs.length === tabs.length) return;- const newActiveId = newTabs.some((t) => t.id === activeTabId) ? activeTabId : targetId;+ const preferredActiveId = newTabs.some((t) => t.id === activeTabId) ? activeTabId : targetId;+ const { activeTabId: newActiveId, splitView } = this.#reconcileSplitView(+ newTabs,+ preferredActiveId,+ );- this.#set({ activeTabId: newActiveId, tabs: this.#touch(newTabs, newActiveId) }, false, action);+ this.#set(+ { activeTabId: newActiveId, splitView, tabs: this.#touch(newTabs, newActiveId) },+ false,+ action,+ );this.#persist();};@@ -293,8 +385,43 @@ export class TabPagesActionImpl {return newTabs;};+ #replaceFocusedPane = (+ splitView: SplitViewState | null,+ activeTabId: string | null,+ nextTabId: string,+ ): SplitViewState | null => {+ if (!splitView) return null;+ if (nextTabId === splitView.primaryTabId || nextTabId === splitView.secondaryTabId) {+ return splitView;+ }++ return activeTabId === splitView.secondaryTabId+ ? { ...splitView, secondaryTabId: nextTabId }+ : { ...splitView, primaryTabId: nextTabId };+ };++ #reconcileSplitView = (+ tabs: TabItem[],+ preferredActiveId: string | null,+ ): Pick<TabPagesState, 'activeTabId' | 'splitView'> => {+ const { splitView } = this.#get();+ if (!splitView) return { activeTabId: preferredActiveId, splitView: null };++ const tabIds = new Set(tabs.map((tab) => tab.id));+ const hasPrimary = tabIds.has(splitView.primaryTabId);+ const hasSecondary = tabIds.has(splitView.secondaryTabId);+ if (hasPrimary && hasSecondary) return { activeTabId: preferredActiveId, splitView };++ const remainingPaneId = hasPrimary+ ? splitView.primaryTabId+ : hasSecondary+ ? splitView.secondaryTabId+ : null;+ return { activeTabId: remainingPaneId ?? preferredActiveId, splitView: null };+ };+#createTab = (url: string, cached: DynamicRouteMeta | undefined, activate: boolean): string => {- const { tabs, activeTabId } = this.#get();+ const { tabs, activeTabId, splitView } = this.#get();const id = generateTabId();const newTab: TabItem = {cached,@@ -304,7 +431,11 @@ export class TabPagesActionImpl {};this.#set(- { activeTabId: activate ? id : activeTabId, tabs: [...tabs, newTab] },+ {+ activeTabId: activate ? id : activeTabId,+ splitView: activate ? this.#replaceFocusedPane(splitView, activeTabId, id) : splitView,+ tabs: [...tabs, newTab],+ },false,'addTab',);@@ -341,7 +472,7 @@ export class TabPagesActionImpl {if (!force && tabScopeKey(activeTabScope) === tabScopeKey(scope)) return;const { tabs, activeTabId } = getTabPages(scope);- this.#set({ activeTabId, activeTabScope: scope, tabs }, false, 'loadTabs');+ this.#set({ activeTabId, activeTabScope: scope, splitView: null, tabs }, false, 'loadTabs');};}diff --git a/src/store/user/slices/preference/selectors.test.ts b/src/store/user/slices/preference/selectors.test.tsindex 03a03051373..56d053adfb4 100644--- a/src/store/user/slices/preference/selectors.test.ts+++ b/src/store/user/slices/preference/selectors.test.ts@@ -82,6 +82,18 @@ describe('preferenceSelectors', () => {});describe('labPreferSelectors', () => {+ it('keeps desktop split view disabled by default', () => {+ store.preference.lab = undefined;++ expect(labPreferSelectors.enableDesktopSplitView(store)).toBe(false);+ });++ it('returns the configured desktop split view preference', () => {+ store.preference.lab = { enableDesktopSplitView: true };++ expect(labPreferSelectors.enableDesktopSplitView(store)).toBe(true);+ });+it('returns false for message text selection actions by default', () => {store.preference.lab = undefined;diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex 806af5ebc15..5517c3733fa 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -13,6 +13,8 @@ export const labPreferSelectors = {s.preference.lab?.enableArtifactDeployment ?? false,enableClaudeCodeSdk: (s: UserState): boolean => s.preference.lab?.enableClaudeCodeSdk ?? false,enableCodexAppServer: (s: UserState): boolean => s.preference.lab?.enableCodexAppServer ?? false,+ enableDesktopSplitView: (s: UserState): boolean =>+ s.preference.lab?.enableDesktopSplitView ?? false,enableHeteroSessionImport: (s: UserState): boolean =>s.preference.lab?.enableHeteroSessionImport ?? false,enableImessage: (s: UserState): boolean => s.preference.lab?.enableImessage ?? false,