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): hold the dev server limit under parallel starts and show a log that can't be read

leepokai94d1b878d563
diff --git a/apps/desktop/e2e/dev-servers.spec.ts b/apps/desktop/e2e/dev-servers.spec.ts
index d68ef113..4e6bac4d 100644
--- a/apps/desktop/e2e/dev-servers.spec.ts
+++ b/apps/desktop/e2e/dev-servers.spec.ts
@@ -1,5 +1,9 @@
import { test, expect, type Page } from '@playwright/test'
-import { api, attach } from './sandbox.ts'
+import { mkdirSync, rmSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+import { SANDBOX_PREFIX } from '../src/shared/dev-sandbox.ts'
+import { api, attach, sandbox } from './sandbox.ts'
/** A port nothing listens on yet, below the range the system picks from. */
const freePort = () => 20_000 + Math.floor(Math.random() * 10_000)
@@ -13,7 +17,7 @@ async function openBot(page: Page, name: string) {
}
const start = (page: Page, botId: string, command: string, name: string) =>
- api(page, 'chatCall', { botId, name: 'start_dev_server', arguments: { command, name } })
+ api<{ id: string }>(page, 'chatCall', { botId, name: 'start_dev_server', arguments: { command, name } })
async function pick(page: Page, row: ReturnType<Page['locator']>, title: string) {
await row.hover()
@@ -87,3 +91,31 @@ test('a failing command shows Failed to start, and its row opens the log with ho
await browser.close()
}
})
+
+test("a log that can't be read says why, and a missing one reads as no output", async () => {
+ const { browser, page } = await attach()
+ let botId: string | undefined
+ try {
+ botId = await openBot(page, `Dev server log e2e ${Date.now()}`)
+ const { id } = await start(page, botId, 'echo finished', 'docs')
+ await page.locator('.title-pill').click()
+ const row = page.locator('.dev-server-row', { hasText: 'docs' })
+ await expect(row).toContainText('Stopped')
+
+ // A folder in its place: reading it fails on every system, unlike file permissions.
+ const log = join(homedir(), SANDBOX_PREFIX + sandbox().name, 'dev-servers', `${id}.log`)
+ rmSync(log)
+ mkdirSync(log)
+ await pick(page, row, 'Logs')
+ const logs = page.locator('.modal-content')
+ await expect(logs).toContainText('reading')
+ await expect(logs).not.toContainText('No output yet')
+
+ rmSync(log, { recursive: true })
+ await logs.getByRole('button', { name: 'Try again' }).click()
+ await expect(logs).toContainText('No output yet')
+ } finally {
+ if (botId) await api(page, 'deleteBot', { botId }).catch(() => {})
+ await browser.close()
+ }
+})
diff --git a/docs/features/dev-servers.md b/docs/features/dev-servers.md
index 98d047bd..0af98c07 100644
--- a/docs/features/dev-servers.md
+++ b/docs/features/dev-servers.md
@@ -125,16 +125,18 @@ Instructions aren't a guarantee, and some agents have their own background-shell
what an agent started outside Codync's helpers and listens below port 32768 (above is where systems hand out ports: an
agent's own callback or inspector). The agent's own processes, by program name (its harness's `bins` and its command's
first word, unless that's a runtime like `node`), don't count: `opencode acp` listens on 4096. Processes that share a
-socket are one server (a pre-fork server), whose Stop ends them all. These show with `managed: false`, marked as stopping
-with the bot, and offer only open, copy and stop: they can't leave the agent's tree. `background_work` still keeps their
-agent running. The `dev_server_detected` event measures how often this happens.
+socket are one server (a pre-fork server), whose Stop ends them all. A Stop reads the agent's tree again and ends only what
+is still in it, since a pid from the last scan can be reused; when the tree can't be read it fails and the row stays. These
+show with `managed: false`, marked as stopping with the bot, and offer only open, copy and stop: they can't leave the
+agent's tree. `background_work` still keeps their agent running. The `dev_server_detected` event measures how often this
+happens.
## Tests
`host/tests/dev_server_e2e.rs` runs on every system host CI does, and walks the table above: its Unix-only parts are a
-crashed host's leftover process and an agent stopped after a routine's run (Windows can't tell that fixture from one with
-a server, see `background_work`). `apps/desktop/e2e/dev-servers.spec.ts` and `apps/maestro/dev-servers.yaml` walk the
-clients.
+crashed host's leftover process, an agent stopped after a routine's run (Windows can't tell that fixture from one with
+a server, see `background_work`) and a process list that can't be read. `apps/desktop/e2e/dev-servers.spec.ts` and
+`apps/maestro/dev-servers.yaml` walk the clients.
## Later
diff --git a/host/src/dev_servers/detected.rs b/host/src/dev_servers/detected.rs
index 2cbab168..5df5d786 100644
--- a/host/src/dev_servers/detected.rs
+++ b/host/src/dev_servers/detected.rs
@@ -9,7 +9,7 @@ use crate::agent::backends;
use crate::agent::process::{self, JobProcess, program_name};
use crate::analytics::Event;
use crate::hub::Hub;
-use anyhow::{Result, bail};
+use anyhow::{Context, Result, bail};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
@@ -109,21 +109,33 @@ fn plain_name(program: &str) -> &str {
}
/// Ends a detected server of `bot` named by `id`. False when `id` isn't one, so it's a server of the host's own.
-pub fn stop(hub: &Hub, bot: &str, id: &str) -> Result<bool> {
+pub async fn stop(hub: &Hub, bot: &str, id: &str) -> Result<bool> {
let Some(first) = id.strip_prefix(ID_PREFIX) else { return Ok(false) };
let first: u32 = first.parse()?;
+ // The last scan can be seconds old and a pid gets reused, so only what's in the agent's tree right now. Read before
+ // its row goes: a failed read or a request that goes away leaves it listed. With no agent, its tree ended with it.
+ let agent = hub.dev_servers.agents_running().into_iter().find(|agent| agent.bot == bot);
+ let tree = match agent {
+ Some(agent) => agent_tree(&agent).await.context("couldn't check the agent's processes")?,
+ None => Vec::new(),
+ };
let server = hub.dev_servers.detected.locked().get_mut(bot).and_then(|servers| {
let at = servers.iter().position(|server| server.pids[0] == first)?;
Some(servers.remove(at))
});
let Some(server) = server else { bail!("unknown dev server") };
- for pid in server.pids {
+ for pid in still_in_tree(&server.pids, &tree) {
platform::end_process(pid);
}
hub.emit_bot(bot);
Ok(true)
}
+/// Those of `pids` the agent's tree still holds.
+pub(super) fn still_in_tree(pids: &[u32], tree: &[JobProcess]) -> Vec<u32> {
+ pids.iter().copied().filter(|pid| tree.iter().any(|process| process.pid == *pid)).collect()
+}
+
/// Finds what each bot's agent left listening, and tells clients when that changed. `moved`: this computer's addresses
/// changed, so the ones worked out before no longer hold.
pub async fn scan(hub: &Hub, agents: &[RunningAgent], listening: &[Listening], moved: bool) {
@@ -220,10 +232,18 @@ async fn agent_trees(agents: &[RunningAgent]) -> Option<Vec<Vec<JobProcess>>> {
.await
.inspect_err(|error| tracing::debug!(error = format!("{error:#}"), "couldn't list processes"))
.ok()?;
- let tree = |agent: &RunningAgent| {
- agent.acp.pid().map_or_else(Vec::new, |leader| process::descendants(&everything, leader))
- };
- Some(agents.iter().map(tree).collect())
+ Some(agents.iter().map(|agent| started_by(agent, &everything)).collect())
+}
+
+/// What one agent started, for a stop: unlike a scan's read, a failed one is an error.
+#[cfg(unix)]
+async fn agent_tree(agent: &RunningAgent) -> Result<Vec<JobProcess>> {
+ Ok(started_by(agent, &process::list_processes().await?))
+}
+
+#[cfg(unix)]
+fn started_by(agent: &RunningAgent, everything: &[JobProcess]) -> Vec<JobProcess> {
+ agent.acp.pid().map_or_else(Vec::new, |leader| process::descendants(everything, leader))
}
/// Everything in each of `agents`' jobs, its own processes too: [`servers_in`] leaves those out by name. A failed read
@@ -232,7 +252,13 @@ async fn agent_trees(agents: &[RunningAgent]) -> Option<Vec<Vec<JobProcess>>> {
async fn agent_trees(agents: &[RunningAgent]) -> Option<Vec<Vec<JobProcess>>> {
let mut trees = Vec::new();
for agent in agents {
- trees.push(agent.acp.job_processes().await.unwrap_or_default());
+ trees.push(agent_tree(agent).await.unwrap_or_default());
}
Some(trees)
}
+
+/// Everything in one agent's job, for a stop: unlike a scan's read, a failed one is an error.
+#[cfg(windows)]
+async fn agent_tree(agent: &RunningAgent) -> Result<Vec<JobProcess>> {
+ agent.acp.job_processes().await
+}
diff --git a/host/src/dev_servers/logs.rs b/host/src/dev_servers/logs.rs
index 74900138..6cb5fb20 100644
--- a/host/src/dev_servers/logs.rs
+++ b/host/src/dev_servers/logs.rs
@@ -1,6 +1,6 @@
//! A dev server's output: `~/.codync/dev-servers/<id>.log`, the current run only, rotated once so it stays bounded.
-use anyhow::Result;
+use anyhow::{Context, Result};
use std::io::{ErrorKind, Read as _, Seek as _, SeekFrom};
use std::path::PathBuf;
use std::sync::Arc;
@@ -98,17 +98,18 @@ fn remove(file: &std::path::Path) {
pub async fn tail(id: &str, lines: usize) -> Result<String> {
let (current, before) = (path(id), rotated(id));
let text = tokio::task::spawn_blocking(move || {
- let mut text = read_end(&current);
+ let mut text = read_end(&current)?;
if text.lines().count() < lines {
- text = read_end(&before) + &text;
+ text = read_end(&before)? + &text;
}
- text
+ anyhow::Ok(text)
})
- .await?;
+ .await??;
Ok(last_lines(&crate::usage::strip_ansi(&text), lines))
}
-fn read_end(path: &std::path::Path) -> String {
+/// The end of a log. A server that wrote nothing yet has no file, which isn't a failure; anything else is.
+pub(super) fn read_end(path: &std::path::Path) -> Result<String> {
let read = || -> std::io::Result<Vec<u8>> {
let mut file = std::fs::File::open(path)?;
let size = file.metadata()?.len();
@@ -117,7 +118,11 @@ fn read_end(path: &std::path::Path) -> String {
file.read_to_end(&mut bytes)?;
Ok(bytes)
};
- read().map(|bytes| String::from_utf8_lossy(&bytes).into_owned()).unwrap_or_default()
+ match read() {
+ Ok(bytes) => Ok(String::from_utf8_lossy(&bytes).into_owned()),
+ Err(error) if error.kind() == ErrorKind::NotFound => Ok(String::new()),
+ Err(error) => Err(error).with_context(|| format!("reading {}", path.display())),
+ }
}
pub(super) fn last_lines(text: &str, lines: usize) -> String {
diff --git a/host/src/dev_servers/mod.rs b/host/src/dev_servers/mod.rs
index 1a6c4730..e91f33a0 100644
--- a/host/src/dev_servers/mod.rs
+++ b/host/src/dev_servers/mod.rs
@@ -23,7 +23,7 @@ use crate::agent::process::Process;
use crate::analytics::{self, Event};
use crate::hub::Hub;
use crate::store::Store;
-use anyhow::{Result, anyhow, bail};
+use anyhow::{Result, anyhow};
use detected::Detected;
use ports::Port;
use serde::{Deserialize, Serialize};
@@ -259,13 +259,8 @@ impl DevServers {
}
}
- /// A bot's server by what it runs and where: starting the same thing twice isn't two servers.
fn same(&self, bot: &str, folder: &str, command: &str) -> Option<String> {
- self.live
- .locked()
- .values()
- .find(|live| live.saved.bot == bot && live.saved.folder == folder && live.saved.command == command)
- .map(|live| live.saved.id.clone())
+ same_server(&self.live.locked(), bot, folder, command)
}
fn view(&self, bot: &str, id: &str) -> Result<View> {
@@ -313,15 +308,28 @@ fn report(hub: &Hub, event: Event, key: &str, value: &str) {
analytics::capture(hub, event, properties);
}
-/// Refuses another running server past the limit, saying which ones run.
+/// A bot's server by what it runs and where: starting the same thing twice isn't two servers.
+fn same_server(live: &HashMap<String, Live>, bot: &str, folder: &str, command: &str) -> Option<String> {
+ live.values()
+ .find(|live| live.saved.bot == bot && live.saved.folder == folder && live.saved.command == command)
+ .map(|live| live.saved.id.clone())
+}
+
+/// Whether `bot` may run one more.
+fn has_room(live: &HashMap<String, Live>, bot: &str) -> bool {
+ live.values().filter(|live| live.saved.bot == bot && live.status.active()).count() < MAX_RUNNING
+}
+
+/// The refusal past the limit, saying which ones run. Call it with the servers unlocked.
+fn no_room(hub: &Hub, bot: &str) -> anyhow::Error {
+ report(hub, Event::DevServerStarted, "outcome", "limit");
+ anyhow!("at most {MAX_RUNNING} dev servers run at once; stop one first. Running: {}", hub.dev_servers.wire(bot))
+}
+
+/// Refuses another running server past the limit, before asking anyone about it. Only what starts one decides, under
+/// the lock that adds it: parallel starts can all pass here, and an approval card can take minutes.
fn check_room(hub: &Hub, bot: &str) -> Result<()> {
- let running =
- hub.dev_servers.live.locked().values().filter(|live| live.saved.bot == bot && live.status.active()).count();
- if running >= MAX_RUNNING {
- report(hub, Event::DevServerStarted, "outcome", "limit");
- bail!("at most {MAX_RUNNING} dev servers run at once; stop one first. Running: {}", hub.dev_servers.wire(bot));
- }
- Ok(())
+ if has_room(&hub.dev_servers.live.locked(), bot) { Ok(()) } else { Err(no_room(hub, bot)) }
}
/// A server's recent output, for the apps.
diff --git a/host/src/dev_servers/ports.rs b/host/src/dev_servers/ports.rs
index adc6ebd4..a33fa5d5 100644
--- a/host/src/dev_servers/ports.rs
+++ b/host/src/dev_servers/ports.rs
@@ -67,6 +67,8 @@ pub(super) fn urls_with(sockets: &[SocketAddr], reachable: impl Fn(u16) -> Vec<S
by_port
.into_iter()
.map(|(port, sockets)| {
+ // ponytail: an `IPV6_V6ONLY` socket on `[::]` counts too, though it serves none of these IPv4 addresses;
+ // the socket doesn't say. Add IPv6 addresses to `reachable` if a server like that turns up.
let everywhere = sockets.iter().any(|s| s.ip().is_unspecified());
let on_loopback = everywhere || sockets.iter().any(|s| s.ip().is_loopback());
let specific: Vec<String> = sockets
diff --git a/host/src/dev_servers/run.rs b/host/src/dev_servers/run.rs
index 1f433554..11615eea 100644
--- a/host/src/dev_servers/run.rs
+++ b/host/src/dev_servers/run.rs
@@ -1,7 +1,8 @@
//! Starting and stopping: a server is the host's own child in a tree of its own.
use super::{
- Leader, Live, Run, STOP_GRACE, STOP_WAIT, Saved, Status, check_room, detected, forget, logs, platform, report, save,
+ Leader, Live, Run, STOP_GRACE, STOP_WAIT, Saved, Status, detected, forget, has_room, logs, no_room, platform,
+ report, same_server, save,
};
use crate::LockExt;
use crate::agent::process::{self, Process};
@@ -16,7 +17,8 @@ use tokio::sync::watch;
const EXIT_POLL: Duration = Duration::from_millis(200);
-/// Adds a new server and starts it. `approved`: someone allowed it on a card.
+/// Adds a new server and starts it, or returns the same one a parallel start already added, saying so with true.
+/// `approved`: someone allowed it on a card.
pub(super) async fn create(
hub: &Arc<Hub>,
bot: &str,
@@ -24,7 +26,7 @@ pub(super) async fn create(
command: String,
folder: String,
approved: bool,
-) -> Result<String> {
+) -> Result<(String, bool)> {
let id = uuid::Uuid::now_v7().to_string();
let saved = Saved {
id: id.clone(),
@@ -38,10 +40,23 @@ pub(super) async fn create(
leader: None,
boot_ms: None,
};
- save(&hub.store, &saved);
- hub.dev_servers.live.locked().insert(id.clone(), Live::stopped(saved));
- launch(hub, &id).await?;
- Ok(id)
+ {
+ let mut live = hub.dev_servers.live.locked();
+ // A parallel start of the same thing got here first, while this one waited on its card.
+ if let Some(same) = same_server(&live, bot, &saved.folder, &saved.command) {
+ return Ok((same, true));
+ }
+ if !has_room(&live, bot) {
+ drop(live);
+ return Err(no_room(hub, bot));
+ }
+ save(&hub.store, &saved);
+ let mut server = Live::stopped(saved.clone());
+ server.begin(now_ms());
+ live.insert(id.clone(), server);
+ }
+ run_begun(hub, saved).await.inspect_err(|_| report(hub, Event::DevServerStarted, "outcome", "failed"))?;
+ Ok((id, false))
}
/// Starts a stopped server: the host's own child in a tree of its own, its output going to its log.
@@ -54,9 +69,20 @@ pub(super) async fn launch(hub: &Arc<Hub>, id: &str) -> Result<()> {
entry.stop_asked = false;
return Ok(());
}
+ let bot = entry.saved.bot.clone();
+ if !has_room(&live, &bot) {
+ drop(live);
+ return Err(no_room(hub, &bot));
+ }
+ let entry = live.get_mut(id).expect("found above, under this same lock");
entry.begin(now_ms());
entry.saved.clone()
};
+ run_begun(hub, saved).await
+}
+
+/// Runs a server just marked as starting.
+async fn run_begun(hub: &Arc<Hub>, saved: Saved) -> Result<()> {
hub.emit_bot(&saved.bot);
// A task of its own: a request that goes away (a closed connection, a cancelled tool call) can't abandon it halfway.
tokio::spawn(start(hub.clone(), saved)).await?
@@ -177,7 +203,7 @@ fn finished(hub: &Hub, id: &str, asked: bool, code: Option<i32>) {
/// Stops a server and waits until it ended; for what a bot left running through its shell, ends that.
pub async fn stop(hub: &Hub, bot: &str, id: &str, by: &str) -> Result<()> {
- if detected::stop(hub, bot, id)? {
+ if detected::stop(hub, bot, id).await? {
report(hub, Event::DevServerStopped, "by", by);
return Ok(());
}
@@ -198,12 +224,10 @@ pub async fn stop(hub: &Hub, bot: &str, id: &str, by: &str) -> Result<()> {
Ok(())
}
-/// Starts it again, stopping it first if it runs. A stopped one would be one more, so the limit holds here too.
+/// Starts it again, stopping it first if it runs.
pub async fn restart(hub: &Arc<Hub>, bot: &str, id: &str) -> Result<()> {
if hub.dev_servers.view(bot, id)?.status.active() {
stop(hub, bot, id, "restart").await?;
- } else {
- check_room(hub, bot)?;
}
launch(hub, id).await
}
diff --git a/host/src/dev_servers/scan.rs b/host/src/dev_servers/scan.rs
index 75e68894..a223fc6b 100644
--- a/host/src/dev_servers/scan.rs
+++ b/host/src/dev_servers/scan.rs
@@ -83,7 +83,7 @@ impl DevServers {
})
}
- fn agents_running(&self) -> Vec<detected::RunningAgent> {
+ pub(super) fn agents_running(&self) -> Vec<detected::RunningAgent> {
let mut agents = self.agents.locked();
agents.retain(|_, agent| agent.acp.strong_count() > 0);
agents
diff --git a/host/src/dev_servers/tests.rs b/host/src/dev_servers/tests.rs
index e1f5fd3e..74279090 100644
--- a/host/src/dev_servers/tests.rs
+++ b/host/src/dev_servers/tests.rs
@@ -1,5 +1,5 @@
-use super::detected::{Detected, agent_programs, changes, servers_in};
-use super::logs::last_lines;
+use super::detected::{Detected, agent_programs, changes, servers_in, still_in_tree};
+use super::logs::{last_lines, read_end};
use super::platform::same_boot;
use super::ports::{Listening, Port, sockets_of, urls_with};
use super::scan::SETTLE_MS;
@@ -255,3 +255,19 @@ fn a_clients_status_from_a_newer_host_reads_as_stopped() {
assert_eq!(serde_json::from_str::<Status>(r#""sleeping""#).expect("any text decodes"), Status::Stopped);
assert_eq!(serde_json::from_str::<Status>(r#""failed""#).expect("a known one decodes"), Status::Failed);
}
+
+#[test]
+fn stopping_a_detected_server_reaches_only_what_the_agent_still_holds() {
+ let tree = [process(30, 1, "python3"), process(40, 1, "node")];
+ assert_eq!(still_in_tree(&[30, 31], &tree), [30], "31 is gone, and its pid may be someone else's by now");
+ assert_eq!(still_in_tree(&[31], &[]), Vec::<u32>::new());
+}
+
+#[test]
+fn a_log_that_cant_be_read_says_so_and_a_missing_one_is_empty() {
+ let folder = std::env::temp_dir().join(format!("codync-log-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&folder).expect("a folder in a test");
+ assert_eq!(read_end(&folder.join("none.log")).expect("no file yet"), "");
+ assert!(read_end(&folder).is_err(), "a folder isn't a log");
+ std::fs::remove_dir_all(&folder).expect("cleaning up a test's folder");
+}
diff --git a/host/src/dev_servers/tools.rs b/host/src/dev_servers/tools.rs
index bacd8700..9a4e695b 100644
--- a/host/src/dev_servers/tools.rs
+++ b/host/src/dev_servers/tools.rs
@@ -103,8 +103,8 @@ async fn start(hub: &Arc<Hub>, bot: &str, args: &Value) -> Result<Value> {
if let Some(id) = servers.same(bot, &folder, &command) {
// A stopped one comes back, with no second card if someone allowed it; under Auto nobody did.
if !servers.view(bot, &id)?.status.active() {
- check_room(hub, bot)?;
if !servers.approved(&id) {
+ check_room(hub, bot)?;
ask(hub, &cfg, &command, &folder).await?;
if on_a_card {
servers.note_approved(&hub.store, &id);
@@ -123,14 +123,15 @@ async fn start(hub: &Arc<Hub>, bot: &str, args: &Value) -> Result<Value> {
.map(str::to_owned)
.or_else(|| Path::new(&folder).file_name().map(|name| name.to_string_lossy().into_owned()))
.unwrap_or_else(|| "dev server".to_owned());
- let id = match create(hub, bot, name, command, folder, on_a_card).await {
- Ok(id) => id,
- Err(error) => {
- report(hub, Event::DevServerStarted, "outcome", "failed");
- return Err(error);
+ let (id, reused) = create(hub, bot, name, command, folder, on_a_card).await?;
+ if reused {
+ // A parallel start added it while this one waited on its card, and it may have ended since.
+ if on_a_card {
+ servers.note_approved(&hub.store, &id);
}
- };
- answer(hub, bot, &id, false).await
+ launch(hub, &id).await?;
+ }
+ answer(hub, bot, &id, reused).await
}
/// Under Ask, waits on the approval card with the command and folder.
@@ -176,6 +177,8 @@ async fn answer(hub: &Arc<Hub>, bot: &str, id: &str, reused: bool) -> Result<Val
report(hub, Event::DevServerStarted, "outcome", outcome);
let mut answer = json!(view);
answer["reused"] = reused.into();
- answer["log"] = logs::tail(id, ANSWER_LINES).await?.into();
+ // How the start went is settled by now: a log that can't be shown mustn't turn that into a failed start.
+ let log = logs::tail(id, ANSWER_LINES).await;
+ answer["log"] = log.unwrap_or_else(|error| format!("couldn't read its log: {error:#}")).into();
Ok(answer)
}
diff --git a/host/src/tui/manage/dev_servers.rs b/host/src/tui/manage/dev_servers.rs
index ce900936..a530bf05 100644
--- a/host/src/tui/manage/dev_servers.rs
+++ b/host/src/tui/manage/dev_servers.rs
@@ -149,6 +149,8 @@ pub struct LogsView {
/// The line under its name: the command, and how it ended if it failed.
pub detail: String,
pub text: Option<String>,
+ /// Why the last read failed. What an earlier one read stays in `text`.
+ pub error: Option<String>,
pub scroll: usize,
}
@@ -159,12 +161,18 @@ impl App {
}
/// The answer to `read_logs`, for the sheet still showing that server.
- pub(super) fn dev_server_logs(&mut self, id: &str, text: String) {
+ pub(super) fn dev_server_logs(&mut self, id: &str, read: Result<String, String>) {
for overlay in &mut self.overlays {
if let Overlay::DevServers(sheet) = overlay
&& let Some(logs) = sheet.logs.as_mut().filter(|logs| logs.id == id)
{
- logs.text = Some(text);
+ match read {
+ Ok(text) => {
+ logs.text = Some(text);
+ logs.error = None;
+ }
+ Err(error) => logs.error = Some(error),
+ }
return;
}
}
@@ -221,7 +229,7 @@ impl App {
Some(note) => format!("{} · {note}", server.command),
None => server.command.clone(),
};
- LogsView { id: server.id.clone(), name: server.name.clone(), detail, text: None, scroll: 0 }
+ LogsView { id: server.id.clone(), name: server.name.clone(), detail, text: None, error: None, scroll: 0 }
}
/// In this computer's browser. Anywhere else (a tunnel looks the same from here) shows where it can be reached.
@@ -295,9 +303,9 @@ mod tests {
assert!(only_here[0].starts_with("http://localhost:5173 · "), "{only_here:?}");
// The first port listens only on the computer; the second doesn't.
assert_eq!(with(vec![port(&[]), port(&[lan])]).reachable(), [lan]);
- assert!(with(vec![]).reachable().is_empty());
+ assert_eq!(with(vec![]).reachable(), Vec::<String>::new());
let stopped = DevServer { ports: vec![port(&[lan])], ..server(Status::Stopped, None) };
- assert!(stopped.reachable().is_empty());
+ assert_eq!(stopped.reachable(), Vec::<String>::new());
}
#[test]
diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rs
index 4dd7c4d3..475834bf 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -63,7 +63,7 @@ impl App {
}
Reply::DevServerLogs(id) => {
let text = v["text"].as_str().unwrap_or_default().to_owned();
- self.dev_server_logs(&id, text);
+ self.dev_server_logs(&id, Ok(text));
}
Reply::BotChat { bot, peer } => {
let entries = entries_of(&v);
@@ -305,10 +305,7 @@ impl App {
self.unfolded.retain(|id| !lines.contains(id));
self.flash(&e);
}
- Reply::DevServerLogs(id) => {
- self.flash(&e);
- self.dev_server_logs(id, String::new());
- }
+ Reply::DevServerLogs(id) => self.dev_server_logs(id, Err(e)),
Reply::BotChat { bot, peer } => {
for o in &mut self.overlays {
if let Overlay::BotChat(c) = o
diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rs
index 91047c0a..e6a8832c 100644
--- a/host/src/tui/sheets.rs
+++ b/host/src/tui/sheets.rs
@@ -24,18 +24,13 @@ use super::manage::{AgentSetup, Fields, Page, RoutineField, RoutineForm, Routine
use super::md::truncate;
use super::view::{
centered, chain_line, composer_lines, frame_box, hline, input_line, put, restyle, rput, set_cursor, theme, u,
- using_line, when_future,
+ using_line, when_future, window,
};
fn s<'a>(v: &'a Value, k: &str) -> &'a str {
v[k].as_str().unwrap_or_default()
}
-/// Rows `off..` of a list that fit `h` lines with `cursor` on screen.
-fn window(cursor: usize, h: usize) -> usize {
- cursor.saturating_sub(h.saturating_sub(1))
-}
-
/// A selectable row's background, highlighted when `sel`.
fn row(buf: &mut Buffer, inner: Rect, y: u16, sel: bool) -> Style {
let t = theme();
diff --git a/host/src/tui/view/buffer.rs b/host/src/tui/view/buffer.rs
index 69aa8c0c..2d92a29c 100644
--- a/host/src/tui/view/buffer.rs
+++ b/host/src/tui/view/buffer.rs
@@ -95,6 +95,11 @@ pub(in crate::tui) fn centered(area: Rect, width: u16, height: u16) -> Rect {
Rect::new(area.x + (area.width - wd) / 2, area.y + (area.height - h) / 3, wd, h)
}
+/// Rows to skip of a list that fits `h` lines, to keep `cursor` on screen.
+pub(in crate::tui) fn window(cursor: usize, h: usize) -> usize {
+ cursor.saturating_sub(h.saturating_sub(1))
+}
+
pub(in crate::tui) fn u(n: usize) -> u16 {
u16::try_from(n).unwrap_or(u16::MAX)
}
diff --git a/host/src/tui/view/dev_servers.rs b/host/src/tui/view/dev_servers.rs
index 850eb4d9..7f71820a 100644
--- a/host/src/tui/view/dev_servers.rs
+++ b/host/src/tui/view/dev_servers.rs
@@ -6,7 +6,8 @@ use ratatui::layout::Rect;
use super::super::app::{App, Bot, Click};
use super::super::l10n::tr;
use super::super::manage::{DevServer, DevServerSummary, DevServersSheet, LogsView, dev_server_summary};
-use super::buffer::{centered, frame_box, hline, put, rput, u};
+use super::buffer::{centered, frame_box, hline, put, rput, u, window};
+use super::network::wrapped;
use super::style::theme;
use crate::dev_servers::Status;
@@ -49,8 +50,7 @@ fn list(buf: &mut Buffer, area: Rect, app: &App, sheet: &DevServersSheet) {
}
let address_lines = u(addresses.len()).min(inner.height - 4);
let rows = usize::from(inner.height - 3 - address_lines);
- for (i, server) in servers.iter().take(rows).enumerate() {
- let y = inner.y + u16::try_from(i).unwrap_or(0);
+ for (y, (i, server)) in (inner.y..).zip(servers.iter().enumerate().skip(window(selected, rows)).take(rows)) {
let chosen = i == selected;
let row = if chosen { t.sel.patch(t.panel) } else { t.panel };
for x in inner.x..inner.right() {
@@ -83,34 +83,51 @@ fn log_view(buf: &mut Buffer, area: Rect, logs: &LogsView) {
put(buf, inner.x, inner.y, inner.width, &logs.detail, t.dim.patch(t.panel));
hline(buf, inner.x, inner.y + 1, inner.width, t.dim.patch(t.panel));
let body = Rect::new(inner.x, inner.y + 2, inner.width, inner.height - 4);
- match &logs.text {
- None => {
+ match (&logs.error, logs.text.as_deref()) {
+ (Some(error), text) => {
+ let mut y = body.y;
+ wrapped(buf, body, &mut y, error, t.red);
+ let below = Rect::new(body.x, y, body.width, body.bottom().saturating_sub(y));
+ log_lines(buf, below, text.unwrap_or_default(), logs.scroll);
+ }
+ (None, None) => {
put(buf, body.x, body.y, body.width, &tr("Loading…"), t.dim.patch(t.panel));
}
- Some(text) if text.is_empty() => {
+ (None, Some("")) => {
put(buf, body.x, body.y, body.width, &tr("No output yet"), t.dim.patch(t.panel));
}
- Some(text) => {
- let lines: Vec<&str> = text.lines().collect();
- let height = usize::from(body.height);
- let end = lines.len().saturating_sub(logs.scroll).max(height.min(lines.len()));
- let start = end.saturating_sub(height);
- for (i, line) in lines[start..end].iter().enumerate() {
- let y = body.y + u16::try_from(i).unwrap_or(0);
- put(buf, body.x, y, body.width, line, t.text.patch(t.panel));
- }
- }
+ (None, Some(text)) => log_lines(buf, body, text, logs.scroll),
}
hline(buf, inner.x, inner.bottom() - 2, inner.width, t.dim.patch(t.panel));
put(buf, inner.x, inner.bottom() - 1, inner.width, &tr(" ↑↓ scroll · r refresh · esc back"), t.dim.patch(t.panel));
}
+/// The end of `text` that fits `body`, `scroll` lines up from the last.
+fn log_lines(buf: &mut Buffer, body: Rect, text: &str, scroll: usize) {
+ let t = theme();
+ let lines: Vec<&str> = text.lines().collect();
+ let height = usize::from(body.height);
+ let end = lines.len().saturating_sub(scroll).max(height.min(lines.len()));
+ let start = end.saturating_sub(height);
+ for (y, line) in (body.y..).zip(&lines[start..end]) {
+ put(buf, body.x, y, body.width, line, t.text.patch(t.panel));
+ }
+}
+
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
- use crate::tui::app::test_app;
+ use crate::tui::app::{Overlay, test_app};
+ use crate::tui::manage::Reply;
+
+ /// What `draw` leaves in `area`, line by line.
+ fn screen(area: Rect, draw: impl FnOnce(&mut Buffer)) -> Vec<String> {
+ let mut buf = Buffer::empty(area);
+ draw(&mut buf);
+ (0..area.height).map(|y| (0..area.width).map(|x| buf[(x, y)].symbol()).collect()).collect()
+ }
#[tokio::test]
async fn elsewhere_the_sheet_lists_every_address_of_the_selected_server_whole() {
@@ -122,22 +139,74 @@ mod tests {
app.bots.insert("b".into(), Bot::parse(&bot).expect("a bot with servers parses"));
let sheet = DevServersSheet { bot: "b".into(), selected: 0, logs: None };
let area = Rect::new(0, 0, 100, 24);
- let screen = |app: &App| {
- let mut buf = Buffer::empty(area);
- list(&mut buf, area, app, &sheet);
- (0..area.height)
- .map(|y| (0..area.width).map(|x| buf[(x, y)].symbol()).collect::<String>())
- .collect::<Vec<_>>()
- };
+ let shown = |app: &App| screen(area, |buf| list(buf, area, app, &sheet));
app.on_this_computer = false;
- let lines = screen(&app);
+ let lines = shown(&app);
let at = |address: &str| lines.iter().position(|line| line.contains(address));
let rows: Vec<_> = addresses.iter().map(|address| at(address).expect("the whole address shows")).collect();
assert_eq!(rows, [rows[0], rows[0] + 1, rows[0] + 2], "one line each");
assert!(at("npm run dev") < Some(rows[0]), "under the servers");
app.on_this_computer = true;
- assert!(!screen(&app).concat().contains("100.64.0.1"), "a browser opens here");
+ assert!(!shown(&app).concat().contains("100.64.0.1"), "a browser opens here");
+ }
+
+ #[tokio::test]
+ async fn the_selected_server_stays_on_screen_when_more_servers_exist_than_fit() {
+ let servers: Vec<_> = (0..8)
+ .map(|i| {
+ json!({"id": format!("s{i}"), "name": format!("server-{i}"), "command": "x", "status": "stopped",
+ "ports": [], "managed": true})
+ })
+ .collect();
+ let mut app = test_app();
+ let bot = json!({"id": "b", "name": "Bot", "devServers": servers});
+ app.bots.insert("b".into(), Bot::parse(&bot).expect("a bot with servers parses"));
+ let area = Rect::new(0, 0, 100, 10);
+ let shown = |selected| {
+ let sheet = DevServersSheet { bot: "b".into(), selected, logs: None };
+ screen(area, |buf| list(buf, area, &app, &sheet)).concat()
+ };
+
+ assert!(shown(7).contains("▸ server-7"), "{}", shown(7));
+ assert!(shown(0).contains("▸ server-0"), "{}", shown(0));
+ assert!(!shown(0).contains("server-7"), "only what fits");
+ }
+
+ #[tokio::test]
+ async fn a_failed_read_says_why_and_keeps_what_an_earlier_one_read() {
+ let mut app = test_app();
+ let view = LogsView {
+ id: "a".into(),
+ name: "web".into(),
+ detail: "npm run dev".into(),
+ text: None,
+ error: None,
+ scroll: 0,
+ };
+ app.overlays.push(Overlay::DevServers(DevServersSheet { bot: "b".into(), selected: 0, logs: Some(view) }));
+ let area = Rect::new(0, 0, 100, 24);
+ let reply = |app: &mut App, read: Result<&str, &str>| {
+ let read = read.map(|text| json!({"text": text})).map_err(str::to_owned);
+ app.on_sheet_reply(Reply::DevServerLogs("a".into()), read);
+ let Some(Overlay::DevServers(DevServersSheet { logs: Some(logs), .. })) = app.overlays.last() else {
+ panic!("the log is open")
+ };
+ screen(area, |buf| log_view(buf, area, logs)).concat()
+ };
+
+ let failed = reply(&mut app, Err("reading a.log: denied"));
+ assert!(failed.contains("reading a.log: denied"), "{failed}");
+ assert!(!failed.contains("No output yet") && !failed.contains("Loading"), "{failed}");
+
+ let read = reply(&mut app, Ok("first line"));
+ assert!(read.contains("first line") && !read.contains("denied"), "{read}");
+
+ let failed = reply(&mut app, Err("reading a.log: denied"));
+ assert!(failed.contains("denied") && failed.contains("first line"), "{failed}");
+
+ let empty = reply(&mut app, Ok(""));
+ assert!(empty.contains("No output yet") && !empty.contains("denied"), "{empty}");
}
}
diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rs
index 7e14b5e5..f544f551 100644
--- a/host/src/tui/view/mod.rs
+++ b/host/src/tui/view/mod.rs
@@ -33,7 +33,7 @@ mod trace;
mod transcript;
mod usage;
-pub(super) use buffer::{centered, frame_box, hline, put, restyle, rput, u};
+pub(super) use buffer::{centered, frame_box, hline, put, restyle, rput, u, window};
pub(super) use chat::composer_lines;
pub(super) use fallbacks::{chain_line, using_line};
pub(super) use lead_agent::lead_agent_scroll_max;
diff --git a/host/tests/common/host.rs b/host/tests/common/host.rs
index a08425c7..25367f25 100644
--- a/host/tests/common/host.rs
+++ b/host/tests/common/host.rs
@@ -28,8 +28,13 @@ impl Drop for Host {
impl Host {
pub async fn start() -> Self {
+ Self::start_with(&[]).await
+ }
+
+ /// [`Self::start`] with `env` on top of the test host's own. [`Self::restart`] doesn't keep it.
+ pub async fn start_with(env: &[(&str, &std::ffi::OsStr)]) -> Self {
let home = std::env::temp_dir().join(format!("codync-memory-e2e-{}", uuid::Uuid::new_v4()));
- let (child, base) = super::serve(&home).await;
+ let (child, base) = super::serve_with(&home, env).await;
let token = std::fs::read_to_string(home.join("token")).unwrap().trim().to_owned();
Self { child, home, base, token }
}
diff --git a/host/tests/dev_server_e2e.rs b/host/tests/dev_server_e2e.rs
index 44b51f94..fbca93b2 100644
--- a/host/tests/dev_server_e2e.rs
+++ b/host/tests/dev_server_e2e.rs
@@ -5,6 +5,11 @@
mod common;
+#[path = "dev_server_e2e/cards.rs"]
+mod cards;
+#[path = "dev_server_e2e/detected.rs"]
+mod detected;
+
use common::host::Host;
use serde_json::{Value, json};
use std::net::{TcpListener, TcpStream};
@@ -16,9 +21,11 @@ fn free_port() -> u16 {
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
-/// A free port below where the system hands out its own, the range a server someone opens sits in.
+/// A free port below where the system hands out its own, the range a server someone opens sits in. Looked for from
+/// somewhere random: tests run side by side and a port only stays free until its server takes it.
fn free_low_port() -> u16 {
- (20_000..32_000).find(|port| TcpListener::bind(("127.0.0.1", *port)).is_ok()).unwrap()
+ let from = 20_000 + u16::try_from(uuid::Uuid::new_v4().as_u128() % 10_000).unwrap();
+ (from..32_000).find(|port| TcpListener::bind(("127.0.0.1", *port)).is_ok()).unwrap()
}
fn serves(port: u16) -> bool {
@@ -381,132 +388,89 @@ async fn deleting_a_bot_ends_its_servers() {
}
#[tokio::test]
-async fn under_ask_a_start_needs_a_turn_to_ask_in() {
+async fn a_log_that_cant_be_read_fails_reading_it_not_a_start() {
let host = Host::start().await;
- let bot = host.bot("Builder", "ask").await;
- let arguments = json!({"command": sleeper(300)});
+ let bot = host.bot("Builder", "auto").await;
+ let port = free_port();
+ let command = server_command(port);
+ let started = start(&host, &bot, &command, "web").await;
+ let id = started["id"].as_str().unwrap();
+ // A folder where its log should be. The running server keeps writing to the file, moved aside.
+ let log = host.home.join("dev-servers").join(format!("{id}.log"));
+ std::fs::rename(&log, log.with_extension("moved")).unwrap();
+ std::fs::create_dir(&log).unwrap();
+
+ let again = start(&host, &bot, &command, "web").await;
+ assert_eq!(again["id"], started["id"], "{again}");
+ assert_eq!(again["status"], "running", "{again}");
+ assert!(again["log"].as_str().unwrap().contains("couldn't read its log"), "{again}");
+
+ let refused = host.refused("devServerLogs", json!({"botId": bot, "id": id})).await;
+ assert!(refused.contains("reading"), "{refused}");
+ let arguments = json!({"id": id});
let refused =
- host.refused("chatCall", json!({"botId": bot, "name": "start_dev_server", "arguments": arguments})).await;
- assert!(refused.contains("didn't allow"), "{refused}");
- assert_eq!(servers(&host, &bot).await, Vec::<Value>::new());
-}
-
-/// What makes the fixture agent call the tool through its real chat helper, in a turn.
-fn start_through_agent(command: &str) -> String {
- format!("CHAT start_dev_server {}", json!({"command": command, "name": "web"}))
-}
+ host.refused("chatCall", json!({"botId": bot, "name": "dev_server_logs", "arguments": arguments})).await;
+ assert!(refused.contains("reading"), "{refused}");
-async fn entry(host: &Host, bot: &str, found: impl Fn(&Value) -> bool) -> Value {
- let deadline = Instant::now() + Duration::from_secs(40);
- loop {
- let history = host.call("history", json!({"botId": bot})).await;
- if let Some(entry) = history["entries"].as_array().unwrap().iter().find(|e| found(e)) {
- return entry.clone();
- }
- assert!(Instant::now() < deadline, "{bot}: {history}");
- tokio::time::sleep(Duration::from_millis(50)).await;
- }
+ std::fs::remove_dir(&log).unwrap();
+ let logs = host.call("devServerLogs", json!({"botId": bot, "id": id})).await;
+ assert_eq!(logs["text"], "", "no file is only an empty log");
+ stop(&host, &bot, &started["id"], port).await;
}
-/// Has the agent start `command`, answers its card with `option`, and returns the agent's reply.
-async fn through_card(host: &Host, bot: &str, command: &str, option: &str, check: impl Fn(&str)) -> String {
- host.call("send", json!({"botId": bot, "text": start_through_agent(command)})).await;
- let card = entry(host, bot, |e| {
- e["kind"] == "permission" && e["data"]["status"] == "pending" && e["data"]["title"] == "Start a dev server"
- })
- .await;
- check(card["data"]["detail"].as_str().unwrap());
- host.call("respondPermission", json!({"entryId": card["id"], "optionId": option})).await;
- let reply =
- entry(host, bot, |e| e["kind"] == "agent" && e["data"]["final"] == true && e["turn"] == card["turn"]).await;
- reply["data"]["text"].as_str().unwrap().to_owned()
+/// One call for each of `bodies`, all at once.
+async fn at_once(host: &Host, method: &str, bodies: &[Value]) -> Vec<(bool, Value)> {
+ futures::future::join_all(bodies.iter().map(|body| host.post(method, body))).await
}
-async fn cards(host: &Host, bot: &str) -> usize {
- let history = host.call("history", json!({"botId": bot})).await;
- history["entries"].as_array().unwrap().iter().filter(|e| e["kind"] == "permission").count()
+fn refused(answers: &[(bool, Value)]) -> Vec<&Value> {
+ answers.iter().filter(|(ok, _)| !ok).map(|(_, answer)| answer).collect()
}
-#[tokio::test]
-async fn under_ask_a_start_waits_for_its_card() {
- let host = Host::start().await;
- let bot = host.fixture_bot("Builder", "team_agent.py", "").await;
- host.call("updateBot", json!({"id": bot, "permission": "ask"})).await;
-
- let denied = free_port();
- let reply = through_card(&host, &bot, &server_command(denied), "deny", |_| {}).await;
- assert!(reply.starts_with("Refused: ") && reply.contains("didn't allow"), "{reply}");
- assert_eq!(servers(&host, &bot).await, Vec::<Value>::new());
- assert!(!serves(denied));
-
- let folder = workspace(&host, &bot).await;
- let port = free_port();
- let command = server_command(port);
- let reply = through_card(&host, &bot, &command, "allow", |detail| {
- assert!(detail.contains(&command) && detail.contains(folder.to_str().unwrap()), "{detail}");
- })
- .await;
- assert!(reply.starts_with("Done: "), "{reply}");
- assert!(serves(port));
-
- // Allowed once, so a stopped one comes back with no second card.
- let id = servers(&host, &bot).await[0]["id"].clone();
- stop(&host, &bot, &id, port).await;
- let before = cards(&host, &bot).await;
- host.reply(&bot, &start_through_agent(&command)).await;
- assert!(serves(port));
- assert_eq!(cards(&host, &bot).await, before);
- stop(&host, &bot, &id, port).await;
+fn active(list: &[Value]) -> usize {
+ list.iter().filter(|s| s["status"] == "running" || s["status"] == "starting").count()
}
#[tokio::test]
-async fn a_server_nobody_allowed_gets_its_card_once_the_bot_is_under_ask() {
+async fn parallel_starts_make_one_server_of_one_command_and_keep_the_limit() {
let host = Host::start().await;
- let bot = host.fixture_bot("Builder", "team_agent.py", "").await;
- host.call("updateBot", json!({"id": bot, "permission": "auto"})).await;
- let port = free_port();
- let command = server_command(port);
- let started = start(&host, &bot, &command, "web").await;
- stop(&host, &bot, &started["id"], port).await;
- host.call("updateBot", json!({"id": bot, "permission": "ask"})).await;
-
- let reply = through_card(&host, &bot, &command, "deny", |_| {}).await;
- assert!(reply.starts_with("Refused: "), "{reply}");
- assert!(!serves(port));
+ let bot = host.bot("Builder", "auto").await;
+ let body = |command: String| json!({"botId": bot, "name": "start_dev_server", "arguments": {"command": command}});
- let reply = through_card(&host, &bot, &command, "allow", |_| {}).await;
- assert!(reply.starts_with("Done: "), "{reply}");
- assert!(serves(port));
+ let same = server_command(free_port());
+ let bodies: Vec<Value> = (0..4).map(|_| body(same.clone())).collect();
+ let answers = at_once(&host, "chatCall", &bodies).await;
+ assert!(answers.iter().all(|(ok, answer)| *ok && answer["id"] == answers[0].1["id"]), "{answers:?}");
+ assert_eq!(answers.iter().filter(|(_, answer)| answer["reused"] == false).count(), 1, "{answers:?}");
+ assert_eq!(servers(&host, &bot).await.len(), 1);
- stop(&host, &bot, &started["id"], port).await;
- let before = cards(&host, &bot).await;
- host.reply(&bot, &start_through_agent(&command)).await;
- assert_eq!(cards(&host, &bot).await, before, "now someone has allowed it");
- stop(&host, &bot, &started["id"], port).await;
+ // Four more fit.
+ let bodies: Vec<Value> = (0..7).map(|_| body(server_command(free_port()))).collect();
+ let answers = at_once(&host, "chatCall", &bodies).await;
+ let refusals = refused(&answers);
+ assert_eq!(refusals.len(), 3, "{answers:?}");
+ assert!(refusals.iter().all(|answer| answer["error"].as_str().unwrap().contains("at most 5")), "{refusals:?}");
+ assert_eq!(active(&servers(&host, &bot).await), 5);
}
#[tokio::test]
-async fn what_an_agent_leaves_running_shows_and_can_be_stopped() {
+async fn parallel_restarts_keep_the_limit() {
let host = Host::start().await;
- let port = free_low_port();
- let bot = agent_bot(&host, port).await;
- host.reply(&bot, "run it").await;
- let list = wait_for(&host, &bot, "the agent's server shows", |list| {
- list.iter().any(|s| s["managed"] == false && s["ports"][0]["port"] == port)
- })
- .await;
- let found = list.iter().find(|s| s["managed"] == false).unwrap();
- assert_eq!(found["status"], "running");
- assert!(found["id"].as_str().unwrap().starts_with("detected:"));
-
- // It can't start again, so asking leaves it running.
- let refused = host.refused("devServerRestart", json!({"botId": bot, "id": found["id"]})).await;
- assert!(refused.contains("unknown dev server"), "{refused}");
- assert!(serves(port));
+ let bot = host.bot("Builder", "auto").await;
+ let mut stopped = Vec::new();
+ for name in ["a", "b"] {
+ let port = free_port();
+ let started = start(&host, &bot, &server_command(port), name).await;
+ stop(&host, &bot, &started["id"], port).await;
+ stopped.push(json!({"botId": bot, "id": started["id"]}));
+ }
+ for n in 0..4 {
+ start(&host, &bot, &server_command(free_port()), &format!("s{n}")).await;
+ }
- stop(&host, &bot, &found["id"], port).await;
- wait_for(&host, &bot, "it no longer shows", <[Value]>::is_empty).await;
- // An id that was never found stops nothing.
- let error = host.refused("devServerStop", json!({"botId": bot, "id": "detected:1"})).await;
- assert!(error.contains("unknown dev server"), "{error}");
+ let answers = at_once(&host, "devServerRestart", &stopped).await;
+ let refusals = refused(&answers);
+ assert_eq!(refusals.len(), 1, "{answers:?}");
+ assert!(refusals[0]["error"].as_str().unwrap().contains("at most 5"), "{refusals:?}");
+ assert_eq!(active(&servers(&host, &bot).await), 5);
}
diff --git a/host/tests/dev_server_e2e/cards.rs b/host/tests/dev_server_e2e/cards.rs
new file mode 100644
index 00000000..88619fa6
--- /dev/null
+++ b/host/tests/dev_server_e2e/cards.rs
@@ -0,0 +1,145 @@
+//! Starts under Ask, which wait on an approval card.
+
+use super::*;
+
+#[tokio::test]
+async fn under_ask_a_start_needs_a_turn_to_ask_in() {
+ let host = Host::start().await;
+ let bot = host.bot("Builder", "ask").await;
+ let arguments = json!({"command": sleeper(300)});
+ let refused =
+ host.refused("chatCall", json!({"botId": bot, "name": "start_dev_server", "arguments": arguments})).await;
+ assert!(refused.contains("didn't allow"), "{refused}");
+ assert_eq!(servers(&host, &bot).await, Vec::<Value>::new());
+}
+
+/// What makes the fixture agent call the tool through its real chat helper, in a turn.
+fn start_through_agent(command: &str) -> String {
+ format!("CHAT start_dev_server {}", json!({"command": command, "name": "web"}))
+}
+
+async fn entry(host: &Host, bot: &str, found: impl Fn(&Value) -> bool) -> Value {
+ let deadline = Instant::now() + Duration::from_secs(40);
+ loop {
+ let history = host.call("history", json!({"botId": bot})).await;
+ if let Some(entry) = history["entries"].as_array().unwrap().iter().find(|e| found(e)) {
+ return entry.clone();
+ }
+ assert!(Instant::now() < deadline, "{bot}: {history}");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+/// Has the agent start `command`, answers its card with `option`, and returns the agent's reply.
+async fn through_card(host: &Host, bot: &str, command: &str, option: &str, check: impl Fn(&str)) -> String {
+ host.call("send", json!({"botId": bot, "text": start_through_agent(command)})).await;
+ let card = entry(host, bot, |e| {
+ e["kind"] == "permission" && e["data"]["status"] == "pending" && e["data"]["title"] == "Start a dev server"
+ })
+ .await;
+ check(card["data"]["detail"].as_str().unwrap());
+ host.call("respondPermission", json!({"entryId": card["id"], "optionId": option})).await;
+ let reply =
+ entry(host, bot, |e| e["kind"] == "agent" && e["data"]["final"] == true && e["turn"] == card["turn"]).await;
+ reply["data"]["text"].as_str().unwrap().to_owned()
+}
+
+async fn cards(host: &Host, bot: &str) -> usize {
+ let history = host.call("history", json!({"botId": bot})).await;
+ history["entries"].as_array().unwrap().iter().filter(|e| e["kind"] == "permission").count()
+}
+
+#[tokio::test]
+async fn under_ask_a_start_waits_for_its_card() {
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Builder", "team_agent.py", "").await;
+ host.call("updateBot", json!({"id": bot, "permission": "ask"})).await;
+
+ let denied = free_port();
+ let reply = through_card(&host, &bot, &server_command(denied), "deny", |_| {}).await;
+ assert!(reply.starts_with("Refused: ") && reply.contains("didn't allow"), "{reply}");
+ assert_eq!(servers(&host, &bot).await, Vec::<Value>::new());
+ assert!(!serves(denied));
+
+ let folder = workspace(&host, &bot).await;
+ let port = free_port();
+ let command = server_command(port);
+ let reply = through_card(&host, &bot, &command, "allow", |detail| {
+ assert!(detail.contains(&command) && detail.contains(folder.to_str().unwrap()), "{detail}");
+ })
+ .await;
+ assert!(reply.starts_with("Done: "), "{reply}");
+ assert!(serves(port));
+
+ // Allowed once, so a stopped one comes back with no second card.
+ let id = servers(&host, &bot).await[0]["id"].clone();
+ stop(&host, &bot, &id, port).await;
+ let before = cards(&host, &bot).await;
+ host.reply(&bot, &start_through_agent(&command)).await;
+ assert!(serves(port));
+ assert_eq!(cards(&host, &bot).await, before);
+ stop(&host, &bot, &id, port).await;
+}
+
+#[tokio::test]
+async fn a_server_nobody_allowed_gets_its_card_once_the_bot_is_under_ask() {
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Builder", "team_agent.py", "").await;
+ host.call("updateBot", json!({"id": bot, "permission": "auto"})).await;
+ let port = free_port();
+ let command = server_command(port);
+ let started = start(&host, &bot, &command, "web").await;
+ stop(&host, &bot, &started["id"], port).await;
+ host.call("updateBot", json!({"id": bot, "permission": "ask"})).await;
+
+ let reply = through_card(&host, &bot, &command, "deny", |_| {}).await;
+ assert!(reply.starts_with("Refused: "), "{reply}");
+ assert!(!serves(port));
+
+ let reply = through_card(&host, &bot, &command, "allow", |_| {}).await;
+ assert!(reply.starts_with("Done: "), "{reply}");
+ assert!(serves(port));
+
+ stop(&host, &bot, &started["id"], port).await;
+ let before = cards(&host, &bot).await;
+ host.reply(&bot, &start_through_agent(&command)).await;
+ assert_eq!(cards(&host, &bot).await, before, "now someone has allowed it");
+ stop(&host, &bot, &started["id"], port).await;
+}
+
+async fn pending_cards(host: &Host, bot: &str) -> Vec<Value> {
+ let history = host.call("history", json!({"botId": bot})).await;
+ let pending = |e: &&Value| e["kind"] == "permission" && e["data"]["status"] == "pending";
+ history["entries"].as_array().unwrap().iter().filter(pending).cloned().collect()
+}
+
+#[tokio::test]
+async fn an_allow_that_finds_the_server_ended_brings_it_back() {
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Builder", "team_agent.py", "").await;
+ host.call("updateBot", json!({"id": bot, "permission": "ask"})).await;
+ let port = free_port();
+ let arguments = json!({"command": server_command(port), "name": "web"});
+ let text = format!("CHAT_TWICE start_dev_server {arguments}");
+ host.call("send", json!({"botId": bot, "text": text})).await;
+ common::eventually("a card for each", Duration::from_secs(40), async || {
+ pending_cards(&host, &bot).await.len() == 2
+ })
+ .await;
+ let waiting = pending_cards(&host, &bot).await;
+
+ host.call("respondPermission", json!({"entryId": waiting[0]["id"], "optionId": "allow"})).await;
+ wait_running(&host, &bot, port).await;
+ let id = servers(&host, &bot).await[0]["id"].clone();
+ stop(&host, &bot, &id, port).await;
+
+ host.call("respondPermission", json!({"entryId": waiting[1]["id"], "optionId": "allow"})).await;
+ let reply =
+ entry(&host, &bot, |e| e["kind"] == "agent" && e["data"]["final"] == true && e["turn"] == waiting[0]["turn"])
+ .await;
+ let reply = reply["data"]["text"].as_str().unwrap();
+ assert!(reply.contains(r#""reused":true"#), "{reply}");
+ assert!(serves(port));
+ assert_eq!(servers(&host, &bot).await.len(), 1);
+ stop(&host, &bot, &id, port).await;
+}
diff --git a/host/tests/dev_server_e2e/detected.rs b/host/tests/dev_server_e2e/detected.rs
new file mode 100644
index 00000000..f94aacdb
--- /dev/null
+++ b/host/tests/dev_server_e2e/detected.rs
@@ -0,0 +1,70 @@
+//! What a bot leaves running through its shell.
+
+use super::*;
+
+#[tokio::test]
+async fn what_an_agent_leaves_running_shows_and_can_be_stopped() {
+ let host = Host::start().await;
+ let port = free_low_port();
+ let bot = agent_bot(&host, port).await;
+ host.reply(&bot, "run it").await;
+ let list = wait_for(&host, &bot, "the agent's server shows", |list| {
+ list.iter().any(|s| s["managed"] == false && s["ports"][0]["port"] == port)
+ })
+ .await;
+ let found = list.iter().find(|s| s["managed"] == false).unwrap();
+ assert_eq!(found["status"], "running");
+ assert!(found["id"].as_str().unwrap().starts_with("detected:"));
+
+ // It can't start again, so asking leaves it running.
+ let refused = host.refused("devServerRestart", json!({"botId": bot, "id": found["id"]})).await;
+ assert!(refused.contains("unknown dev server"), "{refused}");
+ assert!(serves(port));
+
+ stop(&host, &bot, &found["id"], port).await;
+ wait_for(&host, &bot, "it no longer shows", <[Value]>::is_empty).await;
+ // An id that was never found stops nothing.
+ let error = host.refused("devServerStop", json!({"botId": bot, "id": "detected:1"})).await;
+ assert!(error.contains("unknown dev server"), "{error}");
+}
+
+/// A `ps` that fails once a file named `broken` sits beside it, in a folder of its own to put first on a host's PATH.
+#[cfg(unix)]
+fn breakable_ps() -> PathBuf {
+ use std::os::unix::fs::PermissionsExt as _;
+ let folder = std::env::temp_dir().join(format!("codync-ps-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&folder).unwrap();
+ let script = format!("#!/bin/sh\n[ -e '{}/broken' ] && exit 1\nexec /bin/ps \"$@\"\n", folder.display());
+ std::fs::write(folder.join("ps"), script).unwrap();
+ std::fs::set_permissions(folder.join("ps"), std::fs::Permissions::from_mode(0o755)).unwrap();
+ folder
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn stopping_what_an_agent_left_running_fails_while_its_processes_cant_be_read() {
+ let folder = breakable_ps();
+ let path = std::env::join_paths(
+ std::iter::once(folder.clone()).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap())),
+ )
+ .unwrap();
+ let host = Host::start_with(&[("PATH", path.as_os_str())]).await;
+ let port = free_low_port();
+ let bot = agent_bot(&host, port).await;
+ host.reply(&bot, "run it").await;
+ let list = wait_for(&host, &bot, "the agent's server shows", |list| {
+ list.iter().any(|s| s["managed"] == false && s["ports"][0]["port"] == port)
+ })
+ .await;
+ let id = list.iter().find(|s| s["managed"] == false).unwrap()["id"].clone();
+
+ std::fs::write(folder.join("broken"), "").unwrap();
+ let refused = host.refused("devServerStop", json!({"botId": bot, "id": id})).await;
+ assert!(refused.contains("couldn't check the agent's processes"), "{refused}");
+ assert!(serves(port));
+ assert!(servers(&host, &bot).await.iter().any(|s| s["id"] == id), "it still shows");
+
+ std::fs::remove_file(folder.join("broken")).unwrap();
+ stop(&host, &bot, &id, port).await;
+ std::fs::remove_dir_all(&folder).unwrap();
+}
diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.py
index f7c0106c..e5d23cb6 100644
--- a/host/tests/fixtures/team_agent.py
+++ b/host/tests/fixtures/team_agent.py
@@ -6,6 +6,7 @@ import subprocess
import sys
import threading
import time
+from concurrent.futures import ThreadPoolExecutor
output_lock = threading.Lock()
cancel = threading.Event()
@@ -126,6 +127,15 @@ def prompt(request):
update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})
send({"id": request["id"], "result": {"stopReason": "end_turn"}})
return
+ if text.split("\n\n")[-1].startswith("CHAT_TWICE "):
+ # Two calls at once, as an agent's parallel tool calls are.
+ _, tool, arguments = text.split("\n\n")[-1].split(" ", 2)
+ with ThreadPoolExecutor(2) as pool:
+ responses = pool.map(lambda _: mcp_call("chat", tool, json.loads(arguments)), range(2))
+ reply = " | ".join(response["content"][0]["text"] for response in responses)
+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})
+ send({"id": request["id"], "result": {"stopReason": "end_turn"}})
+ return
if text.split("\n\n")[-1] == "OK":
update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "(pass)"}})
send({"id": request["id"], "result": {"stopReason": "end_turn"}})