Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): secure detached workbench actions
nothingyuancandoa5ee2f2fab38
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 1e6de79d3d..43c110ad5b 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -756,7 +756,7 @@ import { SidebarTabWindowsController } from './sidebar-tab-window/controller.js'import { resolveWindowBoundsNearPoint } from './windowBounds.js';import { createSidebarTabWindow } from './sidebar-tab-window/window.js';import { registerSidebarTabWindowIpc } from './sidebar-tab-window/ipc.js';-import { setRightSidebarTabsChangeBroadcaster } from './localDb/ipc/rightSidebarTabs.js';+import { hasAssignedBotWorkbenchTab, setRightSidebarTabsChangeBroadcaster } from './localDb/ipc/rightSidebarTabs.js';import {readRsbWindowSettings,resetRsbWindowSettingsForStartup,@@ -764,6 +764,7 @@ import {} from './right-sidebar-window/settings-store.js';import {anySessionInTurn,+ allowBotWorkbenchPendingPermission,applyCodexSpawnConfigChangeWithRestart,clearDeferredCodexRestartForOwnerBoundary,scheduleDeferredCodexRestart,@@ -2293,6 +2294,18 @@ const rsbWindowController = new RsbWindowController({registerRsbWindowIpc({controller: rsbWindowController,getMainWindow: () => mainWindowRef,+ allowBotWorkbenchPermission: allowBotWorkbenchPendingPermission,+ authorizePoppedWorkbench: async (sender, botId) => {+ const slot = sidebarTabWindowsController.slotForSender(sender);+ if (!slot?.visible) return false;+ const assignment = slot.assignment;+ if (!assignment?.sessionId || assignment.context.remoteHostId !== null) return false;+ const owner = await resolveRsbHostContextFromSession(assignment.sessionId);+ if (owner?.botOwner?.botId !== botId || !owner.botOwner.canonical || owner.remoteHostId !== null) return false;+ const hasTab = await hasAssignedBotWorkbenchTab(assignment.sessionId, assignment.tabs.map((tab) => tab.tabId), botId);+ return hasTab && slot.visible && slot.assignment === assignment &&+ sidebarTabWindowsController.slotForSender(sender) === slot;+ },});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.tsindex 053612e4c6..5cda8e0d72 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts@@ -35,7 +35,7 @@ vi.mock('../../client/current.js', () => ({getDbClient: () => ({ drizzle: h.db }),}));-import { registerRightSidebarTabsIpc } from '../rightSidebarTabs.js';+import { hasAssignedBotWorkbenchTab, registerRightSidebarTabsIpc } from '../rightSidebarTabs.js';import { assertTrustedAppRendererEvent } from '../../../security/trustedAppRenderer.js';function createDb(): Database.Database {@@ -93,6 +93,16 @@ describe('rightSidebarTabs IPC', () => {registerRightSidebarTabsIpc();});+ it('matches a popped-out Bot workbench only by session, assigned tab and Bot id', async () => {+ await invoke('local-db:right-sidebar-tabs:upsert', {+ id: 'workbench-1', sessionId: 's1', kind: 'bot-workbench', position: 0, state: { botId: 'bot-1' },+ });+ expect(await hasAssignedBotWorkbenchTab('s1', ['workbench-1'], 'bot-1')).toBe(true);+ expect(await hasAssignedBotWorkbenchTab('s1', ['other-tab'], 'bot-1')).toBe(false);+ expect(await hasAssignedBotWorkbenchTab('s1', ['workbench-1'], 'bot-2')).toBe(false);+ expect(await hasAssignedBotWorkbenchTab('s2', ['workbench-1'], 'bot-1')).toBe(false);+ });+it('rejects every read and write handler before parsing untrusted payloads', async () => {vi.mocked(assertTrustedAppRendererEvent).mockImplementation(() => {throw new Error('UNTRUSTED_RENDERER');diff --git a/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts b/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.tsindex 947296296d..123b040239 100644--- a/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts+++ b/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts@@ -95,6 +95,19 @@ function rowToTab(row: typeof rightSidebarTabs.$inferSelect): TabRow {};}+/** Main-only check for the narrow permission action from a popped-out workbench tab. */+export async function hasAssignedBotWorkbenchTab(sessionId: string, tabIds: readonly string[], botId: string): Promise<boolean> {+ if (tabIds.length === 0) return false;+ const ids = new Set(tabIds);+ const rows = await getDbClient().drizzle.select({+ id: rightSidebarTabs.id,+ kind: rightSidebarTabs.kind,+ state: rightSidebarTabs.state,+ }).from(rightSidebarTabs).where(eq(rightSidebarTabs.sessionId, sessionId));+ return rows.some((row) => ids.has(row.id) && row.kind === 'bot-workbench' &&+ (parseState(row.state) as { botId?: unknown } | null)?.botId === botId);+}+function requireInt(value: unknown, name: string): number {if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {throwIpcError('INVALID_PARAMS', `${name} must be a non-negative integer`);diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 95df22c4b5..60b644c86a 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -756,6 +756,7 @@ export const MAKER_INVOKE = {RSB_WINDOW_CLOSE: 'maker:rsb-window:close',RSB_WINDOW_SET_DETACHED: 'maker:rsb-window:set-detached',RSB_WINDOW_GET_CONTEXT: 'maker:rsb-window:get-context',+ RSB_WINDOW_ALLOW_BOT_WORKBENCH_PERMISSION: 'maker:rsb-window:allow-bot-workbench-permission',RSB_WINDOW_READY: 'maker:rsb-window:ready',RSB_WINDOW_SEND_COMMAND: 'maker:rsb-window:send-command',/**diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 2132346b9b..bd4beee3de 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -39,7 +39,7 @@ import { getManagedLlamaCppService } from '../local-model-runtime/llamaCppServicimport { ensureManagedLlamaCppProvider } from '../local-model-runtime/managedLlamaCppProvider.js';import { setBotRemoteMessageService } from './botRemoteMessageReceiver.js';import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';-import { configureBotAutonomyHost, noteBotAutonomyInputProjection } from '../bot-autonomy/hub.js';+import { configureBotAutonomyHost, getBotAutonomyGlance, noteBotAutonomyInputProjection } from '../bot-autonomy/hub.js';import { getHostSourceDevice, getSelfDeviceId, remoteBackgroundInvoke, remoteInvoke as invokeBotPeer } from '../device-link/index.js';import { readDeviceProviderViews } from '../remote-agent/controller/deviceCatalog.js';import { checkDeviceRoute } from '../remote-agent/controller/deviceRouteCheck.js';@@ -3519,6 +3519,19 @@ function cancelPendingInteraction(requestId: string, decision: InteractionDecisireturn resolvePendingInteraction(requestId, decision, true);}+/** Narrow detached-workbench action: the Bot's live glance must still own this exact local permission. */+export function allowBotWorkbenchPendingPermission(botId: string, sessionId: string, requestId: string): { accepted: boolean } {+ const row = getBotAutonomyGlance(botId).waiting.find((item) =>+ item.deviceId === null && item.sessionId === sessionId &&+ item.requestId === requestId && item.waitingFor === 'permission');+ const pending = pendingInteractionResolvers.get(requestId);+ if (!row || !pending || pending.sessionId !== sessionId || pending.kind !== 'permission' ||+ pending.request.kind !== 'permission' || pending.request.requestId !== requestId) {+ return { accepted: false };+ }+ return { accepted: resolvePendingInteraction(requestId, { kind: 'permission', behavior: 'allow' }) };+}+function resolvePendingInteraction(requestId: string, decision: InteractionDecision, fromShared = false): boolean {const resolver = pendingInteractionResolvers.get(requestId);if (!resolver || (!fromShared && agentInputCoordinatorHolder?.isExecutionPaused(resolver.sessionId))) return false;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 c510b14979..f76024f2ab 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@@ -12,6 +12,7 @@ vi.mock('electron', () => {},};});+vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: vi.fn() }));import { ipcMain, type BrowserWindow } from 'electron';@@ -21,7 +22,9 @@ import type { RsbWindowController } from '../controller.js';type RsbWindowControllerMock = RsbWindowController & {getState: ReturnType<typeof vi.fn>;+ getContext: ReturnType<typeof vi.fn>;getSidebarWebContents: ReturnType<typeof vi.fn>;+ getVisibleSidebarWebContents: ReturnType<typeof vi.fn>;routeCommand: ReturnType<typeof vi.fn>;};@@ -33,6 +36,7 @@ function makeController() {setDetached: vi.fn(),getContext: vi.fn(),getSidebarWebContents: vi.fn(),+ getVisibleSidebarWebContents: vi.fn(),markReady: vi.fn(),markRendererReady: vi.fn(),markPresentationReady: vi.fn(),@@ -59,7 +63,7 @@ function registerController(controller: RsbWindowController) {isDestroyed: () => false,webContents: mainWebContents,} as unknown as BrowserWindow;- registerRsbWindowIpc({ controller, getMainWindow: () => mainWindow });+ registerRsbWindowIpc({ controller, getMainWindow: () => mainWindow, allowBotWorkbenchPermission: vi.fn(() => ({ accepted: true })) });return { handler: getSendCommandHandler(), mainWebContents };}@@ -70,6 +74,39 @@ beforeEach(() => {});describe('right-sidebar-window IPC', () => {+ it('allows only the visible detached Bot owner to approve its own permission', async () => {+ const controller = makeController();+ const sender = { id: 2 };+ const approve = vi.fn(() => ({ accepted: true }));+ controller.getVisibleSidebarWebContents.mockReturnValue(sender);+ controller.getContext.mockReturnValue({ botOwner: { botId: 'bot-1', canonical: true }, remoteHostId: null });+ registerRsbWindowIpc({ controller, getMainWindow: () => null, allowBotWorkbenchPermission: approve });+ const handler = (ipcMain as unknown as { __handlers: Map<string, (e: unknown, p: unknown) => unknown> })+ .__handlers.get(MAKER_INVOKE.RSB_WINDOW_ALLOW_BOT_WORKBENCH_PERMISSION)!;+ const payload = { botId: 'bot-1', sessionId: 'task-1', requestId: 'permission-1' };+ await expect(handler({ sender }, payload)).resolves.toEqual({ accepted: true });+ expect(approve).toHaveBeenCalledWith('bot-1', 'task-1', 'permission-1');+ await expect(handler({ sender: { id: 3 } }, payload)).resolves.toEqual({ accepted: false });+ await expect(handler({ sender }, { ...payload, botId: 'bot-2' })).resolves.toEqual({ accepted: false });+ await expect(handler({ sender }, { ...payload, requestId: '' })).rejects.toThrow(/requestId/);+ expect(approve).toHaveBeenCalledTimes(1);+ });+ it('accepts a popped-out workbench only after Main verifies the assigned tab', async () => {+ const controller = makeController();+ const sender = { id: 4 };+ const approve = vi.fn(() => ({ accepted: true }));+ const authorizePoppedWorkbench = vi.fn(async () => true);+ registerRsbWindowIpc({ controller, getMainWindow: () => null,+ allowBotWorkbenchPermission: approve, authorizePoppedWorkbench });+ const handler = (ipcMain as unknown as { __handlers: Map<string, (e: unknown, p: unknown) => unknown> })+ .__handlers.get(MAKER_INVOKE.RSB_WINDOW_ALLOW_BOT_WORKBENCH_PERMISSION)!;+ const payload = { botId: 'bot-1', sessionId: 'task-1', requestId: 'permission-1' };+ await expect(handler({ sender }, payload)).resolves.toEqual({ accepted: true });+ expect(authorizePoppedWorkbench).toHaveBeenCalledWith(sender, 'bot-1');+ authorizePoppedWorkbench.mockResolvedValue(false);+ await expect(handler({ sender }, payload)).resolves.toEqual({ accepted: false });+ expect(approve).toHaveBeenCalledTimes(1);+ });// The mail card gesture must survive detached-window routing without mail content.it('routes a mail card by ID and rejects malformed card references', async () => {const controller = makeController();diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.tsindex 0f92a689fc..2c53d144ad 100644--- a/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts@@ -225,10 +225,11 @@ describe('sidebarWindowPreload 椤跺眰濂戠害', () => {expect(botsKeys).toEqual(['autonomy']);expect(botAutonomyKeys).toEqual(['glance']);expect(makerKeys).toEqual(expect.arrayContaining([- 'onBotAutonomyChanged', 'getPendingInteractions', 'resolveInteraction',+ 'onBotAutonomyChanged', 'getPendingInteractions', 'allowBotWorkbenchPermission',]));+ expect(makerKeys).not.toContain('resolveInteraction');expect(source).toContain("ipcRenderer.invoke('local-db:bots:autonomy:glance', botId)");- expect(source).toContain("ipcRenderer.invoke('maker:resolve-interaction', requestId, decision)");+ expect(source).toContain("ipcRenderer.invoke('maker:rsb-window:allow-bot-workbench-permission', { botId, sessionId, requestId })");});it('涓嶆毚闇?maker / agent / voice / login 鑷不鑳藉姏', () => {diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.tsindex eb5bb142f5..0382d2d102 100644--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts@@ -7,11 +7,12 @@*/import { ipcMain } from 'electron';-import type { BrowserWindow } from 'electron';+import type { BrowserWindow, WebContents } from 'electron';import type { SubagentProvider } from '@cindy/maker-shared/subagent-workspace';import { MAKER_INVOKE, MAKER_SEND } from '../maker-ipc/channels.js';import { createLogger } from '../logger.js';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { requireEnum, requireObject, throwIpcError } from '../utils/ipcValidate.js';import type {RsbWindowCommand,@@ -383,8 +384,29 @@ function parseTabHandoff(raw: unknown): RsbWindowTabHandoff | undefined {export function registerRsbWindowIpc(opts: {controller: RsbWindowController;getMainWindow: () => BrowserWindow | null;+ allowBotWorkbenchPermission: (botId: string, sessionId: string, requestId: string) => { accepted: boolean };+ authorizePoppedWorkbench?: (sender: WebContents, botId: string) => Promise<boolean>;}): void {- const { controller, getMainWindow } = opts;+ const { controller, getMainWindow, allowBotWorkbenchPermission, authorizePoppedWorkbench } = opts;++ ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_ALLOW_BOT_WORKBENCH_PERMISSION, async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ const request = requireObject(raw, 'workbench permission');+ for (const key of ['botId', 'sessionId', 'requestId'] as const) {+ if (typeof request[key] !== 'string' || !request[key] || request[key].length > 128) {+ throwIpcError('INVALID_PARAMS', `${key} must be a 1–128 character string`);+ }+ }+ const context = event.sender === controller.getVisibleSidebarWebContents() ? controller.getContext() : null;+ const botOwner = context?.botOwner;+ const authorizedSidebar = Boolean(botOwner && botOwner.botId === request.botId &&+ botOwner.canonical && context?.remoteHostId === null);+ const authorizedPopout = !authorizedSidebar && await authorizePoppedWorkbench?.(event.sender, request.botId as string);+ if (!authorizedSidebar && !authorizedPopout) {+ return { accepted: false };+ }+ return allowBotWorkbenchPermission(request.botId as string, request.sessionId as string, request.requestId as string);+ });ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_GET_STATE, () => controller.getState());diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex e5bfd2044c..6b4b23d9ac 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -613,11 +613,12 @@ contextBridge.exposeInMainWorld('electronAPI', {maker: {onBotAutonomyChanged: (cb: (payload: { botIds?: string[] }) => void): (() => void) =>onPayload('maker:bot-autonomy:changed', cb),- resolveInteraction: (+ allowBotWorkbenchPermission: (+ botId: string,+ sessionId: string,requestId: string,- decision: Record<string, unknown>,): Promise<{ accepted: boolean }> =>- ipcRenderer.invoke('maker:resolve-interaction', requestId, decision),+ ipcRenderer.invoke('maker:rsb-window:allow-bot-workbench-permission', { botId, sessionId, requestId }),// Live event subset consumed by makerChatStore in the detached renderer.onEvent: (cb: (payload: unknown) => void): (() => void) => onPayload('maker:event', cb),onStatusChanged: (cb: (payload: unknown) => void): (() => void) =>diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsxindex 4bc9412595..4db5394bca 100644--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useId, useMemo, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router-dom';+import { useInRouterContext, useNavigate, type NavigateFunction } from 'react-router-dom';import { Button } from '@/components/ui/button';import { Spinner } from '@/components/ui/spinner';@@ -65,6 +65,7 @@ function listFormat(items: string[], language: string): string {const join = (...parts: Array<string | null | undefined | false>) => parts.filter(Boolean).join(' · ');interface RowContext {+ botId: string;t: Translate;/** 自上次读到 glance 以来过去了几分钟,行上的时长按它往后推。 */elapsedMinutes: number;@@ -74,17 +75,28 @@ interface RowContext {onOpen: (row: GlanceRow) => void;}-export function BotWorkbench({- botId,- hostDeviceId = null,-}: {+type BotWorkbenchProps = {botId: string;sessionId?: string;- /** 伙伴所在电脑;null = 这台。 */hostDeviceId?: string | null;-}) {+};++export function BotWorkbench(props: BotWorkbenchProps) {+ return useInRouterContext()+ ? <RoutedBotWorkbench {...props} />+ : <BotWorkbenchContent {...props} navigate={null} />;+}++function RoutedBotWorkbench(props: BotWorkbenchProps) {+ return <BotWorkbenchContent {...props} navigate={useNavigate()} />;+}++function BotWorkbenchContent({+ botId,+ hostDeviceId = null,+ navigate,+}: BotWorkbenchProps & { navigate: NavigateFunction | null }) {const { t, i18n } = useTranslation();- const navigate = useNavigate();const devices = useDeviceLinkDeviceList();const self = devices?.find((device) => device.isSelf) ?? null;const hostDevice = hostDeviceId ? (devices?.find((device) => device.deviceId === hostDeviceId) ?? null) : null;@@ -104,7 +116,7 @@ export function BotWorkbench({[raw, host, hostOnline],);const now = useNow(30_000);- const canNavigate = !isSidebarWindow();+ const canNavigate = navigate !== null && !isSidebarWindow();const onOpen = useCallback((row: GlanceRow) => {@@ -112,7 +124,7 @@ export function BotWorkbench({const owner = getDataOwnerGeneration();void glanceSessionRoute(row).then((route) => {- if (isDataOwnerGenerationCurrent(owner)) navigate(route);+ if (isDataOwnerGenerationCurrent(owner)) navigate?.(route);}).catch(() => undefined);},@@ -136,6 +148,7 @@ export function BotWorkbench({const rows = [...glance.waiting, ...glance.working];const showDevices = rows.some((row) => row.deviceId);const ctx: RowContext = {+ botId,t,elapsedMinutes: fetchedAt > 0 ? Math.max(0, Math.floor((now - fetchedAt) / 60_000)) : 0,deviceLabel: (row) =>@@ -258,7 +271,7 @@ function WaitingRow({ row, ctx }: { row: GlanceRow; ctx: RowContext }) {const allow = () => {if (allowing) return;setAllowing(true);- void allowGlanceRow(row)+ void allowGlanceRow(row, ctx.botId).then((outcome) => {if (outcome === 'gone') ctx.onOpen(row);else if (outcome === 'blocked') toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsxindex 4ac130f868..ceb75cfc98 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx@@ -12,6 +12,8 @@ import type { BotGlance, GlanceRow } from '../../../../shared/botAutonomy';const m = vi.hoisted(() => ({navigate: vi.fn(),+ hasRouter: true,+ sidebar: false,toastWarning: vi.fn(),toastError: vi.fn(),remoteApi: { getPendingInteractions: vi.fn(), resolveInteraction: vi.fn() },@@ -29,7 +31,7 @@ function deviceList(studio: Record<string, unknown> = {}) {{ deviceId: 'dev-2', name: 'Studio', isSelf: false, ...controllable, ...studio },];}-vi.mock('react-router-dom', () => ({ useNavigate: () => m.navigate }));+vi.mock('react-router-dom', () => ({ useInRouterContext: () => m.hasRouter, useNavigate: () => m.navigate }));vi.mock('react-i18next', () => ({useTranslation: () => ({t: (key: string, values?: Record<string, unknown>) =>@@ -41,7 +43,7 @@ vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({useDeviceLinkDeviceList: () => m.devices,}));vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));-vi.mock('@/lib/sidebarWindow', () => ({ isSidebarWindow: () => false }));+vi.mock('@/lib/sidebarWindow', () => ({ isSidebarWindow: () => m.sidebar }));vi.mock('@/lib/orcaSessionIdentity', () => ({ resolveSessionRoute: m.resolveRoute }));vi.mock('@/features/device-link/remoteProjectsStore', () => ({remoteProjectsStore: { pinSessionOrigin: m.pinSessionOrigin, getMergedRemoteSessions: () => m.mirrored },@@ -55,7 +57,7 @@ import { allowGlanceRow } from '../botGlance';type Listener = (payload: { botIds?: string[] }) => void;let listeners: Listener[] = [];const glanceApi = vi.fn<(botId: string) => Promise<BotGlance>>();-const localMaker = { getPendingInteractions: vi.fn(), resolveInteraction: vi.fn() };+const localMaker = { getPendingInteractions: vi.fn(), resolveInteraction: vi.fn(), allowBotWorkbenchPermission: vi.fn() };const remoteInvoke = vi.fn();function row(patch: Partial<GlanceRow>): GlanceRow {@@ -84,6 +86,8 @@ function permission(requestId: string) {beforeEach(() => {vi.clearAllMocks();+ m.hasRouter = true;+ m.sidebar = false;listeners = [];m.makerApiForDevice.mockReturnValue(m.remoteApi);m.mirrored = [];@@ -148,6 +152,21 @@ it('allows only the permission request the row points at, and opens the task wheexpect(localMaker.resolveInteraction).toHaveBeenCalledTimes(1);});+it('renders without a Router in the detached sidebar and uses only its narrow permission bridge', async () => {+ m.hasRouter = false;+ m.sidebar = true;+ glanceApi.mockResolvedValue(glance({ waiting: [row({ waitingFor: 'permission', requestId: 'r-2' })] }));+ localMaker.allowBotWorkbenchPermission.mockResolvedValue({ accepted: true });+ render(<BotWorkbench botId="bot-1" />);++ const waiting = (await screen.findByText('修登录超时')).closest('li')!;+ fireEvent.click(within(waiting).getByRole('button', { name: 'bots.workbench.glance.allow' }));+ await waitFor(() => expect(localMaker.allowBotWorkbenchPermission).toHaveBeenCalledWith('bot-1', 's1', 'r-2'));+ expect(localMaker.getPendingInteractions).not.toHaveBeenCalled();+ expect(localMaker.resolveInteraction).not.toHaveBeenCalled();+ expect(m.navigate).not.toHaveBeenCalled();+});+it('opens a task on another computer through the device-aware route, not a same-id local lookup', async () => {glanceApi.mockResolvedValue(glance({waiting: [diff --git a/apps/desktop/src/renderer/features/bots/botGlance.ts b/apps/desktop/src/renderer/features/bots/botGlance.tsindex f9f30f8645..e7a7f2efa5 100644--- a/apps/desktop/src/renderer/features/bots/botGlance.ts+++ b/apps/desktop/src/renderer/features/bots/botGlance.ts@@ -12,6 +12,7 @@ import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contextsimport { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';+import { isSidebarWindow } from '@/lib/sidebarWindow';import { BOT_AUTONOMY_IPC, type BotGlance, type GlanceRow } from '../../../shared/botAutonomy';export interface GlanceState {@@ -154,11 +155,16 @@ export type AllowOutcome = 'allowed' | 'gone' | 'blocked' | 'failed';* 「允许」:只回应这一行对应的那条权限请求,本机走本机宿主,别的电脑走 device-link 隧道到那台。* 请求已经不在(被处理、被换掉)或行上没有请求 id 时不替主人批准别的请求,交给调用方改为「去任务里看」。*/-export async function allowGlanceRow(row: GlanceRow): Promise<AllowOutcome> {+export async function allowGlanceRow(row: GlanceRow, botId?: string): Promise<AllowOutcome> {// 没有具体请求 id(例如按「需要确认」归成权限类的交互)时不替主人批准任何一条,交给调用方打开任务。if (!row.requestId) return 'gone';if (row.deviceId && !row.online) return 'blocked';const sessionId = bareGlanceSessionId(row);+ if (!row.deviceId && isSidebarWindow()) {+ if (!botId) return 'failed';+ const receipt = await window.electronAPI.maker.allowBotWorkbenchPermission(botId, sessionId, row.requestId);+ return receipt?.accepted === true ? 'allowed' : 'gone';+ }const api = row.deviceId? (await import('@/lib/makerTransport')).makerApiForDevice(row.deviceId): window.electronAPI.maker;diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex fd11c172ab..551b27a702 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -6435,6 +6435,8 @@ interface ElectronAPI {persistId?: string;}>>;+ /** Detached Bot workbench only: approve its current local permission row. */+ allowBotWorkbenchPermission: (botId: string, sessionId: string, requestId: string) => Promise<{ accepted: boolean }>;// ── 运行时切换 (Stage 2 B) ─────────────────────────────────────────────// session 不存在(没 send 过/已 close)时 main 侧 no-op,renderer 可乐观调用。