Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(desktop): harden updates, reclaim cache, quiet startup (PRD-7798) (#3240)
mike-inkeepbbf15c37ae7e
diff --git a/.changeset/desktop-update-hardening.md b/.changeset/desktop-update-hardening.mdnew file mode 100644index 000000000..365fe5a7f--- /dev/null+++ b/.changeset/desktop-update-hardening.md@@ -0,0 +1,9 @@+---+'@inkeep/open-knowledge': patch+---++Desktop: harden updates, reclaim the updater cache, and remove packaged-startup warnings.++- Linux: when no graphical administrator authorization is available (no pkexec or PolicyKit agent), clicking Relaunch now shows a dismissible manual-install dialog with a copyable, shell-quoted package-manager command (`sudo apt install -- '<installer>'` / `sudo dnf install '<installer>'`) and an unconditional Relaunch button, instead of failing through terminal sudo. Cancelling the authorization prompt re-arms the update banner without the dialog; the staged installer is preserved until an install succeeds or a newer update replaces it.+- All platforms: the updater cache's staged installer (`pending/`, ~250 MB) is reclaimed once the installed version is running. Windows additionally stops retaining the NSIS installer's inert differential-update seed copy (`installer.exe`, ~250 MB) at install time. macOS keeps its separate `update.zip` differential-download seed — that copy actively shrinks future mac update downloads and is intentionally untouched.+- Packaged startup no longer emits the duplicate-Yjs warning (the `@inkeep/open-knowledge` library entry now resolves the shared `yjs` from node_modules; the standalone CLI binary still inlines it) or the `No handler registered for 'ok:...:renderer-ready'` errors (a permanent mount-ack sink now absorbs unarmed renderer-ready pings).diff --git a/knip.config.ts b/knip.config.tsindex 13a6b9fb3..78162ec09 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -129,6 +129,7 @@ export default {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],ignoreDependencies: ['@inkeep/open-knowledge-app', // the CLI's `build:assets` script runs `cp -r ../app/dist dist/public`+ 'yjs',],},'packages/desktop': {diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex c083d1e9f..1610f7634 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -31,7 +31,7 @@"access": "public"},"scripts": {- "build:cli": "tsdown",+ "build:cli": "rm -rf dist && tsdown","build:app": "cp -r ../app/dist dist/public","build:skill-asset": "tsx ../server/scripts/build-skill-bundles.ts && mkdir -p dist/assets/skills && cp -R ../server/dist/assets/skills/. dist/assets/skills/","build:notices": "mkdir -p dist && cp ../../THIRD_PARTY_NOTICES.md dist/THIRD_PARTY_NOTICES.md",@@ -64,6 +64,7 @@"smol-toml": "^1.6.1","yaml": "^2.7.1","yazl": "^3.3.1",+ "yjs": "^13.6.30","zod": "^4.3.6"},"optionalDependencies": {diff --git a/packages/cli/src/tsdown-bundle-coverage.test.ts b/packages/cli/src/tsdown-bundle-coverage.test.tsindex 15f289ee8..95a3520bd 100644--- a/packages/cli/src/tsdown-bundle-coverage.test.ts+++ b/packages/cli/src/tsdown-bundle-coverage.test.ts@@ -29,8 +29,11 @@ const declaredDeps = Object.keys(cliPkg.dependencies ?? {}).sort();const configSource = readFileSync(tsdownConfigPath, 'utf8');-function extractBlock(name: 'alwaysBundle' | 'neverBundle'): string {- const match = configSource.match(new RegExp(`${name}:\\s*\\[([\\s\\S]*?)\\]`));+// The config declares its bundling policy as two named shared consts (the+// standalone and library builds compose them), so the coverage anchors are+// the const declarations rather than per-build `alwaysBundle:` literals.+function extractBlock(name: 'alwaysBundlePureJsDeps' | 'nativeAddonNeverBundle'): string {+ const match = configSource.match(new RegExp(`const ${name}\\s*=\\s*\\[([\\s\\S]*?)\\n\\];`));return match?.[1] ?? '';}@@ -44,8 +47,8 @@ function stripLineComments(block: string): string {.join('\n');}-const alwaysBundleBlock = stripLineComments(extractBlock('alwaysBundle'));-const neverBundleBlock = stripLineComments(extractBlock('neverBundle'));+const alwaysBundleBlock = stripLineComments(extractBlock('alwaysBundlePureJsDeps'));+const neverBundleBlock = stripLineComments(extractBlock('nativeAddonNeverBundle'));const neverBundleNames = [...neverBundleBlock.matchAll(/'([^']+)'/g)].map((m) => m[1] as string);describe('tsdown alwaysBundle covers every cli runtime dep', () => {@@ -74,6 +77,35 @@ describe('tsdown alwaysBundle covers every cli runtime dep', () => {}});+/**+ * yjs is the one dep whose bundling deliberately DIFFERS between the two+ * builds: inlined in the standalone bin (no node_modules beside dist/cli.mjs),+ * external in the library entry (so the desktop's main/utility processes share+ * one yjs module record with `@inkeep/open-knowledge-server` — yjs keeps a+ * module-level singleton and duplicate copies break `instanceof` across them,+ * yjs/yjs#438, surfacing as "Yjs was already imported" at packaged startup).+ */+describe('yjs split-bundling policy', () => {+ test('yjs is a declared runtime dependency (library consumers resolve the external import)', () => {+ expect(declaredDeps).toContain('yjs');+ });++ test('standalone build inlines yjs (alwaysBundle covers it)', () => {+ expect(/\^yjs\\?\(/.test(alwaysBundleBlock)).toBe(true);+ });++ test('library build externalizes yjs (its neverBundle lists it)', () => {+ // The library config spreads the shared native-addon list and appends+ // 'yjs' — anchor on that exact composition so a refactor that silently+ // drops the externalization fails here.+ expect(configSource).toMatch(/neverBundle:\s*\[\.\.\.nativeAddonNeverBundle,\s*'yjs'\]/);+ });++ test('library build does not force-inline yjs (alwaysBundle filtered)', () => {+ expect(configSource).toMatch(/alwaysBundlePureJsDeps\.filter\(\(re\) => !re\.test\('yjs'\)\)/);+ });+});+/*** The loop above only covers the cli's OWN `package.json` dependencies. The* same ERR_MODULE_NOT_FOUND class also bites TRANSITIVE runtime deps thatdiff --git a/packages/cli/tsdown.config.ts b/packages/cli/tsdown.config.tsindex ab701f934..0002b43b6 100644--- a/packages/cli/tsdown.config.ts+++ b/packages/cli/tsdown.config.ts@@ -1,4 +1,5 @@import { createRequire } from 'node:module';+import type { UserConfig } from 'tsdown';import { defineConfig } from 'tsdown';// jsonc-parser's package `main` is a UMD bundle whose `require('./impl/format')`@@ -27,133 +28,181 @@ console.warn = (...args: unknown[]) => {originalWarn(...args);};-export default defineConfig({- // `parse-worker` ships as its own entry so the server's parse pool can- // spawn `./parse-worker.mjs` next to dist/cli.mjs at runtime (the- // published install has no node_modules to resolve through).- entry: { cli: 'src/cli.ts', index: 'src/index.ts', 'parse-worker': 'src/parse-worker.ts' },- unbundle: false,- format: 'esm',- dts: true,- clean: true,- minify: true,- plugins: [- {- name: 'jsonc-parser-esm-entry',- resolveId(id) {- return id === 'jsonc-parser' ? jsoncParserEsmEntry : null;- },- },- {- // pino stays value-bundled (see `deps.alwaysBundle` — the packaged DMG- // cannot resolve it as a bare specifier). Its VALUE inlines fine, but its- // TYPES cannot be inlined into cli's .d.mts: pino ships `export = pino`- // with the public API surfacing `pino.Logger` / `pino.LoggerOptions`, and- // rolldown-plugin-dts's declaration bundler fails to extract those- // namespace members from pino's .d.ts under pnpm's isolated node_modules- // (aborts with MISSING_EXPORT). Externalize pino ONLY in the declaration- // pass (importer is a generated `.d.ts`), leaving `import('pino')`- // references that consumers resolve from their own pino dependency- // (e.g. the desktop app declares pino).- name: 'externalize-pino-in-dts',- resolveId(id, importer) {- if (- (id === 'pino' || id.startsWith('pino/')) &&- importer &&- /\.d\.[cm]?ts$/.test(importer)- ) {- return { id, external: true };- }- return null;- },+// Native addons stay external in EVERY build — they ship .node binaries+// resolved at runtime and the desktop bundle places them under+// app.asar.unpacked/node_modules/.+const nativeAddonNeverBundle = [+ '@parcel/watcher',+ '@napi-rs/keyring',+ '@inkeep/open-knowledge-native-config',+];++// tsdown defaults to externalizing entries in `dependencies`, but the+// desktop install ships no node_modules/ next to dist/cli.mjs, so bare+// specifiers crash on resolve. Force-inline every pure-JS runtime dep in the+// standalone (cli / parse-worker) build. Keep this in sync with+// packages/cli/package.json `dependencies` (tsdown-bundle-coverage.test.ts+// enforces).+const alwaysBundlePureJsDeps = [+ /^@inquirer\/checkbox(\/|$)/,+ /^@inquirer\/password(\/|$)/,+ /^@inquirer\/select(\/|$)/,+ /^@modelcontextprotocol\/sdk(\/|$)/,+ /^@octokit\/auth-oauth-device(\/|$)/,+ /^@octokit\/request(\/|$)/,+ /^@octokit\/rest(\/|$)/,+ /^@borewit\/text-codec(\/|$)/,+ /^@tokenizer\/inflate(\/|$)/,+ /^@tokenizer\/token(\/|$)/,+ /^cli-boxes(\/|$)/,+ /^commander(\/|$)/,+ /^file-type(\/|$)/,+ /^ieee754(\/|$)/,+ /^jsonc-parser(\/|$)/,+ /^just-bash(\/|$)/,+ /^picocolors(\/|$)/,+ /^picomatch(\/|$)/,+ // pino is used via `pino.destination()` (sync sonic-boom, no worker+ // transports). Externalized, it resolves as a bare specifier from+ // app.asar.unpacked/ at runtime in packaged DMGs and crashes with+ // ERR_MODULE_NOT_FOUND — Node's resolver from app.asar.unpacked/+ // can't cross into the sibling app.asar/ for node_modules. Inlining+ // here removes the runtime resolution entirely.+ /^pino(\/|$)/,+ /^shell-quote(\/|$)/,+ /^simple-git(\/|$)/,+ /^sirv(\/|$)/,+ /^smol-toml(\/|$)/,+ /^strtok3(\/|$)/,+ /^token-types(\/|$)/,+ /^uint8array-extras(\/|$)/,+ /^yaml(\/|$)/,+ /^yazl(\/|$)/,+ // yjs must stay inlined in the standalone build (same no-node_modules+ // constraint as the rest of this list), and must stay EXTERNAL in the+ // library build below — see that config's `neverBundle`.+ /^yjs(\/|$)/,+ /^zod(\/|$)/,+];++const sharedPlugins: NonNullable<UserConfig['plugins']> = [+ {+ name: 'jsonc-parser-esm-entry',+ resolveId(id) {+ return id === 'jsonc-parser' ? jsoncParserEsmEntry : null;},- ],- inputOptions: (options) => {- // Filter known false-positive warnings. Each branch documents WHY the- // warning is suppressed — re-evaluate when bumping rolldown / tsdown /- // rolldown-plugin-dts. Anything not matched falls through to default.- options.onLog = (level, log, defaultHandler) => {- // `@protobufjs/inquire` uses `eval("quire".replace(/^/,"re"))(name)`- // as a deliberate require-detection workaround for bundlers. The- // dependency reaches us transitively via @opentelemetry/otlp-transformer- // (every OTLP exporter). Cannot be patched at source.- if (- log.code === 'EVAL' &&- typeof log.id === 'string' &&- log.id.includes('/@protobufjs/inquire/')- ) {- return;- }- // rolldown-plugin-dts strips `type` modifiers from emitted intermediate- // .d.ts before tracing cross-package re-exports, then warns that the- // names "are not exported as values". The recommended fix (`dts.eager`)- // forces tsc over the full tsconfig graph and OOMs node@22 on this- // monorepo. The names ARE exported as types in source and are correctly- // bundled into the final dist/index.d.mts.- if (- log.code === 'MISSING_EXPORT' &&- typeof log.id === 'string' &&- (log.id.endsWith('/src/commands/init.d.ts') || log.id.endsWith('/src/config/schema.d.ts'))- ) {- return;- }- // Same root cause as MISSING_EXPORT above — the plugin advises- // enabling `eager` after a fall-back emit; that path OOMs.- if (- log.pluginCode === 'rolldown-plugin-dts' &&- typeof log.message === 'string' &&- log.message.includes('Failed to emit declaration file')- ) {- return;+ },+ {+ // pino stays value-bundled (see `alwaysBundlePureJsDeps` — the packaged+ // DMG cannot resolve it as a bare specifier). Its VALUE inlines fine, but+ // its TYPES cannot be inlined into cli's .d.mts: pino ships `export = pino`+ // with the public API surfacing `pino.Logger` / `pino.LoggerOptions`, and+ // rolldown-plugin-dts's declaration bundler fails to extract those+ // namespace members from pino's .d.ts under pnpm's isolated node_modules+ // (aborts with MISSING_EXPORT). Externalize pino ONLY in the declaration+ // pass (importer is a generated `.d.ts`), leaving `import('pino')`+ // references that consumers resolve from their own pino dependency+ // (e.g. the desktop app declares pino).+ name: 'externalize-pino-in-dts',+ resolveId(id, importer) {+ if ((id === 'pino' || id.startsWith('pino/')) && importer && /\.d\.[cm]?ts$/.test(importer)) {+ return { id, external: true };}- defaultHandler(level, log);- };- return options;+ return null;+ },},- deps: {- // Native addons stay external — they ship .node binaries resolved at runtime- // and the desktop bundle places them under app.asar.unpacked/node_modules/.- neverBundle: ['@parcel/watcher', '@napi-rs/keyring', '@inkeep/open-knowledge-native-config'],- // tsdown defaults to externalizing entries in `dependencies`, but the- // desktop install ships no node_modules/ next to dist/cli.mjs, so bare- // specifiers crash on resolve. Force-inline every pure-JS runtime dep.- // Keep this in sync with packages/cli/package.json `dependencies`.- alwaysBundle: [- /^@inquirer\/checkbox(\/|$)/,- /^@inquirer\/password(\/|$)/,- /^@inquirer\/select(\/|$)/,- /^@modelcontextprotocol\/sdk(\/|$)/,- /^@octokit\/auth-oauth-device(\/|$)/,- /^@octokit\/request(\/|$)/,- /^@octokit\/rest(\/|$)/,- /^@borewit\/text-codec(\/|$)/,- /^@tokenizer\/inflate(\/|$)/,- /^@tokenizer\/token(\/|$)/,- /^cli-boxes(\/|$)/,- /^commander(\/|$)/,- /^file-type(\/|$)/,- /^ieee754(\/|$)/,- /^jsonc-parser(\/|$)/,- /^just-bash(\/|$)/,- /^picocolors(\/|$)/,- /^picomatch(\/|$)/,- // pino is used via `pino.destination()` (sync sonic-boom, no worker- // transports). Externalized, it resolves as a bare specifier from- // app.asar.unpacked/ at runtime in packaged DMGs and crashes with- // ERR_MODULE_NOT_FOUND — Node's resolver from app.asar.unpacked/- // can't cross into the sibling app.asar/ for node_modules. Inlining- // here removes the runtime resolution entirely.- /^pino(\/|$)/,- /^shell-quote(\/|$)/,- /^simple-git(\/|$)/,- /^sirv(\/|$)/,- /^smol-toml(\/|$)/,- /^strtok3(\/|$)/,- /^token-types(\/|$)/,- /^uint8array-extras(\/|$)/,- /^yaml(\/|$)/,- /^yazl(\/|$)/,- /^zod(\/|$)/,- ],+];++const sharedInputOptions: NonNullable<UserConfig['inputOptions']> = (options) => {+ // Filter known false-positive warnings. Each branch documents WHY the+ // warning is suppressed — re-evaluate when bumping rolldown / tsdown /+ // rolldown-plugin-dts. Anything not matched falls through to default.+ options.onLog = (level, log, defaultHandler) => {+ // `@protobufjs/inquire` uses `eval("quire".replace(/^/,"re"))(name)`+ // as a deliberate require-detection workaround for bundlers. The+ // dependency reaches us transitively via @opentelemetry/otlp-transformer+ // (every OTLP exporter). Cannot be patched at source.+ if (+ log.code === 'EVAL' &&+ typeof log.id === 'string' &&+ log.id.includes('/@protobufjs/inquire/')+ ) {+ return;+ }+ // rolldown-plugin-dts strips `type` modifiers from emitted intermediate+ // .d.ts before tracing cross-package re-exports, then warns that the+ // names "are not exported as values". The recommended fix (`dts.eager`)+ // forces tsc over the full tsconfig graph and OOMs node@22 on this+ // monorepo. The names ARE exported as types in source and are correctly+ // bundled into the final dist/index.d.mts.+ if (+ log.code === 'MISSING_EXPORT' &&+ typeof log.id === 'string' &&+ (log.id.endsWith('/src/commands/init.d.ts') || log.id.endsWith('/src/config/schema.d.ts'))+ ) {+ return;+ }+ // Same root cause as MISSING_EXPORT above — the plugin advises+ // enabling `eager` after a fall-back emit; that path OOMs.+ if (+ log.pluginCode === 'rolldown-plugin-dts' &&+ typeof log.message === 'string' &&+ log.message.includes('Failed to emit declaration file')+ ) {+ return;+ }+ defaultHandler(level, log);+ };+ return options;+};++// Two builds instead of one, split on how yjs resolves. yjs keeps a+// module-level singleton and breaks `instanceof` across duplicate copies+// (yjs/yjs#438), and the desktop's main + utility processes import BOTH this+// package's library entry AND `@inkeep/open-knowledge-server` — the server+// leaves yjs external, so a library entry with yjs inlined loads a second+// copy into those processes ("Yjs was already imported" at packaged startup).+// The standalone bin (dist/cli.mjs), by contrast, runs with no node_modules+// beside it and MUST keep yjs inlined. tsdown's externalization is global per+// build, so the two entries get their own builds. `clean` stays off in both:+// the `build:cli` script wipes dist/ up front instead, so neither build can+// clobber the other's output.+export default defineConfig([+ {+ // `parse-worker` ships as its own entry so the server's parse pool can+ // spawn `./parse-worker.mjs` next to dist/cli.mjs at runtime (the+ // published install has no node_modules to resolve through).+ entry: { cli: 'src/cli.ts', 'parse-worker': 'src/parse-worker.ts' },+ unbundle: false,+ format: 'esm',+ dts: true,+ clean: false,+ minify: true,+ plugins: sharedPlugins,+ inputOptions: sharedInputOptions,+ deps: {+ neverBundle: nativeAddonNeverBundle,+ alwaysBundle: alwaysBundlePureJsDeps,+ },+ },+ {+ // Library entry (package export "."). Same inlining as the standalone+ // build EXCEPT yjs, which stays a bare `import 'yjs'` so every consumer+ // process resolves the one copy in its node_modules — the desktop's+ // main/utility processes then share that copy with+ // `@inkeep/open-knowledge-server` and yjs's singleton stays intact.+ // Backed by `yjs` in package.json `dependencies`.+ entry: { index: 'src/index.ts' },+ unbundle: false,+ format: 'esm',+ dts: true,+ clean: false,+ minify: true,+ plugins: sharedPlugins,+ inputOptions: sharedInputOptions,+ deps: {+ neverBundle: [...nativeAddonNeverBundle, 'yjs'],+ alwaysBundle: alwaysBundlePureJsDeps.filter((re) => !re.test('yjs')),+ },},-});+]);diff --git a/packages/desktop/build/installer.nsh b/packages/desktop/build/installer.nshindex 85ca5a878..d3fdf86bc 100644--- a/packages/desktop/build/installer.nsh+++ b/packages/desktop/build/installer.nsh@@ -38,6 +38,17 @@!define OK_CLI_BIN_SUFFIX "resources\cli\bin"!macro customInstall+ ; ---- drop the differential-update seed copy (~250 MB, inert) ----+ ; app-builder-lib's installer template copies this installer to+ ; $LOCALAPPDATA\<updaterCacheDirName>\installer.exe on every install+ ; (templates/nsis/include/installer.nsh, inside installApplicationFiles,+ ; which runs BEFORE customInstall) solely as the base a *differential*+ ; update would patch against. This build ships differentialPackage: false+ ; (mandatory for useZip — see electron-builder.yml), so the copy can never+ ; be consumed; delete it right after it lands. KEEP IN LOCK-STEP: if+ ; differentialPackage is ever re-enabled, this Delete must go.+ Delete "$LOCALAPPDATA\${APP_INSTALLER_STORE_FILE}"+; ---- user PATH append (idempotent) ----ReadRegStr $0 HKCU "Environment" "Path"; Normalize a pre-existing trailing ";" so the append below never writesdiff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.ymlindex a7fddff82..73643b65c 100644--- a/packages/desktop/electron-builder.yml+++ b/packages/desktop/electron-builder.yml@@ -445,6 +445,11 @@ nsis:# Windows (no Windows release channel exists yet to regress), and the# installer grows ~37% (deflate vs solid LZMA; 169 MB → 232 MB arm64).useZip: true+ # KEEP IN LOCK-STEP with build/installer.nsh customInstall: because+ # differential packaging is off, the installer's self-copy to+ # $LOCALAPPDATA\<updaterCacheDirName>\installer.exe (the differential-update+ # seed) is inert and installer.nsh deletes it. Re-enabling+ # differentialPackage requires removing that Delete in the same change.differentialPackage: false# Separate per-arch installers (the default single universal installer# would double the download for every user). Version-less artifact namesdiff --git a/packages/desktop/src/main/auto-updater.ts b/packages/desktop/src/main/auto-updater.tsindex 5e435d769..a454ae0e0 100644--- a/packages/desktop/src/main/auto-updater.ts+++ b/packages/desktop/src/main/auto-updater.ts@@ -31,6 +31,11 @@ import type { IpcMain, IpcMainInvokeEvent } from 'electron';import type { EventChannels } from '../shared/ipc-events.ts';import { createHandler } from '../shared/ipc-handler.ts';import { type SendableWebContents, sendToRenderer } from '../shared/ipc-send.ts';+import {+ classifyInstallFailure,+ type LinuxManualInstallContext,+ manualInstallPlanFor,+} from './linux-install-fallback.ts';import type { AppState, UpdateChannel } from './state-store.ts';/** GitHub provider coordinates — must match `electron-builder.yml` `publish:`. */@@ -89,7 +94,10 @@ export interface UpdaterLike {event: 'download-progress',listener: (info: { percent?: number; bytesPerSecond?: number }) => void,): this;- on(event: 'update-downloaded', listener: (info: { version?: string }) => void): this;+ on(+ event: 'update-downloaded',+ listener: (info: { version?: string; downloadedFile?: string }) => void,+ ): this;on(event: 'error', listener: (err: Error & { code?: string }) => void): this;off(event: string, listener: (...args: unknown[]) => void): this;checkForUpdates(): Promise<unknown>;@@ -139,7 +147,10 @@ export type DispatchKind =| 'install-failed-on-boot'| 'install-failed-giveup'| 'attempted-install-cross-channel'- | 'cross-channel-blocked';+ | 'cross-channel-blocked'+ | 'staged-cache-reclaimed'+ | 'linux-manual-fallback-no-auth'+ | 'linux-manual-fallback-after-error';interface StartAutoUpdaterOpts {updater: UpdaterLike;@@ -233,6 +244,55 @@ interface StartAutoUpdaterOpts {* shutdown (SIGTERM → poll → SIGKILL) can complete cleanly.*/prepareForRelaunch?: () => void | Promise<void>;+ /**+ * Reclaim electron-updater's staged-installer cache (`pending/` under the+ * updater cache dir). Invoked once per boot, from the reconciliation+ * section, ONLY when no install commitment remains armed — i.e.+ * `versionPendingInstall` and `attemptedInstall` are both null after+ * reconciliation and the boot did not just give up on a failing install.+ * That timing is load-bearing: a staged-but-uncommitted update (the Linux+ * download-then-quit shape) and a failed or dismissed install must keep+ * their installer on disk — the Linux manual-install fallback hands the+ * user a command that points into that cache. electron-updater itself only+ * empties `pending/` when a DIFFERENT version is later downloaded, so+ * without this hook the installer for the version already running sits+ * there (~250 MB) until the next release. Production passes+ * `reclaimPendingUpdateCache` (packaged builds only); errors are logged+ * and swallowed — reclaim must never break boot.+ */+ reclaimStagedUpdateCache?: () => undefined | Promise<unknown>;+ /**+ * Linux-only manual-install fallback surface. The Linux installers run a+ * BLOCKING privileged package install inside `quitAndInstall()` behind a+ * graphical auth wrapper (pkexec + a PolicyKit agent, gksudo, …); on+ * minimal desktops with no such wrapper, electron-updater falls back to+ * terminal `sudo`, which cannot prompt in a GUI launch. When provided:+ *+ * - `hasGraphicalAuth` preflights the "Relaunch now" click. If it+ * reports false (and the staged installer is a recognized package),+ * `quitAndInstall()` is skipped entirely and+ * `showManualInstallFallback` fires instead, with the staged state+ * left armed so the update survives dismissal and relaunch.+ * - An install that DID run but failed with anything other than an+ * explicit user cancellation (pkexec exit 126) also triggers the+ * fallback, after the normal `failRelaunch` window recovery.+ *+ * Production wires `showManualInstallFallback` to the dismissible+ * Copy-command / Relaunch / Not-now dialog in+ * `linux-install-fallback.ts`. Never set on other platforms.+ */+ linuxInstallSupport?: {+ hasGraphicalAuth: () => boolean;+ showManualInstallFallback: (ctx: LinuxManualInstallContext) => undefined | Promise<unknown>;+ /**+ * Existence check for the persisted staged-installer path — state can+ * outlive the file (a hand-cleared cache). Production passes an+ * `existsSync` wrapper; optional so unit fixtures keep the pre-check+ * behavior. A missing file falls through to the default+ * electron-updater path instead of offering a command that would fail.+ */+ stagedInstallerExists?: (path: string) => boolean;+ };/*** Surface the result of a menu-driven `Check for Updates…` click. The* periodic hourly check stays silent on a no-change outcome so users@@ -596,6 +656,8 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHafeedUrl,proxyFeed,whenRendererReady,+ reclaimStagedUpdateCache,+ linuxInstallSupport,showCheckNowResult,clock = DEFAULT_CLOCK,now = () => new Date(),@@ -871,6 +933,59 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHawatchdog: ReturnType<typeof setTimeout>;} | null = null;+ // Absolute path of the staged installer. Captured in-session from+ // electron-updater's `update-downloaded` payload (`downloadedFile`) and+ // persisted alongside `versionPendingInstall`, then re-seeded from state at+ // boot (after the reconciliation below) — the standard Linux flow is+ // download, quit, boot, click Relaunch, and the banner becomes clickable+ // long before the launch check re-validates the ~250 MB cache (full sha512)+ // and re-emits the path. Feeds the Linux manual-install fallback command.+ let stagedInstallerPath: string | null = null;++ /**+ * The staged installer path, filtered through the injected existence check+ * (persisted state can outlive the file — e.g. a cache cleared by hand).+ * Null when unknown or missing on disk; callers then fall through to the+ * default electron-updater path.+ */+ const usableStagedInstallerPath = (): string | null => {+ if (stagedInstallerPath === null) return null;+ const exists = linuxInstallSupport?.stagedInstallerExists;+ if (exists && !exists(stagedInstallerPath)) return null;+ return stagedInstallerPath;+ };++ /**+ * Offer the Linux manual-install fallback for `version` if the platform,+ * wiring, and staged-installer shape allow it. Returns true when the+ * dialog was dispatched (fire-and-forget — the dialog runs for as long as+ * the user keeps it open). Shared by the two triggers: the no-auth+ * preflight in `relaunch-now` and the infrastructure-classified install+ * failure in `onError`.+ */+ const offerManualInstallFallback = (version: string, kind: DispatchKind): boolean => {+ if (platform !== 'linux' || !linuxInstallSupport) return false;+ const installerPath = usableStagedInstallerPath();+ const plan = manualInstallPlanFor(installerPath);+ if (!plan || installerPath === null) return false;+ logger.warn('offering manual-install fallback', {+ version,+ packageKind: plan.packageKind,+ trigger: kind,+ });+ onDispatch?.(kind);+ void Promise.resolve(+ linuxInstallSupport.showManualInstallFallback({+ version,+ installerPath,+ ...plan,+ }),+ ).catch((err: unknown) => {+ logger.error('manual-install fallback dialog failed', { err });+ });+ return true;+ };+/*** Single failure routine for all three relaunch-failure triggers — the* synchronous `quitAndInstall()` throw, the in-flight updater `error`@@ -1079,8 +1194,13 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa});};- const onUpdateDownloaded = (info: { version?: string }): void => {+ const onUpdateDownloaded = (info: { version?: string; downloadedFile?: string }): void => {logger.info('update-downloaded', { version: info.version });+ // Track the staged file even when the dispatch below dedupes or skips —+ // the file exists on disk regardless, and the Linux fallback needs it.+ if (typeof info.downloadedFile === 'string' && info.downloadedFile !== '') {+ stagedInstallerPath = info.downloadedFile;+ }const version = typeof info.version === 'string' ? info.version : '';if (!version) {logger.warn('update-downloaded with empty version — skipping dispatch');@@ -1119,6 +1239,10 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa{...state,versionPendingInstall: version,+ // Persist the staged path with the banner gate so the Linux+ // fallback can build its command on the next boot, before the+ // launch check re-validates the cache (see the AppState field doc).+ stagedInstallerPath,...(installCommittedAtDownload? {attemptedInstall: version,@@ -1195,12 +1319,25 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa// independently an updater error in the operator log);// 'relaunch-error-event' reports the recovery, not a replacement.if (relaunchInFlight) {+ const failedVersion = relaunchInFlight.version;+ // On Linux, tell an explicit user cancellation of the auth prompt+ // (pkexec exit 126) apart from authorization infrastructure that+ // cannot work (no agent, sudo-without-tty, …). Cancellation keeps the+ // existing recovery only — the user knows what they clicked; the+ // banner re-arms for another try. Infrastructure failures additionally+ // offer the manual-install fallback after the recovery lands.+ const failureClass = platform === 'linux' ? classifyInstallFailure(err.message) : null;failRelaunch(- relaunchInFlight.version,- err.message || 'update error during relaunch',+ failedVersion,+ failureClass === 'cancelled'+ ? 'authorization was cancelled'+ : err.message || 'update error during relaunch','relaunch-error-event',{ code: err.code, stack: err.stack },);+ if (failureClass === 'infrastructure') {+ offerManualInstallFallback(failedVersion, 'linux-manual-fallback-after-error');+ }}if (menuCheckPending) {menuCheckPending = false;@@ -1262,6 +1399,26 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHareturn undefined;}const pending = snapshot.versionPendingInstall;+ // Linux preflight: with no graphical auth wrapper on PATH,+ // `quitAndInstall()` would route through terminal `sudo` — no usable+ // prompt in a GUI session, guaranteed failure. Skip the attempt+ // entirely: leave `versionPendingInstall` armed (the staged update must+ // survive dismissal, a premature relaunch, and the next boot), restore+ // the clicked window's banner (it swapped to "Relaunching…" locally on+ // click; the re-broadcast is a same-id in-place replace), and hand the+ // user the manual-install dialog instead. Only when the staged installer+ // is a recognized package — otherwise fall through and let+ // electron-updater report whatever it can.+ if (+ platform === 'linux' &&+ linuxInstallSupport &&+ manualInstallPlanFor(usableStagedInstallerPath()) !== null &&+ !linuxInstallSupport.hasGraphicalAuth()+ ) {+ broadcastToAllWindows('ok:update:downloaded', { version: pending });+ offerManualInstallFallback(pending, 'linux-manual-fallback-no-auth');+ return undefined;+ }// Double-invoke guard: clear the state gate// BEFORE calling `quitAndInstall()` so a second IPC fire (rapid// double-click on Toast A's "Relaunch now" — sonner doesn't debounce@@ -1411,7 +1568,7 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa// a genuinely-pending update armed rather than dropping it on garbage.if (state.versionPendingInstall && versionAtLeast(currentVersion, state.versionPendingInstall)) {const cleared = state.versionPendingInstall;- const next = { ...state, versionPendingInstall: null };+ const next = { ...state, versionPendingInstall: null, stagedInstallerPath: null };if (persistSafely(next, 'stale-pending-cleared')) {state = next;logger.info('cleared stale versionPendingInstall — running has caught up', {@@ -1432,6 +1589,12 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa// never fire, leaving the next boot as the only detection point. Uses the// prerelease-aware `installReached` (not the MMP-only `versionAtLeast`) so a// same-major.minor.patch beta bump is not misread as "caught up".+ // True when THIS boot exhausted the failed-install surfacing budget and+ // dropped the record. Blocks the staged-cache reclaim below for one boot:+ // the giveup clears both state gates, but the user may still be acting on+ // the failure notice (e.g. running the Linux manual-install command against+ // the staged installer).+ let installGaveUpThisBoot = false;if (state.attemptedInstall) {const attempted = state.attemptedInstall;if (installReached(currentVersion, attempted)) {@@ -1474,6 +1637,7 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHaattemptedInstall: null,attemptedInstallSurfacedCount: 0,versionPendingInstall: null,+ stagedInstallerPath: null,};if (persistSafely(next, 'attempted-install-cross-channel')) {state = next;@@ -1503,9 +1667,11 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHaattemptedInstall: null,attemptedInstallSurfacedCount: 0,versionPendingInstall: null,+ stagedInstallerPath: null,};if (persistSafely(next, 'install-failed-giveup')) {state = next;+ installGaveUpThisBoot = true;logger.warn('attempted install exhausted its retry budget — clearing record', {attempted,running: currentVersion,@@ -1612,6 +1778,51 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa}}+ // ————————————————————————————————————————————————————————+ // Staged-cache reclaim — strictly after the reconciliation above+ // ————————————————————————————————————————————————————————++ // Seed the in-memory staged-installer path from the reconciled state: the+ // reconciliation above already nulled it wherever the staged update+ // stopped being live, so what survives here is a genuinely-pending+ // installer the Linux fallback may need before the launch check re-emits+ // update-downloaded from cache.+ stagedInstallerPath = state.stagedInstallerPath;++ // With every install commitment settled (no pending banner to restore, no+ // failed install being surfaced or retried), the staged installer in+ // electron-updater's `pending/` cache has no remaining job: either it+ // installed (this boot runs it) or nothing was ever staged. Any armed gate+ // means the file may still be needed — the Linux "Relaunch" path, the+ // manual-install fallback command, and the boot failure notice's Retry all+ // consume it — so reclaim is skipped and re-evaluated next boot.+ //+ // When a reclaim dispatched, the launch check below chains off this+ // promise so the recursive delete of `pending/` can never race a fresh+ // download re-creating the directory. Null when no reclaim ran — the+ // launch check then fires with its usual immediate timing. Never rejects.+ let reclaimSettled: Promise<void> | null = null;+ if (+ reclaimStagedUpdateCache &&+ state.versionPendingInstall === null &&+ state.attemptedInstall === null &&+ !installGaveUpThisBoot+ ) {+ try {+ reclaimSettled = Promise.resolve(reclaimStagedUpdateCache()).then(+ () => undefined,+ (err: unknown) => {+ logger.warn('staged-update cache reclaim failed', { err });+ },+ );+ // Dispatch records "reclaim branch taken", not "rm settled" — matching+ // the module-wide onDispatch convention; the failure path only logs.+ onDispatch?.('staged-cache-reclaimed');+ } catch (err) {+ logger.warn('staged-update cache reclaim threw synchronously', { err });+ }+ }+// ————————————————————————————————————————————————————————// Launch check + periodic timer (hourly + jitter)// ————————————————————————————————————————————————————————@@ -1653,7 +1864,7 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHascheduleNextCheck();};- if (updatesEnabled) {+ const runLaunchCheck = (): void => {void updater.checkForUpdates().then(() => {@@ -1668,6 +1879,16 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa// Still start the timer — the next fire may succeed.startPeriodicChecks();});+ };++ if (updatesEnabled) {+ if (reclaimSettled) {+ // Sequenced after the reclaim so the boot-time delete of `pending/`+ // cannot interleave with a fresh download re-creating it.+ void reclaimSettled.then(runLaunchCheck);+ } else {+ runLaunchCheck();+ }} else {logger.info('skipping checkForUpdates — app.isPackaged=false and OK_UPDATER_FORCE_DEV unset (handlers remain wired for tests + IPC)',diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 8456e597a..625853511 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -292,6 +292,10 @@ import {} from './ipc-handlers.ts';import { logIpcError } from './ipc-log.ts';import { createDesktopKeepaliveFactory, toKeepaliveLogger } from './keepalive.ts';+import {+ detectGraphicalAuthCommand,+ runManualInstallFallbackDialog,+} from './linux-install-fallback.ts';import { createMenuTranslator, resolveMenuCatalogDir } from './main-i18n.ts';import {checkAndRepairMcpWiringOnStartup,@@ -337,6 +341,7 @@ import {} from './reduced-transparency-handler.ts';import { removeGitFolder } from './remove-git-folder.ts';import { attachRendererConsoleCapture } from './renderer-console-capture.ts';+import { createRendererReadySink, type RendererReadySink } from './renderer-ready-sink.ts';import { createRendererRecovery, type RendererRecovery } from './renderer-recovery.ts';import { resolveDetachedSpawnArgs } from './resolve-detached-spawn-args.ts';import { resolveShareTarget as resolveShareTargetMain } from './resolve-share-target.ts';@@ -420,6 +425,7 @@ import {applyStateQuery,type UpdateStateHandlerDeps,} from './update-state-handlers.ts';+import { reclaimPendingUpdateCache } from './updater-cache.ts';import {registerProtocolHandler,type ScreenTarget,@@ -1174,6 +1180,19 @@ let debugIpc: DebugIpcHandle | null = null;* when the wiring no-ops (marker present, dev mode, non-macOS, etc.).*/let mcpWiringHandle: RunMcpWiringHandle | null = null;+/**+ * Permanent sink for the preload's fire-and-forget `*:renderer-ready`+ * mount-ack invokes. Every renderer fires them at module init, but the+ * consent flows that consume them are armed only transiently — without a+ * standing handler, every other packaged boot logs Electron's+ * "No handler registered for 'ok:…:renderer-ready'" error to stderr. Created+ * at the top of `bootPrimaryInstance` (before any window can mount a+ * renderer); the consent flows receive its facade instead of the raw+ * `ipcMain` so their one-shot register/removeHandler lifecycles arm and+ * disarm inside the sink. Null only in the duplicate-instance and+ * driver-smoke boot paths, where the flows never arm.+ */+let rendererReadySink: RendererReadySink | null = null;/*** First-party crash detection (local-only crash reporter, process-gone* listeners, boot-time dirty-shutdown/minidump scan). Created at the top of@@ -2087,7 +2106,9 @@ async function openProject(};const decision = await requestUserConsent({- ipcMain,+ // Sink facade, not the raw ipcMain: the flow's one-shot renderer-ready+ // handler arms inside the sink so unarmed acks stay absorbed.+ ipcMain: rendererReadySink?.ipcMain ?? ipcMain,navigator: (navigator as unknown as { webContents: Electron.WebContents }).webContents,previewContent,},@@ -3879,7 +3900,9 @@ function createMcpWiringOpts(opts: ArmMcpWiringOpts = {}) {executablePath: app.getPath('exe'),home: osHomedir(),platform: process.platform,- ipcMain,+ // Sink facade, not the raw ipcMain: the flow's one-shot renderer-ready+ // handler arms inside the sink so unarmed acks stay absorbed.+ ipcMain: rendererReadySink?.ipcMain ?? ipcMain,cli: createMcpWiringCliSurface(),// PATH leg of the first-launch consent dialog: descriptor for the show// payload + the confirm-path finalizer. `applyConsent` reuses the exact@@ -6494,6 +6517,20 @@ function bootPrimaryInstance(): void {'desktop main process starting',);+ // Stand up the renderer-ready mount-ack sink before anything can open a+ // window: the preload invokes `ok:mcp-wiring:renderer-ready` /+ // `ok:onboarding:renderer-ready` on every renderer mount, and the sink's+ // permanent handlers are what keep an unarmed boot from logging Electron's+ // "No handler registered" error for each ack.+ rendererReadySink = createRendererReadySink(+ ipcMain,+ ['ok:mcp-wiring:renderer-ready', 'ok:onboarding:renderer-ready'],+ {+ debug: (msg, ctx) => getLogger('renderer-ready-sink').debug(ctx ?? {}, msg),+ warn: (msg, ctx) => getLogger('renderer-ready-sink').warn(ctx ?? {}, msg),+ },+ );+// Crash handling is strictly local: Crashpad writes minidumps under// `app.getPath('crashDumps')` and uploads nothing. Started before any// window so every child process inherits coverage, then the boot-time scan@@ -7488,6 +7525,72 @@ function bootPrimaryInstance(): void {tryFire(createdWin as BrowserWindow);});},+ // Linux manual-install fallback: when no graphical auth wrapper+ // exists (or the automatic install fails for an infrastructure+ // reason), the updater offers a dismissible dialog with a copyable+ // shell-safe package-manager command instead of a doomed+ // terminal-sudo attempt. The dialog re-shows after "Copy Command" so+ // Relaunch / Not now stay reachable; Relaunch is unconditional.+ ...(process.platform === 'linux'+ ? {+ linuxInstallSupport: {+ hasGraphicalAuth: () => detectGraphicalAuthCommand() !== null,+ stagedInstallerExists: (p) => {+ try {+ return existsSync(p);+ } catch {+ return false;+ }+ },+ showManualInstallFallback: async (ctx) => {+ await runManualInstallFallbackDialog(+ {+ showDialog: async (request) => {+ const target =+ BrowserWindow.getFocusedWindow() ??+ BrowserWindow.getAllWindows()[0] ??+ null;+ const options = { type: 'info' as const, ...request };+ // Unlike the check-now dialogs, show even with no+ // window — this is the only surface telling the user+ // why their update cannot install.+ return target+ ? dialog.showMessageBox(target, options)+ : dialog.showMessageBox(options);+ },+ copyCommandToClipboard: (command) => clipboard.writeText(command),+ relaunchApp: () => {+ app.relaunch();+ app.quit();+ },+ },+ ctx,+ );+ },+ },+ }+ : {}),+ // Reclaim electron-updater's staged-installer cache once the boot+ // reconciliation proves no install commitment remains armed (the+ // timing contract lives on the `reclaimStagedUpdateCache` opt).+ // Packaged builds only: dev builds ship no app-update.yml, and a+ // guessed path is nothing to aim a recursive delete at.+ ...(app.isPackaged+ ? {+ reclaimStagedUpdateCache: () =>+ reclaimPendingUpdateCache({+ appUpdateConfigPath: join(process.resourcesPath, 'app-update.yml'),+ platform: process.platform,+ env: process.env,+ homeDir: osHomedir(),+ logger: {+ info: (msg, ctx) => getLogger('updater-cache').info(ctx ?? {}, msg),+ warn: (msg, ctx) => getLogger('updater-cache').warn(ctx ?? {}, msg),+ debug: (msg, ctx) => getLogger('updater-cache').debug(ctx ?? {}, msg),+ },+ }),+ }+ : {}),// Pre-relaunch teardown — synchronously hard-kill every project-window// utility (Hocuspocus host) right before// `autoUpdater.quitAndInstall()` so Squirrel.Mac's `pgrep` against@@ -7704,6 +7807,10 @@ function bootPrimaryInstance(): void {bundleReplaceWatcherHandle = null;mcpWiringHandle?.destroy();mcpWiringHandle = null;+ // After the flows (which disarm through its facade), drop the sink's+ // permanent renderer-ready handlers.+ rendererReadySink?.destroy();+ rendererReadySink = null;// Final drain so the lifecycle + teardown lines reach disk before exit// (the destination is `sync: false`).flushDesktopLogger();diff --git a/packages/desktop/src/main/linux-install-fallback.test.ts b/packages/desktop/src/main/linux-install-fallback.test.tsnew file mode 100644index 000000000..977b48201--- /dev/null+++ b/packages/desktop/src/main/linux-install-fallback.test.ts@@ -0,0 +1,265 @@+import { describe, expect, test, vi } from 'vitest';+import {+ classifyInstallFailure,+ detectGraphicalAuthCommand,+ GRAPHICAL_AUTH_COMMANDS,+ hasCommandOnPath,+ type LinuxManualInstallContext,+ type ManualInstallDialogDeps,+ type ManualInstallDialogRequest,+ manualInstallPlanFor,+ runManualInstallFallbackDialog,+ shellSingleQuote,+} from './linux-install-fallback.ts';++describe('shellSingleQuote', () => {+ test('wraps plain paths', () => {+ expect(shellSingleQuote('/tmp/pkg.deb')).toBe("'/tmp/pkg.deb'");+ });++ test('spaces, $, backticks, semicolons, newlines are inert inside single quotes', () => {+ expect(shellSingleQuote('/tmp/my pkgs/$(rm -rf ~)/a;b`c\nd.deb')).toBe(+ "'/tmp/my pkgs/$(rm -rf ~)/a;b`c\nd.deb'",+ );+ });++ test('embedded single quotes re-quote safely', () => {+ expect(shellSingleQuote("/tmp/o'brien.deb")).toBe("'/tmp/o'\\''brien.deb'");+ });+});++describe('manualInstallPlanFor', () => {+ test('deb → sudo apt install with option-parsing stop', () => {+ expect(manualInstallPlanFor('/cache/pending/ok_0.48.0_arm64.deb')).toEqual({+ packageKind: 'deb',+ command: "sudo apt install -- '/cache/pending/ok_0.48.0_arm64.deb'",+ });+ });++ test('rpm → sudo dnf install', () => {+ expect(manualInstallPlanFor('/cache/pending/ok-0.48.0.x86_64.rpm')).toEqual({+ packageKind: 'rpm',+ command: "sudo dnf install '/cache/pending/ok-0.48.0.x86_64.rpm'",+ });+ });++ test('extension match is case-insensitive', () => {+ expect(manualInstallPlanFor('/x/OK.DEB')?.packageKind).toBe('deb');+ });++ test('unknown format and missing path return null', () => {+ expect(manualInstallPlanFor('/x/OpenKnowledge.AppImage')).toBeNull();+ expect(manualInstallPlanFor(null)).toBeNull();+ expect(manualInstallPlanFor('')).toBeNull();+ });++ test('arbitrary paths are quoted, and no trust-bypass flags ever appear', () => {+ const hostile = "/tmp/a b'; rm -rf ~ #/pkg.deb";+ const plan = manualInstallPlanFor(hostile);+ expect(plan?.command).toBe(`sudo apt install -- ${shellSingleQuote(hostile)}`);+ for (const path of [hostile, '/plain/pkg.deb', '/plain/pkg.rpm']) {+ const command = manualInstallPlanFor(path)?.command ?? '';+ expect(command).not.toContain('--allow-unauthenticated');+ expect(command).not.toContain('--nogpgcheck');+ }+ });+});++describe('classifyInstallFailure', () => {+ test('pkexec exit 126 (user dismissed the auth dialog) → cancelled', () => {+ expect(classifyInstallFailure('Command pkexec exited with code 126')).toBe('cancelled');+ });++ test('exit 127 (authorization unobtainable / no agent) → infrastructure', () => {+ expect(classifyInstallFailure('Command pkexec exited with code 127')).toBe('infrastructure');+ });++ test('sudo no-tty and unrecognized shapes → infrastructure', () => {+ expect(classifyInstallFailure('Command sudo exited with code 1')).toBe('infrastructure');+ expect(classifyInstallFailure('spawn ENOENT')).toBe('infrastructure');+ expect(classifyInstallFailure(undefined)).toBe('infrastructure');+ });++ test('126 must be the whole exit code, not a prefix', () => {+ expect(classifyInstallFailure('Command pkexec exited with code 1260')).toBe('infrastructure');+ });+});++describe('detectGraphicalAuthCommand', () => {+ test('returns the first wrapper found in electron-updater probe order', () => {+ expect(detectGraphicalAuthCommand((cmd) => cmd === 'pkexec')).toBe('pkexec');+ expect(detectGraphicalAuthCommand((cmd) => cmd === 'kdesudo' || cmd === 'beesu')).toBe(+ 'kdesudo',+ );+ });++ test('returns null when nothing is available (plain sudo does not count)', () => {+ expect(detectGraphicalAuthCommand(() => false)).toBeNull();+ });++ test('each probe gets the remaining shared budget, capped at the per-probe ceiling', () => {+ const timeouts: number[] = [];+ // Clock advances 1500ms per probe: remaining budget shrinks 4000 → 2500+ // → 1000, so the third probe gets less than the 2000ms ceiling.+ let clock = 0;+ const now = () => clock;+ const hasCommand = vi.fn((_cmd: string, timeoutMs: number) => {+ timeouts.push(timeoutMs);+ clock += 1500;+ return false;+ });+ expect(detectGraphicalAuthCommand(hasCommand, now)).toBeNull();+ expect(timeouts).toEqual([2000, 2000, 1000]);+ // The fourth wrapper is never probed — the budget was spent.+ expect(hasCommand).toHaveBeenCalledTimes(3);+ });++ test('budget exhaustion mid-sweep stops probing instead of serially blocking', () => {+ let clock = 0;+ const now = () => clock;+ const hasCommand = vi.fn((_cmd: string, _timeoutMs: number) => {+ clock += 5000;+ return false;+ });+ expect(detectGraphicalAuthCommand(hasCommand, now)).toBeNull();+ expect(hasCommand).toHaveBeenCalledTimes(1);+ });++ test('probe list matches electron-updater determineSudoCommand', () => {+ expect([...GRAPHICAL_AUTH_COMMANDS]).toEqual(['gksudo', 'kdesudo', 'pkexec', 'beesu']);+ });+});++describe('hasCommandOnPath', () => {+ test('probes via `command -v` through a shell (load-bearing: `command` is a shell built-in)', () => {+ const spy = vi.fn().mockReturnValue({ error: null, status: 0 });+ expect(hasCommandOnPath('pkexec', spy as never)).toBe(true);+ // Single command string, no args array: args + `shell: true` trips+ // Node's DEP0190 deprecation warning on every probe.+ expect(spy).toHaveBeenCalledWith(+ 'command -v pkexec',+ expect.objectContaining({ shell: true, timeout: 2000 }),+ );+ });++ test('refuses to probe non-bare command names (interpolation guard)', () => {+ const spy = vi.fn().mockReturnValue({ error: null, status: 0 });+ for (const hostile of ['pk exec', 'pkexec; rm -rf ~', '$(reboot)', '`id`', 'a|b', '']) {+ expect(hasCommandOnPath(hostile, spy as never)).toBe(false);+ }+ expect(spy).not.toHaveBeenCalled();+ });++ test('status 0 → true, non-zero → false, spawn error → false', () => {+ expect(+ hasCommandOnPath('x', vi.fn().mockReturnValue({ error: null, status: 0 }) as never),+ ).toBe(true);+ expect(+ hasCommandOnPath('x', vi.fn().mockReturnValue({ error: null, status: 1 }) as never),+ ).toBe(false);+ expect(+ hasCommandOnPath(+ 'x',+ vi.fn().mockReturnValue({ error: new Error('ENOENT'), status: null }) as never,+ ),+ ).toBe(false);+ expect(+ hasCommandOnPath(+ 'x',+ vi.fn(() => {+ throw new Error('spawn failed');+ }) as never,+ ),+ ).toBe(false);+ });+});++describe('runManualInstallFallbackDialog', () => {+ const ctx: LinuxManualInstallContext = {+ version: '0.48.0',+ installerPath: '/cache/pending/ok.deb',+ packageKind: 'deb',+ command: "sudo apt install -- '/cache/pending/ok.deb'",+ };++ function makeDeps(responses: number[]): ManualInstallDialogDeps & {+ shown: ReturnType<typeof vi.fn>;+ copied: ReturnType<typeof vi.fn>;+ relaunched: ReturnType<typeof vi.fn>;+ } {+ const queue = [...responses];+ const shown = vi.fn(async (_request: ManualInstallDialogRequest) => ({+ response: queue.shift() ?? 2,+ }));+ const copied = vi.fn();+ const relaunched = vi.fn();+ return {+ shown,+ copied,+ relaunched,+ showDialog: shown,+ copyCommandToClipboard: copied,+ relaunchApp: relaunched,+ };+ }++ test('Not now dismisses without copying or relaunching', async () => {+ const deps = makeDeps([2]);+ await expect(runManualInstallFallbackDialog(deps, ctx)).resolves.toBe('dismissed');+ expect(deps.copied).not.toHaveBeenCalled();+ expect(deps.relaunched).not.toHaveBeenCalled();+ expect(deps.shown).toHaveBeenCalledTimes(1);+ });++ test('Copy Command copies the exact command and re-shows the dialog', async () => {+ const deps = makeDeps([0, 0, 2]);+ await expect(runManualInstallFallbackDialog(deps, ctx)).resolves.toBe('dismissed');+ expect(deps.copied).toHaveBeenCalledTimes(2);+ expect(deps.copied).toHaveBeenCalledWith(ctx.command);+ expect(deps.shown).toHaveBeenCalledTimes(3);+ });++ test('Relaunch is unconditional — fires without any install confirmation', async () => {+ const deps = makeDeps([1]);+ await expect(runManualInstallFallbackDialog(deps, ctx)).resolves.toBe('relaunch');+ expect(deps.relaunched).toHaveBeenCalledTimes(1);+ });++ test('copy-then-relaunch keeps both effects', async () => {+ const deps = makeDeps([0, 1]);+ await expect(runManualInstallFallbackDialog(deps, ctx)).resolves.toBe('relaunch');+ expect(deps.copied).toHaveBeenCalledWith(ctx.command);+ expect(deps.relaunched).toHaveBeenCalledTimes(1);+ });++ test('a dialog rejection mid-loop (parent window destroyed) resolves as dismissal', async () => {+ const copied = vi.fn();+ const relaunched = vi.fn();+ let calls = 0;+ const deps: ManualInstallDialogDeps = {+ showDialog: async () => {+ calls += 1;+ if (calls === 1) return { response: 0 };+ throw new Error('Object has been destroyed');+ },+ copyCommandToClipboard: copied,+ relaunchApp: relaunched,+ };+ await expect(runManualInstallFallbackDialog(deps, ctx)).resolves.toBe('dismissed');+ expect(copied).toHaveBeenCalledWith(ctx.command);+ expect(relaunched).not.toHaveBeenCalled();+ });++ test('dialog copy shows the command and offers the three actions', async () => {+ const deps = makeDeps([2]);+ await runManualInstallFallbackDialog(deps, ctx);+ const request = deps.shown.mock.calls[0]?.[0] as {+ detail: string;+ buttons: string[];+ cancelId: number;+ };+ expect(request.detail).toContain(ctx.command);+ expect(request.buttons).toEqual(['Copy Command', 'Relaunch OpenKnowledge', 'Not Now']);+ expect(request.cancelId).toBe(2);+ });+});diff --git a/packages/desktop/src/main/linux-install-fallback.ts b/packages/desktop/src/main/linux-install-fallback.tsnew file mode 100644index 000000000..0537ec27f--- /dev/null+++ b/packages/desktop/src/main/linux-install-fallback.ts@@ -0,0 +1,247 @@+/**+ * Linux manual-install fallback — the escape hatch for desktops where+ * electron-updater cannot obtain graphical administrator authorization.+ *+ * The normal Linux install path runs a BLOCKING privileged package install+ * inside `quitAndInstall()`, wrapped by whichever graphical auth command+ * electron-updater finds (pkexec via a PolicyKit agent, gksudo, kdesudo,+ * beesu — `LinuxUpdater.determineSudoCommand`). When none exists it falls+ * back to terminal-oriented `sudo`, which has no way to prompt in an+ * ordinary GUI launch — the install just fails. This module supplies the+ * pieces the auto-updater uses to (a) detect that shape up front, (b) tell+ * a user-cancelled auth prompt apart from broken/missing auth+ * infrastructure, and (c) hand the user a copyable, shell-safe package+ * manager command targeting the already-downloaded installer.+ *+ * Deliberately NOT here (locked scope): spawning a terminal, opening the+ * installer folder, polling package databases, or auto-detecting whether+ * the user actually installed — relaunch is unconditional and the old+ * version simply resumes showing the pending update if they didn't.+ */++import { spawnSync } from 'node:child_process';++type LinuxPackageKind = 'deb' | 'rpm';++export interface ManualInstallPlan {+ packageKind: LinuxPackageKind;+ /** Full user-facing command, shell-quoted, ready to paste into a terminal. */+ command: string;+}++/** Context handed to the dialog surface for one fallback offer. */+export interface LinuxManualInstallContext extends ManualInstallPlan {+ version: string;+ installerPath: string;+}++/**+ * POSIX single-quote escaping: wrap in `'…'`, embedded single quotes become+ * `'\''`. Handles every other shell metacharacter (spaces, `$`, backticks,+ * `;`, newlines) by construction — nothing is interpreted inside single+ * quotes.+ */+export function shellSingleQuote(value: string): string {+ return `'${value.replaceAll("'", "'\\''")}'`;+}++/**+ * Build the user-facing install command for a staged installer, or null when+ * the path is unknown or not a recognized package format (the caller then+ * stays on the default electron-updater path).+ *+ * Command shapes are deliberately minimal and safe to paste:+ * - deb: `sudo apt install -- '<path>'` — `--` stops option parsing so an+ * installer path can never be read as a flag; apt treats an argument+ * containing `/` as a local file.+ * - rpm: `sudo dnf install '<path>'`.+ * Neither includes `--allow-unauthenticated` / `--nogpgcheck` — a user+ * pasting our command must not have signature checking silently disabled.+ */+export function manualInstallPlanFor(installerPath: string | null): ManualInstallPlan | null {+ if (!installerPath) return null;+ const lower = installerPath.toLowerCase();+ if (lower.endsWith('.deb')) {+ return {+ packageKind: 'deb',+ command: `sudo apt install -- ${shellSingleQuote(installerPath)}`,+ };+ }+ if (lower.endsWith('.rpm')) {+ return {+ packageKind: 'rpm',+ command: `sudo dnf install ${shellSingleQuote(installerPath)}`,+ };+ }+ return null;+}++export type InstallFailureClass = 'cancelled' | 'infrastructure';++/**+ * Classify a failed Linux `quitAndInstall()`. pkexec exits 126 when the user+ * dismissed the authentication dialog and 127 when authorization could not+ * be obtained at all (no registered agent, policy denial, helper failure);+ * electron-updater surfaces the code in the thrown message+ * (`Command pkexec exited with code 126` — `BaseUpdater.spawnSyncLog`).+ * Everything that is not an explicit user dismissal counts as+ * infrastructure: the sudo-fallback "no tty" failure, agent-less 127s, and+ * unrecognized shapes all mean the automatic path cannot work as launched,+ * which is exactly when the manual command is the actionable next step.+ */+export function classifyInstallFailure(message: string | undefined): InstallFailureClass {+ if (message && /exited with code 126\b/.test(message)) return 'cancelled';+ return 'infrastructure';+}++/**+ * The graphical privilege-escalation wrappers electron-updater's+ * `determineSudoCommand` probes for (its order retained). If ANY is present+ * the automatic path is worth attempting; if none is, `quitAndInstall()`+ * would fall through to terminal `sudo` and fail without a usable prompt.+ */+export const GRAPHICAL_AUTH_COMMANDS = ['gksudo', 'kdesudo', 'pkexec', 'beesu'] as const;++/** Per-probe ceiling for one `command -v` spawn. */+const COMMAND_PROBE_TIMEOUT_MS = 2000;++/**+ * Total synchronous main-process budget for one `detectGraphicalAuthCommand`+ * sweep across all four wrappers — a pathological shell (NFS-stalled rc+ * file) times out per probe, and without a shared deadline four back-to-back+ * timeouts would block the UI for 4× the per-probe bound.+ */+const COMMAND_PROBE_TOTAL_BUDGET_MS = 4000;++/**+ * `command -v` probe through a shell, mirroring electron-updater's+ * `hasCommand` so our preflight agrees with what its installer would find.+ * The timeout bounds a pathological shell — this runs on the main process,+ * once per wrapper, on every "Relaunch now" click.+ *+ * The probe is a single command STRING: an args array combined with+ * `shell: true` trips Node's DEP0190 deprecation warning on every spawn+ * (Node >= 22.15) — the very warning class this module exists to remove+ * from packaged startup. Interpolating requires the shape guard below,+ * since this export could someday be fed something beyond the hardcoded+ * `GRAPHICAL_AUTH_COMMANDS`.+ */+export function hasCommandOnPath(+ cmd: string,+ spawn: typeof spawnSync = spawnSync,+ timeoutMs: number = COMMAND_PROBE_TIMEOUT_MS,+): boolean {+ if (!/^[A-Za-z0-9_.-]+$/.test(cmd)) {+ console.warn('[linux-install-fallback] refusing to probe a non-bare command name', { cmd });+ return false;+ }+ try {+ const result = spawn(`command -v ${cmd}`, {+ shell: true,+ stdio: 'ignore',+ timeout: timeoutMs,+ });+ return result.error == null && result.status === 0;+ } catch (err) {+ // A throw here (EACCES on the shell, ENOMEM) routes the user to the+ // manual-install dialog even when the wrapper exists — leave a trail.+ console.warn('[linux-install-fallback] command probe threw', { cmd, err });+ return false;+ }+}++/**+ * First graphical auth wrapper on PATH, or null when none is available.+ * Probes stop once the shared budget is spent: with a hung shell every+ * remaining probe would time out anyway, so the sweep degrades to "none+ * found" rather than serially blocking the main process on each wrapper.+ */+export function detectGraphicalAuthCommand(+ hasCommand: (cmd: string, timeoutMs: number) => boolean = (cmd, timeoutMs) =>+ hasCommandOnPath(cmd, spawnSync, timeoutMs),+ now: () => number = Date.now,+): string | null {+ const deadline = now() + COMMAND_PROBE_TOTAL_BUDGET_MS;+ for (const cmd of GRAPHICAL_AUTH_COMMANDS) {+ const remainingMs = deadline - now();+ if (remainingMs <= 0) {+ console.warn('[linux-install-fallback] auth-wrapper probe budget exhausted', { cmd });+ return null;+ }+ if (hasCommand(cmd, Math.min(COMMAND_PROBE_TIMEOUT_MS, remainingMs))) return cmd;+ }+ return null;+}++export interface ManualInstallDialogRequest {+ message: string;+ detail: string;+ buttons: string[];+ defaultId: number;+ cancelId: number;+}++export interface ManualInstallDialogDeps {+ /** Production: `dialog.showMessageBox(...)` parented to the active window. */+ showDialog: (request: ManualInstallDialogRequest) => Promise<{ response: number }>;+ /** Production: `clipboard.writeText`. */+ copyCommandToClipboard: (command: string) => void;+ /** Production: `app.relaunch(); app.quit();` — unconditional, no install check. */+ relaunchApp: () => void;+}++/**+ * Drive one fallback-dialog session. "Copy Command" copies and RE-SHOWS the+ * dialog (a message box closes on any button, but the user still needs+ * Relaunch / Not now available after copying); "Relaunch OpenKnowledge"+ * relaunches unconditionally; "Not now" dismisses. One session per explicit+ * failed relaunch attempt — dismissing never re-prompts on its own, so the+ * staged update is preserved without nagging.+ */+export async function runManualInstallFallbackDialog(+ deps: ManualInstallDialogDeps,+ ctx: LinuxManualInstallContext,+): Promise<'relaunch' | 'dismissed'> {+ const request: ManualInstallDialogRequest = {+ message: `OpenKnowledge ${ctx.version} couldn't install automatically`,+ detail:+ 'Administrator authorization is not available in this session, so the update ' ++ 'cannot be installed for you.\n\n' ++ 'To install it manually, run this in a terminal:\n\n' ++ `${ctx.command}\n\n` ++ 'The downloaded update stays on disk until it is installed or replaced by a ' ++ 'newer version. Relaunch restarts OpenKnowledge whether or not you have ' ++ 'installed it yet.',+ buttons: ['Copy Command', 'Relaunch OpenKnowledge', 'Not Now'],+ defaultId: 0,+ cancelId: 2,+ };+ for (;;) {+ let result: { response: number };+ try {+ result = await deps.showDialog(request);+ } catch (err) {+ // Parent window destroyed between iterations (e.g. copied the command,+ // then closed the window before the re-show). The app state is already+ // recovered and the command may be on the clipboard — treat as+ // dismissal. Logged because a FIRST-iteration throw means the user+ // never saw the dialog at all; resolving 'dismissed' would otherwise+ // hide that entirely.+ console.warn('[linux-install-fallback] dialog failed — treating as dismissal', {+ version: ctx.version,+ installerPath: ctx.installerPath,+ err,+ });+ return 'dismissed';+ }+ if (result.response === 0) {+ deps.copyCommandToClipboard(ctx.command);+ continue;+ }+ if (result.response === 1) {+ deps.relaunchApp();+ return 'relaunch';+ }+ return 'dismissed';+ }+}diff --git a/packages/desktop/src/main/renderer-ready-sink.test.ts b/packages/desktop/src/main/renderer-ready-sink.test.tsnew file mode 100644index 000000000..c3a4d5bac--- /dev/null+++ b/packages/desktop/src/main/renderer-ready-sink.test.ts@@ -0,0 +1,124 @@+import type { IpcMainInvokeEvent } from 'electron';+import { beforeEach, describe, expect, test, vi } from 'vitest';+import { createRendererReadySink } from './renderer-ready-sink.ts';++const CHANNELS = ['ok:mcp-wiring:renderer-ready', 'ok:onboarding:renderer-ready'] as const;++type Handler = (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown;++/**+ * Minimal ipcMain stub mirroring Electron's semantics: `handle` throws on a+ * second registration for the same channel; `invoke` simulates a renderer+ * `ipcRenderer.invoke` landing on main — rejecting with the exact "No handler+ * registered" error Electron raises (the packaged-startup stderr warning this+ * sink exists to eliminate).+ */+function createIpcMainStub() {+ const handlers = new Map<string, Handler>();+ return {+ handlers,+ handle(channel: string, handler: Handler): void {+ if (handlers.has(channel)) {+ throw new Error(`Attempted to register a second handler for '${channel}'`);+ }+ handlers.set(channel, handler);+ },+ removeHandler(channel: string): void {+ handlers.delete(channel);+ },+ async invoke(channel: string, ...args: unknown[]): Promise<unknown> {+ const handler = handlers.get(channel);+ if (!handler) {+ throw new Error(`No handler registered for '${channel}'`);+ }+ return handler({ sender: { id: 7 } } as unknown as IpcMainInvokeEvent, ...args);+ },+ };+}++describe('createRendererReadySink', () => {+ let real: ReturnType<typeof createIpcMainStub>;++ beforeEach(() => {+ real = createIpcMainStub();+ });++ test('registers a permanent handler for every sink channel at construction', () => {+ createRendererReadySink(real, CHANNELS);+ for (const channel of CHANNELS) {+ expect(real.handlers.has(channel)).toBe(true);+ }+ });++ test('an ack with no armed flow resolves undefined instead of "No handler registered"', async () => {+ createRendererReadySink(real, CHANNELS);+ // Before the sink, this exact invoke rejected and Electron logged the+ // packaged-startup warning; with it, the invoke settles cleanly.+ await expect(real.invoke('ok:mcp-wiring:renderer-ready')).resolves.toBeUndefined();+ await expect(real.invoke('ok:onboarding:renderer-ready')).resolves.toBeUndefined();+ });++ test('arming via the facade routes acks to the flow listener with the real event', async () => {+ const sink = createRendererReadySink(real, CHANNELS);+ const listener = vi.fn().mockReturnValue(undefined);+ sink.ipcMain.handle('ok:mcp-wiring:renderer-ready', listener);+ await expect(real.invoke('ok:mcp-wiring:renderer-ready')).resolves.toBeUndefined();+ expect(listener).toHaveBeenCalledTimes(1);+ expect((listener.mock.calls[0]?.[0] as IpcMainInvokeEvent).sender.id).toBe(7);+ // The sibling channel stays unarmed and keeps absorbing.+ await expect(real.invoke('ok:onboarding:renderer-ready')).resolves.toBeUndefined();+ });++ test('facade removeHandler disarms — later acks absorb again instead of erroring', async () => {+ const sink = createRendererReadySink(real, CHANNELS);+ const listener = vi.fn();+ sink.ipcMain.handle('ok:onboarding:renderer-ready', listener);+ sink.ipcMain.removeHandler('ok:onboarding:renderer-ready');+ await expect(real.invoke('ok:onboarding:renderer-ready')).resolves.toBeUndefined();+ expect(listener).not.toHaveBeenCalled();+ });++ test('re-arming after disarm works (reconfigure / next folder pick lifecycle)', async () => {+ const sink = createRendererReadySink(real, CHANNELS);+ const first = vi.fn();+ sink.ipcMain.handle('ok:mcp-wiring:renderer-ready', first);+ sink.ipcMain.removeHandler('ok:mcp-wiring:renderer-ready');+ const second = vi.fn();+ sink.ipcMain.handle('ok:mcp-wiring:renderer-ready', second);+ await real.invoke('ok:mcp-wiring:renderer-ready');+ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalledTimes(1);+ });++ test('double-arm throws, mirroring Electron second-handler semantics', () => {+ const sink = createRendererReadySink(real, CHANNELS);+ sink.ipcMain.handle('ok:mcp-wiring:renderer-ready', vi.fn());+ expect(() => sink.ipcMain.handle('ok:mcp-wiring:renderer-ready', vi.fn())).toThrow(+ /second handler/,+ );+ });++ test('non-sink channels pass through to the real ipcMain', async () => {+ const sink = createRendererReadySink(real, CHANNELS);+ const passthrough = vi.fn().mockReturnValue('ok');+ sink.ipcMain.handle('ok:mcp-wiring:confirm', passthrough);+ await expect(real.invoke('ok:mcp-wiring:confirm')).resolves.toBe('ok');+ sink.ipcMain.removeHandler('ok:mcp-wiring:confirm');+ await expect(real.invoke('ok:mcp-wiring:confirm')).rejects.toThrow(/No handler registered/);+ });++ test('listener return value and args flow through the sink', async () => {+ const sink = createRendererReadySink(real, CHANNELS);+ sink.ipcMain.handle('ok:onboarding:renderer-ready', (_event, ...args) => args);+ await expect(real.invoke('ok:onboarding:renderer-ready', 'a', 2)).resolves.toEqual(['a', 2]);+ });++ test('destroy unregisters the permanent handlers and is idempotent', async () => {+ const sink = createRendererReadySink(real, CHANNELS);+ sink.destroy();+ sink.destroy();+ await expect(real.invoke('ok:mcp-wiring:renderer-ready')).rejects.toThrow(+ /No handler registered/,+ );+ });+});diff --git a/packages/desktop/src/main/renderer-ready-sink.ts b/packages/desktop/src/main/renderer-ready-sink.tsnew file mode 100644index 000000000..d794d8cca--- /dev/null+++ b/packages/desktop/src/main/renderer-ready-sink.ts@@ -0,0 +1,112 @@+/**+ * Renderer-ready mount-ack sink — a permanently-registered `ipcMain.handle`+ * for the fire-and-forget `*:renderer-ready` channels the preload invokes on+ * EVERY renderer mount (`okDesktop.mcpWiring.signalReady()` /+ * `okDesktop.onboarding.signalReady()` at module init).+ *+ * The consent flows that consume those acks (`runMcpWiringOnFirstLaunch`,+ * `requestUserConsent`) are armed only transiently — first-launch, an explicit+ * re-configure, or a Navigator folder pick. On every other boot the invoke+ * used to land on an UNREGISTERED channel, and Electron's main process logs+ * `Error occurred in handler for 'ok:…:renderer-ready': No handler registered`+ * to stderr for each one on every packaged startup. The preload's+ * `.catch(() => {})` swallows the renderer side of that rejection but cannot+ * silence main's log line; only a registered handler can.+ *+ * Design: the sink owns the REAL `ipcMain.handle` registration for its+ * channels, permanently. Flows keep their existing one-shot+ * register/removeHandler lifecycles untouched — they receive a facade whose+ * `handle`/`removeHandler` arm/disarm a listener inside the sink for sink+ * channels and delegate to the real `ipcMain` for everything else. An ack+ * arriving while no flow is armed resolves `undefined` silently (debug log)+ * instead of erroring.+ */++import type { IpcMain, IpcMainInvokeEvent } from 'electron';++/** Structurally-compatible subset of Electron's `IpcMain` (test-injectable). */+export interface SinkIpcMainLike extends Pick<IpcMain, 'handle' | 'removeHandler'> {}++interface SinkLogger {+ debug(msg: string, ctx?: Record<string, unknown>): void;+ warn(msg: string, ctx?: Record<string, unknown>): void;+}++export interface RendererReadySink {+ /**+ * Drop-in `ipcMain` replacement for the consent flows. `handle` on a sink+ * channel arms the sink's listener (throwing on double-arm, mirroring+ * Electron's own "second handler" semantics so flow bugs stay visible);+ * `removeHandler` disarms. Non-sink channels pass straight through to the+ * real `ipcMain`.+ */+ readonly ipcMain: SinkIpcMainLike;+ /** Unregister the permanent handlers (will-quit teardown). */+ destroy(): void;+}++type InvokeListener = (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown;++export function createRendererReadySink(+ realIpcMain: SinkIpcMainLike,+ channels: readonly string[],+ logger: SinkLogger = {+ debug: () => {},+ warn: (msg, ctx) => console.warn('[renderer-ready-sink]', msg, ctx ?? ''),+ },+): RendererReadySink {+ const sinkChannels = new Set(channels);+ const armed = new Map<string, InvokeListener>();++ for (const channel of channels) {+ realIpcMain.handle(channel, (event, ...args) => {+ const listener = armed.get(channel);+ if (!listener) {+ // Expected steady-state: a renderer mounted while no consent flow is+ // armed (e.g. every packaged boot after first-launch wiring is done).+ logger.debug('renderer-ready ack with no armed flow — absorbed', { channel });+ return undefined;+ }+ return listener(event, ...args);+ });+ }++ const facade: SinkIpcMainLike = {+ handle(channel: string, listener: InvokeListener): void {+ if (!sinkChannels.has(channel)) {+ realIpcMain.handle(channel, listener);+ return;+ }+ if (armed.has(channel)) {+ // Same failure Electron raises for a genuine double `ipcMain.handle` —+ // keep flow-lifecycle bugs loud rather than silently replacing.+ throw new Error(`Attempted to register a second handler for '${channel}'`);+ }+ armed.set(channel, listener);+ },+ removeHandler(channel: string): void {+ if (!sinkChannels.has(channel)) {+ realIpcMain.removeHandler(channel);+ return;+ }+ armed.delete(channel);+ },+ };++ let destroyed = false;+ return {+ ipcMain: facade,+ destroy(): void {+ if (destroyed) return;+ destroyed = true;+ armed.clear();+ for (const channel of channels) {+ try {+ realIpcMain.removeHandler(channel);+ } catch (err) {+ logger.warn('removeHandler threw during sink destroy', { channel, err });+ }+ }+ },+ };+}diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.tsindex a9be9f2e9..1a1b7dd62 100644--- a/packages/desktop/src/main/state-store.ts+++ b/packages/desktop/src/main/state-store.ts@@ -149,6 +149,20 @@ export interface AppState {* most once per pending-update state; cleared after install completes.*/versionPendingInstall: string | null;+ /**+ * Absolute path of the staged installer electron-updater downloaded+ * (`update-downloaded`'s `downloadedFile`). Persisted so the Linux+ * manual-install fallback can build its copyable command on the standard+ * Linux flow — download, quit, boot, click Relaunch — where the banner+ * (restored from `versionPendingInstall`) becomes clickable long before+ * the updater's launch check re-validates its cache and re-emits the+ * path. Arms alongside `versionPendingInstall` at download time; cleared+ * wherever the staged update stops being live (running version caught up,+ * cross-channel residue, failure-budget giveup). Deliberately NOT cleared+ * by "Relaunch now": a failed install still needs it. May point at a+ * since-deleted file — consumers existence-check before use.+ */+ stagedInstallerPath: string | null;/*** Version the app committed to install and is expected to be running after* the next boot. Set when an update finishes downloading (the install is@@ -302,6 +316,7 @@ export function emptyState(): AppState {recentFiles: [],lastOpenedProject: null,versionPendingInstall: null,+ stagedInstallerPath: null,attemptedInstall: null,attemptedInstallSurfacedCount: 0,lastSeenVersion: null,@@ -810,6 +825,12 @@ export function parseAppState(raw: unknown): AppState | null {// fields match emptyState() defaults (no quarantine, no data loss).const versionPendingInstall =typeof obj.versionPendingInstall === 'string' ? obj.versionPendingInstall : null;+ // Additive field: a state.json lacking it coerces to null (no staged+ // installer known), matching emptyState(); no quarantine.+ const stagedInstallerPath =+ typeof obj.stagedInstallerPath === 'string' && obj.stagedInstallerPath.length > 0+ ? obj.stagedInstallerPath+ : null;const attemptedInstall = typeof obj.attemptedInstall === 'string' ? obj.attemptedInstall : null;// Additive field: a missing or invalid value coerces to 0 (a fresh failure// budget), matching emptyState(); guards against negatives and non-integers@@ -859,6 +880,7 @@ export function parseAppState(raw: unknown): AppState | null {recentFiles,lastOpenedProject,versionPendingInstall,+ stagedInstallerPath,attemptedInstall,attemptedInstallSurfacedCount,lastSeenVersion,diff --git a/packages/desktop/src/main/updater-cache.test.ts b/packages/desktop/src/main/updater-cache.test.tsnew file mode 100644index 000000000..2ba7069fb--- /dev/null+++ b/packages/desktop/src/main/updater-cache.test.ts@@ -0,0 +1,183 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { mkdir, stat, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ getUpdaterBaseCacheDir,+ readUpdaterCacheDirName,+ reclaimPendingUpdateCache,+} from './updater-cache.ts';++describe('getUpdaterBaseCacheDir', () => {+ test('win32 prefers %LOCALAPPDATA%', () => {+ expect(+ getUpdaterBaseCacheDir({+ platform: 'win32',+ env: { LOCALAPPDATA: 'C:\\Users\\u\\AppData\\Local' },+ homeDir: 'C:\\Users\\u',+ }),+ ).toBe('C:\\Users\\u\\AppData\\Local');+ });++ test('win32 falls back to <home>/AppData/Local when LOCALAPPDATA is unset', () => {+ expect(getUpdaterBaseCacheDir({ platform: 'win32', env: {}, homeDir: 'C:\\Users\\u' })).toBe(+ join('C:\\Users\\u', 'AppData', 'Local'),+ );+ });++ test('darwin uses ~/Library/Caches', () => {+ expect(getUpdaterBaseCacheDir({ platform: 'darwin', env: {}, homeDir: '/Users/u' })).toBe(+ '/Users/u/Library/Caches',+ );+ });++ test('linux prefers $XDG_CACHE_HOME', () => {+ expect(+ getUpdaterBaseCacheDir({+ platform: 'linux',+ env: { XDG_CACHE_HOME: '/xdg/cache' },+ homeDir: '/home/u',+ }),+ ).toBe('/xdg/cache');+ });++ test('linux falls back to ~/.cache', () => {+ expect(getUpdaterBaseCacheDir({ platform: 'linux', env: {}, homeDir: '/home/u' })).toBe(+ '/home/u/.cache',+ );+ });+});++describe('readUpdaterCacheDirName', () => {+ test('extracts the generated cache dir name', () => {+ const yml = [+ 'provider: github',+ 'owner: inkeep',+ 'repo: open-knowledge',+ "updaterCacheDirName: '@inkeepopen-knowledge-desktop-updater'",+ ].join('\n');+ expect(readUpdaterCacheDirName(yml)).toBe('@inkeepopen-knowledge-desktop-updater');+ });++ test('returns null when the key is absent', () => {+ expect(readUpdaterCacheDirName('provider: github\nrepo: x')).toBeNull();+ });++ test('returns null on empty or non-string values', () => {+ expect(readUpdaterCacheDirName("updaterCacheDirName: ''")).toBeNull();+ expect(readUpdaterCacheDirName('updaterCacheDirName: 3')).toBeNull();+ expect(readUpdaterCacheDirName('updaterCacheDirName: [a]')).toBeNull();+ });++ test('returns null on unparseable yaml', () => {+ expect(readUpdaterCacheDirName('{{{{not yaml')).toBeNull();+ });++ test('rejects multi-segment / traversal / absolute shapes (rm -rf safety net)', () => {+ // Single-quoted YAML so the backslash case reaches the parser literally+ // (double-quoted YAML would decode `\b` as a backspace escape).+ for (const bad of ['a/b', 'a\\b', '..', '.', '../evil', '/etc']) {+ expect(readUpdaterCacheDirName(`updaterCacheDirName: '${bad}'`)).toBeNull();+ }+ });+});++describe('reclaimPendingUpdateCache', () => {+ const tempRoots: string[] = [];+ function makeTempRoot(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-updater-cache-'));+ tempRoots.push(dir);+ return dir;+ }+ afterEach(() => {+ for (const dir of tempRoots.splice(0)) {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ /** Lay out <root>/{resources/app-update.yml, cache/<name>/pending/...}. */+ async function scaffold(root: string, cacheDirName = 'ok-updater') {+ const configPath = join(root, 'resources', 'app-update.yml');+ await mkdir(join(root, 'resources'), { recursive: true });+ await writeFile(configPath, `provider: github\nupdaterCacheDirName: ${cacheDirName}\n`);+ const pendingDir = join(root, 'cache', cacheDirName, 'pending');+ await mkdir(pendingDir, { recursive: true });+ await writeFile(join(pendingDir, 'OpenKnowledge-Setup-x64.exe'), 'staged-installer-bytes');+ await writeFile(join(pendingDir, 'update-info.json'), '{}');+ return { configPath, pendingDir };+ }++ function linuxDeps(root: string, configPath: string) {+ return {+ appUpdateConfigPath: configPath,+ platform: 'linux' as const,+ env: { XDG_CACHE_HOME: join(root, 'cache') },+ homeDir: join(root, 'home'),+ };+ }++ test('removes the pending dir (and only it) once invoked', async () => {+ const root = makeTempRoot();+ const { configPath, pendingDir } = await scaffold(root);+ const outcome = await reclaimPendingUpdateCache(linuxDeps(root, configPath));+ expect(outcome).toBe('reclaimed');+ await expect(stat(pendingDir)).rejects.toMatchObject({ code: 'ENOENT' });+ // The enclosing updater cache dir survives — only pending/ is reclaimed.+ await expect(stat(join(root, 'cache', 'ok-updater'))).resolves.toBeDefined();+ });++ test('reports nothing-staged when pending/ does not exist', async () => {+ const root = makeTempRoot();+ const { configPath, pendingDir } = await scaffold(root);+ rmSync(pendingDir, { recursive: true, force: true });+ expect(await reclaimPendingUpdateCache(linuxDeps(root, configPath))).toBe('nothing-staged');+ });++ test('reports a stat failure instead of treating it as a missing cache', async () => {+ const root = makeTempRoot();+ const { configPath } = await scaffold(root);+ const warn = vi.fn();+ const statError = Object.assign(new Error('permission denied'), { code: 'EACCES' });+ const outcome = await reclaimPendingUpdateCache({+ ...linuxDeps(root, configPath),+ exists: () => Promise.reject(statError),+ logger: { info: vi.fn(), warn, debug: vi.fn() },+ });++ expect(outcome).toBe('failed');+ expect(warn).toHaveBeenCalledWith('failed to inspect staged updater cache', {+ pendingDir: join(root, 'cache', 'ok-updater', 'pending'),+ err: statError,+ });+ });++ test('missing app-update.yml skips without touching disk', async () => {+ const root = makeTempRoot();+ const { pendingDir } = await scaffold(root);+ const outcome = await reclaimPendingUpdateCache(+ linuxDeps(root, join(root, 'resources', 'does-not-exist.yml')),+ );+ expect(outcome).toBe('config-unreadable');+ await expect(stat(pendingDir)).resolves.toBeDefined();+ });++ test('unusable updaterCacheDirName skips without touching disk', async () => {+ const root = makeTempRoot();+ const { configPath, pendingDir } = await scaffold(root);+ await writeFile(configPath, 'provider: github\n');+ const outcome = await reclaimPendingUpdateCache(linuxDeps(root, configPath));+ expect(outcome).toBe('no-cache-dir-name');+ await expect(stat(pendingDir)).resolves.toBeDefined();+ });++ test('rm failure is reported, not thrown', async () => {+ const root = makeTempRoot();+ const { configPath } = await scaffold(root);+ const outcome = await reclaimPendingUpdateCache({+ ...linuxDeps(root, configPath),+ rm: () => Promise.reject(new Error('EACCES')),+ });+ expect(outcome).toBe('failed');+ });+});diff --git a/packages/desktop/src/main/updater-cache.ts b/packages/desktop/src/main/updater-cache.tsnew file mode 100644index 000000000..f4354e95c--- /dev/null+++ b/packages/desktop/src/main/updater-cache.ts@@ -0,0 +1,181 @@+/**+ * Updater-cache reclamation — deletes electron-updater's staged installer+ * once it can no longer be needed.+ *+ * electron-updater stages every downloaded update under+ * `<baseCacheDir>/<updaterCacheDirName>/pending/` and only empties that+ * directory when a DIFFERENT version is later downloaded+ * (`DownloadedUpdateHelper.cleanCacheDirForPendingUpdate`). After an install+ * commits, the staged installer for the version now running just sits there+ * until the next release — a constant ~250 MB of dead weight on every+ * platform.+ *+ * The caller (auto-updater boot reconciliation) decides WHEN reclaiming is+ * safe — strictly after the install-success signal, never while an update is+ * still staged or a manual Linux install may still consume the file. This+ * module only knows HOW: resolve the cache dir exactly the way+ * electron-updater does (`AppAdapter.getAppCacheDir` + `updaterCacheDirName`+ * from app-update.yml) and remove `pending/`.+ *+ * The Windows-only sibling copy (`<updaterCacheDirName>\installer.exe`, made+ * by the NSIS installer itself to seed differential updates) is handled at+ * install time by `build/installer.nsh`, not here — this process can't win a+ * race against its own installer.+ *+ * The macOS sibling (`<updaterCacheDirName>/update.zip`, copied beside+ * `pending/` by `MacUpdater.doDownloadUpdate`) is deliberately NOT+ * reclaimed: unlike the inert Windows copy it has a live consumer — it is+ * the base electron-updater's differential download patches against on the+ * next mac update (`canDifferentialDownload` gates on its presence), and+ * removing it would demote every future mac update to a full download.+ */++import { readFile as fsReadFile, rm as fsRm, stat as fsStat } from 'node:fs/promises';+import { join } from 'node:path';+import { parse as parseYaml } from 'yaml';++interface UpdaterCacheLogger {+ info(msg: string, ctx?: Record<string, unknown>): void;+ warn(msg: string, ctx?: Record<string, unknown>): void;+ debug(msg: string, ctx?: Record<string, unknown>): void;+}++/**+ * Mirror of electron-updater's `AppAdapter.getAppCacheDir()` — the base the+ * updater cache dir is joined onto. Kept in sync manually; the shape is+ * stable across electron-updater releases (win: %LOCALAPPDATA%, mac:+ * ~/Library/Caches, linux: $XDG_CACHE_HOME or ~/.cache).+ */+export function getUpdaterBaseCacheDir(opts: {+ platform: NodeJS.Platform;+ env: Record<string, string | undefined>;+ homeDir: string;+}): string {+ const { platform, env, homeDir } = opts;+ if (platform === 'win32') {+ return env.LOCALAPPDATA || join(homeDir, 'AppData', 'Local');+ }+ if (platform === 'darwin') {+ return join(homeDir, 'Library', 'Caches');+ }+ return env.XDG_CACHE_HOME || join(homeDir, '.cache');+}++/**+ * Extract `updaterCacheDirName` from app-update.yml text. Returns null when+ * the key is absent, empty, non-string, or the YAML fails to parse — callers+ * skip reclaiming rather than guessing a directory to delete.+ */+export function readUpdaterCacheDirName(appUpdateYmlText: string): string | null {+ let parsed: unknown;+ try {+ parsed = parseYaml(appUpdateYmlText);+ } catch {+ return null;+ }+ if (parsed === null || typeof parsed !== 'object') return null;+ const value = (parsed as Record<string, unknown>).updaterCacheDirName;+ if (typeof value !== 'string' || value === '') return null;+ // Recursive-delete safety net: the name must be a plain single path+ // segment. electron-builder always generates one; anything else (path+ // separators, traversal, absolute) means a corrupt or tampered+ // app-update.yml and is not worth pointing `rm -rf` at.+ if (value.includes('/') || value.includes('\\') || value.includes('..') || value === '.') {+ return null;+ }+ return value;+}++export type ReclaimOutcome =+ | 'reclaimed'+ | 'nothing-staged'+ | 'config-unreadable'+ | 'no-cache-dir-name'+ | 'failed';++export interface ReclaimPendingUpdateCacheDeps {+ /** `join(process.resourcesPath, 'app-update.yml')` in a packaged build. */+ appUpdateConfigPath: string;+ platform: NodeJS.Platform;+ env: Record<string, string | undefined>;+ homeDir: string;+ logger?: UpdaterCacheLogger;+ /** Injectable fs seams for tests. */+ readFile?: (path: string) => Promise<string>;+ rm?: (path: string) => Promise<void>;+ exists?: (path: string) => Promise<boolean>;+}++/**+ * Delete `<updater cache>/pending/` wholesale. electron-updater recreates the+ * directory (and its `update-info.json`) on the next download, so removing+ * the directory itself is exactly what its own `emptyDir`-based cleanup does+ * when a new version supersedes the staged one.+ */+export async function reclaimPendingUpdateCache(+ deps: ReclaimPendingUpdateCacheDeps,+): Promise<ReclaimOutcome> {+ const {+ appUpdateConfigPath,+ platform,+ env,+ homeDir,+ logger = { info: () => {}, warn: () => {}, debug: () => {} },+ readFile = (p) => fsReadFile(p, 'utf8'),+ rm = (p) => fsRm(p, { recursive: true, force: true }),+ exists = async (p) => {+ try {+ await fsStat(p);+ return true;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw err;+ }+ },+ } = deps;++ let configText: string;+ try {+ configText = await readFile(appUpdateConfigPath);+ } catch (err) {+ logger.debug('app-update.yml unreadable — skipping updater-cache reclaim', {+ appUpdateConfigPath,+ err,+ });+ return 'config-unreadable';+ }++ const cacheDirName = readUpdaterCacheDirName(configText);+ if (cacheDirName === null) {+ logger.warn('app-update.yml has no usable updaterCacheDirName — skipping reclaim', {+ appUpdateConfigPath,+ });+ return 'no-cache-dir-name';+ }++ const pendingDir = join(+ getUpdaterBaseCacheDir({ platform, env, homeDir }),+ cacheDirName,+ 'pending',+ );+ let pendingExists: boolean;+ try {+ pendingExists = await exists(pendingDir);+ } catch (err) {+ logger.warn('failed to inspect staged updater cache', { pendingDir, err });+ return 'failed';+ }+ if (!pendingExists) {+ logger.debug('no staged updater cache to reclaim', { pendingDir });+ return 'nothing-staged';+ }++ try {+ await rm(pendingDir);+ } catch (err) {+ logger.warn('failed to reclaim staged updater cache', { pendingDir, err });+ return 'failed';+ }+ logger.info('reclaimed staged updater cache', { pendingDir });+ return 'reclaimed';+}diff --git a/packages/desktop/tests/integration/auto-updater.test.ts b/packages/desktop/tests/integration/auto-updater.test.tsindex f68dfc4ae..2c45642a6 100644--- a/packages/desktop/tests/integration/auto-updater.test.ts+++ b/packages/desktop/tests/integration/auto-updater.test.ts@@ -15,6 +15,8 @@* - Periodic check singleton via injectable clock* - Relaunch-now IPC calls quitAndInstall* - Dev-mode guard skips first-launch check but keeps handlers wired+ * - Staged-cache reclaim fires only with no install commitment armed+ * - Linux manual-install fallback (no-auth preflight, 126 vs 127 routing)*/import { EventEmitter } from 'node:events';@@ -92,6 +94,12 @@ function makeFakeIpc(): FakeIpc {return {handlers,handle(channel: string, listener: (event: unknown, ...args: unknown[]) => unknown): void {+ // Mirror Electron's real ipcMain semantics — a double registration+ // throws. Silent overwrite would let a re-registration bug pass the+ // whole suite and crash only in production.+ if (handlers.has(channel)) {+ throw new Error(`Attempted to register a second handler for '${channel}'`);+ }handlers.set(channel, listener);},removeHandler(channel: string): void {@@ -215,6 +223,20 @@ function makeRig(* discriminated-union shape that lands per outcome.*/showCheckNowResult?: Parameters<typeof startAutoUpdater>[0]['showCheckNowResult'];+ /**+ * Staged-cache reclaim hook — production wires+ * `reclaimPendingUpdateCache` in packaged builds. Tests pass a spy to+ * pin the boot-reconciliation gating (never while an install commitment+ * is armed).+ */+ reclaimStagedUpdateCache?: Parameters<typeof startAutoUpdater>[0]['reclaimStagedUpdateCache'];+ /**+ * Linux manual-install fallback surface — production wires the+ * pkexec-preflight + Copy-command dialog. Tests pass spies to pin the+ * trigger conditions (no graphical auth / infrastructure-classified+ * install failure) and the preserved staged state.+ */+ linuxInstallSupport?: Parameters<typeof startAutoUpdater>[0]['linuxInstallSupport'];/*** RNG for the periodic-check jitter. Defaults to `() => 0` so the* scheduled delay is exactly `UPDATE_CHECK_INTERVAL_MS` in tests that@@ -239,6 +261,8 @@ function makeRig(extraWindowCount = 0,prepareForRelaunch,showCheckNowResult,+ reclaimStagedUpdateCache,+ linuxInstallSupport,random = () => 0,...stateOverrides} = overrides ?? {};@@ -287,6 +311,8 @@ function makeRig(proxyFeed,prepareForRelaunch,showCheckNowResult,+ reclaimStagedUpdateCache,+ linuxInstallSupport,clock: rig.clock,now: () => rig.now,random,@@ -1323,6 +1349,9 @@ describe('boot-time failed-install detection', () => {const { rig } = makeRig({attemptedInstall: '0.24.0',versionPendingInstall: '0.24.0',+ // Seeded so the clearing assertion below has teeth — a branch that+ // stops nulling it would leave a stale path for the Linux fallback.+ stagedInstallerPath: '/tmp/staged-cross-channel.deb',appVersion: '0.23.0-beta.1',});expect(rig.captured.filter((c) => c.channel === 'ok:update:relaunch-failed')).toHaveLength(0);@@ -1330,6 +1359,7 @@ describe('boot-time failed-install detection', () => {// The stale cross-channel pending marker is dropped too — no phantom// "ready to install" banner survives on the beta build.expect(rig.state.versionPendingInstall).toBeNull();+ expect(rig.state.stagedInstallerPath).toBeNull();expect(rig.dispatches).toContain('attempted-install-cross-channel' as DispatchKind);expect(rig.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);expect(rig.dispatches).not.toContain('attempted-install-reconciled' as DispatchKind);@@ -1367,6 +1397,8 @@ describe('boot-time failed-install detection', () => {const { rig } = makeRig({attemptedInstall: '0.17.0-beta.1',versionPendingInstall: '0.17.0-beta.1',+ // Seeded so the clearing assertion below has teeth.+ stagedInstallerPath: '/tmp/staged-giveup.deb',appVersion: '0.16.0-beta.1',attemptedInstallSurfacedCount: INSTALL_FAILURE_MAX_SURFACES,});@@ -1375,6 +1407,7 @@ describe('boot-time failed-install detection', () => {expect(rig.state.attemptedInstallSurfacedCount).toBe(0);// No phantom "ready to install" banner left behind after giving up.expect(rig.state.versionPendingInstall).toBeNull();+ expect(rig.state.stagedInstallerPath).toBeNull();expect(rig.dispatches).toContain('install-failed-giveup' as DispatchKind);expect(rig.dispatches).not.toContain('install-failed-on-boot' as DispatchKind);});@@ -3252,3 +3285,341 @@ describe('bootAutoUpdater catch-path (Major #5)', () => {);});});++// ————————————————————————————————————————————————————————+// Staged-cache reclaim gating (boot reconciliation)+// ————————————————————————————————————————————————————————++describe('staged-cache reclaim — fires only once every install commitment is settled', () => {+ test('clean boot (nothing pending, nothing attempted) invokes the reclaim hook once', () => {+ const reclaim = vi.fn(() => Promise.resolve());+ const { rig } = makeRig({ reclaimStagedUpdateCache: reclaim });+ expect(reclaim).toHaveBeenCalledTimes(1);+ expect(rig.dispatches.filter((d) => d === 'staged-cache-reclaimed')).toHaveLength(1);+ });++ test('boot after a committed install reclaims once reconciliation clears both gates', () => {+ // Running 0.3.2 with versionPendingInstall + attemptedInstall still+ // recording 0.3.2 — the install-on-quit success shape. Reconciliation+ // clears both, then (and only then) the reclaim may fire.+ const reclaim = vi.fn(() => Promise.resolve());+ const { rig } = makeRig({+ appVersion: '0.3.2',+ versionPendingInstall: '0.3.2',+ attemptedInstall: '0.3.2',+ reclaimStagedUpdateCache: reclaim,+ });+ expect(rig.state.versionPendingInstall).toBeNull();+ expect(rig.state.attemptedInstall).toBeNull();+ expect(reclaim).toHaveBeenCalledTimes(1);+ });++ test('a still-staged update (versionPendingInstall armed) blocks the reclaim', () => {+ // The Linux download-then-quit shape: the staged installer is the very+ // file "Relaunch now" / the manual-install command will consume.+ const reclaim = vi.fn(() => Promise.resolve());+ const { rig } = makeRig({+ versionPendingInstall: '0.9.9',+ reclaimStagedUpdateCache: reclaim,+ });+ expect(rig.state.versionPendingInstall).toBe('0.9.9');+ expect(reclaim).not.toHaveBeenCalled();+ expect(rig.dispatches).not.toContain('staged-cache-reclaimed' as DispatchKind);+ });++ test('a failed install being surfaced (attemptedInstall armed) blocks the reclaim', () => {+ // Boot detects the silent install failure, re-arms the banner for Retry —+ // the staged installer must stay for that Retry to have anything to run.+ const reclaim = vi.fn(() => Promise.resolve());+ const { rig } = makeRig({+ attemptedInstall: '0.9.9',+ reclaimStagedUpdateCache: reclaim,+ });+ expect(rig.dispatches).toContain('install-failed-on-boot' as DispatchKind);+ expect(reclaim).not.toHaveBeenCalled();+ });++ test('the giveup boot clears both gates but still skips the reclaim', () => {+ const reclaim = vi.fn(() => Promise.resolve());+ const { rig } = makeRig({+ attemptedInstall: '0.9.9',+ attemptedInstallSurfacedCount: INSTALL_FAILURE_MAX_SURFACES,+ reclaimStagedUpdateCache: reclaim,+ });+ expect(rig.dispatches).toContain('install-failed-giveup' as DispatchKind);+ expect(rig.state.attemptedInstall).toBeNull();+ expect(rig.state.versionPendingInstall).toBeNull();+ expect(reclaim).not.toHaveBeenCalled();+ });++ test('a rejecting reclaim hook is logged, never thrown', async () => {+ const reclaim = vi.fn(() => Promise.reject(new Error('EACCES')));+ const { rig } = makeRig({ reclaimStagedUpdateCache: reclaim });+ await Promise.resolve();+ await Promise.resolve();+ expect(+ rig.logger.warn.mock.calls.some((c) => c[0] === 'staged-update cache reclaim failed'),+ ).toBe(true);+ });++ test('no hook wired (dev build) → no dispatch, no throw', () => {+ const { rig } = makeRig();+ expect(rig.dispatches).not.toContain('staged-cache-reclaimed' as DispatchKind);+ });++ test('the launch check waits for the reclaim to settle (no rm/download interleave)', async () => {+ let resolveReclaim: (() => void) | undefined;+ const reclaim = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveReclaim = resolve;+ }),+ );+ const { rig } = makeRig({ reclaimStagedUpdateCache: reclaim });+ expect(reclaim).toHaveBeenCalledTimes(1);+ await Promise.resolve();+ await Promise.resolve();+ expect(rig.updater.checkForUpdates).not.toHaveBeenCalled();+ resolveReclaim?.();+ await Promise.resolve();+ await Promise.resolve();+ expect(rig.updater.checkForUpdates).toHaveBeenCalledTimes(1);+ });+});++// ————————————————————————————————————————————————————————+// Linux manual-install fallback triggers+// ————————————————————————————————————————————————————————++describe('linux manual-install fallback', () => {+ const STAGED_DEB = '/home/u/.cache/ok-updater/pending/ok_0.3.2_arm64.deb';++ function makeLinuxRig(opts: {+ hasGraphicalAuth: boolean;+ downloadedFile?: string | undefined;+ extraWindowCount?: number;+ /**+ * When false, no `update-downloaded` event fires — the boot-with-staged+ * shape where the fallback must run entirely off the PERSISTED path.+ * Combine with `stateStagedInstallerPath`.+ */+ emitDownloadEvent?: boolean;+ stateStagedInstallerPath?: string;+ stagedInstallerExists?: (path: string) => boolean;+ }) {+ const fallback = vi.fn(() => Promise.resolve());+ const hasAuth = vi.fn(() => opts.hasGraphicalAuth);+ const made = makeRig({+ platform: 'linux',+ versionPendingInstall: '0.3.2',+ ...(opts.stateStagedInstallerPath !== undefined+ ? { stagedInstallerPath: opts.stateStagedInstallerPath }+ : {}),+ extraWindowCount: opts.extraWindowCount ?? 0,+ linuxInstallSupport: {+ hasGraphicalAuth: hasAuth,+ showManualInstallFallback: fallback,+ ...(opts.stagedInstallerExists+ ? { stagedInstallerExists: opts.stagedInstallerExists }+ : {}),+ },+ });+ // Stage the installer path the way production learns it — from the+ // update-downloaded payload. The seeded versionPendingInstall makes this+ // a dedupe re-fire; the staged path must be captured regardless.+ if (opts.emitDownloadEvent !== false) {+ made.rig.updater.emit('update-downloaded', {+ version: '0.3.2',+ downloadedFile: opts.downloadedFile ?? STAGED_DEB,+ });+ }+ return { ...made, fallback, hasAuth };+ }++ test('no graphical auth → fallback dialog instead of quitAndInstall, staged state preserved', async () => {+ const { rig, fallback } = makeLinuxRig({ hasGraphicalAuth: false, extraWindowCount: 1 });+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();+ // The staged update survives: the gate stays armed for the next boot /+ // a later retry, exactly what "premature relaunch" relies on.+ expect(rig.state.versionPendingInstall).toBe('0.3.2');+ // The early return fires BEFORE the install-commitment persist — no+ // attempt ever ran, so the next boot must not see a spurious+ // "install failed" record.+ expect(rig.state.attemptedInstall).toBeNull();+ expect(fallback).toHaveBeenCalledTimes(1);+ expect(fallback).toHaveBeenCalledWith({+ version: '0.3.2',+ installerPath: STAGED_DEB,+ packageKind: 'deb',+ command: `sudo apt install -- '${STAGED_DEB}'`,+ });+ expect(rig.dispatches).toContain('linux-manual-fallback-no-auth' as DispatchKind);+ expect(rig.dispatches).not.toContain('relaunch-now' as DispatchKind);+ // Every window's banner is restored (the clicked one swapped locally);+ // no relaunching broadcast ever goes out.+ for (const win of rig.windows) {+ expect(win.filter((c) => c.channel === 'ok:update:downloaded').length).toBeGreaterThan(0);+ expect(win.filter((c) => c.channel === 'ok:update:relaunching')).toHaveLength(0);+ }+ });++ test('graphical auth present → normal quitAndInstall path, no fallback', async () => {+ const { rig, fallback, hasAuth } = makeLinuxRig({ hasGraphicalAuth: true });+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(hasAuth).toHaveBeenCalled();+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);+ expect(fallback).not.toHaveBeenCalled();+ });++ test('unrecognized staged format (AppImage) falls through to quitAndInstall even without auth', async () => {+ const { rig, fallback } = makeLinuxRig({+ hasGraphicalAuth: false,+ downloadedFile: '/x/OpenKnowledge.AppImage',+ });+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);+ expect(fallback).not.toHaveBeenCalled();+ });++ test('user cancellation (pkexec 126) → recovery with friendly message, NO fallback dialog', async () => {+ const { rig, fallback } = makeLinuxRig({ hasGraphicalAuth: true, extraWindowCount: 1 });+ await Promise.resolve();+ await Promise.resolve();+ await rig.ipc.invoke('ok:update:relaunch-now');+ rig.updater.emit('error', new Error('Command pkexec exited with code 126'));+ expect(rig.state.versionPendingInstall).toBe('0.3.2');+ for (const win of rig.windows) {+ const failed = win.filter((c) => c.channel === 'ok:update:relaunch-failed');+ expect(failed).toHaveLength(1);+ expect(failed[0]?.payload).toEqual({+ version: '0.3.2',+ message: 'authorization was cancelled',+ });+ }+ expect(fallback).not.toHaveBeenCalled();+ expect(rig.dispatches).not.toContain('linux-manual-fallback-after-error' as DispatchKind);+ });++ test('retry after cancellation: the re-armed gate accepts a second relaunch-now', async () => {+ const { rig } = makeLinuxRig({ hasGraphicalAuth: true });+ await rig.ipc.invoke('ok:update:relaunch-now');+ rig.updater.emit('error', new Error('Command pkexec exited with code 126'));+ expect(rig.state.versionPendingInstall).toBe('0.3.2');+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(2);+ });++ test('infrastructure failure (pkexec 127) → recovery AND the fallback dialog', async () => {+ const { rig, fallback } = makeLinuxRig({ hasGraphicalAuth: true, extraWindowCount: 1 });+ await Promise.resolve();+ await Promise.resolve();+ await rig.ipc.invoke('ok:update:relaunch-now');+ rig.updater.emit('error', new Error('Command pkexec exited with code 127'));+ // failRelaunch recovery landed first: gate restored, windows re-armed.+ expect(rig.state.versionPendingInstall).toBe('0.3.2');+ for (const win of rig.windows) {+ const failed = win.filter((c) => c.channel === 'ok:update:relaunch-failed');+ expect(failed).toHaveLength(1);+ expect(failed[0]?.payload).toEqual({+ version: '0.3.2',+ message: 'Command pkexec exited with code 127',+ });+ }+ expect(fallback).toHaveBeenCalledTimes(1);+ expect(fallback).toHaveBeenCalledWith({+ version: '0.3.2',+ installerPath: STAGED_DEB,+ packageKind: 'deb',+ command: `sudo apt install -- '${STAGED_DEB}'`,+ });+ expect(rig.dispatches).toContain('linux-manual-fallback-after-error' as DispatchKind);+ });++ test('sudo-without-tty failure (no graphical wrapper found mid-install) also offers the fallback', async () => {+ const { rig, fallback } = makeLinuxRig({ hasGraphicalAuth: true });+ await rig.ipc.invoke('ok:update:relaunch-now');+ rig.updater.emit('error', new Error('Command sudo exited with code 1'));+ expect(fallback).toHaveBeenCalledTimes(1);+ });++ test('rpm staged file produces the dnf command', async () => {+ const { rig, fallback } = makeLinuxRig({+ hasGraphicalAuth: false,+ downloadedFile: '/home/u/.cache/ok-updater/pending/ok-0.3.2.x86_64.rpm',+ });+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(fallback).toHaveBeenCalledWith(+ expect.objectContaining({+ packageKind: 'rpm',+ command: "sudo dnf install '/home/u/.cache/ok-updater/pending/ok-0.3.2.x86_64.rpm'",+ }),+ );+ });++ test('boot with a staged update: the PERSISTED path powers the fallback before any updater event', async () => {+ // The standard Linux flow — download, quit, boot, click Relaunch. The+ // banner (restored from versionPendingInstall) is clickable long before+ // the launch check re-validates the ~250 MB cache and re-emits+ // update-downloaded, so the fallback must work from state alone.+ const { rig, fallback } = makeLinuxRig({+ hasGraphicalAuth: false,+ emitDownloadEvent: false,+ stateStagedInstallerPath: STAGED_DEB,+ });+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(rig.updater.quitAndInstall).not.toHaveBeenCalled();+ expect(fallback).toHaveBeenCalledWith({+ version: '0.3.2',+ installerPath: STAGED_DEB,+ packageKind: 'deb',+ command: `sudo apt install -- '${STAGED_DEB}'`,+ });+ });++ test('a persisted path whose file is gone falls through to quitAndInstall', async () => {+ const { rig, fallback } = makeLinuxRig({+ hasGraphicalAuth: false,+ emitDownloadEvent: false,+ stateStagedInstallerPath: STAGED_DEB,+ stagedInstallerExists: () => false,+ });+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);+ expect(fallback).not.toHaveBeenCalled();+ });++ test('update-downloaded persists the staged installer path alongside the banner gate', () => {+ const { rig } = makeRig({ platform: 'linux' });+ rig.updater.emit('update-downloaded', { version: '0.9.9', downloadedFile: STAGED_DEB });+ expect(rig.state.versionPendingInstall).toBe('0.9.9');+ expect(rig.state.stagedInstallerPath).toBe(STAGED_DEB);+ });++ test('stale-pending reconciliation clears the persisted staged path with the gate', () => {+ const { rig } = makeRig({+ appVersion: '0.3.2',+ versionPendingInstall: '0.3.2',+ stagedInstallerPath: STAGED_DEB,+ });+ expect(rig.state.versionPendingInstall).toBeNull();+ expect(rig.state.stagedInstallerPath).toBeNull();+ });++ test('non-linux platforms never trigger the fallback even when wired', async () => {+ const fallback = vi.fn(() => Promise.resolve());+ const { rig } = makeRig({+ platform: 'darwin',+ versionPendingInstall: '0.3.2',+ linuxInstallSupport: {+ hasGraphicalAuth: () => false,+ showManualInstallFallback: fallback,+ },+ });+ rig.updater.emit('update-downloaded', { version: '0.3.2', downloadedFile: STAGED_DEB });+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);+ rig.updater.emit('error', new Error('Command pkexec exited with code 127'));+ expect(fallback).not.toHaveBeenCalled();+ });+});diff --git a/packages/desktop/tests/unit/electron-builder-cli-native-deps.test.ts b/packages/desktop/tests/unit/electron-builder-cli-native-deps.test.tsindex f56b4d789..760e2d752 100644--- a/packages/desktop/tests/unit/electron-builder-cli-native-deps.test.ts+++ b/packages/desktop/tests/unit/electron-builder-cli-native-deps.test.ts@@ -31,7 +31,7 @@ const tsdownConfig = resolve(desktopRoot, '..', 'cli', 'tsdown.config.ts');const okRoot = resolve(desktopRoot, '..', '..');/**- * Natives intentionally NOT shipped into cli/node_modules, each with its+ * Externals intentionally NOT shipped into cli/node_modules, each with its* reason. Every entry asserts "we considered this and decided the bundled-CLI* path doesn't need it." Keep this set as small as possible — empty is ideal.*@@ -40,7 +40,17 @@ const okRoot = resolve(desktopRoot, '..', '..');* cli/node_modules` rule (see `stage-parcel-watcher.mjs`), so it is covered* below through `shippedViaParcelStaging`, not allowlisted.*/-const KNOWN_UNCOVERED: Record<string, string> = {};+const KNOWN_UNCOVERED: Record<string, string> = {+ // External ONLY in the CLI package's library build (dist/index.mjs), which+ // nothing under resources/cli ever executes — the wrapper bins and every+ // desktop spawn run dist/cli.mjs (+ parse-worker.mjs), whose build keeps+ // yjs inlined precisely because resources/cli has no node_modules. The+ // library entry's consumer is the desktop main/utility import of+ // '@inkeep/open-knowledge' from app.asar, where yjs ships as a regular+ // collected dependency (the same mechanism -server's external yjs already+ // relies on).+ yjs: 'library-entry-only external; cli.mjs inlines yjs and is the only entry resources/cli runs',+};/*** @parcel/watcher ships as a whole staged tree copied to `cli/node_modules`@@ -91,19 +101,30 @@ function readNeverBundle(): string[] {);}const src = readFileSync(tsdownConfig, 'utf8');- const m = /neverBundle:\s*\[([^\]]*)\]/.exec(src);- if (!m) {+ // The config declares the native-addon externals once as a shared+ // `nativeAddonNeverBundle` const and composes each build's `neverBundle`+ // from it (bare reference for the standalone build, spread + extras for the+ // library build). Parse the const literal, then union in any extra quoted+ // entries from the per-build `neverBundle:` lists so a build-specific+ // external (e.g. the library entry's 'yjs') still surfaces here.+ const constMatch = /const nativeAddonNeverBundle\s*=\s*\[([^\]]*)\]/.exec(src);+ if (!constMatch) {throw new Error(- `could not locate a \`neverBundle: [...]\` array literal in ${tsdownConfig}. If the ` +- `option is now computed rather than written inline, this guard needs a real parser — ` ++ `could not locate the \`nativeAddonNeverBundle = [...]\` array literal in ${tsdownConfig}. ` ++ `If the externals list moved or is now computed, this guard needs a real parser — ` +`it must not silently fall back to an empty list.`,);}- const entries = [...m[1].matchAll(/['"]([^'"]+)['"]/g)].map((x) => x[1] as string);- if (entries.length === 0) {+ const quoted = (block: string): string[] =>+ [...block.matchAll(/['"]([^'"]+)['"]/g)].map((x) => x[1] as string);+ const entries = new Set(quoted(constMatch[1] as string));+ for (const m of src.matchAll(/neverBundle:\s*\[([^\]]*)\]/g)) {+ for (const name of quoted(m[1] as string)) entries.add(name);+ }+ if (entries.size === 0) {throw new Error(`matched \`neverBundle\` in ${tsdownConfig} but extracted no package names.`);}- return entries;+ return [...entries];}function readExtraResourceTargets(platform?: 'mac' | 'win' | 'linux'): string[] {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 298c46d1d..4ba78cbda 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -807,6 +807,9 @@ importers:yazl:specifier: ^3.3.1version: 3.3.1+ yjs:+ specifier: ^13.6.30+ version: 13.6.31zod:specifier: ^4.3.6version: 4.4.3