Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): single-flight the macOS install handoff (PRD-7640) (#3970)
Andrew Mikofalvyfbb4ab93b4c6
diff --git a/.changeset/olive-pugs-shave.md b/.changeset/olive-pugs-shave.mdnew file mode 100644index 000000000..261549e96--- /dev/null+++ b/.changeset/olive-pugs-shave.md@@ -0,0 +1,12 @@+---+'@inkeep/open-knowledge-desktop': patch+'@inkeep/open-knowledge': patch+---++Fixed a macOS auto-update failure that could leave OpenKnowledge missing from your Applications folder, and a "Check for Updates" dialog that named a version it was not going to install.++The app arms an update at download time and installs it when you quit. Underneath, Squirrel arms it by launching ShipIt, which then waits — with no timeout of its own — for the app to exit. Downloading a newer build did not replace that pending request, it armed a second ShipIt beside the first; both then woke in the same instant at quit and raced the same bundle swap. The loser moved aside the bundle the winner had just installed, and when it could not put it back the app was left missing from `/Applications` until a later restore.++On macOS a build already staged in this session is now installed as-is: newer offers are declined until the next session, including the freshness check on the "Relaunch now" click, and a manual check for updates says the staged build is ready rather than advertising the one it declined. Windows and Linux keep taking newer builds mid-session, because neither leaves a second installer armed: Windows runs whichever installer was downloaded last, and Linux arms nothing until you click relaunch.++Bug reports also collect the numeric-suffixed ShipIt logs (`ShipIt_stderr.log.1`, `.2`, …). Squirrel falls back to those when the base log is not writable, which is what happens once the log is owned by root — precisely the machines where a failing install is worth diagnosing.diff --git a/packages/cli/src/commands/bug-report-bundle.test.ts b/packages/cli/src/commands/bug-report-bundle.test.tsindex aeba5250d..c46645338 100644--- a/packages/cli/src/commands/bug-report-bundle.test.ts+++ b/packages/cli/src/commands/bug-report-bundle.test.ts@@ -514,6 +514,63 @@ describe('collectShipItLogFiles — Squirrel.Mac install logs', () => {expect(collectShipItLogFiles(join(makeTmpDir(), 'absent'))).toEqual([]);});+ // Squirrel opens both logs with `ensureWritable`: when the existing file is+ // not writable it appends `.1`, `.2`, … (up to `.100`) and writes THERE+ // instead. Its own source names the cause — the log can end up owned by root,+ // which previously stopped ShipIt launching at all — so the suffixed file is+ // exactly what a machine whose installs run privileged writes to. Collecting+ // only the two base names silently harvests the stale, un-writable original+ // and misses every line of the run being reported.+ test('collects the numeric-suffixed logs Squirrel falls back to', () => {+ const cachesDir = makeTmpDir();+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipIt_stderr.log`, 'stale root-owned\n');+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipIt_stderr.log.1`, 'the live run\n');+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipIt_stdout.log.2`, 'stdout fallback\n');++ const names = collectShipItLogFiles(cachesDir)+ .map((f) => basename(f))+ .sort();++ expect(names).toEqual(['ShipIt_stderr.log', 'ShipIt_stderr.log.1', 'ShipIt_stdout.log.2']);+ });++ // The suffix is the only thing separating a fallback log from an unrelated+ // neighbour, so the match is anchored rather than a prefix test. `.plist` is+ // the binary state file the collector deliberately omits, and `.bak` stands+ // for anything a user or another tool parked in the directory.+ test('ignores neighbours that merely start with a ShipIt log name', () => {+ const cachesDir = makeTmpDir();+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipIt_stderr.log.1`, 'ours\n');+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipIt_stderr.log.bak`, 'theirs\n');+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipItState.plist`, 'theirs\n');+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipIt_stderr.logging`, 'theirs\n');++ const bodies = collectShipItLogFiles(cachesDir).map((f) => readFileSync(f, 'utf8'));++ expect(bodies).toEqual(['ours\n']);+ });++ // Squirrel will walk to `.100`, and each file can be megabytes. A bundle must+ // not scale with how long a machine has been failing to install, so the+ // fallbacks are capped — lowest suffix first, because Squirrel takes the+ // FIRST writable candidate, making the low numbers the live ones.+ test('bounds how many fallback logs one stream contributes', () => {+ const cachesDir = makeTmpDir();+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipIt_stderr.log`, 'base\n');+ for (let i = 1; i <= 12; i++) {+ writeAt(cachesDir, `${DESKTOP_BUNDLE_ID}.ShipIt/ShipIt_stderr.log.${i}`, `n${i}\n`);+ }++ const names = collectShipItLogFiles(cachesDir).map((f) => basename(f));++ expect(names).toEqual([+ 'ShipIt_stderr.log',+ 'ShipIt_stderr.log.1',+ 'ShipIt_stderr.log.2',+ 'ShipIt_stderr.log.3',+ ]);+ });+// The collector existing is not the deliverable — reaching the zip is. This// is the assertion a triager's experience actually depends on.test('stages the ShipIt log into the bundle under logs/', async () => {diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.tsindex 3ffd6ecbc..3e0b85cbb 100644--- a/packages/cli/src/commands/bug-report-bundle.ts+++ b/packages/cli/src/commands/bug-report-bundle.ts@@ -259,12 +259,38 @@ export function collectUserLogFiles(projectSlug: string | null, logsDir: string)export { DESKTOP_BUNDLE_ID };/**- * The two text logs Squirrel.Mac's ShipIt writes into its per-bundle cache- * dir. `ShipItState.plist` sits beside them but is a binary plist — staging it- * through the text scrub would garble it, and the swap narrative lives in- * stderr regardless.+ * The two text log STREAMS Squirrel.Mac's ShipIt writes into its per-bundle+ * cache dir. `ShipItState.plist` sits beside them but is a binary plist —+ * staging it through the text scrub would garble it, and the swap narrative+ * lives in stderr regardless.+ *+ * These are stream names rather than filenames because ShipIt opens each one+ * with `ensureWritable`: when the existing file cannot be opened for writing it+ * appends `.1`, `.2`, … (walking as far as `.100`) and writes to that instead.+ * Squirrel's own source attributes the un-writable case to the log ending up+ * owned by root, which is exactly the state a machine whose installs escalate+ * gets into — so on the machines most worth collecting from, the base name+ * holds a stale log and the live run is in a suffixed sibling.+ */+const SHIPIT_LOG_STREAMS = ['ShipIt_stderr.log', 'ShipIt_stdout.log'] as const;++/**+ * How many files one stream may contribute, in suffix order.+ *+ * Spent on siblings when the base file is absent, which is what you want: once+ * the log is root-owned the base holds a stale run and every live one sits in a+ * sibling, so a missing base should not shrink what gets collected.+ *+ * Squirrel walks to `.100` and each file can reach megabytes, so an uncapped+ * collector would scale the bundle with how long a machine has been failing to+ * install. Lowest suffix first: Squirrel takes the FIRST candidate it can open,+ * so the low numbers are the ones still being written.+ *+ * Capped on file COUNT, not bytes — the bundle's overall size guard is what+ * bounds total volume, and splitting that budget per-source here would make one+ * noisy stream silently evict another.*/-const SHIPIT_LOG_FILES = ['ShipIt_stderr.log', 'ShipIt_stdout.log'] as const;+const SHIPIT_LOG_FILES_PER_STREAM = 4;/*** Squirrel.Mac's own install logs (`~/Library/Caches/<bundleId>.ShipIt/`).@@ -291,7 +317,36 @@ export function collectShipItLogFiles(): string[] {const shipItDir = join(cachesDir, `${bundleId}.ShipIt`);if (!existsSync(shipItDir)) return [];- return SHIPIT_LOG_FILES.map((name) => join(shipItDir, name)).filter((p) => existsSync(p));++ let entries: string[];+ try {+ entries = readdirSync(shipItDir);+ } catch {+ // Same empty result as the missing-directory case above, and deliberately+ // indistinguishable from it downstream: the realistic reason a ShipIt dir+ // exists but cannot be read is the root ownership this whole collector is+ // built around, and there is nothing a bug reporter could do about it. The+ // absence shows up where it is actionable — the bundle simply carries no+ // ShipIt logs, which the reader can see.+ return [];+ }++ return SHIPIT_LOG_STREAMS.flatMap((stream) =>+ entries+ .map((entry) => {+ // Sorted as a number, so the base file leads and `.2` precedes `.10`.+ if (entry === stream) return { entry, suffix: -1 };+ if (!entry.startsWith(`${stream}.`)) return null;+ // Anchored on digits alone: the suffix is the only thing distinguishing+ // a fallback from a neighbour that merely shares the prefix.+ const suffix = entry.slice(stream.length + 1);+ return /^\d+$/.test(suffix) ? { entry, suffix: Number(suffix) } : null;+ })+ .filter((match) => match !== null)+ .sort((a, b) => a.suffix - b.suffix)+ .slice(0, SHIPIT_LOG_FILES_PER_STREAM)+ .map((match) => join(shipItDir, match.entry)),+ );}/**diff --git a/packages/desktop/src/main/auto-updater.ts b/packages/desktop/src/main/auto-updater.tsindex 219983dc0..53c069f19 100644--- a/packages/desktop/src/main/auto-updater.ts+++ b/packages/desktop/src/main/auto-updater.ts@@ -154,6 +154,7 @@ export type DispatchKind =| 'linux-manual-fallback-no-auth'| 'linux-manual-fallback-after-error'| 'download-skipped-already-staged'+ | 'download-skipped-install-armed'| 'relaunch-refresh-found-newer'| 'relaunch-refresh-up-to-date'| 'relaunch-refresh-timed-out'@@ -239,15 +240,24 @@ interface StartAutoUpdaterOpts {* Synchronous teardown hook fired immediately before* `autoUpdater.quitAndInstall()` from the `ok:update:relaunch-now`* IPC handler. Production wires this to a hard SIGKILL of every- * project-window utility process. Squirrel.Mac's ShipIt runs a final- * not-still-running validation and aborts the swap with- * `SQRLInstallerErrorDomain Code=-9 "App Still Running Error"` if- * it still sees the app running when the swap window opens — the- * standard `app.quit()` path posts a graceful `{type:'shutdown'}`- * to each utility, but Hocuspocus / file-watcher cleanup can take- * longer than ShipIt's poll budget, leaving the swap silently- * cancelled. SIGKILLing the utilities first guarantees a clean- * process tree before ShipIt looks. Optional so unit tests don't+ * project-window utility process.+ *+ * What this buys is server lifetime, not ShipIt's pre-swap validation. A+ * detached server survives app-quit by design, and one that outlives the+ * swap is re-attached by the relaunched app, which then reads an older+ * version off `server.lock` and shows the version-drift toast. The graceful+ * `{type:'shutdown'}` window-close IPC is not fast enough on its own —+ * Hocuspocus drain plus file-watcher teardown can outlast the swap window.+ *+ * ShipIt's `SQRLInstallerErrorAppStillRunning` abort is NOT the reason, and+ * restating it here would be wrong: `SQRLInstaller.m` enumerates+ * `NSRunningApplication runningApplicationsWithBundleIdentifier:` and keeps+ * only entries whose `bundleURL` standardizes to the target `.app`, so a+ * `utilityProcess` fork (not an application at all) and the detached server+ * (a distinct helper bundle under `Contents/Frameworks/`) are both filtered+ * out. Only a second GUI instance of the installed bundle can trip it.+ *+ * Optional so unit tests don't* have to provide one — production passes* `async () => await windowManager.stopAllOwnedServers()`. May be* async — the hook is awaited before `quitAndInstall` so a two-phase@@ -341,6 +351,16 @@ interface StartAutoUpdaterOpts {*/type CheckNowResult =| { kind: 'available'; currentVersion: string; latestVersion: string }+ /**+ * A build is already staged and waiting, so the offer this check turned up+ * was declined rather than fetched — whether it was the staged version+ * re-offered or a newer one the single-flight guard turned down.+ * `stagedVersion` is what a relaunch will actually install, which in the+ * newer-offer case is NOT the version just offered: reporting the offer there+ * would promise a build this session has decided not to fetch, and reporting+ * either as "downloading" would describe a download that is not running.+ */+ | { kind: 'ready-to-install'; currentVersion: string; stagedVersion: string }| { kind: 'not-available'; currentVersion: string }| { kind: 'error'; message: string };@@ -1196,6 +1216,32 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa// that already has a failed install behind them.let stagedThisSession: string | null = null;+ /**+ * The build already staged this session, when THAT is why the offer in hand+ * is being declined — otherwise null.+ *+ * Both listeners must answer this identically — `onUpdateAvailable` to decide+ * whether to fetch, `onUpdateAvailableForMenuCheck` to decide what a manual+ * check reports — or the report path advertises a download that is not+ * running. Derived once so the two cannot diverge; call it once per listener+ * rather than re-testing either arm inline. Returning the version rather than+ * a boolean is what lets the reporting path name the build without+ * re-narrowing `stagedThisSession`.+ *+ * Same version: declined on every platform. Re-downloading is not a no-op+ * even from cache, and every re-stage is a window in which a "Relaunch" click+ * hits a half-written staging directory.+ *+ * Version change: declined on macOS only, because only Squirrel.Mac holds a+ * pending install in a separate armed process that a second download races+ * rather than replaces. `onUpdateAvailable` carries the full mechanism.+ */+ const declinedForStagedVersion = (offeredVersion: string | undefined): string | null => {+ if (stagedThisSession === null) return null;+ if (stagedThisSession === offeredVersion) return stagedThisSession;+ return platform === 'darwin' ? stagedThisSession : null;+ };+/** Accessor form, so a read after an `await` is not stale-narrowed. */const currentStaging = (): { version: string } | null => stagingInFlight;@@ -1337,6 +1383,52 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa);if (restored) {broadcastToAllWindows('ok:update:downloaded', { version });+ } else if (platform !== 'darwin') {+ // The persist failed, so `versionPendingInstall` stays cleared and there+ // is no banner to retry from. Only `stagedThisSession` gates the decline,+ // so without releasing it here nothing else would: the guard would turn+ // down the re-offer of this very version on every later poll, and the+ // session would neither re-download nor re-arm the banner.+ //+ // Safe on both platforms that reach this, for different reasons. Linux+ // arms nothing at all (`autoInstallOnAppQuit` is false there), so there+ // is no pending request to double up. Windows arms only a cache entry+ // behind ONE idempotent quit handler, so a re-download replaces the+ // pending installer rather than racing it — the citation for that is at+ // the decline guard in `onUpdateAvailable`. Either way the retry banner+ // comes back for free.+ logger.warn(+ stagedThisSession === null+ ? 'relaunch-failed restore did not persist — no single-flight arm was held'+ : 'relaunch-failed restore did not persist — releasing the single-flight arm',+ { version, kind, armedVersion: stagedThisSession },+ );+ stagedThisSession = null;+ } else {+ // macOS keeps the arm: the trigger cannot tell us whether Squirrel's+ // request is still live. ShipIt is armed at+ // download-completion time (`[email protected]`+ // `out/MacUpdater.js#doDownloadUpdate`), not here, and each of+ // `failRelaunch`'s three triggers leaves a different possibility open:+ // the watchdog fires on an app that then quits anyway, a+ // `quitAndInstall()` throw means the app is not quitting at all, and an+ // `error` event may be Squirrel reporting a swap that already ran and+ // failed — or an unrelated error arriving while ShipIt is still pending+ // (see `onError`, which says both).+ //+ // Keeping the arm is the conservative read of all three: releasing it can+ // arm a SECOND ShipIt beside a live one, which is the bundle-losing race+ // this guard exists to prevent. The price is bounded but not zero. Usually+ // it is just the retry button, since `autoInstallOnAppQuit` installs the+ // staged build at quit regardless; but if the swap had already failed then+ // nothing installs at quit either, and this session takes no update at all+ // until the next launch.+ logger.warn(+ stagedThisSession === null+ ? 'relaunch-failed restore did not persist — no single-flight arm was held'+ : 'relaunch-failed restore did not persist — keeping the single-flight arm (darwin: ShipIt may still be waiting)',+ { version, kind, armedVersion: stagedThisSession },+ );}broadcastToAllWindows('ok:update:relaunch-failed', {version,@@ -1349,13 +1441,18 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa// reveal the stuck card underneath. Clear it instead....(restored ? {} : { dismissPending: true }),});- logger.warn('relaunch failed — restored pending install and re-armed windows', {- version,- kind,- message,- causeCode: cause?.code,- causeStack: cause?.stack,- });+ logger.warn(+ restored+ ? 'relaunch failed — restored pending install and re-armed windows'+ : 'relaunch failed — pending install NOT restored',+ {+ version,+ kind,+ message,+ causeCode: cause?.code,+ causeStack: cause?.stack,+ },+ );onDispatch?.(kind);};@@ -1469,25 +1566,68 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa// identical bytes. Every one of those re-stages is a window in which a// "Relaunch" click hits a half-written staging directory (see// `stagingInFlight`), so an hourly re-stage of a build we already hold is- // pure downside. A version CHANGE still re-downloads, and a download that- // failed left `versionPendingInstall` unset, so retries are unaffected.+ // pure downside.//- // Both conditions are required. `stagedThisSession` is what makes the skip+ // On macOS a version CHANGE is declined too, for a different and harder+ // reason: Squirrel holds a pending install by LAUNCHING ShipIt, which then+ // waits — with no timeout of its own — for this process to exit.+ // Downloading again does not replace that request, it launches a SECOND+ // ShipIt beside the first, and both wake in the same instant when the app+ // finally quits. They then race the same swap: the loser moves aside the+ // bundle the winner just installed, and if it cannot move it back the app+ // is gone from /Applications with nothing left to launch. Nothing in+ // Electron's autoUpdater API can withdraw an armed request, so declining+ // the second download is the only lever available. The staged build still+ // installs at quit and the newer one is picked up in the session after. The+ // cost is not a one-version bound: on macOS nothing clears+ // `stagedThisSession`, so every further offer this process sees is declined+ // too, and a session long enough to span several releases installs the first+ // build it staged and stays there until the next launch. (Off macOS+ // `failRelaunch` releases it when it cannot restore the retry banner; see+ // there for why that release stops at the macOS boundary.)+ //+ // Nowhere else has a request to collide with, so nowhere else pays that+ // cost. On Windows a download only writes an installer to the cache and+ // `BaseUpdater.addQuitHandler` is idempotent — it guards on+ // `quitHandlerAdded`, and the handler it registers calls `install()`, which+ // reads the most recent download — so the single quit handler runs+ // whichever installer was downloaded LAST: a newer build replaces the+ // pending one rather than racing it. On Linux `autoInstallOnAppQuit` is+ // false (see its assignment), so `addQuitHandler` returns early and no quit+ // handler is registered at all, leaving nothing pending between the+ // download and an explicit relaunch click. Cited rather than asserted+ // because this reading is what removes the guard on those platforms:+ // `[email protected]` (exact-pinned in `packages/desktop/package.json`)+ // `out/BaseUpdater.js#addQuitHandler` and `out/NsisUpdater.js#doDownloadUpdate`.+ // The tests cannot catch a mistake here — they run against a stub of+ // electron-updater, so they pin our gating, not its behaviour.+ //+ // `stagedThisSession` — not the persisted field — is what makes both skips// safe (see its declaration): the persisted field alone would also match on// the FIRST offer of a session that inherited a staged-but-uninstalled// build, and skipping there leaves electron-updater with no installer path// and no quit handler, so the update becomes uninstallable until a newer- // one ships.- if (- offeredVersion &&- stagedThisSession === offeredVersion &&- readState().versionPendingInstall === offeredVersion- ) {- logger.debug('update-available for the already-staged version — skipping re-download', {- version: offeredVersion,- });+ // one ships. Keying on a COMPLETED stage likewise leaves a download that+ // failed free to retry: nothing reached Squirrel, so there is no pending+ // request to collide with.+ const armedVersion = declinedForStagedVersion(offeredVersion);+ if (armedVersion !== null) {+ // `debug` for the hourly re-offer of bytes already held; `warn` for a+ // suppressed newer build, because production's log floor is `info`, so a+ // `debug` line never reaches `~/.ok/logs` and therefore never reaches a+ // bug report. That decision suppresses a genuinely newer build for the+ // rest of the process lifetime, which is exactly the question a "why am I+ // not getting the update" report has to be able to answer.+ const reOffer = armedVersion === offeredVersion;+ const logFn = reOffer ? logger.debug : logger.warn;+ logFn(+ reOffer+ ? 'update-available for the already-staged version — skipping re-download'+ : 'update-available while an install is already armed — skipping re-download',+ { version: offeredVersion, armedVersion },+ );settleCheckWaiters('settled');- onDispatch?.('download-skipped-already-staged');+ onDispatch?.(reOffer ? 'download-skipped-already-staged' : 'download-skipped-install-armed');return;}// Tag the artifact fetch with the version being installed. The Windows and@@ -1549,6 +1689,23 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHashowCheckNowResult?.({ kind: 'not-available', currentVersion: getAppVersion() });return;}+ // This listener fires for the same event as `onUpdateAvailable` and cannot+ // see that it declined the offer, so it has to ask the same question that+ // path asked, or it will advertise a download that is not happening. Report+ // the build the session is actually holding: an offer declined by the+ // single-flight guard is not what a relaunch installs, and saying otherwise+ // sends the user round the same check forever waiting for a version that+ // never arrives. The declined-because-already-staged case reaches here too+ // — nothing is downloading there either.+ const armedVersion = declinedForStagedVersion(info.version);+ if (armedVersion !== null) {+ showCheckNowResult?.({+ kind: 'ready-to-install',+ currentVersion: getAppVersion(),+ stagedVersion: armedVersion,+ });+ return;+ }showCheckNowResult?.({kind: 'available',currentVersion: getAppVersion(),@@ -1886,6 +2043,15 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa* Never throws. Every failure and timeout falls through to installing* whatever is currently staged, because a stale install still beats a* refusal to relaunch.+ *+ * On macOS it can no longer resolve staleness once THIS session has staged a+ * build: the single-flight guard in `onUpdateAvailable` declines the newer+ * offer this check turns up, so the refresh confirms which version installs+ * rather than changing it. That is the intended trade — a second armed ShipIt+ * would be woken seconds later by this very click, which is the worst+ * instance of the race the guard exists to prevent. The freshness resolution+ * described above still applies on Windows and Linux, and on a macOS session+ * that has not staged anything yet.*/const refreshBeforeInstall = async (): Promise<void> => {// A stage already running is the dangerous case, and it is also the case@@ -1938,8 +2104,15 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa// not model.const staging = currentStaging();if (result !== 'available' || !staging) {- // Either nothing newer exists, or the offer was vetoed or already- // staged. Both mean the staged build is the one to install.+ // Either nothing newer exists, or the offer was vetoed, already staged,+ // or declined by the single-flight guard. All of them mean the staged+ // build is the one to install, which is what this kind reports — it says+ // the refresh did not change the outcome, not that nothing newer exists.+ // The cases stay separable downstream because each declining path emits+ // its own kind in the same click: `download-skipped-install-armed` for+ // the macOS single-flight, `download-skipped-already-staged` for a+ // re-offer of the staged build, `cross-channel-blocked` for a veto. A+ // lone `relaunch-refresh-up-to-date` is the genuinely-up-to-date case.onDispatch?.('relaunch-refresh-up-to-date');return;}@@ -2142,10 +2315,14 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHabroadcastToAllWindows('ok:update:relaunching', { version: pending });onDispatch?.('relaunching-broadcast');// Fire the pre-relaunch teardown hook BEFORE `quitAndInstall()`. Wrap- // in try/catch so a hook bug never blocks the user's relaunch — the- // worst case if the hook throws is the original failure mode (ShipIt's- // not-still-running validation aborts with code -9), which the user can recover from by- // quitting the app manually. We log the throw so the diagnostic is+ // in try/catch so a hook bug never blocks the user's relaunch. The worst+ // case if the hook throws is that the teardown it owns does not run:+ // servers are not stopped and the async log buffer is not drained, so+ // helper processes can outlive the swap and the tail of the log is lost.+ // Not a blocked install — ShipIt's "App Still Running" abort keys on+ // another process claiming THIS bundle URL, and a spawned server claims its+ // own helper bundle, so it cannot trigger that (see `window-manager.ts`,+ // which states the same constraint). We log the throw so the diagnostic is// visible in main process stderr.if (opts.prepareForRelaunch) {try {diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 1031210a9..77c19fe8d 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -9122,11 +9122,12 @@ function bootPrimaryInstance(): void {: {}),// Pre-relaunch teardown — synchronously hard-kill every project-window// utility (Hocuspocus host) right before- // `autoUpdater.quitAndInstall()` so Squirrel.Mac's pre-swap- // not-still-running validation doesn't see a stale process and abort with code -9- // ("App Still Running Error"). The graceful `{type:'shutdown'}`- // window-close IPC isn't fast enough — Hocuspocus drain + file-watcher- // teardown can outlast ShipIt's poll budget.+ // `autoUpdater.quitAndInstall()`, so no server outlives the bundle swap+ // and gets re-attached by the relaunched app at an older version. The+ // graceful `{type:'shutdown'}` window-close IPC isn't fast enough —+ // Hocuspocus drain + file-watcher teardown can outlast the swap window.+ // Not about ShipIt's "App Still Running" abort, which cannot see these+ // processes; `prepareForRelaunch` in `auto-updater.ts` says why.prepareForRelaunch: async () => {// Freeze focus tracking BEFORE any teardown: the window-close// cascade below re-focuses each surviving window, and tracking@@ -9176,6 +9177,24 @@ function bootPrimaryInstance(): void {message: "You're on the latest version of OpenKnowledge.",detail: `OpenKnowledge ${result.currentVersion} is the most current version available.`,});+ } else if (result.kind === 'ready-to-install') {+ // Stated, not instructed. Every dialog in this chain is OK-only,+ // and the wired "Relaunch" affordance lives on Toast A, which is+ // dismissible — so a user can reach this dialog with no relaunch+ // button anywhere on screen. Copy that said "Relaunch to install+ // it" pointed at a control that may not exist. It also cannot say+ // "quit and reopen": that installs on macOS and Windows, but Linux+ // has `autoInstallOnAppQuit` off, so a plain quit installs nothing+ // there. What holds on all three is that relaunching is when it+ // lands.+ void dialog.showMessageBox(target, {+ type: 'info',+ buttons: ['OK'],+ defaultId: 0,+ title: 'Update Ready',+ message: `OpenKnowledge ${result.stagedVersion} is downloaded and ready.`,+ detail: `It installs the next time you relaunch. Any newer build is offered after that.`,+ });} else if (result.kind === 'available') {void dialog.showMessageBox(target, {type: 'info',diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 5d4a6b19a..14b861cc4 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -1534,11 +1534,10 @@ export class WindowManager {* `quitAndInstall`.*/async stopAllOwnedServers(): Promise<void> {- // Utility-fork pids (dev path) — hard-kill immediately. These are- // children of Electron's process tree and would die anyway on- // `quitAndInstall`, but ShipIt's pre-swap not-still-running validation- // (the `SQRLInstallerErrorDomain Code=-9 "App Still Running"` failure)- // wants the tree clean BEFORE it looks.+ // Utility-fork pids (dev path) — hard-kill immediately. These are children+ // of Electron's process tree and would die on `quitAndInstall` anyway;+ // killing them first makes the teardown ordered rather than a race with+ // the swap, and keeps this path's shape identical to the detached one.signalStopOwnedUtilityForks(this.windowsByPath.values(), this.deps.log);// Detached-spawn pids — two-phase SIGTERM → poll → SIGKILL.@@ -1646,8 +1645,10 @@ export class WindowManager {* design (it runs detached off `process.execPath`, the bundle's Electron* binary). If it outlives the swap, the relaunched app attaches to it, reads* an older version off `server.lock`, and shows the version-drift toast — the- * "every update" complaint. A still-alive bundle-process can also trip- * ShipIt's pre-swap "App Still Running" check. Killing it here removes both.+ * "every update" complaint. Killing it here removes that. It is the whole+ * reason: the server runs as its own helper bundle, so ShipIt's+ * "App Still Running" abort never counts it (see `prepareForRelaunch` in+ * `auto-updater.ts`).** Best-effort by necessity: `before-quit-for-update` cannot hold the quit open* for the grace-poll ladder, so this only sends the signal — but the server'sdiff --git a/packages/desktop/tests/integration/auto-updater.test.ts b/packages/desktop/tests/integration/auto-updater.test.tsindex 829dd278d..554a75b5e 100644--- a/packages/desktop/tests/integration/auto-updater.test.ts+++ b/packages/desktop/tests/integration/auto-updater.test.ts@@ -20,7 +20,10 @@*/import { EventEmitter } from 'node:events';+import { readFileSync } from 'node:fs';import type { OutgoingHttpHeaders } from 'node:http';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';import { describe, expect, test, vi } from 'vitest';import {bootAutoUpdater,@@ -218,8 +221,9 @@ function makeRig(* Pre-relaunch teardown hook — fires synchronously from the* `relaunch-now` IPC handler immediately before* `autoUpdater.quitAndInstall()`. Production wires this to a hard- * SIGKILL of project-window utilities so Squirrel.Mac's pre-swap- * pgrep doesn't see stale processes.+ * SIGKILL of project-window utilities so no server outlives the bundle+ * swap. Not about Squirrel.Mac's "App Still Running" abort, which keys on+ * another process claiming the app's bundle URL and so cannot see these.*/prepareForRelaunch?: () => void;/**@@ -4797,14 +4801,14 @@ function fireTimerFor(clock: FakeClock, ms: number): void {(call[0] as () => void)();}-describe('same-version download guard', () => {- /** Take a rig through a real in-session stage of `version`. */- function stageInSession(rig: TestRig, version: string): void {- rig.updater.emit('update-available', { version });- rig.updater.emit('update-downloaded', { version });- rig.updater.downloadUpdate.mockClear();- }+/** Take a rig through a real in-session stage of `version`. */+function stageInSession(rig: TestRig, version: string): void {+ rig.updater.emit('update-available', { version });+ rig.updater.emit('update-downloaded', { version });+ rig.updater.downloadUpdate.mockClear();+}+describe('same-version download guard', () => {test('a re-offer of the build this session staged does not re-download', () => {const { rig } = makeRig({ versionPendingInstall: null });stageInSession(rig, '0.3.2');@@ -4881,6 +4885,377 @@ describe('same-version download guard', () => {});});+describe('cited upstream behaviour stays tied to the pinned dependency', () => {+ test('the electron-updater version in the guard comment matches package.json', () => {+ // The comment citing `BaseUpdater#addQuitHandler` is what authorizes NOT+ // guarding Windows and Linux, and the suite cannot check it: these tests+ // run against a stub, so they pin our gating rather than electron-updater's+ // behaviour. A version bump is the one event that should force a re-read of+ // that citation, and without this it would pass silently.+ const here = dirname(fileURLToPath(import.meta.url));+ const pkg = JSON.parse(readFileSync(join(here, '../../package.json'), 'utf8')) as {+ dependencies?: Record<string, string>;+ devDependencies?: Record<string, string>;+ };+ const pinned =+ pkg.dependencies?.['electron-updater'] ?? pkg.devDependencies?.['electron-updater'];+ const source = readFileSync(join(here, '../../src/main/auto-updater.ts'), 'utf8');+ // Every occurrence, not the first: the file carries more than one citation+ // and a guard that checks one of them would pass while another rots.+ const cited = [...source.matchAll(/`electron-updater@([^`]+)`/g)].map((m) => m[1]);++ expect(cited.length).toBeGreaterThan(0);+ expect([...new Set(cited)]).toEqual([pinned]);+ });+});++/**+ * A second macOS download arms a second ShipIt beside the pending one, and both+ * race the same bundle swap at quit. The mechanism, and why declining is the+ * only available lever, is stated once at the guard itself — see the comment+ * above the `declinedForStagedVersion` call in `onUpdateAvailable`.+ */+describe('single-flight install handoff', () => {+ test('a newer offer does not arm a second request beside the pending one', () => {+ // The periodic-cadence shape. The staged build still installs at quit; the+ // newer one is picked up in the session after that. The cost is that every+ // further offer this macOS process sees is declined too — nothing clears+ // `stagedThisSession` here — which is the whole price of not racing the+ // swap.+ const { rig } = makeRig({ versionPendingInstall: null });+ stageInSession(rig, '0.3.2');++ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(rig.dispatches).toContain('download-skipped-install-armed' as DispatchKind);+ });++ test('the declined offer still counts as a successful check', () => {+ // Same reasoning as the same-version skip: the manifest was fetched and+ // parsed, so marching the stuck-hint toward firing would be wrong.+ const { rig } = makeRig({ versionPendingInstall: null });+ stageInSession(rig, '0.3.2');+ rig.dispatches.length = 0;++ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(rig.dispatches).toContain('download-skipped-install-armed' as DispatchKind);+ expect(rig.dispatches).toContain('check-success' as DispatchKind);+ });++ test('the click-time freshness check installs the armed build rather than a second one', async () => {+ // The worst instance of the race, because both ShipIts are woken seconds+ // later by this very click. The refresh is documented to fall through to+ // "install whatever is currently staged" on every failure; an already-armed+ // request is one more reason to take that path, not a new failure mode.+ const { rig } = makeRig({ versionPendingInstall: null });+ stageInSession(rig, '0.3.2');+ rig.updater.checkForUpdates.mockImplementation(() => {+ rig.updater.emit('update-available', { version: '0.3.3' });+ return Promise.resolve(undefined);+ });++ await rig.ipc.invoke('ok:update:relaunch-now');++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);+ expect(rig.state.attemptedInstall).toBe('0.3.2');+ // The pair `refreshBeforeInstall` documents as what keeps a decline+ // separable from a genuinely up-to-date check: the outcome kind says the+ // refresh did not change what installs, and the decline kind beside it says+ // why. Telemetry that only saw the former would read this as "nothing+ // newer existed".+ expect(rig.dispatches).toContain('relaunch-refresh-up-to-date' as DispatchKind);+ expect(rig.dispatches).toContain('download-skipped-install-armed' as DispatchKind);+ });++ // Per-platform cases rather than a loop inside one test: a loop reports the+ // first failure as the whole test and never runs the platform after it.+ test.each(['win32', 'linux'] as const)('on %s a newer offer still downloads', (platform) => {+ // Only Squirrel.Mac holds the pending install in a separate armed process.+ // On Windows a download writes an installer to the cache and the single+ // idempotent quit handler runs whichever was downloaded LAST, so a newer+ // build replaces the pending one instead of racing it; on Linux+ // `autoInstallOnAppQuit` is false, so nothing is pending at all. Declining+ // there would pin a long session to the first build it happened to stage+ // and buy nothing for it.+ const { rig } = makeRig({ versionPendingInstall: null, platform });+ stageInSession(rig, '0.3.2');++ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(rig.updater.downloadUpdate).toHaveBeenCalledTimes(1);+ expect(rig.dispatches).not.toContain('download-skipped-install-armed' as DispatchKind);+ });++ test.each([+ 'win32',+ 'linux',+ ] as const)('on %s a manual check for a newer offer reports it as downloading', (platform) => {+ // The reporting gate must ask the same darwin-scoped predicate as the+ // fetch gate, or Windows and Linux report a stale staged version while a+ // newer download is in flight. Pins the direction the fetch test cannot+ // see: there, the correct outcome is that the download happens.+ const showCheckNowResult = vi.fn(() => {});+ const { rig } = makeRig({+ appVersion: '0.3.1',+ versionPendingInstall: null,+ platform,+ showCheckNowResult,+ });+ stageInSession(rig, '0.3.2');+ showCheckNowResult.mockClear();++ rig.ipc.invoke('ok:update:check-now');+ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(showCheckNowResult).toHaveBeenCalledWith({+ kind: 'available',+ currentVersion: '0.3.1',+ latestVersion: '0.3.3',+ });+ });++ test.each([+ 'win32',+ 'linux',+ ] as const)('on %s the same-version skip still applies', (platform) => {+ // Its rationale — not reopening a re-stage window over bytes already+ // held — has nothing to do with Squirrel, so the platform scoping must+ // not leak into it.+ const { rig } = makeRig({ versionPendingInstall: null, platform });+ stageInSession(rig, '0.3.2');++ rig.updater.emit('update-available', { version: '0.3.2' });++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(rig.dispatches).toContain('download-skipped-already-staged' as DispatchKind);+ });++ test('a manual check names the build that will install, not the declined offer', () => {+ // `onUpdateAvailableForMenuCheck` fires for the same event and cannot see+ // that the offer was declined. Left alone it says "0.3.3 is available, it's+ // downloading in the background" — both halves false — and the user+ // relaunches onto 0.3.2 and repeats the check forever.+ const showCheckNowResult = vi.fn(() => {});+ const { rig } = makeRig({+ appVersion: '0.3.1',+ versionPendingInstall: null,+ showCheckNowResult,+ });+ stageInSession(rig, '0.3.2');+ showCheckNowResult.mockClear();++ rig.ipc.invoke('ok:update:check-now');+ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(showCheckNowResult).toHaveBeenCalledTimes(1);+ expect(showCheckNowResult).toHaveBeenCalledWith({+ kind: 'ready-to-install',+ currentVersion: '0.3.1',+ stagedVersion: '0.3.2',+ });+ });++ test('a manual check that turns up the armed build reads as ready, not downloading', () => {+ // The same-version re-offer, which is the COMMON shape: electron-updater+ // re-offers a staged build on every poll for as long as it is newer than+ // the running one, so this fires hourly while the version-change shape+ // needs a release to land mid-session. It is declined too — no+ // `downloadUpdate()` runs — so reporting "downloading in the background"+ // described a download that was not happening on every platform.+ const showCheckNowResult = vi.fn(() => {});+ const { rig } = makeRig({+ appVersion: '0.3.1',+ versionPendingInstall: null,+ showCheckNowResult,+ });+ stageInSession(rig, '0.3.2');+ showCheckNowResult.mockClear();++ rig.ipc.invoke('ok:update:check-now');+ rig.updater.emit('update-available', { version: '0.3.2' });++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(showCheckNowResult).toHaveBeenCalledWith({+ kind: 'ready-to-install',+ currentVersion: '0.3.1',+ stagedVersion: '0.3.2',+ });+ });++ test.each([+ 'win32',+ 'linux',+ ] as const)('on %s a manual check for the armed build still reads as ready', (platform) => {+ // Off macOS the version-change term is false, so this is the only place+ // the same-version half of the predicate is load-bearing — on darwin that+ // term reports `ready-to-install` on its own and would mask its removal.+ // It is also the shape that fires hourly.+ const showCheckNowResult = vi.fn(() => {});+ const { rig } = makeRig({+ appVersion: '0.3.1',+ versionPendingInstall: null,+ platform,+ showCheckNowResult,+ });+ stageInSession(rig, '0.3.2');+ showCheckNowResult.mockClear();++ rig.ipc.invoke('ok:update:check-now');+ rig.updater.emit('update-available', { version: '0.3.2' });++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(showCheckNowResult).toHaveBeenCalledWith({+ kind: 'ready-to-install',+ currentVersion: '0.3.1',+ stagedVersion: '0.3.2',+ });+ });++ test.each([+ 'win32',+ 'linux',+ ] as const)('on %s a relaunch that cannot restore its state releases the arm', async (platform) => {+ // Losing both the persist and the arm leaves the session with no banner+ // to retry from and a guard that declines the re-offer of this very+ // version forever. Only `stagedThisSession` gates that decline, so+ // nothing else would release it. Safe here because neither platform has+ // an armed installer a re-download could duplicate.+ const { rig } = makeRig({ versionPendingInstall: null, platform });+ stageInSession(rig, '0.3.2');+ rig.updater.quitAndInstall = vi.fn(() => {+ // Flip only now: an earlier failure would abort the handler before it+ // reaches the restore path this test is about.+ rig.failNextPersist = true;+ throw new Error('installer refused the handoff');+ });++ await expect(Promise.resolve(rig.ipc.invoke('ok:update:relaunch-now'))).rejects.toThrow(+ 'installer refused the handoff',+ );+ expect(rig.state.versionPendingInstall).toBeNull();+ rig.failNextPersist = false;+ rig.updater.downloadUpdate.mockClear();++ rig.updater.emit('update-available', { version: '0.3.2' });++ expect(rig.updater.downloadUpdate).toHaveBeenCalledTimes(1);+ });++ /**+ * macOS keeps the arm on every `failRelaunch` trigger, because none of them+ * establishes that Squirrel's request is spent — the watchdog fires on an app+ * that may still quit, a throw means it is not quitting at all, and an error+ * event may arrive while ShipIt is still pending. One case per trigger, so a+ * refactor of any single dispatch site cannot break the invariant silently.+ */+ test('on macOS a watchdog fire that cannot restore KEEPS the arm', async () => {+ const { rig } = makeRig({ versionPendingInstall: null });+ stageInSession(rig, '0.3.2');+ await rig.ipc.invoke('ok:update:relaunch-now');+ rig.failNextPersist = true;+ fireTimerFor(rig.clock, RELAUNCH_WATCHDOG_MS);+ rig.failNextPersist = false;+ expect(rig.dispatches).toContain('relaunch-watchdog-fired' as DispatchKind);+ expect(rig.state.versionPendingInstall).toBeNull();+ rig.updater.downloadUpdate.mockClear();++ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(rig.dispatches).toContain('download-skipped-install-armed' as DispatchKind);+ });++ test('on macOS a quitAndInstall throw that cannot restore KEEPS the arm', async () => {+ const { rig } = makeRig({ versionPendingInstall: null });+ stageInSession(rig, '0.3.2');+ rig.updater.quitAndInstall = vi.fn(() => {+ rig.failNextPersist = true;+ throw new Error('squirrel refused the handoff');+ });++ await expect(Promise.resolve(rig.ipc.invoke('ok:update:relaunch-now'))).rejects.toThrow(+ 'squirrel refused the handoff',+ );+ rig.failNextPersist = false;+ expect(rig.state.versionPendingInstall).toBeNull();+ rig.updater.downloadUpdate.mockClear();++ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(rig.dispatches).toContain('download-skipped-install-armed' as DispatchKind);+ });++ test('on macOS an in-flight error that cannot restore KEEPS the arm', async () => {+ // The trigger where the arm may genuinely be spent — this is Squirrel's+ // swap-failure channel, reported after a clean `quitAndInstall()` return.+ // The arm is kept anyway because `onError` cannot tell that case from an+ // unrelated error arriving while ShipIt is still pending, and only one of+ // those two readings is safe to act on.+ const { rig } = makeRig({ versionPendingInstall: null });+ stageInSession(rig, '0.3.2');+ await rig.ipc.invoke('ok:update:relaunch-now');+ rig.failNextPersist = true;+ rig.updater.emit('error', new Error('install failed'));+ rig.failNextPersist = false;+ expect(rig.dispatches).toContain('relaunch-error-event' as DispatchKind);+ expect(rig.state.versionPendingInstall).toBeNull();+ rig.updater.downloadUpdate.mockClear();++ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(rig.dispatches).toContain('download-skipped-install-armed' as DispatchKind);+ });++ test('a relaunch that fails but DOES restore its state keeps the arm', async () => {+ // The ordinary failure path, and the direction a "simplification" that+ // hoists the release above the if/else would silently break: the banner is+ // back, so the retry affordance exists and the arm must survive to keep the+ // single-flight guarantee.+ const { rig } = makeRig({ versionPendingInstall: null });+ stageInSession(rig, '0.3.2');+ rig.updater.quitAndInstall = vi.fn(() => {+ throw new Error('squirrel refused the handoff');+ });++ await expect(Promise.resolve(rig.ipc.invoke('ok:update:relaunch-now'))).rejects.toThrow(+ 'squirrel refused the handoff',+ );+ expect(rig.state.versionPendingInstall).toBe('0.3.2');+ rig.updater.downloadUpdate.mockClear();++ rig.updater.emit('update-available', { version: '0.3.2' });++ expect(rig.updater.downloadUpdate).not.toHaveBeenCalled();+ expect(rig.dispatches).toContain('download-skipped-already-staged' as DispatchKind);+ });++ test('a download that never staged leaves the next offer free to arm', () => {+ // Nothing was handed to Squirrel, so there is no pending request to+ // collide with — the guard must key on a completed stage, not on having+ // attempted one, or a single failed download would end updates for the+ // rest of the session.+ //+ // The same setup as `a retry after a failed download…` above, re-offering a+ // DIFFERENT version rather than the same one, so it lands on the+ // newer-offer branch (`declinedForStagedVersion` returning non-null via the+ // darwin term). Both fail if the not-armed short circuit stops+ // short-circuiting; only this one covers the newer-offer path through it.+ const { rig } = makeRig({ versionPendingInstall: null });+ rig.updater.emit('update-available', { version: '0.3.2' });+ rig.updater.emit('error', new Error('network died'));+ rig.updater.downloadUpdate.mockClear();++ rig.updater.emit('update-available', { version: '0.3.3' });++ expect(rig.updater.downloadUpdate).toHaveBeenCalledTimes(1);+ });+});+describe('click-gated freshness check', () => {test('nothing newer → installs the staged build', async () => {const { rig } = makeRig({ versionPendingInstall: '0.3.2' });