diff --git a/PROGRESS.md b/PROGRESS.md index 98d24a4..d018eb5 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -2,7 +2,7 @@ ## Current -In-app name dialog (New Folder / New File / Rename / favorite naming) and Explorer-style drag-drop inside and between panes, on top of the drive picker, per-pane refresh, and multi-select (Ctrl/Shift/Ctrl+A) with batch copy/cut/paste/F5/F6/delete. +File-type associations with auto-detected local apps (Settings → File apps), plus the in-app name dialog (New Folder / New File / Rename / favorite naming) and Explorer-style drag-drop inside and between panes, on top of the drive picker, per-pane refresh, and multi-select (Ctrl/Shift/Ctrl+A) with batch copy/cut/paste/F5/F6/delete. Public on GitHub since 2026-11-10 (HappyMonkeyAI/ZeroGFileMan, MIT). The history was rewritten before publishing: personal email only, no LAN IPs or home paths. The pre-public history and code-review PRs #1–#3 are in the archived private repo `HappyMonkeyAI/ZeroGFileMan-archive`. PR numbers in this repo restart at #1. @@ -28,6 +28,7 @@ Open check: builtin Whisper model download under the narrowed CSP `connect-src` - Update service covered by 27 tests; `npm run typecheck`, `npm test` (164 tests), and `npm run build` pass - Final Windows NSIS and portable artifacts rebuilt successfully as separate targets after the combined package command timed out - Favorites polish: the global picker now has explicit rename/remove controls, and the path action toggles between Add and Remove while preserving the existing `favorites.json` model +- File-type associations: the development store is scanned for apps declaring `build.fileAssociations` (unpacked exe → portable → dev Electron fallback); Settings → File apps lists detected apps, sets a default app per extension, and adds custom programs with a `{file}` argument template; Open/double-click and the right-click menu honor the associations through the injection-safe spawner (25 new tests; 213 total) - In-app name dialog replaces `window.prompt` (Electron never implements it): New Folder, New File type/name, Rename (F2) and favorite naming now work in both panes; inline validation, Esc/Cancel aborts, new folders land selected - Explorer-style drag-drop inside and between panes: drag = move, Ctrl = copy, Shift = force move, cross-drive defaults to copy; targets are folder rows/tiles, pane background, ".." and breadcrumbs; whole-selection drag; both panes refresh and the transcript logs each op; same-folder moves and drops into a folder's own subtree are no-ops - Name dialog + drag-drop rules covered by 24 new tests (188 total); `npm run ci` passes; verified in a real hidden Electron window against a temp filesystem: 14/14 UI checks (dialog in the right pane, invalid-name error, Esc cancel, F2 rename, cross-pane move, Ctrl copy, folder-row drop, same-folder no-op) diff --git a/README.md b/README.md index 821b2b7..9e4750a 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ Nothing downloads or installs without explicit consent. **Later** hides the prom - Dual local panes with breadcrumbs, history (Alt+←/→), favorites, Ctrl+K jump - Favorites bar with direct open, rename, remove, and an add/remove toggle for the active path - CRUD + cross-pane clipboard; F5/F6 copy/move to the other pane +- File-type associations: apps in your development store that declare file associations are detected automatically; pick a default app per extension or add any program in Settings → File apps - Per-pane **Navigate** / **Action** jewels: click-toggle or hold-to-talk; Esc cancels - Speech engines: demo transcript, builtin Whisper (Transformers.js), or OpenAI-compatible server (API key in OS safeStorage) - Consent-based Windows update checks through the GitHub releases API diff --git a/ROADMAP.md b/ROADMAP.md index 25b1040..5fec4a9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -50,6 +50,7 @@ Repo: [HappyMonkeyAI/ZeroGFileMan](https://github.com/HappyMonkeyAI/ZeroGFileMan | P1.6 | Global jump (⌘K / Ctrl+K) | Focus brand-bar search; Enter → Navigate | done | | P1.7 | In-app name dialog | Electron has no `window.prompt`; New Folder / New File / Rename / favorite naming use a validated dialog | done | | P1.8 | Drag-drop between panes | Drag = move, Ctrl = copy, Shift = force move; folder rows, pane background, "..", breadcrumbs as targets; multi-select drag | done | +| P1.9 | File-type associations | Auto-detect dev-store apps via `build.fileAssociations`; per-extension defaults + custom apps in Settings; Open and right-click honor them | done | ### P2 — Voice that works offline diff --git a/src/main/app-detect.ts b/src/main/app-detect.ts new file mode 100644 index 0000000..6fbe518 --- /dev/null +++ b/src/main/app-detect.ts @@ -0,0 +1,91 @@ +// Find launchable apps in the development store: projects whose package.json +// declares electron-builder fileAssociations. Prefer the unpacked exe, then a +// portable artifact, then the project's own Electron binary in dev mode. + +import { existsSync } from 'node:fs'; +import { readdir, readFile } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { isAbsolute, join } from 'node:path'; +import { + packageAppName, + packageAssociations, + pickPortableExe, + type AppLaunch, + type DetectedApp +} from '../shared/file-apps.js'; + +export function defaultAppsRoot(): string { + return join(homedir(), 'Documents', 'development'); +} + +function devElectronBinary(dir: string): string | null { + const base = join(dir, 'node_modules', 'electron', 'dist'); + const candidate = + process.platform === 'win32' + ? join(base, 'electron.exe') + : process.platform === 'darwin' + ? join(base, 'Electron.app', 'Contents', 'MacOS', 'Electron') + : join(base, 'electron'); + return existsSync(candidate) ? candidate : null; +} + +async function launchForProject(dir: string, name: string, pkg: Record): Promise<{ launch: AppLaunch; source: DetectedApp['source'] } | null> { + const build = (pkg.build ?? {}) as Record; + const directories = (build.directories ?? {}) as Record; + const outputs = [...new Set([directories.output, 'dist', 'release'].filter((value): value is string => typeof value === 'string' && Boolean(value)))]; + + for (const out of outputs) { + const unpacked = join(dir, out, 'win-unpacked', `${name}.exe`); + if (existsSync(unpacked)) return { launch: { command: unpacked, args: ['{file}'] }, source: 'unpacked' }; + } + for (const out of outputs) { + try { + const exe = pickPortableExe(await readdir(join(dir, out))); + if (exe) return { launch: { command: join(dir, out, exe), args: ['{file}'] }, source: 'portable' }; + } catch { + /* no output folder */ + } + } + const electron = devElectronBinary(dir); + if (electron) return { launch: { command: electron, args: ['.', '{file}'], cwd: dir }, source: 'dev' }; + return null; +} + +/** Scan one folder depth for app projects; unreadable entries are skipped. */ +export async function detectLocalApps(rootRaw: unknown): Promise { + const root = + typeof rootRaw === 'string' && rootRaw.trim() && isAbsolute(rootRaw.trim()) + ? rootRaw.trim() + : defaultAppsRoot(); + let entries; + try { + entries = await readdir(root, { withFileTypes: true }); + } catch { + return []; + } + const apps: DetectedApp[] = []; + for (const entry of entries) { + if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules') continue; + const projectDir = join(root, entry.name); + try { + const pkg = JSON.parse(await readFile(join(projectDir, 'package.json'), 'utf8')) as Record; + const extensions = packageAssociations(pkg); + if (!extensions.length) continue; + const name = packageAppName(pkg) || entry.name; + const found = await launchForProject(projectDir, name, pkg); + if (!found) continue; + apps.push({ + id: `detected:${entry.name}`, + name, + version: typeof pkg.version === 'string' ? pkg.version : '', + extensions, + launch: found.launch, + source: found.source, + projectDir + }); + } catch { + /* not an app project */ + } + } + return apps.sort((a, b) => a.name.localeCompare(b.name)); +} diff --git a/src/main/main.ts b/src/main/main.ts index 4606ea2..06dd47e 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -11,9 +11,12 @@ import { type IpcMainInvokeEvent } from 'electron'; import { existsSync } from 'node:fs'; -import { dirname, join } from 'node:path'; +import { access, constants } from 'node:fs/promises'; +import { dirname, isAbsolute, join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { detectLocalApps } from './app-detect.js'; import { buildContextMenu, parseContextMenuTarget } from '../shared/context-menu.js'; +import { appCommandProblem, resolveAppArgs } from '../shared/file-apps.js'; import { parseServerTranscriptionInput, transcribeViaServer } from '../shared/speech-server.js'; import { isAppUrl, type AppLocation } from './app-origin.js'; import { installApplicationMenu } from './app-menu.js'; @@ -231,6 +234,41 @@ handle('shell:openTerminal', (_e, path: unknown, options?: unknown) => { }); }); +handle('apps:detect', (_e, root: unknown) => detectLocalApps(root)); + +handle('apps:open', async (_e, raw: unknown) => { + const request = (raw ?? {}) as { filePath?: unknown; command?: unknown; args?: unknown; cwd?: unknown }; + const filePath = resolveLocalPath(request.filePath); + if (!existsSync(filePath)) throw new Error('That file no longer exists.'); + const command = typeof request.command === 'string' ? request.command.trim() : ''; + if (!command || !isAbsolute(command) || !existsSync(command)) throw new Error('App executable not found.'); + const commandProblem = appCommandProblem(command, process.platform); + if (commandProblem) throw new Error(commandProblem); + if (process.platform !== 'win32') { + try { + await access(command, constants.X_OK); + } catch { + throw new Error('The app must be an executable file.'); + } + } + const args = Array.isArray(request.args) ? request.args : []; + if ( + args.length > 32 || + args.some((arg) => typeof arg !== 'string' || arg.length > 2048 || /[\0\r\n]/.test(arg)) + ) { + throw new Error('Invalid app arguments.'); + } + const cwd = + typeof request.cwd === 'string' && request.cwd && isAbsolute(request.cwd) && existsSync(request.cwd) + ? request.cwd + : undefined; + const resolved = resolveAppArgs(args as string[], filePath); + await new Promise((resolvePromise, reject) => { + spawnDetached(command, resolved, { cwd, onError: reject }); + setTimeout(resolvePromise, 150); + }); +}); + handle('contextMenu:show', (event, raw: unknown) => { const target = parseContextMenuTarget(raw); const window = BrowserWindow.fromWebContents(event.sender) ?? undefined; diff --git a/src/main/preload.cjs b/src/main/preload.cjs index d3ffb8e..b240b4c 100644 --- a/src/main/preload.cjs +++ b/src/main/preload.cjs @@ -20,6 +20,8 @@ contextBridge.exposeInMainWorld('fileman', { openPath: (path) => ipcRenderer.invoke('shell:openPath', path), showItemInFolder: (path) => ipcRenderer.invoke('shell:showItem', path), openWith: (path, app) => ipcRenderer.invoke('shell:openWith', path, app), + detectFileApps: (root) => ipcRenderer.invoke('apps:detect', root), + openWithApp: (request) => ipcRenderer.invoke('apps:open', request), openTerminal: (path, options) => ipcRenderer.invoke('shell:openTerminal', path, options), speechApiKeyStatus: () => ipcRenderer.invoke('speechKey:status'), saveSpeechApiKey: (key) => ipcRenderer.invoke('speechKey:save', key), diff --git a/src/renderer/file-apps-settings.ts b/src/renderer/file-apps-settings.ts new file mode 100644 index 0000000..d8fe010 --- /dev/null +++ b/src/renderer/file-apps-settings.ts @@ -0,0 +1,21 @@ +import { DEFAULT_FILE_APP_PREFS, parseFileAppPrefs, type FileAppPrefs } from '../shared/file-apps.js'; + +const STORAGE_KEY = 'zerogfileman.fileApps'; + +export function loadStoredFileAppPrefs(): FileAppPrefs { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) return { ...DEFAULT_FILE_APP_PREFS, defaults: {}, customApps: [] }; + return parseFileAppPrefs(JSON.parse(raw)); + } catch { + return { ...DEFAULT_FILE_APP_PREFS, defaults: {}, customApps: [] }; + } +} + +export function storeFileAppPrefs(prefs: FileAppPrefs): void { + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(parseFileAppPrefs(prefs))); + } catch { + /* ignore */ + } +} diff --git a/src/renderer/main.tsx b/src/renderer/main.tsx index afffd4e..c637d23 100644 --- a/src/renderer/main.tsx +++ b/src/renderer/main.tsx @@ -23,6 +23,22 @@ import { parentLocal } from '../shared/files.js'; import type { ContextMenuTargetKind } from '../shared/context-menu.js'; +import { + allFileApps, + appsForExtension, + BUILTIN_FILE_APPS, + detectedFileApp, + extensionOptions, + fileExtension, + OPEN_APP_COMMAND_PREFIX, + parseExtensionList, + parseFileAppPrefs, + resolveAppArgs, + resolveDefaultApp, + type DetectedApp, + type FileApp, + type FileAppPrefs +} from '../shared/file-apps.js'; import { endpointNotices } from '../shared/endpoints.js'; import { entryNameProblem } from '../shared/entry-name.js'; import { templateChoice } from '../shared/text-dialog.js'; @@ -105,6 +121,7 @@ import { } from './speech-models.js'; import { loadStoredSpeechSettings, storeSpeechSettings } from './speech-settings.js'; import { loadStoredTerminalPrefs, storeTerminalPrefs } from './terminal-prefs.js'; +import { loadStoredFileAppPrefs, storeFileAppPrefs } from './file-apps-settings.js'; import { applyTheme, isThemeId, @@ -416,6 +433,8 @@ function FilePane(props: { onRefreshPeer?: () => void; onRegisterCommands: (commands: PaneCommands | null) => void; askText: AskText; + onOpenFile: (path: string, name: string) => Promise; + openWithFor: (name: string) => FileApp[]; }) { const { side, @@ -436,16 +455,26 @@ function FilePane(props: { onToggleMaximize, onRefreshPeer, onRegisterCommands, - askText + askText, + onOpenFile, + openWithFor } = props; const showMenu = useCallback( - (kind: ContextMenuTargetKind) => { + (kind: ContextMenuTargetKind, entryName?: string) => { + const openWith = entryName + ? openWithFor(entryName).map((app) => ({ label: app.name, appId: app.id })) + : []; void api() - .showContextMenu({ kind, canPaste: Boolean(clipboard), canTransfer: otherPath !== pane.path }) + .showContextMenu({ + kind, + canPaste: Boolean(clipboard), + canTransfer: otherPath !== pane.path, + ...(openWith.length ? { openWith } : {}) + }) .catch((error: unknown) => onLog(`Context menu failed: ${describeError(error)}`)); }, - [clipboard, onLog, otherPath, pane.path] + [clipboard, onLog, openWithFor, otherPath, pane.path] ); const openTerminalHere = useCallback( @@ -1316,7 +1345,9 @@ function FilePane(props: { copyPath: () => void api().copyText(pane.path).then(() => onLog(`[${stamp()}] copy path ${pane.path}`)), open: () => { const sel = requireSelection(); - if (sel) void api().openPath(sel.path); + if (!sel) return; + if (sel.kind === 'file') void onOpenFile(sel.path, sel.name); + else void api().openPath(sel.path); }, openNotepad: () => { const sel = requireSelection(); @@ -1347,7 +1378,7 @@ function FilePane(props: { const sel = requireSelection(); if (!sel) return; if (sel.kind === 'directory' || sel.kind === 'symlink') void navigateTo(sel.path); - else void runReported(`Open “${sel.name}”`, () => api().openPath(sel.path), onLog); + else void runReported(`Open “${sel.name}”`, () => onOpenFile(sel.path, sel.name), onLog); }, openCursor: () => { const sel = requireSelection(); @@ -1392,6 +1423,7 @@ function FilePane(props: { goForward, navigateTo, onLog, + onOpenFile, onRegisterCommands, openPathEdit, openTerminalHere, @@ -1705,7 +1737,7 @@ function FilePane(props: { event.preventDefault(); event.stopPropagation(); if (!selected) setSelection(exclusiveSelect(entry.name)); - showMenu(entry.kind); + showMenu(entry.kind, entry.name); }; const onEntryClick = (event: ReactMouseEvent) => { selectEntry(entry.name, { @@ -1717,7 +1749,7 @@ function FilePane(props: { if (entry.kind === 'directory' || entry.kind === 'symlink') { void navigateTo(fullPath); } else { - void api().openPath(fullPath); + void onOpenFile(fullPath, entry.name); } }; if (pane.viewMode === 'details') { @@ -1840,6 +1872,9 @@ function App() { const [dismissedUpdate, setDismissedUpdate] = useState(null); const [updateAsked, setUpdateAsked] = useState(false); const [updateSettings, setUpdateSettings] = useState(() => loadStoredUpdateSettings()); + const [fileAppPrefs, setFileAppPrefs] = useState(() => loadStoredFileAppPrefs()); + const [detectedApps, setDetectedApps] = useState([]); + const [appDraft, setAppDraft] = useState({ name: '', command: '', args: '{file}', extensions: '' }); const { askText, dialog: textDialog } = useTextDialog(); const startupCheckDone = useRef(false); const leftCommands = useRef(null); @@ -1893,6 +1928,93 @@ function App() { }); }, []); + const updateFileApps = useCallback((patch: Partial) => { + setFileAppPrefs((prev) => { + const next = parseFileAppPrefs({ ...prev, ...patch }); + storeFileAppPrefs(next); + return next; + }); + }, []); + + const rescanApps = useCallback(() => { + void api() + .detectFileApps(fileAppPrefs.appsRoot) + .then(setDetectedApps) + .catch((error) => pushLog(`App scan failed: ${describeError(error)}`)); + }, [fileAppPrefs.appsRoot, pushLog]); + + useEffect(() => { + rescanApps(); + }, [rescanApps]); + + const detectedFileApps = useMemo(() => detectedApps.map(detectedFileApp), [detectedApps]); + + const launchApp = useCallback(async (app: FileApp, path: string) => { + if (app.kind === 'builtin') { + await api().openWith(path, app.id); + return; + } + if (!app.launch) throw new Error(`${app.name} has no launch command.`); + await api().openWithApp({ + filePath: path, + command: app.launch.command, + args: resolveAppArgs(app.launch.args, path), + cwd: app.launch.cwd + }); + }, []); + + const openFile = useCallback( + async (path: string, name: string) => { + const app = resolveDefaultApp(name, detectedFileApps, fileAppPrefs); + if (!app) { + await api().openPath(path); + return; + } + await launchApp(app, path); + }, + [detectedFileApps, fileAppPrefs, launchApp] + ); + + const openWithFor = useCallback( + (name: string) => { + const ext = fileExtension(name); + return ext ? appsForExtension(ext, detectedFileApps, fileAppPrefs) : []; + }, + [detectedFileApps, fileAppPrefs] + ); + + const addCustomApp = useCallback(() => { + const name = appDraft.name.trim(); + const command = appDraft.command.trim(); + const extensions = parseExtensionList(appDraft.extensions); + if (!name || !command) { + pushLog('App needs a name and an executable path.'); + return; + } + if (!extensions.length) { + pushLog('App needs at least one extension (e.g. md, markdown).'); + return; + } + const base = `custom:${name.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'app'}`; + let id = base; + for (let n = 2; fileAppPrefs.customApps.some((app) => app.id === id); n += 1) id = `${base}-${n}`; + updateFileApps({ + customApps: [...fileAppPrefs.customApps, { id, name, command, args: appDraft.args.trim() || '{file}', extensions }] + }); + setAppDraft({ name: '', command: '', args: '{file}', extensions: '' }); + pushLog(`[${stamp()}] added app ${name} (${extensions.join(' ')})`); + }, [appDraft, fileAppPrefs.customApps, pushLog, updateFileApps]); + + const removeCustomApp = useCallback( + (id: string) => { + updateFileApps({ + customApps: fileAppPrefs.customApps.filter((app) => app.id !== id), + defaults: Object.fromEntries(Object.entries(fileAppPrefs.defaults).filter(([, value]) => value !== id)) + }); + }, + [fileAppPrefs.customApps, fileAppPrefs.defaults, updateFileApps] + ); + const checkForUpdatesNow = useCallback(() => { setUpdateAsked(true); void api().checkForUpdates().catch((error) => pushLog(error instanceof Error ? error.message : String(error))); @@ -2256,10 +2378,18 @@ function App() { pushLog('ZeroG FileMan — local dual-pane voice file manager (HappyMonkeyAI)'); break; default: + if (command.startsWith(OPEN_APP_COMMAND_PREFIX)) { + const appId = command.slice(OPEN_APP_COMMAND_PREFIX.length); + const app = allFileApps(detectedFileApps, fileAppPrefs).find((entry) => entry.id === appId); + const target = c?.selectedItemPath(); + if (app && target) { + void runReported(`Open with ${app.name}`, () => launchApp(app, target), pushLog); + } + } break; } }); - }, [active, addCurrentFavorite, checkForUpdatesNow, focusJump, pushLog]); + }, [active, addCurrentFavorite, checkForUpdatesNow, detectedFileApps, fileAppPrefs, focusJump, launchApp, pushLog]); const runGlobalJump = async () => { const q = jumpQuery.trim(); @@ -2552,6 +2682,8 @@ function App() { onToggleMaximize={() => updateWorkspaceLayout(toggleMaximize(workspaceLayout, 'left'))} onRefreshPeer={() => refreshSide('right')} askText={askText} + onOpenFile={openFile} + openWithFor={openWithFor} onRegisterCommands={(c) => { leftCommands.current = c; }} @@ -2618,6 +2750,8 @@ function App() { onToggleMaximize={() => updateWorkspaceLayout(toggleMaximize(workspaceLayout, 'right'))} onRefreshPeer={() => refreshSide('left')} askText={askText} + onOpenFile={openFile} + openWithFor={openWithFor} onRegisterCommands={(c) => { rightCommands.current = c; }} @@ -2870,6 +3004,97 @@ function App() { {updateSettings.skippedVersion ? `Clear skipped ${updateSettings.skippedVersion}` : 'No skipped version'} +
+ File apps + +
+ +
+ {detectedApps.length ? ( + detectedApps.map((app) => ( +
+ + {app.name} + {app.version ? ` ${app.version}` : ''} + + + {app.extensions.join(' ')} · {app.source} + +
+ )) + ) : ( +
No apps detected — projects need build.fileAssociations in package.json.
+ )} +
+ {extensionOptions(detectedFileApps, fileAppPrefs).map((ext) => ( + + ))} + {fileAppPrefs.customApps.map((app) => ( +
+ {app.name} + + {app.extensions.join(' ')} + + +
+ ))} +
+ setAppDraft({ ...appDraft, name: e.target.value })} + /> + setAppDraft({ ...appDraft, command: e.target.value })} + /> + setAppDraft({ ...appDraft, args: e.target.value })} + /> + setAppDraft({ ...appDraft, extensions: e.target.value })} + /> + +