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。

fix(desktop): 收束侧栏浏览器桥接归属与上下文刷新

DavidShen8090eacddf16
diff --git a/apps/desktop/src/main/rsb-browser-bridge/__tests__/ipc-routing.test.ts b/apps/desktop/src/main/rsb-browser-bridge/__tests__/ipc-routing.test.ts
new file mode 100644
index 0000000000..1edfddb7f1
--- /dev/null
+++ b/apps/desktop/src/main/rsb-browser-bridge/__tests__/ipc-routing.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => {
+ const handlers = new Map<string, (event: unknown, payload: unknown) => unknown>();
+ return {
+ app: { getAppMetrics: vi.fn(() => []) },
+ clipboard: { writeImage: vi.fn() },
+ ipcMain: {
+ handle: vi.fn((channel: string, handler: (event: unknown, payload: unknown) => unknown) => {
+ handlers.set(channel, handler);
+ }),
+ __handlers: handlers,
+ },
+ webContents: { fromId: vi.fn() },
+ };
+});
+
+import { ipcMain } from 'electron';
+import {
+ RSB_BROWSER_BRIDGE_PIN_CHANNEL,
+ RSB_BROWSER_BRIDGE_RELEASE_CHANNEL,
+} from '../../../shared/rsbBrowserBridge.js';
+import { _resetRsbBrowserBridgeIpcForTests, registerRsbBrowserBridgeIpc } from '../ipc.js';
+import type { TabRegistry } from '../registry.js';
+
+function handler(channel: string) {
+ const handlers = (ipcMain as unknown as {
+ __handlers: Map<string, (event: unknown, payload: unknown) => unknown>;
+ }).__handlers;
+ const registered = handlers.get(channel);
+ if (!registered) throw new Error(`missing handler: ${channel}`);
+ return registered;
+}
+
+function fakeGuest(ownerId: number) {
+ return {
+ id: 101,
+ hostWebContents: { id: ownerId },
+ isDestroyed: () => false,
+ getType: () => 'webview',
+ };
+}
+
+function makeRegistry(target: unknown) {
+ let pinListener: ((tabId: string, pinned: boolean) => void) | undefined;
+ return {
+ registry: {
+ getWebContentsByTabId: () => target,
+ release: vi.fn(),
+ onPinChange: (listener: (tabId: string, pinned: boolean) => void) => {
+ pinListener = listener;
+ return () => undefined;
+ },
+ listAll: () => [],
+ isPinned: () => false,
+ } as unknown as TabRegistry,
+ emitPin: (tabId: string, pinned: boolean) => pinListener?.(tabId, pinned),
+ };
+}
+
+function register(registry: TabRegistry) {
+ registerRsbBrowserBridgeIpc({
+ registry,
+ getHostWebContents: () => null,
+ logger: { info: vi.fn(), warn: vi.fn() },
+ });
+}
+
+beforeEach(() => {
+ _resetRsbBrowserBridgeIpcForTests();
+ (ipcMain as unknown as { __handlers: Map<string, unknown> }).__handlers.clear();
+});
+
+afterEach(() => {
+ _resetRsbBrowserBridgeIpcForTests();
+});
+
+describe('RSB browser bridge ownership routing', () => {
+ it('routes pin changes to the renderer that owns the tab', () => {
+ const guest = fakeGuest(7);
+ const owner = { id: 7, send: vi.fn(), isDestroyed: () => false };
+ const harness = makeRegistry(guest);
+ (guest as { hostWebContents: unknown }).hostWebContents = owner;
+ register(harness.registry);
+
+ harness.emitPin('tab-a', true);
+
+ expect(owner.send).toHaveBeenCalledWith(RSB_BROWSER_BRIDGE_PIN_CHANNEL, { tabId: 'tab-a' });
+ });
+
+ it('rejects release from a renderer that does not own the tab', () => {
+ const guest = fakeGuest(7);
+ const harness = makeRegistry(guest);
+ register(harness.registry);
+
+ expect(() =>
+ handler(RSB_BROWSER_BRIDGE_RELEASE_CHANNEL)(
+ { sender: { id: 9 } },
+ { tabId: 'tab-a', webContentsId: guest.id },
+ ),
+ ).toThrow(/INVALID_PARAMS/);
+ });
+
+ it('allows release from the current tab owner', () => {
+ const guest = fakeGuest(7);
+ const harness = makeRegistry(guest);
+ register(harness.registry);
+
+ expect(
+ handler(RSB_BROWSER_BRIDGE_RELEASE_CHANNEL)(
+ { sender: { id: 7 } },
+ { tabId: 'tab-a', webContentsId: guest.id },
+ ),
+ ).toEqual({ ok: true });
+ });
+});
diff --git a/apps/desktop/src/main/rsb-browser-bridge/ipc.ts b/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
index 366a2d1217..ae5b8cac84 100644
--- a/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
+++ b/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
@@ -143,7 +143,7 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
return { ok: true };
});
- ipcMain.handle(RSB_BROWSER_BRIDGE_RELEASE_CHANNEL, (_e, payload: unknown) => {
+ ipcMain.handle(RSB_BROWSER_BRIDGE_RELEASE_CHANNEL, (event, payload: unknown) => {
const obj = requireObject(payload, 'release payload');
const tabId = requireString(obj.tabId, 'tabId');
// 可选 stale 防护:携带旧 renderer report 过的 webContentsId 时,registry
@@ -155,6 +155,18 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
}
expected = obj.webContentsId;
}
+
+ // A release is destructive: do not let one trusted renderer clear a tab
+ // registered by another renderer. Prefer the guest's actual owner when
+ // it is still alive; after a guest crash, the current host is the only
+ // remaining trusted caller that may perform the stale cleanup.
+ const target = registry.getWebContentsByTabId(tabId);
+ if (target) {
+ const owner = resolveOwner(target);
+ if (!owner || owner.id !== event.sender.id) {
+ throwIpcError('INVALID_PARAMS', `tab ${tabId} is not hosted by the sender`);
+ }
+ }
registry.release(tabId, expected);
return { ok: true };
});
@@ -351,7 +363,11 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
// pin changes only happen while automation is running and the renderer is
// live by definition).
const unsubscribe = registry.onPinChange((tabId, pinned) => {
- const wc = getHostWebContents();
+ // Pin state belongs to the renderer hosting this tab, not necessarily the
+ // currently visible RSB window (the detached window may be hidden or the
+ // tab may have migrated between hosts).
+ const target = registry.getWebContentsByTabId(tabId);
+ const wc = target ? resolveOwner(target) : null;
if (!wc || wc.isDestroyed()) return;
wc.send(pinned ? RSB_BROWSER_BRIDGE_PIN_CHANNEL : RSB_BROWSER_BRIDGE_UNPIN_CHANNEL, {
tabId,
diff --git a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
index e9bbc9d04a..3832556cef 100644
--- a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
@@ -152,9 +152,15 @@ export function SidebarWindowLayout() {
.catch((err) => {
if (visibilityRevisionRef.current !== revision) return;
log.warn('refresh context on show failed', err);
- // 保持 context 为空,允许窗口展示安全占位态;后续 context-changed
- // 推送仍可正常恢复真实任务。
- setWindowVisible(true);
+ // Keep the shell mounted for recovery, but never expose the
+ // previous session after a failed context refresh.
+ if (contextRevisionRef.current === contextRevision) {
+ setCtx(null);
+ setWindowVisible(false);
+ } else {
+ // A newer push won the race, so its context is safe to reveal.
+ setWindowVisible(true);
+ }
});
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
}
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
index dddb6ef9ca..e264b83bfc 100644
--- a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
+++ b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
@@ -375,6 +375,35 @@ describe('reusable auxiliary window chrome', () => {
expect(mocks.sidebarLightboxMountId).not.toBe(hiddenMountId);
});
+ it('keeps the sidebar hidden and clears the old context when refresh fails', async () => {
+ window.electronAPI.rightSidebarWindow.getContext = vi
+ .fn()
+ .mockResolvedValueOnce({
+ sessionId: 'session-a',
+ workdir: '/workdir-a',
+ remoteHostId: null,
+ available: true,
+ })
+ .mockResolvedValueOnce({
+ sessionId: 'session-a',
+ workdir: '/workdir-a',
+ remoteHostId: null,
+ available: true,
+ })
+ .mockRejectedValueOnce(new Error('context unavailable'));
+
+ render(<SidebarWindowLayout />);
+ await waitFor(() => expect(mocks.sidebarShellSessionId).toBe('session-a'));
+
+ await act(async () => mocks.sidebarVisibilityListener?.({ visible: true }));
+ await act(async () => mocks.sidebarVisibilityListener?.({ visible: false }));
+ await act(async () => mocks.sidebarVisibilityListener?.({ visible: true }));
+
+ expect(mocks.sidebarShellVisible).toBe(false);
+ expect(mocks.sidebarShellSessionId).toBeNull();
+ expect(mocks.sidebarLightboxSessionId).toBeUndefined();
+ });
+
it('respects a plugin manifest that disables minimize in the detached window', async () => {
mocks.ghostMinimizeEnabled = false;