Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 侧边栏子窗口不再为插件预览与自动化抢占前台
Lizid86da4611022
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 240c0569a0..4ab5e69935 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -992,7 +992,7 @@ installWebviewHardener();// 调用时机远晚于此处构造),状态机本体见 right-sidebar-window/controller.ts。const rsbWindowController = new RsbWindowController({settings: { read: readRsbWindowSettings, writePatch: writeRsbWindowSettingsPatch },- createWindow: () => createRightSidebarWindow(),+ createWindow: (opts) => createRightSidebarWindow(opts),getMainWindow: () => mainWindowRef,broadcastState: (state) => {for (const win of BrowserWindow.getAllWindows()) {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.tsindex 91eae5381f..aaaf200c3d 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@@ -59,6 +59,7 @@ function makeHarness(let settings: RsbWindowSettings = { detached: false, lastOpen: false, ...initial };let quitting = false;const windows: FakeWindow[] = [];+ const createWindowCalls: Array<{ userInitiated: boolean }> = [];const mainWin = fakeWindow(100);const broadcasts: Array<{ detached: boolean; open: boolean }> = [];const sends: Array<{ channel: string; payload: unknown }> = [];@@ -71,7 +72,8 @@ function makeHarness(settings = { ...settings, ...patch };},},- createWindow: () => {+ createWindow: (createOpts) => {+ createWindowCalls.push(createOpts);const w = fakeWindow(200 + windows.length, opts.asyncClose === true);windows.push(w);return w as unknown as BrowserWindow;@@ -93,6 +95,7 @@ function makeHarness(return {controller,windows,+ createWindowCalls,mainWin,broadcasts,sends,@@ -142,6 +145,86 @@ describe('open / close', () => {});});+describe('userInitiated:false 不抢用户前台', () => {+ it('窗口已开:程序自发的 open 完全不动窗口(无 show / focus / restore)', () => {+ const h = makeHarness();+ h.controller.open();+ const win = h.windows[0];+ win.show.mockClear();+ win.focus.mockClear();+ win.restore.mockClear();++ h.controller.open({ userInitiated: false });++ expect(h.windows).toHaveLength(1);+ expect(win.show).not.toHaveBeenCalled();+ expect(win.focus).not.toHaveBeenCalled();+ expect(win.restore).not.toHaveBeenCalled();+ });++ it('窗口未开:照常建窗并落 lastOpen,但把 userInitiated:false 透传给窗口工厂', () => {+ const h = makeHarness();+ h.controller.open({ userInitiated: false });+ expect(h.windows).toHaveLength(1);+ expect(h.createWindowCalls).toEqual([{ userInitiated: false }]);+ expect(h.getSettings().lastOpen).toBe(true);+ expect(h.broadcasts.at(-1)).toEqual({ detached: false, open: true });+ });++ it('ensureOpenForAutomation 缺省按程序自发处理(建窗不抢焦点)', async () => {+ const h = makeHarness({ detached: true });+ const p = h.controller.ensureOpenForAutomation();+ h.controller.markReady();+ await expect(p).resolves.toBeUndefined();+ expect(h.createWindowCalls).toEqual([{ userInitiated: false }]);+ });++ it('routeCommand userInitiated:false:命令照常派发,但开窗不抢焦点', async () => {+ const h = makeHarness({ detached: true });+ h.controller.setContext({+ sessionId: 's1',+ workdir: '/w',+ remoteHostId: null,+ available: true,+ });+ const command = { type: 'open-web-browser' as const, sessionId: 's1', url: 'https://x.test/' };+ const routed = h.controller.routeCommand({+ command,+ allowOpen: true,+ userInitiated: false,+ });+ h.controller.markReady();+ await expect(routed).resolves.toBe('routed');+ expect(h.createWindowCalls).toEqual([{ userInitiated: false }]);+ expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: command });+ });++ it('routeCommand 缺省(用户手势)仍走聚焦开窗', async () => {+ const h = makeHarness({ detached: true });+ h.controller.setContext({+ sessionId: 's1',+ workdir: '/w',+ remoteHostId: null,+ available: true,+ });+ const routed = h.controller.routeCommand({+ command: { type: 'open-terminal', sessionId: 's1' },+ allowOpen: true,+ });+ h.controller.markReady();+ await expect(routed).resolves.toBe('routed');+ expect(h.createWindowCalls).toEqual([{ userInitiated: true }]);+ });++ it('setDetached(true)(用户点按钮)开窗并聚焦', () => {+ const h = makeHarness();+ h.controller.setDetached(true);+ expect(h.createWindowCalls).toEqual([{ userInitiated: true }]);+ h.controller.setDetached(true);+ expect(h.windows[0].focus).toHaveBeenCalled();+ });+});+describe('closed 事件(用户关窗 vs app 退出)', () => {it('非 quitting:lastOpen=false + 广播 open:false', () => {const h = makeHarness();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.tsindex b19711f563..16ec15ca05 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@@ -280,6 +280,47 @@ describe('right-sidebar-window IPC', () => {).rejects.toThrow(/command.sessionId required/);});+ it('forwards userInitiated when present and omits it when absent', async () => {+ const controller = makeController();+ const { handler, mainWebContents } = registerController(controller);+ const command = { type: 'open-web-browser', sessionId: 's1', url: 'https://x.test/' };++ await handler({ sender: mainWebContents }, { command, allowOpen: true, userInitiated: false });+ await handler({ sender: mainWebContents }, { command, allowOpen: true });++ expect(controller.routeCommand).toHaveBeenNthCalledWith(1, {+ command,+ allowOpen: true,+ userInitiated: false,+ });+ // 缺省不注入字段 —— controller 侧自己按 "!== false" 兜到用户手势语义。+ expect(controller.routeCommand).toHaveBeenNthCalledWith(2, { command, allowOpen: true });++ await expect(+ handler({ sender: mainWebContents }, { command, allowOpen: true, userInitiated: 'yes' }),+ ).rejects.toThrow(/request.userInitiated/);+ });++ it('open payload:缺省/空 = 用户手势;显式 false 透传;野值拒绝', async () => {+ const controller = makeController();+ 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');++ open({}, undefined);+ open({}, {});+ open({}, { userInitiated: false });++ expect(controller.open).toHaveBeenNthCalledWith(1, { userInitiated: true });+ expect(controller.open).toHaveBeenNthCalledWith(2, { userInitiated: true });+ expect(controller.open).toHaveBeenNthCalledWith(3, { userInitiated: false });++ expect(() => open({}, { userInitiated: 1 })).toThrow(/options.userInitiated/);+ });+it('requires an explicit allowOpen boolean in the IPC envelope', async () => {const controller = makeController();const { handler, mainWebContents } = registerController(controller);diff --git a/apps/desktop/src/main/right-sidebar-window/controller.ts b/apps/desktop/src/main/right-sidebar-window/controller.tsindex c7d659fef0..5d77b3269b 100644--- a/apps/desktop/src/main/right-sidebar-window/controller.ts+++ b/apps/desktop/src/main/right-sidebar-window/controller.ts@@ -39,8 +39,11 @@ export interface RsbWindowControllerDeps {read(): RsbWindowSettings;writePatch(patch: Partial<RsbWindowSettings>): void;};- /** 创建子窗口(不负责挂 closed 钩子,controller 自己挂)。 */- createWindow: () => BrowserWindow;+ /**+ * 创建子窗口(不负责挂 closed 钩子,controller 自己挂)。+ * userInitiated=false 时实现方须用不抢焦点的方式显示(showInactive)。+ */+ createWindow: (opts: { userInitiated: boolean }) => BrowserWindow;getMainWindow: () => BrowserWindow | null;/** 状态变化广播(所有窗口)。bootstrap 注入 getAllWindows 遍历实现。 */broadcastState: (state: { detached: boolean; open: boolean }) => void;@@ -79,16 +82,28 @@ export class RsbWindowController {return { detached: s.detached, lastOpen: s.lastOpen, open: this.isOpen() };}- /** 幂等打开:已开则 show + focus;未开则建窗 + lastOpen=true + 广播。 */- open(): void {+ /**+ * 幂等打开:已开则 show + focus;未开则建窗 + lastOpen=true + 广播。+ *+ * userInitiated(缺省 true)= 这次开窗是用户当次手势要求的,保持既有+ * 「带出并聚焦子窗口」行为。程序自发的开窗(插件 preview 槽、agent+ * 浏览器自动化)必须传 false:+ * - 窗口已经开着 → **什么都不做**。内容经命令通道照常送达,用户看得见;+ * 这里再 show/focus 只会把用户正在用的别的应用顶掉(Windows 上+ * focus() 即抢前台),属于纯粹的干扰。+ * - 窗口还没开 → 照常建窗,但由 createWindow 走 showInactive 不抢焦点。+ */+ open(opts: { userInitiated?: boolean } = {}): void {+ const userInitiated = opts.userInitiated !== false;if (this.winRef && !this.winRef.isDestroyed()) {if (this.closing) return;+ if (!userInitiated) return;if (this.winRef.isMinimized()) this.winRef.restore();this.winRef.show();this.winRef.focus();return;}- const win = this.deps.createWindow();+ const win = this.deps.createWindow({ userInitiated });this.winRef = win;this.closing = false;this.ready = false;@@ -115,7 +130,8 @@ export class RsbWindowController {setDetached(next: boolean): RsbWindowState {this.deps.settings.writePatch({ detached: next });if (next) {- this.open();+ // 唯一入口是用户点「在新窗口中打开」按钮 —— 明确的用户手势,该带出并聚焦。+ this.open({ userInitiated: true });} else {// queued 调用方早已返回;attach 时必须把 ownership 显式交回主 renderer。this.flushDeferredCommandsToAttachedHost();@@ -143,10 +159,12 @@ export class RsbWindowController {* 保证 dispatchTabOp 时子窗口 renderer 的 RSB store / webview 池已可用。* 非 detached 时 no-op(host 是主窗,常驻)。*/- ensureOpenForAutomation(): Promise<void> {+ ensureOpenForAutomation(opts: { userInitiated?: boolean } = {}): Promise<void> {if (!this.deps.settings.read().detached) return Promise.resolve();if (this.ready && this.winRef && !this.winRef.isDestroyed()) return Promise.resolve();- this.open();+ // 缺省 false:本入口的名字就是 "for automation" —— 调用方没表态时按+ // 「程序自发」处理,不抢用户焦点。用户手势路径显式传 true。+ this.open({ userInitiated: opts.userInitiated === true });if (this.ready) return Promise.resolve();return new Promise<void>((resolve, reject) => {const timeout = setTimeout(() => {@@ -192,6 +210,9 @@ export class RsbWindowController {request: RsbWindowCommandRouteRequest,): Promise<RsbWindowCommandRouteResult> {const { command, allowOpen } = request;+ // 缺省 true:既有调用点绝大多数是用户手势(点链接 / 菜单 / 快捷键),行为不变。+ // 插件 preview 槽与 agent 自动化显式传 false,只送内容不抢焦点。+ const userInitiated = request.userInitiated !== false;if (!this.deps.settings.read().detached) return 'attached';if (!this.canDispatchCommand(command)) return 'stale-context';@@ -210,7 +231,7 @@ export class RsbWindowController {if (allowOpen && (!this.isOpen() || !this.ready)) {try {- await this.ensureOpenForAutomation();+ await this.ensureOpenForAutomation({ userInitiated });} catch (err) {if (!this.deps.settings.read().detached) return 'attached';if (!this.canDispatchCommand(command)) return 'stale-context';diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.tsindex 66ce25a18c..494003a230 100644--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts@@ -130,12 +130,26 @@ function parseCommandRouteRequest(raw: unknown): RsbWindowCommandRouteRequest {if (typeof request.allowOpen !== 'boolean') {throwIpcError('INVALID_PARAMS', 'request.allowOpen required (boolean)');}+ if (request.userInitiated !== undefined && typeof request.userInitiated !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'request.userInitiated must be boolean');+ }return {command: parseCommand(request.command),allowOpen: request.allowOpen,+ ...(request.userInitiated === undefined ? {} : { userInitiated: request.userInitiated }),};}+/** open 的可选 payload:缺省(旧签名 / 无参调用)= 用户手势,保持既有聚焦行为。 */+function parseOpenUserInitiated(raw: unknown): boolean {+ if (raw === undefined || raw === null) return 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;+}+export function registerRsbWindowIpc(opts: {controller: RsbWindowController;getMainWindow: () => BrowserWindow | null;@@ -144,8 +158,8 @@ export function registerRsbWindowIpc(opts: {ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_GET_STATE, () => controller.getState());- ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_OPEN, () => {- controller.open();+ ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_OPEN, (_e, payload: unknown) => {+ controller.open({ userInitiated: parseOpenUserInitiated(payload) });});ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_CLOSE, () => {diff --git a/apps/desktop/src/main/right-sidebar-window/window.ts b/apps/desktop/src/main/right-sidebar-window/window.tsindex 61ea998314..b2f6f80617 100644--- a/apps/desktop/src/main/right-sidebar-window/window.ts+++ b/apps/desktop/src/main/right-sidebar-window/window.ts@@ -22,7 +22,19 @@ import { installSelectionContextMenu } from '../selection-context-menu.js';const log = createLogger('right-sidebar-window');-export function createRightSidebarWindow(): BrowserWindow {+export interface CreateRightSidebarWindowOptions {+ /**+ * 建窗是不是用户当次手势要求的。缺省 true = 首帧就绪后 show()(拿焦点)。+ * false(插件 preview / agent 自动化)走 showInactive():窗口照常出现在原位,+ * 但不夺走用户当前前台应用的焦点。+ */+ userInitiated?: boolean;+}++export function createRightSidebarWindow(+ options: CreateRightSidebarWindowOptions = {},+): BrowserWindow {+ const userInitiated = options.userInitiated !== false;const platformOptions =process.platform === 'darwin'? { titleBarStyle: 'hidden' as const, trafficLightPosition: { x: 12, y: 16 } }@@ -67,7 +79,9 @@ export function createRightSidebarWindow(): BrowserWindow {installExternalLinkGuards(win);win.once('ready-to-show', () => {- if (!win.isDestroyed()) win.show();+ if (win.isDestroyed()) return;+ if (userInitiated) win.show();+ else win.showInactive();});const hash = '/sidebar-window';diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 7f9fe487da..d9dc5266f7 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1146,8 +1146,12 @@ contextBridge.exposeInMainWorld('electronAPI', {rightSidebarWindow: {getState: (): Promise<{ detached: boolean; lastOpen: boolean; open: boolean }> =>ipcRenderer.invoke('maker:rsb-window:get-state'),- /** 幂等:已开则 show + focus。 */- open: (): Promise<void> => ipcRenderer.invoke('maker:rsb-window:open'),+ /**+ * 幂等开窗。缺省(用户手势)已开则 show + focus;+ * userInitiated:false(启动恢复 / 插件 / agent 自发)已开则完全不动窗口。+ */+ open: (options?: { userInitiated?: boolean }): Promise<void> =>+ ipcRenderer.invoke('maker:rsb-window:open', options),close: (): Promise<void> => ipcRenderer.invoke('maker:rsb-window:close'),/** 写偏好;true 附带开窗,false 附带关窗。返回新 state。 */setDetached: (diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex abe621fb24..e9b9d31a9a 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -686,7 +686,11 @@ export function MainLayout() {if (targetSessionId === currentSessionId) {writeCollapsedFor(targetSessionId, targetCollapsed);if (visibility === 'open') {- void window.electronAPI.rightSidebarWindow.open().catch(() => undefined);+ // 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);}@@ -832,7 +836,11 @@ export function MainLayout() {void bootstrapRsbWindowState().then((s) => {if (!s) return;if (s.detached && s.lastOpen && !s.open) {- void window.electronAPI.rightSidebarWindow.open().catch(() => undefined);+ // 启动恢复不是用户当次手势:窗口照常回到上次位置,但走 showInactive,+ // 不在冷启动瞬间把焦点从主窗(或用户别的应用)抢过去。+ void window.electronAPI.rightSidebarWindow+ .open({ userInitiated: false })+ .catch(() => undefined);}});// 插件面板独立窗口的重启恢复(同款语义,按 ghostId 逐个):detached &&diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/detachedSidebarRouting.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/detachedSidebarRouting.test.tsindex 65e25257fc..4b31f0c63b 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/detachedSidebarRouting.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/detachedSidebarRouting.test.ts@@ -39,7 +39,11 @@ describe('routeSidebarCommand', () => {const command = { type: 'open-terminal' as const, sessionId: 's1' };await expect(routeSidebarCommand(command)).resolves.toBe(result);- expect(mocks.sendCommand).toHaveBeenCalledWith({ command, allowOpen: true });+ expect(mocks.sendCommand).toHaveBeenCalledWith({+ command,+ allowOpen: true,+ userInitiated: true,+ });},);@@ -47,7 +51,11 @@ describe('routeSidebarCommand', () => {const command = { type: 'close-orca-workers-tab' as const, sessionId: 's1' };await routeSidebarCommand(command, { allowOpen: false });- expect(mocks.sendCommand).toHaveBeenCalledWith({ command, allowOpen: false });+ expect(mocks.sendCommand).toHaveBeenCalledWith({+ command,+ allowOpen: false,+ userInitiated: true,+ });});it.each([diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openInSidebarBrowser.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openInSidebarBrowser.test.tsindex 5456d9cefa..4a11a2a810 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openInSidebarBrowser.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openInSidebarBrowser.test.ts@@ -59,7 +59,24 @@ describe('openUrlInSidebarBrowser', () => {favicon: null,isAudible: false,});- expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', { sessionId: 's1' });+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {+ sessionId: 's1',+ userInitiated: true,+ });+ });++ it('插件 preview 开页(userInitiated:false)照常落标签,但不请求抢焦点', async () => {+ await openUrlInSidebarBrowser('s1', 'https://example.com/', { userInitiated: false });++ expect(routeSidebarCommand).toHaveBeenCalledWith(+ { type: 'open-web-browser', sessionId: 's1', url: 'https://example.com/' },+ { userInitiated: false },+ );+ expect(addTab).toHaveBeenCalled();+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {+ sessionId: 's1',+ userInitiated: false,+ });});it('does not request visibility when addTab rejects (caller surfaces the error)', async () => {@@ -73,15 +90,19 @@ describe('openUrlInSidebarBrowser', () => {await openUrlInSidebarBrowser('remote-lead', 'https://example.com/');- expect(routeSidebarCommand).toHaveBeenCalledWith({- type: 'open-web-browser',- sessionId: 'remote-lead',- url: 'https://example.com/',- });+ expect(routeSidebarCommand).toHaveBeenCalledWith(+ {+ type: 'open-web-browser',+ sessionId: 'remote-lead',+ url: 'https://example.com/',+ },+ { userInitiated: true },+ );expect(ensureHydrated).not.toHaveBeenCalled();expect(addTab).not.toHaveBeenCalled();expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {sessionId: 'remote-lead',+ userInitiated: true,});});diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.tsindex f641cc34eb..aa60c76242 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts@@ -14,6 +14,11 @@ import type {export interface DetachedSidebarRouteOptions {/** false 时只向已打开的 detached 窗口发命令,不因命令重新打开窗口。 */allowOpen?: boolean;+ /**+ * false = 程序自发的命令(插件 preview / agent 自动化):子窗口照常收内容,+ * 但 main 不得 show/focus 抢走用户前台。缺省 true(用户手势)。+ */+ userInitiated?: boolean;}export async function routeSidebarCommand(@@ -23,5 +28,9 @@ export async function routeSidebarCommand(if (typeof window === 'undefined' || isSecondaryWindow() || isSidebarWindow()) return 'attached';const api = window.electronAPI?.rightSidebarWindow;if (!api) return 'attached';- return api.sendCommand({ command, allowOpen: opts.allowOpen !== false });+ return api.sendCommand({+ command,+ allowOpen: opts.allowOpen !== false,+ userInitiated: opts.userInitiated !== false,+ });}diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.tsindex 5ca1825f0e..d63a3b8e42 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts@@ -36,16 +36,32 @@ export function pathToFileUrl(absPath: string): string {return `file://${encoded}`;}+export interface OpenUrlInSidebarBrowserOptions {+ /**+ * false = 不是用户当次手势(插件 preview 槽开页):标签照常开、内容照常加载,+ * 但 detached 形态下不得把子窗口 show + focus 抢走用户前台。缺省 true。+ */+ userInitiated?: boolean;+}+/** 在指定 session 的侧边栏浏览器里新开一个页签加载 url,并确保侧边栏可见。 */-export async function openUrlInSidebarBrowser(sessionId: string, url: string): Promise<void> {- const routeResult = await routeSidebarCommand({- type: 'open-web-browser',- sessionId,- url,- });+export async function openUrlInSidebarBrowser(+ sessionId: string,+ url: string,+ options: OpenUrlInSidebarBrowserOptions = {},+): Promise<void> {+ const userInitiated = options.userInitiated !== false;+ const routeResult = await routeSidebarCommand(+ {+ type: 'open-web-browser',+ sessionId,+ url,+ },+ { userInitiated },+ );if (routeResult !== 'attached') {if (routeResult !== 'routed') return;- requestRightSidebarVisibility('open', { sessionId });+ requestRightSidebarVisibility('open', { sessionId, userInitiated });return;}// store.addTab 的乐观写以 bucket 已 hydrate 为前提(见 store 内@@ -61,5 +77,5 @@ export async function openUrlInSidebarBrowser(sessionId: string, url: string): Pfavicon: null,isAudible: false,});- requestRightSidebarVisibility('open', { sessionId });+ requestRightSidebarVisibility('open', { sessionId, userInitiated });}diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.tsindex 94bb07cfa6..d39c37788e 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts@@ -389,7 +389,9 @@ async function handleTabOpRequest(// Visibility command runs AFTER the eager-spawn so that by the time// MainLayout reads the new collapsed-state archive (when user later// switches to this session), the webview is already prepared.- requestRightSidebarVisibility('open', { sessionId: req.sessionId });+ // userInitiated:false —— agent 自动化开的标签,不是用户点的:侧边栏该展开+ // 就展开,但 detached 子窗口不得抢走用户当前前台应用的焦点。+ requestRightSidebarVisibility('open', { sessionId: req.sessionId, userInitiated: false });result = { reqId, ok: true, tabId: newTab.id };} else if (req.op === 'focus') {// store.setActiveTab no-ops if the id is already active (returns void on@@ -400,8 +402,9 @@ async function handleTabOpRequest(result = { reqId, ok: false, error: `tab ${req.tabId} not found` };} else {await setActiveTab(req.sessionId, req.tabId);- // Same rationale as open: focus implies the user should see the tab.- requestRightSidebarVisibility('open', { sessionId: req.sessionId });+ // Same rationale as open: focus implies the user should see the tab —+ // but it's still the agent acting, so no OS-level focus steal.+ requestRightSidebarVisibility('open', { sessionId: req.sessionId, userInitiated: false });result = { reqId, ok: true, tabId: req.tabId };}} else if (req.op === 'ensure') {diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.tsindex 2816ff27c7..921c1f949e 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts@@ -55,6 +55,15 @@ export type SidebarVisibilityRequest = 'open' | 'close';export interface SidebarVisibilityRequestOptions {sessionId?: string;animate?: boolean;+ /**+ * 这次请求是不是用户当次手势直接要求的。缺省 true —— 既有调用点几乎全是+ * 用户手势(点链接 / 菜单 / 按钮),观感不变。+ *+ * 程序自发的请求(插件 preview 槽开页、agent 浏览器自动化 tab-op)必须传+ * false:detached 形态下订阅方只更新折叠存档 / 送内容,**不得**把子窗口+ * show + focus 抢走用户当前前台应用(Windows 上 focus() 就是抢前台)。+ */+ userInitiated?: boolean;}type Listener = (diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/__tests__/actions.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/__tests__/actions.test.tsindex f97fed16d6..857aa018ac 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/__tests__/actions.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/__tests__/actions.test.ts@@ -328,6 +328,7 @@ describe('orca-workers tab actions', () => {focusTab: false,},allowOpen: false,+ userInitiated: true,});expect(getBucket('s1').tabs).toEqual([]);expect(tabsIpc.upsert).not.toHaveBeenCalled();@@ -357,6 +358,7 @@ describe('orca-workers tab actions', () => {focusTab: true,},allowOpen: true,+ userInitiated: true,});});@@ -369,6 +371,7 @@ describe('orca-workers tab actions', () => {expect(mocks.sendCommand).toHaveBeenNthCalledWith(1, {command: { type: 'ensure-orca-workers-tab', sessionId: 's1', focusTab: false },allowOpen: false,+ userInitiated: true,});expect(mocks.sendCommand).toHaveBeenNthCalledWith(2, {command: {@@ -378,6 +381,7 @@ describe('orca-workers tab actions', () => {focusTab: false,},allowOpen: false,+ userInitiated: true,});});@@ -400,6 +404,7 @@ describe('orca-workers tab actions', () => {focusTab: true,},allowOpen: true,+ userInitiated: true,});expect(requests).toEqual([{ visibility: 'open', opts: { sessionId: 's1' } }]);expect(getBucket('s1').tabs).toEqual([]);@@ -414,6 +419,7 @@ describe('orca-workers tab actions', () => {expect(mocks.sendCommand).toHaveBeenCalledWith({command: { type: 'close-orca-workers-tab', sessionId: 's1' },allowOpen: false,+ userInitiated: true,});expect(tabsIpc.close).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 00b4eda875..0b14957315 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -4445,7 +4445,10 @@ function initGlobalListeners(): void {} | null;if (!p || typeof p.name !== 'string') return;if (typeof p.sessionId !== 'string' || typeof p.url !== 'string') return;- void openUrlInSidebarBrowser(p.sessionId, p.url).catch(() => {+ // userInitiated:false —— 这是插件在后台干完活自己要求开的页,不是用户点的。+ // 标签照常落地、内容照常加载,但不得把侧边栏子窗口抢到前台打断用户+ // (detached 形态 + Windows 上 focus() 即抢前台)。+ void openUrlInSidebarBrowser(p.sessionId, p.url, { userInitiated: false }).catch(() => {/* 标签落地失败(会话桶异常等)不致命,静默 */});toast.info(i18n.t('chat.ghostPreview.opened'), {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex b352d48cf1..81eeef5e16 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1407,8 +1407,11 @@ interface ElectronAPI {// 「侧边栏在新窗口中显示」偏好 + 子窗口生命周期(main: right-sidebar-window/)。rightSidebarWindow: {getState: () => Promise<{ detached: boolean; lastOpen: boolean; open: boolean }>;- /** 幂等:已开则 show + focus。 */- open: () => Promise<void>;+ /**+ * 幂等开窗。缺省(用户手势)已开则 show + focus;+ * userInitiated:false(启动恢复 / 插件 / agent 自发)已开则完全不动窗口。+ */+ open: (options?: { userInitiated?: boolean }) => Promise<void>;close: () => Promise<void>;/** 写偏好;true 附带开窗,false 附带关窗。返回新 state。 */setDetached: (diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.tsindex 6d391b81f2..aa54b10f59 100644--- a/apps/desktop/src/shared/rightSidebarWindow.ts+++ b/apps/desktop/src/shared/rightSidebarWindow.ts@@ -61,6 +61,15 @@ export interface RsbWindowCommandRouteRequest {command: RsbWindowCommand;/** false 时 detached host 关闭/未 ready 不得重开,main 会保存 intent。 */allowOpen: boolean;+ /**+ * 这条命令是不是用户当次手势直接要求的(点链接 / 点菜单 / 点按钮)。+ *+ * 缺省 true —— 绝大多数调用点都是用户手势,保持既有「带出子窗口」观感。+ * 插件 preview 槽开页、agent 浏览器自动化这类**程序自发**的命令必须显式传+ * false:内容照常送进子窗口,但不得 show/focus 抢走用户当前前台应用+ * (Windows 上 focus() 就是抢前台,后台干活弹窗口是硬伤)。+ */+ userInitiated?: boolean;}/** main-owned 宿主裁决;renderer 只有 attached 可以写本地 store。 */