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(ios): replace pending requests when renewing access

leepokai8e23502a11a1
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 e222f63e..e888e37b 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
@@ -18,6 +18,9 @@ import org.junit.Rule
import org.junit.Test
import java.io.File
import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.withContext
/** The account sheet and Computers & settings. Read-only: no test confirms a sign-out, route, removal or reset. */
class AccountScreenTest {
@@ -258,6 +261,44 @@ class AccountScreenTest {
compose.waitUntil { "session" !in store.state.value.busy }
}
+ @Test fun explicitRenewalReplacesANegotiatingAccessAction() {
+ lateinit var store: AppStore
+ var cancelled = false
+ val cleanupStarted = CompletableDeferred<Unit>()
+ val releaseCleanup = CompletableDeferred<Unit>()
+ compose.setContent { store = viewModel() }
+ compose.waitUntil { !store.state.value.loading }
+ val target = CloudComputer(computer.id, computer.name, computer.signKey, online = true, access = "granted")
+ compose.runOnUiThread {
+ store.cloud = null
+ store.action("access") {
+ try { awaitCancellation() } finally {
+ withContext(NonCancellable) {
+ cleanupStarted.complete(Unit)
+ releaseCleanup.await()
+ cancelled = true
+ }
+ }
+ }
+ store.requestAccess(target)
+ }
+ compose.runOnIdle { assertFalse(cancelled) } // Ordinary repeated asks don't replace it.
+ compose.runOnUiThread { store.requestAccess(target, renew = true) }
+ compose.waitUntil { cleanupStarted.isCompleted }
+ compose.runOnIdle {
+ assertFalse(cancelled)
+ assertTrue("renewAccess" in store.state.value.busy)
+ assertNull(store.state.value.error) // Replacement hasn't reached the missing-cloud check.
+ }
+ compose.runOnUiThread { releaseCleanup.complete(Unit) }
+ compose.waitUntil { cancelled && "access" !in store.state.value.busy && "renewAccess" !in store.state.value.busy }
+ compose.runOnIdle {
+ // The replacement actually ran; merely cancelling the old job cannot produce this error.
+ assertEquals("Sign in to reach your account.", store.state.value.error)
+ assertNull(store.state.value.askingAccess)
+ }
+ }
+
private fun snapshot(name: String) {
if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") != "true") return
val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
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 559d2822..3951a346 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
@@ -63,7 +63,17 @@ 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, renew: Boolean = false) = action("access") {
+fun AppStore.requestAccess(target: CloudComputer, renew: Boolean = false) {
+ if (renew) {
+ action("renewAccess") {
+ // Await cancellation cleanup before replacing this phone's grant and request.
+ actions["access"]?.cancelAndJoin()
+ startAccess(target, renew = true)
+ }
+ } else startAccess(target, renew = false)
+}
+
+private fun AppStore.startAccess(target: CloudComputer, renew: Boolean) = action("access") {
mutableState.update { it.copy(askingAccess = target.computerId) }
try { askForAccess(target, renew) } finally { mutableState.update { it.copy(askingAccess = null) } }
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
index b722aa8a..07435672 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
@@ -1,4 +1,5 @@
import Foundation
+import os
/// An error from the Codync cloud: `{"error":{"code","message"}}`.
public struct CloudError: LocalizedError, Sendable, Equatable {
@@ -107,25 +108,37 @@ public struct CloudClient: Sendable {
struct Created: Decodable { var requestId: String; var expiresAt: Int64 }
let created: Created = try await request("POST", "v1/computers/\(id)/access-requests", body: ["commit": commit], signed: true)
- var hostNonce: Data?
- while hostNonce == nil {
- let status = try await accessStatus(created.requestId)
- guard status.status == .pending else {
- throw CloudError(status: 0, code: status.status == .expired ? "requestExpired" : status.status.rawValue, message: "The computer didn't take the request.")
- }
- if let raw = status.hostNonce {
- guard let n = Data(base64URL: raw), n.count == 32 else { throw CloudError(status: 0, code: "badNonce", message: nil) }
- hostNonce = n
- } else {
- guard Int64(Date.now.timeIntervalSince1970 * 1000) < created.expiresAt else {
- throw CloudError(status: 410, code: "requestExpired", message: nil)
+ do {
+ var hostNonce: Data?
+ while hostNonce == nil {
+ let status = try await accessStatus(created.requestId)
+ guard status.status == .pending else {
+ throw CloudError(status: 0, code: status.status == .expired ? "requestExpired" : status.status.rawValue, message: "The computer didn't take the request.")
+ }
+ if let raw = status.hostNonce {
+ guard let n = Data(base64URL: raw), n.count == 32 else { throw CloudError(status: 0, code: "badNonce", message: nil) }
+ hostNonce = n
+ } else {
+ guard Int64(Date.now.timeIntervalSince1970 * 1000) < created.expiresAt else {
+ throw CloudError(status: 410, code: "requestExpired", message: nil)
+ }
+ try await Task.sleep(for: pollInterval)
}
- try await Task.sleep(for: pollInterval)
}
+ try await send("POST", "v1/access-requests/\(created.requestId)/reveal", body: ["nonce": nD.base64URL], signed: true)
+ let code = RelayCrypto.sasCode(hostSignKey: hostKey, deviceKey: identity.deviceKey, deviceNonce: nD, hostNonce: hostNonce ?? Data())
+ return AccessTicket(requestId: created.requestId, expiresAt: created.expiresAt, code: code, computerId: id, signKey: signKey)
+ } catch {
+ // Cancellation must finish withdrawing the old nonce exchange before renewal starts.
+ await Task.detached {
+ do { try await self.cancelAccess(created.requestId) }
+ catch {
+ Logger(subsystem: "com.pokai.Codync", category: "Cloud").warning(
+ "Access request cleanup failed: \(error.localizedDescription, privacy: .public)")
+ }
+ }.value
+ throw error
}
- try await send("POST", "v1/access-requests/\(created.requestId)/reveal", body: ["nonce": nD.base64URL], signed: true)
- let code = RelayCrypto.sasCode(hostSignKey: hostKey, deviceKey: identity.deviceKey, deviceNonce: nD, hostNonce: hostNonce ?? Data())
- return AccessTicket(requestId: created.requestId, expiresAt: created.expiresAt, code: code, computerId: id, signKey: signKey)
}
public func accessStatus(_ requestId: String) async throws -> AccessStatus {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
index 8334afb9..a1406bb7 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -164,18 +164,23 @@ public final class AccountStore {
/// Asks the computer for access; the code arrives in `pendingAccess`, where it must match the one
/// the computer shows. The request runs here, not in the caller: it outlives a closed sheet, so the
/// computer never waits on a request nobody reveals, and asking again while it runs joins it
- /// instead of committing a second one.
+ /// instead of committing a second one. Explicit renewal cancels and joins that request first.
/// Approval is then picked up in the background and the computer joins `stores`.
public func requestAccess(_ id: ComputerID, renew: Bool = false) async throws {
- if let ask = asks[id], !ask.isCancelled {
+ if !renew, let ask = asks[id], !ask.isCancelled {
_ = try await ask.value
return
}
guard let cloud, let target = cloudComputers.first(where: { $0.computerId == id }) else {
throw CloudError(status: 404, code: "notFound", message: "That computer isn't in your account.")
}
+ let previous = asks[id]
accessPolls[id]?.cancel()
+ if renew { previous?.cancel() }
let ask = Task {
+ // Finish cancellation cleanup before revoking and creating the replacement.
+ if renew, let previous { _ = await previous.result }
+ try Task.checkCancellation()
if renew { try await cloud.revokeDeviceAccess(id) }
return try await cloud.requestAccess(id, signKey: target.signKey)
}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift b/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift
index f82d18e0..c4e4af15 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift
@@ -12,6 +12,8 @@ private final class RenewalCloudStub: URLProtocol {
var deviceKey = ""
var approved = false
var calls: [String] = []
+ var stallFirstRequest = false
+ var created = 0
}
static let state = OSAllocatedUnfairLock(initialState: State())
override class func canInit(with request: URLRequest) -> Bool { true }
@@ -23,6 +25,7 @@ private final class RenewalCloudStub: URLProtocol {
let method = request.httpMethod!
let snapshot = Self.state.withLock { state in
state.calls.append("\(method) \(path)")
+ if method == "POST", path.hasSuffix("/access-requests") { state.created += 1 }
return state
}
let id = RelayCrypto.computerId(signKey: renewalHostKey)
@@ -34,7 +37,10 @@ private final class RenewalCloudStub: URLProtocol {
} 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}"#
+ let rid = snapshot.stallFirstRequest && snapshot.created == 1 ? "initial" : "renewal"
+ json = #"{"requestId":"\#(rid)","expiresAt":4102444800000}"#
+ } else if path == "/v1/access-requests/initial" {
+ json = #"{"requestId":"initial","status":"pending"}"#
} else if path == "/v1/access-requests/renewal" {
json = #"{"requestId":"renewal","status":"\#(snapshot.approved ? "approved" : "pending")","hostNonce":"\#(Data(repeating: 9, count: 32).base64URL)"}"#
} else {
@@ -46,50 +52,89 @@ private final class RenewalCloudStub: URLProtocol {
}
}
-@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") })
+@Suite(.serialized) @MainActor
+struct AccessRenewalTests {
+ @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))
+ 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)
}
- #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 {
+
+ @Test func renewalCancelsANegotiatingRequestBeforeRevokingAndReplacingIt() 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, stallFirstRequest: true) }
+ 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 accounts = AccountStore(storage: storage, cloud: cloud)
+ defer { accounts.retire() }
+ await accounts.refreshCloud()
+ let id = RelayCrypto.computerId(signKey: renewalHostKey)
+ let first = Task { try await accounts.requestAccess(id) }
+ for _ in 0..<100 where !RenewalCloudStub.state.withLock({ $0.calls.contains("GET /v1/access-requests/initial") }) {
+ try await Task.sleep(for: .milliseconds(20))
+ }
+ #expect(RenewalCloudStub.state.withLock { $0.created } == 1)
+ // A normal second ask joins the negotiating request rather than creating another one.
+ let joined = Task { try await accounts.requestAccess(id) }
try await Task.sleep(for: .milliseconds(20))
+ #expect(RenewalCloudStub.state.withLock { $0.created } == 1)
+ try await accounts.requestAccess(id, renew: true)
+ _ = await first.result
+ _ = await joined.result
+ let calls = RenewalCloudStub.state.withLock { $0.calls }
+ let cancelled = try #require(calls.firstIndex(of: "DELETE /v1/access-requests/initial"))
+ let revoked = try #require(calls.firstIndex(of: "DELETE /v1/computers/\(id)/grants/own-grant"))
+ let replacement = try #require(calls.lastIndex(of: "POST /v1/computers/\(id)/access-requests"))
+ #expect(cancelled < revoked && revoked < replacement)
+ #expect(RenewalCloudStub.state.withLock { $0.created } == 2)
}
- #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/docs/plans/2026-10-22-ui-and-device-access.md b/docs/plans/2026-10-22-ui-and-device-access.md
index 19646d55..16c7ec31 100644
--- a/docs/plans/2026-10-22-ui-and-device-access.md
+++ b/docs/plans/2026-10-22-ui-and-device-access.md
@@ -187,3 +187,28 @@ the held mascot worktree's development app remains available until its push.
success. This is Android's queued context handoff; iOS awaits its own transition.
- A memory-layer fullness finding from the pre-#194 comparison is being checked by
the original memory owner before #195 merges. CI/review are not bypassed.
+
+## Final renewal review fix
+
+Adopted the memory owner's `019b4876` implementation, including per-layer prompt
+labels and codync-mem 0.3.1, instead of the equivalent local draft. Android's queued
+approval fix is pushed as `fb82a9d1`.
+
+Explicit renewal now cancels and joins any earlier negotiation before revoking this
+phone's grants and requesting replacement access. iOS also withdraws failed/cancelled
+nonce exchanges and logs cleanup failures while retaining the original error. Normal
+repeated requests still join or ignore the active negotiation.
+
+Three narrow reviews found no correctness/refactor defect. The completeness review's
+optional cleanup-completion coverage suggestion was verified as nonblocking. Android
+now has a NonCancellable cleanup barrier proving replacement waits for cleanup; its
+updated APK and targeted emulator test pass. iOS retains its passing endpoint-order
+regression (old request DELETE, own grant DELETE, replacement POST); a more elaborate
+URLProtocol completion barrier is not added. iOS tests pass 2/2, Android unit/build
+checks and two initial targeted emulator cases pass, and the hardened test passes
+1/1. A baseline iOS run failed until nonce cancellation cleanup was implemented.
+Test devices were stopped; the preexisting iPad was untouched.
+
+The speech/keyboard/module-size comments from the old pre-#194 comparison were
+independently verified to concern files identical to current main; they were resolved
+as outside this PR's current scope, not represented as fixed.