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(host): sync deleted bots after reconnecting

leepokai2cca8acedf03
diff --git a/apps/ios/Kit/Tests/CodyncUITests/BotDeletionSyncTests.swift b/apps/ios/Kit/Tests/CodyncUITests/BotDeletionSyncTests.swift
new file mode 100644
index 00000000..dba2af8c
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/BotDeletionSyncTests.swift
@@ -0,0 +1,50 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+@testable import CodyncUI
+
+@MainActor @Test func fullRefreshDeletionClearsCachedConversationSelectionAndDrafts() async throws {
+ let suite = "BotDeletionSyncTests.\(UUID().uuidString)"
+ let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let computer = Computer(id: UUID().uuidString, name: "Mac", signKey: "test")
+ let fake = FakeRemote(.ready(.direct))
+ await fake.setHello(#"{"hostId":"h1","name":"Mac","version":"\#(VersionMismatch.minHost)","os":"macos","backends":[],"rev":10}"#)
+ let store = BotStore(computer: computer, clientKind: "ios", storage: storage) { fake }
+ defer { store.retire() }
+ let bot = try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"gone","name":"Deleted while offline","rev":9}"#.utf8))
+ let entry = try JSONDecoder().decode(Entry.self, from: Data(#"{"id":"e1","botId":"gone","seq":1,"rev":8,"kind":"user","turn":1,"data":{"text":"cached"},"createdAt":1,"updatedAt":1}"#.utf8))
+ store.bots[bot.id] = bot
+ store.upsert(entry)
+ store.selection = bot.id
+ store.setComposerDraft("draft", for: bot.id)
+ store.setComposerDraft("thread draft", for: bot.id, thread: "root")
+ store.rev = 9
+ store.hostVersion = HostVersion(version: "2.11.1", minApp: nil)
+ let task = Task { await store.runEvents(HostClient(transport: fake)) }
+ defer { task.cancel() }
+ for _ in 0..<200 {
+ if await fake.subscribed { break }
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ #expect(await fake.subscribed)
+ #expect(store.rev == 0)
+ #expect(store.bots[bot.id] != nil) // Full refresh keeps the cache until updates arrive.
+ await fake.emit(#"{"type":"hello","hostId":"h1","rev":10}"#)
+ await fake.emit(#"{"type":"bot","bot":{"id":"gone","deleted":true,"rev":10}}"#)
+ for _ in 0..<200 {
+ if store.rev == 10 { break }
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ #expect(store.rev == 10)
+ #expect(store.bots[bot.id] == nil)
+ #expect(store.chat(bot.id).isEmpty)
+ #expect(store.selection == nil)
+ #expect(store.composerDraft(for: bot.id).isEmpty)
+ #expect(store.composerDraft(for: bot.id, thread: "root").isEmpty)
+ store.saveCache()
+ let restored = BotStore(computer: computer, clientKind: "ios", storage: storage) { fake }
+ defer { restored.retire() }
+ #expect(restored.bots[bot.id] == nil)
+ #expect(restored.chat(bot.id).isEmpty)
+}
diff --git a/host/src/api/events.rs b/host/src/api/events.rs
index 39bea01c..8f646b9b 100644
--- a/host/src/api/events.rs
+++ b/host/src/api/events.rs
@@ -47,6 +47,9 @@ impl Drop for IosClientGuard {
/// Event types only this computer's own apps receive.
const LOCAL_EVENTS: &[&str] = &["accessRequests", "cloud"];
+#[cfg(test)]
+mod tests;
+
/// Subscribes first, then yields a catch-up (everything after `since`, in rev order),
/// then live events. Duplicates are fine: clients upsert by id/rev. Shared by SSE and channels.
pub fn events_stream(
diff --git a/host/src/api/events/tests.rs b/host/src/api/events/tests.rs
new file mode 100644
index 00000000..71cfdfda
--- /dev/null
+++ b/host/src/api/events/tests.rs
@@ -0,0 +1,81 @@
+use super::*;
+use crate::remote::identity::Identity;
+use crate::store::{BotConfig, Store};
+use futures::StreamExt;
+use std::path::PathBuf;
+
+struct Fixture {
+ hub: Arc<Hub>,
+ dir: PathBuf,
+}
+
+impl Fixture {
+ fn new() -> Self {
+ let dir = std::env::temp_dir().join(format!("codync-sync-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ let hub = Hub::new(store, "sync-test".into(), Identity::load_or_create(&dir).unwrap(), "test".into(), 0);
+ Self { hub, dir }
+ }
+
+ fn add_bot(&self, id: &str) -> i64 {
+ let config: BotConfig = serde_json::from_value(json!({
+ "id": id, "name": id, "backend": "fixture", "cwd": self.dir,
+ }))
+ .unwrap();
+ self.hub.store.save_bot(&config).unwrap()
+ }
+
+ async fn catch_up(&self, since: i64) -> Vec<Value> {
+ let stream = events_stream(&self.hub, since, None, &Caller::Local).unwrap();
+ tokio::pin!(stream);
+ let mut events = Vec::new();
+ while let Ok(Some(event)) = tokio::time::timeout(std::time::Duration::from_millis(50), stream.next()).await {
+ events.push(event);
+ }
+ events
+ }
+}
+
+impl Drop for Fixture {
+ fn drop(&mut self) {
+ std::fs::remove_dir_all(&self.dir).unwrap();
+ }
+}
+
+#[tokio::test]
+async fn full_sync_removes_a_bot_deleted_while_the_client_was_offline() {
+ let f = Fixture::new();
+ f.add_bot("deleted");
+ f.add_bot("kept");
+ let deleted_rev = f.hub.store.delete_bot("deleted").unwrap();
+
+ // An app/host update rewinds the cursor to zero while keeping the cached roster.
+ let events = f.catch_up(0).await;
+ assert_eq!(events[0]["type"], "hello");
+ let mut cached = std::collections::HashSet::from(["deleted".to_owned()]);
+ for event in &events[1..] {
+ let bot = &event["bot"];
+ let id = bot["id"].as_str().unwrap();
+ if bot["deleted"] == true {
+ cached.remove(id);
+ assert_eq!(bot["rev"], deleted_rev);
+ } else {
+ cached.insert(id.to_owned());
+ }
+ }
+ assert_eq!(cached, std::collections::HashSet::from(["kept".to_owned()]));
+ assert!(events[1..].windows(2).all(|pair| pair[0]["rev"].as_i64() < pair[1]["rev"].as_i64()));
+}
+
+#[tokio::test]
+async fn incremental_sync_replays_deletions_only_after_the_saved_cursor() {
+ let f = Fixture::new();
+ let before = f.add_bot("deleted");
+ let deleted_rev = f.hub.store.delete_bot("deleted").unwrap();
+ let events = f.catch_up(before).await;
+ assert_eq!(events.len(), 2);
+ assert_eq!(events[1]["bot"]["deleted"], true);
+ assert_eq!(events[1]["rev"], deleted_rev);
+ assert_eq!(f.catch_up(deleted_rev).await.len(), 1);
+}
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 7c088a08..259a7bf4 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -7,7 +7,7 @@ use crate::remote::identity::Identity;
use crate::remote::push;
use crate::screen::Screen;
use crate::service;
-use crate::store::{BotConfig, BotRow, Entry, EntryKind, Lane, ReadScope, Store};
+use crate::store::{BotConfig, Entry, EntryKind, Lane, ReadScope, Store};
use crate::usage::Usage;
use anyhow::{Result, anyhow, bail};
use serde::Serialize;
@@ -18,6 +18,8 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{broadcast, watch};
+mod sync;
+
/// What a bot is doing right now (wire values: `idle` / `working` / `needsInput` / `error`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -159,35 +161,6 @@ impl Hub {
// MARK: bots
- pub fn bot_json(&self, row: &BotRow) -> Value {
- let cfg = &row.config;
- let mut v = serde_json::to_value(cfg).expect("BotConfig is plain data and always serializes");
- v["managedWorkspace"] = crate::agent::workspace::is_managed(cfg).into();
- let rt = if cfg.is_group() {
- self.group_runtime(cfg)
- } else {
- self.runtime.locked().get(&cfg.id).cloned().unwrap_or_default()
- };
- let last = self.store.last_message(&cfg.id);
- v["rev"] = row.rev.into();
- v["deleted"] = row.deleted.into();
- v["status"] = json!(rt.status);
- v["activity"] = rt.activity.into();
- v["startedAt"] = rt.started_at.into();
- v["workingChat"] = rt.lane.as_ref().map(|l| l.chat.clone()).into();
- v["workingThread"] = rt.lane.and_then(|l| l.thread).into();
- v["unread"] = self.store.unread(&cfg.id, row.read_rev, ReadScope::All).into();
- let preview = last.as_ref().map(|l| match &l.author {
- // A group names who spoke.
- Some(author) if cfg.is_group() => format!("{}: {}", self.bot_name(author), l.text),
- Some(_) => l.text.clone(),
- None => format!("You: {}", l.text),
- });
- v["lastMessage"] = preview.map(|p| crate::agent::acp::truncate(&p, 280)).into();
- v["lastAt"] = last.map_or(cfg.created_at, |l| l.at).into();
- v
- }
-
pub fn bot_name(&self, id: &str) -> String {
self.store.bot(id).ok().flatten().map_or_else(|| "A deleted bot".into(), |b| b.config.name)
}
@@ -208,16 +181,6 @@ impl Hub {
r
}
- pub fn bots_json(&self, since: i64) -> Result<Vec<Value>> {
- Ok(self
- .store
- .bots()?
- .iter()
- .filter(|b| b.rev > since && !(since == 0 && b.deleted))
- .map(|b| self.bot_json(b))
- .collect())
- }
-
pub fn create_bot(self: &Arc<Self>, mut cfg: BotConfig) -> Result<Value> {
cfg.id = uuid::Uuid::new_v4().to_string();
cfg.created_at = crate::store::now_ms();
diff --git a/host/src/hub/sync.rs b/host/src/hub/sync.rs
new file mode 100644
index 00000000..f224c138
--- /dev/null
+++ b/host/src/hub/sync.rs
@@ -0,0 +1,43 @@
+//! Bot snapshots shared by full, incremental and live synchronization.
+
+use super::Hub;
+use crate::LockExt;
+use crate::store::{BotRow, ReadScope};
+use anyhow::Result;
+use serde_json::{Value, json};
+
+impl Hub {
+ pub fn bot_json(&self, row: &BotRow) -> Value {
+ let cfg = &row.config;
+ let mut v = serde_json::to_value(cfg).expect("BotConfig is plain data and always serializes");
+ v["managedWorkspace"] = crate::agent::workspace::is_managed(cfg).into();
+ let rt = if cfg.is_group() {
+ self.group_runtime(cfg)
+ } else {
+ self.runtime.locked().get(&cfg.id).cloned().unwrap_or_default()
+ };
+ let last = self.store.last_message(&cfg.id);
+ v["rev"] = row.rev.into();
+ v["deleted"] = row.deleted.into();
+ v["status"] = json!(rt.status);
+ v["activity"] = rt.activity.into();
+ v["startedAt"] = rt.started_at.into();
+ v["workingChat"] = rt.lane.as_ref().map(|l| l.chat.clone()).into();
+ v["workingThread"] = rt.lane.and_then(|l| l.thread).into();
+ v["unread"] = self.store.unread(&cfg.id, row.read_rev, ReadScope::All).into();
+ let preview = last.as_ref().map(|l| match &l.author {
+ // A group names who spoke.
+ Some(author) if cfg.is_group() => format!("{}: {}", self.bot_name(author), l.text),
+ Some(_) => l.text.clone(),
+ None => format!("You: {}", l.text),
+ });
+ v["lastMessage"] = preview.map(|p| crate::agent::acp::truncate(&p, 280)).into();
+ v["lastAt"] = last.map_or(cfg.created_at, |l| l.at).into();
+ v
+ }
+
+ /// Full refreshes retain cached client state, so they need deletion records too.
+ pub fn bots_json(&self, since: i64) -> Result<Vec<Value>> {
+ Ok(self.store.bots()?.iter().filter(|b| b.rev > since).map(|b| self.bot_json(b)).collect())
+ }
+}