From 046eaccdafdd1677721d363fb9304beda10b36f7 Mon Sep 17 00:00:00 2001 From: Stephen Phillips Date: Mon, 16 Nov 2026 17:43:09 +0000 Subject: [PATCH 1/3] feat: consent-based app updates and favorites polish - App updates from GitHub releases: startup/manual checks, NSIS in-place install, portable release-page notification, settings controls, and a tag-driven Windows release workflow (27 tests) - Favorites: order-preserving rename, picker rename/remove controls, and a path action that toggles Add/Remove (+2 tests) Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- .github/workflows/release.yml | 119 ++++++++++++++++ PROGRESS.md | 4 + README.md | 12 ++ ROADMAP.md | 4 +- package-lock.json | 66 +++++++-- package.json | 9 ++ src/main/app-menu.ts | 6 + src/main/favorites-store.ts | 12 ++ src/main/main.ts | 35 ++++- src/main/preload.cjs | 11 ++ src/main/update-service.ts | 150 +++++++++++++++++++ src/renderer/main.tsx | 170 ++++++++++++++++++---- src/renderer/styles.css | 189 +++++++++++++++++++++++- src/renderer/update-prompt.tsx | 68 +++++++++ src/renderer/update-settings.ts | 45 ++++++ src/renderer/update-view.ts | 33 +++++ src/shared/favorites.ts | 8 ++ src/shared/types.ts | 8 ++ src/shared/update.ts | 161 +++++++++++++++++++++ tests/favorites.test.ts | 13 ++ tests/update.test.ts | 245 ++++++++++++++++++++++++++++++++ 21 files changed, 1326 insertions(+), 42 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 src/main/update-service.ts create mode 100644 src/renderer/update-prompt.tsx create mode 100644 src/renderer/update-settings.ts create mode 100644 src/renderer/update-view.ts create mode 100644 src/shared/update.ts create mode 100644 tests/update.test.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..71ea94f --- /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}" == *-* ]]; 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..e1ef26f 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -24,6 +24,10 @@ 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 ## 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..789a400 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,7 +46,7 @@ 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 | ### P2 — Voice that works offline @@ -75,6 +76,7 @@ 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 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..611dcdd 100644 --- a/src/main/favorites-store.ts +++ b/src/main/favorites-store.ts @@ -6,6 +6,7 @@ import { defaultLabelForPath, normalizeFavorites, removeFavoritePath, + renameFavoritePath, upsertFavorite, type Favorite } from '../shared/favorites.js'; @@ -77,6 +78,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 (!current.some((favorite) => favorite.path.toLowerCase() === resolved.toLowerCase())) { + 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..38c36b5 100644 --- a/src/renderer/main.tsx +++ b/src/renderer/main.tsx @@ -79,6 +79,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 +102,9 @@ 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 { 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. @@ -1678,6 +1682,11 @@ function App() { loadStoredTranscriptDrawer() ); const [log, setLog] = useState([`[${stamp()}] ZeroG FileMan ready · dual commander`]); + const [update, setUpdate] = useState(null); + const [dismissedUpdate, setDismissedUpdate] = useState(null); + const [updateAsked, setUpdateAsked] = useState(false); + const [updateSettings, setUpdateSettings] = useState(() => loadStoredUpdateSettings()); + const startupCheckDone = useRef(false); const leftCommands = useRef(null); const rightCommands = useRef(null); const jumpInputRef = useRef(null); @@ -1721,6 +1730,24 @@ function App() { }); }, []); + const updateUpdateSettings = useCallback((patch: Partial) => { + setUpdateSettings((prev) => { + const next = { ...prev, ...patch }; + storeUpdateSettings(next); + return next; + }); + }, []); + + const checkForUpdatesNow = useCallback(() => { + setUpdateAsked(true); + void api().checkForUpdates().catch((error) => pushLog(error instanceof Error ? error.message : String(error))); + }, [pushLog]); + + const closeUpdatePrompt = useCallback(() => { + if (update && 'version' in update) setDismissedUpdate(update.version); + setUpdateAsked(false); + }, [update]); + useEffect(() => { applyTheme(theme); storeTheme(theme); @@ -1733,6 +1760,20 @@ function App() { .catch(() => undefined); }, []); + useEffect(() => { + void api().updateState().then(setUpdate).catch(() => undefined); + return api().onUpdateState(setUpdate); + }, []); + + useEffect(() => { + if (startupCheckDone.current || !updateSettings.checkOnStartup) return; + const timer = window.setTimeout(() => { + startupCheckDone.current = true; + void api().checkForUpdates().catch(() => undefined); + }, 8000); + return () => window.clearTimeout(timer); + }, [updateSettings.checkOnStartup]); + const cmds = () => (active === 'left' ? leftCommands.current : rightCommands.current); const focusJump = useCallback(() => { @@ -1792,6 +1833,21 @@ function App() { [pushLog] ); + const renameFavoriteChip = useCallback( + async (favorite: Favorite) => { + const label = window.prompt('Favorite name', favorite.label); + if (label === null || !label.trim() || label.trim() === favorite.label) return; + try { + const next = await api().renameFavorite(favorite.path, label.trim()); + setFavorites(next); + pushLog(`[${stamp()}] favorite renamed ${favorite.path} → ${label.trim()}`); + } catch (error) { + pushLog(error instanceof Error ? error.message : String(error)); + } + }, + [pushLog] + ); + const refreshSide = useCallback((side: 'left' | 'right') => { const setter = side === 'left' ? setLeft : setRight; setter((prev) => { @@ -2038,6 +2094,9 @@ function App() { case 'voice:action': c?.voiceAction(); break; + case 'help:check-updates': + checkForUpdatesNow(); + break; case 'help:about': pushLog('ZeroG FileMan — local dual-pane voice file manager (HappyMonkeyAI)'); break; @@ -2045,7 +2104,7 @@ function App() { break; } }); - }, [active, addCurrentFavorite, focusJump, pushLog]); + }, [active, addCurrentFavorite, checkForUpdatesNow, focusJump, pushLog]); const runGlobalJump = async () => { const q = jumpQuery.trim(); @@ -2059,6 +2118,7 @@ function App() { const activePath = (active === 'left' ? left : right)?.path ?? ''; const activeIsFavorite = isFavoritePath(favorites, activePath); + const updatePromptOpen = shouldPrompt(update, updateSettings.skippedVersion, dismissedUpdate, updateAsked); if (!left || !right) { return ( @@ -2128,6 +2188,15 @@ function App() { +
@@ -2136,41 +2205,47 @@ function App() {
{favorites.map((fav) => ( - + + + +
))}
+ +
+ Update status + {updateSummary(update)} +
+
+ + +