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(host): a resumed call stays open and a rename keeps its card's reactions
leepokai578c49049090
diff --git a/host/src/api/events/tests.rs b/host/src/api/events/tests.rsindex b24695f4..107bb2d0 100644--- a/host/src/api/events/tests.rs+++ b/host/src/api/events/tests.rs@@ -113,3 +113,47 @@ async fn catch_up_brings_an_artifact_renamed_while_the_client_was_offline() {assert!(events[1..].windows(2).all(|pair| pair[0]["rev"].as_i64() < pair[1]["rev"].as_i64()), "in rev order");assert_eq!(f.catch_up(f.hub.store.current_rev()).await[1..], [] as [Value; 0]);}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn renaming_an_artifact_keeps_the_reactions_its_card_gets_meanwhile() {+ let f = Fixture::new();+ f.add_bot("b");+ let id = uuid::Uuid::new_v4().to_string();+ let card = f+ .hub+ .add_entry(+ &crate::store::Lane::main("b"),+ crate::store::EntryKind::Agent,+ 0,+ &json!({"text": "Artifact: Old", "final": true, "artifact": {"id": id, "title": "Old", "updatedAt": 1}}),+ )+ .unwrap();+ let saved = json!({"id": id, "botId": "b", "title": "Old", "size": 1, "sha256": "x", "createdAt": 1, "updatedAt": 1,+ "entryId": card.id});+ f.hub.store.kv_set(&format!("artifact.b.{id}"), &saved.to_string()).unwrap();++ let emoji: [&'static str; 8] = ["👍", "🎉", "❤️", "🔥", "👀", "✅", "🙏", "💯"];+ let reacting: Vec<_> = emoji+ .iter()+ .map(|&e| {+ let (hub, card) = (f.hub.clone(), card.id.clone());+ std::thread::spawn(move || hub.react(&card, e).unwrap())+ })+ .collect();+ for n in 0..40 {+ let title = format!("Title {n}");+ crate::chat::artifacts::api(&f.hub, "renameArtifact", &json!({"botId": "b", "artifactId": id, "title": title}))+ .await+ .unwrap();+ }+ for t in reacting {+ t.join().unwrap();+ }+ let card = f.hub.store.entry(&card.id).unwrap();+ let mut reactions: Vec<String> = serde_json::from_value(card.data["reactions"].clone()).unwrap();+ reactions.sort();+ let mut all: Vec<String> = emoji.iter().map(|e| (*e).to_owned()).collect();+ all.sort();+ assert_eq!(reactions, all, "no rename wrote over a reaction");+ assert_eq!(card.data["artifact"]["title"], "Title 39");+}diff --git a/host/src/chat/artifacts.rs b/host/src/chat/artifacts.rsindex 9acbb86e..5f2d1b5b 100644--- a/host/src/chat/artifacts.rs+++ b/host/src/chat/artifacts.rs@@ -257,13 +257,18 @@ pub async fn api(hub: &Arc<Hub>, method: &str, b: &Value) -> Result<Value> {/// The artifact's newest card takes the new title too: older apps and a cache that never saw the rename show the card's.fn retitle_card(hub: &Hub, artifact: &Artifact) {- let Some(mut card) = artifact.entry_id.as_deref().and_then(|id| hub.store.entry(id)) else { return };- if card.data["artifact"]["id"] != artifact.id.as_str() {- return;+ let Some(id) = artifact.entry_id.as_deref() else { return };+ let retitled = hub.edit_entry(id, |card| {+ if card.data["artifact"]["id"] != artifact.id.as_str() {+ return Ok(false);+ }+ card.data["text"] = card_text(&artifact.title).into();+ card.data["artifact"]["title"] = artifact.title.clone().into();+ Ok(true)+ });+ if let Err(e) = retitled {+ tracing::info!(artifact = artifact.id, error = format!("{e:#}"), "couldn't retitle the artifact's card");}- card.data["text"] = card_text(&artifact.title).into();- card.data["artifact"]["title"] = artifact.title.clone().into();- hub.set_entry(&card.id, &card.data);}/// One chunk of an artifact's HTML, from `offset`.diff --git a/host/src/chat/calls/mod.rs b/host/src/chat/calls/mod.rsindex 484b6ba6..e2f46f16 100644--- a/host/src/chat/calls/mod.rs+++ b/host/src/chat/calls/mod.rs@@ -249,19 +249,32 @@ fn take_said(store: &Store, call: &str) -> Result<String> {/// `endCall`: the rest of the transcript (`raw`), the call's line in the chat, then a title written for it. A call/// ends once: an app trying again changes nothing.pub fn end(hub: &Arc<Hub>, bot: &str, call: &str, seconds: u64, raw: &Value) -> Result<Option<Entry>> {- let s = {+ end_when(hub, bot, call, raw, |_| Some(seconds))+}++/// Ends `call` if `length`, asked under the lock that marks it ended, gives its length in seconds; `None` keeps it+/// going. The sweep decides there, so a call its app resumed meanwhile isn't ended.+fn end_when(+ hub: &Arc<Hub>,+ bot: &str,+ call: &str,+ raw: &Value,+ length: impl FnOnce(Option<&CallState>) -> Option<u64>,+) -> Result<Option<Entry>> {+ let (s, seconds) = {let _one = STATE.locked();if hub.store.kv_get(&ended_key(call)).is_some() {return Ok(None);}let mut s = state(&hub.store, call);+ let Some(seconds) = length(s.as_ref()) else { return Ok(None) };if let Some(s) = s.as_mut() {append(s, transcript(raw));}hub.store.kv_set(&ended_key(call), "1")?;hub.store.kv_delete(&state_key(call))?;mark_open(&hub.store, call, false)?;- s+ (s, seconds)};let bot = s.as_ref().map_or(bot, |s| s.bot.as_str()).to_owned();let cfg = hub.store.bot(&bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?.config;diff --git a/host/src/chat/calls/sweep.rs b/host/src/chat/calls/sweep.rsindex d7c1bde4..26b5b806 100644--- a/host/src/chat/calls/sweep.rs+++ b/host/src/chat/calls/sweep.rs@@ -1,7 +1,7 @@//! Calls whose app went away (a crash, a phone switched off): the host keeps the calls in progress and ends one//! nothing happened on for a long while, writing its line, so what it carried never stays hidden without one.-use super::{STATE, end, state};+use super::{CallState, STATE, end_when, state};use crate::LockExt;use crate::hub::{BotStatus, Hub};use crate::store::{Store, now_ms};@@ -50,18 +50,24 @@ fn sweep(hub: &Arc<Hub>, now: i64) {}continue;};- let last = s.last.max(s.started).max(newest_entry(&hub.store, &s.bot, &call));- if now - last < ABANDONED_MS || busy(hub, &s.bot) {- continue;- }- let seconds = u64::try_from((last - s.started) / 1000).unwrap_or(0);- tracing::info!(call, bot = s.bot, "ending a call its app abandoned");- if let Err(e) = end(hub, &s.bot, &call, seconds, &Value::Null) {- tracing::warn!(call, error = format!("{e:#}"), "couldn't end an abandoned call");+ // Decided under the lock that ends it: its app may have resumed it since the read above.+ match end_when(hub, &s.bot, &call, &Value::Null, |s| abandoned(hub, &call, s?, now)) {+ Ok(Some(_)) => tracing::info!(call, bot = s.bot, "ended a call its app abandoned"),+ Ok(None) => {}+ Err(e) => tracing::warn!(call, error = format!("{e:#}"), "couldn't end an abandoned call"),}}}+/// How long the call lasted, if nothing happened on it for [`ABANDONED_MS`] by `now` and its bot isn't at work.+fn abandoned(hub: &Hub, call: &str, s: &CallState, now: i64) -> Option<u64> {+ let last = s.last.max(s.started).max(newest_entry(&hub.store, &s.bot, call));+ if now - last < ABANDONED_MS || busy(hub, &s.bot) {+ return None;+ }+ Some(u64::try_from((last - s.started) / 1000).unwrap_or(0))+}+/// When the call's newest message or reply was written (0 for none): the bot answering it is work on the call.fn newest_entry(store: &Store, bot: &str, call: &str) -> i64 {store.call_entries(bot, call, 1).ok().and_then(|e| e.first().map(|e| e.updated_at)).unwrap_or(0)@@ -107,6 +113,22 @@ mod tests {assert_eq!(open_calls(&hub.store), Vec::<String>::new());}+ #[tokio::test]+ async fn a_call_resumed_before_the_sweep_ends_it_stays_open() {+ let (hub, id) = hub_with_bot();+ heard(&hub.store, &id, "back").unwrap();+ let later = now_ms() + ABANDONED_MS + 1;+ // What the sweep read first: quiet for long enough.+ let read = state(&hub.store, "back").unwrap();+ assert!(abandoned(&hub, "back", &read, later).is_some());+ // Its app speaks again before the sweep takes the lock to end it.+ let mut resumed = state(&hub.store, "back").unwrap();+ resumed.last = later;+ save(&hub.store, "back", &resumed).unwrap();+ let ended = end_when(&hub, &id, "back", &Value::Null, |s| abandoned(&hub, "back", s?, later)).unwrap();+ assert!(ended.is_none() && is_live(&hub.store, "back"), "decided on the call as it is under the lock");+ }+#[tokio::test]async fn a_call_its_bot_works_on_stays_open() {let (hub, id) = hub_with_bot();diff --git a/host/src/hub.rs b/host/src/hub.rsindex 12114281..017706fe 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -468,6 +468,20 @@ impl Hub {}}+ /// Changes part of an entry and broadcasts it, reading and writing under the emission lock: an edit made+ /// meanwhile elsewhere (a reaction from another device) isn't written over. `edit` returns `false` to leave the+ /// entry as it is.+ pub fn edit_entry(&self, id: &str, edit: impl FnOnce(&mut Entry) -> Result<bool>) -> Result<Entry> {+ let _g = self.emit_lock.locked();+ let mut e = self.store.entry(id).ok_or_else(|| anyhow!("unknown message"))?;+ if !edit(&mut e)? {+ return Ok(e);+ }+ let e = self.store.update_entry(id, &e.data)?.ok_or_else(|| anyhow!("unknown message"))?;+ let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));+ Ok(e)+ }+pub fn set_usage(&self, usage: Usage) {let _ = self.events.send(json!({"type": "usage", "usage": usage}));*self.usage.locked() = usage;diff --git a/host/src/hub/reactions.rs b/host/src/hub/reactions.rsindex dc8bc723..f9776dbc 100644--- a/host/src/hub/reactions.rs+++ b/host/src/hub/reactions.rs@@ -3,7 +3,7 @@use super::Hub;use crate::store::{Entry, EntryKind};-use anyhow::{Result, anyhow, bail};+use anyhow::{Result, bail};use serde_json::json;/// The user's reactions per message: a handful of distinct emoji.@@ -14,47 +14,50 @@ impl Hub {/// A message keeps `reactions: []` once reacted to, so it never turns unread again.pub fn react(&self, id: &str, emoji: &str) -> Result<Entry> {let emoji = one_emoji(emoji)?;- let mut e = self.chat_message(id)?;- let mut reactions: Vec<String> = serde_json::from_value(e.data["reactions"].clone()).unwrap_or_default();- if let Some(i) = reactions.iter().position(|r| r == emoji) {- reactions.remove(i);- } else if reactions.len() >= MAX_REACTIONS {- bail!("a message takes at most {MAX_REACTIONS} reactions");- } else {- reactions.push(emoji.to_owned());- }- e.data["reactions"] = json!(reactions);- self.set_entry(id, &e.data).ok_or_else(|| anyhow!("couldn't save the reaction"))+ self.edit_entry(id, |e| {+ chat_message(e)?;+ let mut reactions: Vec<String> = serde_json::from_value(e.data["reactions"].clone()).unwrap_or_default();+ if let Some(i) = reactions.iter().position(|r| r == emoji) {+ reactions.remove(i);+ } else if reactions.len() >= MAX_REACTIONS {+ bail!("a message takes at most {MAX_REACTIONS} reactions");+ } else {+ reactions.push(emoji.to_owned());+ }+ e.data["reactions"] = json!(reactions);+ Ok(true)+ })}/// `bot` reacts to a chat message with `emoji`, replacing its earlier reaction there./// The message keeps the rev of its content (`contentRev`), so a message the user read stays read.pub fn bot_react(&self, id: &str, bot: &str, emoji: &str) -> Result<Entry> {let emoji = one_emoji(emoji)?;- let mut e = self.chat_message(id)?;- let mut reactions = e.data["botReactions"].as_array().cloned().unwrap_or_default();- if reactions.iter().any(|r| r["bot"] == bot && r["emoji"] == emoji) {- return Ok(e);- }- reactions.retain(|r| r["bot"] != bot);- reactions.push(json!({"bot": bot, "emoji": emoji}));- e.data["botReactions"] = json!(reactions);- if e.data["contentRev"].is_null() {- e.data["contentRev"] = e.rev.into();- }- self.set_entry(id, &e.data).ok_or_else(|| anyhow!("couldn't save the reaction"))+ self.edit_entry(id, |e| {+ chat_message(e)?;+ let mut reactions = e.data["botReactions"].as_array().cloned().unwrap_or_default();+ if reactions.iter().any(|r| r["bot"] == bot && r["emoji"] == emoji) {+ return Ok(false);+ }+ reactions.retain(|r| r["bot"] != bot);+ reactions.push(json!({"bot": bot, "emoji": emoji}));+ e.data["botReactions"] = json!(reactions);+ if e.data["contentRev"].is_null() {+ e.data["contentRev"] = e.rev.into();+ }+ Ok(true)+ })}+}- /// A message the user sees: theirs, or a bot's final one.- fn chat_message(&self, id: &str) -> Result<Entry> {- let e = self.store.entry(id).ok_or_else(|| anyhow!("unknown message"))?;- let visible =- e.kind == EntryKind::User.as_str() || (e.kind == EntryKind::Agent.as_str() && e.data["final"] == true);- if !visible {- bail!("only chat messages take reactions");- }- Ok(e)+/// Only a message the user sees takes reactions: theirs, or a bot's final one.+fn chat_message(e: &Entry) -> Result<()> {+ let visible =+ e.kind == EntryKind::User.as_str() || (e.kind == EntryKind::Agent.as_str() && e.data["final"] == true);+ if !visible {+ bail!("only chat messages take reactions");}+ Ok(())}fn one_emoji(emoji: &str) -> Result<&str> {