From 31b2a1eb4eefcede158b7eba7bd0ddbc60fdcc60 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Tue, 16 Dec 2025 22:04:34 -0800 Subject: [PATCH] windows path resolution for electron --- electron/main.js | 55 +++++++---- package-lock.json | 44 ++++++--- src/components/AppProvider.tsx | 15 +-- src/components/ImageLightbox.tsx | 3 +- src/components/ToolCallDisplay.tsx | 8 +- src/lib/ElectronFSAdapter.ts | 149 +++++++++++++++++++++++++++-- src/lib/build/fsPlugin.ts | 24 ++++- src/lib/pathUtils.ts | 120 +++++++++++++++++++++++ src/lib/security.ts | 12 ++- src/lib/tools/ShellTool.ts | 4 +- 10 files changed, 373 insertions(+), 61 deletions(-) create mode 100644 src/lib/pathUtils.ts diff --git a/electron/main.js b/electron/main.js index a50bbd35..4f192d10 100644 --- a/electron/main.js +++ b/electron/main.js @@ -178,9 +178,13 @@ ipcMain.handle('get-platform', () => { }); // Helper function to expand tilde (~) in paths +// Handles both Unix (~/) and Windows (~\) style paths function expandTilde(filepath) { - if (filepath.startsWith('~/') || filepath === '~') { - return path.join(os.homedir(), filepath.slice(1)); + if (filepath === '~') { + return os.homedir(); + } + if (filepath.startsWith('~/') || filepath.startsWith('~\\')) { + return path.join(os.homedir(), filepath.slice(2)); } return filepath; } @@ -188,10 +192,8 @@ function expandTilde(filepath) { // Filesystem IPC handlers 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; + // Return error object instead of throwing to avoid Electron's noisy error logging + return { __error: true, code: 'EINVAL', message: 'Failed to read file: path is required' }; } try { const fullPath = expandTilde(filePath); @@ -199,10 +201,13 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => { // If no encoding, convert Buffer to array for IPC serialization return encoding ? data : Array.from(data); } catch (error) { - // Re-throw with original error code preserved for ENOENT handling - // Serialize the error code as a regular property so it survives IPC + // For ENOENT/EINVAL errors, return error info instead of throwing to avoid Electron's noisy error logging + // These are expected during module resolution and git operations + if (error.code === 'ENOENT' || error.code === 'EINVAL') { + return { __error: true, code: error.code, message: `Failed to read file ${filePath}: ${error.message}` }; + } + // Re-throw other errors with original error code preserved const err = new Error(`Failed to read file ${filePath}: ${error.message}`); - // Copy enumerable properties including code if (error.code) { Object.defineProperty(err, 'code', { value: error.code, @@ -211,11 +216,7 @@ 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); - } + console.error(err); throw err; } }); @@ -263,7 +264,11 @@ ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => { return entries; } catch (error) { - // Re-throw with original error code preserved for ENOENT handling + // Return error object instead of throwing for expected errors to suppress Electron's noisy logging + if (error.code === 'ENOTDIR' || error.code === 'ENOENT') { + return { __error: true, message: error.message, code: error.code }; + } + // For other errors, re-throw with original error code preserved const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`); if (error.code) { Object.defineProperty(err, 'code', { @@ -273,10 +278,6 @@ 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; } }); @@ -323,7 +324,12 @@ ipcMain.handle('fs:stat', async (event, filePath) => { atime: stats.atime?.getTime() ?? now, }; } catch (error) { - // Re-throw with original error code preserved for ENOENT handling + // For ENOENT errors, return error info instead of throwing to avoid Electron's noisy error logging + // These are expected during module resolution and git operations + if (error.code === 'ENOENT') { + return { __error: true, code: 'ENOENT', message: `Failed to stat ${filePath}: ${error.message}` }; + } + // Re-throw other errors with original error code preserved const err = new Error(`Failed to stat ${filePath}: ${error.message}`); if (error.code) { Object.defineProperty(err, 'code', { @@ -361,6 +367,10 @@ ipcMain.handle('fs:lstat', async (event, filePath) => { atime: stats.atime?.getTime() ?? now, }; } catch (error) { + // For ENOENT errors, return error info instead of throwing to avoid Electron's noisy error logging + if (error.code === 'ENOENT') { + return { __error: true, code: 'ENOENT', message: `Failed to lstat ${filePath}: ${error.message}` }; + } const err = new Error(`Failed to lstat ${filePath}: ${error.message}`); if (error.code) { Object.defineProperty(err, 'code', { @@ -379,6 +389,11 @@ ipcMain.handle('fs:unlink', async (event, filePath) => { const fullPath = expandTilde(filePath); await fs.unlink(fullPath); } catch (error) { + // Return error object instead of throwing for ENOENT to suppress Electron's noisy logging + // This is expected when isomorphic-git tries to delete .git/shallow on non-shallow clones + if (error.code === 'ENOENT') { + return { __error: true, message: error.message, code: error.code }; + } const err = new Error(`Failed to unlink ${filePath}: ${error.message}`); if (error.code) { Object.defineProperty(err, 'code', { diff --git a/package-lock.json b/package-lock.json index 5e235ccb..bdcc103e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -196,6 +196,7 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -1831,6 +1832,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -1854,6 +1856,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" } @@ -1875,6 +1878,7 @@ "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", "license": "MIT", + "peer": true, "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", @@ -5459,8 +5463,7 @@ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@types/cacheable-request": { "version": "6.0.3", @@ -5702,6 +5705,7 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz", "integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==", "license": "MIT", + "peer": true, "dependencies": { "@types/prop-types": "*", "csstype": "^3.0.2" @@ -5713,6 +5717,7 @@ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", "devOptional": true, "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^18.0.0" } @@ -5817,6 +5822,7 @@ "integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.31.1", "@typescript-eslint/types": "8.31.1", @@ -6176,6 +6182,7 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -6679,6 +6686,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.19", "caniuse-lite": "^1.0.30001751", @@ -6947,6 +6955,7 @@ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "license": "MIT", + "peer": true, "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -7747,8 +7756,7 @@ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/dom-helpers": { "version": "5.2.1", @@ -7832,7 +7840,8 @@ "version": "8.6.0", "resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz", "integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/embla-carousel-react": { "version": "8.6.0", @@ -8146,6 +8155,7 @@ "integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", @@ -8411,6 +8421,7 @@ "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", "license": "MIT", + "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.0", @@ -9633,6 +9644,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.27.6" }, @@ -10416,6 +10428,7 @@ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", @@ -10812,7 +10825,6 @@ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "lz-string": "bin/bin.js" } @@ -12610,6 +12622,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.8", "picocolors": "^1.1.1", @@ -12777,7 +12790,6 @@ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", @@ -12793,7 +12805,6 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -12804,7 +12815,6 @@ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" }, @@ -12817,8 +12827,7 @@ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/prismjs": { "version": "1.30.0", @@ -13026,6 +13035,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -13052,6 +13062,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -13077,6 +13088,7 @@ "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz", "integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=18.0.0" }, @@ -13125,6 +13137,7 @@ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz", "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==", "license": "MIT", + "peer": true, "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", @@ -13706,6 +13719,7 @@ "integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { "@types/estree": "1.0.7" }, @@ -14820,6 +14834,7 @@ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz", "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", "license": "MIT", + "peer": true, "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", @@ -15023,6 +15038,7 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -15318,6 +15334,7 @@ "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -15845,6 +15862,7 @@ "integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", @@ -15989,6 +16007,7 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -16459,6 +16478,7 @@ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -16535,6 +16555,7 @@ "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "dev": true, "license": "MIT", + "peer": true, "bin": { "rollup": "dist/bin/rollup" }, @@ -16994,6 +17015,7 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index 069efb80..1a5cd3a6 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -3,6 +3,7 @@ import { z } from 'zod'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext'; import i18n from '@/lib/i18n'; +import { expandTildePath, normalizeToForwardSlashes } from '@/lib/pathUtils'; interface AppProviderProps { children: ReactNode; @@ -156,16 +157,16 @@ function useApplyLanguage(language?: string): void { }, [language]); } -/** Expand FS paths with the user's home directory, if available. */ +/** Expand FS paths with the user's home directory, if available. + * Also normalizes to forward slashes for cross-platform consistency. + */ function expandPath(path: string): string { const homedir = window.electron?.homedir; if (!homedir) { return path; - } else if (path.startsWith('~/')) { - return homedir + path.slice(1); - } else if (path === '~') { - return homedir; - } else { - return path; } + // Expand tilde and normalize to forward slashes for consistency + // This ensures paths work correctly on Windows where homedir uses backslashes + const expanded = expandTildePath(path, homedir); + return normalizeToForwardSlashes(expanded); } \ No newline at end of file diff --git a/src/components/ImageLightbox.tsx b/src/components/ImageLightbox.tsx index e8ef3350..23b8f19d 100644 --- a/src/components/ImageLightbox.tsx +++ b/src/components/ImageLightbox.tsx @@ -3,6 +3,7 @@ import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog'; import * as DialogPrimitive from '@radix-ui/react-dialog'; import { VFSImage } from '@/components/VFSImage'; import { cn } from '@/lib/utils'; +import { isAbsolutePath } from '@/lib/pathUtils'; interface ImageLightboxProps { imageUrl: string | null; @@ -46,7 +47,7 @@ export function ImageLightbox({ imageUrl, onClose }: ImageLightboxProps) { className="relative z-[2] flex items-center justify-center w-full h-full pointer-events-none" onClick={(e) => e.stopPropagation()} > - {imageUrl.startsWith('/') ? ( + {isAbsolutePath(imageUrl) ? ( " from result + // Path can be VFS style (/tmp/...) or OS path (C:/Users/.../Temp/... on Windows) + const match = result.match(/Generated image:\s*([^\s\n]+)/); if (match) { const imagePath = match[1]; - const filename = imagePath.split('/').pop() || imagePath; + // Handle both forward and back slashes for getting filename + const filename = imagePath.split(/[/\\]/).pop() || imagePath; // Hide the image section if there was a load error if (imageLoadError) return null; diff --git a/src/lib/ElectronFSAdapter.ts b/src/lib/ElectronFSAdapter.ts index fbb2207f..3eba8a58 100644 --- a/src/lib/ElectronFSAdapter.ts +++ b/src/lib/ElectronFSAdapter.ts @@ -1,4 +1,25 @@ import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime'; +import { getParentDirectory } from './pathUtils'; + +/** + * Error object returned from IPC handlers instead of throwing + * to avoid Electron's noisy error logging for expected errors. + */ +interface IPCErrorResult { + __error: true; + code: string; + message: string; +} + +/** + * Type guard to check if an IPC result is an error object. + */ +function isIPCError(result: unknown): result is IPCErrorResult { + return result !== null && + typeof result === 'object' && + '__error' in result && + (result as IPCErrorResult).__error === true; +} /** * Electron filesystem adapter that implements JSRuntimeFS interface @@ -7,9 +28,27 @@ import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime'; * * Note: This adapter should only be instantiated when running in Electron. */ +/** Stat result with function methods matching the JSRuntimeFS interface */ +interface StatResult { + isDirectory(): boolean; + isFile(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + size: number; + mtimeMs: number; + ctimeMs: number; + atimeMs: number; + mtime: Date; + ctime: Date; + atime: Date; +} + export class ElectronFSAdapter implements JSRuntimeFS { // Cache for stat results to avoid repeated IPC calls - private statCache = new Map>; timestamp: number }>(); + private statCache = new Map(); 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) @@ -80,6 +119,23 @@ export class ElectronFSAdapter implements JSRuntimeFS { const encoding = typeof options === 'string' ? options : options?.encoding; const result = await this.electron.fs.readFile(path, encoding); + // Handle error objects returned from IPC (to avoid Electron's noisy error logging) + if (isIPCError(result)) { + const err = new Error(result.message); + (err as NodeJS.ErrnoException).code = result.code; + + // Cache ENOENT errors + if (result.code === 'ENOENT') { + this.enoentCache.add(path); + if (this.enoentCache.size > this.ENOENT_CACHE_MAX_SIZE) { + const entries = Array.from(this.enoentCache); + entries.slice(0, 1000).forEach(entry => this.enoentCache.delete(entry)); + } + } + + throw err; + } + // If no encoding, convert array to Uint8Array if (!encoding && Array.isArray(result)) { return new Uint8Array(result); @@ -117,7 +173,7 @@ export class ElectronFSAdapter implements JSRuntimeFS { this.statCache.delete(path); this.statCache.delete(`lstat:${path}`); this.enoentCache.delete(path); // File now exists - const parentDir = path.substring(0, path.lastIndexOf('/')); + const parentDir = getParentDirectory(path); if (parentDir) { this.statCache.delete(parentDir); this.statCache.delete(`lstat:${parentDir}`); @@ -138,19 +194,71 @@ export class ElectronFSAdapter implements JSRuntimeFS { // 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) { + // Note: cached.result has isFile as a function (from statResult), so we must call it + 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; } + } else { + // No cached stat - do a stat check first to avoid unnecessary readdir IPC calls on files + // This is important for performance since FileTree iterates all entries and calls readdir on each + try { + const statResult = await this.stat(path); + if (statResult.isFile()) { + const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`); + (err as NodeJS.ErrnoException).code = 'ENOTDIR'; + throw err; + } + } catch (statError) { + // If stat fails with ENOENT, let readdir handle it + if ((statError as NodeJS.ErrnoException).code !== 'ENOENT') { + throw statError; + } + } } const result = await this.electron.fs.readdir(path, options?.withFileTypes); + // Handle error objects returned from IPC (to avoid Electron's noisy error logging) + if (isIPCError(result)) { + const err = new Error(result.message); + (err as NodeJS.ErrnoException).code = result.code; + throw err; + } + if (options?.withFileTypes) { + const entries = result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>; + const now = Date.now(); + + // Cache the file type info for each child entry to speed up subsequent stat/readdir calls + // This is a key optimization - FileTree calls readdir on all children, and we can fast-fail + // files without hitting IPC + for (const entry of entries) { + const childPath = path.endsWith('/') ? `${path}${entry.name}` : `${path}/${entry.name}`; + const nowDate = new Date(now); + const statResult: StatResult = { + isDirectory: () => entry.isDirectory, + isFile: () => entry.isFile, + isBlockDevice: () => false, + isCharacterDevice: () => false, + isSymbolicLink: () => false, + isFIFO: () => false, + isSocket: () => false, + size: 0, + mtimeMs: now, + ctimeMs: now, + atimeMs: now, + mtime: nowDate, + ctime: nowDate, + atime: nowDate, + }; + this.statCache.set(childPath, { result: statResult, timestamp: now }); + } + // Convert plain objects to DirectoryEntry format - return (result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>).map(entry => ({ + return entries.map(entry => ({ name: entry.name, isDirectory: () => entry.isDirectory, isFile: () => entry.isFile, @@ -173,7 +281,7 @@ export class ElectronFSAdapter implements JSRuntimeFS { // Invalidate cache for this path and parent this.statCache.delete(path); this.statCache.delete(`lstat:${path}`); - const parentDir = path.substring(0, path.lastIndexOf('/')); + const parentDir = getParentDirectory(path); if (parentDir) { this.statCache.delete(parentDir); this.statCache.delete(`lstat:${parentDir}`); @@ -209,6 +317,14 @@ export class ElectronFSAdapter implements JSRuntimeFS { } const result = await this.electron.fs.stat(path); + + // Handle error objects returned from IPC (to avoid Electron's noisy error logging) + if (isIPCError(result)) { + const err = new Error(result.message); + (err as NodeJS.ErrnoException).code = result.code; + throw err; + } + const now = Date.now(); const statResult = { isDirectory: () => result.isDirectory, @@ -270,6 +386,14 @@ export class ElectronFSAdapter implements JSRuntimeFS { } const result = await this.electron.fs.lstat(path); + + // Handle error objects returned from IPC (to avoid Electron's noisy error logging) + if (isIPCError(result)) { + const err = new Error(result.message); + (err as NodeJS.ErrnoException).code = result.code; + throw err; + } + const now = Date.now(); const statResult = { isDirectory: () => result.isDirectory, @@ -309,10 +433,17 @@ export class ElectronFSAdapter implements JSRuntimeFS { try { const result = await this.electron.fs.unlink(path); + // Handle error objects returned from IPC (to avoid Electron's noisy error logging) + if (isIPCError(result)) { + const err = new Error(result.message); + (err as NodeJS.ErrnoException).code = result.code; + throw err; + } + // Invalidate cache for this path and parent this.statCache.delete(path); this.statCache.delete(`lstat:${path}`); - const parentDir = path.substring(0, path.lastIndexOf('/')); + const parentDir = getParentDirectory(path); if (parentDir) { this.statCache.delete(parentDir); this.statCache.delete(`lstat:${parentDir}`); @@ -331,7 +462,7 @@ export class ElectronFSAdapter implements JSRuntimeFS { // Invalidate cache for this path and parent this.statCache.delete(path); this.statCache.delete(`lstat:${path}`); - const parentDir = path.substring(0, path.lastIndexOf('/')); + const parentDir = getParentDirectory(path); if (parentDir) { this.statCache.delete(parentDir); this.statCache.delete(`lstat:${parentDir}`); @@ -353,13 +484,13 @@ export class ElectronFSAdapter implements JSRuntimeFS { this.statCache.delete(newPath); this.statCache.delete(`lstat:${newPath}`); - const oldParent = oldPath.substring(0, oldPath.lastIndexOf('/')); + const oldParent = getParentDirectory(oldPath); if (oldParent) { this.statCache.delete(oldParent); this.statCache.delete(`lstat:${oldParent}`); } - const newParent = newPath.substring(0, newPath.lastIndexOf('/')); + const newParent = getParentDirectory(newPath); if (newParent) { this.statCache.delete(newParent); this.statCache.delete(`lstat:${newParent}`); diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index 553a2aa2..b134b287 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -2,6 +2,7 @@ import { join, dirname, extname } from "path-browserify"; import type { Loader, Plugin } from "esbuild-wasm"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; +import { isAbsolutePath, normalizeToForwardSlashes } from '@/lib/pathUtils'; interface TsConfig { compilerOptions?: { @@ -35,21 +36,36 @@ export function fsPlugin(options: FsPluginOptions): Plugin { return; } + // Check if this looks like a bare module specifier (npm package) + // Bare specifiers don't start with '.', '..', '/', or '@/' (our alias) + // Examples: 'react', 'react/jsx-runtime', '@tanstack/react-query' + const isBareSpecifier = !args.path.startsWith('.') && + !args.path.startsWith('/') && + !args.path.startsWith('@/') && + !isAbsolutePath(args.path); + let resolved: string; - if (args.path.startsWith("/")) { - resolved = args.path; + // Handle absolute paths (Unix or Windows style) + if (isAbsolutePath(args.path)) { + resolved = normalizeToForwardSlashes(args.path); } else if (args.path.startsWith("@/")) { resolved = join(cwd, "src", args.path.slice(2)); } else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) { resolved = join(dirname(args.importer), args.path); - } else if (args.importer && tsconfig?.compilerOptions?.baseUrl) { + } else if (args.importer && tsconfig?.compilerOptions?.baseUrl && !isBareSpecifier) { + // Only use baseUrl for non-bare specifiers (local project paths) + // Don't try to resolve npm packages via baseUrl resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path); } else { return; } + // Normalize to forward slashes for consistent comparison + resolved = normalizeToForwardSlashes(resolved); + const normalizedCwd = normalizeToForwardSlashes(cwd); + // Security: prevent accessing files outside the project directory - if (resolved.startsWith("/") && !resolved.startsWith(cwd)) { + if (isAbsolutePath(resolved) && !resolved.startsWith(normalizedCwd)) { throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`); } diff --git a/src/lib/pathUtils.ts b/src/lib/pathUtils.ts new file mode 100644 index 00000000..da8a01d5 --- /dev/null +++ b/src/lib/pathUtils.ts @@ -0,0 +1,120 @@ +/** + * Cross-platform path utilities for handling both Unix and Windows path separators. + * These utilities ensure consistent behavior across different operating systems. + */ + +/** + * Get the parent directory of a path, handling both forward and back slashes. + * This is particularly important for Windows paths in Electron. + * + * @param path - The file or directory path + * @returns The parent directory path, or empty string if at root + */ +export function getParentDirectory(path: string): string { + // Find the last occurrence of either separator + const lastForwardSlash = path.lastIndexOf('/'); + const lastBackSlash = path.lastIndexOf('\\'); + const lastSeparator = Math.max(lastForwardSlash, lastBackSlash); + + if (lastSeparator === -1) { + return ''; + } + + return path.substring(0, lastSeparator); +} + +/** + * Normalize a path to use forward slashes consistently. + * This is useful for the VFS which uses Unix-style paths internally. + * + * @param path - The path to normalize + * @returns The path with all backslashes converted to forward slashes + */ +export function normalizeToForwardSlashes(path: string): string { + return path.replace(/\\/g, '/'); +} + +/** + * Normalize a path to use the native separator for the current platform. + * On Windows, uses backslashes; on Unix-like systems, uses forward slashes. + * + * @param path - The path to normalize + * @returns The path with separators appropriate for the current platform + */ +export function normalizeToNativeSeparator(path: string): string { + const isWindows = typeof navigator !== 'undefined' + ? navigator.platform?.toLowerCase().includes('win') + : false; + + if (isWindows) { + return path.replace(/\//g, '\\'); + } + return path.replace(/\\/g, '/'); +} + +/** + * Join path segments with forward slashes, regardless of platform. + * This is useful for VFS paths which always use forward slashes. + * + * @param segments - Path segments to join + * @returns The joined path with forward slashes + */ +export function joinWithForwardSlashes(...segments: string[]): string { + return segments + .filter(Boolean) + .map(s => s.replace(/^[/\\]+|[/\\]+$/g, '')) // Trim leading/trailing slashes + .join('/'); +} + +/** + * Check if a path is absolute on any platform. + * Recognizes: + * - Unix absolute paths starting with / + * - Windows absolute paths starting with \ or drive letter (C:\) + * + * @param path - The path to check + * @returns True if the path is absolute + */ +export function isAbsolutePath(path: string): boolean { + return path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path); +} + +/** + * Get the file name from a path, handling both separators. + * + * @param path - The file path + * @returns The file name + */ +export function getBasename(path: string): string { + const lastForwardSlash = path.lastIndexOf('/'); + const lastBackSlash = path.lastIndexOf('\\'); + const lastSeparator = Math.max(lastForwardSlash, lastBackSlash); + + if (lastSeparator === -1) { + return path; + } + + return path.substring(lastSeparator + 1); +} + +/** + * Expand tilde (~) in paths to the home directory. + * Works with both Unix (~/) and Windows (~\) style paths. + * + * @param path - The path that may contain tilde + * @param homedir - The user's home directory + * @returns The expanded path + */ +export function expandTildePath(path: string, homedir: string): string { + if (path === '~') { + return homedir; + } + if (path.startsWith('~/')) { + return homedir + path.slice(1); + } + if (path.startsWith('~\\')) { + return homedir + path.slice(1); + } + return path; +} + diff --git a/src/lib/security.ts b/src/lib/security.ts index 4e1532e7..5818bb8d 100644 --- a/src/lib/security.ts +++ b/src/lib/security.ts @@ -3,6 +3,7 @@ */ import { normalize } from "path-browserify"; +import { normalizeToForwardSlashes } from "./pathUtils"; /** * Check if the given path is an absolute path @@ -38,11 +39,12 @@ export function isWriteAllowed( } // For absolute paths, apply restrictions - const absolutePath = normalize(path); + // Normalize to forward slashes for consistent comparison (handles both Unix and Windows paths) + const absolutePath = normalizeToForwardSlashes(normalize(path)); - // Get configured paths with defaults - const tmpPath = options?.tmpPath || '/tmp'; - const projectsPath = options?.projectsPath || '/projects'; + // Get configured paths with defaults and normalize them + const tmpPath = normalizeToForwardSlashes(options?.tmpPath || '/tmp'); + const projectsPath = normalizeToForwardSlashes(options?.projectsPath || '/projects'); // Allow writes to tmp directory and its subdirectories if (absolutePath.startsWith(tmpPath + '/') || absolutePath === tmpPath) { @@ -56,7 +58,7 @@ export function isWriteAllowed( // If we have a current working directory, allow writes within that directory tree if (cwd) { - const normalizedCwd = normalize(cwd); + const normalizedCwd = normalizeToForwardSlashes(normalize(cwd)); if (absolutePath.startsWith(normalizedCwd + '/') || absolutePath === normalizedCwd) { return true; } diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index c3e4c339..7a80d0ab 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -1,10 +1,12 @@ import { z } from "zod"; +import { join } from "path-browserify"; import type { Tool, ToolResult } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; import type { ShellCommand } from "../commands/ShellCommand"; import { Git } from "../git"; import { stripAnsiCodes } from "../ansiToHtml"; import type { NostrSigner } from "@nostrify/nostrify"; +import { isAbsolutePath } from "../pathUtils"; import { CatCommand, CdCommand, @@ -433,7 +435,7 @@ export class ShellTool implements Tool { */ private async handleRedirection(output: string, redirectType: '>' | '>>', redirectFile: string): Promise { // Resolve the file path relative to current working directory - const filePath = redirectFile.startsWith('/') ? redirectFile : `${this.cwd}/${redirectFile}`; + const filePath = isAbsolutePath(redirectFile) ? redirectFile : join(this.cwd, redirectFile); if (redirectType === '>') { // Overwrite the file