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(kit): remember unsent drafts for each bot

Sean Ferguson080b602fa204
diff --git a/apps/linux/src/ui.rs b/apps/linux/src/ui.rs
index 3848f253..e4951c53 100644
--- a/apps/linux/src/ui.rs
+++ b/apps/linux/src/ui.rs
@@ -22,6 +22,14 @@ pub struct Outgoing {
pub files: Vec<std::path::PathBuf>,
}
+type ComposerDestination = (String, Option<String>);
+
+#[derive(Clone, Default)]
+struct ComposerDraft {
+ text: String,
+ files: Vec<std::path::PathBuf>,
+}
+
#[derive(Default)]
pub struct State {
pub bots: HashMap<String, Value>,
@@ -44,6 +52,7 @@ pub struct State {
/// The host/app versions a newer-release reminder was shown for (once each).
reminded: Option<String>,
pub outbox: HashMap<String, Outgoing>,
+ drafts: HashMap<ComposerDestination, ComposerDraft>,
history_busy: HashSet<String>,
history_done: HashSet<String>,
}
@@ -51,6 +60,7 @@ pub struct State {
/// A message box: send, or stop while the chat (or thread) is working. In a group,
/// typing `@` suggests its bots.
pub struct Composer {
+ destination: RefCell<Option<ComposerDestination>>,
view: gtk::TextView,
attach_btn: gtk::Button,
/// Files picked or dropped for the next message, shown as chips above the box.
@@ -166,6 +176,7 @@ fn composer() -> Composer {
.build(),
);
Composer {
+ destination: RefCell::new(None),
view,
attach_btn,
files: RefCell::default(),
@@ -1078,6 +1089,7 @@ fn handle(ui: &App, ev: Event) {
if bot["deleted"].as_bool().unwrap_or(false) {
st.bots.remove(&id);
st.entries.remove(&id);
+ st.drafts.retain(|(bot, _), _| bot != &id);
if st.current.as_deref() == Some(&id) {
st.current = None;
st.open_thread = None;
@@ -1247,6 +1259,8 @@ pub fn render(ui: &App) {
compose::render(ui);
return;
}
+ restore_composer(ui, false);
+ restore_composer(ui, true);
render_chat(ui);
render_side(ui);
}
@@ -1962,6 +1976,53 @@ pub fn open_thread(ui: &App, root: &str) {
);
}
+/// Snapshot the old destination before replacing the shared widgets with the next draft.
+fn restore_composer(ui: &App, in_thread: bool) {
+ let destination = {
+ let st = ui.state.borrow();
+ st.current
+ .as_ref()
+ .filter(|id| st.bots.contains_key(*id))
+ .and_then(|id| {
+ if in_thread {
+ st.open_thread
+ .as_ref()
+ .map(|root| (id.clone(), Some(root.clone())))
+ } else {
+ Some((id.clone(), None))
+ }
+ })
+ };
+ let c = ui.composer(in_thread);
+ if *c.destination.borrow() == destination {
+ return;
+ }
+ let buf = c.view.buffer();
+ let draft = {
+ let mut st = ui.state.borrow_mut();
+ if let Some(old) = c.destination.borrow().as_ref() {
+ let text = buf
+ .text(&buf.start_iter(), &buf.end_iter(), false)
+ .to_string();
+ let files = c.files.borrow().clone();
+ if !st.bots.contains_key(&old.0) || (text.is_empty() && files.is_empty()) {
+ st.drafts.remove(old);
+ } else {
+ st.drafts.insert(old.clone(), ComposerDraft { text, files });
+ }
+ }
+ destination
+ .as_ref()
+ .and_then(|key| st.drafts.get(key))
+ .cloned()
+ .unwrap_or_default()
+ };
+ c.destination.replace(destination);
+ c.files.replace(draft.files);
+ buf.set_text(&draft.text);
+ show_files(ui, in_thread);
+}
+
fn update_composer(ui: &App, in_thread: bool) {
let st = ui.state.borrow();
if let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id)) {
@@ -2071,6 +2132,9 @@ fn send(ui: &App, in_thread: bool) {
return;
}
let files = c.files.take();
+ if let Some(destination) = c.destination.borrow().as_ref() {
+ ui.state.borrow_mut().drafts.remove(destination);
+ }
buf.set_text("");
show_files(ui, in_thread);
send_text(ui, &bot, &text, thread, files);
diff --git a/apps/linux/src/ui_tests.rs b/apps/linux/src/ui_tests.rs
index c948ef00..c4fa2164 100644
--- a/apps/linux/src/ui_tests.rs
+++ b/apps/linux/src/ui_tests.rs
@@ -133,6 +133,34 @@ fn native_ui_flows() {
assert!(text(&ui.chat_list, "Streaming fixture answer"));
screenshot("linux-chat-streaming");
+ // Switching restores each bot's draft; sending clears only its destination.
+ let draft_text = |c: &Composer| {
+ let buf = c.view.buffer();
+ buf.text(&buf.start_iter(), &buf.end_iter(), false)
+ .to_string()
+ };
+ ui.compose
+ .view
+ .buffer()
+ .set_text(" Bot draft\nunfinished 🐱\n");
+ select(&ui, "other");
+ assert_eq!(draft_text(&ui.compose), "");
+ ui.compose.view.buffer().set_text("Other draft");
+ select(&ui, "bot");
+ assert_eq!(draft_text(&ui.compose), " Bot draft\nunfinished 🐱\n");
+ select(&ui, "other");
+ send(&ui, false);
+ assert_eq!(draft_text(&ui.compose), "");
+ select(&ui, "bot");
+ assert_eq!(draft_text(&ui.compose), " Bot draft\nunfinished 🐱\n");
+ select(&ui, "other");
+ assert_eq!(draft_text(&ui.compose), "");
+ wait(|| text(&ui.chat_list, "Failed to send"));
+ click(&ui.chat_list, "Resend");
+ wait(|| ui.state.borrow().outbox.is_empty());
+ select(&ui, "bot");
+ ui.compose.view.buffer().set_text("");
+
send_text(&ui, "bot", "Retry this message", None, vec![]);
wait(|| text(&ui.chat_list, "Failed to send"));
click(&ui.chat_list, "Resend");
@@ -148,7 +176,7 @@ fn native_ui_flows() {
.as_array()
.unwrap()
.iter()
- .filter(|r| r[0] == "send")
+ .filter(|r| r[0] == "send" && r[1]["text"] == "Retry this message")
.cloned()
.collect();
assert_eq!(sent.len(), 2);
diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swift
index 3180e277..470494fc 100644
--- a/kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/kit/Sources/CodyncUI/Store/BotStore.swift
@@ -69,6 +69,12 @@ public final class BotStore {
/// Bots whose older history has been fully paged in.
public private(set) var historyComplete: Set<String> = []
public var routineDrafts: [String: String] = [:]
+ /// Unsent composer text belongs to a conversation, not the view displaying it.
+ private struct ComposerDestination: Hashable {
+ let botId: String
+ let thread: String?
+ }
+ private var composerDrafts: [ComposerDestination: String] = [:]
public var lastError: String?
/// The open conversation (iOS navigation path / Mac sidebar selection).
public var selection: String?
@@ -222,6 +228,7 @@ public final class BotStore {
private func resetMirror() {
bots = [:]
+ composerDrafts = [:]
entries = entries.mapValues { $0.filter { $0.id.hasPrefix("local-") } }.filter { !$0.value.isEmpty }
selection = nil
onRosterChanged?()
@@ -241,6 +248,7 @@ public final class BotStore {
voiceCalls.removeAll()
setActive(false)
retired = true
+ composerDrafts = [:]
for call in calls { call.end() }
saveTask?.cancel()
dropTimer?.cancel()
@@ -545,6 +553,7 @@ public final class BotStore {
}
}
case let .botDeleted(id, r):
+ composerDrafts = composerDrafts.filter { $0.key.botId != id }
bots[id] = nil
entries[id] = nil
bump(r)
@@ -676,6 +685,26 @@ public final class BotStore {
}
}
+ func composerDraft(for botId: String, thread: String? = nil) -> String {
+ composerDrafts[ComposerDestination(botId: botId, thread: thread)] ?? ""
+ }
+
+ func setComposerDraft(_ text: String, for botId: String, thread: String? = nil) {
+ guard !retired else { return }
+ let destination = ComposerDestination(botId: botId, thread: thread)
+ composerDrafts[destination] = text.isEmpty ? nil : text
+ }
+
+ /// Submission moves the text to the local message/outbox; later delivery never clears a new draft.
+ @discardableResult
+ func sendComposerDraft(to botId: String, thread: String? = nil, files: [OutgoingFile] = []) -> Bool {
+ let text = composerDraft(for: botId, thread: thread)
+ guard !retired, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !files.isEmpty else { return false }
+ send(text, to: botId, thread: thread, files: files)
+ setComposerDraft("", for: botId, thread: thread)
+ return true
+ }
+
/// `thread`: reply in the thread on that main-chat message.
public func send(_ text: String, to botId: String, thread: String? = nil, files: [OutgoingFile] = []) {
send(text, to: botId, thread: thread, nonce: UUID().uuidString, files: files)
@@ -982,6 +1011,7 @@ public final class BotStore {
}
public func delete(_ bot: Bot) {
+ composerDrafts = composerDrafts.filter { $0.key.botId != bot.id }
bots[bot.id] = nil
entries[bot.id] = nil
perform(replay: true) { try await $0.deleteBot(bot.id) }
diff --git a/kit/Sources/CodyncUI/Thread/Composer.swift b/kit/Sources/CodyncUI/Thread/Composer.swift
index 6042fcf3..1c6d6a03 100644
--- a/kit/Sources/CodyncUI/Thread/Composer.swift
+++ b/kit/Sources/CodyncUI/Thread/Composer.swift
@@ -16,7 +16,10 @@ struct Composer: View {
@Environment(BotStore.self) private var model
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.conversationTypography) private var typography
- @State private var draft = ""
+ private var draft: String {
+ get { model.composerDraft(for: botId, thread: thread) }
+ nonmutating set { model.setComposerDraft(newValue, for: botId, thread: thread) }
+ }
/// Files going out with the next message.
@State private var files: [OutgoingFile] = []
@State private var pickingFiles = false
@@ -161,7 +164,7 @@ struct Composer: View {
private var box: some View {
HStack(alignment: .bottom, spacing: 8) {
- TextField(placeholder, text: $draft, axis: .vertical)
+ TextField(placeholder, text: Binding(get: { draft }, set: { draft = $0 }), axis: .vertical)
.lineLimit(1...8)
.font(typography.body)
.textFieldStyle(.plain)
@@ -403,8 +406,7 @@ struct Composer: View {
private func submit() {
guard canSend else { return }
withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {
- model.send(draft, to: botId, thread: thread, files: files)
- draft = ""
+ guard model.sendComposerDraft(to: botId, thread: thread, files: files) else { return }
files = []
}
}
diff --git a/kit/Tests/CodyncUITests/StoreTests.swift b/kit/Tests/CodyncUITests/StoreTests.swift
index 202bd89d..9fbbbe0c 100644
--- a/kit/Tests/CodyncUITests/StoreTests.swift
+++ b/kit/Tests/CodyncUITests/StoreTests.swift
@@ -639,3 +639,45 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String
store.retire()
}
}
+
+@MainActor @Test func composerDraftsRestoreSeparatelyForEachBotAndThread() {
+ let (storage, suite) = context()
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) {
+ FakeRemote(.connecting)
+ }
+ defer { store.retire() }
+ let text = " Unfinished message\nnext line 🐱\n"
+ store.selection = "first"
+ store.setComposerDraft(text, for: "first")
+ store.selection = "second"
+ #expect(store.composerDraft(for: "second").isEmpty)
+ store.setComposerDraft("Other bot's draft", for: "second")
+ store.setComposerDraft("Thread reply", for: "first", thread: "root")
+ store.selection = "first"
+ #expect(store.composerDraft(for: "first") == text)
+ #expect(store.composerDraft(for: "second") == "Other bot's draft")
+ #expect(store.composerDraft(for: "first", thread: "root") == "Thread reply")
+}
+
+@MainActor @Test func sendingComposerDraftClearsOnlyThatConversation() async {
+ 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("first", name: "First", rev: 1))
+ #expect(await until { store.connection == .online })
+ store.setComposerDraft("First message", for: "first")
+ store.setComposerDraft("Other bot's draft", for: "second")
+ store.setComposerDraft("Thread reply", for: "first", thread: "root")
+ #expect(store.sendComposerDraft(to: "first"))
+ #expect(store.composerDraft(for: "first").isEmpty)
+ #expect(store.composerDraft(for: "second") == "Other bot's draft")
+ #expect(store.composerDraft(for: "first", thread: "root") == "Thread reply")
+ store.setComposerDraft("Next unfinished message", for: "first")
+ #expect(await until { store.chat("first").last?.id == "e1" })
+ #expect(store.composerDraft(for: "first") == "Next unfinished message")
+}