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): pin sidebar browser to the agent session (#3226)

Chris Zhang69d417d21ed8
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 18e3c6b3ee..c0f79cf7f9 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -535,6 +535,7 @@ import {
setIsDetachedForBackend,
} from './mcp-integrations/browser.js';
import { RsbWindowController } from './right-sidebar-window/controller.js';
+import { resolveRsbHostContextFromSession } from './right-sidebar-window/resolveHostContext.js';
import { createRightSidebarWindow } from './right-sidebar-window/window.js';
import { registerRsbWindowIpc } from './right-sidebar-window/ipc.js';
import { ResourceUsageWindowController } from './resource-usage-window/controller.js';
@@ -1835,6 +1836,7 @@ const rsbWindowController = new RsbWindowController({
tabHandoffChannel: MAKER_PUSH.RSB_WINDOW_TAB_HANDOFF,
isQuitting: () => isQuitting,
canCloseWindow: () => !hasActiveRsbNativePopupSurfaces(),
+ resolveHostContext: resolveRsbHostContextFromSession,
log: createLogger('right-sidebar-window-controller'),
});
@@ -2089,7 +2091,9 @@ registerTabOpResultHandler({
// an automation tab-op pop the sidebar window first when the user prefers
// detached mode but has the window closed.
setMainWindowAccessorForBackend(() => rsbWindowController.getHostWebContents());
-setEnsureHostForBackend(() => rsbWindowController.ensureOpenForAutomation());
+setEnsureHostForBackend((sessionId) =>
+ rsbWindowController.ensureOpenForAutomation({ sessionId }),
+);
setIsDetachedForBackend(() => readRsbWindowSettings().detached);
setBrowserSessionUploadRootResolver(async (sessionId) => {
try {
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-backend.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-backend.test.ts
index 605d570ec2..95397eb461 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-backend.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-backend.test.ts
@@ -2040,6 +2040,30 @@ describe('RsbWebviewBackend — detached-window ensure/wait for direct actions',
url: 'https://example.com',
} as never);
expect(ensureHost).toHaveBeenCalledTimes(1);
+ expect(ensureHost).toHaveBeenCalledWith('s1');
+ expect(res.ok).toBe(true);
+ });
+
+ it('direct action asks ensureHost for the request session, not the focused one', async () => {
+ const ensureHost = vi.fn(async () => undefined);
+ const wc = fakeWc();
+ const registry = fakeRegistry(
+ [{ sessionId: 's1', tabId: 't1', webContentsId: 101 }],
+ new Map([['t1', wc]]),
+ );
+ const backend = new RsbWebviewBackend({
+ registry,
+ getActiveSessionId: () => 's2',
+ bridge: { getHostWebContents: () => null, ensureHost, logger: logger() },
+ logger: logger(),
+ });
+ const res = await backend.call({
+ action: 'navigate',
+ targetId: 't1',
+ url: 'https://example.com',
+ __mcpSessionId: 's1',
+ } as never);
+ expect(ensureHost).toHaveBeenCalledWith('s1');
expect(res.ok).toBe(true);
});
@@ -2175,9 +2199,9 @@ describe('RsbWebviewBackend — detached-window ensure/wait for direct actions',
expect(res.message).toMatch(/t-ghost not in active session s1/);
});
- it('ensureHost rejection does not mask a resolvable tab', async () => {
+ it('ensureHost rejection fails closed even if a pooled tab still exists', async () => {
const ensureHost = vi.fn(async () => {
- throw new Error('ready timeout');
+ throw new Error('host context not ready');
});
const wc = fakeWc();
const registry = fakeRegistry(
@@ -2186,15 +2210,17 @@ describe('RsbWebviewBackend — detached-window ensure/wait for direct actions',
);
const backend = new RsbWebviewBackend({
registry,
- getActiveSessionId: () => 's1',
+ getActiveSessionId: () => 's2',
bridge: { getHostWebContents: () => null, ensureHost, logger: logger() },
logger: logger(),
});
const res = await backend.call({
action: 'screenshot',
targetId: 't1',
+ __mcpSessionId: 's1',
} as never);
- expect(res.ok).toBe(true);
+ expect(res.ok).toBe(false);
+ expect(res.message).toMatch(/host context not ready/);
});
it('embedded mode (isDetached false) → resolve miss fails fast, no polling', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
index f1d91ff02b..3a85877810 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
@@ -1226,18 +1226,27 @@ export class RsbWebviewBackend implements BrowserBackend {
tabId: string,
): Promise<{ ok: true; wc: WebContents } | { ok: false; result: BrowserControlResult }> {
const ensureHost = this.opts.bridge.ensureHost;
+ const requestSessionId = this.resolveSessionId(req);
if (ensureHost) {
try {
this.assertActive();
- await ensureHost();
+ await ensureHost(requestSessionId ?? undefined);
this.assertActive();
} catch (err) {
- // Window failed to come up (ready timeout etc.) — fall through, the
- // resolve below surfaces the concrete tab error to the agent.
this.opts.logger.warn('ensureHost failed before direct action', {
action: req.action,
err,
});
+ if (requestSessionId) {
+ return {
+ ok: false,
+ result: actionFailed(
+ req.action,
+ err instanceof Error ? err.message : String(err),
+ 'BROWSER_RUNTIME_UNAVAILABLE',
+ ),
+ };
+ }
}
}
let resolved = this.resolveTabInActiveSession(req, tabId);
diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.ts
index 0fcabf22b6..8b2e611c8b 100644
--- a/apps/desktop/src/main/mcp-integrations/browser.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser.ts
@@ -135,7 +135,7 @@ function createRsbBackend(): RsbWebviewBackend {
},
// detached 偏好开 + 侧边栏子窗口关着时,tab-op 前先把子窗口拉起来并等
// renderer ready 握手(否则没有任何 renderer 挂着 RSB store 可执行 op)。
- ensureHost: () => ensureHostForBackend(),
+ ensureHost: (sessionId) => ensureHostForBackend(sessionId),
// detached 偏好信号:直连动作解析 miss 时,只有 detached 模式才值得等
// 子窗口 renderer 重注册 tab;内嵌模式主窗常驻,miss 即真失效,快速失败。
isDetached: () => isDetachedForBackend(),
@@ -200,14 +200,14 @@ export function setMainWindowAccessorForBackend(
* controller's `ensureOpenForAutomation`. Default no-op keeps the embedded
* (non-detached) behavior: host is the always-alive main window.
*/
-let ensureHostForBackendImpl: () => Promise<void> = () => Promise.resolve();
+let ensureHostForBackendImpl: (sessionId?: string) => Promise<void> = () => Promise.resolve();
-function ensureHostForBackend(): Promise<void> {
- return ensureHostForBackendImpl();
+function ensureHostForBackend(sessionId?: string): Promise<void> {
+ return ensureHostForBackendImpl(sessionId);
}
/** Bootstrap hook, same pattern as `setMainWindowAccessorForBackend`. */
-export function setEnsureHostForBackend(impl: () => Promise<void>): void {
+export function setEnsureHostForBackend(impl: (sessionId?: string) => Promise<void>): void {
ensureHostForBackendImpl = impl;
}
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/controller.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/controller.test.ts
index 5585a0a1ce..d6ea0b6df2 100644
--- a/apps/desktop/src/main/right-sidebar-window/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/controller.test.ts
@@ -5,6 +5,7 @@
// - 崩溃恢复有界
// - getHostWebContents 三态(detached+open → 子窗;否则主窗)
// - setContext 缓存 + 仅窗口活跃时转发;routeCommand 原子裁决宿主
+// - 跨 session 呼起 adopt/pin,不被主窗焦点抢回
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BrowserWindow, WebContents } from 'electron';
@@ -99,7 +100,10 @@ function fakeWindow(id = 1): FakeWindow {
return win;
}
-function makeHarness(initial: Partial<RsbWindowSettings> = {}) {
+function makeHarness(
+ initial: Partial<RsbWindowSettings> = {},
+ extras: Pick<RsbWindowControllerDeps, 'resolveHostContext'> = {},
+) {
let settings: RsbWindowSettings = { detached: false, lastOpen: false, ...initial };
let quitting = false;
const windows: FakeWindow[] = [];
@@ -142,6 +146,7 @@ function makeHarness(initial: Partial<RsbWindowSettings> = {}) {
commandChannel: 'cmd-channel',
tabHandoffChannel: 'handoff-channel',
isQuitting: () => quitting,
+ resolveHostContext: extras.resolveHostContext,
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
};
const controller = new RsbWindowController(deps);
@@ -327,6 +332,21 @@ describe('open / close (hide-reuse)', () => {
expect(h.controller.getState().open).toBe(true);
});
+ it('native minimize releases a cross-session pin', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext(ctx);
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open({ userInitiated: false, sessionId: 's1' });
+ expect(h.controller.getContext()?.sessionId).toBe('s1');
+ win.emitWindowEvent('minimize');
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.open();
+ expect(h.controller.getContext()?.sessionId).toBe('s2');
+ });
+
it('native taskbar restore updates the main-window state mirror', () => {
const h = makeHarness({ detached: true });
h.controller.prewarm();
@@ -362,6 +382,30 @@ describe('open / close (hide-reuse)', () => {
expect(h.controller.getState().open).toBe(true);
});
+ it('hot reopen after a focus switch records the visible host', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext({ ...ctx, sessionId: 's1' });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+ expect(h.controller.getState().hostSessionId).toBe('s1');
+
+ h.controller.close();
+ expect(h.controller.getState().hostSessionId).toBe('s1');
+ expect(h.broadcasts.at(-1)).toMatchObject({
+ detached: true,
+ open: false,
+ hostSessionId: 's1',
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ expect(h.controller.getState().hostSessionId).toBe('s1');
+
+ h.controller.open();
+ expect(h.controller.getContext()?.sessionId).toBe('s2');
+ expect(h.controller.getState().hostSessionId).toBe('s2');
+ });
+
it('open repairs stale controller visibility using the native window state', () => {
const h = makeHarness({ detached: true });
h.controller.prewarm();
@@ -745,6 +789,18 @@ describe('ensureOpenForAutomation', () => {
await assertion;
});
+ it('ready timeout with a session pin lets a later context take the host', async () => {
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ const pending = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ const assertion = expect(pending).rejects.toThrow(/ready timeout/);
+ await vi.advanceTimersByTimeAsync(8000);
+ await assertion;
+ markReady(h.controller, h.windows[0]);
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ h.controller.open();
+ expect(h.controller.getContext()).toEqual({ ...ctx, sessionId: 's3' });
+ });
+
it('window closed before ready rejects', async () => {
const h = makeHarness({ detached: true });
const pending = h.controller.ensureOpenForAutomation();
@@ -752,6 +808,118 @@ describe('ensureOpenForAutomation', () => {
h.windows[0].emitClosed();
await assertion;
});
+
+ it('waits for the target session context before resolving a tab-op host', async () => {
+ const focused = { ...ctx, sessionId: 's2' };
+ const resolved = {
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/device/app',
+ deviceLinkDeviceId: 'dev-1',
+ };
+ let lookup: typeof resolved | null = null;
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: () => lookup,
+ });
+ h.controller.setContext(focused);
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ const pending = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ let settled = false;
+ void pending.then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ expect(h.controller.getContext()).toBeNull();
+ lookup = resolved;
+ await vi.advanceTimersByTimeAsync(400);
+ await expect(pending).resolves.toBeUndefined();
+ expect(h.controller.getContext()).toEqual(resolved);
+ });
+
+ it('resolves a host waiter when Main reports the pinned session', async () => {
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ const pending = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ let settled = false;
+ void pending.then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ h.controller.setContext({
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/from-main',
+ });
+ await expect(pending).resolves.toBeUndefined();
+ expect(h.controller.getContext()).toEqual({
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/from-main',
+ });
+ });
+
+ it('cancels an in-flight adopt after Main leaves chat', async () => {
+ const resolved = {
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/device/app',
+ deviceLinkDeviceId: 'dev-1',
+ };
+ let finishLookup!: (value: typeof resolved) => void;
+ const lookup = new Promise<typeof resolved>((resolve) => {
+ finishLookup = resolve;
+ });
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: () => lookup,
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ const pending = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ h.controller.setContext({ sessionId: null, workdir: null, remoteHostId: null, available: false });
+ finishLookup(resolved);
+ await expect(pending).rejects.toThrow(/cancelled/);
+ h.controller.open();
+ expect(h.controller.getContext()).toEqual({
+ sessionId: null,
+ workdir: null,
+ remoteHostId: null,
+ available: false,
+ });
+ });
+
+ it('does not show a pending window after Main leaves chat', async () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext(ctx);
+ const pending = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ expect(h.windows).toHaveLength(1);
+ h.controller.setContext({ sessionId: null, workdir: null, remoteHostId: null, available: false });
+ await expect(pending).rejects.toThrow(/cancelled/);
+ markReady(h.controller, h.windows[0]);
+ expect(h.windows[0].show).not.toHaveBeenCalled();
+ expect(h.windows[0].showInactive).not.toHaveBeenCalled();
+ expect(h.controller.getState().open).toBe(false);
+ });
+
+ it('fails closed when the target session context never arrives', async () => {
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ const pending = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ const assertion = expect(pending).rejects.toThrow(/host context not ready/);
+ await vi.advanceTimersByTimeAsync(8000);
+ await assertion;
+ expect(h.controller.getContext()).toBeNull();
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ h.controller.open();
+ expect(h.controller.getContext()).toEqual({ ...ctx, sessionId: 's3' });
+ });
});
// ═══════════════════════════════════════════════════════════════════════
@@ -912,10 +1080,512 @@ describe('setContext / routeCommand', () => {
});
});
- it('context mismatch returns stale-context', async () => {
+ it('context mismatch adopts the command session and routes', async () => {
+ const remote = {
+ sessionId: 's1',
+ workdir: '/remote/app',
+ remoteHostId: 'ssh-1',
+ deviceLinkDeviceId: 'device-1',
+ subagentsAvailable: true,
+ available: true,
+ };
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => (sessionId === 's1' ? remote : null),
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ const pending = h.controller.routeCommand(terminalRequest());
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ await expect(pending).resolves.toBe('routed');
+ expect(h.controller.getContext()).toEqual(remote);
+ expect(h.controller.getState().hostSessionId).toBe('s1');
+ expect(h.sends.at(-1)).toEqual({
+ channel: 'cmd-channel',
+ payload: { type: 'open-terminal', sessionId: 's1' },
+ });
+ h.controller.close();
+ expect(h.controller.getState().hostSessionId).toBe('s1');
+ });
+
+ it('does not forge a local host when resolve misses', async () => {
+ const focused = { ...ctx, sessionId: 's2' };
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ h.controller.setContext(focused);
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ h.sends.length = 0;
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('queued');
+ expect(h.controller.getContext()).toEqual(focused);
+ expect(h.sends.filter((entry) => entry.channel === 'ctx-channel')).toEqual([]);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
+ });
+
+ it('starts a bounded waiter when allowOpen arrives before any context', async () => {
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('queued');
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ expect(h.controller.getContext()?.sessionId).not.toBe('s2');
+ await vi.advanceTimersByTimeAsync(8000);
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ expect(h.controller.getContext()).toEqual({ ...ctx, sessionId: 's2' });
+ });
+
+ it('releases a visible-window pin when allowOpen host never resolves', async () => {
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('queued');
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ expect(h.controller.getContext()?.sessionId).toBe('s2');
+ await vi.advanceTimersByTimeAsync(8000);
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ expect(h.controller.getContext()).toEqual({ ...ctx, sessionId: 's3' });
+ });
+
+ it('opens a hidden window after a missed allowOpen lookup is adopted', async () => {
+ const focused = { ...ctx, sessionId: 's2' };
+ const resolved = {
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/device/app',
+ deviceLinkDeviceId: 'dev-1',
+ };
+ let lookup: typeof resolved | null = null;
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: () => lookup,
+ });
+ h.controller.setContext(focused);
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ h.controller.open();
+ h.controller.close();
+ h.sends.length = 0;
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('queued');
+ expect(h.controller.getContext()).toBeNull();
+ lookup = resolved;
+ await vi.advanceTimersByTimeAsync(400);
+ expect(h.controller.getContext()).toEqual(resolved);
+ expect(h.controller.getState().open).toBe(true);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([
+ { channel: 'cmd-channel', payload: { type: 'open-terminal', sessionId: 's1' } },
+ ]);
+ });
+
+ it('retries a missed host lookup and flushes the queued reveal', async () => {
+ const focused = { ...ctx, sessionId: 's2' };
+ const resolved = {
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/device/app',
+ deviceLinkDeviceId: 'dev-1',
+ };
+ let lookup: typeof resolved | null = null;
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: () => lookup,
+ });
+ h.controller.setContext(focused);
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ h.sends.length = 0;
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('queued');
+ lookup = resolved;
+ await vi.advanceTimersByTimeAsync(400);
+ expect(h.controller.getContext()).toEqual(resolved);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([
+ { channel: 'cmd-channel', payload: { type: 'open-terminal', sessionId: 's1' } },
+ ]);
+ });
+
+ it('does not flush a pinned session queue into a foreign host context', async () => {
+ const focused = { ...ctx, sessionId: 's2' };
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ h.controller.setContext(focused);
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ h.sends.length = 0;
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('queued');
+ h.controller.refreshContext(h.windows[0].webContents as unknown as WebContents);
+ expect(h.controller.getContext()).toEqual(focused);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
+ });
+
+ it('keeps retrying a missed lookup after the fast budget without another focus change', async () => {
+ const focused = { ...ctx, sessionId: 's2' };
+ const resolved = {
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/device/app',
+ deviceLinkDeviceId: 'dev-1',
+ };
+ let lookup: typeof resolved | null = null;
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: () => lookup,
+ });
+ h.controller.setContext(focused);
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('queued');
+ await vi.advanceTimersByTimeAsync(2_500);
+ expect(h.controller.getContext()).toEqual(focused);
+ lookup = resolved;
+ h.sends.length = 0;
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(h.controller.getContext()).toEqual(resolved);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([
+ { channel: 'cmd-channel', payload: { type: 'open-terminal', sessionId: 's1' } },
+ ]);
+ });
+
+ it('retries an exhausted lookup when the main window reports another context', async () => {
+ const focused = { ...ctx, sessionId: 's2' };
+ const resolved = {
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/device/app',
+ deviceLinkDeviceId: 'dev-1',
+ };
+ let lookup: typeof resolved | null = null;
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: () => lookup,
+ });
+ h.controller.setContext(focused);
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('queued');
+ await vi.advanceTimersByTimeAsync(2_500);
+ expect(h.controller.getContext()).toEqual(focused);
+ lookup = resolved;
+ h.sends.length = 0;
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ await vi.advanceTimersByTimeAsync(400);
+ expect(h.controller.getContext()).toEqual(resolved);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([
+ { channel: 'cmd-channel', payload: { type: 'open-terminal', sessionId: 's1' } },
+ ]);
+ });
+
+ it('reuses a previously reported host context instead of forging a local one', async () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext({
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/visited',
+ remoteHostId: 'ssh-visited',
+ deviceLinkDeviceId: 'dev-visited',
+ subagentsAvailable: true,
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ const pending = h.controller.routeCommand(terminalRequest());
+ markReady(h.controller, h.windows[0]);
+ await expect(pending).resolves.toBe('routed');
+ expect(h.controller.getContext()).toMatchObject({
+ sessionId: 's1',
+ workdir: '/visited',
+ remoteHostId: 'ssh-visited',
+ deviceLinkDeviceId: 'dev-visited',
+ subagentsAvailable: true,
+ });
+ });
+
+ it('does not switch a visible host for passive commands from another session', async () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ h.sends.length = 0;
+ const cmd = { type: 'close-orca-workers-tab' as const, sessionId: 's1' };
+ await expect(
+ h.controller.routeCommand({ command: cmd, allowOpen: false }),
+ ).resolves.toBe('queued');
+ expect(h.controller.getContext()).toEqual({ ...ctx, sessionId: 's2' });
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
+ expect(h.sends.filter((entry) => entry.channel === 'ctx-channel')).toEqual([]);
+ });
+
+ it('keeps another session queued when a later reveal adopts a different host', async () => {
+ const s3 = { ...ctx, sessionId: 's3' };
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => (sessionId === 's3' ? s3 : null),
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ const first = { type: 'open-web-browser' as const, sessionId: 's1', url: 'https://a.example' };
+ await expect(
+ h.controller.routeCommand({ command: first, allowOpen: false }),
+ ).resolves.toBe('queued');
+ const pending = h.controller.routeCommand(terminalRequest('s3'));
+ markReady(h.controller, h.windows[0]);
+ await expect(pending).resolves.toBe('routed');
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([
+ { channel: 'cmd-channel', payload: { type: 'open-terminal', sessionId: 's3' } },
+ ]);
+
+ h.sends.length = 0;
+ h.controller.setContext(s3);
+ h.controller.setContext({ ...ctx, sessionId: 's1' });
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([
+ { channel: 'cmd-channel', payload: first },
+ ]);
+ });
+
+ it('remembers an earlier resolve after a later pin takes the host', async () => {
+ const resolvedA = { ...ctx, sessionId: 's1', workdir: '/from-a' };
+ const resolvedB = { ...ctx, sessionId: 's3', workdir: '/from-b' };
+ let finishA!: (value: typeof resolvedA) => void;
+ const lookupA = new Promise<typeof resolvedA>((resolve) => {
+ finishA = resolve;
+ });
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => {
+ if (sessionId === 's1') return lookupA;
+ if (sessionId === 's3') return resolvedB;
+ return null;
+ },
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ const pendingA = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ await expect(h.controller.routeCommand(terminalRequest('s3'))).resolves.toBe('routed');
+ finishA(resolvedA);
+ await expect(pendingA).rejects.toThrow(/cancelled/);
+ h.controller.open({ userInitiated: false, sessionId: 's1' });
+ expect(h.controller.getContext()).toEqual(resolvedA);
+ });
+
+ it('does not let a replaced async route steal the host', async () => {
+ const resolvedA = { ...ctx, sessionId: 's1', workdir: '/from-a' };
+ const resolvedB = { ...ctx, sessionId: 's3', workdir: '/from-b' };
+ let finishA!: (value: typeof resolvedA) => void;
+ const lookupA = new Promise<typeof resolvedA>((resolve) => {
+ finishA = resolve;
+ });
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => {
+ if (sessionId === 's1') return lookupA;
+ if (sessionId === 's3') return resolvedB;
+ return null;
+ },
+ });
+ const pendingA = h.controller.routeCommand(terminalRequest('s1'));
+ const pendingB = h.controller.routeCommand(terminalRequest('s3'));
+ markReady(h.controller, h.windows[0]);
+ await expect(pendingB).resolves.toBe('routed');
+ finishA(resolvedA);
+ await expect(pendingA).resolves.toBe('queued');
+ expect(h.controller.getContext()).toEqual(resolvedB);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload)).toEqual([
+ { type: 'open-terminal', sessionId: 's3' },
+ ]);
+ });
+
+ it('flushes only the current host on attach, then the focused session later', async () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext(ctx);
+ const closeA = { type: 'close-orca-workers-tab' as const, sessionId: 's1' };
+ const closeB = { type: 'close-orca-workers-tab' as const, sessionId: 's2' };
+ await expect(
+ h.controller.routeCommand({ command: closeA, allowOpen: false }),
+ ).resolves.toBe('queued');
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ await expect(
+ h.controller.routeCommand({ command: closeB, allowOpen: false }),
+ ).resolves.toBe('queued');
+ h.controller.setDetached(false);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload)).toEqual([
+ closeB,
+ ]);
+ h.sends.length = 0;
+ h.controller.setContext(ctx);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload)).toEqual([
+ closeA,
+ ]);
+ });
+
+ it('flushes the main-window focus queue when merging back from a pinned host', async () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext(ctx);
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ h.controller.open({ userInitiated: false, sessionId: 's1' });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ const closeB = { type: 'close-orca-workers-tab' as const, sessionId: 's2' };
+ await expect(
+ h.controller.routeCommand({ command: closeB, allowOpen: false }),
+ ).resolves.toBe('queued');
+ h.controller.setDetached(false);
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload)).toEqual([
+ closeB,
+ ]);
+ });
+
+ it('lets a user raise of the current host cancel a foreign pin', async () => {
+ const resolvedA = { ...ctx, sessionId: 's1', workdir: '/from-a' };
+ let finishA!: (value: typeof resolvedA) => void;
+ const lookupA = new Promise<typeof resolvedA>((resolve) => {
+ finishA = resolve;
+ });
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => (sessionId === 's1' ? lookupA : null),
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ h.controller.open({ userInitiated: false, sessionId: 's1' });
+ h.controller.open({ userInitiated: true });
+ finishA(resolvedA);
+ await Promise.resolve();
+ expect(h.controller.getContext()?.sessionId).toBe('s2');
+ });
+
+ it('lets a command for the visible host replace a foreign async pin', async () => {
+ const resolvedA = { ...ctx, sessionId: 's1', workdir: '/from-a' };
+ let finishA!: (value: typeof resolvedA) => void;
+ const lookupA = new Promise<typeof resolvedA>((resolve) => {
+ finishA = resolve;
+ });
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => (sessionId === 's1' ? lookupA : null),
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ const pendingA = h.controller.routeCommand(terminalRequest('s1'));
+ await expect(h.controller.routeCommand(terminalRequest('s2'))).resolves.toBe('routed');
+ finishA(resolvedA);
+ await expect(pendingA).resolves.toBe('queued');
+ expect(h.controller.getContext()?.sessionId).toBe('s2');
+ });
+
+ it('lets ensureOpen for the visible host cancel a foreign pin', async () => {
+ const resolvedA = { ...ctx, sessionId: 's1', workdir: '/from-a' };
+ let finishA!: (value: typeof resolvedA) => void;
+ const lookupA = new Promise<typeof resolvedA>((resolve) => {
+ finishA = resolve;
+ });
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => (sessionId === 's1' ? lookupA : null),
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ const pendingA = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ await expect(h.controller.ensureOpenForAutomation({ sessionId: 's2' })).resolves.toBeUndefined();
+ finishA(resolvedA);
+ await expect(pendingA).rejects.toThrow(/cancelled/);
+ expect(h.controller.getContext()?.sessionId).toBe('s2');
+ });
+
+ it('submits adopted context before revealing a pending window', () => {
const h = makeHarness({ detached: true });
+ h.controller.setContext(ctx);
h.controller.setContext({ ...ctx, sessionId: 's2' });
- await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('stale-context');
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ h.controller.open();
+ h.controller.close();
+ h.sends.length = 0;
+ h.controller.open({ userInitiated: false, sessionId: 's1' });
+ const channels = h.sends.map((entry) => entry.channel);
+ expect(channels.indexOf('ctx-channel')).toBeGreaterThanOrEqual(0);
+ expect(channels.indexOf('ctx-channel')).toBeLessThan(
+ channels.indexOf('rsb-window:visibility-changed'),
+ );
+ expect(h.sends.find((entry) => entry.channel === 'ctx-channel')?.payload).toMatchObject({
+ sessionId: 's1',
+ });
+ });
+
+ it('cancels an earlier ready waiter when a later pin takes the host', async () => {
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => {
+ if (sessionId === 's1') return { ...ctx, sessionId: 's1' };
+ if (sessionId === 's3') return { ...ctx, sessionId: 's3' };
+ return null;
+ },
+ });
+ const pendingA = h.controller.ensureOpenForAutomation({ sessionId: 's1' });
+ const pendingB = h.controller.ensureOpenForAutomation({ sessionId: 's3' });
+ markReady(h.controller, h.windows[0]);
+ await expect(pendingA).rejects.toThrow(/cancelled/);
+ await expect(pendingB).resolves.toBeUndefined();
+ expect(h.controller.getContext()?.sessionId).toBe('s3');
+ });
+
+ it('does not reopen a left session after adopt returns', async () => {
+ const resolvedA = { ...ctx, sessionId: 's1', workdir: '/from-a' };
+ let finishA!: (value: typeof resolvedA) => void;
+ const lookupA = new Promise<typeof resolvedA>((resolve) => {
+ finishA = resolve;
+ });
+ const h = makeHarness({ detached: true }, {
+ resolveHostContext: (sessionId) => (sessionId === 's1' ? lookupA : null),
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ const pending = h.controller.routeCommand(terminalRequest());
+ h.controller.setContext({ sessionId: null, workdir: null, remoteHostId: null, available: false });
+ finishA(resolvedA);
+ await expect(pending).resolves.toBe('queued');
+ expect(h.controller.getContext()).toBeNull();
+ });
+
+ it('does not advertise a cancelled pending reveal as a user close', async () => {
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ h.controller.open({ userInitiated: false, sessionId: 's1' });
+ await vi.advanceTimersByTimeAsync(8000);
+ expect(h.broadcasts.at(-1)).toMatchObject({ open: false, userClose: false });
+ });
+
+ it('pinned host session ignores later focus switches until the user arrives', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext(ctx);
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.open({ userInitiated: false, sessionId: 's1' });
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ expect(h.controller.getContext()).toEqual(ctx);
+
+ h.controller.setContext({
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/adopted',
+ });
+ expect(h.controller.getContext()).toEqual({
+ ...ctx,
+ sessionId: 's1',
+ workdir: '/adopted',
+ });
+ });
+
+ it('releases a fire-and-forget open pin when the host never resolves', async () => {
+ const h = makeHarness({ detached: true }, { resolveHostContext: () => null });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ h.controller.prewarm();
+ markReady(h.controller, h.windows[0]);
+ h.controller.open({ userInitiated: false, sessionId: 's1' });
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ expect(h.controller.getContext()?.sessionId).not.toBe('s3');
+ await vi.advanceTimersByTimeAsync(8000);
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ h.controller.open();
+ expect(h.controller.getContext()).toEqual({ ...ctx, sessionId: 's3' });
+ });
+
+ it('does not pin an already-active host, so a later focus switch is applied', async () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext(ctx);
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('routed');
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ expect(h.controller.getContext()).toEqual({ ...ctx, sessionId: 's2' });
});
it('allowOpen=false + window hidden: stays queued through prewarm and flushes on open', async () => {
@@ -968,14 +1638,37 @@ describe('setContext / routeCommand', () => {
expect(h.sends.filter(e => e.channel === 'cmd-channel')).toEqual([]);
});
- it('context switch during ready wait: returns stale-context', async () => {
+ it('pins the opening session so a focus switch during ready wait cannot drop it', async () => {
const h = makeHarness({ detached: true });
h.controller.setContext(ctx);
const pending = h.controller.routeCommand(terminalRequest());
h.controller.setContext({ ...ctx, sessionId: 's2' });
const win = h.windows[0];
markReady(h.controller, win);
- await expect(pending).resolves.toBe('stale-context');
+ await expect(pending).resolves.toBe('routed');
+ expect(h.controller.getContext()).toEqual(ctx);
+ expect(h.sends.at(-1)).toEqual({
+ channel: 'cmd-channel',
+ payload: { type: 'open-terminal', sessionId: 's1' },
+ });
+ });
+
+ it('keeps another session queued across an ordinary focus switch', async () => {
+ const h = makeHarness({ detached: true });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ const first = { type: 'open-web-browser' as const, sessionId: 's1', url: 'https://a.example' };
+ await expect(
+ h.controller.routeCommand({ command: first, allowOpen: false }),
+ ).resolves.toBe('queued');
+ h.controller.setContext({ ...ctx, sessionId: 's3' });
+ await expect(h.controller.routeCommand(terminalRequest('s1'))).resolves.toBe('queued');
+ h.controller.open();
+ markReady(h.controller, h.windows[0]);
+ h.controller.setContext({ ...ctx, sessionId: 's1' });
+ expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([
+ { channel: 'cmd-channel', payload: first },
+ { channel: 'cmd-channel', payload: { type: 'open-terminal', sessionId: 's1' } },
+ ]);
});
});
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
index 2a77558d13..9d70c707ea 100644
--- a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
@@ -103,6 +103,38 @@ describe('right-sidebar-window IPC', () => {
});
});
+ it('drops oversized setContext strings before they reach the controller', () => {
+ const controller = makeController();
+ const { mainWebContents } = registerController(controller);
+ const setContextCall = (ipcMain.on as ReturnType<typeof vi.fn>).mock.calls.find(
+ ([channel]) => channel === MAKER_SEND.RSB_WINDOW_SET_CONTEXT,
+ );
+ const setContext = setContextCall?.[1] as
+ | ((event: { sender: unknown }, payload: unknown) => void)
+ | undefined;
+ if (!setContext) throw new Error('RSB_WINDOW_SET_CONTEXT handler not registered');
+
+ setContext(
+ { sender: mainWebContents },
+ {
+ sessionId: 'x'.repeat(129),
+ workdir: '/workspace',
+ remoteHostId: null,
+ available: true,
+ },
+ );
+ setContext(
+ { sender: mainWebContents },
+ {
+ sessionId: 's1',
+ workdir: `/${'a'.repeat(4096)}`,
+ remoteHostId: null,
+ available: true,
+ },
+ );
+ expect(controller.setContext).not.toHaveBeenCalled();
+ });
+
it('preserves unknown Subagents eligibility so cold Pi restore cannot auto-collapse', () => {
const controller = makeController();
const { mainWebContents } = registerController(controller);
@@ -392,7 +424,13 @@ describe('right-sidebar-window IPC', () => {
{ sender: { id: 2 } },
{ command: { type: 'open-terminal', sessionId: '' }, allowOpen: true },
),
- ).rejects.toThrow(/command.sessionId required/);
+ ).rejects.toThrow(/command.sessionId must be a 1–128 character string/);
+ await expect(
+ handler(
+ { sender: { id: 2 } },
+ { command: { type: 'open-terminal', sessionId: 'x'.repeat(129) }, allowOpen: true },
+ ),
+ ).rejects.toThrow(/1–128/);
});
it('forwards userInitiated when present and omits it when absent', async () => {
@@ -476,22 +514,34 @@ describe('right-sidebar-window IPC', () => {
it('open payload:缺省/空 = 用户手势;显式 false 透传;野值拒绝', async () => {
const controller = makeController();
- registerController(controller);
+ const { mainWebContents } = registerController(controller);
const handlers = (
ipcMain as unknown as { __handlers: Map<string, (e: unknown, p: unknown) => unknown> }
).__handlers;
const open = handlers.get(MAKER_INVOKE.RSB_WINDOW_OPEN);
if (!open) throw new Error('RSB_WINDOW_OPEN handler not registered');
+ const mainEvent = { sender: mainWebContents };
- open({}, undefined);
- open({}, {});
- open({}, { userInitiated: false });
+ open(mainEvent, undefined);
+ open(mainEvent, {});
+ open(mainEvent, { userInitiated: false });
+ open(mainEvent, { userInitiated: false, sessionId: 'agent-session' });
expect(controller.open).toHaveBeenNthCalledWith(1, { userInitiated: true });
expect(controller.open).toHaveBeenNthCalledWith(2, { userInitiated: true });
expect(controller.open).toHaveBeenNthCalledWith(3, { userInitiated: false });
+ expect(controller.open).toHaveBeenNthCalledWith(4, {
+ userInitiated: false,
+ sessionId: 'agent-session',
+ });
+
+ expect(() => open(mainEvent, { userInitiated: 1 })).toThrow(/options.userInitiated/);
+ expect(() => open(mainEvent, { sessionId: '' })).toThrow(/options.sessionId/);
+ expect(() => open(mainEvent, { sessionId: 'x'.repeat(129) })).toThrow(/1–128/);
- expect(() => open({}, { userInitiated: 1 })).toThrow(/options.userInitiated/);
+ (controller.open as ReturnType<typeof vi.fn>).mockClear();
+ open({ sender: { id: 99 } }, { userInitiated: false, sessionId: 'other-session' });
+ expect(controller.open).not.toHaveBeenCalled();
});
it('accepts a memory-only tab handoff only from the detached sidebar sender', () => {
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/resolveHostContext.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/resolveHostContext.test.ts
new file mode 100644
index 0000000000..4679a95e93
--- /dev/null
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/resolveHostContext.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ contextFromDeviceLinkMirror,
+ contextFromLocalSessionRow,
+} from '../resolveHostContext.js';
+
+describe('resolveHostContext mappers', () => {
+ it('marks a local session row as confirmed non-device-link', () => {
+ expect(
+ contextFromLocalSessionRow({
+ id: 'local-1',
+ workingDir: '/repo',
+ remoteHostId: null,
+ agentKind: 'pi',
+ }),
+ ).toEqual({
+ sessionId: 'local-1',
+ workdir: '/repo',
+ remoteHostId: null,
+ deviceLinkDeviceId: null,
+ available: true,
+ subagentsAvailable: true,
+ });
+ });
+
+ it('does not enable Subagents for an SSH-hosted Pi session', () => {
+ expect(
+ contextFromLocalSessionRow({
+ id: 'ssh-1',
+ workingDir: '/remote/repo',
+ remoteHostId: 'host-1',
+ agentKind: 'pi',
+ }).subagentsAvailable,
+ ).toBe(false);
+ });
+
+ it('fills device-link context from the main mirror list', () => {
+ expect(
+ contextFromDeviceLinkMirror('device-9', {
+ id: 'remote-1',
+ workingDir: '/remote/app',
+ agentKind: 'pi',
+ }),
+ ).toEqual({
+ sessionId: 'remote-1',
+ workdir: '/remote/app',
+ remoteHostId: null,
+ deviceLinkDeviceId: 'device-9',
+ available: true,
+ subagentsAvailable: false,
+ });
+ });
+
+ it('does not advertise Subagents for a mirrored Pi session', () => {
+ expect(
+ contextFromDeviceLinkMirror('device-9', {
+ id: 'remote-ssh',
+ workingDir: '/remote/app',
+ agentKind: 'pi',
+ })?.subagentsAvailable,
+ ).toBe(false);
+ });
+
+ it('leaves a truncated device-link workdir unresolved', () => {
+ expect(
+ contextFromDeviceLinkMirror('device-9', {
+ id: 'remote-1',
+ workingDir: `/${'a'.repeat(239)}`,
+ agentKind: 'pi',
+ })?.workdir,
+ ).toBeNull();
+ expect(
+ contextFromDeviceLinkMirror('device-9', {
+ id: 'remote-1',
+ worktreePath: `/${'b'.repeat(239)}`,
+ agentKind: 'codex',
+ })?.workdir,
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/right-sidebar-window/controller.ts b/apps/desktop/src/main/right-sidebar-window/controller.ts
index a99b9dae7d..d523d54e89 100644
--- a/apps/desktop/src/main/right-sidebar-window/controller.ts
+++ b/apps/desktop/src/main/right-sidebar-window/controller.ts
@@ -55,9 +55,21 @@ export interface RsbWindowControllerDeps {
createWindow: () => BrowserWindow;
getMainWindow: () => BrowserWindow | null;
/** 状态变化广播(所有窗口)。bootstrap 注入 getAllWindows 遍历实现。 */
- broadcastState: (state: { detached: boolean; open: boolean }) => void;
+ broadcastState: (state: {
+ detached: boolean;
+ open: boolean;
+ hostSessionId?: string;
+ userClose?: boolean;
+ }) => void;
/** 向裁决后的 renderer host 推送 context / command;窗口有效性由 controller 保证。 */
sendToWindow: (win: BrowserWindow, channel: string, payload: unknown) => void;
+ /**
+ * 主窗没上报过该 session 时,从权威会话来源补齐 workdir / 远程归属。
+ * 不要在 controller 里把远程会话捏成本机空上下文。
+ */
+ resolveHostContext?: (
+ sessionId: string,
+ ) => RsbWindowContext | null | Promise<RsbWindowContext | null>;
/**
* 缓存窗口每次重新显示前的 Host 同步钩子。调用时窗口仍标记为 hidden,
* capability 同步必须以该精确 WebContents 为目标;原生 show 前完成。
@@ -82,6 +94,10 @@ const DEFAULT_PREWARM_TIMEOUT_MS = 10_000;
const DEFAULT_RECOVERY_STABILITY_MS = 30_000;
const MAX_AUTOMATIC_RECOVERY_ATTEMPTS = 1;
const MAX_DEFERRED_SESSIONS = 8;
+const MAX_KNOWN_CONTEXTS = 32;
+const MAX_ADOPT_RESOLVE_RETRIES = 5;
+const ADOPT_RESOLVE_RETRY_MS = 400;
+const ADOPT_RESOLVE_SLOW_RETRY_MS = 2_000;
/**
* 单会话 deferred 队列上限。正常路径远达不到(passive 命令种类有限且有合并
* 规则);达到时丢最旧一条并记 warn —— 不能静默,登记类命令被丢意味着这次
@@ -124,12 +140,32 @@ export class RsbWindowController {
resolve: () => void;
reject: (err: Error) => void;
timeout: NodeJS.Timeout;
+ sessionId?: string;
+ }> = [];
+ private hostWaiters: Array<{
+ sessionId: string;
+ resolve: () => void;
+ reject: (err: Error) => void;
+ timeout: NodeJS.Timeout;
}> = [];
private openTimeout: NodeJS.Timeout | null = null;
private prewarmTimeout: NodeJS.Timeout | null = null;
private recoveryStabilityTimeout: NodeJS.Timeout | null = null;
private automaticRecoveryAttempts = 0;
private lastContext: RsbWindowContext | null = null;
+ /** 主窗最近一次上报的焦点上下文;pin 期间 lastContext 可能仍是侧栏宿主。 */
+ private lastReportedContext: RsbWindowContext | null = null;
+ /**
+ * Agent / 跨 session 呼起把子窗口钉在发起方 session 上。
+ * 钉住期间主窗 setContext 的焦点切换不能把展示抢回台前 session;
+ * 用户切到被 pin 的 session、离开聊天视图或关掉子窗口时解除。
+ */
+ private pinnedSessionId: string | null = null;
+ private lastHostSessionId: string | null = null;
+ private adoptRetryTimer: NodeJS.Timeout | null = null;
+ private adoptRetryAttempts = 0;
+ /** 主窗曾上报、或权威来源解析过的完整宿主上下文,按 session 复用。 */
+ private knownContexts = new Map<string, RsbWindowContext>();
/** 冷启动分离窗尚未 presentation-ready 时暂存主窗交来的内存态 tab。 */
private pendingDetachedTabHandoff: RsbWindowTabHandoff | null = null;
/**
@@ -154,7 +190,12 @@ export class RsbWindowController {
getState(): RsbWindowState {
const s = this.deps.settings.read();
// pendingOpen:窗口已创建但等待 presentation-ready,外部视为 open。
- return { detached: s.detached, lastOpen: s.lastOpen, open: this.isOpen() || this.pendingOpen };
+ return {
+ detached: s.detached,
+ lastOpen: s.lastOpen,
+ open: this.isOpen() || this.pendingOpen,
+ ...(this.lastHostSessionId ? { hostSessionId: this.lastHostSessionId } : {}),
+ };
}
/** 后台预热:主窗口首帧后创建隐藏窗口并挂载 renderer。不改变用户焦点。 */
@@ -177,9 +218,25 @@ export class RsbWindowController {
* 幂等打开:热窗口(presentationReady)立即显示;冷窗口等待首份业务内容,
* 超时按 Loading 壳兜底。
*/
- open(opts: { userInitiated?: boolean } = {}): void {
+ open(opts: { userInitiated?: boolean; sessionId?: string } = {}): void {
if (this.disposed) return;
const userInitiated = opts.userInitiated !== false;
+ const revealSessionId = typeof opts.sessionId === 'string' ? opts.sessionId.trim() : '';
+ if (userInitiated) {
+ const currentHost = this.lastContext?.available ? this.lastContext.sessionId : '';
+ const targetHost = revealSessionId || currentHost;
+ if (this.pinnedSessionId && targetHost && this.pinnedSessionId !== targetHost) {
+ this.replacePinnedSession(null);
+ }
+ }
+ if (
+ revealSessionId &&
+ (userInitiated === false || this.lastContext?.sessionId !== revealSessionId)
+ ) {
+ void this.waitForHostSession(revealSessionId).catch(() => {
+ // waiter 超时或离开聊天会放掉 pin;open 是 fire-and-forget。
+ });
+ }
this.automaticRecoveryAttempts = 0;
this.clearRecoveryStabilityTimeout();
@@ -293,6 +350,9 @@ export class RsbWindowController {
// command 可以安全交付的统一边界。不能在 showWindow 后提前返回,否则
// 点击路径会永久留下此前排队的 passive intent。
this.flushDeferredCommandsToDetachedHost();
+ if (this.pinnedSessionId && this.lastContext?.sessionId !== this.pinnedSessionId) {
+ this.pokeAdoptRetry(this.pinnedSessionId);
+ }
return true;
}
@@ -325,6 +385,7 @@ export class RsbWindowController {
dispose(): void {
if (this.disposed) return;
this.disposed = true;
+ this.knownContexts.clear();
this.destroyWindow();
}
@@ -333,35 +394,57 @@ export class RsbWindowController {
/**
* agent tab-op(浏览器自动化)前置:detached 且窗口未就绪时先开窗并等 ready 握手。
*/
- ensureOpenForAutomation(opts: { userInitiated?: boolean } = {}): Promise<void> {
- if (!this.deps.settings.read().detached) return Promise.resolve();
- this.open({ userInitiated: opts.userInitiated === true });
- if (this.presentationReady) return Promise.resolve();
- return new Promise<void>((resolve, reject) => {
- const timeout = setTimeout(() => {
- const idx = this.readyWaiters.findIndex((w) => w.timeout === timeout);
- if (idx >= 0) this.readyWaiters.splice(idx, 1);
- reject(new Error(`right-sidebar window ready timeout after ${READY_TIMEOUT_MS}ms`));
- }, READY_TIMEOUT_MS);
- this.readyWaiters.push({ resolve, reject, timeout });
+ async ensureOpenForAutomation(opts: { userInitiated?: boolean; sessionId?: string } = {}): Promise<void> {
+ if (!this.deps.settings.read().detached) return;
+ this.open({
+ userInitiated: opts.userInitiated === true,
+ ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),
});
+ if (!this.presentationReady) {
+ await new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ const idx = this.readyWaiters.findIndex((w) => w.timeout === timeout);
+ if (idx >= 0) this.readyWaiters.splice(idx, 1);
+ reject(new Error(`right-sidebar window ready timeout after ${READY_TIMEOUT_MS}ms`));
+ if (opts.sessionId) this.releaseUnresolvedHostPin(opts.sessionId);
+ }, READY_TIMEOUT_MS);
+ this.readyWaiters.push({ resolve, reject, timeout, sessionId: opts.sessionId });
+ });
+ }
+ if (opts.sessionId) await this.waitForHostSession(opts.sessionId);
}
/** 主窗上报渲染上下文:缓存 + 窗口活跃就转发。 */
setContext(ctx: RsbWindowContext): void {
- const previousSessionId = this.lastContext?.sessionId ?? null;
- this.lastContext = ctx;
- if (!ctx.available || !ctx.sessionId) {
- this.deferredCommands.clear();
- } else if (previousSessionId !== ctx.sessionId) {
- for (const sessionId of this.deferredCommands.keys()) {
- if (sessionId !== ctx.sessionId) this.deferredCommands.delete(sessionId);
+ this.rememberContext(ctx);
+ this.lastReportedContext = ctx;
+ if (this.pinnedSessionId) {
+ if (ctx.available && ctx.sessionId === this.pinnedSessionId) {
+ this.clearPinnedSession();
+ } else if (ctx.available && ctx.sessionId) {
+ // 钉住中: 主窗切到别的焦点 session 不能把子窗口抢走。
+ this.pokeAdoptRetry(this.pinnedSessionId);
+ return;
+ } else {
+ const pinned = this.pinnedSessionId;
+ this.clearPinnedSession();
+ if (pinned) this.settleHostWaiters(pinned, false);
}
}
+ if (!ctx.available) this.cancelPendingOpen();
+ this.lastContext = ctx;
+ this.rememberLastHostSession(ctx, { onlyIfShowing: true });
+ this.revealPendingOpenIfHostReady();
if (this.visible && this.winRef && !this.winRef.isDestroyed()) {
this.deps.sendToWindow(this.winRef, this.deps.contextChannel, ctx);
}
this.flushDeferredCommandsToDetachedHost();
+ if (ctx.available && ctx.sessionId) {
+ this.settleHostWaiters(ctx.sessionId, true);
+ if (!this.deps.settings.read().detached) {
+ this.flushDeferredCommandsToAttachedHost(ctx.sessionId);
+ }
+ }
}
getContext(): RsbWindowContext | null {
@@ -377,22 +460,59 @@ export class RsbWindowController {
const { command, allowOpen } = request;
const userInitiated = request.userInitiated !== false;
if (!this.deps.settings.read().detached) return 'attached';
- if (!this.canDispatchCommand(command)) return 'stale-context';
-
- const windowAlive = this.winRef && !this.winRef.isDestroyed();
- if (!allowOpen && (!windowAlive || !this.presentationReady || !this.visible)) {
+ const hostSessionId = commandHostSessionId(command);
+ if (!allowOpen) {
+ const windowReady =
+ this.winRef &&
+ !this.winRef.isDestroyed() &&
+ this.presentationReady &&
+ this.visible;
+ if (windowReady && this.canDispatchCommand(command)) {
+ this.deps.sendToWindow(this.winRef!, this.deps.commandChannel, command);
+ return 'routed';
+ }
this.enqueueDeferredCommand(command);
return 'queued';
}
+ const adopted = this.adoptHostSession(hostSessionId);
+ if (adopted) await adopted;
+ if (!this.stillOwnsHost(hostSessionId)) {
+ this.enqueueDeferredCommand(command);
+ return 'queued';
+ }
+ if (!this.canDispatchCommand(command)) {
+ this.enqueueDeferredCommand(command);
+ if (allowOpen && hostSessionId && this.pinnedSessionId === hostSessionId) {
+ if (!this.isOpen() || !this.presentationReady) {
+ this.open({
+ userInitiated,
+ sessionId: hostSessionId,
+ });
+ } else {
+ void this.waitForHostSession(hostSessionId).catch(() => {
+ // 窗口已可见时不会再走 open();同样用有界 waiter 释放失败 pin。
+ });
+ }
+ }
+ return 'queued';
+ }
if (allowOpen && (!this.isOpen() || !this.presentationReady)) {
+ const holdPin =
+ Boolean(hostSessionId) &&
+ this.lastContext?.available &&
+ this.lastContext.sessionId === hostSessionId &&
+ this.pinnedSessionId !== hostSessionId;
+ if (holdPin) this.pinnedSessionId = hostSessionId;
try {
await this.ensureOpenForAutomation({ userInitiated });
} catch (err) {
+ if (holdPin && this.pinnedSessionId === hostSessionId) this.clearPinnedSession();
if (!this.deps.settings.read().detached) return 'attached';
if (!this.canDispatchCommand(command)) return 'stale-context';
throw err;
}
+ if (holdPin && this.pinnedSessionId === hostSessionId) this.clearPinnedSession();
}
if (!this.deps.settings.read().detached) return 'attached';
@@ -520,6 +640,12 @@ export class RsbWindowController {
}
private showWindow(win: BrowserWindow, shouldFocus: boolean): void {
+ if (this.pinnedSessionId && this.lastContext?.sessionId !== this.pinnedSessionId) {
+ this.pendingOpen = true;
+ this.pendingOpenShouldFocus = shouldFocus;
+ this.broadcast();
+ return;
+ }
this.clearOpenTimeout();
this.clearPrewarmTimeout();
this.pendingOpen = false;
@@ -541,6 +667,7 @@ export class RsbWindowController {
// 隐藏复用期间的 passive 命令不能在用户看不见时改动子窗口 store;
// 窗口重新显示后按原顺序统一交付。
this.flushDeferredCommandsToDetachedHost();
+ if (this.lastContext) this.rememberLastHostSession(this.lastContext);
this.broadcast();
}
@@ -558,6 +685,7 @@ export class RsbWindowController {
// 窗口可能在 isVisible 检查与 send 之间被系统销毁
}
this.deps.settings.writePatch({ lastOpen: false });
+ this.clearPinnedSession();
this.broadcast();
this.deps.log.info('right-sidebar window hidden');
}
@@ -572,9 +700,11 @@ export class RsbWindowController {
this.deps.onWindowWillShow?.(win);
this.visible = true;
this.pendingOpen = false;
+ if (this.lastContext) this.rememberLastHostSession(this.lastContext);
} else {
this.visible = false;
this.deps.onWindowHidden?.(win);
+ this.clearPinnedSession();
}
try {
this.deps.sendToWindow(win, RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible });
@@ -601,12 +731,14 @@ export class RsbWindowController {
this.pendingOpen = false;
this.pendingOpenShouldFocus = true;
this.destroyingWindow = false;
+ this.clearPinnedSession();
const waiters = this.readyWaiters.splice(0);
for (const w of waiters) {
clearTimeout(w.timeout);
w.reject(new Error('right-sidebar window closed before ready'));
}
+ this.settleHostWaiters(null, false);
if (this.deps.isQuitting()) return;
this.deps.settings.writePatch({ lastOpen: false });
@@ -789,6 +921,222 @@ export class RsbWindowController {
// ── 命令路由辅助 ─────────────────────────────────────────────────
+ private adoptHostSession(sessionId: string): void | Promise<void> {
+ if (!sessionId) return;
+ if (this.lastContext?.available && this.lastContext.sessionId === sessionId) {
+ // 已经在目标宿主上。再钉一次会挡住之后的 setContext。
+ // 若 pin 还钉着别人,当前宿主的新请求要先把它拆掉。
+ if (this.pinnedSessionId && this.pinnedSessionId !== sessionId) {
+ this.replacePinnedSession(null);
+ } else if (this.pinnedSessionId === sessionId) {
+ this.clearPinnedSession();
+ }
+ return;
+ }
+ if (this.pinnedSessionId !== sessionId) this.replacePinnedSession(sessionId);
+ const cached = this.knownContexts.get(sessionId);
+ if (cached) {
+ this.applyAdoptedContext(cached);
+ return;
+ }
+ const pending = this.deps.resolveHostContext?.(sessionId);
+ if (pending && typeof (pending as Promise<RsbWindowContext | null>).then === 'function') {
+ return Promise.resolve(pending).then((resolved) => {
+ if (this.disposed) return;
+ if (resolved) this.rememberContext(resolved);
+ if (this.pinnedSessionId !== sessionId) return;
+ this.finishAdoptHostSession(sessionId, resolved);
+ });
+ }
+ this.finishAdoptHostSession(sessionId, (pending as RsbWindowContext | null | undefined) ?? null);
+ }
+
+ private finishAdoptHostSession(sessionId: string, resolved: RsbWindowContext | null): void {
+ if (!resolved) {
+ this.scheduleAdoptRetry(sessionId);
+ return;
+ }
+ this.resetAdoptRetry();
+ this.rememberContext(resolved);
+ this.applyAdoptedContext(resolved);
+ }
+
+ private pokeAdoptRetry(sessionId: string): void {
+ if (this.disposed || this.pinnedSessionId !== sessionId) return;
+ if (this.lastContext?.available && this.lastContext.sessionId === sessionId) return;
+ if (this.adoptRetryAttempts >= MAX_ADOPT_RESOLVE_RETRIES) {
+ this.adoptRetryAttempts = MAX_ADOPT_RESOLVE_RETRIES - 1;
+ }
+ this.scheduleAdoptRetry(sessionId);
+ }
+
+ private scheduleAdoptRetry(sessionId: string): void {
+ if (this.disposed || this.pinnedSessionId !== sessionId) return;
+ this.clearAdoptRetryTimer();
+ this.adoptRetryAttempts += 1;
+ const delay =
+ this.adoptRetryAttempts > MAX_ADOPT_RESOLVE_RETRIES
+ ? ADOPT_RESOLVE_SLOW_RETRY_MS
+ : ADOPT_RESOLVE_RETRY_MS;
+ this.adoptRetryTimer = setTimeout(() => {
+ this.adoptRetryTimer = null;
+ if (this.disposed || this.pinnedSessionId !== sessionId) return;
+ void this.adoptHostSession(sessionId);
+ }, delay);
+ }
+
+ private clearAdoptRetryTimer(): void {
+ if (!this.adoptRetryTimer) return;
+ clearTimeout(this.adoptRetryTimer);
+ this.adoptRetryTimer = null;
+ }
+
+ private resetAdoptRetry(): void {
+ this.clearAdoptRetryTimer();
+ this.adoptRetryAttempts = 0;
+ }
+
+ private rememberContext(ctx: RsbWindowContext): void {
+ if (!ctx.available || !ctx.sessionId) return;
+ if (this.knownContexts.size >= MAX_KNOWN_CONTEXTS && !this.knownContexts.has(ctx.sessionId)) {
+ const oldest = this.knownContexts.keys().next().value as string | undefined;
+ if (oldest) this.knownContexts.delete(oldest);
+ }
+ this.knownContexts.set(ctx.sessionId, ctx);
+ }
+
+ private applyAdoptedContext(next: RsbWindowContext): void {
+ this.lastContext = next;
+ this.rememberLastHostSession(next);
+ this.submitHostContext();
+ this.revealPendingOpenIfHostReady();
+ this.flushDeferredCommandsToDetachedHost();
+ this.settleHostWaiters(next.sessionId, true);
+ }
+
+ private submitHostContext(): void {
+ if (!this.lastContext || !this.winRef || this.winRef.isDestroyed()) return;
+ if (!this.presentationReady) return;
+ this.deps.sendToWindow(this.winRef, this.deps.contextChannel, this.lastContext);
+ }
+
+ private revealPendingOpenIfHostReady(): void {
+ if (
+ !this.pendingOpen ||
+ !this.winRef ||
+ this.winRef.isDestroyed() ||
+ !this.presentationReady
+ ) {
+ return;
+ }
+ if (this.pinnedSessionId && this.lastContext?.sessionId !== this.pinnedSessionId) return;
+ this.showWindow(this.winRef, this.pendingOpenShouldFocus);
+ }
+
+ private waitForHostSession(sessionId: string): Promise<void> {
+ if (this.lastContext?.available && this.lastContext.sessionId === sessionId) {
+ this.adoptHostSession(sessionId);
+ return Promise.resolve();
+ }
+ const adopted = this.adoptHostSession(sessionId);
+ if (adopted) {
+ return adopted.then(() => {
+ if (this.lastContext?.available && this.lastContext.sessionId === sessionId) return;
+ if (this.pinnedSessionId !== sessionId) {
+ return Promise.reject(new Error('right-sidebar host context wait cancelled'));
+ }
+ return this.queueHostWaiter(sessionId);
+ });
+ }
+ if (this.lastContext?.available && this.lastContext.sessionId === sessionId) {
+ return Promise.resolve();
+ }
+ return this.queueHostWaiter(sessionId);
+ }
+
+ private queueHostWaiter(sessionId: string): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ const idx = this.hostWaiters.findIndex((w) => w.timeout === timeout);
+ if (idx >= 0) this.hostWaiters.splice(idx, 1);
+ reject(new Error(`right-sidebar host context not ready for ${sessionId}`));
+ this.releaseUnresolvedHostPin(sessionId);
+ }, READY_TIMEOUT_MS);
+ this.hostWaiters.push({ sessionId, resolve, reject, timeout });
+ });
+ }
+
+ private releaseUnresolvedHostPin(sessionId: string): void {
+ if (this.pinnedSessionId !== sessionId) return;
+ if (this.hostWaiters.some((waiter) => waiter.sessionId === sessionId)) return;
+ if (this.readyWaiters.some((waiter) => waiter.sessionId === sessionId)) return;
+ this.clearPinnedSession();
+ this.cancelPendingOpen();
+ }
+
+ private settleHostWaiters(sessionId: string | null, ok: boolean): void {
+ if (this.hostWaiters.length === 0) return;
+ const remaining: typeof this.hostWaiters = [];
+ for (const waiter of this.hostWaiters) {
+ if (sessionId && waiter.sessionId !== sessionId) {
+ remaining.push(waiter);
+ continue;
+ }
+ clearTimeout(waiter.timeout);
+ if (ok) waiter.resolve();
+ else waiter.reject(new Error('right-sidebar host context wait cancelled'));
+ }
+ this.hostWaiters = remaining;
+ }
+
+ private rememberLastHostSession(
+ ctx: RsbWindowContext,
+ opts: { onlyIfShowing?: boolean } = {},
+ ): void {
+ if (opts.onlyIfShowing && !this.visible && !this.pendingOpen) return;
+ if (!ctx.available || !ctx.sessionId) return;
+ if (this.lastHostSessionId === ctx.sessionId) return;
+ this.lastHostSessionId = ctx.sessionId;
+ this.broadcast();
+ }
+
+ private clearPinnedSession(): void {
+ this.resetAdoptRetry();
+ this.pinnedSessionId = null;
+ }
+
+ private replacePinnedSession(next: string | null): void {
+ const previous = this.pinnedSessionId;
+ if (previous && previous !== next) {
+ this.settleHostWaiters(previous, false);
+ this.rejectReadyWaiters(previous);
+ }
+ this.resetAdoptRetry();
+ this.pinnedSessionId = next;
+ }
+
+ private rejectReadyWaiters(sessionId?: string): void {
+ if (this.readyWaiters.length === 0) return;
+ const remaining: typeof this.readyWaiters = [];
+ for (const waiter of this.readyWaiters) {
+ if (sessionId && waiter.sessionId !== sessionId) {
+ remaining.push(waiter);
+ continue;
+ }
+ clearTimeout(waiter.timeout);
+ waiter.reject(new Error('right-sidebar host context wait cancelled'));
+ }
+ this.readyWaiters = remaining;
+ }
+
+ private stillOwnsHost(sessionId: string): boolean {
+ if (!sessionId) return false;
+ return (
+ this.pinnedSessionId === sessionId ||
+ Boolean(this.lastContext?.available && this.lastContext.sessionId === sessionId)
+ );
+ }
+
private canDispatchCommand(cmd: RsbWindowCommand): boolean {
return Boolean(
this.lastContext?.available &&
@@ -855,8 +1203,8 @@ export class RsbWindowController {
private flushDeferredCommands(
isHostAlive: () => boolean,
send: (command: RsbWindowCommand) => void,
+ sessionId = this.lastContext?.available ? this.lastContext.sessionId : null,
): void {
- const sessionId = this.lastContext?.available ? this.lastContext.sessionId : null;
if (!sessionId) return;
const queue = this.deferredCommands.get(sessionId);
if (!queue || queue.length === 0) return;
@@ -897,19 +1245,37 @@ export class RsbWindowController {
);
}
- private flushDeferredCommandsToAttachedHost(): void {
+ private flushDeferredCommandsToAttachedHost(sessionId?: string | null): void {
if (this.deps.settings.read().detached) return;
const main = this.deps.getMainWindow();
if (!main || main.isDestroyed()) return;
+ const focusedSessionId =
+ sessionId ??
+ (this.lastReportedContext?.available ? this.lastReportedContext.sessionId : null);
this.flushDeferredCommands(
() => !main.isDestroyed(),
(command) => this.deps.sendToWindow(main, this.deps.commandChannel, command),
+ focusedSessionId,
);
}
- private broadcast(): void {
+ private broadcast(opts: { userClose?: boolean } = {}): void {
const s = this.deps.settings.read();
// pendingOpen:窗口已创建但等待 presentation-ready,从调用方视角视为 open。
- this.deps.broadcastState({ detached: s.detached, open: this.isOpen() || this.pendingOpen });
+ this.deps.broadcastState({
+ detached: s.detached,
+ open: this.isOpen() || this.pendingOpen,
+ ...(this.lastHostSessionId ? { hostSessionId: this.lastHostSessionId } : {}),
+ ...(opts.userClose === false ? { userClose: false } : {}),
+ });
+ }
+
+ private cancelPendingOpen(): void {
+ const advertisedPending = this.pendingOpen && !this.visible;
+ this.pendingOpen = false;
+ this.pendingOpenShouldFocus = true;
+ this.clearOpenTimeout();
+ this.rejectReadyWaiters();
+ if (advertisedPending) this.broadcast({ userClose: false });
}
}
diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.ts
index 47ba745e9e..08bba975d6 100644
--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts
+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts
@@ -38,16 +38,26 @@ const SUBAGENT_PROVIDERS = [
'pi',
] as const satisfies readonly SubagentProvider[];
+const MAX_CONTEXT_SESSION_ID_LENGTH = 128;
+const MAX_CONTEXT_PATH_LENGTH = 4096;
+
function parseContext(raw: unknown): RsbWindowContext {
const r = requireObject(raw, 'context');
- const nullableString = (v: unknown, name: string): string | null => {
+ const nullableString = (v: unknown, name: string, maxLength: number): string | null => {
if (v === null || v === undefined) return null;
if (typeof v !== 'string') throwIpcError('INVALID_PARAMS', `${name} must be string | null`);
+ if (v.length > maxLength) {
+ throwIpcError('INVALID_PARAMS', `${name} must be at most ${maxLength} characters`);
+ }
return v;
};
- const optionalNullableString = (v: unknown, name: string): string | null | undefined => {
+ const optionalNullableString = (
+ v: unknown,
+ name: string,
+ maxLength: number,
+ ): string | null | undefined => {
if (v === undefined) return undefined;
- return nullableString(v, name);
+ return nullableString(v, name, maxLength);
};
if (typeof r.available !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'available must be boolean');
@@ -55,11 +65,15 @@ function parseContext(raw: unknown): RsbWindowContext {
if (r.subagentsAvailable !== undefined && typeof r.subagentsAvailable !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'subagentsAvailable must be boolean when provided');
}
- const deviceLinkDeviceId = optionalNullableString(r.deviceLinkDeviceId, 'deviceLinkDeviceId');
+ const deviceLinkDeviceId = optionalNullableString(
+ r.deviceLinkDeviceId,
+ 'deviceLinkDeviceId',
+ MAX_CONTEXT_SESSION_ID_LENGTH,
+ );
return {
- sessionId: nullableString(r.sessionId, 'sessionId'),
- workdir: nullableString(r.workdir, 'workdir'),
- remoteHostId: nullableString(r.remoteHostId, 'remoteHostId'),
+ sessionId: nullableString(r.sessionId, 'sessionId', MAX_CONTEXT_SESSION_ID_LENGTH),
+ workdir: nullableString(r.workdir, 'workdir', MAX_CONTEXT_PATH_LENGTH),
+ remoteHostId: nullableString(r.remoteHostId, 'remoteHostId', MAX_CONTEXT_SESSION_ID_LENGTH),
...(deviceLinkDeviceId === undefined ? {} : { deviceLinkDeviceId }),
...(r.subagentsAvailable === undefined
? {}
@@ -70,8 +84,12 @@ function parseContext(raw: unknown): RsbWindowContext {
function parseCommand(raw: unknown): RsbWindowCommand {
const r = requireObject(raw, 'command');
- if (typeof r.sessionId !== 'string' || r.sessionId.length === 0) {
- throwIpcError('INVALID_PARAMS', 'command.sessionId required');
+ if (
+ typeof r.sessionId !== 'string' ||
+ r.sessionId.length === 0 ||
+ r.sessionId.length > 128
+ ) {
+ throwIpcError('INVALID_PARAMS', 'command.sessionId must be a 1–128 character string');
}
if (r.type === 'open-terminal') {
return { type: 'open-terminal', sessionId: r.sessionId };
@@ -258,13 +276,22 @@ function parseCommandRouteRequest(raw: unknown): RsbWindowCommandRouteRequest {
}
/** open 的可选 payload:缺省(旧签名 / 无参调用)= 用户手势,保持既有聚焦行为。 */
-function parseOpenUserInitiated(raw: unknown): boolean {
- if (raw === undefined || raw === null) return true;
+function parseOpenOptions(raw: unknown): { userInitiated: boolean; sessionId?: string } {
+ if (raw === undefined || raw === null) return { userInitiated: true };
const r = requireObject(raw, 'options');
if (r.userInitiated !== undefined && typeof r.userInitiated !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'options.userInitiated must be boolean');
}
- return r.userInitiated !== false;
+ if (
+ r.sessionId !== undefined &&
+ (typeof r.sessionId !== 'string' || r.sessionId.length === 0 || r.sessionId.length > 128)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'options.sessionId must be a 1–128 character string');
+ }
+ return {
+ userInitiated: r.userInitiated !== false,
+ ...(typeof r.sessionId === 'string' ? { sessionId: r.sessionId } : {}),
+ };
}
const MAX_HANDOFF_SNAPSHOTS = 8;
@@ -333,8 +360,14 @@ export function registerRsbWindowIpc(opts: {
ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_GET_STATE, () => controller.getState());
- ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_OPEN, (_e, payload: unknown) => {
- controller.open({ userInitiated: parseOpenUserInitiated(payload) });
+ ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_OPEN, (event, payload: unknown) => {
+ const options = parseOpenOptions(payload);
+ const main = getMainWindow();
+ if (!main || main.isDestroyed() || event.sender !== main.webContents) {
+ log.warn('RSB_WINDOW_OPEN from non-main-window sender, dropped');
+ return;
+ }
+ controller.open(options);
});
ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_CLOSE, () => {
diff --git a/apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts b/apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts
new file mode 100644
index 0000000000..bc9f8c13f5
--- /dev/null
+++ b/apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts
@@ -0,0 +1,107 @@
+/**
+ * Detached 侧栏 pin 到非焦点 session 时,从主进程权威来源补齐宿主上下文。
+ *
+ * 查找顺序:
+ * 1. 本地 sessions 表:命中即本机或 SSH 会话。device-link 任务不落这张表,
+ * 所以这里显式写成 deviceLinkDeviceId:null(已确认非设备互联)。
+ * 2. device-link 镜像列表:控制端远程任务的 Main 注册表,只读补 deviceId / workdir。
+ */
+import { eq } from 'drizzle-orm';
+
+import {
+ getMirrorCache,
+ MAX_CACHED_TEXT_CHARS,
+} from '../device-link/mirrorCacheStore.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { sessions } from '../localDb/schema.js';
+import type { RsbWindowContext } from '../../shared/rightSidebarWindow.js';
+
+export function contextFromLocalSessionRow(row: {
+ id: string;
+ workingDir: string | null;
+ remoteHostId: string | null;
+ agentKind: string;
+}): RsbWindowContext {
+ return {
+ sessionId: row.id,
+ workdir: row.workingDir ?? null,
+ remoteHostId: row.remoteHostId ?? null,
+ deviceLinkDeviceId: null,
+ available: true,
+ subagentsAvailable: row.agentKind === 'pi' && !row.remoteHostId,
+ };
+}
+
+function workdirFromDeviceLinkMirror(session: Record<string, unknown>): string | null {
+ const raw =
+ typeof session.workingDir === 'string'
+ ? session.workingDir
+ : typeof session.worktreePath === 'string'
+ ? session.worktreePath
+ : null;
+ // 冷镜像把路径截到 240 字给列表显示。截断值不能当操作目录。
+ if (!raw || raw.length >= MAX_CACHED_TEXT_CHARS) return null;
+ return raw;
+}
+
+export function contextFromDeviceLinkMirror(
+ deviceId: string,
+ session: Record<string, unknown>,
+): RsbWindowContext | null {
+ const sessionId = typeof session.id === 'string' ? session.id : '';
+ if (!deviceId || !sessionId) return null;
+ const workdir = workdirFromDeviceLinkMirror(session);
+ return {
+ sessionId,
+ workdir,
+ remoteHostId: null,
+ deviceLinkDeviceId: deviceId,
+ available: true,
+ // 冷镜像没有 remoteHostId,不能把 SSH Pi 当成有 Subagents。
+ subagentsAvailable: false,
+ };
+}
+
+export async function resolveRsbHostContextFromSession(
+ sessionId: string,
+): Promise<RsbWindowContext | null> {
+ if (!sessionId) return null;
+ const local = await readLocalSessionContext(sessionId);
+ if (local) return local;
+ return readDeviceLinkMirrorContext(sessionId);
+}
+
+async function readLocalSessionContext(sessionId: string): Promise<RsbWindowContext | null> {
+ try {
+ const rows = await getDbClient()
+ .drizzle.select({
+ id: sessions.id,
+ workingDir: sessions.workingDir,
+ remoteHostId: sessions.remoteHostId,
+ agentKind: sessions.agentKind,
+ status: sessions.status,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ const row = rows[0];
+ if (!row || row.status === 'deleted') return null;
+ return contextFromLocalSessionRow(row);
+ } catch {
+ return null;
+ }
+}
+
+async function readDeviceLinkMirrorContext(sessionId: string): Promise<RsbWindowContext | null> {
+ try {
+ const devices = await getMirrorCache().readSessionList();
+ for (const device of devices) {
+ const session = device.sessions.find((item) => item.id === sessionId);
+ if (!session) continue;
+ return contextFromDeviceLinkMirror(device.deviceId, session);
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
diff --git a/apps/desktop/src/main/rsb-browser-bridge/__tests__/renderer-bridge.test.ts b/apps/desktop/src/main/rsb-browser-bridge/__tests__/renderer-bridge.test.ts
index fc00b90953..d45bdf6be5 100644
--- a/apps/desktop/src/main/rsb-browser-bridge/__tests__/renderer-bridge.test.ts
+++ b/apps/desktop/src/main/rsb-browser-bridge/__tests__/renderer-bridge.test.ts
@@ -285,6 +285,7 @@ describe('dispatchTabOp — ensureHost(detached 侧边栏子窗口)', () => {
const pending = dispatchTabOp({ op: 'open', sessionId: 's1', url: 'https://x.dev' }, opts);
expect(ensureHost).toHaveBeenCalledTimes(1);
+ expect(ensureHost).toHaveBeenCalledWith('s1');
expect(wc.send).not.toHaveBeenCalled();
releaseEnsure();
diff --git a/apps/desktop/src/main/rsb-browser-bridge/renderer-bridge.ts b/apps/desktop/src/main/rsb-browser-bridge/renderer-bridge.ts
index cb372bafdb..39683d9aea 100644
--- a/apps/desktop/src/main/rsb-browser-bridge/renderer-bridge.ts
+++ b/apps/desktop/src/main/rsb-browser-bridge/renderer-bridge.ts
@@ -46,7 +46,7 @@ export interface RendererBridgeOptions {
* waits for its renderer's ready handshake so the tab-op has a live host.
* Rejection fails the tab-op (no host to run it against).
*/
- ensureHost?: () => Promise<void>;
+ ensureHost?: (sessionId?: string) => Promise<void>;
/**
* Whether the user currently prefers the sidebar in a detached window.
* Consumers use it to decide if a tab-resolve miss is worth waiting on
@@ -108,7 +108,8 @@ export async function dispatchTabOp(
): Promise<RsbBrowserBridgeTabOpResult> {
assertActive?.();
if (dispatchOptions.ensureHost !== false && opts.ensureHost) {
- await opts.ensureHost();
+ const sessionId = 'sessionId' in op ? op.sessionId : undefined;
+ await opts.ensureHost(sessionId);
assertActive?.();
}
const wc = opts.getHostWebContents();
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 83cf8e03a1..e6029d6e7f 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1642,13 +1642,17 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 「侧边栏在新窗口中显示」偏好 + 子窗口生命周期。状态机在 main
// (right-sidebar-window/controller.ts),renderer 只 invoke + 订阅广播。
rightSidebarWindow: {
- getState: (): Promise<{ detached: boolean; lastOpen: boolean; open: boolean }> =>
- ipcRenderer.invoke('maker:rsb-window:get-state'),
+ getState: (): Promise<{
+ detached: boolean;
+ lastOpen: boolean;
+ open: boolean;
+ hostSessionId?: string | null;
+ }> => ipcRenderer.invoke('maker:rsb-window:get-state'),
/**
* 幂等开窗。缺省(用户手势)已开则 show + focus;
* userInitiated:false(启动恢复 / 插件 / agent 自发)已开则完全不动窗口。
*/
- open: (options?: { userInitiated?: boolean }): Promise<void> =>
+ open: (options?: { userInitiated?: boolean; sessionId?: string }): Promise<void> =>
ipcRenderer.invoke('maker:rsb-window:open', options),
close: (): Promise<void> => ipcRenderer.invoke('maker:rsb-window:close'),
/** 写偏好;true 附带开窗,false 附带关窗。返回新 state。 */
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
index eccb5f5754..e19f977012 100644
--- a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
@@ -463,6 +463,11 @@ describe('OrcaWorkflowRoute source invariants', () => {
expect(mainLayoutSource).toContain("routeSidebarCommand({ type: 'open-terminal', sessionId })");
expect(mainLayoutSource).toContain('const windowState = getRsbWindowUiState();');
expect(mainLayoutSource).toContain('const currentSessionId = rightSidebarSessionIdRef.current;');
+ expect(mainLayoutSource).toContain('sessionId: targetSessionId');
+ expect(mainLayoutSource).toContain(
+ "if (visibility === 'open' && opts.userInitiated !== false)",
+ );
+ expect(mainLayoutSource).toContain('navigateToSessionRef.current?.(targetSessionId)');
});
it('passes Orca lead vendor options when sending from the plain lead route', () => {
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 76e88bf254..a744231129 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -50,7 +50,12 @@ import {
getRsbWindowUiState,
useRightSidebarWindowState,
} from '@/lib/rightSidebarWindowState';
-import { didUserCloseDetachedSidebarWindow } from '@/lib/rsbWindowTransitions';
+import {
+ detachedHostAfterOpen,
+ didUserCloseDetachedSidebarWindow,
+ nextDetachedHostAfterFocus,
+ sessionIdForDetachedSidebarClose,
+} from '@/lib/rsbWindowTransitions';
import { routeSidebarCommand } from '@/features/right-sidebar/lib/detachedSidebarRouting';
import { openTerminalFromShortcut } from '@/features/right-sidebar/lib/openTerminalShortcut';
import { executeSidebarCommand } from '@/features/right-sidebar/lib/executeSidebarCommand';
@@ -277,13 +282,19 @@ export function MainLayout() {
>(undefined);
const rightSidebarSessionIdRef = useRef(rightSidebarSessionId);
rightSidebarSessionIdRef.current = rightSidebarSessionId;
+ const detachedHostSessionIdRef = useRef<string | null>(null);
const isRightSidebarCollapsedRef = useRef(isRightSidebarCollapsed);
isRightSidebarCollapsedRef.current = isRightSidebarCollapsed;
const rsbDetachedRef = useRef(rsbDetached);
rsbDetachedRef.current = rsbDetached;
+ const navigateToSessionRef = useRef<(sessionId: string) => void>(() => undefined);
const declareRightSidebarSessionId = useCallback(
(sessionId: string | null, opts: RightSidebarSessionDeclarationOptions = {}) => {
rightSidebarSessionIdRef.current = sessionId;
+ detachedHostSessionIdRef.current = nextDetachedHostAfterFocus(
+ detachedHostSessionIdRef.current,
+ sessionId,
+ );
setRightSidebarSessionId(sessionId);
setRightSidebarSubagentsAvailable(sessionId ? opts.subagentsAvailable : undefined);
if (!sessionId || !rsbWindow.loaded || rsbDetached) return;
@@ -520,6 +531,7 @@ export function MainLayout() {
},
[navigate],
);
+ navigateToSessionRef.current = navigateToSession;
useEffect(() => {
const unsubscribe = window.electronAPI.onNotificationFocusSession((sessionId) => {
if (typeof sessionId !== 'string' || !sessionId) return;
@@ -763,21 +775,12 @@ export function MainLayout() {
// .handleTabOpRequest):open/focus → 'open',close 最后一个 tab → 'close'。
// 全部走纯代码确定性,不让模型推理。
//
- // Cross-session race(用户痛点):
+ // Cross-session 呼起必须跟发起方 session,不能只认当前焦点:
// 1) agent 在 session A 调 open → 触发 visibility 'open' + sessionId=A
- // 2) 用户在 dispatch 到达本 listener 之前切到 session B
- // 3) 此时 `rightSidebarSessionId` 已经是 B
- // 朴素实现会把 B 的侧边栏弹开(用户没要求的 UI 跳),并且 A 的新 tab 还存在 A
- // 的 bucket 里(其 collapsed 存档没改,用户切回 A 还要手动展开才能看见)。
- //
- // 正确分支:
- // - 信号 sessionId === 当前 rightSidebarSessionId → 前台路径:setState + 动画
- // + 持久化(用户体感:agent 操作可见)
- // - 信号 sessionId !== 当前 rightSidebarSessionId → 后台路径:仅 writeCollapsedFor
- // 到目标 sessionId 的存档,UI 不动。用户切回 A 时,sessionId useEffect 触发
- // `readCollapsedFor(A)` 拿到 false,瞬间渲染展开的侧栏 — 没有"刚到就弹"的
- // 违和感(规则 7: 不要 loading 闪屏)。
- // - 信号未带 sessionId(直接 UI button 触发) → 跟前台路径同意义,默认走当前 session
+ // 2) 用户此时看着 session B(远程连接、副窗、切走等)
+ // 旧实现只给 B 弹栏 / 或把异会话请求丢掉,A 的浏览器永远看不见。
+ // 现在: detached 把子窗口钉到 A;内嵌则写入 A 的存档并 navigate 到 A。
+ // 信号未带 sessionId(直接 UI button)仍走当前 session。
useEffect(() => {
return onRequestRightSidebarVisibility((visibility, opts) => {
const currentSessionId = rightSidebarSessionIdRef.current;
@@ -787,24 +790,29 @@ export function MainLayout() {
const windowState = getRsbWindowUiState();
if (!windowState.loaded) return;
const detachedNow = !isSecondaryWindow() && windowState.detached;
- // detached 模式:可见性 = 子窗口开闭。当前会话的请求驱动窗口;异会话请求
- // 只写内嵌折叠存档(供日后关偏好回内嵌时用),UI 不动。
+ // detached 模式:可见性 = 子窗口开闭。呼起必须跟发起方 session,不能只认
+ // 主窗当前焦点 —— 远程连接 / 后台 session 的 agent 开页否则会丢在焦点桶里。
// (agent tab-op 在 detached 时 dispatch 到子窗口 renderer,其内的
// SidebarWindowLayout 也订阅了本通道;这里主要覆盖主窗内直接调用方。)
if (detachedNow) {
- if (targetSessionId === currentSessionId) {
- writeCollapsedFor(targetSessionId, targetCollapsed);
- if (visibility === 'open') {
- // userInitiated 透传:插件 preview / agent 自动化(false)只把内容送进
- // 子窗口,不 show+focus 抢用户前台;用户手势(缺省 true)行为不变。
- void window.electronAPI.rightSidebarWindow
- .open({ userInitiated: opts.userInitiated !== false })
- .catch(() => undefined);
- } else {
- void window.electronAPI.rightSidebarWindow.close().catch(() => undefined);
- }
- } else {
- writeCollapsedFor(targetSessionId, targetCollapsed);
+ writeCollapsedFor(targetSessionId, targetCollapsed);
+ if (visibility === 'open') {
+ detachedHostSessionIdRef.current = detachedHostAfterOpen({
+ currentSessionId,
+ targetSessionId,
+ previousHostSessionId: detachedHostSessionIdRef.current,
+ });
+ // userInitiated 透传:插件 preview / agent 自动化(false)只把内容送进
+ // 子窗口,不 show+focus 抢用户前台;用户手势(缺省 true)行为不变。
+ // sessionId 让 controller 把子窗口钉在发起方 session 上。
+ void window.electronAPI.rightSidebarWindow
+ .open({
+ userInitiated: opts.userInitiated !== false,
+ sessionId: targetSessionId,
+ })
+ .catch(() => undefined);
+ } else if (targetSessionId === currentSessionId) {
+ void window.electronAPI.rightSidebarWindow.close().catch(() => undefined);
}
return;
}
@@ -819,23 +827,29 @@ export function MainLayout() {
return targetCollapsed;
});
} else {
- // 后台路径:只写存档,用户切回该 session 时 useEffect 读到新值瞬间渲染
+ // 后台路径:写入目标 session 存档。用户手势跨任务 open 才切主窗;
+ // agent / 插件自动化(userInitiated:false)只落档,不抢当前输入焦点。
writeCollapsedFor(targetSessionId, targetCollapsed);
+ if (visibility === 'open' && opts.userInitiated !== false) {
+ navigateToSessionRef.current?.(targetSessionId);
+ }
}
});
}, []);
// detached 子窗口的所有真实关窗入口最终都会广播 open:true→false。只要偏好仍是
- // detached,就把当前 session 记为用户显式收起;合并回主窗会先变 detached=false,
- // 不命中本分支,继续由 attach 路径写“开”。
+ // detached,就把**实际宿主 session**记为用户显式收起;合并回主窗会先变
+ // detached=false,不命中本分支,继续由 attach 路径写“开”。
const prevRsbWindowStateRef = useRef(rsbWindow);
useEffect(() => {
const prev = prevRsbWindowStateRef.current;
prevRsbWindowStateRef.current = rsbWindow;
- const sessionId = rightSidebarSessionIdRef.current;
- if (sessionId && didUserCloseDetachedSidebarWindow(prev, rsbWindow, !isSecondaryWindow())) {
- writeCollapsedFor(sessionId, true);
- }
+ if (!didUserCloseDetachedSidebarWindow(prev, rsbWindow, !isSecondaryWindow())) return;
+ const sessionId = sessionIdForDetachedSidebarClose(
+ rsbWindow.hostSessionId ?? detachedHostSessionIdRef.current,
+ rightSidebarSessionIdRef.current,
+ );
+ if (sessionId) writeCollapsedFor(sessionId, true);
}, [rsbWindow]);
// RSB Maximize(Phase 6):侧栏接管整个内容区。
diff --git a/apps/desktop/src/renderer/lib/__tests__/rsbWindowTransitions.test.ts b/apps/desktop/src/renderer/lib/__tests__/rsbWindowTransitions.test.ts
index e059b45197..064ad94cd1 100644
--- a/apps/desktop/src/renderer/lib/__tests__/rsbWindowTransitions.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/rsbWindowTransitions.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { didUserCloseDetachedSidebarWindow } from '../rsbWindowTransitions';
+import {
+ detachedHostAfterOpen,
+ didUserCloseDetachedSidebarWindow,
+ nextDetachedHostAfterFocus,
+ sessionIdForDetachedSidebarClose,
+} from '../rsbWindowTransitions';
describe('didUserCloseDetachedSidebarWindow', () => {
it('recognizes every close path by the detached open-to-closed transition', () => {
@@ -10,6 +15,12 @@ describe('didUserCloseDetachedSidebarWindow', () => {
{ loaded: true, detached: true, open: false },
),
).toBe(true);
+ expect(
+ didUserCloseDetachedSidebarWindow(
+ { loaded: true, detached: true, open: true },
+ { loaded: true, detached: true, open: false, userClose: false },
+ ),
+ ).toBe(false);
});
it('does not treat merge-back, bootstrap, or opening as a user close', () => {
@@ -33,6 +44,50 @@ describe('didUserCloseDetachedSidebarWindow', () => {
).toBe(false);
});
+ it('attributes a detached close to the pinned host, not the focused session', () => {
+ expect(
+ sessionIdForDetachedSidebarClose(
+ { loaded: true, detached: true, open: false, hostSessionId: 'session-a' }.hostSessionId,
+ 'session-b',
+ ),
+ ).toBe('session-a');
+ expect(sessionIdForDetachedSidebarClose('session-a', 'session-b')).toBe('session-a');
+ expect(sessionIdForDetachedSidebarClose(null, 'session-b')).toBe('session-b');
+ expect(sessionIdForDetachedSidebarClose(null, null)).toBeNull();
+ expect(nextDetachedHostAfterFocus('session-a', 'session-b')).toBe('session-a');
+ expect(nextDetachedHostAfterFocus('session-a', 'session-a')).toBeNull();
+ expect(sessionIdForDetachedSidebarClose(
+ nextDetachedHostAfterFocus('session-a', 'session-a'),
+ 'session-c',
+ )).toBe('session-c');
+ expect(detachedHostAfterOpen({
+ currentSessionId: 'session-a',
+ targetSessionId: 'session-a',
+ previousHostSessionId: null,
+ })).toBeNull();
+ expect(detachedHostAfterOpen({
+ currentSessionId: 'session-b',
+ targetSessionId: 'session-a',
+ previousHostSessionId: null,
+ })).toBe('session-a');
+ expect(detachedHostAfterOpen({
+ currentSessionId: 'session-b',
+ targetSessionId: 'session-b',
+ previousHostSessionId: 'session-a',
+ })).toBeNull();
+ expect(sessionIdForDetachedSidebarClose(
+ nextDetachedHostAfterFocus(
+ detachedHostAfterOpen({
+ currentSessionId: 'session-a',
+ targetSessionId: 'session-a',
+ previousHostSessionId: null,
+ }),
+ 'session-c',
+ ),
+ 'session-c',
+ )).toBe('session-c');
+ });
+
it('does not let a secondary window persist the primary detached close transition', () => {
expect(
didUserCloseDetachedSidebarWindow(
diff --git a/apps/desktop/src/renderer/lib/rightSidebarWindowState.ts b/apps/desktop/src/renderer/lib/rightSidebarWindowState.ts
index ac43543f55..321cac3143 100644
--- a/apps/desktop/src/renderer/lib/rightSidebarWindowState.ts
+++ b/apps/desktop/src/renderer/lib/rightSidebarWindowState.ts
@@ -17,6 +17,8 @@ export interface RsbWindowUiState {
loaded: boolean;
detached: boolean;
open: boolean;
+ hostSessionId?: string | null;
+ userClose?: boolean;
}
function initialState(): RsbWindowUiState {
@@ -36,8 +38,15 @@ let bootstrapPromise: Promise<{
} | null> | null = null;
function setState(next: RsbWindowUiState): void {
- if (state.loaded === next.loaded && state.detached === next.detached && state.open === next.open)
+ if (
+ state.loaded === next.loaded &&
+ state.detached === next.detached &&
+ state.open === next.open &&
+ state.hostSessionId === next.hostSessionId &&
+ state.userClose === next.userClose
+ ) {
return;
+ }
state = next;
subscribers.forEach((cb) => cb());
}
@@ -47,7 +56,13 @@ function ensureWired(): void {
if (wired || isSecondaryWindow()) return;
wired = true;
window.electronAPI?.rightSidebarWindow?.onStateChanged((s) => {
- setState({ loaded: true, detached: s.detached, open: s.open });
+ setState({
+ loaded: true,
+ detached: s.detached,
+ open: s.open,
+ ...(s.hostSessionId ? { hostSessionId: s.hostSessionId } : {}),
+ ...(s.userClose === false ? { userClose: false } : {}),
+ });
});
}
@@ -82,7 +97,12 @@ export async function bootstrapRsbWindowState(): Promise<{
bootstrapPromise = (async () => {
try {
const s = await window.electronAPI.rightSidebarWindow.getState();
- setState({ loaded: true, detached: s.detached, open: s.open });
+ setState({
+ loaded: true,
+ detached: s.detached,
+ open: s.open,
+ ...(s.hostSessionId ? { hostSessionId: s.hostSessionId } : {}),
+ });
return s;
} catch {
// IPC 异常时明确落到 attached fallback,避免整个会话期永久卡在 unknown。
diff --git a/apps/desktop/src/renderer/lib/rsbWindowTransitions.ts b/apps/desktop/src/renderer/lib/rsbWindowTransitions.ts
index 73dbf65c82..c00b6f734d 100644
--- a/apps/desktop/src/renderer/lib/rsbWindowTransitions.ts
+++ b/apps/desktop/src/renderer/lib/rsbWindowTransitions.ts
@@ -1,6 +1,38 @@
import type { RsbWindowUiState } from './rightSidebarWindowState';
/** 用户真正关 detached 窗口时记录 collapsed;合并回 attached 和启动 unknown 不算。 */
+export function sessionIdForDetachedSidebarClose(
+ detachedHostSessionId: string | null | undefined,
+ focusedSessionId: string | null | undefined,
+): string | null {
+ return detachedHostSessionId || focusedSessionId || null;
+}
+
+/** 用户切到被 pin 的宿主后,关窗归属改回跟随焦点。 */
+export function nextDetachedHostAfterFocus(
+ detachedHostSessionId: string | null | undefined,
+ focusedSessionId: string | null | undefined,
+): string | null {
+ if (focusedSessionId && focusedSessionId === detachedHostSessionId) return null;
+ return detachedHostSessionId ?? null;
+}
+
+/** 只有真正跨会话 pin 才记录关窗宿主;同会话 open 不会制造陈旧 ref。 */
+export function detachedHostAfterOpen(params: {
+ currentSessionId: string | null | undefined;
+ targetSessionId: string;
+ previousHostSessionId: string | null | undefined;
+}): string | null {
+ if (params.targetSessionId !== params.currentSessionId) return params.targetSessionId;
+ if (
+ params.previousHostSessionId &&
+ params.previousHostSessionId !== params.targetSessionId
+ ) {
+ return null;
+ }
+ return params.previousHostSessionId ?? null;
+}
+
export function didUserCloseDetachedSidebarWindow(
previous: RsbWindowUiState,
next: RsbWindowUiState,
@@ -13,6 +45,7 @@ export function didUserCloseDetachedSidebarWindow(
previous.open &&
next.loaded &&
next.detached &&
- !next.open,
+ !next.open &&
+ next.userClose !== false,
);
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index ee0c13483a..c3873ecca3 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1863,12 +1863,17 @@ interface ElectronAPI {
// ── 右侧栏独立子窗口(RSB window)──────────────────────────────────────
// 「侧边栏在新窗口中显示」偏好 + 子窗口生命周期(main: right-sidebar-window/)。
rightSidebarWindow: {
- getState: () => Promise<{ detached: boolean; lastOpen: boolean; open: boolean }>;
+ getState: () => Promise<{
+ detached: boolean;
+ lastOpen: boolean;
+ open: boolean;
+ hostSessionId?: string | null;
+ }>;
/**
* 幂等开窗。缺省(用户手势)已开则 show + focus;
* userInitiated:false(启动恢复 / 插件 / agent 自发)已开则完全不动窗口。
*/
- open: (options?: { userInitiated?: boolean }) => Promise<void>;
+ open: (options?: { userInitiated?: boolean; sessionId?: string }) => Promise<void>;
close: () => Promise<void>;
/** 写偏好;true 附带开窗,false 附带关窗。返回新 state。 */
setDetached: (
@@ -1904,7 +1909,12 @@ interface ElectronAPI {
subagentsAvailable?: boolean;
available: boolean;
}) => void;
- onStateChanged: (cb: (state: { detached: boolean; open: boolean }) => void) => () => void;
+ onStateChanged: (cb: (state: {
+ detached: boolean;
+ open: boolean;
+ hostSessionId?: string | null;
+ userClose?: boolean;
+ }) => void) => () => void;
onContextChanged: (
cb: (ctx: {
sessionId: string | null;
diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.ts
index 90f4f8044a..39b404bf6c 100644
--- a/apps/desktop/src/shared/rightSidebarWindow.ts
+++ b/apps/desktop/src/shared/rightSidebarWindow.ts
@@ -17,6 +17,8 @@ export interface RsbWindowState {
lastOpen: boolean;
/** 运行时:子窗口当前是否存在。不持久化。 */
open: boolean;
+ /** 子窗口最近一次真正展示的宿主 session。关窗后仍保留,供主窗写折叠归属。 */
+ hostSessionId?: string | null;
}
/**