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: wait through reconnects instead of showing an error
leepokaidcf1d76333a5
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swiftindex 6bf69028..6d18e804 100644--- a/apps/ios/App/CodyncApp.swift+++ b/apps/ios/App/CodyncApp.swift@@ -224,10 +224,10 @@ final class AppStore {Task { [weak accounts] indo {try await cloud.registerDevice(name: UIDevice.current.name, platform: "ios")- } catch let error as CloudError {+ } catch let error as CloudError where !error.isTransient {accounts?.lastError = error.localizedDescription} catch {- // Transient (network, token not ready): the next launch registers again.+ // Transient (network, busy cloud, token not ready): the next launch registers again.}await accounts?.refreshCloud()}diff --git a/apps/linux/src/client.rs b/apps/linux/src/client.rsindex 8f28e501..3123f6d9 100644--- a/apps/linux/src/client.rs+++ b/apps/linux/src/client.rs@@ -49,29 +49,43 @@ fn http() -> &'static reqwest::Client {C.get_or_init(reqwest::Client::new)}+/// How long a command keeps trying while the host can't be reached (it is restarting, say).+const PATIENCE: Duration = Duration::from_secs(20);+async fn call_async(method: String, body: Value) -> Result<Value, String> {let token = token().ok_or("The Codync host isn't set up on this computer.")?;- let res = http()- .post(format!("{}/api/{method}", base()))- .bearer_auth(token)- .json(&body)- .timeout(Duration::from_secs(- if matches!(- method.as_str(),- "agentAuth"- | "agentAuthenticate"- | "setAgentEnv"- | "installSkill"- | "installConnector"- ) {- 660- } else {- 120- },- ))- .send()- .await- .map_err(|_| "Can't reach the Codync host.".to_owned())?;+ let started = std::time::Instant::now();+ let res = loop {+ let sent = http()+ .post(format!("{}/api/{method}", base()))+ .bearer_auth(&token)+ .json(&body)+ .timeout(Duration::from_secs(+ if matches!(+ method.as_str(),+ "agentAuth"+ | "agentAuthenticate"+ | "setAgentEnv"+ | "installSkill"+ | "installConnector"+ ) {+ 660+ } else {+ 120+ },+ ))+ .send()+ .await;+ match sent {+ Ok(res) => break res,+ // Nothing was sent, so any command is safe to repeat while the host comes back.+ // `hello` is the probe that says why it can't be reached, so it answers at once.+ Err(e) if e.is_connect() && method != "hello" && started.elapsed() < PATIENCE => {+ tokio::time::sleep(Duration::from_millis(500)).await;+ }+ Err(_) => return Err("Can't reach the Codync host.".to_owned()),+ }+ };let ok = res.status().is_success();let v: Value = res.json().await.unwrap_or(Value::Null);if ok {diff --git a/apps/linux/src/rows.rs b/apps/linux/src/rows.rsindex 54921cca..a84d9ad6 100644--- a/apps/linux/src/rows.rs+++ b/apps/linux/src/rows.rs@@ -500,24 +500,44 @@ pub fn permission_card(ui: &App, st: &State, e: &Value, group: bool) -> gtk::Widif !kind.starts_with("allow") {l.add_css_class("danger-text");}+ l.set_hexpand(true);+ let spinner = gtk::Spinner::builder().visible(false).build();+ let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);+ row.append(&l);+ row.append(&spinner);let btn = gtk::Button::builder()- .child(&l)+ .child(&row).css_classes(["choice"]).build();let (entry_id, opt) = (e["id"].as_str().unwrap_or("").to_owned(),o["optionId"].clone(),);- let ui2 = ui.clone();- btn.connect_clicked(move |b| {- b.set_sensitive(false);- let ui3 = ui2.clone();+ let (ui2, choices2) = (ui.clone(), choices.clone());+ btn.connect_clicked(move |_| {+ // One answer per card: while it is on its way, the chosen row spins and the rest wait.+ choices2.set_sensitive(false);+ spinner.set_visible(true);+ spinner.start();+ let (ui3, choices3, spinner2) = (ui2.clone(), choices2.clone(), spinner.clone());client::call("respondPermission",json!({"entryId": entry_id, "optionId": opt}),move |r| {- if let Err(e) = r {- toast(&ui3, &e);+ let settle = move || {+ spinner2.stop();+ spinner2.set_visible(false);+ choices3.set_sensitive(true);+ };+ match r {+ Err(e) => {+ settle();+ toast(&ui3, &e);+ }+ // The card's own update follows on the events stream; hold the spinner until then.+ Ok(_) => {+ gtk::glib::timeout_add_seconds_local_once(2, settle);+ }}},);diff --git a/apps/macos/App/HostController.swift b/apps/macos/App/HostController.swiftindex 920c9990..a2a9a90b 100644--- a/apps/macos/App/HostController.swift+++ b/apps/macos/App/HostController.swift@@ -534,10 +534,10 @@ final class HostController {Task { [weak accounts] indo {try await cloud.registerDevice(name: Host.current().localizedName ?? "Mac", platform: "macos")- } catch let error as CloudError {+ } catch let error as CloudError where !error.isTransient {accounts?.lastError = error.localizedDescription} catch {- // Transient (network, token not ready): the next launch registers again.+ // Transient (network, busy cloud, token not ready): the next launch registers again.}await accounts?.refreshCloud()}diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex 875dbcd9..d2fa98a2 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -8,7 +8,7 @@ The conversation hides the navigation bar background and the top scroll-edge effDo not wrap those toolbar controls in `IconButtonStyle`, hand-sized rounded backgrounds or another glass effect. The account avatar is toolbar content, with the system supplying the enclosing surface. This is the explicit exception to the custom-chrome rule below.-Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort pinned first, then by recency. On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Long-press a heading and drag it onto another computer's section to reorder computers (VoiceOver: Move up / Move down); the order is saved on the device (`AccountStore.move`). The Mac shows a flat roster. There are no connection banners. The compact Mac rail uses a computer icon for the same menu. Conversation headers show a small connection label, with the computer name available in the header menu or help text. Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers.+Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. An action taken during a reconnect (back in the foreground, a new network, a drop still inside its grace) waits for the link, up to 20 seconds, instead of failing; while one waits, headers read `Connecting…` and the conversation's connection label shows a spinner. Calls that are safe to repeat (send, stop, approvals, pin, hide, mark as read, delete) are tried again when the link drops under them. Tapping while the header says Offline because the computer can't be reached starts a fresh connection attempt and waits for it, instead of failing until the backoff gets there; a computer the relay reports as off fails at once, since the relay says when it is back. A permission card shows a spinner on the chosen option, dims the others and takes no second answer until the computer has it. The Linux app and the TUI follow the same rule over loopback: a command the host can't be reached for is retried for up to 20 seconds behind their "Reconnecting…" indicator (the `hello` probe that explains an unreachable host still answers at once), and their permission cards spin on the chosen option. The "Something went wrong" dialog is left for a computer that is off, a refused device, the computer's own answers, and reconnects that outlast the wait. Background work (cloud refresh, device registration, automatic access requests) logs connection, busy-cloud and stale-token failures instead of showing them. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort pinned first, then by recency. On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Long-press a heading and drag it onto another computer's section to reorder computers (VoiceOver: Move up / Move down); the order is saved on the device (`AccountStore.move`). The Mac shows a flat roster. There are no connection banners. The compact Mac rail uses a computer icon for the same menu. Conversation headers show a small connection label, with the computer name available in the header menu or help text. Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers.Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `kit/Sources/CodyncUI/Thread/ThreadView.swift`, `Bots/ComputerFilterHeader.swift`, `Store/ComputerSelection.swift`, `Bots/BotRow.swift`.diff --git a/host/src/tui/app.rs b/host/src/tui/app.rsindex 1704135f..fae9c061 100644--- a/host/src/tui/app.rs+++ b/host/src/tui/app.rs@@ -25,6 +25,8 @@ pub enum Msg {#[derive(Clone)]pub enum After {Nothing,+ /// A permission card's answer arrived (or couldn't).+ Answered(String),Sent(String),Connection(String, super::connections::Step),Hello,@@ -702,6 +704,8 @@ pub struct App {pub shell: Option<Shell>,reading: HashSet<String>,history_busy: HashSet<String>,+ /// Permission cards whose answer is on its way, with the chosen option.+ pub answering: HashMap<String, String>,history_done: HashSet<String>,pub hint: Option<(String, Instant)>,}@@ -749,6 +753,7 @@ impl App {shell: None,reading: HashSet::new(),history_busy: HashSet::new(),+ answering: HashMap::new(),history_done: HashSet::new(),hint: None,}@@ -846,7 +851,11 @@ impl App {}pub fn animating(&self) -> bool {- !self.toasts.is_empty() || self.hint.is_some() || self.bots.values().any(|b| b.status == Status::Working)+ !self.toasts.is_empty()+ || self.hint.is_some()+ || !self.online+ || !self.answering.is_empty()+ || self.bots.values().any(|b| b.status == Status::Working)}fn select(&mut self, id: &str) {@@ -1053,6 +1062,13 @@ impl App {self.sent(&key, r);return;}+ if let After::Answered(entry) = after {+ self.answering.remove(&entry);+ if let Err(e) = r {+ self.flash(&e);+ }+ return;+ }if let After::Sheet(s) = after {self.on_sheet_reply(s, r);return;@@ -1087,7 +1103,7 @@ impl App {}};match after {- After::Nothing | After::Sheet(_) | After::Sent(_) | After::Connection(_, _) => {}+ After::Nothing | After::Answered(_) | After::Sheet(_) | After::Sent(_) | After::Connection(_, _) => {}After::Installed => {self.error = None;self.flash("Host installed; connecting…");@@ -1647,7 +1663,16 @@ impl App {}fn answer(&mut self, entry: &str, option: &str) {- self.call("respondPermission", json!({"entryId": entry, "optionId": option}), After::Nothing);+ // One answer per card: while it is on its way, the card spins and takes no other.+ if self.answering.contains_key(entry) {+ return;+ }+ self.answering.insert(entry.to_owned(), option.to_owned());+ self.call(+ "respondPermission",+ json!({"entryId": entry, "optionId": option}),+ After::Answered(entry.to_owned()),+ );}fn answer_kind(&mut self, key: char) {diff --git a/host/src/tui/net.rs b/host/src/tui/net.rsindex 94e2968f..b075827e 100644--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@ -24,6 +24,9 @@ const SLOW: [&str; 7] = [pub const NOT_INSTALLED: &str = "The Codync host isn't set up on this computer yet.";+/// How long a command keeps trying while the host can't be reached (it is restarting, say).+const PATIENCE: Duration = Duration::from_secs(20);+#[derive(Clone)]pub struct Client {base: Arc<str>,@@ -50,20 +53,26 @@ impl Client {pub async fn call(&self, method: &str, body: &Value) -> Result<Value, String> {let token = self.token().ok_or(NOT_INSTALLED)?;- let res = crate::http()- .post(format!("{}/api/{method}", self.base))- .bearer_auth(token)- .json(body)- .timeout(Duration::from_secs(if SLOW.contains(&method) { 11 * 60 } else { 60 }))- .send()- .await- .map_err(|e| {- if e.is_timeout() {- "The host took too long to answer.".to_owned()- } else {- format!("Can't reach codync-host at {}. Is it running?", self.base)+ let started = std::time::Instant::now();+ let res = loop {+ let sent = crate::http()+ .post(format!("{}/api/{method}", self.base))+ .bearer_auth(&token)+ .json(body)+ .timeout(Duration::from_secs(if SLOW.contains(&method) { 11 * 60 } else { 60 }))+ .send()+ .await;+ match sent {+ Ok(res) => break res,+ // Nothing was sent, so any command is safe to repeat while the host comes back.+ // `hello` is the probe that says why it can't be reached, so it answers at once.+ Err(e) if e.is_connect() && method != "hello" && started.elapsed() < PATIENCE => {+ tokio::time::sleep(Duration::from_millis(500)).await;}- })?;+ Err(e) if e.is_timeout() => return Err("The host took too long to answer.".to_owned()),+ Err(_) => return Err(format!("Can't reach codync-host at {}. Is it running?", self.base)),+ }+ };let ok = res.status().is_success();let v: Value = res.json().await.unwrap_or(Value::Null);if ok { Ok(v) } else { Err(v["error"].as_str().unwrap_or("The host refused that.").to_owned()) }@@ -258,6 +267,22 @@ fn free_path(dir: &std::path::Path, name: &str) -> PathBuf {#[cfg(test)]mod tests {+ #[tokio::test]+ async fn call_waits_for_a_restarting_host() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ // A free port with nothing listening yet: the host is restarting.+ let addr = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap();+ let client = super::Client::new(&format!("http://{addr}"), Some("t"));+ let call = tokio::spawn(async move { client.call("stop", &serde_json::json!({})).await });+ tokio::time::sleep(std::time::Duration::from_millis(700)).await;+ assert!(!call.is_finished());+ let listener = tokio::net::TcpListener::bind(addr).await.unwrap();+ let (mut socket, _) = listener.accept().await.unwrap();+ let _ = socket.read(&mut [0; 4096]).await.unwrap();+ socket.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\n{}").await.unwrap();+ assert_eq!(call.await.unwrap(), Ok(serde_json::json!({})));+ }+#[test]fn saved_files_never_overwrite_or_escape() {let dir = std::env::temp_dir().join(format!("codync-dl-{}", uuid::Uuid::new_v4()));diff --git a/host/src/tui/view.rs b/host/src/tui/view.rsindex 259ba1c3..cfe4f103 100644--- a/host/src/tui/view.rs+++ b/host/src/tui/view.rs@@ -1155,7 +1155,7 @@ fn entry_lines(gap(out);if e.pending() {// A card in a group is its asking bot's.- permission_card(out, e, author.unwrap_or(b), width, &app.home);+ permission_card(out, app, e, author.unwrap_or(b), width);} else {decided_line(out, e);}@@ -1276,8 +1276,11 @@ fn option_keys(opts: &[(String, String, String)]) -> Vec<String> {.collect()}-fn permission_card(out: &mut Built, e: &Entry, b: &Bot, width: usize, home: &str) {+fn permission_card(out: &mut Built, app: &App, e: &Entry, b: &Bot, width: usize) {let t = theme();+ let home = app.home.as_str();+ // The option whose answer is on its way: it spins, the others dim.+ let answering = app.answering.get(&e.id);let bw = width.saturating_sub(1).max(20);let inner = bw.saturating_sub(4);let title = e.data["title"].as_str().unwrap_or("Use a tool");@@ -1356,13 +1359,15 @@ fn permission_card(out: &mut Built, e: &Entry, b: &Bot, width: usize, home: &str*used = 0;};for (i, (id, name, kind)) in opts.iter().enumerate() {- let key = format!(" {} ", keys[i]);+ let key = format!(" {} ", if answering == Some(id) { spin(app) } else { keys[i].as_str() });let label = format!("{name} ");let bw_ = w(&key) + w(&label);if used > 0 && used + bw_ + 1 > inner {flush(out, &mut line, &mut used, &mut pending);}- let style = if i == 0 {+ let style = if answering.is_some_and(|a| a != id) {+ t.dim.patch(t.btn)+ } else if i == 0 {t.btn_primary} else if kind.starts_with("reject") {t.red.patch(t.btn)diff --git a/kit/Sources/CodyncKit/Client/CloudClient.swift b/kit/Sources/CodyncKit/Client/CloudClient.swiftindex adf609bd..83b884ce 100644--- a/kit/Sources/CodyncKit/Client/CloudClient.swift+++ b/kit/Sources/CodyncKit/Client/CloudClient.swift@@ -21,6 +21,10 @@ public struct CloudError: LocalizedError, Sendable, Equatable {default: message ?? "Codync cloud error (\(code))"}}++ /// A busy or failing cloud, or a session token that wasn't fresh yet: trying again later+ /// settles it, so background work (launch, foreground refresh) keeps it out of the error dialog.+ public var isTransient: Bool { status >= 500 || status == 429 || status == 401 }}/// The user-facing `/v1` API (§8.4): account, devices, computers, access requests, claims.diff --git a/kit/Sources/CodyncKit/Client/HostTransport.swift b/kit/Sources/CodyncKit/Client/HostTransport.swiftindex 2b8f42ae..1f505495 100644--- a/kit/Sources/CodyncKit/Client/HostTransport.swift+++ b/kit/Sources/CodyncKit/Client/HostTransport.swift@@ -59,6 +59,14 @@ public enum HostError: LocalizedError, Sendable, Equatable {case .upgradeRequired: "Update Codync to connect to this computer."}}++ /// The link failed, not the request: the same call can work once the computer is reachable again.+ public var isTransient: Bool {+ switch self {+ case .unreachable, .computerOffline: true+ default: false+ }+ }}/// Today's HTTP API on loopback: the Mac talking to its own host, or through an SSH tunnel.diff --git a/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift b/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swiftindex faf189b5..dd31e221 100644--- a/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift+++ b/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift@@ -21,7 +21,7 @@ public struct ComputerFilterHeader: View {}private var stores: [BotStore] { selection.shown.compactMap { accounts.store(for: $0) } }- private var summary: String { ConnectionSummary(connections: stores.map(\.connection)).text }+ private var summary: String { ConnectionSummary(connections: stores.map(\.shownConnection)).text }public var body: some View {#if os(iOS)@@ -102,7 +102,7 @@ public struct ComputerFilterHeader: View {public extension BotStore {var connectionLabel: String {- switch connection {+ switch shownConnection {case .online: "Connected"case .connecting: "Connecting…"case .computerOffline, .offline: "Offline"diff --git a/kit/Sources/CodyncUI/Store/AccountStore.swift b/kit/Sources/CodyncUI/Store/AccountStore.swiftindex cdbfdca1..8ee1fe92 100644--- a/kit/Sources/CodyncUI/Store/AccountStore.swift+++ b/kit/Sources/CodyncUI/Store/AccountStore.swift@@ -177,11 +177,11 @@ public final class AccountStore {guard !retired else { return }if list != cloudComputers { Motion.animate { cloudComputers = list } }if asksForAccess { await askForAccess() }- } catch let error as CloudError {+ } catch let error as CloudError where !error.isTransient {lastError = error.localizedDescription} catch {- // Runs on every launch and foreground: a dropped connection or a token not ready yet- // fixes itself on the next refresh, so only the cloud's own answers reach the dialog.+ // Runs on every launch and foreground: a dropped connection, a busy cloud or a token+ // not ready yet fixes itself on the next refresh, so only answers that stay reach the dialog.log.info("cloud refresh failed: \(error.localizedDescription, privacy: .public)")}}@@ -239,8 +239,12 @@ public final class AccountStore {asked.insert(computer.computerId)do {_ = try await requestAccess(computer.computerId)- } catch {+ } catch let error as CloudError where !error.isTransient {lastError = error.localizedDescription+ } catch {+ // Asked without a tap: a connection or cloud hiccup isn't worth a dialog.+ // The computer stays in the list, where it can be asked by hand.+ log.info("access request failed: \(error.localizedDescription, privacy: .public)")}}}diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swiftindex 21ac3bf8..3151f8e2 100644--- a/kit/Sources/CodyncUI/Store/BotStore.swift+++ b/kit/Sources/CodyncUI/Store/BotStore.swift@@ -45,6 +45,10 @@ public final class BotStore {private static let initialConnectionGrace: Duration = .seconds(1)private var heldDrop: Connection?private var dropTimer: Task<Void, Never>?+ /// How long an action waits for a reconnect before it gives up.+ private static let actionPatience: Duration = .seconds(20)+ /// Actions waiting for the link to come back.+ private var waiting = 0public private(set) var hostRoute: HostRoute?public private(set) var client: HostClient?public private(set) var hello: Hello?@@ -146,6 +150,10 @@ public final class BotStore {if case .computerOffline = heldDrop ?? connection { computer.boxKey != nil && transport is any RemoteTransport } else { false }}+ /// What headers show: a reconnect the grace period keeps quiet reads "Connecting…"+ /// as soon as an action is waiting on it.+ public var shownConnection: Connection { waiting > 0 && connection == .online ? .connecting : connection }+public var hostName: String { hello?.name ?? computer.name }/// Roster order: pinned first (manual order not tracked yet), then most recent activity.@@ -554,9 +562,55 @@ public final class BotStore {// MARK: actions- private func require() throws -> HostClient {- guard !retired, let client, connection == .online else { throw HostError.unreachable }- return client+ /// The client while the link is really up: not during a reconnect the grace period keeps+ /// quiet, nor right after coming back to the foreground, when the old link is already gone.+ private var live: HostClient? {+ connection == .online && heldDrop == nil && eventsTask != nil && !retired ? client : nil+ }++ /// The client once the link is up. A reconnect in progress is waited out (headers show it,+ /// see `shownConnection`), and an unreachable computer gets one fresh attempt first. A computer+ /// that is off or refusing this device throws at once; so does a reconnect that outlasts `deadline`.+ private func ready(until deadline: ContinuousClock.Instant = .now + BotStore.actionPatience) async throws -> HostClient {+ var counted = false+ var retried = false+ defer { if counted { Motion.animate { waiting -= 1 } } }+ while !retired {+ if let live { return live }+ switch connection {+ case .online, .connecting: break+ case .offline where !retried:+ // The link retries on a backoff of up to 30 s: with someone waiting, try now.+ retried = true+ restartStream()+ case .offline, .unpaired: throw HostError.unreachable+ // The relay reports when it comes back, so there is no attempt of ours to wait for.+ case let .computerOffline(lastSeen): throw HostError.computerOffline(lastSeen: lastSeen)+ case let .unauthorized(message): throw HostError.unauthorized(message)+ }+ guard ContinuousClock.now < deadline else { break }+ if !counted {+ counted = true+ Motion.animate { waiting += 1 }+ }+ try await Task.sleep(for: .milliseconds(100))+ }+ throw HostError.unreachable+ }++ /// Runs `op` once the link is up. With `replay`, only for calls the computer can safely get+ /// twice, a call the link dropped under is tried again after the reconnect.+ private func withLink<T>(replay: Bool = false, _ op: @MainActor (HostClient) async throws -> T) async throws -> T {+ let deadline = ContinuousClock.now + Self.actionPatience+ while true {+ let client = try await ready(until: deadline)+ do {+ return try await op(client)+ } catch let error as HostError where replay && error.isTransient && ContinuousClock.now < deadline {+ log.info("retrying after: \(error.localizedDescription)")+ try await Task.sleep(for: .milliseconds(500))+ }+ }}/// `thread`: reply in the thread on that main-chat message.@@ -589,19 +643,21 @@ public final class BotStore {private func deliver(_ text: String, botId: String, thread: String?, nonce: String) {Task {do {- let client = try require()- var ids: [String]?- if let files = outgoingFiles[nonce] {- // A fresh upload per attempt: a retry never appends to a half-sent file.- ids = []- for file in files {- let id = UUID().uuidString- try await client.upload(botId: botId, id: id, name: file.name, data: file.data)- Self.cacheAttachment(id, file.data)- ids?.append(id)+ // Safe to repeat: the computer skips a nonce it already has.+ let e = try await withLink(replay: true) { client in+ var ids: [String]?+ if let files = self.outgoingFiles[nonce] {+ // A fresh upload per attempt: a retry never appends to a half-sent file.+ ids = []+ for file in files {+ let id = UUID().uuidString+ try await client.upload(botId: botId, id: id, name: file.name, data: file.data)+ Self.cacheAttachment(id, file.data)+ ids?.append(id)+ }}+ return try await client.send(botId: botId, text: text, clientNonce: nonce, threadId: thread, attachments: ids)}- let e = try await client.send(botId: botId, text: text, clientNonce: nonce, threadId: thread, attachments: ids)outgoingFiles[nonce] = nilupsert(e)if let bot = bots[botId] { onSent?(bot) }@@ -626,7 +682,8 @@ public final class BotStore {markLocal(nonce: nonce, botId: botId, status: "sending")await deliverWhenOnline(text, botId: botId, thread: thread, nonce: nonce)} catch {- lastError = error.localizedDescription+ // A dropped relay link: the message's own "Failed to send" and Resend say enough.+ if (error as? HostError)?.isTransient != true { lastError = error.localizedDescription }markLocal(nonce: nonce, botId: botId, status: "failed")}saveCache()@@ -713,7 +770,7 @@ public final class BotStore {public func attachmentData(_ file: Attachment, bot botId: String) async -> Data? {guard let url = Self.attachmentCache(file.id) else { return nil }if let data = try? Data(contentsOf: url) { return data }- guard let client = try? require(), let data = try? await client.readUpload(botId: botId, id: file.id) else { return nil }+ guard let client = live, let data = try? await client.readUpload(botId: botId, id: file.id) else { return nil }Self.cacheAttachment(file.id, data)return data}@@ -742,7 +799,7 @@ public final class BotStore {scheduleSave()}- public func stop(_ botId: String) { perform { try await $0.stop(botId) } }+ public func stop(_ botId: String) { perform(replay: true) { try await $0.stop(botId) } }public func logCall(_ botId: String, seconds: Int) { perform { try await $0.logCall(botId, seconds: seconds) } }public func newSession(_ botId: String) { perform { try await $0.newSession(botId) } }@@ -750,12 +807,12 @@ public final class BotStore {/// Takes control from bots (they can still look) or hands it back.public func screenTakeover(_ on: Bool) {- perform { [weak self] in self?.screen = try await $0.screenTakeover(on) }+ perform(replay: true) { [weak self] in self?.screen = try await $0.screenTakeover(on) }}/// Only the computer itself may turn remote screen on (the Mac menu).public func setScreenEnabled(_ on: Bool) async throws {- screen = try await require().setScreenEnabled(on)+ screen = try await ready().setScreenEnabled(on)}/// Quick reactions offered on every message (Slack's hover bar).@@ -773,8 +830,23 @@ public final class BotStore {}}+ /// Permission cards whose answer is on its way, with the chosen option: the card shows+ /// a spinner on it and takes no second answer.+ public private(set) var answering: [String: String] = [:]+public func respond(_ entry: Entry, option: String?) {- perform { try await $0.respondPermission(entryId: entry.id, optionId: option) }+ guard answering[entry.id] == nil else { return }+ Motion.animate { answering[entry.id] = option ?? "" }+ Task {+ do {+ try await withLink(replay: true) { try await $0.respondPermission(entryId: entry.id, optionId: option) }+ // The card's own update follows on the events stream; hold the spinner until then.+ try? await Task.sleep(for: .seconds(2))+ } catch {+ lastError = error.localizedDescription+ }+ Motion.animate { answering[entry.id] = nil }+ }}struct ReadingScope: Hashable {@@ -812,11 +884,10 @@ public final class BotStore {Task {// Opening a cached conversation can race the foreground reconnect.// This background acknowledgement must never interrupt the conversation.- if connection != .online || heldDrop != nil {+ if live == nil {try? await Task.sleep(for: Self.initialConnectionGrace)}- guard !Task.isCancelled, !retired, isActive, heldDrop == nil,- let client = try? require() else { return }+ guard !Task.isCancelled, isActive, let client = live else { return }do {try await client.markRead(botId, threadId: thread)} catch {@@ -830,39 +901,39 @@ public final class BotStore {public func markAllRead(_ botId: String) {guard (bots[botId]?.unread ?? 0) > 0 else { return }bots[botId]?.unread = 0- perform { try await $0.markRead(botId, all: true) }+ perform(replay: true) { try await $0.markRead(botId, all: true) }}public func setPinned(_ bot: Bot, _ pinned: Bool) {var d = BotDraft(bot)d.pinned = pinnedbots[bot.id]?.pinned = pinned- perform { _ = try await $0.updateBot(d) }+ perform(replay: true) { _ = try await $0.updateBot(d) }}public func setHidden(_ bot: Bot, _ hidden: Bool) {var d = BotDraft(bot)d.hidden = hiddenbots[bot.id]?.hidden = hidden- perform { _ = try await $0.updateBot(d) }+ perform(replay: true) { _ = try await $0.updateBot(d) }}public func delete(_ bot: Bot) {bots[bot.id] = nilentries[bot.id] = nil- perform { try await $0.deleteBot(bot.id) }+ perform(replay: true) { try await $0.deleteBot(bot.id) }}/// Creates a group chat (or opens the one these bots already share) and selects it.public func createGroup(name: String, description: String = "", members: [String]) async throws -> Bot {- let group = try await require().createGroup(GroupDraft(name: name, description: description, members: members))+ let group = try await ready().createGroup(GroupDraft(name: name, description: description, members: members))bots[group.id] = groupselection = group.idreturn group}public func updateGroup(_ draft: GroupDraft) async throws {- let group = try await require().updateGroup(draft)+ let group = try await ready().updateGroup(draft)bots[group.id] = group}@@ -873,7 +944,7 @@ public final class BotStore {}public func save(_ draft: BotDraft) async throws -> Bot {- let client = try require()+ let client = try await ready()let bot = draft.id == nil ? try await client.createBot(draft) : try await client.updateBot(draft)bots[bot.id] = botreturn bot@@ -890,39 +961,39 @@ public final class BotStore {}public func marketConnectors(search: String, cursor: String? = nil) async throws -> (items: [MarketConnector], next: String?) {- try await require().marketConnectors(search: search, cursor: cursor)+ try await ready().marketConnectors(search: search, cursor: cursor)}public func marketSkills() async throws -> [MarketSkill] {- try await require().marketSkills()+ try await ready().marketSkills()}@discardableResultpublic func installConnector(_ item: MarketConnector, option: String, inputs: [String: String]) async throws -> InstalledConnector {- let c = try await require().installConnector(registryName: item.name, option: option, inputs: inputs)+ let c = try await ready().installConnector(registryName: item.name, option: option, inputs: inputs)await refreshPlugins()return c}@discardableResultpublic func addConnector(name: String, command: String?, url: String?, env: [String: String], headers: [String: String]) async throws -> InstalledConnector {- let c = try await require().addConnector(name: name, command: command, url: url, env: env, headers: headers)+ let c = try await ready().addConnector(name: name, command: command, url: url, env: env, headers: headers)await refreshPlugins()return c}public func importConnectors(config: String) async throws -> [InstalledConnector] {- let added = try await require().importConnectors(config: config)+ let added = try await ready().importConnectors(config: config)await refreshPlugins()return added}public func connectorSignIn(_ id: String) async throws -> ConnectorSignIn {- try await require().connectorSignIn(id)+ try await ready().connectorSignIn(id)}public func finishConnectorSignIn(state: String, code: String?, error: String?) async throws {- try await require().finishConnectorSignIn(state: state, code: code, error: error)+ try await ready().finishConnectorSignIn(state: state, code: code, error: error)await refreshPlugins()}@@ -936,22 +1007,22 @@ public final class BotStore {}public func removeConnector(_ id: String) async throws {- try await require().removeConnector(id)+ try await ready().removeConnector(id)await refreshPlugins()}public func installSkill(source: String) async throws {- try await require().installSkill(source: source)+ try await ready().installSkill(source: source)await refreshPlugins()}public func addSkill(name: String, description: String, instructions: String) async throws {- try await require().addSkill(name: name, description: description, instructions: instructions)+ try await ready().addSkill(name: name, description: description, instructions: instructions)await refreshPlugins()}public func removeSkill(_ id: String) async throws {- try await require().removeSkill(id)+ try await ready().removeSkill(id)await refreshPlugins()}@@ -962,7 +1033,7 @@ public final class BotStore {}public func listDirs(_ path: String?) async throws -> DirListing {- try await require().listDirs(path)+ try await ready().listDirs(path)}public func refreshUsage() async {@@ -978,10 +1049,11 @@ public final class BotStore {for e in older { upsert(e) }}- private func perform(_ op: @escaping @MainActor (HostClient) async throws -> Void) {+ /// Fire-and-forget actions; only what waiting and retrying couldn't settle reaches the dialog.+ private func perform(replay: Bool = false, _ op: @escaping @MainActor (HostClient) async throws -> Void) {Task {do {- try await op(try require())+ try await withLink(replay: replay, op)} catch {lastError = error.localizedDescription}diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swiftindex cf749c8c..41997740 100644--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -41,7 +41,7 @@ struct ChatRow: View {case "permission":VStack(alignment: .leading, spacing: 4) {if chat?.isGroup == true { AuthorLabel(botId: entry.data.author) }- PermissionCard(entry: entry, hostName: model.hostName) { option in+ PermissionCard(entry: entry, hostName: model.hostName, answering: model.answering[entry.id]) { option inmodel.respond(entry, option: option)}}diff --git a/kit/Sources/CodyncUI/Thread/PermissionCard.swift b/kit/Sources/CodyncUI/Thread/PermissionCard.swiftindex f69218e3..b2f02e6c 100644--- a/kit/Sources/CodyncUI/Thread/PermissionCard.swift+++ b/kit/Sources/CodyncUI/Thread/PermissionCard.swift@@ -6,6 +6,8 @@ import SwiftUIstruct PermissionCard: View {let entry: Entrylet hostName: String+ /// The option whose answer is on its way to the computer, if any.+ var answering: String?let respond: (String?) -> Void@State private var expanded = false@@ -94,14 +96,20 @@ struct PermissionCard: View {ForEach(Array(options.enumerated()), id: \.element.id) { i, o inif i > 0 { Rectangle().fill(Palette.border).frame(height: 0.5) }Button { respond(o.optionId) } label: {- Text(label(o))- .font(.body.weight(o.kind == "allow_once" ? .semibold : .regular))- .foregroundStyle(o.kind.hasPrefix("allow") ? Palette.text : Palette.danger)- .frame(maxWidth: .infinity, minHeight: 46, alignment: .leading)- .padding(.horizontal, 14)- .contentShape(Rectangle())+ HStack(spacing: 8) {+ Text(label(o))+ .font(.body.weight(o.kind == "allow_once" ? .semibold : .regular))+ .foregroundStyle(o.kind.hasPrefix("allow") ? Palette.text : Palette.danger)+ Spacer(minLength: 0)+ if answering == o.optionId { Spinner(size: 14) }+ }+ .frame(maxWidth: .infinity, minHeight: 46, alignment: .leading)+ .padding(.horizontal, 14)+ .contentShape(Rectangle())}.buttonStyle(.plain)+ .disabled(answering != nil)+ .opacity(answering == nil || answering == o.optionId ? 1 : 0.4)}}.background(Palette.background, in: RoundedRectangle(cornerRadius: 14, style: .continuous))diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swiftindex b75f69ff..0f58c1e2 100644--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -291,10 +291,15 @@ public struct ThreadView: View {private var connectionSubtitle: some View {HStack(spacing: 6) {- Image(systemName: connectionSymbol)- .font(.system(size: 8, weight: .medium))- .frame(width: 12)- .accessibilityHidden(true)+ Group {+ if model.shownConnection == .connecting {+ Spinner(size: 8)+ } else {+ Image(systemName: connectionSymbol).font(.system(size: 8, weight: .medium))+ }+ }+ .frame(width: 12)+ .accessibilityHidden(true)Text(model.connectionLabel).lineLimit(1).truncationMode(.middle)@@ -307,9 +312,7 @@ public struct ThreadView: View {}private var connectionSymbol: String {- guard model.connection == .online else {- return model.connection == .connecting ? "arrow.triangle.2.circlepath" : "wifi.slash"- }+ guard model.connection == .online else { return "wifi.slash" }switch model.hostRoute {case .relay: return "cloud"case .direct: return "wifi"@@ -319,7 +322,7 @@ public struct ThreadView: View {}private var connectionDescription: String {- switch model.connection {+ switch model.shownConnection {case .connecting: return "Connecting"case .computerOffline, .offline: return "Offline"case .unauthorized: return "No access"diff --git a/kit/Tests/CodyncUITests/StoreTests.swift b/kit/Tests/CodyncUITests/StoreTests.swiftindex 88eee99f..908ab778 100644--- a/kit/Tests/CodyncUITests/StoreTests.swift+++ b/kit/Tests/CodyncUITests/StoreTests.swift@@ -18,6 +18,10 @@ actor FakeRemote: RemoteTransport {private var isShutdown = falsefunc setReadFailure(_ fail: Bool) { failReadReceipts = fail }+ private(set) var calls: [String] = []+ private var failures: [String: Int] = [:]+ /// The next `count` calls of `method` fail as if the link dropped under them.+ func fail(_ method: String, times count: Int) { failures[method] = count }private(set) var enqueued: [String] = []var cancelResult = MailboxCancel.cancelled@@ -41,6 +45,11 @@ actor FakeRemote: RemoteTransport {private func respond(_ method: String, _ body: Data) throws -> Data {guard !isShutdown else { throw HostError.unreachable }+ calls.append(method)+ if let left = failures[method], left > 0 {+ failures[method] = left - 1+ throw HostError.unreachable+ }switch method {case "hello":return Data(#"{"hostId":"h1","name":"Mac","version":"3.0.0","os":"macos","backends":[],"rev":0}"#.utf8)@@ -461,3 +470,89 @@ extension FakeRemote {#expect(store.connection == .online)#expect(store.lastError == nil)}++@MainActor @Test func actionDuringReconnectWaitsInsteadOfFailing() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) { fake }+ defer { store.retire() }+ store.setActive(true)+ #expect(await until { await fake.subscribed })+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { store.connection == .online })+ // A drop still inside its grace: the header says connected, the link is gone.+ await fake.set(.connecting)+ #expect(await until { store.hostRoute == nil })+ store.stop("b1")+ #expect(await until { store.shownConnection == .connecting })+ #expect(await !fake.calls.contains("stop"))+ await fake.set(.ready(.relay))+ #expect(await until { await fake.eventSubscriptionCount == 2 })+ await fake.emit(botEvent("b1", name: "Bot", rev: 2))+ #expect(await until { await fake.calls.contains("stop") })+ #expect(store.shownConnection == .online)+ #expect(store.lastError == nil)+}++@MainActor @Test func droppedCallIsRetriedOnlyWhenSafeToRepeat() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) { fake }+ defer { store.retire() }+ store.setActive(true)+ #expect(await until { await fake.subscribed })+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { store.connection == .online })+ await fake.fail("stop", times: 1)+ store.stop("b1")+ #expect(await until { await fake.calls.filter { $0 == "stop" }.count == 2 })+ #expect(store.lastError == nil)+ // A new session can't be told apart from a second one, so it isn't sent twice.+ await fake.fail("newSession", times: 1)+ store.newSession("b1")+ #expect(await until { store.lastError != nil })+ #expect(await fake.calls.filter { $0 == "newSession" }.count == 1)+}++@MainActor @Test func offlineTapReconnectsBeforeGivingUp() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ // The first link can't reach the computer; a fresh attempt would.+ let down = FakeRemote(.failed("Can't reach"))+ let up = FakeRemote(.ready(.relay))+ var made = 0+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) {+ made += 1+ return made == 1 ? down : up+ }+ defer { store.retire() }+ store.setActive(true)+ #expect(await until { store.connection == .offline("Can't reach") })+ store.stop("b1")+ #expect(await until { await up.subscribed })+ await up.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { await up.calls.contains("stop") })+ #expect(store.lastError == nil)+}++@MainActor @Test func permissionAnswerShowsOnTheCardAndIsSentOnce() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) { fake }+ defer { store.retire() }+ store.setActive(true)+ #expect(await until { await fake.subscribed })+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { store.connection == .online })+ let card = Entry(id: "p1", seq: 1, botId: "b1", threadId: nil, rev: 1, kind: "permission", turn: 1,+ data: EntryData(status: "pending"), createdAt: 1, updatedAt: 1)+ store.respond(card, option: "allow")+ store.respond(card, option: "deny")+ #expect(store.answering["p1"] == "allow")+ #expect(await until { await fake.calls.contains("respondPermission") })+ try await Task.sleep(for: .milliseconds(100))+ #expect(await fake.calls.filter { $0 == "respondPermission" }.count == 1)+}