diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..bdf7c7d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,119 @@ +name: Release desktop builds + +on: + push: + tags: + - 'v*' + +permissions: + contents: read + +jobs: + windows: + name: Build Windows x64 release assets + runs-on: windows-latest + timeout-minutes: 30 + + steps: + - name: Check out repository + uses: actions/checkout@v5 + + - name: Set up Node.js + uses: actions/setup-node@v5 + with: + node-version: 22 + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Verify source + run: | + npm run typecheck + npm test + + - name: Build Windows installer and portable executable + run: npm run package:win + + - name: Upload Windows release assets + uses: actions/upload-artifact@v4 + with: + name: release-windows + path: | + release/*.exe + release/*.exe.blockmap + release/latest.yml + !release/**/*__uninstaller* + if-no-files-found: error + retention-days: 1 + + publish: + name: Publish GitHub release + needs: + - windows + runs-on: ubuntu-22.04 + timeout-minutes: 10 + permissions: + contents: write + + steps: + - name: Check out repository + uses: actions/checkout@v5 + with: + fetch-depth: 0 + + - name: Set up Node.js + uses: actions/setup-node@v5 + with: + node-version: 22 + + - name: Download release assets + uses: actions/download-artifact@v4 + with: + pattern: release-* + merge-multiple: true + path: release-assets + + - name: Restore the annotated release tag + shell: bash + run: git fetch --force origin "refs/tags/${GITHUB_REF_NAME}:refs/tags/${GITHUB_REF_NAME}" + + - name: Verify release version and assets + shell: bash + run: | + package_version="$(node -p "require('./package.json').version")" + tag_version="${GITHUB_REF_NAME#v}" + tag_type="$(git cat-file -t "refs/tags/${GITHUB_REF_NAME}")" + [[ "$package_version" == "$tag_version" ]] + [[ "$tag_type" == "tag" ]] + shopt -s nullglob + windows_assets=(release-assets/*.exe) + ((${#windows_assets[@]} == 2)) + [[ -f release-assets/latest.yml ]] + grep -qx "version: ${package_version}" release-assets/latest.yml + target="$(grep -m1 '^path: ' release-assets/latest.yml | sed 's/^path: //')" + [[ -n "$target" && -f "release-assets/${target}" ]] + + - name: Generate asset checksums + shell: bash + run: | + ( + cd release-assets + sha256sum ./*.exe > SHA256SUMS + ) + + - name: Publish GitHub release + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + shopt -s nullglob + assets=(release-assets/*) + release_flags=() + if [[ "${GITHUB_REF_NAME}" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+- ]]; then release_flags+=(--prerelease); fi + gh release create "${GITHUB_REF_NAME}" \ + "${assets[@]}" \ + --verify-tag \ + --title "ZeroG FileMan ${GITHUB_REF_NAME}" \ + "${release_flags[@]}" \ + --generate-notes diff --git a/PROGRESS.md b/PROGRESS.md index 3fac751..98d24a4 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -2,7 +2,7 @@ ## Current -Drive picker, per-pane refresh, and multi-select (Ctrl/Shift/Ctrl+A) with batch copy/cut/paste/F5/F6/delete. +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. @@ -24,6 +24,13 @@ Open check: builtin Whisper model download under the narrowed CSP `connect-src` - SonarCloud removed for this repo: both FileMan projects deleted in the happymonkeyai SonarCloud org; the org-wide GitHub app is unchanged - Per-pane Windows drive dropdown (`fs:drives` / path chrome) - Per-pane refresh pill; multi-select with batch clipboard and F5/F6/delete +- Consent-based app updates from GitHub releases: startup/manual checks, in-place updates for NSIS installs, release-page notifications for portable builds, and a tag-driven Windows release workflow +- 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 +- 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) ## Next diff --git a/README.md b/README.md index 10c78fd..821b2b7 100644 --- a/README.md +++ b/README.md @@ -47,12 +47,24 @@ Packaged builds are Windows x64 only for now. Signing is off (`signAndEditExecutable: false`). App id: `com.happymonkeyai.zerogfileman`. Window/installer icon lives in `build/` (`npm run icon:render` regenerates png/ico from the SVG). +## Updates + +The app checks GitHub releases about eight seconds after launch, unless you switch **Settings → Updates** to **Manual** or run an unpackaged development build. + +- **NSIS install:** the prompt can download the signed `latest.yml`-checked installer, then install it when you explicitly choose **Install and restart**. +- **Portable executable:** the app cannot safely replace itself, so the prompt only opens the release page. +- **Development or npm-installed builds:** update checks are disabled. + +Nothing downloads or installs without explicit consent. **Later** hides the prompt until the next check; **Skip this version** hides it until a newer release appears or you clear the skipped version in Settings. Pushing a `v*` tag runs `.github/workflows/release.yml`, which publishes the two Windows executables, the installer blockmap, and `latest.yml`. + ## What it does - 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 - 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 ## Docs diff --git a/ROADMAP.md b/ROADMAP.md index 3e9f21b..25b1040 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -26,6 +26,7 @@ Repo: [HappyMonkeyAI/ZeroGFileMan](https://github.com/HappyMonkeyAI/ZeroGFileMan | D14 | Listing view modes | Details / Icons / Thumbnails + Ctrl+wheel scale; thumb caps | | D15 | Split layouts | Side-by-side / stacked + maximize; draggable gutter | | D16 | Terminal launcher pref | System / ZeroG Term / custom command from Settings | +| D17 | App updates | Consent-based GitHub release checks; NSIS installs, portable notifies | ## Near-term (ordered) @@ -45,8 +46,10 @@ Repo: [HappyMonkeyAI/ZeroGFileMan](https://github.com/HappyMonkeyAI/ZeroGFileMan | P1.2 | Tab switches active pane | Tab focus LEFT ↔ RIGHT | done | | P1.3 | F-keys like classic commanders | F2 rename, F5 copy→, F6 move→, F7 mkdir, Del | done (ADR-0004) | | P1.4 | Copy/Move **to other pane** | Copy → / Move → toolbar + F5/F6 | done | -| P1.5 | Editable favorites | Persist bookmarks in userData | done | +| P1.5 | Editable favorites | Persist bookmarks in userData; rename/remove chips and active-path toggle | done | | 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 | ### P2 — Voice that works offline @@ -75,10 +78,10 @@ Repo: [HappyMonkeyAI/ZeroGFileMan](https://github.com/HappyMonkeyAI/ZeroGFileMan | P4.2 | App icon | Distinct FileMan dual-pane icon (`build/icon.*`); electron-builder + window chrome | done | | P4.3 | README quickstart | Screenshots optional; clear `npm start` path | done | | P4.4 | CI | GitHub Action: typecheck + test + build on push | done | +| P4.5 | App updates | electron-updater, release-page fallback, Settings controls, tag release workflow | done | ## Later / park -- Drag-drop between panes (multi-select shipped) - Recursive delete with explicit danger modal (default stays non-recursive) - Permissions / owner columns (platform-accurate, not fake Unix on NTFS) - Thumbnail generation caps (size/type allowlist; no decode of huge RAW by default) diff --git a/package-lock.json b/package-lock.json index 2812f78..60b6fe1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,18 +1,22 @@ { "name": "zerogfileman", - "version": "0.1.0", + "version": "0.2.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "zerogfileman", - "version": "0.1.0", + "version": "0.2.1", "license": "MIT", "dependencies": { "@huggingface/transformers": "^4.3.2", + "electron-updater": "^6.8.11", "react": "^19.1.1", "react-dom": "^19.1.1" }, + "bin": { + "zerogfileman": "bin/zerogfileman.cjs" + }, "devDependencies": { "@fontsource-variable/inter": "^5.3.0", "@fontsource-variable/jetbrains-mono": "^5.3.0", @@ -2975,7 +2979,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, "license": "Python-2.0" }, "node_modules/asn1js": { @@ -3188,7 +3191,6 @@ "version": "9.7.0", "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz", "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==", - "dev": true, "license": "MIT", "dependencies": { "debug": "^4.3.4", @@ -3557,7 +3559,6 @@ "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -3889,6 +3890,34 @@ "dev": true, "license": "ISC" }, + "node_modules/electron-updater": { + "version": "6.8.11", + "resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.11.tgz", + "integrity": "sha512-12U/mbzaIKQS3Q543aQ7DjyAZMXeVJy1Wpu0qdq5ne4RXpIQDpWYm25zRjgXngAoo6swMrm4C4owGyiIipelsg==", + "license": "MIT", + "dependencies": { + "builder-util-runtime": "9.7.0", + "fs-extra": "^10.1.0", + "js-yaml": "^4.1.0", + "lazy-val": "^1.0.5", + "lodash.escaperegexp": "^4.1.2", + "lodash.isequal": "^4.5.0", + "semver": "~7.7.3", + "tiny-typed-emitter": "^2.1.0" + } + }, + "node_modules/electron-updater/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/electron-winstaller": { "version": "5.4.0", "resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz", @@ -4248,7 +4277,6 @@ "version": "10.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", - "dev": true, "license": "MIT", "dependencies": { "graceful-fs": "^4.2.0", @@ -4504,7 +4532,6 @@ "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, "license": "ISC" }, "node_modules/guid-typescript": { @@ -4757,7 +4784,6 @@ "version": "4.3.2", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", - "dev": true, "funding": [ { "type": "github", @@ -4828,7 +4854,6 @@ "version": "6.2.1", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", - "dev": true, "license": "MIT", "dependencies": { "universalify": "^2.0.0" @@ -4851,7 +4876,6 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz", "integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==", - "dev": true, "license": "MIT" }, "node_modules/lodash": { @@ -4861,6 +4885,19 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.escaperegexp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz", + "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==", + "license": "MIT" + }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", + "license": "MIT" + }, "node_modules/long": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", @@ -5042,7 +5079,6 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, "license": "MIT" }, "node_modules/nanoid": { @@ -5863,7 +5899,6 @@ "version": "1.6.1", "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz", "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==", - "dev": true, "license": "BlueOak-1.0.0", "engines": { "node": ">=11.0.0" @@ -6268,6 +6303,12 @@ "semver": "bin/semver" } }, + "node_modules/tiny-typed-emitter": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tiny-typed-emitter/-/tiny-typed-emitter-2.1.0.tgz", + "integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==", + "license": "MIT" + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -6423,7 +6464,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", - "dev": true, "license": "MIT", "engines": { "node": ">= 10.0.0" diff --git a/package.json b/package.json index ce0f365..19df6ab 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ }, "dependencies": { "@huggingface/transformers": "^4.3.2", + "electron-updater": "^6.8.11", "react": "^19.1.1", "react-dom": "^19.1.1" }, @@ -70,6 +71,14 @@ "appId": "com.happymonkeyai.zerogfileman", "productName": "ZeroG FileMan", "asar": true, + "publish": [ + { + "provider": "github", + "owner": "HappyMonkeyAI", + "repo": "ZeroGFileMan", + "releaseType": "release" + } + ], "directories": { "output": "release", "buildResources": "build" diff --git a/src/main/app-menu.ts b/src/main/app-menu.ts index e8c7228..5e6bc65 100644 --- a/src/main/app-menu.ts +++ b/src/main/app-menu.ts @@ -30,6 +30,7 @@ export type MenuCommand = | 'go:add-favorite' | 'voice:navigate' | 'voice:action' + | 'help:check-updates' | 'help:about'; function send(win: BrowserWindow | undefined, command: MenuCommand): void { @@ -210,6 +211,11 @@ export function installApplicationMenu(getWindow: () => BrowserWindow | undefine { label: 'Help', submenu: [ + { + label: 'Check for Updates', + click: () => send(getWindow(), 'help:check-updates') + }, + { type: 'separator' }, { label: 'About ZeroG FileMan', click: () => send(getWindow(), 'help:about') diff --git a/src/main/favorites-store.ts b/src/main/favorites-store.ts index 0960be9..47075e3 100644 --- a/src/main/favorites-store.ts +++ b/src/main/favorites-store.ts @@ -4,8 +4,10 @@ import { join } from 'node:path'; import { app } from 'electron'; import { defaultLabelForPath, + isFavoritePath, normalizeFavorites, removeFavoritePath, + renameFavoritePath, upsertFavorite, type Favorite } from '../shared/favorites.js'; @@ -77,6 +79,17 @@ export async function addFavorite(path: unknown, label?: unknown): Promise { + const resolved = resolveLocalPath(path); + const nextLabel = typeof label === 'string' ? label.trim() : ''; + if (!nextLabel) throw new Error('Favorite name cannot be empty.'); + const current = await listFavorites(); + if (!isFavoritePath(current, resolved)) { + throw new Error('Favorite not found.'); + } + return writeStore(renameFavoritePath(current, resolved, nextLabel)); +} + export async function removeFavorite(path: unknown): Promise { const resolved = resolveLocalPath(path); const current = await listFavorites(); diff --git a/src/main/main.ts b/src/main/main.ts index 1ae50b4..4606ea2 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -4,6 +4,7 @@ import { clipboard, ipcMain, Menu, + net, safeStorage, session, shell, @@ -16,7 +17,9 @@ import { buildContextMenu, parseContextMenuTarget } from '../shared/context-menu import { parseServerTranscriptionInput, transcribeViaServer } from '../shared/speech-server.js'; import { isAppUrl, type AppLocation } from './app-origin.js'; import { installApplicationMenu } from './app-menu.js'; -import { addFavorite, listFavorites, removeFavorite } from './favorites-store.js'; +import { addFavorite, listFavorites, removeFavorite, renameFavorite } from './favorites-store.js'; +import { LATEST_RELEASE_API, RELEASES_URL, safeReleaseUrl, updateMode } from '../shared/update.js'; +import { UpdateService, type InstallUpdater } from './update-service.js'; import { copyLocalEntry, createLocalDirectory, @@ -119,10 +122,40 @@ function asKind(value: unknown): FileEntry['kind'] { throw new Error('Invalid entry kind.'); } +const updates = new UpdateService({ + mode: updateMode({ isPackaged: app.isPackaged, platform: process.platform, env: process.env }), + currentVersion: app.getVersion(), + loadUpdater: async () => { + const module = await import('electron-updater'); + return (module.default ?? module).autoUpdater as unknown as InstallUpdater; + }, + fetchLatest: async () => { + const response = await net.fetch(LATEST_RELEASE_API, { + headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'ZeroGFileMan-update-check' }, + signal: AbortSignal.timeout(15_000) + }); + if (response.status === 404) return null; + if (!response.ok) throw new Error(`GitHub answered ${response.status} to the update check.`); + return response.json(); + }, + onChange: (state) => mainWindow?.webContents.send('updates:state', state) +}); + +handle('updates:state', () => updates.current()); +handle('updates:check', () => updates.check()); +handle('updates:download', () => updates.download()); +handle('updates:install', () => updates.install()); +handle('updates:openRelease', () => { + const state = updates.current(); + const url = 'releaseUrl' in state ? safeReleaseUrl(state.releaseUrl) : RELEASES_URL; + return shell.openExternal(url); +}); + handle('fs:home', () => localHome()); handle('fs:drives', () => listLocalDrives()); handle('favorites:list', () => listFavorites()); handle('favorites:add', (_e, path: unknown, label?: unknown) => addFavorite(path, label)); +handle('favorites:rename', (_e, path: unknown, label: unknown) => renameFavorite(path, label)); handle('favorites:remove', (_e, path: unknown) => removeFavorite(path)); handle('fs:list', (_e, path?: unknown) => listLocalDirectory(typeof path === 'string' ? path : undefined) diff --git a/src/main/preload.cjs b/src/main/preload.cjs index b682b69..d3ffb8e 100644 --- a/src/main/preload.cjs +++ b/src/main/preload.cjs @@ -14,6 +14,7 @@ contextBridge.exposeInMainWorld('fileman', { listLocalDrives: () => ipcRenderer.invoke('fs:drives'), listFavorites: () => ipcRenderer.invoke('favorites:list'), addFavorite: (path, label) => ipcRenderer.invoke('favorites:add', path, label), + renameFavorite: (path, label) => ipcRenderer.invoke('favorites:rename', path, label), removeFavorite: (path) => ipcRenderer.invoke('favorites:remove', path), copyText: (text) => ipcRenderer.invoke('clipboard:write', text), openPath: (path) => ipcRenderer.invoke('shell:openPath', path), @@ -24,6 +25,16 @@ contextBridge.exposeInMainWorld('fileman', { saveSpeechApiKey: (key) => ipcRenderer.invoke('speechKey:save', key), clearSpeechApiKey: () => ipcRenderer.invoke('speechKey:clear'), transcribeViaServer: (request) => ipcRenderer.invoke('speech:transcribeServer', request), + updateState: () => ipcRenderer.invoke('updates:state'), + checkForUpdates: () => ipcRenderer.invoke('updates:check'), + downloadUpdate: () => ipcRenderer.invoke('updates:download'), + installUpdate: () => ipcRenderer.invoke('updates:install'), + openReleasePage: () => ipcRenderer.invoke('updates:openRelease'), + onUpdateState: (callback) => { + const handler = (_event, state) => callback(state); + ipcRenderer.on('updates:state', handler); + return () => ipcRenderer.removeListener('updates:state', handler); + }, showContextMenu: (target) => ipcRenderer.invoke('contextMenu:show', target), onMenuCommand: (callback) => { const handler = (_event, command) => callback(command); diff --git a/src/main/update-service.ts b/src/main/update-service.ts new file mode 100644 index 0000000..1308e1c --- /dev/null +++ b/src/main/update-service.ts @@ -0,0 +1,150 @@ +// Checking for, downloading and installing a newer release. +// +// Nothing happens on its own: the renderer asks for a check (at startup, when +// the setting allows it, or from Settings), and a download only starts when the +// user says so in the popup. That keeps the app from reaching out or replacing +// itself without consent, and keeps the policy — when to check, which version +// was skipped — in the renderer's settings where the user can see it. +// +// The installer is behind a small interface rather than imported directly, so +// the service can be tested with a fake and electron-updater is only loaded in a +// build that can actually use it. + +import { + type UpdateMode, + type UpdateState, + isNewer, + parseLatestRelease, + releaseUrlFor +} from '../shared/update.js'; + +/** The part of electron-updater's AppUpdater this uses. */ +export type InstallUpdater = { + autoDownload: boolean; + autoInstallOnAppQuit: boolean; + checkForUpdates(): Promise<{ updateInfo: { version: string } } | null>; + downloadUpdate(): Promise; + quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void; + on(event: 'download-progress', listener: (progress: { percent: number }) => void): unknown; +}; + +export type UpdateServiceOptions = { + mode: UpdateMode; + currentVersion: string; + /** Loads electron-updater; only called in `install` mode. */ + loadUpdater?: () => Promise; + /** GitHub's latest-release JSON; used in `notify` mode. */ + fetchLatest: () => Promise; + onChange: (state: UpdateState) => void; +}; + +/** An error from the network can carry a whole HTML page; keep one short line. */ +export function shortError(error: unknown): string { + const text = error instanceof Error ? error.message : String(error); + const line = text.split(/\r?\n/, 1)[0]?.trim() ?? ''; + if (!line) return 'The update check failed.'; + return line.length > 200 ? `${line.slice(0, 197)}…` : line; +} + +export class UpdateService { + private state: UpdateState; + private updater: InstallUpdater | null = null; + + constructor(private readonly options: UpdateServiceOptions) { + this.state = { status: 'idle', mode: options.mode, currentVersion: options.currentVersion }; + } + + current(): UpdateState { + return this.state; + } + + private set(state: UpdateState): UpdateState { + this.state = state; + this.options.onChange(state); + return state; + } + + private base() { + return { mode: this.options.mode, currentVersion: this.options.currentVersion }; + } + + private async installer(): Promise { + if (this.updater) return this.updater; + if (!this.options.loadUpdater) throw new Error('This build cannot install updates.'); + const updater = await this.options.loadUpdater(); + // Downloading is the user's call, made in the popup. + updater.autoDownload = false; + updater.autoInstallOnAppQuit = true; + updater.on('download-progress', (progress) => { + if (this.state.status !== 'downloading') return; + const percent = Math.max(0, Math.min(100, Math.round(Number(progress?.percent) || 0))); + if (percent !== this.state.percent) this.set({ ...this.state, percent }); + }); + this.updater = updater; + return updater; + } + + /** Look for a newer release. A check already under way, or a download, is left alone. */ + async check(): Promise { + const { mode } = this.options; + if (mode === 'disabled') return this.state; + if (this.state.status === 'checking' || this.state.status === 'downloading' || this.state.status === 'ready') { + return this.state; + } + this.set({ status: 'checking', ...this.base() }); + if (mode === 'install') { + try { + const updater = await this.installer(); + const result = await updater.checkForUpdates(); + const version = result?.updateInfo?.version; + if (typeof version === 'string' && isNewer(version, this.options.currentVersion)) { + return this.set({ status: 'available', ...this.base(), version, releaseUrl: releaseUrlFor(version) }); + } + return this.set({ status: 'current', ...this.base(), checkedAt: Date.now() }); + } catch (error) { + // A release published without its update manifest (latest.yml), or one + // the installer cannot read, should still be announced: fall back to + // the release page, and offer the download link instead of an install. + const fallback = await this.lookUpRelease(); + if (fallback.status === 'available') return this.set({ ...fallback, mode: 'notify' }); + return this.set({ status: 'error', ...this.base(), message: shortError(error) }); + } + } + return this.set(await this.lookUpRelease()); + } + + /** Ask GitHub for the newest release, without installing anything. */ + private async lookUpRelease(): Promise { + try { + const latest = parseLatestRelease(await this.options.fetchLatest()); + if (latest && isNewer(latest.version, this.options.currentVersion)) { + return { status: 'available', ...this.base(), ...latest }; + } + return { status: 'current', ...this.base(), checkedAt: Date.now() }; + } catch (error) { + return { status: 'error', ...this.base(), message: shortError(error) }; + } + } + + /** Fetch the update the last check found. Only an installable build can. */ + async download(): Promise { + // The state's own mode, not the build's: a release found through the + // fallback lookup has no manifest to download against. + if (this.state.status !== 'available' || this.state.mode !== 'install') return this.state; + const { version, releaseUrl } = this.state; + this.set({ status: 'downloading', ...this.base(), version, releaseUrl, percent: 0 }); + try { + const updater = await this.installer(); + await updater.downloadUpdate(); + return this.set({ status: 'ready', ...this.base(), version, releaseUrl }); + } catch (error) { + return this.set({ status: 'error', ...this.base(), message: shortError(error) }); + } + } + + /** Restart into the downloaded update. */ + install(): void { + if (this.state.status !== 'ready' || !this.updater) return; + this.updater.quitAndInstall(false, true); + } +} diff --git a/src/renderer/main.tsx b/src/renderer/main.tsx index 56e82c3..afffd4e 100644 --- a/src/renderer/main.tsx +++ b/src/renderer/main.tsx @@ -6,6 +6,7 @@ import { useRef, useState, type CSSProperties, + type DragEvent as ReactDragEvent, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from 'react'; @@ -24,6 +25,16 @@ import { import type { ContextMenuTargetKind } from '../shared/context-menu.js'; import { endpointNotices } from '../shared/endpoints.js'; import { entryNameProblem } from '../shared/entry-name.js'; +import { templateChoice } from '../shared/text-dialog.js'; +import { + DRAG_MIME, + decodeDragPayload, + dropMode, + encodeDragPayload, + planDrop, + type DropMode, + type DropMods +} from '../shared/drag-drop.js'; import { describeError, runReported } from '../shared/file-op.js'; import { fuzzyMatchEntries, fuzzyMatchHits, parseActionCommand } from '../shared/fuzzy-path.js'; import { @@ -79,6 +90,7 @@ import type { TerminalPrefs, VoiceMode } from '../shared/types.js'; +import { shouldPrompt, type UpdateState } from '../shared/update.js'; import { shouldStopJewelOnRelease } from '../shared/voice-jewel.js'; import { Icon } from './icons.js'; import { loadStoredWorkspaceLayout, storeWorkspaceLayout } from './layout-prefs.js'; @@ -101,6 +113,10 @@ import { type ThemeId } from './themes.js'; import { loadStoredTranscriptDrawer, storeTranscriptDrawer } from './transcript-prefs.js'; +import { loadStoredUpdateSettings, storeUpdateSettings, type UpdateSettings } from './update-settings.js'; +import { UpdatePrompt } from './update-prompt.js'; +import { useTextDialog, type AskText } from './text-dialog.js'; +import { updateSummary } from './update-view.js'; import { isMostlySilence, VoiceRecorder } from './voice.js'; // Fonts are bundled rather than fetched from Google Fonts, so a launch makes // no network request and the UI looks the same offline. @@ -112,6 +128,9 @@ type VoicePhase = 'idle' | 'listening' | 'transcribing'; const thumbCache = new Map(); +// Paths being dragged inside the app; dragover events cannot read the payload. +let activeDragPaths: string[] | null = null; + function EntryThumbnail(props: { path: string; name: string; @@ -396,6 +415,7 @@ function FilePane(props: { onToggleMaximize: () => void; onRefreshPeer?: () => void; onRegisterCommands: (commands: PaneCommands | null) => void; + askText: AskText; }) { const { side, @@ -415,7 +435,8 @@ function FilePane(props: { onClipboard, onToggleMaximize, onRefreshPeer, - onRegisterCommands + onRegisterCommands, + askText } = props; const showMenu = useCallback( @@ -675,23 +696,31 @@ function FilePane(props: { ); const doNewFolder = useCallback(async () => { - const name = window.prompt('New folder name', 'New Folder'); - if (!name?.trim()) return; - const nameProblem = entryNameProblem(name.trim(), isWindowsPath(pane.path) ? 'win32' : 'posix'); - if (nameProblem) { - onLog(`New folder: ${nameProblem}`); - return; - } + const platform = isWindowsPath(pane.path) ? 'win32' : 'posix'; + const name = await askText({ + title: 'New folder', + defaultValue: 'New Folder', + validate: (value) => entryNameProblem(value, platform) + }); + if (!name) return; await runReported( - `New folder “${name.trim()}”`, + `New folder “${name}”`, async () => { - await api().createLocalDirectory(joinLocal(pane.path, name.trim())); - await navigateTo(pane.path); - onLog(`[${stamp()}] mkdir ${name.trim()}`); + await api().createLocalDirectory(joinLocal(pane.path, name)); + const next = await loadPane(pane.path); + onChange({ + ...pane, + ...next, + ...exclusiveSelect(name), + matchNames: new Set(), + status: `Created ${name}`, + listening: null + }); + onLog(`[${stamp()}] mkdir ${name}`); }, onLog ); - }, [navigateTo, onLog, pane.path]); + }, [askText, onChange, onLog, pane]); const FILE_TEMPLATES = useMemo(() => [ { label: 'Text Document', ext: '.txt', content: '' }, @@ -707,30 +736,30 @@ function FilePane(props: { ], []); const doNewFile = useCallback(async () => { - const templateOptions = FILE_TEMPLATES.map(t => t.label).join('\n'); - const selectedType = window.prompt( - `Choose file type:\n\n${templateOptions}\n\nEnter number (1-${FILE_TEMPLATES.length}):`, - '1' - ); - if (!selectedType?.trim()) return; - - const typeIndex = parseInt(selectedType.trim(), 10) - 1; - if (isNaN(typeIndex) || typeIndex < 0 || typeIndex >= FILE_TEMPLATES.length) { - onLog('New file: invalid file type selection'); - return; - } + const selectedType = await askText({ + title: 'New file — choose type', + message: FILE_TEMPLATES.map((t, i) => `${i + 1}. ${t.label}`).join('\n'), + defaultValue: '1', + confirmLabel: 'Next', + validate: (value) => + templateChoice(value, FILE_TEMPLATES.length) === null + ? `Enter a number 1–${FILE_TEMPLATES.length}.` + : null + }); + if (!selectedType) return; + const typeIndex = templateChoice(selectedType, FILE_TEMPLATES.length); + if (typeIndex === null) return; const template = FILE_TEMPLATES[typeIndex]!; - const defaultName = `New File${template.ext}`; - const name = window.prompt(`New ${template.label} name`, defaultName); - if (!name?.trim()) return; - - const fileName = name.trim().endsWith(template.ext) ? name.trim() : name.trim() + template.ext; - const nameProblem = entryNameProblem(fileName, isWindowsPath(pane.path) ? 'win32' : 'posix'); - if (nameProblem) { - onLog(`New file: ${nameProblem}`); - return; - } + const platform = isWindowsPath(pane.path) ? 'win32' : 'posix'; + const withExt = (value: string) => (value.endsWith(template.ext) ? value : value + template.ext); + const name = await askText({ + title: `New ${template.label} name`, + defaultValue: `New File${template.ext}`, + validate: (value) => entryNameProblem(withExt(value), platform) + }); + if (!name) return; + const fileName = withExt(name); await runReported( `New file "${fileName}"`, @@ -741,28 +770,29 @@ function FilePane(props: { }, onLog ); - }, [FILE_TEMPLATES, navigateTo, onLog, pane.path]); + }, [FILE_TEMPLATES, askText, navigateTo, onLog, pane.path]); const doRename = useCallback(async () => { const sel = requireSelection(); if (!sel) return; - const next = window.prompt('Rename to', sel.name); - if (!next?.trim() || next.trim() === sel.name) return; - const nameProblem = entryNameProblem(next.trim(), isWindowsPath(pane.path) ? 'win32' : 'posix'); - if (nameProblem) { - onLog(`Rename “${sel.name}”: ${nameProblem}`); - return; - } + const platform = isWindowsPath(pane.path) ? 'win32' : 'posix'; + const next = await askText({ + title: 'Rename', + message: sel.name, + defaultValue: sel.name, + validate: (value) => entryNameProblem(value, platform) + }); + if (!next || next === sel.name) return; await runReported( `Rename “${sel.name}”`, async () => { - await api().renameLocalEntry(sel.path, joinLocal(pane.path, next.trim())); + await api().renameLocalEntry(sel.path, joinLocal(pane.path, next)); await refresh(); - onLog(`[${stamp()}] rename ${sel.name} → ${next.trim()}`); + onLog(`[${stamp()}] rename ${sel.name} → ${next}`); }, onLog ); - }, [onLog, pane.path, refresh, requireSelection]); + }, [askText, onLog, pane.path, refresh, requireSelection]); const doDelete = useCallback(async () => { const items = requireSelections(); @@ -833,6 +863,122 @@ function FilePane(props: { } }, [clipboard, onClipboard, onLog, onRefreshPeer, pane.path, refresh]); + const [dropHint, setDropHint] = useState<{ target: string; mode: DropMode } | null>(null); + const dragDepth = useRef(new Map()); + + const dragPreviewMode = useCallback((mods: DropMods, targetDir: string): DropMode => { + const source = activeDragPaths?.[0]; + return source ? dropMode(mods, source, targetDir) : mods.ctrl ? 'copy' : 'move'; + }, []); + + const performDrop = useCallback( + async (paths: string[], targetDir: string, mods: DropMods) => { + const plan = planDrop(paths, targetDir, mods); + if (!plan.items.length) { + onLog(`[${stamp()}] drop: nothing to do here`); + return; + } + let ok = 0; + for (const item of plan.items) { + try { + const dest = + item.mode === 'copy' + ? await api().copyLocalEntry(item.path, targetDir) + : await api().moveLocalEntry(item.path, targetDir); + ok += 1; + onLog(`[${stamp()}] ${item.mode} → ${targetDir}: ${baseName(dest)}`); + } catch (error) { + onLog(describeError(error)); + } + } + await refresh(); + onRefreshPeer?.(); + if (plan.items.length > 1) onLog(`[${stamp()}] drop: ${ok}/${plan.items.length} done`); + }, + [onLog, onRefreshPeer, refresh] + ); + + const dropTargetProps = useCallback( + (targetDir: string) => { + const hasPayload = (event: ReactDragEvent) => Array.from(event.dataTransfer.types).includes(DRAG_MIME); + const modsOf = (event: ReactDragEvent): DropMods => ({ + ctrl: event.ctrlKey || event.metaKey, + shift: event.shiftKey + }); + const hint = (event: ReactDragEvent) => { + const mode = dragPreviewMode(modsOf(event), targetDir); + setDropHint((prev) => + prev && prev.target === targetDir && prev.mode === mode ? prev : { target: targetDir, mode } + ); + }; + return { + onDragEnter: (event: ReactDragEvent) => { + if (!hasPayload(event)) return; + event.preventDefault(); + event.stopPropagation(); + dragDepth.current.set(targetDir, (dragDepth.current.get(targetDir) ?? 0) + 1); + hint(event); + }, + onDragOver: (event: ReactDragEvent) => { + if (!hasPayload(event)) return; + event.preventDefault(); + event.stopPropagation(); + event.dataTransfer.dropEffect = dragPreviewMode(modsOf(event), targetDir); + hint(event); + }, + onDragLeave: (event: ReactDragEvent) => { + if (!hasPayload(event)) return; + event.stopPropagation(); + const depth = (dragDepth.current.get(targetDir) ?? 1) - 1; + if (depth <= 0) { + dragDepth.current.delete(targetDir); + setDropHint((prev) => (prev?.target === targetDir ? null : prev)); + } else { + dragDepth.current.set(targetDir, depth); + } + }, + onDrop: (event: ReactDragEvent) => { + if (!hasPayload(event)) return; + event.preventDefault(); + event.stopPropagation(); + dragDepth.current.delete(targetDir); + setDropHint(null); + const paths = decodeDragPayload(event.dataTransfer.getData(DRAG_MIME)); + if (paths) void performDrop(paths, targetDir, modsOf(event)); + } + }; + }, + [dragPreviewMode, performDrop] + ); + + const dragSourceProps = useCallback( + (fullPath: string, selected: boolean) => ({ + draggable: true, + onDragStart: (event: ReactDragEvent) => { + const paths = + selected && selectedEntries.length > 1 + ? selectedEntries.map((entry) => joinLocal(pane.path, entry.name)) + : [fullPath]; + activeDragPaths = paths; + event.dataTransfer.setData(DRAG_MIME, encodeDragPayload(paths)); + event.dataTransfer.effectAllowed = 'copyMove'; + if (paths.length > 1) { + const chip = document.createElement('div'); + chip.className = 'drag-chip'; + chip.textContent = `${paths.length} items`; + document.body.appendChild(chip); + event.dataTransfer.setDragImage(chip, 12, 12); + window.setTimeout(() => chip.remove(), 0); + } + }, + onDragEnd: () => { + activeDragPaths = null; + setDropHint(null); + } + }), + [pane.path, selectedEntries] + ); + const applyNavigate = useCallback( async (transcript: string) => { onChange({ ...pane, status: `Searching “${transcript}”…`, listening: null }); @@ -1330,7 +1476,8 @@ function FilePane(props: { {driveRoot || index > 0 ? / : null}
@@ -2136,41 +2360,47 @@ function App() {
{favorites.map((fav) => ( - + + + +
))}
+ +
+ Update status + {updateSummary(update)} +
+
+ + +