Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

Add automatic updates and a tag-driven release workflow (#107)

Anmol Kapilb2d2698c2c0b
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..1cb8b02
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,102 @@
+name: Release
+
+# Pushing a version tag (git tag v1.0.0-rc.15 && git push origin v1.0.0-rc.15) builds every OS
+# and leaves a draft GitHub Release. Apps only see it once the draft is published.
+on:
+ push:
+ tags: ['v*']
+
+permissions:
+ contents: write
+
+jobs:
+ build:
+ name: Build (${{ matrix.os }})
+ strategy:
+ matrix:
+ include:
+ - os: macos-latest
+ target: --mac
+ - os: windows-latest
+ target: --win
+ - os: ubuntu-latest
+ target: --linux
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+
+ # The tag names the version the build gets; a mismatch would ship one version as another.
+ - name: Check the tag matches package.json
+ shell: bash
+ run: test "v$(node -p "require('./package.json').version")" = "$GITHUB_REF_NAME"
+
+ - name: Install rpmbuild
+ if: runner.os == 'Linux'
+ run: sudo apt-get update && sudo apt-get install -y rpm
+
+ - name: Install dependencies
+ run: npm ci
+
+ # Without the certificate secrets the Mac build is unsigned, and can't update itself; without
+ # the API key ones it's signed but not notarized. Exported on the Mac only: electron-builder
+ # would otherwise sign Windows with CSC_LINK too.
+ - name: Build
+ shell: bash
+ env:
+ MAC_CERTIFICATE_P12_BASE64: ${{ secrets.MAC_CERTIFICATE_P12_BASE64 }}
+ MAC_CERTIFICATE_PASSWORD: ${{ secrets.MAC_CERTIFICATE_PASSWORD }}
+ APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}
+ APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
+ APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
+ run: |
+ if [ "$RUNNER_OS" = macOS ] && [ -n "$MAC_CERTIFICATE_P12_BASE64" ]; then
+ export CSC_LINK="$MAC_CERTIFICATE_P12_BASE64" CSC_KEY_PASSWORD="$MAC_CERTIFICATE_PASSWORD"
+ fi
+ if [ "$RUNNER_OS" = macOS ] && [ -n "$APPLE_API_KEY_P8" ]; then
+ echo "$APPLE_API_KEY_P8" > "$RUNNER_TEMP/apple-api-key.p8"
+ export APPLE_API_KEY="$RUNNER_TEMP/apple-api-key.p8"
+ fi
+ npm run build
+ npx electron-builder ${{ matrix.target }} --publish never
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: dist-${{ runner.os }}
+ path: |
+ dist/*.dmg
+ dist/*.zip
+ dist/*.exe
+ dist/*.AppImage
+ dist/*.deb
+ dist/*.rpm
+ dist/*.yml
+ dist/*.blockmap
+ if-no-files-found: error
+
+ release:
+ needs: build
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/download-artifact@v4
+ with:
+ path: dist
+ merge-multiple: true
+
+ - name: Create a draft release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ TAG: ${{ github.ref_name }}
+ run: |
+ node scripts/release-notes.mjs "$TAG" > "$RUNNER_TEMP/notes.md"
+ node scripts/release-notes.mjs "$TAG" --files > "$RUNNER_TEMP/files.txt"
+ # Not --prerelease, even for an rc: the app updates to the release GitHub marks Latest,
+ # and a pre-release never is (see src/main/updater.ts).
+ xargs -d '\n' gh release create "$TAG" --draft --title "$TAG" \
+ --notes-file "$RUNNER_TEMP/notes.md" < "$RUNNER_TEMP/files.txt"
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4e924fb..af7b769 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -60,16 +60,19 @@ Tests build the app first; set `PLEXO_E2E_SKIP_BUILD=1` when `out/` is already f
A release ships seven files: `Plexo` for macOS (Apple silicon and Intel `.dmg`), Windows (one installer for x64 and ARM64) and Linux (`AppImage` and `.deb`, x86_64 and ARM64). The download page (`docs/`, served by GitHub Pages) reads them from the latest GitHub Release and labels each one from its file name (`docs/downloads.js`), so keep the naming in `electron-builder.yml` intact.
-```bash
-npm version <version> --no-git-tag-version # e.g. 1.0.0-rc.8
-npm run build:mac && npm run build:win && npm run build:linux
+A version tag releases it: `.github/workflows/release.yml` builds every OS and leaves a draft GitHub Release with the downloads table.
-node scripts/release-notes.mjs v<version> notes.md > body.md # your notes + the downloads table
-gh release create v<version> --prerelease --title v<version> --notes-file body.md \
- $(node scripts/release-notes.mjs v<version> --files)
+```bash
+npm version <version> --no-git-tag-version # e.g. 1.0.0-rc.15
+git commit -am "Release v<version>" && git push
+git tag v<version> && git push origin v<version>
```
-The script only picks up files the download page knows how to describe, so the update metadata and blockmaps electron-builder leaves in `dist/` are never uploaded.
+Then add your notes to the draft and publish it. Publishing is what ships it: it becomes the Latest release, and within a few hours every running Plexo downloads it in the background and offers a restart. Leave rc releases unmarked as pre-release: the app only updates to Latest, which a pre-release never is. Mark one pre-release (a beta after 1.0, say) to keep it from everyone's automatic updates. A build to throw away? Delete the draft and the tag.
+
+Besides the downloads, a release carries what the app's updater reads (`src/main/updater.ts`): the `latest*.yml` channel files, the macOS `.zip`s and the blockmaps. `scripts/release-notes.mjs --files` lists them; the download page ignores them.
+
+macOS only installs signed updates. The release workflow signs and notarizes the Mac build when these repository secrets are set: `MAC_CERTIFICATE_P12_BASE64` and `MAC_CERTIFICATE_PASSWORD` (a Developer ID Application certificate), and `APPLE_API_KEY_P8`, `APPLE_API_KEY_ID` and `APPLE_API_ISSUER` (an App Store Connect API key). Without them a Mac that finds an update sends you to the website for it.
## Reporting bugs
diff --git a/e2e/releaseNotes.spec.ts b/e2e/releaseNotes.spec.ts
index 4a82670..ac26690 100644
--- a/e2e/releaseNotes.spec.ts
+++ b/e2e/releaseNotes.spec.ts
@@ -15,6 +15,23 @@ const builds = (version: string): string[] => [
`plexo_${version}_arm64.deb`
]
+/** What the app's updater reads besides the downloads (see src/main/updater.ts); the release
+ * notes never list them. */
+const updateFiles = (version: string): string[] => [
+ `plexo-${version}-arm64-mac.zip`,
+ `plexo-${version}-x64-mac.zip`,
+ `plexo-${version}-arm64-mac.zip.blockmap`,
+ `plexo-${version}-setup.exe.blockmap`
+]
+const channelFiles = ['latest.yml', 'latest-mac.yml', 'latest-linux.yml']
+
+/** Writes channel files the way electron-builder does: the version first. */
+function writeChannelFiles(root: string, version: string, names = channelFiles): void {
+ for (const name of names) {
+ writeFileSync(join(root, 'dist', name), `version: ${version}\nfiles: []\n`)
+ }
+}
+
function prepareRelease(root: string, files: string[]): string {
for (const dir of ['scripts', 'docs', 'dist']) mkdirSync(join(root, dir), { recursive: true })
for (const file of ['scripts/release-notes.mjs', 'docs/downloads.js']) {
@@ -33,24 +50,26 @@ test.describe('release artifact selection @smoke', () => {
test(`only ${version} builds appear in the upload list and release notes`, () => {
const root = test.info().outputPath('release')
const expected = builds(version)
+ // 1.0.0-rc.10's files must not pass for 1.0.0-rc.1's, nor 1.0.0-rc.11's for 1.0.0's.
const otherBuilds = ['1.0.0-rc.10', '1.0.0-rc.11', '1.0.0', '11.0.0']
.filter((other) => other !== version)
- .flatMap(builds)
- const noise = [
- 'latest.yml',
- `plexo-${version}-arm64.dmg.blockmap`,
- `plexo-${version}-setup.exe.blockmap`,
- `plexo-${version}.aarch64.rpm.blockmap`,
- `plexo-${version}.x86_64.rpm.blockmap`,
- `plexo_${version}_amd64.snap`
- ]
- const script = prepareRelease(root, [...expected, ...otherBuilds, ...noise])
+ .flatMap((other) => [...builds(other), ...updateFiles(other)])
+ const noise = [`plexo_${version}_amd64.snap`]
+ const script = prepareRelease(root, [
+ ...expected,
+ ...updateFiles(version),
+ ...otherBuilds,
+ ...noise
+ ])
+ writeChannelFiles(root, version)
const files = spawnSync(process.execPath, [script, `v${version}`, '--files'], {
encoding: 'utf8'
})
expect(files.status, files.stderr).toBe(0)
expect(files.stdout.trim().split('\n').sort()).toEqual(
- expected.map((file) => join(root, 'dist', file)).sort()
+ [...expected, ...updateFiles(version), ...channelFiles]
+ .map((file) => join(root, 'dist', file))
+ .sort()
)
const notesPath = join(root, 'notes.md')
@@ -64,10 +83,29 @@ test.describe('release artifact selection @smoke', () => {
const url = `https://github.com/anmolkapil/plexo/releases/download/v${version}/${file}`
expect(notes.stdout.split(url + ')')).toHaveLength(2)
}
- for (const file of [...otherBuilds, ...noise]) expect(notes.stdout).not.toContain(file)
+ for (const file of [...otherBuilds, ...noise, ...updateFiles(version), ...channelFiles]) {
+ expect(notes.stdout).not.toContain(file)
+ }
})
}
+ // Either way the release would reach no installed app, or point them all at another build.
+ test('a release without its own latest*.yml is refused', () => {
+ const root = test.info().outputPath('release')
+ const script = prepareRelease(root, builds('1.0.0'))
+ const run = (): { status: number | null; stderr: string } =>
+ spawnSync(process.execPath, [script, 'v1.0.0', '--files'], { encoding: 'utf8' })
+
+ expect(run()).toMatchObject({ status: 1, stderr: expect.stringContaining('No latest*.yml') })
+
+ writeChannelFiles(root, '1.0.0')
+ writeChannelFiles(root, '1.0.0-rc.15', ['latest-linux.yml'])
+ expect(run()).toMatchObject({
+ status: 1,
+ stderr: expect.stringContaining("latest-linux.yml isn't for 1.0.0")
+ })
+ })
+
for (const version of ['1.0.0-rc.1', '1.0.0']) {
test(`other versions do not satisfy a missing ${version} build`, () => {
const script = prepareRelease(test.info().outputPath('release'), builds('1.0.0-rc.11'))
diff --git a/e2e/ui.spec.ts b/e2e/ui.spec.ts
index 4b981e9..382ffe2 100644
--- a/e2e/ui.spec.ts
+++ b/e2e/ui.spec.ts
@@ -285,72 +285,61 @@ test.describe('UI journeys @smoke', () => {
// What a user sets is still set after they reload or restart — checked only through what they see.
test.describe('settings @smoke', () => {
- test.describe('with an update available', () => {
- test.use({ appEnv: { PLEXO_FORCE_UPDATE_VERSION: '9.9.9' } })
-
- test('every choice survives a reload and a restart, even made right before', async ({
- plexo,
- dirs
- }) => {
- const page = (): Page => plexo.page
- await page().getByRole('button', { name: 'Not now' }).click()
+ test('every choice survives a reload and a restart, even made right before', async ({
+ plexo,
+ dirs
+ }) => {
+ const page = (): Page => plexo.page
+ const themeToggle = page().getByRole('button', { name: /^Switch to (dark|light) theme$/ })
+ // After switching, the toggle offers to switch back.
+ const labelAfterSwitch = (await themeToggle.getAttribute('aria-label'))!.includes('dark')
+ ? 'Switch to light theme'
+ : 'Switch to dark theme'
+ await themeToggle.click()
- const themeToggle = page().getByRole('button', { name: /^Switch to (dark|light) theme$/ })
- // After switching, the toggle offers to switch back.
- const labelAfterSwitch = (await themeToggle.getAttribute('aria-label'))!.includes('dark')
- ? 'Switch to light theme'
- : 'Switch to dark theme'
- await themeToggle.click()
+ await stubNativeUi(plexo, dirs.dest)
+ await plexo.newDownload()
+ await page().getByRole('button', { name: 'Change' }).click()
+ const destinationRow = (): Locator => page().getByText('Save to', { exact: true }).locator('..')
+ const chosenDestination = await destinationRow().innerText()
+ await page().keyboard.press('Escape')
+ // A function: the window, and so the page, is a new one after a relaunch.
+ const networksMenu = (): Locator =>
+ page()
+ .getByRole('button', { name: /network/ })
+ .first()
+ .first()
+ await networksMenu().click()
+ await page().getByRole('button', { name: 'Edit network' }).first().click()
+ await page().getByRole('textbox', { name: 'Name' }).fill('Office fibre')
+ await page().getByRole('button', { name: 'Violet' }).click()
+ await page().getByRole('button', { name: 'Done' }).click()
+ await page().keyboard.press('Escape')
- await stubNativeUi(plexo, dirs.dest)
+ const expectAllKept = async (): Promise<void> => {
+ await expect(page().getByRole('button', { name: labelAfterSwitch })).toBeVisible()
await plexo.newDownload()
- await page().getByRole('button', { name: 'Change' }).click()
- const destinationRow = (): Locator =>
- page().getByText('Save to', { exact: true }).locator('..')
- const chosenDestination = await destinationRow().innerText()
+ await expect(destinationRow()).toHaveText(chosenDestination, { useInnerText: true })
+ // Presentation may abbreviate home; persistence must retain the usable absolute path.
+ const saved = JSON.parse(await readFile(join(dirs.userData, 'app-settings.json'), 'utf8'))
+ expect(saved.destinationDir).toBe(dirs.dest)
await page().keyboard.press('Escape')
- // A function: the window, and so the page, is a new one after a relaunch.
- const networksMenu = (): Locator =>
- page()
- .getByRole('button', { name: /network/ })
- .first()
- .first()
await networksMenu().click()
+ await expect(page().getByText('Office fibre')).toBeVisible()
await page().getByRole('button', { name: 'Edit network' }).first().click()
- await page().getByRole('textbox', { name: 'Name' }).fill('Office fibre')
- await page().getByRole('button', { name: 'Violet' }).click()
- await page().getByRole('button', { name: 'Done' }).click()
+ await expect(page().getByRole('button', { name: 'Violet' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ )
await page().keyboard.press('Escape')
+ await page().keyboard.press('Escape')
+ }
- const expectAllKept = async (): Promise<void> => {
- // Waiting on the status bar's indicator first means the update check has answered, so
- // the dialog's absence below is a real "stayed dismissed", not "not checked yet".
- await expect(page().getByRole('link', { name: 'Update available: 9.9.9' })).toBeVisible()
- await expect(page().getByRole('alertdialog')).toBeHidden()
- await expect(page().getByRole('button', { name: labelAfterSwitch })).toBeVisible()
- await plexo.newDownload()
- await expect(destinationRow()).toHaveText(chosenDestination, { useInnerText: true })
- // Presentation may abbreviate home; persistence must retain the usable absolute path.
- const saved = JSON.parse(await readFile(join(dirs.userData, 'app-settings.json'), 'utf8'))
- expect(saved.destinationDir).toBe(dirs.dest)
- await page().keyboard.press('Escape')
- await networksMenu().click()
- await expect(page().getByText('Office fibre')).toBeVisible()
- await page().getByRole('button', { name: 'Edit network' }).first().click()
- await expect(page().getByRole('button', { name: 'Violet' })).toHaveAttribute(
- 'aria-pressed',
- 'true'
- )
- await page().keyboard.press('Escape')
- await page().keyboard.press('Escape')
- }
-
- // No waiting for saves: a user doesn't either.
- await page().reload()
- await expectAllKept()
- await plexo.relaunch()
- await expectAllKept()
- })
+ // No waiting for saves: a user doesn't either.
+ await page().reload()
+ await expectAllKept()
+ await plexo.relaunch()
+ await expectAllKept()
})
test('a broken settings file falls back to what a fresh install shows', async ({
diff --git a/electron-builder.yml b/electron-builder.yml
index e7f6e0d..f71e858 100644
--- a/electron-builder.yml
+++ b/electron-builder.yml
@@ -43,6 +43,9 @@ mac:
target:
- target: dmg
arch: [x64, arm64]
+ # Not for people: the app's updater installs from these (see src/main/updater.ts).
+ - target: zip
+ arch: [x64, arm64]
entitlementsInherit: build/entitlements.mac.plist
extendInfo:
- NSDownloadsFolderUsageDescription: Plexo saves downloaded files to your Downloads folder.
@@ -60,7 +63,9 @@ mac:
LSHandlerRank: Alternate
CFBundleTypeExtensions: [torrent]
LSItemContentTypes: [org.bittorrent.torrent]
- notarize: false
+ # Signed when CSC_LINK/CSC_KEY_PASSWORD are set, and then notarized when APPLE_API_KEY,
+ # APPLE_API_KEY_ID and APPLE_API_ISSUER are (see .github/workflows/release.yml). An unsigned
+ # build still works, but can't update itself: macOS only installs signed updates.
dmg:
artifactName: ${name}-${version}-${arch}.${ext}
linux:
@@ -75,9 +80,14 @@ linux:
category: Utility
# Offered for magnet links and .torrent files ("Open with"), not made their default.
mimeTypes: [x-scheme-handler/magnet, application/x-bittorrent, x-scheme-handler/plexo]
+zip:
+ artifactName: ${name}-${version}-${arch}-mac.${ext}
appImage:
artifactName: ${name}-${version}-${arch}.${ext}
npmRebuild: false
+# Where the app looks for updates. Builds never publish themselves (--publish never): the release
+# workflow uploads them, with the latest*.yml files the updater reads.
publish:
- provider: generic
- url: https://example.com/auto-updates
+ provider: github
+ owner: anmolkapil
+ repo: plexo
diff --git a/package-lock.json b/package-lock.json
index 2580a2b..20cf616 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "plexo",
- "version": "1.0.0-rc.14",
+ "version": "1.0.0-rc.15",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "plexo",
- "version": "1.0.0-rc.14",
+ "version": "1.0.0-rc.15",
"hasInstallScript": true,
"dependencies": {
"@base-ui/react": "^1.8.0",
@@ -16,6 +16,7 @@
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
"date-fns": "^4.4.0",
+ "electron-updater": "^6.8.9",
"fs-chunk-store": "5.0.1",
"koffi": "^2.16.3",
"lucide-react": "^1.47.0",
@@ -3486,7 +3487,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/array-buffer-byte-length": {
@@ -4274,7 +4274,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",
@@ -5256,6 +5255,34 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/electron-updater": {
+ "version": "6.8.9",
+ "resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.9.tgz",
+ "integrity": "sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==",
+ "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-vite": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/electron-vite/-/electron-vite-5.0.0.tgz",
@@ -6423,7 +6450,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",
@@ -6438,7 +6464,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"
@@ -6451,7 +6476,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"
@@ -7760,7 +7784,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",
@@ -7980,7 +8003,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/levn": {
@@ -8317,6 +8339,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/lodash.merge": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
@@ -11154,6 +11189,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/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
diff --git a/package.json b/package.json
index ba40858..8495a77 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "plexo",
- "version": "1.0.0-rc.14",
+ "version": "1.0.0-rc.15",
"description": "Speed up downloads by combining multiple network connections in parallel",
"main": "./out/main/index.js",
"author": "Anmol Kapil",
@@ -36,6 +36,7 @@
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
"date-fns": "^4.4.0",
+ "electron-updater": "^6.8.9",
"fs-chunk-store": "5.0.1",
"koffi": "^2.16.3",
"lucide-react": "^1.47.0",
diff --git a/scripts/release-notes.mjs b/scripts/release-notes.mjs
index b8f1981..bdc75f1 100644
--- a/scripts/release-notes.mjs
+++ b/scripts/release-notes.mjs
@@ -46,7 +46,35 @@ if (files.length === 0) {
}
if (arg === '--files') {
- console.log(files.map((file) => file.path).join('\n'))
+ // What the app's updater reads (src/main/updater.ts): each OS's latest*.yml (a GitHub-published
+ // build never writes an rc*.yml), the zips macOS installs from, and blockmaps, which let an
+ // update download only what changed.
+ // Named after the build they belong to, so read its version the same way (1.0.0 must not take
+ // 1.0.0-rc.15's).
+ const buildOf = (name) => name.replace(/\.blockmap$/, '').replace(/-mac\.zip$/, '.zip')
+ const updateFiles = readdirSync(dist).filter(
+ (name) =>
+ /^latest(-[a-z0-9-]+)?\.yml$/.test(name) ||
+ ((name.endsWith('-mac.zip') || name.endsWith('.blockmap')) &&
+ buildOf(name).match(artifactName)?.[1] === version)
+ )
+ // Without them the release is invisible to every installed app.
+ const channelFiles = updateFiles.filter((name) => name.endsWith('.yml'))
+ if (channelFiles.length === 0) {
+ console.error('No latest*.yml in dist/ — the app could never update to this release.')
+ process.exit(1)
+ }
+ // Channel files carry no version in their name, so one left over from an older build would
+ // point every app at that build.
+ for (const name of channelFiles) {
+ if (!readFileSync(join(dist, name), 'utf-8').includes(`version: ${version}\n`)) {
+ console.error(`dist/${name} isn't for ${version} — rebuild that platform.`)
+ process.exit(1)
+ }
+ }
+ console.log(
+ [...files.map((file) => file.path), ...updateFiles.map((name) => join(dist, name))].join('\n')
+ )
} else {
const notes = arg ? readFileSync(arg, 'utf-8').trim() + '\n\n' : ''
console.log(notes + downloads.markdown(files, SITE))
diff --git a/src/main/index.ts b/src/main/index.ts
index e709f6e..eff6091 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -5,7 +5,8 @@ import icon from '../../resources/icon-dark.png?asset'
import { registerIpcHandlers } from './ipc/handlers'
import { keepsRunningForBrowser, startBridge } from './browserBridge'
import { acceptedLink, bringForward, linkFromArgs, offerLink } from './openLinks'
-import { loadThemeSource, migrateLegacyNetworkPreferences } from './settings'
+import { loadSettings, loadThemeSource, migrateLegacyNetworkPreferences } from './settings'
+import { startUpdater } from './updater'
import { testKnobs } from './testKnobs'
import type { DownloadManager } from './download/downloadManager'
@@ -171,6 +172,7 @@ app.whenReady().then(async () => {
createWindow()
if (testKnobs.hideWindow) app.dock?.hide()
+ startUpdater(() => mainWindow, (await loadSettings()).autoUpdate !== false)
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.ts
index 1f07300..5ed3eb7 100644
--- a/src/main/ipc/handlers.ts
+++ b/src/main/ipc/handlers.ts
@@ -1,6 +1,5 @@
import { stat, statfs } from 'node:fs/promises'
import {
- app,
clipboard,
dialog,
ipcMain,
@@ -26,8 +25,7 @@ import { deviceBindingSupported } from '../network/deviceBinding'
import { pendingLink, pendingLinks, releaseLink } from '../openLinks'
import { NetworkMonitor } from '../network/interfaces'
import { loadSettings, saveSettings } from '../settings'
-import { testKnobs } from '../testKnobs'
-import { checkForUpdate, UPDATE_PAGE_URL } from '../updateCheck'
+import { showUpdateMenu, updateState } from '../updater'
async function openNetworkSettings(): Promise<void> {
if (process.platform === 'win32') {
@@ -246,23 +244,8 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
manager.remove(id, options?.trashFile === true)
)
- // Kicked off once at startup, not per-call — later renderer calls (e.g. a remount) just await
- // the same in-flight/settled check instead of re-hitting the GitHub API.
- const updateCheckPromise = (async () => {
- const info = testKnobs.forceUpdateVersion
- ? { version: testKnobs.forceUpdateVersion, url: UPDATE_PAGE_URL }
- : await checkForUpdate(app.getVersion())
- return info
- })()
-
- // Dismissal is read per call, not cached with the check — a reload after "Not now" must not
- // bring the dialog back.
- handle('checkForUpdate', async () => {
- const info = await updateCheckPromise
- if (!info) return null
- const { dismissedUpdateVersion } = await loadSettings()
- return { ...info, dismissed: info.version === dismissedUpdateVersion }
- })
+ handle('updateState', () => updateState())
+ handle('showUpdateMenu', () => showUpdateMenu())
return manager
}
diff --git a/src/main/settings.ts b/src/main/settings.ts
index 69af7d3..fa12346 100644
--- a/src/main/settings.ts
+++ b/src/main/settings.ts
@@ -61,7 +61,7 @@ function sanitizeNetworkPreferences(parsed: unknown): NetworkPreferences {
function sanitizeSettings(parsed: unknown): AppSettings {
if (!isRecord(parsed)) return {}
- const { themeSource, dismissedUpdateVersion, destinationDir, downloadsAtOnce } = parsed
+ const { themeSource, destinationDir, downloadsAtOnce } = parsed
const settings: AppSettings = {}
if (parsed.downloadSchedule !== undefined) {
settings.downloadSchedule = validSchedule(parsed.downloadSchedule)
@@ -70,9 +70,7 @@ function sanitizeSettings(parsed: unknown): AppSettings {
}
// 'system' was once an option — dropping it falls back to the OS appearance (loadThemeSource).
if (themeSource === 'light' || themeSource === 'dark') settings.themeSource = themeSource
- if (typeof dismissedUpdateVersion === 'string') {
- settings.dismissedUpdateVersion = dismissedUpdateVersion
- }
+ if (parsed.autoUpdate === false) settings.autoUpdate = false
if (typeof destinationDir === 'string' && isAbsolute(destinationDir)) {
settings.destinationDir = destinationDir
}
diff --git a/src/main/testKnobs.ts b/src/main/testKnobs.ts
index 579179b..8d75eca 100644
--- a/src/main/testKnobs.ts
+++ b/src/main/testKnobs.ts
@@ -29,10 +29,7 @@ export const testKnobs = {
/** How long a magnet link may take to find peers that send its metadata. */
magnetTimeoutMs: positiveNumber('PLEXO_E2E_MAGNET_MS', 3 * 60_000),
/** Tests turn the DHT off, so a run never reaches out to the internet's DHT nodes. */
- torrentDht: env['PLEXO_E2E_DHT'] !== '0',
- /** Skips the real GitHub check and pretends this version is available, for exercising the
- * update banner without needing an actual newer release published. */
- forceUpdateVersion: env['PLEXO_FORCE_UPDATE_VERSION']
+ torrentDht: env['PLEXO_E2E_DHT'] !== '0'
}
/** `PLEXO_E2E_STREAMS=2` fixes how many streams each network runs and turns the automatic
diff --git a/src/main/updateCheck.ts b/src/main/updateCheck.ts
deleted file mode 100644
index 260f1f0..0000000
--- a/src/main/updateCheck.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { net } from 'electron'
-import type { UpdateInfo } from '../shared/types'
-
-type ReleaseInfo = Omit<UpdateInfo, 'dismissed'>
-
-const REPO = 'anmolkapil/plexo'
-export const UPDATE_PAGE_URL = 'https://getplexo.app/'
-
-function parseVersion(version: string): number[] {
- // ponytail: naive numeric-segment compare, not full semver (a "1.0.0-rc.2" pre-release tag
- // reads as a plain 4th segment) — swap for the `semver` package if pre-release ordering ever
- // needs to be exact.
- return version
- .replace(/^v/, '')
- .split(/[.-]/)
- .map((part) => parseInt(part, 10) || 0)
-}
-
-function isNewer(latest: string, current: string): boolean {
- const a = parseVersion(latest)
- const b = parseVersion(current)
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
- const diff = (a[i] ?? 0) - (b[i] ?? 0)
- if (diff !== 0) return diff > 0
- }
- return false
-}
-
-/** Checks the repo's latest GitHub release against the running app version. Same data source the
- * landing page's downloads list already reads, so there's no separate update feed to stand up.
- *
- * Uses the releases list rather than the `/releases/latest` endpoint: every release here ships
- * as a pre-release, and GitHub's "latest" endpoint only ever considers non-prerelease releases —
- * it 404s when there isn't one, so it would never surface an update. */
-export async function checkForUpdate(currentVersion: string): Promise<ReleaseInfo | null> {
- try {
- const response = await net.fetch(`https://api.github.com/repos/${REPO}/releases?per_page=1`)
- if (!response.ok) return null
- const [data] = (await response.json()) as { tag_name?: string }[]
- if (!data?.tag_name) return null
- const version = data.tag_name.replace(/^v/, '')
- if (!isNewer(version, currentVersion)) return null
- return { version, url: UPDATE_PAGE_URL }
- } catch {
- // Offline, rate-limited, or GitHub is down — silently skip the notification rather than
- // surface a startup error for a non-essential check.
- return null
- }
-}
diff --git a/src/main/updater.ts b/src/main/updater.ts
new file mode 100644
index 0000000..7cc0322
--- /dev/null
+++ b/src/main/updater.ts
@@ -0,0 +1,174 @@
+import {
+ app,
+ dialog,
+ Menu,
+ shell,
+ type BrowserWindow,
+ type MenuItemConstructorOptions
+} from 'electron'
+import { autoUpdater } from 'electron-updater'
+import { IpcChannels } from '../shared/ipc-channels'
+import type { UpdateState } from '../shared/types'
+import { saveSettings } from './settings'
+
+const CHECK_EVERY_MS = 4 * 60 * 60_000
+/** Where an update the app couldn't install itself is downloaded from instead. */
+const DOWNLOAD_PAGE = 'https://getplexo.app/'
+
+let state: UpdateState = { status: 'idle', autoUpdate: true }
+let getWindow: () => BrowserWindow | null = () => null
+/** A check asked for from the menu answers even when there's nothing new. */
+let asked = false
+
+export function updateState(): UpdateState {
+ return state
+}
+
+function set(patch: Partial<UpdateState>): void {
+ const before = state
+ state = { ...state, ...patch }
+ getWindow()?.webContents.send(IpcChannels.updateStateChanged, state)
+ // Progress alone changes no menu item.
+ if (state.status !== before.status || state.autoUpdate !== before.autoUpdate) setAppMenu()
+}
+
+function answer(message: string, detail?: string): void {
+ if (!asked) return
+ asked = false
+ void dialog.showMessageBox({ message, detail })
+}
+
+function check(fromMenu = false): void {
+ const { status } = state
+ // A failed install isn't retried on a timer: on an unsigned Mac it would fail again, after
+ // downloading the whole update again.
+ if (status === 'checking' || status === 'downloading' || status === 'ready') return
+ if (status === 'error' && !fromMenu) return
+ asked = fromMenu
+ // A failure is reported by the 'error' event too. Unpackaged (dev, e2e), this does nothing.
+ autoUpdater.checkForUpdates().catch(() => {})
+}
+
+function download(): void {
+ set({ status: 'downloading', percent: 0 })
+ autoUpdater.downloadUpdate().catch(() => {})
+}
+
+function setAutoUpdate(on: boolean): void {
+ autoUpdater.autoDownload = on
+ set({ autoUpdate: on })
+ saveSettings({ autoUpdate: on }).catch((error) =>
+ console.error('[plexo] failed to save the automatic updates setting', error)
+ )
+ if (on && state.status === 'available') download()
+}
+
+/** The same items in the macOS app menu and in the menu the status bar's update button opens —
+ * Windows and Linux windows show no menu bar, so that button is their only way to these. */
+function menuItems(): MenuItemConstructorOptions[] {
+ const { status, version } = state
+ const items: MenuItemConstructorOptions[] = []
+ if (status === 'ready') {
+ // Silent, and opened again after: the installer's own pages were all answered the first time.
+ items.push({
+ label: `Restart to Update to ${version}`,
+ click: () => autoUpdater.quitAndInstall(true, true)
+ })
+ } else if (status === 'downloading') {
+ items.push({ label: `Downloading ${version}…`, enabled: false })
+ } else if (status === 'available') {
+ items.push({ label: `Download Plexo ${version}`, click: download })
+ } else if (status === 'error') {
+ items.push({
+ label: `Get Plexo ${version} from the Website…`,
+ click: () => void shell.openExternal(DOWNLOAD_PAGE)
+ })
+ }
+ items.push(
+ {
+ label: status === 'checking' ? 'Checking for Updates…' : 'Check for Updates…',
+ enabled: status === 'idle' || status === 'available' || status === 'error',
+ click: () => check(true)
+ },
+ {
+ label: 'Update Automatically',
+ type: 'checkbox',
+ checked: state.autoUpdate,
+ click: (item) => setAutoUpdate(item.checked)
+ }
+ )
+ return items
+}
+
+export function showUpdateMenu(): void {
+ const window = getWindow()
+ if (window) Menu.buildFromTemplate(menuItems()).popup({ window })
+}
+
+/** Electron's default macOS menu, with the update items under the app's name. */
+function setAppMenu(): void {
+ if (process.platform !== 'darwin') return
+ Menu.setApplicationMenu(
+ Menu.buildFromTemplate([
+ {
+ label: app.name,
+ submenu: [
+ { role: 'about' },
+ { type: 'separator' },
+ ...menuItems(),
+ { type: 'separator' },
+ { role: 'services' },
+ { type: 'separator' },
+ { role: 'hide' },
+ { role: 'hideOthers' },
+ { role: 'unhide' },
+ { type: 'separator' },
+ { role: 'quit' }
+ ]
+ },
+ { role: 'fileMenu' },
+ { role: 'editMenu' },
+ { role: 'viewMenu' },
+ { role: 'windowMenu' }
+ ])
+ )
+}
+
+/** Checks GitHub Releases now and every few hours (see electron-builder.yml's publish), for the
+ * release GitHub marks Latest. A downloaded update installs on restart, or on the next quit if
+ * there isn't one. */
+export function startUpdater(window: () => BrowserWindow | null, autoUpdate: boolean): void {
+ getWindow = window
+ state = { ...state, autoUpdate }
+ autoUpdater.autoDownload = autoUpdate
+ // On by default for an rc build, and then it only ever looks for newer rc tags: 1.0.0 would
+ // never reach it. Off, every build follows Latest, whatever its version. A release marked
+ // pre-release on GitHub is never Latest, so it reaches nobody.
+ autoUpdater.allowPrerelease = false
+
+ autoUpdater.on('checking-for-update', () => set({ status: 'checking' }))
+ autoUpdater.on('update-not-available', () => {
+ set({ status: 'idle', version: undefined })
+ answer('You’re up to date', `Plexo ${app.getVersion()} is the newest version.`)
+ })
+ autoUpdater.on('update-available', ({ version }) => {
+ asked = false
+ set({ status: autoUpdater.autoDownload ? 'downloading' : 'available', version, percent: 0 })
+ })
+ autoUpdater.on('download-progress', ({ percent }) => {
+ const whole = Math.floor(percent)
+ if (whole !== state.percent) set({ status: 'downloading', percent: whole })
+ })
+ autoUpdater.on('update-downloaded', ({ version }) => set({ status: 'ready', version }))
+ autoUpdater.on('error', (error) => {
+ console.error('[plexo] update failed', error)
+ // Before an update is found (offline, GitHub down) there's nothing to show. After, the
+ // website still has it — the way an unsigned Mac build, which can't install it, gets it.
+ set({ status: state.version ? 'error' : 'idle' })
+ answer('Couldn’t check for updates', 'Check your connection and try again.')
+ })
+
+ setAppMenu()
+ check()
+ setInterval(check, CHECK_EVERY_MS)
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index c1d6307..e11a3e1 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -5,7 +5,8 @@ import type {
AppSettings,
DownloadUpdate,
InitialState,
- NetworkInterfaceInfo
+ NetworkInterfaceInfo,
+ UpdateState
} from '../shared/types'
/** Typed wrapper around ipcRenderer.invoke — the channel name picks its args/result shape out of
@@ -54,7 +55,8 @@ const plexoApi = {
cancelDownload: (downloadId: string) => invoke('cancelDownload', downloadId),
removeDownload: (downloadId: string, options?: { trashFile?: boolean }) =>
invoke('removeDownload', downloadId, options),
- checkForUpdate: () => invoke('checkForUpdate'),
+ updateState: () => invoke('updateState'),
+ showUpdateMenu: () => invoke('showUpdateMenu'),
pendingLinks: () => invoke('pendingLinks'),
resumeFromLink: (linkId: string, downloadId: string) =>
invoke('resumeFromLink', linkId, downloadId),
@@ -80,6 +82,12 @@ const plexoApi = {
return () => ipcRenderer.removeListener(IpcChannels.historyChanged, listener)
},
+ onUpdateState: (callback: (state: UpdateState) => void): (() => void) => {
+ const listener = (_event: IpcRendererEvent, state: UpdateState): void => callback(state)
+ ipcRenderer.on(IpcChannels.updateStateChanged, listener)
+ return () => ipcRenderer.removeListener(IpcChannels.updateStateChanged, listener)
+ },
+
onNetworksChanged: (callback: (networks: NetworkInterfaceInfo[]) => void): (() => void) => {
const listener = (_event: IpcRendererEvent, networks: NetworkInterfaceInfo[]): void =>
callback(networks)
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 78a7a85..f1d55f2 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -1,11 +1,9 @@
import type { DownloadState, FinishedDownload } from '@shared/types'
-import { useEffect } from 'react'
import { DownloadActionsProvider } from './components/DownloadActionsProvider'
import { NetworkBindingDialog } from './components/NetworkBindingDialog'
import { NewDownloadDialog } from './components/NewDownloadDialog'
import { StatusBar } from './components/StatusBar'
import { TitleBar } from './components/TitleBar'
-import { UpdateDialog } from './components/UpdateDialog'
import { TooltipProvider } from './components/ui/tooltip'
import { useDownloadEvents } from './hooks/useDownloadEvents'
import { useNetworkEvents } from './hooks/useNetworks'
@@ -49,12 +47,6 @@ function App(): React.JSX.Element {
const downloads = useAppStore((store) => store.downloads)
const history = useAppStore((store) => store.history)
const view = useAppStore((store) => store.view)
- const checkForUpdate = useAppStore((store) => store.checkForUpdate)
-
- useEffect(() => {
- checkForUpdate()
- }, [checkForUpdate])
-
// A download that's gone (removed, deleted) leaves the list showing.
const shown =
view.name === 'download'
@@ -72,7 +64,6 @@ function App(): React.JSX.Element {
</div>
<StatusBar />
<NewDownloadDialog />
- <UpdateDialog />
<NetworkBindingDialog />
</div>
</DownloadActionsProvider>
diff --git a/src/renderer/src/components/UpdateDialog.tsx b/src/renderer/src/components/UpdateDialog.tsx
deleted file mode 100644
index dc37303..0000000
--- a/src/renderer/src/components/UpdateDialog.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useRef } from 'react'
-import { DownloadIcon } from 'lucide-react'
-import { useAppStore } from '../store/useAppStore'
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle
-} from './ui/alert-dialog'
-import { buttonVariants } from './ui/button'
-
-export function UpdateDialog(): React.JSX.Element | null {
- const availableUpdate = useAppStore((store) => store.availableUpdate)
- const dismissUpdate = useAppStore((store) => store.dismissUpdate)
- const downloadRef = useRef<HTMLAnchorElement>(null)
-
- if (!availableUpdate) return null
-
- return (
- <AlertDialog
- open={!availableUpdate.dismissed}
- onOpenChange={(open) => {
- if (!open) dismissUpdate()
- }}
- >
- {/* Focus Download, not the first button (Not now), so the primary action is the default. */}
- <AlertDialogContent initialFocus={downloadRef}>
- <AlertDialogHeader>
- <AlertDialogTitle>Plexo {availableUpdate.version} is available</AlertDialogTitle>
- <AlertDialogDescription>A new version is ready to download.</AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Not now</AlertDialogCancel>
- {/* target="_blank" routes through the main process's window-open handler, which hands
- * http(s) links to the OS browser instead of opening a second app window. */}
- <AlertDialogAction
- className={buttonVariants({ size: 'sm' })}
- render={
- <a ref={downloadRef} href={availableUpdate.url} target="_blank" rel="noreferrer" />
- }
- >
- <DownloadIcon /> Download
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- )
-}
diff --git a/src/renderer/src/components/UpdateIndicator.tsx b/src/renderer/src/components/UpdateIndicator.tsx
index 39c6aaf..dd739c3 100644
--- a/src/renderer/src/components/UpdateIndicator.tsx
+++ b/src/renderer/src/components/UpdateIndicator.tsx
@@ -1,32 +1,71 @@
-import { CircleArrowUp } from 'lucide-react'
-import { useAppStore } from '../store/useAppStore'
+import type { UpdateState } from '@shared/types'
+import { cn } from 'cn'
+import { CircleAlert, CircleArrowUp, LoaderCircle } from 'lucide-react'
+import { useEffect, useState } from 'react'
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
-/** Sits next to ThemeToggle once the banner has been dismissed — same size/shape, so it reads as
- * part of the same row of controls rather than a separate alert. */
-export function UpdateIndicator(): React.JSX.Element | null {
- const availableUpdate = useAppStore((store) => store.availableUpdate)
+function describe({ status, version, percent, autoUpdate }: UpdateState): string {
+ switch (status) {
+ case 'checking':
+ return 'Checking for updates…'
+ case 'available':
+ return `Plexo ${version} is available`
+ case 'downloading':
+ return `Downloading Plexo ${version}… ${percent}%`
+ case 'ready':
+ return `Plexo ${version} is ready — restart to update`
+ case 'error':
+ return `Couldn’t install Plexo ${version}`
+ default:
+ return autoUpdate ? 'Plexo updates automatically' : 'Automatic updates are off'
+ }
+}
+
+/** Where the app's own update is, at a glance. Clicking opens the update menu (see
+ * main/updater.ts) — natively, so it's the same menu as the macOS app menu's. */
+export function UpdateIndicator(): React.JSX.Element {
+ const [update, setUpdate] = useState<UpdateState>({ status: 'idle', autoUpdate: true })
+
+ useEffect(() => {
+ const stop = window.plexo.onUpdateState(setUpdate)
+ window.plexo.updateState().then(setUpdate, () => {})
+ return stop
+ }, [])
- if (!availableUpdate?.dismissed) return null
+ const { status, percent } = update
+ const label = describe(update)
+ const text =
+ status === 'downloading'
+ ? `${percent}%`
+ : status === 'ready'
+ ? 'Restart to update'
+ : status === 'available'
+ ? 'Update'
+ : null
+ const busy = status === 'checking' || status === 'downloading'
+ const Icon = busy ? LoaderCircle : status === 'error' ? CircleAlert : CircleArrowUp
return (
<Tooltip>
<TooltipTrigger
render={
- // target="_blank" routes through the main process's window-open handler, which hands
- // http(s) links to the OS browser instead of opening a second app window.
- <a
- href={availableUpdate.url}
- target="_blank"
- rel="noreferrer"
- aria-label={`Update available: ${availableUpdate.version}`}
- className="flex size-[26px] shrink-0 cursor-default items-center justify-center rounded-[6px] border-[0.5px] border-border bg-secondary text-[var(--text-secondary)] [-webkit-app-region:no-drag]"
+ <button
+ type="button"
+ aria-label={label}
+ onClick={() => void window.plexo.showUpdateMenu()}
+ className={cn(
+ 'flex h-[26px] min-w-[26px] shrink-0 cursor-default items-center justify-center gap-1.5 rounded-[6px] border-[0.5px] border-border bg-secondary px-[5px] [-webkit-app-region:no-drag]',
+ status === 'available' || status === 'ready'
+ ? 'text-primary'
+ : 'text-[var(--text-secondary)]'
+ )}
>
- <CircleArrowUp size={15} strokeWidth={1.3} />
- </a>
+ <Icon size={15} strokeWidth={1.3} className={busy ? 'animate-spin' : undefined} />
+ {text && <span className="tabular-nums">{text}</span>}
+ </button>
}
/>
- <TooltipContent>New update available</TooltipContent>
+ <TooltipContent>{label}</TooltipContent>
</Tooltip>
)
}
diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.ts
index 5f29252..f7d3454 100644
--- a/src/renderer/src/store/useAppStore.ts
+++ b/src/renderer/src/store/useAppStore.ts
@@ -10,8 +10,7 @@ import type {
NetworkPreferences,
PendingLink,
SpeedUnit,
- ThemeSource,
- UpdateInfo
+ ThemeSource
} from '@shared/types'
import { create } from 'zustand'
@@ -32,10 +31,6 @@ interface AppStore {
/** Persisted in the main process alongside nativeTheme.themeSource. */
themeSource: ThemeSource
- /** Null until the one-time startup check resolves, or if it found nothing worth showing
- * (already up to date, already dismissed, or the check failed). */
- availableUpdate: UpdateInfo | null
-
homeDir: string
downloadsDir: string
@@ -77,8 +72,6 @@ interface AppStore {
receiveInterfaces: (interfaces: NetworkInterfaceInfo[]) => void
setNetworkPreference: (id: string, patch: NetworkPreference) => void
setThemeSource: (source: ThemeSource) => void
- checkForUpdate: () => Promise<void>
- dismissUpdate: () => void
/** A snapshot or an update of a download, from the main process. */
receiveDownloadUpdate: (update: DownloadUpdate) => void
/** Finished downloads as main lists them; any that finished leave `downloads`. */
@@ -124,7 +117,6 @@ export const useAppStore = create<AppStore>((set, get) => ({
interfacesError: null,
networkPreferences: initial.networkPreferences,
themeSource: initial.themeSource,
- availableUpdate: null,
homeDir: initial.homeDir,
downloadsDir: initial.downloadsDir,
@@ -181,23 +173,6 @@ export const useAppStore = create<AppStore>((set, get) => ({
persist({ themeSource })
},
- checkForUpdate: async () => {
- try {
- const availableUpdate = await window.plexo.checkForUpdate()
- set({ availableUpdate })
- } catch {
- // Best-effort — a failed check just leaves the banner hidden.
- }
- },
-
- dismissUpdate: () => {
- const update = get().availableUpdate
- if (!update) return
- // Keeps the update visible as a quiet titlebar icon rather than clearing it outright.
- set({ availableUpdate: { ...update, dismissed: true } })
- persist({ dismissedUpdateVersion: update.version })
- },
-
receiveDownloadUpdate: (update) => {
const { downloads, history } = get()
// Finished already: an update that arrives late mustn't bring it back.
diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.ts
index 5b3129d..ee38396 100644
--- a/src/shared/ipc-channels.ts
+++ b/src/shared/ipc-channels.ts
@@ -32,5 +32,7 @@ export const IpcChannels = {
pendingLinks: 'app:pending-links',
resumeFromLink: 'app:resume-from-link',
dismissLink: 'app:dismiss-link',
- checkForUpdate: 'update:check'
+ updateState: 'update:state',
+ updateStateChanged: 'update:state-changed',
+ showUpdateMenu: 'update:show-menu'
} as const
diff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.ts
index 5bf7db6..5041be7 100644
--- a/src/shared/ipc-contract.ts
+++ b/src/shared/ipc-contract.ts
@@ -7,11 +7,12 @@ import type {
ProbeResult,
StartDownloadRequest,
TorrentFileEntry,
- UpdateInfo
+ UpdateState
} from './types'
/** The request/response half of the IPC surface (every IpcChannels entry except the
- * main->renderer push events, downloadUpdated, networksChanged, historyChanged and linkReceived) — one source of truth for
+ * main->renderer push events, downloadUpdated, networksChanged, historyChanged, linkReceived and
+ * updateStateChanged) — one source of truth for
* both plexoApi (preload) and registerIpcHandlers (main), so a signature drift between the two
* is a compile error instead of a runtime one. */
export interface IpcContract {
@@ -56,7 +57,9 @@ export interface IpcContract {
/** Removes a download, cancelling one under way. A finished one's file stays, unless
* `trashFile`: then it goes to the Trash. */
removeDownload: { args: [id: string, options?: { trashFile?: boolean }]; result: void }
- checkForUpdate: { args: []; result: UpdateInfo | null }
+ updateState: { args: []; result: UpdateState }
+ /** The update menu, as a native menu at the pointer. */
+ showUpdateMenu: { args: []; result: void }
/** Oldest first: every link not yet started or dismissed. */
pendingLinks: { args: []; result: PendingLink[] }
/** Resumes the failed download a link was matched to, from that link (see relinkDownload). */
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 2dffee1..5f08203 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -310,13 +310,13 @@ export interface NetworkPreference {
export type NetworkPreferences = Record<string, NetworkPreference>
-export interface UpdateInfo {
- version: string
- /** Where clicking the notification should take the user — the landing page's downloads. */
- url: string
- /** True once the user has dismissed the banner for this exact version (persisted, so it stays
- * dismissed across relaunches) — the app then falls back to a quiet titlebar icon instead. */
- dismissed: boolean
+/** Where the app's own update is (see main/updater.ts). `version` is the update's, once one is
+ * found; `percent` only means something while downloading. */
+export interface UpdateState {
+ status: 'idle' | 'checking' | 'available' | 'downloading' | 'ready' | 'error'
+ autoUpdate: boolean
+ version?: string
+ percent?: number
}
/** A repeating window for all transfers, interpreted in the computer's local timezone. */
@@ -336,7 +336,8 @@ export interface DownloadSchedule {
export interface AppSettings {
downloadSchedule?: DownloadSchedule
themeSource?: ThemeSource
- dismissedUpdateVersion?: string
+ /** Only ever saved as false: updates download on their own unless turned off. */
+ autoUpdate?: boolean
/** The last destination folder picked. */
destinationDir?: string
/** User customizations (name/color) per network interface id. */