Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
页签窗口 review 第二轮:崩溃交回内存页签、全局页签迁移不截断、写入基于最新存储
Dash1a731e0b2084
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.tsindex e650f72059..2fbb765a8f 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@@ -426,6 +426,34 @@ describe('SidebarTabWindowsController', () => {expect(h.returned).toHaveLength(0);});+ // 测试价值+ // - 生产入口与可观察结果:adoptTab(snapshot) → 窗口崩溃;可观察的是不可持久化会话里窗口内新建的+ // 页签,崩溃时交回通知带着当时的内存快照(主窗从未见过这个页签,否则它随窗口一起消失)。+ // - Bug / 规则依据:PR #6468 review(保留崩溃窗口中新建的内存页签)。+ // - 现有覆盖缺口:崩溃交回快照固定为 null。+ // - 最小失败输入:adopt 一个带快照的页签后触发 render-process-gone。+ // - tier:unit(mock deps)。+ it('returns the snapshot of an adopted in-memory tab when the window crashes', () => {+ 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));+ const snapshot = {+ sessionId: 's1',+ tab: { id: 'tab-n', kind: 'web-browser', state: { url: 'x' } },+ };+ h.controller.adoptTab(h.wc(win), 'tab-n', 's1', snapshot);+ win.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });+ expect(h.returned.find((payload) => payload.tabId === 'tab-n')).toEqual({+ sessionId: 's1',+ tabId: 'tab-n',+ snapshot,+ reason: 'crash',+ });+ expect(h.returned.find((payload) => payload.tabId === 'tab-a')?.snapshot).toBeNull();+ });+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.tsindex b0cb4be904..2a2e105e15 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@@ -222,6 +222,6 @@ describe('sidebar-tab-window IPC', () => {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);+ expect(controller.adoptTab).toHaveBeenCalledWith(otherSender, 'tab-n', null, null);});});diff --git a/apps/desktop/src/main/sidebar-tab-window/controller.ts b/apps/desktop/src/main/sidebar-tab-window/controller.tsindex 635dab3625..7781f140ab 100644--- a/apps/desktop/src/main/sidebar-tab-window/controller.ts+++ b/apps/desktop/src/main/sidebar-tab-window/controller.ts@@ -81,6 +81,8 @@ export interface WindowSlot {presentationReady: boolean;visible: boolean;pendingOpen: boolean;+ /** 窗口里新建的不可持久化页签的内存态(tabId → 快照):崩溃 / 作废交回时带回,不让页签连窗口一起消失。 */+ adoptedSnapshots: Map<string, SidebarTabReturnSnapshot>;/** 首次展示前要套用的位置(拖出窗口松手点);展示后清空。 */pendingPosition: { x: number; y: number } | null;destroyingWindow: boolean;@@ -223,6 +225,7 @@ export class SidebarTabWindowsController {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);+ slot.adoptedSnapshots.delete(tabId);return ref;}@@ -315,7 +318,12 @@ export class SidebarTabWindowsController {}/** 弹出窗口 renderer 在自己里面新建了页签:归它承载。已在别处的页签忽略。 */- adoptTab(sender: WebContents, tabId: string, sessionId: string | null): void {+ adoptTab(+ sender: WebContents,+ tabId: string,+ sessionId: string | null,+ snapshot: SidebarTabReturnSnapshot | null = null,+ ): void {const slot = this.slotForSender(sender);if (!slot?.assignment || this.tabToWindow.has(tabId)) return;if (@@ -331,6 +339,7 @@ export class SidebarTabWindowsController {}slot.assignment.tabs = [...slot.assignment.tabs, { tabId, sessionId }];this.tabToWindow.set(tabId, slot.assignment.windowId);+ if (snapshot && snapshot.tab.id === tabId) slot.adoptedSnapshots.set(tabId, snapshot);this.deliverAssignment(slot);this.broadcast();}@@ -455,6 +464,7 @@ export class SidebarTabWindowsController {presentationReady: false,visible: false,pendingOpen: false,+ adoptedSnapshots: new Map(),pendingPosition: null,destroyingWindow: false,openTimeout: null,@@ -565,7 +575,7 @@ export class SidebarTabWindowsController {this.deps.notifyTabReturned({sessionId: tab.sessionId,tabId: tab.tabId,- snapshot: null,+ snapshot: slot.adoptedSnapshots.get(tab.tabId) ?? null,reason,});}diff --git a/apps/desktop/src/main/sidebar-tab-window/ipc.ts b/apps/desktop/src/main/sidebar-tab-window/ipc.tsindex 2c9322d84d..bcd54b5de6 100644--- a/apps/desktop/src/main/sidebar-tab-window/ipc.ts+++ b/apps/desktop/src/main/sidebar-tab-window/ipc.ts@@ -239,6 +239,6 @@ export function registerSidebarTabWindowIpc(opts: {log.warn('SIDEBAR_TAB_WINDOW_ADOPT_TAB from non-tab-window sender, ignored', { tabId });return;}- controller.adoptTab(event.sender, tabId, sessionId);+ controller.adoptTab(event.sender, tabId, sessionId, parseReturnSnapshot(obj.snapshot));});}diff --git a/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsxindex daa81e6b2e..8f16054fa8 100644--- a/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx@@ -39,6 +39,7 @@ import {import {closeTab,getBucket,+ getSingleTabSnapshot,importTabSnapshot,isTabClosing,refreshSessionFromDb,@@ -313,7 +314,9 @@ export function SidebarTabWindowLayout() {(tabId: string) => {addHostedTabId(tabId);const created = isGlobalTabId(tabId) ? null : sessionId;- void api?.adoptTab?.({ tabId, sessionId: created }).catch((err) => {+ // 不可持久化会话的新页签只存在于本 renderer:带上内存态,窗口崩溃时 main 才能把它交回。+ const snapshot = created ? getSingleTabSnapshot(created, tabId) : null;+ void api?.adoptTab?.({ tabId, sessionId: created, snapshot }).catch((err) => {log.warn('adopt new tab failed', { tabId, err });});},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.tsindex f8360adb1e..8fd4148438 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@@ -26,6 +26,7 @@ import {isPluginWindowPlacement,rememberPluginWindowPlacement,removeGlobalTab,+ reconcileGlobalPluginTabs,reorderGlobalTabs,resetPluginPlacement,sanitizeGlobalTabsSnapshot,@@ -50,7 +51,7 @@ afterEach(() => {describe('globalTabs', () => {it('adds one tab per plugin instance, persists per data owner and remembers dismissals', () => {const tab = addGlobalPluginTab('alpha')!;- expect(addGlobalPluginTab('alpha')).toBe(tab);+ expect(addGlobalPluginTab('alpha')).toEqual(tab);expect(getGlobalTabs()).toHaveLength(1);expect(window.localStorage.getItem('xdt:rightSidebarGlobalTabs:v1:owner-a')).toContain('alpha');@@ -202,4 +203,31 @@ describe('globalTabs', () => {expect(effectivePluginView({ instanceId: 'gamma' }, g)).toBe('panel');expect(effectivePluginView({ instanceId: 'gamma' }, ghost({ panel: undefined }))).toBe('main');});+ // 测试价值+ // - 生产入口与可观察结果:reconcileGlobalPluginTabs / removeGlobalTab / setTabGroup 的写路径;可观察的是+ // 超过 20 个停靠面板的存量插件全部迁移成页签(不被会话页签的小上限截断),以及另一个窗口刚做的+ // 修改(storage 事件还没送到、本窗口缓存是旧的)不会被本窗口接下来的写入整份覆盖回去。+ // - Bug / 规则依据:PR #6468 review(迁移截断 / 跨窗口全局页签写入互相覆盖);存量插件兼容红线。+ // - 现有覆盖缺口:此前只有单窗口读写。+ // - 最小失败输入:25 个面板插件;窗口 A 缓存旧列表,localStorage 被窗口 B 改过后窗口 A 再关另一个页签。+ it('migrates every stored docked panel and never overwrites another window with a stale cache', () => {+ const many = Array.from({ length: 25 }, (_, i) => ({+ manifest: { id: `p${i}`, name: `P${i}`, panel: { html: 'p.html' } },+ enabled: true,+ })) as unknown as import('../../../../shared/ghost').InstalledGhost[];+ reconcileGlobalPluginTabs(many);+ expect(getGlobalTabs()).toHaveLength(25);++ // 本窗口缓存里是 25 个;另一个窗口把 p0 关掉并写回 localStorage(storage 事件尚未处理)。+ const key = 'xdt:rightSidebarGlobalTabs:v1:owner-a';+ const other = JSON.parse(window.localStorage.getItem(key)!);+ other.tabs = other.tabs.filter((tab: { id: string }) => tab.id !== 'g_p0');+ window.localStorage.setItem(key, JSON.stringify(other));+ // 本窗口再关 p1:必须基于 localStorage 最新一份,p0 不会被写回来。+ removeGlobalTab('g_p1');+ const ids = getGlobalTabs().map((tab) => tab.id);+ expect(ids).toHaveLength(23);+ expect(ids).not.toContain('g_p0');+ expect(ids).not.toContain('g_p1');+ });});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.tsindex 8ac95e3822..9e61ce6527 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@@ -1568,7 +1568,7 @@ describe('cross-renderer sync for popped-out tabs', () => {tab: { id: tab.id, kind: 'web-browser', state: { url: 'https://edited' } },});expect(store.getBucket('mem-s1').tabs[0].state).toEqual({ url: 'https://edited' });- // 未知页签 / 未加载会话:不新增、不报错。+ // 主窗没见过的页签(窗口里新建、窗口崩溃时带回)追加回桶;未加载的会话:丢弃、不报错。store.importReturnedTabState({sessionId: 'mem-s1',tab: { id: 'ghost', kind: 'web-browser', state: {} },@@ -1577,7 +1577,7 @@ describe('cross-renderer sync for popped-out tabs', () => {sessionId: 'never-loaded',tab: { id: 'x', kind: 'y', state: {} },});- expect(store.getBucket('mem-s1').tabs).toHaveLength(1);+ expect(store.getBucket('mem-s1').tabs.map((t) => t.id)).toEqual([tab.id, 'ghost']);expect(store.getBucket('never-loaded').hydrated).toBe(false);});});@@ -1617,6 +1617,22 @@ describe('multi-tab window handoff merge (memory-only sessions)', () => {expect(bucket.activeTabId).toBe('tab-a');});+ it('importReturnedTabState re-adds a returned tab the main window never saw', async () => {+ store = await import('../store');+ store._resetStore();+ store.importTabSnapshot({+ sessionId: 'remote-m3',+ persistable: false,+ activeTabId: null,+ tabs: [{ id: 'tab-a', kind: 'file-browser', state: null }],+ });+ store.importReturnedTabState({+ sessionId: 'remote-m3',+ tab: { id: 'tab-new', kind: 'web-browser', state: { url: 'https://n.example/' } },+ });+ expect(store.getBucket('remote-m3').tabs.map((tab) => tab.id)).toEqual(['tab-a', 'tab-new']);+ });+it('removeTabLocally drops a tab closed elsewhere without issuing a close IPC', async () => {store = await import('../store');store._resetStore();diff --git a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.tsindex fd41702c58..c42ed84aa3 100644--- a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts@@ -34,7 +34,11 @@ import type { TabState } from './types';const log = createLogger('rightSidebar.globalTabs');const STORAGE_KEY_PREFIX = 'xdt:rightSidebarGlobalTabs:v1:';-const MAX_GLOBAL_TABS = 20;+/**+ * 全局页签数量上限只是防损坏存档的兜底,必须远大于已装插件的现实数量:存量停靠面板要全部迁移,+ * 不能被会话页签那种小上限截断(截断 = 升级后部分面板插件静默不可用)。+ */+const MAX_GLOBAL_TABS = 500;/** 页签承载插件的哪个页面:停靠面板(panel.html)或主视图(mainView.html)。 */export type PluginViewKind = 'panel' | 'main';@@ -170,6 +174,16 @@ function ensureStorageListener(): void {});}+/**+ * 写路径专用:先丢掉本窗口内存缓存、从 localStorage 重读最新一份再改。主窗与每扇弹出窗口各有+ * 独立缓存,拿旧缓存做「读—改—写」会把别的窗口刚做的修改(刚关掉的页签等)整份覆盖回去。+ * localStorage 同步且跨窗口共享,同一 JS 任务内「重读 + 写回」之间没有别的窗口能插进来。+ */+function freshSnapshot(): GlobalTabsSnapshot {+ cache = null;+ return getGlobalTabsSnapshot();+}+export function getGlobalTabsSnapshot(): GlobalTabsSnapshot {const key = ownerKey();if (cache === null || cacheOwnerKey !== key) {@@ -244,7 +258,7 @@ export function addGlobalPluginTab(instanceId: string,opts?: { groupId?: TabGroupId; ghost?: InstalledGhost; view?: PluginViewKind },): TabState | null {- const current = getGlobalTabsSnapshot();+ const current = freshSnapshot();const existing = current.tabs.find((tab) => (tab.state as PluginViewTabState | null)?.instanceId === instanceId,);@@ -298,7 +312,7 @@ export function addGlobalPluginTab(/** 用户关闭全局页签:全局动作,同时记 dismissed,插件不再自动加回。 */export function removeGlobalTab(tabId: string): void {- const current = getGlobalTabsSnapshot();+ const current = freshSnapshot();const tab = current.tabs.find((candidate) => candidate.id === tabId);if (!tab) return;const instanceId = (tab.state as PluginViewTabState).instanceId;@@ -321,7 +335,7 @@ export function removeGlobalTab(tabId: string): void {}export function reorderGlobalTabs(orderedIds: string[]): void {- const current = getGlobalTabsSnapshot();+ const current = freshSnapshot();if (orderedIds.length !== current.tabs.length) return;const byId = new Map(current.tabs.map((tab) => [tab.id, tab]));const next: TabState[] = [];@@ -335,7 +349,7 @@ export function reorderGlobalTabs(orderedIds: string[]): void {/** 记住 / 忘记「这个插件上次弹在独立窗口里」。 */export function rememberPluginWindowPlacement(instanceId: string, inWindow: boolean): void {- const current = getGlobalTabsSnapshot();+ const current = freshSnapshot();const has = current.windowInstanceIds.includes(instanceId);if (has === inWindow) return;persist({@@ -366,7 +380,7 @@ export function hasPluginPlacementMemory(instanceId: string): boolean {* 弹在窗口里的页签由调用方先合并回侧边栏(这里不碰窗口)。*/export function resetPluginPlacement(instanceId: string, ghost?: InstalledGhost): void {- const current = getGlobalTabsSnapshot();+ const current = freshSnapshot();const tabId = globalTabIdForInstance(instanceId);clearTabGroup(tabId);const presentTab = current.tabs.find((tab) => tab.id === tabId);@@ -427,7 +441,7 @@ export function isGlobalTabCapableGhost(ghost: InstalledGhost): boolean {* 停用的插件页签**保留**(投影时按可用性隐藏),重新启用原位回来。*/export function reconcileGlobalPluginTabs(ghosts: readonly InstalledGhost[]): void {- const current = getGlobalTabsSnapshot();+ const current = freshSnapshot();const installed = new Map(ghosts.map((ghost) => [installedGhostStoragePart(ghost), ghost]));let tabs = current.tabs.filter((tab) =>installed.has((tab.state as PluginViewTabState).instanceId),@@ -439,7 +453,6 @@ export function reconcileGlobalPluginTabs(ghosts: readonly InstalledGhost[]): vofor (const [instanceId, ghost] of installed) {if (!isAutoGlobalPanelGhost(ghost)) continue;if (present.has(instanceId) || dismissed.includes(instanceId)) continue;- if (tabs.length >= MAX_GLOBAL_TABS) break;const tabId = globalTabIdForInstance(instanceId);// 首次出现:按插件声明放默认边(存量 panel.position 的插件回到它原来停的那一边)。if (!placed.includes(instanceId)) {diff --git a/apps/desktop/src/renderer/features/right-sidebar/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.tsindex 853449e46b..24ae69d347 100644--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts@@ -600,9 +600,18 @@ export function importReturnedTabState(snapshot: SidebarTabReturnSnapshot): voidreturn;}const idx = bucket.tabs.findIndex((t) => t.id === snapshot.tab.id);- if (idx < 0) return;+ const restored: TabState = {+ id: snapshot.tab.id,+ kind: snapshot.tab.kind as TabKindId,+ state: snapshot.tab.state,+ };+ // 窗口里新建、主窗从未见过的页签(窗口崩溃时 main 带回快照):追加回桶里,不让它随窗口消失。+ if (idx < 0) {+ setBucket(snapshot.sessionId, { tabs: [...bucket.tabs, restored] });+ return;+ }const tabs = [...bucket.tabs];- tabs[idx] = { ...tabs[idx], kind: snapshot.tab.kind as TabKindId, state: snapshot.tab.state };+ tabs[idx] = { ...tabs[idx], ...restored };setBucket(snapshot.sessionId, { tabs });}diff --git a/apps/desktop/src/renderer/features/right-sidebar/tabGroups.ts b/apps/desktop/src/renderer/features/right-sidebar/tabGroups.tsindex a6d776c6a9..53c70b1321 100644--- a/apps/desktop/src/renderer/features/right-sidebar/tabGroups.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/tabGroups.ts@@ -80,6 +80,12 @@ function ensureStorageListener(): void {});}+/** 写路径专用:丢掉本窗口缓存、从 localStorage 重读最新再改(理由同 globalTabs 的 freshSnapshot)。 */+function freshAssignments(): TabGroupAssignments {+ cache = null;+ return getTabGroupAssignments();+}+export function getTabGroupAssignments(): TabGroupAssignments {const key = ownerKey();if (cache === null || cacheOwnerKey !== key) {@@ -114,7 +120,7 @@ export function tabGroupOf(assignments: TabGroupAssignments, tabId: string): Tab/** 把页签放进某组。放回右侧组 = 删条目。超出上限时丢最早的条目。 */export function setTabGroup(tabId: string, groupId: TabGroupId): void {- const current = getTabGroupAssignments();+ const current = freshAssignments();if (tabGroupOf(current, tabId) === groupId) return;const next: Record<string, TabGroupId> = { ...current };if (groupId === DEFAULT_TAB_GROUP) {@@ -130,7 +136,7 @@ export function setTabGroup(tabId: string, groupId: TabGroupId): void {/** 页签关闭:清掉它的组记录(没有记录时 no-op,不触发通知)。 */export function clearTabGroup(tabId: string): void {- const current = getTabGroupAssignments();+ const current = freshAssignments();if (!(tabId in current)) return;const next = { ...current };delete next[tabId];diff --git a/apps/desktop/src/shared/sidebarTabWindow.ts b/apps/desktop/src/shared/sidebarTabWindow.tsindex 971d4c91bf..f0e8819ce5 100644--- a/apps/desktop/src/shared/sidebarTabWindow.ts+++ b/apps/desktop/src/shared/sidebarTabWindow.ts@@ -70,6 +70,11 @@ export interface SidebarTabWindowMergeBackRequest {export interface SidebarTabWindowAdoptRequest {tabId: string;sessionId: string | null;+ /**+ * 不可持久化会话(device-link 远程)里新建页签的内存态:页签只存在于该 renderer 里,+ * main 留一份,窗口崩溃 / 作废时随交回通知带回侧栏,页签不会连同窗口一起消失。+ */+ snapshot?: SidebarTabReturnSnapshot | null;}/** 单个已弹出页签的运行时状态;只在当前进程有效,不跨重启。 */