Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): normalize open-path IPC lifecycle failures (#4404)
fancivez05a0d318800d
diff --git a/apps/desktop/src/preload/__tests__/openPath.test.ts b/apps/desktop/src/preload/__tests__/openPath.test.tsnew file mode 100644index 0000000000..e89c638ae5--- /dev/null+++ b/apps/desktop/src/preload/__tests__/openPath.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it, vi } from 'vitest';+import { invokeOpenPath } from '../openPath';+import { shouldShowOpenPathError } from '../../shared/openPathResult';++describe('openPath IPC result boundary', () => {+ it.each([+ { success: true },+ { success: false, error: 'Path must be absolute' },+ { success: false, error: '不允许访问该路径' },+ { success: false, error: 'No application is associated with this file' },+ { success: false, error: 'reply was never sent' },+ ])('preserves main result %j', async (result) => {+ const invoke = vi.fn().mockResolvedValue(result);+ // The preload transports an opaque target; it does not resolve filesystem paths.+ expect(await invokeOpenPath(invoke, 'target')).toBe(result);+ expect(invoke).toHaveBeenCalledExactlyOnceWith('shell:open-path', 'target');+ expect(shouldShowOpenPathError(result)).toBe(!result.success);+ });++ it.each([+ 'reply was never sent',+ 'Render frame was disposed before WebFrameMain could be accessed',+ "Error invoking remote method 'shell:open-path': reply was never sent",+ "Error invoking remote method 'shell:open-path': Error: Render frame was disposed before WebFrameMain could be accessed",+ ])('keeps lifecycle rejection as failure without a toast: %s', async (message) => {+ const result = await invokeOpenPath(vi.fn().mockRejectedValue(new Error(message)), 'target');+ expect(result).toEqual({ success: false, error: message, failureKind: 'ipc_lifecycle' });+ expect(shouldShowOpenPathError(result)).toBe(false);+ });++ it.each([+ new Error(+ "Error invoking remote method 'shell:open-path': No handler registered for 'shell:open-path'",+ ),+ new Error('Permission denied'),+ new Error('Operation failed: reply was never sent'),+ 'non-Error rejection',+ ])('preserves actionable rejection %s', async (cause) => {+ const result = await invokeOpenPath(vi.fn().mockRejectedValue(cause), 'target');+ expect(result).toEqual({+ success: false,+ error: cause instanceof Error ? cause.message : cause,+ });+ expect(shouldShowOpenPathError(result)).toBe(true);+ });+});diff --git a/apps/desktop/src/preload/openPath.ts b/apps/desktop/src/preload/openPath.tsnew file mode 100644index 0000000000..da787ae7fd--- /dev/null+++ b/apps/desktop/src/preload/openPath.ts@@ -0,0 +1,26 @@+import type { OpenPathResult } from '../shared/openPathResult';++/** Keep invoke transport failures inside the existing openPath result boundary. */+export async function invokeOpenPath(+ invoke: (channel: string, target: string) => Promise<OpenPathResult>,+ target: string,+): Promise<OpenPathResult> {+ try {+ return await invoke('shell:open-path', target);+ } catch (cause) {+ const error = cause instanceof Error ? cause.message : String(cause);+ const message = error.replace(+ /^Error invoking remote method ['"]shell:open-path['"]: (?:Error: )?/,+ '',+ );+ // Classify only rejected IPC calls; main's path/OS errors pass through unchanged.+ // No handler registered can mean version skew or broken initialization.+ const lifecycle =+ /^(?:reply was never sent[.!]?|Render frame was disposed(?: before WebFrameMain could be accessed)?[.!]?)$/.test(+ message,+ );+ return lifecycle+ ? { success: false, error, failureKind: 'ipc_lifecycle' }+ : { success: false, error };+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e0f4f28a70..254d299493 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1,3 +1,4 @@+import { invokeOpenPath } from './openPath';import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';import type { RoutineInput } from '@cindy/maker-scheduler';import type { BotToolsetContext } from '../shared/botRemoteCapabilities';@@ -3757,8 +3758,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// Open a local absolute path or a main-resolved cindy-media reference with// the OS default application (the renderer never receives the blob path).- openPath: (filePathOrUrl: string): Promise<{ success: boolean; error?: string }> =>- ipcRenderer.invoke('shell:open-path', filePathOrUrl),+ openPath: (filePathOrUrl: string) => invokeOpenPath(ipcRenderer.invoke.bind(ipcRenderer), filePathOrUrl),// 文件 chip 右键「打开方式」。appId 只能是 listOpenWithApps 返回的 id,// main 侧反查可执行体;renderer 无法让 main 执行任意路径。diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex 826086aeb5..5bf07ab725 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -1,3 +1,4 @@+import { invokeOpenPath } from './openPath';/*** 鍙充晶鏍忓瓙绐楀彛涓撶敤 preload锛氬彧鏆撮湶 RSB 绐楀彛鎵€闇€鐨勬渶灏忚兘鍔涖€?*@@ -236,7 +237,7 @@ contextBridge.exposeInMainWorld('electronAPI', {},openExternal: (url: string): Promise<unknown> => ipcRenderer.invoke('shell:open-external', url),openFileInBrowser: (pathOrUrl: string): Promise<unknown> => ipcRenderer.invoke('shell:open-file-in-browser', pathOrUrl),- openPath: (pathOrUrl: string): Promise<unknown> => ipcRenderer.invoke('shell:open-path', pathOrUrl),+ openPath: (pathOrUrl: string) => invokeOpenPath(ipcRenderer.invoke.bind(ipcRenderer), pathOrUrl),showItemInFolder: (params: unknown): Promise<unknown> => ipcRenderer.invoke('shell:show-item-in-folder', params),copyMediaToClipboard: (params: unknown): Promise<unknown> =>ipcRenderer.invoke('media:copy-to-clipboard', params),diff --git a/apps/desktop/src/renderer/__tests__/openPathFeedback.test.ts b/apps/desktop/src/renderer/__tests__/openPathFeedback.test.tsnew file mode 100644index 0000000000..84bb3d013c--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/openPathFeedback.test.ts@@ -0,0 +1,40 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest';+import { invokeOpenPath } from '../../preload/openPath';+import { shouldOpenTextLightbox } from '../lib/filePreview';+import { toast } from '../lib/toast';++vi.mock('../lib/toast', () => ({ toast: { error: vi.fn() } }));+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));+vi.mock('../lib/remoteFileOpen', () => ({ openRemoteChatFile: vi.fn() }));++afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++describe('opening a non-text file from chat', () => {+ it.each([+ ['reply was never sent', false],+ ['Render frame was disposed before WebFrameMain could be accessed', false],+ ["No handler registered for 'shell:open-path'", true],+ ['Permission denied', true],+ ])('handles invoke rejection %s', async (message, visible) => {+ const invoke = vi.fn().mockRejectedValue(new Error(message));+ vi.stubGlobal('electronAPI', undefined);+ window.electronAPI = {+ openPath: (target: string) => invokeOpenPath(invoke, target),+ } as typeof window.electronAPI;+ expect(await shouldOpenTextLightbox('report.pdf')).toBe(false);+ expect(toast.error).toHaveBeenCalledTimes(visible ? 1 : 0);+ if (visible) expect(toast.error).toHaveBeenCalledWith(message);+ });++ it('still shows an ordinary system error returned by main', async () => {+ vi.stubGlobal('electronAPI', {+ openPath: vi.fn().mockResolvedValue({ success: false, error: 'No application associated' }),+ });+ await shouldOpenTextLightbox('report.pdf');+ expect(toast.error).toHaveBeenCalledWith('No application associated');+ });+});diff --git a/apps/desktop/src/renderer/components/chat/ModelLightbox.tsx b/apps/desktop/src/renderer/components/chat/ModelLightbox.tsxindex 6a7a277acf..8f0f163f7c 100644--- a/apps/desktop/src/renderer/components/chat/ModelLightbox.tsx+++ b/apps/desktop/src/renderer/components/chat/ModelLightbox.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../shared/openPathResult';/*** ModelLightbox* ---------------------------------------------------------------------------@@ -166,7 +167,7 @@ export function ModelLightbox({ source, onClose }: ModelLightboxProps) {action === 'open'? await window.electronAPI.openPath(source.absPath): await window.electronAPI.showItemInFolder({ filePath: source.absPath });- if (!res.success) {+ if (shouldShowOpenPathError(res)) {toast.error(res.error ??(action === 'open'diff --git a/apps/desktop/src/renderer/components/chat/TextLightbox.tsx b/apps/desktop/src/renderer/components/chat/TextLightbox.tsxindex 027926ad74..9c144c4e9c 100644--- a/apps/desktop/src/renderer/components/chat/TextLightbox.tsx+++ b/apps/desktop/src/renderer/components/chat/TextLightbox.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../shared/openPathResult';/*** TextLightbox* ---------------------------------------------------------------------------@@ -343,7 +344,7 @@ export function TextLightbox({ filePath, fileName, initialLine, triggerRef, onClconst target = remoteOrigin ? remoteCopy?.cachePath : filePath;if (!target) return;const res = await window.electronAPI.openPath(target);- if (!res.success) {+ if (shouldShowOpenPathError(res)) {toast.error(res.error || t('chat.textLightbox.openSystemFailed'));}}diff --git a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsxindex 9e16023505..f24b583c95 100644--- a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx+++ b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../shared/openPathResult';/*** useFileChipContextMenu* ---------------------------------------------------------------------------@@ -261,7 +262,7 @@ export function useFileChipContextMenu({setMenuPos(null);const abs = await getAbsPath();const res = await window.electronAPI.openPath(abs);- if (!res.success) toast.error(res.error ?? t('chat.markdownRenderer.openWithAppFailed'));+ if (shouldShowOpenPathError(res)) toast.error(res.error ?? t('chat.markdownRenderer.openWithAppFailed'));}async function handleOpenWithApp(appId: string): Promise<void> {diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsxindex 33321bf192..50d9e68c22 100644--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../shared/openPathResult';import { ConnectProviderCard } from '@/components/onboarding/ConnectProviderCard';import { useProviderOnboarding } from '@/hooks/useProviderOnboarding';import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';@@ -579,7 +580,7 @@ export function BotSettings({if (!bot.homeDir) return;setFolderError(null);void window.electronAPI.openPath(bot.homeDir).then((result) => {- if (!result.success)+ if (shouldShowOpenPathError(result))setFolderError(result.error ?? t('bots.homeFolder.openFailed'));});}}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex ffbfb35cf5..1ede34b3bd 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../shared/openPathResult';import { shouldShowFailedScheduleNotice } from '@cindy/maker-shared/schedule-model';/*** CCAgentSessionView@@ -1503,7 +1504,7 @@ export function CCAgentSessionView({if (isRemoteWorktreeSession) return;try {const result = await window.electronAPI.openPath(wd);- if (!result.success) toast.error(result.error || t('ccAgent.common.openFolderFailed'));+ if (shouldShowOpenPathError(result)) toast.error(result.error || t('ccAgent.common.openFolderFailed'));} catch (err) {log.error('[open workingDir]', err);toast.error(t('ccAgent.common.openFolderFailed'));diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex cfc4e4abe5..007608d85f 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../shared/openPathResult';/*** CCAgentFeature 的 Sidebar 上半内容。* ---------------------------------------------------------------------------@@ -2495,7 +2496,7 @@ function ExpandedView({async (workingDir: string) => {try {const result = await window.electronAPI.openPath(workingDir);- if (!result.success) {+ if (shouldShowOpenPathError(result)) {toast.error(result.error || t('ccAgent.common.openFolderFailed'));}} catch (err) {diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsxindex 48e590e5ea..e6aaaffe88 100644--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../../shared/openPathResult';import { ExternalLink, FolderOpen } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -23,7 +24,7 @@ export function OpenInSystemActions({const onOpenFile = async () => {try {const r = await window.electronAPI.openPath(absPath);- if (!r.success) toast.error(r.error || t('ccAgent.common.openFailed'));+ if (shouldShowOpenPathError(r)) toast.error(r.error || t('ccAgent.common.openFailed'));} catch (err) {toast.error(t('ccAgent.common.openFailedWith', {@@ -36,7 +37,7 @@ export function OpenInSystemActions({const onOpenFolder = async () => {try {const r = await window.electronAPI.openPath(folderPath);- if (!r.success) toast.error(r.error || t('ccAgent.common.openFolderFailed'));+ if (shouldShowOpenPathError(r)) toast.error(r.error || t('ccAgent.common.openFolderFailed'));} catch (err) {toast.error(t('ccAgent.common.openFolderFailedWith', {diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 5c3cc208de..423c425a93 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../shared/openPathResult';/*** Plugin detail presentation for configuration, Tools, permissions, and factual metadata.*@@ -944,7 +945,7 @@ export function DetailsSection({if (!installDir) return;void window.electronAPI.openPath(installDir).then((result) => {- if (!result.success) toast.error(t('settings.ghosts.errors.generic'));+ if (shouldShowOpenPathError(result)) toast.error(t('settings.ghosts.errors.generic'));},() => toast.error(t('settings.ghosts.errors.generic')),);diff --git a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsxindex 8f6cdb98e6..272ff7c539 100644--- a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx+++ b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../shared/openPathResult';/*** SchedulerPage — /schedules 主路由(master-detail 改版)* ---------------------------------------------------------------------------@@ -456,7 +457,7 @@ export function SchedulerPage() {const filePath = projectAutomationConfigPath(workingDir);try {const result = await window.electronAPI.openPath(filePath);- if (!result.success)+ if (shouldShowOpenPathError(result))toast.error(result.error || t('scheduler.list.section.openConfigFailed'));} catch (e) {toast.error(e instanceof Error ? e.message : String(e));diff --git a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsxindex 136d639f8f..1f82c4e996 100644--- a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../../../shared/openPathResult';/*** RunHistoryPane — 右侧执行历史面板* ---------------------------------------------------------------------------@@ -219,7 +220,7 @@ export function RunHistoryPane({if (!dest.workingDir) return;try {const result = await window.electronAPI.openPath(dest.workingDir);- if (!result.success) toast.error(result.error || t('scheduler.detail.openWorkdirFailed'));+ if (shouldShowOpenPathError(result)) toast.error(result.error || t('scheduler.detail.openWorkdirFailed'));} catch {toast.error(t('scheduler.detail.openWorkdirFailed'));}diff --git a/apps/desktop/src/renderer/lib/filePreview.ts b/apps/desktop/src/renderer/lib/filePreview.tsindex 8c31069dc5..de7736c633 100644--- a/apps/desktop/src/renderer/lib/filePreview.ts+++ b/apps/desktop/src/renderer/lib/filePreview.ts@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../shared/openPathResult';import { toast } from './toast';import { isTextPreviewSupported } from './textPreview';import { i18n } from '@/i18n';@@ -14,7 +15,7 @@ export async function shouldOpenTextLightbox(filePath: string): Promise<boolean>try {const res = await window.electronAPI.openPath(filePath);- if (!res.success) {+ if (shouldShowOpenPathError(res)) {toast.error(res.error || i18n.t('logic.errors.openFileFailed'));}} catch (err) {diff --git a/apps/desktop/src/renderer/lib/remoteFileOpen.ts b/apps/desktop/src/renderer/lib/remoteFileOpen.tsindex 808a9ffcc4..6d9e868461 100644--- a/apps/desktop/src/renderer/lib/remoteFileOpen.ts+++ b/apps/desktop/src/renderer/lib/remoteFileOpen.ts@@ -1,3 +1,4 @@+import { shouldShowOpenPathError } from '../../shared/openPathResult';/*** remoteFileOpen — 聊天流文件类交互的远程分流入口(renderer 侧)。* ---------------------------------------------------------------------------@@ -88,7 +89,7 @@ export async function openRemoteChatFile(const cachePath = await fetchChatFileWithToasts(origin, workdir, absPath);if (!cachePath) return;const res = await window.electronAPI.openPath(cachePath);- if (!res.success) toast.error(res.error || i18n.t('logic.errors.openFileFailed'));+ if (shouldShowOpenPathError(res)) toast.error(res.error || i18n.t('logic.errors.openFileFailed'));}/** 远程会话「定位文件」:取回缓存副本后在文件管理器中定位本地副本。 */diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 2c15d613c5..3653b30ab6 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2934,7 +2934,7 @@ interface ElectronAPI {* Open a local file path with the OS default application. Used by the* TextLightbox toolbar Open-in-System button and the Oversize main button.*/- openPath: (filePath: string) => Promise<{ success: boolean; error?: string }>;+ openPath: (filePath: string) => Promise<import('../shared/openPathResult').OpenPathResult>;/*** 文件 chip 右键「打开方式」:枚举可打开该文件的应用(Windows 注册表;diff --git a/apps/desktop/src/shared/openPathResult.ts b/apps/desktop/src/shared/openPathResult.tsnew file mode 100644index 0000000000..59b1f7a0d7--- /dev/null+++ b/apps/desktop/src/shared/openPathResult.ts@@ -0,0 +1,10 @@+/** An IPC lifecycle failure does not establish whether the OS opened the path. */+export interface OpenPathResult {+ success: boolean;+ error?: string;+ failureKind?: 'ipc_lifecycle';+}++export function shouldShowOpenPathError(result: OpenPathResult): boolean {+ return !result.success && result.failureKind !== 'ipc_lifecycle';+}