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
feat: update a computer that's behind from any device
leepokai06bc193ad9cf
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.mdindex 8c1e5994..bca1b329 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -11,9 +11,11 @@ else a generic "Bug fixes and improvements" line. Delete old sections.### zh-Hant- Bot 傳來的圖片會直接顯示在聊天裡,點一下可以放大看,不用先下載。+- 電腦上的 Codync 版本太舊時,更新提示多了「Update now」按鈕,直接從手機叫那台電腦更新。### en-US- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.+- When a computer's Codync is too old for this app, Update now on the notice updates that computer from your phone.## 2.26.0diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.ktindex b52d3ecb..e25f826a 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt@@ -56,6 +56,8 @@ data class AppState(val screenRequest: ScreenRequest? = null,/** The host sent data this app can't read even after fetching everything again. */val unreadable: Boolean = false,+ /** The update this phone asked of a computer that's behind (`requestHostUpdate`). */+ val hostUpdate: HostUpdate? = null,val error: String? = null,) {/** Connection alone cannot make a cached roster current before event catch-up. */diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.ktindex a0ddf056..e403153a 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt@@ -221,15 +221,19 @@ private suspend fun AppStore.decode(event: JsonObject): MirrorEvent? {}}-/** Reached, but nothing to sync until one side updates: ask again every 30 s (a host update restarts the link anyway). */+/**+ * Reached, but nothing to sync until one side updates: ask again every 30 s (a host update restarts+ * the link anyway), every 5 s while an update this phone asked for runs, so the card goes soon.+ */private suspend fun AppStore.awaitUpdate(active: EncryptedChannel) {- delay(30_000)+ delay(if (state.value.hostUpdate.updating(System.currentTimeMillis())) 5_000 else 30_000)noteHello(active.call("hello").jsonObject)}-/** A different host version may read fine: forget that its data was unreadable (iOS `noteHostVersion`). */+/** A different host version may read fine: forget that its data was unreadable and any update asked of the old one (iOS `noteHostVersion`). */private fun AppStore.noteHello(hello: JsonObject) = mutableState.update {- it.copy(hello = hello, unreadable = it.unreadable && it.hello?.text("version") == hello.text("version"))+ val same = it.hello?.text("version") == hello.text("version")+ it.copy(hello = hello, unreadable = it.unreadable && same, hostUpdate = it.hostUpdate.takeIf { same })}private fun AppStore.showConnection(link: LinkState) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreHostUpdate.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreHostUpdate.ktnew file mode 100644index 00000000..22edcaca--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreHostUpdate.kt@@ -0,0 +1,53 @@+package com.codync.android++import com.codync.android.core.VersionMismatch+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.flow.update+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.jsonPrimitive++// Updating a computer that's behind this app, from here (iOS `BotStore+HostUpdate`).++/** An update this phone asked of the computer: waiting for it to come back newer, or why it couldn't start. */+sealed interface HostUpdate {+ data class Requested(val at: Long) : HostUpdate+ data class Failed(val message: String) : HostUpdate+}++/** How long a requested update shows as under way before the card offers it again. */+internal const val HOST_UPDATE_WAIT_MS = 10 * 60_000L++/** `installHostUpdate` can update this computer from here (missing from older hosts: it can't). */+internal val AppState.canUpdateHost get() = hello?.get("canUpdate")?.jsonPrimitive?.booleanOrNull == true++/** A requested update still within its wait: the computer is updating. */+internal fun HostUpdate?.updating(now: Long) = this is HostUpdate.Requested && now - at < HOST_UPDATE_WAIT_MS++/** What the notice says about a computer that's behind, and whether it offers Update now. */+internal data class HostUpdateNotice(val detail: String, val offersUpdate: Boolean)++internal fun hostUpdateNotice(host: String, mismatch: VersionMismatch.UpdateHost, os: String?, canUpdate: Boolean,+ update: HostUpdate?, now: Long): HostUpdateNotice {+ if (update.updating(now)) return HostUpdateNotice("Updating Codync on $host. This takes a few minutes.", false)+ val needs = "$host runs Codync ${mismatch.version}; this app needs ${mismatch.minimum} or newer."+ if (!canUpdate) return HostUpdateNotice("$needs " + when (os) {+ "macos" -> "Open Codync on that Mac and choose Check for Updates."+ "linux" -> "Run codync-host update there."+ else -> "Update Codync on that computer."+ }, false)+ return HostUpdateNotice(when (update) {+ is HostUpdate.Failed -> "$needs ${update.message}"+ is HostUpdate.Requested -> "$needs $host didn't finish updating. Try again, or update Codync on that computer."+ null -> needs+ }, true)+}++/** Asks a computer that's behind to install the latest release (the update card's Update now). */+fun AppStore.requestHostUpdate() = action("hostUpdate") {+ mutableState.update { it.copy(hostUpdate = HostUpdate.Requested(System.currentTimeMillis())) }+ try { ready().call("installHostUpdate") }+ catch (error: CancellationException) { throw error }+ catch (error: Exception) {+ mutableState.update { it.copy(hostUpdate = HostUpdate.Failed(error.message ?: "Couldn't start the update.")) }+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.ktindex 5de65f8a..033c3ba6 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt@@ -80,7 +80,7 @@ import kotlinx.serialization.json.putJsonArrayPullToRefresh({ store.reconnect(); store.refreshComputers() }, Modifier.fillMaxSize(), indicatorTop = top + 50.dp) {LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = top + 56.dp, bottom = bottomInset)) {// A computer waiting for an update has its card instead; its bots may not be readable yet.- state.mismatch?.let { mismatch -> item("update") { UpdateNeededCard(state, mismatch, Modifier.padding(vertical = 8.dp)) } }+ state.mismatch?.let { mismatch -> item("update") { UpdateNeededCard(state, mismatch, store::requestHostUpdate, Modifier.padding(vertical = 8.dp)) } }if (roster.isEmpty() && state.mismatch == null) item {EmptyRoster(canCreate = usable, hasComputer = usable, create = newBot, showComputers = manage)}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.ktindex 04ab2479..40238918 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt@@ -111,7 +111,7 @@ import com.kyant.shapes.Capsule.imePadding().navigationBarsPadding()) {// Nothing sent now could be read on the other side.val mismatch = state.mismatch- if (mismatch != null) UpdateNeededCard(state, mismatch, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp))+ if (mismatch != null) UpdateNeededCard(state, mismatch, store::requestHostUpdate, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp))// An artifact's viewer has its own box for the same draft; two would overwrite each other.else if (viewing == null) MessageComposer(bot, chatState, store, onCall = if (state.voice == null && state.actualConnection is LinkState.Ready) startCall else null,onInterrupt = if (state.voice?.botId == bot.id && state.voice.state.phase == VoicePhase.Speaking) store::interruptVoice else null,diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.ktindex 660ef265..6680c8cd 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt@@ -8,6 +8,11 @@ import androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip@@ -16,6 +21,7 @@ import com.codync.android.core.AppVersionimport com.codync.android.core.VersionMismatchimport com.codync.android.design.*import com.kyant.shapes.RoundedRectangle+import kotlinx.coroutines.delay/** Which side must update before this app and the computer can work together (iOS `BotStore.mismatch`), from the host's `hello`. */internal val AppState.mismatch: VersionMismatch? get() {@@ -26,8 +32,15 @@ internal val AppState.mismatch: VersionMismatch? get() {}/** Says which side has to update, shown instead of the composer and above the computer's bots. */-@Composable internal fun UpdateNeededCard(state: AppState, mismatch: VersionMismatch, modifier: Modifier = Modifier) {+@Composable internal fun UpdateNeededCard(state: AppState, mismatch: VersionMismatch, requestUpdate: () -> Unit, modifier: Modifier = Modifier) {val host = state.hello?.text("name") ?: state.computers.firstOrNull()?.name ?: "your computer"+ // A requested update that never finishes offers the button again once its wait is over.+ var now by remember { mutableLongStateOf(System.currentTimeMillis()) }+ LaunchedEffect(state.hostUpdate) {+ val requested = state.hostUpdate as? HostUpdate.Requested ?: return@LaunchedEffect+ delay(requested.at + HOST_UPDATE_WAIT_MS - System.currentTimeMillis())+ now = System.currentTimeMillis()+ }Row(modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.surface).padding(14.dp),verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(12.dp)) {Symbol("arrow.down.circle", size = 22.dp, tint = Palette.warning)@@ -36,15 +49,16 @@ internal val AppState.mismatch: VersionMismatch? get() {is VersionMismatch.UpdateApp -> "Update this app"is VersionMismatch.UpdateHost -> "Update Codync on $host"}, style = Type.subheadline.semibold, color = Palette.text)- Text(when (mismatch) {- is VersionMismatch.UpdateApp -> "${state.hello?.text("version")?.let { "$host runs Codync $it and" } ?: host} needs this app to be " +- "${mismatch.minimum} or newer. Your chats are safe on the computer."- is VersionMismatch.UpdateHost -> "$host runs Codync ${mismatch.version}; this app needs ${mismatch.minimum} or newer. " + when (state.hello?.text("os")) {- "macos" -> "Open Codync on that Mac and choose Check for Updates."- "linux" -> "Run codync-host update there."- else -> "Update Codync on that computer."+ when (mismatch) {+ is VersionMismatch.UpdateApp -> Text("${state.hello?.text("version")?.let { "$host runs Codync $it and" } ?: host} needs this app to be " ++ "${mismatch.minimum} or newer. Your chats are safe on the computer.", style = Type.footnote, color = Palette.secondary)+ is VersionMismatch.UpdateHost -> {+ val notice = hostUpdateNotice(host, mismatch, state.hello?.text("os"), state.canUpdateHost, state.hostUpdate,+ maxOf(now, System.currentTimeMillis()))+ Text(notice.detail, style = Type.footnote, color = Palette.secondary)+ if (notice.offersUpdate) PrimaryButton("Update now", Modifier.padding(top = 4.dp), action = requestUpdate)}- }, style = Type.footnote, color = Palette.secondary)+ }}}}diff --git a/apps/android/app/src/test/kotlin/com/codync/android/HostUpdateNoticeTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/HostUpdateNoticeTest.ktnew file mode 100644index 00000000..edb6da62--- /dev/null+++ b/apps/android/app/src/test/kotlin/com/codync/android/HostUpdateNoticeTest.kt@@ -0,0 +1,33 @@+package com.codync.android++import com.codync.android.core.VersionMismatch+import org.junit.Assert.*+import org.junit.Test++class HostUpdateNoticeTest {+ private val behind = VersionMismatch.UpdateHost("2.23.1", "2.26.0")+ private val needs = "Mini runs Codync 2.23.1; this app needs 2.26.0 or newer."+ private val now = 1_000_000_000L+ private fun notice(canUpdate: Boolean, update: HostUpdate?, os: String? = "macos") = hostUpdateNotice("Mini", behind, os, canUpdate, update, now)++ @Test fun aComputerThatCanUpdateOffersUpdateNow() {+ assertEquals(HostUpdateNotice(needs, true), notice(true, null))+ }++ @Test fun aRequestedUpdateShowsAsUnderWayUntilItsWaitIsOver() {+ assertEquals(HostUpdateNotice("Updating Codync on Mini. This takes a few minutes.", false),+ notice(true, HostUpdate.Requested(now - HOST_UPDATE_WAIT_MS + 1)))+ assertEquals(HostUpdateNotice("$needs Mini didn't finish updating. Try again, or update Codync on that computer.", true),+ notice(true, HostUpdate.Requested(now - HOST_UPDATE_WAIT_MS)))+ }++ @Test fun aRefusedUpdateSaysWhy() {+ val busy = "A bot is working on this computer. Update it once the bot is done."+ assertEquals(HostUpdateNotice("$needs $busy", true), notice(true, HostUpdate.Failed(busy)))+ }++ @Test fun anOlderHostKeepsItsInstructions() {+ assertEquals(HostUpdateNotice("$needs Open Codync on that Mac and choose Check for Updates.", false), notice(false, null))+ assertEquals(HostUpdateNotice("$needs Run codync-host update there.", false), notice(false, null, "linux"))+ }+}diff --git a/apps/desktop/src/main/host-controller.ts b/apps/desktop/src/main/host-controller.tsindex 181971fd..41f9ce96 100644--- a/apps/desktop/src/main/host-controller.ts+++ b/apps/desktop/src/main/host-controller.ts@@ -27,11 +27,14 @@ interface Health {binaryPath?: stringbinaryHash?: stringbusy?: boolean+ /** When another device asked this computer to update (`installHostUpdate`), if it's still waiting. */+ updateRequested?: number | null}+/** This app's own host; `app` tells it the app is open to carry out an update request. */export async function fetchHealth(url = baseURL, timeoutMs = 2000): Promise<Health | null> {try {- const res = await fetch(`${url}/health`, { signal: AbortSignal.timeout(timeoutMs) })+ const res = await fetch(`${url}/health?app=true`, { signal: AbortSignal.timeout(timeoutMs) })if (!res.ok) return nullreturn (await res.json()) as Health} catch {@@ -82,10 +85,10 @@ class SetupError extends Error {/*** Manages the local codync-host (binary, background service, health): bundled with the app,- * else a Homebrew / cargo install. Emits `change`, and `setupFailed` (a `HostSetupStage`) when- * it couldn't get a working host.+ * else a Homebrew / cargo install. `setupFailed`: it couldn't get a working host;+ * `updateRequested`: another device asked this computer to update.*/-export class HostController extends EventEmitter {+export class HostController extends EventEmitter<{ change: []; setupFailed: [stage: HostSetupStage]; updateRequested: [] }> {state: HostState = { kind: 'starting' }local: LocalHost | null = nullprivate loop: NodeJS.Timeout | null = null@@ -95,6 +98,8 @@ export class HostController extends EventEmitter {private expectedHash: string | null = nullprivate failures = 0private preparingForUpdate = false+ /** The update request already passed on to the app's updater. */+ private updateRequest: number | null = nullget binary(): string | null {const candidates = [@@ -322,10 +327,18 @@ export class HostController extends EventEmitter {return new SetupError('not_responding', "Another build of the host is running, not this app's. Try again to replace it.")}}+ this.relayUpdateRequest(health)if (this.local?.computerId === health.computerId && this.local.token === token) return nullthis.setLocal({ computerId: health.computerId, baseURL, token })return null}++ /** Passes each new update request on to the app's updater, once. */+ private relayUpdateRequest(health: Health) {+ if (!health.updateRequested || health.updateRequested === this.updateRequest) return+ this.updateRequest = health.updateRequested+ this.emit('updateRequested')+ }}async function readToken(): Promise<string | null> {diff --git a/apps/desktop/src/main/updates.ts b/apps/desktop/src/main/updates.tsindex 00a052be..653621a0 100644--- a/apps/desktop/src/main/updates.ts+++ b/apps/desktop/src/main/updates.ts@@ -23,6 +23,9 @@ const shipIt = `${identity.appId}.ShipIt`const bundlePath = () => join(app.getPath('exe'), '../../..')+/** How long another device's update request lasts: as long as that device shows it updating. */+const REQUEST_WAIT = 10 * 60_000+/*** 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@@ -61,6 +64,11 @@ export class Updates extends EventEmitter<{ change: []; upToDate: []; setAutoCheprivate userInitiated = false/** The person chose Update: restart into the release as soon as it's downloaded. */private installWhenDownloaded = false+ /**+ * Until when another device's request to update this computer (`installHostUpdate`) lasts: the+ * release downloads, and installs once no bot is working without waiting for the person.+ */+ private requestedUntil = 0private preparing: Promise<boolean> | null = nullprivate prepared = falseprivate updateGeneration = 0@@ -89,6 +97,7 @@ export class Updates extends EventEmitter<{ change: []; upToDate: []; setAutoCheif (process.platform === 'darwin') void shell.openPath(bundlePath())}+ this.host.on('updateRequested', () => this.installRequested())autoUpdater.autoDownload = falseautoUpdater.autoInstallOnAppQuit = trueautoUpdater.on('checking-for-update', () => this.set({ checking: true, error: null }))@@ -148,6 +157,7 @@ export class Updates extends EventEmitter<{ change: []; upToDate: []; setAutoChe/** A check the person asked for answers even when there's nothing new (`upToDate`). */private upToDate() {this.installWhenDownloaded = false+ this.requestedUntil = 0const asked = this.userInitiatedthis.userInitiated = falsethis.checked({ availableVersion: null })@@ -157,6 +167,7 @@ export class Updates extends EventEmitter<{ change: []; upToDate: []; setAutoCheprivate failed(error: unknown) {this.updateGeneration++this.installWhenDownloaded = false+ this.requestedUntil = 0prefs.set('updateRelaunchInFront', false)prefs.set('updateInstalling', undefined)// A preparation still stopping the host restores it after stop completes.@@ -195,23 +206,38 @@ export class Updates extends EventEmitter<{ change: []; upToDate: []; setAutoChethis.check()}+ /** Another device asked this computer to update: download the release and restart into it in the background. */+ private installRequested() {+ this.requestedUntil = Date.now() + REQUEST_WAIT+ if (this.state.staged) return this.installWhenIdle()+ if (this.state.checking || this.state.downloadPercent !== null) return+ void autoUpdater.checkForUpdates().catch(() => {})+ }++ private get requested() {+ return Date.now() < this.requestedUntil+ }+/*** The release GitHub marks latest, which the release gate gives only to one the App Store's* iPhone app works with (docs/reference/compatibility.md).*/private available(info: UpdateInfo) {this.checked({ availableVersion: info.version })- if (this.userInitiated || this.state.autoDownload) {+ if (this.userInitiated || this.state.autoDownload || this.requested) {this.set({ downloadPercent: 0 })void autoUpdater.downloadUpdate().catch(() => {})}}- /** Waits until the app is in the background, nobody has typed for ten minutes and no bot is working. */+ /**+ * Waits until no bot is working and, unless another device asked for the update, the app is in+ * the background and nobody has typed for ten minutes.+ */private installWhenIdle() {const timer = setInterval(async () => {if (!this.state.staged) return clearInterval(timer)- if (!this.state.autoDownload || BrowserWindow.getFocusedWindow() || powerMonitor.getSystemIdleTime() < 600) return+ if (!this.requested && (!this.state.autoDownload || BrowserWindow.getFocusedWindow() || powerMonitor.getSystemIdleTime() < 600)) returnif (!(await this.host.isIdleForUpdate())) returnclearInterval(timer)void this.install(false)diff --git a/apps/desktop/src/renderer/lib/host-update.test.ts b/apps/desktop/src/renderer/lib/host-update.test.tsnew file mode 100644index 00000000..8fd63ed5--- /dev/null+++ b/apps/desktop/src/renderer/lib/host-update.test.ts@@ -0,0 +1,16 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { HOST_UPDATE_WAIT, offerHostUpdate } from './host-update.ts'++test('an update asked from here runs for a while, then is offered again', () => {+ const requested = { kind: 'requested', at: 1_000_000 } as const+ assert.deepEqual(offerHostUpdate(null, true, requested.at), { kind: 'available', last: null })+ assert.deepEqual(offerHostUpdate(requested, true, requested.at + HOST_UPDATE_WAIT - 1), { kind: 'updating' })+ assert.deepEqual(offerHostUpdate(requested, true, requested.at + HOST_UPDATE_WAIT), { kind: 'available', last: requested })+})++test('a refused update is offered again with why; a computer that cannot update from here is not', () => {+ const failed = { kind: 'failed', message: 'A bot is working on this computer. Update it once the bot is done.' } as const+ assert.deepEqual(offerHostUpdate(failed, true), { kind: 'available', last: failed })+ assert.deepEqual(offerHostUpdate(null, false), { kind: 'unavailable' })+})diff --git a/apps/desktop/src/renderer/lib/host-update.ts b/apps/desktop/src/renderer/lib/host-update.tsnew file mode 100644index 00000000..7e4dde7d--- /dev/null+++ b/apps/desktop/src/renderer/lib/host-update.ts@@ -0,0 +1,18 @@+/** An update this app asked of a computer that's behind it (`installHostUpdate`). */+export type HostUpdate = { kind: 'requested'; at: number } | { kind: 'failed'; message: string }++/**+ * What the update notice offers for a computer that's behind (iOS `HostUpdateOffer`): `updating`+ * while a request runs; `available` when the computer updates when asked, with `last` a request+ * that didn't (it failed, or the computer never came back updated); `unavailable` when the notice+ * says how to update it on the computer instead.+ */+export type HostUpdateOffer = { kind: 'updating' } | { kind: 'available'; last: HostUpdate | null } | { kind: 'unavailable' }++/** How long a requested update may take before the notice offers it again. */+export const HOST_UPDATE_WAIT = 10 * 60_000++export function offerHostUpdate(update: HostUpdate | null, canUpdate: boolean, now = Date.now()): HostUpdateOffer {+ if (update?.kind === 'requested' && now - update.at < HOST_UPDATE_WAIT) return { kind: 'updating' }+ return canUpdate ? { kind: 'available', last: update } : { kind: 'unavailable' }+}diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.tsindex 4114a2ac..3a06e98b 100644--- a/apps/desktop/src/renderer/store/bot-mirror.ts+++ b/apps/desktop/src/renderer/store/bot-mirror.ts@@ -11,6 +11,7 @@ import {} from '@shared/models'import type { HostClient, HostRoute, HostTransport } from '../client/host-client'import { rosterOrder } from '../lib/computer-roster'+import { offerHostUpdate, type HostUpdate, type HostUpdateOffer } from '../lib/host-update'import { Observable } from '../lib/observable'import { ComposerDrafts } from '@shared/composer-drafts'import { canLoadHistory } from '@shared/mirror-window'@@ -34,6 +35,8 @@ export class BotMirror extends Observable {client: HostClient | null = nullhello: Hello | null = nullhostVersion: { version: string; minApp?: string | null } | null = null+ /** An update asked of this computer from here while it's behind; cleared once its version changes. */+ hostUpdate: HostUpdate | null = nullbots = new Map<string, Bot>()entries = new Map<string, Entry[]>()usage: Usage = { providers: [] }@@ -103,6 +106,11 @@ export class BotMirror extends Observable {return null}+ /** What the update notice offers while this computer is behind this app. */+ get hostUpdateOffer(): HostUpdateOffer {+ return offerHostUpdate(this.hostUpdate, this.hello?.canUpdate === true)+ }+/** Roster order: the lead, then pinned bots, then where the user dragged them, then most recent activity. */get roster(): Bot[] {return [...this.bots.values()].filter((b) => !b.hidden).sort(rosterOrder)diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex d7284874..0dd8b35b 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -96,6 +96,16 @@ export class BotStore extends BotSync {})()}+ /** Asks this computer to update itself while it's behind this app (`installHostUpdate`). */+ requestHostUpdate() {+ this.hostUpdate = { kind: 'requested', at: Date.now() }+ this.changed()+ void this.withLink((c) => c.call('installHostUpdate', {})).catch((error: unknown) => {+ this.hostUpdate = { kind: 'failed', message: error instanceof Error ? error.message : String(error) }+ this.changed()+ })+ }+retry(entry: Entry) {const files = (entry.data.clientNonce && this.outgoingFiles.get(entry.data.clientNonce)) || []const text = entry.data.text ?? ''diff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.tsindex df5554c9..91d981d9 100644--- a/apps/desktop/src/renderer/store/bot-sync.ts+++ b/apps/desktop/src/renderer/store/bot-sync.ts@@ -9,6 +9,8 @@ const DROP_GRACE = 5000const INITIAL_GRACE = 1000const ACTION_PATIENCE = 20_000const MISMATCH_RECHECK = 30_000+/** The mismatch recheck while an update asked from here runs, so the notice leaves soon after. */+const UPDATE_RECHECK = 5_000export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))const same = (a: Connection, b: Connection) => a.kind === b.kind && JSON.stringify(a) === JSON.stringify(b)@@ -122,7 +124,7 @@ export class BotSync extends BotMirror {if (!alive()) returnif (this.mismatch) {this.setConnection({ kind: 'online' })- await sleep(MISMATCH_RECHECK)+ await sleep(this.hostUpdateOffer.kind === 'updating' ? UPDATE_RECHECK : MISMATCH_RECHECK)return void attempt()}if (this.isLoopback) {@@ -187,6 +189,7 @@ export class BotSync extends BotMirror {this.refetchAll()this.rewound = falsethis.unreadable = false+ this.hostUpdate = null}this.cacheStamp = nullthis.hostVersion = nextdiff --git a/apps/desktop/src/renderer/views/UpdateNeededCard.tsx b/apps/desktop/src/renderer/views/UpdateNeededCard.tsxindex 0715f27b..f0974e9e 100644--- a/apps/desktop/src/renderer/views/UpdateNeededCard.tsx+++ b/apps/desktop/src/renderer/views/UpdateNeededCard.tsx@@ -3,6 +3,7 @@ import { Button } from '../components/Controls'import { Icon } from '../components/Icon'import { HStack, VStack } from '../components/Stack'import { Text } from '../components/Text'+import type { HostUpdate } from '../lib/host-update'import { useApp, useStore } from '../store/context'import { UpdateButton, useUpdates } from './UpdateButton'@@ -23,6 +24,14 @@ export const updateNeededText = {const needs = `${host} runs Codync ${m.version}; this app needs ${m.minimum} or newer.`return instructions ? `${needs} ${how}` : needs},+ /** A computer updating at this app's request. */+ updating(host: string) {+ return `Updating Codync on ${host}. This takes a few minutes.`+ },+ /** Why the last update asked of the computer didn't take. */+ notUpdated(last: HostUpdate, host: string) {+ return last.kind === 'failed' ? last.message : `${host} didn't finish updating. Try again, or update Codync on that computer.`+ },}/**@@ -35,22 +44,33 @@ export function UpdateNeededCard() {const updates = useUpdates()const mismatch = store.mismatchif (!mismatch) return null+ const host = store.hostName+ const offer = mismatch.kind === 'updateHost' ? store.hostUpdateOffer : null// This app updates itself (its download and restart, as in Settings); on macOS and Windows this- // computer's own host is put back on the app's bundled copy. Linux has no bundled host, so the- // card says how to update it instead.- const updatesApp = mismatch.kind === 'updateApp'- const restartsHost = !updatesApp && store === app.local && !app.host.dev && window.codync.platform !== 'linux'- const button = updatesApp- ? updates && <UpdateButton updates={updates} kind="primary" />- : restartsHost && <Button onClick={() => window.codync.host.restart()}>{`Update ${store.hostName}`}</Button>+ // computer's own host is put back on the app's bundled copy. Any other computer that can update+ // itself does when asked from here; otherwise the card says how to update it there.+ const action =+ mismatch.kind === 'updateApp' ? 'updateApp'+ : store === app.local && !app.host.dev && window.codync.platform !== 'linux' ? 'restartHost'+ : offer?.kind === 'available' ? 'askHost'+ : null+ const button =+ action === 'updateApp' ? updates && <UpdateButton updates={updates} kind="primary" />+ : action === 'restartHost' ? <Button onClick={() => window.codync.host.restart()}>Update now</Button>+ : action === 'askHost' ? <Button onClick={() => store.requestHostUpdate()}>Update now</Button>+ : null+ // With a button here, instructions for that computer would only confuse.+ const needs = updateNeededText.detail(mismatch, host, store.hostVersion?.version, store.hello?.os, action === null)+ const detail =+ offer?.kind === 'updating' ? updateNeededText.updating(host)+ : offer?.kind === 'available' && offer.last ? `${needs} ${updateNeededText.notUpdated(offer.last, host)}`+ : needsreturn (<HStack align="flex-start" gap={12} className="update-needed"><Icon name="arrow.down.circle" size={15} color="var(--warning)" /><VStack gap={6} grow>- <Text as="div" size="subheadline" weight="semibold" tone="text">{updateNeededText.title(mismatch, store.hostName)}</Text>- <Text as="div" size="footnote" tone="secondary">- {updateNeededText.detail(mismatch, store.hostName, store.hostVersion?.version, store.hello?.os, !updatesApp && !restartsHost)}- </Text>+ <Text as="div" size="subheadline" weight="semibold" tone="text">{updateNeededText.title(mismatch, host)}</Text>+ <Text as="div" size="footnote" tone="secondary">{detail}</Text>{button ? <div className="update-needed-action">{button}</div> : null}</VStack></HStack>diff --git a/apps/desktop/src/shared/host-update.test.ts b/apps/desktop/src/shared/host-update.test.tsindex 9783269c..24c6e5aa 100644--- a/apps/desktop/src/shared/host-update.test.ts+++ b/apps/desktop/src/shared/host-update.test.ts@@ -106,6 +106,25 @@ test('idle detection distinguishes working, offline and idle hosts', async () =>})+test('an update another device asks for reaches the updater once per request', async () => {+ const f = hostUpdateFixture()+ let requests = 0+ f.host.on('updateRequested', () => requests++)+ const installing = f.host.install()+ await settle()+ await f.tick(1000)+ await installing+ assert.equal(requests, 0)+ f.behavior.updateRequested = 1_000+ await f.tick(5000)+ await f.tick(5000)+ assert.equal(requests, 1, 'a request the poll sees again is passed on once')+ f.behavior.updateRequested = 2_000+ await f.tick(5000)+ assert.equal(requests, 2)+ assert.ok(f.fetched.length > 0 && f.fetched.every((url) => url.endsWith('/health?app=true')), 'the poll tells the host this app is open')+})+test('development install and stop reject a production binary before touching its service', async () => {const f = hostUpdateFixture({ environment: 'dev' })f.behavior.binaryEnvironment = 'main'diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex fb60ac15..5f6d4117 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -463,6 +463,8 @@ export interface Hello {signKey?: stringboxKey?: stringminApp?: string+ /** `installHostUpdate` can update this computer (absent before hosts could be updated from a client). */+ canUpdate?: booleancloud?: string | null/** Product analytics on this computer: on unless its owner turned it off. */analytics?: booleandiff --git a/apps/desktop/src/shared/test-support/host-update.ts b/apps/desktop/src/shared/test-support/host-update.tsindex d2226eaf..558914d8 100644--- a/apps/desktop/src/shared/test-support/host-update.ts+++ b/apps/desktop/src/shared/test-support/host-update.ts@@ -12,6 +12,7 @@ export function hostUpdateFixture(options: { environment?: 'main' | 'dev'; platfconst persisted: Record<string, unknown> = { hostRestartAfterAppUpdate: options.restartMarker ?? false }const calls: string[][] = []const order: string[] = []+ const fetched: string[] = []const timers = new Map<number, { callback: () => void; ms: number }>()let timerId = 0const behavior = {@@ -19,6 +20,7 @@ export function hostUpdateFixture(options: { environment?: 'main' | 'dev'; platfinstallStatus: 0,installed: options.installed ?? true,busy: false,+ updateRequested: null as number | null,reachable: true,wrongBinary: false,binaryEnvironment: identity.environment as string,@@ -62,9 +64,10 @@ export function hostUpdateFixture(options: { environment?: 'main' | 'dev'; platfprocess: { 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 () => {+ fetch: async (url: string) => {+ fetched.push(url)if (!behavior.reachable) throw new Error('Host offline')- return { ok: true, json: async () => ({ environment: behavior.runningEnvironment, computerId: 'fixture-computer', busy: behavior.busy, binaryPath: binary, binaryHash: behavior.wrongBinary ? 'stale' : crypto.createHash('sha256').update(binaryBytes).digest('hex') }) }+ return { ok: true, json: async () => ({ environment: behavior.runningEnvironment, computerId: 'fixture-computer', busy: behavior.busy, updateRequested: behavior.updateRequested, binaryPath: binary, binaryHash: behavior.wrongBinary ? 'stale' : crypto.createHash('sha256').update(binaryBytes).digest('hex') }) }},})const host = new module.HostController()@@ -76,5 +79,5 @@ export function hostUpdateFixture(options: { environment?: 'main' | 'dev'; platf}await settle()}- return { host, prefs: module.prefs, persisted, calls, order, behavior, tick }+ return { host, prefs: module.prefs, persisted, calls, order, fetched, behavior, tick }}diff --git a/apps/desktop/src/shared/test-support/updater.ts b/apps/desktop/src/shared/test-support/updater.tsindex 86a47bc0..df8bcefb 100644--- a/apps/desktop/src/shared/test-support/updater.ts+++ b/apps/desktop/src/shared/test-support/updater.ts@@ -60,11 +60,11 @@ export function updaterFixture(options: { packaged?: boolean; main?: boolean; prdownloadUpdate: async () => { calls.download++; await behavior.download() },quitAndInstall: () => { calls.install++; behavior.install() },})- const host = {+ const host = Object.assign(new EventEmitter(), {prepareForUpdate: async () => { calls.prepare++; await behavior.prepare() },resumeAfterCancelledUpdate: () => { calls.resume++ },isIdleForUpdate: async () => behavior.hostIdle,- }+ })const timer = (callback: () => unknown, ms: number) => {const id = ++nextTimertimers.set(id, { callback, ms })@@ -100,5 +100,5 @@ export function updaterFixture(options: { packaged?: boolean; main?: boolean; pr}await settle()}- return { updates, yieldsToInstall, app, ipc, handlers, updater, calls, opened, spawned, behavior, preferences, sent, timers, shipIt, emit, tick, now: () => now, advance: (ms: number) => { now += ms } }+ return { updates, yieldsToInstall, app, host, 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 7d38bc84..8911a435 100644--- a/apps/desktop/src/shared/updates.test.ts+++ b/apps/desktop/src/shared/updates.test.ts@@ -102,6 +102,46 @@ test('the Update badge clicked during an automatic download restarts once it finassert.equal(f.calls.install, 1)})+test('another device asking this computer to update downloads the release and restarts into it once no bot is working', async () => {+ const f = updaterFixture({ prefs: { updatesAutoDownload: false } })+ let upToDate = 0+ f.updates.on('upToDate', () => upToDate++)+ f.host.emit('updateRequested')+ await f.emit('update-not-available')+ assert.equal(upToDate, 0, 'nobody at this computer asked, so nothing says up to date')+ f.host.emit('updateRequested')+ assert.equal(f.calls.check, 2)+ await f.emit('update-available', release)+ assert.equal(f.calls.download, 1, 'downloads even with automatic downloads off')+ f.behavior.focused = true+ f.behavior.hostIdle = false+ await f.emit('update-downloaded', release)+ await f.tick(30_000)+ assert.equal(f.calls.prepare + f.calls.install, 0, 'a working bot is never stopped')+ f.behavior.hostIdle = true+ await f.tick(30_000)+ assert.equal(f.calls.install, 1, "doesn't wait for the person at this computer")+ assert.notEqual(f.preferences.get('updateRelaunchInFront'), true, 'the app comes back in the background')++ const staged = updaterFixture()+ staged.behavior.focused = true+ await staged.emit('update-downloaded', release)+ staged.host.emit('updateRequested')+ await staged.tick(30_000)+ assert.equal(staged.calls.check, 0)+ assert.equal(staged.calls.install, 1)++ const lapsed = updaterFixture()+ lapsed.behavior.focused = true+ lapsed.behavior.hostIdle = false+ await lapsed.emit('update-downloaded', release)+ lapsed.host.emit('updateRequested')+ lapsed.advance(10 * 60_000)+ lapsed.behavior.hostIdle = true+ await lapsed.tick(30_000)+ assert.equal(lapsed.calls.install, 0, 'a request that lapsed waits for the person again')+})+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 [diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex d37c6e48..d81deb2b 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -137,6 +137,11 @@ public struct HostClient: Sendable {public extension HostClient {func hello() async throws -> Hello { try await call("hello") }+ /// Updates a computer that's behind this app to the latest release (`Hello.canUpdate`).+ func installHostUpdate() async throws {+ let _: Empty = try await call("installHostUpdate")+ }+func history(botId: String, beforeSeq: Int64, limit: Int = 100) async throws -> [Entry] {struct Body: Encodable { var botId: String; var beforeSeq: Int64; var limit: Int }struct Res: Decodable { var entries: [Entry] }diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftindex c52b9cdf..4c8b40ae 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift@@ -235,6 +235,8 @@ public struct Hello: Codable, Sendable {public var minApp: String?/// The cloud relay the host uses; nil = cloud off.public var cloud: String?+ /// `installHostUpdate` can update this computer from here (missing from older hosts: it can't).+ public var canUpdate: Bool?}public struct DirListing: Codable, Sendable {diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+HostUpdate.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+HostUpdate.swiftnew file mode 100644index 00000000..97408930--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+HostUpdate.swift@@ -0,0 +1,43 @@+import CodyncKit+import Foundation++/// An update this phone asked of a computer that's behind (`installHostUpdate`).+public enum HostUpdate: Equatable, Sendable {+ case requested(at: Date)+ case failed(String)+}++/// What the update notice offers for a computer that's behind (`.updateHost`).+public enum HostUpdateOffer: Equatable, Sendable {+ /// Asked within `BotStore.hostUpdateWait`: the computer is updating.+ case updating+ /// The computer updates when asked; `last` is a request that didn't (it failed, or the+ /// computer never came back updated).+ case available(last: HostUpdate?)+ /// Not from here: the notice says how to update it on the computer.+ case unavailable+}++extension BotStore {+ /// How long an update may take before the notice offers it again.+ static let hostUpdateWait: TimeInterval = 10 * 60+ /// While it updates, `hello` is asked this often, so the notice goes away soon after.+ static let updatingRecheck: Duration = .seconds(5)++ public func hostUpdateOffer(now: Date = .now) -> HostUpdateOffer {+ if case let .requested(at) = hostUpdate, now.timeIntervalSince(at) < Self.hostUpdateWait { return .updating }+ return hello?.canUpdate == true ? .available(last: hostUpdate) : .unavailable+ }++ /// Asks the computer to update itself; the notice follows along until its version changes.+ public func requestHostUpdate() {+ Motion.animate { hostUpdate = .requested(at: .now) }+ Task {+ do {+ try await withLink { try await $0.installHostUpdate() }+ } catch {+ Motion.animate { hostUpdate = .failed(error.localizedDescription) }+ }+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swiftindex ff4cb403..73d1e816 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift@@ -16,7 +16,7 @@ extension BotStore {// Reached, but nothing to sync until one side updates. A host update restarts// the link (and this loop) anyway; this catches one that doesn't.setConnection(.online)- try await Task.sleep(for: Self.mismatchRecheck)+ try await Task.sleep(for: hostUpdateOffer() == .updating ? Self.updatingRecheck : Self.mismatchRecheck)continue}requestedSince = rev@@ -70,6 +70,7 @@ extension BotStore {refetchAll()rewound = falseunreadable = false+ hostUpdate = nil}cacheStamp = nil// An update notice may appear or go away with it.diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex e8094058..3d8127b3 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -58,6 +58,8 @@ public final class BotStore {public internal(set) var hello: Hello?/// The host's version and `minApp`, kept even when the rest of its `hello` can't be read.public internal(set) var hostVersion: HostVersion?+ /// An update this phone asked of the computer; cleared when its version changes.+ public internal(set) var hostUpdate: HostUpdate?public internal(set) var bots: [String: Bot] = [:]public internal(set) var entries: [String: [Entry]] = [:]public internal(set) var usage: Usagediff --git a/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swift b/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swiftindex 3636a698..97aee0c2 100644--- a/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swift+++ b/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swift@@ -56,12 +56,20 @@ public struct UpdateNeededCard: View {var title: String { UpdateNeededText.title(mismatch, host: store.hostName) }var detail: String {+ let offer = hostOffer+ if offer == .updating { return UpdateNeededText.updating(host: store.hostName) }let text = UpdateNeededText.detail(mismatch, host: store.hostName, hostVersion: store.hostVersion?.version,// With a button here, instructions for that computer would only confuse.os: store.hello?.os, instructions: action == nil)+ if case let .available(last?) = offer { return "\(text) \(UpdateNeededText.notUpdated(last, host: store.hostName))" }return inReview ? "\(text) That version is still in App Store review; it'll be there soon." : text}+ /// What this app can do about a computer that's behind; nil when the app itself is.+ private var hostOffer: HostUpdateOffer? {+ if case .updateHost = mismatch { store.hostUpdateOffer() } else { nil }+ }+/// The App Store doesn't have the app this computer needs yet. An unknown store version/// keeps the button: the App Store page itself shows what's there.private var inReview: Bool {@@ -75,8 +83,9 @@ public struct UpdateNeededCard: View {guard let appUpdate else { return nil }return ("Update Codync", { appUpdate() })case .updateHost:- // The computer updates itself; the card says how.- return nil+ // Otherwise the card says how to update it on the computer.+ guard case .available = hostOffer else { return nil }+ return ("Update now", { store.requestHostUpdate() })}}}@@ -107,6 +116,19 @@ public enum UpdateNeededText {return instructions ? "\(needs) \(how)" : needs}}++ /// A computer updating at this app's request.+ public static func updating(host: String) -> String {+ "Updating Codync on \(host). This takes a few minutes."+ }++ /// Why the last update asked of the computer didn't take.+ public static func notUpdated(_ last: HostUpdate, host: String) -> String {+ switch last {+ case let .failed(message): message+ case .requested: "\(host) didn't finish updating. Try again, or update Codync on that computer."+ }+ }}/// What the App Store has, asked now and then (iPhone): the update notice greys out its buttondiff --git a/apps/ios/Kit/Tests/CodyncUITests/HostUpdateTests.swift b/apps/ios/Kit/Tests/CodyncUITests/HostUpdateTests.swiftnew file mode 100644index 00000000..0085e293--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/HostUpdateTests.swift@@ -0,0 +1,41 @@+import Foundation+import Testing+@testable import CodyncKit+@testable import CodyncUI++// Updating a computer that's behind this app, from here (BotStore+HostUpdate).++@MainActor @Test func aComputerThatsBehindUpdatesWhenAsked() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.relay))+ await fake.setHello(helloJSON(version: "2.2.0", canUpdate: true))+ let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: VersionMismatch.minHost) { _ in fake }+ defer { store.retire() }+ store.setActive(true)+ #expect(await until { store.mismatch != nil })+ #expect(store.hostUpdateOffer() == .available(last: nil))++ store.requestHostUpdate()+ #expect(store.hostUpdateOffer() == .updating)+ #expect(await until { await fake.calls.contains("installHostUpdate") })+ // It never came back updated: offered again, saying so.+ guard case let .requested(at) = store.hostUpdate else { Issue.record("not requested"); return }+ #expect(store.hostUpdateOffer(now: at + BotStore.hostUpdateWait) == .available(last: .requested(at: at)))++ await fake.fail("installHostUpdate", times: 1)+ store.requestHostUpdate()+ let failed = HostUpdate.failed(HostError.unreachable.localizedDescription)+ #expect(await until { store.hostUpdate == failed })+ #expect(store.hostUpdateOffer() == .available(last: failed))++ // The computer comes back updated: nothing is left of the request.+ await fake.setHello(helloJSON(version: VersionMismatch.minHost, canUpdate: true))+ await fake.set(.connecting)+ await fake.set(.ready(.relay))+ #expect(await until { store.mismatch == nil })+ #expect(store.hostUpdate == nil)+ // A host that can't update on request offers nothing.+ store.hello?.canUpdate = nil+ #expect(store.hostUpdateOffer() == .unavailable)+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swiftindex f678086a..0ce576a1 100644--- a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift@@ -621,9 +621,9 @@ extension FakeRemote {// MARK: - Version compatibility (docs/reference/compatibility.md)-private func helloJSON(version: String, minApp: String? = nil, backends: String = "[]") -> String {+func helloJSON(version: String, minApp: String? = nil, backends: String = "[]", canUpdate: Bool = false) -> String {let min = minApp.map { #","minApp":"\#($0)""# } ?? ""- return #"{"hostId":"h1","name":"Mac","version":"\#(version)"\#(min),"os":"macos","backends":\#(backends),"rev":0}"#+ return #"{"hostId":"h1","name":"Mac","version":"\#(version)"\#(min),"os":"macos","backends":\#(backends),"rev":0,"canUpdate":\#(canUpdate)}"#}@MainActor @Test func hostNeedingANewerAppStopsSyncAndAsksForTheUpdate() async throws {diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex 9d3f6c2d..ed826ebb 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -10,9 +10,11 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o### zh-Hant- Bot 傳來的圖片會直接顯示在聊天裡,點一下可以放大看,不用先下載。+- 電腦上的 Codync 版本太舊時,更新提示多了「Update now」按鈕,直接從手機叫那台電腦更新。### en-US- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.+- When a computer's Codync is too old for this app, Update now on the notice updates that computer from your phone.## 2.26.1diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex d3904bd6..02772750 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -29,7 +29,8 @@ Updates page and the update-needed card): **Check for updates** → **Update to→ **Downloading… N%** (the Updates page adds a progress bar) → **Restart to update** →**Restarting…**. A check the person starts that finds nothing opens a **You're up to date**dialog in the chat window (scheduled checks stay silent). 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 right+or it installs once idle (once no bot is working, when another device chose **Update now** for+this computer). While a release is available, a filled arrow badge sits rightof **Extensions** in the sidebar footer (under theExtensions icon in the collapsed rail), its tooltip the same action label; one clickrestarts into the release, downloading it first if needed (a ring fills with the downloaddiff --git a/docs/guides/linux-servers.md b/docs/guides/linux-servers.mdindex 22a3eb6e..9074da25 100644--- a/docs/guides/linux-servers.md+++ b/docs/guides/linux-servers.md@@ -39,7 +39,7 @@ The phone connects over the encrypted device channel. The pairing link lists onl- **Your own HTTPS reverse proxy:** forward only `/channel` (WebSocket upgrade) at the root of a hostname to the host; don't forward `/api`, `/events`, `/term` or `/oauth`: through a local proxy every request looks like it comes from this computer, so the loopback-only checks no longer protect them. Then set `CODYNC_EXTERNAL_URL=https://codync.example.com` (comma-separated for several) in the host's environment: `systemctl --user edit codync-host`, add `[Service]` and `Environment=CODYNC_EXTERNAL_URL=https://codync.example.com`, then `systemctl --user restart codync-host`. The host advertises those URLs first, in the pairing link and on every connection, so the phone keeps them (a phone keeps only the addresses the host advertises). Under your own supervisor, `CODYNC_EXTERNAL_URL=… codync-host serve --bind 127.0.0.1` keeps the host on loopback behind the proxy. The phone dials `<url>/channel?v=1`. Opening `/channel` in a browser or with `curl` gets `400` (no WebSocket upgrade), and an upgrade without `?v=1` gets `426` `upgradeRequired`: that means the proxy works. A working proxy answers the phone's upgrade with `101`.- **Desktop app over SSH:** the desktop app (macOS or Linux) can attach an SSH computer and tunnel to its loopback API ([Accounts and SSH](accounts-and-ssh.md)). From any terminal: `ssh -L 19222:127.0.0.1:19222 vm`, then `codync-host tui` locally.-The host listens on `0.0.0.0:19222`. The local API (`/api/*`, `/events`, terminals; bearer token) answers **loopback callers only**, so a public address never exposes it. From outside, only `/health` (host id, computer id, version, environment; the binary path and hash and `busy` go to loopback callers only), local routine webhooks (`/hooks/routines/{id}`, which need the routine's key) and the end-to-end encrypted device channel answer, and the channel only serves devices holding this host's pairing keys. Keep 19222 closed in the cloud firewall anyway unless you deliberately pair over a VPN or private network.+The host listens on `0.0.0.0:19222`. The local API (`/api/*`, `/events`, terminals; bearer token) answers **loopback callers only**, so a public address never exposes it. From outside, only `/health` (host id, computer id, version, environment; the binary path and hash, `busy` and `updateRequested` go to loopback callers only), local routine webhooks (`/hooks/routines/{id}`, which need the routine's key) and the end-to-end encrypted device channel answer, and the channel only serves devices holding this host's pairing keys. Keep 19222 closed in the cloud firewall anyway unless you deliberately pair over a VPN or private network.## Limitations on a headless serverdiff --git a/docs/guides/updates.md b/docs/guides/updates.mdindex 4f642f8e..3d4e2a01 100644--- a/docs/guides/updates.md+++ b/docs/guides/updates.md@@ -13,7 +13,8 @@ action on its Updates page. Only packaged `main` builds update: `npm run dev` anwith `tools/account-config.mjs dev` never replace themselves with a release.A check the person starts downloads right away and shows **Downloading… N%** with a-progress bar. A finished download never quits the app by itself: the button becomes+progress bar. A finished download never quits the app by itself (except at another device's+request, below): the button becomes**Restart to update**, and choosing it shows **Restarting…** while the host stops and theinstaller takes over. The relaunched app comes to the front (macOS doesn't activate an appthe installer relaunches from the background, so a one-shot `updateRelaunchInFront`@@ -37,7 +38,11 @@ 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 nokeyboard/mouse input for ten minutes, and the local host reports that it is idle.-A staged update also installs when quitting. Manual installation can interrupt work.+When another device asks this computer to update (`installHostUpdate`, see+[standalone hosts](#standalone-hosts-on-linux-and-macos)), the app downloads the release+whatever the automatic-download setting and restarts into it in the background as soon as the+local host is idle, without the focus and input conditions, for as long as the request lasts+(ten minutes). A staged update also installs when quitting. Manual installation can interrupt work.The release it finds is the one the release gate marked latest, so it always works with theiPhone app in the App Store([holding releases](../reference/compatibility.md#holding-releases-for-the-app-store)).@@ -179,8 +184,20 @@ update status.The TUI's actionlist (`^k`) has **Check for updates**, which reports the result in the status line.-The API operations (`hostUpdateStatus`, `checkHostUpdate`, `installHostUpdate`,-`setHostAutomaticUpdates`) require a local connection, including an SSH tunnel.+The API operations `hostUpdateStatus`, `checkHostUpdate` and `setHostAutomaticUpdates`+require a local connection, including an SSH tunnel.++`installHostUpdate` is also open to paired devices: it's what a client's **Update now**+calls when a computer is too old for it. `hello.canUpdate` says whether it can work there:+a release host the installed service runs, or one the desktop app bundles while that app is+open (it polls `/health?app=true` every 5 seconds; `canUpdate` needs a poll in the last 15).+Both cases are decided in one place, `update::route`. A standalone host schedules the+updater above. An app-bundled host can't replace itself, so it records the request and+reports it as `updateRequested` (when, in ms) in its loopback `/health` for ten minutes; the+desktop app downloads its release and restarts into it in the background once no bot is+working (`apps/desktop/src/main/updates.ts`). The host refuses while a bot is working unless+the call passes `force`. The TUI keeps **Check for updates** only: it runs on the computer+or reaches it through `ssh -L`, so `codync-host update` there is the direct fix.Installed services schedule the updater as an independent launchd job or systemduser unit, so stopping the daemon does not kill its updater. The CLI returns afterdiff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.mdindex 01e5a52b..c4e8de09 100644--- a/docs/reference/compatibility.md+++ b/docs/reference/compatibility.md@@ -32,8 +32,8 @@ reason to lock someone out.|---|---|---|| Notice | `UpdateNeededCard` above the computer's bots and in place of the composer; status reads *Needs update* | *needs update* in the status line, with the reason || Update this app | iPhone: App Store page. Desktop: electron-updater check (`apps/desktop/src/main/updates.ts`). Android: text only | Text only |-| Update the host | Desktop: its own host is reinstalled (**Restart host**). iPhone and Android: instructions for that computer | `^k` → Check for updates |-| Sync while mismatched | Stopped; `hello` is asked again every 30 s and on every reconnect | Continues; sending is blocked |+| Update the host | Desktop on macOS and Windows, its own computer: the bundled host is reinstalled (**Update now**). Any computer whose `hello` has `canUpdate` (the Linux desktop's own too): **Update now** calls `installHostUpdate` ([updates](../guides/updates.md#standalone-hosts-on-linux-and-macos)), and the notice reads *Updating Codync on …* until the host comes back newer, or for 10 minutes; then it offers the update again with why. Otherwise: instructions for that computer | `^k` → Check for updates |+| Sync while mismatched | Stopped; `hello` is asked again every 30 s (5 s while an update asked from here runs) and on every reconnect | Continues; sending is blocked |Drafts are kept while sending is blocked. A host update restarts the host, so the reconnectreads the new `hello` and the notice goes away on its own.@@ -164,5 +164,10 @@ on `~/.codync` or 19222:4. Swap hosts on the same `CODYNC_HOME` (patched ↔ normal) to see the notice appear in thelist and in place of an open chat's composer, and go away after the reconnect.+A Debug host is a development build, so its `hello.canUpdate` is false and the notice gives+instructions. To see **Update now** too, also patch `installable()` in `host/src/update/mod.rs`+to return `true` and `request_install` to return `Ok(())` (or an `Err` with a message, for the+failure note); restarting the scratch host unpatched then plays the update finishing.+The simulator has no App Store app, so *Update Codync* ends in a Safari error there; on adevice it opens the App Store.diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex 00fdef70..50e56b3a 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -32,7 +32,6 @@ impl Caller {const LOCAL_ONLY: &[&str] = &["hostUpdateStatus","checkHostUpdate",- "installHostUpdate","setHostAutomaticUpdates","setScreenEnabled","requestScreenPermission",@@ -240,6 +239,7 @@ mod tests {assert!(permit(&control, "screenPrepare").is_err());assert!(permit(&control, "screenOffer").is_err(), "screen needs the screen scope");assert!(permit(&control, "screenStatus").is_ok(), "status is control");+ assert!(permit(&control, "installHostUpdate").is_ok(), "a phone can update a computer that's behind");assert!(permit(&Caller::Device { key: "k".into(), scopes: vec![] }, "hello").is_err());assert!(permit(&both, "pair").is_err(), "pair only on a pairing channel");assert!(permit(&Caller::Pairing { key: "k".into() }, "hello").is_err());diff --git a/host/src/api/host.rs b/host/src/api/host.rsindex a1157e24..932392d1 100644--- a/host/src/api/host.rs+++ b/host/src/api/host.rs@@ -23,9 +23,9 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Valuelet port = hub.port;let force = b["force"].as_bool().unwrap_or(false);if !force && hub.busy() {- bail!("host is busy; retry when idle or explicitly allow interruption");+ bail!("A bot is working on this computer. Update it once the bot is done.");}- tokio::task::spawn_blocking(move || crate::update::spawn_worker(port, force)).await??;+ tokio::task::spawn_blocking(move || crate::update::request_install(port, force)).await??;json!({"scheduled": true})}"voiceStatus" => crate::voice::status(&hub.store)?,@@ -66,6 +66,8 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value"name": crate::service::host_name(),"version": env!("CARGO_PKG_VERSION"),"minApp": crate::compat::MIN_APP,+ // Whether `installHostUpdate` can update this computer, from here or a phone.+ "canUpdate": tokio::task::spawn_blocking(crate::update::installable).await?,"os": std::env::consts::OS,"device": tokio::task::spawn_blocking(crate::service::device).await?,"home": dirs::home_dir().map(|p| p.to_string_lossy().into_owned()),diff --git a/host/src/api/http.rs b/host/src/api/http.rsindex 7e80581e..c64ca271 100644--- a/host/src/api/http.rs+++ b/host/src/api/http.rs@@ -62,9 +62,20 @@ impl IntoResponse for ApiError {}}+#[derive(Default, Deserialize)]+struct HealthQuery {+ /// Sent by the desktop app's own poll: it's open to carry out an update request.+ #[serde(default)]+ app: bool,+}+/// `GET /health`, open to the network. Where the binary lives (a path with the user's name) and whether/// a turn is running are for this computer's updater and desktop app only.-async fn health(State(hub): State<Arc<Hub>>, ConnectInfo(peer): ConnectInfo<SocketAddr>) -> Json<Value> {+async fn health(+ State(hub): State<Arc<Hub>>,+ ConnectInfo(peer): ConnectInfo<SocketAddr>,+ Query(q): Query<HealthQuery>,+) -> Json<Value> {let mut health = json!({"ok": true,"hostId": hub.host_id,@@ -73,10 +84,14 @@ async fn health(State(hub): State<Arc<Hub>>, ConnectInfo(peer): ConnectInfo<Sock"environment": crate::environment::Environment::current().name(),});if is_loopback(peer.ip()) {+ if q.app {+ crate::update::note_app_poll();+ }let binary = crate::service::binary_identity();health["binaryPath"] = json!(binary.map(|(path, _)| path));health["binaryHash"] = json!(binary.map(|(_, hash)| hash));health["busy"] = hub.busy().into();+ health["updateRequested"] = crate::update::app_requested().into();}Json(health)}@@ -274,13 +289,14 @@ mod tests {async fn health_keeps_the_binary_and_busy_state_on_this_computer() {let (hub, dir) = temp_hub();let at = |addr: &str| ConnectInfo(addr.parse::<SocketAddr>().expect("address"));- let lan = health(State(hub.clone()), at("192.168.1.20:50000")).await.0;+ let lan = health(State(hub.clone()), at("192.168.1.20:50000"), Query(HealthQuery::default())).await.0;assert!(lan["computerId"].is_string());- for key in ["binaryPath", "binaryHash", "busy"] {+ for key in ["binaryPath", "binaryHash", "busy", "updateRequested"] {assert!(lan.get(key).is_none(), "{key} reached the network");}- let local = health(State(hub), at("[::ffff:127.0.0.1]:50000")).await.0;+ let local = health(State(hub), at("[::ffff:127.0.0.1]:50000"), Query(HealthQuery::default())).await.0;assert_eq!(local["busy"], false);+ assert!(local["updateRequested"].is_null(), "nobody asked this computer to update");assert!(local.get("binaryPath").is_some());let _ = std::fs::remove_dir_all(dir);}diff --git a/host/src/update/mod.rs b/host/src/update/mod.rsindex 4c02178c..2f57cde2 100644--- a/host/src/update/mod.rs+++ b/host/src/update/mod.rs@@ -1,5 +1,6 @@//! Standalone host updates. App bundles and package managers retain ownership-//! of their binaries. A signed manifest is required before executing new code.+//! of their binaries; a host the desktop app bundles hands an update request to+//! the app. A signed manifest is required before executing new code.mod install;mod release;#[cfg(test)]@@ -9,7 +10,14 @@ use crate::{hub::Hub, service};use anyhow::{Context, Result, ensure};use serde::{Deserialize, Serialize};use serde_json::{Value, json};-use std::{path::Path, sync::Arc, time::Duration};+use std::{+ path::Path,+ sync::{+ Arc,+ atomic::{AtomicI64, Ordering},+ },+ time::Duration,+};#[derive(Deserialize, Serialize)]struct Config {@@ -30,11 +38,82 @@ const fn on() -> bool {/// A release build of a standalone binary that the installed service runs: the hosts that/// update themselves (app bundles and Homebrew own their binaries).-fn self_updating(executable: &Path) -> bool {- crate::environment::Environment::current().require_release_updates().is_ok()- && install::require_standalone(executable).is_ok()- && service::installed()- && service::require_executable(executable).is_ok()+fn require_self_updating(executable: &Path) -> Result<()> {+ crate::environment::Environment::current().require_release_updates()?;+ install::require_standalone(executable)?;+ ensure!(+ service::installed(),+ "background updates require an installed host service; run `codync-host update` in a terminal"+ );+ service::require_executable(executable)+}++/// When the desktop app that bundles this host last polled `/health` (ms; 0: never).+static APP_POLLED: AtomicI64 = AtomicI64::new(0);++/// The app polls every 5 s: quiet for longer, it isn't open to carry out a request.+const APP_POLL_TTL_MS: i64 = 15_000;++/// When an update was last asked of that app (ms; 0: never). Its main process sees it in+/// `/health` and runs its own updater.+static APP_REQUESTED: AtomicI64 = AtomicI64::new(0);++/// How long a request waits for the app: one it never saw doesn't update the app days later.+const APP_REQUEST_TTL_MS: i64 = 10 * 60 * 1000;++/// `at` (ms; 0: never) when it was less than `ttl` ms before `now`.+fn recent(at: i64, now: i64, ttl: i64) -> Option<i64> {+ (at > 0 && now - at < ttl).then_some(at)+}++/// The desktop app polled `/health`: it's open to carry out an update request.+pub fn note_app_poll() {+ APP_POLLED.store(crate::store::now_ms(), Ordering::Release);+}++/// Who carries out `installHostUpdate` on this computer.+enum Route {+ /// The desktop app that bundles this host, through `/health`.+ App,+ /// The independent updater (`spawn_worker`).+ Worker,+}++/// How `installHostUpdate` updates this computer, or why it can't: both what `hello.canUpdate`+/// promises and what the call does. Homebrew and development builds update through their owners.+fn route(executable: &Path) -> Result<Route> {+ if install::method(executable) != install::Method::AppBundle {+ require_self_updating(executable)?;+ release::platform()?;+ return Ok(Route::Worker);+ }+ crate::environment::Environment::current().require_release_updates()?;+ ensure!(+ recent(APP_POLLED.load(Ordering::Acquire), crate::store::now_ms(), APP_POLL_TTL_MS).is_some(),+ "Codync isn't open on this computer. Open it, then try again."+ );+ Ok(Route::App)+}++/// Whether `installHostUpdate` can update this computer (`hello.canUpdate`).+pub fn installable() -> bool {+ service::current_exe().is_ok_and(|executable| route(&executable).is_ok())+}++/// Installs the latest release now (`installHostUpdate`).+pub fn request_install(port: u16, force: bool) -> Result<()> {+ match route(&service::current_exe()?)? {+ Route::App => {+ APP_REQUESTED.store(crate::store::now_ms(), Ordering::Release);+ Ok(())+ }+ Route::Worker => spawn_worker(port, force),+ }+}++/// The update asked of the app that bundles this host and not yet expired (when, in ms).+pub fn app_requested() -> Option<i64> {+ recent(APP_REQUESTED.load(Ordering::Acquire), crate::store::now_ms(), APP_REQUEST_TTL_MS)}#[derive(Default, Deserialize, Serialize)]@@ -85,7 +164,7 @@ fn status_at(executable: &Path) -> Result<Value> {let config: Config = read("update-config.json")?;Ok(json!({"currentVersion": env!("CARGO_PKG_VERSION"), "method": install::method(executable),- "automatic": config.automatic && self_updating(executable), "state": state,+ "automatic": config.automatic && require_self_updating(executable).is_ok(), "state": state,}))}@@ -180,12 +259,7 @@ pub fn spawn_worker(port: u16, force: bool) -> Result<()> {let previous: State = read("update-state.json")?;ensure!(!awaiting_worker(&previous), "a host update is already starting");let executable = service::current_exe()?;- install::require_standalone(&executable)?;- ensure!(- service::installed(),- "background updates require an installed host service; run `codync-host update` in a terminal"- );- service::require_executable(&executable)?;+ require_self_updating(&executable)?;let mut args = vec!["update".to_owned(), "--worker".to_owned(), "--port".to_owned(), port.to_string()];if force {args.push("--force".to_owned());@@ -251,7 +325,7 @@ pub async fn automatic_loop(hub: Arc<Hub>) {continue;}last_check = Some(tokio::time::Instant::now());- if !service::current_exe().is_ok_and(|exe| self_updating(&exe)) {+ if !service::current_exe().is_ok_and(|exe| require_self_updating(&exe).is_ok()) {continue;}match check().await {diff --git a/host/src/update/tests.rs b/host/src/update/tests.rsindex 38910750..2697c1b8 100644--- a/host/src/update/tests.rs+++ b/host/src/update/tests.rs@@ -1,4 +1,4 @@-use super::{install, release};+use super::{APP_POLL_TTL_MS, APP_REQUEST_TTL_MS, install, recent, release};use base64::{Engine as _, engine::general_purpose::STANDARD as B64};use ed25519_dalek::{Signer as _, SigningKey};use std::{@@ -176,3 +176,13 @@ fn app_and_homebrew_binaries_keep_their_installation_owner() {install::Method::Homebrew);}++#[test]+fn app_requests_and_polls_count_only_while_recent() {+ let at = 1_000_000;+ for ttl in [APP_REQUEST_TTL_MS, APP_POLL_TTL_MS] {+ assert_eq!(recent(at, at + ttl - 1, ttl), Some(at));+ assert_eq!(recent(at, at + ttl, ttl), None, "an app opened later doesn't act on an old request");+ assert_eq!(recent(0, at, ttl), None, "never asked, never polled");+ }+}diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex a64e3320..b31e0496 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -183,6 +183,7 @@"hello": "object","hello.analytics": "bool","hello.boxKey": "string",+ "hello.canUpdate": "bool","hello.cloud": "null","hello.computerId": "string","hello.device": "string",diff --git a/web/content/docs/updates.mdx b/web/content/docs/updates.mdxindex 1912c226..ee1ab1a2 100644--- a/web/content/docs/updates.mdx+++ b/web/content/docs/updates.mdx@@ -22,6 +22,8 @@ While a release is available, an **Update** button also appears in the chat windA finished download never quits the app by itself. Automatic installation waits until no Codync window is in front, you haven't used the keyboard or mouse for ten minutes, and no bot is working. A downloaded update also installs when you quit Codync.+The exception is **Update now** chosen for this computer on another device (see [below](#when-the-phone-and-computer-versions-dont-match)): the app then downloads the release, even with automatic download off, and restarts into it in the background as soon as no bot is working, without waiting for you to step away.+On macOS and Windows, updating the app also updates this computer's host: the app stops the host, installs, and starts the new one. If you installed the Mac app with Homebrew, it still updates itself this way.## The host on its own@@ -56,7 +58,7 @@ Each side knows the oldest version of the other side it still works with. When o| Notice | What to do || --- | --- || **Update this app** | The app you're using is too old for that computer. On the iPhone, **Update Codync** opens the App Store; if the version you need is still in App Store review, the button stays greyed out until it's available. In the desktop app, use the update button on the notice. |-| **Update Codync on** and the computer's name | The computer's host is too old for this app. The notice says how: on a Mac, open Codync there and check for updates; on Linux, run `codync-host update` there. For the computer the desktop app runs on (macOS and Windows), the notice has a button that updates it. |+| **Update Codync on** and the computer's name | The computer's host is too old for this app. Choose **Update now** on the notice: the computer downloads the new version and restarts into it, usually within a few minutes, and the notice goes away once it's back. A computer doesn't update while a bot is working on it; the notice then says so, and you can try again when the bot is done. A Mac or Windows computer updates this way while the Codync app is open on it. When the computer can't be updated from another device (the app isn't open there, or its Codync is older), the notice says how to do it there: on a Mac, open Codync and check for updates; on Linux, run `codync-host update`. |In the terminal UI, the status line shows **needs update** with the reason, and sending is blocked until you update.