Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 缓存目录缺失时创建后打开 #3519 (#3523)
DavidShenXD193e9c0c259a
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex c50bcc75fe..1e0acd21fc 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -271,6 +271,7 @@ import {} from './cindy-media/cindyMediaProtocol';import * as cindyMediaBlobStore from './cindy-media/blobStore';import * as cindyChatAttachments from './cindy-media/chatAttachments';+import { openOrCreateFixedDirectory } from './cindy-media/fixedDirectory';import { createStorageIpcHandlers } from './cindy-media/storageIpc';import {getAllRegisteredDraftUrls,@@ -7245,22 +7246,14 @@ const registerIpcHandlers = () => {throwIpcError('INTERNAL', 'fixed cache directory action failed');}};- const openExistingFixedDirectory = async (+ const openFixedDirectory = (rootDir: string,canOpen: () => boolean = () => true,- ): Promise<boolean> => {- try {- const stat = await fs.promises.lstat(rootDir);- if (!stat.isDirectory()) return false;- } catch (err) {- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return false;- throw err;- }- if (!canOpen()) throw new Error('fixed directory owner changed before open');- const error = await shell.openPath(rootDir);- if (error) throw new Error(error);- return true;- };+ ): Promise<boolean> =>+ openOrCreateFixedDirectory(rootDir, {+ canOpen,+ openPath: (filePath) => shell.openPath(filePath),+ });// These actions intentionally accept no renderer path. The frozen xdt-image// cache has no owner metadata, so its confirmed cleanup applies to the whole// profile-level legacy root. Chat attachments remain scoped to the active@@ -7327,11 +7320,11 @@ const registerIpcHandlers = () => {getQueueScanTexts: collectAgentInputQueueScanTexts,loadSnapshotPayloads: loadAllQueueSnapshotPayloads,getRegisteredDraftUrls: getAllRegisteredDraftUrls,- openLegacyImagesDir: () => openExistingFixedDirectory(imageCacheStore.getCacheRoot()),+ openLegacyImagesDir: () => openFixedDirectory(imageCacheStore.getCacheRoot()),clearLegacyImagesDir: () => clearFixedDirectory(imageCacheStore.getCacheRoot()),openChatAttachmentsDir: () =>withActiveChatAttachmentRoot((rootDir, isCurrentOwner) =>- openExistingFixedDirectory(rootDir, isCurrentOwner),+ openFixedDirectory(rootDir, isCurrentOwner),),clearChatAttachmentsDir: () =>withActiveChatAttachmentRoot((rootDir, isCurrentOwner) =>diff --git a/apps/desktop/src/main/cindy-media/__tests__/fixedDirectory.test.ts b/apps/desktop/src/main/cindy-media/__tests__/fixedDirectory.test.tsnew file mode 100644index 0000000000..138f5e0adb--- /dev/null+++ b/apps/desktop/src/main/cindy-media/__tests__/fixedDirectory.test.ts@@ -0,0 +1,190 @@+import { describe, expect, it, vi } from 'vitest';+import type fs from 'node:fs';++import { openOrCreateFixedDirectory } from '../fixedDirectory';++function directoryStat(isDirectory: boolean): fs.Stats {+ return { isDirectory: () => isDirectory } as fs.Stats;+}++function missingPathError(): NodeJS.ErrnoException {+ return Object.assign(new Error('missing'), { code: 'ENOENT' });+}++describe('openOrCreateFixedDirectory', () => {+ it('creates a missing fixed directory before opening it', async () => {+ const lstat = vi.fn().mockRejectedValueOnce(missingPathError()).mockResolvedValueOnce(+ directoryStat(true),+ );+ const mkdir = vi.fn().mockResolvedValue(undefined);+ const openPath = vi.fn().mockResolvedValue('');+ const canOpen = vi.fn().mockReturnValue(true);++ await expect(+ openOrCreateFixedDirectory('C:\\cache\\images', {+ canOpen,+ fileSystem: { lstat, mkdir },+ openPath,+ }),+ ).resolves.toBe(true);++ expect(mkdir).toHaveBeenCalledWith('C:\\cache\\images', { recursive: true });+ expect(lstat).toHaveBeenCalledTimes(2);+ expect(canOpen).toHaveBeenCalledTimes(2);+ expect(openPath).toHaveBeenCalledWith('C:\\cache\\images');+ });++ it('recreates a directory removed by concurrent cleanup before opening it', async () => {+ const lstat = vi+ .fn()+ .mockRejectedValueOnce(missingPathError())+ .mockRejectedValueOnce(missingPathError())+ .mockResolvedValueOnce(directoryStat(true));+ const mkdir = vi.fn().mockResolvedValue(undefined);+ const openPath = vi.fn().mockResolvedValue('');++ await expect(+ openOrCreateFixedDirectory('/cache/images', {+ fileSystem: { lstat, mkdir },+ openPath,+ }),+ ).resolves.toBe(true);++ expect(mkdir).toHaveBeenCalledTimes(2);+ expect(openPath).toHaveBeenCalledWith('/cache/images');+ });++ it('keeps repeated concurrent deletion as a recoverable not-opened result', async () => {+ const mkdir = vi.fn().mockResolvedValue(undefined);+ const openPath = vi.fn();++ await expect(+ openOrCreateFixedDirectory('/cache/images', {+ fileSystem: {+ lstat: vi.fn().mockRejectedValue(missingPathError()),+ mkdir,+ },+ openPath,+ }),+ ).resolves.toBe(false);++ expect(mkdir).toHaveBeenCalledTimes(2);+ expect(openPath).not.toHaveBeenCalled();+ });++ it('opens an existing fixed directory without creating it again', async () => {+ const lstat = vi.fn().mockResolvedValue(directoryStat(true));+ const mkdir = vi.fn();+ const openPath = vi.fn().mockResolvedValue('');++ await expect(+ openOrCreateFixedDirectory('/cache/images', {+ fileSystem: { lstat, mkdir },+ openPath,+ }),+ ).resolves.toBe(true);++ expect(mkdir).not.toHaveBeenCalled();+ expect(openPath).toHaveBeenCalledWith('/cache/images');+ });++ it('does not open or replace a fixed path that is not a directory', async () => {+ const mkdir = vi.fn();+ const openPath = vi.fn();++ await expect(+ openOrCreateFixedDirectory('/cache/images', {+ fileSystem: {+ lstat: vi.fn().mockResolvedValue(directoryStat(false)),+ mkdir,+ },+ openPath,+ }),+ ).resolves.toBe(false);++ expect(mkdir).not.toHaveBeenCalled();+ expect(openPath).not.toHaveBeenCalled();+ });++ it('does not create a missing owner-scoped directory after the owner changes', async () => {+ const mkdir = vi.fn();+ const openPath = vi.fn();++ await expect(+ openOrCreateFixedDirectory('/cache/owner-a', {+ canOpen: () => false,+ fileSystem: {+ lstat: vi.fn().mockRejectedValue(missingPathError()),+ mkdir,+ },+ openPath,+ }),+ ).rejects.toThrow('fixed directory owner changed before open');++ expect(mkdir).not.toHaveBeenCalled();+ expect(openPath).not.toHaveBeenCalled();+ });++ it('rechecks the owner after creating the directory and before opening it', async () => {+ const canOpen = vi.fn().mockReturnValueOnce(true).mockReturnValueOnce(false);+ const openPath = vi.fn();++ await expect(+ openOrCreateFixedDirectory('/cache/owner-a', {+ canOpen,+ fileSystem: {+ lstat: vi+ .fn()+ .mockRejectedValueOnce(missingPathError())+ .mockResolvedValueOnce(directoryStat(true)),+ mkdir: vi.fn().mockResolvedValue(undefined),+ },+ openPath,+ }),+ ).rejects.toThrow('fixed directory owner changed before open');++ expect(openPath).not.toHaveBeenCalled();+ });++ it('propagates directory creation and shell opening failures', async () => {+ const createError = new Error('access denied');+ await expect(+ openOrCreateFixedDirectory('/cache/images', {+ fileSystem: {+ lstat: vi.fn().mockRejectedValue(missingPathError()),+ mkdir: vi.fn().mockRejectedValue(createError),+ },+ openPath: vi.fn(),+ }),+ ).rejects.toBe(createError);++ await expect(+ openOrCreateFixedDirectory('/cache/images', {+ fileSystem: {+ lstat: vi.fn().mockResolvedValue(directoryStat(true)),+ mkdir: vi.fn(),+ },+ openPath: vi.fn().mockResolvedValue('shell failed'),+ }),+ ).rejects.toThrow('shell failed');+ });++ it('keeps deletion during shell opening as a recoverable not-opened result', async () => {+ const openPath = vi.fn().mockResolvedValue('path disappeared');++ await expect(+ openOrCreateFixedDirectory('/cache/images', {+ fileSystem: {+ lstat: vi+ .fn()+ .mockResolvedValueOnce(directoryStat(true))+ .mockRejectedValueOnce(missingPathError()),+ mkdir: vi.fn(),+ },+ openPath,+ }),+ ).resolves.toBe(false);++ expect(openPath).toHaveBeenCalledWith('/cache/images');+ });+});diff --git a/apps/desktop/src/main/cindy-media/fixedDirectory.ts b/apps/desktop/src/main/cindy-media/fixedDirectory.tsnew file mode 100644index 0000000000..544484d34d--- /dev/null+++ b/apps/desktop/src/main/cindy-media/fixedDirectory.ts@@ -0,0 +1,45 @@+import fs from 'node:fs';++type FixedDirectoryFileSystem = Pick<typeof fs.promises, 'lstat' | 'mkdir'>;++const MAX_CREATE_ATTEMPTS = 2;++export interface OpenFixedDirectoryOptions {+ canOpen?: () => boolean;+ fileSystem?: FixedDirectoryFileSystem;+ openPath: (filePath: string) => Promise<string>;+}++export async function openOrCreateFixedDirectory(+ rootDir: string,+ options: OpenFixedDirectoryOptions,+): Promise<boolean> {+ const canOpen = options.canOpen ?? (() => true);+ const fileSystem = options.fileSystem ?? fs.promises;+ const lstatIfExists = async () => {+ try {+ return await fileSystem.lstat(rootDir);+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return null;+ throw error;+ }+ };++ let stat = await lstatIfExists();+ for (let attempt = 0; stat === null && attempt < MAX_CREATE_ATTEMPTS; attempt += 1) {+ if (!canOpen()) throw new Error('fixed directory owner changed before open');+ await fileSystem.mkdir(rootDir, { recursive: true });+ stat = await lstatIfExists();+ }++ if (stat === null) return false;+ if (!stat.isDirectory()) return false;+ if (!canOpen()) throw new Error('fixed directory owner changed before open');++ const error = await options.openPath(rootDir);+ if (error) {+ if ((await lstatIfExists()) === null) return false;+ throw new Error(error);+ }+ return true;+}diff --git a/apps/desktop/src/main/cindy-media/storageIpc.ts b/apps/desktop/src/main/cindy-media/storageIpc.tsindex 7489842137..d459b82f52 100644--- a/apps/desktop/src/main/cindy-media/storageIpc.ts+++ b/apps/desktop/src/main/cindy-media/storageIpc.ts@@ -43,7 +43,7 @@ export interface StorageIpcDeps {db?: ledger.LedgerDb;/** 测试注入死目录根;生产缺省 userData/cc-agent。 */legacyRootDir?: string;- /** Fixed-purpose directory opener. It returns false when the legacy directory is absent. */+ /** Fixed-purpose directory opener. It returns false when the fixed path is not a directory. */openLegacyImagesDir?: () => Promise<boolean>;/** Delete only the fixed legacy image cache directory; no ledger or message lookup. */clearLegacyImagesDir?: () => Promise<void>;diff --git a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsxindex 5b376003f2..5ae7de268d 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/StorageManagementCard.test.tsx@@ -112,7 +112,7 @@ describe('StorageManagementCard fixed cache directories', () => {});});- it('reports a missing legacy directory without creating one', async () => {+ it('reports when Main cannot open the fixed legacy directory', async () => {vi.mocked(window.electronAPI.cindyMediaStorage.openLegacyImagesDir).mockResolvedValue({opened: false,});