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): stabilize chat updates and queued sends

leepokaib345442a4a8a
diff --git a/kit/Sources/CodyncKit/Client/ChannelTransport.swift b/kit/Sources/CodyncKit/Client/ChannelTransport.swift
index b3f44592..72e8784e 100644
--- a/kit/Sources/CodyncKit/Client/ChannelTransport.swift
+++ b/kit/Sources/CodyncKit/Client/ChannelTransport.swift
@@ -43,7 +43,7 @@ public actor ChannelTransport: RemoteTransport {
private var streamIds: [UUID: UInt32] = [:]
private var puts: [String: CheckedContinuation<Void, Error>] = [:]
private var cancels: [String: CheckedContinuation<MailboxCancel, Never>] = [:]
- private var lists: [UUID: CheckedContinuation<[QueuedItem], Never>] = [:]
+ private var lists: [UUID: CheckedContinuation<[QueuedItem], Error>] = [:]
private var waiters: [UUID: CheckedContinuation<Void, Never>] = [:]
private var stateObservers: [UUID: AsyncStream<LinkState>.Continuation] = [:]
@@ -624,7 +624,10 @@ public actor ChannelTransport: RemoteTransport {
case "mbox.gone":
if let nonce = wire.nonce { cancels.removeValue(forKey: nonce)?.resume(returning: wire.state == "delivering" ? .delivering : .unknown) }
case "mbox.items":
- if let key = lists.keys.first { lists.removeValue(forKey: key)?.resume(returning: wire.items ?? []) }
+ if let key = lists.keys.first, let continuation = lists.removeValue(forKey: key) {
+ if let items = wire.items { continuation.resume(returning: items) }
+ else { continuation.resume(throwing: HostError.unreachable) }
+ }
case "mbox.delivered":
if let nonce = wire.nonce { broadcast(.delivered(nonce: nonce)) }
case "mbox.failed":
@@ -912,10 +915,10 @@ public actor ChannelTransport: RemoteTransport {
cancels.removeValue(forKey: nonce)?.resume(returning: .unknown)
}
- public func listQueued() async -> [QueuedItem] {
- guard let link = try? relaySocket() else { return [] }
+ public func listQueued() async throws -> [QueuedItem] {
+ let link = try relaySocket()
let key = UUID()
- return await withCheckedContinuation { c in
+ return try await withCheckedThrowingContinuation { (c: CheckedContinuation<[QueuedItem], Error>) in
lists[key] = c
link.outbox.yield(#"{"t":"mbox.list"}"#)
Task {
@@ -926,7 +929,7 @@ public actor ChannelTransport: RemoteTransport {
}
private func expireList(_ key: UUID) {
- lists.removeValue(forKey: key)?.resume(returning: [])
+ lists.removeValue(forKey: key)?.resume(throwing: HostError.unreachable)
}
}
diff --git a/kit/Sources/CodyncKit/Client/HostTransport.swift b/kit/Sources/CodyncKit/Client/HostTransport.swift
index 98153d13..2b8f42ae 100644
--- a/kit/Sources/CodyncKit/Client/HostTransport.swift
+++ b/kit/Sources/CodyncKit/Client/HostTransport.swift
@@ -36,7 +36,7 @@ public protocol RemoteTransport: HostTransport {
func computerUpdates() -> AsyncStream<Computer>
func enqueue(botId: String, text: String, clientNonce: String, threadId: String?) async throws
func cancelQueued(clientNonce: String) async -> MailboxCancel
- func listQueued() async -> [QueuedItem]
+ func listQueued() async throws -> [QueuedItem]
func mailboxEvents() -> AsyncStream<MailboxEvent>
/// Stops for good: closes sockets and ends every stream.
func shutdown() async
diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swift
index 663f3736..ab4ae22a 100644
--- a/kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/kit/Sources/CodyncUI/Store/BotStore.swift
@@ -582,10 +582,10 @@ public final class BotStore {
try await remote.enqueue(botId: botId, text: text, clientNonce: nonce, threadId: thread)
if let bot = bots[botId] { onSent?(bot) }
} catch MailboxError.hostOnline {
- // It came back meanwhile: send it the normal way once the link is up.
+ // Presence can race the stream state. Wait for the host's events channel
+ // before trying the normal API, instead of turning that race into a failure.
markLocal(nonce: nonce, botId: botId, status: "sending")
- try? await Task.sleep(for: .seconds(2))
- deliver(text, botId: botId, thread: thread, nonce: nonce)
+ await deliverWhenOnline(text, botId: botId, thread: thread, nonce: nonce)
} catch {
lastError = error.localizedDescription
markLocal(nonce: nonce, botId: botId, status: "failed")
@@ -594,6 +594,21 @@ public final class BotStore {
}
}
+ private func deliverWhenOnline(_ text: String, botId: String, thread: String?, nonce: String) async {
+ let deadline = ContinuousClock.now + .seconds(30)
+ while !retired, connection != .online, ContinuousClock.now < deadline {
+ try? await Task.sleep(for: .milliseconds(200))
+ }
+ guard !retired else { return }
+ guard connection == .online else {
+ lastError = "The computer came online, but the message couldn't be sent. Retry it when the connection is ready."
+ markLocal(nonce: nonce, botId: botId, status: "failed")
+ saveCache()
+ return
+ }
+ deliver(text, botId: botId, thread: thread, nonce: nonce)
+ }
+
/// Takes a waiting message back out of the mailbox, unless the computer already has it.
public func cancelQueued(_ entry: Entry) {
guard let nonce = entry.data.clientNonce, let remote = transport as? any RemoteTransport else { return }
@@ -626,7 +641,14 @@ public final class BotStore {
private func reconcileQueued(_ remote: any RemoteTransport) async {
let waiting = entries.values.flatMap { $0 }.filter { $0.data.status == "waiting" }
guard !waiting.isEmpty else { return }
- let held = Dictionary(await remote.listQueued().map { ($0.nonce, $0.state) }, uniquingKeysWith: { a, _ in a })
+ let heldItems: [QueuedItem]
+ do {
+ heldItems = try await remote.listQueued()
+ } catch {
+ log.debug("mailbox reconciliation deferred: \(error.localizedDescription)")
+ return
+ }
+ let held = Dictionary(heldItems.map { ($0.nonce, $0.state) }, uniquingKeysWith: { a, _ in a })
guard !retired else { return }
for e in waiting {
guard let nonce = e.data.clientNonce else { continue }
@@ -671,12 +693,14 @@ public final class BotStore {
public func discard(_ entry: Entry) {
if let nonce = entry.data.clientNonce { outgoingFiles[nonce] = nil }
entries[entry.botId]?.removeAll { $0.id == entry.id }
+ scheduleSave()
}
private func markLocal(nonce: String, botId: String, status: String) {
guard var list = entries[botId], let i = list.firstIndex(where: { $0.id == "local-\(nonce)" }) else { return }
list[i].data.status = status
entries[botId] = list
+ scheduleSave()
}
public func stop(_ botId: String) { perform { try await $0.stop(botId) } }
@@ -966,11 +990,11 @@ public final class BotStore {
public func saveCache() {
guard !retired else { return }
- // Keep the newest 200 entries per bot; older ones page in from the host. Messages waiting
- // in the mailbox stay too, so they can still be seen and cancelled after a relaunch.
+ // Keep the newest 200 entries per bot; older ones page in from the host. Local queued and
+ // failed messages stay visible so they can be cancelled or retried after a relaunch.
let kept = entries.values.flatMap { list in
list.filter { !$0.id.hasPrefix("local-") }.suffix(200)
- + list.filter { $0.id.hasPrefix("local-") && ["waiting", "delivering"].contains($0.data.status) }
+ + list.filter { $0.id.hasPrefix("local-") && ["waiting", "delivering", "failed"].contains($0.data.status) }
}
let cache = Cache(stamp: "\(Self.appBuild)/\(hello?.version ?? "")", hostId: hostId, rev: rev, bots: Array(bots.values), entries: kept)
if let data = try? JSONEncoder().encode(cache) {
diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swift
index edb10783..421b912b 100644
--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -172,8 +172,10 @@ struct UserBubble: View {
switch entry.data.status {
case "sending":
Text("Sending…").font(.caption2).foregroundStyle(Palette.tertiary)
- case "queued" where botWorking:
- Text("Waiting to send — it'll read this when it's done").font(.caption2).foregroundStyle(Palette.tertiary)
+ case "queued":
+ Text(botWorking ? "Queued until this response finishes" : "Queued")
+ .font(.caption2)
+ .foregroundStyle(Palette.tertiary)
case "failed":
HStack(spacing: 10) {
Text("Failed to send").foregroundStyle(Palette.danger)
diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swift
index 3832859b..a1e25c45 100644
--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -29,6 +29,7 @@ public struct ThreadView: View {
@State private var showRoutines = false
@State private var routineId: String?
@State private var routineRequest = UUID()
+ @State private var isAtBottom = true
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private var bot: Bot? { model.bots[botId] }
@@ -119,16 +120,19 @@ public struct ThreadView: View {
.frame(maxWidth: .infinity)
#endif
}
- .defaultScrollAnchor(.bottom)
+ .conversationInitialBottomAnchor()
.scrollDismissesKeyboard(.interactively)
.conversationScrollEdges()
+ .conversationBottomObserver($isAtBottom)
#if os(iOS)
.simultaneousGesture(TapGesture().onEnded { dismissChatKeyboard() })
#endif
.onChange(of: items.last?.id) { _, _ in
+ guard isAtBottom || items.last?.isUserMessage == true else { return }
proxy.scrollTo("bottom", anchor: .bottom)
}
.onChange(of: bot?.isWorking) { _, _ in
+ guard isAtBottom else { return }
proxy.scrollTo("bottom", anchor: .bottom)
}
}
@@ -446,18 +450,23 @@ struct ChatItem: Identifiable {
var lastAuthor: String?
for e in entries where e.isChat {
let date = e.date
+ let id = e.kind == "user" ? e.data.clientNonce.map { "user-\($0)" } ?? e.id : e.id
if lastDate.map({ date.timeIntervalSince($0) > 3600 }) ?? true {
- out.append(ChatItem(id: "sep-\(e.id)", kind: .separator(date)))
+ out.append(ChatItem(id: "sep-\(id)", kind: .separator(date)))
lastAuthor = nil
}
// In a group each bot is its own author.
let author = e.kind == "user" ? "user" : e.kind == "agent" ? "agent:\(e.data.author ?? "")" : e.kind
- out.append(ChatItem(id: e.id, kind: .entry(e, groupStart: author != lastAuthor)))
+ out.append(ChatItem(id: id, kind: .entry(e, groupStart: author != lastAuthor)))
lastAuthor = (author == "user" || e.kind == "agent") ? author : nil
lastDate = date
}
return out
}
+
+ var isUserMessage: Bool {
+ if case let .entry(entry, _) = kind { entry.kind == "user" } else { false }
+ }
}
/// The start of an empty group chat: who's in it and how the room works.
@@ -714,6 +723,26 @@ private struct DetailsPanel: View {
#endif
private extension View {
+ @ViewBuilder func conversationInitialBottomAnchor() -> some View {
+ if #available(iOS 18, macOS 15, *) {
+ defaultScrollAnchor(.bottom, for: .initialOffset)
+ } else {
+ defaultScrollAnchor(.bottom)
+ }
+ }
+
+ @ViewBuilder func conversationBottomObserver(_ isAtBottom: Binding<Bool>) -> some View {
+ if #available(iOS 18, macOS 15, *) {
+ onScrollGeometryChange(for: Bool.self) { geometry in
+ geometry.contentSize.height - geometry.visibleRect.maxY < 48
+ } action: { _, isAtBottomNow in
+ isAtBottom.wrappedValue = isAtBottomNow
+ }
+ } else {
+ self
+ }
+ }
+
@ViewBuilder func conversationScrollEdges() -> some View {
if #available(iOS 26, macOS 26, *) {
#if os(iOS)
diff --git a/kit/Tests/CodyncKitTests/ChannelTransportTests.swift b/kit/Tests/CodyncKitTests/ChannelTransportTests.swift
index 4ebd254e..e5303b6e 100644
--- a/kit/Tests/CodyncKitTests/ChannelTransportTests.swift
+++ b/kit/Tests/CodyncKitTests/ChannelTransportTests.swift
@@ -329,7 +329,7 @@ private func waitFor(_ states: AsyncStream<LinkState>, _ match: (LinkState) -> B
async let listed = t.listQueued()
#expect(try await relay.raw()["t"] as? String == "mbox.list")
await relay.push(["t": "mbox.items", "items": [["nonce": nonce, "exp": 1, "state": "queued"]]])
- #expect(await listed.map(\.nonce) == [nonce])
+ #expect(try await listed.map(\.nonce) == [nonce])
async let cancelled = t.cancelQueued(clientNonce: nonce)
#expect(try await relay.raw()["t"] as? String == "mbox.cancel")
diff --git a/kit/Tests/CodyncUITests/StoreTests.swift b/kit/Tests/CodyncUITests/StoreTests.swift
index 29846f3e..60cc5258 100644
--- a/kit/Tests/CodyncUITests/StoreTests.swift
+++ b/kit/Tests/CodyncUITests/StoreTests.swift
@@ -79,7 +79,7 @@ actor FakeRemote: RemoteTransport {
func enqueue(botId: String, text: String, clientNonce: String, threadId: String?) async throws { enqueued.append(clientNonce) }
func cancelQueued(clientNonce: String) async -> MailboxCancel { cancelResult }
- func listQueued() async -> [QueuedItem] { enqueued.map { QueuedItem(nonce: $0, exp: nil, state: "queued") } }
+ func listQueued() async throws -> [QueuedItem] { enqueued.map { QueuedItem(nonce: $0, exp: nil, state: "queued") } }
nonisolated func mailboxEvents() -> AsyncStream<MailboxEvent> {
AsyncStream { c in Task { await self.addMailbox(c) } }