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): update in one click and keep installs from being cancelled
leepokai75a279625b44
diff --git a/apps/desktop/src/main/host-controller.ts b/apps/desktop/src/main/host-controller.tsindex 7fd2c5c7..4eb36d59 100644--- a/apps/desktop/src/main/host-controller.ts+++ b/apps/desktop/src/main/host-controller.ts@@ -1,7 +1,7 @@import { execFile, execFileSync } from 'node:child_process'import { createHash } from 'node:crypto'import { EventEmitter } from 'node:events'-import { existsSync, promises as fs, readFileSync, realpathSync } from 'node:fs'+import { existsSync, mkdirSync, promises as fs, readFileSync, realpathSync, writeFileSync } from 'node:fs'import { homedir, platform } from 'node:os'import { join, resolve } from 'node:path'import { app } from 'electron'@@ -385,7 +385,13 @@ export const prefs = (() => {set: (key: string, value: unknown) => {const data = load()data[key] = value- void fs.mkdir(app.getPath('userData'), { recursive: true }).then(() => fs.writeFile(file(), JSON.stringify(data)))+ // Synchronous: a marker set right before the app quits (an update install) must be on disk.+ try {+ mkdirSync(app.getPath('userData'), { recursive: true })+ writeFileSync(file(), JSON.stringify(data))+ } catch (error) {+ console.error(`prefs: couldn't save ${key}:`, error)+ }},}})()diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex d0745e4f..a8540d1d 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -11,7 +11,7 @@ import { readClipboardFiles, readFiles } from './files'import { Tray } from './tray'import { applyDockVisibility, setShowInDock, showInDock } from './dock'import { AccountService } from './account'-import { Updates } from './updates'+import { Updates, yieldsToInstall } from './updates'import { handleURL, registerAuthIPC, registerSchemes, urlFromArgv } from './auth'import { registerSpeech } from './speech'import { registerScreenIPC } from './screen'@@ -206,7 +206,9 @@ function registerIPC(tray: Tray) {})}-if (!app.requestSingleInstanceLock()) {+if (yieldsToInstall()) {+ app.exit(0)+} else if (!app.requestSingleInstanceLock()) {if (!app.isPackaged) console.error(`${app.getName()} is already running. Quit it first, or run another copy beside it: npm run dev -- --name <name>`)app.quit()} else {diff --git a/apps/desktop/src/main/updates.ts b/apps/desktop/src/main/updates.tsindex 75ad8e58..aa67aab0 100644--- a/apps/desktop/src/main/updates.ts+++ b/apps/desktop/src/main/updates.ts@@ -1,4 +1,4 @@-import { execFile } from 'node:child_process'+import { execFile, execFileSync, spawn } from 'node:child_process'import { EventEmitter } from 'node:events'import { existsSync } from 'node:fs'import { homedir } from 'node:os'@@ -19,6 +19,30 @@ const { autoUpdater } = electronUpdater* stopped first, and a restart marker makes the next launch reinstall it from the new bundle.*/const enabled = app.isPackaged && isMainEnvironment()+const shipIt = `${identity.appId}.ShipIt`++const bundlePath = () => join(app.getPath('exe'), '../../..')++/**+ * macOS's installer (ShipIt) cancels when the old app runs again while it swaps the bundle+ * ("App Still Running"), and someone who sees no window for those seconds opens it. An old copy+ * launched during an install quits at once and opens the app again once the installer stops:+ * the new release after an install, this one after a failed attempt.+ */+export function yieldsToInstall(): boolean {+ const pending = prefs.get('updateInstalling') as { version: string; at: number } | undefined+ if (!pending) return false+ const installing = pending.version !== app.getVersion() && Date.now() - pending.at < 120_000 && shipItRunning()+ if (installing) reopenAfterInstall()+ else prefs.set('updateInstalling', undefined)+ return installing+}++/** A detached wait (two minutes at most) for the installer job to stop, then `open`. */+function reopenAfterInstall() {+ const script = 'for _ in $(seq 120); do /bin/launchctl list "$0" 2>/dev/null | grep -q \'"PID" =\' || break; sleep 1; done; exec /usr/bin/open "$1"'+ spawn('/bin/sh', ['-c', script, shipIt, bundlePath()], { detached: true, stdio: 'ignore' }).unref()+}export class Updates extends EventEmitter {state: UpdateState = {@@ -62,7 +86,7 @@ export class Updates extends EventEmitter {// `app.focus` there (cooperative activation); opening its own bundle brings it forward.if (prefs.get('updateRelaunchInFront') === true) {prefs.set('updateRelaunchInFront', false)- if (process.platform === 'darwin') void shell.openPath(join(app.getPath('exe'), '../../..'))+ if (process.platform === 'darwin') void shell.openPath(bundlePath())}autoUpdater.autoDownload = false@@ -131,6 +155,7 @@ export class Updates extends EventEmitter {this.updateGeneration++this.installWhenDownloaded = falseprefs.set('updateRelaunchInFront', false)+ prefs.set('updateInstalling', undefined)// A preparation still stopping the host restores it after stop completes.if (this.prepared) {this.prepared = false@@ -201,6 +226,8 @@ export class Updates extends EventEmitter {return false}this.prepared = true+ // Both installer paths (Restart, and Quit with a staged update) pass here right before quitting.+ prefs.set('updateInstalling', { version: this.state.availableVersion, at: Date.now() })this.set({ error: null })return true} catch (error) {@@ -235,11 +262,20 @@ export class Updates extends EventEmitter {*/function removeStuckShipIt() {if (process.platform !== 'darwin') return- const label = `${identity.appId}.ShipIt`- if (existsSync(join(homedir(), 'Library/Caches', label, 'ShipItState.plist'))) return- execFile('/bin/launchctl', ['list', label], (error, stdout) => {+ if (existsSync(join(homedir(), 'Library/Caches', shipIt, 'ShipItState.plist'))) return+ execFile('/bin/launchctl', ['list', shipIt], (error, stdout) => {// Not submitted, or running right now (the next check finds it idle).if (error || stdout.includes('"PID" =')) return- execFile('/bin/launchctl', ['remove', label], () => {})+ execFile('/bin/launchctl', ['remove', shipIt], () => {})})}++function shipItRunning() {+ if (process.platform !== 'darwin') return false+ try {+ return execFileSync('/bin/launchctl', ['list', shipIt], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).includes('"PID" =')+ } catch {+ // Not submitted.+ return false+ }+}diff --git a/apps/desktop/src/renderer/components/Controls.tsx b/apps/desktop/src/renderer/components/Controls.tsxindex 01d08948..01bc16c6 100644--- a/apps/desktop/src/renderer/components/Controls.tsx+++ b/apps/desktop/src/renderer/components/Controls.tsx@@ -27,16 +27,41 @@ export function Button({ kind = 'primary', children, onClick, disabled, classNam/** Loading indicator: a thin arc that turns. */export function Spinner({ size = 14 }: { size?: number }) {- const w = Math.max(1.5, size / 9)- const r = (size - w) / 2- const c = 2 * Math.PI * r+ const { w, r, c, center } = ring(size)return (<svg className="spinner" width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-label="Loading" role="img">- <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--secondary)" strokeWidth={w} strokeLinecap="round" strokeDasharray={`${c * 0.7} ${c}`} />+ <circle cx={center} cy={center} r={r} fill="none" stroke="var(--secondary)" strokeWidth={w} strokeLinecap="round" strokeDasharray={`${c * 0.7} ${c}`} /></svg>)}+/** Determinate progress (`value` 0...1): a ring that fills clockwise, in the color around it. */+export function ProgressRing({ value, size = 14 }: { value: number; size?: number }) {+ const { w, r, c, center } = ring(size)+ return (+ <svg className="progress-ring" width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden>+ <circle className="progress-ring-track" cx={center} cy={center} r={r} strokeWidth={w} />+ <circle+ className="progress-ring-fill"+ cx={center}+ cy={center}+ r={r}+ strokeWidth={w}+ strokeDasharray={c}+ strokeDashoffset={c * (1 - value)}+ transform={`rotate(-90 ${center} ${center})`}+ />+ </svg>+ )+}++/** The geometry `Spinner` and `ProgressRing` share: stroke width, radius, circumference. */+function ring(size: number) {+ const w = Math.max(1.5, size / 9)+ const r = (size - w) / 2+ return { w, r, c: 2 * Math.PI * r, center: size / 2 }+}+/** On/off switch: label on the left, a flat capsule track on the right. *//** `label` names a switch whose visible label sits outside it (beside an info button, say). */export function Switch({ on, onChange, children, label, disabled, className }: { on: boolean; onChange: (on: boolean) => void; children?: ReactNode; label?: string; disabled?: boolean; className?: string }) {diff --git a/apps/desktop/src/renderer/components/controls.css b/apps/desktop/src/renderer/components/controls.cssindex 1c075fd4..b1d90df2 100644--- a/apps/desktop/src/renderer/components/controls.css+++ b/apps/desktop/src/renderer/components/controls.css@@ -41,10 +41,29 @@transform: rotate(360deg);}}++.progress-ring {+ flex: none;+}+.progress-ring circle {+ fill: none;+ stroke: currentColor;+}+.progress-ring-track {+ opacity: 0.3;+}+.progress-ring-fill {+ stroke-linecap: round;+ transition: stroke-dashoffset var(--hover);+}+@media (prefers-reduced-motion: reduce) {.spinner {animation: none;}+ .progress-ring-fill {+ transition: none;+ }}.switch {diff --git a/apps/desktop/src/renderer/views/UpdateButton.tsx b/apps/desktop/src/renderer/views/UpdateButton.tsxindex ecd4cdd8..66d52451 100644--- a/apps/desktop/src/renderer/views/UpdateButton.tsx+++ b/apps/desktop/src/renderer/views/UpdateButton.tsx@@ -1,9 +1,8 @@import { useEffect, useState } from 'react'import type { UpdateState } from '@shared/ipc'import { updateAction } from '@shared/update-action'-import { Button } from '../components/Controls'+import { Button, ProgressRing, Spinner } from '../components/Controls'import { Icon } from '../components/Icon'-import { Dialog } from '../components/Overlay'/** The app's update state, kept live. */export function useUpdates() {@@ -25,30 +24,31 @@ export function UpdateButton({ updates, kind = 'secondary' }: { updates: UpdateS)}-/** The sidebar's nudge while a release is available: Update, once confirmed, restarts into it. */+/**+ * The sidebar's Update: one tap downloads the release while Codync stays usable (a ring fills as+ * it downloads), then restarts into it.+ */export function UpdateBadge({ size }: { size: number }) {const updates = useUpdates()- const [confirming, setConfirming] = useState(false)if (!updates?.supported || !updates.availableVersion) return null+ const action = updateAction(updates)return (- <>- <button- className="update-badge"- style={{ width: size, height: size }}- title="Update"- aria-label="Update"- disabled={updates.installing}- onClick={() => setConfirming(true)}- >- <Icon name="arrow.down" size={size * 0.42} weight="semibold" />- </button>- <Dialog- open={confirming}- title={`Update to Codync ${updates.availableVersion}?`}- message="Codync restarts to install it."- actions={[{ title: 'Update', action: () => window.codync.updates.install() }]}- onClose={() => setConfirming(false)}- />- </>+ <button+ className="update-badge"+ style={{ width: size, height: size }}+ title={action.label}+ aria-label={action.label}+ aria-busy={updates.installing || updates.downloadPercent !== null}+ disabled={updates.installing}+ onClick={() => window.codync.updates.install()}+ >+ <BadgeIcon updates={updates} size={size} />+ </button>)}++function BadgeIcon({ updates, size }: { updates: UpdateState; size: number }) {+ if (updates.installing) return <Spinner size={size * 0.5} />+ if (updates.downloadPercent !== null) return <ProgressRing value={updates.downloadPercent / 100} size={size * 0.5} />+ return <Icon name="arrow.down" size={size * 0.42} weight="semibold" />+}diff --git a/apps/desktop/src/renderer/views/sidebar-footer.css b/apps/desktop/src/renderer/views/sidebar-footer.cssindex 54f31457..19407346 100644--- a/apps/desktop/src/renderer/views/sidebar-footer.css+++ b/apps/desktop/src/renderer/views/sidebar-footer.css@@ -89,7 +89,7 @@}.update-badge:hover:not(:disabled) { opacity: .85; }.update-badge:active:not(:disabled) { transform: scale(.94); }-.update-badge:disabled { opacity: .35; }+.update-badge .spinner circle { stroke: currentColor; }@keyframes update-badge-in { from { opacity: 0; transform: scale(.6); } }@media (prefers-reduced-motion: reduce) {diff --git a/apps/desktop/src/shared/test-support/host-update.ts b/apps/desktop/src/shared/test-support/host-update.tsindex 48fc3b10..d2226eaf 100644--- a/apps/desktop/src/shared/test-support/host-update.ts+++ b/apps/desktop/src/shared/test-support/host-update.ts@@ -32,9 +32,9 @@ export function hostUpdateFixture(options: { environment?: 'main' | 'dev'; platfexistsSync: (name: string) => !options.missingBinary && name === binary,realpathSync: (name: string) => name,readFileSync: (name: string) => name.endsWith('host-prefs.json') ? JSON.stringify(persisted) : service(),+ mkdirSync: () => {},+ writeFileSync: (_name: string, value: string) => { Object.assign(persisted, JSON.parse(value)) },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,},}diff --git a/apps/desktop/src/shared/test-support/updater.ts b/apps/desktop/src/shared/test-support/updater.tsindex 9f21af7d..86a47bc0 100644--- a/apps/desktop/src/shared/test-support/updater.ts+++ b/apps/desktop/src/shared/test-support/updater.ts@@ -17,14 +17,18 @@ export function updaterFixture(options: { packaged?: boolean; main?: boolean; prconst calls = { check: 0, download: 0, install: 0, prepare: 0, resume: 0, quit: 0 }// macOS's installer job: whether its update request exists, and its launchd state.const shipIt = { ...(options.shipIt ?? { request: true, job: 'idle' }), removed: 0 }+ const list = () => {+ if (shipIt.job === 'none') throw new Error('Could not find service')+ return shipIt.job === 'running' ? '{\n\t"PID" = 42;\n};' : '{\n\t"LastExitStatus" = 256;\n};'+ }const launchctl = (_bin: string, args: string[], done: (error: Error | null, stdout: string) => void) => {if (args[0] === 'remove') {shipIt.removed++return done(null, '')}- if (shipIt.job === 'none') return done(new Error('Could not find service'), '')- done(null, shipIt.job === 'running' ? '{\n\t"PID" = 42;\n};' : '{\n\t"LastExitStatus" = 256;\n};')+ try { done(null, list()) } catch (error) { done(error as Error, '') }}+ const spawned: string[][] = []const opened: string[] = []const preferences = new Map(Object.entries(options.prefs ?? {}))const timers = new Map<number, { callback: () => unknown; ms: number }>()@@ -43,6 +47,7 @@ export function updaterFixture(options: { packaged?: boolean; main?: boolean; prisPackaged: options.packaged ?? true,quit: () => { calls.quit++ },getPath: () => '/Applications/Codync.app/Contents/MacOS/Codync',+ getVersion: () => '2.11.2',})const handlers = new Map<string, (...args: unknown[]) => unknown>()const ipc = Object.assign(new EventEmitter(), {@@ -65,8 +70,12 @@ export function updaterFixture(options: { packaged?: boolean; main?: boolean; prtimers.set(id, { callback, ms })return id}- const { Updates } = loadMainModule<{ Updates: new (host: unknown) => UpdatesInstance }>('updates', {- 'node:child_process': { execFile: launchctl },+ const { Updates, yieldsToInstall } = loadMainModule<{ Updates: new (host: unknown) => UpdatesInstance; yieldsToInstall: () => boolean }>('updates', {+ 'node:child_process': {+ execFile: launchctl,+ execFileSync: list,+ spawn: (_bin: string, args: string[]) => { spawned.push([...args]); return { unref() {} } },+ },'node:events': { EventEmitter },'node:fs': { existsSync: (file: string) => shipIt.request && file === '/Users/me/Library/Caches/com.pokai.Codync.ShipIt/ShipItState.plist' },'node:os': { homedir: () => '/Users/me' },@@ -91,5 +100,5 @@ export function updaterFixture(options: { packaged?: boolean; main?: boolean; pr}await settle()}- return { updates, app, ipc, handlers, updater, calls, opened, behavior, preferences, sent, timers, shipIt, emit, tick, advance: (ms: number) => { now += ms } }+ return { updates, yieldsToInstall, app, ipc, handlers, updater, calls, opened, spawned, behavior, preferences, sent, timers, shipIt, emit, tick, now: () => now, advance: (ms: number) => { now += ms } }}diff --git a/apps/desktop/src/shared/updates.test.ts b/apps/desktop/src/shared/updates.test.tsindex 4bd6af71..bcb4e2e5 100644--- a/apps/desktop/src/shared/updates.test.ts+++ b/apps/desktop/src/shared/updates.test.ts@@ -82,6 +82,7 @@ test('the Update badge downloads the release if needed, then restarts into it',await f.emit('update-downloaded', release)assert.equal(f.calls.install, 1, 'restarts without a second click')assert.equal(f.preferences.get('updateRelaunchInFront'), true)+ assert.deepEqual({ ...f.preferences.get('updateInstalling') as object }, { version: release.version, at: f.now() })const staged = updaterFixture()await staged.emit('update-downloaded', release)@@ -91,6 +92,36 @@ test('the Update badge downloads the release if needed, then restarts into it',assert.equal(staged.calls.install, 1)})+test('the Update badge clicked during an automatic download restarts once it finishes', async () => {+ const f = updaterFixture()+ await f.emit('update-available', release)+ await f.emit('download-progress', { percent: 30 })+ f.ipc.emit('updates:install')+ assert.equal(f.calls.check, 0, 'the running download continues')+ await f.emit('update-downloaded', release)+ assert.equal(f.calls.install, 1)+})++test('an older copy opened while the installer runs quits and reopens the app once it stops', () => {+ const recent = { version: release.version, at: Date.UTC(2026, 9, 9) - 60_000 }+ for (const [name, marker, job] of [+ ['this version', { ...recent, version: '2.11.2' }, 'running'],+ ['marker too old', { ...recent, at: recent.at - 61_000 }, 'running'],+ ['installer idle', recent, 'idle'],+ ['installer gone', recent, 'none'],+ ] as const) {+ const f = updaterFixture({ prefs: { updateInstalling: marker }, shipIt: { request: true, job } })+ assert.equal(f.yieldsToInstall(), false, name)+ assert.equal(f.preferences.get('updateInstalling'), undefined, name)+ assert.deepEqual(f.spawned, [], name)+ }+ assert.equal(updaterFixture().yieldsToInstall(), false)+ const f = updaterFixture({ prefs: { updateInstalling: recent }, shipIt: { request: true, job: 'running' } })+ assert.equal(f.yieldsToInstall(), true)+ assert.deepEqual(f.preferences.get('updateInstalling'), recent)+ assert.deepEqual(f.spawned.map((args) => args.slice(2)), [['com.pokai.Codync.ShipIt', '/Applications/Codync.app']])+})+test('the app relaunched by a chosen restart opens its own bundle once to come forward', () => {const relaunched = updaterFixture({ prefs: { updateRelaunchInFront: true } })assert.deepEqual(relaunched.opened, ['/Applications/Codync.app'])@@ -142,11 +173,13 @@ test('installer error restarts the stopped host and retry prepares it again', asawait f.emit('update-downloaded', release)f.updates.check()await settle()+ assert.deepEqual({ ...f.preferences.get('updateInstalling') as object }, { version: release.version, at: f.now() })await f.emit('error', new Error('signature rejected'))assert.equal(f.calls.resume, 1)assert.equal(f.updates.state.error, 'signature rejected')assert.equal(f.updates.state.installing, false)assert.equal(f.preferences.get('updateRelaunchInFront'), false)+ assert.equal(f.preferences.get('updateInstalling'), undefined)f.updates.check()await settle()assert.equal(f.calls.prepare, 2)@@ -187,6 +220,7 @@ test('Quit with a staged update waits for the host then retries Quit once', asynawait settle()assert.equal(f.calls.quit, 1)assert.equal(f.calls.install, 0)+ assert.deepEqual({ ...f.preferences.get('updateInstalling') as object }, { version: release.version, at: f.now() }, 'an old copy opened while it installs yields')f.app.emit('before-quit', { preventDefault: () => assert.fail('prepared Quit must proceed') })})diff --git a/apps/desktop/tools/dev.mjs b/apps/desktop/tools/dev.mjsindex a468ff25..9b3b092f 100644--- a/apps/desktop/tools/dev.mjs+++ b/apps/desktop/tools/dev.mjs@@ -78,7 +78,8 @@ function startApp(env = process.env) {try {process.kill(-child.pid, 'SIGTERM')} catch (e) {- if (e.code !== 'ESRCH') throw e+ // ESRCH: the group is gone. EPERM: macOS answers this for a group left with only zombies (Electron quit at once).+ if (e.code !== 'ESRCH' && e.code !== 'EPERM') throw e}}return { child, stop }diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex d7460ccb..4d3133cc 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -30,9 +30,10 @@ Updates page and the update-needed card): **Check for updates** → **Update to**Restarting…**. A finished download never quits the app on its own; the person restarts,or it installs once idle. While a release is available, a filled arrow badge sits rightof **Extensions** in the sidebar footer (under the-Extensions icon in the collapsed rail), tooltip **Update**; it asks **Update to Codync-<version>?** and then restarts into the release, downloading it first if needed, and it-is gone once the app runs the latest version. The TUI action list has **Check for updates**. Download and+Extensions icon in the collapsed rail), its tooltip the same action label; one click+restarts into the release, downloading it first if needed (a ring fills with the download+while the app stays usable, then a spinner while it restarts), and it is gone once the app+runs the latest version. The TUI action list has **Check for updates**. Download andinstall go through electron-updater (`apps/desktop/src/main/updates.ts`); there is noseparate update window.diff --git a/docs/guides/updates.md b/docs/guides/updates.mdindex b863d3de..06de24bc 100644--- a/docs/guides/updates.md+++ b/docs/guides/updates.md@@ -20,9 +20,18 @@ the installer relaunches from the background, so a one-shot `updateRelaunchInFropreference asks for it).While a release is available, an **Update** badge sits right of **Extensions** in the-chat window's sidebar (`UpdateBadge`). After a confirmation it restarts into the release+chat window's sidebar (`UpdateBadge`). One click restarts into the release(`updates.install()`): straight away when it is staged, otherwise once its download-finishes, without a second click. The badge disappears once Codync runs the latest version.+finishes, without a second click. Codync stays usable while it downloads; the badge fills a+ring with the progress, then spins while the app restarts. The badge disappears once Codync+runs the latest version.++For the seconds macOS's installer (ShipIt) takes to swap the bundle, no Codync window shows.+Opening the old app then would cancel the install ("App Still Running"), so the app records+the install it starts, on Restart or on Quit with a staged release (`updateInstalling`),+and an older copy launched within two minutes, while ShipIt still runs, quits at once. A detached wait opens Codync again once ShipIt stops+(at most two minutes): the new release comes forward after an install, and the old one opens+normally after a failed attempt instead of staying shut.The app checks daily.Automatic installation waits until no Codync window is focused, there has been no