Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(browser): 保留任务切换后的原生页面状态
shenjiachenga0dabf3a3f91
diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex 16bae6691f..d5a98c0066 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -63,6 +63,7 @@ import './plugins';import { initRsbBrowserBridge } from './lib/rsbBrowserBridge';import { initPopupRouter, setPopupFallbackSession } from './lib/popupRouter';import { TabBodyErrorBoundary } from './TabBodyErrorBoundary';+import { useRetainedBrowserTabHosts } from './hooks/useRetainedBrowserTabHosts';import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';import {mergeAvailableTabOrder,@@ -563,6 +564,14 @@ export function RightSidebarShell({return off;}, [handleCycleTab, sessionId]);+ const bodyHosts = useRetainedBrowserTabHosts(+ bucket.hydrated+ ? tabs+ .filter((tab) => tab.id === activeTabId || deferredMountedTabIds.has(tab.id))+ .map((tab) => ({ tab, sessionId, workdir, remoteHostId, deviceLinkDeviceId }))+ : [],+ );+return (<div className="flex h-full min-h-0 flex-1 flex-col overflow-hidden">{unifiedTopbar ? (@@ -703,26 +712,19 @@ export function RightSidebarShell({onAddBrowserTab={() => handleAdd('web-browser')}onAddTerminalTab={() => handleAdd('terminal')}/>- ) : (- // 所有 tab 都挂载,只切换可见性(规则 7:杜绝切顶层 tab 时 plugin 内部 state /- // webview / 编辑器 / 文件树 expansion 全部丢失重建)。pointer-events 用- // `hidden` 自然 disable,visibility 状态由 onVisibilityChange 给 plugin。- tabs- .filter((tab) => tab.id === activeTabId || deferredMountedTabIds.has(tab.id))- .map((tab) => (- <PluginBodyHost- key={tab.id}- tab={tab}- active={tab.id === activeTabId}- sessionId={sessionId}- workdir={workdir}- remoteHostId={remoteHostId}- deviceLinkDeviceId={deviceLinkDeviceId}- shellVisible={shellVisible}- t={t}- />- ))- )}+ ) : null}+ {/* Keep one keyed list even when the foreground task is empty or still+ hydrating. Pool-backed background browsers keep their original slot+ and task context; the pool still decides when to release them. */}+ {bodyHosts.map((host) => (+ <PluginBodyHost+ key={host.tab.id}+ {...host}+ active={host.sessionId === sessionId && host.tab.id === activeTabId}+ shellVisible={shellVisible}+ t={t}+ />+ ))}</div></div>);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.tsindex 23e35daa8e..546c5e5ced 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@@ -4,7 +4,7 @@ import { createElement, useEffect } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { AppShortcutOverrides } from '../../../../shared/appShortcuts';-import type { LucideIcon } from 'lucide-react';+import { Globe, type LucideIcon } from 'lucide-react';vi.mock('react-i18next', () => ({initReactI18next: { type: '3rdParty', init: vi.fn() },@@ -41,6 +41,10 @@ vi.mock('../lib/rsbBrowserBridge', async () => {});import { RightSidebarShell } from '../RightSidebarShell';+import { BrowserTabBody } from '../plugins/web-browser/BrowserTabBody';+import type { WebBrowserState } from '../plugins/web-browser';+import type { TabKindBodyProps } from '../types';+import { browserWebviewPool } from '../lib/browserWebviewPool';import { registerTabKind, unregisterTabKind } from '../registry';import { _resetRsbBrowserBridgeForTests } from '../lib/rsbBrowserBridge';import { _resetPopupRouterForTests } from '../lib/popupRouter';@@ -276,6 +280,104 @@ describe('RightSidebarShell empty state', () => {delete (window as unknown as { electronAPI?: unknown }).electronAPI;});+ it.each([+ { otherBrowser: false, release: 'close' },+ { otherBrowser: true, release: 'close' },+ { otherBrowser: false, release: 'evict' },+ { otherBrowser: true, release: 'evict' },+ ])('keeps a live browser connected across task switches ($otherBrowser) until $release', async ({ otherBrowser, release }) => {+ Object.assign(window.electronAPI, { onRsbBrowserFocusUrlBar: () => () => undefined });+ registerTabKind({+ kind: 'web-browser',+ menu: { kind: 'web-browser', labelKey: 'browser', icon: Globe, order: 1, enabled: true },+ TabPillTitle: () => createElement('span', null, 'browser'),+ TabBody: (props: TabKindBodyProps) => createElement(BrowserTabBody, { ...props, state: props.state as WebBrowserState }),+ defaultState: () => ({ url: 'https://example.test/', title: '', favicon: null, isAudible: false }),+ });+ const entry = browserWebviewPool.acquire('browser-a');+ // jsdom has no Electron guest APIs. Keep the real pool, hook and bodies;+ // only supply the native boundary used to observe a loaded guest.+ Object.assign(entry.webview, {+ getURL: () => 'https://example.test/',+ getTitle: () => '',+ canGoBack: () => false,+ canGoForward: () => false,+ getWebContentsId: () => 101,+ setAudioMuted: () => undefined,+ executeJavaScript: async () => undefined,+ });+ if (otherBrowser) {+ const b = browserWebviewPool.acquire('browser-b');+ Object.assign(b.webview, {+ getURL: () => 'https://other.test/', getTitle: () => '',+ canGoBack: () => false, canGoForward: () => false,+ getWebContentsId: () => 102, setAudioMuted: () => undefined,+ executeJavaScript: async () => undefined,+ });+ }+ tabsIpc.list.mockImplementation(async ({ sessionId }: { sessionId: string }) => sessionId === 'task-a' ? {+ tabs: [{ id: 'browser-a', kind: 'web-browser', state: { url: 'https://example.test/' } }],+ activeTabId: 'browser-a',+ } : otherBrowser ? {+ tabs: [{ id: 'browser-b', kind: 'web-browser', state: { url: 'https://other.test/' } }],+ activeTabId: 'browser-b',+ } : { tabs: [], activeTabId: null });+ const props = { workdir: '/tmp/task-a', remoteHostId: null, isMac: true };+ const view = render(createElement(RightSidebarShell, { ...props, sessionId: 'task-a' }));+ try {+ await waitFor(() => expect(entry.wrapper.parentElement?.id).not.toBe('browser-webview-pool'));+ const slot = entry.wrapper.parentElement!;+ expect(slot.isConnected).toBe(true);+ const removedAncestors: Node[] = [];+ const observer = new MutationObserver((records) => {+ for (const record of records) for (const node of record.removedNodes) {+ if (node.contains(entry.wrapper)) removedAncestors.push(node);+ }+ });+ observer.observe(view.container, { childList: true, subtree: true });+ for (let i = 0; i < 3; i++) {+ view.rerender(createElement(RightSidebarShell, { ...props, workdir: '/tmp/task-b', sessionId: 'task-b' }));+ await waitFor(() => expect(getBucket('task-b').hydrated).toBe(true));+ expect(entry.wrapper.parentElement).toBe(slot);+ expect(slot.isConnected).toBe(true);+ expect(slot.closest('[aria-hidden="true"]')).not.toBeNull();+ view.rerender(createElement(RightSidebarShell, { ...props, sessionId: 'task-a' }));+ expect(entry.wrapper.parentElement).toBe(slot);+ expect(slot.closest('[aria-hidden="true"]')).toBeNull();+ }+ await act(async () => { await Promise.resolve(); });+ observer.disconnect();+ expect(removedAncestors).toHaveLength(0);+ // A's event writes to A's bucket even while B is the foreground task.+ view.rerender(createElement(RightSidebarShell, { ...props, workdir: '/tmp/task-b', sessionId: 'task-b' }));+ await act(async () => {+ entry.webview.dispatchEvent(Object.assign(new Event('page-title-updated'), { title: 'A in background' }));+ });+ expect(getBucket('task-a').tabs[0].state).toMatchObject({ title: 'A in background' });+ if (otherBrowser) expect(getBucket('task-b').tabs[0].state).not.toMatchObject({ title: 'A in background' });+ if (release === 'close') {+ await act(async () => { await closeTab('task-a', 'browser-a'); });+ } else {+ act(() => { for (let i = 0; i < 5; i++) browserWebviewPool.acquire('pressure-' + i); });+ }+ expect(browserWebviewPool.peek('browser-a')).toBeNull();+ expect(entry.wrapper.isConnected).toBe(false);+ expect(slot.isConnected).toBe(false);+ if (release === 'evict') {+ view.rerender(createElement(RightSidebarShell, { ...props, sessionId: 'task-a' }));+ await waitFor(() => expect(browserWebviewPool.peek('browser-a')).not.toBeNull());+ const restored = browserWebviewPool.peek('browser-a')!;+ expect(restored.wrapper).not.toBe(entry.wrapper);+ expect(restored.webview.getAttribute('src')).toBe('https://example.test/');+ expect(browserWebviewPool.inspectTabIds().length).toBeLessThanOrEqual(5);+ }+ } finally {+ view.unmount();+ browserWebviewPool.releaseAll();+ unregisterTabKind('web-browser');+ }+ });+it('clears the active browser session only when a visible detached shell is hidden', async () => {const setActiveSession = window.electronAPI.rsbBrowserBridge.setActiveSession;const view = render(diff --git a/apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts b/apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.tsnew file mode 100644index 0000000000..c48ab34780--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts@@ -0,0 +1,69 @@+import { useEffect, useLayoutEffect, useRef, useState } from 'react';++import { browserWebviewPool } from '../lib/browserWebviewPool';+import { getBucket, subscribe } from '../store';+import type { TabState } from '../types';++export interface TabBodyHostDescriptor {+ tab: TabState;+ sessionId: string | null;+ workdir: string;+ remoteHostId: string | null;+ deviceLinkDeviceId?: string | null;+}++/**+ * Keep the slots of live browser guests connected when their task leaves the+ * sidebar. Moving a pooled webview to parking and back recreates its Electron+ * guest, even when the wrapper DOM object itself survives.+ *+ * The pool remains the sole resource budget: retention never acquires or pins+ * a guest. Close, eviction and host handoff remove the corresponding hidden+ * body. Other plugins and unmaterialized browser tabs are not kept across tasks.+ */+export function useRetainedBrowserTabHosts(+ current: readonly TabBodyHostDescriptor[],+): TabBodyHostDescriptor[] {+ const previous = useRef<readonly TabBodyHostDescriptor[]>([]);+ const [, refresh] = useState(0);++ useEffect(() => {+ const onChange = () => refresh((version) => version + 1);+ const unsubscribeStore = subscribe(onChange);+ const unsubscribeRelease = browserWebviewPool.onRelease(onChange);+ const unsubscribeCreated = browserWebviewPool.onEntryCreated(onChange);+ return () => {+ unsubscribeStore();+ unsubscribeRelease();+ unsubscribeCreated();+ };+ }, []);++ const hosts: TabBodyHostDescriptor[] = [];+ const remaining = new Map(current.map((host) => [host.tab.id, host]));+ for (const host of previous.current) {+ const foreground = remaining.get(host.tab.id);+ if (foreground) {+ hosts.push(foreground);+ remaining.delete(host.tab.id);+ continue;+ }+ if (!host.sessionId || !browserWebviewPool.peek(host.tab.id)) continue;+ // Background navigation/close updates belong to the original task. Never+ // reuse the foreground task's context or revive a tab missing from its bucket.+ const bucket = getBucket(host.sessionId);+ const tab = bucket.hydrated && bucket.tabs.find((candidate) => candidate.id === host.tab.id);+ if (tab && tab.kind === 'web-browser') hosts.push({ ...host, tab });+ }+ // Stable browser order matters too: React moving an ancestor of a webview+ // within this list disconnects the guest just like reparenting its wrapper.+ hosts.push(...remaining.values());++ useLayoutEffect(() => {+ // Capture current candidates too: their child effects may materialize the+ // guest later in this commit, before the user can switch tasks.+ previous.current = hosts.filter(({ tab }) => tab.kind === 'web-browser');+ });++ return hosts;+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.tsindex 4dc8ef68c8..60cafaca91 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts@@ -5,8 +5,9 @@* 一旦被 React unmount(切到别的 tab / 切 RSB 整体卸载/重挂),guest webContents* 会被 detach + 销毁,下次切回来要重新加载,Cookie / form state / 浏览历史全丢。* 业界做法:把 webview DOM 节点保活在脱离当前 tab 子树的"停车区" container 里,- * 切 tab 时用 vanilla `appendChild` 把同一个 DOM 节点搬到目标 slot —— 浏览器 DOM- * 移动不会 detach iframe / webview 内部的 webContents,实现"切 tab 不重载"。+ * 首次物化时把 wrapper 放进目标 slot,之后由 Shell 保持仍存活的浏览器 body+ * 挂载。跨父节点搬动即使用 vanilla DOM 也会重建 Electron guest;池里保留同一个+ * DOM 对象不等于保留页面运行上下文,正常切换不能经过停车区。** **关键:不要用 React Portal**。Portal 内部跨 reconcile 的搬动会触发 React 把* 节点 remove + insert,这中间一帧会让 webview detach 丢 webContents。所以