Skip to content

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.

fix: keep computers and devices accurate across apps

leepokai553994e9978e
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
index 069c91d3..3593561a 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
@@ -147,6 +147,16 @@ class AccountScreenTest {
assertEquals(listOf(cloud, cloud), asked)
}
+ @Test fun whileOneComputerIsAskedForAccessTheOthersWait() {
+ val asked = CloudComputer("asked-computer", "Asked computer", "asked-key", online = true)
+ val other = CloudComputer("other-computer", "Other computer", "other-key", online = true)
+ val state = fixture().copy(cloudComputers = listOf(asked, other), askingAccess = asked.computerId)
+ compose.setContent { Hosted { SettingsView(state, viewModel(), null, {}, {}, {}) } }
+ val buttons = compose.onAllNodesWithText("Ask for access")
+ buttons[0].assertIsEnabled()
+ buttons[1].assertIsNotEnabled()
+ }
+
@Test fun thePendingAccessBannerShowsTheCodeAndCancels() {
var cancelled = false
compose.setContent { Hosted { AccessBanner(AccessTicket("request", Long.MAX_VALUE, "123456", "computer", "key"), "Fixture computer") { cancelled = true } } }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
index a8b30eb1..465f5509 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
@@ -15,6 +15,8 @@ data class AppState(
val account: AccountState = AccountState(),
val cloudComputers: List<CloudComputer> = emptyList(),
val access: AccessTicket? = null,
+ /** The account computer an access request is running for: one at a time. */
+ val askingAccess: String? = null,
val notifications: Boolean = true,
val tasks: Boolean = true,
val setupComplete: Boolean = false,
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
index 3fd42a60..056dc2d8 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
@@ -51,6 +51,8 @@ class AppStore(application: Application) : AndroidViewModel(application) {
internal val sends = mutableSetOf<String>()
internal val actions = mutableMapOf<String, Job>()
internal var pluginsRefreshAgain = false
+ /** Bumped by each local change to the account's computers: a list asked for before one is out of date. */
+ internal var cloudListVersion = 0
internal var widgetOwner: WidgetOwner? = null
/** The host version an undecodable event already made the mirror fetch everything again for. */
internal var rewoundFor: String? = null
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt
index be468b2b..c0c64301 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt
@@ -48,17 +48,33 @@ fun AppStore.refreshCloud() = action("cloud") {
val client = cloud ?: return@action
try {
client.registerDevice(Build.MODEL.take(100))
- val computers = client.computers()
+ // The list changed here while one was on its way (a removal): it's out of date, so it's asked
+ // for again. A removal's own refresh, asked for while this one ran, is this one.
+ var computers: List<CloudComputer>
+ do {
+ val version = cloudListVersion
+ computers = client.computers()
+ } while (version != cloudListVersion)
mutableState.update { it.copy(cloudComputers = computers) }
// Signed in to an account with computers, before pairing any (iOS: the same moment).
if (computers.isNotEmpty() && state.value.computers.isEmpty()) Analytics.completeOnboarding(OnboardingVia.Account)
- } catch (error: CloudError) { if (!error.isTransient) throw error }
+ } catch (error: IOException) {
+ if (error is CloudError && !error.isTransient) throw error
+ // Runs on every launch and foreground: a dropped connection, a busy cloud or a token not ready
+ // yet fixes itself on the next refresh, so only answers that stay reach the dialog (as on iOS).
+ android.util.Log.i("Codync", "Cloud refresh failed: ${error.message}")
+ }
}
/** A pull to refresh: the account's computers, joining a refresh already under way. */
suspend fun AppStore.refreshComputers() { refreshCloud(); actions["cloud"]?.join() }
fun AppStore.requestAccess(target: CloudComputer) = action("access") {
+ mutableState.update { it.copy(askingAccess = target.computerId) }
+ try { askForAccess(target) } finally { mutableState.update { it.copy(askingAccess = null) } }
+}
+
+private suspend fun AppStore.askForAccess(target: CloudComputer) {
val client = requireNotNull(cloud) { "Sign in to reach your account." }
require(state.value.computers.isEmpty() || state.value.computers.first().id == target.computerId) { "Forget the current computer before connecting a different one." }
val ticket = client.requestAccess(target.computerId, target.signKey)
@@ -80,12 +96,21 @@ fun AppStore.requestAccess(target: CloudComputer) = action("access") {
withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }
mutableState.update { it.copy(computers = listOf(computer), setupComplete = true) }
Analytics.capture(AnalyticsEvent.ComputerPaired(PairedVia.Account, computer.id))
- openMirror(); connect(); return@action
+ openMirror(); connect()
+ // Its account entry now says granted, which offers Revoke.
+ refreshCloud()
+ return
}
"denied" -> {
Analytics.capture(AnalyticsEvent.AccessRequestFailed(AccessFailure.Denied))
throw IOException("${target.name} declined the request.")
}
+ "cancelled" -> {
+ Analytics.capture(AnalyticsEvent.AccessRequestFailed(AccessFailure.Cancelled))
+ // Withdrawn by the account: the list shows what's left of it.
+ refreshCloud()
+ throw IOException("The request was withdrawn: ${target.name} or this phone was removed from your account.")
+ }
else -> throw CloudError(410, "requestExpired")
}
}
@@ -115,9 +140,27 @@ fun AppStore.revokeAccess(computerId: String) = action("revoke") {
if (state.value.computers.firstOrNull()?.id == computerId) forgetComputer() else refreshCloud()
}
-/** Takes an older copy of a computer out of the account (its grants and pending requests go with it). */
+/**
+ * Takes an older copy of a computer out of the account (its grants and pending requests go with it).
+ * Its row goes at once, and a list asked for before the removal finished can't bring it back (iOS
+ * `AccountStore.removeFromAccount`); a failed removal puts it back.
+ */
fun AppStore.removeFromAccount(computerId: String) = action("removeFromAccount") {
- requireNotNull(cloud) { "Sign in to reach your account." }.removeComputer(computerId)
+ val client = requireNotNull(cloud) { "Sign in to reach your account." }
+ val index = state.value.cloudComputers.indexOfFirst { it.computerId == computerId }
+ if (index < 0) return@action
+ val removed = state.value.cloudComputers[index]
+ cloudListVersion++
+ mutableState.update { s -> s.copy(cloudComputers = s.cloudComputers.filter { it.computerId != computerId }) }
+ try { client.removeComputer(computerId) }
+ catch (error: CancellationException) { throw error }
+ catch (error: Exception) {
+ mutableState.update { s ->
+ if (s.cloudComputers.any { it.computerId == computerId }) s
+ else s.copy(cloudComputers = s.cloudComputers.toMutableList().apply { add(minOf(index, size), removed) })
+ }
+ throw error
+ } finally { cloudListVersion++ }
refreshCloud()
}
@@ -129,7 +172,24 @@ fun AppStore.setColor(color: String) = action("color") {
mutableState.update { it.copy(computers = listOf(changed)) }
}
-fun AppStore.forgetComputer() = sessionAction {
+/**
+ * Remove: forgets the computer here. Approved through the account, its grant goes too (as on iOS), or it
+ * would come straight back as an account row; a failed revoke still forgets it, and its error shows.
+ */
+fun AppStore.removeComputer() = sessionAction {
+ val id = state.value.computers.firstOrNull()?.id ?: return@sessionAction
+ val granted = state.value.cloudComputers.any { it.computerId == id && it.isGranted }
+ val failure = if (!granted) null else try { requireNotNull(cloud) { "Sign in to reach your account." }.revokeAccess(id); null }
+ catch (error: CancellationException) { throw error }
+ catch (error: Exception) { error }
+ forget()
+ // Thrown after the context reloads, which clears the error shown.
+ failure?.let { throw it }
+}
+
+fun AppStore.forgetComputer() = sessionAction { forget() }
+
+private suspend fun AppStore.forget() {
transitions.withLock {
val userId = state.value.account.userId
retireContext()
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.kt
index 667c512e..0245efac 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
@@ -57,10 +57,12 @@ internal fun AppStore.pair(text: String, via: PairedVia) {
try {
val pairing = Pairing.parse(text, BuildConfig.URL_SCHEME)
val old = state.value.computers.firstOrNull()
- require(old == null || old.id == pairing.computer.id) { "Use Start over to pair a different computer." }
+ require(old == null || old.id == pairing.computer.id) { "Remove this phone's computer in Computers & settings to pair a different one." }
require(old == null || old.signKey == pairing.computer.signKey) { "This computer's identity changed. Start over before pairing again." }
val identity = withContext(Dispatchers.IO) { local.identity() }
- val computer = HostConnector.pair(pairing, identity, Build.MODEL.take(100)).copy(color = old?.color)
+ // Picked on this phone: re-pairing keeps them (iOS `AccountStore.pair`).
+ val paired = HostConnector.pair(pairing, identity, Build.MODEL.take(100))
+ val computer = old?.let { paired.copy(color = it.color, route = it.route) } ?: paired
withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }
mutableState.update { it.copy(computers = listOf(computer), setupComplete = true) }
Analytics.capture(AnalyticsEvent.ComputerPaired(via, computer.id))
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.kt
index 929fbf6e..dde93782 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
@@ -62,6 +62,8 @@ import kotlinx.serialization.json.putJsonArray
val reorder = remember { RosterReorder() }
reorder.roster = roster.map(Bot::id)
val online = state.actualConnection is LinkState.Ready
+ // A computer that turned this phone away, or this computer's older identity, counts as none (iOS `availableStores`).
+ val usable = state.computers.isNotEmpty() && !state.isStale
val top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
GlassStage(Modifier.fillMaxSize().background(Palette.background), chrome = {
ScrollEdge(Edge.Top, top + 64.dp)
@@ -69,7 +71,7 @@ import kotlinx.serialization.json.putJsonArray
verticalAlignment = Alignment.CenterVertically) {
AccountSwitcherButton(state, account)
Box(Modifier.weight(1f), contentAlignment = Alignment.Center) { ComputerFilterHeader(state, store, manage) }
- NewMenuButton(enabled = state.computers.isNotEmpty(), groupEnabled = online, newBot, newGroup)
+ NewMenuButton(enabled = usable, groupEnabled = online, newBot, newGroup)
}
}) {
// Pull to refresh reconnects and asks the account for its computers again (iOS `refreshable`).
@@ -78,7 +80,7 @@ import kotlinx.serialization.json.putJsonArray
// 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)) } }
if (roster.isEmpty() && state.mismatch == null) item {
- EmptyRoster(canCreate = state.computers.isNotEmpty(), hasComputer = state.computers.isNotEmpty(), create = newBot, showComputers = manage)
+ EmptyRoster(canCreate = usable, hasComputer = usable, create = newBot, showComputers = manage)
}
items(reorder.shown(roster), key = Bot::id) { bot ->
val lifted = reorder.dragged == bot.id
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
index 2534a4d8..15d8604a 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
@@ -1,6 +1,7 @@
package com.codync.android
import com.codync.android.core.CloudComputer
+import com.codync.android.core.Computer
import com.codync.android.core.HostRoute
import com.codync.android.core.LinkState
@@ -54,35 +55,42 @@ internal fun connectionSummary(state: AppState): String = when {
/**
* The computer this phone uses won't come back as it is: it turned this phone away, or it's offline
- * while an account computer with its name is online, the same machine under a new identity
- * (iOS `AccountStore.isStale`). Removing it is the fix.
+ * while an account computer with its name that joined after it was last seen is online, the same
+ * machine under a new identity (iOS `AccountStore.isStale`). Removing it is the fix.
*/
internal val AppState.isStale: Boolean get() {
val computer = computers.firstOrNull() ?: return false
return when (val link = connection) {
- is LinkState.Failed -> link.unauthorized || renamedCopyOnline(computer.id, computer.name)
- is LinkState.ComputerOffline -> renamedCopyOnline(computer.id, computer.name)
+ is LinkState.Failed -> link.unauthorized || renamedCopyOnline(computer)
+ is LinkState.ComputerOffline -> renamedCopyOnline(computer)
else -> false
}
}
-private fun AppState.renamedCopyOnline(id: String, name: String) =
- cloudComputers.any { it.computerId != id && it.name == name && it.online == true }
+private fun AppState.renamedCopyOnline(computer: Computer): Boolean {
+ val seen = cloudComputers.firstOrNull { it.computerId == computer.id }?.lastSeenAt ?: (connection as? LinkState.ComputerOffline)?.lastSeenAt
+ return cloudComputers.any { it.computerId != computer.id && it.name == computer.name && it.online == true && replacedBy(it.computerId, seen) }
+}
+
+/**
+ * A computer last [seen] no later than account computer [id] joined the account was replaced by it;
+ * seen after, it ran beside it: another machine with the same name. Without both times the name decides.
+ */
+private fun AppState.replacedBy(id: String, seen: Long?): Boolean {
+ seen ?: return true
+ val claimed = cloudComputers.firstOrNull { it.computerId == id }?.claimedAt ?: return true
+ return seen <= claimed
+}
/**
- * An offline account computer named like one this phone uses or sees online: most likely the same
- * machine under an earlier identity (its host keys were reset), left behind in the account.
- * Seen after that one joined the account, it ran beside it: another machine with the same name.
+ * An offline account computer named like one this phone uses or sees online, and [replacedBy] it: most
+ * likely the same machine under an earlier identity (its host keys were reset), left behind in the account.
*/
internal fun AppState.isOlderCopy(computer: CloudComputer): Boolean {
if (computer.online == true) return false
- fun replacedBy(id: String): Boolean {
- val seen = computer.lastSeenAt ?: return true
- val claimed = cloudComputers.firstOrNull { it.computerId == id }?.claimedAt ?: return true
- return seen <= claimed
- }
+ val seen = computer.lastSeenAt
// The current copy may be paired with its code without being listed in the account.
- return computers.any { it.id != computer.computerId && it.name == computer.name && replacedBy(it.id) }
+ return computers.any { it.id != computer.computerId && it.name == computer.name && replacedBy(it.id, seen) }
|| cloudComputers.any { other -> other.computerId != computer.computerId && other.name == computer.name
- && (computers.any { it.id == other.computerId } || other.online == true) && replacedBy(other.computerId) }
+ && (computers.any { it.id == other.computerId } || other.online == true) && replacedBy(other.computerId, seen) }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
index 85196241..d8a8c2e7 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
@@ -79,11 +79,12 @@ import kotlinx.serialization.json.put
if (paired != null) row {
val inAccount = state.cloudComputers.firstOrNull { it.computerId == paired.id }
ComputerRow(state, store, inAccount != null, ComputerActions(extensions, store::openScreen, voice = { voice = true }, color = { coloring = true },
- revoke = inAccount?.takeIf { it.access == "granted" }?.let { c -> { confirmRevoke = c } }) { confirmForget = true })
+ revoke = inAccount?.takeIf { it.isGranted }?.let { c -> { confirmRevoke = c } }) { confirmForget = true })
}
for (computer in state.cloudComputers.filter { it.computerId != paired?.id }) row {
if (state.isOlderCopy(computer)) OlderCopyRow(computer) { confirmRemoveCopy = computer }
else AccountComputerRow(computer, state.access?.takeIf { it.computerId == computer.computerId }?.code, canAsk = paired == null,
+ askingAnother = state.askingAccess.let { it != null && it != computer.computerId },
ask = { ask(computer) }, revoke = { confirmRevoke = computer })
}
row {
@@ -148,7 +149,7 @@ import kotlinx.serialization.json.put
}
CodyncDialog("Remove ${paired?.name ?: "computer"}?", confirmForget, { confirmForget = false },
"Its bots and conversations stay on that computer. You can pair again any time.") {
- listOf(DialogAction("Remove", destructive = true, action = store::forgetComputer))
+ listOf(DialogAction("Remove", destructive = true, action = store::removeComputer))
}
CodyncDialog("Revoke this phone's access to ${confirmRevoke?.name ?: "the computer"}?", confirmRevoke != null, { confirmRevoke = null },
"You can ask for access again; the computer will show a new code to confirm.") {
@@ -224,12 +225,13 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unit
}
}
-/** A computer in the account that this phone can't use yet. */
-@Composable private fun AccountComputerRow(computer: CloudComputer, code: String?, canAsk: Boolean, ask: () -> Unit, revoke: () -> Unit) {
+/** A computer in the account that this phone can't use yet; `askingAnother` while this phone asks a different one. */
+@Composable private fun AccountComputerRow(computer: CloudComputer, code: String?, canAsk: Boolean, askingAnother: Boolean, ask: () -> Unit,
+ revoke: () -> Unit) {
val online = if (computer.online == true) "Online" else "Offline"
val detail = when {
code != null -> "Waiting for your OK on the computer · $code"
- computer.access == "granted" -> "Approved for an earlier install of Codync. Revoke it, then ask again."
+ computer.isGranted -> "Approved for an earlier install of Codync. Revoke it, then ask again."
computer.access == "pending" -> "$online · A request is waiting"
canAsk -> "$online · In your account"
// One computer per phone for now: the paired one goes first.
@@ -243,8 +245,8 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unit
}
when {
code != null -> SecondaryButton("Code", action = ask)
- computer.access == "granted" -> SecondaryButton("Revoke", action = revoke)
- else -> SecondaryButton("Ask for access", enabled = canAsk, action = ask)
+ computer.isGranted -> SecondaryButton("Revoke", action = revoke)
+ else -> SecondaryButton("Ask for access", enabled = canAsk && !askingAnother, action = ask)
}
}
}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
index e7dc4b5c..f98dc618 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
@@ -64,6 +64,20 @@ class ConnectionPresentationTest {
assertEquals("Revoked", computerStatusText(state(LinkState.Failed("Revoked", 403), listOf(cloud("new", online = true)))))
}
+ @Test fun aComputerSeenAfterItsNamesakeJoinedTheAccountRunsBesideItAndIsNotStale() {
+ val namesake = cloud("new", online = true).copy(claimedAt = 100)
+ fun own(seen: Long) = cloud("fixture", online = false).copy(lastSeenAt = seen)
+ // Its own account entry says when it was last seen.
+ assertFalse(state(LinkState.ComputerOffline(null), listOf(own(200), namesake)).isStale)
+ assertTrue(state(LinkState.ComputerOffline(null), listOf(own(50), namesake)).isStale)
+ assertFalse(state(LinkState.Failed("Connection closed."), listOf(own(200), namesake)).isStale)
+ // Paired with its code only: the relay's last seen decides.
+ assertFalse(state(LinkState.ComputerOffline(200), listOf(namesake)).isStale)
+ assertTrue(state(LinkState.ComputerOffline(50), listOf(namesake)).isStale)
+ // Without the namesake's join time, the name alone.
+ assertTrue(state(LinkState.ComputerOffline(200), listOf(cloud("new", online = true))).isStale)
+ }
+
@Test fun anOfflineAccountComputerNamedLikeTheCurrentOneIsAnOlderCopy() {
val old = cloud("old", online = false)
assertTrue(state(LinkState.Connecting, listOf(old)).isOlderCopy(old))
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
index 237b01c2..460d93d0 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
@@ -22,7 +22,10 @@ import java.util.concurrent.TimeUnit
data class CloudComputer(val computerId: String, val name: String, val signKey: String,
val platform: String? = null, val device: String? = null, val boxKey: String? = null,
val version: String? = null, val online: Boolean? = null, val lastSeenAt: Long? = null,
- val claimedAt: Long? = null, val access: String? = null)
+ val claimedAt: Long? = null, val access: String? = null) {
+ /** This device was approved on it through the account. */
+ val isGranted: Boolean get() = access == "granted"
+}
data class AccessTicket(val requestId: String, val expiresAt: Long, val code: String, val computerId: String, val signKey: String)
@@ -132,12 +135,12 @@ class CloudClient private constructor(base: String, private val identity: Device
val source = response.body?.source()
if (source?.request(MAX_RESPONSE + 1) == true) throw IOException("Cloud response is too large.")
val text = source?.readUtf8().orEmpty().ifBlank { "{}" }
- val result = json.parseToJsonElement(text).jsonObject
if (!response.isSuccessful) {
- val detail = result["error"]?.jsonObject
+ // A proxy or platform error page isn't JSON; the status still says what happened.
+ val detail = runCatching { json.parseToJsonElement(text).jsonObject["error"]?.jsonObject }.getOrNull()
throw CloudError(response.code, detail?.text("code") ?: "http${response.code}", detail?.text("message"))
}
- result
+ json.parseToJsonElement(text).jsonObject
}
continuation.resumeWith(Result.success(parsed))
} catch (error: Exception) { continuation.resumeWith(Result.failure(error)) }
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/EncryptedChannel.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/EncryptedChannel.kt
index 0b92237f..f7587432 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/EncryptedChannel.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/EncryptedChannel.kt
@@ -156,8 +156,15 @@ class EncryptedChannel internal constructor(
mutableState.value = LinkState.Ready(route)
firstState.complete(Unit)
}
- "reject" -> throw HostError(if (wire.text("code") == "unsupportedVersion") 426 else 403,
- wire.text("message") ?: "This device isn't allowed on the computer. Pair it again.")
+ "reject" -> {
+ val message = wire.text("message")
+ throw when (wire.text("code")) {
+ // The computer couldn't confirm the account's approval lately; it may again, so the owner retries.
+ "leaseExpired" -> IOException(message ?: "The computer can't confirm this device's access right now. Try again shortly.")
+ "unsupportedVersion" -> HostError(426, message ?: "Update Codync to connect to this computer.")
+ else -> HostError(403, message ?: "This device isn't allowed on the computer. Pair it again.")
+ }
+ }
"f" -> {
val current = requireNotNull(opener) { "Encrypted frame arrived before the handshake" }
val counter = requireNotNull(wire["c"]?.jsonPrimitive?.longOrNull)
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
index 08843c9e..9c549261 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
@@ -42,7 +42,7 @@ class ChannelIntegrationTest {
private fun identity(): DeviceIdentity = DeviceIdentity(ByteArray(32) { 3 }, ByteArray(32) { 12 })
private fun enqueueHost(forgeSignature: Boolean = false, holdCalls: Boolean = false, burst: Int = 0, welcomeDelay: Long = 0,
- snapshotHead: Int = 5) {
+ snapshotHead: Int = 5, reject: String? = null) {
server.enqueue(MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
private lateinit var opener: FrameOpener
private lateinit var sealer: FrameSealer
@@ -50,6 +50,11 @@ class ChannelIntegrationTest {
override fun onMessage(webSocket: WebSocket, text: String) {
val wire = Json.parseToJsonElement(text).jsonObject
if (wire.text("t") == "hello") {
+ if (reject != null) {
+ webSocket.send(buildJsonObject { put("t", "reject"); put("code", reject); put("message", "Refused: $reject") }.toString())
+ webSocket.close(4001, reject)
+ return
+ }
if (welcomeDelay > 0) Thread.sleep(welcomeDelay)
val dk = requireNotNull(wire.text("dk")).decodeBase64Url(32)
val ek = requireNotNull(wire.text("ek")).decodeBase64Url(32)
@@ -148,6 +153,16 @@ class ChannelIntegrationTest {
assertTrue(rejected)
}
+ @Test fun `a lapsed account lease is a transient failure while a revoked device is turned away`() = runBlocking {
+ enqueueHost(reject = "leaseExpired")
+ enqueueHost(reject = "revoked")
+ val lapsed = runCatching { HostConnector.connect(computer(), identity()) }.exceptionOrNull()
+ assertTrue(lapsed is IOException && lapsed !is HostError)
+ assertEquals("Refused: leaseExpired", lapsed?.message)
+ val revoked = runCatching { HostConnector.connect(computer(), identity()) }.exceptionOrNull()
+ assertEquals(403, (revoked as HostError).status)
+ }
+
@Test fun `an uncertain call timeout cancels its response without replaying the mutation`() = runBlocking {
enqueueHost(holdCalls = true)
val connected = withTimeout(5_000) { HostConnector.connect(computer(), identity()) }
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
index fc23d56a..cfa08b95 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
@@ -60,6 +60,19 @@ class CloudClientTest {
} finally { server.shutdown() }
}
+ @Test fun `an error page that isn't JSON still fails with its status`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setResponseCode(502).setBody("<html><body>Bad gateway</body></html>"))
+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)
+ val error = try { client.computers(); error("Expected a cloud error") } catch (error: CloudError) { error }
+ assertEquals(502, error.status)
+ assertEquals("http502", error.code)
+ assertTrue(error.isTransient)
+ } finally { server.shutdown() }
+ }
+
@Test fun `mismatched host identity cannot start an access request`() = runBlocking {
val server = MockWebServer()
server.start()
diff --git a/apps/desktop/src/main/host-controller.ts b/apps/desktop/src/main/host-controller.ts
index 4eb36d59..181971fd 100644
--- a/apps/desktop/src/main/host-controller.ts
+++ b/apps/desktop/src/main/host-controller.ts
@@ -73,7 +73,7 @@ function serviceDefinition(): string | null {
const serviceInstalled = () => serviceDefinition() !== null
-/** A failed check of the host binary, and the `host_setup_failed` stage it counts as. */
+/** A failed check of the host or its binary, and the `host_setup_failed` stage it counts as. */
class SetupError extends Error {
constructor(readonly stage: HostSetupStage, message: string) {
super(message)
@@ -279,14 +279,17 @@ export class HostController extends EventEmitter {
this.failures = 0
const tick = async () => {
if (generation !== this.generation) return
- if (await this.attachLocal()) {
+ const problem = await this.attachLocal()
+ // It may have started a reinstall (a stale build), which connects on its own.
+ if (generation !== this.generation) return
+ if (!problem) {
this.failures = 0
- if (generation !== this.generation) return
this.setState({ kind: 'running' })
if (devPort === null && prefs.get('hostRestartAfterAppUpdate') === true) prefs.set('hostRestartAfterAppUpdate', false)
} else {
this.failures++
- if (this.failures > 5) this.setupFailed('not_responding', { kind: 'failed', message: "The host isn't responding. See the log for details." })
+ // The other environment's host doesn't become this one's by waiting: shown right away.
+ if (problem.stage === 'environment' || this.failures > 5) this.setupFailed(problem.stage, { kind: 'failed', message: problem.message })
else if (this.state.kind !== 'running') this.setState({ kind: 'starting' })
}
if (generation === this.generation) this.loop = setTimeout(tick, 5000)
@@ -298,33 +301,30 @@ export class HostController extends EventEmitter {
})()
}
- /** Attaches the local host once it answers, and again when its token or identity changed. */
- private async attachLocal(): Promise<boolean> {
+ /** Attaches the local host once it answers, and again when its token or identity changed; else says why not. */
+ private async attachLocal(): Promise<SetupError | null> {
const health = await fetchHealth()
- if (!health?.computerId) return false
+ if (!health?.computerId) return new SetupError('not_responding', "The host isn't responding. See the log for details.")
const mismatch = hostEnvironmentError(identity.environment, health.environment)
- if (mismatch) {
- this.setupFailed('environment', { kind: 'failed', message: mismatch })
- return false
- }
+ if (mismatch) return new SetupError('environment', mismatch)
const token = await readToken()
- if (!token) return false
+ if (!token) return new SetupError('not_responding', `The host is running, but its token (${join(dataDir, 'token')}) can't be read.`)
if (devPort === null) {
// A rebuild can change the host without changing the release version.
const bin = this.binary
- if (!this.expectedHash || !bin) return false
+ if (!this.expectedHash || !bin) return new SetupError('not_responding', "Couldn't read this app's host to check the one that's running.")
const matches = health.binaryHash === this.expectedHash && samePath(health.binaryPath, resolved(bin))
if (!matches) {
if (!this.replacedStale) {
this.replacedStale = true
void this.install()
}
- return false
+ return new SetupError('not_responding', "Another build of the host is running, not this app's. Try again to replace it.")
}
}
- if (this.local?.computerId === health.computerId && this.local.token === token) return true
+ if (this.local?.computerId === health.computerId && this.local.token === token) return null
this.setLocal({ computerId: health.computerId, baseURL, token })
- return true
+ return null
}
}
diff --git a/apps/desktop/src/renderer/lib/auto-claim.test.ts b/apps/desktop/src/renderer/lib/auto-claim.test.ts
new file mode 100644
index 00000000..9abdfc2f
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/auto-claim.test.ts
@@ -0,0 +1,21 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { mayAutoClaim } from './auto-claim.ts'
+
+const host = { id: 'new', online: true, cloud: { enabled: true, owner: null } }
+
+test('a new identity with the cloud on joins the account on its own', () => {
+ assert.equal(mayAutoClaim(host, [], ['old']), true)
+})
+
+test('an identity seen in the account and removed since stays out', () => {
+ assert.equal(mayAutoClaim(host, [], ['old', 'new']), false)
+})
+
+test('no auto-claim when kept out, owned, offline, or the cloud is off or unknown', () => {
+ assert.equal(mayAutoClaim(host, ['new'], []), false)
+ assert.equal(mayAutoClaim({ ...host, cloud: { enabled: true, owner: { userId: 'u' } } }, [], []), false)
+ assert.equal(mayAutoClaim({ ...host, online: false }, [], []), false)
+ assert.equal(mayAutoClaim({ ...host, cloud: { enabled: false } }, [], []), false)
+ assert.equal(mayAutoClaim({ ...host, cloud: null }, [], []), false)
+})
diff --git a/apps/desktop/src/renderer/lib/auto-claim.ts b/apps/desktop/src/renderer/lib/auto-claim.ts
new file mode 100644
index 00000000..56077f8c
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/auto-claim.ts
@@ -0,0 +1,16 @@
+/** What the auto-claim rule reads of this computer's host. */
+export interface ClaimCandidate {
+ id: string
+ online: boolean
+ cloud: { enabled: boolean; owner?: unknown } | null
+}
+
+/**
+ * Whether this computer joins the signed-in account on its own. Only with the cloud on: joining needs
+ * it, and turning it back on is never done silently. Never an identity the user took out here
+ * (`keptOut`), nor one this app has seen in the account (`seen`): without an owner now, it was removed,
+ * maybe from a phone, and stays out until it's added by hand. A new identity (a host reset) joins.
+ */
+export function mayAutoClaim(host: ClaimCandidate, keptOut: readonly string[], seen: readonly string[]) {
+ return host.online && !!host.cloud?.enabled && !host.cloud.owner && !keptOut.includes(host.id) && !seen.includes(host.id)
+}
diff --git a/apps/desktop/src/renderer/store/cloud.ts b/apps/desktop/src/renderer/store/cloud.ts
index 005f3bd5..d1dbed01 100644
--- a/apps/desktop/src/renderer/store/cloud.ts
+++ b/apps/desktop/src/renderer/store/cloud.ts
@@ -1,7 +1,8 @@
import type { CloudStatus, ClaimSignature } from '@shared/models'
+import { mayAutoClaim } from '../lib/auto-claim'
import { Observable } from '../lib/observable'
import { isOlderCopy } from '../lib/older-copy'
-import { pref } from '../lib/prefs'
+import { pref, type Pref } from '../lib/prefs'
import { account } from './account'
import type { AppModel } from './app-model'
import type { BotStore } from './bot-store'
@@ -24,25 +25,6 @@ export interface CloudComputer {
access?: string | null
}
-export interface CloudDevice {
- deviceId: string
- deviceKey: string
- name: string
- platform?: string | null
- createdAt?: number | null
- lastUsedAt?: number | null
- revoked?: boolean | null
-}
-
-export interface CloudGrant {
- grantId: string
- deviceId: string
- deviceName?: string | null
- platform?: string | null
- scopes?: string[] | null
- createdAt?: number | null
-}
-
export class CloudError extends Error {
constructor(
readonly status: number,
@@ -56,11 +38,6 @@ export class CloudError extends Error {
: (message ?? `Codync cloud error (${code})`),
)
}
-
- /** A busy or failing cloud, or a session token that wasn't fresh yet: trying again later settles it. */
- get isTransient() {
- return this.status === 0 || this.status >= 500 || this.status === 429 || this.status === 401
- }
}
async function request<T>(method: string, path: string, body?: unknown, signed = false): Promise<T> {
@@ -71,9 +48,34 @@ async function request<T>(method: string, path: string, body?: unknown, signed =
/** Host identities whose cloud default has been applied (or found already on). */
const cloudDefaultApplied = pref<string[]>('cloudDefaultApplied', [])
-/** The identities this computer claimed: a later key reset can clean them up. */
-const claimedComputerIds = pref<string[]>('claimedComputerIds', [])
-const keptOut = (userId: string) => pref<string[]>(`keptOutOfAccount.${userId}`, [])
+const userPrefs = new Map<string, Pref<string[]>>()
+/** A list kept for each user; one pref each, as each one listens for changes. */
+function userPref(name: string, userId: string) {
+ const key = `${name}.${userId}`
+ let list = userPrefs.get(key)
+ if (!list) userPrefs.set(key, (list = pref<string[]>(key, [])))
+ return list
+}
+/** Adds `id` to a list pref unless it's there. */
+function include(list: Pref<string[]>, id: string) {
+ if (!list.get().includes(id)) list.set([...list.get(), id])
+}
+/** The identities a user took out of their account here. */
+const keptOut = (userId: string) => userPref('keptOutOfAccount', userId)
+/**
+ * The identities of this computer seen in a user's account: a later key reset cleans them up, and
+ * one that leaves the account (a phone's "Remove from account" too) isn't added back on its own.
+ */
+const claimedIds = (userId: string) => userPref('claimedComputerIds', userId)
+/** `claimedComputerIds` from before it was kept per user: its ids go to the first user signed in here. */
+function moveClaimsToUser(userId: string) {
+ try {
+ const raw = localStorage.getItem('claimedComputerIds')
+ if (raw === null) return
+ localStorage.removeItem('claimedComputerIds')
+ for (const id of JSON.parse(raw) as string[]) include(claimedIds(userId), id)
+ } catch {}
+}
/**
* The signed-in account's side of this computer (mirrors kit's `CloudClient`): registering this device, the account's computers, claiming this
@@ -82,6 +84,12 @@ const keptOut = (userId: string) => pref<string[]>(`keptOutOfAccount.${userId}`,
export class CloudModel extends Observable {
computers: CloudComputer[] = []
private registeredFor: string | null = null
+ /** This app's computers (their ids) when the account's computers were last listed. */
+ private listedWith: string | null = null
+ /** Bumped by each list request: only the latest one's answer is kept. */
+ private listVersion = 0
+ /** The latest list request: an earlier one it overtook answers with it. */
+ private listing: Promise<boolean> = Promise.resolve(false)
private enablingCloud = false
private autoClaiming = false
@@ -91,9 +99,10 @@ export class CloudModel extends Observable {
app.subscribe(() => this.tick())
}
+ /** What the user started shows its error; the app's own background calls (`quiet`) only log it. */
private fail(error: unknown, quiet = false) {
- if (quiet || (error instanceof CloudError && error.isTransient)) return
- this.app.setError(error instanceof Error ? error.message : String(error))
+ if (quiet) console.warn('Codync cloud:', error)
+ else this.app.setError(error instanceof Error ? error.message : String(error))
}
private get userId() {
@@ -111,30 +120,55 @@ export class CloudModel extends Observable {
this.registeredFor = null
return
}
+ const managed = this.app.managedStores.map((s) => s.computer.id).sort().join(' ')
if (this.registeredFor !== user) {
this.registeredFor = user
+ this.listedWith = managed
+ moveClaimsToUser(user)
// Signed in: make this computer known to the account, then list its computers.
void (async () => {
try {
await request('POST', 'v1/devices', { name: await deviceName(), platform: { darwin: 'macos', linux: 'linux', win32: 'windows' }[window.codync.platform] }, true)
} catch (error) {
- this.fail(error)
+ this.fail(error, true)
}
- await this.refresh()
+ await this.refresh(true)
})()
+ } else if (this.listedWith !== managed) {
+ // A computer came or went here (a host reset to a new identity, an uninstalled host, an SSH
+ // computer): listed again, one that left shows how it is now, not as the last list had it.
+ this.listedWith = managed
+ void this.refresh(true)
}
this.applyCloudDefault()
this.autoClaim()
}
- async refresh() {
- if (!this.userId) return
+ /**
+ * Lists the account's computers; `quiet` when the app does it on its own. True when a list at least
+ * as new as this call's is shown: a newer request that overtook this one answers for it.
+ */
+ refresh(quiet = false): Promise<boolean> {
+ const user = this.userId
+ if (!user) return Promise.resolve(false)
+ return (this.listing = this.list(user, ++this.listVersion, quiet))
+ }
+
+ private async list(user: string, version: number, quiet: boolean): Promise<boolean> {
try {
const res = await request<{ computers: CloudComputer[] }>('GET', 'v1/computers', undefined, true)
+ // Signed out or into another account while it was on its way.
+ if (this.userId !== user) return false
+ // A newer list was asked for while this one was on its way (after a removal): that one is shown.
+ if (version !== this.listVersion) return this.listing
this.computers = res.computers
this.changed()
+ return true
} catch (error) {
- this.fail(error)
+ if (this.userId !== user) return false
+ if (version !== this.listVersion) return this.listing
+ this.fail(error, quiet)
+ return false
}
}
@@ -151,15 +185,15 @@ export class CloudModel extends Observable {
if (store.cloud.enabled || this.enablingCloud) return
this.enablingCloud = true
void this.enableCloud(store)
- .catch(() => {})
+ .catch((error: unknown) => this.fail(error, true))
.finally(() => (this.enablingCloud = false))
}
- /** Signed in, this computer joins the account on its own, unless the user took it out of it. */
+ /** Signed in, this computer joins the account on its own (`mayAutoClaim`). */
private autoClaim() {
const user = this.userId
const store = this.app.local
- if (user && store && store.cloud?.owner?.userId === user) claimedComputerIds.set([store.computer.id])
+ if (user && store && store.cloud?.owner?.userId === user) include(claimedIds(user), store.computer.id)
const target = this.autoClaimTarget
if (!target || this.autoClaiming) return
this.autoClaiming = true
@@ -176,13 +210,11 @@ export class CloudModel extends Observable {
}
private get autoClaimTarget(): BotStore | null {
- // Only with the cloud on: joining needs it, and turning it back on is never done silently.
const user = this.userId
const store = this.app.local
- if (!user || !store || store.connection.kind !== 'online') return null
- const status = store.cloud
- if (!status?.enabled || status.owner || keptOut(user).get().includes(store.computer.id)) return null
- return store
+ if (!user || !store) return null
+ const host = { id: store.computer.id, online: store.connection.kind === 'online', cloud: store.cloud }
+ return mayAutoClaim(host, keptOut(user).get(), claimedIds(user).get()) ? store : null
}
/** §4.2 A: makes a computer this app manages part of the account; its cloud is turned on first. */
@@ -200,8 +232,8 @@ export class CloudModel extends Observable {
const challenge = await request<{ claimId: string; nonce: string }>('POST', 'v1/claims', {})
const signed = await client.call<ClaimSignature>('claimSign', { claimId: challenge.claimId, nonce: challenge.nonce, userId: user })
await request('POST', `v1/claims/${challenge.claimId}/complete`, signed)
- await this.refresh()
- if (store === this.app.local) await this.forgetEarlierIdentities(store.computer.id)
+ // Only against a list that came back: one that didn't can't tell which earlier identities are gone.
+ if ((await this.refresh(true)) && store === this.app.local) await this.forgetEarlierIdentities(user, store.computer.id)
return true
} catch (error) {
this.fail(error, quiet)
@@ -211,30 +243,33 @@ export class CloudModel extends Observable {
/**
* This computer's host got new keys (a reset data folder, a reinstall): the identities claimed
- * before are dead copies of it, so they leave the account instead of showing up twice.
+ * before are dead copies of it, so they leave the account instead of showing up twice. One still
+ * online, or that couldn't be removed, stays listed for the next time.
*/
- private async forgetEarlierIdentities(current: string) {
- const earlier = new Set(claimedComputerIds.get().filter((id) => id !== current))
- for (const c of this.computers) if (earlier.has(c.computerId) && !c.online) await this.removeFromAccount(c.computerId)
- claimedComputerIds.set([current])
+ private async forgetEarlierIdentities(user: string, current: string) {
+ const seen = claimedIds(user)
+ const kept = [current]
+ for (const id of seen.get()) {
+ const entry = this.computers.find((c) => c.computerId === id)
+ if (id === current || !entry) continue
+ if (entry.online || !(await this.removeFromAccount(id, true))) kept.push(id)
+ }
+ seen.set(kept)
}
async unclaim(store: BotStore) {
const user = this.userId
- if (user) {
- const out = keptOut(user)
- if (!out.get().includes(store.computer.id)) out.set([...out.get(), store.computer.id])
- }
+ if (user) include(keptOut(user), store.computer.id)
try {
await (await store.ready()).call('unclaim', {}, 30_000)
- await this.refresh()
+ await this.refresh(true)
} catch (error) {
this.fail(error)
}
}
async setCloud(store: BotStore, enabled: boolean) {
- if (!cloudDefaultApplied.get().includes(store.computer.id)) cloudDefaultApplied.set([...cloudDefaultApplied.get(), store.computer.id])
+ include(cloudDefaultApplied, store.computer.id)
try {
if (enabled) await this.enableCloud(store)
else await (await store.ready()).call<CloudStatus>('setCloud', { enabled: false }, 30_000)
@@ -248,39 +283,20 @@ export class CloudModel extends Observable {
return (await store.ready()).call<CloudStatus>('setCloud', { enabled: true }, 30_000)
}
- async removeFromAccount(computerId: string) {
+ async removeFromAccount(computerId: string, quiet = false) {
try {
await request('DELETE', `v1/computers/${computerId}`)
- await this.refresh()
+ await this.refresh(true)
+ return true
} catch (error) {
- this.fail(error)
+ this.fail(error, quiet)
+ return false
}
}
isOlderCopy(c: CloudComputer) {
return isOlderCopy(c, this.computers, this.app.computers)
}
-
- devices() {
- return request<{ devices: CloudDevice[] }>('GET', 'v1/devices').then((r) => r.devices)
- }
-
- revokeDevice(deviceId: string) {
- return request('DELETE', `v1/devices/${deviceId}`)
- }
-
- grants(computerId: string) {
- return request<{ grants: CloudGrant[] }>('GET', `v1/computers/${computerId}/grants`).then((r) => r.grants)
- }
-
- revokeGrant(computerId: string, grantId: string) {
- return request('DELETE', `v1/computers/${computerId}/grants/${grantId}`)
- }
-
- async renameComputer(computerId: string, name: string) {
- await request('PATCH', `v1/computers/${computerId}`, { name })
- await this.refresh()
- }
}
/** This computer's name for the account's device list. */
diff --git a/apps/desktop/src/renderer/views/PairingCode.tsx b/apps/desktop/src/renderer/views/PairingCode.tsx
new file mode 100644
index 00000000..6e38293c
--- /dev/null
+++ b/apps/desktop/src/renderer/views/PairingCode.tsx
@@ -0,0 +1,82 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import QRCode from 'qrcode'
+import type { PairingInfo } from '@shared/models'
+import { IconButton, Spinner } from '../components/Controls'
+import { HStack, VStack } from '../components/Stack'
+import { Text } from '../components/Text'
+import { useScreenViewed } from '../store/analytics'
+import './pairing-code.css'
+
+/**
+ * A one-time pairing QR (v3) from a computer this app manages: its keys, a code, and how to reach it.
+ * A new code comes when `renew` changes and when this one expires on screen; when none comes, the
+ * error takes the place of the old code, which may have expired.
+ */
+export function PairingCode({ name, cloudOn, requestCode, renew = 0 }: { name: string; cloudOn: boolean; requestCode: () => Promise<PairingInfo>; renew?: number }) {
+ const [code, setCode] = useState<{ info: PairingInfo; qr: string } | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ useScreenViewed('pairing', renew)
+
+ // Loads overlap (expiry, "New code", a renew): only the latest one's code or error shows.
+ const latest = useRef(0)
+ const load = useCallback(async () => {
+ const request = ++latest.current
+ try {
+ const info = await requestCode()
+ const qr = await QRCode.toDataURL(info.pairingUrl, { errorCorrectionLevel: 'M', margin: 0, width: 400, color: { dark: '#000000', light: '#ffffff' } })
+ if (request !== latest.current) return
+ setCode({ info, qr })
+ setError(null)
+ } catch (e) {
+ if (request !== latest.current) return
+ setCode(null)
+ setError(e instanceof Error ? e.message : String(e))
+ }
+ }, [requestCode])
+
+ useEffect(() => void load(), [load, renew])
+ const expiresAt = code?.info.expiresAt
+ useEffect(() => {
+ if (!expiresAt) return
+ const timer = setTimeout(() => void load(), Math.max(1000, expiresAt - Date.now()))
+ return () => clearTimeout(timer)
+ }, [expiresAt, load])
+
+ return (
+ <VStack align="center" gap={12} className="pairing">
+ {code ? (
+ <>
+ <div className="pairing-qr fade-in">
+ <img src={code.qr} alt={`Pairing code for ${name}`} width={200} height={200} />
+ </div>
+ <Text as="div" size="caption" tone="secondary" className="pairing-note">
+ Scan with the Codync app or the iPhone Camera. No Tailscale or open ports needed: your iPhone connects directly on the same Wi-Fi, and through the encrypted relay anywhere else.
+ </Text>
+ {!cloudOn ? (
+ <Text as="div" size="caption" tone="attention" className="pairing-note">
+ {code.info.urls.length === 0
+ ? 'No network address found and “Reach from anywhere” is off. Connect to Wi-Fi or turn it on.'
+ : `“Reach from anywhere” is off, so the iPhone only reaches ${name} on the same network.`}
+ </Text>
+ ) : null}
+ <HStack gap={4}>
+ {expiresAt ? (
+ <Text size="caption2" tone="tertiary">
+ Works once, until {new Date(expiresAt).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}
+ </Text>
+ ) : null}
+ <IconButton title="New code" icon="arrow.clockwise" onClick={() => void load()} />
+ <IconButton title="Copy pairing link" icon="doc.on.doc" onClick={() => window.codync.app.copy(code.info.pairingUrl)} />
+ </HStack>
+ </>
+ ) : error ? (
+ <>
+ <Text as="div" size="caption" tone="danger" className="pairing-note fade-in">{error}</Text>
+ <IconButton title="Try again" icon="arrow.clockwise" onClick={() => void load()} />
+ </>
+ ) : (
+ <Spinner size={20} />
+ )}
+ </VStack>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/PairingWindow.tsx b/apps/desktop/src/renderer/views/PairingWindow.tsx
index 433ac10b..d7f64a85 100644
--- a/apps/desktop/src/renderer/views/PairingWindow.tsx
+++ b/apps/desktop/src/renderer/views/PairingWindow.tsx
@@ -1,96 +1,34 @@
import { useCallback, useEffect, useState } from 'react'
-import QRCode from 'qrcode'
import type { CloudStatus, PairingInfo } from '@shared/models'
-import { IconButton, Spinner } from '../components/Controls'
-import { HStack, VStack } from '../components/Stack'
-import { Text } from '../components/Text'
import { LoopbackTransport } from '../client/host-client'
-import { analytics, useScreenViewed } from '../store/analytics'
import { useApp } from '../store/context'
-import './pairing-window.css'
+import { PairingCode } from './PairingCode'
-/** A one-time pairing QR (v3) from this computer: its keys, a code, and how to reach it. */
+/** The pairing window: this computer's code, without a mirror of its bots. */
export function PairingWindow() {
- const app = useApp()
- const local = app.host.local
- const [info, setInfo] = useState<PairingInfo | null>(null)
- const [qr, setQr] = useState<string | null>(null)
- const [cloud, setCloud] = useState<CloudStatus | null>(null)
+ // By value: the host's snapshot is a new object on each of its changes (every few seconds), and
+ // each request issues a new code.
+ const { baseURL, token } = useApp().host.local ?? {}
+ const [cloudOn, setCloudOn] = useState(false)
const [name, setName] = useState('this computer')
- const [error, setError] = useState<string | null>(null)
- useScreenViewed('pairing')
+ // The window stays open between uses: each "Pair iPhone…" shows it again, with a new code.
+ const [shown, setShown] = useState(0)
+ useEffect(() => window.codync.app.onCommand((c) => {
+ if (c.kind === 'reviewApprovals') setShown((n) => n + 1)
+ }), [])
- const load = useCallback(async () => {
- if (!local) return setError("This computer's host isn't connected.")
- const transport = new LoopbackTransport(local.baseURL, local.token)
- try {
- const [pairing, status, hello] = await Promise.all([
- transport.call('pairing', {}, 20_000) as Promise<PairingInfo>,
- transport.call('cloudStatus', {}, 20_000).catch(() => null) as Promise<CloudStatus | null>,
- transport.call('hello', {}, 20_000).catch(() => null) as Promise<{ name?: string } | null>,
- ])
- setInfo(pairing)
- setCloud(status)
- if (hello?.name) setName(hello.name)
- setQr(await QRCode.toDataURL(pairing.pairingUrl, { errorCorrectionLevel: 'M', margin: 0, width: 400, color: { dark: '#000000', light: '#ffffff' } }))
- setError(null)
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e))
- }
- }, [local])
+ const requestCode = useCallback(async () => {
+ if (!baseURL || !token) throw new Error("This computer's host isn't connected.")
+ const transport = new LoopbackTransport(baseURL, token)
+ const [pairing, status, hello] = await Promise.all([
+ transport.call('pairing', {}, 20_000) as Promise<PairingInfo>,
+ transport.call('cloudStatus', {}, 20_000).catch(() => null) as Promise<CloudStatus | null>,
+ transport.call('hello', {}, 20_000).catch(() => null) as Promise<{ name?: string } | null>,
+ ])
+ setCloudOn(status?.enabled === true)
+ if (hello?.name) setName(hello.name)
+ return pairing
+ }, [baseURL, token])
- // A new code each time "Pair iPhone…" is chosen (the window stays open between uses, so it's shown again)…
- useEffect(() => {
- void load()
- return window.codync.app.onCommand((c) => {
- if (c.kind !== 'reviewApprovals') return
- analytics.track({ event: 'screen_viewed', screen: 'pairing' })
- void load()
- })
- }, [load])
-
- // …and a fresh one when this code expires while it's on screen.
- useEffect(() => {
- if (!info?.expiresAt) return
- const timer = setTimeout(() => void load(), Math.max(1000, info.expiresAt - Date.now()))
- return () => clearTimeout(timer)
- }, [info?.expiresAt, load])
-
- return (
- <VStack align="center" gap={12} className="pairing">
- {info && qr ? (
- <>
- <div className="pairing-qr">
- <img src={qr} alt={`Pairing code for ${name}`} width={200} height={200} />
- </div>
- <Text as="div" size="caption" tone="secondary" className="pairing-note">
- Scan with the Codync app or the iPhone Camera. No Tailscale or open ports needed: your iPhone connects directly on the same Wi-Fi, and through the encrypted relay anywhere else.
- </Text>
- {cloud?.enabled !== true ? (
- <Text as="div" size="caption" tone="attention" className="pairing-note">
- {info.urls.length === 0
- ? 'No network address found and “Reach from anywhere” is off. Connect to Wi-Fi or turn it on.'
- : `“Reach from anywhere” is off, so the iPhone only reaches ${name} on the same network.`}
- </Text>
- ) : null}
- <HStack gap={4}>
- {info.expiresAt ? (
- <Text size="caption2" tone="tertiary">
- Works once, until {new Date(info.expiresAt).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}
- </Text>
- ) : null}
- <IconButton title="New code" icon="arrow.clockwise" onClick={() => void load()} />
- <IconButton title="Copy pairing link" icon="doc.on.doc" onClick={() => window.codync.app.copy(info.pairingUrl)} />
- </HStack>
- </>
- ) : error ? (
- <>
- <Text as="div" size="caption" tone="danger" className="pairing-note">{error}</Text>
- <IconButton title="Try again" icon="arrow.clockwise" onClick={() => void load()} />
- </>
- ) : (
- <Spinner size={20} />
- )}
- </VStack>
- )
+ return <PairingCode name={name} cloudOn={cloudOn} requestCode={requestCode} renew={shown} />
}
diff --git a/apps/desktop/src/renderer/views/pairing-window.css b/apps/desktop/src/renderer/views/pairing-code.css
similarity index 58%
rename from apps/desktop/src/renderer/views/pairing-window.css
rename to apps/desktop/src/renderer/views/pairing-code.css
index 23fbb9ef..5904827e 100644
--- a/apps/desktop/src/renderer/views/pairing-window.css
+++ b/apps/desktop/src/renderer/views/pairing-code.css
@@ -1,9 +1,8 @@
-/* The pairing QR window (PairingWindow). */
+/* PairingCode: the pairing window and the Computers page's pairing sheet. */
.pairing {
- width: 340px;
padding: 16px;
}
-/* White in both schemes, so cameras read the code (also the Computers page's pairing panel). */
+/* White in both schemes, so cameras read the code. */
.pairing-qr {
padding: 10px;
background: #fff;
diff --git a/apps/desktop/src/renderer/views/settings/AuthorizedDevicesSection.tsx b/apps/desktop/src/renderer/views/settings/AuthorizedDevicesSection.tsx
new file mode 100644
index 00000000..88e05579
--- /dev/null
+++ b/apps/desktop/src/renderer/views/settings/AuthorizedDevicesSection.tsx
@@ -0,0 +1,83 @@
+import { useCallback, useEffect, useState } from 'react'
+import type { AuthorizedDevice } from '@shared/models'
+import { CardSection, IconButton, Spinner } from '../../components/Controls'
+import { Icon } from '../../components/Icon'
+import { Dialog } from '../../components/Overlay'
+import { HStack, IconSlot, VStack } from '../../components/Stack'
+import { Text } from '../../components/Text'
+import { useModel } from '../../lib/observable'
+import type { BotStore } from '../../store/bot-store'
+import { deviceIcon, errorText, liveClient, relativeDay } from './parts'
+
+/** The devices that can use a computer this app manages, each one revocable. */
+export function AuthorizedDevicesSection({ store }: { store: BotStore }) {
+ useModel(store)
+ const [devices, setDevices] = useState<AuthorizedDevice[] | { error: string } | null>(null)
+ const [confirmRevoke, setConfirmRevoke] = useState<AuthorizedDevice | null>(null)
+ const online = store.connection.kind === 'online'
+ const name = store.hostName
+
+ const loadDevices = useCallback(async () => {
+ const client = liveClient(store)
+ if (!client) return
+ try {
+ setDevices((await client.call<{ devices: AuthorizedDevice[] }>('devices')).devices)
+ } catch (e) {
+ setDevices({ error: errorText(e) })
+ }
+ }, [store])
+
+ // Also when it changes account: the devices approved through the old one lose access.
+ useEffect(() => void loadDevices(), [loadDevices, online, store.accessRequests.length, store.cloud?.owner?.userId])
+
+ const revoke = async (device: AuthorizedDevice) => {
+ try {
+ await (await store.ready()).call('revokeDevice', { key: device.key })
+ } catch (e) {
+ store.setError(errorText(e))
+ }
+ await loadDevices()
+ }
+
+ return (
+ <>
+ <CardSection title={`Devices that can use ${name}`}>
+ {devices === null
+ ? [<Spinner key="loading" />]
+ : 'error' in devices
+ ? [<Text key="error" tone="danger" className="settings-appear">{devices.error}</Text>]
+ : [
+ ...(devices.length === 0
+ ? [<Text key="none" tone="secondary">None yet. Pair an iPhone, or approve one from your account.</Text>]
+ : []),
+ ...devices.map((device) => (
+ <HStack key={device.key} gap={8} className="settings-row settings-appear">
+ <IconSlot width={18} tone="secondary">
+ <Icon name={deviceIcon(device.platform)} size={13} />
+ </IconSlot>
+ <VStack grow className="settings-stack">
+ <span>{device.name}</span>
+ <Text size="caption" tone="tertiary">{deviceDetail(device)}</Text>
+ </VStack>
+ <IconButton title="Revoke access" icon="xmark.circle" onClick={() => setConfirmRevoke(device)} />
+ </HStack>
+ )),
+ ]}
+ </CardSection>
+ <Dialog
+ open={confirmRevoke !== null}
+ title={`Revoke ${confirmRevoke?.name ?? 'device'}?`}
+ message="It disconnects right away and has to pair or ask again."
+ actions={confirmRevoke ? [{ title: 'Revoke access', destructive: true, action: () => void revoke(confirmRevoke) }] : []}
+ onClose={() => setConfirmRevoke(null)}
+ />
+ </>
+ )
+}
+
+function deviceDetail(device: AuthorizedDevice) {
+ const parts = [device.source === 'account' ? 'Approved through the account' : 'Paired with a QR code']
+ if (device.connected) parts.push('connected')
+ else if (device.lastSeenAt) parts.push(`seen ${relativeDay(new Date(device.lastSeenAt))}`)
+ return parts.join(' · ')
+}
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index b3824223..8cfb8ff3 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -1,24 +1,23 @@
-import { useCallback, useEffect, useState } from 'react'
-import QRCode from 'qrcode'
-import type { AccountApproval, AuthorizedDevice, PairingInfo } from '@shared/models'
+import { useCallback, useState } from 'react'
+import type { AccountApproval, PairingInfo } from '@shared/models'
import { newSSHProfile, type SSHProfile } from '@shared/ssh'
-import { Button, CardSection, IconButton, Spinner, Switch } from '../../components/Controls'
+import { Button, CardSection, IconButton, Switch } from '../../components/Controls'
import { Icon } from '../../components/Icon'
import { Dialog, ModalHeader, Sheet, useDismiss } from '../../components/Overlay'
-import { HStack, IconSlot, Spacer, VStack } from '../../components/Stack'
+import { HStack, Spacer, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useModel } from '../../lib/observable'
import { useAccount } from '../../store/account'
import type { CloudComputer } from '../../store/cloud'
import type { BotStore } from '../../store/bot-store'
-import { useScreenViewed } from '../../store/analytics'
import { StoreContext, useApp } from '../../store/context'
import { ComputerBadge } from '../ComputerBadge'
-import { deviceIcon, errorText, liveClient, relativeDay, Reveal, SectionHeader, statusText, thisMac } from './parts'
+import { PairingCode } from '../PairingCode'
+import { AuthorizedDevicesSection } from './AuthorizedDevicesSection'
+import { errorText, liveClient, relativeDay, Reveal, SectionHeader, statusText, thisMac } from './parts'
import { useSSH } from './ssh-model'
import { SSHRow } from './SSHRow'
import { VoiceChatSettingsView } from './VoiceChatSettingsView'
-import '../pairing-window.css'
/**
* Computers this app manages (itself and SSH), with their account, relay and authorized devices;
@@ -33,8 +32,7 @@ export function ComputersView() {
const [removingCopy, setRemovingCopy] = useState<CloudComputer | null>(null)
const managed = app.managedStores
const managedIds = new Set(managed.map((s) => s.computer.id))
- const reached = app.computers.filter((c) => !managedIds.has(c.id))
- const others = cloud.computers.filter((c) => !managedIds.has(c.computerId) && !reached.some((r) => r.id === c.computerId))
+ const others = cloud.computers.filter((c) => !managedIds.has(c.computerId))
return (
<div className="settings-computers">
@@ -58,36 +56,14 @@ export function ComputersView() {
</div>
<div>
- <SectionHeader title="In your account">
+ <SectionHeader title="Other computers in your account">
{account.isSignedIn ? <IconButton title="Refresh" icon="arrow.clockwise" onClick={() => void cloud.refresh()} /> : null}
</SectionHeader>
{!account.isSignedIn ? (
- <Text as="div" size="callout" tone="secondary">Sign in to reach the other computers in your account from {thisMac}.</Text>
- ) : reached.length === 0 && others.length === 0 ? (
+ <Text as="div" size="callout" tone="secondary">Sign in to see the other computers in your account.</Text>
+ ) : others.length === 0 ? (
<Text as="div" size="callout" tone="secondary">No other computers in your account yet.</Text>
) : null}
- {reached.map((computer) => {
- const store = app.store(computer.id)
- if (!store) return null
- const cloudEntry = cloud.computers.find((c) => c.computerId === computer.id)
- const stale = !!cloudEntry && cloud.isOlderCopy(cloudEntry) && store.connection.kind !== 'unauthorized'
- return (
- <div key={computer.id} className="settings-card settings-appear">
- <div className="settings-row">
- <ComputerBadge computer={store.computer} size={22} />
- <div className="settings-stack">
- <Text size="callout" weight="medium">{store.hostName}</Text>
- <Text size="caption" tone={stale ? 'attention' : 'secondary'}>
- {stale ? `Older copy · ${statusText(store)}` : statusText(store)}
- </Text>
- </div>
- <RouteIcon store={store} />
- <Spacer />
- <IconButton title={`Remove from ${thisMac}`} icon="minus.circle" onClick={() => app.detach(computer.id)} />
- </div>
- </div>
- )
- })}
{others.map((computer) => (
<AccountComputerRow key={computer.computerId} computer={computer} olderCopy={cloud.isOlderCopy(computer)} onRemove={() => setRemovingCopy(computer)} />
))}
@@ -108,17 +84,6 @@ export function ComputersView() {
)
}
-/** How this app reaches a computer: direct LAN or the encrypted relay. */
-function RouteIcon({ store }: { store: BotStore }) {
- if (store.connection.kind !== 'online' || !store.hostRoute || store.hostRoute === 'loopback') return null
- const relay = store.hostRoute === 'relay'
- return (
- <HStack as="span" align="stretch" title={relay ? 'Through Cloudflare (encrypted)' : 'Direct: Wi-Fi or Tailscale'} aria-label={relay ? 'Through Cloudflare' : 'Wi-Fi or Tailscale'} className="settings-route">
- <Icon name={relay ? 'cloud' : 'wifi'} size={12} />
- </HStack>
- )
-}
-
const isMacLabel = thisMac === 'this Mac' ? 'This Mac' : 'This computer'
/** This computer or an SSH computer: relay, account membership, pairing and authorized devices. */
@@ -126,16 +91,17 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo
const app = useApp()
const account = useAccount()
useModel(store)
- const [devices, setDevices] = useState<AuthorizedDevice[] | null>(null)
const [busy, setBusy] = useState(false)
const [showPairing, setShowPairing] = useState(false)
const [showVoice, setShowVoice] = useState(false)
- const [confirmRevoke, setConfirmRevoke] = useState<AuthorizedDevice | null>(null)
const [confirmUnclaim, setConfirmUnclaim] = useState(false)
const [confirmAutoApproval, setConfirmAutoApproval] = useState(false)
const cloud = store.cloud
+ const owner = cloud?.owner ?? null
const autoApproval = cloud?.approval === 'auto'
const online = store.connection.kind === 'online'
+ // A host that needs an update doesn't give its cloud status: nothing there to show or change.
+ const manageable = online && !store.mismatch
const name = store.hostName
const run = (work: () => Promise<void>) => {
@@ -143,16 +109,6 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo
void work().finally(() => setBusy(false))
}
- const loadDevices = useCallback(async () => {
- const client = liveClient(store)
- if (!client) return
- try {
- setDevices((await client.call<{ devices: AuthorizedDevice[] }>('devices')).devices)
- } catch {}
- }, [store])
-
- useEffect(() => void loadDevices(), [loadDevices, online, store.accessRequests.length])
-
const setApproval = (approval: AccountApproval) =>
run(async () => {
try {
@@ -166,9 +122,8 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo
? 'Off: only Wi-Fi and Tailscale reach it, nothing goes through Cloudflare.'
: (cloud.lastError ?? (cloud.connected ? 'Reachable from anywhere through Cloudflare (encrypted).' : 'Connecting to Cloudflare…'))
- const owner = cloud?.owner ?? null
const accountLine = (
- <HStack gap={8} className="settings-row">
+ <HStack key="account" gap={8} className="settings-row settings-appear">
<Icon name={owner ? 'person.crop.circle.badge.checkmark' : 'person.crop.circle.badge.plus'} size={13} color="var(--secondary)" />
<Text size="callout" grow>
{owner
@@ -180,11 +135,11 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo
: 'Sign in to add it to your account'}
</Text>
{owner ? (
- <Button kind="secondary" onClick={() => setConfirmUnclaim(true)} disabled={busy || !online}>
+ <Button kind="secondary" onClick={() => setConfirmUnclaim(true)} disabled={busy || !manageable}>
Remove from account
</Button>
) : account.isSignedIn ? (
- <Button kind="secondary" onClick={() => run(async () => void (await app.cloud.claim(store)))} disabled={busy || !online}>
+ <Button kind="secondary" onClick={() => run(async () => void (await app.cloud.claim(store)))} disabled={busy || !manageable}>
{busy ? 'Adding…' : 'Add to account'}
</Button>
) : null}
@@ -209,19 +164,24 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo
) : null}
<IconButton title="Pair iPhone" icon="qrcode" selected={showPairing} disabled={!online} onClick={() => setShowPairing((s) => !s)} />
</div>,
- <Switch key="cloud" on={cloud?.enabled ?? false} disabled={busy || !online} onChange={(on) => run(() => app.cloud.setCloud(store, on))}>
- <span className="settings-stack">
- <span>Reach from anywhere</span>
- <Text size="caption" tone={cloud?.lastError ? 'attention' : 'secondary'}>{cloudLine}</Text>
- </span>
- </Switch>,
- accountLine,
+ // Until the host gives its cloud status, there's no way to tell its relay or account.
+ ...(cloud
+ ? [
+ <Switch key="cloud" className="settings-appear" on={cloud.enabled} disabled={busy || !manageable} onChange={(on) => run(() => app.cloud.setCloud(store, on))}>
+ <span className="settings-stack">
+ <span>Reach from anywhere</span>
+ <Text size="caption" tone={cloud.lastError ? 'attention' : 'secondary'}>{cloudLine}</Text>
+ </span>
+ </Switch>,
+ accountLine,
+ ]
+ : []),
...(owner
? [
<Switch
key="approval"
on={autoApproval}
- disabled={busy || !online}
+ disabled={busy || !manageable}
onChange={(on) => (on ? setConfirmAutoApproval(true) : setApproval('code'))}
>
<span className="settings-stack settings-appear">
@@ -236,27 +196,7 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo
]}
</CardSection>
- <CardSection title={`Devices that can use ${name}`}>
- {devices === null
- ? [<Spinner key="loading" />]
- : [
- ...(devices.length === 0
- ? [<Text key="none" tone="secondary">None yet. Pair an iPhone, or approve one from your account.</Text>]
- : []),
- ...devices.map((device) => (
- <HStack key={device.key} gap={8} className="settings-row settings-appear">
- <IconSlot width={18} tone="secondary">
- <Icon name={deviceIcon(device.platform)} size={13} />
- </IconSlot>
- <VStack grow className="settings-stack">
- <span>{device.name}</span>
- <Text size="caption" tone="tertiary">{deviceDetail(device)}</Text>
- </VStack>
- <IconButton title="Revoke access" icon="xmark.circle" onClick={() => setConfirmRevoke(device)} />
- </HStack>
- )),
- ]}
- </CardSection>
+ <AuthorizedDevicesSection store={store} />
<Sheet open={showVoice} onClose={() => setShowVoice(false)}>
<StoreContext.Provider value={store}>
@@ -267,29 +207,6 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo
<ModalHeader icon="qrcode" title={`Pair iPhone with ${name}`} />
<PairingPanel store={store} />
</Sheet>
- <Dialog
- open={confirmRevoke !== null}
- title={`Revoke ${confirmRevoke?.name ?? 'device'}?`}
- message="It disconnects right away and has to pair or ask again."
- actions={
- confirmRevoke
- ? [{
- title: 'Revoke access',
- destructive: true,
- action: () =>
- run(async () => {
- try {
- await (await store.ready()).call('revokeDevice', { key: confirmRevoke.key })
- } catch (e) {
- store.setError(errorText(e))
- }
- await loadDevices()
- }),
- }]
- : []
- }
- onClose={() => setConfirmRevoke(null)}
- />
<Dialog
open={confirmAutoApproval}
title="Let account devices in without a code?"
@@ -333,81 +250,17 @@ function accountComputerStatus(computer: CloudComputer, olderCopy: boolean) {
return computer.lastSeenAt ? `Older copy · last seen ${relativeDay(new Date(computer.lastSeenAt))}` : 'Older copy'
}
-function deviceDetail(device: AuthorizedDevice) {
- const parts = [device.source === 'account' ? 'Approved through the account' : 'Paired with a QR code']
- if (device.connected) parts.push('connected')
- else if (device.lastSeenAt) parts.push(`seen ${relativeDay(new Date(device.lastSeenAt))}`)
- return parts.join(' · ')
-}
-
-/** A one-time pairing QR (v3) from a computer this app manages: its keys, a code, and how to reach it. */
+/** "Pair iPhone" for a computer this app manages, through its store. */
function PairingPanel({ store }: { store: BotStore }) {
useModel(store)
- useScreenViewed('pairing')
- const [info, setInfo] = useState<PairingInfo | null>(null)
- const [qr, setQr] = useState<string | null>(null)
- const [error, setError] = useState<string | null>(null)
- const name = store.hostName
-
- const load = useCallback(async () => {
+ const requestCode = useCallback(async () => {
const client = liveClient(store)
- if (!client) return setError(`${store.hostName} isn't connected.`)
- try {
- const pairing = await client.call<PairingInfo>('pairing')
- setQr(await QRCode.toDataURL(pairing.pairingUrl, { errorCorrectionLevel: 'M', margin: 0, width: 400, color: { dark: '#000000', light: '#ffffff' } }))
- setInfo(pairing)
- setError(null)
- } catch (e) {
- setError(errorText(e))
- }
+ if (!client) throw new Error(`${store.hostName} isn't connected.`)
+ return client.call<PairingInfo>('pairing')
}, [store])
-
- useEffect(() => void load(), [load])
- // A fresh code when this one expires while it's on screen.
- useEffect(() => {
- if (!info?.expiresAt) return
- const timer = setTimeout(() => void load(), Math.max(1000, info.expiresAt - Date.now()))
- return () => clearTimeout(timer)
- }, [info?.expiresAt, load])
-
- return (
- <VStack align="center" gap={12} className="settings-pairing">
- {info && qr ? (
- <>
- <div className="pairing-qr settings-appear">
- <img src={qr} alt={`Pairing code for ${name}`} width={200} height={200} />
- </div>
- <Text as="div" size="caption" tone="secondary" className="settings-centered">
- Scan with the Codync app or the iPhone Camera. No Tailscale or open ports needed: your iPhone connects directly on the same Wi-Fi, and through the encrypted relay anywhere else.
- </Text>
- {store.cloud?.enabled !== true ? (
- <Text as="div" size="caption" tone="attention" className="settings-centered">
- {info.urls.length === 0
- ? 'No network address found and “Reach from anywhere” is off. Connect to Wi-Fi or turn it on.'
- : `“Reach from anywhere” is off, so the iPhone only reaches ${name} on the same network.`}
- </Text>
- ) : null}
- <HStack gap={4}>
- {info.expiresAt ? (
- <Text size="caption2" tone="tertiary">
- Works once, until {new Date(info.expiresAt).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}
- </Text>
- ) : null}
- <IconButton title="New code" icon="arrow.clockwise" onClick={() => void load()} />
- <IconButton title="Copy pairing link" icon="doc.on.doc" onClick={() => window.codync.app.copy(info.pairingUrl)} />
- </HStack>
- </>
- ) : error ? (
- <>
- <Text as="div" size="caption" tone="danger" className="settings-centered">{error}</Text>
- <IconButton title="Try again" icon="arrow.clockwise" onClick={() => void load()} />
- </>
- ) : (
- <Spinner size={20} />
- )}
- </VStack>
- )
+ return <PairingCode name={store.hostName} cloudOn={store.cloud?.enabled === true} requestCode={requestCode} />
}
+
// MARK: SSH
/** Add or change an SSH computer. Only fields ssh takes as separate arguments; nothing goes through a shell. */
diff --git a/apps/desktop/src/renderer/views/settings/settings.css b/apps/desktop/src/renderer/views/settings/settings.css
index 6cabd82e..f782e367 100644
--- a/apps/desktop/src/renderer/views/settings/settings.css
+++ b/apps/desktop/src/renderer/views/settings/settings.css
@@ -163,12 +163,6 @@
.settings-computers-content {
padding: 14px 14px 20px;
}
-.settings-route {
- color: var(--tertiary);
-}
-.settings-pairing {
- padding: 16px;
-}
.settings-ssh-editor {
width: 460px;
}
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index e92476dc..6974d5a6 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -309,6 +309,16 @@ final class AppStore {
accounts.lastError = error.localizedDescription
}
}
+
+ /// Forgets a computer here. Approved through the account, its grant goes too, or it would come
+ /// straight back as an account row; a failed revoke (offline) still forgets it, and its error says
+ /// why the grant stayed.
+ func removeComputer(_ id: ComputerID) async {
+ let accounts = accounts
+ if accounts.cloudComputers.first(where: { $0.computerId == id })?.isGranted == true { await revokeAccess(id) }
+ // A revoke that went through forgot it already.
+ if accounts.computers.contains(where: { $0.id == id }) { accounts.forget(id) }
+ }
}
final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Connection.swift b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Connection.swift
index 3dcddd3f..5052fada 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Connection.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Connection.swift
@@ -206,8 +206,9 @@ extension ChannelTransport {
case "unauthorized", "revoked":
return .stop(.unauthorized(message ?? "This device isn't allowed on that computer anymore."))
case "leaseExpired":
- // The computer couldn't confirm the account's approval lately; it may again.
- return .wait(.unauthorized(message ?? "Your computer couldn't confirm this device's access. Retrying."))
+ // The computer couldn't confirm the account's approval lately; it may again, so this
+ // isn't a refusal: the channel keeps retrying.
+ return .wait(.failed(message ?? "Your computer couldn't confirm this device's access. Retrying."))
case "unsupportedVersion":
return .stop(.failed(HostError.upgradeRequired.localizedDescription))
case "pairingClosed":
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swift
index b8898820..19d88f4c 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swift
@@ -15,9 +15,10 @@ public enum LinkState: Sendable, Equatable {
case ready(HostRoute)
/// The relay says the computer isn't connected (asleep, off): the mailbox still works.
case hostOffline(lastSeen: Date?)
- /// Revoked, lease expired, or the computer's identity changed: retrying won't help.
+ /// Revoked, or the computer's identity changed: retrying won't help.
case unauthorized(String)
- /// Can't reach the computer at all (neither directly nor through the relay).
+ /// Can't reach the computer at all (neither directly nor through the relay), or it can't confirm
+ /// this device's access for now.
case failed(String)
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swift
index f13f0dbb..49115200 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swift
@@ -21,6 +21,8 @@ public struct CloudComputer: Codable, Hashable, Sendable, Identifiable {
public var id: ComputerID { computerId }
public var isOnline: Bool { online ?? false }
+ /// This device was approved on it through the account.
+ public var isGranted: Bool { access == "granted" }
}
/// A started access request, after both nonces were exchanged: `code` is ready to show.
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
index ee67960e..36a0fdc1 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -48,6 +48,11 @@ public final class AccountStore {
/// Persisted in the context (channel route).
private var saved: [Computer]
private var accessPolls: [ComputerID: Task<Void, Never>] = [:]
+ /// Bumped by each account list request and each local change to the list: a list that comes back
+ /// after a newer one was asked for (or the list changed here) is out of date.
+ private var cloudListVersion = 0
+ /// Computers being taken out of the account: a list that comes back meanwhile leaves them out.
+ private var removing: Set<ComputerID> = []
/// Access requests still waiting for their code, joined by a second ask.
private var asks: [ComputerID: Task<AccessTicket, any Error>] = [:]
private var isActive = true
@@ -92,7 +97,11 @@ public final class AccountStore {
let identity = try DeviceIdentity.load(context: storage)
var computer = try await HostConnector.pair(pairing, identity: identity, deviceName: deviceName, platform: platform)
guard !retired else { throw CancellationError() }
- computer.color = saved.first { $0.id == computer.id }?.color
+ // Picked on this device: re-pairing keeps them.
+ if let previous = saved.first(where: { $0.id == computer.id }) {
+ computer.color = previous.color
+ computer.route = previous.route
+ }
save(computer)
open(computer)
return computer
@@ -138,9 +147,11 @@ public final class AccountStore {
public func refreshCloud() async {
guard let cloud, !retired else { return }
+ cloudListVersion += 1
+ let version = cloudListVersion
do {
- let list = try await cloud.computers()
- guard !retired else { return }
+ let list = try await cloud.computers().filter { !removing.contains($0.computerId) }
+ guard !retired, version == cloudListVersion else { return }
if list != cloudComputers { Motion.animate { cloudComputers = list } }
} catch let error as CloudError where !error.isTransient {
lastError = error.localizedDescription
@@ -196,22 +207,19 @@ public final class AccountStore {
/// Seen after that one joined the account, it ran beside it: another machine with the same name.
public func isOlderCopy(_ computer: CloudComputer) -> Bool {
guard !computer.isOnline else { return false }
- func replaced(by id: ComputerID) -> Bool {
- guard let seen = computer.lastSeenAt,
- let claimed = cloudComputers.first(where: { $0.computerId == id })?.claimedAt else { return true }
- return seen <= claimed
- }
+ let seen = computer.lastSeenAt
// The current copy may be QR-paired without being listed in the account.
- return computers.contains { $0.id != computer.computerId && $0.name == computer.name && replaced(by: $0.id) }
+ return computers.contains { $0.id != computer.computerId && $0.name == computer.name && replaced(lastSeen: seen, by: $0.id) }
|| cloudComputers.contains { other in
other.computerId != computer.computerId && other.name == computer.name
- && (stores[other.computerId] != nil || other.isOnline) && replaced(by: other.computerId)
+ && (stores[other.computerId] != nil || other.isOnline) && replaced(lastSeen: seen, by: other.computerId)
}
}
/// A computer this device uses that won't come back as it is: it turned this device away (access
/// revoked, or its identity changed after a reset or reinstall), or it's offline while a computer
- /// with its name is reachable, the same machine under a new identity. Removing it is the fix.
+ /// with its name is reachable that joined the account after it was last seen, the same machine
+ /// under a new identity. Removing it is the fix.
public func isStale(_ id: ComputerID) -> Bool {
guard let store = stores[id] else { return false }
switch store.connection {
@@ -219,13 +227,31 @@ public final class AccountStore {
return true
case .computerOffline, .offline:
let name = store.computer.name
- return stores.values.contains { $0.computer.id != id && $0.computer.name == name && $0.connection == .online }
- || cloudComputers.contains { $0.computerId != id && $0.name == name && $0.isOnline }
+ let seen = lastSeen(store)
+ return stores.values.contains {
+ $0.computer.id != id && $0.computer.name == name && $0.connection == .online && replaced(lastSeen: seen, by: $0.computer.id)
+ } || cloudComputers.contains {
+ $0.computerId != id && $0.name == name && $0.isOnline && replaced(lastSeen: seen, by: $0.computerId)
+ }
default:
return false
}
}
+ /// A same-named computer last seen (epoch ms) before `id` joined the account was replaced by it;
+ /// seen after, it ran beside it: another machine. Without either time, the name alone decides.
+ private func replaced(lastSeen seen: Int64?, by id: ComputerID) -> Bool {
+ guard let seen, let claimed = cloudComputers.first(where: { $0.computerId == id })?.claimedAt else { return true }
+ return seen <= claimed
+ }
+
+ /// When the account or, for a computer only paired here, the relay last saw it.
+ private func lastSeen(_ store: BotStore) -> Int64? {
+ if let seen = cloudComputers.first(where: { $0.computerId == store.computer.id })?.lastSeenAt { return seen }
+ guard case let .computerOffline(date?) = store.connection else { return nil }
+ return Int64(date.timeIntervalSince1970 * 1000)
+ }
+
/// Access requests appear and settle with an animation, like connection changes.
private func setPending(_ id: ComputerID, _ ticket: AccessTicket?) {
guard pendingAccess[id] != ticket else { return }
@@ -233,15 +259,25 @@ public final class AccountStore {
}
/// Takes a computer out of the account (its grants and pending requests go with it).
+ /// Its row goes at once, so a second tap finds nothing to remove; no list brings it back while the
+ /// removal runs, nor one asked for before it finished. A failed removal puts it back.
public func removeFromAccount(_ id: ComputerID) async {
- guard let cloud else { return }
+ guard let cloud, let index = cloudComputers.firstIndex(where: { $0.computerId == id }) else { return }
+ let removed = cloudComputers[index]
+ removing.insert(id)
+ Motion.animate { _ = cloudComputers.remove(at: index) }
do {
try await cloud.removeComputer(id)
setPending(id, nil)
- await refreshCloud()
} catch {
lastError = error.localizedDescription
+ if !cloudComputers.contains(where: { $0.computerId == id }) {
+ Motion.animate { cloudComputers.insert(removed, at: min(index, cloudComputers.count)) }
+ }
}
+ removing.remove(id)
+ cloudListVersion += 1
+ await refreshCloud()
}
/// Withdraws a pending access request; the computer drops it from its approval list.
@@ -284,7 +320,13 @@ public final class AccountStore {
default: .cancelled
}
Analytics.shared.capture(.accessRequestFailed(reason))
- lastError = status.status == .denied ? "\(target.name) declined the request." : "The request expired. Ask again."
+ lastError = switch reason {
+ case .denied: "\(target.name) declined the request."
+ case .expired: "The request expired. Ask again."
+ case .cancelled: "The request was withdrawn: \(target.name) or this iPhone was removed from your account."
+ }
+ // Withdrawn by the account: the list shows what's left of it.
+ if reason == .cancelled { await refreshCloud() }
return
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
index 8cc7cd1a..317b6ecb 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
@@ -79,7 +79,7 @@ extension BotStore {
var transport: any HostTransport
while true {
do {
- transport = try await makeTransport()
+ transport = try await makeTransport(computer)
break
} catch HostError.unauthorized(let message) {
if !Task.isCancelled, !retired { setConnection(.unauthorized(message)) }
@@ -185,11 +185,12 @@ extension BotStore {
Task { [weak self] in
for await computer in updates {
guard let self, !self.retired else { return }
- // The color is picked on this device; the transport's copy may be older.
+ // The color and route are picked on this device; the transport's copy may be older.
self.updateComputer { current in
- let color = current.color
+ let (color, route) = (current.color, current.route)
current = computer
current.color = color
+ current.route = route
}
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
index 3e09d16b..5c7f93c0 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
@@ -27,9 +27,10 @@ public final class BotStore {
case online
/// The relay says the computer isn't connected; messages can wait in its mailbox.
case computerOffline(lastSeen: Date?)
- /// Can't reach the computer at all (no direct route, no relay).
+ /// Can't reach the computer at all (no direct route, no relay), or it can't confirm this
+ /// device's access for now.
case offline(String)
- /// Revoked, lease expired, or the computer's identity changed.
+ /// Revoked, or the computer's identity changed.
case unauthorized(String)
}
@@ -91,7 +92,8 @@ public final class BotStore {
var onComputerChanged: (@MainActor (Computer) -> Void)?
public let storage: SharedStore.Context
- let makeTransport: @MainActor () async throws -> any HostTransport
+ /// Opens a channel to the computer as it is now: its route, and the addresses and keys merged since.
+ let makeTransport: @MainActor (Computer) async throws -> any HostTransport
var transport: (any HostTransport)?
var retired = false
/// Files of messages not delivered yet (by client nonce), kept for a retry.
@@ -131,14 +133,14 @@ public final class BotStore {
/// Loads this context's `DeviceIdentity` itself.
public convenience init(computer: Computer, storage: SharedStore.Context) {
- self.init(computer: computer, storage: storage) {
- try await HostConnector.connect(computer, identity: try DeviceIdentity.load(context: storage))
+ self.init(computer: computer, storage: storage) { current in
+ try await HostConnector.connect(current, identity: try DeviceIdentity.load(context: storage))
}
}
init(computer: Computer, storage: SharedStore.Context,
appVersion: String = AppVersion.current,
- transport: @escaping @MainActor () async throws -> any HostTransport) {
+ transport: @escaping @MainActor (Computer) async throws -> any HostTransport) {
self.appVersion = appVersion
self.computer = computer
self.storage = storage
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift
index 391d59e7..59176426 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift
@@ -382,3 +382,10 @@ private func waitFor(_ states: AsyncStream<LinkState>, _ match: (LinkState) -> B
#expect(await waitFor(t.states()) { if case .failed = $0 { true } else { false } } == .failed("Paired."))
await t.shutdown()
}
+
+@Test func lapsedLeaseIsRetriedNotARevocation() throws {
+ let reject = { (code: String) in ChannelTransport.rejection(try ChannelTransport.decodeWire(#"{"t":"reject","code":"\#(code)"}"#)) }
+ // The computer couldn't confirm the account's approval lately: the channel keeps trying.
+ guard case .wait(.failed) = try reject("leaseExpired") else { Issue.record("expected a retrying failure"); return }
+ guard case .stop(.unauthorized) = try reject("revoked") else { Issue.record("expected a revocation"); return }
+}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/BotDeletionSyncTests.swift b/apps/ios/Kit/Tests/CodyncUITests/BotDeletionSyncTests.swift
index 4c7965f1..2d079381 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/BotDeletionSyncTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/BotDeletionSyncTests.swift
@@ -10,7 +10,7 @@ import Testing
let computer = Computer(id: UUID().uuidString, name: "Mac", signKey: "test")
let fake = FakeRemote(.ready(.direct))
await fake.setHello(#"{"hostId":"h1","name":"Mac","version":"\#(VersionMismatch.minHost)","os":"macos","backends":[],"rev":10}"#)
- let store = BotStore(computer: computer, storage: storage) { fake }
+ let store = BotStore(computer: computer, storage: storage) { _ in fake }
defer { store.retire() }
let bot = try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"gone","name":"Deleted while offline","rev":9}"#.utf8))
let entry = try JSONDecoder().decode(Entry.self, from: Data(#"{"id":"e1","botId":"gone","seq":1,"rev":8,"kind":"user","turn":1,"data":{"text":"cached"},"createdAt":1,"updatedAt":1}"#.utf8))
@@ -41,7 +41,7 @@ import Testing
#expect(store.selection == nil)
#expect(store.composerDraft(for: bot.id).isEmpty)
store.saveCache()
- let restored = BotStore(computer: computer, storage: storage) { fake }
+ let restored = BotStore(computer: computer, storage: storage) { _ in fake }
defer { restored.retire() }
#expect(restored.bots[bot.id] == nil)
#expect(restored.chat(bot.id).isEmpty)
diff --git a/apps/ios/Kit/Tests/CodyncUITests/ComputerAccessIsolationTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ComputerAccessIsolationTests.swift
index 37df4004..1c3fef95 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/ComputerAccessIsolationTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/ComputerAccessIsolationTests.swift
@@ -26,7 +26,7 @@ func phoneRosterUsesItsOwnPairingsNotUnavailableOrderEntries(hasIndependentAcces
let bot = try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"same-bot-id","name":"Local bot","rev":1}"#.utf8))
let accounts = AccountStore(storage: storage, cloud: nil) { computer in
opened.append(computer.id)
- let store = BotStore(computer: computer, storage: storage) { FakeRemote(.connecting) }
+ let store = BotStore(computer: computer, storage: storage) { _ in FakeRemote(.connecting) }
store.bots[bot.id] = bot
return store
}
@@ -51,7 +51,7 @@ func phoneRosterUsesItsOwnPairingsNotUnavailableOrderEntries(hasIndependentAcces
storage.computers = [a, b]
storage.computerOrder = ComputerOrder(ids: [b.id, a.id])
let accounts = AccountStore(storage: storage, cloud: nil) { computer in
- BotStore(computer: computer, storage: storage) { FakeRemote(.connecting) }
+ BotStore(computer: computer, storage: storage) { _ in FakeRemote(.connecting) }
}
defer { accounts.retire() }
accounts.setActive(false)
diff --git a/apps/ios/Kit/Tests/CodyncUITests/FileDownloadTests.swift b/apps/ios/Kit/Tests/CodyncUITests/FileDownloadTests.swift
index 28fbae21..4b053899 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/FileDownloadTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/FileDownloadTests.swift
@@ -40,7 +40,7 @@ private actor DelayedFileTransport: HostTransport {
guard let directory = ProcessInfo.processInfo.environment["CODYNC_RENDER_DIR"] else { return }
let suite = "CodyncFileCardRender.\(UUID().uuidString)"
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
- let store = BotStore(computer: Computer(id: "render", name: "Computer", signKey: "", boxKey: "", cloud: nil), storage: SharedStore.Context(accountID: "render", suite: suite)) { FakeRemote(.connecting) }
+ let store = BotStore(computer: Computer(id: "render", name: "Computer", signKey: "", boxKey: "", cloud: nil), storage: SharedStore.Context(accountID: "render", suite: suite)) { _ in FakeRemote(.connecting) }
defer { store.retire() }
func entry(_ name: String, size: Int64) -> Entry {
var data = EntryData(text: "\(name) (\(size) bytes)")
diff --git a/apps/ios/Kit/Tests/CodyncUITests/HistoryPagingTests.swift b/apps/ios/Kit/Tests/CodyncUITests/HistoryPagingTests.swift
index f8ee0664..04d5cfd3 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/HistoryPagingTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/HistoryPagingTests.swift
@@ -8,7 +8,7 @@ import Testing
let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let computer = Computer(id: "history", name: "Test", signKey: "")
- let store = BotStore(computer: computer, storage: storage) { throw HostError.unreachable }
+ let store = BotStore(computer: computer, storage: storage) { _ in throw HostError.unreachable }
defer { store.retire() }
store.entries["b"] = (0..<200).map { index in
Entry(id: "e\(index)", seq: Int64(index + 100), botId: "b", rev: 1, kind: "notice", turn: 0, data: EntryData(),
@@ -24,7 +24,7 @@ import Testing
let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let computer = Computer(id: "history", name: "Test", signKey: "")
- let store = BotStore(computer: computer, storage: storage) { throw HostError.unreachable }
+ let store = BotStore(computer: computer, storage: storage) { _ in throw HostError.unreachable }
defer { store.retire() }
#expect(!store.canLoadOlder("b"))
store.entries["b"] = [Entry(id: "local-draft", seq: Int64.max, botId: "b", rev: 1, kind: "user", turn: 0,
diff --git a/apps/ios/Kit/Tests/CodyncUITests/OlderCopyTests.swift b/apps/ios/Kit/Tests/CodyncUITests/OlderCopyTests.swift
index 66ca29f0..f7e4b500 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/OlderCopyTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/OlderCopyTests.swift
@@ -4,20 +4,18 @@ import Testing
@testable import CodyncKit
@testable import CodyncUI
-/// The account lists an offline "Desk" last seen at 200 and an online "Desk" claimed at `claimedAt`.
-private final class OlderCopyCloudStub: URLProtocol {
- static let claimedAt = OSAllocatedUnfairLock(initialState: 0)
+/// Answers `/v1/computers` with the subclass's `computers(for:)` and every other request with `{}`.
+private class CloudStub: URLProtocol {
+ /// The listed computers' JSON objects, comma-separated; asked for every request.
+ class func computers(for request: URLRequest) -> String { "" }
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func stopLoading() {}
override func startLoading() {
- let claimed = Self.claimedAt.withLock { $0 }
- let json = request.url?.path.hasSuffix("/v1/computers") == true
- ? #"{"computers":[{"computerId":"old","name":"Desk","signKey":"a","online":false,"lastSeenAt":200},"#
- + #"{"computerId":"new","name":"Desk","signKey":"b","online":true,"claimedAt":\#(claimed)}]}"#
- : "{}"
+ let computers = Self.computers(for: request)
+ let json = request.url?.path.hasSuffix("/v1/computers") == true ? #"{"computers":[\#(computers)]}"# : "{}"
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: Data(json.utf8))
@@ -25,16 +23,30 @@ private final class OlderCopyCloudStub: URLProtocol {
}
}
+/// A cloud client whose requests `stub` answers.
+private func stubbedCloud(_ stub: CloudStub.Type, token: @escaping @Sendable () async throws -> String = { "token" }) -> CloudClient {
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [stub]
+ return CloudClient(baseURL: URL(string: "https://cloud.test")!, identity: DeviceIdentity(signing: .init(), push: .init()),
+ session: URLSession(configuration: config), token: token)
+}
+
+/// The account lists an offline "Desk" last seen at 200 and an online "Desk" claimed at `claimedAt`.
+private final class OlderCopyCloudStub: CloudStub {
+ static let claimedAt = OSAllocatedUnfairLock(initialState: 0)
+
+ override class func computers(for request: URLRequest) -> String {
+ #"{"computerId":"old","name":"Desk","signKey":"a","online":false,"lastSeenAt":200},"#
+ + #"{"computerId":"new","name":"Desk","signKey":"b","online":true,"claimedAt":\#(claimedAt.withLock { $0 })}"#
+ }
+}
+
/// A same-named offline computer is an older copy only if it was last seen before the online one
/// joined the account; seen after, it ran beside it and is another machine.
@MainActor @Test func olderCopyNeedsToBeLastSeenBeforeTheCurrentOneJoined() async throws {
let suite = "OlderCopy.\(UUID().uuidString)"
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
- let config = URLSessionConfiguration.ephemeral
- config.protocolClasses = [OlderCopyCloudStub.self]
- let cloud = CloudClient(baseURL: URL(string: "https://cloud.test")!, identity: DeviceIdentity(signing: .init(), push: .init()),
- session: URLSession(configuration: config)) { "token" }
- let accounts = AccountStore(storage: SharedStore.Context(accountID: "account", suite: suite), cloud: cloud)
+ let accounts = AccountStore(storage: SharedStore.Context(accountID: "account", suite: suite), cloud: stubbedCloud(OlderCopyCloudStub.self))
defer { accounts.retire() }
OlderCopyCloudStub.claimedAt.withLock { $0 = 100 }
@@ -46,3 +58,109 @@ private final class OlderCopyCloudStub: URLProtocol {
await accounts.refreshCloud()
#expect(accounts.isOlderCopy(old))
}
+
+private let currentKey = Data(repeating: 5, count: 32)
+
+/// The account lists only the online "Desk", claimed at `claimedAt`.
+private final class StaleCopyCloudStub: CloudStub {
+ static let claimedAt = OSAllocatedUnfairLock(initialState: 0)
+
+ override class func computers(for request: URLRequest) -> String {
+ #"{"computerId":"\#(RelayCrypto.computerId(signKey: currentKey))","name":"Desk","signKey":"\#(currentKey.base64URL)","online":true,"claimedAt":\#(claimedAt.withLock { $0 })}"#
+ }
+}
+
+/// A computer paired here and gone offline is stale beside an online one with its name only if the relay
+/// last saw it before that one joined the account; seen after, it's another machine still to come back.
+@MainActor @Test func offlineComputerIsStaleOnlyIfLastSeenBeforeTheCurrentOneJoined() async throws {
+ let suite = "StaleCopy.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let storage = SharedStore.Context(accountID: "account", suite: suite)
+ let oldKey = Data(repeating: 4, count: 32)
+ let old = Computer(id: RelayCrypto.computerId(signKey: oldKey), name: "Desk", signKey: oldKey.base64URL)
+ storage.computers = [old]
+ let accounts = AccountStore(storage: storage, cloud: stubbedCloud(StaleCopyCloudStub.self)) { computer in
+ BotStore(computer: computer, storage: storage) { _ in FakeRemote(.connecting) }
+ }
+ defer { accounts.retire() }
+ accounts.setActive(false)
+ let store = try #require(accounts.store(for: old.id))
+ store.connection = .computerOffline(lastSeen: Date(milliseconds: 200))
+
+ StaleCopyCloudStub.claimedAt.withLock { $0 = 100 }
+ await accounts.refreshCloud()
+ #expect(!accounts.isStale(old.id))
+
+ StaleCopyCloudStub.claimedAt.withLock { $0 = 300 }
+ await accounts.refreshCloud()
+ #expect(accounts.isStale(old.id))
+}
+
+private let olderKey = Data(repeating: 6, count: 32)
+
+/// The account lists the older "Desk" beside the current one until a DELETE removes it. A list asked
+/// for with the `stale` token is the one from before the removal.
+private final class RemoveCopyCloudStub: CloudStub {
+ static let state = OSAllocatedUnfairLock(initialState: (removed: false, deletes: 0))
+
+ override class func computers(for request: URLRequest) -> String {
+ let removed = request.httpMethod == "DELETE"
+ ? state.withLock { $0.removed = true; $0.deletes += 1; return true }
+ : state.withLock { $0.removed } && request.value(forHTTPHeaderField: "Authorization") != "Bearer stale"
+ let older = #"{"computerId":"\#(RelayCrypto.computerId(signKey: olderKey))","name":"Desk","signKey":"\#(olderKey.base64URL)","online":false,"lastSeenAt":200}"#
+ let current = #"{"computerId":"\#(RelayCrypto.computerId(signKey: currentKey))","name":"Desk","signKey":"\#(currentKey.base64URL)","online":true,"claimedAt":300}"#
+ return removed ? current : "\(older),\(current)"
+ }
+}
+
+/// Removing an older copy takes its row away at once: a second tap sends no second DELETE, and a list
+/// asked for before the removal that arrives after it doesn't bring the row back.
+@MainActor @Test func removedOlderCopyIsRemovedOnceAndStaysGone() async throws {
+ let suite = "RemoveCopy.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ // The second token (the refresh asked for before the removal) comes late, and gets the earlier list.
+ let tokens = OSAllocatedUnfairLock(initialState: 0)
+ let cloud = stubbedCloud(RemoveCopyCloudStub.self) {
+ guard tokens.withLock({ $0 += 1; return $0 }) == 2 else { return "token" }
+ try await Task.sleep(for: .milliseconds(300))
+ return "stale"
+ }
+ let accounts = AccountStore(storage: SharedStore.Context(accountID: "account", suite: suite), cloud: cloud)
+ defer { accounts.retire() }
+ await accounts.refreshCloud()
+ let older = RelayCrypto.computerId(signKey: olderKey), current = RelayCrypto.computerId(signKey: currentKey)
+ #expect(accounts.cloudComputers.map(\.computerId) == [older, current])
+
+ let earlier = Task { await accounts.refreshCloud() }
+ for _ in 0..<100 where tokens.withLock({ $0 }) < 2 { try await Task.sleep(for: .milliseconds(10)) }
+ async let tap: Void = accounts.removeFromAccount(older)
+ async let secondTap: Void = accounts.removeFromAccount(older)
+ _ = await (tap, secondTap)
+ await earlier.value
+
+ #expect(RemoveCopyCloudStub.state.withLock { $0.deletes } == 1)
+ #expect(accounts.cloudComputers.map(\.computerId) == [current])
+}
+
+/// A list that comes back while the removal is still on its way leaves the older copy out, so its row
+/// can't come back to be tapped again.
+@MainActor @Test func listDuringRemovalLeavesTheOlderCopyOut() async throws {
+ let suite = "RemovingCopy.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ // The second request, the DELETE, is slow; the account keeps listing both copies meanwhile.
+ let tokens = OSAllocatedUnfairLock(initialState: 0)
+ let cloud = stubbedCloud(OlderCopyCloudStub.self) {
+ if tokens.withLock({ $0 += 1; return $0 }) == 2 { try await Task.sleep(for: .milliseconds(300)) }
+ return "token"
+ }
+ let accounts = AccountStore(storage: SharedStore.Context(accountID: "account", suite: suite), cloud: cloud)
+ defer { accounts.retire() }
+ await accounts.refreshCloud()
+ #expect(accounts.cloudComputers.map(\.computerId) == ["old", "new"])
+
+ let removal = Task { await accounts.removeFromAccount("old") }
+ for _ in 0..<100 where tokens.withLock({ $0 }) < 2 { try await Task.sleep(for: .milliseconds(10)) }
+ await accounts.refreshCloud()
+ #expect(accounts.cloudComputers.map(\.computerId) == ["new"])
+ await removal.value
+}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/ReplyTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ReplyTests.swift
index 4ce85824..707d647e 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/ReplyTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/ReplyTests.swift
@@ -32,7 +32,7 @@ private func message(_ id: String, kind: String, final: Bool? = nil, text: Strin
let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: Computer(id: "reply", name: "Mac", signKey: ""), storage: storage) { fake }
+ let store = BotStore(computer: Computer(id: "reply", name: "Mac", signKey: ""), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await eventually { await fake.subscribed })
diff --git a/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift
index f1afcb63..2f01fcf9 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift
@@ -7,7 +7,7 @@ import Testing
let suite = "RosterOrderTests.\(UUID().uuidString)"
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)
- let store = BotStore(computer: Computer(id: UUID().uuidString, name: "Mac", signKey: "test"), storage: storage) {
+ let store = BotStore(computer: Computer(id: UUID().uuidString, name: "Mac", signKey: "test"), storage: storage) { _ in
FakeRemote(.connecting)
}
defer { store.retire() }
diff --git a/apps/ios/Kit/Tests/CodyncUITests/RouteChangeTests.swift b/apps/ios/Kit/Tests/CodyncUITests/RouteChangeTests.swift
new file mode 100644
index 00000000..a02c7402
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/RouteChangeTests.swift
@@ -0,0 +1,28 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+@testable import CodyncUI
+
+/// A route picked in Settings takes effect on the next channel: each connect gets the computer as it
+/// is now, not as it was when its store opened.
+@MainActor @Test func newRouteReachesTheNextChannel() async throws {
+ let suite = "RouteChange.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let storage = SharedStore.Context(accountID: "account", suite: suite)
+ let key = Data(repeating: 3, count: 32)
+ let computer = Computer(id: RelayCrypto.computerId(signKey: key), name: "Desk", signKey: key.base64URL)
+ storage.computers = [computer]
+ var routes: [ConnectionRoute?] = []
+ let accounts = AccountStore(storage: storage, cloud: nil) { computer in
+ BotStore(computer: computer, storage: storage) { current in
+ routes.append(current.route)
+ return FakeRemote(.connecting)
+ }
+ }
+ defer { accounts.retire() }
+ for _ in 0..<100 where routes.isEmpty { try await Task.sleep(for: .milliseconds(10)) }
+
+ accounts.setRoute(computer.id, .directOnly)
+ for _ in 0..<100 where routes.count < 2 { try await Task.sleep(for: .milliseconds(10)) }
+ #expect(routes == [nil, .directOnly])
+}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
index cba4870f..e65bd3ca 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
@@ -151,7 +151,7 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -189,7 +189,7 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.relay))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -210,7 +210,7 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
store.setActive(true)
#expect(await until { await fake.subscribed })
await fake.emit(botEvent("b1", name: "Bot", rev: 1))
@@ -232,7 +232,7 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.hostOffline(lastSeen: nil))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
store.setActive(true)
#expect(await until { store.connection == .computerOffline(lastSeen: nil) })
#expect(store.canQueue && store.isOffline)
@@ -281,7 +281,7 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
storage.computers = [c1, c2]
let fakes = [c1.id: FakeRemote(.ready(.direct)), c2.id: FakeRemote(.ready(.relay))]
let account = AccountStore(storage: storage, cloud: nil) { computer in
- BotStore(computer: computer, storage: storage) { fakes[computer.id]! }
+ BotStore(computer: computer, storage: storage) { _ in fakes[computer.id]! }
}
var updates: [BotReference] = []
account.onBotUpdated = { ref, _ in updates.append(ref) }
@@ -321,7 +321,7 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
let a = randomComputer("A"), b = randomComputer("B"), c = randomComputer("C")
storage.computers = [a, b, c]
let account = AccountStore(storage: storage, cloud: nil) { computer in
- BotStore(computer: computer, storage: storage) { FakeRemote(.ready(.direct)) }
+ BotStore(computer: computer, storage: storage) { _ in FakeRemote(.ready(.direct)) }
}
account.move(a.id, to: c.id)
#expect(account.computers.map(\.id) == [b.id, c.id, a.id])
@@ -338,7 +338,7 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
let saved = randomComputer("Saved")
storage.computers = [saved]
let account = AccountStore(storage: storage, cloud: nil) { _ in
- BotStore(computer: saved, storage: storage) { FakeRemote(.ready(.direct)) }
+ BotStore(computer: saved, storage: storage) { _ in FakeRemote(.ready(.direct)) }
}
account.setColor(saved.id, "red")
#expect(storage.computers.first?.color == "red")
@@ -356,7 +356,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
store.setActive(true)
defer { store.setActive(false) }
#expect(await until { await fake.subscribed })
@@ -389,7 +389,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
store.setActive(true)
defer { store.setActive(false) }
#expect(await until { await fake.subscribed })
@@ -415,7 +415,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.hostOffline(lastSeen: nil))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
try await Task.sleep(for: .milliseconds(200))
@@ -433,7 +433,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.failed("Can't reach"))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
try await Task.sleep(for: .milliseconds(200))
@@ -446,7 +446,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -474,7 +474,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -498,7 +498,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -522,7 +522,7 @@ extension FakeRemote {
let down = FakeRemote(.failed("Can't reach"))
let up = FakeRemote(.ready(.relay))
var made = 0
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) {
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in
made += 1
return made == 1 ? down : up
}
@@ -540,7 +540,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -563,7 +563,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -599,7 +599,7 @@ extension FakeRemote {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -625,7 +625,7 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.relay))
await fake.setHello(helloJSON(version: "2.6.0", minApp: "2.5.0"))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: "2.4.0") { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: "2.4.0") { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { store.mismatch == .updateApp(minimum: "2.5.0") })
@@ -640,7 +640,7 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.relay))
await fake.setHello(helloJSON(version: "2.2.0"))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: VersionMismatch.minHost) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: VersionMismatch.minHost) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { store.mismatch == .updateHost(version: "2.2.0", minimum: VersionMismatch.minHost) })
@@ -660,7 +660,7 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
for minApp in ["9.1.0", "2.0.0"] {
let fake = FakeRemote(.ready(.relay))
await fake.setHello(helloJSON(version: "9.1.0", minApp: minApp, backends: #""changed shape""#))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: "9.0.0") { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: "9.0.0") { _ in fake }
store.setActive(true)
#expect(await until { store.mismatch == .updateApp(minimum: "9.1.0") }, "minApp \(minApp)")
#expect(store.hello == nil)
@@ -674,7 +674,7 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
for (hostVersion, appIsBehind) in [("9.1.0", true), ("9.0.0", false)] {
let fake = FakeRemote(.ready(.relay))
await fake.setHello(helloJSON(version: hostVersion, minApp: "2.3.0"))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: "9.0.0") { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage, appVersion: "9.0.0") { _ in fake }
store.setActive(true)
let broken = #"{"type":"bot","bot":{"id":"b1","name":7}}"#
#expect(await until { await fake.eventSubscriptionCount == 1 })
@@ -697,7 +697,7 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let computer = randomComputer("Mac")
storage.composerDrafts[computer.id] = [#"["first",null]"#: "Unsent", #"["first","root"]"#: "Aside", "second": "New"]
- let store = BotStore(computer: computer, storage: storage) { FakeRemote(.connecting) }
+ let store = BotStore(computer: computer, storage: storage) { _ in FakeRemote(.connecting) }
defer { store.retire() }
#expect(store.composerDraft(for: "first") == "Unsent")
#expect(store.composerDraft(for: "second") == "New")
@@ -709,7 +709,7 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let computer = randomComputer("Mac")
- let store = BotStore(computer: computer, storage: storage) { FakeRemote(.connecting) }
+ let store = BotStore(computer: computer, storage: storage) { _ in FakeRemote(.connecting) }
let text = " 中文\nunfinished 🐱\n"
store.setComposerDraft(text, for: "first")
store.setComposerDraft("Other draft", for: "second")
@@ -717,13 +717,13 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
#expect(store.composerDraft(for: "first") == text)
store.retire()
store.setComposerDraft("late edit", for: "first")
- let reopened = BotStore(computer: computer, storage: storage) { FakeRemote(.connecting) }
+ let reopened = BotStore(computer: computer, storage: storage) { _ in FakeRemote(.connecting) }
defer { reopened.retire() }
#expect(reopened.composerDraft(for: "first") == text)
reopened.setComposerDraft("", for: "first")
#expect(reopened.composerDraft(for: "first").isEmpty)
#expect(reopened.composerDraft(for: "second") == "Other draft")
- let other = BotStore(computer: randomComputer("Other"), storage: storage) { FakeRemote(.connecting) }
+ let other = BotStore(computer: randomComputer("Other"), storage: storage) { _ in FakeRemote(.connecting) }
defer { other.retire() }
#expect(other.composerDraft(for: "first").isEmpty)
storage.erase()
@@ -734,7 +734,7 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.setActive(true)
#expect(await until { await fake.subscribed })
@@ -767,7 +767,7 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
]}
"""#
try Data(cached.utf8).write(to: url)
- let store = BotStore(computer: computer, storage: storage) { FakeRemote(.ready(.direct)) }
+ let store = BotStore(computer: computer, storage: storage) { _ in FakeRemote(.ready(.direct)) }
defer { store.retire() }
// Adding conversation metadata does not invalidate the existing base cache.
#expect(store.chat("dex").map(\.id) == ["notice", "local-pending"])
@@ -802,7 +802,7 @@ private func windowEntry(_ id: String, seq: Int64, rev: Int64 = 1) -> Entry {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.upsert(windowEntry("e100", seq: 100))
store.upsert(windowEntry("local-1", seq: 0)) // optimistic: not a floor
@@ -830,7 +830,7 @@ private func windowEntry(_ id: String, seq: Int64, rev: Int64 = 1) -> Entry {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let fake = FakeRemote(.ready(.direct))
- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { fake }
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
defer { store.retire() }
store.upsert(windowEntry("sent", seq: 100)) // RPC response before the catch-up
store.setActive(true)
diff --git a/apps/ios/Views/AccessRequestView.swift b/apps/ios/Views/AccessRequestView.swift
index edd9264f..a56f979e 100644
--- a/apps/ios/Views/AccessRequestView.swift
+++ b/apps/ios/Views/AccessRequestView.swift
@@ -12,6 +12,9 @@ struct AccessRequestView: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
/// A code was shown: when it goes away without an approval, the request is over (denied or expired).
@State private var sawTicket: Bool
+ /// Why it ended, taken from `accounts.lastError` when the code went: shown here, so the computers
+ /// list under this sheet doesn't say it again.
+ @State private var outcome: String?
init(computer: CloudComputer, pending: Bool) {
self.computer = computer
@@ -63,12 +66,12 @@ struct AccessRequestView: View {
Button("Try again") { withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { self.error = nil } }
.buttonStyle(.secondary)
} else if sawTicket {
- Text(accounts.lastError ?? "\(computer.name) didn't approve this request.")
+ Text(outcome ?? "\(computer.name) didn't approve this request.")
.foregroundStyle(Palette.secondary)
.multilineTextAlignment(.center)
Button("Ask again") {
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) {
- accounts.lastError = nil
+ outcome = nil
sawTicket = false
}
}
@@ -90,7 +93,14 @@ struct AccessRequestView: View {
.background(Palette.background)
// Closing keeps waiting in the background; the computer shows up once approved.
.safeAreaInset(edge: .top, spacing: 0) { ModalHeader("Access") }
- .onChange(of: ticket?.requestId) { _, id in if id != nil { sawTicket = true } }
+ .onChange(of: ticket?.requestId) { old, id in
+ if id != nil {
+ sawTicket = true
+ } else if old != nil, !approved {
+ outcome = accounts.lastError
+ accounts.lastError = nil
+ }
+ }
.onChange(of: approved) { _, done in
guard done else { return }
Task {
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index bdee2de9..cfe6b8ef 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -51,9 +51,10 @@ struct BotListView: View {
availableStores.filter { $0.connection == .online }
}
- /// Computers that can take a new bot once they're connected (not ones waiting for an update).
+ /// Computers that can take a new bot once they're connected (not ones waiting for an update, or
+ /// ones that won't come back: they turned this iPhone away, or are this computer's older identity).
private var availableStores: [BotStore] {
- accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.mismatch == nil }
+ accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.mismatch == nil && !accounts.isStale($0.computer.id) }
}
/// The rows the user can drag: each shown computer's heading (with several computers), in the
@@ -80,7 +81,8 @@ struct BotListView: View {
}
// A computer waiting for an update has its card instead; its bots aren't known yet.
if roster.isEmpty && shownStores.allSatisfy({ $0.mismatch == nil }) {
- EmptyRoster(canCreate: !availableStores.isEmpty, hasComputer: !accounts.computers.isEmpty,
+ // Computers that turned this iPhone away count as none: the way on is in Computers.
+ EmptyRoster(canCreate: !availableStores.isEmpty, hasComputer: accounts.computers.contains { !accounts.isStale($0.id) },
create: newBot, showComputers: { app.showComputers = true })
}
ForEach(lines) { line in
diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swift
index b57bd4e1..3e763607 100644
--- a/apps/ios/Views/SettingsView.swift
+++ b/apps/ios/Views/SettingsView.swift
@@ -33,7 +33,7 @@ struct SettingsView: View {
ComputerRow(store: store, inAccount: cloudComputer(computer.id),
openScreen: { openScreen(store) },
openMarketplace: { closeSheets { app.marketplace = store.computer.id } },
- revoke: cloudComputer(computer.id).flatMap { c in c.access == "granted" ? { confirmRevoke = c } : nil },
+ revoke: cloudComputer(computer.id).flatMap { c in c.isGranted ? { confirmRevoke = c } : nil },
remove: { confirmForget = computer })
}
}
@@ -157,7 +157,7 @@ struct SettingsView: View {
isPresented: Binding(get: { confirmForget != nil }, set: { if !$0 { confirmForget = nil } }),
message: "Its bots and conversations stay on that computer. You can pair again any time.") {
[DialogAction("Remove", destructive: true) {
- if let c = confirmForget { accounts.forget(c.id) }
+ if let c = confirmForget { Task { await app.removeComputer(c.id) } }
}]
}
.codyncDialog("Revoke this iPhone's access to \(confirmRevoke?.name ?? "the computer")?",
@@ -168,6 +168,12 @@ struct SettingsView: View {
}]
}
.task { notificationsAllowed = await PushRegistrar.shared.isAllowed() }
+ // What failed here (removing, revoking, refreshing) shows over this sheet, not under it at the root,
+ // where the same error clears with this one. In place: a failure right after a confirmation comes
+ // while that dialog's cover is still fading out, and a second cover can't present over it.
+ .codyncDialog("Something went wrong", isPresented: Binding(
+ get: { accounts.lastError != nil }, set: { if !$0 { accounts.lastError = nil } }
+ ), message: accounts.lastError, cancel: "OK", inPlace: true) { [] }
}
@@ -363,7 +369,7 @@ private struct AccountComputerRow: View {
Spacer()
if ticket != nil {
Button("Code", action: ask).buttonStyle(.secondary)
- } else if computer.access == "granted" {
+ } else if computer.isGranted {
Button("Revoke", role: .destructive, action: revoke).buttonStyle(.secondary)
} else {
Button("Ask for access", action: ask).buttonStyle(.secondary)
diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.md
index 33c6c89a..6b77589c 100644
--- a/docs/guides/accounts-and-ssh.md
+++ b/docs/guides/accounts-and-ssh.md
@@ -193,8 +193,12 @@ first). See [desktop app](../architecture/desktop-app.md).
*Reach from anywhere* (`setCloud`, on/off; the host's build decides which cloud),
*Add to account* (claim: `POST /v1/claims` → loopback `claimSign` → complete) and
*Remove from account* (`unclaim`), a pairing QR, and the authorized devices with revoke.
-A device asking for access raises the menu bar dot and opens the approval sheet with the
-6-digit code; Approve stays disabled until the device revealed its code.
+Signed in, this computer joins the account on its own once per host identity; an identity
+that was already in the account and was removed (here or from a phone) is never re-added
+silently, only through *Add to account*. The section below, *Other computers in your account*,
+lists only the account's other computers. A device asking for access raises the menu bar dot
+and opens the approval sheet with the 6-digit code; Approve stays disabled until the device
+revealed its code.
SSH computers use the system OpenSSH (`apps/desktop/src/main/ssh.ts`): `ssh -G` to
resolve the target, `ssh-keygen -F` against `~/.ssh/known_hosts` and
diff --git a/docs/plans/android-app.md b/docs/plans/android-app.md
index 72572e4a..f6810015 100644
--- a/docs/plans/android-app.md
+++ b/docs/plans/android-app.md
@@ -58,7 +58,7 @@ was walked through on an emulator against a real host.
| What | Code | What it needs |
| --- | --- | --- |
-| Revoke this phone's access; removing older copies of the computer from the account | `core/.../CloudClient.kt` (`revokeAccess`, `removeComputer`), `SettingsView.kt` | A signed-in account on the emulator or a phone; only request tests cover it |
+| Revoke this phone's access (also on Remove of a computer approved through the account); removing older copies of the computer from the account | `core/.../CloudClient.kt` (`revokeAccess`, `removeComputer`), `AppStoreAccount.kt`, `SettingsView.kt` | A signed-in account on the emulator or a phone; only request tests cover it |
| Push delivery (alerts, background Live update refresh) | `PushService.kt`, `AppStoreNotifications.kt` | A Firebase project and the push Worker's FCM secret (owner's go-ahead). The notification look is covered by `AlertNotificationTest` |
| OpenAI Realtime, Gemini Live and Speech mode with a real key | `WebRtcPeer.kt`, `core/.../OpenAIRealtimeEngine.kt`, `GeminiLiveEngine.kt`, `CloudSpeechEngine.kt` | A provider key on the paired computer; the fallback to on-device voice is verified |
| Remote screen: Chinese IME composition, a hardware keyboard, the TURN relay path and its credential renewal | `ScreenKeys.kt`, `ScreenSession.kt`, `ScreenView.kt` | A computer it's safe to type into, and a signed-in host for the relay; viewing, trackpad and pinch zoom are verified |
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index ed2efcf6..c11dfd2b 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -189,6 +189,7 @@ host 的授權裝置表(`host/src/api/devices.rs`)每一列:`key, name, pl
- 狀態拉取成功時才延長 lease;連不到雲端就讓 lease 自然到期。
- `lease_until` 過期的列視同不存在(不必立即刪;下次拉取時清)。
- 每次連上 relay(含重連):先完成一次 state 拉取(最多等 10 秒)才送 `acl`/`ready`;拉取成功之前,`source=account` 的列在直連與中繼上都不接受握手。
+- 連線期間每 5 分鐘再拉一次,有沒有 owner 都拉:漏接的 `cloud.changed`(例如剛被 claim)由此補上;成功的拉取也清掉 `lastError`。
- 表有任何變動 → `acl_ver` 前進(§7.3 規則)→ 發佈 ACL。
ACL(host 簽章,DO 驗證;逐位元組簽章,不做 JSON 正規化;向量 `acl`):
diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rs
index 32382452..b0854d09 100644
--- a/host/src/remote/cloud.rs
+++ b/host/src/remote/cloud.rs
@@ -328,7 +328,11 @@ pub async fn pull(hub: &Hub, base: &str) -> Result<()> {
let state: State = serde_json::from_value(call(hub, base, Method::GET, "/v1/host/state", None).await?)
.context("reading the cloud state")?;
apply_grants(hub, &state.grants)?;
- update_status(hub, |s| s.owner = state.owner);
+ // A pull that works also settles an earlier failed one.
+ update_status(hub, |s| {
+ s.owner = state.owner;
+ s.last_error = None;
+ });
sync_requests(hub, base, state.requests).await;
if approval(&hub.store) == Approval::Auto {
// The SAS exchange still runs (the device's commit must match); only the user's comparison is skipped.
@@ -783,6 +787,17 @@ mod tests {
assert_eq!(hub.store.device(&b64(&dk)).unwrap().source, DeviceSource::Account, "approved without the user");
}
+ #[tokio::test]
+ async fn a_pull_that_works_clears_an_earlier_error() {
+ let hub = temp_hub();
+ let fake = Arc::new(FakeCloud::default());
+ let base = fake_cloud(fake.clone()).await;
+ *fake.state.lock().unwrap() = json!({"owner": null, "grants": [], "requests": []});
+ update_status(&hub, |s| s.last_error = Some("couldn't get the cloud state".into()));
+ pull(&hub, &base).await.unwrap();
+ assert_eq!(hub.cloud.status().last_error, None, "Settings stops showing a relay error that's gone");
+ }
+
#[tokio::test]
async fn host_nonces_are_rationed() {
let hub = temp_hub();
@@ -805,6 +820,6 @@ mod tests {
hub.cloud.requests.locked().clear();
pull(&hub, &base).await.unwrap();
assert_eq!(fake.posts.lock().unwrap().len(), SAS_NONCES_PER_HOUR);
- assert!(hub.cloud.status().last_error.is_some(), "the Mac hears about it");
+ assert!(hub.cloud.status().last_error.is_some(), "the Mac hears about it, though the pull worked");
}
}
diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rs
index 43e04787..526e4406 100644
--- a/host/src/remote/relay.rs
+++ b/host/src/remote/relay.rs
@@ -246,11 +246,8 @@ async fn session(hub: &Arc<Hub>, base: &str) -> Result<Option<u16>> {
s.pull();
}
}
- _ = poll.tick() => {
- if hub.cloud.status().owner.is_some() {
- s.pull();
- }
- }
+ // Also without an owner: a claim whose `cloud.changed` never arrived is picked up here.
+ _ = poll.tick() => s.pull(),
Some(_) = s.pulls.join_next() => s.deliver_held().await?,
}
}
diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rs
index 5bbccc46..b8f1461f 100644
--- a/host/src/tui/app/events.rs
+++ b/host/src/tui/app/events.rs
@@ -4,7 +4,7 @@ use std::collections::HashMap;
use serde_json::{Value, json};
-use super::{After, App, Bot, Dir, Entry, Focus, Msg, Overlay, Status, merge_toggles};
+use super::{After, App, Bot, Dir, Entry, Focus, Msg, Overlay, PairCode, Status, merge_toggles};
/// An entry the mirror doesn't hold, below the floor its bot's loaded chat had when this
/// connection began: `seq` grows with insertion, so it predates the window and only arrived because
@@ -184,6 +184,12 @@ impl App {
p.error = Some(e);
}
}
+ // In place of the code, which may have expired.
+ After::Pairing => {
+ if let Some(Overlay::Pair(code)) = self.overlays.last_mut() {
+ *code = PairCode::Failed(e);
+ }
+ }
_ => self.flash(&e),
}
return;
@@ -250,8 +256,11 @@ impl App {
}
}
After::Pairing => {
- if let Some(Overlay::Pair(url)) = self.overlays.last_mut() {
- *url = v["pairingUrl"].as_str().map(str::to_owned);
+ if let Some(Overlay::Pair(code)) = self.overlays.last_mut() {
+ *code = match v["pairingUrl"].as_str() {
+ Some(url) => PairCode::Ready(url.to_owned()),
+ None => PairCode::Failed("The host sent no pairing code.".into()),
+ };
}
}
After::Saved => {
diff --git a/host/src/tui/app/forms.rs b/host/src/tui/app/forms.rs
index d9bdafb3..aad2a510 100644
--- a/host/src/tui/app/forms.rs
+++ b/host/src/tui/app/forms.rs
@@ -5,14 +5,14 @@ use serde_json::{Value, json};
use std::collections::BTreeMap;
use super::{
- After, App, Bot, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, Overlay, SHAPES, Toggle, cycle,
- merge_toggles,
+ After, App, Bot, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, Overlay, PairCode, SHAPES, Toggle,
+ cycle, merge_toggles,
};
use crate::tui::manage::Page;
impl App {
pub(super) fn open_pair(&mut self) {
- self.overlays.push(Overlay::Pair(None));
+ self.overlays.push(Overlay::Pair(PairCode::Loading));
self.call("pairing", json!({}), After::Pairing);
}
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index 232b5a8c..7e779086 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -19,7 +19,8 @@ pub use model::{After, AgentModel, Bot, Entry, Kind, Mark, ModelOption, Msg, Sta
pub use slash::SlashAction;
pub use ui::{
ACTIONS, Action, COLORS, Click, Confirm, ConfirmAct, Dir, FIELDS, FILTERS, Field, Focus, FolderPicker, Form, Goto,
- GotoItem, GroupField, GroupForm, Hits, NewBot, NewBotField, Overlay, SHAPES, Toast, Toggle, TraceMode, Width,
+ GotoItem, GroupField, GroupForm, Hits, NewBot, NewBotField, Overlay, PairCode, SHAPES, Toast, Toggle, TraceMode,
+ Width,
};
use serde_json::{Value, json};
diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index 305271bb..686280d5 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -6,7 +6,7 @@ use serde_json::json;
use super::super::manage::{AnalyticsSheet, Reply};
use super::{
ACTIONS, Action, After, App, Bot, ConfirmAct, Dir, Editor, FILTERS, FolderPicker, Goto, GotoItem, Overlay,
- contains, fuzzy,
+ PairCode, contains, fuzzy,
};
impl App {
@@ -108,6 +108,11 @@ impl App {
Overlay::Fields(f) => self.fields_key(f, k),
Overlay::Skill(s) => self.skill_key(s, k),
Overlay::Analytics(s) => s.key(k),
+ // A new code: after a failure, or in place of the one shown.
+ Overlay::Pair(_) if k.code == KeyCode::Char('r') => {
+ self.call("pairing", json!({}), After::Pairing);
+ Some(Overlay::Pair(PairCode::Loading))
+ }
o @ (Overlay::Usage | Overlay::Pair(_)) => {
if matches!(k.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q' | 'U' | 'P')) {
None
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index 1e3a39e8..1a39985d 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -275,6 +275,13 @@ pub struct GroupForm {
pub saving: bool,
}
+/// The pair-a-phone sheet's code: on its way, shown (its pairing link), or why none came.
+pub enum PairCode {
+ Loading,
+ Ready(String),
+ Failed(String),
+}
+
pub enum Overlay {
Goto(Goto),
Help(Editor),
@@ -284,7 +291,7 @@ pub enum Overlay {
Form(Box<Form>),
Group(GroupForm),
Usage,
- Pair(Option<String>),
+ Pair(PairCode),
Memory(MemorySheet),
/// A read-only conversation between two bots.
BotChat(BotChatSheet),
diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rs
index 0d5abced..5299d1f0 100644
--- a/host/src/tui/view/overlay.rs
+++ b/host/src/tui/view/overlay.rs
@@ -120,7 +120,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay
Overlay::Form(form) => form_view(buf, area, app, form),
Overlay::Group(g) => group_view(buf, area, app, g),
Overlay::Usage => usage(buf, area, app),
- Overlay::Pair(url) => pair(buf, area, url.as_deref()),
+ Overlay::Pair(code) => pair(buf, area, code),
Overlay::Memory(m) => super::super::sheets::memory(buf, area, app, m),
Overlay::BotChat(c) => super::bot_chat::bot_chat(buf, area, app, c),
Overlay::Routines(l) => super::super::sheets::routines(buf, area, app, l),
diff --git a/host/src/tui/view/pair.rs b/host/src/tui/view/pair.rs
index 794c2c7c..9a14ba86 100644
--- a/host/src/tui/view/pair.rs
+++ b/host/src/tui/view/pair.rs
@@ -4,18 +4,28 @@ use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Style};
+use super::super::app::PairCode;
use super::super::md::{truncate, width as w};
use super::buffer::{centered, frame_box, put, u};
use super::style::theme;
-pub(super) fn pair(buf: &mut Buffer, area: Rect, url: Option<&str>) {
+pub(super) fn pair(buf: &mut Buffer, area: Rect, code: &PairCode) {
let t = theme();
- let Some(url) = url else {
- let r = centered(area, 40, 5);
- let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));
- put(buf, inner.x, inner.y + 1, inner.width, "Getting the pairing code…", t.secondary.patch(t.panel));
- return;
+ let (text, style) = match code {
+ PairCode::Ready(url) => return qr(buf, area, url),
+ PairCode::Loading => ("Getting the pairing code…", t.secondary),
+ PairCode::Failed(e) => (e.as_str(), t.red),
};
+ let r = centered(area, 56, 6);
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));
+ put(buf, inner.x, inner.y + 1, inner.width, text, style.patch(t.panel));
+ if matches!(code, PairCode::Failed(_)) {
+ put(buf, inner.x, inner.bottom() - 1, inner.width, "r try again · esc close", t.dim.patch(t.panel));
+ }
+}
+
+fn qr(buf: &mut Buffer, area: Rect, url: &str) {
+ let t = theme();
let qr = qrcode::QrCode::new(url.as_bytes())
.map(|c| c.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build())
.unwrap_or_default();
@@ -51,4 +61,5 @@ pub(super) fn pair(buf: &mut Buffer, area: Rect, url: Option<&str>) {
t.secondary.patch(t.panel),
);
put(buf, inner.x, y + 1, inner.width, &truncate(url, usize::from(inner.width)), t.dim.patch(t.panel));
+ put(buf, inner.x, inner.bottom() - 1, inner.width, "r new code · esc close", t.dim.patch(t.panel));
}