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。

页签窗口 review 收敛:owner 边界销毁、协议镜像、搬入 / 关闭 / 交回一致性、页签记录承载页面

Dash838e197f3b9d
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 5947c07cae..1e6fe04620 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -2506,6 +2506,8 @@ setAppSessionCommitBoundaryHook(() => {
cancelClaudeCliLogin();
clearAllSessionAttention();
remoteDesktopViewerWindows.reset();
+ // 弹出的页签窗口带着旧 owner 的任务指派与 renderer 本地页签缓存:同步销毁,不让新 owner 看到旧内容。
+ sidebarTabWindowsController.destroyAllWindows();
clearAllSessionProviders();
clearAllSessionRuntimeAxes();
clearAllSessionRuntimeControlStates();
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 0ac6748487..4ff47ce596 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -761,6 +761,8 @@ export const MAKER_INVOKE = {
SIDEBAR_TAB_WINDOW_OPEN: 'maker:sidebar-tab-window:open',
SIDEBAR_TAB_WINDOW_FOCUS: 'maker:sidebar-tab-window:focus',
SIDEBAR_TAB_WINDOW_CLOSE_FOR_TAB: 'maker:sidebar-tab-window:close-for-tab',
+ /** 主窗口把弹在独立窗口里的全局页签交回侧栏(无任务数据,不经窗口侧快照)。 */
+ SIDEBAR_TAB_WINDOW_RETURN_TAB: 'maker:sidebar-tab-window:return-tab',
/**
* 会话内 /goal 自主续跑(goal-host)——
* - GOAL_SET: 设/替换目标并立刻发首轮。入参 { sessionId, objective, agentKind, budgetTokens? }(budgetTokens 留空=不设预算)
diff --git a/apps/desktop/src/main/sidebar-tab-window/__tests__/controller.test.ts b/apps/desktop/src/main/sidebar-tab-window/__tests__/controller.test.ts
index a7dcc2b6b7..e650f72059 100644
--- a/apps/desktop/src/main/sidebar-tab-window/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/sidebar-tab-window/__tests__/controller.test.ts
@@ -268,10 +268,13 @@ describe('SidebarTabWindowsController', () => {
expect(win.isDestroyed()).toBe(false);
expect(h.returned).toHaveLength(0);
- // renderer 关掉页签后请求销毁:不交回页签。
+ // renderer 关掉页签后请求销毁:不交回页签,只告知主窗「已被关掉」(reason closed),
+ // 主窗据此丢掉自己缓存里的副本(不可持久化会话没有数据库广播可依赖)。
h.controller.closeForTab('tab-a');
expect(win.destroy).toHaveBeenCalledOnce();
- expect(h.returned).toHaveLength(0);
+ expect(h.returned).toEqual([
+ { sessionId: 's1', tabId: 'tab-a', snapshot: null, reason: 'closed' },
+ ]);
// renderer 还没挂上时没人能执行关闭流程:页签交回侧边栏而不是丢掉。
const cold = makeHarness();
@@ -345,17 +348,29 @@ describe('SidebarTabWindowsController', () => {
).tabs.map((tab) => tab.tabId),
).toEqual(['tab-a', 'tab-g', 'tab-new']);
- // 窗口里关掉一个页签:摘掉不交回,窗口留着。
+ // 窗口里关掉一个页签:摘掉不交回(只告知 closed),窗口留着。
h.controller.closeForTab('tab-new');
expect(win.isDestroyed()).toBe(false);
- expect(h.returned).toHaveLength(1);
+ expect(h.returned.slice(1)).toEqual([
+ { sessionId: 's1', tabId: 'tab-new', snapshot: null, reason: 'closed' },
+ ]);
+
+ // 主窗把窗里的全局页签交回(只限全局页签;任务页签必须由窗口自己合并回来)。
+ expect(h.controller.returnGlobalTab('tab-a')).toBe(false);
+ expect(h.controller.returnGlobalTab('tab-g')).toBe(true);
+ expect(h.returned.at(-1)).toEqual({
+ sessionId: null,
+ tabId: 'tab-g',
+ snapshot: null,
+ reason: 'merge',
+ });
+ expect(h.controller.isTabPoppedOut('tab-g')).toBe(false);
// 崩溃:剩下的页签全部交回。
win.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });
expect(win.destroy).toHaveBeenCalledOnce();
- expect(h.returned.slice(1)).toEqual([
+ expect(h.returned.slice(-1)).toEqual([
{ sessionId: 's1', tabId: 'tab-a', snapshot: null, reason: 'crash' },
- { sessionId: null, tabId: 'tab-g', snapshot: null, reason: 'crash' },
]);
expect(h.controller.getState()).toEqual({
'tab-x': { windowId: 'w2', sessionId: 's2', open: true },
@@ -387,13 +402,38 @@ describe('SidebarTabWindowsController', () => {
expect(positionWindow).toHaveBeenCalledTimes(1);
});
+ // 测试价值
+ // - 生产入口与可观察结果:owner 提交边界调用的 destroyAllWindows;可观察的是所有页签窗口(含 spare)
+ // 被销毁、归属清空,并广播空状态让各 renderer 不再把页签当作「已弹出」。
+ // - Bug / 规则依据:PR #6468 review(切换账号后弹出窗口仍显示旧 owner 的任务 / 插件内容)。
+ // - 现有覆盖缺口:销毁只在主窗口关闭 / 退出时被测过,没有断言广播。
+ // - 最小失败输入:一扇已展示的窗口 + 一扇 spare,调用 destroyAllWindows。
+ // - tier:unit(mock deps)。
+ it('destroys every window and clears the popped-out mirror at an owner boundary', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ h.controller.open(request('tab-a'));
+ h.controller.markRendererReady(h.wc(h.created[0]));
+ h.controller.markPresentationReady(h.wc(h.created[0]));
+ vi.advanceTimersByTime(2_000);
+ expect(h.created).toHaveLength(2);
+ h.controller.destroyAllWindows();
+ expect(h.created.every((win) => win.isDestroyed())).toBe(true);
+ expect(h.controller.getState()).toEqual({});
+ expect(h.controller.isTabPoppedOut('tab-a')).toBe(false);
+ expect(h.broadcasts.at(-1)).toEqual({});
+ // 旧窗口不当作崩溃把页签交回新 owner。
+ expect(h.returned).toHaveLength(0);
+ });
+
it('closes a window whose tab was closed in the sidebar without returning the tab', () => {
const h = makeHarness();
h.controller.open(request('tab-a'));
const win = h.created[0];
h.controller.closeForTab('tab-a');
expect(win.destroy).toHaveBeenCalledOnce();
- expect(h.returned).toHaveLength(0);
+ // 只有 closed 通知,没有 merge / crash 形式的「交回」。
+ expect(h.returned.map((payload) => payload.reason)).toEqual(['closed']);
expect(h.controller.getState()).toEqual({});
// 未弹出的页签 no-op。
h.controller.closeForTab('tab-missing');
diff --git a/apps/desktop/src/main/sidebar-tab-window/__tests__/ipc.test.ts b/apps/desktop/src/main/sidebar-tab-window/__tests__/ipc.test.ts
index 98eb2be137..b0cb4be904 100644
--- a/apps/desktop/src/main/sidebar-tab-window/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/sidebar-tab-window/__tests__/ipc.test.ts
@@ -66,6 +66,7 @@ function makeController() {
slotOwnsTab: (slot: { assignment: { tabs: { tabId: string }[] } }, tabId: string) =>
slot.assignment.tabs.some((tab) => tab.tabId === tabId),
adoptTab: vi.fn(),
+ returnGlobalTab: vi.fn(() => true),
};
}
@@ -172,6 +173,19 @@ describe('sidebar-tab-window IPC', () => {
expect(controller.closeForTab).toHaveBeenCalledTimes(2);
});
+ it('lets only the main window hand a global tab back from a window', async () => {
+ const controller = makeController();
+ register(controller);
+ const back = handlers().get(MAKER_INVOKE.SIDEBAR_TAB_WINDOW_RETURN_TAB)!;
+ await expect(call(back, { sender: otherSender }, 'g_plugin')).rejects.toThrow(
+ /PERMISSION_DENIED/,
+ );
+ expect(controller.returnGlobalTab).not.toHaveBeenCalled();
+ await expect(call(back, { sender: mainSender }, '')).rejects.toThrow(/INVALID_PARAMS/);
+ await call(back, { sender: mainSender }, 'g_plugin');
+ expect(controller.returnGlobalTab).toHaveBeenCalledWith('g_plugin');
+ });
+
it('accepts merge-back only from the owning tab window and validates the snapshot', async () => {
const controller = makeController();
controller.slotForSender.mockImplementation((sender: unknown) =>
diff --git a/apps/desktop/src/main/sidebar-tab-window/controller.ts b/apps/desktop/src/main/sidebar-tab-window/controller.ts
index b4a4d0c4a2..635dab3625 100644
--- a/apps/desktop/src/main/sidebar-tab-window/controller.ts
+++ b/apps/desktop/src/main/sidebar-tab-window/controller.ts
@@ -206,8 +206,9 @@ export class SidebarTabWindowsController {
sessionId: request.sessionId,
context: request.context,
};
- slot.handoff = request.handoff ?? slot.handoff;
}
+ // 搬入的页签带着主窗此刻最新的内存快照:总是换成最新一份(renderer 只导入新增页签的数据)。
+ if (request.handoff) slot.handoff = request.handoff;
slot.assignment.tabs = [
...slot.assignment.tabs,
{ tabId: request.tabId, sessionId: request.sessionId },
@@ -248,12 +249,22 @@ export class SidebarTabWindowsController {
closeForTab(tabId: string): void {
const slot = this.slotForTab(tabId);
if (!slot?.assignment) return;
- this.removeTabFromSlot(slot, tabId);
+ const ref = this.removeTabFromSlot(slot, tabId);
if (slot.assignment.tabs.length === 0) {
this.disposeSlot(slot);
} else {
this.deliverAssignment(slot);
}
+ // 先告知主窗「这个页签已被关掉」再广播状态:不可持久化会话的页签只存在于各 renderer
+ // 内存里,没有数据库广播;窗口归属一清,主窗缓存里的旧副本会重新显示出来(复活)。
+ if (ref && !this.deps.isQuitting()) {
+ this.deps.notifyTabReturned({
+ sessionId: ref.sessionId,
+ tabId,
+ snapshot: null,
+ reason: 'closed',
+ });
+ }
this.broadcast();
this.deps.log.info('sidebar tab window dropped closed tab', { tabId });
}
@@ -281,6 +292,28 @@ export class SidebarTabWindowsController {
this.deps.log.info('sidebar tab merged back', { tabId, withSnapshot: snapshot !== null });
}
+ /**
+ * 主窗口把弹在窗口里的**全局页签**交回侧栏(左侧导航入口 / 详情页「在侧边栏中打开」「恢复默认
+ * 位置」)。任务页签带内存态,必须由窗口自己合并回来(mergeBack),这里拒绝。
+ */
+ returnGlobalTab(tabId: string): boolean {
+ const slot = this.slotForTab(tabId);
+ if (!slot?.assignment) return false;
+ const ref = slot.assignment.tabs.find((tab) => tab.tabId === tabId);
+ if (!ref || ref.sessionId !== null) return false;
+ this.removeTabFromSlot(slot, tabId);
+ if (slot.assignment.tabs.length === 0) {
+ this.disposeSlot(slot);
+ } else {
+ this.deliverAssignment(slot);
+ }
+ if (!this.deps.isQuitting()) {
+ this.deps.notifyTabReturned({ sessionId: null, tabId, snapshot: null, reason: 'merge' });
+ }
+ this.broadcast();
+ return true;
+ }
+
/** 弹出窗口 renderer 在自己里面新建了页签:归它承载。已在别处的页签忽略。 */
adoptTab(sender: WebContents, tabId: string, sessionId: string | null): void {
const slot = this.slotForSender(sender);
@@ -375,6 +408,8 @@ export class SidebarTabWindowsController {
this.tabToWindow.clear();
this.spare = null;
this.spareRecoveryAttempts = 0;
+ // 让各 renderer 的「已弹出」镜像清空(owner 切换时页签留在原 renderer 缓存里,不再被隐藏)。
+ if (!this.disposed) this.broadcast();
}
/** 应用退出时永久停止。 */
diff --git a/apps/desktop/src/main/sidebar-tab-window/ipc.ts b/apps/desktop/src/main/sidebar-tab-window/ipc.ts
index a6fa6838c7..2c9322d84d 100644
--- a/apps/desktop/src/main/sidebar-tab-window/ipc.ts
+++ b/apps/desktop/src/main/sidebar-tab-window/ipc.ts
@@ -178,6 +178,16 @@ export function registerSidebarTabWindowIpc(opts: {
controller.focus(id);
});
+ ipcMain.handle(MAKER_INVOKE.SIDEBAR_TAB_WINDOW_RETURN_TAB, (event, tabId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const id = requireId(tabId, 'tabId');
+ if (!isMainWindowSender(event.sender)) {
+ log.warn('SIDEBAR_TAB_WINDOW_RETURN_TAB from non-main-window sender, dropped');
+ throwIpcError('PERMISSION_DENIED', 'only the main window can return a global tab');
+ }
+ return controller.returnGlobalTab(id);
+ });
+
ipcMain.handle(MAKER_INVOKE.SIDEBAR_TAB_WINDOW_CLOSE_FOR_TAB, (event, tabId: unknown) => {
assertTrustedAppRendererEvent(event);
const id = requireId(tabId, 'tabId');
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 792b78619f..c93bb1da38 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2026,6 +2026,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** 页签已在侧边栏关闭:销毁其弹出窗口,不交回。 */
closeForTab: (tabId: string): Promise<void> =>
ipcRenderer.invoke('maker:sidebar-tab-window:close-for-tab', tabId),
+ /** 把弹在独立窗口里的全局页签(插件视图)交回侧栏;任务页签由窗口自己合并回来。 */
+ returnTab: (tabId: string): Promise<boolean> =>
+ ipcRenderer.invoke('maker:sidebar-tab-window:return-tab', tabId),
/** 页签拖出窗口:窗外跟随指针的预览卡(复用任务拖出的那扇预览窗口)。 */
beginDragPreview: (label: string, palette: SessionDragPreviewPalette): Promise<void> =>
ipcRenderer.invoke('maker:sidebar-tab-drag-preview:start', label, palette),
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 5e32e4069e..847aa130f3 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -52,6 +52,7 @@ import {
getBucket,
getTabSnapshot,
importReturnedTabState,
+ removeTabLocally,
importTabSnapshot,
refreshSessionFromDb,
resetCachesForHostTransition,
@@ -1186,6 +1187,11 @@ export function MainLayout() {
const api = window.electronAPI.sidebarTabWindow;
if (!api?.onTabReturned) return;
return api.onTabReturned(({ sessionId, tabId, snapshot, reason }) => {
+ // 页签在弹出窗口里被关掉:不是交回。丢掉本窗口缓存里的副本,免得窗口归属一清它又出现。
+ if (reason === 'closed') {
+ if (sessionId !== null) removeTabLocally(sessionId, tabId);
+ return;
+ }
// 全局页签回来:数据一直在全局存储里,只需选中它并确保侧栏展开。
if (sessionId === null) {
const globalTab = findGlobalTab(tabId);
diff --git a/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx
index fe0dc89905..daa81e6b2e 100644
--- a/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx
@@ -36,7 +36,14 @@ import {
setHostedTabIds,
useHostedTabIds,
} from '@/features/right-sidebar/lib/tabHosting';
-import { closeTab, getBucket, importTabSnapshot, subscribe } from '@/features/right-sidebar/store';
+import {
+ closeTab,
+ getBucket,
+ importTabSnapshot,
+ isTabClosing,
+ refreshSessionFromDb,
+ subscribe,
+} from '@/features/right-sidebar/store';
import {
findGlobalTab,
isGlobalTabId,
@@ -59,6 +66,9 @@ import type {
const log = createLogger('SidebarTabWindowLayout');
+/** 新搬入页签在本窗口出现前的宽限:数据库刷新回来 / 主窗创建写入落定所需的时间。 */
+const NEW_TAB_GRACE_MS = 5000;
+
export function SidebarTabWindowLayout() {
const { t } = useTranslation();
const { effectiveLocale, setLocale } = useLocale();
@@ -77,17 +87,46 @@ export function SidebarTabWindowLayout() {
const presentationReadySentRef = useRef(false);
/** 已向 main 报过「在本窗口里消失了」的页签,避免重复 close-for-tab。 */
const reportedGoneRef = useRef(new Set<string>());
+ /** 本窗口见到过「在场」的页签:没见过的新搬入页签有一段宽限,不立刻当作已消失。 */
+ const seenRef = useRef(new Set<string>());
+ /** 页签被指派给本窗口的时间(宽限起点)。 */
+ const assignedAtRef = useRef(new Map<string, number>());
+ const lastAssignedIdsRef = useRef<ReadonlySet<string> | null>(null);
+ const [recheck, setRecheck] = useState(0);
const [windowChromeRevision, setWindowChromeRevision] = useState(0);
const [activeTabId, setActiveTabId] = useState<string | null>(null);
const applyAssignment = useCallback((next: SidebarTabWindowAssignmentPayload) => {
- // 必须早于 Shell 的 ensureHydrated:不可持久化会话只能从这份快照水合。
- if (next.handoff) importTabSnapshot(next.handoff);
+ const previousIds = lastAssignedIdsRef.current;
+ const nextIds = new Set(next.tabs.map((tab) => tab.tabId));
+ const addedIds = new Set([...nextIds].filter((id) => !previousIds?.has(id)));
+ lastAssignedIdsRef.current = nextIds;
+ // 必须早于 Shell 的 ensureHydrated:不可持久化会话只能从这份快照水合。首次指派整桶导入;
+ // 后续指派(搬入新页签)只并入新增页签的数据,不抹掉窗口里已有页签刚改的状态。
+ if (next.handoff) {
+ importTabSnapshot(next.handoff, previousIds === null ? {} : { onlyTabIds: addedIds });
+ }
setHostedTabIds(next.tabs.map((tab) => tab.tabId));
- const stillAssigned = new Set(next.tabs.map((tab) => tab.tabId));
+ const now = Date.now();
+ for (const id of addedIds) assignedAtRef.current.set(id, now);
+ // 搬入的任务页签在主窗刚改过的数据可能还没通过数据库广播传到本窗口缓存:按数据库强制取一次最新,
+ // 并让「已消失」判定等它回来(见下方宽限)。
+ if (previousIds !== null) {
+ const bySession = new Map<string, string[]>();
+ for (const ref of next.tabs) {
+ if (!addedIds.has(ref.tabId) || ref.sessionId === null) continue;
+ bySession.set(ref.sessionId, [...(bySession.get(ref.sessionId) ?? []), ref.tabId]);
+ }
+ for (const [sid, ids] of bySession) {
+ void refreshSessionFromDb(sid, { forceTabIds: ids }).catch((err) =>
+ log.warn('refresh moved-in tabs failed', { sessionId: sid, err }),
+ );
+ }
+ }
for (const id of [...reportedGoneRef.current]) {
- if (!stillAssigned.has(id)) reportedGoneRef.current.delete(id);
+ if (!nextIds.has(id)) reportedGoneRef.current.delete(id);
}
+ for (const id of [...seenRef.current]) if (!nextIds.has(id)) seenRef.current.delete(id);
setAssignment(next);
}, []);
@@ -172,15 +211,40 @@ export function SidebarTabWindowLayout() {
// 最后一个离开时 main 销毁窗口。
useEffect(() => {
if (!assignment || !contentReady) return;
+ let recheckDelay: number | null = null;
+ const needRecheck = (ms: number) => {
+ recheckDelay = recheckDelay === null ? ms : Math.min(recheckDelay, ms);
+ };
for (const ref of assignment.tabs) {
- if (isPresent(ref) || reportedGoneRef.current.has(ref.tabId)) continue;
+ if (isPresent(ref)) {
+ seenRef.current.add(ref.tabId);
+ continue;
+ }
+ if (reportedGoneRef.current.has(ref.tabId)) continue;
+ // 关闭还在进行(乐观移除已生效、close IPC / 状态写入在途):此刻销毁 renderer 会让删除请求
+ // 发不出去,记录留在数据库里下次又出现。等它收尾再判。
+ if (isTabClosing(ref.tabId)) {
+ needRecheck(150);
+ continue;
+ }
+ // 刚搬入、还没在本窗口见到过的页签:数据库刷新可能还没回来(或创建写入还在主窗途中),给一段宽限。
+ if (!seenRef.current.has(ref.tabId)) {
+ const waited = Date.now() - (assignedAtRef.current.get(ref.tabId) ?? 0);
+ if (waited < NEW_TAB_GRACE_MS) {
+ needRecheck(NEW_TAB_GRACE_MS - waited + 20);
+ continue;
+ }
+ }
reportedGoneRef.current.add(ref.tabId);
void api?.closeForTab(ref.tabId).catch((err) => {
reportedGoneRef.current.delete(ref.tabId);
log.warn('close-for-tab for a closed tab failed', { tabId: ref.tabId, err });
});
}
- }, [api, assignment, contentReady, isPresent]);
+ if (recheckDelay === null) return;
+ const timer = window.setTimeout(() => setRecheck((n) => n + 1), recheckDelay);
+ return () => window.clearTimeout(timer);
+ }, [api, assignment, contentReady, isPresent, recheck]);
const refFor = useCallback(
(tabId: string) => assignment?.tabs.find((tab) => tab.tabId === tabId) ?? null,
@@ -209,6 +273,8 @@ export function SidebarTabWindowLayout() {
return;
}
await closeTab(ref.sessionId, tabId);
+ // closeTab 成功收尾后立刻重判:此时页签已真正关完,可以放心请 main 摘掉。
+ setRecheck((n) => n + 1);
},
[refFor],
);
diff --git a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx
index fb30c5f1d9..2910cb371e 100644
--- a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx
@@ -16,15 +16,12 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import {
- hasPluginPlacementMemory,
- resetPluginPlacement,
- useGlobalTabs,
-} from '@/features/right-sidebar/globalTabs';
+import { hasPluginPlacementMemory, useGlobalTabs } from '@/features/right-sidebar/globalTabs';
import {
focusExistingPluginTab,
openPluginInSidebar,
openPluginInWindow,
+ resetPluginPlacementAndReturn,
resolvePluginOpenTarget,
} from '@/features/right-sidebar/pluginPlacement';
import { useTabGroupAssignments } from '@/features/right-sidebar/tabGroups';
@@ -77,7 +74,7 @@ export function GhostMainViewNavEntry({
const open = () => {
if (focusExistingPluginTab(item.installedGhost)) return;
const target = resolvePluginOpenTarget(item.installedGhost);
- if (target === 'sidebar') openPluginInSidebar(item.installedGhost);
+ if (target === 'sidebar') void openPluginInSidebar(item.installedGhost);
else if (target === 'window') openPluginInWindow(item.installedGhost);
else openPage();
};
@@ -94,9 +91,9 @@ export function GhostMainViewNavEntry({
e.stopPropagation();
setContextMenuPos({ x: e.clientX, y: e.clientY });
};
- const openInSidebar = () => openPluginInSidebar(item.installedGhost);
+ const openInSidebar = () => void openPluginInSidebar(item.installedGhost);
const openInWindow = () => openPluginInWindow(item.installedGhost);
- const resetPlacement = () => resetPluginPlacement(item.instanceId, item.installedGhost);
+ const resetPlacement = () => void resetPluginPlacementAndReturn(item.installedGhost);
const contextMenu = (
<DropdownMenu
open={contextMenuPos !== null}
diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx
index 68f411ab5e..6c0e6772ce 100644
--- a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx
@@ -31,12 +31,11 @@ const placementMock = vi.hoisted(() => ({
focusExistingPluginTab: vi.fn(() => false),
openPluginInSidebar: vi.fn(),
openPluginInWindow: vi.fn(),
- resetPluginPlacement: vi.fn(),
+ resetPluginPlacementAndReturn: vi.fn(),
hasMemory: false,
}));
vi.mock('@/features/right-sidebar/globalTabs', () => ({
hasPluginPlacementMemory: () => placementMock.hasMemory,
- resetPluginPlacement: placementMock.resetPluginPlacement,
useGlobalTabs: () => [],
}));
vi.mock('@/features/right-sidebar/tabGroups', () => ({
@@ -47,6 +46,7 @@ vi.mock('@/features/right-sidebar/pluginPlacement', () => ({
focusExistingPluginTab: placementMock.focusExistingPluginTab,
openPluginInSidebar: placementMock.openPluginInSidebar,
openPluginInWindow: placementMock.openPluginInWindow,
+ resetPluginPlacementAndReturn: placementMock.resetPluginPlacementAndReturn,
}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
@@ -118,7 +118,7 @@ describe('GhostMainViewNavEntries', () => {
expect(placementMock.openPluginInWindow).toHaveBeenCalledWith(items[1].installedGhost);
fireEvent.contextMenu(entry);
fireEvent.click(screen.getByText('ghostMainView.resetPlacement'));
- expect(placementMock.resetPluginPlacement).toHaveBeenCalledWith('workspace', items[1].installedGhost);
+ expect(placementMock.resetPluginPlacementAndReturn).toHaveBeenCalledWith(items[1].installedGhost);
placementMock.hasMemory = false;
});
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 97ac31b352..9cc601897d 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -62,10 +62,10 @@ import { GhostPluginIcon } from './GhostPluginIcon';
import {
addGlobalPluginTab,
hasPluginPlacementMemory,
- resetPluginPlacement,
setActiveGlobalTabId,
useGlobalTabs,
} from '@/features/right-sidebar/globalTabs';
+import { resetPluginPlacementAndReturn } from '@/features/right-sidebar/pluginPlacement';
import { useTabGroupAssignments } from '@/features/right-sidebar/tabGroups';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
@@ -985,7 +985,7 @@ export function DetailsSection({
<button
type="button"
onClick={() => {
- const tab = addGlobalPluginTab(detail.id, { ghost: installedGhost });
+ const tab = addGlobalPluginTab(detail.id, { ghost: installedGhost, view: 'panel' });
if (tab) setActiveGlobalTabId(tab.id);
}}
className={placementActionClass}
@@ -996,7 +996,9 @@ export function DetailsSection({
{canResetPlacement && (
<button
type="button"
- onClick={() => resetPluginPlacement(detail.id, installedGhost)}
+ onClick={() => {
+ if (installedGhost) void resetPluginPlacementAndReturn(installedGhost);
+ }}
className={placementActionClass}
>
{t('settings.ghosts.detail.resetPlacement')}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx
index f1b718167c..bc386d13c8 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx
@@ -387,6 +387,19 @@ describe('GhostMainViewHost · 单实例视图守卫', () => {
expect(getGlobalTabs()).toHaveLength(1);
});
+ it('does not treat a docked panel tab on a different page as the main view', async () => {
+ const { addGlobalPluginTab, getGlobalTabs } = await import('@/features/right-sidebar/globalTabs');
+ // panel.html ≠ mainView.html:两个页面是不同界面,可以并存,整页不收页签。
+ const distinct = { ...manifest, panel: { html: 'panel.html' } };
+ mocks.routeCapable = [
+ { ...mocks.routeCapable[0], manifest: distinct, installedGhost: { ...ghostOf(), manifest: distinct } },
+ ];
+ addGlobalPluginTab('workspace', { ghost: ghostOf() });
+ renderInHeaderSlot();
+ expect(getGlobalTabs()).toHaveLength(1);
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
it('leaves both alive when the plugin declares mainView.multiple', async () => {
const { addGlobalPluginTab, getGlobalTabs } = await import('@/features/right-sidebar/globalTabs');
const { act } = await import('@testing-library/react');
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.ts
index 078ce077eb..f8360adb1e 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.ts
@@ -18,6 +18,7 @@ import {
__resetGlobalTabsForTest,
addGlobalPluginTab,
defaultGroupForGhost,
+ effectivePluginView,
getActiveGlobalTabId,
getGlobalTabs,
getGlobalTabsSnapshot,
@@ -29,6 +30,7 @@ import {
resetPluginPlacement,
sanitizeGlobalTabsSnapshot,
setActiveGlobalTabId,
+ tabShowsMainView,
} from '../globalTabs';
import { __resetTabGroupsForTest, getTabGroup, setTabGroup } from '../tabGroups';
@@ -161,4 +163,43 @@ describe('globalTabs', () => {
expect(defaultGroupForGhost(ghost(undefined, { open: 'sidebar', side: 'right' }))).toBe('right');
expect(defaultGroupForGhost(ghost(undefined, { open: 'page' }))).toBe('right');
});
+ // 测试价值
+ // - 生产入口与可观察结果:addGlobalPluginTab({view}) / tabShowsMainView / defaultGroupForGhost(view);
+ // 可观察的是页签记录自己承载 panel 还是 mainView(panel 与 mainView 指向不同页面时互不串)、
+ // 同一插件的页签被明确要求另一个页面时切换、单实例判定只看主视图那一份、mainView.open:'sidebar'
+ // 未声明 side 时默认右侧(即使插件同时声明停靠面板)。
+ // - Bug / 规则依据:PR #6468 review(主视图入口显示面板 / 主视图默认边不符)。
+ // - 现有覆盖缺口:此前页签不记承载页面,panel 永远优先。
+ // - 最小失败输入:panel.html ≠ mainView.html 的插件,先自动出现 panel,再从入口要 main。
+ it('records which page a plugin-view tab hosts and defaults the side per page', () => {
+ const ghost = (extra: object = {}) =>
+ ({
+ manifest: {
+ id: 'gamma',
+ name: 'Gamma',
+ panel: { html: 'panel.html' },
+ mainView: { html: 'view.html', open: 'sidebar' },
+ ...extra,
+ },
+ enabled: true,
+ }) as unknown as import('../../../../shared/ghost').InstalledGhost;
+ const g = ghost();
+ // 停靠面板自动出现:panel(缺省边 left);主视图 open:sidebar 未声明 side 默认右侧,不被 panel 带偏。
+ const panelTab = addGlobalPluginTab('gamma', { ghost: g })!;
+ expect((panelTab.state as { view?: string }).view).toBe('panel');
+ expect(defaultGroupForGhost(g, 'panel')).toBe('left');
+ expect(defaultGroupForGhost(g, 'main')).toBe('right');
+ // 页面不同 → panel 页签不算主视图,整页单实例不互斥;入口要 main 时同一页签切到 main。
+ expect(tabShowsMainView(panelTab.state as never, g)).toBe(false);
+ const mainTab = addGlobalPluginTab('gamma', { ghost: g, view: 'main' })!;
+ expect(mainTab.id).toBe(panelTab.id);
+ expect((mainTab.state as { view?: string }).view).toBe('main');
+ expect(tabShowsMainView(mainTab.state as never, g)).toBe(true);
+ // 同一 html 的 panel 页签等于主视图那一份。
+ const same = ghost({ mainView: { html: 'panel.html' } });
+ expect(tabShowsMainView({ instanceId: 'gamma', view: 'panel' }, same)).toBe(true);
+ // 旧数据没有 view:按插件声明推导(有停靠面板 → panel)。
+ expect(effectivePluginView({ instanceId: 'gamma' }, g)).toBe('panel');
+ expect(effectivePluginView({ instanceId: 'gamma' }, ghost({ panel: undefined }))).toBe('main');
+ });
});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts
index d9d2361b40..8ac95e3822 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts
@@ -1581,3 +1581,60 @@ describe('cross-renderer sync for popped-out tabs', () => {
expect(store.getBucket('never-loaded').hydrated).toBe(false);
});
});
+
+// 测试价值
+// - 生产入口与可观察结果:importTabSnapshot({onlyTabIds}) / removeTabLocally / isTabClosing;可观察的是
+// 弹出窗口收到后续指派(搬入新页签)时只并入新增页签的内存态、窗口里已有页签刚改的状态不被旧
+// 整桶快照抹掉;窗口里关掉的页签经 closed 通知从主窗缓存里丢掉(不可持久化会话没有数据库广播)。
+// - Bug / 规则依据:PR #6468 review(旧快照覆盖窗口修改 / 关闭的远程页签复活 / 窗口过早销毁)。
+// - 现有覆盖缺口:上面只测整桶导入与交回,没有增量并入与本地丢弃。
+// - 最小失败输入:窗口已有 tab-a(URL 已改),再搬入 tab-b 的快照里 tab-a 仍是旧 URL。
+// - tier:unit(jsdom,进程内 store)。
+describe('multi-tab window handoff merge (memory-only sessions)', () => {
+ it('merges only newly assigned tabs and keeps window-local edits to existing ones', async () => {
+ store = await import('../store');
+ store._resetStore();
+ const stale = {
+ sessionId: 'remote-m1',
+ persistable: false as const,
+ activeTabId: 'tab-a',
+ tabs: [
+ { id: 'tab-a', kind: 'web-browser', state: { url: 'https://old.example/' } },
+ { id: 'tab-b', kind: 'web-browser', state: { url: 'https://b.example/' } },
+ ],
+ };
+ // 首次指派:整桶导入(此时只有 tab-a 归本窗口,但整桶可见)。
+ store.importTabSnapshot({ ...stale, tabs: [stale.tabs[0]] });
+ // 窗口里把 tab-a 导航到了新地址。
+ await store.patchTabState('remote-m1', 'tab-a', () => ({ url: 'https://new.example/' }));
+ // 后续指派:搬入 tab-b,握手快照里 tab-a 还是旧 URL。
+ store.importTabSnapshot(stale, { onlyTabIds: new Set(['tab-b']) });
+ const bucket = store.getBucket('remote-m1');
+ expect(bucket.tabs.map((tab) => tab.id)).toEqual(['tab-a', 'tab-b']);
+ expect(bucket.tabs.find((tab) => tab.id === 'tab-a')?.state).toEqual({
+ url: 'https://new.example/',
+ });
+ expect(bucket.activeTabId).toBe('tab-a');
+ });
+
+ it('removeTabLocally drops a tab closed elsewhere without issuing a close IPC', async () => {
+ store = await import('../store');
+ store._resetStore();
+ const stub = makeIpcStub();
+ installIpc(stub);
+ store.importTabSnapshot({
+ sessionId: 'remote-m2',
+ persistable: false,
+ activeTabId: 'tab-a',
+ tabs: [
+ { id: 'tab-a', kind: 'file-browser', state: null },
+ { id: 'tab-b', kind: 'file-browser', state: null },
+ ],
+ });
+ store.removeTabLocally('remote-m2', 'tab-a');
+ expect(store.getBucket('remote-m2').tabs.map((tab) => tab.id)).toEqual(['tab-b']);
+ expect(store.getBucket('remote-m2').activeTabId).toBe('tab-b');
+ expect(stub.close).not.toHaveBeenCalled();
+ expect(store.isTabClosing('tab-b')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts
index a1d4a504fe..fd41702c58 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts
@@ -36,9 +36,45 @@ const log = createLogger('rightSidebar.globalTabs');
const STORAGE_KEY_PREFIX = 'xdt:rightSidebarGlobalTabs:v1:';
const MAX_GLOBAL_TABS = 20;
+/** 页签承载插件的哪个页面:停靠面板(panel.html)或主视图(mainView.html)。 */
+export type PluginViewKind = 'panel' | 'main';
+
export interface PluginViewTabState {
/** 插件物理实例 id(storage part)。 */
instanceId: string;
+ /**
+ * 承载的页面。缺省(旧数据)按插件声明推导:有停靠面板 → panel,否则 main——
+ * 与升级前「panel 优先」的行为一致。
+ */
+ view?: PluginViewKind;
+}
+
+/** 插件有没有停靠形态(非 tab)的面板。 */
+export function ghostHasDockedPanel(ghost: InstalledGhost): boolean {
+ return ghost.manifest.panel !== undefined && ghost.manifest.panel.position !== 'tab';
+}
+
+/** 页签实际承载的页面:显式记录优先,旧数据按插件声明推导。 */
+export function effectivePluginView(
+ state: PluginViewTabState | null | undefined,
+ ghost: InstalledGhost | undefined,
+): PluginViewKind {
+ if (state?.view) return state.view;
+ return ghost && ghostHasDockedPanel(ghost) ? 'panel' : 'main';
+}
+
+/**
+ * 该页签承载的页面是不是插件的主视图(整页入口那一份)。panel 与 mainView 指向不同
+ * html 的插件,两个页面是不同的界面,可以并存;同一 html 或页签本身承载主视图才算同一视图。
+ */
+export function tabShowsMainView(
+ state: PluginViewTabState | null | undefined,
+ ghost: InstalledGhost,
+): boolean {
+ const view = effectivePluginView(state, ghost);
+ if (view === 'main') return true;
+ const panelHtml = ghost.manifest.panel?.html;
+ return panelHtml !== undefined && panelHtml === ghost.manifest.mainView?.html;
}
export interface GlobalTabsSnapshot {
@@ -92,7 +128,12 @@ export function sanitizeGlobalTabsSnapshot(raw: unknown): GlobalTabsSnapshot {
tabs.push({
id: entry.id,
kind: 'plugin-view',
- state: { instanceId: entry.state.instanceId } satisfies PluginViewTabState,
+ state: {
+ instanceId: entry.state.instanceId,
+ ...(entry.state.view === 'panel' || entry.state.view === 'main'
+ ? { view: entry.state.view }
+ : {}),
+ } satisfies PluginViewTabState,
});
if (tabs.length >= MAX_GLOBAL_TABS) break;
}
@@ -178,18 +219,19 @@ export function globalTabIdForInstance(instanceId: string): string {
}
/**
- * 插件声明的默认放置边:mainView.open:'sidebar' 的 side;停靠面板的 panel.position
- * (缺省 left,与历史停靠面板「停在聊天区左侧」一致);其它(纯 mainView)右侧组。
+ * 插件声明的默认放置边,按页签承载的页面取:
+ * - 主视图(main):`mainView.open:'sidebar'` 的 `side`,缺省右侧;
+ * - 停靠面板(panel):`panel.position`,缺省 left(与历史停靠面板「停在聊天区左侧」一致)。
+ * 两个页面都声明时互不影响对方的默认边。
*/
-export function defaultGroupForGhost(ghost: InstalledGhost): TabGroupId {
+export function defaultGroupForGhost(ghost: InstalledGhost, view?: PluginViewKind): TabGroupId {
const { manifest } = ghost;
- if (manifest.mainView?.open === 'sidebar' && manifest.mainView.side) {
- return manifest.mainView.side;
+ const resolved = view ?? (ghostHasDockedPanel(ghost) ? 'panel' : 'main');
+ if (resolved === 'main') {
+ return manifest.mainView?.open === 'sidebar' ? (manifest.mainView.side ?? 'right') : 'right';
}
- if (manifest.panel && manifest.panel.position !== 'tab') {
- return manifest.panel.position ?? 'left';
- }
- return 'right';
+ const position = manifest.panel?.position;
+ return position && position !== 'tab' ? position : 'left';
}
/**
@@ -200,7 +242,7 @@ export function defaultGroupForGhost(ghost: InstalledGhost): TabGroupId {
*/
export function addGlobalPluginTab(
instanceId: string,
- opts?: { groupId?: TabGroupId; ghost?: InstalledGhost },
+ opts?: { groupId?: TabGroupId; ghost?: InstalledGhost; view?: PluginViewKind },
): TabState | null {
const current = getGlobalTabsSnapshot();
const existing = current.tabs.find(
@@ -209,26 +251,40 @@ export function addGlobalPluginTab(
const dismissed = current.dismissedInstanceIds.filter((id) => id !== instanceId);
if (existing) {
if (opts?.groupId) setTabGroup(existing.id, opts.groupId);
- if (dismissed.length !== current.dismissedInstanceIds.length) {
- persist({ ...current, dismissedInstanceIds: dismissed });
+ // 同一插件只有一个页签:明确要求另一个页面时把页签切过去(panel 与 mainView 不同页面时)。
+ const existingState = existing.state as PluginViewTabState;
+ const wantedView = opts?.view;
+ const switched =
+ wantedView !== undefined && effectivePluginView(existingState, opts?.ghost) !== wantedView;
+ const next = switched
+ ? { ...existing, state: { ...existingState, view: wantedView } as PluginViewTabState }
+ : existing;
+ if (switched || dismissed.length !== current.dismissedInstanceIds.length) {
+ persist({
+ ...current,
+ tabs: switched ? current.tabs.map((tab) => (tab === existing ? next : tab)) : current.tabs,
+ dismissedInstanceIds: dismissed,
+ });
}
- return existing;
+ return next;
}
if (current.tabs.length >= MAX_GLOBAL_TABS) {
log.warn('global tab limit reached', { instanceId });
return null;
}
+ const view: PluginViewKind | undefined =
+ opts?.view ?? (opts?.ghost ? effectivePluginView(undefined, opts.ghost) : undefined);
const tab: TabState = {
id: globalTabIdForInstance(instanceId),
kind: 'plugin-view',
- state: { instanceId } satisfies PluginViewTabState,
+ state: { instanceId, ...(view ? { view } : {}) } satisfies PluginViewTabState,
};
let placed = current.placedInstanceIds;
// 组归属先于页签出现落定,首帧就在目标组里。
if (opts?.groupId) {
setTabGroup(tab.id, opts.groupId);
} else if (opts?.ghost && !placed.includes(instanceId)) {
- setTabGroup(tab.id, defaultGroupForGhost(opts.ghost));
+ setTabGroup(tab.id, defaultGroupForGhost(opts.ghost, view));
placed = [...placed, instanceId];
}
persist({
@@ -313,10 +369,16 @@ export function resetPluginPlacement(instanceId: string, ghost?: InstalledGhost)
const current = getGlobalTabsSnapshot();
const tabId = globalTabIdForInstance(instanceId);
clearTabGroup(tabId);
- const tabPresent = current.tabs.some((tab) => tab.id === tabId);
+ const presentTab = current.tabs.find((tab) => tab.id === tabId);
let placed = current.placedInstanceIds.filter((id) => id !== instanceId);
- if (tabPresent && ghost) {
- setTabGroup(tabId, defaultGroupForGhost(ghost));
+ if (presentTab && ghost) {
+ setTabGroup(
+ tabId,
+ defaultGroupForGhost(
+ ghost,
+ effectivePluginView(presentTab.state as PluginViewTabState, ghost),
+ ),
+ );
placed = [...placed, instanceId];
}
persist({
@@ -381,10 +443,11 @@ export function reconcileGlobalPluginTabs(ghosts: readonly InstalledGhost[]): vo
const tabId = globalTabIdForInstance(instanceId);
// 首次出现:按插件声明放默认边(存量 panel.position 的插件回到它原来停的那一边)。
if (!placed.includes(instanceId)) {
- setTabGroup(tabId, defaultGroupForGhost(ghost));
+ setTabGroup(tabId, defaultGroupForGhost(ghost, 'panel'));
placed = [...placed, instanceId];
}
- tabs = [...tabs, { id: tabId, kind: 'plugin-view', state: { instanceId } }];
+ // 自动出现的是停靠面板:显式记 panel,之后即使同时有 mainView 入口也不串页面。
+ tabs = [...tabs, { id: tabId, kind: 'plugin-view', state: { instanceId, view: 'panel' } }];
present.add(instanceId);
}
if (
diff --git a/apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts b/apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts
index c48ab34780..1406f23aad 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts
@@ -1,6 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { browserWebviewPool } from '../lib/browserWebviewPool';
+import { isTabHostedHere } from '../lib/tabHosting';
import { getBucket, subscribe } from '../store';
import type { TabState } from '../types';
@@ -48,7 +49,9 @@ export function useRetainedBrowserTabHosts(
remaining.delete(host.tab.id);
continue;
}
- if (!host.sessionId || !browserWebviewPool.peek(host.tab.id)) continue;
+ // 页签已不由本 renderer 承载(弹出到别的窗口 / 从多页签窗口合并回去):不再保留它的后台 body。
+ if (!host.sessionId || !isTabHostedHere(host.tab.id)) continue;
+ if (!browserWebviewPool.peek(host.tab.id)) continue;
// Background navigation/close updates belong to the original task. Never
// reuse the foreground task's context or revive a tab missing from its bucket.
const bucket = getBucket(host.sessionId);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts
index 308bbd6948..159586cd89 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts
@@ -6,7 +6,8 @@
*/
import { isSidebarTabWindow } from '@/lib/sidebarTabWindow';
-import { getSingleTabSnapshot, getTabSnapshot } from '../store';
+import { browserWebviewPool } from './browserWebviewPool';
+import { getBucket, getSingleTabSnapshot, getTabSnapshot } from '../store';
export async function mergeSidebarWindowBack(
sessionId: string | null | undefined,
@@ -16,6 +17,14 @@ export async function mergeSidebarWindowBack(
if (isSidebarTabWindow()) {
if (!tabId) return;
const snapshot = getSingleTabSnapshot(sessionId, tabId);
+ // 多页签窗口合并回去后窗口往往还在:必须先把这个页签的浏览器 guest 释放掉,否则它在
+ // 本窗口后台继续跑,主窗又按同一状态新建一份,两份页面写同一个页签状态。
+ if (
+ sessionId &&
+ getBucket(sessionId).tabs.some((t) => t.id === tabId && t.kind === 'web-browser')
+ ) {
+ browserWebviewPool.release(tabId);
+ }
await window.electronAPI.sidebarTabWindow?.mergeBack?.({ tabId, snapshot });
return;
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.ts b/apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.ts
index 4f8b59ac4b..1d59f6b68d 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.ts
@@ -21,6 +21,9 @@ import { isTabPoppedOut } from '@/lib/sidebarTabWindowState';
import {
addGlobalPluginTab,
findGlobalTabByInstance,
+ resetPluginPlacement,
+ tabShowsMainView,
+ type PluginViewTabState,
isPluginWindowPlacement,
rememberPluginWindowPlacement,
removeGlobalTab,
@@ -34,10 +37,17 @@ const log = createLogger('rightSidebar.pluginPlacement');
export type PluginOpenTarget = 'page' | 'sidebar' | 'window';
+/** 实例当前的页签若承载的就是主视图(整页入口那一份),返回它;承载别的页面(停靠面板)返回 null。 */
+function existingMainViewTab(ghost: InstalledGhost) {
+ const existing = findGlobalTabByInstance(installedGhostStoragePart(ghost));
+ if (!existing) return null;
+ return tabShowsMainView(existing.state as PluginViewTabState, ghost) ? existing : null;
+}
+
/** 左侧栏入口点击时的打开目标(不含「已在侧边栏 / 窗口里」的聚焦分支)。 */
export function resolvePluginOpenTarget(ghost: InstalledGhost): PluginOpenTarget {
const instanceId = installedGhostStoragePart(ghost);
- const existing = findGlobalTabByInstance(instanceId);
+ const existing = existingMainViewTab(ghost);
if (existing) return isTabPoppedOut(existing.id) ? 'window' : 'sidebar';
if (isPluginWindowPlacement(instanceId)) return 'window';
const open = ghost.manifest.mainView?.open;
@@ -45,11 +55,27 @@ export function resolvePluginOpenTarget(ghost: InstalledGhost): PluginOpenTarget
return 'page';
}
+/**
+ * 页签正弹在独立窗口里时,先把它真正交回主窗(窗口登记与主窗投影一起切过来),
+ * 再谈放置:只改记忆不交回,主窗会继续把它当作「已弹出」隐藏。全局页签没有任务数据要带,
+ * 交回只需 main 把它从窗口摘掉。
+ */
+async function returnPluginTabFromWindow(tabId: string): Promise<void> {
+ if (!isTabPoppedOut(tabId)) return;
+ try {
+ await window.electronAPI?.sidebarTabWindow?.returnTab?.(tabId);
+ } catch (err) {
+ log.warn('return plugin tab from window failed', { tabId, err });
+ }
+}
+
/** 作为全局页签放进侧边栏(默认边见模块说明),选中它;落在右侧组时展开右侧栏。 */
-export function openPluginInSidebar(ghost: InstalledGhost): void {
+export async function openPluginInSidebar(ghost: InstalledGhost): Promise<void> {
const instanceId = installedGhostStoragePart(ghost);
- const tab = addGlobalPluginTab(instanceId, { ghost });
+ // 左侧导航入口放进侧栏的是主视图页面(而不是停靠面板)。
+ const tab = addGlobalPluginTab(instanceId, { ghost, view: 'main' });
if (!tab) return;
+ await returnPluginTabFromWindow(tab.id);
rememberPluginWindowPlacement(instanceId, false);
setActiveGlobalTabId(tab.id);
if (getTabGroup(tab.id) === 'right') requestRightSidebarVisibility('open');
@@ -59,7 +85,7 @@ export function openPluginInSidebar(ghost: InstalledGhost): void {
export function openPluginInWindow(ghost: InstalledGhost): void {
const instanceId = installedGhostStoragePart(ghost);
const api = window.electronAPI?.sidebarTabWindow;
- const tab = addGlobalPluginTab(instanceId, { ghost });
+ const tab = addGlobalPluginTab(instanceId, { ghost, view: 'main' });
if (!tab || !api) return;
rememberPluginWindowPlacement(instanceId, true);
if (isTabPoppedOut(tab.id)) {
@@ -81,10 +107,20 @@ export function openPluginInWindow(ghost: InstalledGhost): void {
.catch((err) => log.warn('pop out plugin view failed', { instanceId, err }));
}
-/** 已在侧边栏 / 窗口里的页签:聚焦它。返回 false = 还没有页签。 */
-export function focusExistingPluginTab(ghost: InstalledGhost): boolean {
+/**
+ * 恢复默认位置:弹在窗口里的页签先交回主窗,再清放置记忆并回到插件声明的默认边。
+ * (resetPluginPlacement 只管记忆,不碰窗口。)
+ */
+export async function resetPluginPlacementAndReturn(ghost: InstalledGhost): Promise<void> {
const instanceId = installedGhostStoragePart(ghost);
const existing = findGlobalTabByInstance(instanceId);
+ if (existing) await returnPluginTabFromWindow(existing.id);
+ resetPluginPlacement(instanceId, ghost);
+}
+
+/** 已在侧边栏 / 窗口里、且承载的就是主视图的页签:聚焦它。返回 false = 没有(含页签承载别的页面)。 */
+export function focusExistingPluginTab(ghost: InstalledGhost): boolean {
+ const existing = existingMainViewTab(ghost);
if (!existing) return false;
if (isTabPoppedOut(existing.id)) {
void window.electronAPI?.sidebarTabWindow?.focus(existing.id).catch(() => undefined);
@@ -118,8 +154,12 @@ export function useSingleInstanceViewGuard(ghost: InstalledGhost | null): void {
settledRef.current = null;
return;
}
+ // 只看承载主视图的页签:panel 与 mainView 是不同页面时可以并存。
const existing = globalTabs.find(
- (tab) => (tab.state as { instanceId?: string } | null)?.instanceId === instanceId,
+ (tab) =>
+ (tab.state as PluginViewTabState | null)?.instanceId === instanceId &&
+ ghost !== null &&
+ tabShowsMainView(tab.state as PluginViewTabState, ghost),
);
if (settledRef.current !== instanceId) {
// 刚进整页:页签在别处就收掉。
@@ -131,5 +171,5 @@ export function useSingleInstanceViewGuard(ghost: InstalledGhost | null): void {
// 整页开着时页签出现:整页让位。
navigate('/', { replace: true });
}
- }, [globalTabs, instanceId, navigate, single]);
+ }, [ghost, globalTabs, instanceId, navigate, single]);
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx
index 185c11b8d8..49c2b4e881 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx
@@ -23,7 +23,11 @@ import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
import { MAIN_VIEW_ICONS } from '@/cindy-brain/mainViewIcons';
import type { InstalledGhost } from '../../../../../shared/ghost';
import { installedGhostStoragePart } from '../../../../../shared/pluginIdentity';
-import { globalTabTitleForGhost, type PluginViewTabState } from '../../globalTabs';
+import {
+ effectivePluginView,
+ globalTabTitleForGhost,
+ type PluginViewTabState,
+} from '../../globalTabs';
import { registerTabKind } from '../../registry';
import type { TabKindBodyProps, TabKindPlugin } from '../../types';
@@ -50,8 +54,12 @@ function PluginViewBody({ state }: TabKindBodyProps<PluginViewTabState>) {
if (runtimeState === 'crashed' || runtimeState === 'fused') {
return <GhostPanelError ghost={ghost} state={runtimeState} />;
}
+ // 按页签记录的页面选内容:主视图入口放进侧栏的是 mainView,停靠面板自动出现的是 panel。
+ const view = effectivePluginView(state, ghost);
const panelHtml =
- ghost.manifest.panel?.position !== 'tab' ? ghost.manifest.panel?.html : undefined;
+ view === 'panel' && ghost.manifest.panel?.position !== 'tab'
+ ? ghost.manifest.panel?.html
+ : undefined;
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
{panelHtml ? (
diff --git a/apps/desktop/src/renderer/features/right-sidebar/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.ts
index f683d6d610..853449e46b 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts
@@ -510,24 +510,68 @@ export function getTabSnapshot(sessionId: string | null | undefined): RsbWindowT
};
}
-/** Import a non-persistable tab bucket received before the previous host is destroyed. */
-export function importTabSnapshot(snapshot: RsbWindowTabSnapshot): void {
+/**
+ * Import a non-persistable tab bucket received before the previous host is destroyed.
+ *
+ * `onlyTabIds`:页签独立窗口收到**后续**指派(搬入新页签)时,只把这些页签的数据并进现有桶,
+ * 其它页签保持本窗口当前的内存态——整桶替换会把窗口里刚改的 URL / 刚新建的页签抹掉。
+ */
+export function importTabSnapshot(
+ snapshot: RsbWindowTabSnapshot,
+ opts: { onlyTabIds?: ReadonlySet<string> } = {},
+): void {
if (snapshot.persistable || !snapshot.sessionId) return;
+ if (opts.onlyTabIds) {
+ const existing = cache.get(snapshot.sessionId);
+ const incoming = snapshot.tabs
+ .filter((tab) => tab.id && tab.kind && opts.onlyTabIds!.has(tab.id))
+ .map((tab) => ({ ...tab, kind: tab.kind as TabKindId }));
+ if (incoming.length === 0) return;
+ memoryOnlySessions.add(snapshot.sessionId);
+ const byId = new Map((existing?.tabs ?? []).map((tab) => [tab.id, tab]));
+ for (const tab of incoming) byId.set(tab.id, tab);
+ setBucket(snapshot.sessionId, {
+ hydrated: true,
+ tabs: [...byId.values()],
+ activeTabId: existing?.activeTabId ?? null,
+ });
+ return;
+ }
const seen = new Set<string>();
- const tabs: TabState[] = snapshot.tabs.filter((tab) => {
- if (!tab.id || !tab.kind || seen.has(tab.id)) return false;
- seen.add(tab.id);
- return true;
- }).map((tab) => ({ ...tab, kind: tab.kind as TabKindId }));
- const activeTabId = snapshot.activeTabId && seen.has(snapshot.activeTabId)
- ? snapshot.activeTabId
- : null;
+ const tabs: TabState[] = snapshot.tabs
+ .filter((tab) => {
+ if (!tab.id || !tab.kind || seen.has(tab.id)) return false;
+ seen.add(tab.id);
+ return true;
+ })
+ .map((tab) => ({ ...tab, kind: tab.kind as TabKindId }));
+ const activeTabId =
+ snapshot.activeTabId && seen.has(snapshot.activeTabId) ? snapshot.activeTabId : null;
const bucket: TabBucket = { hydrated: true, tabs, activeTabId };
memoryOnlySessions.add(snapshot.sessionId);
pendingHandoffBuckets.set(snapshot.sessionId, bucket);
setBucket(snapshot.sessionId, bucket);
}
+/** 页签正在关闭(乐观移除已生效、close IPC 在途)。弹出窗口据此推迟「页签已消失」的上报。 */
+export function isTabClosing(tabId: string): boolean {
+ return closingTabIds.has(tabId);
+}
+
+/**
+ * 页签已在别的 renderer 里被关掉(弹出窗口关页签后 main 的 closed 通知):只丢本地副本并
+ * 释放资源,不发 close IPC(数据库那一侧已由关掉它的一方处理;不可持久化会话本就没有)。
+ */
+export function removeTabLocally(sessionId: string, tabId: string): void {
+ const bucket = cache.get(sessionId);
+ const tab = bucket?.tabs.find((candidate) => candidate.id === tabId);
+ if (!bucket || !tab) return;
+ const tabs = bucket.tabs.filter((candidate) => candidate.id !== tabId);
+ const activeTabId = bucket.activeTabId === tabId ? (tabs[0]?.id ?? null) : bucket.activeTabId;
+ setBucket(sessionId, { tabs, activeTabId });
+ forgetClosedTab(sessionId, tabId, tab.kind);
+}
+
/** 弹出窗口合并回侧边栏时交回的单页签内存态(仅不可持久化会话;其余返回 null)。 */
export function getSingleTabSnapshot(
sessionId: string | null | undefined,
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 32725143fc..1b9a9fa485 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2066,6 +2066,8 @@ interface ElectronAPI {
) => Promise<void>;
focus: (tabId: string) => Promise<void>;
closeForTab: (tabId: string) => Promise<void>;
+ /** 主窗口:把弹在独立窗口里的全局页签交回侧栏(任务页签不支持)。 */
+ returnTab?: (tabId: string) => Promise<boolean>;
/** 主窗口:页签拖出窗口时的窗外预览卡。 */
beginDragPreview?: (
label: string,
diff --git a/apps/desktop/src/shared/sidebarTabWindow.ts b/apps/desktop/src/shared/sidebarTabWindow.ts
index 8764b40836..971d4c91bf 100644
--- a/apps/desktop/src/shared/sidebarTabWindow.ts
+++ b/apps/desktop/src/shared/sidebarTabWindow.ts
@@ -89,7 +89,11 @@ export interface SidebarTabReturnedPayload {
tabId: string;
/** 不可持久化会话交回的内存态;可持久化会话为 null,主窗按 SQLite 刷新。 */
snapshot: SidebarTabReturnSnapshot | null;
- reason: 'merge' | 'crash';
+ /**
+ * merge = 用户合并回侧栏;crash = 窗口崩溃 / 作废;closed = 页签在窗口里被关掉(不再显示,
+ * 主窗据此丢掉自己缓存里的副本——不可持久化会话没有数据库广播可依赖)。
+ */
+ reason: 'merge' | 'crash' | 'closed';
}
/** main → 所有窗口:某会话的页签持久化数据被其它 renderer 改动。 */
diff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.ts
index 25622ed536..ac64afd78c 100644
--- a/packages/plugin-protocol/src/__tests__/manifest.test.ts
+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts
@@ -1810,12 +1810,36 @@ describe('Ghost manifest contract', () => {
if (!rejected.ok) expect(rejected.reason).toContain('仅停靠形态');
}
- // top/bottom 仍收词明确拒绝,野值仍拒。
- const pending = validateGhostManifest(withPanel({ position: 'top' }));
- expect(pending.ok).toBe(false);
- if (!pending.ok) expect(pending.reason).toContain('暂未支持');
+ // 四条边都是真实的页签组位置(与 Desktop 校验一致),野值仍拒。
+ for (const side of ['left', 'right', 'top', 'bottom'] as const) {
+ const ok = validateGhostManifest(withPanel({ position: side }));
+ expect(ok.ok, side).toBe(true);
+ if (ok.ok) expect(ok.manifest.panel?.position).toBe(side);
+ }
expect(validateGhostManifest(withPanel({ position: 'center' })).ok).toBe(false);
});
+
+ it('mainView.open / side / multiple 与 Desktop 校验一致:合法保留,野值与错配拒', () => {
+ const withView = (mainView: Record<string, unknown>) =>
+ validateGhostManifest({
+ schemaVersion: 3,
+ minCindyVersion: '0.1.61',
+ id: 'view-helper',
+ name: 'View Helper',
+ version: '1.0.0',
+ entry: 'main.js',
+ mainView: { html: 'main-view.html', ...mainView },
+ });
+ const ok = withView({ open: 'sidebar', side: 'bottom', multiple: true });
+ expect(ok.ok).toBe(true);
+ if (ok.ok) {
+ expect(ok.manifest.mainView).toMatchObject({ open: 'sidebar', side: 'bottom', multiple: true });
+ }
+ expect(withView({ open: 'popup' }).ok).toBe(false);
+ expect(withView({ open: 'page', side: 'left' }).ok).toBe(false);
+ expect(withView({ open: 'sidebar', side: 'middle' }).ok).toBe(false);
+ expect(withView({ multiple: false }).ok).toBe(false);
+ });
});
describe('cindy 详单:media/text/embed/search 类目与 oneshotModel 校验', () => {
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index 10e4143bb0..fcaa12b0d1 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -124,12 +124,10 @@ export const GHOST_LAUNCH_MODES = ['on-demand', 'resident'] as const;
export type GhostLaunchMode = (typeof GHOST_LAUNCH_MODES)[number];
/**
- * 面板显示形态(相对主聊天窗)。left / right = 顶层布局树停靠 pane;
- * 'tab' = 不进布局树,作为右侧栏(right-tabs)里的每会话单例页签
- * (2026-07-24 定案)。top / bottom 需要嵌套上下分割(树操作/拖缝/卸载
- * 查找全链路),排期中——校验层先收词并明确拒绝,不静默降级(规则 9)。
+ * 面板显示形态:left / right / top / bottom = 右侧栏页签系统里聊天区对应边的页签组
+ * (不跟对话的全局页签,用户放置过后以用户为准);'tab' = 不进页签组,由插件页独占承载。
*/
-export const GHOST_PANEL_POSITIONS = ['left', 'right', 'tab'] as const;
+export const GHOST_PANEL_POSITIONS = ['left', 'right', 'top', 'bottom', 'tab'] as const;
export type GhostPanelPosition = (typeof GHOST_PANEL_POSITIONS)[number];
/** 面板声明(卡槽之一,一段意识至多一块)。 */
@@ -164,6 +162,13 @@ export type GhostMainViewIcon = (typeof GHOST_MAIN_VIEW_ICONS)[number];
* 插件一级主视图声明。它是应用级导航能力,与会话内 panel 独立授权;
* Host 只会挂载这里声明且经过批准的包内 HTML 入口。
*/
+/** 左侧导航入口点击后主视图在哪里打开(插件给的默认偏好;用户放置过后以用户的为准)。 */
+export const GHOST_MAIN_VIEW_OPEN_MODES = ['page', 'sidebar', 'window'] as const;
+export type GhostMainViewOpenMode = (typeof GHOST_MAIN_VIEW_OPEN_MODES)[number];
+/** 主视图以页签形态打开时默认停在聊天区的哪一边。 */
+export const GHOST_TAB_SIDES = ['left', 'right', 'top', 'bottom'] as const;
+export type GhostTabSide = (typeof GHOST_TAB_SIDES)[number];
+
export interface GhostMainViewDecl {
/** 侧边栏与主视图标题;缺省回退插件 name。 */
title?: string;
@@ -171,6 +176,12 @@ export interface GhostMainViewDecl {
icon?: GhostMainViewIcon;
/** 主视图界面入口(安装目录内安全相对路径)。 */
html: string;
+ /** 左侧导航入口点击后的默认打开方式;缺省 page。 */
+ open?: GhostMainViewOpenMode;
+ /** open:'sidebar' 时的默认边;其它 open 值下声明拒装。 */
+ side?: GhostTabSide;
+ /** 允许同一视图同时开在多处;缺省单实例。只接受字面量 true。 */
+ multiple?: true;
}
/**
@@ -1575,13 +1586,6 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
};
}
if (p.position !== undefined) {
- if (p.position === 'top' || p.position === 'bottom') {
- // 收词但明确拒绝(规则 9 不静默降级):上下停靠等布局引擎嵌套分割就绪后开放。
- return {
- ok: false,
- reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / right / tab',
- };
- }
if (!(GHOST_PANEL_POSITIONS as readonly string[]).includes(p.position as string)) {
return {
ok: false,
@@ -1593,7 +1597,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
return {
ok: false,
reason:
- "panel.minWidth / panel.defaultFraction 仅停靠形态(left / right)有效,position:'tab' 时请移除",
+ "panel.minWidth / panel.defaultFraction 仅停靠形态(left / right / top / bottom)有效,position:'tab' 时请移除",
};
}
}
@@ -1638,10 +1642,35 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
reason: 'mainView.html 必填,且必须是安装目录内的安全相对路径',
};
}
+ if (
+ raw.mainView.open !== undefined &&
+ !(GHOST_MAIN_VIEW_OPEN_MODES as readonly unknown[]).includes(raw.mainView.open)
+ ) {
+ return {
+ ok: false,
+ reason: `mainView.open 必须是 ${GHOST_MAIN_VIEW_OPEN_MODES.join(' / ')}`,
+ };
+ }
+ if (raw.mainView.multiple !== undefined && raw.mainView.multiple !== true) {
+ return { ok: false, reason: 'mainView.multiple 只接受字面量 true(不需要时省略)' };
+ }
+ if (raw.mainView.side !== undefined) {
+ if (raw.mainView.open !== 'sidebar') {
+ return { ok: false, reason: "mainView.side 只在 open:'sidebar' 时有效,其它打开方式请移除" };
+ }
+ if (!(GHOST_TAB_SIDES as readonly unknown[]).includes(raw.mainView.side)) {
+ return { ok: false, reason: `mainView.side 必须是 ${GHOST_TAB_SIDES.join(' / ')}` };
+ }
+ }
mainView = {
- ...unknownDeclarationFields(raw.mainView, ['html', 'title', 'icon']),
+ ...unknownDeclarationFields(raw.mainView, ['html', 'title', 'icon', 'open', 'side', 'multiple']),
...(raw.mainView.title !== undefined ? { title: raw.mainView.title } : {}),
...(raw.mainView.icon !== undefined ? { icon: raw.mainView.icon as GhostMainViewIcon } : {}),
+ ...(raw.mainView.open !== undefined
+ ? { open: raw.mainView.open as GhostMainViewOpenMode }
+ : {}),
+ ...(raw.mainView.side !== undefined ? { side: raw.mainView.side as GhostTabSide } : {}),
+ ...(raw.mainView.multiple === true ? { multiple: true as const } : {}),
html: raw.mainView.html,
};
}