Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(desktop): auto-update wiring and native update UI (M4b, unsigned) (#193)

Yaowei Zheng740e101fdb8a
diff --git a/.github/workflows/desktop-build.yml b/.github/workflows/desktop-build.yml
index e980ca3e..04f17121 100644
--- a/.github/workflows/desktop-build.yml
+++ b/.github/workflows/desktop-build.yml
@@ -6,19 +6,59 @@
# installers must exist at creation time. workflow_dispatch runs it standalone as a dry
# run on any branch.
#
-# M3 ships unsigned artifacts; macOS signing/notarization, Windows code signing and
-# electron-updater are milestone M4.
+# macOS release artifacts are Developer ID signed and notarized when release.yml calls
+# this workflow with require_macos_signing=true. Standalone dry-runs can still build
+# unsigned artifacts when signing secrets are absent.
name: Desktop packages
on:
workflow_call:
inputs:
+ ref:
+ description: "Git ref to check out; release.yml passes the tag being published."
+ required: false
+ type: string
+ default: ""
tag:
description: Release tag (vX.Y.Z) stamped into the app; empty keeps dev versions.
required: false
type: string
default: ""
- workflow_dispatch: {}
+ require_macos_signing:
+ description: "Sign/notarize macOS artifacts, failing the job if credentials are missing."
+ required: false
+ type: boolean
+ default: false
+ secrets:
+ CSC_LINK:
+ required: false
+ CSC_KEY_PASSWORD:
+ required: false
+ APPLE_API_KEY:
+ required: false
+ APPLE_API_KEY_ID:
+ required: false
+ APPLE_API_ISSUER:
+ required: false
+ APPLE_TEAM_ID:
+ required: false
+ workflow_dispatch:
+ inputs:
+ ref:
+ description: "Optional Git ref to check out."
+ required: false
+ type: string
+ default: ""
+ tag:
+ description: Release tag (vX.Y.Z) stamped into the app; empty keeps dev versions.
+ required: false
+ type: string
+ default: ""
+ require_macos_signing:
+ description: "Sign/notarize macOS artifacts, failing the job if credentials are missing."
+ required: false
+ type: boolean
+ default: false
env:
# Keep in sync with release.yml (its header comment is the source of truth; duplicated
@@ -34,15 +74,23 @@ jobs:
include:
- os: ubuntu-latest
args: --linux
+ environment: desktop-build
- os: macos-latest
args: --mac
+ environment: apple-signing
- os: windows-latest
args: --win
+ environment: desktop-build
runs-on: ${{ matrix.os }}
+ environment:
+ name: ${{ matrix.environment }}
+ deployment: false
permissions:
contents: read
steps:
- uses: actions/checkout@v5
+ with:
+ ref: ${{ inputs.ref || '' }}
# pnpm version comes from package.json's packageManager field.
- uses: pnpm/action-setup@v6
@@ -99,8 +147,211 @@ jobs:
"https://github.com/git-for-windows/git/releases/download/$MINGIT_TAG/$mingit"
unzip -q "$mingit" -d packages/desktop/stage/minigit
+ - name: Prepare macOS signing credentials
+ if: runner.os == 'macOS'
+ shell: bash
+ env:
+ REQUIRE_MACOS_SIGNING: ${{ inputs.require_macos_signing && 'true' || 'false' }}
+ CSC_LINK: ${{ secrets.CSC_LINK }}
+ CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
+ APPLE_API_KEY_BASE64: ${{ secrets.APPLE_API_KEY }}
+ APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
+ APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ run: |
+ if [[ "$REQUIRE_MACOS_SIGNING" != "true" ]]; then
+ echo "macOS signing not required for this dry-run; building unsigned."
+ echo "CSC_IDENTITY_AUTO_DISCOVERY=false" >> "$GITHUB_ENV"
+ exit 0
+ fi
+
+ missing=()
+ [[ -z "${CSC_LINK:-}" ]] && missing+=("CSC_LINK")
+ [[ -z "${CSC_KEY_PASSWORD:-}" ]] && missing+=("CSC_KEY_PASSWORD")
+ [[ -z "${APPLE_API_KEY_BASE64:-}" ]] && missing+=("APPLE_API_KEY")
+ [[ -z "${APPLE_API_KEY_ID:-}" ]] && missing+=("APPLE_API_KEY_ID")
+ [[ -z "${APPLE_API_ISSUER:-}" ]] && missing+=("APPLE_API_ISSUER")
+
+ if ((${#missing[@]})); then
+ printf '::error title=Missing macOS signing secrets::%s\n' "${missing[*]}"
+ exit 1
+ fi
+
+ multiline=()
+ for name in CSC_LINK CSC_KEY_PASSWORD APPLE_API_KEY_BASE64 APPLE_API_KEY_ID APPLE_API_ISSUER APPLE_TEAM_ID; do
+ value="${!name:-}"
+ if [[ "$value" == *$'\n'* || "$value" == *$'\r'* ]]; then
+ multiline+=("$name")
+ fi
+ done
+ if ((${#multiline[@]})); then
+ printf '::error title=Invalid macOS signing secrets::Secrets must be stored as single-line values: %s\n' "${multiline[*]}"
+ exit 1
+ fi
+
+ api_key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
+ printf '%s' "$APPLE_API_KEY_BASE64" | base64 -D > "$api_key_path"
+ chmod 600 "$api_key_path"
+
+ if ! grep -q "BEGIN PRIVATE KEY" "$api_key_path"; then
+ echo "::error title=Invalid APPLE_API_KEY::Decoded App Store Connect key is not a .p8 private key."
+ exit 1
+ fi
+
+ {
+ echo "CSC_LINK=$CSC_LINK"
+ echo "CSC_KEY_PASSWORD=$CSC_KEY_PASSWORD"
+ echo "APPLE_API_KEY=$api_key_path"
+ echo "APPLE_API_KEY_ID=$APPLE_API_KEY_ID"
+ echo "APPLE_API_ISSUER=$APPLE_API_ISSUER"
+ if [[ -n "${APPLE_TEAM_ID:-}" ]]; then
+ echo "APPLE_TEAM_ID=$APPLE_TEAM_ID"
+ fi
+ } >> "$GITHUB_ENV"
+
- name: Build packages
- run: pnpm --dir packages/desktop exec electron-builder ${{ matrix.args }}
+ run: pnpm --dir packages/desktop exec electron-builder ${{ matrix.args }} --publish never ${{ runner.os == 'macOS' && inputs.require_macos_signing && '-c.mac.forceCodeSigning=true' || '' }}
+
+ - name: Notarize and staple macOS DMGs
+ if: runner.os == 'macOS' && inputs.require_macos_signing
+ shell: bash
+ run: |
+ set -euo pipefail
+
+ shopt -s nullglob
+ dmgs=(packages/desktop/stage/out/*.dmg)
+ if ((${#dmgs[@]} == 0)); then
+ echo "::error title=Missing macOS DMG::No DMG files were produced."
+ exit 1
+ fi
+
+ for dmg in "${dmgs[@]}"; do
+ echo "::group::notarize and staple $dmg"
+ echo "started_at=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
+ xcrun notarytool submit "$dmg" \
+ --key "$APPLE_API_KEY" \
+ --key-id "$APPLE_API_KEY_ID" \
+ --issuer "$APPLE_API_ISSUER" \
+ --wait
+ xcrun stapler staple "$dmg"
+ xcrun stapler validate "$dmg"
+ rm -f "$dmg.blockmap"
+ echo "Removed stale $dmg.blockmap because stapling changes the DMG bytes."
+ echo "completed_at=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
+ echo "::endgroup::"
+ done
+
+ - name: Clean macOS update metadata
+ if: runner.os == 'macOS' && inputs.require_macos_signing
+ shell: bash
+ run: |
+ set -euo pipefail
+
+ metadata="packages/desktop/stage/out/latest-mac.yml"
+ if [[ ! -f "$metadata" ]]; then
+ echo "::error title=Missing macOS update metadata::$metadata was not produced."
+ exit 1
+ fi
+
+ node <<'NODE'
+ const fs = require("node:fs");
+
+ const metadata = "packages/desktop/stage/out/latest-mac.yml";
+ const text = fs.readFileSync(metadata, "utf8");
+ const lines = text.split(/\r?\n/);
+ const output = [];
+ let removed = 0;
+ let inFiles = false;
+
+ for (let index = 0; index < lines.length; ) {
+ const line = lines[index];
+
+ if (/^files:\s*$/.test(line)) {
+ inFiles = true;
+ output.push(line);
+ index += 1;
+ continue;
+ }
+
+ if (inFiles && /^\S/.test(line)) {
+ inFiles = false;
+ }
+
+ if (inFiles && /^ - /.test(line)) {
+ const block = [line];
+ index += 1;
+ while (index < lines.length && (/^ /.test(lines[index]) || lines[index] === "")) {
+ block.push(lines[index]);
+ index += 1;
+ }
+
+ if (block.join("\n").includes(".dmg")) {
+ removed += 1;
+ continue;
+ }
+
+ output.push(...block);
+ continue;
+ }
+
+ output.push(line);
+ index += 1;
+ }
+
+ const next = output.join("\n");
+ if (next.includes(".dmg")) {
+ console.error("latest-mac.yml still references .dmg after cleanup.");
+ process.exit(1);
+ }
+ if (!/\.zip\b/.test(next)) {
+ console.error("latest-mac.yml no longer references a zip update artifact.");
+ process.exit(1);
+ }
+
+ fs.writeFileSync(metadata, next, "utf8");
+ console.log(`Removed ${removed} DMG update metadata entr${removed === 1 ? "y" : "ies"} from ${metadata}.`);
+ NODE
+
+ - name: Verify macOS signing and notarization
+ if: runner.os == 'macOS' && inputs.require_macos_signing
+ shell: bash
+ run: |
+ set -euo pipefail
+
+ apps=(
+ packages/desktop/stage/out/mac-arm64/PenguinHarness.app
+ packages/desktop/stage/out/mac/PenguinHarness.app
+ )
+ for app in "${apps[@]}"; do
+ if [[ ! -d "$app" ]]; then
+ echo "::error title=Missing macOS app::$app was not produced."
+ exit 1
+ fi
+
+ echo "::group::verify app $app"
+ echo "started_at=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
+ codesign --verify --deep --strict --verbose=4 "$app"
+ codesign -dv --verbose=4 "$app"
+ xcrun stapler validate "$app"
+ spctl --assess --type execute --verbose=4 "$app"
+ echo "completed_at=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
+ echo "::endgroup::"
+ done
+
+ shopt -s nullglob
+ dmgs=(packages/desktop/stage/out/*.dmg)
+ if ((${#dmgs[@]} == 0)); then
+ echo "::error title=Missing macOS DMG::No DMG files were produced."
+ exit 1
+ fi
+
+ for dmg in "${dmgs[@]}"; do
+ echo "::group::verify dmg $dmg"
+ echo "started_at=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
+ xcrun stapler validate "$dmg"
+ echo "completed_at=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
+ echo "::endgroup::"
+ done
- name: Upload artifacts
uses: actions/upload-artifact@v4
@@ -113,3 +364,8 @@ jobs:
packages/desktop/stage/out/penguin-desktop-*.dmg
packages/desktop/stage/out/penguin-desktop-*.zip
packages/desktop/stage/out/penguin-desktop-*.exe
+ # Update metadata: electron-updater reads latest*.yml from the Release, and
+ # the blockmaps are what make differential downloads possible. Without these
+ # the installers ship but nothing can auto-update.
+ packages/desktop/stage/out/*.yml
+ packages/desktop/stage/out/*.blockmap
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 47ba2900..7938507c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -85,7 +85,9 @@ jobs:
if: needs.check-release.outputs.exists != 'true'
uses: ./.github/workflows/desktop-build.yml
with:
+ ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
tag: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
+ require_macos_signing: true
release:
needs: [check-release, desktop]
diff --git a/packages/desktop/build/entitlements.mac.inherit.plist b/packages/desktop/build/entitlements.mac.inherit.plist
new file mode 100644
index 00000000..9a279dc8
--- /dev/null
+++ b/packages/desktop/build/entitlements.mac.inherit.plist
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+ <dict>
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+ <key>com.apple.security.cs.disable-library-validation</key>
+ <true/>
+ </dict>
+</plist>
diff --git a/packages/desktop/build/entitlements.mac.plist b/packages/desktop/build/entitlements.mac.plist
new file mode 100644
index 00000000..9a279dc8
--- /dev/null
+++ b/packages/desktop/build/entitlements.mac.plist
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+ <dict>
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+ <key>com.apple.security.cs.disable-library-validation</key>
+ <true/>
+ </dict>
+</plist>
diff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.yml
index 6269f46e..ba3840e6 100644
--- a/packages/desktop/electron-builder.yml
+++ b/packages/desktop/electron-builder.yml
@@ -9,10 +9,18 @@
# files sidestep every asar edge (fork-from-archive, unpacked-tree resolution splits)
# at the cost of some inodes.
#
-# M3 ships unsigned artifacts: macOS signing/notarization and Windows code signing are
-# milestone M4, together with electron-updater.
+# macOS release artifacts are Developer ID signed and notarized in CI when the signing
+# secrets are present; unsigned dry-run builds remain possible outside the release path.
appId: com.prismshadow.penguinharness
productName: PenguinHarness
+# Declaring the publish target is what makes electron-builder emit the update metadata
+# (latest.yml / latest-mac.yml / latest-linux.yml and the .blockmap files) next to the
+# installers; nothing is uploaded from here — the release workflow attaches the artifacts
+# it collected. electron-updater reads the same metadata from the Release.
+publish:
+ provider: github
+ owner: Prism-Shadow
+ repo: penguin-harness
directories:
app: stage/app
output: stage/out
@@ -28,8 +36,10 @@ mac:
# scripts/render-icon.mjs, committed): electron-builder converts the 1024px PNG to
# icns itself (app-builder-lib iconConverter; >=512px required).
icon: build/icon.png
- # No Developer ID yet (M4): identity null skips codesign instead of failing.
- identity: null
+ hardenedRuntime: true
+ entitlements: build/entitlements.mac.plist
+ entitlementsInherit: build/entitlements.mac.inherit.plist
+ notarize: true
# Version-less artifact names, following the CLI bundles (penguin-darwin-arm64.tar.gz):
# the version lives in the Release tag and SHA256SUMS.desktop, so the download page and
# the OSS mirror manifest can address every installer by a stable name — and GitHub's
diff --git a/packages/desktop/package.json b/packages/desktop/package.json
index 827aeada..04dbd702 100644
--- a/packages/desktop/package.json
+++ b/packages/desktop/package.json
@@ -19,7 +19,8 @@
"dependencies": {
"@prismshadow/penguin-cli": "workspace:*",
"@prismshadow/penguin-core": "workspace:*",
- "@prismshadow/penguin-server": "workspace:*"
+ "@prismshadow/penguin-server": "workspace:*",
+ "electron-updater": "^6.8.9"
},
"devDependencies": {
"@types/node": "^24.0.0",
diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts
index 50121de2..9d3b25d1 100644
--- a/packages/desktop/src/main.ts
+++ b/packages/desktop/src/main.ts
@@ -24,6 +24,7 @@ import { installCliCommand, maybeOfferCliInstall, currentCliInstallKind } from "
import { installAppMenu } from "./menu.js";
import { startEmbeddedServer, stopEmbeddedServer } from "./server-process.js";
import type { EmbeddedServer } from "./server-process.js";
+import { initUpdater } from "./updater.js";
import {
desktopLoginUrl,
isAppUrl,
@@ -216,12 +217,12 @@ if (!app.requestSingleInstanceLock()) {
void app.whenReady().then(() =>
(async () => {
- // Standard menu plus the CLI-install entry where installing makes sense
- // (packaged macOS / Windows / AppImage; deb ships /usr/bin/penguin itself).
+ // Standard menu plus native desktop-only actions; the window gets no IPC channel.
installAppMenu({
includeCliInstall: currentCliInstallKind() !== null,
onInstallCli: () => void installCliCommand(win),
});
+ initUpdater(() => win);
await boot();
// First launch only: offer the 'penguin' command once; the menu entry remains.
// Skipped in smoke mode — a modal dialog would hang the automated run.
diff --git a/packages/desktop/src/menu.ts b/packages/desktop/src/menu.ts
index aa0d2a68..d60b5ac2 100644
--- a/packages/desktop/src/menu.ts
+++ b/packages/desktop/src/menu.ts
@@ -1,16 +1,17 @@
/**
* Application menu. Electron's default menu cannot be extended, only replaced, so the
- * standard structure is rebuilt here — on macOS the Edit roles are what make clipboard
- * shortcuts work inside the window, so they must be present. The one custom entry is
- * "Install 'penguin' Command…" (see cli-install.ts), shown only where installing makes
- * sense (packaged macOS / Windows / AppImage; deb ships /usr/bin/penguin itself).
- * On Windows/Linux the window uses autoHideMenuBar, so the bar appears on Alt.
+ * standard structure is rebuilt here. The custom entries are native-only shell actions:
+ * installing the bundled `penguin` command and checking for desktop updates.
*/
-import { app, Menu } from "electron";
+import { app, Menu, shell } from "electron";
import type { MenuItemConstructorOptions } from "electron";
+import { checkForUpdatesManually, updatesAvailableInThisForm } from "./updater.js";
export const INSTALL_CLI_MENU_LABEL = "Install 'penguin' Command…";
+const CHECK_FOR_UPDATES_MENU_LABEL = "Check for Updates…";
+const REPO_URL = "https://github.com/Prism-Shadow/penguin-harness";
+
export function installAppMenu(opts: {
includeCliInstall: boolean;
onInstallCli: () => void;
@@ -19,6 +20,15 @@ export function installAppMenu(opts: {
const cliItems: MenuItemConstructorOptions[] = opts.includeCliInstall
? [{ label: INSTALL_CLI_MENU_LABEL, click: opts.onInstallCli }]
: [];
+ const checkForUpdates: MenuItemConstructorOptions = {
+ label: CHECK_FOR_UPDATES_MENU_LABEL,
+ enabled: updatesAvailableInThisForm(),
+ click: () => void checkForUpdatesManually(),
+ };
+ const projectOnGitHub: MenuItemConstructorOptions = {
+ label: "Project on GitHub",
+ click: () => void shell.openExternal(REPO_URL),
+ };
const template: MenuItemConstructorOptions[] = [];
if (isMac) {
@@ -26,9 +36,10 @@ export function installAppMenu(opts: {
label: app.name,
submenu: [
{ role: "about" },
- ...(cliItems.length > 0
- ? ([{ type: "separator" }, ...cliItems] as MenuItemConstructorOptions[])
- : []),
+ { type: "separator" },
+ ...cliItems,
+ ...(cliItems.length > 0 ? ([{ type: "separator" }] as MenuItemConstructorOptions[]) : []),
+ checkForUpdates,
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
@@ -49,6 +60,17 @@ export function installAppMenu(opts: {
],
});
}
- template.push({ role: "editMenu" }, { role: "viewMenu" }, { role: "windowMenu" });
+ template.push(
+ { role: "editMenu" },
+ { role: "viewMenu" },
+ { role: "windowMenu" },
+ {
+ role: "help",
+ submenu: [
+ ...(isMac ? [] : [checkForUpdates, { type: "separator" } as MenuItemConstructorOptions]),
+ projectOnGitHub,
+ ],
+ },
+ );
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
diff --git a/packages/desktop/src/update-support.ts b/packages/desktop/src/update-support.ts
new file mode 100644
index 00000000..8b9a17e4
--- /dev/null
+++ b/packages/desktop/src/update-support.ts
@@ -0,0 +1,44 @@
+/**
+ * Whether this running form can update itself (pure; no Electron import, so it unit-tests
+ * directly). See design § "桌面端原型 · 自动更新".
+ *
+ * electron-updater can only replace the forms it installed: the NSIS installer on
+ * Windows, the app bundle on macOS, and an AppImage on Linux. A `.deb` belongs to the
+ * system package manager — silently "updating" around dpkg would leave the two disagreeing
+ * about what is installed — and a dev run has no installed artifact at all.
+ */
+export type UpdateSupport =
+ { supported: true } | { supported: false; reason: "dev" | "linux-not-appimage" };
+
+export function updateSupport(opts: {
+ isPackaged: boolean;
+ platform: NodeJS.Platform;
+ env: NodeJS.ProcessEnv;
+}): UpdateSupport {
+ if (!opts.isPackaged) return { supported: false, reason: "dev" };
+ // The AppImage runtime exports APPIMAGE with the path of the running image; a deb
+ // install (or an extracted tree) has no such variable, and that is exactly the
+ // distinction electron-updater's Linux path depends on.
+ if (opts.platform === "linux" && !opts.env.APPIMAGE) {
+ return { supported: false, reason: "linux-not-appimage" };
+ }
+ return { supported: true };
+}
+
+/**
+ * Optional feed override (`PENGUIN_UPDATE_FEED_URL`), the seed of the documented
+ * auto | oss | github source switch and what makes an end-to-end update test possible
+ * against a local server. Returns null when unset or unparseable — an unusable override
+ * must not silently redirect updates, so the caller keeps the default GitHub feed.
+ */
+export function feedUrlOverride(env: NodeJS.ProcessEnv): string | null {
+ const raw = env.PENGUIN_UPDATE_FEED_URL?.trim();
+ if (!raw) return null;
+ try {
+ const url = new URL(raw);
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
+ return url.toString();
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/desktop/src/updater.ts b/packages/desktop/src/updater.ts
new file mode 100644
index 00000000..08cbe3cc
--- /dev/null
+++ b/packages/desktop/src/updater.ts
@@ -0,0 +1,183 @@
+/**
+ * Auto-update (design § "桌面端原型 · 自动更新").
+ *
+ * electron-updater against the GitHub Releases feed the build publishes
+ * (`latest*.yml` + `.blockmap` ship as Release assets). The shell deliberately exposes
+ * updates through **native UI only** — an app-menu item plus dialogs — because it injects
+ * no IPC channel into the page; the Web App keeps hiding its own self-update entry in
+ * desktop mode.
+ *
+ * Automatic checks are quiet: they run on a timer, download in the background, and speak
+ * up only when a build is ready to install. A manual check reports every outcome (already
+ * up to date / downloading / failed), the same rule the Web App's check-for-updates row
+ * follows — a manual action that answers with silence reads as broken.
+ *
+ * Release builds use Developer ID signing on macOS; unsigned dry-run macOS artifacts can
+ * still find updates, but Gatekeeper will not apply them as trusted replacements.
+ * Windows NSIS and Linux AppImage continue to work without code-signing for now.
+ */
+import { app, dialog, shell } from "electron";
+import type { BrowserWindow } from "electron";
+import electronUpdater from "electron-updater";
+import { feedUrlOverride, updateSupport } from "./update-support.js";
+
+const { autoUpdater } = electronUpdater;
+
+/** First check runs after this delay: booting the server and the window comes first. */
+const FIRST_CHECK_DELAY_MS = 20_000;
+/** Subsequent automatic checks. */
+const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
+
+const RELEASES_URL = "https://github.com/Prism-Shadow/penguin-harness/releases";
+
+function log(line: string): void {
+ process.stdout.write(`[updater] ${line}\n`);
+}
+
+let manualCheckInFlight = false;
+let downloadedVersion: string | null = null;
+
+/** Whether the "Check for Updates…" menu item should be enabled at all. */
+export function updatesAvailableInThisForm(): boolean {
+ return updateSupport({ isPackaged: app.isPackaged, platform: process.platform, env: process.env })
+ .supported;
+}
+
+/**
+ * Wires the updater and starts the automatic schedule. Safe to call in any form: an
+ * unsupported one (dev run, deb install) only logs why it is standing down.
+ */
+export function initUpdater(getWindow: () => BrowserWindow | null): void {
+ const support = updateSupport({
+ isPackaged: app.isPackaged,
+ platform: process.platform,
+ env: process.env,
+ });
+ if (!support.supported) {
+ log(`disabled (${support.reason})`);
+ return;
+ }
+
+ // Background downloads, explicit install: the user decides when to restart. Quitting
+ // normally must NOT swap the app underneath a running server, so install happens only
+ // through the dialog's own path.
+ autoUpdater.autoDownload = true;
+ autoUpdater.autoInstallOnAppQuit = false;
+ autoUpdater.logger = null;
+
+ const override = feedUrlOverride(process.env);
+ if (override) {
+ // Generic provider: also the shape the documented auto | oss | github source switch
+ // will use for the OSS mirror.
+ autoUpdater.setFeedURL({ provider: "generic", url: override });
+ log(`feed override: ${override}`);
+ }
+
+ autoUpdater.on("checking-for-update", () => log("checking"));
+ autoUpdater.on("update-not-available", (info: { version: string }) => {
+ log(`up to date (${info.version})`);
+ if (manualCheckInFlight) {
+ manualCheckInFlight = false;
+ void dialog.showMessageBox({
+ type: "info",
+ message: "PenguinHarness is up to date.",
+ detail: `Version ${app.getVersion()} is the latest release.`,
+ buttons: ["OK"],
+ });
+ }
+ });
+ autoUpdater.on("update-available", (info: { version: string }) => {
+ log(`update available: ${info.version} (downloading)`);
+ if (manualCheckInFlight) {
+ manualCheckInFlight = false;
+ void dialog.showMessageBox({
+ type: "info",
+ message: `Version ${info.version} is available.`,
+ detail:
+ "It is downloading in the background; you will be asked to restart when it is ready.",
+ buttons: ["OK"],
+ });
+ }
+ });
+ autoUpdater.on("download-progress", (p: { percent: number }) => {
+ log(`downloading ${Math.round(p.percent)}%`);
+ });
+ autoUpdater.on("update-downloaded", (info: { version: string }) => {
+ downloadedVersion = info.version;
+ log(`downloaded: ${info.version}`);
+ void promptRestart(info.version, getWindow());
+ });
+ autoUpdater.on("error", (err: Error) => {
+ log(`error: ${err.message}`);
+ if (manualCheckInFlight) {
+ manualCheckInFlight = false;
+ void dialog
+ .showMessageBox({
+ type: "error",
+ message: "Could not check for updates.",
+ detail: `${err.message}\n\nYou can always download the latest release manually.`,
+ buttons: ["Open Releases", "OK"],
+ defaultId: 1,
+ cancelId: 1,
+ })
+ .then((r) => {
+ if (r.response === 0) void shell.openExternal(RELEASES_URL);
+ });
+ }
+ });
+
+ setTimeout(() => void check(), FIRST_CHECK_DELAY_MS).unref();
+ setInterval(() => void check(), CHECK_INTERVAL_MS).unref();
+}
+
+async function check(): Promise<void> {
+ try {
+ await autoUpdater.checkForUpdates();
+ } catch (err) {
+ // The error event already reported it; this catch only keeps the rejection from
+ // reaching the process-level handler.
+ log(`check failed: ${(err as Error).message}`);
+ }
+}
+
+/** Menu action: same check, but every outcome is reported. */
+export async function checkForUpdatesManually(): Promise<void> {
+ if (!updatesAvailableInThisForm()) {
+ const support = updateSupport({
+ isPackaged: app.isPackaged,
+ platform: process.platform,
+ env: process.env,
+ });
+ const detail =
+ support.supported || support.reason === "dev"
+ ? "This build does not update itself."
+ : "This copy was installed from a system package; update it with your package manager.";
+ await dialog.showMessageBox({ type: "info", message: "Updates are unavailable.", detail });
+ return;
+ }
+ if (downloadedVersion !== null) {
+ await promptRestart(downloadedVersion, null);
+ return;
+ }
+ manualCheckInFlight = true;
+ await check();
+}
+
+/** "Ready to install" prompt; restarting is the only path that swaps the app. */
+async function promptRestart(version: string, parent: BrowserWindow | null): Promise<void> {
+ const options = {
+ type: "info" as const,
+ message: `Version ${version} is ready to install.`,
+ detail: "PenguinHarness will restart to finish updating. Running tasks will be interrupted.",
+ buttons: ["Restart now", "Later"],
+ defaultId: 0,
+ cancelId: 1,
+ };
+ const result = parent
+ ? await dialog.showMessageBox(parent, options)
+ : await dialog.showMessageBox(options);
+ if (result.response !== 0) return;
+ // quitAndInstall triggers the normal quit path first, so the shell's before-quit hook
+ // still stops the embedded server gracefully before the files are replaced.
+ autoUpdater.quitAndInstall();
+}
diff --git a/packages/desktop/test/update-support.test.ts b/packages/desktop/test/update-support.test.ts
new file mode 100644
index 00000000..c101794b
--- /dev/null
+++ b/packages/desktop/test/update-support.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import { feedUrlOverride, updateSupport } from "../src/update-support.js";
+
+describe("updateSupport", () => {
+ it("supports packaged macOS and Windows builds", () => {
+ for (const platform of ["darwin", "win32"] as const) {
+ expect(updateSupport({ isPackaged: true, platform, env: {} })).toEqual({ supported: true });
+ }
+ });
+
+ it("supports Linux only when running as an AppImage", () => {
+ const env = { APPIMAGE: "/opt/PenguinHarness.AppImage" };
+ expect(updateSupport({ isPackaged: true, platform: "linux", env })).toEqual({
+ supported: true,
+ });
+ // A deb install has no APPIMAGE: updating around dpkg would desync the two.
+ expect(updateSupport({ isPackaged: true, platform: "linux", env: {} })).toEqual({
+ supported: false,
+ reason: "linux-not-appimage",
+ });
+ });
+
+ it("never updates a dev run, whatever the platform", () => {
+ expect(
+ updateSupport({ isPackaged: false, platform: "darwin", env: { APPIMAGE: "/x" } }),
+ ).toEqual({ supported: false, reason: "dev" });
+ });
+});
+
+describe("feedUrlOverride", () => {
+ it("accepts http(s) URLs and normalizes them", () => {
+ expect(feedUrlOverride({ PENGUIN_UPDATE_FEED_URL: "http://127.0.0.1:8080/feed" })).toBe(
+ "http://127.0.0.1:8080/feed",
+ );
+ expect(feedUrlOverride({ PENGUIN_UPDATE_FEED_URL: " https://example.com/u " })).toBe(
+ "https://example.com/u",
+ );
+ });
+
+ it("ignores unset, blank, non-http and unparseable values", () => {
+ expect(feedUrlOverride({})).toBeNull();
+ expect(feedUrlOverride({ PENGUIN_UPDATE_FEED_URL: " " })).toBeNull();
+ expect(feedUrlOverride({ PENGUIN_UPDATE_FEED_URL: "file:///etc/passwd" })).toBeNull();
+ expect(feedUrlOverride({ PENGUIN_UPDATE_FEED_URL: "not a url" })).toBeNull();
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d351a4ff..63f0c15f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -123,6 +123,9 @@ importers:
'@prismshadow/penguin-server':
specifier: workspace:*
version: link:../server
+ electron-updater:
+ specifier: ^6.8.9
+ version: 6.8.9([email protected])
devDependencies:
'@types/node':
specifier: ^24.0.0
@@ -1899,6 +1902,9 @@ packages:
resolution: {integrity: sha512-TaxwufTFDufvPEoXdhwVrA3UdFWBeWGkYoJ1K8ldF1xe6gKfth6iRNS5lTQ5JPNOHdGQm8PT1QYKUqFLCiUefQ==}
+ resolution: {integrity: sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==}
+
resolution: {integrity: sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==}
engines: {node: '>=8.0.0'}
@@ -2452,6 +2458,13 @@ packages:
resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+ resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}
+
+ resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}
+ deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.
+
resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
@@ -3272,6 +3285,9 @@ packages:
resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}
+ resolution: {integrity: sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==}
+
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
@@ -5442,6 +5458,19 @@ snapshots:
+ dependencies:
+ builder-util-runtime: 9.7.0([email protected])
+ fs-extra: 10.1.0
+ js-yaml: 4.3.1
+ lazy-val: 1.0.5
+ lodash.escaperegexp: 4.1.2
+ lodash.isequal: 4.5.0
+ semver: 7.7.4
+ tiny-typed-emitter: 2.1.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@electron/asar': 3.4.1
@@ -6110,6 +6139,10 @@ snapshots:
+
+
@@ -7194,6 +7227,8 @@ snapshots:
dependencies:
semver: 5.7.2
+