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。

弹出窗口改为多页签的页签组

Dash065783d1e6cb
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 26663bca42..31ab8b3d8d 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
@@ -139,7 +139,7 @@ function makeHarness() {
};
}
-const request = (tabId: string, sessionId = 's1') => ({
+const request = (tabId: string, sessionId: string | null = 's1') => ({
tabId,
sessionId,
context: { workdir: '/repo', remoteHostId: null, deviceLinkDeviceId: null },
@@ -170,8 +170,14 @@ describe('SidebarTabWindowsController', () => {
// spare 被直接消费,没有再冷建窗口;指派随即送达(壳已就绪)。
expect(h.created).toHaveLength(1);
const assigned = h.sends.find((s) => s.channel === SIDEBAR_TAB_WINDOW_ASSIGNED_CHANNEL);
- expect(assigned?.payload).toMatchObject({ tabId: 'tab-a', sessionId: 's1' });
- expect(h.controller.getState()).toEqual({ 'tab-a': { sessionId: 's1', open: true } });
+ expect(assigned?.payload).toMatchObject({
+ windowId: 'w1',
+ sessionId: 's1',
+ tabs: [{ tabId: 'tab-a', sessionId: 's1' }],
+ });
+ expect(h.controller.getState()).toEqual({
+ 'tab-a': { windowId: 'w1', sessionId: 's1', open: true },
+ });
// 首份内容前不显示。
expect(spare.show).not.toHaveBeenCalled();
h.controller.markPresentationReady(h.wc(spare));
@@ -206,7 +212,9 @@ describe('SidebarTabWindowsController', () => {
1,
);
// 重载后的 renderer 主动取指派也拿得到同一份。
- expect(h.controller.getAssignment(h.wc(win))).toMatchObject({ tabId: 'tab-a' });
+ expect(h.controller.getAssignment(h.wc(win))).toMatchObject({
+ tabs: [{ tabId: 'tab-a', sessionId: 's1' }],
+ });
expect(win.show).not.toHaveBeenCalled();
// 同一页签再次 open = 聚焦已有窗口,不建第二扇。
@@ -227,13 +235,13 @@ describe('SidebarTabWindowsController', () => {
sessionId: 's1',
tab: { id: 'tab-a', kind: 'web-browser', state: { url: 'x' } },
};
- h.controller.mergeBack(h.wc(win), snapshot);
+ h.controller.mergeBack(h.wc(win), 'tab-a', snapshot);
expect(win.destroy).toHaveBeenCalledOnce();
expect(h.returned).toEqual([{ sessionId: 's1', tabId: 'tab-a', snapshot, reason: 'merge' }]);
expect(h.broadcasts.at(-1)).toEqual({});
expect(h.controller.getWebContentsForTab('tab-a')).toBeNull();
// 未知 sender 的 merge-back 被忽略。
- h.controller.mergeBack({} as WebContents, null);
+ h.controller.mergeBack({} as WebContents, 'tab-a', null);
expect(h.returned).toHaveLength(1);
});
@@ -274,6 +282,85 @@ describe('SidebarTabWindowsController', () => {
]);
});
+ // 测试价值
+ // - 生产入口与可观察结果:open({targetWindowId}) / adoptTab / 按页签 mergeBack / closeForTab;
+ // 可观察的是同任务页签搬进已有窗口后指派重发为全量、状态按 tabId 指向同一 windowId、
+ // 只摘一个页签时窗口留着且重发指派、窗口清空才销毁、别的任务的页签不进这扇窗(新开)、
+ // 崩溃时窗口里全部页签都交回。
+ // - Bug / 规则依据:弹出窗口 = 住在别的窗口里的页签组(本 PR)。
+ // - 现有覆盖缺口:其余用例都是单页签窗口。
+ // - 最小失败输入:两个同任务页签 + targetWindowId。
+ // - tier:unit(mock deps)。
+ it('hosts several tabs per window: move-in, adopt, per-tab merge/close, crash returns all', () => {
+ const h = makeHarness();
+ h.controller.open(request('tab-a'));
+ const win = h.created[0];
+ h.controller.markRendererReady(h.wc(win));
+ h.controller.markPresentationReady(h.wc(win));
+
+ // 同任务页签搬进已有窗口:不建新窗,指派重发全量,状态指向同一扇窗。
+ h.controller.open({ ...request('tab-b'), targetWindowId: 'w1' });
+ expect(h.created).toHaveLength(1);
+ const assigned = h.sends.filter((s) => s.channel === SIDEBAR_TAB_WINDOW_ASSIGNED_CHANNEL);
+ expect(assigned.at(-1)?.payload).toMatchObject({
+ windowId: 'w1',
+ tabs: [
+ { tabId: 'tab-a', sessionId: 's1' },
+ { tabId: 'tab-b', sessionId: 's1' },
+ ],
+ });
+ expect(h.controller.getState()).toEqual({
+ 'tab-a': { windowId: 'w1', sessionId: 's1', open: true },
+ 'tab-b': { windowId: 'w1', sessionId: 's1', open: true },
+ });
+ expect(h.controller.getWebContentsForTab('tab-b')).toBe(h.wc(win));
+
+ // 全局页签可以进任何窗口;别的任务的页签进不来 → 新开一扇。
+ h.controller.open({ ...request('tab-g', null), targetWindowId: 'w1' });
+ expect(h.created).toHaveLength(1);
+ h.controller.open({ ...request('tab-x', 's2'), targetWindowId: 'w1' });
+ expect(h.created).toHaveLength(2);
+ expect(h.controller.getState()['tab-x']).toMatchObject({ windowId: 'w2', sessionId: 's2' });
+
+ // 窗口里新建的页签被收编;别的 sender 收编无效。
+ h.controller.adoptTab(h.wc(win), 'tab-new', 's1');
+ h.controller.adoptTab({} as WebContents, 'tab-nope', 's1');
+ expect(Object.keys(h.controller.getState())).toEqual(
+ expect.arrayContaining(['tab-a', 'tab-b', 'tab-g', 'tab-new']),
+ );
+ expect(h.controller.isTabPoppedOut('tab-nope')).toBe(false);
+
+ // 合并回一个页签:窗口留着,指派重发,只交回那一个。
+ h.controller.mergeBack(h.wc(win), 'tab-b', null);
+ expect(win.isDestroyed()).toBe(false);
+ expect(h.returned).toEqual([
+ { sessionId: 's1', tabId: 'tab-b', snapshot: null, reason: 'merge' },
+ ]);
+ expect(h.controller.isTabPoppedOut('tab-b')).toBe(false);
+ expect(
+ (
+ h.sends.filter((s) => s.channel === SIDEBAR_TAB_WINDOW_ASSIGNED_CHANNEL).at(-1)
+ ?.payload as { tabs: { tabId: string }[] }
+ ).tabs.map((tab) => tab.tabId),
+ ).toEqual(['tab-a', 'tab-g', 'tab-new']);
+
+ // 窗口里关掉一个页签:摘掉不交回,窗口留着。
+ h.controller.closeForTab('tab-new');
+ expect(win.isDestroyed()).toBe(false);
+ expect(h.returned).toHaveLength(1);
+
+ // 崩溃:剩下的页签全部交回。
+ win.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });
+ expect(win.destroy).toHaveBeenCalledOnce();
+ 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 },
+ });
+ });
+
it('closes a window whose tab was closed in the sidebar without returning the tab', () => {
const h = makeHarness();
h.controller.open(request('tab-a'));
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 fd585e14a2..d25264495d 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
@@ -30,7 +30,10 @@ vi.mock('../../security/trustedAppRenderer.js', () => ({
import { ipcMain, type BrowserWindow } from 'electron';
import { MAKER_INVOKE } from '../../maker-ipc/channels.js';
-import { SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL } from '../../../shared/sidebarTabWindow.js';
+import {
+ SIDEBAR_TAB_WINDOW_ADOPT_TAB_CHANNEL,
+ SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL,
+} from '../../../shared/sidebarTabWindow.js';
import { registerSidebarTabWindowIpc } from '../ipc.js';
import type { SidebarTabWindowsController } from '../controller.js';
@@ -57,7 +60,12 @@ function makeController() {
getAssignment: vi.fn(() => null),
markRendererReady: vi.fn(),
markPresentationReady: vi.fn(),
- slotForSender: vi.fn<(sender: unknown) => { assignment: { tabId: string } } | null>(() => null),
+ slotForSender: vi.fn<(sender: unknown) => { assignment: { tabs: { tabId: string }[] } } | null>(
+ () => null,
+ ),
+ slotOwnsTab: (slot: { assignment: { tabs: { tabId: string }[] } }, tabId: string) =>
+ slot.assignment.tabs.some((tab) => tab.tabId === tabId),
+ adoptTab: vi.fn(),
};
}
@@ -141,7 +149,7 @@ describe('sidebar-tab-window IPC', () => {
it('lets the main window or the owning tab window close a window for a closed tab, nobody else', async () => {
const controller = makeController();
controller.slotForSender.mockImplementation((sender: unknown) =>
- sender === otherSender ? { assignment: { tabId: 'tab-a' } } : null,
+ sender === otherSender ? { assignment: { tabs: [{ tabId: 'tab-a' }] } } : null,
);
register(controller);
const close = handlers().get(MAKER_INVOKE.SIDEBAR_TAB_WINDOW_CLOSE_FOR_TAB)!;
@@ -156,30 +164,42 @@ describe('sidebar-tab-window IPC', () => {
expect(controller.closeForTab).toHaveBeenCalledTimes(2);
});
- it('accepts merge-back only from a managed tab window and validates the snapshot', async () => {
+ it('accepts merge-back only from the owning tab window and validates the snapshot', async () => {
const controller = makeController();
controller.slotForSender.mockImplementation((sender: unknown) =>
- sender === otherSender ? { assignment: { tabId: 'tab-a' } } : null,
+ sender === otherSender ? { assignment: { tabs: [{ tabId: 'tab-a' }] } } : null,
);
register(controller);
const merge = handlers().get(SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL)!;
- await call(merge, { sender: mainSender }, null);
+ await call(merge, { sender: mainSender }, { tabId: 'tab-a', snapshot: null });
+ // 别人的页签也不行。
+ await call(merge, { sender: otherSender }, { tabId: 'tab-b', snapshot: null });
expect(controller.mergeBack).not.toHaveBeenCalled();
- await expect(call(merge, { sender: otherSender }, { sessionId: 's1' })).rejects.toThrow(
- /INVALID_PARAMS/,
- );
+ await expect(
+ call(merge, { sender: otherSender }, { tabId: 'tab-a', snapshot: { sessionId: 's1' } }),
+ ).rejects.toThrow(/INVALID_PARAMS/);
await call(
merge,
{ sender: otherSender },
{
- sessionId: 's1',
- tab: { id: 'tab-a', kind: 'terminal', state: { created: true } },
+ tabId: 'tab-a',
+ snapshot: {
+ sessionId: 's1',
+ tab: { id: 'tab-a', kind: 'terminal', state: { created: true } },
+ },
},
);
- expect(controller.mergeBack).toHaveBeenCalledWith(otherSender, {
+ expect(controller.mergeBack).toHaveBeenCalledWith(otherSender, 'tab-a', {
sessionId: 's1',
tab: { id: 'tab-a', kind: 'terminal', state: { created: true } },
});
+
+ // 收编新建页签:只认弹出窗口自身。
+ const adopt = handlers().get(SIDEBAR_TAB_WINDOW_ADOPT_TAB_CHANNEL)!;
+ await call(adopt, { sender: mainSender }, { tabId: 'tab-n', sessionId: 's1' });
+ expect(controller.adoptTab).not.toHaveBeenCalled();
+ await call(adopt, { sender: otherSender }, { tabId: 'tab-n', sessionId: null });
+ expect(controller.adoptTab).toHaveBeenCalledWith(otherSender, 'tab-n', null);
});
});
diff --git a/apps/desktop/src/main/sidebar-tab-window/controller.ts b/apps/desktop/src/main/sidebar-tab-window/controller.ts
index d6d087c7fa..bdca36c2c1 100644
--- a/apps/desktop/src/main/sidebar-tab-window/controller.ts
+++ b/apps/desktop/src/main/sidebar-tab-window/controller.ts
@@ -1,12 +1,12 @@
/**
- * SidebarTabWindowsController —— 右侧栏单页签独立窗口的状态机(main 侧单例,
+ * SidebarTabWindowsController —— 右侧栏页签独立窗口的状态机(main 侧单例,
* 依赖注入可测)。
*
- * 模型:每个弹出的页签(tabId)一扇窗。主窗的侧边栏继续存在并显示其余页签;
- * 「合并回侧边栏」按钮 = 页签回到侧边栏;关窗(红绿灯 / ⌘W / Windows X)= 关闭该页签
- * (与侧边栏里关页签同一条 store.closeTab 流程,插件清理与确认拦截照常);崩溃 = 页签
- * 回到侧边栏(数据不丢)。没有
- * 「偏好」可落盘:弹出是本次运行期的视图态,客户端重启后所有页签都回到主窗。
+ * 模型:一扇窗口 = 一个住在别的窗口里的页签组,承载同一任务的若干页签 + 任意全局
+ * 页签。主窗的侧边栏继续存在并显示其余页签;「合并回侧边栏」按页签送回,窗口清空即
+ * 销毁;关窗(红绿灯 / Windows X)= 关闭窗口里的全部页签(与侧边栏里关页签同一条
+ * store.closeTab 流程,插件清理与确认拦截照常);崩溃 = 全部页签回到侧边栏(数据不丢)。
+ * 没有「偏好」可落盘:弹出是本次运行期的视图态,客户端重启后所有页签都回到主窗。
*
* 生命周期基线对齐 docs/dev-rules/electron-security-and-process-boundaries.md §3.1
* (资源用量窗口 controller 为权威基线):
@@ -32,7 +32,9 @@ import type {
SidebarTabReturnSnapshot,
SidebarTabReturnedPayload,
SidebarTabWindowAssignment,
+ SidebarTabWindowAssignmentPayload,
SidebarTabWindowOpenRequest,
+ SidebarTabWindowTabRef,
SidebarTabWindowsState,
} from '../../shared/sidebarTabWindow.js';
import {
@@ -66,7 +68,7 @@ const DEFAULT_OPEN_TIMEOUT_MS = 5000;
const SPARE_REPLENISH_DELAY_MS = 1_500;
const MAX_SPARE_RECOVERY_ATTEMPTS = 1;
-interface WindowSlot {
+export interface WindowSlot {
win: BrowserWindow;
/** null = 预热中的 spare,尚未承载任何页签。 */
assignment: SidebarTabWindowAssignment | null;
@@ -82,7 +84,11 @@ interface WindowSlot {
}
export class SidebarTabWindowsController {
+ /** windowId → 已指派的窗口。 */
private readonly slots = new Map<string, WindowSlot>();
+ /** tabId → windowId。 */
+ private readonly tabToWindow = new Map<string, string>();
+ private windowSeq = 0;
private spare: WindowSlot | null = null;
private spareRecoveryAttempts = 0;
private replenishTimer: NodeJS.Timeout | null = null;
@@ -97,12 +103,15 @@ export class SidebarTabWindowsController {
getState(): SidebarTabWindowsState {
const out: SidebarTabWindowsState = {};
- for (const [tabId, slot] of this.slots) {
+ for (const slot of this.slots.values()) {
if (!slot.assignment || slot.win.isDestroyed()) continue;
- out[tabId] = {
- sessionId: slot.assignment.sessionId,
- open: slot.visible || slot.pendingOpen,
- };
+ for (const tab of slot.assignment.tabs) {
+ out[tab.tabId] = {
+ windowId: slot.assignment.windowId,
+ sessionId: tab.sessionId,
+ open: slot.visible || slot.pendingOpen,
+ };
+ }
}
return out;
}
@@ -127,42 +136,99 @@ export class SidebarTabWindowsController {
}
/**
- * 把页签弹出到独立窗口。已弹出则只聚焦。优先消费预热的 spare;没有时冷建
+ * 把页签弹出到独立窗口。已弹出则只聚焦。指定 targetWindowId 且该窗口能接(同一
+ * 任务或任一方是全局)→ 搬进去;否则新开一扇:优先消费预热的 spare,没有时冷建
* (首份内容前不显示,超时展示 Loading 壳)。
*/
open(request: SidebarTabWindowOpenRequest): void {
if (this.disposed) return;
- const existing = this.slots.get(request.tabId);
- if (existing) {
+ if (this.tabToWindow.has(request.tabId)) {
this.focus(request.tabId);
return;
}
+ const target = request.targetWindowId ? this.slots.get(request.targetWindowId) : undefined;
+ if (target?.assignment && !target.win.isDestroyed() && this.canHost(target, request)) {
+ this.addTabToSlot(target, request);
+ this.deliverAssignment(target);
+ this.broadcast();
+ this.focus(request.tabId);
+ this.deps.log.info('sidebar tab moved into window', {
+ tabId: request.tabId,
+ windowId: target.assignment.windowId,
+ });
+ return;
+ }
const slot = this.takeSpare() ?? this.createSlot();
if (!slot) return;
+ const windowId = `w${++this.windowSeq}`;
slot.assignment = {
- tabId: request.tabId,
+ windowId,
sessionId: request.sessionId,
+ tabs: [{ tabId: request.tabId, sessionId: request.sessionId }],
context: request.context,
};
slot.handoff = request.handoff ?? null;
slot.assignmentDelivered = false;
slot.presentationReady = false;
slot.pendingOpen = true;
- this.slots.set(request.tabId, slot);
+ this.slots.set(windowId, slot);
+ this.tabToWindow.set(request.tabId, windowId);
if (slot.rendererReady) this.deliverAssignment(slot);
this.scheduleOpenFallback(slot);
this.broadcast();
this.scheduleSpareReplenish();
this.deps.log.info('sidebar tab window assigned', {
+ windowId,
tabId: request.tabId,
sessionId: request.sessionId,
prewarmed: slot.rendererReady,
});
}
+ /** 窗口能否接下这个页签:全局页签哪里都能去;任务页签只进同任务或尚无任务的窗口。 */
+ private canHost(slot: WindowSlot, request: SidebarTabWindowOpenRequest): boolean {
+ if (!slot.assignment) return false;
+ if (request.sessionId === null || slot.assignment.sessionId === null) return true;
+ return slot.assignment.sessionId === request.sessionId;
+ }
+
+ private addTabToSlot(slot: WindowSlot, request: SidebarTabWindowOpenRequest): void {
+ if (!slot.assignment) return;
+ if (slot.assignment.sessionId === null && request.sessionId !== null) {
+ // 只有全局页签的窗口第一次接任务页签:接过任务上下文(与不可持久化会话的快照)。
+ slot.assignment = {
+ ...slot.assignment,
+ sessionId: request.sessionId,
+ context: request.context,
+ };
+ slot.handoff = request.handoff ?? slot.handoff;
+ }
+ slot.assignment.tabs = [
+ ...slot.assignment.tabs,
+ { tabId: request.tabId, sessionId: request.sessionId },
+ ];
+ this.tabToWindow.set(request.tabId, slot.assignment.windowId);
+ }
+
+ /** 从窗口里摘掉一个页签;返回它的引用(不在该窗口则 null)。不负责销毁 / 广播。 */
+ private removeTabFromSlot(slot: WindowSlot, tabId: string): SidebarTabWindowTabRef | null {
+ if (!slot.assignment) return null;
+ const ref = slot.assignment.tabs.find((tab) => tab.tabId === tabId) ?? null;
+ if (!ref) return null;
+ slot.assignment.tabs = slot.assignment.tabs.filter((tab) => tab.tabId !== tabId);
+ if (this.tabToWindow.get(tabId) === slot.assignment.windowId) this.tabToWindow.delete(tabId);
+ return ref;
+ }
+
+ private slotForTab(tabId: string): WindowSlot | null {
+ const windowId = this.tabToWindow.get(tabId);
+ const slot = windowId ? this.slots.get(windowId) : undefined;
+ return slot ?? null;
+ }
+
/** 聚焦已弹出页签的窗口;未弹出 / 仍在等首份内容时 no-op。 */
focus(tabId: string): void {
- const slot = this.slots.get(tabId);
+ const slot = this.slotForTab(tabId);
if (!slot || slot.win.isDestroyed()) return;
if (!slot.visible) return;
if (slot.win.isMinimized()) slot.win.restore();
@@ -171,25 +237,67 @@ export class SidebarTabWindowsController {
}
/**
- * 页签已在宿主 renderer 里关闭(agent close / 关闭全部 / guest 自关):销毁窗口,
- * 不交回页签。
+ * 页签已在宿主 renderer 里关闭(agent close / 关闭全部 / guest 自关 / 窗口里关页签):
+ * 从窗口里摘掉,不交回;窗口没有页签了就销毁。
*/
closeForTab(tabId: string): void {
- const slot = this.slots.get(tabId);
- if (!slot) return;
- this.disposeSlot(slot);
+ const slot = this.slotForTab(tabId);
+ if (!slot?.assignment) return;
+ this.removeTabFromSlot(slot, tabId);
+ if (slot.assignment.tabs.length === 0) {
+ this.disposeSlot(slot);
+ } else {
+ this.deliverAssignment(slot);
+ }
this.broadcast();
- this.deps.log.info('sidebar tab window closed for closed tab', { tabId });
+ this.deps.log.info('sidebar tab window dropped closed tab', { tabId });
}
- /** 弹出窗口 renderer 请求合并回侧边栏(按钮 / ⌘W / 响应原生关窗请求)。 */
- mergeBack(sender: WebContents, snapshot: SidebarTabReturnSnapshot | null): void {
+ /** 弹出窗口 renderer 请求把某个页签合并回侧边栏(按钮 / 右键菜单)。 */
+ mergeBack(sender: WebContents, tabId: string, snapshot: SidebarTabReturnSnapshot | null): void {
const slot = this.slotForSender(sender);
if (!slot?.assignment) return;
- this.finishSlot(slot, snapshot, 'merge');
+ const ref = this.removeTabFromSlot(slot, tabId);
+ if (!ref) return;
+ if (slot.assignment.tabs.length === 0) {
+ this.disposeSlot(slot);
+ } else {
+ this.deliverAssignment(slot);
+ }
+ if (!this.deps.isQuitting()) {
+ this.deps.notifyTabReturned({
+ sessionId: ref.sessionId,
+ tabId,
+ snapshot: snapshot && snapshot.tab.id === tabId ? snapshot : null,
+ reason: 'merge',
+ });
+ }
+ this.broadcast();
+ this.deps.log.info('sidebar tab merged back', { tabId, withSnapshot: snapshot !== null });
+ }
+
+ /** 弹出窗口 renderer 在自己里面新建了页签:归它承载。已在别处的页签忽略。 */
+ adoptTab(sender: WebContents, tabId: string, sessionId: string | null): void {
+ const slot = this.slotForSender(sender);
+ if (!slot?.assignment || this.tabToWindow.has(tabId)) return;
+ if (
+ sessionId !== null &&
+ slot.assignment.sessionId !== null &&
+ slot.assignment.sessionId !== sessionId
+ ) {
+ this.deps.log.warn('adopt tab rejected: session mismatch', { tabId, sessionId });
+ return;
+ }
+ if (slot.assignment.sessionId === null && sessionId !== null) {
+ slot.assignment = { ...slot.assignment, sessionId };
+ }
+ slot.assignment.tabs = [...slot.assignment.tabs, { tabId, sessionId }];
+ this.tabToWindow.set(tabId, slot.assignment.windowId);
+ this.deliverAssignment(slot);
+ this.broadcast();
}
- getAssignment(sender: WebContents): SidebarTabWindowOpenRequest | null {
+ getAssignment(sender: WebContents): SidebarTabWindowAssignmentPayload | null {
const slot = this.slotForSender(sender);
if (!slot?.assignment) return null;
slot.assignmentDelivered = true;
@@ -229,16 +337,21 @@ export class SidebarTabWindowsController {
/** 页签所在弹出窗口的 WebContents;未弹出返回 null。tab-op / 命令按页签路由用。 */
getWebContentsForTab(tabId: string): WebContents | null {
- const slot = this.slots.get(tabId);
+ const slot = this.slotForTab(tabId);
if (!slot || slot.win.isDestroyed()) return null;
return slot.win.webContents;
}
isTabPoppedOut(tabId: string): boolean {
- const slot = this.slots.get(tabId);
+ const slot = this.slotForTab(tabId);
return Boolean(slot && !slot.win.isDestroyed());
}
+ /** 某窗口承载哪些页签(IPC 的 sender 归属校验用)。 */
+ slotOwnsTab(slot: WindowSlot, tabId: string): boolean {
+ return slot.assignment?.tabs.some((tab) => tab.tabId === tabId) ?? false;
+ }
+
// ── 生命周期 ────────────────────────────────────────────────────────
/** 主窗口销毁时回收所有窗口(含 spare);主窗 renderer 已不在,不交回页签。 */
@@ -254,6 +367,7 @@ export class SidebarTabWindowsController {
}
}
this.slots.clear();
+ this.tabToWindow.clear();
this.spare = null;
this.spareRecoveryAttempts = 0;
}
@@ -333,11 +447,14 @@ export class SidebarTabWindowsController {
private deliverAssignment(slot: WindowSlot): void {
if (!slot.assignment || slot.win.isDestroyed()) return;
+ // 壳还没挂上:等 renderer-ready 时再送(它会主动 getAssignment / 收推送)。
+ if (!slot.rendererReady) return;
slot.assignmentDelivered = true;
- this.deps.sendToWindow(slot.win, SIDEBAR_TAB_WINDOW_ASSIGNED_CHANNEL, {
+ const payload: SidebarTabWindowAssignmentPayload = {
...slot.assignment,
handoff: slot.handoff,
- });
+ };
+ this.deps.sendToWindow(slot.win, SIDEBAR_TAB_WINDOW_ASSIGNED_CHANNEL, payload);
}
private showAndFocus(slot: WindowSlot): void {
@@ -377,54 +494,61 @@ export class SidebarTabWindowsController {
}
if (slot.rendererReady) {
// 每次关窗手势都转达:上一次可能被插件的确认框否决了。关闭流程(插件清理、
- // 确认拦截、落库)全在 renderer 里,页签消失后它再调 close-for-tab。
+ // 确认拦截、落库)全在 renderer 里,页签消失后它再逐个调 close-for-tab。
this.deps.sendToWindow(slot.win, SIDEBAR_TAB_WINDOW_CLOSE_REQUESTED_CHANNEL, undefined);
return;
}
- // renderer 还没挂上(冷开 / 重载中),无人能执行关闭流程:不丢数据,把页签交回侧边栏。
- this.finishSlot(slot, null, 'merge');
+ // renderer 还没挂上(冷开 / 重载中),无人能执行关闭流程:不丢数据,把页签全部交回侧边栏。
+ this.finishSlot(slot, 'merge');
}
- /** 页签离开本窗口:销毁窗口、通知主窗接回页签、广播。 */
- private finishSlot(
- slot: WindowSlot,
- snapshot: SidebarTabReturnSnapshot | null,
- reason: SidebarTabReturnedPayload['reason'],
- ): void {
+ /** 整扇窗口结束:销毁窗口、把它承载的全部页签交回主窗、广播。 */
+ private finishSlot(slot: WindowSlot, reason: SidebarTabReturnedPayload['reason']): void {
const assignment = slot.assignment;
this.disposeSlot(slot);
if (assignment && !this.deps.isQuitting()) {
// 先交回页签再广播状态:主窗 renderer 按序处理,刷新状态时页签尚未重新
// 投影进侧边栏,避免先画旧状态再跳变。
- this.deps.notifyTabReturned({
- sessionId: assignment.sessionId,
- tabId: assignment.tabId,
- snapshot: snapshot && snapshot.tab.id === assignment.tabId ? snapshot : null,
- reason,
- });
+ for (const tab of assignment.tabs) {
+ this.deps.notifyTabReturned({
+ sessionId: tab.sessionId,
+ tabId: tab.tabId,
+ snapshot: null,
+ reason,
+ });
+ }
}
this.broadcast();
this.deps.log.info('sidebar tab window finished', {
- tabId: assignment?.tabId,
+ windowId: assignment?.windowId,
+ tabIds: assignment?.tabs.map((tab) => tab.tabId),
reason,
- withSnapshot: snapshot !== null,
});
}
private onClosed(slot: WindowSlot): void {
this.clearTimeouts(slot);
if (this.spare === slot) this.spare = null;
- const tabId = slot.assignment?.tabId;
- if (tabId !== undefined && this.slots.get(tabId) === slot) this.slots.delete(tabId);
+ const assignment = slot.assignment;
+ if (assignment && this.slots.get(assignment.windowId) === slot) {
+ this.slots.delete(assignment.windowId);
+ for (const tab of assignment.tabs) {
+ if (this.tabToWindow.get(tab.tabId) === assignment.windowId) {
+ this.tabToWindow.delete(tab.tabId);
+ }
+ }
+ }
if (slot.destroyingWindow || this.deps.isQuitting()) return;
// 不经 controller 的销毁(理论上不该发生):页签照样交回侧边栏,不让它消失。
- if (slot.assignment) {
- this.deps.notifyTabReturned({
- sessionId: slot.assignment.sessionId,
- tabId: slot.assignment.tabId,
- snapshot: null,
- reason: 'crash',
- });
+ if (assignment) {
+ for (const tab of assignment.tabs) {
+ this.deps.notifyTabReturned({
+ sessionId: tab.sessionId,
+ tabId: tab.tabId,
+ snapshot: null,
+ reason: 'crash',
+ });
+ }
this.broadcast();
}
}
@@ -496,11 +620,12 @@ export class SidebarTabWindowsController {
this.scheduleSpareReplenish();
return;
}
- this.deps.log.warn('sidebar tab window invalidated, returning tab to sidebar', {
- tabId: slot.assignment.tabId,
+ this.deps.log.warn('sidebar tab window invalidated, returning tabs to sidebar', {
+ windowId: slot.assignment.windowId,
+ tabIds: slot.assignment.tabs.map((tab) => tab.tabId),
reason,
});
- this.finishSlot(slot, null, 'crash');
+ this.finishSlot(slot, 'crash');
}
// ── 销毁 ────────────────────────────────────────────────────────────
@@ -508,8 +633,15 @@ export class SidebarTabWindowsController {
private disposeSlot(slot: WindowSlot): void {
this.clearTimeouts(slot);
if (this.spare === slot) this.spare = null;
- const tabId = slot.assignment?.tabId;
- if (tabId !== undefined && this.slots.get(tabId) === slot) this.slots.delete(tabId);
+ const assignment = slot.assignment;
+ if (assignment && this.slots.get(assignment.windowId) === slot) {
+ this.slots.delete(assignment.windowId);
+ for (const tab of assignment.tabs) {
+ if (this.tabToWindow.get(tab.tabId) === assignment.windowId) {
+ this.tabToWindow.delete(tab.tabId);
+ }
+ }
+ }
slot.destroyingWindow = true;
try {
if (!slot.win.isDestroyed()) slot.win.destroy();
diff --git a/apps/desktop/src/main/sidebar-tab-window/ipc.ts b/apps/desktop/src/main/sidebar-tab-window/ipc.ts
index 6179723b29..8e5b911055 100644
--- a/apps/desktop/src/main/sidebar-tab-window/ipc.ts
+++ b/apps/desktop/src/main/sidebar-tab-window/ipc.ts
@@ -1,10 +1,10 @@
/**
- * registerSidebarTabWindowIpc —— 右侧栏单页签独立窗口的 IPC 注册。
+ * registerSidebarTabWindowIpc —— 右侧栏页签独立窗口的 IPC 注册。
*
* 全部委托给 SidebarTabWindowsController,这里只做:
- * - sender 归属校验:弹出 / 聚焦 / 关闭由主窗发起(弹出窗口自己也可以
- * 对自己承载的页签发 close-for-tab:页签在它里面被 guest 自关时);
- * 就绪握手、取指派、合并回侧边栏只认弹出窗口自身;
+ * - sender 归属校验:弹出 / 搬入 / 聚焦 / 关闭由主窗发起(弹出窗口自己也可以
+ * 对自己承载的页签发 close-for-tab:页签在它里面被关掉 / guest 自关时);
+ * 就绪握手、取指派、合并回侧边栏、收编新建页签只认弹出窗口自身;
* - payload 运行时校验(throwIpcError INVALID_PARAMS)。
*/
@@ -22,6 +22,7 @@ import type {
SidebarTabWindowOpenRequest,
} from '../../shared/sidebarTabWindow.js';
import {
+ SIDEBAR_TAB_WINDOW_ADOPT_TAB_CHANNEL,
SIDEBAR_TAB_WINDOW_GET_ASSIGNMENT_CHANNEL,
SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL,
SIDEBAR_TAB_WINDOW_PRESENTATION_READY_CHANNEL,
@@ -118,12 +119,14 @@ function parseReturnSnapshot(raw: unknown): SidebarTabReturnSnapshot | null {
function parseOpenRequest(raw: unknown): SidebarTabWindowOpenRequest {
const obj = requireObject(raw, 'open request');
+ const targetWindowId = optionalNullableString(obj.targetWindowId, 'targetWindowId');
return {
tabId: requireId(obj.tabId, 'tabId'),
// 全局页签(插件视图)不属于任何任务:sessionId 为 null。
sessionId: optionalNullableString(obj.sessionId, 'sessionId') ?? null,
context: parseContext(obj.context),
handoff: parseHandoff(obj.handoff),
+ ...(targetWindowId ? { targetWindowId } : {}),
};
}
@@ -163,7 +166,7 @@ export function registerSidebarTabWindowIpc(opts: {
assertTrustedAppRendererEvent(event);
const id = requireId(tabId, 'tabId');
const ownSlot = controller.slotForSender(event.sender);
- const ownsTab = ownSlot?.assignment?.tabId === id;
+ const ownsTab = ownSlot ? controller.slotOwnsTab(ownSlot, id) : false;
if (!isMainWindowSender(event.sender) && !ownsTab) {
log.warn('SIDEBAR_TAB_WINDOW_CLOSE_FOR_TAB from unrelated sender, dropped', { tabId: id });
throwIpcError('PERMISSION_DENIED', 'sender does not own this tab');
@@ -188,13 +191,28 @@ export function registerSidebarTabWindowIpc(opts: {
controller.markPresentationReady(event.sender);
});
- ipcMain.handle(SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL, (event, rawSnapshot: unknown) => {
+ ipcMain.handle(SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL, (event, rawRequest: unknown) => {
assertTrustedAppRendererEvent(event);
- const snapshot = parseReturnSnapshot(rawSnapshot);
+ const obj = requireObject(rawRequest, 'merge-back request');
+ const tabId = requireId(obj.tabId, 'tabId');
+ const snapshot = parseReturnSnapshot(obj.snapshot);
+ const slot = controller.slotForSender(event.sender);
+ if (!slot || !controller.slotOwnsTab(slot, tabId)) {
+ log.warn('SIDEBAR_TAB_WINDOW_MERGE_BACK from non-owner sender, ignored', { tabId });
+ return;
+ }
+ controller.mergeBack(event.sender, tabId, snapshot);
+ });
+
+ ipcMain.handle(SIDEBAR_TAB_WINDOW_ADOPT_TAB_CHANNEL, (event, rawRequest: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const obj = requireObject(rawRequest, 'adopt request');
+ const tabId = requireId(obj.tabId, 'tabId');
+ const sessionId = optionalNullableString(obj.sessionId, 'sessionId') ?? null;
if (!controller.slotForSender(event.sender)) {
- log.warn('SIDEBAR_TAB_WINDOW_MERGE_BACK from non-tab-window sender, ignored');
+ log.warn('SIDEBAR_TAB_WINDOW_ADOPT_TAB from non-tab-window sender, ignored', { tabId });
return;
}
- controller.mergeBack(event.sender, snapshot);
+ controller.adoptTab(event.sender, tabId, sessionId);
});
}
diff --git a/apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts b/apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts
index 9e6112f14b..4270c1bf18 100644
--- a/apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts
+++ b/apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts
@@ -50,7 +50,7 @@ describe('Ghost panel media IPC bridge', () => {
});
-describe.each(['preload.ts', 'ghostPanelWindowPreload.ts', 'sidebarWindowPreload.ts'])('%s media bridge', (filename) => {
+describe.each(['preload.ts', 'sidebarWindowPreload.ts'])('%s media bridge', (filename) => {
it('forwards the confirmed install approval while preserving calls without it', async () => {
const invoke = vi.fn().mockResolvedValue({ ok: true });
const setEnabled = loadResolvePanelMedia(invoke, filename, 'setEnabled');
diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.ts
index 7708989ec4..38b810eac1 100644
--- a/apps/desktop/src/preload/sidebarWindowPreload.ts
+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts
@@ -32,6 +32,7 @@ import {
} from '../shared/rightSidebarWindow';
import type { RsbWindowTabHandoff } from '../shared/rightSidebarWindow';
import {
+ SIDEBAR_TAB_WINDOW_ADOPT_TAB_CHANNEL,
SIDEBAR_TAB_WINDOW_ASSIGNED_CHANNEL,
SIDEBAR_TAB_WINDOW_GET_ASSIGNMENT_CHANNEL,
SIDEBAR_TAB_WINDOW_LOCALE_CHANGED_CHANNEL,
@@ -42,8 +43,9 @@ import {
SIDEBAR_TAB_WINDOW_VISIBILITY_CHANGED_CHANNEL,
} from '../shared/sidebarTabWindow';
import type {
- SidebarTabReturnSnapshot,
- SidebarTabWindowOpenRequest,
+ SidebarTabWindowAdoptRequest,
+ SidebarTabWindowAssignmentPayload,
+ SidebarTabWindowMergeBackRequest,
SidebarTabWindowsState,
} from '../shared/sidebarTabWindow';
@@ -414,16 +416,20 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** 本窗口承载的页签已被关闭:销毁本窗口,不交回页签。 */
closeForTab: (tabId: string): Promise<void> =>
ipcRenderer.invoke('maker:sidebar-tab-window:close-for-tab', tabId),
- getAssignment: (): Promise<SidebarTabWindowOpenRequest | null> =>
+ getAssignment: (): Promise<SidebarTabWindowAssignmentPayload | null> =>
ipcRenderer.invoke(SIDEBAR_TAB_WINDOW_GET_ASSIGNMENT_CHANNEL),
- onAssigned: (cb: (assignment: SidebarTabWindowOpenRequest) => void): (() => void) =>
+ onAssigned: (cb: (assignment: SidebarTabWindowAssignmentPayload) => void): (() => void) =>
onPayload(SIDEBAR_TAB_WINDOW_ASSIGNED_CHANNEL, cb),
rendererReady: (): Promise<void> =>
ipcRenderer.invoke(SIDEBAR_TAB_WINDOW_RENDERER_READY_CHANNEL),
presentationReady: (): Promise<void> =>
ipcRenderer.invoke(SIDEBAR_TAB_WINDOW_PRESENTATION_READY_CHANNEL),
- mergeBack: (snapshot: SidebarTabReturnSnapshot | null): Promise<void> =>
- ipcRenderer.invoke(SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL, snapshot),
+ /** 把本窗口里的某个页签合并回侧边栏(窗口清空后 main 关窗)。 */
+ mergeBack: (request: SidebarTabWindowMergeBackRequest): Promise<void> =>
+ ipcRenderer.invoke(SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL, request),
+ /** 本窗口里新建的页签归本窗口承载。 */
+ adoptTab: (request: SidebarTabWindowAdoptRequest): Promise<void> =>
+ ipcRenderer.invoke(SIDEBAR_TAB_WINDOW_ADOPT_TAB_CHANNEL, request),
onCloseRequested: (cb: () => void): (() => void) =>
onPayload(SIDEBAR_TAB_WINDOW_CLOSE_REQUESTED_CHANNEL, cb),
onVisibilityChanged: (cb: (payload: { visible: boolean }) => void): (() => void) =>
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 9dc378f0c2..c3e2a8f6cc 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -1102,10 +1102,11 @@ export function MainLayout() {
// 弹出前释放本窗对该页签的独占资源:浏览器 webview 归还池(弹出窗口会重新
// 物化并向 main 重新登记),终端标记 PTY 未附着(弹出窗口 re-attach 抢走 sink,
// 交回后本窗必须再 attach 一次)。不可持久化会话附整桶内存快照。
- const handleDetachRightSidebarTab = useCallback((tabId: string) => {
+ const handleDetachRightSidebarTab = useCallback((tabId: string, targetWindowId?: string) => {
if (isSecondaryWindow()) return;
const api = window.electronAPI.sidebarTabWindow;
if (!api?.open) return;
+ const target = targetWindowId ? { targetWindowId } : {};
const info = rightSidebarWorkdirInfoRef.current;
const context = {
workdir: info.workdir || null,
@@ -1115,7 +1116,7 @@ export function MainLayout() {
};
// 全局页签(插件视图)不属于任何任务:无桶快照,也没有任务级资源要释放。
if (findGlobalTab(tabId)) {
- void api.open({ tabId, sessionId: null, context, handoff: null }).catch((err) => {
+ void api.open({ tabId, sessionId: null, context, handoff: null, ...target }).catch((err) => {
applicationMenuLog.warn('pop out global sidebar tab failed', { tabId, err });
});
return;
@@ -1127,7 +1128,7 @@ export function MainLayout() {
if (tab.kind === 'web-browser') browserWebviewPool.release(tabId);
if (tab.kind === 'terminal') markPtyDetached(tabId);
void api
- .open({ tabId, sessionId, context, handoff: getTabSnapshot(sessionId) })
+ .open({ tabId, sessionId, context, handoff: getTabSnapshot(sessionId), ...target })
.catch((err) => {
applicationMenuLog.warn('pop out sidebar tab failed', { sessionId, tabId, err });
});
diff --git a/apps/desktop/src/renderer/components/layout/RightSidebar.tsx b/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
index 5fa62080d3..f160b5026c 100644
--- a/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
+++ b/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
@@ -78,7 +78,7 @@ interface RightSidebarProps {
railChromeActionsHitHole?: boolean;
/** 「在独立窗口中打开」某个页签:主窗侧栏继续存在,只把该页签弹出到自己的窗口。
* Shell 的顶栏按钮作用于当前页签,页签右键菜单作用于被点的页签。 */
- onDetachTab?: (tabId: string) => void;
+ onDetachTab?: (tabId: string, targetWindowId?: string) => void;
/** M2(mac 交换态):面板当前贴哪条边。透传给 Shell —— 'left' 时 Shell 顶栏
* 右端渲染 detach / maximize 真按钮(折叠 toggle 恒在 MainLayout 窗口右上浮层)。 */
panelSide?: 'left' | 'right';
diff --git a/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx
index 1c52ea691b..fe0dc89905 100644
--- a/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx
@@ -1,22 +1,22 @@
/**
- * SidebarTabWindowLayout —— 右侧栏单页签独立窗口的根组件。
+ * SidebarTabWindowLayout —— 右侧栏页签独立窗口的根组件(一扇窗 = 住在别的窗口里的页签组)。
*
* 窗口由 main/sidebar-tab-window/window.ts 打开(`?sidebarWindow=1&sidebarTabWindow=1`),
* 由 sidebar-window-entry.tsx 分流进来。本组件:
- * - 等 main 指派页签(预热的 spare 窗口在壳挂载后才收到指派;重载时主动
- * getAssignment 拿回):登记 soloTabId、导入不可持久化会话的内存快照,再把
- * 会话交给 RightSidebarShell(soloTabId 形态:只投影 / 挂载这一个页签)。
- * - 双阶段就绪握手:mount → rendererReady;被指派页签所在桶水合且页签在场 →
- * presentationReady,main 这时才 show。
- * - 46px 自绘 chrome:整条 drag region;mac 左端红绿灯让位、win 右端 WindowControls
- * (close = 合并回侧边栏);中部页签图标 + 标题(复用插件的 TabPillIcon /
- * TabPillTitle);右端「合并回侧边栏」按钮。
- * - 「合并回侧边栏」(按钮 / 协同页签「在主窗查看」):不可持久化会话附本页签内存态,
- * main 销毁窗口并把页签交回主窗。
- * - 关窗 = 关闭页签(⌘W / 红绿灯 / Windows X / 原生关窗请求):走 store.closeTab,
- * 与侧边栏里关页签同一流程(插件 onBeforeClose、确认拦截照常,被否决则窗口留着)。
- * - 页签从桶里消失(上面的关闭 / guest 自关 / agent close):通知 main 销毁窗口
- * (不交回)。
+ * - 等 main 指派(预热的 spare 窗口在壳挂载后才收到指派;重载时主动 getAssignment
+ * 拿回;页签加入 / 离开时 main 重发全量):登记本窗口承载的页签、导入不可持久化
+ * 会话的内存快照,再把会话交给 RightSidebarShell(hostedTabIds 形态:只投影 / 挂载
+ * 这些页签,页签条与「+」照常,激活位只在本窗口内存里)。
+ * - 双阶段就绪握手:mount → rendererReady;至少一个被指派页签在场 → presentationReady,
+ * main 这时才 show。
+ * - 46px 自绘 chrome 由 Shell 的合并顶栏承担:mac 左端红绿灯让位、页签条、右端
+ * 「合并回侧边栏」(当前页签)+ win 端 WindowControls(close = 关闭全部页签)。
+ * - 「合并回侧边栏」(按钮 / 右键菜单 / 协同页签「在主窗查看」):按页签交回(不可持久化
+ * 会话附内存态);窗口清空后 main 关窗。
+ * - 关窗 = 关闭全部页签(红绿灯 / Windows X / 原生关窗请求);⌘W = 关闭当前页签。
+ * 都走 store.closeTab,与侧边栏里关页签同一流程(插件 onBeforeClose、确认拦截照常,
+ * 被否决则留着)。页签从桶里消失后通知 main 从本窗口摘掉(不交回),最后一个离开即关窗。
+ * - 「+」新建的页签乐观登记为本窗口承载并请 main 收编,主窗不会把它画出来。
* - 显隐推送:隐藏时模糊焦点、重挂 chrome(复用隐藏窗口不继承上次 hover 态)。
*
* 与 SidebarWindowLayout 一样挂 useDeviceLinkRemoteProjects / makerChatStore 监听:
@@ -31,15 +31,18 @@ import { RightSidebarShell } from '@/features/right-sidebar/RightSidebarShell';
import { ToastContainer } from '@/components/ui/toast';
import { useDeviceLinkRemoteProjects } from '@/features/device-link/useDeviceLinkRemoteProjects';
import { mergeSidebarWindowBack } from '@/features/right-sidebar/lib/mergeSidebarWindowBack';
-import { setSoloTabId } from '@/features/right-sidebar/lib/tabHosting';
-import { getTabKind, hydrateTabState } from '@/features/right-sidebar/registry';
+import {
+ addHostedTabId,
+ setHostedTabIds,
+ useHostedTabIds,
+} from '@/features/right-sidebar/lib/tabHosting';
import { closeTab, getBucket, importTabSnapshot, subscribe } from '@/features/right-sidebar/store';
import {
findGlobalTab,
+ isGlobalTabId,
removeGlobalTab,
useGlobalTabs,
} from '@/features/right-sidebar/globalTabs';
-import { iconForTabKind, labelKeyForTabKind } from '@/features/right-sidebar/TabBar';
import { WindowControls } from '@/components/title-bar/WindowControls';
import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';
import { useAppShortcut } from '@/hooks/useAppShortcut';
@@ -49,7 +52,10 @@ import { createLogger } from '@/lib/logger';
import { makerChatStore } from '@/lib/makerChatStore';
import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';
import { ensureGhostPanelsRegistered, useGhostPanelsSync } from '@/cindy-brain/ghostPanels';
-import type { SidebarTabWindowOpenRequest } from '../../../shared/sidebarTabWindow';
+import type {
+ SidebarTabWindowAssignmentPayload,
+ SidebarTabWindowTabRef,
+} from '../../../shared/sidebarTabWindow';
const log = createLogger('SidebarTabWindowLayout');
@@ -65,23 +71,24 @@ export function SidebarTabWindowLayout() {
}, []);
const isMac = window.electronAPI?.platform === 'darwin';
const api = window.electronAPI?.sidebarTabWindow;
- const [assignment, setAssignment] = useState<SidebarTabWindowOpenRequest | null>(null);
+ const [assignment, setAssignment] = useState<SidebarTabWindowAssignmentPayload | null>(null);
const [windowVisible, setWindowVisible] = useState(false);
useDeviceLinkRemoteProjects(windowVisible, 'sidebar');
const presentationReadySentRef = useRef(false);
- const leavingRef = useRef(false);
+ /** 已向 main 报过「在本窗口里消失了」的页签,避免重复 close-for-tab。 */
+ const reportedGoneRef = useRef(new Set<string>());
const [windowChromeRevision, setWindowChromeRevision] = useState(0);
+ const [activeTabId, setActiveTabId] = useState<string | null>(null);
- const applyAssignment = useCallback((next: SidebarTabWindowOpenRequest) => {
- setAssignment((prev) => {
- if (prev?.tabId === next.tabId && prev.sessionId === next.sessionId) return prev;
- // 必须早于 Shell 的 ensureHydrated:不可持久化会话只能从这份快照水合。
- if (next.handoff) importTabSnapshot(next.handoff);
- setSoloTabId(next.tabId);
- leavingRef.current = false;
- presentationReadySentRef.current = false;
- return next;
- });
+ const applyAssignment = useCallback((next: SidebarTabWindowAssignmentPayload) => {
+ // 必须早于 Shell 的 ensureHydrated:不可持久化会话只能从这份快照水合。
+ if (next.handoff) importTabSnapshot(next.handoff);
+ setHostedTabIds(next.tabs.map((tab) => tab.tabId));
+ const stillAssigned = new Set(next.tabs.map((tab) => tab.tabId));
+ for (const id of [...reportedGoneRef.current]) {
+ if (!stillAssigned.has(id)) reportedGoneRef.current.delete(id);
+ }
+ setAssignment(next);
}, []);
// mount:订阅指派推送 + 主动拉一次(重载 / 推送早于订阅)+ renderer-ready 握手。
@@ -126,7 +133,6 @@ export function SidebarTabWindowLayout() {
}, [api]);
const sessionId = assignment?.sessionId ?? null;
- const tabId = assignment?.tabId ?? null;
const subscribeBucket = useCallback(
(onChange: () => void) =>
subscribe((changedSessionId) => {
@@ -136,122 +142,148 @@ export function SidebarTabWindowLayout() {
);
const getBucketSnapshot = useCallback(() => getBucket(sessionId), [sessionId]);
const bucket = useSyncExternalStore(subscribeBucket, getBucketSnapshot);
- // 全局页签(插件视图,sessionId=null)不在任务桶里,从全局存储找;它不需要任务桶水合。
const globalTabs = useGlobalTabs();
- const isGlobal = assignment !== null && assignment.sessionId === null;
- const tab = useMemo(() => {
- if (!tabId) return null;
- if (isGlobal) return globalTabs.find((candidate) => candidate.id === tabId) ?? null;
- return bucket.tabs.find((candidate) => candidate.id === tabId) ?? null;
- }, [bucket.tabs, globalTabs, isGlobal, tabId]);
- const contentReady = isGlobal || bucket.hydrated;
+ const hostedTabIds = useHostedTabIds();
+ // 任务桶水合后才知道任务页签在不在;只有全局页签的窗口不需要任务桶。
+ const needsBucket = assignment?.tabs.some((tab) => tab.sessionId !== null) ?? false;
+ const contentReady = assignment !== null && (!needsBucket || bucket.hydrated);
+ const isPresent = useCallback(
+ (ref: SidebarTabWindowTabRef) =>
+ ref.sessionId === null
+ ? globalTabs.some((tab) => tab.id === ref.tabId)
+ : bucket.tabs.some((tab) => tab.id === ref.tabId),
+ [bucket.tabs, globalTabs],
+ );
+ const presentTabs = useMemo(
+ () => (assignment ? assignment.tabs.filter(isPresent) : []),
+ [assignment, isPresent],
+ );
- // presentation-ready:被指派页签的桶已水合且页签在场 → main 可以展示窗口。
+ // presentation-ready:至少一个被指派页签在场 → main 可以展示窗口。
useEffect(() => {
- if (presentationReadySentRef.current || !assignment || !contentReady || !tab) return;
+ if (presentationReadySentRef.current || !contentReady || presentTabs.length === 0) return;
presentationReadySentRef.current = true;
void api?.presentationReady?.().catch((err) => {
log.warn('presentation-ready handshake failed', err);
});
- }, [api, assignment, contentReady, tab]);
+ }, [api, contentReady, presentTabs.length]);
- // 页签已不在桶 / 全局列表里(本窗口内被关闭):销毁本窗口,不交回。
+ // 页签已不在桶 / 全局列表里(本窗口内被关闭 / 别处关掉):请 main 从本窗口摘掉,不交回;
+ // 最后一个离开时 main 销毁窗口。
useEffect(() => {
- if (!assignment || !contentReady || tab || leavingRef.current) return;
- leavingRef.current = true;
- void api?.closeForTab(assignment.tabId).catch((err) => {
- leavingRef.current = false;
- log.warn('close window for closed tab failed', err);
- });
- }, [api, assignment, contentReady, tab]);
+ if (!assignment || !contentReady) return;
+ for (const ref of assignment.tabs) {
+ if (isPresent(ref) || reportedGoneRef.current.has(ref.tabId)) 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]);
- const mergeBack = useCallback(() => {
- if (!assignment || leavingRef.current) return;
- leavingRef.current = true;
- void mergeSidebarWindowBack(assignment.sessionId).catch((err) => {
- leavingRef.current = false;
- log.warn('merge tab back failed', err);
- });
- }, [assignment]);
+ const refFor = useCallback(
+ (tabId: string) => assignment?.tabs.find((tab) => tab.tabId === tabId) ?? null,
+ [assignment],
+ );
- // 关窗 = 关闭这个页签。closeTab 内部跑插件 onBeforeClose / 确认拦截,被否决就什么
- // 都不发生;页签真的消失后,上面的 effect 再请求 main 销毁窗口。
- const closeOwnTab = useCallback(() => {
- if (!assignment || leavingRef.current) return;
- if (assignment.sessionId === null) {
- // 全局页签:关闭是全局动作,列表变化后上面的 effect 收窗。
- if (findGlobalTab(assignment.tabId)) removeGlobalTab(assignment.tabId);
- return;
- }
- void closeTab(assignment.sessionId, assignment.tabId).catch((err) => {
- log.warn('close popped-out tab failed', err);
- });
- }, [assignment]);
+ const mergeBackTab = useCallback(
+ (tabId: string) => {
+ const ref = refFor(tabId);
+ if (!ref) return;
+ void mergeSidebarWindowBack(ref.sessionId, tabId).catch((err) => {
+ log.warn('merge tab back failed', { tabId, err });
+ });
+ },
+ [refFor],
+ );
+
+ // 关页签走与侧边栏同一条流程(插件 onBeforeClose / 确认拦截);页签真的消失后,
+ // 上面的 effect 再请 main 摘掉。
+ const closeHostedTab = useCallback(
+ async (tabId: string) => {
+ const ref = refFor(tabId);
+ if (!ref) return;
+ if (ref.sessionId === null || isGlobalTabId(tabId)) {
+ if (findGlobalTab(tabId)) removeGlobalTab(tabId);
+ return;
+ }
+ await closeTab(ref.sessionId, tabId);
+ },
+ [refFor],
+ );
+
+ /** 原生关窗(红绿灯 / Windows X):关闭窗口里的全部页签;有被否决的就留着。 */
+ const closeAllHostedTabs = useCallback(() => {
+ if (!assignment) return;
+ void (async () => {
+ for (const ref of assignment.tabs) {
+ try {
+ await closeHostedTab(ref.tabId);
+ } catch (err) {
+ log.warn('close popped-out tab failed', { tabId: ref.tabId, err });
+ }
+ }
+ })();
+ }, [assignment, closeHostedTab]);
- // 原生关窗(红绿灯 / 系统关闭 / Windows X):main 拦下后转达到这里。
useEffect(() => {
- return api?.onCloseRequested?.(() => closeOwnTab()) ?? undefined;
- }, [api, closeOwnTab]);
+ return api?.onCloseRequested?.(() => closeAllHostedTabs()) ?? undefined;
+ }, [api, closeAllHostedTabs]);
- // ⌘W / Ctrl+W:本窗口整个就是一个页签,与侧边栏里 ⌘W 关当前页签同义。
+ // ⌘W / Ctrl+W:关闭当前页签(与侧边栏里 ⌘W 关当前页签同义)。
useCloseShortcutShellOwner();
useAppShortcut('close-tab-or-window', () => {
- closeOwnTab();
+ if (activeTabId) {
+ void closeHostedTab(activeTabId).catch((err) => {
+ log.warn('close active popped-out tab failed', { tabId: activeTabId, err });
+ });
+ }
return true;
});
- const plugin = tab ? getTabKind(tab.kind) : null;
- const hydratedState = tab ? hydrateTabState(plugin, tab.state) : null;
- const FallbackIcon = tab ? iconForTabKind(tab.kind) : PanelRight;
- const IconNode = plugin?.TabPillIcon;
- const TitleNode = plugin?.TabPillTitle;
- const context = assignment?.context;
+ // 「+」新建的页签:乐观登记为本窗口承载,并请 main 收编(主窗据广播不画它)。
+ const handleTabCreated = useCallback(
+ (tabId: string) => {
+ addHostedTabId(tabId);
+ const created = isGlobalTabId(tabId) ? null : sessionId;
+ void api?.adoptTab?.({ tabId, sessionId: created }).catch((err) => {
+ log.warn('adopt new tab failed', { tabId, err });
+ });
+ },
+ [api, sessionId],
+ );
- return (
- <div className="flex h-screen flex-col bg-content-area text-foreground">
- <div
- className="relative flex h-[46px] shrink-0 items-center border-b border-[var(--border-default)] bg-[var(--panel-bg)]"
- style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
- >
- <div className={isMac ? 'w-20 shrink-0' : 'w-3 shrink-0'} />
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <span className="shrink-0 text-[var(--text-tertiary)]">
- {tab && IconNode ? (
- <IconNode state={hydratedState} sessionId={sessionId} active />
- ) : (
- <FallbackIcon size={14} />
- )}
- </span>
- <span className="truncate text-13 text-[var(--text-secondary)]">
- {tab ? (
- TitleNode ? (
- <TitleNode state={hydratedState} sessionId={sessionId} active t={t} />
- ) : (
- t(labelKeyForTabKind(tab.kind))
- )
- ) : (
- t('rightSidebar.tabWindow.title')
- )}
- </span>
- </div>
+ const context = assignment?.context;
+ const topbarLeading = <div className={isMac ? 'w-[72px] shrink-0' : 'w-1 shrink-0'} />;
+ const topbarTrailing = (
+ <>
+ {activeTabId && (
<div
- className="flex shrink-0 items-center gap-0.5 pr-2"
+ className="flex h-full shrink-0 items-center gap-0.5"
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
>
- <ChromeIconButton onClick={mergeBack} aria-label={t('rightSidebar.tabWindow.mergeBack')}>
+ <ChromeIconButton
+ onClick={() => mergeBackTab(activeTabId)}
+ aria-label={t('rightSidebar.tabWindow.mergeBack')}
+ >
<PanelRight size={14} />
</ChromeIconButton>
</div>
- {!isMac && (
- <div
- className="flex h-full shrink-0 items-center"
- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
- >
- <WindowControls key={windowChromeRevision} onClose={closeOwnTab} />
- </div>
- )}
- </div>
+ )}
+ {!isMac && (
+ <div
+ className="flex h-full shrink-0 items-center"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ <WindowControls key={windowChromeRevision} onClose={closeAllHostedTabs} />
+ </div>
+ )}
+ </>
+ );
+ return (
+ <div className="flex h-screen flex-col bg-content-area text-foreground">
<div className="relative flex flex-1 flex-col overflow-hidden">
{assignment && (
<RightSidebarShell
@@ -262,13 +294,19 @@ export function SidebarTabWindowLayout() {
subagentsAvailable={context?.subagentsAvailable}
shellVisible={windowVisible}
isMac={isMac}
- soloTabId={assignment.tabId}
+ unifiedTopbar
+ hostedTabIds={hostedTabIds}
+ onMergeBackTab={mergeBackTab}
+ onTabCreated={handleTabCreated}
+ onActiveTabChange={setActiveTabId}
+ topbarLeading={topbarLeading}
+ topbarTrailing={topbarTrailing}
/>
)}
- {(!windowVisible || !assignment || !tab) && (
+ {(!windowVisible || !assignment || presentTabs.length === 0) && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-[var(--panel-bg)]">
<span className="text-13 text-[var(--text-tertiary)]">
- {assignment && contentReady && !tab
+ {assignment && contentReady && presentTabs.length === 0
? t('rightSidebar.tabWindow.closed')
: t('rightSidebar.tabWindow.loading')}
</span>
diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
index 972befb89b..39637422ac 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
@@ -61,6 +61,8 @@ interface AddTabDropdownProps {
sessionId?: string | null;
/** 本菜单所属的页签组:插件分组里新加的全局页签直接落在这一组。缺省右侧组。 */
groupId?: TabGroupId;
+ /** 插件分组新加了全局页签(独立窗口据此收编)。已存在的不算。 */
+ onGlobalTabAdded?: (tabId: string) => void;
/** 锚点消失 / 面板收起时关闭(点外部与 Esc 由 DropdownMenu 根处理)。 */
onClose: () => void;
/** 选 kind。调用方负责真创建 tab + 关闭 dropdown。单例 kind 已存在时
@@ -139,6 +141,7 @@ export function AddTabDropdown({
anchorRef,
sessionId,
groupId,
+ onGlobalTabAdded,
onClose,
onSelect,
existingKinds,
@@ -257,7 +260,10 @@ export function AddTabDropdown({
trailing={entry.open ? t('rightSidebar.tabs.menu.alreadyOpen') : undefined}
onSelect={() => {
const tab = addGlobalPluginTab(entry.instanceId, { groupId });
- if (tab) setActiveGlobalTabId(tab.id);
+ if (tab) {
+ if (!entry.open) onGlobalTabAdded?.(tab.id);
+ 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 60e863eb60..e41ae3a9e4 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
@@ -27,6 +27,7 @@ import {
useRef,
useState,
useSyncExternalStore,
+ type ReactNode,
} from 'react';
import { useTranslation } from 'react-i18next';
@@ -40,7 +41,7 @@ import { RightSidebarDetach } from '@/components/layout/RightSidebarDetach';
import { RightSidebarMaximize } from '@/components/layout/RightSidebarMaximize';
import { RightSidebarToggle } from '@/components/layout/RightSidebarToggle';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
-import { TabBar, TabStrip } from './TabBar';
+import { TabBar, TabStrip, TabTitleLabel, type PopoutWindowOption } from './TabBar';
import { EmptyState } from './EmptyState';
import { getTabKind, hydrateTabState } from './registry';
import {
@@ -65,7 +66,10 @@ import { initPopupRouter, setPopupFallbackSession } from './lib/popupRouter';
import { TabBodyErrorBoundary } from './TabBodyErrorBoundary';
import { useRetainedBrowserTabHosts } from './hooks/useRetainedBrowserTabHosts';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
-import { useSidebarTabWindowsState } from '@/lib/sidebarTabWindowState';
+import {
+ summarizeSidebarTabWindows,
+ useSidebarTabWindowsState,
+} from '@/lib/sidebarTabWindowState';
import {
isGlobalTabId,
removeGlobalTab,
@@ -103,7 +107,7 @@ type RightTabDirection = 'prev' | 'next';
interface RightSidebarShellProps {
/**
* 本 Shell 承载哪个页签组(见 tabGroups.ts):只投影归属该组的页签。缺省右侧组
- * (历史右侧栏);左 / 上 / 下边组由 TabGroupPanel 传入。弹出窗口(soloTabId)不分组。
+ * (历史右侧栏);左 / 上 / 下边组由 TabGroupPanel 传入。弹出窗口(hostedTabIds)不分组。
*/
groupId?: TabGroupId;
/**
@@ -147,17 +151,26 @@ interface RightSidebarShellProps {
/** 工具面板处于最左 rail 邻位时,顶栏为浮动 ChromeActions 挖 no-drag 命中区并预留布局空间。 */
railChromeActionsHitHole?: boolean;
/**
- * 「在独立窗口中打开」页签:主窗侧栏继续存在,只把该页签弹出到自己的窗口。
- * 顶栏按钮作用于当前激活页签(没有激活页签时不渲染);页签右键菜单作用于被点
- * 的页签。弹出窗口(soloTabId 形态)与会话副窗不传。
+ * 「在独立窗口中打开」页签:主窗侧栏继续存在,只把该页签弹出到自己的窗口;带
+ * targetWindowId 时搬进已有的弹出窗口。顶栏按钮作用于当前激活页签(没有激活页签时
+ * 不渲染);页签右键菜单作用于被点的页签。弹出窗口(hostedTabIds 形态)与会话副窗不传。
*/
- onDetachTab?: (tabId: string) => void;
+ onDetachTab?: (tabId: string, targetWindowId?: string) => void;
/**
- * 单页签独立窗口形态:Shell 只投影并挂载这一个页签,不渲染 TabBar / 合并顶栏 /
- * 空态,不写激活位,也不向 main 上报「活跃侧栏会话」(主窗仍是侧栏宿主权威)。
- * 该页签从桶里消失(被关闭)后 Shell 渲染为空,由 SidebarTabWindowLayout 关窗。
+ * 页签独立窗口形态:Shell 只投影并挂载 main 指派给本窗口的这些页签(不分组),
+ * 激活位只在本窗口内存里,不写任务桶,也不向 main 上报「活跃侧栏会话」(主窗仍是
+ * 侧栏宿主权威)。页签全部从桶里消失后 Shell 渲染为空,由 SidebarTabWindowLayout 关窗。
*/
- soloTabId?: string;
+ hostedTabIds?: ReadonlySet<string>;
+ /** 独立窗口形态:右键菜单「合并回侧边栏」作用于被点的页签。 */
+ onMergeBackTab?: (tabId: string) => void;
+ /** 独立窗口形态:本窗口里经「+」新建的页签(乐观插入那一刻回调),宿主拿去收编。 */
+ onTabCreated?: (tabId: string) => void;
+ /** 当前激活页签变化(独立窗口的 ⌘W / 合并按钮要知道作用于谁)。 */
+ onActiveTabChange?: (tabId: string | null) => void;
+ /** 合并顶栏首 / 尾插槽(独立窗口的红绿灯让位、合并按钮与窗口控件)。 */
+ topbarLeading?: ReactNode;
+ topbarTrailing?: ReactNode;
/** TabBar 横带是否作为窗口拖拽区(见 TabBar 同名 prop):主窗口内嵌形态传
* false(空白处 = 拖面板手势面);detached 子窗口不传,默认 true。 */
chromeWindowDrag?: boolean;
@@ -189,16 +202,21 @@ export function RightSidebarShell({
onMaximize,
isMaximized,
onDetachTab,
- soloTabId,
+ hostedTabIds,
+ onMergeBackTab,
+ onTabCreated,
+ onActiveTabChange,
+ topbarLeading,
+ topbarTrailing,
chromeWindowDrag = true,
panelSide = 'right',
onAllTabsClosed,
reserveLeftChromeActions = false,
railChromeActionsHitHole = false,
}: RightSidebarShellProps) {
- const soloMode = typeof soloTabId === 'string';
+ const soloMode = hostedTabIds !== undefined;
/** 右侧组是页签系统的"主组":任务级的激活位对账、快捷键、浏览器桥的活跃会话上报只由它做。 */
- const isPrimaryGroup = groupId === DEFAULT_TAB_GROUP;
+ const isPrimaryGroup = groupId === DEFAULT_TAB_GROUP && !soloMode;
const { isFullscreen } = useMacFullscreen();
const chromeActionsLeft =
isMac && !isFullscreen
@@ -219,7 +237,7 @@ export function RightSidebarShell({
const { t } = useTranslation();
const installedGhosts = useInstalledGhosts();
// 已弹出到独立窗口的页签:数据留在桶里,但本 Shell 不投影、不挂 body。
- // 弹出窗口自身(soloMode)反过来只投影自己承载的那一个。
+ // 弹出窗口自身(soloMode)反过来只投影 main 指派给它承载的那几个。
const poppedOutTabs = useSidebarTabWindowsState();
// RSB browser bridge (Phase 2):在 Shell 整个生命周期内只 init 一次。bridge 内部
@@ -260,14 +278,14 @@ export function RightSidebarShell({
// 承载全局页签就是这种形态。
const contentReady = bucket.hydrated || sessionId === null;
const hiddenTabIds = useMemo<ReadonlySet<string> | undefined>(() => {
- if (soloMode) {
+ if (hostedTabIds) {
return new Set(
- [...globalTabs, ...bucket.tabs].map((tab) => tab.id).filter((id) => id !== soloTabId),
+ [...globalTabs, ...bucket.tabs].map((tab) => tab.id).filter((id) => !hostedTabIds.has(id)),
);
}
const ids = Object.keys(poppedOutTabs);
return ids.length > 0 ? new Set(ids) : undefined;
- }, [bucket.tabs, globalTabs, poppedOutTabs, soloMode, soloTabId]);
+ }, [bucket.tabs, globalTabs, hostedTabIds, poppedOutTabs]);
const previousShellVisibleRef = useRef(shellVisible);
const subagentsEligibilityKnown = typeof subagentsAvailable === 'boolean';
const subagentsEnabled = subagentsAvailable === true;
@@ -347,14 +365,23 @@ export function RightSidebarShell({
// 激活位:用户选中的全局页签优先并跨任务保持;否则是任务自己的激活页签(在本组时);
// 本组不含任务级激活页签时用组内上次选中的;再没有就落到第一个页签。
const groupRememberedActiveId = groupActiveVersion;
- const activeTabId =
- activeGlobalTabId && pinnedTabs.some((tab) => tab.id === activeGlobalTabId)
+ // 独立窗口:激活位只在本窗口内存里(不写任务桶、不碰主窗的全局激活位)。
+ const [hostedActiveTabId, setHostedActiveTabId] = useState<string | null>(null);
+ const activeTabId = soloMode
+ ? hostedActiveTabId && tabs.some((tab) => tab.id === hostedActiveTabId)
+ ? hostedActiveTabId
+ : (tabs.at(-1)?.id ?? null)
+ : activeGlobalTabId && pinnedTabs.some((tab) => tab.id === activeGlobalTabId)
? activeGlobalTabId
: sessionActiveTabId && sessionTabs.some((tab) => tab.id === sessionActiveTabId)
? sessionActiveTabId
: groupRememberedActiveId && tabs.some((tab) => tab.id === groupRememberedActiveId)
? groupRememberedActiveId
- : sessionTabs[0]?.id ?? pinnedTabs[0]?.id ?? null;
+ : (sessionTabs[0]?.id ?? pinnedTabs[0]?.id ?? null);
+
+ useEffect(() => {
+ onActiveTabChange?.(activeTabId);
+ }, [activeTabId, onActiveTabChange]);
// 首帧只挂当前激活 tab。其余 tab 在浏览器空闲期逐个补挂载,随后继续按原有
// keep-alive 语义保留组件 / webview / 编辑器状态。这样恢复一个多 tab 会话时,
@@ -543,7 +570,17 @@ export function RightSidebarShell({
// 否则正常 addTab。menu meta 的 singleton 字段是数据来源,目前只有 review。
const isSingleton = plugin?.menu?.singleton === true;
// 边组里点「+」:新页签直接落在本组(乐观插入那一帧就带着组归属,不闪过右侧栏)。
- const addOpts = isPrimaryGroup ? undefined : { groupId };
+ // 独立窗口里点「+」:乐观插入那一刻交给宿主收编(登记为本窗口承载)。
+ const addOpts = soloMode
+ ? {
+ onOptimisticAdd: (tabId: string) => {
+ setHostedActiveTabId(tabId);
+ onTabCreated?.(tabId);
+ },
+ }
+ : isPrimaryGroup
+ ? undefined
+ : { groupId };
const action = isSingleton
? addOrFocusSingletonTab(sessionId, kind, initialState, addOpts)
: addTab(sessionId, kind, initialState, addOpts);
@@ -559,7 +596,7 @@ export function RightSidebarShell({
log.error('handleAdd failed', { sessionId, kind, err });
});
},
- [groupId, isPrimaryGroup, sessionId, subagentsEnabled, t],
+ [groupId, isPrimaryGroup, onTabCreated, sessionId, soloMode, subagentsEnabled, t],
);
const handleClose = useCallback(
@@ -579,6 +616,10 @@ export function RightSidebarShell({
const handleActivate = useCallback(
(tabId: string) => {
+ if (soloMode) {
+ setHostedActiveTabId(tabId);
+ return;
+ }
setGroupActiveTabId(groupId, sessionId, tabId);
if (isGlobalTabId(tabId)) {
setActiveGlobalTabId(tabId);
@@ -595,9 +636,28 @@ export function RightSidebarShell({
log.error('handleActivate failed', { sessionId, tabId, err });
});
},
- [activeGlobalTabId, groupId, pinnedTabs, sessionId],
+ [activeGlobalTabId, groupId, pinnedTabs, sessionId, soloMode],
);
+ // 主窗:已弹出的页签窗口(同任务或只有全局页签的),右键菜单「移到窗口 …」的目标。
+ // 标签用窗口里第一个页签的标题(插件的 TabPillTitle 组件,不是字符串)。
+ const popoutWindows = useMemo<PopoutWindowOption[] | undefined>(() => {
+ if (soloMode || !onDetachTab) return undefined;
+ const options: PopoutWindowOption[] = [];
+ for (const summary of summarizeSidebarTabWindows(poppedOutTabs)) {
+ if (summary.sessionId !== null && summary.sessionId !== sessionId) continue;
+ const firstTab =
+ bucket.tabs.find((tab) => summary.tabIds.includes(tab.id)) ??
+ globalTabs.find((tab) => summary.tabIds.includes(tab.id));
+ if (!firstTab) continue;
+ options.push({
+ windowId: summary.windowId,
+ label: <TabTitleLabel tab={firstTab} sessionId={sessionId} />,
+ });
+ }
+ return options.length > 0 ? options : undefined;
+ }, [bucket.tabs, globalTabs, onDetachTab, poppedOutTabs, sessionId, soloMode]);
+
// 右键菜单「移到 …」:改组归属,目标组里立刻选中它;组 pane 的出现 / 隐藏由
// tabGroupPanes 按在场判定处理。
const handleMoveTab = useCallback(
@@ -727,7 +787,7 @@ export function RightSidebarShell({
return (
<div className="flex h-full min-h-0 flex-1 flex-col overflow-hidden">
- {soloMode ? null : unifiedTopbar ? (
+ {unifiedTopbar ? (
<div
data-testid="right-sidebar-unified-topbar"
// bg 走 --panel-bg 与下方 TabBar / Body 同源(2026-07-21 用户裁决:CINDY 下
@@ -736,6 +796,7 @@ export function RightSidebarShell({
className="relative flex h-[46px] shrink-0 flex-none items-center border-b border-[var(--border-default)] bg-[var(--panel-bg)] px-2"
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
>
+ {topbarLeading}
{!isFullscreen && railChromeActionsHitHole && (
<div
aria-hidden
@@ -791,9 +852,12 @@ export function RightSidebarShell({
onAdd={handleAdd}
onCloseOthers={handleCloseOthers}
onCloseAll={handleCloseAll}
- onDetachTab={onDetachTab}
+ onDetachTab={soloMode ? undefined : onDetachTab}
+ onMergeBackTab={onMergeBackTab}
+ popoutWindows={popoutWindows}
groupId={groupId}
onMoveTab={soloMode ? undefined : handleMoveTab}
+ onGlobalTabAdded={soloMode ? onTabCreated : undefined}
pillVariant="chip"
addButtonWrapperClassName="h-[30px]"
subagentsAvailable={subagentsEnabled}
@@ -832,6 +896,7 @@ export function RightSidebarShell({
style={{ width: MAC_HEADER_ACTION_SPACER_PX }}
/>
)}
+ {topbarTrailing}
</div>
) : (
<TabBar
@@ -849,10 +914,13 @@ export function RightSidebarShell({
onShowSidebar={onShowSidebar}
panelSide={panelSide}
isMaximized={isMaximized}
- onDetach={handleDetachActiveTab}
- onDetachTab={onDetachTab}
+ onDetach={soloMode ? undefined : handleDetachActiveTab}
+ onDetachTab={soloMode ? undefined : onDetachTab}
+ onMergeBackTab={onMergeBackTab}
+ popoutWindows={popoutWindows}
groupId={groupId}
onMoveTab={soloMode ? undefined : handleMoveTab}
+ onGlobalTabAdded={soloMode ? onTabCreated : undefined}
onCloseOthers={handleCloseOthers}
onCloseAll={handleCloseAll}
chromeWindowDrag={chromeWindowDrag}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
index 4d1201d3cf..537d04d8f9 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
@@ -18,7 +18,7 @@
* i18n key 用 record 映射;Phase 2+ 改为从 plugin registry 取。
*/
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Activity, Bot, FolderTree, Globe, Terminal, GitPullRequestArrow, UsersRound, LayoutGrid, ListTodo, Pin, Plus, Puzzle, X, Maximize2, Minimize2, PanelRightClose, PictureInPicture2, Wrench } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import type { TFunction } from 'i18next';
@@ -40,6 +40,12 @@ import { getTabKind, hydrateTabState } from './registry';
import { TAB_GROUP_IDS, tabGroupLabelKey, type TabGroupId } from './tabGroups';
import type { BuiltinTabKindId, TabKindId, TabState } from './types';
+/** 右键菜单里一扇可搬入的弹出窗口:标签是它第一个页签的标题(React 节点)。 */
+export interface PopoutWindowOption {
+ windowId: string;
+ label: ReactNode;
+}
+
interface TabBarProps {
tabs: TabState[];
/** 全局页签(不跟对话):钉在条首,不参与拖拽排序,切任务不变。 */
@@ -76,12 +82,18 @@ interface TabBarProps {
* Windows 主窗口展开态同时传入 onCloseSidebar,折叠按钮归属本 TabBar;
* 折叠后再由聊天区角上的 chip 提供展开入口。 */
onDetach?: () => void;
- /** 页签右键菜单「在独立窗口中打开」:作用于被点的页签。 */
- onDetachTab?: (tabId: string) => void;
+ /** 页签右键菜单「在独立窗口中打开」:作用于被点的页签;带 windowId = 搬进已有窗口。 */
+ onDetachTab?: (tabId: string, targetWindowId?: string) => void;
+ /** 已弹出的页签窗口(右键菜单「移到窗口 …」的目标);不传 / 空 = 不显示。 */
+ popoutWindows?: PopoutWindowOption[];
+ /** 独立窗口形态:右键菜单「合并回侧边栏」。 */
+ onMergeBackTab?: (tabId: string) => void;
/** 本条属于哪个页签组;右键菜单「移到 …」列出其余各组。 */
groupId?: TabGroupId;
/** 页签右键菜单「移到 左侧 / 右侧栏 / 上方 / 下方」。不传 = 不显示。 */
onMoveTab?: (tabId: string, groupId: TabGroupId) => void;
+ /** 「+」菜单插件分组新加了全局页签(独立窗口据此收编)。 */
+ onGlobalTabAdded?: (tabId: string) => void;
/** 本条横带是否作为**窗口**拖拽区(B3):主窗口内嵌形态传 false —— 空白处是
* "拖面板"手势面(窗口拖拽区收不到鼠标事件,二者物理互斥;拖窗走左栏顶行);
* detached 子窗口等其它宿主不传,默认 true 维持经典拖窗行为。 */
@@ -103,10 +115,14 @@ interface TabStripProps {
onCloseOthers?: (keepTabId: string) => void;
onCloseAll?: () => void;
/** Tab pill 右键菜单「在独立窗口中打开」。 */
- onDetachTab?: (tabId: string) => void;
- /** 见 TabBarProps.groupId / onMoveTab。 */
+ onDetachTab?: (tabId: string, targetWindowId?: string) => void;
+ /** 见 TabBarProps.popoutWindows / onMergeBackTab。 */
+ popoutWindows?: PopoutWindowOption[];
+ onMergeBackTab?: (tabId: string) => void;
+ /** 见 TabBarProps.groupId / onMoveTab / onGlobalTabAdded。 */
groupId?: TabGroupId;
onMoveTab?: (tabId: string, groupId: TabGroupId) => void;
+ onGlobalTabAdded?: (tabId: string) => void;
className?: string;
/**
* pill 视觉变体:
@@ -221,8 +237,11 @@ export function TabBar({
onCloseAll,
onDetach,
onDetachTab,
+ popoutWindows,
+ onMergeBackTab,
groupId,
onMoveTab,
+ onGlobalTabAdded,
chromeWindowDrag = true,
subagentsAvailable = false,
}: TabBarProps) {
@@ -249,8 +268,11 @@ export function TabBar({
onCloseOthers={onCloseOthers}
onCloseAll={onCloseAll}
onDetachTab={onDetachTab}
+ popoutWindows={popoutWindows}
+ onMergeBackTab={onMergeBackTab}
groupId={groupId}
onMoveTab={onMoveTab}
+ onGlobalTabAdded={onGlobalTabAdded}
addButtonWrapperClassName="h-[36px]"
addButtonClassName="mt-[3px]"
subagentsAvailable={subagentsAvailable}
@@ -318,8 +340,11 @@ export function TabStrip({
onCloseOthers,
onCloseAll,
onDetachTab,
+ popoutWindows,
+ onMergeBackTab,
groupId = 'right',
onMoveTab,
+ onGlobalTabAdded,
className,
pillVariant = 'flush',
addButtonWrapperClassName,
@@ -518,6 +543,7 @@ export function TabStrip({
anchorRef={addButtonWrapperRef}
sessionId={sessionId}
groupId={groupId}
+ onGlobalTabAdded={onGlobalTabAdded}
onClose={closeDropdown}
onSelect={onAdd}
existingKinds={existingKinds}
@@ -613,6 +639,37 @@ export function TabStrip({
{t('rightSidebar.tabs.contextMenu.openInWindow')}
</DropdownMenuItem>
)}
+ {onDetachTab &&
+ popoutWindows?.map((option) => (
+ <DropdownMenuItem
+ key={option.windowId}
+ data-testid={`right-sidebar-tab-move-window-${option.windowId}`}
+ onClick={() => {
+ const id = contextMenu.tabId;
+ closeContextMenu();
+ onDetachTab(id, option.windowId);
+ }}
+ >
+ <span className="flex min-w-0 items-center gap-1">
+ <span className="shrink-0">
+ {t('rightSidebar.tabs.contextMenu.moveToWindow')}
+ </span>
+ <span className="truncate">{option.label}</span>
+ </span>
+ </DropdownMenuItem>
+ ))}
+ {onMergeBackTab && (
+ <DropdownMenuItem
+ data-testid="right-sidebar-tab-merge-back"
+ onClick={() => {
+ const id = contextMenu.tabId;
+ closeContextMenu();
+ onMergeBackTab(id);
+ }}
+ >
+ {t('rightSidebar.tabWindow.mergeBack')}
+ </DropdownMenuItem>
+ )}
</>
)}
</DropdownMenuContent>
@@ -621,6 +678,22 @@ export function TabStrip({
);
}
+/**
+ * 页签标题(复用插件的 TabPillTitle;未注册 kind 落到固定文案)。右键菜单「移到窗口 …」
+ * 用它给窗口起名:窗口里第一个页签叫什么,窗口就叫什么。
+ */
+export function TabTitleLabel({ tab, sessionId }: { tab: TabState; sessionId: string | null }) {
+ const { t } = useTranslation();
+ const plugin = getTabKind(tab.kind);
+ const TitleNode = plugin?.TabPillTitle;
+ const hydratedState = hydrateTabState(plugin, tab.state);
+ return TitleNode ? (
+ <TitleNode state={hydratedState} sessionId={sessionId} active={false} t={t} />
+ ) : (
+ <>{t(labelKeyForTabKind(tab.kind))}</>
+ );
+}
+
function TabPill({
tab,
active,
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 0db3afb964..77c71b50b0 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
@@ -1655,7 +1655,7 @@ describe('RightSidebarShell empty state', () => {
// - 生产入口与可观察结果:RightSidebarShell 渲染同一会话桶;页签弹出到独立窗口
// (sidebarTabWindowState 镜像)后主窗侧栏不再显示它的 pill 与 body,激活位落到
// 仍在侧栏的页签并落库;窗口关闭(镜像清空)后 pill 回来。弹出窗口自身
- // (soloTabId)只挂那一个页签、不画 TabBar / 空态、不写激活位。
+ // (hostedTabIds)只挂被指派的页签、不画空态、不写任务级激活位。
// - Bug / 规则依据:侧栏「弹出」从整栏改为单页签(本 PR);webview / 终端不能双实例,
// 两个 renderer 投影同一页签就是双实例。
// - 现有覆盖缺口:相邻用例只覆盖可用性过滤(subagents / retired),没有跨窗口归属。
@@ -1692,7 +1692,9 @@ describe('RightSidebarShell empty state', () => {
// 终端页签弹出:侧栏不再显示它,激活位移到文件页签并落库。
act(() => {
- __setSidebarTabWindowsStateForTest({ 'tab-term': { sessionId: 's1', open: true } });
+ __setSidebarTabWindowsStateForTest({
+ 'tab-term': { windowId: 'w1', sessionId: 's1', open: true },
+ });
});
await waitFor(() => expect(screen.queryByText('terminal-pill')).toBeNull());
expect(screen.queryByText('terminal-body')).toBeNull();
@@ -1709,7 +1711,7 @@ describe('RightSidebarShell empty state', () => {
await waitFor(() => expect(screen.getByText('terminal-pill')).toBeTruthy());
unmount();
- // 弹出窗口自身:只挂被指派页签,没有 TabBar / 空态,不改激活位。
+ // 弹出窗口自身:只挂被指派的页签(页签条照常,供多页签切换),没有空态,不改任务级激活位。
tabsIpc.setActive.mockClear();
_resetStore();
render(
@@ -1719,12 +1721,12 @@ describe('RightSidebarShell empty state', () => {
remoteHostId: null,
isMac: true,
subagentsAvailable: false,
- soloTabId: 'tab-term',
+ hostedTabIds: new Set(['tab-term']),
}),
);
await waitFor(() => expect(screen.getByText('terminal-body')).toBeTruthy());
- expect(screen.queryByTestId('right-sidebar-tab-bar')).toBeNull();
- expect(screen.queryByTestId('right-sidebar-unified-topbar')).toBeNull();
+ expect(screen.getByTestId('right-sidebar-tab-bar')).toBeTruthy();
+ expect(screen.getByText('terminal-pill')).toBeTruthy();
expect(screen.queryByText('rightSidebar.tabs.empty.title')).toBeNull();
expect(screen.queryByText('rightSidebar.tabs.kinds.fileBrowser')).toBeNull();
await new Promise((resolve) => setTimeout(resolve, 0));
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 fcc5891ff3..0fef378b70 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
@@ -213,6 +213,39 @@ describe('TabStrip context menu · move to group', () => {
});
});
+// 测试价值
+// - 生产入口与可观察结果:页签右键菜单的「移到窗口 …」(主窗,按已弹出窗口列出)与
+// 「合并回侧边栏」(弹出窗口);可观察的是回调带被点页签与目标窗口 id。
+// - Bug / 规则依据:弹出窗口 = 多页签的页签组(本 PR),主窗能把页签搬进已有窗口。
+// - 现有覆盖缺口:右键菜单此前只有关闭 / 移组用例。
+// - 最小失败输入:一扇弹出窗口选项 + 右键一个页签。
+// - tier:unit(jsdom)。
+describe('TabStrip context menu · popped-out windows', () => {
+ it('offers existing popped-out windows as move targets and merge-back inside a window', () => {
+ const onDetachTab = vi.fn();
+ const onMergeBackTab = vi.fn();
+ render(
+ <TabStrip
+ tabs={TABS}
+ activeTabId={null}
+ onActivate={vi.fn()}
+ onClose={vi.fn()}
+ onReorder={vi.fn()}
+ onAdd={vi.fn()}
+ onDetachTab={onDetachTab}
+ popoutWindows={[{ windowId: 'w7', label: <span>Docs</span> }]}
+ onMergeBackTab={onMergeBackTab}
+ />,
+ );
+ fireEvent.contextMenu(pillFor(LABEL_FILE));
+ fireEvent.click(screen.getByTestId('right-sidebar-tab-move-window-w7'));
+ expect(onDetachTab).toHaveBeenCalledWith('tab-file', 'w7');
+ fireEvent.contextMenu(pillFor(LABEL_ORCA));
+ fireEvent.click(screen.getByTestId('right-sidebar-tab-merge-back'));
+ expect(onMergeBackTab).toHaveBeenCalledWith('tab-orca');
+ });
+});
+
afterEach(() => cleanup());
describe('TabStrip 中键关闭 tab', () => {
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 51f56901a0..d9d2361b40 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
@@ -1435,7 +1435,7 @@ describe('cross-renderer sync for popped-out tabs', () => {
it('merges a DB refresh: hosted tabs stay local, popped tabs take DB, foreign adds/removes apply', async () => {
await hydrateTwoTabs();
- popped.__setSidebarTabWindowsStateForTest({ 'tab-web': { sessionId: 's1', open: true } });
+ popped.__setSidebarTabWindowsStateForTest({ 'tab-web': { windowId: 'w1', sessionId: 's1', open: true } });
// 本窗对承载页签的乐观改动(写还在途)不能被对方的刷新覆盖。
void store.patchTabState('s1', 'tab-files', () => ({ path: 'local-edit' }));
ipc.list.mockResolvedValueOnce({
@@ -1514,7 +1514,7 @@ describe('cross-renderer sync for popped-out tabs', () => {
it('activating a popped-out tab focuses its window instead of moving the sidebar marker', async () => {
await hydrateTwoTabs();
- popped.__setSidebarTabWindowsStateForTest({ 'tab-web': { sessionId: 's1', open: true } });
+ popped.__setSidebarTabWindowsStateForTest({ 'tab-web': { windowId: 'w1', sessionId: 's1', open: true } });
await store.setActiveTab('s1', 'tab-web');
expect(sidebarTabWindow.focus).toHaveBeenCalledWith('tab-web');
expect(store.getBucket('s1').activeTabId).toBe('tab-files');
@@ -1523,7 +1523,7 @@ describe('cross-renderer sync for popped-out tabs', () => {
it('closing a popped-out tab in the sidebar tears down its window without returning it', async () => {
await hydrateTwoTabs();
- popped.__setSidebarTabWindowsStateForTest({ 'tab-web': { sessionId: 's1', open: true } });
+ popped.__setSidebarTabWindowsStateForTest({ 'tab-web': { windowId: 'w1', sessionId: 's1', open: true } });
await store.closeTab('s1', 'tab-web');
expect(ipc.close).toHaveBeenCalledWith({ id: 'tab-web' });
expect(sidebarTabWindow.closeForTab).toHaveBeenCalledWith('tab-web');
@@ -1541,7 +1541,7 @@ describe('cross-renderer sync for popped-out tabs', () => {
],
activeTabId: 'tab-files',
});
- popped.__setSidebarTabWindowsStateForTest({ 'tab-web': { sessionId: 's1', open: true } });
+ popped.__setSidebarTabWindowsStateForTest({ 'tab-web': { windowId: 'w1', sessionId: 's1', open: true } });
onChangedListeners[0]({ sessionId: 's1' });
onChangedListeners[0]({ sessionId: 's1' });
onChangedListeners[0]({ sessionId: 's1' });
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 c8a0a834e7..308bbd6948 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts
@@ -1,20 +1,22 @@
/**
* 分离侧栏窗口「合并回主窗口」的唯一出口。
*
- * 不可持久化会话(device-link 远程)的 tab 只在本 renderer 内存里,必须随
- * setDetached(false) 交接给主窗;可持久化会话的快照为 null,主窗按 SQLite 重新水合。
+ * 不可持久化会话(device-link 远程)的 tab 只在本 renderer 内存里,必须随
+ * setDetached(false) 交接给主窗;可持久化会话的快照为 null,主窗按 SQLite 重新水合。
*/
import { isSidebarTabWindow } from '@/lib/sidebarTabWindow';
import { getSingleTabSnapshot, getTabSnapshot } from '../store';
-import { getSoloTabId } from './tabHosting';
-export async function mergeSidebarWindowBack(sessionId: string | null | undefined): Promise<void> {
- // 单页签独立窗口:只交回自己承载的那个页签(不可持久化会话附内存态),窗口随之关闭。
+export async function mergeSidebarWindowBack(
+ sessionId: string | null | undefined,
+ tabId?: string,
+): Promise<void> {
+ // 页签独立窗口:只交回指定的那个页签(不可持久化会话附内存态);窗口清空后 main 关窗。
if (isSidebarTabWindow()) {
- const tabId = getSoloTabId();
- const snapshot = tabId ? getSingleTabSnapshot(sessionId, tabId) : null;
- await window.electronAPI.sidebarTabWindow?.mergeBack?.(snapshot);
+ if (!tabId) return;
+ const snapshot = getSingleTabSnapshot(sessionId, tabId);
+ await window.electronAPI.sidebarTabWindow?.mergeBack?.({ tabId, snapshot });
return;
}
const snapshot = getTabSnapshot(sessionId);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts
index a9703c233c..3444f2e874 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts
@@ -1,36 +1,66 @@
/**
* tabHosting —— 「这个页签的内容由本 renderer 承载吗」。
*
- * 同一会话的页签桶可能同时水合在两个 renderer 里:主窗侧边栏 + 若干弹出的单页签
+ * 同一会话的页签桶可能同时水合在多个 renderer 里:主窗侧边栏 + 若干弹出的页签
* 窗口。每个页签只由一个 renderer 真正挂载它的 body(webview / 终端 / 文件树),
* 其它 renderer 只持有它的数据副本:
* - 主窗 / 副窗:承载所有**未弹出**的页签;
- * - 弹出窗口:只承载被指派给它的那一个页签。
+ * - 弹出窗口:只承载 main 指派给它的那几个页签。
*
* store 据此决定跨 renderer 刷新时哪些页签以本地为准(承载方)、哪些以 SQLite
* 为准(非承载方),Shell 据此隐藏非承载页签。
*/
+import { useSyncExternalStore } from 'react';
+
import { isSidebarTabWindow } from '@/lib/sidebarTabWindow';
import { isTabPoppedOut } from '@/lib/sidebarTabWindowState';
-let soloTabId: string | null = null;
+let hosted: ReadonlySet<string> = new Set();
+const subscribers = new Set<() => void>();
+
+function notify(): void {
+ for (const cb of [...subscribers]) cb();
+}
/** 弹出窗口收到指派后登记自己承载的页签;主窗不调用。 */
-export function setSoloTabId(tabId: string | null): void {
- soloTabId = tabId;
+export function setHostedTabIds(tabIds: readonly string[]): void {
+ const next = new Set(tabIds);
+ if (next.size === hosted.size && [...next].every((id) => hosted.has(id))) return;
+ hosted = next;
+ notify();
+}
+
+/** 弹出窗口里新建页签:乐观登记为本窗口承载(main 确认后随指派重发)。 */
+export function addHostedTabId(tabId: string): void {
+ if (hosted.has(tabId)) return;
+ hosted = new Set([...hosted, tabId]);
+ notify();
}
-export function getSoloTabId(): string | null {
- return soloTabId;
+export function getHostedTabIds(): ReadonlySet<string> {
+ return hosted;
}
export function isTabHostedHere(tabId: string): boolean {
- if (isSidebarTabWindow()) return soloTabId !== null && tabId === soloTabId;
+ if (isSidebarTabWindow()) return hosted.has(tabId);
return !isTabPoppedOut(tabId);
}
+function subscribe(cb: () => void): () => void {
+ subscribers.add(cb);
+ return () => {
+ subscribers.delete(cb);
+ };
+}
+
+/** React hook:本窗口承载的页签集合(弹出窗口用)。 */
+export function useHostedTabIds(): ReadonlySet<string> {
+ return useSyncExternalStore(subscribe, getHostedTabIds);
+}
+
/** 仅测试用。 */
export function __resetTabHostingForTest(): void {
- soloTabId = null;
+ hosted = new Set();
+ subscribers.clear();
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx b/apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx
index eb8da764ad..5b46044b00 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx
@@ -12,8 +12,8 @@ export interface TabGroupHostValue {
deviceLinkDeviceId?: string | null;
subagentsAvailable?: boolean;
isMac: boolean;
- /** 「在独立窗口中打开」某个页签;副窗口不提供。 */
- onDetachTab?: (tabId: string) => void;
+ /** 「在独立窗口中打开」某个页签(带 windowId = 搬进已有窗口);副窗口不提供。 */
+ onDetachTab?: (tabId: string, targetWindowId?: string) => void;
/**
* mac 下窗口左上的红绿灯 / ChromeActions 会盖住最左面板的顶栏:左侧组贴着窗口
* 顶边且左栏收起 / rail 时,为它们预留 no-drag 空位。
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index a1e70efeb5..79ef60c280 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8047,7 +8047,8 @@
"closeOthers": "Close others",
"closeAll": "Close all",
"openInWindow": "Open in a new window",
- "moveTo": "Move to {{target}}"
+ "moveTo": "Move to {{target}}",
+ "moveToWindow": "Move to window:"
},
"empty": {
"eyebrow": "Right Sidebar",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 1bc6e2127c..d110481351 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8015,7 +8015,8 @@
"closeOthers": "他のタブを閉じる",
"closeAll": "すべて閉じる",
"openInWindow": "新しいウィンドウで開く",
- "moveTo": "{{target}}に移動"
+ "moveTo": "{{target}}に移動",
+ "moveToWindow": "ウィンドウに移動:"
},
"empty": {
"eyebrow": "右サイドバー",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index bbb6fab7d1..08a60064b2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8015,7 +8015,8 @@
"closeOthers": "다른 탭 닫기",
"closeAll": "모두 닫기",
"openInWindow": "새 창에서 열기",
- "moveTo": "{{target}}(으)로 이동"
+ "moveTo": "{{target}}(으)로 이동",
+ "moveToWindow": "창으로 이동:"
},
"empty": {
"eyebrow": "오른쪽 사이드바",
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 d565b5b13c..2e88a43a79 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8015,7 +8015,8 @@
"closeOthers": "关闭其他",
"closeAll": "关闭所有",
"openInWindow": "在独立窗口中打开",
- "moveTo": "移到{{target}}"
+ "moveTo": "移到{{target}}",
+ "moveToWindow": "移到窗口:"
},
"empty": {
"eyebrow": "右侧栏",
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 fc517936ff..c9844b7577 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8015,7 +8015,8 @@
"closeOthers": "關閉其他",
"closeAll": "關閉所有",
"openInWindow": "在獨立視窗中開啟",
- "moveTo": "移到{{target}}"
+ "moveTo": "移到{{target}}",
+ "moveToWindow": "移到視窗:"
},
"empty": {
"eyebrow": "右側欄",
diff --git a/apps/desktop/src/renderer/lib/sidebarTabWindowState.ts b/apps/desktop/src/renderer/lib/sidebarTabWindowState.ts
index f104deb412..99c97a74e7 100644
--- a/apps/desktop/src/renderer/lib/sidebarTabWindowState.ts
+++ b/apps/desktop/src/renderer/lib/sidebarTabWindowState.ts
@@ -76,6 +76,30 @@ export function useSidebarTabWindowsState(): SidebarTabWindowsState {
return useSyncExternalStore(subscribe, getSidebarTabWindowsState);
}
+export interface SidebarTabWindowSummary {
+ windowId: string;
+ /** 窗口里任务页签所属任务;只有全局页签时为 null。 */
+ sessionId: string | null;
+ tabIds: string[];
+}
+
+/** 纯函数:按窗口归并镜像(tabId → 窗口)。页签顺序按镜像枚举序。 */
+export function summarizeSidebarTabWindows(
+ state: SidebarTabWindowsState,
+): SidebarTabWindowSummary[] {
+ const byWindow = new Map<string, SidebarTabWindowSummary>();
+ for (const [tabId, entry] of Object.entries(state)) {
+ let summary = byWindow.get(entry.windowId);
+ if (!summary) {
+ summary = { windowId: entry.windowId, sessionId: null, tabIds: [] };
+ byWindow.set(entry.windowId, summary);
+ }
+ summary.tabIds.push(tabId);
+ if (entry.sessionId !== null) summary.sessionId = entry.sessionId;
+ }
+ return [...byWindow.values()];
+}
+
/** 仅测试用。 */
export function __setSidebarTabWindowsStateForTest(next: SidebarTabWindowsState): void {
wired = true;
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index d5570a0de5..55d8a0e53e 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2064,15 +2064,20 @@ interface ElectronAPI {
cb: (payload: import('../shared/sidebarTabWindow').SidebarTabReturnedPayload) => void,
) => () => void;
getAssignment?: () => Promise<
- import('../shared/sidebarTabWindow').SidebarTabWindowOpenRequest | null
+ import('../shared/sidebarTabWindow').SidebarTabWindowAssignmentPayload | null
>;
onAssigned?: (
- cb: (assignment: import('../shared/sidebarTabWindow').SidebarTabWindowOpenRequest) => void,
+ cb: (
+ assignment: import('../shared/sidebarTabWindow').SidebarTabWindowAssignmentPayload,
+ ) => void,
) => () => void;
rendererReady?: () => Promise<void>;
presentationReady?: () => Promise<void>;
mergeBack?: (
- snapshot: import('../shared/sidebarTabWindow').SidebarTabReturnSnapshot | null,
+ request: import('../shared/sidebarTabWindow').SidebarTabWindowMergeBackRequest,
+ ) => Promise<void>;
+ adoptTab?: (
+ request: import('../shared/sidebarTabWindow').SidebarTabWindowAdoptRequest,
) => Promise<void>;
onCloseRequested?: (cb: () => void) => () => void;
onVisibilityChanged?: (cb: (payload: { visible: boolean }) => void) => () => void;
diff --git a/apps/desktop/src/shared/sidebarTabWindow.ts b/apps/desktop/src/shared/sidebarTabWindow.ts
index 7e296fd030..29c2af217e 100644
--- a/apps/desktop/src/shared/sidebarTabWindow.ts
+++ b/apps/desktop/src/shared/sidebarTabWindow.ts
@@ -1,11 +1,12 @@
/**
- * 右侧栏「单个页签独立窗口」(sidebar tab window)的跨进程共享类型。
+ * 右侧栏「页签独立窗口」(sidebar tab window)的跨进程共享类型。
*
- * 与 shared/rightSidebarWindow.ts(整栏子窗口)的差异:按 **tabId 多实例**。
- * 用户把正在看的页签弹出到自己的窗口,主窗口的侧边栏继续存在并显示其余页签;
- * 关闭弹出窗口 = 关闭该页签,「合并回侧边栏」按钮才把页签送回。三方共用:main(controller / IPC)、preload
- * (桥接签名)、renderer(主窗镜像 store + 弹出窗口根组件)。只放纯类型与
- * channel 常量,不放运行时代码。
+ * 与 shared/rightSidebarWindow.ts(整栏子窗口)的差异:按 **窗口多实例**,一扇窗口
+ * 可以承载多个页签(同一任务的页签 + 任意全局页签),本质上是「住在别的窗口里的
+ * 页签组」。用户把正在看的页签弹出到自己的窗口,或搬进已有的弹出窗口;主窗口的
+ * 侧边栏继续存在并显示其余页签。关闭弹出窗口 = 关闭它承载的全部页签;「合并回侧边栏」
+ * 按页签送回。三方共用:main(controller / IPC)、preload(桥接签名)、renderer(主窗
+ * 镜像 store + 弹出窗口根组件)。只放纯类型与 channel 常量,不放运行时代码。
*/
import type { RsbWindowTabSnapshot } from './rightSidebarWindow.js';
@@ -19,17 +20,36 @@ export interface SidebarTabWindowContext {
subagentsAvailable?: boolean;
}
-/** main 指派给某扇弹出窗口的页签身份;窗口整个生命周期只承载这一个页签。 */
-export interface SidebarTabWindowAssignment {
+/** 窗口里的一个页签:任务页签带所属任务,全局页签(插件视图)为 null。 */
+export interface SidebarTabWindowTabRef {
tabId: string;
- /** 任务页签所属任务;全局页签(不跟对话,如插件视图)为 null。 */
sessionId: string | null;
+}
+
+/** main 指派给某扇弹出窗口的内容;随页签加入 / 离开更新并重新下发。 */
+export interface SidebarTabWindowAssignment {
+ windowId: string;
+ /** 窗口里任务页签所属的任务;只有全局页签时为 null。一扇窗口只服务一个任务。 */
+ sessionId: string | null;
+ tabs: SidebarTabWindowTabRef[];
context: SidebarTabWindowContext;
}
-/** 主窗 → main 的弹出请求。handoff 只对不可持久化会话(device-link 远程)非空。 */
-export interface SidebarTabWindowOpenRequest extends SidebarTabWindowAssignment {
+/** 下发给弹出窗口的指派:附不可持久化会话的整桶内存快照(仅 device-link 远程会话非空)。 */
+export interface SidebarTabWindowAssignmentPayload extends SidebarTabWindowAssignment {
+ handoff: RsbWindowTabSnapshot | null;
+}
+
+/** 主窗 → main 的弹出 / 搬入请求。 */
+export interface SidebarTabWindowOpenRequest {
+ tabId: string;
+ /** 任务页签所属任务;全局页签(不跟对话,如插件视图)为 null。 */
+ sessionId: string | null;
+ context: SidebarTabWindowContext;
+ /** 只对不可持久化会话(device-link 远程)非空。 */
handoff?: RsbWindowTabSnapshot | null;
+ /** 搬进已有的弹出窗口;缺省 / 窗口不存在或任务不符时新开一扇。 */
+ targetWindowId?: string;
}
/** 弹出窗口合并回侧边栏时交回的单页签内存态(仅不可持久化会话)。 */
@@ -38,17 +58,30 @@ export interface SidebarTabReturnSnapshot {
tab: { id: string; kind: string; state: unknown };
}
-/** 单扇弹出窗口的运行时状态;只在当前进程有效,不跨重启。 */
+/** 弹出窗口 → main:把某个页签合并回侧边栏。 */
+export interface SidebarTabWindowMergeBackRequest {
+ tabId: string;
+ snapshot: SidebarTabReturnSnapshot | null;
+}
+
+/** 弹出窗口 → main:在本窗口里新建的页签归本窗口承载。 */
+export interface SidebarTabWindowAdoptRequest {
+ tabId: string;
+ sessionId: string | null;
+}
+
+/** 单个已弹出页签的运行时状态;只在当前进程有效,不跨重启。 */
export interface SidebarTabWindowEntryState {
+ windowId: string;
sessionId: string | null;
/** 窗口是否已经展示(或正在等待首份内容后展示)。 */
open: boolean;
}
-/** 全量状态:tabId → 窗口状态。没有条目 = 该页签没有弹出。 */
+/** 全量状态:tabId → 所在窗口。没有条目 = 该页签没有弹出。 */
export type SidebarTabWindowsState = Record<string, SidebarTabWindowEntryState>;
-/** main → 主窗:页签离开弹出窗口,回到侧边栏(合并 / 窗口崩溃)。 */
+/** main → 主窗:页签离开弹出窗口,回到侧边栏(合并 / 崩溃)。 */
export interface SidebarTabReturnedPayload {
sessionId: string | null;
tabId: string;
@@ -70,14 +103,17 @@ export const SIDEBAR_TAB_WINDOW_PRESENTATION_READY_CHANNEL =
'sidebar-tab-window:presentation-ready';
/** renderer → main(invoke):读取本窗口的指派(重载 / 预热窗口晚于指派挂载时用)。 */
export const SIDEBAR_TAB_WINDOW_GET_ASSIGNMENT_CHANNEL = 'sidebar-tab-window:get-assignment';
-/** renderer → main(invoke):把页签合并回侧边栏并关闭本窗口。 */
+/** renderer → main(invoke):把某个页签合并回侧边栏;窗口清空后随之关闭。 */
export const SIDEBAR_TAB_WINDOW_MERGE_BACK_CHANNEL = 'sidebar-tab-window:merge-back';
-/** main → 弹出窗口(send):指派页签。 */
+/** renderer → main(invoke):本窗口里新建的页签归本窗口承载。 */
+export const SIDEBAR_TAB_WINDOW_ADOPT_TAB_CHANNEL = 'sidebar-tab-window:adopt-tab';
+/** main → 弹出窗口(send):指派(页签加入 / 离开时重发全量)。 */
export const SIDEBAR_TAB_WINDOW_ASSIGNED_CHANNEL = 'sidebar-tab-window:assigned';
/**
* main → 弹出窗口(send):用户经原生入口关窗(红绿灯 / 系统关闭 / Windows X)。
- * 关窗 = 关闭这个页签:renderer 走 store.closeTab(插件 onBeforeClose、确认拦截照常),
- * 页签从桶里消失后再由 renderer 请求 close-for-tab 销毁窗口;被否决则窗口留着。
+ * 关窗 = 关闭窗口里的全部页签:renderer 逐个走 store.closeTab(插件 onBeforeClose、
+ * 确认拦截照常),页签从桶里消失后再由 renderer 请求 close-for-tab;最后一个页签
+ * 离开时 main 销毁窗口;有页签被否决则窗口留着。
*/
export const SIDEBAR_TAB_WINDOW_CLOSE_REQUESTED_CHANNEL = 'sidebar-tab-window:close-requested';
/** main → 弹出窗口(send):显示 / 隐藏切换。 */
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 6b0965e7b7..7a8f2fec9a 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -807,7 +807,7 @@ Cindy Desktop is an Electron app: layout responds to window resizing, not page b
### Desktop Window
-- Minimum window size: **800 × 600** for the main window and secondary session windows (enforced at the BrowserWindow level — `apps/desktop/src/main/bootstrap-electron.ts` / `secondary-windows.ts`). The detached right-sidebar window has its own smaller floor of **360 × 480** (`right-sidebar-window/window.ts`), and a popped-out single sidebar tab window floors at **360 × 420** (`sidebar-tab-window/window.ts`) — layouts hosted there must stay legible down to that width
+- Minimum window size: **800 × 600** for the main window and secondary session windows (enforced at the BrowserWindow level — `apps/desktop/src/main/bootstrap-electron.ts` / `secondary-windows.ts`). The detached right-sidebar window has its own smaller floor of **360 × 480** (`right-sidebar-window/window.ts`), and a popped-out sidebar tab window (one or more tabs) floors at **360 × 420** (`sidebar-tab-window/window.ts`) — layouts hosted there must stay legible down to that width
- The sidebar is collapsible; region dividers and paddings hold as the window narrows, and content reflows fluidly
- Chat stream and composer reflow with the window; code blocks keep horizontal scroll instead of wrapping
- Ordinary control sizes and paddings follow their §4 component treatments at every window size. Registered shapes and their hit regions follow their owning component treatments and §5 Interaction constraints; the usage charts' dense date targets use the Equivalent route only under the conditions stated there. Window resizing does not waive the applicable target requirements or authorize changing a mark's registered geometry.
diff --git a/docs/dev-rules/electron-security-and-process-boundaries.md b/docs/dev-rules/electron-security-and-process-boundaries.md
index bb1b6e4885..7df34471ce 100644
--- a/docs/dev-rules/electron-security-and-process-boundaries.md
+++ b/docs/dev-rules/electron-security-and-process-boundaries.md
@@ -116,8 +116,8 @@ Renderer 可以负责组件渲染、交互状态、表单状态、展示数据
必须区分冷启动与热打开,并确认热打开链路没有重新创建 BrowserWindow、重新加载 Renderer
或同步等待业务数据。
-按内容多实例、内容回到主窗即结束的窗口(右侧栏单页签弹出窗口,
-`main/sidebar-tab-window/controller.ts`)对「隐藏复用」取另一种等价形式:关窗即关闭该页签
+按内容多实例、内容回到主窗即结束的窗口(右侧栏页签弹出窗口,一扇窗承载若干页签,
+`main/sidebar-tab-window/controller.ts`)对「隐藏复用」取另一种等价形式:关窗即关闭窗内页签
(经 renderer 走与侧边栏相同的 closeTab 流程),页签关掉或合并回侧边栏后窗口没有可复用的
内容,随即销毁;「准备成本移出点击路径」由一扇未指派的预热 spare
窗口承担(弹出时只做指派 → 首份内容 → `show()`),指派后再延迟补一扇。崩溃不重建 renderer,
@@ -128,7 +128,7 @@ Renderer 可以负责组件渲染、交互状态、表单状态、展示数据
隔离要求仍然适用。
`webviewTag` 默认关闭;受控例外目前只有两类——主界面与右侧栏子窗口(内置浏览器需要;
-右侧栏整栏子窗口与单页签弹出窗口共用 `main/right-sidebar-window/window.ts` 的
+右侧栏整栏子窗口与页签弹出窗口共用 `main/right-sidebar-window/window.ts` 的
`createSidebarHostWindow` 工厂与 `sidebarWindowPreload`,`main/sidebar-tab-window/window.ts`
只改启动参数、尺寸与位置记忆)。插件面板(ghost 分区 webview)不再有专属窗口:它以右侧栏
全局页签承载,弹出时走同一扇页签窗口——所有例外都必须继续由 `webview-security.ts` 在 `will-attach-webview` 阶段