From f5d1c31b3bcb0d65944b72a30195189a6127c19b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 30 Oct 2025 00:28:55 -0500 Subject: [PATCH] Electron FS performance improvements & fixes --- electron/main.js | 10 ++ src/hooks/useGitStatus.ts | 15 ++- src/lib/ElectronFSAdapter.ts | 175 +++++++++++++++++++++++++++++++++-- src/lib/tools/ShellTool.ts | 14 +-- 4 files changed, 194 insertions(+), 20 deletions(-) diff --git a/electron/main.js b/electron/main.js index 0ed98cc5..a50bbd35 100644 --- a/electron/main.js +++ b/electron/main.js @@ -190,6 +190,7 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => { if (!filePath) { const err = new Error('Failed to read file: path is required'); err.code = 'EINVAL'; + // Don't log - empty paths are expected from isomorphic-git's ref resolution throw err; } try { @@ -210,6 +211,11 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => { configurable: true, }); } + // Don't log ENOENT errors - these are expected for git packed objects and missing refs + // Only log unexpected errors + if (error.code !== 'ENOENT' && error.code !== 'EINVAL') { + console.error(err); + } throw err; } }); @@ -267,6 +273,10 @@ ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => { configurable: true, }); } + // Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory) + if (error.code !== 'ENOTDIR') { + console.error(err); + } throw err; } }); diff --git a/src/hooks/useGitStatus.ts b/src/hooks/useGitStatus.ts index a4bbaf8f..08340d70 100644 --- a/src/hooks/useGitStatus.ts +++ b/src/hooks/useGitStatus.ts @@ -90,7 +90,8 @@ export function useGitStatus(projectId: string | null) { dir: cwd, fullname: false, }); - currentBranch = branch || null; + // Ensure we have a valid branch name (not empty string or undefined) + currentBranch = (branch && branch.trim() !== '') ? branch : null; } catch (error) { console.warn('Could not get current branch:', error); } @@ -150,6 +151,11 @@ export function useGitStatus(projectId: string | null) { }); for (const remote of remoteNames) { + // Skip remotes with empty names + if (!remote.remote || !remote.url) { + console.warn('Skipping remote with empty name or URL:', remote); + continue; + } remotes.push({ name: remote.remote, url: remote.url, @@ -197,6 +203,13 @@ export function useGitStatus(projectId: string | null) { try { if (currentBranch && remotes.length > 0) { const remote = remotes[0]; // Use first remote (usually 'origin') + + // Validate remote and branch names before constructing ref + if (!remote.name || !currentBranch) { + console.warn('Invalid remote or branch name for ahead/behind calculation'); + throw new Error('Invalid remote or branch name'); + } + const remoteBranchName = `${remote.name}/${currentBranch}`; try { diff --git a/src/lib/ElectronFSAdapter.ts b/src/lib/ElectronFSAdapter.ts index c445c9d3..fbb2207f 100644 --- a/src/lib/ElectronFSAdapter.ts +++ b/src/lib/ElectronFSAdapter.ts @@ -8,6 +8,14 @@ import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime'; * Note: This adapter should only be instantiated when running in Electron. */ export class ElectronFSAdapter implements JSRuntimeFS { + // Cache for stat results to avoid repeated IPC calls + private statCache = new Map>; timestamp: number }>(); + private readonly STAT_CACHE_TTL = 1000; // 1 second TTL for stat cache + + // Cache for ENOENT results to avoid repeated failed reads (especially for git objects) + private enoentCache = new Set(); + private readonly ENOENT_CACHE_MAX_SIZE = 5000; + private get electron() { if (!window.electron) { throw new Error('ElectronFSAdapter can only be used in Electron environment'); @@ -55,6 +63,20 @@ export class ElectronFSAdapter implements JSRuntimeFS { async readFile(path: string, options?: string | { encoding?: string }): Promise>; async readFile(path: string, options?: string | { encoding?: string }): Promise> { try { + // Validate path is not empty (isomorphic-git sometimes passes empty strings during ref resolution) + if (!path || path.trim() === '') { + const err = new Error(`EINVAL: invalid path ''`); + (err as NodeJS.ErrnoException).code = 'EINVAL'; + throw err; + } + + // Check if we've already seen ENOENT for this path (common for git packed objects) + if (this.enoentCache.has(path)) { + const err = new Error(`ENOENT: no such file or directory, open '${path}'`); + (err as NodeJS.ErrnoException).code = 'ENOENT'; + throw err; + } + const encoding = typeof options === 'string' ? options : options?.encoding; const result = await this.electron.fs.readFile(path, encoding); @@ -65,7 +87,22 @@ export class ElectronFSAdapter implements JSRuntimeFS { return result as string; } catch (error) { - throw this.unwrapElectronError(error); + const unwrapped = this.unwrapElectronError(error); + + // Cache ENOENT errors to avoid repeated IPC calls for missing files + // This is especially important for git packed objects that isomorphic-git tries to read + if ((unwrapped as NodeJS.ErrnoException).code === 'ENOENT') { + this.enoentCache.add(path); + + // Limit cache size to prevent memory leaks + if (this.enoentCache.size > this.ENOENT_CACHE_MAX_SIZE) { + // Clear oldest entries (first 1000) + const entries = Array.from(this.enoentCache); + entries.slice(0, 1000).forEach(entry => this.enoentCache.delete(entry)); + } + } + + throw unwrapped; } } @@ -74,7 +111,19 @@ export class ElectronFSAdapter implements JSRuntimeFS { const encoding = typeof options === 'string' ? options : options?.encoding; // Convert Uint8Array to regular array for IPC serialization const dataToWrite = data instanceof Uint8Array ? Array.from(data) : data; - return await this.electron.fs.writeFile(path, dataToWrite, encoding); + const result = await this.electron.fs.writeFile(path, dataToWrite, encoding); + + // Invalidate caches for this path and its parent directory + this.statCache.delete(path); + this.statCache.delete(`lstat:${path}`); + this.enoentCache.delete(path); // File now exists + const parentDir = path.substring(0, path.lastIndexOf('/')); + if (parentDir) { + this.statCache.delete(parentDir); + this.statCache.delete(`lstat:${parentDir}`); + } + + return result; } catch (error) { throw this.unwrapElectronError(error); } @@ -85,6 +134,18 @@ export class ElectronFSAdapter implements JSRuntimeFS { async readdir(path: string, options?: { withFileTypes?: boolean }): Promise; async readdir(path: string, options?: { withFileTypes?: boolean }): Promise { try { + // Fast path: check if this is a file first (common case causing errors) + // Use cached stat if available to avoid extra IPC call + const cached = this.statCache.get(path); + if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) { + if (cached.result.isFile) { + // This is a file, not a directory - throw ENOTDIR immediately + const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`); + (err as NodeJS.ErrnoException).code = 'ENOTDIR'; + throw err; + } + } + const result = await this.electron.fs.readdir(path, options?.withFileTypes); if (options?.withFileTypes) { @@ -107,7 +168,18 @@ export class ElectronFSAdapter implements JSRuntimeFS { // Default to recursive: true for isomorphic-git compatibility // isomorphic-git expects mkdir to behave like 'mkdir -p' const recursive = options?.recursive !== false; - return await this.electron.fs.mkdir(path, recursive); + const result = await this.electron.fs.mkdir(path, recursive); + + // Invalidate cache for this path and parent + this.statCache.delete(path); + this.statCache.delete(`lstat:${path}`); + const parentDir = path.substring(0, path.lastIndexOf('/')); + if (parentDir) { + this.statCache.delete(parentDir); + this.statCache.delete(`lstat:${parentDir}`); + } + + return result; } catch (error) { throw this.unwrapElectronError(error); } @@ -130,9 +202,15 @@ export class ElectronFSAdapter implements JSRuntimeFS { atime: Date; }> { try { + // Check cache first + const cached = this.statCache.get(path); + if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) { + return cached.result; + } + const result = await this.electron.fs.stat(path); const now = Date.now(); - return { + const statResult = { isDirectory: () => result.isDirectory, isFile: () => result.isFile, isBlockDevice: () => result.isBlockDevice, @@ -149,6 +227,18 @@ export class ElectronFSAdapter implements JSRuntimeFS { ctime: new Date(result.ctime ?? now), atime: new Date(result.atime ?? now), }; + + // Cache the result + this.statCache.set(path, { result: statResult, timestamp: Date.now() }); + + // Limit cache size to prevent memory leaks + if (this.statCache.size > 10000) { + // Remove oldest entries (first 1000) + const entries = Array.from(this.statCache.entries()); + entries.slice(0, 1000).forEach(([key]) => this.statCache.delete(key)); + } + + return statResult; } catch (error) { // Electron IPC wraps errors, extract the original error code throw this.unwrapElectronError(error); @@ -172,9 +262,16 @@ export class ElectronFSAdapter implements JSRuntimeFS { atime: Date; }> { try { + // Check cache first (use separate cache key for lstat) + const cacheKey = `lstat:${path}`; + const cached = this.statCache.get(cacheKey); + if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) { + return cached.result; + } + const result = await this.electron.fs.lstat(path); const now = Date.now(); - return { + const statResult = { isDirectory: () => result.isDirectory, isFile: () => result.isFile, isBlockDevice: () => result.isBlockDevice, @@ -191,6 +288,18 @@ export class ElectronFSAdapter implements JSRuntimeFS { ctime: new Date(result.ctime ?? now), atime: new Date(result.atime ?? now), }; + + // Cache the result + this.statCache.set(cacheKey, { result: statResult, timestamp: Date.now() }); + + // Limit cache size to prevent memory leaks + if (this.statCache.size > 10000) { + // Remove oldest entries (first 1000) + const entries = Array.from(this.statCache.entries()); + entries.slice(0, 1000).forEach(([key]) => this.statCache.delete(key)); + } + + return statResult; } catch (error) { throw this.unwrapElectronError(error); } @@ -198,7 +307,18 @@ export class ElectronFSAdapter implements JSRuntimeFS { async unlink(path: string): Promise { try { - return await this.electron.fs.unlink(path); + const result = await this.electron.fs.unlink(path); + + // Invalidate cache for this path and parent + this.statCache.delete(path); + this.statCache.delete(`lstat:${path}`); + const parentDir = path.substring(0, path.lastIndexOf('/')); + if (parentDir) { + this.statCache.delete(parentDir); + this.statCache.delete(`lstat:${parentDir}`); + } + + return result; } catch (error) { throw this.unwrapElectronError(error); } @@ -206,7 +326,18 @@ export class ElectronFSAdapter implements JSRuntimeFS { async rmdir(path: string): Promise { try { - return await this.electron.fs.rmdir(path); + const result = await this.electron.fs.rmdir(path); + + // Invalidate cache for this path and parent + this.statCache.delete(path); + this.statCache.delete(`lstat:${path}`); + const parentDir = path.substring(0, path.lastIndexOf('/')); + if (parentDir) { + this.statCache.delete(parentDir); + this.statCache.delete(`lstat:${parentDir}`); + } + + return result; } catch (error) { throw this.unwrapElectronError(error); } @@ -214,7 +345,27 @@ export class ElectronFSAdapter implements JSRuntimeFS { async rename(oldPath: string, newPath: string): Promise { try { - return await this.electron.fs.rename(oldPath, newPath); + const result = await this.electron.fs.rename(oldPath, newPath); + + // Invalidate cache for both paths and their parents + this.statCache.delete(oldPath); + this.statCache.delete(`lstat:${oldPath}`); + this.statCache.delete(newPath); + this.statCache.delete(`lstat:${newPath}`); + + const oldParent = oldPath.substring(0, oldPath.lastIndexOf('/')); + if (oldParent) { + this.statCache.delete(oldParent); + this.statCache.delete(`lstat:${oldParent}`); + } + + const newParent = newPath.substring(0, newPath.lastIndexOf('/')); + if (newParent) { + this.statCache.delete(newParent); + this.statCache.delete(`lstat:${newParent}`); + } + + return result; } catch (error) { throw this.unwrapElectronError(error); } @@ -235,4 +386,12 @@ export class ElectronFSAdapter implements JSRuntimeFS { throw this.unwrapElectronError(error); } } + + /** + * Clear all caches. Useful when switching projects or after major filesystem changes. + */ + clearCaches(): void { + this.statCache.clear(); + this.enoentCache.clear(); + } } diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index f286fd43..85e4c874 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -357,17 +357,9 @@ export class ShellTool implements Tool { } try { - // Get relative path from projects root - // Remove the projectsPath prefix to get the relative path for the OS - const projectsPrefix = this.projectsPath.endsWith('/') - ? this.projectsPath - : this.projectsPath + '/'; - - const relativeCwd = this.cwd.startsWith(projectsPrefix) - ? this.cwd.substring(projectsPrefix.length) - : this.cwd; - - const result = await window.electron.shell.exec(commandStr, relativeCwd); + // In Electron, use the full cwd path (with ~ if present) + // The Electron main process will expand ~ to the home directory + const result = await window.electron.shell.exec(commandStr, this.cwd); // Strip ANSI codes from output (color codes, cursor movements, etc.) // This is important for AI consumption and consistent output