Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

页签组:右侧栏页签可移到聊天区左 / 上 / 下边

Dash08078dca33ae
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 6f3aef29d1..6aeae4367b 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -135,7 +135,6 @@ import {
isUserInstallReservedGhostId,
isValidGhostId,
isValidNewGhostId,
- layoutWithGhostPanel,
type GhostHostNoticeKey,
type GhostManifest,
type GhostCindyPreferenceResult,
@@ -163,7 +162,6 @@ import {
type ActiveAppSession,
type AppSessionMode,
} from '../appSessionState.js';
-import { getLayoutStore } from '../layout/index.js';
import { relocateGhostUserDataResources } from './ghostUserDataRelocation.js';
import {
GhostManager,
@@ -1772,21 +1770,7 @@ async function reconcileBuiltinGhostsLocked(
// 完成时,靠 ghosts:changed 热更新兜底,多窗口同一套通道)。
// 对账跑完 = 一次完整扫描,清单权威(见 broadcastGhostsChanged 的说明)。
broadcastGhostsChanged(manager.list(), true);
- // 首装的意识停进布局树(与 installAndDock 同一套停靠逻辑;覆盖更新 id 未变,
- // 布局位置天然保留,不动树;回收不动树 —— 与 uninstall 口径一致,位置记录
- // 由布局引擎保留)。
- const store = getLayoutStore();
for (const manifest of outcome.installed) {
- const docked = layoutWithGhostPanel(store.getLayout(), manifest);
- if (docked) {
- const applied = store.setLayout(docked);
- if ('rejection' in applied) {
- log.warn('builtin ghost panel dock rejected', {
- id: manifest.id,
- reason: applied.rejection,
- });
- }
- }
// 登录触发的对账装上常驻意识时,这里就是它的点火时机(启动那趟扫描早过了)。
const ghost = manager.list().find((g) => g.manifest.id === manifest.id);
if (ghost) spawnIfResident(ghost);
@@ -6878,21 +6862,6 @@ async function installAndDockLocked(
// 内置墓碑清除已并入 GhostManager 的 durable install journal(marker.clearBuiltinTombstone
// + 提交时清除 + 崩溃恢复补清),此处不再直接调用:瞬时状态写失败会保留 marker 交由
// 启动恢复,而不是把已提交的安装误报成错误。
- // 声明了面板的意识装入后立即停进布局树(树上已有 = 重装,原位复活不动树)。
- // 顺序刻意:manager.install 内已广播 ghosts:changed(renderer 先注册面板),
- // 这里再 setLayout 触发 layout:changed(pane 出现时面板组件必然已就位,规则 7)。
- const store = getLayoutStore();
- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest, installedGhostStoragePart(result.ghost));
- if (docked) {
- const applied = store.setLayout(docked);
- if ('rejection' in applied) {
- // 停靠失败不阻断装入(意识本体已就绪);记日志供排查。
- log.warn('ghost panel dock rejected', {
- id: result.ghost.manifest.id,
- reason: applied.rejection,
- });
- }
- }
// 常驻意识(launch: resident)且装入即开启:立刻拉起电子脑。
spawnIfResident(result.ghost);
if (!opts.deferUsageBinding) await bindPluginUsage(result.ghost);
@@ -7086,17 +7055,6 @@ async function updateLocalGhostPackageLocked(
runtime.resetFuse(instanceId);
await bindPluginUsage(result.ghost,
!detachMarketRecord && previousGhost?.approval.state === 'approved' ? previousGhost.approval.revision : undefined);
- const store = getLayoutStore();
- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest, installedGhostStoragePart(result.ghost));
- if (docked) {
- const applied = store.setLayout(docked);
- if ('rejection' in applied) {
- log.warn('ghost panel dock rejected', {
- id: result.ghost.manifest.id,
- reason: applied.rejection,
- });
- }
- }
spawnIfResident(result.ghost);
return result.ghost;
}
@@ -7546,17 +7504,6 @@ async function installOrUpdateMarketGhostPackageLocked(
throwInstallError(result.rejection);
}
runtime.resetFuse(installedGhostStoragePart(result.ghost));
- const store = getLayoutStore();
- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest, installedGhostStoragePart(result.ghost));
- if (docked) {
- const applied = store.setLayout(docked);
- if ('rejection' in applied) {
- log.warn('market ghost panel dock rejected', {
- id: result.ghost.manifest.id,
- reason: applied.rejection,
- });
- }
- }
spawnIfResident(result.ghost);
await expected.afterCommitInLock?.(result.ghost, commitEvidence);
await bindPluginUsage(result.ghost);
diff --git a/apps/desktop/src/main/layout/LayoutStore.ts b/apps/desktop/src/main/layout/LayoutStore.ts
index deb36099dc..ec15811b16 100644
--- a/apps/desktop/src/main/layout/LayoutStore.ts
+++ b/apps/desktop/src/main/layout/LayoutStore.ts
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import {
coerceLayout,
- createDefaultLayoutPreservingGhostPanels,
+ createDefaultLayout,
validateLayout,
type Layout,
} from '../../shared/layoutTree.js';
@@ -99,9 +99,12 @@ export class LayoutStore {
return { layout: cloned, persisted };
}
- /** 重置为默认布局(等价 WoW /resetui):写盘 + 广播。 */
+ /**
+ * 重置为默认布局(等价 WoW /resetui):写盘 + 广播。页签组的 pane 不保留:
+ * 组里仍有页签时由 renderer 按需重新插入(ensureTabGroupPane),位置回到默认。
+ */
reset(): LayoutMutationResult {
- const layout = createDefaultLayoutPreservingGhostPanels(this.getLayout());
+ const layout = createDefaultLayout();
this.cached = layout;
const persisted = this.persist(layout);
this.options.onChanged?.(layout);
diff --git a/apps/desktop/src/main/layout/__tests__/LayoutStore.test.ts b/apps/desktop/src/main/layout/__tests__/LayoutStore.test.ts
index dfbbf06bca..0955d9eebb 100644
--- a/apps/desktop/src/main/layout/__tests__/LayoutStore.test.ts
+++ b/apps/desktop/src/main/layout/__tests__/LayoutStore.test.ts
@@ -8,7 +8,6 @@ import {
insertRootSplitPane,
validateLayout,
type Layout,
- type SplitNode,
} from '../../../shared/layoutTree';
import { LAYOUT_FILE_NAME, LayoutStore } from '../LayoutStore';
@@ -153,30 +152,20 @@ describe('LayoutStore · reset 与 ensurePersisted', () => {
expect(onChanged).toHaveBeenCalledTimes(2);
});
- it('reset 恢复内置默认排列但保留已停靠的意识面板', () => {
+ it('reset 不保留树里的额外 pane(页签组由 renderer 按需重新插入)', () => {
const store = makeStore();
- const withGhost = insertRootSplitPane(
+ const withExtra = insertRootSplitPane(
createDefaultLayout(),
- { id: 'custom-ghost', panelKind: 'ghost:calendar', minWidth: 260 },
- { index: 2, fraction: 0.3 },
+ { id: 'tab-group-left', panelKind: 'tab-group:left' },
+ { index: 0, fraction: 0.3 },
);
- expect(withGhost.applied).toBe(true);
- store.setLayout(withGhost.layout);
+ expect(withExtra.applied).toBe(true);
+ store.setLayout(withExtra.layout);
const result = store.reset();
expect(result.persisted).toBe(true);
- const children = (result.layout.content as SplitNode).children;
- expect(children.map((child) => child.node.type === 'pane' && child.node.panelKind)).toEqual([
- 'ghost:calendar',
- 'chat-main',
- 'right-tabs',
- ]);
- expect(children[0].node).toMatchObject({
- id: 'ghost-calendar',
- panelKind: 'ghost:calendar',
- minWidth: 260,
- });
- expect(readFileJson()).toEqual(result.layout);
+ expect(result.layout).toEqual(createDefaultLayout());
+ expect(readFileJson()).toEqual(createDefaultLayout());
});
it('ensurePersisted:缺失时落默认存档;已有合法存档不覆盖', () => {
diff --git a/apps/desktop/src/preload/__tests__/appearanceSnapshot.test.ts b/apps/desktop/src/preload/__tests__/appearanceSnapshot.test.ts
index 6906379b70..45e3988b14 100644
--- a/apps/desktop/src/preload/__tests__/appearanceSnapshot.test.ts
+++ b/apps/desktop/src/preload/__tests__/appearanceSnapshot.test.ts
@@ -32,7 +32,7 @@ function emit(settings: AppearanceSettings) {
}
afterEach(() => vi.unstubAllGlobals());
-describe.each(['sidebar', 'resource', 'ghost-panel'])('%s appearance startup', (kind) => {
+describe.each(['sidebar', 'resource'])('%s appearance startup', (kind) => {
let bridge: {
getSync(): AppearanceSettings | null;
onChanged(callback: (settings: AppearanceSettings) => void): () => void;
@@ -50,10 +50,9 @@ describe.each(['sidebar', 'resource', 'ghost-panel'])('%s appearance startup', (
mocks.sendSync.mockImplementation((channel) =>
channel === 'appearance-settings:get-sync' ? DEFAULT_APPEARANCE_SETTINGS : null,
);
- vi.stubGlobal('window', { location: { search: '?ghostPanelWindow=fixture' } });
+ vi.stubGlobal('window', { location: { search: '?sidebarWindow=1' } });
if (kind === 'sidebar') await import('../sidebarWindowPreload');
- else if (kind === 'resource') await import('../resourceUsagePreload');
- else await import('../ghostPanelWindowPreload');
+ else await import('../resourceUsagePreload');
bridge = mocks.expose.mock.calls.at(-1)![1].appearanceSettings;
});
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 9e557ec3cb..f1faf29b8a 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -59,6 +59,8 @@ import {
} from '@/features/right-sidebar/store';
import { browserWebviewPool } from '@/features/right-sidebar/lib/browserWebviewPool';
import { findGlobalTab, setActiveGlobalTabId } from '@/features/right-sidebar/globalTabs';
+import { TabGroupHostProvider, type TabGroupHostValue } from '@/features/right-sidebar/tabGroupHost';
+import { useTabGroupPanes } from '@/features/right-sidebar/tabGroupPanes';
import {
markAllPtyDetached,
markPtyDetached,
@@ -973,6 +975,14 @@ export function MainLayout() {
const handleMaximizeRightSidebar = useCallback(() => {
setIsRightSidebarMaximized((v) => !v);
}, []);
+ // 左 / 上 / 下边页签组:按「组里有没有可见页签」注册 / 注销 pane,并保证树里有它。
+ useTabGroupPanes({
+ sessionId: rightSidebarSessionId,
+ enabled: rightSidebarAvailable && rsbWindow.loaded && !rsbDetached && !isSettingsRoute,
+ remoteHostId: rightSidebarWorkdirInfo.remoteHostId,
+ deviceLinkDeviceId: rightSidebarWorkdirInfo.deviceLinkDeviceId,
+ subagentsAvailable: rightSidebarSubagentsAvailable,
+ });
useEffect(() => {
if (!isRightSidebarMaximized) return;
const handler = (e: KeyboardEvent) => {
@@ -1122,6 +1132,30 @@ export function MainLayout() {
});
}, []);
+ // 边页签组(左 / 上 / 下)的宿主上下文:与右侧栏拿到的会话上下文同一份。
+ const tabGroupHost = useMemo<TabGroupHostValue>(
+ () => ({
+ sessionId: rightSidebarSessionId,
+ workdir: rightSidebarWorkdirInfo.workdir,
+ remoteHostId: rightSidebarWorkdirInfo.remoteHostId,
+ deviceLinkDeviceId: rightSidebarWorkdirInfo.deviceLinkDeviceId,
+ subagentsAvailable: rightSidebarSubagentsAvailable,
+ isMac,
+ onDetachTab: isSecondaryWindow() ? undefined : handleDetachRightSidebarTab,
+ // 左栏完全收起或 rail 态时,窗口左上的红绿灯 / ChromeActions 会压到最左面板顶栏。
+ reserveLeftChromeActions: isSidebarCollapsed || hasRailChromeActions,
+ }),
+ [
+ handleDetachRightSidebarTab,
+ hasRailChromeActions,
+ isMac,
+ isSidebarCollapsed,
+ rightSidebarSessionId,
+ rightSidebarSubagentsAvailable,
+ rightSidebarWorkdirInfo,
+ ],
+ );
+
// 5) 页签从弹出窗口回到侧边栏(合并 / 关窗 / 崩溃):刷新它的数据副本并选中。
// 可持久化会话按 SQLite 强制刷新该页签(弹出期间的改动都在 DB);不可持久化
// 会话用交回的内存态覆盖。终端同样要重新 attach PTY。侧边栏若因「最后一个页签
@@ -1735,7 +1769,9 @@ export function MainLayout() {
>
{/* 面板稳态宽度由 LayoutRoot 输出 CSS 百分比/clamp,BrowserWindow live resize
不再逐像素回灌 React;设置页接管时非 chat 面板统一歇业。 */}
- <LayoutRoot suppressNonChatPanels={isSettingsRoute} />
+ <TabGroupHostProvider value={tabGroupHost}>
+ <LayoutRoot suppressNonChatPanels={isSettingsRoute} />
+ </TabGroupHostProvider>
</BuiltinPanelBridgeProvider>
{/* 拖面板换位(B3 转正;M3 起 mac 同步开闸——mac 顶栏全部保留窗口拖拽,
手势天然只剩长按窗体)。总开关只管全局语境(内容区路由在场、非
diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
index d5b7226a16..972befb89b 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
@@ -42,6 +42,7 @@ import { canonicalBotSessionId, useBotProfiles } from '@/features/bots/botStore'
import { findBotProfileForSession } from '@/features/bots/botSessionOwners';
import { sessionsStore } from '@/lib/sessionsStore';
import { openBotWorkbenchTab } from './lib/openBotWorkbenchTab';
+import type { TabGroupId } from './tabGroups';
import type { TabKindId, TabKindMenuMeta } from './types';
const BOT_SECONDARY_KINDS = new Set<TabKindId>([
@@ -58,6 +59,8 @@ interface AddTabDropdownProps {
anchorRef: React.RefObject<HTMLElement | null>;
/** 当前会话。伙伴任务用来把工程面板从默认菜单里收掉。 */
sessionId?: string | null;
+ /** 本菜单所属的页签组:插件分组里新加的全局页签直接落在这一组。缺省右侧组。 */
+ groupId?: TabGroupId;
/** 锚点消失 / 面板收起时关闭(点外部与 Esc 由 DropdownMenu 根处理)。 */
onClose: () => void;
/** 选 kind。调用方负责真创建 tab + 关闭 dropdown。单例 kind 已存在时
@@ -135,6 +138,7 @@ export function AddTabDropdown({
open,
anchorRef,
sessionId,
+ groupId,
onClose,
onSelect,
existingKinds,
@@ -252,7 +256,7 @@ export function AddTabDropdown({
label={entry.title}
trailing={entry.open ? t('rightSidebar.tabs.menu.alreadyOpen') : undefined}
onSelect={() => {
- const tab = addGlobalPluginTab(entry.instanceId);
+ const tab = addGlobalPluginTab(entry.instanceId, { groupId });
if (tab) setActiveGlobalTabId(tab.id);
onClose();
}}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
index 097e0bc8f8..3cae1d56f0 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
@@ -74,11 +74,24 @@ import {
useGlobalTabs,
} from './globalTabs';
import {
+ buildTabAvailabilities,
mergeAvailableTabOrder,
projectAvailableTabs,
} from './tabAvailability';
+import {
+ DEFAULT_TAB_GROUP,
+ getGroupActiveTabId,
+ setGroupActiveTabId,
+ setTabGroup,
+ tabGroupOf,
+ subscribeTabGroups,
+ useTabGroupAssignments,
+ type TabGroupId,
+} from './tabGroups';
const log = createLogger('rightSidebar.shell');
+/** 组内激活记忆的订阅(与组归属同一个通知源)。 */
+const subscribeGroupActive = (cb: () => void) => subscribeTabGroups(cb);
const EMPTY_TAB_ID_SET = new Set<string>();
/**
* Mac 合并顶栏右端 spacer 宽度,对应 MainLayout 固定唤起按钮:28px 按钮 + 8px 右距。
@@ -88,6 +101,11 @@ const MAC_HEADER_ACTION_SPACER_PX = 36;
type RightTabDirection = 'prev' | 'next';
interface RightSidebarShellProps {
+ /**
+ * 本 Shell 承载哪个页签组(见 tabGroups.ts):只投影归属该组的页签。缺省右侧组
+ * (历史右侧栏);左 / 上 / 下边组由 TabGroupPanel 传入。弹出窗口(soloTabId)不分组。
+ */
+ groupId?: TabGroupId;
/**
* 当前 cc-agent session id;由 MainLayout 透传(CCAgentSessionView ownsRoute 时声明)。
* null = 尚无激活会话(或不在 cc-agent 路由),store 不工作,Shell 渲染空状态。
@@ -157,6 +175,7 @@ interface RightSidebarShellProps {
}
export function RightSidebarShell({
+ groupId = DEFAULT_TAB_GROUP,
sessionId,
workdir,
remoteHostId,
@@ -178,6 +197,8 @@ export function RightSidebarShell({
railChromeActionsHitHole = false,
}: RightSidebarShellProps) {
const soloMode = typeof soloTabId === 'string';
+ /** 右侧组是页签系统的"主组":任务级的激活位对账、快捷键、浏览器桥的活跃会话上报只由它做。 */
+ const isPrimaryGroup = groupId === DEFAULT_TAB_GROUP;
const { isFullscreen } = useMacFullscreen();
const chromeActionsLeft =
isMac && !isFullscreen
@@ -230,6 +251,11 @@ export function RightSidebarShell({
// 全局页签(不跟对话):在所有任务里都在场,切任务留在原位;与任务页签一起投影。
const globalTabs = useGlobalTabs();
const activeGlobalTabId = useActiveGlobalTabId();
+ const groupAssignments = useTabGroupAssignments();
+ const groupActiveVersion = useSyncExternalStore(
+ subscribeGroupActive,
+ () => getGroupActiveTabId(groupId, sessionId),
+ );
// 没有任务(sessionId=null)时任务桶不存在,但全局页签照常可展示——弹出窗口里
// 承载全局页签就是这种形态。
const contentReady = bucket.hydrated || sessionId === null;
@@ -251,8 +277,8 @@ export function RightSidebarShell({
// null 也推(切到非 RSB 路由时),让 main 端清掉 active session — 否则
// 之前的 sessionId 会成 stale 引用。隐藏的分离窗口只是预热/待命实例,不能
// 覆盖主窗口当前的浏览器 session。setActiveSession 失败容错(preload 未就绪)。
- // 单页签独立窗口不是侧栏宿主,不上报(主窗仍是「活跃侧栏会话」权威)。
- if (soloMode) {
+ // 单页签独立窗口不是侧栏宿主,不上报(主窗仍是「活跃侧栏会话」权威);边组同理。
+ if (soloMode || !isPrimaryGroup) {
// no-op
} else if (shellVisible) {
void window.electronAPI?.rsbBrowserBridge
@@ -270,7 +296,7 @@ export function RightSidebarShell({
void ensureHydrated(sessionId).catch((err) => {
log.error('ensureHydrated failed', { sessionId, err });
});
- }, [sessionId, shellVisible, soloMode]);
+ }, [isPrimaryGroup, sessionId, shellVisible, soloMode]);
// Subagents eligibility is tri-state: `undefined` while the session row is
// still loading, then true/false once the harness is known. Folding unknown
@@ -279,49 +305,56 @@ export function RightSidebarShell({
// persist a different tab (or null) as active — the user's selection is gone
// by the time eligibility resolves to true. Keep the tab projected while
// unknown and only converge once we actually know.
- const tabAvailability = useMemo(
- () => ({
- installedGhosts: remoteHostId || deviceLinkDeviceId !== null ? [] : installedGhosts,
- subagentsAvailable: subagentsEnabled || !subagentsEligibilityKnown,
- hiddenTabIds,
- }),
- [
- hiddenTabIds,
- installedGhosts,
- remoteHostId,
- deviceLinkDeviceId,
- subagentsEligibilityKnown,
- subagentsEnabled,
- ],
+ // 可用性口径与页签组在场判定(tabGroupPanes)同源:两边必须对"哪些页签可见"
+ // 给出同一答案,否则会出现有组无页签的空壳。
+ const availabilities = useMemo(
+ () =>
+ buildTabAvailabilities({
+ installedGhosts,
+ remoteHostId,
+ deviceLinkDeviceId,
+ subagentsAvailable,
+ hiddenTabIds,
+ }),
+ [deviceLinkDeviceId, hiddenTabIds, installedGhosts, remoteHostId, subagentsAvailable],
);
+ const tabAvailability = availabilities.session;
+ // 整个任务的可见页签投影(所有组):任务级激活位对账用它,不受本组过滤影响。
const projectedTabs = useMemo(
() => projectAvailableTabs(bucket.tabs, bucket.activeTabId, tabAvailability),
[bucket.activeTabId, bucket.tabs, tabAvailability],
);
- // 全局页签的可用性只看本机已装插件(插件视图运行在本机,不随任务归属变化)。
- const globalAvailability = useMemo(
- () => ({
- installedGhosts: [] as typeof installedGhosts,
- subagentsAvailable: true,
- hiddenTabIds,
- pluginViewGhosts: installedGhosts,
- }),
- [hiddenTabIds, installedGhosts],
+ const allPinnedTabs = useMemo(
+ () => projectAvailableTabs(globalTabs, null, availabilities.global).tabs,
+ [availabilities.global, globalTabs],
+ );
+ /** 页签是否归本 Shell 的组:弹出窗口不分组(它只投影被指派的那一个)。 */
+ const inGroup = useCallback(
+ (tabId: string) => soloMode || tabGroupOf(groupAssignments, tabId) === groupId,
+ [groupAssignments, groupId, soloMode],
);
const pinnedTabs = useMemo(
- () => projectAvailableTabs(globalTabs, null, globalAvailability).tabs,
- [globalAvailability, globalTabs],
+ () => allPinnedTabs.filter((tab) => inGroup(tab.id)),
+ [allPinnedTabs, inGroup],
+ );
+ const sessionTabs = useMemo(
+ () => projectedTabs.tabs.filter((tab) => inGroup(tab.id)),
+ [inGroup, projectedTabs.tabs],
);
- const sessionTabs = projectedTabs.tabs;
const sessionActiveTabId = projectedTabs.activeTabId;
- /** 侧栏可见页签 = 全局页签(钉在前) + 当前任务页签。 */
+ /** 本组可见页签 = 归本组的全局页签(钉在前) + 归本组的当前任务页签。 */
const tabs = useMemo(() => [...pinnedTabs, ...sessionTabs], [pinnedTabs, sessionTabs]);
- // 激活位:用户选中的全局页签优先并跨任务保持;否则是任务自己的激活页签;
- // 任务没有页签时落到第一个全局页签。
+ // 激活位:用户选中的全局页签优先并跨任务保持;否则是任务自己的激活页签(在本组时);
+ // 本组不含任务级激活页签时用组内上次选中的;再没有就落到第一个页签。
+ const groupRememberedActiveId = groupActiveVersion;
const activeTabId =
activeGlobalTabId && pinnedTabs.some((tab) => tab.id === activeGlobalTabId)
? activeGlobalTabId
- : sessionActiveTabId ?? pinnedTabs[0]?.id ?? null;
+ : sessionActiveTabId && sessionTabs.some((tab) => tab.id === sessionActiveTabId)
+ ? sessionActiveTabId
+ : groupRememberedActiveId && tabs.some((tab) => tab.id === groupRememberedActiveId)
+ ? groupRememberedActiveId
+ : sessionTabs[0]?.id ?? pinnedTabs[0]?.id ?? null;
// 首帧只挂当前激活 tab。其余 tab 在浏览器空闲期逐个补挂载,随后继续按原有
// keep-alive 语义保留组件 / webview / 编辑器状态。这样恢复一个多 tab 会话时,
@@ -394,7 +427,8 @@ export function RightSidebarShell({
// taken from incomplete information and destroy the restored selection.
useEffect(() => {
// 单页签独立窗口不写激活位:它只投影自己承载的页签,激活位归主窗侧栏管。
- if (soloMode || !subagentsEligibilityKnown) return;
+ // 边组也不写:任务级激活位是整个任务(所有组)的对账,只由右侧组做一次。
+ if (soloMode || !isPrimaryGroup || !subagentsEligibilityKnown) return;
if (!bucket.hydrated || !sessionId || bucket.activeTabId === sessionActiveTabId) return;
void setActiveTab(sessionId, sessionActiveTabId).catch((err) => {
log.error('unavailable active-tab reconciliation failed', {
@@ -407,6 +441,7 @@ export function RightSidebarShell({
sessionActiveTabId,
bucket.activeTabId,
bucket.hydrated,
+ isPrimaryGroup,
sessionId,
soloMode,
subagentsEligibilityKnown,
@@ -451,7 +486,7 @@ export function RightSidebarShell({
// 这些 kind 已无渲染方,
// 留着只会落到 PlaceholderBody 变成"敬请期待"的死页签。
useEffect(() => {
- if (soloMode || !bucket.hydrated || !sessionId) return;
+ if (soloMode || !isPrimaryGroup || !bucket.hydrated || !sessionId) return;
const legacyGhostTabs = bucket.tabs.filter((tab) =>
tab.kind.startsWith('ghost:') ||
tab.kind === ('bot-delegations' as TabKindId) ||
@@ -467,7 +502,7 @@ export function RightSidebarShell({
}
}
})();
- }, [bucket.hydrated, bucket.tabs, sessionId, soloMode]);
+ }, [bucket.hydrated, bucket.tabs, isPrimaryGroup, sessionId, soloMode]);
// 关掉最后一个 tab → 通知 host 自动收起侧栏。只在 tab 数「从 >0 变 0」的转变时
// 触发,不是"等于 0"就触发:
@@ -507,9 +542,11 @@ export function RightSidebarShell({
// 单例 kind(当前仅 review)走 addOrFocusSingletonTab:已存在则切到现有,
// 否则正常 addTab。menu meta 的 singleton 字段是数据来源,目前只有 review。
const isSingleton = plugin?.menu?.singleton === true;
+ // 边组里点「+」:新页签直接落在本组(乐观插入那一帧就带着组归属,不闪过右侧栏)。
+ const addOpts = isPrimaryGroup ? undefined : { groupId };
const action = isSingleton
- ? addOrFocusSingletonTab(sessionId, kind, initialState)
- : addTab(sessionId, kind, initialState);
+ ? addOrFocusSingletonTab(sessionId, kind, initialState, addOpts)
+ : addTab(sessionId, kind, initialState, addOpts);
void action.catch((err) => {
// 按错误码 toast:专属文案挂在全局 ipcError 命名空间(RIGHT_SIDEBAR_*),其余错误落通用 addFailed 兜底。
toast.error(
@@ -522,7 +559,7 @@ export function RightSidebarShell({
log.error('handleAdd failed', { sessionId, kind, err });
});
},
- [sessionId, subagentsEnabled, t],
+ [groupId, isPrimaryGroup, sessionId, subagentsEnabled, t],
);
const handleClose = useCallback(
@@ -542,29 +579,52 @@ export function RightSidebarShell({
const handleActivate = useCallback(
(tabId: string) => {
+ setGroupActiveTabId(groupId, sessionId, tabId);
if (isGlobalTabId(tabId)) {
setActiveGlobalTabId(tabId);
return;
}
- // 选中任务页签 = 离开全局页签;任务自己的激活位照常落库。
- setActiveGlobalTabId(null);
+ // 选中本组的任务页签 = 离开本组里的全局页签(别的组里的全局页签不受影响);
+ // 任务自己的激活位照常落库。
+ const activeGlobal = activeGlobalTabId;
+ if (activeGlobal && pinnedTabs.some((tab) => tab.id === activeGlobal)) {
+ setActiveGlobalTabId(null);
+ }
if (!sessionId) return;
void setActiveTab(sessionId, tabId).catch((err) => {
log.error('handleActivate failed', { sessionId, tabId, err });
});
},
- [sessionId],
+ [activeGlobalTabId, groupId, pinnedTabs, sessionId],
+ );
+
+ // 右键菜单「移到 …」:改组归属,目标组里立刻选中它;组 pane 的出现 / 隐藏由
+ // tabGroupPanes 按在场判定处理。
+ const handleMoveTab = useCallback(
+ (tabId: string, target: TabGroupId) => {
+ if (target === groupId) return;
+ setTabGroup(tabId, target);
+ setGroupActiveTabId(target, sessionId, tabId);
+ if (isGlobalTabId(tabId)) setActiveGlobalTabId(tabId);
+ },
+ [groupId, sessionId],
);
const handleReorder = useCallback(
(orderedIds: string[]) => {
if (!sessionId) return;
- const fullOrder = mergeAvailableTabOrder(bucket.tabs, orderedIds, tabAvailability);
+ // 只重排本组可见的页签:别的组的页签当作"不可见槽位"原位保留。
+ const hidden = new Set(tabAvailability.hiddenTabIds ?? []);
+ for (const tab of bucket.tabs) if (!inGroup(tab.id)) hidden.add(tab.id);
+ const fullOrder = mergeAvailableTabOrder(bucket.tabs, orderedIds, {
+ ...tabAvailability,
+ hiddenTabIds: hidden,
+ });
void reorderTabs(sessionId, fullOrder).catch((err) => {
log.error('handleReorder failed', { sessionId, orderedIds, err });
});
},
- [bucket.tabs, sessionId, tabAvailability],
+ [bucket.tabs, inGroup, sessionId, tabAvailability],
);
const handleCycleTab = useCallback(
@@ -588,11 +648,11 @@ export function RightSidebarShell({
);
useAppShortcut('right-tab-prev', () => handleCycleTab('prev'), {
- enabled: Boolean(sessionId),
+ enabled: Boolean(sessionId) && isPrimaryGroup,
stopImmediate: true,
});
useAppShortcut('right-tab-next', () => handleCycleTab('next'), {
- enabled: Boolean(sessionId),
+ enabled: Boolean(sessionId) && isPrimaryGroup,
stopImmediate: true,
});
@@ -643,7 +703,7 @@ export function RightSidebarShell({
}, [sessionId]);
useEffect(() => {
- if (!sessionId) return;
+ if (!sessionId || !isPrimaryGroup) return;
const off = window.electronAPI.onRsbBrowserCommand(({ command }) => {
if (command === 'right-tab-prev') {
handleCycleTab('prev');
@@ -652,7 +712,7 @@ export function RightSidebarShell({
}
});
return off;
- }, [handleCycleTab, sessionId]);
+ }, [handleCycleTab, isPrimaryGroup, sessionId]);
// 顶栏「在独立窗口中打开」作用于当前激活页签;没有激活页签时不渲染按钮。
const handleDetachActiveTab = useMemo(
@@ -735,6 +795,8 @@ export function RightSidebarShell({
onCloseOthers={handleCloseOthers}
onCloseAll={handleCloseAll}
onDetachTab={onDetachTab}
+ groupId={groupId}
+ onMoveTab={soloMode ? undefined : handleMoveTab}
pillVariant="chip"
addButtonWrapperClassName="h-[30px]"
subagentsAvailable={subagentsEnabled}
@@ -792,6 +854,8 @@ export function RightSidebarShell({
isMaximized={isMaximized}
onDetach={handleDetachActiveTab}
onDetachTab={onDetachTab}
+ groupId={groupId}
+ onMoveTab={soloMode ? undefined : handleMoveTab}
onCloseOthers={handleCloseOthers}
onCloseAll={handleCloseAll}
chromeWindowDrag={chromeWindowDrag}
@@ -802,7 +866,7 @@ export function RightSidebarShell({
{/* 首次切到某 session 时 cache 尚未 hydrate(等 IPC list 回包),保留 panel
背景而非闪 EmptyState —— EmptyState 是"真的没 tab"的 Welcome 内容。
sessionId 为 null 也走这条:Shell 不显示任何内容(无激活会话)。 */}
- {!contentReady || soloMode || !sessionId ? null : tabs.length === 0 ? (
+ {!contentReady || soloMode || !sessionId || !isPrimaryGroup ? null : tabs.length === 0 ? (
// tab 列表为空时永远渲染 EmptyState。审查页签只通过「+」dropdown 或
// EmptyState 的"打开审查"入口由用户主动创建。
<EmptyState
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
index c3f86c800c..449c32731d 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
@@ -37,6 +37,7 @@ import {
} from '@/components/ui/dropdown-menu';
import { AddTabDropdown } from './AddTabDropdown';
import { getTabKind, hydrateTabState } from './registry';
+import { TAB_GROUP_IDS, tabGroupLabelKey, type TabGroupId } from './tabGroups';
import type { BuiltinTabKindId, TabKindId, TabState } from './types';
interface TabBarProps {
@@ -77,6 +78,10 @@ interface TabBarProps {
onDetach?: () => void;
/** 页签右键菜单「在独立窗口中打开」:作用于被点的页签。 */
onDetachTab?: (tabId: string) => void;
+ /** 本条属于哪个页签组;右键菜单「移到 …」列出其余各组。 */
+ groupId?: TabGroupId;
+ /** 页签右键菜单「移到 左侧 / 右侧栏 / 上方 / 下方」。不传 = 不显示。 */
+ onMoveTab?: (tabId: string, groupId: TabGroupId) => void;
/** 本条横带是否作为**窗口**拖拽区(B3):主窗口内嵌形态传 false —— 空白处是
* "拖面板"手势面(窗口拖拽区收不到鼠标事件,二者物理互斥;拖窗走左栏顶行);
* detached 子窗口等其它宿主不传,默认 true 维持经典拖窗行为。 */
@@ -99,6 +104,9 @@ interface TabStripProps {
onCloseAll?: () => void;
/** Tab pill 右键菜单「在独立窗口中打开」。 */
onDetachTab?: (tabId: string) => void;
+ /** 见 TabBarProps.groupId / onMoveTab。 */
+ groupId?: TabGroupId;
+ onMoveTab?: (tabId: string, groupId: TabGroupId) => void;
className?: string;
/**
* pill 视觉变体:
@@ -213,6 +221,8 @@ export function TabBar({
onCloseAll,
onDetach,
onDetachTab,
+ groupId,
+ onMoveTab,
chromeWindowDrag = true,
subagentsAvailable = false,
}: TabBarProps) {
@@ -239,6 +249,8 @@ export function TabBar({
onCloseOthers={onCloseOthers}
onCloseAll={onCloseAll}
onDetachTab={onDetachTab}
+ groupId={groupId}
+ onMoveTab={onMoveTab}
addButtonWrapperClassName="h-[36px]"
addButtonClassName="mt-[3px]"
subagentsAvailable={subagentsAvailable}
@@ -306,6 +318,8 @@ export function TabStrip({
onCloseOthers,
onCloseAll,
onDetachTab,
+ groupId = 'right',
+ onMoveTab,
className,
pillVariant = 'flush',
addButtonWrapperClassName,
@@ -501,6 +515,7 @@ export function TabStrip({
open={dropdownOpen}
anchorRef={addButtonWrapperRef}
sessionId={sessionId}
+ groupId={groupId}
onClose={closeDropdown}
onSelect={onAdd}
existingKinds={existingKinds}
@@ -569,6 +584,22 @@ export function TabStrip({
{t('rightSidebar.tabs.contextMenu.closeAll')}
</DropdownMenuItem>
)}
+ {onMoveTab &&
+ TAB_GROUP_IDS.filter((target) => target !== groupId).map((target) => (
+ <DropdownMenuItem
+ key={target}
+ data-testid={`right-sidebar-tab-move-${target}`}
+ onClick={() => {
+ const id = contextMenu.tabId;
+ closeContextMenu();
+ onMoveTab(id, target);
+ }}
+ >
+ {t('rightSidebar.tabs.contextMenu.moveTo', {
+ target: t(tabGroupLabelKey(target)),
+ })}
+ </DropdownMenuItem>
+ ))}
{onDetachTab && (
<DropdownMenuItem
onClick={() => {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabGroupPanel.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabGroupPanel.tsx
new file mode 100644
index 0000000000..af9f6125ba
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabGroupPanel.tsx
@@ -0,0 +1,84 @@
+/**
+ * TabGroupPanel —— 左 / 上 / 下边页签组的 pane 组件(panelKind `tab-group:<边>`)。
+ *
+ * 右侧组仍由 MainLayout 构造的 <RightSidebar>(折叠动画、mac 浮层按钮等历史外壳)
+ * 承载;其余三组是布局引擎按需挂载的通用 pane:同一个 RightSidebarShell 换个
+ * `groupId`,顶栏自带「在独立窗口中打开 / 撑满」,没有折叠 —— 组里页签清空就由
+ * tabGroupPanes 注销 kind,引擎把它隐藏、空间回流给聊天区。
+ *
+ * 宽高口径与其它 pane 一致:根横排里的左组按引擎下发的像素宽(PaneWidthContext),
+ * 聊天列里的上下组填满父格(PaneFillContext)。
+ */
+
+import type { CSSProperties, ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { tabGroupPanelKind, type TabGroupId } from '../../../shared/layoutTree';
+import { usePanelMaximize } from '@/layout/panelMaximize';
+import { usePaneAtWindowTop, usePaneFill } from '@/layout/panePlacement';
+import { usePanelWidth } from '@/layout/paneWidths';
+import type { PanelComponentProps } from '@/panels/registry';
+import { RightSidebarShell } from './RightSidebarShell';
+import { useTabGroupHost } from './tabGroupHost';
+import { tabGroupLabelKey } from './tabGroups';
+
+function TabGroupPanelBody({ groupId }: { groupId: TabGroupId }): ReactNode {
+ const { t } = useTranslation();
+ const host = useTabGroupHost();
+ const fill = usePaneFill();
+ const atWindowTop = usePaneAtWindowTop();
+ const maximize = usePanelMaximize();
+ const kind = tabGroupPanelKind(groupId);
+ const engineWidth = usePanelWidth(kind);
+ if (!host) return null;
+ const isMaximized = maximize?.maximizedKind === kind;
+ const style: CSSProperties | undefined =
+ fill || isMaximized ? undefined : { width: engineWidth ?? undefined };
+ return (
+ <section
+ aria-label={t(tabGroupLabelKey(groupId))}
+ data-panel-drag-root={kind}
+ data-tab-group={groupId}
+ className={
+ fill || isMaximized
+ ? 'relative flex h-full min-h-0 w-full min-w-0 flex-1 flex-col overflow-hidden bg-content-area'
+ : 'relative flex h-full min-h-0 min-w-0 shrink flex-col overflow-hidden bg-content-area'
+ }
+ style={style}
+ >
+ <RightSidebarShell
+ groupId={groupId}
+ sessionId={host.sessionId}
+ workdir={host.workdir}
+ remoteHostId={host.remoteHostId}
+ deviceLinkDeviceId={host.deviceLinkDeviceId}
+ subagentsAvailable={host.subagentsAvailable}
+ isMac={host.isMac}
+ unifiedTopbar={host.isMac && atWindowTop}
+ reserveLeftChromeActions={
+ host.isMac && atWindowTop && groupId === 'left' && host.reserveLeftChromeActions
+ }
+ onMaximize={maximize ? () => maximize.toggle(kind) : undefined}
+ isMaximized={isMaximized}
+ onDetachTab={host.onDetachTab}
+ chromeWindowDrag={false}
+ />
+ </section>
+ );
+}
+
+const panels: Partial<Record<TabGroupId, (props: PanelComponentProps) => ReactNode>> = {};
+
+/** 某边组的 pane 组件(按组缓存,注册表拿到稳定引用)。右侧组不在此列。 */
+export function tabGroupPanelComponent(
+ groupId: Exclude<TabGroupId, 'right'>,
+): (props: PanelComponentProps) => ReactNode {
+ let component = panels[groupId];
+ if (!component) {
+ component = function TabGroupPanel(): ReactNode {
+ return <TabGroupPanelBody groupId={groupId} />;
+ };
+ panels[groupId] = component;
+ }
+ return component;
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
index f4a2d76c92..1670b1b520 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
@@ -88,6 +88,7 @@ import {
addGlobalPluginTab,
getActiveGlobalTabId,
} from '../globalTabs';
+import { __resetTabGroupsForTest, getTabGroup } from '../tabGroups';
import { toast } from '@/lib/toast';
import { writePanelCollapsed } from '@/layout/collapsePrefs';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
@@ -311,6 +312,7 @@ describe('RightSidebarShell empty state', () => {
_resetNativePopupTabsForTests();
__resetSidebarTabWindowsStateForTest();
__resetGlobalTabsForTest();
+ __resetTabGroupsForTest();
window.localStorage.clear();
installedGhostsMock.list = [];
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
@@ -398,6 +400,68 @@ describe('RightSidebarShell empty state', () => {
await waitFor(() => expect(onAllTabsClosed).toHaveBeenCalledOnce());
});
+ // 测试价值
+ // - 生产入口与可观察结果:同一任务的右侧组与左侧组两个 Shell;可观察的是页签右键
+ // 「移到左侧」后从右侧条消失、出现在左侧条并被选中(组归属落 localStorage),在左侧
+ // 组点它仍写任务级激活位;「关闭其他」只作用于本组。
+ // - Bug / 规则依据:页签组模型——页签可移到聊天区任一边,两边投影同一任务桶不串。
+ // - 现有覆盖缺口:Shell 此前只有单组。
+ // - 最小失败输入:两个任务页签 + 一次「移到左侧」。
+ // - tier:unit(jsdom,进程内 store + localStorage 组归属)。
+ it('moves a task tab between groups; each group projects only its own tabs', async () => {
+ tabsIpc.list.mockResolvedValueOnce({
+ tabs: [
+ { id: 'tab-files', kind: 'file-browser', state: null },
+ { id: 'tab-web', kind: 'web-browser', state: null },
+ ],
+ activeTabId: 'tab-files',
+ });
+ const shellProps = {
+ sessionId: 's1',
+ workdir: '/tmp/repo',
+ remoteHostId: null,
+ isMac: false,
+ subagentsAvailable: false,
+ };
+ const right = render(createElement(RightSidebarShell, { ...shellProps, groupId: 'right' }));
+ await waitFor(() => expect(getBucket('s1').hydrated).toBe(true));
+ const left = render(createElement(RightSidebarShell, { ...shellProps, groupId: 'left' }));
+ const stripOf = (view: ReturnType<typeof render>) =>
+ view.container.querySelector('[data-testid="right-sidebar-tab-strip"]')!;
+ expect(stripOf(right).textContent).toContain('rightSidebar.tabs.kinds.browser');
+ expect(stripOf(left).textContent).not.toContain('rightSidebar.tabs.kinds.browser');
+
+ // 右键浏览器页签 →「移到左侧」。
+ const webPill = right.getByText('rightSidebar.tabs.kinds.browser').closest('.group')!;
+ fireEvent.contextMenu(webPill);
+ fireEvent.click(screen.getByTestId('right-sidebar-tab-move-left'));
+ expect(getTabGroup('tab-web')).toBe('left');
+ await waitFor(() =>
+ expect(stripOf(left).textContent).toContain('rightSidebar.tabs.kinds.browser'),
+ );
+ expect(stripOf(right).textContent).not.toContain('rightSidebar.tabs.kinds.browser');
+ // 左侧组里它是激活页签(组内记忆),右侧组仍显示任务级激活页签。
+ expect(stripOf(left).querySelector('.group')?.className).toContain('font-medium');
+ expect(
+ right.getByText('rightSidebar.tabs.kinds.fileBrowser').closest('.group')?.className,
+ ).toContain('font-medium');
+
+ // 在左侧组点它:任务级激活位照常落库。
+ tabsIpc.setActive.mockClear();
+ fireEvent.click(left.getByText('rightSidebar.tabs.kinds.browser'));
+ await waitFor(() => expect(tabsIpc.setActive).toHaveBeenCalled());
+ expect(getBucket('s1').activeTabId).toBe('tab-web');
+
+ // 右侧组「关闭其他」只关本组的页签(本组只剩文件页签,无其它可关)。
+ fireEvent.contextMenu(right.getByText('rightSidebar.tabs.kinds.fileBrowser').closest('.group')!);
+ const closeOthers = screen
+ .getByText('rightSidebar.tabs.contextMenu.closeOthers')
+ .closest('[role="menuitem"]')!;
+ expect(closeOthers.getAttribute('data-disabled')).not.toBeNull();
+ left.unmount();
+ right.unmount();
+ });
+
it.each([
{ otherBrowser: false, release: 'close' },
{ otherBrowser: true, release: 'close' },
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBar.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBar.test.tsx
index c75602f68e..fcc5891ff3 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBar.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBar.test.tsx
@@ -175,6 +175,44 @@ describe('TabStrip add menu · plugins group', () => {
});
});
+// 测试价值
+// - 生产入口与可观察结果:页签右键菜单的「移到 …」项;可观察的是列出除本组外的三个
+// 目标组、点选回调带目标组 id、未提供 onMoveTab(弹出窗口)时不出现。
+// - Bug / 规则依据:页签组模型——页签可移到聊天区左 / 上 / 下边。
+// - 现有覆盖缺口:右键菜单此前无用例。
+// - 最小失败输入:groupId='right' + 一个页签,右键。
+// - tier:unit(jsdom)。
+describe('TabStrip context menu · move to group', () => {
+ it('lists the other three groups and reports the chosen target', () => {
+ const onMoveTab = vi.fn();
+ render(
+ <TabStrip
+ tabs={TABS}
+ activeTabId={null}
+ onActivate={vi.fn()}
+ onClose={vi.fn()}
+ onReorder={vi.fn()}
+ onAdd={vi.fn()}
+ groupId="right"
+ onMoveTab={onMoveTab}
+ />,
+ );
+ fireEvent.contextMenu(pillFor(LABEL_WEB));
+ expect(screen.queryByTestId('right-sidebar-tab-move-right')).toBeNull();
+ expect(screen.getByTestId('right-sidebar-tab-move-top')).toBeTruthy();
+ expect(screen.getByTestId('right-sidebar-tab-move-bottom')).toBeTruthy();
+ fireEvent.click(screen.getByTestId('right-sidebar-tab-move-left'));
+ expect(onMoveTab).toHaveBeenCalledWith('tab-web', 'left');
+ });
+
+ it('offers no move items when the host does not support moving (popped-out window)', () => {
+ renderStrip();
+ fireEvent.contextMenu(pillFor(LABEL_FILE));
+ expect(screen.getByText('rightSidebar.tabs.contextMenu.close')).toBeTruthy();
+ expect(screen.queryByTestId('right-sidebar-tab-move-left')).toBeNull();
+ });
+});
+
afterEach(() => cleanup());
describe('TabStrip 中键关闭 tab', () => {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabGroupPanes.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabGroupPanes.test.tsx
new file mode 100644
index 0000000000..482f3dd2b7
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabGroupPanes.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+/**
+ * 测试价值
+ * - 生产入口与可观察结果:useTabGroupPanes(主窗口挂载的边组在场维护);可观察的是
+ * 某组第一次有可见页签时 `tab-group:<边>` 进入面板注册表且布局树经 layout.set 多出
+ * 它的 pane;页签移走后 kind 注销(树不动);路由离开聊天视图(enabled=false)时全部注销。
+ * - Bug / 规则依据:页签组模型——组的 pane 只在有页签时在场,树数据保留
+ * (architecture-invariants §3「未注册的面板允许保留在存档中但不渲染」)。
+ * - 现有覆盖缺口:新 hook。
+ * - 最小失败输入:一个全局页签 setTabGroup('left') + renderHook。
+ * - tier:unit(jsdom,localStorage 全局页签 + stub layout 桥)。
+ */
+
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const installedGhostsMock = vi.hoisted(() => ({ list: [] as unknown[] }));
+vi.mock('@/cindy-brain/useInstalledGhosts', () => ({
+ useInstalledGhosts: () => installedGhostsMock.list,
+ readInstalledGhostsSnapshot: () => installedGhostsMock.list,
+}));
+vi.mock('../TabGroupPanel', () => ({
+ tabGroupPanelComponent: () => () => null,
+}));
+
+import { createDefaultLayout, type Layout } from '../../../../shared/layoutTree';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { __resetSidebarTabWindowsStateForTest } from '@/lib/sidebarTabWindowState';
+import { __resetPanelRegistryForTest, hasPanelKind } from '@/panels/registry';
+import { __resetGlobalTabsForTest, addGlobalPluginTab } from '../globalTabs';
+import { _resetStore } from '../store';
+import { useTabGroupPanes } from '../tabGroupPanes';
+import { __resetTabGroupsForTest, setTabGroup } from '../tabGroups';
+
+let currentLayout: Layout;
+const setLayout = vi.fn(async (layout: Layout) => {
+ currentLayout = layout;
+});
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetGlobalTabsForTest();
+ __resetTabGroupsForTest();
+ __resetPanelRegistryForTest();
+ __resetSidebarTabWindowsStateForTest();
+ _resetStore();
+ setDataOwnerGeneration('owner-a', 1);
+ currentLayout = createDefaultLayout();
+ setLayout.mockClear();
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ layout: {
+ getStateSync: () => ({ layout: currentLayout }),
+ onChanged: () => () => undefined,
+ set: setLayout,
+ },
+ sidebarTabWindow: {},
+ };
+ installedGhostsMock.list = [
+ {
+ manifest: { id: 'alpha', name: 'Alpha', panel: { html: 'p.html', title: 'Alpha' } },
+ enabled: true,
+ },
+ ];
+});
+
+afterEach(() => {
+ __resetGlobalTabsForTest();
+ __resetTabGroupsForTest();
+ __resetPanelRegistryForTest();
+ installedGhostsMock.list = [];
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+});
+
+describe('useTabGroupPanes', () => {
+ it('registers an edge group and inserts its pane when a visible tab lands there; unregisters when it leaves', () => {
+ const tab = addGlobalPluginTab('alpha')!;
+ const { rerender } = renderHook(
+ (props: { enabled: boolean }) =>
+ useTabGroupPanes({ sessionId: null, enabled: props.enabled, remoteHostId: null }),
+ { initialProps: { enabled: true } },
+ );
+ expect(hasPanelKind('tab-group:left')).toBe(false);
+
+ act(() => setTabGroup(tab.id, 'left'));
+ expect(hasPanelKind('tab-group:left')).toBe(true);
+ expect(setLayout).toHaveBeenCalledTimes(1);
+ const kinds = (
+ currentLayout.content as { children: { node: { panelKind?: string } }[] }
+ ).children.map((c) => c.node.panelKind);
+ expect(kinds).toEqual(['tab-group:left', 'chat-main', 'right-tabs']);
+
+ // 移回右侧组:kind 注销,树不动(位置记忆保留)。
+ act(() => setTabGroup(tab.id, 'right'));
+ expect(hasPanelKind('tab-group:left')).toBe(false);
+ expect(setLayout).toHaveBeenCalledTimes(1);
+
+ // 再移到左侧:pane 已在树里,不再写树。
+ act(() => setTabGroup(tab.id, 'left'));
+ expect(hasPanelKind('tab-group:left')).toBe(true);
+ expect(setLayout).toHaveBeenCalledTimes(1);
+
+ // 离开聊天视图:全部注销。
+ rerender({ enabled: false });
+ expect(hasPanelKind('tab-group:left')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabGroups.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabGroups.test.ts
new file mode 100644
index 0000000000..eda7dbeda0
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabGroups.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment jsdom
+/**
+ * 测试价值
+ * - 生产入口与可观察结果:tabGroups 的 setTabGroup / clearTabGroup / 组内激活记忆与
+ * localStorage 持久化;可观察的是页签缺省在右侧组、改组后按数据所有者分键保存、
+ * 放回右侧组即删条目、另一窗口的写入经 storage 事件同步、坏数据整条丢弃。
+ * - Bug / 规则依据:页签组模型(页签可移到聊天区左 / 上 / 下边)——老数据零迁移要求
+ * "没有记录 = 右侧组"。
+ * - 现有覆盖缺口:新模块。
+ * - 最小失败输入:setTabGroup('t1','left') 后 getTabGroup('t1')。
+ * - tier:unit(jsdom localStorage + storage 事件)。
+ */
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import {
+ __resetTabGroupsForTest,
+ clearTabGroup,
+ getGroupActiveTabId,
+ getTabGroup,
+ getTabGroupAssignments,
+ sanitizeTabGroupAssignments,
+ setGroupActiveTabId,
+ setTabGroup,
+ subscribeTabGroups,
+} from '../tabGroups';
+
+const KEY = 'xdt:sidebarTabGroups:v1:owner-a';
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetTabGroupsForTest();
+ setDataOwnerGeneration('owner-a', 1);
+});
+
+afterEach(() => {
+ __resetTabGroupsForTest();
+ window.localStorage.clear();
+});
+
+describe('tabGroups', () => {
+ it('defaults to the right group, persists per data owner and drops entries moved back', () => {
+ expect(getTabGroup('t1')).toBe('right');
+ let notified = 0;
+ const off = subscribeTabGroups(() => notified++);
+ setTabGroup('t1', 'left');
+ expect(getTabGroup('t1')).toBe('left');
+ expect(JSON.parse(window.localStorage.getItem(KEY)!)).toEqual({ t1: 'left' });
+ expect(notified).toBe(1);
+
+ // 同组重复写不通知;放回右侧组 = 删条目,存储清空。
+ setTabGroup('t1', 'left');
+ expect(notified).toBe(1);
+ setTabGroup('t1', 'right');
+ expect(getTabGroup('t1')).toBe('right');
+ expect(window.localStorage.getItem(KEY)).toBeNull();
+
+ setTabGroup('t2', 'bottom');
+ setDataOwnerGeneration('owner-b', 1);
+ expect(getTabGroup('t2')).toBe('right');
+ setDataOwnerGeneration('owner-a', 1);
+ expect(getTabGroup('t2')).toBe('bottom');
+ clearTabGroup('t2');
+ expect(getTabGroupAssignments()).toEqual({});
+ off();
+ });
+
+ it('syncs writes from another window through the storage event', () => {
+ expect(getTabGroup('t9')).toBe('right');
+ window.localStorage.setItem(KEY, JSON.stringify({ t9: 'top' }));
+ window.dispatchEvent(new StorageEvent('storage', { key: KEY }));
+ expect(getTabGroup('t9')).toBe('top');
+ });
+
+ it('keeps a per-group, per-task active memory and sanitizes persisted data', () => {
+ expect(getGroupActiveTabId('left', 's1')).toBeNull();
+ setGroupActiveTabId('left', 's1', 'tab-a');
+ expect(getGroupActiveTabId('left', 's1')).toBe('tab-a');
+ expect(getGroupActiveTabId('left', 's2')).toBeNull();
+ expect(getGroupActiveTabId('bottom', 's1')).toBeNull();
+ setGroupActiveTabId('left', 's1', null);
+ expect(getGroupActiveTabId('left', 's1')).toBeNull();
+
+ expect(
+ sanitizeTabGroupAssignments({ a: 'left', b: 'right', c: 'nowhere', '': 'top', d: 3 }),
+ ).toEqual({ a: 'left' });
+ expect(sanitizeTabGroupAssignments(['left'])).toEqual({});
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts
index d4290ede06..72241aae81 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts
@@ -23,6 +23,7 @@ import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import { createLogger } from '@/lib/logger';
import { isSidebarTabWindow } from '@/lib/sidebarTabWindow';
import { isTabPoppedOut } from '@/lib/sidebarTabWindowState';
+import { clearTabGroup, setTabGroup, type TabGroupId } from './tabGroups';
import type { TabState } from './types';
const log = createLogger('rightSidebar.globalTabs');
@@ -157,7 +158,10 @@ function makeTabId(): string {
* 加入(或返回已有的)某个插件的全局页签。幂等:同一实例只有一个页签。
* 用户手动加入会清掉它的 dismissed 记录。
*/
-export function addGlobalPluginTab(instanceId: string): TabState | null {
+export function addGlobalPluginTab(
+ instanceId: string,
+ opts?: { groupId?: TabGroupId },
+): TabState | null {
const current = getGlobalTabsSnapshot();
const existing = current.tabs.find(
(tab) => (tab.state as PluginViewTabState | null)?.instanceId === instanceId,
@@ -178,6 +182,8 @@ export function addGlobalPluginTab(instanceId: string): TabState | null {
kind: 'plugin-view',
state: { instanceId } satisfies PluginViewTabState,
};
+ // 组归属先于页签出现落定,首帧就在目标组里。
+ if (opts?.groupId) setTabGroup(tab.id, opts.groupId);
persist({ tabs: [...current.tabs, tab], dismissedInstanceIds: dismissed });
return tab;
}
@@ -196,6 +202,7 @@ export function removeGlobalTab(tabId: string): void {
tabs: current.tabs.filter((candidate) => candidate.id !== tabId),
dismissedInstanceIds: dismissed,
});
+ clearTabGroup(tabId);
// 页签正弹在独立窗口里:窗口没有内容可交回,直接销毁(与任务页签同一规则)。
if (!isSidebarTabWindow() && isTabPoppedOut(tabId)) {
void window.electronAPI?.sidebarTabWindow?.closeForTab(tabId).catch((err) => {
@@ -280,6 +287,7 @@ export function reconcileGlobalPluginTabs(ghosts: readonly InstalledGhost[]): vo
if (activeGlobalTabId && !tabs.some((tab) => tab.id === activeGlobalTabId)) {
activeGlobalTabId = null;
}
+ for (const tab of current.tabs) if (!tabs.includes(tab)) clearTabGroup(tab.id);
persist({ tabs, dismissedInstanceIds: dismissed });
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.ts
index 514a745085..f683d6d610 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts
@@ -29,6 +29,7 @@ import { closeNativePopupForTab } from './lib/nativePopupTabs';
import { isTabHostedHere } from './lib/tabHosting';
import { isSidebarTabWindow } from '@/lib/sidebarTabWindow';
import { isTabPoppedOut } from '@/lib/sidebarTabWindowState';
+import { clearTabGroup, setTabGroup, type TabGroupId } from './tabGroups';
import type { TabKindId, TabState } from './types';
import type { RsbWindowTabSnapshot } from '../../../shared/rightSidebarWindow';
import type { SidebarTabReturnSnapshot } from '../../../shared/sidebarTabWindow';
@@ -776,12 +777,13 @@ export async function ensureHydrated(sessionId: string): Promise<void> {
* `opts.activate === false`:追加 tab 但**不抢激活位**(cache 与 DB 的 active 都
* 保持原样)。钉住面板的跨会话自动补挂用 —— 用户切到某会话时补挂的页签不该
* 把他正看着的 tab 顶掉。默认 true 维持既有语义(用户手动加 tab = 看它)。
+ * `opts.groupId`:新页签落在哪个页签组(缺省右侧组);乐观插入前就登记,首帧不闪组。
*/
export async function addTab(
sessionId: string,
kind: TabKindId,
initialState: unknown = null,
- opts?: { onOptimisticAdd?: (tabId: string) => void; activate?: boolean },
+ opts?: { onOptimisticAdd?: (tabId: string) => void; activate?: boolean; groupId?: TabGroupId },
): Promise<TabState> {
const activate = opts?.activate !== false;
const prev = getBucket(sessionId);
@@ -795,6 +797,7 @@ export async function addTab(
const id = makeTabId();
const position = prev.tabs.length;
const newTab: TabState = { id, kind, state: initialState };
+ if (opts?.groupId) setTabGroup(id, opts.groupId);
setBucket(sessionId, {
tabs: [...prev.tabs, newTab],
activeTabId: activate ? id : prev.activeTabId,
@@ -869,6 +872,7 @@ export async function addOrFocusSingletonTab(
sessionId: string,
kind: TabKindId,
initialState: unknown = null,
+ opts?: { groupId?: TabGroupId },
): Promise<TabState> {
const bucket = getBucket(sessionId);
const existing = bucket.tabs.find((t) => t.kind === kind);
@@ -878,7 +882,7 @@ export async function addOrFocusSingletonTab(
}
return existing;
}
- return addTab(sessionId, kind, initialState);
+ return addTab(sessionId, kind, initialState, opts);
}
/**
@@ -982,6 +986,7 @@ function forgetClosedTab(sessionId: string, tabId: string, kind: TabKindId): voi
const key = tabStateWriteKey(sessionId, tabId);
patchRevisions.delete(key);
persistedStateBaselines.delete(key);
+ clearTabGroup(tabId);
if (kind === 'web-browser') browserWebviewPool.release(tabId);
unmarkPopupSpawnedTab(tabId);
closeNativePopupForTab(tabId);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts b/apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts
index 68136286c9..e2cf25bf0c 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts
@@ -100,3 +100,42 @@ export function mergeAvailableTabOrder(
isUnavailableTab(tab, availability) ? tab.id : (orderedVisibleIds[index++] ?? tab.id),
);
}
+
+export interface TabAvailabilityInput {
+ installedGhosts: readonly InstalledGhost[];
+ remoteHostId: string | null;
+ /** device-link 会话归属:null = 已确认本机,undefined = 尚未解析。 */
+ deviceLinkDeviceId?: string | null;
+ /** Subagents 资格三态:undefined = 会话行仍在加载,先不把它折成"不可用"。 */
+ subagentsAvailable?: boolean;
+ hiddenTabIds?: ReadonlySet<string>;
+}
+
+export interface TabAvailabilities {
+ /** 任务页签的可用性:远程 / 他机会话关闭本地插件能力。 */
+ session: RightSidebarTabAvailability;
+ /** 全局页签(插件视图)的可用性:只看本机已装插件,不随任务归属变化。 */
+ global: RightSidebarTabAvailability;
+}
+
+/**
+ * Shell 与页签组在场判定共用的可用性构造:两处必须用同一口径算"哪些页签可见",
+ * 否则会出现「组被判定为有页签而显示,Shell 里却一个都不投影」的空组。
+ */
+export function buildTabAvailabilities(input: TabAvailabilityInput): TabAvailabilities {
+ const eligibilityKnown = typeof input.subagentsAvailable === 'boolean';
+ return {
+ session: {
+ installedGhosts:
+ input.remoteHostId || input.deviceLinkDeviceId !== null ? [] : input.installedGhosts,
+ subagentsAvailable: input.subagentsAvailable === true || !eligibilityKnown,
+ hiddenTabIds: input.hiddenTabIds,
+ },
+ global: {
+ installedGhosts: [],
+ subagentsAvailable: true,
+ hiddenTabIds: input.hiddenTabIds,
+ pluginViewGhosts: input.installedGhosts,
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx b/apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx
new file mode 100644
index 0000000000..eb8da764ad
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx
@@ -0,0 +1,30 @@
+import { createContext, useContext } from 'react';
+
+/**
+ * 页签组 pane(左 / 上 / 下边组)运行所需的宿主上下文。右侧组由 MainLayout 直接
+ * 构造 <RightSidebar>(经 BuiltinPanelBridge 下发);其余边组是布局引擎按需挂载的
+ * 通用 pane,所需的会话渲染上下文从这里取 —— 与右侧栏拿到的完全同一份。
+ */
+export interface TabGroupHostValue {
+ sessionId: string | null;
+ workdir: string;
+ remoteHostId: string | null;
+ deviceLinkDeviceId?: string | null;
+ subagentsAvailable?: boolean;
+ isMac: boolean;
+ /** 「在独立窗口中打开」某个页签;副窗口不提供。 */
+ onDetachTab?: (tabId: string) => void;
+ /**
+ * mac 下窗口左上的红绿灯 / ChromeActions 会盖住最左面板的顶栏:左侧组贴着窗口
+ * 顶边且左栏收起 / rail 时,为它们预留 no-drag 空位。
+ */
+ reserveLeftChromeActions: boolean;
+}
+
+const TabGroupHostContext = createContext<TabGroupHostValue | null>(null);
+
+export const TabGroupHostProvider = TabGroupHostContext.Provider;
+
+export function useTabGroupHost(): TabGroupHostValue | null {
+ return useContext(TabGroupHostContext);
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/tabGroupPanes.ts b/apps/desktop/src/renderer/features/right-sidebar/tabGroupPanes.ts
new file mode 100644
index 0000000000..8d9a076e39
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/tabGroupPanes.ts
@@ -0,0 +1,158 @@
+/**
+ * tabGroupPanes —— 左 / 上 / 下边页签组的「在场」判定与 pane 注册。
+ *
+ * 一个边组只在「本窗口当前能看到至少一个页签」时存在:任务页签看当前任务桶,
+ * 全局页签全局在场,两者都按 Shell 同一口径的可用性投影(buildTabAvailabilities)
+ * 并排除已弹出到独立窗口的页签。在场 → 向面板注册表注册 `tab-group:<边>` 并保证
+ * 布局树里有它的 pane(第一次用到时按边插入);不在场 → 注销 kind,引擎把 pane
+ * 隐藏、空间回流(树数据保留,下次原位回来)。右侧组始终注册,不经这里。
+ */
+
+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';
+
+import {
+ ensureTabGroupPane,
+ findSplitChildByPanelKind,
+ TAB_GROUP_IDS,
+ tabGroupPanelKind,
+ type TabGroupId,
+} from '../../../shared/layoutTree';
+import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
+import { createLogger } from '@/lib/logger';
+import { useSidebarTabWindowsState } from '@/lib/sidebarTabWindowState';
+import { registerPanelKind, unregisterPanelKind } from '@/panels/registry';
+import { useGlobalTabs } from './globalTabs';
+import { getBucket, subscribe } from './store';
+import { projectAvailableTabs, buildTabAvailabilities } from './tabAvailability';
+import { tabGroupPanelComponent } from './TabGroupPanel';
+import { tabGroupOf, useTabGroupAssignments } from './tabGroups';
+
+const log = createLogger('rightSidebar.tabGroupPanes');
+
+export type EdgeTabGroupId = Exclude<TabGroupId, 'right'>;
+export const EDGE_TAB_GROUP_IDS = TAB_GROUP_IDS.filter(
+ (id): id is EdgeTabGroupId => id !== 'right',
+);
+
+export interface TabGroupPanesInput {
+ sessionId: string | null;
+ /** 内容区在聊天路由上(右侧栏可用);false 时所有边组一律不在场。 */
+ enabled: boolean;
+ remoteHostId: string | null;
+ deviceLinkDeviceId?: string | null;
+ subagentsAvailable?: boolean;
+}
+
+/** 纯函数:哪些边组当前有可见页签。 */
+export function presentEdgeTabGroups(input: {
+ sessionTabs: readonly { id: string }[];
+ globalTabs: readonly { id: string }[];
+ assignments: Readonly<Record<string, TabGroupId>>;
+}): Set<EdgeTabGroupId> {
+ const out = new Set<EdgeTabGroupId>();
+ for (const tab of [...input.globalTabs, ...input.sessionTabs]) {
+ const group = tabGroupOf(input.assignments, tab.id);
+ if (group !== 'right') out.add(group);
+ }
+ return out;
+}
+
+function ensurePaneInTree(groupId: EdgeTabGroupId): void {
+ try {
+ const api = window.electronAPI?.layout;
+ if (!api) return;
+ const layout = api.getStateSync().layout;
+ if (findSplitChildByPanelKind(layout, tabGroupPanelKind(groupId))) return;
+ const op = ensureTabGroupPane(layout, groupId);
+ if (!op.applied) {
+ log.warn('ensure tab group pane rejected', { groupId, reason: op.reason });
+ return;
+ }
+ void api.set(op.layout).catch((err) => {
+ log.warn('persist tab group pane failed', { groupId, err });
+ });
+ } catch (err) {
+ log.warn('ensure tab group pane failed', { groupId, err });
+ }
+}
+
+/**
+ * 挂在主窗口(MainLayout):随任务桶 / 全局页签 / 组归属 / 弹出状态的变化维护
+ * 边组 pane 的注册与树里的在场。
+ */
+export function useTabGroupPanes(input: TabGroupPanesInput): void {
+ const { sessionId, enabled, remoteHostId, deviceLinkDeviceId, subagentsAvailable } = input;
+ const subscribeBucket = useCallback(
+ (onChange: () => void) =>
+ subscribe((changedSessionId) => {
+ if (changedSessionId === sessionId) onChange();
+ }),
+ [sessionId],
+ );
+ const getBucketSnapshot = useCallback(() => getBucket(sessionId), [sessionId]);
+ const bucket = useSyncExternalStore(subscribeBucket, getBucketSnapshot);
+ const globalTabs = useGlobalTabs();
+ const assignments = useTabGroupAssignments();
+ const poppedOut = useSidebarTabWindowsState();
+ const installedGhosts = useInstalledGhosts();
+
+ const present = useMemo(() => {
+ if (!enabled) return new Set<EdgeTabGroupId>();
+ const hidden = Object.keys(poppedOut);
+ const availability = buildTabAvailabilities({
+ installedGhosts,
+ remoteHostId,
+ deviceLinkDeviceId,
+ subagentsAvailable,
+ hiddenTabIds: hidden.length > 0 ? new Set(hidden) : undefined,
+ });
+ const sessionTabs = bucket.hydrated
+ ? projectAvailableTabs(bucket.tabs, bucket.activeTabId, availability.session).tabs
+ : [];
+ const pinned = projectAvailableTabs(globalTabs, null, availability.global).tabs;
+ return presentEdgeTabGroups({ sessionTabs, globalTabs: pinned, assignments });
+ }, [
+ assignments,
+ bucket,
+ deviceLinkDeviceId,
+ enabled,
+ globalTabs,
+ installedGhosts,
+ poppedOut,
+ remoteHostId,
+ subagentsAvailable,
+ ]);
+ const presentKey = [...present].sort().join(',');
+
+ // 布局被重置 / 外部改写后重新保证在场组的 pane 还在树里。
+ const [layoutRevision, setLayoutRevision] = useState(0);
+ useEffect(() => {
+ const api = window.electronAPI?.layout;
+ if (!api?.onChanged) return;
+ return api.onChanged(() => setLayoutRevision((revision) => revision + 1));
+ }, []);
+
+ useEffect(() => {
+ for (const groupId of EDGE_TAB_GROUP_IDS) {
+ const kind = tabGroupPanelKind(groupId);
+ if (present.has(groupId)) {
+ registerPanelKind({
+ kind,
+ Component: tabGroupPanelComponent(groupId),
+ collapseMemory: 'none',
+ });
+ ensurePaneInTree(groupId);
+ } else {
+ unregisterPanelKind(kind);
+ }
+ }
+ // presentKey 是 present 的稳定字符串化;layoutRevision 触发树重检。
+ }, [present, presentKey, layoutRevision]);
+
+ useEffect(
+ () => () => {
+ for (const groupId of EDGE_TAB_GROUP_IDS) unregisterPanelKind(tabGroupPanelKind(groupId));
+ },
+ [],
+ );
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/tabGroups.ts b/apps/desktop/src/renderer/features/right-sidebar/tabGroups.ts
new file mode 100644
index 0000000000..a6d776c6a9
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/tabGroups.ts
@@ -0,0 +1,186 @@
+/**
+ * tabGroups —— 页签属于哪个页签组(左 / 右 / 上 / 下)。
+ *
+ * 右侧栏的页签默认都在右侧组(历史右侧栏)。用户可以把任意页签(任务页签或全局
+ * 页签)移到聊天区的另一条边:这里只记「tabId → 组」,页签本体仍在原来的存储里
+ * (任务页签在 SQLite 桶,全局页签在 globalTabs)。缺省 = 右侧组,所以老数据零迁移。
+ *
+ * 持久化走 renderer 自有的 localStorage(按数据所有者分键,与 globalTabs 同一条路;
+ * 存的是界面配置而不是任务数据),`storage` 事件做跨窗口同步。条目有上限,关闭
+ * 页签时顺手清掉(store.forgetClosedTab / globalTabs.removeGlobalTab)。
+ *
+ * 每个组另有一份「组内激活页签」的运行期记忆(不持久化):任务桶的 activeTabId
+ * 仍是任务级的焦点页签;某组里不含它时,组内显示自己上次选中的那个。
+ */
+
+import { useSyncExternalStore } from 'react';
+
+import { isTabGroupId, TAB_GROUP_IDS, type TabGroupId } from '../../../shared/layoutTree';
+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { createLogger } from '@/lib/logger';
+
+export { TAB_GROUP_IDS };
+export type { TabGroupId };
+
+const log = createLogger('rightSidebar.tabGroups');
+
+const STORAGE_KEY_PREFIX = 'xdt:sidebarTabGroups:v1:';
+const MAX_ENTRIES = 1000;
+export const DEFAULT_TAB_GROUP: TabGroupId = 'right';
+
+/** tabId → 非默认组。右侧组不落条目。 */
+export type TabGroupAssignments = Readonly<Record<string, TabGroupId>>;
+
+const EMPTY: TabGroupAssignments = Object.freeze({}) as TabGroupAssignments;
+
+let cache: TabGroupAssignments | null = null;
+let cacheOwnerKey: string | null = null;
+const subscribers = new Set<() => void>();
+let storageListenerWired = false;
+/** `${groupId}|${sessionId ?? ''}` → 组内上次激活的页签。 */
+const groupActive = new Map<string, string>();
+
+function ownerKey(): string {
+ return STORAGE_KEY_PREFIX + (getDataOwnerGeneration().dataOwnerId ?? 'none');
+}
+
+export function sanitizeTabGroupAssignments(raw: unknown): TabGroupAssignments {
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return EMPTY;
+ const out: Record<string, TabGroupId> = {};
+ let count = 0;
+ for (const [tabId, groupId] of Object.entries(raw as Record<string, unknown>)) {
+ if (!tabId || !isTabGroupId(groupId) || groupId === DEFAULT_TAB_GROUP) continue;
+ out[tabId] = groupId;
+ if (++count >= MAX_ENTRIES) break;
+ }
+ return out;
+}
+
+function load(): TabGroupAssignments {
+ try {
+ const raw = window.localStorage.getItem(ownerKey());
+ if (!raw) return EMPTY;
+ return sanitizeTabGroupAssignments(JSON.parse(raw));
+ } catch {
+ return EMPTY;
+ }
+}
+
+function notify(): void {
+ for (const cb of [...subscribers]) cb();
+}
+
+function ensureStorageListener(): void {
+ if (storageListenerWired || typeof window === 'undefined') return;
+ storageListenerWired = true;
+ window.addEventListener('storage', (event) => {
+ if (event.key !== null && event.key !== cacheOwnerKey) return;
+ cache = null;
+ notify();
+ });
+}
+
+export function getTabGroupAssignments(): TabGroupAssignments {
+ const key = ownerKey();
+ if (cache === null || cacheOwnerKey !== key) {
+ cache = load();
+ cacheOwnerKey = key;
+ ensureStorageListener();
+ }
+ return cache;
+}
+
+function persist(next: Record<string, TabGroupId>): void {
+ const key = ownerKey();
+ cache = next;
+ cacheOwnerKey = key;
+ try {
+ if (Object.keys(next).length === 0) window.localStorage.removeItem(key);
+ else window.localStorage.setItem(key, JSON.stringify(next));
+ } catch (err) {
+ log.warn('persist tab group assignments failed', { err });
+ }
+ notify();
+}
+
+/** 某页签所在的组;没有记录 = 右侧组。 */
+export function getTabGroup(tabId: string): TabGroupId {
+ return getTabGroupAssignments()[tabId] ?? DEFAULT_TAB_GROUP;
+}
+
+export function tabGroupOf(assignments: TabGroupAssignments, tabId: string): TabGroupId {
+ return assignments[tabId] ?? DEFAULT_TAB_GROUP;
+}
+
+/** 把页签放进某组。放回右侧组 = 删条目。超出上限时丢最早的条目。 */
+export function setTabGroup(tabId: string, groupId: TabGroupId): void {
+ const current = getTabGroupAssignments();
+ if (tabGroupOf(current, tabId) === groupId) return;
+ const next: Record<string, TabGroupId> = { ...current };
+ if (groupId === DEFAULT_TAB_GROUP) {
+ delete next[tabId];
+ } else {
+ delete next[tabId];
+ next[tabId] = groupId;
+ const keys = Object.keys(next);
+ for (let i = 0; keys.length - i > MAX_ENTRIES; i++) delete next[keys[i]];
+ }
+ persist(next);
+}
+
+/** 页签关闭:清掉它的组记录(没有记录时 no-op,不触发通知)。 */
+export function clearTabGroup(tabId: string): void {
+ const current = getTabGroupAssignments();
+ if (!(tabId in current)) return;
+ const next = { ...current };
+ delete next[tabId];
+ persist(next);
+}
+
+function activeKey(groupId: TabGroupId, sessionId: string | null): string {
+ return `${groupId}|${sessionId ?? ''}`;
+}
+
+/** 组内上次激活的页签(运行期记忆);没有返回 null。 */
+export function getGroupActiveTabId(groupId: TabGroupId, sessionId: string | null): string | null {
+ return groupActive.get(activeKey(groupId, sessionId)) ?? null;
+}
+
+export function setGroupActiveTabId(
+ groupId: TabGroupId,
+ sessionId: string | null,
+ tabId: string | null,
+): void {
+ const key = activeKey(groupId, sessionId);
+ const prev = groupActive.get(key) ?? null;
+ if (prev === tabId) return;
+ if (tabId === null) groupActive.delete(key);
+ else groupActive.set(key, tabId);
+ notify();
+}
+
+export function subscribeTabGroups(cb: () => void): () => void {
+ getTabGroupAssignments();
+ subscribers.add(cb);
+ return () => {
+ subscribers.delete(cb);
+ };
+}
+
+/** React hook:全部组归属(引用变化 = 有写入或跨窗口同步)。 */
+export function useTabGroupAssignments(): TabGroupAssignments {
+ return useSyncExternalStore(subscribeTabGroups, getTabGroupAssignments);
+}
+
+/** 右键菜单 / 入口文案的 i18n key。 */
+export function tabGroupLabelKey(groupId: TabGroupId): string {
+ return `rightSidebar.tabGroups.${groupId}`;
+}
+
+/** 仅测试用。 */
+export function __resetTabGroupsForTest(): void {
+ cache = null;
+ cacheOwnerKey = null;
+ subscribers.clear();
+ groupActive.clear();
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e0552dc4d5..a1e70efeb5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8046,7 +8046,8 @@
"close": "Close",
"closeOthers": "Close others",
"closeAll": "Close all",
- "openInWindow": "Open in a new window"
+ "openInWindow": "Open in a new window",
+ "moveTo": "Move to {{target}}"
},
"empty": {
"eyebrow": "Right Sidebar",
@@ -8069,6 +8070,12 @@
},
"placeholderHint": "{{kind}} — content coming in a later phase"
},
+ "tabGroups": {
+ "left": "left side",
+ "right": "right sidebar",
+ "top": "top",
+ "bottom": "bottom"
+ },
"fileBrowser": {
"noWorkdir": "This session has no local working directory; file browser unavailable",
"filterPlaceholder": "Filter files…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 21e98d5fff..1bc6e2127c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8014,7 +8014,8 @@
"close": "閉じる",
"closeOthers": "他のタブを閉じる",
"closeAll": "すべて閉じる",
- "openInWindow": "新しいウィンドウで開く"
+ "openInWindow": "新しいウィンドウで開く",
+ "moveTo": "{{target}}に移動"
},
"empty": {
"eyebrow": "右サイドバー",
@@ -8037,6 +8038,12 @@
},
"placeholderHint": "{{kind}} — コンテンツは後続フェーズで追加されます"
},
+ "tabGroups": {
+ "left": "左側",
+ "right": "右サイドバー",
+ "top": "上部",
+ "bottom": "下部"
+ },
"fileBrowser": {
"noWorkdir": "このセッションにローカル作業ディレクトリが関連付けられていないため、ファイルブラウザは利用できません",
"filterPlaceholder": "ファイルを絞り込み…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a0755ba93c..bbb6fab7d1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8014,7 +8014,8 @@
"close": "닫기",
"closeOthers": "다른 탭 닫기",
"closeAll": "모두 닫기",
- "openInWindow": "새 창에서 열기"
+ "openInWindow": "새 창에서 열기",
+ "moveTo": "{{target}}(으)로 이동"
},
"empty": {
"eyebrow": "오른쪽 사이드바",
@@ -8037,6 +8038,12 @@
},
"placeholderHint": "{{kind}} — 콘텐츠는 이후 단계에서 추가됩니다"
},
+ "tabGroups": {
+ "left": "왼쪽",
+ "right": "오른쪽 사이드바",
+ "top": "위쪽",
+ "bottom": "아래쪽"
+ },
"fileBrowser": {
"noWorkdir": "현재 세션에 로컬 작업 디렉터리가 연결되지 않아 파일 브라우저를 사용할 수 없습니다",
"filterPlaceholder": "파일 필터…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 9a5b511f20..d565b5b13c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8014,7 +8014,8 @@
"close": "关闭",
"closeOthers": "关闭其他",
"closeAll": "关闭所有",
- "openInWindow": "在独立窗口中打开"
+ "openInWindow": "在独立窗口中打开",
+ "moveTo": "移到{{target}}"
},
"empty": {
"eyebrow": "右侧栏",
@@ -8037,6 +8038,12 @@
},
"placeholderHint": "{{kind}} — 内容将在后续阶段加入"
},
+ "tabGroups": {
+ "left": "左侧",
+ "right": "右侧栏",
+ "top": "上方",
+ "bottom": "下方"
+ },
"fileBrowser": {
"noWorkdir": "当前任务未关联本地工作目录,文件浏览器不可用",
"filterPlaceholder": "筛选文件…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 95f7dc107b..fc517936ff 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8014,7 +8014,8 @@
"close": "關閉",
"closeOthers": "關閉其他",
"closeAll": "關閉所有",
- "openInWindow": "在獨立視窗中開啟"
+ "openInWindow": "在獨立視窗中開啟",
+ "moveTo": "移到{{target}}"
},
"empty": {
"eyebrow": "右側欄",
@@ -8037,6 +8038,12 @@
},
"placeholderHint": "{{kind}} — 內容將在後續階段加入"
},
+ "tabGroups": {
+ "left": "左側",
+ "right": "右側欄",
+ "top": "上方",
+ "bottom": "下方"
+ },
"fileBrowser": {
"noWorkdir": "當前任務未關聯本地工作目錄,檔案瀏覽器不可用",
"filterPlaceholder": "篩選檔案…",
diff --git a/apps/desktop/src/renderer/layout/LayoutRoot.tsx b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
index 626acd41e4..97a48e93e6 100644
--- a/apps/desktop/src/renderer/layout/LayoutRoot.tsx
+++ b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
@@ -4,6 +4,7 @@ import {
useMemo,
useRef,
useState,
+ useSyncExternalStore,
type CSSProperties,
type ReactNode,
type RefObject,
@@ -20,7 +21,12 @@ import {
import { installGhostDevTools } from '../cindy-brain/ghostDevTools';
import { ensureGhostPanelsRegistered, useGhostPanelsSync } from '../cindy-brain/ghostPanels';
import { registerBuiltinPanels } from '../panels/builtinPanels';
-import { getPanelKind, type PanelDefinition } from '../panels/registry';
+import {
+ getPanelKind,
+ getPanelRegistryVersion,
+ subscribePanelRegistry,
+ type PanelDefinition,
+} from '../panels/registry';
import { installLayoutDevTools } from './layoutDevTools';
import { PanelMaximizeContext, type PanelMaximizeState } from './panelMaximize';
import { PaneAtWindowTopProvider, PaneFillProvider } from './panePlacement';
@@ -67,6 +73,8 @@ const ROOT_WIDTH_SELF_HEAL_SETTLE_MS = 120;
* 不再参与拖缝钳制与渲染 clamp。
*/
const NON_CHAT_FLOOR_PX = 120;
+/** 聊天列里非聊天格的最小像素高(同宽度口径:只防拖丢,不是产品下限)。 */
+const GRID_PANE_MIN_HEIGHT_PX = 120;
/**
* pane 是否在本窗口渲染:未注册 kind(历史遗留的插件停靠面板 `ghost:*`、未安装
@@ -77,6 +85,16 @@ function isPanelKindVisible(kind: string): boolean {
return getPanelKind(kind) !== null;
}
+/**
+ * 该节点是不是「聊天区所在的根级区域」:聊天区自己,或包着它与上下页签组的
+ * `chat-column` 纵向分割。根横排里只有这一块是弹性的(flex-1 吸收剩余宽度),
+ * 其余根 child 按份额给像素宽;拖缝压缩聊天区的接力口径也以它为准。
+ */
+function containsChat(node: LayoutNode): boolean {
+ if (node.type === 'pane') return node.panelKind === 'chat-main';
+ return node.children.some((child) => containsChat(child.node));
+}
+
/** 单个 pane 的挂载点:查注册表渲染;不可见 kind = 隐藏(数据保留在树里)。 */
const PanelHost = memo(function PanelHost({
node,
@@ -163,6 +181,16 @@ function paneMinPx(node: LayoutNode): number {
: Math.max(NON_CHAT_FLOOR_PX, ...childMins);
}
+/** 聊天列里各格的最小像素高:聊天区保底一屏输入区,其余只防拖丢。 */
+const CHAT_MIN_HEIGHT_PX = 200;
+function paneMinHeightPx(node: LayoutNode): number {
+ if (node.type === 'pane') return node.panelKind === 'chat-main' ? CHAT_MIN_HEIGHT_PX : GRID_PANE_MIN_HEIGHT_PX;
+ const childMins = node.children.map((child) => paneMinHeightPx(child.node));
+ return node.direction === 'column'
+ ? childMins.reduce((sum, value) => sum + value, 0)
+ : Math.max(GRID_PANE_MIN_HEIGHT_PX, ...childMins);
+}
+
/**
* 布局自愈(纯函数):把"份额折算像素低于面板最小宽"的非 chat 面板份额抬到
* 最小宽对应值,差额由弹性的 chat 捐出;无需修正返回 null。
@@ -183,9 +211,7 @@ export function normalizeSubMinFractions(
): Layout | null {
if (layout.content.type !== 'split' || layout.content.direction !== 'row') return null;
const children = layout.content.children;
- const chatIndex = children.findIndex(
- (c) => c.node.type === 'pane' && c.node.panelKind === 'chat-main',
- );
+ const chatIndex = children.findIndex((c) => containsChat(c.node));
if (chatIndex < 0) return null;
const nodeIsRegistered = (node: LayoutNode): boolean =>
node.type === 'pane'
@@ -202,7 +228,7 @@ export function normalizeSubMinFractions(
const bumps = new Map<number, number>(); // treeIndex → 目标在场份额
children.forEach((child, index) => {
const node = child.node;
- if (node.type === 'pane' && node.panelKind === 'chat-main') return;
+ if (containsChat(node)) return;
if (!nodeIsRegistered(node)) return; // 隐藏面板/空 grid 不渲染,不参与自愈
const minShare = paneMinPx(node) / avail;
const share = child.fraction / scale;
@@ -241,7 +267,7 @@ function computeRootWidths(layout: Layout, live: Record<string, number> | null):
}
for (const entry of visibleSplitChildren(layout.content.children)) {
const node = entry.node;
- if (node.type === 'pane' && node.panelKind === 'chat-main') continue;
+ if (containsChat(node)) continue;
const share = live?.[node.id] ?? entry.share;
const min = paneMinPx(node);
// Resolve every consumer against the dedicated layout-content query container. A plain `%`
@@ -278,6 +304,8 @@ interface NodeViewProps {
atWindowTop?: boolean;
liveFractions: Record<string, number> | null;
maximizedKind: string | null;
+ /** 接管态(设置页):聊天列里只渲染聊天区,上下页签组连同横缝一起不画。 */
+ chatOnly?: boolean;
onLive: (live: Record<string, number> | null) => void;
onCommitted: (layout: Layout) => void;
}
@@ -289,6 +317,7 @@ function NodeView({
atWindowTop = true,
liveFractions,
maximizedKind,
+ chatOnly = false,
onLive,
onCommitted,
}: NodeViewProps): ReactNode {
@@ -305,7 +334,9 @@ function NodeView({
);
}
const ledger = activeSplitLedger(node.children);
- const visible = ledger.entries;
+ const visible = chatOnly
+ ? ledger.entries.filter((entry) => containsChat(entry.node))
+ : ledger.entries;
const items: ReactNode[] = [];
visible.forEach((entry, i) => {
const entryHasMaximized =
@@ -338,19 +369,21 @@ function NodeView({
const childAtWindowTop =
atWindowTop &&
(node.direction === 'row' || (maximizedKind !== null ? entryHasMaximized : i === 0));
+ // 接管态下列里只剩聊天区一格:撑满整列,不按旧份额留空。
+ const fillsColumn = entryHasMaximized || (chatOnly && visible.length === 1);
items.push(
<div
key={entry.node.id}
data-layout-node-id={entry.node.id}
className={`flex min-h-0 min-w-0 overflow-hidden ${
node.direction === 'column' ? 'w-full flex-col' : 'h-full flex-row'
- } ${entryHasMaximized ? 'flex-1' : 'flex-none'}`}
+ } ${fillsColumn ? 'flex-1' : 'flex-none'}`}
style={
hiddenByMaximize
? node.direction === 'column'
? { height: 0 }
: { width: 0 }
- : entryHasMaximized
+ : fillsColumn
? undefined
: { flexBasis: `${share * 100}%` }
}
@@ -361,6 +394,7 @@ function NodeView({
atWindowTop={childAtWindowTop}
liveFractions={liveFractions}
maximizedKind={maximizedKind}
+ chatOnly={chatOnly}
onLive={onLive}
onCommitted={onCommitted}
/>
@@ -412,9 +446,6 @@ interface RelayPlan {
receiver: number;
}
-function isChatPane(node: LayoutNode): boolean {
- return node.type === 'pane' && node.panelKind === 'chat-main';
-}
/** 起拖时实测某布局节点的宽;split 量自己的 grid 列壳,pane 量标准拖拽根。 */
function measuredPanePx(node: LayoutNode): number | null {
@@ -582,7 +613,7 @@ function RootDivider({
const startL = alignedLeft?.share ?? left.share;
const startR = alignedRight?.share ?? right.share;
// 起拖只量一次(拖动期间界面静止,没有失效场景);chat 量不到时回落账本估值。
- const chatEntry = isChatPane(left.node) ? left : isChatPane(right.node) ? right : null;
+ const chatEntry = containsChat(left.node) ? left : containsChat(right.node) ? right : null;
const shrinkPlan = chatEntry
? chatShrinkPlan(chatEntry, chatEntry === left ? right : left, available)
: null;
@@ -634,7 +665,7 @@ function RootDivider({
: measuredAvailable > 0
? measuredAvailable
: AVAILABLE_WIDTH_FALLBACK;
- const chatEntry = isChatPane(left.node) ? left : isChatPane(right.node) ? right : null;
+ const chatEntry = containsChat(left.node) ? left : containsChat(right.node) ? right : null;
const plan = chatEntry
? chatShrinkPlan(chatEntry, chatEntry === left ? right : left, available)
: null;
@@ -671,8 +702,6 @@ function RootDivider({
);
}
-const GRID_PANE_MIN_HEIGHT_PX = 120;
-
interface ColumnDividerProps {
splitId: string;
top: SplitChildEntry;
@@ -725,14 +754,14 @@ function ColumnDivider({
const topRoom = Math.max(
0,
Math.min(
- startTop - GRID_PANE_MIN_HEIGHT_PX / available,
+ startTop - paneMinHeightPx(top.node) / available,
shareScale > 0 ? (top.fraction - MIN_SPLIT_CHILD_FRACTION) / shareScale : 0,
),
);
const bottomRoom = Math.max(
0,
Math.min(
- startBottom - GRID_PANE_MIN_HEIGHT_PX / available,
+ startBottom - paneMinHeightPx(bottom.node) / available,
shareScale > 0 ? (bottom.fraction - MIN_SPLIT_CHILD_FRACTION) / shareScale : 0,
),
);
@@ -816,7 +845,10 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
installGhostDevTools();
// 装/卸广播 → 注册表对齐 + 重渲(卸下不动布局树,靠这里让引擎重过滤在场面板)。
- const ghostSyncVersion = useGhostPanelsSync();
+ useGhostPanelsSync();
+ // 注册表版本:页签组 pane 的 kind 随「组里有没有页签」动态注册 / 注销,引擎按它
+ // 重过滤在场面板(插件装卸也经注册表,统一走这一个信号)。
+ const ghostSyncVersion = useSyncExternalStore(subscribePanelRegistry, getPanelRegistryVersion);
// 首帧同步读取(sendSync):布局在第一帧就位,不出现默认布局闪现。
const [layout, setLayout] = useState<Layout>(
@@ -898,9 +930,7 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
// root split 扁平化(见文件头注释):children(含交互式分割线)直接作为父 row
// 容器的 flex 子项。接管态只留 chat-main(见 LayoutRootProps)。
const ledger = activeSplitLedger(content.children);
- const visible = ledger.entries.filter(
- (e) => !suppressNonChatPanels || (e.node.type === 'pane' && e.node.panelKind === 'chat-main'),
- );
+ const visible = ledger.entries.filter((e) => !suppressNonChatPanels || containsChat(e.node));
// 撑满态:目标 pane 独占一行(自身经 PanelMaximizeContext 切成 flex-1),
// 兄弟收成 0 宽裁切 —— 保持挂载不动 display:webview 卸载丢 webContents,
// display:none 对 webview 也不友好;分割线整组不画。树账本(fraction/顺序)
@@ -984,18 +1014,26 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
}
}
if (entry.node.type === 'split' && content.direction === 'row') {
+ // 聊天列(chat-main + 上下页签组)是根横排里唯一的弹性区域:flex-1 吸收剩余
+ // 宽,与聊天区单独在根里时同一口径;其它嵌套分割按份额给像素宽。
+ const elastic = containsChat(entry.node);
items.push(
<div
key={entry.node.id}
data-layout-root-child-id={entry.node.id}
- className="flex h-full min-h-0 min-w-0 flex-none overflow-hidden"
- style={{ width: rootWidths.splitWidths[entry.node.id] }}
+ className={
+ elastic
+ ? 'flex h-full min-h-0 min-w-[400px] flex-1 overflow-hidden'
+ : 'flex h-full min-h-0 min-w-0 flex-none overflow-hidden'
+ }
+ style={elastic ? undefined : { width: rootWidths.splitWidths[entry.node.id] }}
>
<NodeView
node={entry.node}
fillPane
liveFractions={liveFractions}
maximizedKind={null}
+ chatOnly={suppressNonChatPanels}
onLive={setLiveFractions}
onCommitted={setLayout}
/>
diff --git a/apps/desktop/src/renderer/layout/PanelDragController.tsx b/apps/desktop/src/renderer/layout/PanelDragController.tsx
index ebdb367f9f..4982e64997 100644
--- a/apps/desktop/src/renderer/layout/PanelDragController.tsx
+++ b/apps/desktop/src/renderer/layout/PanelDragController.tsx
@@ -9,10 +9,10 @@
* 已知边界:网页(webview)/独立进程区域宿主收不到按压事件,长按在那里
* 天然无效(平台机制)——标准头手势是这类面板的主入口。
*
- * 交互语义(drop-zone 式):**拖动过程不改树**。插件拖到另一个插件的上/下边缘
- * 形成纵向 grid,拖到任一根级区域的左/右边缘回到横排,中心保持交换;内置
- * chat/right-tabs 只参加根级交换,不进入插件 column。高亮罩严格显示最终占位的
- * 半区或整块区域,松手才一次性 layout.set 持久化;Esc / 无高亮松手 = 取消。
+ * 交互语义(drop-zone 式):**拖动过程不改树**。拖到另一块根级区域身上 = 两块
+ * 根级区域换位(聊天区所在的列整体跟着走,上下页签组随聊天区移动);高亮罩显示
+ * 最终占位的整块区域,松手才一次性 layout.set 持久化;Esc / 无高亮松手 = 取消。
+ * 边组(`tab-group:*`)不作为拖拽源:它们的位置由组名决定,搬的是页签不是面板。
*
* 性能口径(按 Lizi "卡手"反馈定型):pointermove 热路径**零 React 渲染、零
* 布局读取**——边界几何在起拖时量一次缓存(拖动期间不换位,界面静止,没有
@@ -31,13 +31,7 @@ import { useEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
-import {
- moveGhostPaneToRootByKind,
- stackGhostPaneByKind,
- swapPanesByKind,
- swapRootSplitChildrenByKind,
- type LayoutNode,
-} from '../../shared/layoutTree';
+import { swapRootSplitChildrenByKind, type LayoutNode } from '../../shared/layoutTree';
import { toast } from '@/lib/toast';
/** 长按窗体:按住该时长(ms)且位移小于容差才"浮起"。 */
@@ -127,72 +121,30 @@ interface ZoneRect {
height: number;
}
-export type PanelDropIntent =
- 'swap' | 'stack-before' | 'stack-after' | 'root-before' | 'root-after';
+export type PanelDropIntent = 'swap';
interface RectLike extends ZoneRect {
right: number;
bottom: number;
}
-const GRID_EDGE_RATIO = 0.28;
-
function pointInRect(x: number, y: number, rect: RectLike): boolean {
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
}
/**
- * 二维停靠意图:插件之间上/下形成 grid,左/右回到根横排,中心交换槽位。
- * 内置面板保持根级交换;落在插件纵向列时交换整列,不把内置面板塞进列内。
+ * 落点意图:指针落在另一块根级区域里 → 两块根级区域换位。同一根级区域(例如
+ * 聊天列里的上下页签组)之间没有新的布局含义,返回 null。
*/
export function computePanelDropIntent(input: {
pointerX: number;
pointerY: number;
paneRect: RectLike;
- rootRect: RectLike;
- sourceKind: string;
- targetKind: string;
sourceRootIndex: number;
targetRootIndex: number;
- sourceIsRootPane: boolean;
- targetIsRootPane: boolean;
}): PanelDropIntent | null {
- const { pointerX, pointerY, paneRect, sourceKind, targetKind } = input;
- if (!pointInRect(pointerX, pointerY, paneRect)) return null;
- const sourceGhost = sourceKind.startsWith('ghost:');
- const targetGhost = targetKind.startsWith('ghost:');
- if (!sourceGhost) {
- return input.sourceIsRootPane && input.sourceRootIndex !== input.targetRootIndex
- ? 'swap'
- : null;
- }
-
- const nx = paneRect.width > 0 ? (pointerX - paneRect.left) / paneRect.width : 0.5;
- const ny = paneRect.height > 0 ? (pointerY - paneRect.top) / paneRect.height : 0.5;
- const edgeCandidates: Array<{ distance: number; intent: PanelDropIntent }> = [
- { distance: nx, intent: 'root-before' },
- { distance: 1 - nx, intent: 'root-after' },
- ];
- if (targetGhost) {
- edgeCandidates.push(
- { distance: ny, intent: 'stack-before' },
- { distance: 1 - ny, intent: 'stack-after' },
- );
- }
- const nearest = edgeCandidates.sort((a, b) => a.distance - b.distance)[0];
- if (nearest && nearest.distance <= GRID_EDGE_RATIO) return nearest.intent;
-
- // 嵌套插件只能和插件交换,避免把 chat/right-tabs 换进 ghost-only 的 column。
- if (
- targetGhost ||
- (input.sourceIsRootPane &&
- input.targetIsRootPane &&
- input.sourceRootIndex !== input.targetRootIndex)
- ) {
- return 'swap';
- }
- // 同一 root 区域的中心没有新的布局含义。
- return null;
+ if (!pointInRect(input.pointerX, input.pointerY, input.paneRect)) return null;
+ return input.sourceRootIndex !== input.targetRootIndex ? 'swap' : null;
}
function insetRect(rect: RectLike): RectLike {
@@ -203,29 +155,10 @@ function insetRect(rect: RectLike): RectLike {
return { left, top, width, height, right: left + width, bottom: top + height };
}
-export function computePanelDropZone(
- intent: PanelDropIntent,
- paneRect: RectLike,
- rootRect: RectLike,
- swapAtRoot = false,
-): ZoneRect {
- const base = insetRect(
- intent === 'root-before' || intent === 'root-after' || (intent === 'swap' && swapAtRoot)
- ? rootRect
- : paneRect,
- );
- switch (intent) {
- case 'stack-before':
- return { ...base, height: base.height / 2 };
- case 'stack-after':
- return { ...base, top: base.top + base.height / 2, height: base.height / 2 };
- case 'root-before':
- return { ...base, width: base.width / 2 };
- case 'root-after':
- return { ...base, left: base.left + base.width / 2, width: base.width / 2 };
- case 'swap':
- return base;
- }
+/** 高亮整块根级区域(聊天列时是整列,而不是列里的单个 pane)。 */
+export function computePanelDropZone(rootRect: RectLike): ZoneRect {
+ const base = insetRect(rootRect);
+ return { left: base.left, top: base.top, width: base.width, height: base.height };
}
/** 单个可落靶面板:pane 与其根级区域几何均在起拖时缓存。 */
@@ -234,7 +167,6 @@ interface DropTarget {
paneRect: RectLike;
rootRect: RectLike;
rootIndex: number;
- isRootPane: boolean;
}
/** 起拖时一次性缓存的几何:全部可落靶面板(N 面板,拖到谁身上就和谁换位)。 */
@@ -278,7 +210,6 @@ export function PanelDragController({
// 拖动期间树不变,热路径无需再次读取布局。
const targets: DropTarget[] = [];
let sourceRootIndex = -1;
- let sourceIsRootPane = false;
try {
const layout = window.electronAPI.layout.getStateSync().layout;
if (layout.content.type !== 'split' || layout.content.direction !== 'row') return;
@@ -290,7 +221,6 @@ export function PanelDragController({
paneKinds(child.node).includes(sourceKind),
);
if (sourceRootIndex < 0) return;
- sourceIsRootPane = layout.content.children[sourceRootIndex].node.type === 'pane';
layout.content.children.forEach((rootChild, rootIndex) => {
const kinds = paneKinds(rootChild.node);
@@ -310,6 +240,8 @@ export function PanelDragController({
};
kinds.forEach((kind) => {
if (kind === sourceKind) return;
+ // 边组不参与换位(位置由组名决定),既不做源也不做落点。
+ if (kind.startsWith('tab-group:')) return;
const el = document.querySelector(`[data-panel-drag-root="${kind}"]`);
if (!el) return; // 未注册(隐藏)的 kind 没有 DOM,自然不可落靶
const rect = el.getBoundingClientRect();
@@ -328,7 +260,6 @@ export function PanelDragController({
},
rootRect,
rootIndex,
- isRootPane: rootChild.node.type === 'pane',
});
});
});
@@ -369,13 +300,8 @@ export function PanelDragController({
pointerX: e.clientX,
pointerY: e.clientY,
paneRect: target.paneRect,
- rootRect: target.rootRect,
- sourceKind,
- targetKind: target.kind,
sourceRootIndex,
targetRootIndex: target.rootIndex,
- sourceIsRootPane,
- targetIsRootPane: target.isRootPane,
});
if (!intent) continue;
nextTarget = target;
@@ -388,15 +314,7 @@ export function PanelDragController({
targetIntentNow = nextIntent;
setDrag({
targetKind: nextKind,
- zone:
- nextTarget && nextIntent
- ? computePanelDropZone(
- nextIntent,
- nextTarget.paneRect,
- nextTarget.rootRect,
- nextIntent === 'swap' && !sourceKind.startsWith('ghost:'),
- )
- : null,
+ zone: nextTarget && nextIntent ? computePanelDropZone(nextTarget.rootRect) : null,
});
}
};
@@ -417,24 +335,7 @@ export function PanelDragController({
if (opts.commit && targetKindNow && targetIntentNow) {
try {
const layout = window.electronAPI.layout.getStateSync().layout;
- const op =
- targetIntentNow === 'stack-before' || targetIntentNow === 'stack-after'
- ? stackGhostPaneByKind(
- layout,
- sourceKind,
- targetKindNow,
- targetIntentNow === 'stack-before' ? 'before' : 'after',
- )
- : targetIntentNow === 'root-before' || targetIntentNow === 'root-after'
- ? moveGhostPaneToRootByKind(
- layout,
- sourceKind,
- targetKindNow,
- targetIntentNow === 'root-before' ? 'before' : 'after',
- )
- : sourceKind.startsWith('ghost:')
- ? swapPanesByKind(layout, sourceKind, targetKindNow)
- : swapRootSplitChildrenByKind(layout, sourceKind, targetKindNow);
+ const op = swapRootSplitChildrenByKind(layout, sourceKind, targetKindNow);
if (op.applied) {
void window.electronAPI.layout
.set(op.layout)
@@ -490,6 +391,8 @@ export function PanelDragController({
// 标记值即面板身份(chat-main / right-tabs),两块都可拖、都往对面半区落。
const sourceKind = root.getAttribute('data-panel-drag-root');
if (!sourceKind) return;
+ // 边组的位置由组名决定(左 / 上 / 下),不作为换位拖拽源;搬页签走页签拖拽。
+ if (sourceKind.startsWith('tab-group:')) return;
if (target.closest('[data-rsb-resize-handle]')) return; // 拖宽把手让路
const startX = e.clientX;
diff --git a/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx b/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
index 7f4e622dbd..2ad4785f65 100644
--- a/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
+++ b/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
@@ -307,6 +307,67 @@ describe('LayoutRoot · 树驱动的顺序与在场', () => {
expect(screen.getAllByTestId('layout-divider')).toHaveLength(3);
});
+ // 测试价值
+ // - 生产入口与可观察结果:LayoutRoot 渲染「聊天列」(chat-main 与上下页签组同在一层
+ // column split);可观察的是聊天列作为根级弹性区域(flex-1、不吃像素宽)、列内有横缝、
+ // 下方页签组填满格;接管态(设置页)只剩聊天区且撑满整列。
+ // - Bug / 规则依据:页签组可停在聊天区上 / 下边(页签组模型);根横排里只有包着聊天区
+ // 的那块是弹性的,否则聊天列会按份额被钉成固定宽、页签组在设置页冒出来。
+ // - 现有覆盖缺口:此前 column split 只有插件 grid 用例,聊天区从不在列里。
+ // - 最小失败输入:chat-column{chat-main, tab-group:bottom} + right-tabs。
+ // - tier:unit(jsdom)。
+ it('聊天列:chat-main 与下方页签组同列,列是根级弹性区域;接管态只剩聊天区', () => {
+ registerPanelKind({
+ kind: 'tab-group:bottom',
+ Component: () => <div data-testid="p-bottom" data-fill={String(usePaneFill())} />,
+ collapseMemory: 'none',
+ });
+ currentLayout = {
+ ...createDefaultLayout(),
+ content: {
+ type: 'split',
+ id: 'root',
+ direction: 'row',
+ children: [
+ {
+ fraction: 0.7,
+ node: {
+ type: 'split',
+ id: 'chat-column',
+ direction: 'column',
+ children: [
+ { fraction: 0.65, node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 } },
+ { fraction: 0.35, node: { type: 'pane', id: 'tab-group-bottom', panelKind: 'tab-group:bottom' } },
+ ],
+ },
+ },
+ { fraction: 0.3, node: { type: 'pane', id: 'right', panelKind: 'right-tabs' } },
+ ],
+ },
+ };
+ const rendered = renderLayoutRoot();
+ const column = document.querySelector<HTMLElement>('[data-layout-root-child-id="chat-column"]');
+ expect(column).not.toBeNull();
+ expect(column!.className).toContain('flex-1');
+ expect(column!.style.width).toBe('');
+ expect(screen.getByTestId('p-chat')).toBeTruthy();
+ expect(screen.getByTestId('p-bottom').getAttribute('data-fill')).toBe('true');
+ // 列内一条横缝 + 根级一条竖缝。
+ expect(screen.getAllByTestId('layout-divider')).toHaveLength(2);
+
+ rendered.rerender(
+ <BuiltinPanelBridgeProvider value={bridge}>
+ <div data-testid="row">
+ <LayoutRoot suppressNonChatPanels />
+ </div>
+ </BuiltinPanelBridgeProvider>,
+ );
+ expect(screen.queryByTestId('p-bottom')).toBeNull();
+ expect(screen.queryByTestId('p-right')).toBeNull();
+ expect(screen.getByTestId('p-chat')).toBeTruthy();
+ expect(screen.queryAllByTestId('layout-divider')).toHaveLength(0);
+ });
+
it('插件重新注册但布局树未变化时,恢复 grid 列', () => {
currentLayout = {
...createDefaultLayout(),
@@ -341,10 +402,13 @@ describe('LayoutRoot · 树驱动的顺序与在场', () => {
const rendered = renderLayoutRoot();
expect(document.querySelector('[data-layout-root-child-id="grid-restored"]')).toBeNull();
- registerPanelKind({
- kind: 'ghost:restored',
- Component: () => <div data-testid="restored-panel" />,
- collapseMemory: 'global',
+ // 注册表变更会同步通知 LayoutRoot(页签组 pane 动态注册走同一信号),包进 act。
+ act(() => {
+ registerPanelKind({
+ kind: 'ghost:restored',
+ Component: () => <div data-testid="restored-panel" />,
+ collapseMemory: 'global',
+ });
});
ghostPanelSyncMock.version += 1;
rendered.rerender(
@@ -389,10 +453,12 @@ describe('LayoutRoot · 树驱动的顺序与在场', () => {
expect(screen.getByTestId('updated-panel').textContent).toBe('before');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
- registerPanelKind({
- kind: 'ghost:updated',
- Component: () => <div data-testid="updated-panel">after</div>,
- collapseMemory: 'global',
+ act(() => {
+ registerPanelKind({
+ kind: 'ghost:updated',
+ Component: () => <div data-testid="updated-panel">after</div>,
+ collapseMemory: 'global',
+ });
});
expect(warn).toHaveBeenCalledWith(
'[panels] duplicate registration overwrites kind: ghost:updated',
diff --git a/apps/desktop/src/renderer/layout/__tests__/panelDragController.test.ts b/apps/desktop/src/renderer/layout/__tests__/panelDragController.test.ts
index d1197318fb..81b7973a5e 100644
--- a/apps/desktop/src/renderer/layout/__tests__/panelDragController.test.ts
+++ b/apps/desktop/src/renderer/layout/__tests__/panelDragController.test.ts
@@ -64,103 +64,42 @@ describe('isDroppableRect', () => {
});
});
-describe('插件面板二维停靠落点', () => {
- const paneRect = {
- left: 100,
- top: 100,
- width: 400,
- height: 600,
- right: 500,
- bottom: 700,
- };
- const rootRect = paneRect;
- const base = {
- paneRect,
- rootRect,
- sourceKind: 'ghost:alpha',
- targetKind: 'ghost:beta',
- sourceRootIndex: 0,
- targetRootIndex: 1,
- sourceIsRootPane: true,
- targetIsRootPane: true,
- };
+describe('根级区域换位落点', () => {
+ const paneRect = { left: 100, top: 100, width: 400, height: 600, right: 500, bottom: 700 };
- it('插件拖到目标上/下边缘 → 形成纵向 grid', () => {
- expect(computePanelDropIntent({ ...base, pointerX: 300, pointerY: 110 })).toBe('stack-before');
- expect(computePanelDropIntent({ ...base, pointerX: 300, pointerY: 690 })).toBe('stack-after');
- });
-
- it('插件拖到目标左/右边缘 → 回到根横排', () => {
- expect(computePanelDropIntent({ ...base, pointerX: 105, pointerY: 400 })).toBe('root-before');
- expect(computePanelDropIntent({ ...base, pointerX: 495, pointerY: 400 })).toBe('root-after');
- });
-
- it('插件拖到目标中心 → 交换槽位', () => {
- expect(computePanelDropIntent({ ...base, pointerX: 300, pointerY: 400 })).toBe('swap');
- });
-
- it('内置面板与根 pane 或整个插件 column 做根级交换', () => {
+ it('指针落在另一块根级区域里 → swap;同一根级区域(聊天列内)或矩形外 → null', () => {
expect(
computePanelDropIntent({
- ...base,
pointerX: 300,
pointerY: 400,
- sourceKind: 'chat-main',
- targetKind: 'right-tabs',
+ paneRect,
+ sourceRootIndex: 0,
+ targetRootIndex: 1,
}),
).toBe('swap');
expect(
computePanelDropIntent({
- ...base,
pointerX: 300,
pointerY: 400,
- sourceKind: 'chat-main',
- targetIsRootPane: false,
+ paneRect,
+ sourceRootIndex: 1,
+ targetRootIndex: 1,
}),
- ).toBe('swap');
+ ).toBeNull();
expect(
computePanelDropIntent({
- ...base,
- pointerX: 300,
+ pointerX: 50,
pointerY: 400,
- sourceKind: 'chat-main',
- sourceRootIndex: 1,
+ paneRect,
+ sourceRootIndex: 0,
targetRootIndex: 1,
- targetIsRootPane: false,
}),
).toBeNull();
});
- it('纵向列里的插件可从内置区域左右边缘抽回横排,但中心不交换', () => {
- const nestedSource = {
- ...base,
- sourceIsRootPane: false,
- targetKind: 'chat-main',
- };
- expect(computePanelDropIntent({ ...nestedSource, pointerX: 105, pointerY: 400 })).toBe(
- 'root-before',
- );
- expect(computePanelDropIntent({ ...nestedSource, pointerX: 300, pointerY: 400 })).toBeNull();
- });
-
- it('高亮区域与停靠方向一致:上下/左右各占目标一半', () => {
- expect(computePanelDropZone('stack-before', paneRect, rootRect)).toMatchObject({
- left: 106,
- top: 106,
- width: 388,
- height: 294,
- });
- expect(computePanelDropZone('root-after', paneRect, rootRect)).toMatchObject({
- left: 300,
- top: 106,
- width: 194,
- height: 588,
- });
- });
-
- it('内置面板交换插件 grid 时高亮整个根级列,而不是单个插件 pane', () => {
+ it('高亮整块根级区域(聊天列时是整列,不是列里的单个 pane),四边内缩 6px', () => {
const columnRect = { left: 80, top: 80, width: 440, height: 640, right: 520, bottom: 720 };
- expect(computePanelDropZone('swap', paneRect, columnRect, true)).toMatchObject({
+ expect(computePanelDropZone(columnRect)).toEqual({
left: 86,
top: 86,
width: 428,
diff --git a/apps/desktop/src/renderer/panels/registry.ts b/apps/desktop/src/renderer/panels/registry.ts
index 5bf5017658..ed9b1d98d5 100644
--- a/apps/desktop/src/renderer/panels/registry.ts
+++ b/apps/desktop/src/renderer/panels/registry.ts
@@ -37,6 +37,18 @@ export interface PanelDefinition {
}
const registry = new Map<string, PanelDefinition>();
+/**
+ * 注册表版本与订阅:页签组 pane 的 kind 随「组里有没有页签」动态注册 / 注销
+ * (features/right-sidebar/tabGroupPanes.ts),布局引擎靠订阅感知在场面板变化,
+ * 不再只依赖插件装卸广播。
+ */
+let version = 0;
+const subscribers = new Set<() => void>();
+
+function bump(): void {
+ version += 1;
+ for (const cb of [...subscribers]) cb();
+}
/**
* 注册一种面板。重复注册同 kind 采取"覆盖 + dev 告警"而非抛错 —— 注册走
@@ -48,6 +60,7 @@ export function registerPanelKind(definition: PanelDefinition): void {
console.warn(`[panels] duplicate registration overwrites kind: ${definition.kind}`);
}
registry.set(definition.kind, definition);
+ bump();
}
/**
@@ -55,7 +68,20 @@ export function registerPanelKind(definition: PanelDefinition): void {
* "未安装意识"隐藏 —— 树数据保留,重装即原位复活。幂等。
*/
export function unregisterPanelKind(kind: PanelKind): void {
- registry.delete(kind);
+ if (registry.delete(kind)) bump();
+}
+
+/** 注册表变更订阅(注册 / 注销都会通知);返回退订函数。 */
+export function subscribePanelRegistry(cb: () => void): () => void {
+ subscribers.add(cb);
+ return () => {
+ subscribers.delete(cb);
+ };
+}
+
+/** 单调递增的注册表版本:放进 memo / effect deps 即可感知在场面板变化。 */
+export function getPanelRegistryVersion(): number {
+ return version;
}
/** 查面板定义;未注册(如未安装的意识)返回 null,由调用方决定隐藏策略。 */
@@ -75,4 +101,6 @@ export function listPanelKinds(): string[] {
/** 仅测试用:清空注册表,保证用例间隔离。 */
export function __resetPanelRegistryForTest(): void {
registry.clear();
+ subscribers.clear();
+ version = 0;
}
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index bf0e43d396..dd1e3f4eb3 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -38,7 +38,6 @@ import {
isBrokerEligibleGhostId,
isFirstPartyHostPrivilegeGhostId,
isValidGhostNetworkHostPattern,
- layoutWithGhostPanel,
parseGhostPartition,
resolveGhostManifestLocale,
validateGhostManifest,
@@ -47,7 +46,6 @@ import {
withGhostResolvedLocale,
type GhostManifest,
} from '../ghost';
-import { createDefaultLayout, type SplitNode } from '../layoutTree';
/** 一份全绿的清单基底(意识唯一形态:芯片,2026-07-12 单形态定案),单点破坏它来测各字段规则。 */
function goodManifest(): Record<string, unknown> {
@@ -1837,83 +1835,6 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {
});
});
-describe('ghost · layoutWithGhostPanel(装入即停靠)', () => {
- const manifest = (): GhostManifest => ({
- schemaVersion: 2,
- id: 'hello',
- name: 'Hello 意识',
- version: '1.0.0',
- kind: 'chip',
- entry: 'main.js',
- slots: ['panel'],
- panel: { html: 'panel.html', minWidth: 240, defaultFraction: 0.18 },
- });
-
- it('新装缺省 position:停在主聊天窗左侧(right 退役,2026-07-25 定案)', () => {
- const next = layoutWithGhostPanel(createDefaultLayout(), manifest());
- expect(next).not.toBeNull();
- const split = next!.content as SplitNode;
- expect(split.children.map((c) => (c.node.type === 'pane' ? c.node.panelKind : '?'))).toEqual([
- 'ghost:hello',
- 'chat-main',
- 'right-tabs',
- ]);
- const pane = split.children[0];
- expect(pane.fraction).toBeCloseTo(0.18, 5);
- expect(pane.node.type === 'pane' && pane.node.minWidth).toBe(240);
- // 全体份额仍归一
- expect(split.children.reduce((s, c) => s + c.fraction, 0)).toBeCloseTo(1, 5);
- });
-
- it("position: 'left' → 停在主聊天窗左侧(chat-main 之前)", () => {
- const m = manifest();
- m.panel!.position = 'left';
- const next = layoutWithGhostPanel(createDefaultLayout(), m);
- const split = next!.content as SplitNode;
- expect(split.children.map((c) => (c.node.type === 'pane' ? c.node.panelKind : '?'))).toEqual([
- 'ghost:hello',
- 'chat-main',
- 'right-tabs',
- ]);
- });
-
- it('重装:树上已有同 kind 的 pane → 返回 null(位置记忆保留,原位复活)', () => {
- const first = layoutWithGhostPanel(createDefaultLayout(), manifest());
- expect(layoutWithGhostPanel(first!, manifest())).toBeNull();
- });
-
- it('没声明面板的意识 → null,树不动', () => {
- const m = manifest();
- delete m.panel;
- expect(layoutWithGhostPanel(createDefaultLayout(), m)).toBeNull();
- });
-
- it('清单未给 defaultFraction → 默认 0.2', () => {
- const m = manifest();
- delete m.panel!.defaultFraction;
- const next = layoutWithGhostPanel(createDefaultLayout(), m);
- // 缺省 position=left,面板在 chat-main 之前(下标 0)。
- expect((next!.content as SplitNode).children[0].fraction).toBeCloseTo(0.2, 5);
- });
-
- it("position: 'tab' → null,不进布局树(页签形态由右侧栏承载)", () => {
- const m = manifest();
- m.panel = { html: 'panel.html', position: 'tab' };
- expect(layoutWithGhostPanel(createDefaultLayout(), m)).toBeNull();
- });
- it('企业实例用 storage part 作为 panelKind,不与 root 同名面板撞车', () => {
- const m = manifest();
- const rootLayout = layoutWithGhostPanel(createDefaultLayout(), m);
- expect(rootLayout).not.toBeNull();
- const next = layoutWithGhostPanel(rootLayout!, m, '_ns__acme__hello');
- expect(next).not.toBeNull();
- const split = next!.content as SplitNode;
- const kinds = split.children.map((c) => (c.node.type === 'pane' ? c.node.panelKind : '?'));
- expect(kinds).toEqual(expect.arrayContaining(['ghost:hello', 'ghost:_ns__acme__hello', 'chat-main']));
- });
-
-});
-
describe('ghost · keywords(语义触发扩展词表)', () => {
function chipWithKeywords(keywords: unknown): Record<string, unknown> {
return {
diff --git a/apps/desktop/src/shared/__tests__/layoutTree.test.ts b/apps/desktop/src/shared/__tests__/layoutTree.test.ts
index 25d3e7908b..faac3bce37 100644
--- a/apps/desktop/src/shared/__tests__/layoutTree.test.ts
+++ b/apps/desktop/src/shared/__tests__/layoutTree.test.ts
@@ -1,28 +1,29 @@
import { describe, expect, it } from 'vitest';
import {
- LAYOUT_SCHEMA_VERSION,
- MAX_TREE_DEPTH,
coerceLayout,
countPanelKind,
createDefaultLayout,
- createDefaultLayoutPreservingGhostPanels,
+ ensureTabGroupPane,
findPaneById,
findSplitChildByPanelKind,
insertRootSplitPane,
- moveGhostPaneToRootByKind,
+ LAYOUT_SCHEMA_VERSION,
+ MAX_TREE_DEPTH,
removeRootSplitPaneByKind,
- stackGhostPaneByKind,
- swapPanesByKind,
+ setPaneCollapsed,
+ setSplitChildFraction,
swapRootSplitChildrenByKind,
+ TAB_GROUP_IDS,
+ tabGroupIdFromPanelKind,
+ tabGroupPanelKind,
transferSplitFraction,
transferSplitFractionRelay,
- setPaneCollapsed,
- setSplitChildFraction,
validateLayout,
walkPanes,
type Layout,
type LayoutNode,
+ type PaneNode,
type SplitNode,
} from '../layoutTree';
@@ -54,47 +55,6 @@ describe('createDefaultLayout', () => {
});
});
-describe('createDefaultLayoutPreservingGhostPanels', () => {
- it('恢复内置默认排列时保留意识面板槽位、相对顺序与最小宽度', () => {
- const first = insertRootSplitPane(
- createDefaultLayout(),
- { id: 'custom-a', panelKind: 'ghost:alpha', minWidth: 280 },
- { index: 0, fraction: 0.25 },
- );
- const second = insertRootSplitPane(
- first.layout,
- { id: 'custom-b', panelKind: 'ghost:beta' },
- { index: 1, fraction: 0.15 },
- );
- expect(first.applied).toBe(true);
- expect(second.applied).toBe(true);
-
- const restored = createDefaultLayoutPreservingGhostPanels(second.layout);
- const children = (restored.content as SplitNode).children;
- expect(children.map((child) => child.node.type === 'pane' && child.node.panelKind)).toEqual([
- 'ghost:alpha',
- 'ghost:beta',
- 'chat-main',
- 'right-tabs',
- ]);
- expect(children[0].node).toMatchObject({
- id: 'ghost-alpha',
- panelKind: 'ghost:alpha',
- minWidth: 280,
- });
- expect(children[2].fraction).toBeCloseTo(children[3].fraction);
- expect(children.reduce((sum, child) => sum + child.fraction, 0)).toBeCloseTo(1);
- expect(validateLayout(restored)).toEqual({ ok: true });
- expect((second.layout.content as SplitNode).children[0].node).toMatchObject({ id: 'custom-a' });
- });
-
- it('没有意识面板时严格返回内置默认布局', () => {
- const current = createDefaultLayout();
- (current.content as SplitNode).children.reverse();
- expect(createDefaultLayoutPreservingGhostPanels(current)).toEqual(createDefaultLayout());
- });
-});
-
describe('validateLayout · 结构性不变量', () => {
it('chat-main 缺失被拒', () => {
const layout = makeLayout((l) => {
@@ -457,140 +417,63 @@ describe('swapRootSplitChildrenByKind(N 面板换位)', () => {
});
});
-function layoutWithTwoGhostPanes(): Layout {
- const alpha = insertRootSplitPane(
- createDefaultLayout(),
- { id: 'ghost-alpha', panelKind: 'ghost:alpha' },
- { index: 0, fraction: 0.2 },
- );
- const beta = insertRootSplitPane(
- alpha.layout,
- { id: 'ghost-beta', panelKind: 'ghost:beta' },
- { index: 1, fraction: 0.25 },
- );
- expect(alpha.applied).toBe(true);
- expect(beta.applied).toBe(true);
- return beta.layout;
-}
-
-describe('插件面板 grid 停靠', () => {
- it('把两个根级插件上下合并为 column,外层宽度继承双方份额之和', () => {
- const layout = layoutWithTwoGhostPanes();
- const before = (layout.content as SplitNode).children;
- const alphaWidth = before[0].fraction;
- const betaWidth = before[1].fraction;
-
- const result = stackGhostPaneByKind(layout, 'ghost:alpha', 'ghost:beta', 'before');
-
- expect(result.applied).toBe(true);
- const root = result.layout.content as SplitNode;
- expect(root.direction).toBe('row');
- expect(root.children).toHaveLength(3);
- expect(root.children[0].fraction).toBeCloseTo(alphaWidth + betaWidth);
- expect(root.children[0].node).toMatchObject({ type: 'split', direction: 'column' });
- const column = root.children[0].node as SplitNode;
- expect(
- column.children.map((child) => child.node.type === 'pane' && child.node.panelKind),
- ).toEqual(['ghost:alpha', 'ghost:beta']);
- expect(column.children.map((child) => child.fraction)).toEqual([0.5, 0.5]);
- expect(validateLayout(result.layout)).toEqual({ ok: true });
- expect(layout.content).not.toEqual(result.layout.content);
- });
-
- it('同一纵向列内上下拖动只调整顺序,保留每块高度份额', () => {
- const stacked = stackGhostPaneByKind(
- layoutWithTwoGhostPanes(),
- 'ghost:alpha',
- 'ghost:beta',
- 'before',
+describe('ensureTabGroupPane(页签组按边插入)', () => {
+ const kinds = (layout: Layout) =>
+ (layout.content as SplitNode).children.map((c) =>
+ c.node.type === 'pane' ? c.node.panelKind : `split:${c.node.direction}`,
);
- const column = (stacked.layout.content as SplitNode).children[0].node as SplitNode;
- column.children[0].fraction = 0.35;
- column.children[1].fraction = 0.65;
-
- const reordered = stackGhostPaneByKind(stacked.layout, 'ghost:alpha', 'ghost:beta', 'after');
- expect(reordered.applied).toBe(true);
- const nextColumn = (reordered.layout.content as SplitNode).children[0].node as SplitNode;
+ it('left / right 插到根横排里聊天区的前 / 后,全体份额归一', () => {
+ const left = ensureTabGroupPane(createDefaultLayout(), 'left');
+ expect(left.applied).toBe(true);
+ expect(kinds(left.layout)).toEqual(['tab-group:left', 'chat-main', 'right-tabs']);
+ expect((left.layout.content as SplitNode).children[0].node.id).toBe('tab-group-left');
expect(
- nextColumn.children.map((child) => child.node.type === 'pane' && child.node.panelKind),
- ).toEqual(['ghost:beta', 'ghost:alpha']);
- expect(nextColumn.children.map((child) => child.fraction)).toEqual([0.65, 0.35]);
- });
-
- it('从两块等分 column 抽回根横排时,恢复为两份相同列宽并折叠单子节点 split', () => {
- const stacked = stackGhostPaneByKind(
- layoutWithTwoGhostPanes(),
- 'ghost:alpha',
- 'ghost:beta',
- 'before',
- );
-
- const result = moveGhostPaneToRootByKind(stacked.layout, 'ghost:alpha', 'chat-main', 'before');
+ (left.layout.content as SplitNode).children.reduce((sum, c) => sum + c.fraction, 0),
+ ).toBeCloseTo(1);
+ expect(validateLayout(left.layout)).toEqual({ ok: true });
+
+ const noRight = removeRootSplitPaneByKind(left.layout, 'right-tabs');
+ const right = ensureTabGroupPane(noRight.layout, 'right');
+ expect(right.applied).toBe(true);
+ expect(kinds(right.layout)).toEqual(['tab-group:left', 'chat-main', 'right-tabs']);
+ });
+
+ it('top / bottom 把聊天区原地换成 chat-column 纵向分割,再次插入进同一列', () => {
+ const bottom = ensureTabGroupPane(createDefaultLayout(), 'bottom');
+ expect(bottom.applied).toBe(true);
+ expect(kinds(bottom.layout)).toEqual(['split:column', 'right-tabs']);
+ const column = (bottom.layout.content as SplitNode).children[0].node as SplitNode;
+ expect(column.id).toBe('chat-column');
+ expect(column.children.map((c) => (c.node as PaneNode).panelKind)).toEqual([
+ 'chat-main',
+ 'tab-group:bottom',
+ ]);
+ expect(validateLayout(bottom.layout)).toEqual({ ok: true });
- expect(result.applied).toBe(true);
- const root = result.layout.content as SplitNode;
- expect(
- root.children.map((child) => child.node.type === 'pane' && child.node.panelKind),
- ).toEqual(['ghost:beta', 'ghost:alpha', 'chat-main', 'right-tabs']);
- expect(root.children[0].fraction).toBeCloseTo(root.children[1].fraction);
- expect(validateLayout(result.layout)).toEqual({ ok: true });
+ const top = ensureTabGroupPane(bottom.layout, 'top');
+ expect(top.applied).toBe(true);
+ const column2 = (top.layout.content as SplitNode).children[0].node as SplitNode;
+ expect(column2.children.map((c) => (c.node as PaneNode).panelKind)).toEqual([
+ 'tab-group:top',
+ 'chat-main',
+ 'tab-group:bottom',
+ ]);
+ expect(column2.children.reduce((sum, c) => sum + c.fraction, 0)).toBeCloseTo(1);
+ expect(validateLayout(top.layout)).toEqual({ ok: true });
});
- it('中心交换支持纵向列中的插件槽位,且不会改变槽位高度', () => {
- const withGamma = insertRootSplitPane(
- layoutWithTwoGhostPanes(),
- { id: 'ghost-gamma', panelKind: 'ghost:gamma' },
- { index: 2, fraction: 0.1 },
- );
- const stacked = stackGhostPaneByKind(withGamma.layout, 'ghost:alpha', 'ghost:beta', 'before');
- const rootBefore = stacked.layout.content as SplitNode;
- const columnBefore = rootBefore.children[0].node as SplitNode;
- columnBefore.children[0].fraction = 0.4;
- columnBefore.children[1].fraction = 0.6;
-
- const result = swapPanesByKind(stacked.layout, 'ghost:alpha', 'ghost:gamma');
-
- expect(result.applied).toBe(true);
- const root = result.layout.content as SplitNode;
- const column = root.children[0].node as SplitNode;
- expect(column.children[0].node).toMatchObject({ panelKind: 'ghost:gamma' });
- expect(column.children.map((child) => child.fraction)).toEqual([0.4, 0.6]);
- expect(walkPanes(result.layout).map((pane) => pane.panelKind)).toContain('ghost:alpha');
- expect(validateLayout(result.layout)).toEqual({ ok: true });
- });
-
- it('内置面板可与整个插件纵向列交换,但仍拒绝进入列内槽位', () => {
- const stacked = stackGhostPaneByKind(
- layoutWithTwoGhostPanes(),
- 'ghost:alpha',
- 'ghost:beta',
- 'before',
- );
- const before = stacked.layout.content as SplitNode;
- const columnFraction = before.children[0].fraction;
- const chatFraction = before.children[1].fraction;
-
- expect(swapPanesByKind(stacked.layout, 'chat-main', 'ghost:alpha').applied).toBe(false);
- const result = swapRootSplitChildrenByKind(stacked.layout, 'chat-main', 'ghost:alpha');
- expect(result.applied).toBe(true);
- const root = result.layout.content as SplitNode;
- expect(root.children[0].node).toMatchObject({ type: 'pane', panelKind: 'chat-main' });
- expect(root.children[0].fraction).toBeCloseTo(chatFraction);
- expect(root.children[1].node).toMatchObject({ type: 'split', direction: 'column' });
- expect(root.children[1].fraction).toBeCloseTo(columnFraction);
- expect(countPanelKind(result.layout, 'chat-main')).toBe(1);
- expect(validateLayout(result.layout)).toEqual({ ok: true });
- });
-
- it('上下停靠拒绝内置面板或缺失目标,保持 chat-main 不变量', () => {
- const layout = layoutWithTwoGhostPanes();
- expect(stackGhostPaneByKind(layout, 'chat-main', 'ghost:alpha', 'before').applied).toBe(false);
- expect(stackGhostPaneByKind(layout, 'ghost:alpha', 'ghost:missing', 'after').applied).toBe(
- false,
- );
- expect(validateLayout(layout)).toEqual({ ok: true });
- expect(countPanelKind(layout, 'chat-main')).toBe(1);
+ it('组已在树里 → applied:false 且返回原引用;kind 映射双向一致', () => {
+ const left = ensureTabGroupPane(createDefaultLayout(), 'left').layout;
+ const again = ensureTabGroupPane(left, 'left');
+ expect(again.applied).toBe(false);
+ expect(again.layout).toBe(left);
+ for (const id of TAB_GROUP_IDS) {
+ expect(tabGroupIdFromPanelKind(tabGroupPanelKind(id))).toBe(id);
+ }
+ expect(tabGroupPanelKind('right')).toBe('right-tabs');
+ expect(tabGroupIdFromPanelKind('chat-main')).toBeNull();
+ expect(tabGroupIdFromPanelKind('tab-group:right')).toBeNull();
});
});
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 0a34b0b86a..0ef1b02b66 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -9,7 +9,6 @@ import {
type GhostLocale,
type GhostManifestLocales,
} from '@cindy/plugin-protocol';
-import { findSplitChildByPanelKind, insertRootSplitPane, type Layout } from './layoutTree';
import { PLUGIN_STORAGE_PART_RE } from './pluginStoragePartPattern.js';
import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from './locale';
@@ -2913,46 +2912,6 @@ export function ghostWebviewEntryPaths(manifest: GhostManifest): string[] {
return paths;
}
-/**
- * 装入带面板的意识后,把面板停进布局树(main 侧随 install 调用)。
- * - 树上已有同 kind 的 pane(重装)→ 返回 null:不动树,位置记忆保留、原位复活;
- * - 意识没声明面板 → null;
- * - position:'tab' → null:页签形态不进布局树,由插件页(GhostPagePanelHost)承载;
- * - 否则停在聊天区左侧,宽度占比/最小宽取清单声明。
- * 卸下时**不做**逆操作 —— 树数据保留正是"重装复活"的记忆来源(§6 规则 5)。
- */
-export function layoutWithGhostPanel(
- layout: Layout,
- manifest: GhostManifest,
- instanceId: string = manifest.id,
-): Layout | null {
- if (!manifest.panel) return null;
- if (manifest.panel.position === 'tab') return null;
- const kind = ghostPanelKind(instanceId);
- if (findSplitChildByPanelKind(layout, kind)) return null;
- // 停靠位置(相对主聊天窗):按 chat-main 的实际下标定插入点,不写死
- // 序号(未来树形态变化不至于错位)。停靠恒在聊天区左侧(2026-07-25 Lizi
- // 定案:right 退役,右侧留给右侧边栏;用户要右侧自己拖拽换位——已在树里
- // 的 pane 是用户布局记忆,本函数只管首次装入,不搬动存量)。
- const chatIndex =
- layout.content.type === 'split'
- ? layout.content.children.findIndex(
- (c) => c.node.type === 'pane' && c.node.panelKind === 'chat-main',
- )
- : -1;
- const index = chatIndex < 0 ? 0 : chatIndex;
- const result = insertRootSplitPane(
- layout,
- {
- id: `ghost-${instanceId}`,
- panelKind: kind,
- ...(manifest.panel.minWidth !== undefined ? { minWidth: manifest.panel.minWidth } : {}),
- },
- { index, fraction: manifest.panel.defaultFraction ?? 0.2 },
- );
- return result.applied ? result.layout : null;
-}
-
export type ManifestValidation =
| { ok: true; manifest: GhostManifest; unsupportedLegacySlots: string[] }
| { ok: false; reason: string };
diff --git a/apps/desktop/src/shared/layoutTree.ts b/apps/desktop/src/shared/layoutTree.ts
index c7533c1644..7765eefe66 100644
--- a/apps/desktop/src/shared/layoutTree.ts
+++ b/apps/desktop/src/shared/layoutTree.ts
@@ -34,7 +34,10 @@ export const MIN_SPLIT_CHILD_FRACTION = 0.05;
*/
const FRACTION_TOLERANCE = 1e-9;
-/** 内置面板类型。未来意识面板使用 `ghost:<id>` 前缀,不在此枚举内。 */
+/**
+ * 内置面板类型。`right-tabs` 同时是右侧页签组的 kind;其余页签组用
+ * `tab-group:<边>`(见 tabGroupPanelKind),历史插件停靠面板曾用 `ghost:<id>`。
+ */
export const BUILTIN_PANEL_KINDS = ['session-list', 'chat-main', 'right-tabs'] as const;
export type BuiltinPanelKind = (typeof BUILTIN_PANEL_KINDS)[number];
@@ -42,10 +45,10 @@ export type BuiltinPanelKind = (typeof BUILTIN_PANEL_KINDS)[number];
* 面板类型标识。
*
* 故意保持"开放命名空间"(任意非空字符串合法),而不是封闭枚举:
- * - 未来意识面板注册为 `ghost:<id>`,类型/校验/持久化零改动;
- * - 卸载意识后存档里残留的 kind 依然是**合法树**(渲染层查注册表查不到时隐藏该
- * pane 并回流空间,编辑模式下显示幽灵槽位)——绝不能因为"不认识"就把整棵树
- * 打回默认,否则卸载一张意识会毁掉用户全部布局;
+ * - 页签组按边注册为 `tab-group:<边>`,类型/校验/持久化零改动;
+ * - 组里暂时没有页签、或存档里残留历史插件面板的 kind 时依然是**合法树**(渲染层
+ * 查注册表查不到时隐藏该 pane 并回流空间)——绝不能因为"不认识"就把整棵树
+ * 打回默认,否则关掉一组页签会毁掉用户全部布局;
* - 同理,新版本新增的内置面板在旧版本上打开时也只是"隐藏",不是"重置"。
*
* `(string & {})` 是保留字面量自动补全的常用技巧,语义上等价于 string。
@@ -166,46 +169,6 @@ export function walkPanes(layout: Layout): PaneNode[] {
return out;
}
-/**
- * 恢复内置默认布局,但保留现有意识面板的停靠槽位。
- *
- * `layout.reset` 是用户从坏布局逃生的正式入口,不能顺手把已安装或等待重装复活的
- * `ghost:*` 面板从树里删掉。意识面板统一重新停在聊天区左侧,保留相对顺序和
- * minWidth;位置、折叠态与宽度则回到一组有界默认值。
- */
-export function createDefaultLayoutPreservingGhostPanels(current: Layout): Layout {
- const ghostPanes = walkPanes(current).filter((pane) => pane.panelKind.startsWith('ghost:'));
- const next = createDefaultLayout();
- if (ghostPanes.length === 0 || next.content.type !== 'split') return next;
-
- const root = next.content;
- const ghostTotalFraction = Math.min(0.6, ghostPanes.length * 0.2);
- const ghostFraction = ghostTotalFraction / ghostPanes.length;
- const builtinFraction = (1 - ghostTotalFraction) / root.children.length;
- for (const child of root.children) child.fraction = builtinFraction;
-
- const usedIds = new Set<string>(['sessions', root.id, ...root.children.map((c) => c.node.id)]);
- const ghostChildren = ghostPanes.map((pane, index) => {
- const baseId = `ghost-${pane.panelKind.slice('ghost:'.length)}`;
- let id = baseId;
- let suffix = index + 1;
- while (usedIds.has(id)) id = `${baseId}-${suffix++}`;
- usedIds.add(id);
- return {
- fraction: ghostFraction,
- node: {
- type: 'pane' as const,
- id,
- panelKind: pane.panelKind,
- ...(pane.minWidth !== undefined ? { minWidth: pane.minWidth } : {}),
- },
- };
- });
- root.children = [...ghostChildren, ...root.children];
- normalizeSplitFractions(root);
- return next;
-}
-
/** 按 id 查找 pane(含 sidebar 与 float)。找不到返回 null。 */
export function findPaneById(layout: Layout, paneId: string): PaneNode | null {
return walkPanes(layout).find((p) => p.id === paneId) ?? null;
@@ -533,30 +496,38 @@ export function swapRootSplitChildrenByKind(
return finishOp(layout, next, 'swapRootSplitChildrenByKind rejected');
}
-/** 插件面板二维停靠只使用一层纵向分组,避免把主界面演化成任意深度的自由网格。 */
-interface RootGhostPaneLocation {
- rootIndex: number;
- columnIndex: number | null;
+// ---------------------------------------------------------------------------
+// 页签组(tab group)—— 承载右侧栏页签的 pane,可停在聊天区四条边
+// ---------------------------------------------------------------------------
+
+/**
+ * 页签组标识 = 它相对聊天区所在的边。右侧组是历史上的右侧栏(panelKind 沿用
+ * `right-tabs`,老存档零迁移);其余三组按需插入树里,pane 一旦存在就保留
+ * (组里没有页签时由渲染层按「未注册 kind」隐藏,位置与宽度记忆不丢)。
+ */
+export const TAB_GROUP_IDS = ['left', 'right', 'top', 'bottom'] as const;
+export type TabGroupId = (typeof TAB_GROUP_IDS)[number];
+
+/** 承载聊天区与上下页签组的纵向分割节点 id(上下组只在这一层 column 里)。 */
+export const CHAT_COLUMN_SPLIT_ID = 'chat-column';
+
+const TAB_GROUP_KIND_PREFIX = 'tab-group:';
+
+export function isTabGroupId(value: unknown): value is TabGroupId {
+ return typeof value === 'string' && (TAB_GROUP_IDS as readonly string[]).includes(value);
}
-function isGhostPanelKind(kind: PanelKind): boolean {
- return kind.startsWith('ghost:');
+/** 页签组对应的 panelKind:右侧组 = `right-tabs`,其余 = `tab-group:<id>`。 */
+export function tabGroupPanelKind(groupId: TabGroupId): PanelKind {
+ return groupId === 'right' ? 'right-tabs' : `${TAB_GROUP_KIND_PREFIX}${groupId}`;
}
-function findRootGhostPaneLocation(layout: Layout, kind: PanelKind): RootGhostPaneLocation | null {
- if (layout.content.type !== 'split' || layout.content.direction !== 'row') return null;
- for (let rootIndex = 0; rootIndex < layout.content.children.length; rootIndex++) {
- const node = layout.content.children[rootIndex].node;
- if (node.type === 'pane' && node.panelKind === kind) {
- return { rootIndex, columnIndex: null };
- }
- if (node.type !== 'split' || node.direction !== 'column') continue;
- const columnIndex = node.children.findIndex(
- (child) => child.node.type === 'pane' && child.node.panelKind === kind,
- );
- if (columnIndex >= 0) return { rootIndex, columnIndex };
- }
- return null;
+/** panelKind → 页签组 id;不是页签组的 pane 返回 null。 */
+export function tabGroupIdFromPanelKind(kind: PanelKind): TabGroupId | null {
+ if (kind === 'right-tabs') return 'right';
+ if (!kind.startsWith(TAB_GROUP_KIND_PREFIX)) return null;
+ const id = kind.slice(TAB_GROUP_KIND_PREFIX.length);
+ return isTabGroupId(id) && id !== 'right' ? id : null;
}
function rootChildIndexContainingKind(layout: Layout, kind: PanelKind): number {
@@ -568,290 +539,75 @@ function rootChildIndexContainingKind(layout: Layout, kind: PanelKind): number {
return layout.content.children.findIndex((child) => contains(child.node));
}
-function collectLayoutNodeIds(node: LayoutNode, ids: Set<string>): void {
- ids.add(node.id);
- if (node.type === 'split') {
- for (const child of node.children) collectLayoutNodeIds(child.node, ids);
- }
-}
-
-function nextGridSplitId(layout: Layout, targetId: string): string {
- const ids = new Set<string>([layout.sidebar.id]);
- collectLayoutNodeIds(layout.content, ids);
- const base = `grid-${targetId}`.slice(0, 120);
- if (!ids.has(base)) return base;
- for (let suffix = 2; suffix < 10_000; suffix++) {
- const candidate = `${base.slice(0, 127 - String(suffix).length)}-${suffix}`;
- if (!ids.has(candidate)) return candidate;
- }
- return `grid-${targetId.slice(0, 110)}-fallback`;
-}
-
-function removeGhostPaneFromColumn(
- root: SplitNode,
- location: RootGhostPaneLocation,
-): PaneNode | null {
- if (location.columnIndex === null) return null;
- const rootChild = root.children[location.rootIndex];
- if (!rootChild || rootChild.node.type !== 'split' || rootChild.node.direction !== 'column') {
- return null;
- }
- const [removed] = rootChild.node.children.splice(location.columnIndex, 1);
- if (!removed || removed.node.type !== 'pane') return null;
- if (rootChild.node.children.length === 1) {
- rootChild.node = rootChild.node.children[0].node;
- } else {
- normalizeSplitFractions(rootChild.node);
- }
- return removed.node;
-}
+/** 左右组插入时的初始宽度份额;上下组插入时在聊天列里的初始高度份额。 */
+const TAB_GROUP_SIDE_FRACTION = 0.25;
+const TAB_GROUP_STACK_FRACTION = 0.35;
/**
- * 把一个插件面板停靠到另一个插件面板的上方/下方。
- *
- * 根布局始终保持横向;纵向 grid 只存在于根 child 的一层 column split 中,且只包含
- * `ghost:*` pane。两个根级插件合并时,目标列继承双方宽度份额之和,画面不会突然变窄。
+ * 保证某个页签组的 pane 在树里(用户第一次把页签移到该边时调用):
+ * - left / right:插到根横排里聊天区(或包着聊天区的列)的前 / 后,与其它根 child
+ * 等比让出份额;
+ * - top / bottom:聊天区 pane 原地换成一层 `chat-column` 纵向分割,组在聊天区的
+ * 上 / 下;列已存在则插到列首 / 列尾。
+ * 已在树里 → applied:false(原树)。不负责删除:组空了由渲染层隐藏,位置记忆保留。
*/
-export function stackGhostPaneByKind(
- layout: Layout,
- sourceKind: PanelKind,
- targetKind: PanelKind,
- placement: 'before' | 'after',
-): LayoutOpResult {
- if (!isGhostPanelKind(sourceKind) || !isGhostPanelKind(targetKind)) {
- return { layout, applied: false, reason: 'vertical grid only supports ghost panels' };
- }
- if (sourceKind === targetKind) {
- return { layout, applied: false, reason: 'cannot stack a pane with itself' };
+export function ensureTabGroupPane(layout: Layout, groupId: TabGroupId): LayoutOpResult {
+ const kind = tabGroupPanelKind(groupId);
+ if (findSplitChildByPanelKind(layout, kind)) {
+ return { layout, applied: false, reason: `tab group already present: ${groupId}` };
}
if (layout.content.type !== 'split' || layout.content.direction !== 'row') {
return { layout, applied: false, reason: 'content root must be a row split' };
}
- const source = findRootGhostPaneLocation(layout, sourceKind);
- const target = findRootGhostPaneLocation(layout, targetKind);
- if (!source || !target) {
- return {
+ const chatRootIndex = rootChildIndexContainingKind(layout, 'chat-main');
+ if (chatRootIndex < 0) return { layout, applied: false, reason: 'chat-main not found' };
+ const paneId = `tab-group-${groupId}`;
+
+ if (groupId === 'left' || groupId === 'right') {
+ return insertRootSplitPane(
layout,
- applied: false,
- reason: `ghost pane not found: ${!source ? sourceKind : targetKind}`,
- };
+ { id: paneId, panelKind: kind },
+ {
+ index: groupId === 'left' ? chatRootIndex : chatRootIndex + 1,
+ fraction: TAB_GROUP_SIDE_FRACTION,
+ },
+ );
}
const next = structuredClone(layout);
const root = next.content as SplitNode;
-
- // 同一列内只做顺序调整,份额随面板走。
- if (
- source.rootIndex === target.rootIndex &&
- source.columnIndex !== null &&
- target.columnIndex !== null
- ) {
- const column = root.children[source.rootIndex].node;
- if (column.type !== 'split' || column.direction !== 'column') return { layout, applied: false };
- const [sourceChild] = column.children.splice(source.columnIndex, 1);
- const targetIndex = column.children.findIndex(
- (child) => child.node.type === 'pane' && child.node.panelKind === targetKind,
- );
- if (!sourceChild || targetIndex < 0) return { layout, applied: false };
- column.children.splice(placement === 'before' ? targetIndex : targetIndex + 1, 0, sourceChild);
- return finishOp(layout, next, 'stackGhostPaneByKind reorder rejected');
- }
-
- let sourceNode: PaneNode | null = null;
- let transferredRootFraction = 0;
- if (source.columnIndex === null) {
- const [sourceRootChild] = root.children.splice(source.rootIndex, 1);
- if (!sourceRootChild || sourceRootChild.node.type !== 'pane') return { layout, applied: false };
- sourceNode = sourceRootChild.node;
- transferredRootFraction = sourceRootChild.fraction;
- } else {
- sourceNode = removeGhostPaneFromColumn(root, source);
- }
- if (!sourceNode) return { layout, applied: false, reason: `ghost pane not found: ${sourceKind}` };
-
- // source 移除后目标 rootIndex 可能左移,重新寻址。
- const targetAfterRemoval = findRootGhostPaneLocation(next, targetKind);
- if (!targetAfterRemoval)
- return { layout, applied: false, reason: `ghost pane not found: ${targetKind}` };
- const targetRootChild = root.children[targetAfterRemoval.rootIndex];
- targetRootChild.fraction += transferredRootFraction;
-
- if (targetAfterRemoval.columnIndex === null) {
- if (targetRootChild.node.type !== 'pane') return { layout, applied: false };
- const targetNode = targetRootChild.node;
- targetRootChild.node = {
+ const rootChild = root.children[chatRootIndex];
+ const pane: PaneNode = { type: 'pane', id: paneId, panelKind: kind };
+ if (rootChild.node.type === 'pane') {
+ const chat = rootChild.node;
+ rootChild.node = {
type: 'split',
- id: nextGridSplitId(next, targetNode.id),
+ id: CHAT_COLUMN_SPLIT_ID,
direction: 'column',
children:
- placement === 'before'
+ groupId === 'top'
? [
- { fraction: 0.5, node: sourceNode },
- { fraction: 0.5, node: targetNode },
+ { fraction: TAB_GROUP_STACK_FRACTION, node: pane },
+ { fraction: 1 - TAB_GROUP_STACK_FRACTION, node: chat },
]
: [
- { fraction: 0.5, node: targetNode },
- { fraction: 0.5, node: sourceNode },
+ { fraction: 1 - TAB_GROUP_STACK_FRACTION, node: chat },
+ { fraction: TAB_GROUP_STACK_FRACTION, node: pane },
],
};
- } else {
- const column = targetRootChild.node;
- if (column.type !== 'split' || column.direction !== 'column') return { layout, applied: false };
- const targetIndex = targetAfterRemoval.columnIndex;
- const targetChild = column.children[targetIndex];
- const half = targetChild.fraction / 2;
- targetChild.fraction = half;
- column.children.splice(placement === 'before' ? targetIndex : targetIndex + 1, 0, {
- fraction: half,
- node: sourceNode,
- });
- normalizeSplitFractions(column);
- }
-
- normalizeSplitFractions(root);
- return finishOp(layout, next, 'stackGhostPaneByKind rejected');
-}
-
-/**
- * 把插件面板从纵向列中抽出(或移动现有根 pane),停到某个根级区域左/右侧。
- * 从 column 抽出时按它在列中的高度份额拆分外层列宽;两块 50/50 的列可因此恢复为
- * 合并前近似相同的两列宽度。
- */
-export function moveGhostPaneToRootByKind(
- layout: Layout,
- sourceKind: PanelKind,
- targetKind: PanelKind,
- placement: 'before' | 'after',
-): LayoutOpResult {
- if (!isGhostPanelKind(sourceKind)) {
- return { layout, applied: false, reason: 'only ghost panels can leave a grid column' };
- }
- if (sourceKind === targetKind) {
- return { layout, applied: false, reason: 'cannot move a pane relative to itself' };
- }
- if (layout.content.type !== 'split' || layout.content.direction !== 'row') {
- return { layout, applied: false, reason: 'content root must be a row split' };
+ return finishOp(layout, next, 'ensureTabGroupPane rejected');
}
- const source = findRootGhostPaneLocation(layout, sourceKind);
- if (!source) return { layout, applied: false, reason: `ghost pane not found: ${sourceKind}` };
- if (rootChildIndexContainingKind(layout, targetKind) < 0) {
- return { layout, applied: false, reason: `target pane not found: ${targetKind}` };
+ const column = rootChild.node;
+ if (column.direction !== 'column') {
+ return { layout, applied: false, reason: 'chat container must be a column split' };
}
-
- const next = structuredClone(layout);
- const root = next.content as SplitNode;
- let sourceRootChild: { fraction: number; node: LayoutNode } | null = null;
-
- if (source.columnIndex === null) {
- [sourceRootChild] = root.children.splice(source.rootIndex, 1);
- } else {
- const rootChild = root.children[source.rootIndex];
- if (rootChild.node.type !== 'split' || rootChild.node.direction !== 'column') {
- return { layout, applied: false };
- }
- const sourceColumnChild = rootChild.node.children[source.columnIndex];
- if (!sourceColumnChild || sourceColumnChild.node.type !== 'pane')
- return { layout, applied: false };
- const ideal = rootChild.fraction * sourceColumnChild.fraction;
- const maxTransfer = rootChild.fraction - MIN_SPLIT_CHILD_FRACTION;
- if (maxTransfer < MIN_SPLIT_CHILD_FRACTION) {
- return { layout, applied: false, reason: 'grid column is too narrow to split' };
- }
- const extractedFraction = Math.min(maxTransfer, Math.max(MIN_SPLIT_CHILD_FRACTION, ideal));
- const sourceNode = removeGhostPaneFromColumn(root, source);
- if (!sourceNode) return { layout, applied: false };
- rootChild.fraction -= extractedFraction;
- sourceRootChild = { fraction: extractedFraction, node: sourceNode };
- }
- if (!sourceRootChild) return { layout, applied: false };
-
- const targetRootIndex = rootChildIndexContainingKind(next, targetKind);
- if (targetRootIndex < 0)
- return { layout, applied: false, reason: `target pane not found: ${targetKind}` };
- root.children.splice(
- placement === 'before' ? targetRootIndex : targetRootIndex + 1,
- 0,
- sourceRootChild,
- );
- normalizeSplitFractions(root);
- return finishOp(layout, next, 'moveGhostPaneToRootByKind rejected');
-}
-
-function findPanePath(node: LayoutNode, kind: PanelKind, path: number[] = []): number[] | null {
- if (node.type === 'pane') return node.panelKind === kind ? path : null;
- for (let index = 0; index < node.children.length; index++) {
- const found = findPanePath(node.children[index].node, kind, [...path, index]);
- if (found) return found;
- }
- return null;
-}
-
-function nodeAtPath(root: LayoutNode, path: number[]): LayoutNode | null {
- let node = root;
- for (const index of path) {
- if (node.type !== 'split' || !node.children[index]) return null;
- node = node.children[index].node;
- }
- return node;
-}
-
-function setNodeAtPath(root: LayoutNode, path: number[], value: LayoutNode): LayoutNode | null {
- if (path.length === 0) return value;
- let node = root;
- for (let depth = 0; depth < path.length - 1; depth++) {
- if (node.type !== 'split' || !node.children[path[depth]]) return null;
- node = node.children[path[depth]].node;
- }
- const index = path[path.length - 1];
- if (node.type !== 'split' || !node.children[index]) return null;
- node.children[index].node = value;
- return root;
-}
-
-/** 交换任意两个 pane 的停靠槽位;份额属于槽位,不随面板移动。 */
-export function swapPanesByKind(
- layout: Layout,
- kindA: PanelKind,
- kindB: PanelKind,
-): LayoutOpResult {
- if (kindA === kindB) return { layout, applied: false, reason: 'cannot swap a pane with itself' };
- const rootA = rootChildIndexContainingKind(layout, kindA);
- const rootB = rootChildIndexContainingKind(layout, kindB);
- const aIsRootPane =
- layout.content.type === 'split' &&
- rootA >= 0 &&
- layout.content.children[rootA].node.type === 'pane';
- const bIsRootPane =
- layout.content.type === 'split' &&
- rootB >= 0 &&
- layout.content.children[rootB].node.type === 'pane';
- if ((!aIsRootPane || !bIsRootPane) && (!isGhostPanelKind(kindA) || !isGhostPanelKind(kindB))) {
- return {
- layout,
- applied: false,
- reason: 'built-in panes cannot enter a ghost grid column',
- };
- }
- const pathA = findPanePath(layout.content, kindA);
- const pathB = findPanePath(layout.content, kindB);
- if (!pathA || !pathB) {
- return { layout, applied: false, reason: `pane kind not found: ${!pathA ? kindA : kindB}` };
- }
- const next = structuredClone(layout);
- const nodeA = nodeAtPath(next.content, pathA);
- const nodeB = nodeAtPath(next.content, pathB);
- if (!nodeA || !nodeB || nodeA.type !== 'pane' || nodeB.type !== 'pane') {
- return { layout, applied: false };
- }
- const cloneA = structuredClone(nodeA);
- const cloneB = structuredClone(nodeB);
- const withA = setNodeAtPath(next.content, pathA, cloneB);
- if (!withA) return { layout, applied: false };
- next.content = withA;
- const withB = setNodeAtPath(next.content, pathB, cloneA);
- if (!withB) return { layout, applied: false };
- next.content = withB;
- return finishOp(layout, next, 'swapPanesByKind rejected');
+ for (const child of column.children) child.fraction *= 1 - TAB_GROUP_STACK_FRACTION;
+ column.children.splice(groupId === 'top' ? 0 : column.children.length, 0, {
+ fraction: TAB_GROUP_STACK_FRACTION,
+ node: pane,
+ });
+ normalizeSplitFractions(column);
+ return finishOp(layout, next, 'ensureTabGroupPane rejected');
}
/**
diff --git a/docs/dev-rules/architecture-invariants.md b/docs/dev-rules/architecture-invariants.md
index 58b143e781..d683fafae4 100644
--- a/docs/dev-rules/architecture-invariants.md
+++ b/docs/dev-rules/architecture-invariants.md
@@ -42,6 +42,11 @@ Agent 能力归属另见 [`maker-core-and-agent-behavior.md`](maker-core-and-age
跳成用户布局。
- 未注册、沉睡或已抽离的面板允许保留在存档中但不渲染,重新注入/唤醒后必须原位恢复;
不要用清理未知 `panelKind` 的方式破坏这份位置记忆。
+- 右侧栏的页签住在**页签组**里(`shared/layoutTree.ts` 的 `TAB_GROUP_IDS`):右侧组沿用
+ `right-tabs`,左/上/下边组的 `panelKind` 是 `tab-group:<边>`,上下组与 `chat-main` 同在
+ 一层 `chat-column` 纵向分割里。页签归属由 renderer 记(`tabGroups.ts`),边组 pane 在
+ 组里第一次有页签时经 `ensureTabGroupPane` 插入,之后**只隐藏不删除**(组空了就按未注册
+ kind 隐藏);根横排里包着 `chat-main` 的那块是唯一的弹性区域。
- 新增面板经 panel registry 注册并复用标准 pane chrome/平台顶部安全区;折叠记忆按面板
声明的 global/per-session/none 语义处理。详细数据结构与迁移语义由上述模块顶层注释和
测试维护。