Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复本地页面无法在系统浏览器打开 (#1530)
Dash64d8f96fdf23
diff --git a/apps/desktop/src/main/__tests__/openFileInBrowser.test.ts b/apps/desktop/src/main/__tests__/openFileInBrowser.test.tsnew file mode 100644index 0000000000..61677b9bac--- /dev/null+++ b/apps/desktop/src/main/__tests__/openFileInBrowser.test.ts@@ -0,0 +1,122 @@+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { describe, expect, it, vi } from 'vitest';++import {+ handleOpenFileInBrowser,+ resolveBrowserFileTarget,+ type OpenFileInBrowserDeps,+} from '../openFileInBrowser.js';++function harness(overrides: Partial<OpenFileInBrowserDeps> = {}) {+ const deps: OpenFileInBrowserDeps = {+ isPathAllowed: vi.fn(() => true),+ isBrowserOpenablePath: vi.fn(() => true),+ existsSync: vi.fn(() => true),+ openExternal: vi.fn(async () => undefined),+ openPath: vi.fn(async () => ''),+ openUrlWithWindowsHandler: vi.fn(async () => undefined),+ onOpenExternalError: vi.fn(),+ onWindowsUrlFallbackError: vi.fn(),+ ...overrides,+ };+ return deps;+}++describe('resolveBrowserFileTarget', () => {+ it('keeps query and hash on a local file URL while resolving its path', () => {+ const filePath = path.resolve('/tmp', 'preview page.html');+ const url = pathToFileURL(filePath);+ url.search = '?mode=review';+ url.hash = '#/section';++ expect(resolveBrowserFileTarget(url.toString())).toEqual({+ filePath,+ fileUrl: url.toString(),+ hasUrlState: true,+ });+ });++ it('rejects non-local file authorities and non-file URLs', () => {+ expect(resolveBrowserFileTarget('file://server/share/index.html')).toBeNull();+ expect(resolveBrowserFileTarget('file://localhost:8080/tmp/index.html')).toBeNull();+ expect(resolveBrowserFileTarget('https://example.test/index.html')).toBeNull();+ });+});++describe('handleOpenFileInBrowser', () => {+ it('opens a full local file URL without dropping query or hash', async () => {+ const filePath = path.resolve('/tmp', 'preview.html');+ const url = pathToFileURL(filePath);+ url.search = '?mode=review';+ url.hash = '#/section';+ const deps = harness();++ await expect(handleOpenFileInBrowser(url.toString(), deps)).resolves.toEqual({+ success: true,+ });++ expect(deps.isPathAllowed).toHaveBeenCalledWith(filePath);+ expect(deps.openExternal).toHaveBeenCalledWith(url.toString());+ expect(deps.openPath).not.toHaveBeenCalled();+ });++ it('keeps legacy absolute paths and falls back to openPath', async () => {+ const filePath = path.resolve('/tmp', 'preview.html');+ const deps = harness({+ openExternal: vi.fn(async () => {+ throw new Error('file URL unavailable');+ }),+ });++ await expect(handleOpenFileInBrowser(filePath, deps)).resolves.toEqual({ success: true });++ expect(deps.openExternal).toHaveBeenCalledWith(pathToFileURL(filePath).toString());+ expect(deps.openPath).toHaveBeenCalledWith(filePath);+ });++ it('uses the Windows URL fallback without dropping query or hash', async () => {+ const url = pathToFileURL(path.resolve('/tmp', 'preview.html'));+ url.search = '?mode=review';+ url.hash = '#/section';+ const deps = harness({+ openExternal: vi.fn(async () => {+ throw new Error('file URL unavailable');+ }),+ });++ await expect(handleOpenFileInBrowser(url.toString(), deps)).resolves.toEqual({+ success: true,+ });+ expect(deps.openUrlWithWindowsHandler).toHaveBeenCalledWith(url.toString());+ expect(deps.openPath).not.toHaveBeenCalled();+ });++ it('does not discard URL state when openExternal fails', async () => {+ const url = pathToFileURL(path.resolve('/tmp', 'preview.html'));+ url.hash = '#/section';+ const deps = harness({+ openExternal: vi.fn(async () => {+ throw new Error('browser rejected URL');+ }),+ openUrlWithWindowsHandler: undefined,+ });++ await expect(handleOpenFileInBrowser(url.toString(), deps)).resolves.toEqual({+ success: false,+ error: '无法在系统浏览器中打开该本地页面',+ errorCode: 'BROWSER_FILE_OPEN_FAILED',+ });+ expect(deps.openPath).not.toHaveBeenCalled();+ });++ it('returns a localized error for invalid input', async () => {+ await expect(+ handleOpenFileInBrowser('https://example.test/index.html', harness()),+ ).resolves.toEqual({+ success: false,+ error: '路径必须是绝对路径或本地 file:// URL',+ errorCode: 'BROWSER_FILE_INVALID_TARGET',+ });+ });+});diff --git a/apps/desktop/src/main/__tests__/windowsFileUrlOpener.test.ts b/apps/desktop/src/main/__tests__/windowsFileUrlOpener.test.tsnew file mode 100644index 0000000000..cafe159b9c--- /dev/null+++ b/apps/desktop/src/main/__tests__/windowsFileUrlOpener.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it, vi } from 'vitest';++import { createWindowsFileUrlOpener } from '../windowsFileUrlOpener.js';++describe('createWindowsFileUrlOpener', () => {+ it('does not create a Windows launcher on other platforms', () => {+ expect(+ createWindowsFileUrlOpener({+ platform: 'darwin',+ execFile: vi.fn(),+ }),+ ).toBeUndefined();+ });++ it('passes the complete URL as one argv value without cmd expansion', async () => {+ const execFile = vi.fn((_file, _args, _options, callback) => {+ callback(null, '', '');+ });+ const openUrl = createWindowsFileUrlOpener({+ platform: 'win32',+ windowsDir: 'C:\\Windows',+ execFile,+ });+ const fileUrl = 'file:///C:/tmp/preview.html?mode=review#%PATH%';++ await expect(openUrl?.(fileUrl)).resolves.toBeUndefined();++ expect(execFile).toHaveBeenCalledWith(+ 'C:\\Windows\\System32\\rundll32.exe',+ ['url.dll,FileProtocolHandler', fileUrl],+ { windowsHide: true },+ expect.any(Function),+ );+ });++ it.each([+ ['C:\\CustomWindows', 'C:\\CustomWindows\\System32\\rundll32.exe'],+ ['C:\\Windows\\System32', 'C:\\Windows\\System32\\rundll32.exe'],+ ['\\\\server\\share', 'C:\\Windows\\System32\\rundll32.exe'],+ ['//server/share', 'C:\\Windows\\System32\\rundll32.exe'],+ ['relative\\windows', 'C:\\Windows\\System32\\rundll32.exe'],+ ])('resolves %s to a trusted rundll32 path', (windowsDir, expectedPath) => {+ const execFile = vi.fn((_file, _args, _options, callback) => {+ callback(null, '', '');+ });+ const openUrl = createWindowsFileUrlOpener({+ platform: 'win32',+ windowsDir,+ execFile,+ });++ void openUrl?.('file:///C:/tmp/preview.html');++ expect(execFile).toHaveBeenCalledWith(+ expectedPath,+ ['url.dll,FileProtocolHandler', 'file:///C:/tmp/preview.html'],+ { windowsHide: true },+ expect.any(Function),+ );+ });++ it('returns the Windows handler error without exposing a shell command', async () => {+ const execFile = vi.fn((_file, _args, _options, callback) => {+ callback(new Error('handler failed'), '', 'URL handler unavailable');+ });+ const openUrl = createWindowsFileUrlOpener({+ platform: 'win32',+ execFile,+ });++ await expect(openUrl?.('file:///C:/tmp/preview.html')).rejects.toThrow(+ 'URL handler unavailable',+ );++ expect(execFile).toHaveBeenCalledWith(+ 'C:\\Windows\\System32\\rundll32.exe',+ ['url.dll,FileProtocolHandler', 'file:///C:/tmp/preview.html'],+ { windowsHide: true },+ expect.any(Function),+ );+ });+});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex e773504d5c..1c7f9f9445 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -21,7 +21,6 @@ import { applyVibrancyToSecondaryWindows } from './secondary-windows';import path from 'node:path';import fs from 'node:fs';import os from 'node:os';-import { pathToFileURL } from 'node:url';import { pipeline } from 'node:stream/promises';import { execFile, execFileSync, spawn } from 'node:child_process';import { machineIdSync } from 'node-machine-id';@@ -240,6 +239,8 @@ import {} from './filePathPolicy';import { readFileThumbnail } from './fileThumbnail';import { resolveShellOpenPathTarget } from './shellOpenPath';+import { handleOpenFileInBrowser } from './openFileInBrowser';+import { createWindowsFileUrlOpener } from './windowsFileUrlOpener';import { cindyGhostSchemePrivilege } from './cindy-brain/runtime/electronSandboxAdapter';import { fetchReleaseNotes, fetchReleaseNotesIndex } from './releaseNotesService';import { resolveWorkspacePathCached, resolveWorkspacePathBatchCached } from './pathResolver';@@ -4980,56 +4981,52 @@ const registerIpcHandlers = () => {},);- // file-chip 右键菜单 "在浏览器中查看":拿绝对路径,校验扩展名在 HTML- // 白名单内,然后 shell.openExternal(file:// URL) 走系统默认 file://+ // file-chip 右键菜单 / 内置浏览器 "在系统浏览器打开":接收绝对路径或+ // 本机 file:// URL,校验扩展名在 HTML 白名单内,然后走系统默认 file://// 处理器(绝大多数 OS 上 .html/.htm 都映射到默认浏览器)。和// `shell:open-external` 分开是因为后者只放行 http(s) 防滥用;这里收窄到// 受控的扩展名集合后,放行 file:// 是可控的。+ const openFileInBrowserLog = createLogger('shell:open-file-in-browser');+ const openFileUrlWithWindowsHandler = createWindowsFileUrlOpener({+ platform: process.platform,+ windowsDir: process.env.WINDIR,+ execFile: (file, args, options, callback) => execFile(file, args, options, callback),+ });ipcMain.handle('shell:open-file-in-browser',async (- _event: Electron.IpcMainInvokeEvent,- filePath: string,- ): Promise<{ success: boolean; error?: string }> => {- try {- if (!filePath || !path.isAbsolute(filePath)) {- return { success: false, error: 'Path must be absolute' };- }- if (!isPathAllowed(filePath)) {- return { success: false, error: '不允许访问该路径' };- }- if (!isBrowserOpenablePath(filePath)) {- return { success: false, error: '该文件类型不支持浏览器查看' };- }- if (!fs.existsSync(filePath)) {- return { success: false, error: '文件不存在' };- }- // 先试 file:// + openExternal —— 保留原行为(按扩展名走默认处理器,- // .html / .pdf / .svg 一般落到浏览器)。但 Windows 上 openExternal 对- // percent-encode 过的 file:// URL(路径含中文 / 空格时)会报- // 0x2 ERROR_FILE_NOT_FOUND;此时兜底走 shell.openPath(原生路径,不做- // URL 编码,中文 / 空格都稳)。兜底只在原 file:// URL 本就打不开时触发,- // 故不会回归任何原本能正常打开的情况。- const fileUrl = pathToFileURL(filePath).toString();- try {- await shell.openExternal(fileUrl);- } catch (e) {- // 记录 openExternal 首因再走兜底,否则兜底也失败时只剩 openPath 的- // 错误,无法区分"file:// 编码问题"还是"文件 / 权限问题",难排障。- createLogger('shell:open-file-in-browser').warn(- 'openExternal failed, fallback to openPath',- {- fileUrl,- error: String(e),- },- );- const errMsg = await shell.openPath(filePath);- if (errMsg) return { success: false, error: errMsg };- }- return { success: true };- } catch (err) {- return { success: false, error: err instanceof Error ? err.message : String(err) };- }+ event: Electron.IpcMainInvokeEvent,+ filePathOrUrl: string,+ ): Promise<{ success: true }> => {+ assertTrustedAppRendererEvent(event);+ const result = await handleOpenFileInBrowser(filePathOrUrl, {+ isPathAllowed,+ isBrowserOpenablePath,+ existsSync: fs.existsSync,+ openExternal: (url) => shell.openExternal(url),+ openPath: (filePath) => shell.openPath(filePath),+ openUrlWithWindowsHandler: openFileUrlWithWindowsHandler,+ onOpenExternalError: ({ filePath, hasUrlState, error }) => {+ openFileInBrowserLog.warn('openExternal failed', {+ filePath,+ hasUrlState,+ fallback: hasUrlState+ ? openFileUrlWithWindowsHandler+ ? 'windows-url-handler'+ : 'disabled'+ : 'openPath',+ error: String(error),+ });+ },+ onWindowsUrlFallbackError: ({ filePath, error }) => {+ openFileInBrowserLog.warn('Windows file URL fallback failed', {+ filePath,+ error: String(error),+ });+ },+ });+ if (!result.success) throwIpcError(result.errorCode, result.error);+ return result;},);diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 26c1e0cc82..76e1513a45 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -625,7 +625,7 @@ export const MAKER_INVOKE = {* - GET_STATE: renderer 启动期拉 { detached, lastOpen, open }* - OPEN / CLOSE: 幂等开(已开则 focus)/ 关子窗口,写 lastOpen* - SET_DETACHED(boolean): 落盘偏好;true 附带开窗,false 附带关窗;返回新 state- * - GET_CONTEXT: 子窗口 mount 时拉主窗上报的 { sessionId, workdir, remoteHostId, available }+ * - GET_CONTEXT: 子窗口 mount 时拉主窗上报的 { sessionId, workdir, remoteHostId, deviceLinkDeviceId, available }* - READY: 子窗口根组件挂载握手(resolve main 侧 ensureOpen 等待)* - SEND_COMMAND: 主窗把命令(如 open-terminal 快捷键)转发给子窗口,必要时先开窗*/@@ -703,7 +703,7 @@ export const MAKER_SEND = {*/SYNC_SESSION_MODEL_PREF: 'maker:sync-session-model-pref',/**- * 主窗 MainLayout → main:侧边栏渲染上下文 { sessionId, workdir, remoteHostId, available }+ * 主窗 MainLayout → main:侧边栏渲染上下文 { sessionId, workdir, remoteHostId, deviceLinkDeviceId, available }* 变化时无条件推(main 只在 detached 时消费,开偏好瞬间就有 context 可转发)。* main 校验 sender 必须是主窗,其它窗口的推送丢弃。fire-and-forget。*/diff --git a/apps/desktop/src/main/openFileInBrowser.ts b/apps/desktop/src/main/openFileInBrowser.tsnew file mode 100644index 0000000000..f188c3b47e--- /dev/null+++ b/apps/desktop/src/main/openFileInBrowser.ts@@ -0,0 +1,152 @@+/** Safely open a local HTML file in the system browser. */++import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import type {+ BrowserFileOpenErrorCode,+ BrowserFileOpenResult,+} from '../shared/openFileInBrowser';++const INVALID_BROWSER_FILE_TARGET_ERROR = '路径必须是绝对路径或本地 file:// URL';+const OPEN_BROWSER_FILE_ERROR = '无法在系统浏览器中打开该本地页面';++export interface BrowserFileTarget {+ filePath: string;+ fileUrl: string;+ hasUrlState: boolean;+}++/**+ * Accept the legacy absolute-path input and the full local file URL used by the+ * built-in browser. Non-local authorities are rejected instead of being+ * silently mapped onto a different local path.+ */+export function resolveBrowserFileTarget(value: string): BrowserFileTarget | null {+ if (!value) return null;+ if (path.isAbsolute(value)) {+ return {+ filePath: value,+ fileUrl: pathToFileURL(value).toString(),+ hasUrlState: false,+ };+ }++ let parsed: URL;+ try {+ parsed = new URL(value);+ } catch {+ return null;+ }+ if (parsed.protocol !== 'file:') return null;+ if (parsed.username || parsed.password) return null;+ if (parsed.hostname && parsed.hostname !== 'localhost') return null;+ if (parsed.port) return null;++ let filePath: string;+ try {+ filePath = fileURLToPath(parsed);+ } catch {+ return null;+ }+ if (!path.isAbsolute(filePath)) return null;++ return {+ filePath,+ fileUrl: parsed.toString(),+ hasUrlState: Boolean(parsed.search || parsed.hash),+ };+}++export interface OpenFileInBrowserDeps {+ isPathAllowed(filePath: string): boolean;+ isBrowserOpenablePath(filePath: string): boolean;+ existsSync(filePath: string): boolean;+ openExternal(url: string): Promise<void>;+ openPath(filePath: string): Promise<string>;+ /** Windows-only fallback that hands the complete file URL to the OS handler. */+ openUrlWithWindowsHandler?(url: string): Promise<void>;+ onOpenExternalError?(details: { filePath: string; hasUrlState: boolean; error: unknown }): void;+ onWindowsUrlFallbackError?(details: { filePath: string; error: unknown }): void;+}++export async function handleOpenFileInBrowser(+ value: string,+ deps: OpenFileInBrowserDeps,+): Promise<BrowserFileOpenResult> {+ try {+ const target = resolveBrowserFileTarget(value);+ if (!target) {+ return {+ success: false,+ error: INVALID_BROWSER_FILE_TARGET_ERROR,+ errorCode: 'BROWSER_FILE_INVALID_TARGET',+ };+ }+ if (!deps.isPathAllowed(target.filePath)) {+ return {+ success: false,+ error: '不允许访问该路径',+ errorCode: 'BROWSER_FILE_PATH_NOT_ALLOWED',+ };+ }+ if (!deps.isBrowserOpenablePath(target.filePath)) {+ return {+ success: false,+ error: '该文件类型不支持浏览器查看',+ errorCode: 'BROWSER_FILE_UNSUPPORTED_TYPE',+ };+ }+ if (!deps.existsSync(target.filePath)) {+ return {+ success: false,+ error: '文件不存在',+ errorCode: 'BROWSER_FILE_NOT_FOUND',+ };+ }++ try {+ await deps.openExternal(target.fileUrl);+ return { success: true };+ } catch (error) {+ deps.onOpenExternalError?.({+ filePath: target.filePath,+ hasUrlState: target.hasUrlState,+ error,+ });+ // openPath only accepts a native path. On Windows, hand the complete URL+ // to the OS URL handler first so query/hash state survives the fallback.+ if (target.hasUrlState) {+ if (deps.openUrlWithWindowsHandler) {+ try {+ await deps.openUrlWithWindowsHandler(target.fileUrl);+ return { success: true };+ } catch (fallbackError) {+ deps.onWindowsUrlFallbackError?.({+ filePath: target.filePath,+ error: fallbackError,+ });+ }+ }+ return {+ success: false,+ error: OPEN_BROWSER_FILE_ERROR,+ errorCode: 'BROWSER_FILE_OPEN_FAILED',+ };+ }+ const errorMessage = await deps.openPath(target.filePath);+ return errorMessage+ ? {+ success: false,+ error: errorMessage,+ errorCode: 'BROWSER_FILE_OPEN_FAILED',+ }+ : { success: true };+ }+ } catch (error) {+ return {+ success: false,+ error: OPEN_BROWSER_FILE_ERROR,+ errorCode: 'BROWSER_FILE_OPEN_FAILED',+ };+ }+}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 172a352106..1858e462de 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@@ -15,7 +15,7 @@ vi.mock('electron', () => {import { ipcMain, type BrowserWindow } from 'electron';-import { MAKER_INVOKE } from '../../maker-ipc/channels.js';+import { MAKER_INVOKE, MAKER_SEND } from '../../maker-ipc/channels.js';import { registerRsbWindowIpc } from '../ipc.js';import type { RsbWindowController } from '../controller.js';@@ -61,6 +61,37 @@ beforeEach(() => {});describe('right-sidebar-window IPC', () => {+ it('forwards the optional device-link origin in window context', () => {+ 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: 's1',+ workdir: '/remote/workdir',+ remoteHostId: null,+ deviceLinkDeviceId: 'device-1',+ available: true,+ },+ );++ expect(controller.setContext).toHaveBeenCalledWith({+ sessionId: 's1',+ workdir: '/remote/workdir',+ remoteHostId: null,+ deviceLinkDeviceId: 'device-1',+ available: true,+ });+ });+it('preserves missing vs explicit null worker focus hints in ensure commands', async () => {const controller = makeController();const { handler, mainWebContents } = registerController(controller);diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.tsindex 5a2c777586..c8d8bc3daa 100644--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts@@ -29,13 +29,19 @@ function parseContext(raw: unknown): RsbWindowContext {if (typeof v !== 'string') throwIpcError('INVALID_PARAMS', `${name} must be string | null`);return v;};+ const optionalNullableString = (v: unknown, name: string): string | null | undefined => {+ if (v === undefined) return undefined;+ return nullableString(v, name);+ };if (typeof r.available !== 'boolean') {throwIpcError('INVALID_PARAMS', 'available must be boolean');}+ const deviceLinkDeviceId = optionalNullableString(r.deviceLinkDeviceId, 'deviceLinkDeviceId');return {sessionId: nullableString(r.sessionId, 'sessionId'),workdir: nullableString(r.workdir, 'workdir'),remoteHostId: nullableString(r.remoteHostId, 'remoteHostId'),+ ...(deviceLinkDeviceId === undefined ? {} : { deviceLinkDeviceId }),available: r.available,};}diff --git a/apps/desktop/src/main/windowsFileUrlOpener.ts b/apps/desktop/src/main/windowsFileUrlOpener.tsnew file mode 100644index 0000000000..dabc1c19ac--- /dev/null+++ b/apps/desktop/src/main/windowsFileUrlOpener.ts@@ -0,0 +1,62 @@+import path from 'node:path';++export interface WindowsFileUrlOpenerOptions {+ platform?: NodeJS.Platform;+ windowsDir?: string;+ execFile: (+ file: string,+ args: string[],+ options: { windowsHide: boolean },+ callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void,+ ) => unknown;+}++const DEFAULT_WINDOWS_DIR = 'C:\\Windows';++function resolveRundll32Path(windowsDir: string | undefined): string {+ const candidate = windowsDir?.trim();+ const normalized = candidate ? path.win32.normalize(candidate) : '';+ const isLocalAbsolutePath = /^[A-Za-z]:[\\/]/.test(candidate ?? '');+ const isUncPath = candidate?.startsWith('\\\\') || candidate?.startsWith('//');++ if (!normalized || !isLocalAbsolutePath || isUncPath) {+ return path.win32.join(DEFAULT_WINDOWS_DIR, 'System32', 'rundll32.exe');+ }++ if (path.win32.basename(normalized).toLowerCase() === 'system32') {+ return path.win32.join(normalized, 'rundll32.exe');+ }++ return path.win32.join(normalized, 'System32', 'rundll32.exe');+}++/**+ * Create a Windows-only launcher that passes the complete file URL as an argv+ * value. Direct execFile avoids cmd.exe percent expansion and command parsing.+ */+export function createWindowsFileUrlOpener(+ options: WindowsFileUrlOpenerOptions,+): ((fileUrl: string) => Promise<void>) | undefined {+ if ((options.platform ?? process.platform) !== 'win32') return undefined;+ // Never fall back to PATH lookup for this privileged URL handoff. WINDIR is+ // normally present, but the fixed default keeps a stripped-down environment+ // from becoming an executable-search-path trust boundary.+ const rundll32 = resolveRundll32Path(options.windowsDir);++ return (fileUrl) =>+ new Promise<void>((resolve, reject) => {+ options.execFile(+ rundll32,+ ['url.dll,FileProtocolHandler', fileUrl],+ { windowsHide: true },+ (error, _stdout, stderr) => {+ if (!error) {+ resolve();+ return;+ }+ const detail = String(stderr).trim();+ reject(new Error(detail || error.message));+ },+ );+ });+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e5a2a54038..cf551769e6 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1325,6 +1325,7 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string | null;workdir: string | null;remoteHostId: string | null;+ deviceLinkDeviceId?: string | null;available: boolean;} | null> => ipcRenderer.invoke('maker:rsb-window:get-context'),/** 子窗口根组件挂载握手(main 侧 ensureOpen 等它)。 */@@ -1337,6 +1338,7 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string | null;workdir: string | null;remoteHostId: string | null;+ deviceLinkDeviceId?: string | null;available: boolean;}): void => ipcRenderer.send('maker:rsb-window:set-context', ctx),onStateChanged: fanOutRsbWindowStateChanged,@@ -2678,11 +2680,10 @@ contextBridge.exposeInMainWorld('electronAPI', {openChatGPTApp: (): Promise<{ success: boolean }> =>ipcRenderer.invoke('shell:open-chatgpt-app'),- // file-chip 右键菜单 "在浏览器中查看": 把本地文件用 file:// 喂给系统- // 默认浏览器(或 .html/.pdf/.svg 等扩展名的默认 handler)。main 端会再做- // 一次扩展名白名单校验和 isPathAllowed 安全校验。- openFileInBrowser: (filePath: string): Promise<{ success: boolean; error?: string }> =>- ipcRenderer.invoke('shell:open-file-in-browser', filePath),+ // file-chip 传绝对路径;内置浏览器传完整本地 file:// URL 以保留 query/hash。+ // main 端统一解析并做扩展名白名单与 isPathAllowed 安全校验。+ openFileInBrowser: (filePathOrUrl: string): Promise<{ success: true }> =>+ ipcRenderer.invoke('shell:open-file-in-browser', filePathOrUrl),// ── 系统级通知(CC Agent session 状态变更)──// kind: 'done' = 真正完成;'error' = 执行失败;'needs-reply' = 等用户回复 ask/permission/plan-review。diff --git a/apps/desktop/src/renderer/__tests__/newMakerDraftRightSidebar.test.ts b/apps/desktop/src/renderer/__tests__/newMakerDraftRightSidebar.test.tsindex 15a53bdaf8..8539b7f73a 100644--- a/apps/desktop/src/renderer/__tests__/newMakerDraftRightSidebar.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerDraftRightSidebar.test.ts@@ -21,6 +21,7 @@ describe('New Maker draft right sidebar', () => {sessionId: makeProjectDraftRightSidebarSessionId('C:\\Work\\XDMaker'),workdir: 'C:\\Work\\XDMaker',remoteHostId: null,+ deviceLinkDeviceId: null,});});diff --git a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsxindex cfd721c740..6fda1331c4 100644--- a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx+++ b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx@@ -32,6 +32,7 @@ import { ClipboardCopy, Copy, FileCode, FolderOpen, FolderTree, Globe, PanelRighimport { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';+import { mapIpcErrorToI18nKey } from '@/utils/ipcError';import {DropdownMenu,DropdownMenuContent,@@ -138,8 +139,18 @@ export function useFileChipContextMenu({async function handleOpenInBrowser(): Promise<void> {setMenuPos(null);const abs = await getAbsPath();- const res = await window.electronAPI.openFileInBrowser(abs);- if (!res.success) toast.error(res.error ?? t('chat.markdownRenderer.openInBrowserFailed'));+ try {+ await window.electronAPI.openFileInBrowser(abs);+ } catch (error) {+ toast.error(+ t(+ mapIpcErrorToI18nKey(error, {+ namespace: 'chat.markdownRenderer',+ fallback: 'chat.markdownRenderer.openInBrowserFailed',+ }),+ ),+ );+ }}async function handleOpenInSidebar(): Promise<void> {diff --git a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsxindex 7219440385..b61819f7ae 100644--- a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx+++ b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx@@ -22,6 +22,7 @@ import { useTranslation } from 'react-i18next';import type { TFunction } from 'i18next';import { toast } from '@/lib/toast';+import { mapIpcErrorToI18nKey } from '@/utils/ipcError';import {DropdownMenu,DropdownMenuContent,@@ -77,8 +78,18 @@ export async function openHtmlFileByPreference(await openInSidebar(sessionId, pathToFileUrl(absPath), t);return;}- const res = await window.electronAPI.openFileInBrowser(absPath);- if (!res.success) toast.error(res.error ?? t('chat.markdownRenderer.openInBrowserFailed'));+ try {+ await window.electronAPI.openFileInBrowser(absPath);+ } catch (error) {+ toast.error(+ t(+ mapIpcErrorToI18nKey(error, {+ namespace: 'chat.markdownRenderer',+ fallback: 'chat.markdownRenderer.openInBrowserFailed',+ }),+ ),+ );+ }}export interface UseOpenWithMenu {diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex c9206cd3f4..00713e4660 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -286,18 +286,21 @@ export function MainLayout() {const [rightSidebarWorkdirInfo, setRightSidebarWorkdirInfo] = useState<{workdir: string;remoteHostId: string | null;- }>({ workdir: '', remoteHostId: null });+ deviceLinkDeviceId?: string | null;+ }>({ workdir: '', remoteHostId: null, deviceLinkDeviceId: undefined });const setRightSidebarWorkdir = useCallback(- (workdir: string, remoteHostId: string | null = null) =>+ (workdir: string, remoteHostId: string | null = null, deviceLinkDeviceId?: string | null) =>// 同值 bailout(返回 prev 引用):恢复"字符串 state 同值不重渲染"的旧语义。// Outlet context 对象每次渲染都是新身份,OrcaWorkflowRoute 等消费方的// effect 以 outletContext 为 dep——如果同值 declare 也换新对象,会形成// declare → 重渲染 → 新 context → effect 重跑 → declare 的死循环// (真机实测 Maximum update depth exceeded)。setRightSidebarWorkdirInfo((prev) =>- prev.workdir === workdir && prev.remoteHostId === remoteHostId+ prev.workdir === workdir &&+ prev.remoteHostId === remoteHostId &&+ prev.deviceLinkDeviceId === deviceLinkDeviceId? prev- : { workdir, remoteHostId },+ : { workdir, remoteHostId, deviceLinkDeviceId },),[],);@@ -802,6 +805,7 @@ export function MainLayout() {sessionId: rightSidebarSessionId,workdir: rightSidebarWorkdirInfo.workdir || null,remoteHostId: rightSidebarWorkdirInfo.remoteHostId,+ deviceLinkDeviceId: rightSidebarWorkdirInfo.deviceLinkDeviceId,available: rightSidebarAvailable,});}, [rightSidebarSessionId, rightSidebarWorkdirInfo, rightSidebarAvailable]);@@ -1277,6 +1281,7 @@ export function MainLayout() {sessionId={rightSidebarSessionId}workdir={rightSidebarWorkdirInfo.workdir}remoteHostId={rightSidebarWorkdirInfo.remoteHostId}+ deviceLinkDeviceId={rightSidebarWorkdirInfo.deviceLinkDeviceId}onDetach={isSecondaryWindow() ? undefined : handleDetachRightSidebar}// M2:面板贴左时 detach / maximize 由 Shell 顶栏右端自渲染// (面板自属控件跟面板走);折叠 toggle 恒在窗口右上浮层,不下沉。diff --git a/apps/desktop/src/renderer/components/layout/RightSidebar.tsx b/apps/desktop/src/renderer/components/layout/RightSidebar.tsxindex 08bee2b485..5440b4411f 100644--- a/apps/desktop/src/renderer/components/layout/RightSidebar.tsx+++ b/apps/desktop/src/renderer/components/layout/RightSidebar.tsx@@ -63,6 +63,8 @@ interface RightSidebarProps {workdir: string;/** 非空 = SSH remote 会话(workdir 为远端路径),透传给 Shell → plugin ctx。 */remoteHostId: string | null;+ /** device-link 会话归属:null = 已确认本机,undefined = 尚未解析。 */+ deviceLinkDeviceId?: string | null;/** Maximize 态(Phase 6):RSB 撑满整个非左栏区,主区 hidden。本组件用来隐藏* resize handle(maximize 不允许拖宽)+ 把 TabBar maximize 按钮图标切到"还原"。 */isMaximized?: boolean;@@ -93,6 +95,7 @@ export const RightSidebar = forwardRef<RightSidebarHandle, RightSidebarProps>(fusessionId,workdir,remoteHostId,+ deviceLinkDeviceId,onDetach,panelSide,onAllTabsClosed,@@ -254,6 +257,7 @@ export const RightSidebar = forwardRef<RightSidebarHandle, RightSidebarProps>(fusessionId={sessionId}workdir={workdir}remoteHostId={remoteHostId}+ deviceLinkDeviceId={deviceLinkDeviceId}shellVisible={!displayCollapsed}isMac={isMac}unifiedTopbar={isMac}diff --git a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsxindex 79320ad249..5992e48a53 100644--- a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx@@ -8,7 +8,7 @@* 主窗收广播后恢复内嵌侧栏)。* - 挂 RightSidebarShell(零改动复用:Shell 自带 store 订阅 / rsbBrowserBridge* init / setActiveSession / popup 订阅)。- * - 渲染上下文(sessionId / workdir / remoteHostId)不自查 —— 主窗 MainLayout+ * - 渲染上下文(sessionId / workdir / remoteHostId / deviceLinkDeviceId)不自查 —— 主窗 MainLayout* 是唯一真相(草稿会话 / remote 会话语义只有主窗路由视图知道),经 main 中转:* mount 时 invoke getContext 拉一次,此后订阅 context-changed 推送跟随主窗切换。* - mount 后 invoke ready() 握手:main 的 ensureOpenForAutomation(agent tab-op@@ -51,6 +51,7 @@ interface SidebarWindowContext {sessionId: string | null;workdir: string | null;remoteHostId: string | null;+ deviceLinkDeviceId?: string | null;available: boolean;}@@ -193,6 +194,7 @@ export function SidebarWindowLayout() {sessionId={sessionId}workdir={ctx?.workdir ?? ''}remoteHostId={ctx?.remoteHostId ?? null}+ deviceLinkDeviceId={ctx?.deviceLinkDeviceId}isMac={isMac}/>{!sessionId && (diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsxindex 3747507e27..9ed6f207cd 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx@@ -53,7 +53,11 @@ export function CCAgentFeatureLayout() {* file-browser plugin 据此 useFileTree / useFileContent。空串 = 尚未解析或 remote session。* 同 setRightSidebarSessionId,仅主实例调。*/- setRightSidebarWorkdir?: (workdir: string, remoteHostId?: string | null) => void;+ setRightSidebarWorkdir?: (+ workdir: string,+ remoteHostId?: string | null,+ deviceLinkDeviceId?: string | null,+ ) => void;} | null>();return <Outlet context={shellContext} />;}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex eb908b6ddb..269b526b6f 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -410,17 +410,24 @@ function RightSidebarSessionIdRegistration({function RightSidebarWorkdirRegistration({workdir,remoteHostId,+ deviceLinkDeviceId,declare,}: {workdir: string;/** 非空 = SSH remote 会话(workdir 为远端路径);plugin 据此走远端 file-service。 */remoteHostId: string | null;- declare: (workdir: string, remoteHostId?: string | null) => void;+ /** device-link 会话归属:null = 已确认本机,undefined = 尚未解析。 */+ deviceLinkDeviceId?: string | null;+ declare: (+ workdir: string,+ remoteHostId?: string | null,+ deviceLinkDeviceId?: string | null,+ ) => void;}) {useLayoutEffect(() => {- declare(workdir, remoteHostId);- return () => declare('');- }, [workdir, remoteHostId, declare]);+ declare(workdir, remoteHostId, deviceLinkDeviceId);+ return () => declare('', null, undefined);+ }, [workdir, remoteHostId, deviceLinkDeviceId, declare]);return null;}@@ -499,7 +506,11 @@ export function CCAgentSessionView({sessionId: string | null,opts?: { initialCollapsed?: boolean; writeInitialCollapsedRecord?: boolean },) => void;- setRightSidebarWorkdir?: (workdir: string) => void;+ setRightSidebarWorkdir?: (+ workdir: string,+ remoteHostId?: string | null,+ deviceLinkDeviceId?: string | null,+ ) => void;} | null>();const rightSidebarCollapsed = outletContext?.rightSidebarCollapsed ?? true;const onToggleRightSidebar = outletContext?.onToggleRightSidebar;@@ -694,6 +705,10 @@ export function CCAgentSessionView({() => (sessionId ? getStickySessionDeviceId(sessionId) : undefined),[sessionId, remoteProjectSessions],);+ // 右栏本地-only 能力需要区分三态:字符串=远端、null=已确认本机、undefined=归属尚未解析。+ // 冷启动 / bootstrap 竞态期间宁可暂时禁用系统文件打开,也不能把被控端 file:// 交给控制端。+ const rightSidebarDeviceLinkDeviceId =+ remoteDeviceId ?? session?.deviceLinkDeviceId ?? (session ? null : undefined);// device-link 远程会话:重 topic 订阅(含 WS 重连 / 被控端回在线时重建)+ 消息对账触发// (重连 / presence / turn 结束 / 窗口聚焦 / 手动)。修「控制端丢消息」—— 以被控端为准重新同步。// 本机会话(remoteDeviceId 为 undefined)整体 no-op。resync 供连接 banner 的「重新同步」按钮用。@@ -3106,6 +3121,7 @@ export function CCAgentSessionView({<RightSidebarWorkdirRegistrationworkdir={session?.workingDir ?? ''}remoteHostId={session?.remoteHostId ?? null}+ deviceLinkDeviceId={rightSidebarDeviceLinkDeviceId}declare={setRightSidebarWorkdir}/>)}diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex 28d875bfc1..f4fb52b79a 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -558,7 +558,11 @@ export function NewMakerDraftRoute() {rightSidebarSide?: 'left' | 'right';setRightSidebarAvailable?: (available: boolean) => void;setRightSidebarSessionId?: (sessionId: string | null) => void;- setRightSidebarWorkdir?: (workdir: string, remoteHostId?: string | null) => void;+ setRightSidebarWorkdir?: (+ workdir: string,+ remoteHostId?: string | null,+ deviceLinkDeviceId?: string | null,+ ) => void;} | null>();const rightSidebarCollapsed = outletContext?.rightSidebarCollapsed ?? true;const onToggleRightSidebar = outletContext?.onToggleRightSidebar;@@ -886,12 +890,21 @@ export function NewMakerDraftRoute() {useLayoutEffect(() => {if (draftRightSidebar.workdir) {- setRightSidebarWorkdir?.(draftRightSidebar.workdir, draftRightSidebar.remoteHostId);+ setRightSidebarWorkdir?.(+ draftRightSidebar.workdir,+ draftRightSidebar.remoteHostId,+ draftRightSidebar.deviceLinkDeviceId,+ );} else {- setRightSidebarWorkdir?.('');+ setRightSidebarWorkdir?.('', null, undefined);}- return () => setRightSidebarWorkdir?.('');- }, [draftRightSidebar.workdir, draftRightSidebar.remoteHostId, setRightSidebarWorkdir]);+ return () => setRightSidebarWorkdir?.('', null, undefined);+ }, [+ draftRightSidebar.deviceLinkDeviceId,+ draftRightSidebar.remoteHostId,+ draftRightSidebar.workdir,+ setRightSidebarWorkdir,+ ]);// 跨 Agent 工作区迁移弹窗:detect → ask → run → 等关闭 → 才创建会话const crossAgentDialog = useCrossAgentMigrationDialog();diff --git a/apps/desktop/src/renderer/features/cc-agent/newMakerDraftRightSidebar.ts b/apps/desktop/src/renderer/features/cc-agent/newMakerDraftRightSidebar.tsindex 2b6f6e0bf0..543bec5e8e 100644--- a/apps/desktop/src/renderer/features/cc-agent/newMakerDraftRightSidebar.ts+++ b/apps/desktop/src/renderer/features/cc-agent/newMakerDraftRightSidebar.ts@@ -15,6 +15,8 @@ export interface NewMakerDraftRightSidebarState {sessionId: string | null;workdir: string | null;remoteHostId: string | null;+ /** device-link 会话归属:null = 已确认本机,undefined = 尚未解析。 */+ deviceLinkDeviceId?: string | null;}export const DRAFT_RIGHT_SIDEBAR_TOGGLE_DRAG_STYLE = {@@ -59,6 +61,7 @@ export function resolveNewMakerDraftRightSidebar(sessionId: null,workdir: null,remoteHostId: null,+ deviceLinkDeviceId,};}@@ -67,5 +70,6 @@ export function resolveNewMakerDraftRightSidebar(sessionId: makeProjectDraftRightSidebarSessionId(workdir),workdir,remoteHostId: null,+ deviceLinkDeviceId: null,};}diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsxindex 4064c2e9d3..ab06a20300 100644--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx@@ -37,6 +37,7 @@ import {import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { toast } from '@/lib/toast';import { createLogger } from '@/lib/logger';+import { extractIpcError, mapIpcErrorToI18nKey } from '@/utils/ipcError';import { useFileTree, type DirEntry } from './hooks/useFileTree';import { fileBrowserApiFor } from '@/lib/fileBrowserTransport';@@ -502,10 +503,21 @@ export function WorkdirBrowseSidebar({const handleOpenInBrowser = useCallback(async (entry: DirEntry) => {const abs = toOsAbsolutePath(workdir, entry.relPath);- const res = await window.electronAPI.openFileInBrowser(abs);- if (!res.success) {- log.warn('open in browser failed', { relPath: entry.relPath, error: res.error });- toast.error(res.error ?? t('chat.markdownRenderer.openInBrowserFailed'));+ try {+ await window.electronAPI.openFileInBrowser(abs);+ } catch (error) {+ log.warn('open in browser failed', {+ relPath: entry.relPath,+ errorCode: extractIpcError(error)?.code ?? 'unknown',+ });+ toast.error(+ t(+ mapIpcErrorToI18nKey(error, {+ namespace: 'chat.markdownRenderer',+ fallback: 'chat.markdownRenderer.openInBrowserFailed',+ }),+ ),+ );}},[workdir, t],diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex 1f89f33599..38546f2dd1 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -76,6 +76,8 @@ interface RightSidebarShellProps {workdir: string;/** 非空 = SSH remote 会话(workdir 为远端路径);见 TabKindHostContext.remoteHostId。 */remoteHostId: string | null;+ /** device-link 会话归属:null = 已确认本机,undefined = 尚未解析。 */+ deviceLinkDeviceId?: string | null;/** RightSidebar aside 当前是否真实展开。折叠时 keep-alive body 仍挂载但不可见。 */shellVisible?: boolean;isMac: boolean;@@ -120,6 +122,7 @@ export function RightSidebarShell({sessionId,workdir,remoteHostId,+ deviceLinkDeviceId,shellVisible = true,isMac,unifiedTopbar = false,@@ -519,6 +522,7 @@ export function RightSidebarShell({sessionId={sessionId}workdir={workdir}remoteHostId={remoteHostId}+ deviceLinkDeviceId={deviceLinkDeviceId}shellVisible={shellVisible}t={t}/>@@ -535,6 +539,7 @@ interface PluginBodyHostProps {sessionId: string | null;workdir: string;remoteHostId: string | null;+ deviceLinkDeviceId?: string | null;shellVisible: boolean;t: ReturnType<typeof useTranslation>['t'];}@@ -554,6 +559,7 @@ function PluginBodyHost({sessionId,workdir,remoteHostId,+ deviceLinkDeviceId,shellVisible,t,}: PluginBodyHostProps) {@@ -571,6 +577,7 @@ function PluginBodyHost({sessionId: sessionId ?? '',workdir,remoteHostId,+ deviceLinkDeviceId,patchState: (patch: unknown) => {if (!sessionId) return;void patchTabState(sessionId, tab.id, (current) => {@@ -597,7 +604,7 @@ function PluginBodyHost({setCloseInterceptor: (interceptor) =>setTabCloseInterceptor(tab.id, interceptor),}),- [sessionId, workdir, remoteHostId, tab.id],+ [sessionId, workdir, remoteHostId, deviceLinkDeviceId, tab.id],);// active 切换:走 effect 通知 plugin(plugin 自己内部用 ctx.onVisibilityChangediff --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 d17ea5dd28..cf0c77bd45 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@@ -62,6 +62,14 @@ describe('fileUrlToAbsPath / isLocalHtmlFileUrl', () => {expect(isLocalHtmlFileUrl('https://example.com/x.html')).toBe(false);expect(isLocalHtmlFileUrl('file:///tmp/notes.md')).toBe(false);expect(isLocalHtmlFileUrl('about:blank')).toBe(false);+ expect(isLocalHtmlFileUrl('file:///tmp/preview.xhtml')).toBe(false);+ });++ it('rejects non-local file authorities', () => {+ expect(fileUrlToAbsPath('file://server/share/index.html')).toBeNull();+ expect(isLocalHtmlFileUrl('file://server/share/index.html')).toBe(false);+ expect(fileUrlToAbsPath('file://localhost:8080/tmp/index.html')).toBeNull();+ expect(isLocalHtmlFileUrl('file://localhost:8080/tmp/index.html')).toBe(false);});it('ignores hash/query when recovering the path', () => {diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.tsindex 033049c100..9a8e5dc15b 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts@@ -17,6 +17,7 @@import { addTab, ensureHydrated } from '../store';import { requestRightSidebarVisibility } from './sidebarCommands';import { routeSidebarCommand } from './detachedSidebarRouting';+import { isBrowserOpenablePath } from '../../../../shared/browserOpenableExts';/*** 绝对路径 → file:// URL。macOS/Linux POSIX 路径与 Windows 盘符路径都支持:@@ -36,15 +37,13 @@ export function pathToFileUrl(absPath: string): string {return `file://${encoded}`;}-/** 本地 HTML 预览自动刷新只认这些扩展名(与 browserOpenableExts / 文件树菜单对齐)。 */-const LOCAL_HTML_EXT_RE = /\.(html?|xhtml)$/i;-/*** file:// URL → 本机绝对路径。与 pathToFileUrl 互逆:* file:///Users/a%20b/x.html → /Users/a b/x.html* file:///E:/out/index.html → E:\out\index.html (win32 风格分隔)*- * 只取 pathname(忽略 hash / query);非 file: 或解析失败 → null。+ * 仅接受无凭证、无端口且 authority 为空或 localhost 的本地 file URL;只取+ * pathname(忽略 hash / query),非 file:、远端 authority 或解析失败 → null。*/export function fileUrlToAbsPath(url: string): string | null {let parsed: URL;@@ -54,6 +53,9 @@ export function fileUrlToAbsPath(url: string): string | null {return null;}if (parsed.protocol !== 'file:') return null;+ if (parsed.username || parsed.password) return null;+ if (parsed.hostname && parsed.hostname !== 'localhost') return null;+ if (parsed.port) return null;let pathname: string;try {pathname = decodeURIComponent(parsed.pathname);@@ -67,10 +69,10 @@ export function fileUrlToAbsPath(url: string): string | null {return pathname || null;}-/** 当前页是否为本地 HTML 文件预览(file:// + html/htm/xhtml)。 */+/** 当前页是否为本地 HTML 文件预览(file:// + html/htm)。 */export function isLocalHtmlFileUrl(url: string): boolean {const abs = fileUrlToAbsPath(url);- return abs !== null && LOCAL_HTML_EXT_RE.test(abs);+ return abs !== null && isBrowserOpenablePath(abs);}export interface OpenUrlInSidebarBrowserOptions {diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsxindex 8f73b192cb..7b5ffca3b6 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx@@ -35,6 +35,7 @@ import { ChevronsDownUp, FolderX, RefreshCw, Search, X as XIcon } from 'lucide-rimport { cn } from '@/lib/utils';import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';import { toast } from '@/lib/toast';+import { mapIpcErrorToI18nKey } from '@/utils/ipcError';import { Tip } from '@/components/ui/tooltip';import { ImageLightbox } from '@/components/chat/ImageLightbox';import {@@ -391,9 +392,17 @@ function FileBrowserBodyWithWorkdir({const handleOpenInBrowser = useCallback(async (entry: DirEntry) => {const abs = toOsAbsolutePath(workdir, entry.relPath);- const res = await window.electronAPI.openFileInBrowser(abs);- if (!res.success) {- toast.error(res.error ?? t('chat.markdownRenderer.openInBrowserFailed'));+ try {+ await window.electronAPI.openFileInBrowser(abs);+ } catch (error) {+ toast.error(+ t(+ mapIpcErrorToI18nKey(error, {+ namespace: 'chat.markdownRenderer',+ fallback: 'chat.markdownRenderer.openInBrowserFailed',+ }),+ ),+ );}},[workdir, t],diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsxindex ef492bbd30..f67c3fd146 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx@@ -79,6 +79,8 @@ export interface BrowserChromeProps {* 评论写进去无处可发(且会误弹成功 toast)——故子窗口传 false 隐藏该按钮。*/commentSupported?: boolean;+ /** 当前页是否能交给系统默认浏览器打开。 */+ canOpenInSystemBrowser: boolean;/** 「更多」菜单项:用系统默认浏览器打开当前页(main 端 shell.openExternal)。 */onOpenInSystemBrowser: () => void;/** 「更多」菜单项:复制当前页链接到剪贴板(反馈 toast 由 TabBody 做)。 */@@ -107,6 +109,7 @@ export const BrowserChrome = forwardRef<BrowserChromeHandle, BrowserChromeProps>commentActive,onToggleComment,commentSupported = true,+ canOpenInSystemBrowser,onOpenInSystemBrowser,onCopyLink,},@@ -196,8 +199,9 @@ export const BrowserChrome = forwardRef<BrowserChromeHandle, BrowserChromeProps>// 是否 https:左侧 lock icon 决定。about:blank 等非 web 协议显示 unlock 占位。const isSecure = url.startsWith('https://');- // 「更多」菜单里"系统浏览器打开 / 复制链接"两项:仅当存在有效页面 URL(非空、非- // about:blank)时可用,新标签空白态置灰。判据与 displayValue 一致。+ // 「更多」菜单里复制链接只要求有有效页面 URL;系统浏览器打开还要由宿主确认+ // 当前协议/页面类型有对应的安全 IPC 能力。比如本地 HTML 走 openFileInBrowser,+ // 其它 file/data/custom scheme 不应显示一个点击必失败的可用菜单项。const hasValidLink = Boolean(url) && url !== 'about:blank';return (@@ -304,7 +308,10 @@ export const BrowserChrome = forwardRef<BrowserChromeHandle, BrowserChromeProps></button></DropdownMenuTrigger><DropdownMenuContent align="end" className="min-w-[9rem]">- <DropdownMenuItem disabled={!hasValidLink} onSelect={onOpenInSystemBrowser}>+ <DropdownMenuItem+ disabled={!hasValidLink || !canOpenInSystemBrowser}+ onSelect={onOpenInSystemBrowser}+ ><ExternalLink size={14} strokeWidth={2} className="mr-2 shrink-0" />{t('rightSidebar.browser.openInSystemBrowser')}</DropdownMenuItem>diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsxindex 83973422c9..f7176a3099 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx@@ -36,12 +36,14 @@ import { createLogger } from '@/lib/logger';import { isSidebarWindow } from '@/lib/sidebarWindow';import { toast } from '@/lib/toast';import { cn } from '@/lib/utils';+import { mapIpcErrorToI18nKey } from '@/utils/ipcError';import { browserWebviewPool } from '../../lib/browserWebviewPool';import {forceKillBrowserTab,setForegroundBrowserTab,} from '../../lib/rsbBrowserBridge';+import { isLocalHtmlFileUrl } from '../../lib/openInSidebarBrowser';import { closeTab } from '../../store';import { useBrowserWebview } from '../../hooks/useBrowserWebview';import type { TabKindHostContext } from '../../types';@@ -85,6 +87,9 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB// sessionId 跟 tabId 一起喂给 hook,用于 dom-ready 后给 main 端 TabRegistry// 上报 (sessionId, tabId, webContentsId) 三元组(Phase 2 browser bridge)。const { tabId, sessionId } = ctx;+ // device-link 归属由 host context 携带三态事实:字符串=远端、null=已确认本机、+ // undefined=冷启动/bootstrap 尚未解析。系统文件打开对后两者只放行已确认本机。+ const deviceLinkDeviceId = ctx.deviceLinkDeviceId;// 真实可见性:顶层 active tab 且整个侧栏展开。shellVisible 缺省(旧宿主 /// 测试)按可见处理,与 active 的既有缺省语义一致。const tabVisible = active === true && shellVisible !== false;@@ -109,7 +114,11 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabBworkdir: ctx.workdir,url: browser.url || state.url,reload: browser.reload,- enabled: active === true && ctx.remoteHostId === null && !browser.crash,+ enabled:+ active === true &&+ ctx.remoteHostId === null &&+ deviceLinkDeviceId === null &&+ !browser.crash,});// 把 pool 的 wrapper 挂进 slot —— useLayoutEffect(在 paint 前移 DOM,避免闪)。@@ -396,23 +405,42 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabBconst menuUrlRef = useRef(state.url || 'about:blank');menuUrlRef.current = state.url || 'about:blank';+ const menuUrl = menuUrlRef.current;+ const isWebUrl = /^https?:\/\//i.test(menuUrl);+ const isLocalHtmlUrl =+ ctx.remoteHostId === null && deviceLinkDeviceId === null && isLocalHtmlFileUrl(menuUrl);+ const canOpenInSystemBrowser = isWebUrl || isLocalHtmlUrl;+// 「更多」菜单 —— 用系统默认浏览器打开当前页。- // 菜单项在无有效链接时已 disabled,这里再兜一层空 / about:blank 保护。- // openExternal 在被控端(远程控制场景)本机打开,语义正确(见规则 26)。+ // HTTP(S) 走 openExternal;本地 HTML 走专用文件 IPC。远程 SSH 会话的 file://+ // URL 指向远端 workdir,不能误交给控制端本机的文件打开器,因此由菜单禁用。const handleOpenInSystemBrowser = useCallback(() => {const url = menuUrlRef.current;if (!url || url === 'about:blank') return;- void window.electronAPI- .openExternal(url)+ const localFileUrl =+ ctx.remoteHostId === null && deviceLinkDeviceId === null && isLocalHtmlFileUrl(url);+ const openPromise: Promise<{ success: boolean; error?: string }> | null = localFileUrl+ ? window.electronAPI.openFileInBrowser(url)+ : /^https?:\/\//i.test(url)+ ? window.electronAPI.openExternal(url)+ : null;+ if (!openPromise) return;+ void openPromise.then((res) => {if (!res?.success) {- toast.error(t('chat.markdownRenderer.openInBrowserFailed'));+ toast.error(res?.error || t('chat.markdownRenderer.openInBrowserFailed'));}})- .catch(() => {- toast.error(t('chat.markdownRenderer.openInBrowserFailed'));+ .catch((error) => {+ const errorKey = localFileUrl+ ? mapIpcErrorToI18nKey(error, {+ namespace: 'chat.markdownRenderer',+ fallback: 'chat.markdownRenderer.openInBrowserFailed',+ })+ : 'chat.markdownRenderer.openInBrowserFailed';+ toast.error(t(errorKey));});- }, [t]);+ }, [ctx.remoteHostId, deviceLinkDeviceId, t]);// 「更多」菜单 —— 复制当前页链接到剪贴板(renderer clipboard,项目惯例)。const handleCopyLink = useCallback(async () => {@@ -443,6 +471,7 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabBcommentActive={comment.mode !== 'off'}onToggleComment={comment.toggle}commentSupported={commentSupported}+ canOpenInSystemBrowser={canOpenInSystemBrowser}onOpenInSystemBrowser={handleOpenInSystemBrowser}onCopyLink={handleCopyLink}/>diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserChrome.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserChrome.test.tsindex 73e0fb2424..2a1e721290 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserChrome.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserChrome.test.ts@@ -47,6 +47,7 @@ function renderChrome(url = 'https://www.taptap.cn/',extra: {commentSupported?: boolean;+ canOpenInSystemBrowser?: boolean;isLoading?: boolean;onReload?: () => void;onStop?: () => void;@@ -74,6 +75,7 @@ function renderChrome(onOpenInSystemBrowser,onCopyLink,commentSupported: extra.commentSupported,+ canOpenInSystemBrowser: extra.canOpenInSystemBrowser ?? true,}),);return { onNavigate, onOpenInSystemBrowser, onCopyLink, ref };@@ -196,4 +198,20 @@ describe('BrowserChrome', () => {expect(onOpenInSystemBrowser).not.toHaveBeenCalled();expect(onCopyLink).not.toHaveBeenCalled();});++ it('disables system-browser opening when the host has no safe opener for the URL', () => {+ const { onOpenInSystemBrowser, onCopyLink } = renderChrome('file:///tmp/notes.md', {+ canOpenInSystemBrowser: false,+ });++ const openItem = screen.getByRole('button', {+ name: 'rightSidebar.browser.openInSystemBrowser',+ }) as HTMLButtonElement;+ const copyItem = screen.getByRole('button', {+ name: 'rightSidebar.browser.copyLink',+ }) as HTMLButtonElement;++ expect(openItem.disabled).toBe(true);+ expect(copyItem.disabled).toBe(false);+ });});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.tsindex 9f3ec174a2..b07198f723 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts@@ -8,6 +8,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { UseBrowserWebviewResult } from '../../../hooks/useBrowserWebview';import type { TabKindHostContext } from '../../../types';import { BrowserTabBody } from '../BrowserTabBody';+import { useLocalHtmlAutoReload } from '../useLocalHtmlAutoReload';++const toastMocks = vi.hoisted(() => ({+ error: vi.fn(),+ success: vi.fn(),+}));const browserNavigate = vi.fn();let browserState: UseBrowserWebviewResult;@@ -22,6 +28,34 @@ vi.mock('react-i18next', () => ({}),}));+vi.mock('@/lib/toast', () => ({ toast: toastMocks }));++vi.mock('@/components/ui/dropdown-menu', () => {+ const react = require('react') as typeof import('react');+ return {+ DropdownMenu: ({ children }: { children: React.ReactNode }) =>+ react.createElement(react.Fragment, null, children),+ DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) =>+ react.createElement(react.Fragment, null, children),+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) =>+ react.createElement('div', null, children),+ DropdownMenuItem: ({+ children,+ onSelect,+ disabled,+ }: {+ children: React.ReactNode;+ onSelect?: () => void;+ disabled?: boolean;+ }) =>+ react.createElement(+ 'button',+ { type: 'button', disabled, onClick: () => onSelect?.() },+ children,+ ),+ };+});+vi.mock('../../../hooks/useBrowserWebview', () => ({useBrowserWebview: () => browserState,}));@@ -80,12 +114,17 @@ function renderBrowserTab(favicon: string | null;isAudible: boolean;}> = {},+ deviceLinkDeviceId?: string | null,): ReactElement {+ // Omitted fifth arg models the confirmed-local default; an explicit undefined+ // models the unresolved bootstrap/cache state under test.+ const resolvedDeviceLinkDeviceId = arguments.length >= 5 ? deviceLinkDeviceId : null;const ctx: TabKindHostContext = {tabId: 'tab-browser',sessionId: 'session-a',workdir: 'C:/repo',remoteHostId: null,+ deviceLinkDeviceId: resolvedDeviceLinkDeviceId,patchState,onVisibilityChange: vi.fn(),setCloseInterceptor: vi.fn(() => () => undefined),@@ -109,6 +148,8 @@ describe('BrowserTabBody navigation', () => {configurable: true,value: {platform: 'win32',+ openExternal: vi.fn().mockResolvedValue({ success: true }),+ openFileInBrowser: vi.fn().mockResolvedValue({ success: true }),onRsbBrowserFocusUrlBar: vi.fn(() => vi.fn()),onRsbBrowserCommand: vi.fn(() => vi.fn()),},@@ -120,6 +161,8 @@ describe('BrowserTabBody navigation', () => {poolMocks.currentWrapper = null;document.getElementById('browser-webview-pool')?.remove();vi.clearAllMocks();+ toastMocks.error.mockReset();+ toastMocks.success.mockReset();browserState = makeBrowserState();});@@ -480,4 +523,157 @@ describe('BrowserTabBody navigation', () => {expect(browserNavigate).not.toHaveBeenCalled();});++ it('opens a local HTML page through the file opener, preserving URL state', async () => {+ const openExternal = vi.fn().mockResolvedValue({ success: true });+ const openFileInBrowser = vi.fn().mockResolvedValue({ success: true });+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'win32',+ openExternal,+ openFileInBrowser,+ onRsbBrowserFocusUrlBar: vi.fn(() => vi.fn()),+ onRsbBrowserCommand: vi.fn(() => vi.fn()),+ },+ });+ browserState = makeBrowserState({+ url: 'file:///C:/repo/%E6%B5%8B%E8%AF%95%20page.html?mode=review#section',+ });+ render(+ renderBrowserTab(+ 'file:///C:/repo/%E6%B5%8B%E8%AF%95%20page.html?mode=review#section',+ ),+ );++ fireEvent.click(+ screen.getByRole('button', { name: 'rightSidebar.browser.openInSystemBrowser' }),+ );+ await Promise.resolve();++ expect(openFileInBrowser).toHaveBeenCalledWith(+ 'file:///C:/repo/%E6%B5%8B%E8%AF%95%20page.html?mode=review#section',+ );+ expect(openExternal).not.toHaveBeenCalled();+ });++ it('shows the file opener error when opening a local HTML page fails', async () => {+ const openFileInBrowser = vi.fn().mockRejectedValue(+ new Error('[BROWSER_FILE_NOT_FOUND] 文件不存在'),+ );+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'win32',+ openExternal: vi.fn().mockResolvedValue({ success: true }),+ openFileInBrowser,+ onRsbBrowserFocusUrlBar: vi.fn(() => vi.fn()),+ onRsbBrowserCommand: vi.fn(() => vi.fn()),+ },+ });+ browserState = makeBrowserState({ url: 'file:///tmp/missing.html' });+ render(renderBrowserTab('file:///tmp/missing.html'));++ fireEvent.click(+ screen.getByRole('button', { name: 'rightSidebar.browser.openInSystemBrowser' }),+ );+ await Promise.resolve();+ await Promise.resolve();++ expect(toastMocks.error).toHaveBeenCalledWith(+ 'chat.markdownRenderer.BROWSER_FILE_NOT_FOUND',+ );+ });++ it('keeps HTTP pages on the external URL opener', async () => {+ const openExternal = vi.fn().mockResolvedValue({ success: true });+ const openFileInBrowser = vi.fn().mockResolvedValue({ success: true });+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'win32',+ openExternal,+ openFileInBrowser,+ onRsbBrowserFocusUrlBar: vi.fn(() => vi.fn()),+ onRsbBrowserCommand: vi.fn(() => vi.fn()),+ },+ });+ browserState = makeBrowserState({ url: 'https://example.com/path?q=1' });+ render(renderBrowserTab('https://example.com/path?q=1'));++ fireEvent.click(+ screen.getByRole('button', { name: 'rightSidebar.browser.openInSystemBrowser' }),+ );+ await Promise.resolve();++ expect(openExternal).toHaveBeenCalledWith('https://example.com/path?q=1');+ expect(openFileInBrowser).not.toHaveBeenCalled();+ });++ it('disables system-browser opening for remote local-file URLs', () => {+ browserState = makeBrowserState({ url: 'file:///remote/repo/index.html' });+ const ctx: TabKindHostContext = {+ tabId: 'tab-browser',+ sessionId: 'session-a',+ workdir: 'C:/repo',+ remoteHostId: 'ssh-host',+ patchState: vi.fn(),+ onVisibilityChange: vi.fn(),+ setCloseInterceptor: vi.fn(() => () => undefined),+ };+ render(+ createElement(BrowserTabBody, {+ active: true,+ ctx,+ state: {+ url: 'file:///remote/repo/index.html',+ title: '',+ favicon: null,+ isAudible: false,+ },+ }),+ );++ expect(+ (screen.getByRole('button', {+ name: 'rightSidebar.browser.openInSystemBrowser',+ }) as HTMLButtonElement).disabled,+ ).toBe(true);+ expect(+ (screen.getByRole('button', { name: 'rightSidebar.browser.copyLink' }) as HTMLButtonElement)+ .disabled,+ ).toBe(false);+ });++ it('disables system-browser opening for device-link local-file URLs', async () => {+ browserState = makeBrowserState({ url: 'file:///remote/repo/index.html' });+ render(renderBrowserTab('file:///remote/repo/index.html', vi.fn(), true, {}, 'device-1'));++ expect(+ (screen.getByRole('button', {+ name: 'rightSidebar.browser.openInSystemBrowser',+ }) as HTMLButtonElement).disabled,+ ).toBe(true);+ });++ it('disables system-browser opening until device-link ownership is resolved', () => {+ browserState = makeBrowserState({ url: 'file:///remote/repo/index.html' });+ render(renderBrowserTab('file:///remote/repo/index.html', vi.fn(), true, {}, undefined));++ expect(+ (screen.getByRole('button', {+ name: 'rightSidebar.browser.openInSystemBrowser',+ }) as HTMLButtonElement).disabled,+ ).toBe(true);+ });++ it.each([+ ['remote device-link', 'device-1' as string | undefined],+ ['unresolved device-link', undefined],+ ])('disables local HTML auto reload for %s sessions', (_label, deviceLinkDeviceId) => {+ browserState = makeBrowserState({ url: 'file:///remote/repo/index.html' });+ render(renderBrowserTab('file:///remote/repo/index.html', vi.fn(), true, {}, deviceLinkDeviceId));++ expect(vi.mocked(useLocalHtmlAutoReload).mock.lastCall?.[0].enabled).toBe(false);+ });});diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.tsindex 622e4faac2..54a0b9aabf 100644--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts@@ -88,6 +88,11 @@ export interface TabKindHostContext {* 远端 file-service。plugin 据此关闭本地-only 能力(watch / 系统打开 / 搜索)。*/remoteHostId: string | null;+ /**+ * device-link 会话归属:字符串 = 被控设备,null = 已确认本机,undefined = 归属尚未解析。+ * 本地-only 能力必须对 undefined fail closed,避免冷启动竞态把远端路径交给本机。+ */+ deviceLinkDeviceId?: string | null;patchState: (patch: unknown) => void;onVisibilityChange: (visible: boolean) => void;setCloseInterceptor: (interceptor: TabCloseInterceptor | null) => () => void;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 2de1183357..12a456d039 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5918,6 +5918,11 @@"openInBrowser": "Open in browser","fileCopied": "File copied","pathCopied": "Path copied",+ "BROWSER_FILE_INVALID_TARGET": "The local page path is invalid",+ "BROWSER_FILE_PATH_NOT_ALLOWED": "This path is not allowed",+ "BROWSER_FILE_UNSUPPORTED_TYPE": "This file type cannot be opened in a browser",+ "BROWSER_FILE_NOT_FOUND": "The local page was not found",+ "BROWSER_FILE_OPEN_FAILED": "Failed to open in browser","openInBrowserFailed": "Failed to open in browser","openLinkFailed": "Failed to open link","anchorNotFound": "Heading not found",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 450805e5d9..5b6f133100 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5916,6 +5916,11 @@"openInBrowser": "ブラウザで開く","fileCopied": "ファイルをコピーしました","pathCopied": "パスをコピーしました",+ "BROWSER_FILE_INVALID_TARGET": "ローカルページのパスが無効です",+ "BROWSER_FILE_PATH_NOT_ALLOWED": "このパスにはアクセスできません",+ "BROWSER_FILE_UNSUPPORTED_TYPE": "このファイル形式はブラウザで開けません",+ "BROWSER_FILE_NOT_FOUND": "ローカルページが見つかりません",+ "BROWSER_FILE_OPEN_FAILED": "ブラウザで開けませんでした","openInBrowserFailed": "ブラウザで開けませんでした","openLinkFailed": "リンクを開けませんでした","anchorNotFound": "対応する見出しが見つかりません",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b919900d28..cb6c3a3ee3 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5916,6 +5916,11 @@"openInBrowser": "브라우저에서 열기","fileCopied": "파일이 복사되었습니다","pathCopied": "경로가 복사되었습니다",+ "BROWSER_FILE_INVALID_TARGET": "로컬 페이지 경로가 올바르지 않습니다",+ "BROWSER_FILE_PATH_NOT_ALLOWED": "이 경로에는 접근할 수 없습니다",+ "BROWSER_FILE_UNSUPPORTED_TYPE": "이 파일 형식은 브라우저에서 열 수 없습니다",+ "BROWSER_FILE_NOT_FOUND": "로컬 페이지를 찾을 수 없습니다",+ "BROWSER_FILE_OPEN_FAILED": "브라우저에서 열지 못했습니다","openInBrowserFailed": "브라우저에서 열지 못했습니다","openLinkFailed": "링크를 열지 못했습니다","anchorNotFound": "해당 제목을 찾을 수 없습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 8e9d55f4eb..83860143d0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5916,6 +5916,11 @@"openInBrowser": "在浏览器中查看","fileCopied": "文件已复制","pathCopied": "路径已复制",+ "BROWSER_FILE_INVALID_TARGET": "本地页面路径无效",+ "BROWSER_FILE_PATH_NOT_ALLOWED": "不允许访问该路径",+ "BROWSER_FILE_UNSUPPORTED_TYPE": "该文件类型无法在浏览器中打开",+ "BROWSER_FILE_NOT_FOUND": "未找到本地页面",+ "BROWSER_FILE_OPEN_FAILED": "在浏览器中打开失败","openInBrowserFailed": "在浏览器中打开失败","openLinkFailed": "打开链接失败","anchorNotFound": "未找到对应标题",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 1e65c30c0d..72276b7d1d 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1614,6 +1614,7 @@ interface ElectronAPI {sessionId: string | null;workdir: string | null;remoteHostId: string | null;+ deviceLinkDeviceId?: string | null;available: boolean;} | null>;/** 子窗口根组件挂载握手。 */@@ -1628,6 +1629,7 @@ interface ElectronAPI {sessionId: string | null;workdir: string | null;remoteHostId: string | null;+ deviceLinkDeviceId?: string | null;available: boolean;}) => void;onStateChanged: (cb: (state: { detached: boolean; open: boolean }) => void) => () => void;@@ -1636,6 +1638,7 @@ interface ElectronAPI {sessionId: string | null;workdir: string | null;remoteHostId: string | null;+ deviceLinkDeviceId?: string | null;available: boolean;}) => void,) => () => void;@@ -2208,9 +2211,8 @@ interface ElectronAPI {openExternal: (url: string) => Promise<{ success: boolean }>;openChatGPTApp: () => Promise<{ success: boolean }>;- // file-chip 右键菜单 "在浏览器中查看": 把本地文件用 file:// 喂给系统- // 默认浏览器(或 .html/.pdf/.svg 等扩展名的默认 handler)。- openFileInBrowser: (filePath: string) => Promise<{ success: boolean; error?: string }>;+ // 绝对路径或完整本地 file:// URL;URL 形态用于保留 query/hash 页面状态。+ openFileInBrowser: (filePathOrUrl: string) => Promise<{ success: true }>;// ── 系统级通知(CC Agent session 状态变更)──/**diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex af8c055a25..36affb5e1f 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -133,6 +133,12 @@ export type IpcErrorCode =// 个人资料自助修改(settings → 用户卡片;服务端直写)| 'PROFILE_AVATAR_UPLOAD_FAILED' // 头像经 oss-server 预签名直传失败(presign 或 PUT 阶段)| 'PROFILE_UPDATE_FAILED' // PATCH /api/me/profile 失败(网络 / 服务端拒绝)+ // 本机 HTML 页面打开到系统浏览器+ | 'BROWSER_FILE_INVALID_TARGET'+ | 'BROWSER_FILE_PATH_NOT_ALLOWED'+ | 'BROWSER_FILE_UNSUPPORTED_TYPE'+ | 'BROWSER_FILE_NOT_FOUND'+ | 'BROWSER_FILE_OPEN_FAILED'// 会话分享(.cshare 导出/导入)| 'SHARE_FILE_INVALID' // 不是 .cshare / 头或 manifest 损坏 / payload 不是 zip| 'SHARE_PASSWORD_REQUIRED' // 文件已加密但未提供密码@@ -257,6 +263,11 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['DINGTALK_STREAM_CONNECTION_FAILED','PROFILE_AVATAR_UPLOAD_FAILED','PROFILE_UPDATE_FAILED',+ 'BROWSER_FILE_INVALID_TARGET',+ 'BROWSER_FILE_PATH_NOT_ALLOWED',+ 'BROWSER_FILE_UNSUPPORTED_TYPE',+ 'BROWSER_FILE_NOT_FOUND',+ 'BROWSER_FILE_OPEN_FAILED','SHARE_FILE_INVALID','SHARE_PASSWORD_REQUIRED','SHARE_PASSWORD_WRONG',diff --git a/apps/desktop/src/shared/openFileInBrowser.ts b/apps/desktop/src/shared/openFileInBrowser.tsnew file mode 100644index 0000000000..a20e0c0a9b--- /dev/null+++ b/apps/desktop/src/shared/openFileInBrowser.ts@@ -0,0 +1,8 @@+import type { IpcErrorCode } from './ipc-errors';++/** Stable failure codes for the local HTML system-browser opener. */+export type BrowserFileOpenErrorCode = Extract<IpcErrorCode, `BROWSER_FILE_${string}`>;++export type BrowserFileOpenResult =+ | { success: true }+ | { success: false; error: string; errorCode: BrowserFileOpenErrorCode };diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.tsindex 1717ffe351..01ab334eca 100644--- a/apps/desktop/src/shared/rightSidebarWindow.ts+++ b/apps/desktop/src/shared/rightSidebarWindow.ts@@ -25,6 +25,8 @@ export interface RsbWindowContext {sessionId: string | null;workdir: string | null;remoteHostId: string | null;+ /** device-link 会话归属:null = 已确认本机,undefined = 尚未解析。 */+ deviceLinkDeviceId?: string | null;/** 当前主窗视图是否有侧边栏语义(设置页等无会话视图为 false,子窗口显示占位空态)。 */available: boolean;}