Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix(desktop): complete updates without blocking shutdown
leepokaib630478a4cf7
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 307fcb38..384557c5 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -1,7 +1,7 @@import { execFileSync } from 'node:child_process'import { hostname } from 'node:os'import { join } from 'node:path'-import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeTheme, session, shell } from 'electron'+import { app, autoUpdater, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeTheme, session, shell } from 'electron'import type { HostSnapshot, WindowCommand } from '../shared/ipc'import { devPort, fetchHealth, HostController } from './host-controller'import { registerHostProxy } from './host-proxy'@@ -15,6 +15,7 @@ import { registerSpeech } from './speech'import { registerScreenIPC } from './screen'import { registerCloud } from './cloud'import { registerSSH } from './ssh'+import { QuitLifecycle } from './quit-lifecycle'/** macOS's user-facing computer name, else the host name. */function computerName() {@@ -34,7 +35,7 @@ const account = new AccountService()const updates = new Updates(host)let chat: BrowserWindow | null = nulllet pairing: BrowserWindow | null = null-let quitting = false+const quitLifecycle = new QuitLifecycle(app, autoUpdater)const isMac = process.platform === 'darwin'function rendererURL(page: string) {@@ -70,11 +71,7 @@ function openChat() {// CODYNC_SHOW_INACTIVE: development and UI checks open the window without taking focus.chat.on('ready-to-show', () => (process.env.CODYNC_SHOW_INACTIVE ? chat?.showInactive() : chat?.show()))// Closing hides: the window keeps the stores (and the menu bar's data) alive.- chat.on('close', (e) => {- if (quitting) return- e.preventDefault()- chat?.hide()- })+ chat.on('close', (e) => quitLifecycle.closeToBackground(e, () => chat?.hide()))chat.on('closed', () => (chat = null))chat.webContents.setWindowOpenHandler(({ url }) => {void shell.openExternal(url)@@ -189,7 +186,7 @@ function registerIPC(tray: Tray) {await rm(dataDir, { recursive: true, force: true })await rm(app.getPath('userData'), { recursive: true, force: true })app.relaunch()- quitting = true+ quitLifecycle.beginQuit()app.exit(0)})}@@ -203,7 +200,6 @@ if (!app.requestSingleInstanceLock()) {if (url) handleURL(url)else openChat()})- app.on('before-quit', () => (quitting = true))app.on('activate', () => openChat())app.on('window-all-closed', () => {// A menu bar app: it keeps running with no window.diff --git a/apps/desktop/src/main/quit-lifecycle.ts b/apps/desktop/src/main/quit-lifecycle.tsnew file mode 100644index 00000000..8797adba--- /dev/null+++ b/apps/desktop/src/main/quit-lifecycle.ts@@ -0,0 +1,22 @@+import type { EventEmitter } from 'node:events'++/** Keeps ordinary window closes in the background, but lets installers exit. */+export class QuitLifecycle {+ private quitting = false++ constructor(app: Pick<EventEmitter, 'on'>, updater: Pick<EventEmitter, 'on'>) {+ app.on('before-quit', () => this.beginQuit())+ // Native macOS updates close windows BEFORE app's before-quit event.+ updater.on('before-quit-for-update', () => this.beginQuit())+ }++ beginQuit() {+ this.quitting = true+ }++ closeToBackground(event: { preventDefault(): void }, hide: () => void) {+ if (this.quitting) return+ event.preventDefault()+ hide()+ }+}diff --git a/apps/desktop/src/main/updates.ts b/apps/desktop/src/main/updates.tsindex 80520058..aaf43217 100644--- a/apps/desktop/src/main/updates.ts+++ b/apps/desktop/src/main/updates.ts@@ -32,6 +32,8 @@ export class Updates extends EventEmitter {private userInitiated = falseprivate preparing: Promise<boolean> | null = nullprivate prepared = false+ private installing = false+ private updateGeneration = 0private appStoreVersion: string | null = nullconstructor(private host: HostController) {@@ -60,15 +62,7 @@ export class Updates extends EventEmitter {if (this.userInitiated) void this.install()else this.installWhenIdle()})- autoUpdater.on('error', (error) => {- // An install that failed after the host was stopped puts the host back.- if (this.prepared) {- this.prepared = false- this.host.resumeAfterCancelledUpdate()- }- this.checked({ error: this.userInitiated || this.state.staged ? error.message : null })- this.userInitiated = false- })+ autoUpdater.on('error', (error) => this.failed(error))// A staged update installs on Quit, once the host has actually stopped.app.on('before-quit', (event) => {@@ -102,6 +96,19 @@ export class Updates extends EventEmitter {this.set({ checking: false, lastCheck: now, ...change })}+ private failed(error: unknown) {+ this.updateGeneration+++ this.installing = false+ // A preparation still stopping the host restores it after stop completes.+ if (this.prepared) {+ this.prepared = false+ this.host.resumeAfterCancelledUpdate()+ }+ const message = error instanceof Error ? error.message : String(error)+ this.checked({ error: this.userInitiated || this.state.staged ? message : null })+ this.userInitiated = false+ }+/** Daily, or hourly while a release waits for the iPhone app to pass review. */private scheduled() {if (!this.state.autoCheck || this.state.checking || this.state.staged) return@@ -170,9 +177,14 @@ export class Updates extends EventEmitter {private prepare(): Promise<boolean> {if (this.prepared) return Promise.resolve(true)+ const generation = this.updateGenerationthis.preparing ??= (async () => {try {await this.host.prepareForUpdate()+ if (generation !== this.updateGeneration) {+ this.host.resumeAfterCancelledUpdate()+ return false+ }this.prepared = truethis.set({ error: null })return true@@ -188,7 +200,14 @@ export class Updates extends EventEmitter {}private async install() {- if (await this.prepare()) autoUpdater.quitAndInstall(true, true)+ if (this.installing) return+ this.installing = true+ try {+ if (await this.prepare()) autoUpdater.quitAndInstall(true, true)+ else this.installing = false+ } catch (error) {+ this.failed(error)+ }}}diff --git a/apps/desktop/src/shared/host-update.test.ts b/apps/desktop/src/shared/host-update.test.tsnew file mode 100644index 00000000..cbdcc4ba--- /dev/null+++ b/apps/desktop/src/shared/host-update.test.ts@@ -0,0 +1,105 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { hostUpdateFixture } from './test-support/host-update.ts'+import { settle } from './test-support/main-module.ts'++for (const platform of ['darwin', 'win32']) {+ test(`${platform}: updating stops the bundled host after unregistering screen and persists restart`, async () => {+ const f = hostUpdateFixture({ platform })+ await f.host.prepareForUpdate()+ await settle()+ assert.deepEqual(f.order, ['unregisterScreen', 'stop'])+ assert.equal(f.persisted.hostRestartAfterAppUpdate, true)+ await f.host.refresh()+ assert.deepEqual(f.calls, [['stop']], 'refresh cannot restart the host during replacement')+ assert.equal(await f.host.isIdleForUpdate(), false)+ })+}++for (const options of [{ platform: 'linux' }, { devPort: '19333' }]) {+ test(`app replacement leaves externally managed hosts running: ${JSON.stringify(options)}`, async () => {+ const f = hostUpdateFixture(options)+ await f.host.prepareForUpdate()+ assert.equal(f.calls.length, 0)+ assert.equal(f.order.length, 0)+ assert.equal(f.prefs.get('hostRestartAfterAppUpdate'), false)+ })+}++test('an install already in progress prevents update preparation from stopping the host', async () => {+ const f = hostUpdateFixture()+ const installing = f.host.install()+ await settle()+ await assert.rejects(f.host.prepareForUpdate(), /being installed/)+ assert.equal(f.calls.some((args) => args[0] === 'stop'), false)+ await f.tick(1000)+ await installing+})++test('missing bundled binary rejects preparation without pretending stop succeeded', async () => {+ const f = hostUpdateFixture({ missingBinary: true })+ await assert.rejects(f.host.prepareForUpdate(), /bundled host is missing/)+ assert.equal(f.calls.length, 0)+})++test('failed stop reports the error and cancellation reinstalls the service once', async () => {+ const f = hostUpdateFixture()+ f.behavior.stopStatus = 1+ await assert.rejects(f.host.prepareForUpdate(), /service command failed/)+ f.host.resumeAfterCancelledUpdate()+ f.host.resumeAfterCancelledUpdate()+ assert.deepEqual(f.calls, [['stop'], ['install', '--port', '19222']])+ await f.tick(1000)+})++test('new app launch reinstalls the host and clears restart marker only after health matches', async () => {+ const f = hostUpdateFixture({ restartMarker: true })+ const starting = f.host.refresh()+ await settle()+ assert.deepEqual(f.calls, [['install', '--port', '19222']])+ assert.equal(f.prefs.get('hostRestartAfterAppUpdate'), true)+ f.behavior.reachable = false+ await f.tick(1000)+ await starting+ assert.equal(f.prefs.get('hostRestartAfterAppUpdate'), true)+ f.behavior.reachable = true+ await f.tick(5000)+ assert.equal(f.host.state.kind, 'running')+ assert.equal(f.host.local?.computerId, 'fixture-computer')+ assert.equal(f.prefs.get('hostRestartAfterAppUpdate'), false)+})++test('a stale host binary cannot satisfy the restart marker', async () => {+ const f = hostUpdateFixture({ restartMarker: true })+ f.behavior.wrongBinary = true+ const starting = f.host.refresh()+ await settle()+ await f.tick(1000)+ await starting+ assert.equal(f.prefs.get('hostRestartAfterAppUpdate'), true)+ assert.notEqual(f.host.state.kind, 'running')+})++test('failed service installation keeps the restart marker and exposes the error', async () => {+ const f = hostUpdateFixture({ restartMarker: true })+ f.behavior.installStatus = 1+ await f.host.refresh()+ assert.equal(f.prefs.get('hostRestartAfterAppUpdate'), true)+ assert.equal(f.host.state.kind, 'failed')+ if (f.host.state.kind === 'failed') assert.match(f.host.state.message, /service command failed/)+})++test('an uninstalled host does not acquire a restart marker', async () => {+ const f = hostUpdateFixture({ installed: false })+ await f.host.prepareForUpdate()+ assert.equal(f.prefs.get('hostRestartAfterAppUpdate'), false)+})++test('idle detection distinguishes working, offline and idle hosts', async () => {+ const f = hostUpdateFixture()+ assert.equal(await f.host.isIdleForUpdate(), true)+ f.behavior.busy = true+ assert.equal(await f.host.isIdleForUpdate(), false)+ f.behavior.reachable = false+ assert.equal(await f.host.isIdleForUpdate(), false)+})diff --git a/apps/desktop/src/shared/quit-lifecycle.test.ts b/apps/desktop/src/shared/quit-lifecycle.test.tsnew file mode 100644index 00000000..02ea1117--- /dev/null+++ b/apps/desktop/src/shared/quit-lifecycle.test.ts@@ -0,0 +1,55 @@+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'+import test from 'node:test'+import { QuitLifecycle } from '../main/quit-lifecycle.ts'++function fixture() {+ const app = new EventEmitter()+ const updater = new EventEmitter()+ const lifecycle = new QuitLifecycle(app, updater)+ const close = () => {+ let prevented = false+ let hidden = false+ lifecycle.closeToBackground({ preventDefault: () => { prevented = true } }, () => { hidden = true })+ return { prevented, hidden }+ }+ return { app, updater, lifecycle, close }+}++test('closing a window keeps the app running in the background', () => {+ const { close } = fixture()+ assert.deepEqual(close(), { prevented: true, hidden: true })+})++test('ordinary Quit lets the chat window close', () => {+ const { app, close } = fixture()+ app.emit('before-quit')+ assert.deepEqual(close(), { prevented: false, hidden: false })+})++test('a native update can close windows before app before-quit fires', () => {+ const { app, updater, close } = fixture()+ let appQuitStarted = false+ app.on('before-quit', () => { appQuitStarted = true })+ updater.emit('before-quit-for-update')+ assert.equal(appQuitStarted, false)+ assert.deepEqual(close(), { prevented: false, hidden: false })+ assert.deepEqual(close(), { prevented: false, hidden: false })+ app.emit('before-quit')+ assert.deepEqual(close(), { prevented: false, hidden: false })+})++test('checking and staging an update do not change ordinary close behavior', () => {+ const { updater, close } = fixture()+ for (const event of ['checking-for-update', 'update-available', 'update-downloaded', 'update-not-available']) {+ updater.emit(event)+ assert.deepEqual(close(), { prevented: true, hidden: true })+ }+})++test('explicit shutdown allows a previously hidden window to close', () => {+ const { lifecycle, close } = fixture()+ assert.deepEqual(close(), { prevented: true, hidden: true })+ lifecycle.beginQuit()+ assert.deepEqual(close(), { prevented: false, hidden: false })+})diff --git a/apps/desktop/src/shared/test-support/host-update.ts b/apps/desktop/src/shared/test-support/host-update.tsnew file mode 100644index 00000000..d57b0c7b--- /dev/null+++ b/apps/desktop/src/shared/test-support/host-update.ts@@ -0,0 +1,69 @@+import { EventEmitter } from 'node:events'+import * as crypto from 'node:crypto'+import * as path from 'node:path'+import { loadMainModule, settle } from './main-module.ts'++export function hostUpdateFixture(options: { platform?: string; devPort?: string; installed?: boolean; missingBinary?: boolean; restartMarker?: boolean } = {}) {+ const platform = options.platform ?? 'darwin'+ const binary = platform === 'win32' ? '/bundle/codync-host.exe' : platform === 'linux' ? '/home/test/.local/bin/codync-host' : '/bundle/codync-host'+ const binaryBytes = Buffer.from('new signed host fixture')+ const persisted: Record<string, unknown> = { hostRestartAfterAppUpdate: options.restartMarker ?? false }+ const calls: string[][] = []+ const order: string[] = []+ const timers = new Map<number, { callback: () => void; ms: number }>()+ let timerId = 0+ const behavior = {+ stopStatus: 0,+ installStatus: 0,+ installed: options.installed ?? true,+ busy: false,+ reachable: true,+ wrongBinary: false,+ }+ const service = () => {+ if (!behavior.installed) throw new Error('No service')+ return binary.replace(/codync-host\.exe$/, 'codync-hostw.exe')+ }+ const fs = {+ existsSync: (name: string) => !options.missingBinary && name === binary,+ realpathSync: (name: string) => name,+ readFileSync: (name: string) => name.endsWith('host-prefs.json') ? JSON.stringify(persisted) : service(),+ promises: {+ mkdir: async () => {},+ writeFile: async (_name: string, value: string) => { Object.assign(persisted, JSON.parse(value)) },+ readFile: async (name: string) => name.endsWith('/token') ? 'fixture-token' : binaryBytes,+ },+ }+ const module = loadMainModule<typeof import('../../main/host-controller.ts')>('host-controller', {+ 'node:events': { EventEmitter }, 'node:crypto': crypto, 'node:path': path, 'node:fs': fs,+ 'node:os': { homedir: () => '/home/test', platform: () => platform },+ 'node:child_process': {+ execFileSync: () => service(),+ execFile: (_bin: string, args: string[], _options: unknown, callback: (error: { code: number } | null, stdout: string, stderr: string) => void) => {+ calls.push([...args]); order.push(args[0]!)+ const status = args[0] === 'stop' ? behavior.stopStatus : behavior.installStatus+ callback(status ? { code: status } : null, '', status ? 'service command failed' : '')+ },+ },+ electron: { app: { isPackaged: true, getPath: () => '/prefs' } },+ './screen': { unregisterScreenAgent: () => { order.push('unregisterScreen') } },+ }, {+ process: { env: options.devPort ? { CODYNC_PORT: options.devPort } : {}, resourcesPath: '/bundle' },+ setTimeout: (callback: () => void, ms: number) => { const id = ++timerId; timers.set(id, { callback, ms }); return id },+ clearTimeout: (id: number) => timers.delete(id),+ fetch: async () => {+ if (!behavior.reachable) throw new Error('Host offline')+ return { ok: true, json: async () => ({ computerId: 'fixture-computer', busy: behavior.busy, binaryPath: binary, binaryHash: behavior.wrongBinary ? 'stale' : crypto.createHash('sha256').update(binaryBytes).digest('hex') }) }+ },+ })+ const host = new module.HostController()+ const tick = async (ms: number) => {+ for (const [id, timer] of [...timers]) {+ if (timer.ms !== ms) continue+ timers.delete(id)+ timer.callback()+ }+ await settle()+ }+ return { host, prefs: module.prefs, persisted, calls, order, behavior, tick }+}diff --git a/apps/desktop/src/shared/test-support/main-module.ts b/apps/desktop/src/shared/test-support/main-module.tsnew file mode 100644index 00000000..71652cce--- /dev/null+++ b/apps/desktop/src/shared/test-support/main-module.ts@@ -0,0 +1,32 @@+import { readFileSync } from 'node:fs'+import { createContext, Script } from 'node:vm'+import ts from 'typescript'++/** Runs the actual main-process source with explicit, fail-closed OS boundaries. */+export function loadMainModule<T>(file: string, dependencies: Record<string, unknown>, globals: Record<string, unknown> = {}): T {+ const url = new URL(`../../main/${file}.ts`, import.meta.url)+ const output = ts.transpileModule(readFileSync(url, 'utf8'), {+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2023, esModuleInterop: true },+ fileName: url.pathname,+ }).outputText+ const exports = {}+ const context = createContext({+ exports, Error, Promise, console, AbortSignal,+ require: (name: string) => {+ if (!(name in dependencies)) throw new Error(`Unmocked main-process dependency: ${name}`)+ return dependencies[name]+ },+ ...globals,+ })+ new Script(output, { filename: url.pathname }).runInContext(context)+ return exports as T+}++export function deferred<T = void>() {+ let resolve!: (value: T | PromiseLike<T>) => void+ let reject!: (reason: unknown) => void+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no })+ return { promise, resolve, reject }+}++export const settle = () => new Promise<void>((resolve) => setImmediate(resolve))diff --git a/apps/desktop/src/shared/test-support/updater.ts b/apps/desktop/src/shared/test-support/updater.tsnew file mode 100644index 00000000..435b2ea1--- /dev/null+++ b/apps/desktop/src/shared/test-support/updater.ts@@ -0,0 +1,89 @@+import { EventEmitter } from 'node:events'+import * as compat from '../compat.ts'+import type { UpdateState } from '../ipc.ts'+import { loadMainModule, settle } from './main-module.ts'++interface UpdatesInstance extends EventEmitter {+ state: UpdateState+ register(windows: () => unknown[]): void+ check(): void+ setAutoCheck(on: boolean): void+ setAutoDownload(on: boolean): void+}++export function updaterFixture(options: { packaged?: boolean; main?: boolean; prefs?: Record<string, unknown> } = {}) {+ const calls = { check: 0, download: 0, install: 0, prepare: 0, resume: 0, quit: 0, fetch: 0 }+ const preferences = new Map(Object.entries(options.prefs ?? {}))+ const timers = new Map<number, { callback: () => unknown; ms: number }>()+ let nextTimer = 0+ let now = Date.UTC(2026, 9, 9)+ const behavior = {+ prepare: async () => {},+ check: async () => {},+ download: async () => {},+ install: () => {},+ hostFactsFail: false,+ minApp: '2.0.0',+ devices: [{ platform: 'ios' }],+ storeVersion: '2.0.0' as string | null,+ focused: false,+ idleSeconds: 600,+ hostIdle: true,+ }+ const app = Object.assign(new EventEmitter(), {+ isPackaged: options.packaged ?? true,+ quit: () => { calls.quit++ },+ })+ const handlers = new Map<string, (...args: unknown[]) => unknown>()+ const ipc = Object.assign(new EventEmitter(), {+ handle: (name: string, fn: (...args: unknown[]) => unknown) => handlers.set(name, fn),+ })+ const updater = Object.assign(new EventEmitter(), {+ autoDownload: true,+ autoInstallOnAppQuit: false,+ checkForUpdates: async () => { calls.check++; updater.emit('checking-for-update'); await behavior.check() },+ downloadUpdate: async () => { calls.download++; await behavior.download() },+ quitAndInstall: () => { calls.install++; behavior.install() },+ })+ const host = {+ prepareForUpdate: async () => { calls.prepare++; await behavior.prepare() },+ resumeAfterCancelledUpdate: () => { calls.resume++ },+ isIdleForUpdate: async () => behavior.hostIdle,+ call: async (method: string) => {+ if (behavior.hostFactsFail) throw new Error('Host unreachable')+ return method === 'hello' ? { minApp: behavior.minApp } : { devices: behavior.devices }+ },+ }+ const timer = (callback: () => unknown, ms: number) => {+ const id = ++nextTimer+ timers.set(id, { callback, ms })+ return id+ }+ const { Updates } = loadMainModule<{ Updates: new (host: unknown) => UpdatesInstance }>('updates', {+ 'node:events': { EventEmitter },+ electron: { app, ipcMain: ipc, BrowserWindow: { getFocusedWindow: () => behavior.focused }, powerMonitor: { getSystemIdleTime: () => behavior.idleSeconds } },+ 'electron-updater': { autoUpdater: updater },+ '../shared/compat': compat,+ './account': { isMainEnvironment: () => options.main ?? true },+ './host-controller': { prefs: { get: (key: string) => preferences.get(key), set: (key: string, value: unknown) => preferences.set(key, value) } },+ }, {+ Date: class extends Date { static override now() { return now } },+ setTimeout: timer, setInterval: timer, clearInterval: (id: number) => timers.delete(id),+ fetch: async () => {+ calls.fetch+++ if (behavior.storeVersion === null) throw new Error('Offline')+ return { json: async () => ({ results: [{ version: behavior.storeVersion }] }) }+ },+ })+ const updates = new Updates(host)+ const sent: { window: number; channel: string; state: UpdateState }[] = []+ updates.register(() => [0, 1].map((window) => ({ webContents: { send: (channel: string, state: UpdateState) => sent.push({ window, channel, state: { ...state } }) } })))+ const emit = async (event: string, value?: unknown) => { updater.emit(event, value); await settle() }+ const tick = async (ms: number) => {+ for (const [id, entry] of [...timers]) {+ if (entry.ms === ms && timers.has(id)) await entry.callback()+ }+ await settle()+ }+ return { updates, app, ipc, handlers, updater, calls, behavior, preferences, sent, timers, emit, tick, advance: (ms: number) => { now += ms } }+}diff --git a/apps/desktop/src/shared/updates.test.ts b/apps/desktop/src/shared/updates.test.tsnew file mode 100644index 00000000..a3568e8f--- /dev/null+++ b/apps/desktop/src/shared/updates.test.ts@@ -0,0 +1,307 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { EventEmitter } from 'node:events'+import { QuitLifecycle } from '../main/quit-lifecycle.ts'+import { deferred, settle } from './test-support/main-module.ts'+import { updaterFixture } from './test-support/updater.ts'++const release = { version: '2.11.3' }++for (const options of [{ packaged: false }, { main: false }]) {+ test(`development builds never check, download or install: ${JSON.stringify(options)}`, async () => {+ const f = updaterFixture(options)+ f.updates.check()+ await f.emit('update-downloaded', release)+ assert.equal(f.updates.state.supported, false)+ assert.equal(f.updates.state.canCheck, false)+ assert.equal(f.calls.check + f.calls.download + f.calls.install, 0)+ assert.equal(f.timers.size, 0)+ })+}++test('manual check broadcasts checking, release, staged states to every window', async () => {+ const f = updaterFixture()+ const stopped = deferred()+ f.behavior.prepare = () => stopped.promise+ f.ipc.emit('updates:check')+ assert.equal(f.updates.state.checking, true)+ assert.equal(f.handlers.get('updates:state')?.(), f.updates.state)+ await f.emit('update-available', release)+ assert.equal(f.calls.download, 1)+ assert.equal(f.updates.state.availableVersion, release.version)+ assert.equal(f.updates.state.checking, false)+ await f.emit('update-downloaded', release)+ assert.equal(f.updates.state.staged, true)+ assert.equal(f.calls.prepare, 1)+ assert.equal(f.calls.install, 0, 'must wait until the host stops')+ for (const window of [0, 1]) {+ const states = f.sent.filter((s) => s.window === window)+ assert.ok(states.every((s) => s.channel === 'updates:change'))+ assert.ok(states.some((s) => s.state.checking))+ assert.ok(states.some((s) => s.state.availableVersion === release.version))+ assert.ok(states.some((s) => s.state.staged))+ }+ stopped.resolve()+ await settle()+ assert.equal(f.calls.install, 1)+})++test('latest version records the last check without downloading or stopping the host', async () => {+ const f = updaterFixture()+ f.updates.check()+ await f.emit('update-not-available')+ assert.equal(f.updates.state.checking, false)+ assert.equal(f.updates.state.availableVersion, null)+ assert.equal(f.preferences.get('updatesLastCheck'), f.updates.state.lastCheck)+ assert.equal(f.calls.download + f.calls.prepare + f.calls.install, 0)+})++test('host stop failure preserves the staged release, reports an error and permits retry', async () => {+ const f = updaterFixture()+ f.behavior.prepare = async () => { throw new Error('stop failed') }+ f.updates.check()+ await f.emit('update-downloaded', release)+ assert.equal(f.calls.install, 0)+ assert.equal(f.calls.resume, 1)+ assert.equal(f.updates.state.error, 'Update paused: stop failed')+ assert.equal(f.updates.state.staged, true)+ f.behavior.prepare = async () => {}+ f.updates.check()+ await settle()+ assert.equal(f.calls.prepare, 2)+ assert.equal(f.calls.install, 1)+ assert.equal(f.updates.state.error, null)+ assert.equal(f.calls.download, 0, 'retry uses the staged archive')+})++test('installer error restarts the stopped host and retry prepares it again', async () => {+ const f = updaterFixture()+ f.updates.check()+ await f.emit('update-downloaded', release)+ await f.emit('error', new Error('signature rejected'))+ assert.equal(f.calls.resume, 1)+ assert.equal(f.updates.state.error, 'signature rejected')+ f.updates.check()+ await settle()+ assert.equal(f.calls.prepare, 2)+ assert.equal(f.calls.install, 2)+})++test('download errors are visible for manual checks without restarting a running host', async () => {+ const f = updaterFixture()+ f.updates.check()+ await f.emit('update-available', release)+ await f.emit('error', new Error('network disconnected'))+ assert.equal(f.updates.state.error, 'network disconnected')+ assert.equal(f.updates.state.checking, false)+ assert.equal(f.calls.prepare + f.calls.resume + f.calls.install, 0)+ f.updates.check()+ assert.equal(f.updates.state.error, null)+ assert.equal(f.calls.check, 2)+})++test('normal Quit without a staged update leaves the host alone', () => {+ const f = updaterFixture()+ let prevented = false+ f.app.emit('before-quit', { preventDefault: () => { prevented = true } })+ assert.equal(prevented, false)+ assert.equal(f.calls.prepare, 0)+})++test('Quit with a staged update waits for the host then retries Quit once', async () => {+ const f = updaterFixture()+ await f.emit('update-downloaded', release)+ const stopped = deferred()+ f.behavior.prepare = () => stopped.promise+ let prevented = false+ f.app.emit('before-quit', { preventDefault: () => { prevented = true } })+ assert.equal(prevented, true)+ assert.equal(f.calls.quit, 0)+ stopped.resolve()+ await settle()+ assert.equal(f.calls.quit, 1)+ assert.equal(f.calls.install, 0)+ f.app.emit('before-quit', { preventDefault: () => assert.fail('prepared Quit must proceed') })+})++test('failed preparation cancels Quit and reports a retryable error', async () => {+ const f = updaterFixture()+ await f.emit('update-downloaded', release)+ f.behavior.prepare = async () => { throw new Error('busy') }+ f.app.emit('before-quit', { preventDefault() {} })+ await settle()+ assert.equal(f.calls.quit, 0)+ assert.equal(f.calls.resume, 1)+ assert.match(f.updates.state.error!, /busy/)+})++test('automatic checks respect opt-out and run daily after the startup check', async () => {+ const f = updaterFixture()+ await f.tick(30_000)+ assert.equal(f.calls.check, 1)+ await f.emit('update-not-available')+ f.advance(3600_000)+ await f.tick(3600_000)+ assert.equal(f.calls.check, 1)+ f.advance(23 * 3600_000)+ await f.tick(3600_000)+ assert.equal(f.calls.check, 2)+ await f.emit('update-not-available')+ f.updates.setAutoCheck(false)+ f.advance(24 * 3600_000)+ await f.tick(3600_000)+ assert.equal(f.calls.check, 2)+ assert.equal(f.preferences.get('updatesAutoCheck'), false)+})++test('background discovery downloads only after automatic download is enabled', async () => {+ const f = updaterFixture()+ await f.emit('update-available', release)+ assert.equal(f.calls.download, 0)+ f.ipc.emit('updates:autoDownload', {}, true)+ await f.emit('update-available', release)+ assert.equal(f.calls.download, 1)+ assert.equal(f.preferences.get('updatesAutoDownload'), true)+})++for (const block of ['disabled', 'focused', 'recentInput', 'busyHost'] as const) {+ test(`automatic install waits while ${block}, then installs once idle`, async () => {+ const f = updaterFixture({ prefs: { updatesAutoDownload: true } })+ if (block === 'disabled') f.updates.setAutoDownload(false)+ if (block === 'focused') f.behavior.focused = true+ if (block === 'recentInput') f.behavior.idleSeconds = 599+ if (block === 'busyHost') f.behavior.hostIdle = false+ await f.emit('update-downloaded', release)+ await f.tick(30_000)+ assert.equal(f.calls.prepare + f.calls.install, 0)+ f.updates.setAutoDownload(true)+ f.behavior.focused = false+ f.behavior.idleSeconds = 600+ f.behavior.hostIdle = true+ await f.tick(30_000)+ await f.tick(30_000)+ assert.equal(f.calls.prepare, 1)+ assert.equal(f.calls.install, 1)+ })+}++test('paired iPhones hold an incompatible release until the App Store catches up', async () => {+ const f = updaterFixture()+ f.updates.check()+ await f.emit('update-available', { ...release, minApp: '2.11.0' })+ assert.equal(f.updates.state.waitingForApp, '2.11.0')+ assert.match(f.updates.state.error!, /iPhone app 2.11.0/)+ assert.equal(f.calls.download, 0)+ f.behavior.storeVersion = '2.11.0'+ f.updates.check()+ await f.emit('update-available', { ...release, minApp: '2.11.0' })+ assert.equal(f.updates.state.waitingForApp, null)+ assert.equal(f.calls.download, 1)+})++for (const condition of ['noPhones', 'compatibleHost', 'manualOffline'] as const) {+ test(`compatibility permits download with ${condition}`, async () => {+ const f = updaterFixture()+ if (condition === 'noPhones') f.behavior.devices = []+ if (condition === 'compatibleHost') f.behavior.minApp = '2.11.0'+ if (condition === 'manualOffline') f.behavior.storeVersion = null+ f.updates.check()+ await f.emit('update-available', { ...release, minApp: '2.11.0' })+ assert.equal(f.updates.state.waitingForApp, null)+ assert.equal(f.calls.download, 1)+ })+}++test('unattended updates wait when App Store or paired-device information is unknown', async () => {+ const f = updaterFixture({ prefs: { updatesAutoDownload: true } })+ f.behavior.storeVersion = null+ f.behavior.hostFactsFail = true+ await f.emit('update-available', { ...release, minApp: '2.11.0' })+ assert.equal(f.calls.download, 0)+ assert.equal(f.updates.state.waitingForApp, '2.11.0')+ assert.equal(f.updates.state.error, null)+ f.advance(3600_000)+ await f.tick(3600_000)+ assert.equal(f.calls.check, 1, 'held releases recheck hourly')+})++test('repeated clicks during host shutdown must invoke the installer once', async () => {+ const f = updaterFixture()+ const stopped = deferred()+ f.behavior.prepare = () => stopped.promise+ f.updates.check()+ await f.emit('update-downloaded', release)+ f.updates.check()+ f.updates.check()+ stopped.resolve()+ await settle()+ assert.equal(f.calls.prepare, 1)+ assert.equal(f.calls.install, 1)+})++test('an updater error during host shutdown cancels installation and restores the host', async () => {+ const f = updaterFixture()+ const stopped = deferred()+ f.behavior.prepare = () => stopped.promise+ f.updates.check()+ await f.emit('update-downloaded', release)+ await f.emit('error', new Error('invalid archive'))+ stopped.resolve()+ await settle()+ assert.equal(f.calls.install, 0)+ assert.equal(f.calls.resume, 1)+ assert.equal(f.updates.state.error, 'invalid archive')+})++test('a synchronous installer failure restores the host and permits retry', async () => {+ const f = updaterFixture()+ f.behavior.install = () => { throw new Error('installer unavailable') }+ f.updates.check()+ await f.emit('update-downloaded', release)+ assert.equal(f.calls.resume, 1)+ assert.equal(f.updates.state.error, 'installer unavailable')+ f.behavior.install = () => {}+ f.updates.check()+ await settle()+ assert.equal(f.calls.prepare, 2)+ assert.equal(f.calls.install, 2)+})++test('an update error while preparing a normal Quit prevents that Quit', async () => {+ const f = updaterFixture()+ const stopped = deferred()+ f.behavior.prepare = () => stopped.promise+ await f.emit('update-downloaded', release)+ f.app.emit('before-quit', { preventDefault() {} })+ await f.emit('error', new Error('archive removed'))+ stopped.resolve()+ await settle()+ assert.equal(f.calls.quit, 0)+ assert.equal(f.calls.resume, 1)+ assert.equal(f.updates.state.error, 'archive removed')+})++test('manual installation crosses the native quit boundary after stopping the host', async () => {+ const f = updaterFixture()+ const nativeUpdater = new EventEmitter()+ const lifecycle = new QuitLifecycle(f.app, nativeUpdater)+ const stopped = deferred()+ f.behavior.prepare = () => stopped.promise+ let closed = false+ f.behavior.install = () => {+ nativeUpdater.emit('before-quit-for-update')+ lifecycle.closeToBackground(+ { preventDefault: () => assert.fail('native update must close the window') },+ () => assert.fail('native update must not hide the window'),+ )+ closed = true+ f.app.emit('before-quit', { preventDefault: () => assert.fail('host has already stopped') })+ }+ f.updates.check()+ await f.emit('update-downloaded', release)+ assert.equal(closed, false)+ stopped.resolve()+ await settle()+ assert.equal(closed, true)+ assert.equal(f.calls.install, 1)+})diff --git a/docs/guides/updates.md b/docs/guides/updates.mdindex 4e39fedb..515221e9 100644--- a/docs/guides/updates.md+++ b/docs/guides/updates.md@@ -27,6 +27,35 @@ persistent restart marker makes the next app launch reinstall the host service fthe new bundle; remote screen registration is restored when the host reports thatit is enabled. Ordinary Quit keeps the host running when no update is staged.+The desktop window's close-to-background handler also listens to Electron's native+`before-quit-for-update` event. On macOS, `quitAndInstall()` closes windows before+`app.before-quit`, so waiting for the latter blocks installation after the host has+already stopped. If an older release is stuck on **Update to …** after downloading,+choose **Codync → Quit Codync**: the staged installer can finish and relaunch the app.+This lifecycle fix is desktop-only; iOS uses the App Store, and the terminal client+uses the independent host updater without Electron windows.++Installation requests are single-flight while the host stops and the installer+starts. An updater error during shutdown cancels that pending installation and+restores the host after the stop finishes; an installer exception also restores+the host and leaves the staged release available to retry.++### Desktop updater regression tests++Run `cd apps/desktop && npm run typecheck && npm test`. The updater tests load the+actual main-process modules with fake Electron, service commands, network and+timers; they never stop a real host or replace an installed app. Coverage includes+manual and idle installation, renderer state broadcasts, download errors, repeated+clicks, errors during shutdown, staged Quit, host restart markers and binary health+checks, development-build exclusion, and iPhone compatibility holds. The native+quit event ordering has a separate regression test and an updater integration test.++The macOS and Windows bundled-host branches and Linux's externally managed host+branch run against simulated OS boundaries. These tests do not replace a signed+release upgrade on each OS, nor do they verify download progress rendering: the+current Updates page exposes checking, available/staged and error states but has+no download percentage or installation progress UI yet.+The release workflow publishes `latest-mac.yml` and `latest-linux*.yml` with theapp archives. macOS build versions follow the marketing version; the iOS buildcounter is independent. Installs of the SwiftUI Mac app that preceded the desktop