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
Merge remote-tracking branch 'origin/dev' into pr-79
leepokai1aae8ec98972
diff --cc apps/desktop/src/main/index.tsindex eaefae23,122a4fb9..445562e2--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@@ -1,10 -2,9 +2,10 @@@ import { identity } from './environmentimport { execFileSync } from 'node:child_process'import { hostname } from 'node:os'import { join } from 'node:path'- import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeTheme, session, shell } from 'electron'+ import { app, autoUpdater, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeTheme, session, shell } from 'electron'import type { HostSnapshot, WindowCommand } from '../shared/ipc'import { devPort, fetchHealth, HostController } from './host-controller'+import { registerFileSaves } from './file-saves'import { registerHostProxy } from './host-proxy'import { readClipboardFiles, readFiles } from './files'import { Tray } from './tray'@@@ -139,7 -136,9 +137,10 @@@ function menu()function registerIPC(tray: Tray) {registerHostProxy()+ ipcMain.on('app:hostPort', (e) => (e.returnValue = identity.port))+ ipcMain.on('app:name', (e) => (e.returnValue = identity.name))+ ipcMain.on('app:scheme', (e) => (e.returnValue = identity.scheme))+ registerFileSaves()ipcMain.on('app:version', (e) => (e.returnValue = app.getVersion()))ipcMain.on('app:computerName', (e) => (e.returnValue = computerName()))ipcMain.on('app:debugOpen', (e) => (e.returnValue = app.isPackaged ? null : (process.env.CODYNC_DEBUG_OPEN ?? null)))diff --cc apps/desktop/src/shared/ipc.tsindex f6fb125c,07f78305..25eb1149--- a/apps/desktop/src/shared/ipc.ts+++ b/apps/desktop/src/shared/ipc.ts@@@ -1,5 -1,5 +1,6 @@@+import type { SharedFile } from './models'import type { SSHBridge } from './ssh'+ import type { ScreenAgentState } from './computer-access'// The bridge between the main process (host lifecycle, loopback HTTP, tray, windows)// and the renderer (stores and UI). Exposed as `window.codync` by the preload script.diff --cc apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swiftindex 1b3c2baa,00000000..918d6c84mode 100644,000000..100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift@@@ -1,61 -1,0 +1,67 @@@+import Foundation++public struct EntryData: Codable, Hashable, Sendable {+ public var connectionRequest: ConnectionRequest?+ public var routineId: String?+ public var runId: String?+ public var text: String?+ public var final: Bool?+ /// user: queued | sent | cancelled | failed · tool: pending | in_progress | completed | failed · permission: pending | answered | cancelled | expired+ public var status: String?+ public var clientNonce: String?+ public var title: String?+ public var toolKind: String?+ public var output: String?+ public var diffs: [FileDiff]?+ public var locations: [Location]?+ public var options: [PermissionOption]?+ public var selected: String?+ public var command: String?+ public var detail: String?+ public var cwd: String?+ public var entries: [PlanItem]?+ /// notice: info | error | divider+ public var style: String?++ /// Structured conversation data added to the existing team-tool notice.++ public var botMessage: BotMessage?++ public var heading: String?++ public var delegationId: String?++ public var sourceBotId: String?++ public var targetBotId: String?+ /// The bot that wrote it (a group shows who spoke).+ public var author: String?+ /// On a main-chat message that has a thread: its replies.+ public var thread: ThreadSummary?+ /// The user's emoji reactions, oldest first.+ public var reactions: [String]?+ /// Files sent with a user message.+ public var attachments: [Attachment]?+ /// Immutable files explicitly sent by the bot.+ public var files: [SharedFile]?+ /// notice: a finished voice call's length.+ public var callSeconds: Int?++ public init(text: String? = nil, status: String? = nil, clientNonce: String? = nil) {+ self.text = text+ self.status = status+ self.clientNonce = clientNonce+ }+}++/// A file sent with a message; the agent reads it on the computer.+public struct Attachment: Codable, Hashable, Sendable, Identifiable {+ public var id: String+ public var name: String+ public var size: Int64++ public init(id: String, name: String, size: Int64) {+ self.id = id+ self.name = name+ self.size = size+ }++ public var isImage: Bool {+ ["png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp"].contains((name as NSString).pathExtension.lowercased())+ }+}+diff --cc apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swiftindex ed851244,00000000..2fec3bbdmode 100644,000000..100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swift@@@ -1,86 -1,0 +1,88 @@@+import CodyncKit+import Foundation+import Observation++protocol FileDownloadWriting: Sendable {+ func save(client: HostClient, entryId: String, file: SharedFile,+ directory: URL, progress: @Sendable (Int64) async -> Void) async throws -> URL+ func remove(_ url: URL) async throws+}++extension FileDownload: FileDownloadWriting {}++@MainActor @Observable+public final class FileDownloads {+ public enum State {+ case downloading(Int64), saved, failed(String)+ }+ public struct Export: Identifiable {+ public let id: String+ public let url: URL+ public let botId: String+ public let threadId: String?+ }+ public private(set) var states: [String: State] = [:]+ public var export: Export?+ @ObservationIgnored private var exported: Export?+ @ObservationIgnored private var tasks: [String: Task<Void, Never>] = [:]+ @ObservationIgnored private let writer: any FileDownloadWriting+ @ObservationIgnored private var retired = false++ public init() { writer = FileDownload() }++ init(writer: any FileDownloadWriting) { self.writer = writer }++ public func save(client: HostClient?, entry: Entry, file: SharedFile) {+ guard !retired else { return }+ guard tasks.isEmpty else {+ if tasks[file.id] == nil { states[file.id] = .failed("Finish the current download first.") }+ return+ }- // An export whose chat was left never showed its sheet; this tap replaces it.++ // This file's export sheet is already waiting in its chat.++ if export?.id == file.id { return }++ // Another file's export whose chat was left never showed its sheet; this tap replaces it.+ dismissExport()+ guard let client else { states[file.id] = .failed("Connect to this computer to download the file."); return }+ states[file.id] = .downloading(0)+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CodyncDownloads", isDirectory: true)+ tasks[file.id] = Task {+ defer { tasks[file.id] = nil }+ do {+ let url = try await writer.save(client: client, entryId: entry.id, file: file, directory: directory) { [weak self] received in+ await self?.update(file.id, received: received)+ }+ guard !Task.isCancelled, !retired else { try await writer.remove(url); return }+ states[file.id] = .saved+ let item = Export(id: file.id, url: url, botId: entry.botId, threadId: entry.threadId)+ exported = item+ export = item+ } catch is CancellationError {+ states[file.id] = nil+ } catch {+ if !Task.isCancelled, !retired { states[file.id] = .failed(error.localizedDescription) }+ }+ }+ }++ private func update(_ id: String, received: Int64) {+ guard !retired, tasks[id]?.isCancelled == false else { return }+ states[id] = .downloading(received)+ }++ public func cancel(_ id: String) { tasks[id]?.cancel(); states[id] = nil }++ /// The native share sheet has finished using the verified temporary file.+ public func dismissExport() {+ export = nil+ guard let item = exported else { return }+ exported = nil+ Task { do { try await writer.remove(item.url) } catch { states[item.id] = .failed(error.localizedDescription) } }+ }++ public func retire() {+ retired = true+ for task in tasks.values { task.cancel() }+ dismissExport()+ states.removeAll()+ }+}diff --cc docs/features/chat-messages.mdindex e3172427,c2acacf4..f919beab--- a/docs/features/chat-messages.md+++ b/docs/features/chat-messages.md@@@ -9,15 -9,20 +9,23 @@@ How a bot's work turns into what the usthreads, each call is one chat bubble, added to the turn's lane at once as an `agent` entry with`final: true`. A turn can send several.- The agent's own reply text (`agent_message_chunk`) stays in the trace when the turn sent- anything. A turn that sent nothing (an agent that ignores the tool, or has no MCP) falls back to+ text through `send_message`. A turn that sent nothing (an agent that ignores the tool, or has no MCP) falls back tothe old rule: its last text becomes the turn's final message.-- Group room turns, `ask_bot` requests and routines reject `send_message`: their reply is the+- File cards are separate final entries. Sharing a file preserves an intended final text+ reply; a files-only turn uses its filename for the completion summary. See+ [file attachments](file-attachments.md#files-from-a-bot).+- Group room turns, `ask_bot` requests and routines reject `send_message` and `send_file`: their reply is theturn's last text, as before (`chat/group.rs`, `chat/team.rs`, `routines`).+ - An `ask_bot` reply stays in the recipient's trace and the request notice; it does+ not also become a message to the user. The requesting bot uses it to answer the user.+ Independent `message_bot` turns report to the user in the recipient's main chat, through+ `send_message` or the final-text fallback, and do not add that report to the request notice.- The rules reach the agent twice: the MCP server's instructions, and the frozen instructionsnapshot (`chat/context.rs`).+ - A bot-to-bot exchange (`ask_bot`, `message_bot`) is one compact notice row, "Messaged Owen" /+ "Message from Egan". Its text lives only in the bot conversation sheet it opens; follow-ups+ are normal bubbles. Consecutive exchanges with the same peer in the main chat (either+ direction, trace entries ignored) collapse into one "3 messages with Owen" row ([bot collaboration](bot-collaboration.md#notice-data)).- Clients never stream text into a bubble: the chat shows user messages, `final` agent entries,permission cards and notices (`isChat`). Nothing pops in and out while a turn runs.diff --cc host/src/agent/bot/turn.rsindex 2e29a0a6,e3924c2f..f316ab9b--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@@ -109,9 -109,16 +111,17 @@@ impl Actor}let claude = self.conn.as_ref().is_some_and(|c| c.claude);let sid = self.turn_session.clone().ok_or_else(|| anyhow!("no session"))?;+ let memory_session = memory::lifecycle::begin(&self.hub, &self.cfg.id, &sid).await?;+ self.memory_session = Some(memory_session.clone());+ if !hidden && let Err(error) = memory::lifecycle::capture_prompt(&self.cfg.id, &memory_session, text).await {+ tracing::warn!(bot = %self.cfg.id, %error, "memory prompt capture failed");+ }let snapshot = self.snapshot(&sid).await?;+ let remind_files = !snapshot.system.contains("send_file");let mut prompt = text.to_owned();+ if let Some(notice) = memory::lifecycle::change_notice(&self.hub, &self.cfg.id, &sid) {+ prompt = format!("{notice}\n\n{prompt}");+ }if let Some(intro) = self.thread_intro.take() {prompt = format!("{intro}\n\n{prompt}");}diff --cc host/src/mcp.rsindex 32b7285c,1cad9f20..59567dca--- a/host/src/mcp.rs+++ b/host/src/mcp.rs@@@ -105,9 -120,9 +120,9 @@@ async fn call(port: u16, token: &str, bServer::Connectors => ("connectorCall", Duration::from_secs(90)),Server::Routines => ("routineCall", Duration::from_secs(30)),Server::Computer => ("computerCall", Duration::from_secs(60)),- Server::Chat => ("chatCall", Duration::from_secs(30)),+ Server::Chat => ("chatCall", Duration::from_secs(if params["name"] == "send_file" { 70 } else { 30 })),Server::Team => ("teamCall", crate::chat::team::ASK_TIMEOUT + Duration::from_secs(30)),- Server::Memory => ("memoryCall", Duration::from_secs(30)),+ Server::Memory => ("memoryCall", Duration::from_secs(120)),Server::Composio => ("composioCall", Duration::from_secs(120)),};let res = crate::http()diff --cc host/src/tui/app/events.rsindex 253684d0,040bdf9b..1999ad73--- a/host/src/tui/app/events.rs+++ b/host/src/tui/app/events.rs@@@ -28,16 -38,12 +38,20 @@@ impl Appself.call("thread", json!({"botId": id, "rootId": root}), After::Thread);}}+ Msg::Connected { since } => {+ self.stream_since = since;+ self.floors.clear();+ }Msg::Event(v) => self.on_event(&v),Msg::Reply(after, r) => self.on_reply(after, r),+ Msg::FileDownload { id, status, done } => {+ if self.download.as_ref().is_some_and(|job| job.id == id) {+ self.flash(&status.unwrap_or_else(|error| format!("Download failed: {error}")));+ if done {+ self.download = None;+ }+ }+ }Msg::Term(id, v) => self.on_term(&id, &v),}}diff --cc host/src/tui/app/model.rsindex 74d9561a,e366bdee..82c4a219--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@@ -7,11 -7,10 +7,15 @@@ use super::tildepub enum Msg {Online(bool),+ /// A new events connection asked for everything after `since`; its `hello` starts the catch-up.+ Connected {+ since: i64,+ },+ FileDownload {+ id: String,+ status: Result<String, String>,+ done: bool,+ },Event(Value),Reply(After, Result<Value, String>),/// The stream is starting over from rev 0: drop what we have.diff --cc host/src/tui/net.rsindex 2edd5688,344b37f9..bcd28133--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@@ -255,15 -266,8 +268,15 @@@ impl Client/// `dir/name`, or `name (2)` … when that's taken. The name is only its last part (no `../`).fn free_path(dir: &std::path::Path, name: &str) -> PathBuf {- let name =- std::path::Path::new(name).file_name().map_or_else(|| "file".into(), |n| n.to_string_lossy().into_owned());+ // Only the last plain component: a drive prefix ("C:x") or parent can't escape `dir`.+ let name = std::path::Path::new(name)+ .components()- .filter_map(|c| match c {++ .rev()++ .find_map(|c| match c {+ std::path::Component::Normal(n) => Some(n.to_string_lossy().into_owned()),+ _ => None,+ })- .last()+ .unwrap_or_else(|| "file".into());let (stem, ext) = match name.rsplit_once('.') {Some((s, e)) if !s.is_empty() => (s.to_owned(), format!(".{e}")),_ => (name.clone(), String::new()),diff --cc host/src/tui/view/transcript.rsindex 24c0cfef,e1c1742d..9e500a9e--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@@ -367,23 -389,92 +404,109 @@@ fn thread_summary(v: &serde_json::Valuemod tests {use super::*;+ #[tokio::test]+ async fn generated_files_are_selectable_cards_without_duplicate_fallback_text() {+ use crate::tui::app::Msg;+ use serde_json::json;+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(crate::tui::net::Client::new("http://127.0.0.1:1", Some("fixture")), tx, String::new());+ app.on_msg(Msg::Event(json!({"type":"bot", "bot":{"id":"bot", "name":"Files", "cwd":"/workspace", "backend":"custom", "status":"idle"}})));+ app.on_msg(Msg::Event(json!({"type":"entry", "entry":{"id":"file-entry", "botId":"bot", "seq":1, "kind":"agent", "turn":1, "data":{"author":"bot", "text":"fallback must stay hidden", "final":true, "files":[{"id":"file", "name":".empty", "size":0, "sha256":"hash"}]}}})));+ let bot = app.bots.get("bot").unwrap();+ let chat = build_chat(&app, bot, 80);+ let text = chat.lines.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n");+ assert!(text.contains(".empty"));+ assert!(text.contains("f to download"));+ assert!(!text.contains("fallback must stay hidden"));+ assert!(chat.messages.iter().any(|(id, _, _)| id == "file-entry"));+ }++ fn app_with_bots() -> App {+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(super::super::super::net::Client::new("http://127.0.0.1:1", None), tx, String::new());+ for (id, name) in [("a", "Egan"), ("b", "Owen")] {+ app.on_msg(super::super::super::app::Msg::Event(+ serde_json::json!({"type":"bot","bot":{"id":id,"name":name}}),+ ));+ }+ app+ }++ fn exchange_entry(status: &str) -> Entry {+ Entry {+ id: "n".into(),+ seq: 1,+ turn: 1,+ kind: Kind::Notice,+ created_at: 0,+ thread_id: None,+ data: serde_json::json!({+ "text": "Messaged b: Please review the secret plan\nCompleted.", "style": "info", "status": status,+ "heading": "Messaged b: Please review the secret plan",+ "botMessage": {"sourceBotId": "a", "targetBotId": "b", "text": "Please review the secret plan"},+ "sourceBotId": "a", "targetBotId": "b", "delegationId": "r",+ }),+ }+ }++ #[test]+ fn bot_message_is_one_line_with_a_click_and_marks_only_failure() {+ let app = app_with_bots();+ let bot = &app.bots["a"];+ let render = |e: &Entry| {+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ entry_lines(&mut out, &app, bot, e, &HashMap::new(), true, 80);+ out+ };+ let ok = render(&exchange_entry("completed"));+ let text = ok.lines.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n");+ assert!(text.contains("Messaged") && text.contains("Owen"));+ assert!(!text.contains("secret plan") && !text.contains("failed"));+ assert!(matches!(ok.buttons.as_slice(), [(_, 3, _, Click::BotChat(id))] if id == "n"));+ assert_eq!(ok.messages.len(), 1);+ let mut failed = exchange_entry("failed");+ failed.data["text"] = "Messaged b: Please review the secret plan\nRecipient stopped.".into();+ let bad = render(&failed);+ let line = bad.lines.last().unwrap();+ assert!(line.to_string().ends_with("Owen · failed"));+ assert_eq!(line.spans[0].style, theme().red);+ }++ #[test]+ fn a_run_of_exchanges_is_one_counted_line() {+ let app = app_with_bots();+ let bot = &app.bots["a"];+ let mut entries = vec![];+ for (i, status) in ["completed", "failed", "completed"].into_iter().enumerate() {+ let mut e = exchange_entry(status);+ e.id = format!("n{i}");+ e.seq = i64::try_from(i).unwrap_or(0) + 1;+ entries.push(e);+ }+ let refs: Vec<&Entry> = entries.iter().collect();+ let build = |refs: &[&Entry]| {+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ for item in group(&bot.id, refs, true) {+ match item {+ Item::Entry(e) => entry_lines(&mut out, &app, bot, e, &HashMap::new(), true, 80),+ Item::Group(g) => {+ let lead = format!("{} messages with ", g.count);+ bot_message_line(&mut out, &app, g.first, &g.peer, &lead, g.failed, 0);+ }+ }+ }+ out+ };+ let out = build(&refs);+ assert_eq!(out.lines.len(), 1);+ let line = &out.lines[0];+ assert!(line.to_string().contains("3 messages with") && line.to_string().ends_with("Owen · failed"), "{line}");+ assert_eq!(line.spans[0].style, theme().red);+ assert!(matches!(out.buttons.as_slice(), [(_, 3, _, Click::BotChat(id))] if id == "n0"));+ assert_eq!(out.messages.len(), 1);+ assert!(build(&refs[..1]).lines[0].to_string().contains("Messaged"));+ }+#[test]fn thread_summary_counts_replies() {assert_eq!(thread_summary(&serde_json::json!({"count": 0})), None);diff --cc host/tests/files_e2e.rsindex 261498e5,00000000..b21a08efmode 100644,000000..100644--- a/host/tests/files_e2e.rs+++ b/host/tests/files_e2e.rs@@@ -1,321 -1,0 +1,322 @@@+//! Generated file publication through real ACP/MCP and authenticated HTTP.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use serde_json::{Value, json};+use std::path::PathBuf;+use std::process::{Child, Command, Stdio};+use std::time::Duration;++struct Host {+ child: Child,+ home: PathBuf,+ base: String,+ token: String,+}++impl Drop for Host {+ fn drop(&mut self) {+ common::stop(&mut self.child);+ let _ = std::fs::remove_dir_all(&self.home);+ }+}++impl Host {+ async fn start() -> Self {+ let home = std::env::temp_dir().join(format!("codync-files-e2e-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&home).unwrap();++ common::seed_memory_runtime(&home);+ let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();+ let child = Command::new(env!("CARGO_BIN_EXE_codync-host"))+ .args(["serve", "--bind", "127.0.0.1", "--port", &port.to_string()])+ .env("CODYNC_CLOUD", "off")+ .env("CODYNC_HOME", &home)+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();+ let mut host = Self { child, home, base: format!("http://127.0.0.1:{port}"), token: String::new() };+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ let response = reqwest::get(format!("{}/health", host.base)).await;+ if response.is_ok() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+ std::fs::read_to_string(host.home.join("token")).unwrap().trim().clone_into(&mut host.token);+ host+ }++ async fn restart(&mut self) {+ common::stop(&mut self.child);+ let port = self.base.rsplit(':').next().unwrap();+ self.child = Command::new(env!("CARGO_BIN_EXE_codync-host"))+ .args(["serve", "--bind", "127.0.0.1", "--port", port])+ .env("CODYNC_CLOUD", "off")+ .env("CODYNC_HOME", &self.home)+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ let response = reqwest::get(format!("{}/health", self.base)).await;+ if response.is_ok() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+ }++ async fn call(&self, method: &str, body: Value) -> Value {+ let response_result = reqwest::Client::new()+ .post(format!("{}/api/{method}", self.base))+ .bearer_auth(&self.token)+ .json(&body)+ .timeout(Duration::from_secs(10))+ .send()+ .await;+ let response = response_result.unwrap();+ let status = response.status();+ let decoded = response.json().await;+ let value: Value = decoded.unwrap();+ assert!(status.is_success(), "{method}: {value}");+ value+ }+}++async fn ready(host: &Host, bot: &str, expected_files: usize) -> Vec<Value> {+ let waited = tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ let history = host.call("history", json!({"botId": bot})).await;+ let entries = history["entries"].as_array().unwrap();+ let files = entries.iter().filter(|e| e["data"]["files"].is_array()).count();+ if files == expected_files+ && entries.iter().any(|e| e["data"]["text"] == "The files are ready." && e["data"]["final"] == true)+ {+ return entries.clone();+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap()+}++#[tokio::test]+async fn publishes_all_types_with_final_text_and_survives_restart_workspace_changes_and_threads() {+ use base64::Engine as _;+ let mut host = Host::start().await;+ let cwd = host.home.join("workspace");+ std::fs::create_dir_all(&cwd).unwrap();+ let data = [0, 255, 128, 17].repeat(150_000);+ for (name, bytes) in [+ ("binary.dat", data.clone()),+ (".hidden", vec![13]),+ ("empty", vec![]),+ ("report.pdf", b"%PDF-example".to_vec()),+ ] {+ std::fs::write(cwd.join(name), bytes).unwrap();+ }+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/file_agent.py");+ let created = host.call("createBot", json!({"name":"Files", "backend":"custom", "cwd":cwd, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ let root = host.call("send", json!({"botId":bot,"text":"share-files"})).await;+ let entries = ready(&host, bot, 4).await;+ let file_entry = entries.iter().find(|e| e["data"]["files"][0]["name"] == "binary.dat").unwrap();+ let entry_id = file_entry["id"].as_str().unwrap();+ let file_id = file_entry["data"]["files"][0]["id"].as_str().unwrap();+ std::fs::remove_file(cwd.join("binary.dat")).unwrap();+ host.restart().await;+ let mut received = Vec::new();+ while received.len() < data.len() {+ let response =+ host.call("readFile", json!({"entryId":entry_id,"fileId":file_id,"offset":received.len()})).await;+ assert_eq!(response["size"], data.len());+ let bytes = base64::engine::general_purpose::STANDARD.decode(response["data"].as_str().unwrap()).unwrap();+ received.extend(bytes);+ }+ assert_eq!(received, data);+ let response_result = reqwest::Client::new()+ .post(format!("{}/api/readFile", host.base))+ .json(&json!({"entryId":entry_id,"fileId":file_id,"offset":0}))+ .send()+ .await;+ let response = response_result.unwrap();+ assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED);+ for body in [+ json!({"entryId":root["entry"]["id"],"fileId":file_id,"offset":0}),+ json!({"entryId":entry_id,"fileId":"../escape","offset":0}),+ json!({"entryId":entry_id,"fileId":file_id,"offset":-1}),+ json!({"entryId":entry_id,"fileId":file_id,"offset":data.len()+1}),+ ] {+ let response_result = reqwest::Client::new()+ .post(format!("{}/api/readFile", host.base))+ .bearer_auth(&host.token)+ .json(&body)+ .send()+ .await;+ let response = response_result.unwrap();+ assert!(!response.status().is_success());+ }+ std::fs::write(cwd.join("binary.dat"), &data).unwrap();+ host.call("send", json!({"botId":bot,"text":"share-files resumed"})).await;+ ready(&host, bot, 8).await;+ assert!(cwd.join("resumed").exists());+ host.call("send", json!({"botId":bot,"text":"share-files in a thread", "threadId":root["entry"]["id"]})).await;+ let waited = tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ let response = host.call("thread", json!({"botId":bot,"rootId":root["entry"]["id"]})).await;+ let files: Vec<_> = response["entries"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|e| e["data"]["files"].is_array())+ .cloned()+ .collect();+ if files.len() == 4 {+ let file = &files[0];+ host.call("readFile", json!({"entryId":file["id"],"fileId":file["data"]["files"][0]["id"],"offset":0}))+ .await;+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+ let mut updated = created["bot"].clone();+ updated["cwd"] = host.home.to_string_lossy().into();+ host.call("updateBot", updated).await;+ host.call("readFile", json!({"entryId":entry_id,"fileId":file_id,"offset":0})).await;+ host.call("deleteBot", json!({"botId":bot})).await;+ let response_result = reqwest::Client::new()+ .post(format!("{}/api/readFile", host.base))+ .bearer_auth(&host.token)+ .json(&json!({"entryId":entry_id,"fileId":file_id,"offset":0}))+ .send()+ .await;+ let response = response_result.unwrap();+ assert!(!response.status().is_success());+}++#[tokio::test]+async fn rejects_invalid_sources_without_a_file_entry() {+ let host = Host::start().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/file_agent.py");+ let large = std::fs::File::create(host.home.join("oversized")).unwrap();+ large.set_len(100 * 1024 * 1024 + 1).unwrap();+ let created = host.call("createBot", json!({"name":"Errors", "backend":"custom", "cwd":host.home, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ host.call("send", json!({"botId":bot,"text":"invalid-files"})).await;+ ready(&host, bot, 0).await;+ let results: Value = serde_json::from_slice(&std::fs::read(host.home.join("file-results.json")).unwrap()).unwrap();+ assert!(results.as_array().unwrap().iter().all(|r| r["isError"] == true));+}++async fn rejected(path: &std::path::Path) {+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ if let Ok(data) = std::fs::read(path) {+ let results: Value = serde_json::from_slice(&data).unwrap();+ assert!(+ results.as_array().unwrap().iter().all(|result| result["isError"] == true+ && result["content"][0]["text"].as_str().unwrap().contains("own chat and threads")),+ "{results}"+ );+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+}++#[tokio::test]+async fn groups_routines_and_delegated_turns_cannot_publish_files() {+ let host = Host::start().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/file_agent.py");+ let created = host.call("createBot", json!({"name":"Recipient", "backend":"custom", "cwd":host.home, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ let results_path = host.home.join("file-results.json");+ let group = host.call("createBot", json!({"name":"Group", "kind":"group", "members":[bot]})).await;+ host.call("send", json!({"botId":group["bot"]["id"],"text":"share-files"})).await;+ rejected(&results_path).await;+ host.call("stop", json!({"botId":group["bot"]["id"]})).await;+ tokio::time::sleep(Duration::from_millis(300)).await;+ let _ = std::fs::remove_file(&results_path);+ let routine = host+ .call(+ "saveRoutine",+ json!({"botId":bot,"name":"Files","instruction":"share-files","triggers":[{"type":"webhook"}]}),+ )+ .await;+ host.call("runRoutine", json!({"botId":bot,"id":routine["routine"]["id"]})).await;+ rejected(&results_path).await;+ tokio::time::sleep(Duration::from_millis(300)).await;+ std::fs::remove_file(&results_path).unwrap();+ let caller_dir = host.home.join("caller");+ std::fs::create_dir_all(&caller_dir).unwrap();+ let caller_agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");+ let caller = host.call("createBot", json!({"name":"Caller", "backend":"custom", "cwd":caller_dir, "command":common::python_agent(&caller_agent), "connectors":[], "notify":false})).await;+ let caller = caller["bot"]["id"].as_str().unwrap();+ host.call("send", json!({"botId":caller,"text":"warm up"})).await;+ tokio::time::sleep(Duration::from_millis(800)).await;+ host.call("send", json!({"botId":caller,"text":format!("DELEGATE {bot}")})).await;+ rejected(&results_path).await;+ let history = host.call("history", json!({"botId":bot})).await;+ assert!(history["entries"].as_array().unwrap().iter().all(|entry| entry["data"]["files"].is_null()));+}++#[tokio::test]+async fn files_only_turns_finish_without_duplicate_text_and_input_uploads_still_work() {+ use base64::Engine as _;+ let host = Host::start().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/file_agent.py");+ for name in ["binary.dat", ".hidden", "empty", "report.pdf"] {+ std::fs::write(host.home.join(name), []).unwrap();+ }+ let created = host.call("createBot", json!({"name":"Files only", "backend":"custom", "cwd":host.home, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ let upload_id = uuid::Uuid::new_v4().to_string();+ host.call(+ "upload",+ json!({"botId":bot,"uploadId":upload_id,"name":"input.txt","offset":0,"data":"aGVsbG8=","done":true}),+ )+ .await;+ let sent = host.call("send", json!({"botId":bot,"text":"files-only","attachments":[upload_id]})).await;+ assert_eq!(sent["entry"]["data"]["attachments"][0]["id"], upload_id);+ let response = host.call("readUpload", json!({"botId":bot,"uploadId":upload_id,"offset":0})).await;+ assert_eq!(base64::engine::general_purpose::STANDARD.decode(response["data"].as_str().unwrap()).unwrap(), b"hello");+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ let history = host.call("history", json!({"botId":bot})).await;+ let final_entries: Vec<_> = history["entries"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|e| e["kind"] == "agent" && e["data"]["final"] == true)+ .collect();+ let sync = host.call("sync", json!({"since":0})).await;+ if final_entries.len() == 4+ && sync["bots"].as_array().unwrap().iter().any(|b| b["id"] == bot && b["status"] == "idle")+ {+ assert!(final_entries.iter().all(|e| e["data"]["files"].is_array()));+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+}