Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix(ios): recover phone access without deleting account computers
leepokai14861c21ef14
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.ktindex 3593561a..c5a83eec 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@@ -17,6 +17,7 @@ import org.junit.Beforeimport org.junit.Ruleimport org.junit.Testimport java.io.File+import kotlinx.coroutines.CompletableDeferred/** The account sheet and Computers & settings. Read-only: no test confirms a sign-out, route, removal or reset. */class AccountScreenTest {@@ -63,7 +64,10 @@ class AccountScreenTest {compose.onNodeWithText("Continue with Google").performScrollTo().assertIsDisplayed()compose.onNodeWithContentDescription("Add account").performScrollTo().performClick()compose.onNodeWithText("Continue with Google").assertDoesNotExist()+ // The sign-in spinner intentionally keeps drawing; freeze it while checking disabled actions.+ compose.mainClock.autoAdvance = falsecompose.runOnUiThread { state.value = state.value.copy(busy = setOf("session")) }+ compose.mainClock.advanceTimeBy(300)compose.onNodeWithContentDescription("Signing in").assertIsDisplayed()compose.onNodeWithContentDescription(second.email).assertIsNotEnabled()compose.onNodeWithContentDescription("Add account").assertIsNotEnabled()@@ -108,7 +112,7 @@ class AccountScreenTest {var paired = 0; var popped = 0; var extensions = 0compose.setContent { Hosted { SettingsView(state, viewModel(), { popped++ }, { paired++ }, {}) { extensions++ } } }compose.onNodeWithText("Computers & settings").assertIsDisplayed()- compose.onAllNodesWithText(computer.name).assertCountEquals(1)+ compose.onNode(hasText(computer.name) and hasClickAction()).assertIsDisplayed()compose.onNodeWithText("1 bot · Wi-Fi/Tailscale").assertIsDisplayed()compose.onNodeWithContentDescription("Extensions").performClick()assertEquals(1, extensions)@@ -124,7 +128,7 @@ class AccountScreenTest {compose.onNodeWithText("Start over?").assertIsDisplayed()compose.onNodeWithText("Cancel").performClick()compose.onNodeWithText("Start over?").assertDoesNotExist()- compose.onNodeWithText(computer.name).performScrollTo().performTouchInput { longClick() }+ compose.onNode(hasText(computer.name) and hasClickAction()).performScrollTo().performTouchInput { longClick() }compose.onNodeWithText("Remove").performClick()compose.onNodeWithText("Remove ${computer.name}?").assertIsDisplayed()compose.onNodeWithText("Cancel").performClick()@@ -166,6 +170,67 @@ class AccountScreenTest {assertTrue(cancelled)}+ @Test fun anUnreachableAccountComputerOffersAccessInsteadOfRemoval() {+ val cloud = CloudComputer(computer.id, computer.name, computer.signKey, online = true, access = "granted")+ val state = fixture().copy(computers = listOf(computer), cloudComputers = listOf(cloud),+ connection = LinkState.Failed("This phone cannot reach the computer.", 403))+ var asked: CloudComputer? = null+ compose.setContent { Hosted { SettingsView(state, viewModel(), null, {}, { asked = it }, {}) } }+ compose.onNodeWithText("This phone cannot reach the computer.").assertIsDisplayed()+ compose.onNodeWithText("Ask for access").performClick()+ assertEquals(cloud, asked)+ compose.onNodeWithContentDescription("Remove").assertDoesNotExist()+ compose.onNodeWithText(computer.name).performTouchInput { longClick() }+ compose.onNodeWithText("Remove").assertDoesNotExist()+ compose.onNodeWithText("Revoke this phone's access").assertIsDisplayed()+ }++ @Test fun aRevokedSavedComputerDoesNotBlockAskingItsReplacement() {+ val old = CloudComputer(computer.id, computer.name, computer.signKey, online = false)+ val replacement = CloudComputer("replacement", "New computer", "new-key", online = true)+ val state = fixture().copy(computers = listOf(computer), cloudComputers = listOf(old, replacement),+ connection = LinkState.Failed("Access revoked.", 403))+ var asked: CloudComputer? = null+ compose.setContent { Hosted { SettingsView(state, viewModel(), null, {}, { asked = it }, {}) } }+ compose.onAllNodesWithText("Ask for access")[1].assertIsEnabled().performClick()+ assertEquals(replacement, asked)+ compose.onNodeWithText("Remove this phone's computer to use this one", substring = true).assertDoesNotExist()+ }++ @Test fun anExistingPairingDoesNotPretendANewRequestWasApproved() {+ val cloud = CloudComputer(computer.id, computer.name, computer.signKey, online = true, access = "granted")+ val state = mutableStateOf(fixture().copy(computers = listOf(computer), cloudComputers = listOf(cloud),+ access = AccessTicket("new-request", Long.MAX_VALUE, "123456", computer.id, computer.signKey), busy = setOf("access")))+ compose.setContent { Hosted { AccessRequestView(state.value, viewModel(), cloud) } }+ compose.onNodeWithText("123 456").assertIsDisplayed()+ compose.onNodeWithText("${computer.name} approved this phone").assertDoesNotExist()+ compose.runOnUiThread { state.value = state.value.copy(access = null, busy = emptySet(), approvedAccess = mapOf(computer.id to "new-request")) }+ compose.onNodeWithText("${computer.name} approved this phone").assertIsDisplayed()+ }++ @Test fun existingApprovalRequiresAnExplicitRenewal() {+ val cloud = CloudComputer(computer.id, computer.name, computer.signKey, online = true, access = "granted")+ compose.setContent { Hosted { AccessRequestView(fixture().copy(computers = listOf(computer)), viewModel(), cloud) } }+ compose.onNodeWithText("Request new approval").assertIsDisplayed()+ compose.onNodeWithText("${computer.name} approved this phone").assertDoesNotExist()+ compose.onNodeWithText("Waiting for approval…").assertDoesNotExist()+ }++ @Test fun anApprovedHandoffWaitsForAnActiveSessionOperation() {+ lateinit var store: AppStore+ val release = CompletableDeferred<Unit>()+ val calls = mutableListOf<String>()+ compose.setContent { store = viewModel() }+ compose.runOnUiThread {+ store.sessionAction { calls.add("first"); release.await(); calls.add("finished") }+ store.sessionAction(wait = true) { calls.add("approved") }+ }+ compose.runOnIdle { assertEquals(listOf("first"), calls) }+ compose.runOnUiThread { release.complete(Unit) }+ compose.waitUntil { calls.size == 3 }+ compose.runOnIdle { assertEquals(listOf("first", "finished", "approved"), calls) }+ }+private fun snapshot(name: String) {if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") != "true") returnval bitmap = compose.onRoot().captureToImage().asAndroidBitmap()diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.ktindex aa9377d0..01f03b6b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt@@ -34,24 +34,29 @@ import com.kyant.shapes.RoundedRectangleimport com.codync.android.design.*import kotlinx.coroutines.delay-private enum class AccessPhase { Asking, Code, Approved, Ended }+private enum class AccessPhase { Renew, Asking, Code, Approved, Ended }/** Asks an account computer for this phone: the code to check on it, until it answers (iOS `AccessRequestView`). */@Composable internal fun AccessRequestView(state: AppState, store: AppStore, computer: CloudComputer) {val dismiss = LocalDismissModal.currentval ticket = state.access?.takeIf { it.computerId == computer.computerId }- val approved = state.computers.any { it.id == computer.computerId }+ var requestId by remember { mutableStateOf(ticket?.requestId) }+ var confirmRenewal by remember { mutableStateOf(computer.isGranted && ticket == null) }+ var renewRequest by remember { mutableStateOf(false) }+ val approved = requestId != null && state.approvedAccess[computer.computerId] == requestId+ LaunchedEffect(ticket?.requestId) { ticket?.requestId?.let { requestId = it; renewRequest = false } }// The request ran and is over without an approval: denied, expired, or it failed.var asked by remember { mutableStateOf("access" in state.busy) }var ended by remember { mutableStateOf<String?>(null) }val asking = "access" in state.busy- LaunchedEffect(Unit) { if (!asking && !approved) store.requestAccess(computer) }+ LaunchedEffect(Unit) { if (!asking && !approved && ticket == null && !confirmRenewal) store.requestAccess(computer) }LaunchedEffect(asking, approved) {if (asking) asked = trueelse if (asked && !approved) { ended = state.error ?: "${computer.name} didn't approve this request."; store.clearError(); asked = false }}LaunchedEffect(approved) { if (approved) { delay(1000); dismiss() } }val phase = when {+ confirmRenewal -> AccessPhase.Renewapproved -> AccessPhase.Approvedticket != null -> AccessPhase.Codeended != null -> AccessPhase.Ended@@ -65,6 +70,13 @@ private enum class AccessPhase { Asking, Code, Approved, Ended }AnimatedContent(phase, transitionSpec = { fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade()) }, label = "Access") { shown ->Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(24.dp)) {when (shown) {+ AccessPhase.Renew -> {+ Text("This phone already has approval. If access no longer works, request a new approval on the computer.",+ style = Type.body, color = Palette.secondary, textAlign = TextAlign.Center)+ Text("This replaces this phone's current approval. The computer must be online to show the new code.",+ style = Type.footnote, color = Palette.secondary, textAlign = TextAlign.Center)+ SecondaryButton("Request new approval") { confirmRenewal = false; renewRequest = true; store.requestAccess(computer, renew = true) }+ }AccessPhase.Approved -> IconLabel("${computer.name} approved this phone", "checkmark.circle.fill", Palette.added, style = Type.headline)AccessPhase.Code -> {val code = ticket?.code.orEmpty()@@ -86,7 +98,7 @@ private enum class AccessPhase { Asking, Code, Approved, Ended }}AccessPhase.Ended -> {Text(ended.orEmpty(), style = Type.body, color = Palette.secondary, textAlign = TextAlign.Center)- SecondaryButton("Ask again") { ended = null; store.requestAccess(computer) }+ SecondaryButton("Ask again") { ended = null; store.requestAccess(computer, renew = renewRequest) }}AccessPhase.Asking -> Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {Spinner()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.ktindex 465f5509..2a3de5d9 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,7 @@ data class AppState(val account: AccountState = AccountState(),val cloudComputers: List<CloudComputer> = emptyList(),val access: AccessTicket? = null,+ val approvedAccess: Map<String, String> = emptyMap(),/** The account computer an access request is running for: one at a time. */val askingAccess: String? = null,val notifications: Boolean = true,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.ktindex 056dc2d8..00ecd5d7 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,8 +51,6 @@ 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 = 0internal var widgetOwner: WidgetOwner? = null/** The host version an undecodable event already made the mirror fetch everything again for. */internal var rewoundFor: String? = null@@ -143,9 +141,11 @@ class AppStore(application: Application) : AndroidViewModel(application) {contextScope = CoroutineScope(contextJob + Dispatchers.Main.immediate)}- internal fun sessionAction(operation: suspend () -> Unit) {- if (sessionJob?.isActive == true) return+ internal fun sessionAction(wait: Boolean = false, operation: suspend () -> Unit) {+ val previous = sessionJob+ if (previous?.isActive == true && !wait) returnsessionJob = viewModelScope.launch {+ previous?.join()mutableState.update { it.copy(busy = it.busy + "session", error = null) }try { operation() }catch (error: CancellationException) { throw error }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.ktindex c0c64301..ded3e2aa 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,13 +48,7 @@ fun AppStore.refreshCloud() = action("cloud") {val client = cloud ?: return@actiontry {client.registerDevice(Build.MODEL.take(100))- // 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)+ val computers = client.computers()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)@@ -69,14 +63,14 @@ fun AppStore.refreshCloud() = action("cloud") {/** 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") {+fun AppStore.requestAccess(target: CloudComputer, renew: Boolean = false) = action("access") {mutableState.update { it.copy(askingAccess = target.computerId) }- try { askForAccess(target) } finally { mutableState.update { it.copy(askingAccess = null) } }+ try { askForAccess(target, renew) } finally { mutableState.update { it.copy(askingAccess = null) } }}-private suspend fun AppStore.askForAccess(target: CloudComputer) {+private suspend fun AppStore.askForAccess(target: CloudComputer, renew: Boolean) {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." }+ if (renew) client.revokeAccess(target.computerId)val ticket = client.requestAccess(target.computerId, target.signKey)Analytics.capture(AnalyticsEvent.AccessRequested)mutableState.update { it.copy(access = ticket) }@@ -91,14 +85,13 @@ private suspend fun AppStore.askForAccess(target: CloudComputer) {"pending" -> continue"approved" -> {// Pin only the key used in the SAS. The first authenticated hello supplies addresses and box key.+ val previous = state.value.computers.firstOrNull { it.id == ticket.computerId && it.signKey == ticket.signKey }val computer = Computer(ticket.computerId, target.name, ticket.signKey, cloud = BuildConfig.CLOUD_URL)+ .copy(urls = previous?.urls.orEmpty(), boxKey = previous?.boxKey,+ color = previous?.color, route = previous?.route ?: ConnectionRoute.Automatic)computer.validate()- 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()- // Its account entry now says granted, which offers Revoke.- refreshCloud()+ useApprovedComputer(computer, ticket.requestId)return}"denied" -> {@@ -120,6 +113,25 @@ private suspend fun AppStore.askForAccess(target: CloudComputer) {} finally { mutableState.update { it.copy(access = null) } }}+/** Switch only after approval, retiring the old channel and its writers before replacing its mirror. */+private fun AppStore.useApprovedComputer(computer: Computer, requestId: String) {+ val contextId = state.value.contextId+ val generation = state.value.generation+ sessionAction(wait = true) {+ transitions.withLock {+ if (state.value.contextId != contextId || state.value.generation != generation) return@withLock+ val userId = state.value.account.userId+ retireContext()+ try {+ withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }+ } finally {+ loadContext(userId)+ }+ mutableState.update { it.copy(approvedAccess = it.approvedAccess + (computer.id to requestId)) }+ }+ }+}+fun AppStore.cancelAccess() {val ticket = state.value.accessval client = cloud@@ -140,30 +152,6 @@ 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).- * 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") {- 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()-}-/** The computer's badge color, picked on this phone (an `AvatarPalette` id). */fun AppStore.setColor(color: String) = action("color") {val computer = state.value.computers.firstOrNull() ?: return@actiondiff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.ktindex 15d8604a..a3e557ea 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@@ -56,7 +56,7 @@ 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 that joined after it was last seen is online, the same- * machine under a new identity (iOS `AccountStore.isStale`). Removing it is the fix.+ * machine under a new identity (iOS `AccountStore.isStale`). Account computers offer access recovery; only independently paired computers offer removal.*/internal val AppState.isStale: Boolean get() {val computer = computers.firstOrNull() ?: return falsediff --git a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.ktindex d8a8c2e7..40482ff0 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@@ -15,6 +15,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSourceimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth@@ -65,7 +66,6 @@ import kotlinx.serialization.json.putval paired = state.computers.firstOrNull()var confirmForget by remember { mutableStateOf(false) }var confirmRevoke by remember { mutableStateOf<CloudComputer?>(null) }- var confirmRemoveCopy by remember { mutableStateOf<CloudComputer?>(null) }var coloring by remember { mutableStateOf(false) }var confirmStartOver by remember { mutableStateOf(false) }var voice by remember { mutableStateOf(false) }@@ -79,11 +79,12 @@ import kotlinx.serialization.json.putif (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 },+ ask = inAccount?.let { c -> { ask(c) } },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,+ if (state.isOlderCopy(computer)) OlderCopyRow(computer)+ else AccountComputerRow(computer, state.access?.takeIf { it.computerId == computer.computerId }?.code,askingAnother = state.askingAccess.let { it != null && it != computer.computerId },ask = { ask(computer) }, revoke = { confirmRevoke = computer })}@@ -138,10 +139,6 @@ import kotlinx.serialization.json.put}CodyncSheet(voice, { voice = false }) { VoiceChatSettings(state, store) }SwatchPanel(coloring, paired?.color, { coloring = false }, store::setColor)- CodyncDialog("Remove the older ${confirmRemoveCopy?.name ?: "computer"}?", confirmRemoveCopy != null, { confirmRemoveCopy = null },- "It's this computer under an earlier identity and can't be reached anymore. Removing it only cleans up your account.") {- listOfNotNull(confirmRemoveCopy?.let { copy -> DialogAction("Remove", destructive = true) { store.removeFromAccount(copy.computerId) } })- }CodyncSheet(aboutAnalytics, { aboutAnalytics = false }) { AnalyticsSheet() }CodyncDialog("Start over?", confirmStartOver, { confirmStartOver = false },"Signs out of every account and forgets every computer on this phone, then shows the welcome again. Your computers keep their bots and chats; pair again to use them.") {@@ -179,7 +176,7 @@ import kotlinx.serialization.json.put/** What the paired computer's row and its menu open; `revoke` is set when this phone's account access can be revoked. */private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unit, val voice: () -> Unit, val color: () -> Unit,- val revoke: (() -> Unit)?, val remove: () -> Unit)+ val ask: (() -> Unit)?, val revoke: (() -> Unit)?, val remove: () -> Unit)/** The paired computer: its connection, how it's reached, and whether it's in the account. */@Composable private fun ComputerRow(state: AppState, store: AppStore, inAccount: Boolean, actions: ComputerActions) {@@ -192,50 +189,52 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unitval count = state.bots.count { !it.deleted && it.kind != "group" }"$count bot${if (count == 1) "" else "s"} · ${if (link.route == HostRoute.Direct) "Wi-Fi/Tailscale" else "Cloudflare"}"} else computerStatusText(state)- Row(Modifier.fillMaxWidth().contextActions(items = {+ Column(Modifier.fillMaxWidth().contextActions(items = {listOfNotNull(MenuItem("Color", icon = "paintpalette", action = actions.color),if (online) MenuItem("Extensions", icon = "square.grid.2x2", action = actions.extensions) else null,if (online) MenuItem("Voice chat", icon = "waveform", action = actions.voice) else null,if (viewable) MenuItem("Screen", icon = "display", action = actions.screen) else null,actions.revoke?.let { MenuItem("Revoke this phone's access", icon = "lock.slash", destructive = true, divider = true, action = it) },- MenuItem("Remove", icon = "trash", destructive = true, divider = actions.revoke == null, action = actions.remove),+ if (!inAccount) MenuItem("Remove", icon = "trash", destructive = true, divider = actions.revoke == null, action = actions.remove) else null,)- }), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {- ComputerBadge(state.hello?.text("device"), 40.dp, computer.color)- Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text(state.hello?.text("name") ?: computer.name, style = Type.body.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {- val ink = if (link is LinkState.ComputerOffline || link is LinkState.Failed) Palette.warning else Palette.secondary- Text(detail, style = Type.subheadline, color = ink, maxLines = if (stale) 2 else 1, overflow = TextOverflow.Ellipsis)- if (link is LinkState.Ready) Symbol(if (link.route == HostRoute.Direct) "wifi" else "cloud", size = 14.dp, tint = ink,- contentDescription = if (link.route == HostRoute.Direct) "Wi-Fi or Tailscale" else "Through Cloudflare")- }+ }), verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ ComputerBadge(state.hello?.text("device"), 40.dp, computer.color)+ Text(state.hello?.text("name") ?: computer.name, Modifier.weight(1f), style = Type.body.semibold, color = Palette.text)+ if (inAccount) Symbol("person.crop.circle.badge.checkmark", size = 20.dp, tint = Palette.tertiary, contentDescription = "In your account")}- if (online) IconButton("Extensions", "square.grid.2x2", action = actions.extensions)- if (viewable) IconButton("Screen", "display", action = actions.screen)- // Revoked, or this computer under an earlier identity: nothing to do but remove it.- if (stale) IconButton("Remove", "trash", action = actions.remove)- // Which route goes first, and whether Cloudflare is a fallback at all.- else DropdownMenu({ ConnectionRoute.entries.map { route -> MenuItem(route.title, icon = route.icon, selected = route == computer.route) { store.setRoute(route) } } },- Modifier.size(36.dp), label = "Connection") {- Symbol(computer.route.icon, size = 21.dp, tint = Palette.secondary)+ Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ val ink = if (link is LinkState.ComputerOffline || link is LinkState.Failed) Palette.warning else Palette.secondary+ Text(detail, Modifier.weight(1f, fill = false), style = Type.subheadline, color = ink)+ if (link is LinkState.Ready) Symbol(if (link.route == HostRoute.Direct) "wifi" else "cloud", size = 14.dp, tint = ink,+ contentDescription = if (link.route == HostRoute.Direct) "Wi-Fi or Tailscale" else "Through Cloudflare")+ }+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if ((link is LinkState.Failed || link is LinkState.ComputerOffline) && actions.ask != null) {+ SecondaryButton(if (state.access?.computerId == computer.id) "Show code" else "Ask for access", action = actions.ask)+ }+ if (online) IconButton("Extensions", "square.grid.2x2", action = actions.extensions)+ if (viewable) IconButton("Screen", "display", action = actions.screen)+ Spacer(Modifier.weight(1f))+ DropdownMenu({ ConnectionRoute.entries.map { route -> MenuItem(route.title, icon = route.icon, selected = route == computer.route) { store.setRoute(route) } } },+ Modifier.size(36.dp), label = "Connection") {+ Symbol(computer.route.icon, size = 21.dp, tint = Palette.secondary)+ }+ if (stale && !inAccount) IconButton("Remove", "trash", action = actions.remove)}- if (inAccount) Symbol("person.crop.circle.badge.checkmark", size = 20.dp, tint = Palette.tertiary, contentDescription = "In your account")}}/** 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,+@Composable private fun AccountComputerRow(computer: CloudComputer, code: String?, 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.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.- else -> "$online · Remove this phone's computer to use this one"+ else -> "$online · In your account"}Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {Box(Modifier.graphicsLayer { alpha = 0.5f }) { ComputerBadge(computer.device, 40.dp) }@@ -246,13 +245,13 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unitwhen {code != null -> SecondaryButton("Code", action = ask)computer.isGranted -> SecondaryButton("Revoke", action = revoke)- else -> SecondaryButton("Ask for access", enabled = canAsk && !askingAnother, action = ask)+ else -> SecondaryButton("Ask for access", enabled = !askingAnother, action = ask)}}}-/** The same machine under an earlier identity: one tap cleans it out of the account. */-@Composable private fun OlderCopyRow(computer: CloudComputer, remove: () -> Unit) {+/** An older account identity stays visible; only account management can remove it. */+@Composable private fun OlderCopyRow(computer: CloudComputer) {val seen = computer.lastSeenAt?.let { " · last seen ${RelativeTime.day(it)}" }.orEmpty()Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {Box(Modifier.graphicsLayer { alpha = 0.35f }) { ComputerBadge(computer.device, 40.dp) }@@ -260,7 +259,6 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> UnitText(computer.name, style = Type.body.semibold, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)Text("Older copy of this computer$seen", style = Type.subheadline, color = Palette.tertiary, maxLines = 2, overflow = TextOverflow.Ellipsis)}- IconButton("Remove from account", "trash", action = remove)}}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.ktindex 460d93d0..18487667 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@@ -108,9 +108,6 @@ class CloudClient private constructor(base: String, private val identity: Device}}- /** Takes a computer out of the account; its grants and pending requests go with it. */- suspend fun removeComputer(id: String) { request("DELETE", listOf("v1", "computers", id)) }-suspend fun accessStatus(id: String): AccessStatus {val result = request("GET", listOf("v1", "access-requests", id))return json.decodeFromJsonElement(result)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.ktindex cfa08b95..79f6c757 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@@ -122,19 +122,14 @@ class CloudClientTest {} finally { server.shutdown() }}- @Test fun `an unknown device has no grants to revoke and removing a computer deletes it from the account`() = runBlocking {+ @Test fun `an unknown device has no grants to revoke`() = runBlocking {val server = MockWebServer()server.start()try {server.enqueue(MockResponse().setBody("""{"devices":[]}"""))- server.enqueue(MockResponse().setBody("{}"))val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)client.revokeAccess(id)- client.removeComputer(id)assertEquals("/v1/devices", server.takeRequest().path)- val remove = server.takeRequest()- assertEquals("DELETE", remove.method)- assertEquals("/v1/computers/$id", remove.path)} finally { server.shutdown() }}}diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swiftindex 6974d5a6..91a9e937 100644--- a/apps/ios/App/CodyncApp.swift+++ b/apps/ios/App/CodyncApp.swift@@ -297,12 +297,7 @@ final class AppStore {guard let cloud else { return }let accounts = accountsdo {- let identity = try DeviceIdentity.load(context: accounts.storage)- if let device = try await cloud.devices().first(where: { $0.deviceKey == identity.publicKey }) {- for grant in try await cloud.grants(id) where grant.deviceId == device.deviceId {- try await cloud.revokeGrant(id, grantId: grant.grantId)- }- }+ try await cloud.revokeDeviceAccess(id)accounts.forget(id)await accounts.refreshCloud()} catch {diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swiftindex 0cc38d40..b722aa8a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift@@ -72,11 +72,6 @@ public struct CloudClient: Sendable {return res.computers}- /// Removes the computer from the account; every device's access to it through the account ends.- public func removeComputer(_ id: ComputerID) async throws {- try await send("DELETE", "v1/computers/\(id)")- }-public func grants(_ id: ComputerID) async throws -> [CloudGrant] {struct Res: Decodable { var grants: [CloudGrant] }let res: Res = try await request("GET", "v1/computers/\(id)/grants")@@ -87,6 +82,17 @@ public struct CloudClient: Sendable {try await send("DELETE", "v1/computers/\(id)/grants/\(grantId)")}+ /// Revokes only this phone's grants, so it can request a fresh approval without removing the computer.+ public func revokeDeviceAccess(_ id: ComputerID) async throws {+ guard let identity else { throw CloudError(status: 0, code: "noDeviceKey", message: "Sign in again on this device.") }+ guard let device = try await devices().first(where: { $0.deviceKey == identity.publicKey }) else {+ throw CloudError(status: 404, code: "notFound", message: "This phone isn't registered in your account. Sign in again.")+ }+ for grant in try await grants(id) where grant.deviceId == device.deviceId {+ try await revokeGrant(id, grantId: grant.grantId)+ }+ }+// MARK: access requests (§4.2 B, commit-then-reveal SAS)/// Commit → wait for the host's nonce → reveal. Returns once `code` can be shown.diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swiftindex 36a0fdc1..8334afb9 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift@@ -31,6 +31,8 @@ public final class AccountStore {public private(set) var cloudComputers: [CloudComputer] = []/// Access requests waiting for approval on the computer, with the SAS to show.public private(set) var pendingAccess: [ComputerID: AccessTicket] = [:]+ /// The actual request approved most recently, distinct from a previously paired computer.+ public private(set) var approvedAccess: [ComputerID: String] = [:]public var lastError: String?public var selection: BotReference? {didSet { if let id = selection?.computerId, !retired { storage.lastComputerId = id } }@@ -48,11 +50,8 @@ 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.+ /// A list that comes back after a newer request was started 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@@ -150,7 +149,7 @@ public final class AccountStore {cloudListVersion += 1let version = cloudListVersiondo {- let list = try await cloud.computers().filter { !removing.contains($0.computerId) }+ let list = try await cloud.computers()guard !retired, version == cloudListVersion else { return }if list != cloudComputers { Motion.animate { cloudComputers = list } }} catch let error as CloudError where !error.isTransient {@@ -167,7 +166,7 @@ public final class AccountStore {/// computer never waits on a request nobody reveals, and asking again while it runs joins it/// instead of committing a second one./// Approval is then picked up in the background and the computer joins `stores`.- public func requestAccess(_ id: ComputerID) async throws {+ public func requestAccess(_ id: ComputerID, renew: Bool = false) async throws {if let ask = asks[id], !ask.isCancelled {_ = try await ask.valuereturn@@ -176,7 +175,10 @@ public final class AccountStore {throw CloudError(status: 404, code: "notFound", message: "That computer isn't in your account.")}accessPolls[id]?.cancel()- let ask = Task { try await cloud.requestAccess(id, signKey: target.signKey) }+ let ask = Task {+ if renew { try await cloud.revokeDeviceAccess(id) }+ return try await cloud.requestAccess(id, signKey: target.signKey)+ }asks[id] = askaccessPolls[id] = Task { [weak self] inawait withTaskCancellationHandler {@@ -219,7 +221,7 @@ public final class AccountStore {/// 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 that joined the account after it was last seen, the same machine- /// under a new identity. Removing it is the fix.+ /// under a new identity. Account computers offer access recovery; only independently paired computers offer removal.public func isStale(_ id: ComputerID) -> Bool {guard let store = stores[id] else { return false }switch store.connection {@@ -258,28 +260,6 @@ public final class AccountStore {Motion.animate { pendingAccess[id] = ticket }}- /// 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, 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)- } 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.public func cancelAccess(_ id: ComputerID) async {guard let ticket = pendingAccess[id] else { return }@@ -303,10 +283,17 @@ public final class AccountStore {case .pending:continuecase .approved:+ approvedAccess[ticket.computerId] = ticket.requestIdsetPending(ticket.computerId, nil)// Pin the key the SAS was computed with; the first hello brings its mailbox key and addresses.- let computer = Computer(id: ticket.computerId, name: target.name, signKey: ticket.signKey,+ var computer = Computer(id: ticket.computerId, name: target.name, signKey: ticket.signKey,cloud: cloud.baseURL, device: target.device)+ if let previous = saved.first(where: { $0.id == computer.id && $0.signKey == computer.signKey }) {+ computer.urls = previous.urls+ computer.boxKey = previous.boxKey+ computer.color = previous.color+ computer.route = previous.route+ }save(computer)open(computer)Analytics.shared.capture(.computerPaired(via: .account, computer: computer.id))diff --git a/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift b/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swiftnew file mode 100644index 00000000..f82d18e0--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift@@ -0,0 +1,95 @@+import CryptoKit+import Foundation+import os+import Testing+@testable import CodyncKit+@testable import CodyncUI++private let renewalHostKey = Data(repeating: 17, count: 32)++private final class RenewalCloudStub: URLProtocol {+ struct State {+ var deviceKey = ""+ var approved = false+ var calls: [String] = []+ }+ static let state = OSAllocatedUnfairLock(initialState: State())+ 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 path = request.url!.path+ let method = request.httpMethod!+ let snapshot = Self.state.withLock { state in+ state.calls.append("\(method) \(path)")+ return state+ }+ let id = RelayCrypto.computerId(signKey: renewalHostKey)+ let json: String+ if path == "/v1/computers" {+ json = #"{"computers":[{"computerId":"\#(id)","name":"Desk","signKey":"\#(renewalHostKey.base64URL)","online":true,"access":"granted"}]}"#+ } else if path == "/v1/devices" {+ json = #"{"devices":[{"deviceId":"this-phone","deviceKey":"\#(snapshot.deviceKey)","name":"Phone"},{"deviceId":"other-phone","deviceKey":"other","name":"Other phone"}]}"#+ } else if path.hasSuffix("/grants") {+ json = #"{"grants":[{"grantId":"own-grant","deviceId":"this-phone"},{"grantId":"other-grant","deviceId":"other-phone"}]}"#+ } else if path.hasSuffix("/access-requests") {+ json = #"{"requestId":"renewal","expiresAt":4102444800000}"#+ } else if path == "/v1/access-requests/renewal" {+ json = #"{"requestId":"renewal","status":"\#(snapshot.approved ? "approved" : "pending")","hostNonce":"\#(Data(repeating: 9, count: 32).base64URL)"}"#+ } else {+ json = "{}"+ }+ client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!, cacheStoragePolicy: .notAllowed)+ client?.urlProtocol(self, didLoad: Data(json.utf8))+ client?.urlProtocolDidFinishLoading(self)+ }+}++@MainActor @Test func renewingAccessKeepsTheComputerAndOnlyReplacesThisPhonesApproval() async throws {+ let suite = "AccessRenewal.\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let config = URLSessionConfiguration.ephemeral+ config.protocolClasses = [RenewalCloudStub.self]+ let identity = DeviceIdentity(signing: .init(), push: .init())+ RenewalCloudStub.state.withLock { $0 = .init(deviceKey: identity.publicKey) }+ let cloud = CloudClient(baseURL: URL(string: "https://cloud.test")!, identity: identity,+ session: URLSession(configuration: config)) { "token" }+ let storage = SharedStore.Context(accountID: "account", suite: suite)+ let id = RelayCrypto.computerId(signKey: renewalHostKey)+ var computer = Computer(id: id, name: "Desk", signKey: renewalHostKey.base64URL, urls: ["http://192.168.1.20:19223"])+ computer.color = "blue"+ computer.route = .directOnly+ storage.computers = [computer]+ let accounts = AccountStore(storage: storage, cloud: cloud) { computer in+ BotStore(computer: computer, storage: storage) { _ in FakeRemote(.connecting) }+ }+ defer { accounts.retire() }+ accounts.setActive(false)+ await accounts.refreshCloud()+ #expect(accounts.approvedAccess.isEmpty)+ #expect(!RenewalCloudStub.state.withLock { $0.calls }.contains { $0.hasPrefix("DELETE") })++ try await accounts.requestAccess(id, renew: true)+ for _ in 0..<100 where accounts.pendingAccess[id] == nil {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(accounts.pendingAccess[id]?.requestId == "renewal")+ #expect(accounts.approvedAccess.isEmpty) // A saved computer is not this request's approval.+ #expect(storage.computers == [computer])+ let calls = RenewalCloudStub.state.withLock { $0.calls }+ #expect(calls.filter { $0.hasPrefix("DELETE") } == ["DELETE /v1/computers/\(id)/grants/own-grant"])+ let revoked = try #require(calls.firstIndex(of: "DELETE /v1/computers/\(id)/grants/own-grant"))+ let requested = try #require(calls.firstIndex(of: "POST /v1/computers/\(id)/access-requests"))+ #expect(revoked < requested)++ RenewalCloudStub.state.withLock { $0.approved = true }+ for _ in 0..<150 where accounts.approvedAccess[id] == nil {+ try await Task.sleep(for: .milliseconds(20))+ }+ #expect(accounts.approvedAccess[id] == "renewal")+ #expect(accounts.pendingAccess[id] == nil)+ #expect(storage.computers.first?.color == "blue")+ #expect(storage.computers.first?.route == .directOnly)+ #expect(storage.computers.first?.urls == computer.urls)+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/OlderCopyTests.swift b/apps/ios/Kit/Tests/CodyncUITests/OlderCopyTests.swiftindex 75fc8268..8580ccdf 100644--- a/apps/ios/Kit/Tests/CodyncUITests/OlderCopyTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/OlderCopyTests.swift@@ -95,74 +95,3 @@ private final class StaleCopyCloudStub: CloudStub {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, waits until the list is in; the account keeps listing both copies meanwhile.- let (deleteGate, openDelete) = AsyncStream<Void>.makeStream()- let tokens = OSAllocatedUnfairLock(initialState: 0)- let cloud = stubbedCloud(OlderCopyCloudStub.self) {- if tokens.withLock({ $0 += 1; return $0 }) == 2 { for await _ in deleteGate {} }- 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"])- openDelete.finish()- await removal.value-}diff --git a/apps/ios/Views/AccessRequestView.swift b/apps/ios/Views/AccessRequestView.swiftindex a56f979e..72bca4d2 100644--- a/apps/ios/Views/AccessRequestView.swift+++ b/apps/ios/Views/AccessRequestView.swift@@ -15,21 +15,41 @@ struct AccessRequestView: View {/// 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?+ @State private var requestId: String?+ @State private var confirmRenewal: Bool+ @State private var requesting = false+ @State private var renewRequest = false- init(computer: CloudComputer, pending: Bool) {+ init(computer: CloudComputer, pending: AccessTicket?) {self.computer = computer- _sawTicket = State(initialValue: pending)+ _sawTicket = State(initialValue: pending != nil)+ _requestId = State(initialValue: pending?.requestId)+ _confirmRenewal = State(initialValue: computer.isGranted && pending == nil)}private var ticket: AccessTicket? { accounts.pendingAccess[computer.computerId] }- private var approved: Bool { accounts.store(for: computer.computerId) != nil }+ private var approved: Bool { requestId != nil && accounts.approvedAccess[computer.computerId] == requestId }var body: some View {VStack(spacing: 24) {ComputerBadge(Computer(id: computer.computerId, name: computer.name, signKey: computer.signKey, device: computer.device), size: 64).padding(.top, 32)- if approved {+ if confirmRenewal {+ Text("This phone already has approval. If access no longer works, request a new approval on the computer.")+ .foregroundStyle(Palette.secondary)+ .multilineTextAlignment(.center)+ Text("This replaces this phone's current approval. The computer must be online to show the new code.")+ .font(.footnote)+ .foregroundStyle(Palette.secondary)+ .multilineTextAlignment(.center)+ Button("Request new approval") {+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) {+ renewRequest = true+ confirmRenewal = false+ }+ }.buttonStyle(.secondary)+ } else if approved {Label("\(computer.name) approved this iPhone", systemImage: "checkmark.circle.fill").font(.headline).foregroundStyle(Palette.added)@@ -94,7 +114,8 @@ struct AccessRequestView: View {// Closing keeps waiting in the background; the computer shows up once approved..safeAreaInset(edge: .top, spacing: 0) { ModalHeader("Access") }.onChange(of: ticket?.requestId) { old, id in- if id != nil {+ if let id {+ requestId = idsawTicket = true} else if old != nil, !approved {outcome = accounts.lastError@@ -114,8 +135,12 @@ struct AccessRequestView: View {/// Closing the sheet leaves the request, and this wait, running to its end with the result/// ignored; the code then shows in the banner.private func request() async {+ guard !requesting else { return }+ requesting = true+ defer { requesting = false }do {- try await accounts.requestAccess(computer.computerId)+ try await accounts.requestAccess(computer.computerId, renew: renewRequest)+ renewRequest = false} catch is CancellationError {return} catch {diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swiftindex 3e763607..1bc207af 100644--- a/apps/ios/Views/SettingsView.swift+++ b/apps/ios/Views/SettingsView.swift@@ -19,7 +19,6 @@ struct SettingsView: View {@State private var confirmRevoke: CloudComputer?@State private var access: AccessTarget?@State private var confirmStartOver = false- @State private var confirmRemoveCopy: CloudComputer?@State private var voice: VoiceTarget?@State private var aboutAnalytics = false@@ -33,13 +32,14 @@ struct SettingsView: View {ComputerRow(store: store, inAccount: cloudComputer(computer.id),openScreen: { openScreen(store) },openMarketplace: { closeSheets { app.marketplace = store.computer.id } },+ ask: cloudComputer(computer.id).map { c in { access = AccessTarget(computer: c) } },revoke: cloudComputer(computer.id).flatMap { c in c.isGranted ? { confirmRevoke = c } : nil },remove: { confirmForget = computer })}}ForEach(accountOnly) { computer inif accounts.isOlderCopy(computer) {- OlderCopyRow(computer: computer) { confirmRemoveCopy = computer }+ OlderCopyRow(computer: computer)} else {AccountComputerRow(computer: computer, ticket: accounts.pendingAccess[computer.computerId],ask: { access = AccessTarget(computer: computer) },@@ -130,12 +130,6 @@ struct SettingsView: View {.buttonStyle(.plain)}}- .codyncDialog("Remove the older \(confirmRemoveCopy?.name ?? "computer")?", isPresented: Binding(- get: { confirmRemoveCopy != nil }, set: { if !$0 { confirmRemoveCopy = nil } }- ), message: "It's this computer under an earlier identity and can't be reached anymore. Removing it only cleans up your account.") {- guard let copy = confirmRemoveCopy else { return [] }- return [DialogAction("Remove", destructive: true) { Task { await accounts.removeFromAccount(copy.computerId) } }]- }.codyncDialog("Start over?", isPresented: $confirmStartOver,message: "Signs out of every account and forgets every computer on this iPhone, then shows the welcome again. Your computers keep their bots and chats; pair again to use them.") {[DialogAction("Start over", destructive: true) { Task { await app.startOver() } }]@@ -151,7 +145,7 @@ struct SettingsView: View {.codyncSheet(item: $voice) { target in VoiceChatSettingsView().environment(target.store) }.codyncSheet(isPresented: $aboutAnalytics) { AnalyticsSheet() }.codyncSheet(item: $access) { target in- AccessRequestView(computer: target.computer, pending: accounts.pendingAccess[target.id] != nil)+ AccessRequestView(computer: target.computer, pending: accounts.pendingAccess[target.id])}.codyncDialog("Remove \(confirmForget?.name ?? "computer")?",isPresented: Binding(get: { confirmForget != nil }, set: { if !$0 { confirmForget = nil } }),@@ -249,6 +243,7 @@ private struct ComputerRow: View {let openScreen: () -> Void/// Agents, connectors and skills installed on this computer.let openMarketplace: () -> Void+ let ask: (() -> Void)?/// Set when this iPhone's access to the computer can be revoked.let revoke: (() -> Void)?let remove: () -> Void@@ -257,29 +252,33 @@ private struct ComputerRow: View {@State private var voiceSettings = falsevar body: some View {- HStack(spacing: 12) {- ComputerBadge(store.computer, size: 40)- VStack(alignment: .leading, spacing: 2) {+ VStack(alignment: .leading, spacing: 10) {+ HStack(spacing: 12) {+ ComputerBadge(store.computer, size: 40)Text(store.hostName).font(.body.weight(.semibold)).foregroundStyle(Palette.text)- HStack(spacing: 4) {- Text(detail).lineLimit(stale ? 2 : 1)- if store.connection == .online { RouteIcon(route: store.hostRoute) }+ .frame(maxWidth: .infinity, alignment: .leading)+ if inAccount != nil {+ Image(systemName: "person.crop.circle.badge.checkmark")+ .foregroundStyle(Palette.tertiary)+ .accessibilityLabel("In your account")}- .font(.subheadline)- .foregroundStyle(store.isOffline ? Palette.warning : Palette.secondary)- }- Spacer()- if store.connection == .online {- IconButton("Extensions", systemImage: "square.grid.2x2", action: openMarketplace)}- if store.screen != nil, store.connection == .online {- IconButton("Screen", systemImage: "display", action: openScreen)+ HStack(alignment: .top, spacing: 4) {+ Text(detail).fixedSize(horizontal: false, vertical: true)+ if store.connection == .online { RouteIcon(route: store.hostRoute) }}- if stale {- // Revoked, or this computer under an earlier identity: nothing to do but remove it.- IconButton("Remove", systemImage: "trash", action: remove)- } else {- // Which route goes first, and whether Cloudflare is a fallback at all.+ .font(.subheadline)+ .foregroundStyle(store.isOffline ? Palette.warning : Palette.secondary)+ HStack(spacing: 8) {+ if store.isOffline, let ask {+ Button(accounts.pendingAccess[store.computer.id] == nil ? "Ask for access" : "Show code", action: ask)+ .buttonStyle(.secondary)+ }+ if store.connection == .online {+ IconButton("Extensions", systemImage: "square.grid.2x2", action: openMarketplace)+ if store.screen != nil { IconButton("Screen", systemImage: "display", action: openScreen) }+ }+ Spacer(minLength: 0)DropdownMenu {ConnectionRoute.allCases.map { route inMenuItem(route.title, icon: route.icon, selected: route == preference) {@@ -294,11 +293,7 @@ private struct ComputerRow: View {.contentShape(Rectangle())}.accessibilityLabel("Connection")- }- if inAccount != nil {- Image(systemName: "person.crop.circle.badge.checkmark")- .foregroundStyle(Palette.tertiary)- .accessibilityLabel("In your account")+ if stale, inAccount == nil { IconButton("Remove", systemImage: "trash", action: remove) }}}.padding(.vertical, 2)@@ -317,7 +312,9 @@ private struct ComputerRow: View {if let revoke {items.append(MenuItem("Revoke this iPhone's access", icon: "lock.slash", destructive: true, divider: true, action: revoke))}- items.append(MenuItem("Remove", icon: "trash", destructive: true, divider: revoke == nil, action: remove))+ if inAccount == nil {+ items.append(MenuItem("Remove", icon: "trash", destructive: true, divider: revoke == nil, action: remove))+ }return items}.codyncSheet(isPresented: $voiceSettings) { VoiceChatSettingsView().environment(store) }@@ -389,10 +386,9 @@ private struct AccountComputerRow: View {}}-/// The same machine under an earlier identity: one tap cleans it out of the account.+/// An older account identity stays visible; only account management can remove it.private struct OlderCopyRow: View {let computer: CloudComputer- let remove: () -> Voidvar body: some View {HStack(spacing: 12) {@@ -403,7 +399,6 @@ private struct OlderCopyRow: View {Text(detail).font(.subheadline).foregroundStyle(Palette.tertiary).lineLimit(2)}Spacer()- IconButton("Remove from account", systemImage: "trash", action: remove)}.padding(.vertical, 2)}diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex bc1598ab..d070760c 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -6,6 +6,16 @@ any left). tools/asc-submit.py reads the released version's section;a version without one gets a generic "Bug fixes and improvements" line. Delete old sections.-->+## 2.22.1++### zh-Hant+- 手機連不上帳號內的電腦時,可直接要求存取權限;連線說明也更容易閱讀+- 手機的裝置清單不再提供刪除同帳號電腦的操作,避免誤刪++### en-US+- Ask for access directly when your phone cannot reach an account computer, with clearer connection details+- Account computers can no longer be removed from the phone's device list, preventing accidental removal+## 2.22.0### zh-Hantdiff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.mdindex 6b77589c..58d237c4 100644--- a/docs/guides/accounts-and-ssh.md+++ b/docs/guides/accounts-and-ssh.md@@ -4,6 +4,26 @@ The iOS app uses the official ClerkKit SDK (1.5.6). The desktop app talks to CleFrontend API directly, the way ClerkKit does on native apps (`apps/desktop/src/main/account.ts`):a device token kept encrypted with Electron `safeStorage`, OAuth in the system browser.+## Recovering phone access++On iOS and Android, an unreachable paired account computer shows **Ask for access**+next to its connection error. A pending request reopens its code. If this phone+already has account approval, **Request new approval** explicitly replaces only+this phone's grants, then starts the normal matching-code approval flow. Opening+the sheet alone does not revoke anything. The computer must be online to answer;+requesting access cannot repair an offline host. Existing pairing data and local+addresses and color/route preferences survive renewal, and a saved pairing never counts as+approval of a new request.++Phone device lists do not offer **Remove** for computers in the signed-in account,+including older identities. Independently paired computers can still be removed+locally, and **Revoke this phone's access** remains available for account grants.+Android keeps the current pairing while another computer is being approved, then+switches its local connection only after approval; both account records remain.+Desktop account management remains the place to remove an account computer.+This is a phone recovery flow: the desktop manages the host/account and the TUI+connects to its local host; neither has this phone access-request screen.+## ConfigurationThe iOS app uses `apps/ios/App/AccountSession.swift`. Public keys and cloud URLs come from `apps/shared/Config/<env>.plist`, copied into the bundle as `AccountConfig.plist` by `project.yml`; `iOS Dev` (`DevDebug` / `DevRelease`) selects dev and `iOS` (`Debug` / `Release`) selects main. The desktop app reads the same plist through `node apps/desktop/tools/account-config.mjs <env>` (run by `npm run dev` and `npm run dist:*:<env>`), which writes `resources/account-config.json` (`CODYNC_CLERK_PUBLISHABLE_KEY` / `CODYNC_CLOUD_URL` override it). See [environments](environments-and-deployment.md).