Keep test consoles and slow restarts from taking over the desktop app's window

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-25 21:26:11 -07:00
1 parent 94063fc0a9
commit a2b43d1188
6 files changed
+282 -46

No files matched your search

+25 -9
View File
@@ -27,7 +27,9 @@ pub struct PageNotice {
pub workflow: String,
}
pub type OnPage = Arc<dyn Fn(PageNotice) + Send + Sync>;
/// Says whether the window took the page. Only a page it took becomes the
/// window's current session, so a refused one never steers the next `open`.
pub type OnPage = Arc<dyn Fn(PageNotice) -> bool + Send + Sync>;
pub struct AnnounceServer {
port: u16,
@@ -197,11 +199,15 @@ impl AnnounceServer {
.and_then(|(head, body)| check_request(&head, &body, &expected))
{
Ok(Request::Page(notice)) => {
if let Ok(mut slot) = shared.lock() {
*slot = Some(notice.clone());
if on_page(notice.clone()) {
if let Ok(mut slot) = shared.lock() {
*slot = Some(notice);
}
(204, String::new())
} else {
// `open` reads anything but 2xx as "the app did not take the page".
(409, String::new())
}
on_page(notice);
(204, String::new())
}
Ok(Request::Session) => {
let now = shared.lock().ok().and_then(|slot| slot.clone());
@@ -330,8 +336,8 @@ mod tests {
let (tx_a, rx_a) = channel();
let (tx_b, rx_b) = channel();
let (tx_a, tx_b) = (Mutex::new(tx_a), Mutex::new(tx_b));
let a = AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).unwrap())).unwrap();
let b = AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).unwrap())).unwrap();
let a = AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).is_ok())).unwrap();
let b = AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).is_ok())).unwrap();
assert_ne!(a.url(), b.url());
let port = |s: &AnnounceServer| s.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse::<u16>().unwrap();
@@ -343,7 +349,7 @@ mod tests {
#[test]
fn agent_env_names_this_windows_values() {
let server = AnnounceServer::start(Arc::new(|_| {})).unwrap();
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
let env = server.agent_env("http://127.0.0.1:1430", "3.0.0");
let get = |key: &str| env.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone());
assert_eq!(get("PLAN2CODE_IN_APP").as_deref(), Some("1"));
@@ -356,7 +362,7 @@ mod tests {
#[test]
fn the_current_session_is_what_was_announced_last() {
let server = AnnounceServer::start(Arc::new(|_| {})).unwrap();
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap();
let ask = |token: &str| {
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
@@ -374,4 +380,14 @@ mod tests {
assert!(ask(server.token()).ends_with("null"), "forgotten: the next open starts its own session");
assert_eq!(server.current(), None);
}
#[test]
fn a_page_the_window_refuses_is_not_its_session() {
// A test's throwaway console: remembered, it would steer the next
// agent `open` away from the window's real session.
let server = AnnounceServer::start(Arc::new(|_| false)).unwrap();
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap();
assert_eq!(post(port, server.token(), GOOD), 409, "open hears that the app did not take it");
assert_eq!(server.current(), None);
}
}
@@ -10,10 +10,17 @@ use std::time::Duration;
use serde::Serialize;
use crate::session_reader;
/// How long a health check waits for the console before calling it dead. The
/// server is on loopback, so anything longer is a hang, not a slow network.
const HEALTH_TIMEOUT: Duration = Duration::from_secs(3);
/// The second, longer look a server gets before it is restarted, as the
/// console's own `open` gives one: a machine busy with a test run can keep a
/// healthy server from answering inside the first.
const BUSY_HEALTH_TIMEOUT: Duration = Duration::from_secs(5);
/// A running console session, as `console.mjs open` reports it.
#[derive(Clone, Serialize)]
pub struct ConsoleSession {
@@ -247,6 +254,10 @@ impl ConsoleSupervisor {
/// A GET on the session URL: any HTTP answer means the server is alive.
pub fn health(&self) -> bool {
self.health_within(HEALTH_TIMEOUT)
}
fn health_within(&self, timeout: Duration) -> bool {
if self.stopped {
return false;
}
@@ -257,11 +268,11 @@ impl ConsoleSupervisor {
else {
return false;
};
let Ok(mut stream) = TcpStream::connect_timeout(&addr, HEALTH_TIMEOUT) else {
let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) else {
return false;
};
let _ = stream.set_read_timeout(Some(HEALTH_TIMEOUT));
let _ = stream.set_write_timeout(Some(HEALTH_TIMEOUT));
let _ = stream.set_read_timeout(Some(timeout));
let _ = stream.set_write_timeout(Some(timeout));
let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
if stream.write_all(request.as_bytes()).is_err() {
return false;
@@ -277,14 +288,15 @@ impl ConsoleSupervisor {
/// when a new session was started. Never loops: the caller (the bar) asks
/// and shows the outcome.
pub fn restart_if_dead(&mut self) -> Result<bool, String> {
if self.stopped || self.health() {
if self.stopped || self.health() || self.health_within(BUSY_HEALTH_TIMEOUT) {
return Ok(false);
}
// The same session first, so the page and a skill's place in it survive;
// a session that cannot be resumed (gone from disk) starts a new one.
let sid = self.session.sid.clone();
self.session = Self::open_session(&self.console_dir, &self.project_dir, &self.embed_origin, Some(&sid))
.or_else(|_| Self::open_session(&self.console_dir, &self.project_dir, &self.embed_origin, None))?;
let on_disk = session_on_disk(&sid);
let (console_dir, project_dir, embed_origin) = (&self.console_dir, &self.project_dir, &self.embed_origin);
self.session = resume_or_fresh(&sid, on_disk, |resume| {
Self::open_session(console_dir, project_dir, embed_origin, resume)
})?;
self.stopped = false;
Ok(true)
}
@@ -310,6 +322,31 @@ impl ConsoleSupervisor {
}
}
/// Is the session's folder still in the console's home. Unknown (no home
/// directory) counts as there, so the answer never throws a session away. A
/// sid that is not a plain folder name (empty, `..`, a path) is never there.
pub fn session_on_disk(sid: &str) -> bool {
if Path::new(sid).file_name() != Some(std::ffi::OsStr::new(sid)) {
return false;
}
session_reader::console_home().map_or(true, |home| session_reader::session_dir(&home, sid).is_dir())
}
/// The same session, so the page and a skill's place in it survive, tried
/// twice. Only a session gone from disk starts a new one: falling back to a
/// fresh dashboard while the folder is still there once swapped a build's page
/// for an empty dashboard mid-run, and the agent went on posting to a session
/// the window no longer showed. A failure is the bar's to report, with Retry.
fn resume_or_fresh<F>(sid: &str, on_disk: bool, mut open: F) -> Result<ConsoleSession, String>
where
F: FnMut(Option<&str>) -> Result<ConsoleSession, String>,
{
if !on_disk {
return open(None);
}
open(Some(sid)).or_else(|_| open(Some(sid)))
}
impl Drop for ConsoleSupervisor {
/// The app going away takes the console it started with it. `stop` is
/// idempotent, so a session ended by hand just returns early here.
@@ -358,6 +395,56 @@ mod tests {
sup.stopped = true;
}
fn opened(sid: &str) -> ConsoleSession {
ConsoleSession { sid: sid.to_string(), url: "http://127.0.0.1:5/s/t/".into(), pid: 1, port: 5, embed: true }
}
#[test]
fn only_a_plain_folder_name_can_be_a_session_on_disk() {
// `<home>/sessions/` and `<home>` are folders too: these must not pass.
for sid in ["", ".", "..", "../x", "a/b", "a\\b"] {
assert!(!session_on_disk(sid), "{sid:?} counted as a session");
}
}
#[test]
fn a_failed_resume_of_a_session_still_on_disk_never_opens_a_fresh_dashboard() {
// A build's console that was slow to answer: swapping its page for a
// new dashboard left the agent posting to a session nobody could see.
let mut calls = Vec::new();
let result = resume_or_fresh("s1", true, |resume| {
calls.push(resume.map(str::to_string));
Err("busy".to_string())
});
assert!(result.is_err(), "the failure is reported, not papered over");
assert!(calls.iter().all(|c| c.as_deref() == Some("s1")), "only ever resumed: {calls:?}");
assert_eq!(calls.len(), 2, "the resume is tried twice");
}
#[test]
fn a_resume_that_works_the_second_time_keeps_the_session() {
let mut tries = 0;
let session = resume_or_fresh("s1", true, |resume| {
tries += 1;
assert_eq!(resume, Some("s1"));
if tries == 1 { Err("busy".to_string()) } else { Ok(opened("s1")) }
})
.unwrap();
assert_eq!(session.sid, "s1");
}
#[test]
fn a_session_gone_from_disk_starts_a_fresh_dashboard() {
let mut calls = Vec::new();
let session = resume_or_fresh("s1", false, |resume| {
calls.push(resume.map(str::to_string));
Ok(opened(if resume.is_some() { "s1" } else { "s2" }))
})
.unwrap();
assert_eq!(session.sid, "s2");
assert_eq!(calls, vec![None], "nothing on disk to resume");
}
#[test]
fn parses_open_output() {
let json = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1}
+154 -28
View File
@@ -3,10 +3,10 @@
use std::sync::{Arc, Mutex};
use plan2code_app_lib::announce::AnnounceServer;
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, BeforeFresh, Sink};
use plan2code_app_lib::agents::{self, AgentKind, PermissionMode};
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, ConsoleSupervisor};
use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode};
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, session_on_disk, ConsoleSupervisor};
use plan2code_app_lib::node_check;
use plan2code_app_lib::project::{self, ProjectDir};
use plan2code_app_lib::restart_brief;
@@ -50,7 +50,9 @@ fn platform_info() -> serde_json::Value {
// to install it), and whether it takes its own reasoning effort.
#[tauri::command]
fn agent_availability() -> serde_json::Value {
let entries: Vec<_> = AgentKind::ALL
// Built-ins first, then the custom agents, read afresh on every call so
// "Check again" sees a change to agents.json.
let mut entries: Vec<_> = AgentKind::ALL
.iter()
.map(|&kind| {
let at = agents::installed_at(kind);
@@ -61,13 +63,64 @@ fn agent_availability() -> serde_json::Value {
// Which binary was used (Task 9.9), when one was found.
"path": at.map(|p| p.to_string_lossy().into_owned()),
"installHint": kind.install_hint(),
"installUrl": kind.install_url(),
"hasEffort": kind.has_effort(),
"custom": false,
"models": null,
})
})
.collect();
for custom in agents::custom_agents() {
let at = Agent::Custom(custom.clone()).installed_at();
entries.push(serde_json::json!({
"id": custom.id,
"label": custom.name,
"installed": at.is_some(),
"path": at.map(|p| p.to_string_lossy().into_owned()),
"installHint": null,
"installUrl": null,
"hasEffort": false,
"custom": true,
"models": custom.models,
}));
}
serde_json::json!(entries)
}
// Opens a built-in agent install page in the default browser. Any other id
// is an error: the page never names the link itself.
#[tauri::command]
fn open_install_page(id: String) -> Result<(), String> {
let url = agents::install_page_url(&id)?;
// The same switches as the console open-link.mjs.
if std::env::var_os("NO_BROWSER").is_some_and(|v| !v.is_empty())
|| std::env::var_os("PLAN2CODE_NO_BROWSER").is_some_and(|v| !v.is_empty())
{
return Ok(());
}
let mut command = if cfg!(windows) {
let mut c = std::process::Command::new("rundll32.exe");
c.args(["url.dll,FileProtocolHandler", url]);
c
} else if cfg!(target_os = "macos") {
let mut c = std::process::Command::new("open");
c.arg(url);
c
} else {
let browser = std::env::var("BROWSER").ok().filter(|b| !b.is_empty()).unwrap_or_else(|| "xdg-open".to_string());
let mut c = std::process::Command::new(browser);
c.arg(url);
c
};
command.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
command.spawn().map(|_| ()).map_err(|e| format!("could not open {url}: {e}"))
}
// `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`.
fn windows_build() -> Option<u32> {
let out = std::process::Command::new("cmd").args(["/c", "ver"]).output().ok()?;
@@ -144,6 +197,33 @@ fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
// The origin the app page has, which the console must allow as its frame
// parent. In a release build that is a constant, but `tauri dev` serves the
// page from a loopback dev server, so the window is asked for its real URL.
/// A page the agent's `open` announced: the supervisor follows it, or adopts
/// it when the agent started the console (the app owns its stop from there).
/// Says whether the window should show it. A session outside this app's
/// console store is refused: `cargo test` run by the agent inside the app
/// once announced a test's throwaway console, the window followed it, and
/// when the test shut it down the reconnect opened an empty dashboard, so the
/// build's own page was never seen again.
fn take_announced(state: &AppState, notice: &PageNotice, origin: String, on_disk: impl Fn(&str) -> bool) -> bool {
if !on_disk(&notice.sid) {
return false;
}
if let Ok(mut guard) = state.console.lock() {
match guard.as_mut() {
Some(sup) => sup.follow(&notice.url, &notice.sid),
None => {
let dir = state.project.lock().ok().and_then(|p| p.as_ref().map(|p| p.dir.clone()));
if let Some(dir) = dir {
if let Ok(sup) = ConsoleSupervisor::adopt(dir, origin, &notice.url, &notice.sid) {
*guard = Some(sup);
}
}
}
}
}
true
}
fn window_origin(app: &tauri::AppHandle) -> String {
app.get_webview_window("main")
.and_then(|window| window.url().ok())
@@ -186,15 +266,15 @@ fn agent_start(
cols: u16,
rows: u16,
) -> Result<(), String> {
let kind = AgentKind::from_id(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?;
let kind = agents::find_agent(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?;
let mode = PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?;
let agent = agent_for_project(&state)?;
agent.resize(cols, rows)?;
sync_agent_env(&app);
agent.start(kind, model, effort, mode, None)?;
agent.start(kind.clone(), model, effort, mode, None)?;
// A settings file that cannot be written must not stop the agent.
if let Some(file) = settings::settings_file() {
let _ = settings::save_last_agent(&file, kind);
let _ = settings::save_last_agent(&file, kind.id());
}
Ok(())
}
@@ -288,11 +368,15 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
let project = state.project.lock().ok().and_then(|p| p.clone());
let settings_file = settings::settings_file();
// The agent picked in the launcher starts the bar's picker, ahead of the app's own last one.
// An id that no longer resolves (a removed custom agent) is skipped.
let known = |id: &String| agents::find_agent(id).is_some();
let last_agent = state
.launch
.agent
.or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file)))
.or_else(project::remembered_agent);
.clone()
.filter(known)
.or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file)).filter(known))
.or_else(|| project::remembered_agent().filter(known));
let term_panel = settings_file.as_ref().map_or(
settings::TermPanelSettings {
dock: settings::DEFAULT_TERM_DOCK.to_string(),
@@ -305,7 +389,7 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
serde_json::json!({
"projectDir": project.as_ref().map(|p| p.dir.to_string_lossy().into_owned()),
"projectDirSource": project.as_ref().map(|p| p.source),
"lastAgent": last_agent.map(|kind| kind.id()),
"lastAgent": last_agent,
"launchModel": state.launch.model,
// Task 1.7 already exits before the window opens on a missing or too-old
// Node, so this is always a pass; the checklist's Node row just names it.
@@ -316,7 +400,7 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
// The launcher always passes `--project` alongside `--agent`, so an
// explicit `--agent` means skip straight to starting it, no checklist
// or launch card shown.
"autoStart": state.launch.agent.map(|kind| kind.id()),
"autoStart": state.launch.agent,
"termPanel": term_panel,
})
}
@@ -501,6 +585,7 @@ fn main() {
.invoke_handler(tauri::generate_handler![
platform_info,
agent_availability,
open_install_page,
agent_start,
agent_input,
agent_resize,
@@ -533,23 +618,13 @@ fn main() {
let handle = app.handle().clone();
let server = AnnounceServer::start(Arc::new(move |notice| {
let state = handle.state::<AppState>();
if let Ok(mut guard) = state.console.lock() {
match guard.as_mut() {
Some(sup) => sup.follow(&notice.url, &notice.sid),
// The agent started the console: the app owns its stop from here.
None => {
let dir = state.project.lock().ok().and_then(|p| p.as_ref().map(|p| p.dir.clone()));
if let Some(dir) = dir {
if let Ok(sup) =
ConsoleSupervisor::adopt(dir, window_origin(&handle), &notice.url, &notice.sid)
{
*guard = Some(sup);
}
}
}
}
let taken = take_announced(&state, &notice, window_origin(&handle), session_on_disk);
if taken {
let _ = handle.emit("console-page", &notice);
} else {
eprintln!("plan2code: ignored a page outside the console store: {}", notice.sid);
}
let _ = handle.emit("console-page", &notice);
taken
}));
match server {
Ok(server) => {
@@ -596,6 +671,52 @@ mod tests {
}
}
fn notice(sid: &str) -> PageNotice {
PageNotice { url: "http://127.0.0.1:5555/s/t/".into(), sid: sid.into(), workflow: "dashboard".into() }
}
/// A supervisor following the build's console, adopted with the repo's own
/// console source so it never depends on an installed one.
fn following_the_build() -> ConsoleSupervisor {
std::env::set_var("PLAN2CODE_CONSOLE_DIR", PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"));
ConsoleSupervisor::adopt(PathBuf::from("."), app_origin().to_string(), "http://127.0.0.1:4444/s/b/", "build")
.expect("adopt with the repo's console")
}
fn sid_followed(state: &AppState) -> String {
state.console.lock().unwrap().as_ref().unwrap().session().sid.clone()
}
/// Adopted, never started here: skip Drop's `stop`.
fn let_go(state: &AppState) {
std::mem::forget(state.console.lock().unwrap().take());
}
#[test]
fn a_page_from_outside_the_console_store_never_takes_the_window() {
// A test's throwaway console, opened by `cargo test` inside the app with
// the agent's in-app variables: following it swapped a build's page for
// the test's, then for an empty dashboard once the test shut it down.
let state = state_for("project-a");
assert!(!take_announced(&state, &notice("test-console"), app_origin().to_string(), |_| false));
assert!(state.console.lock().unwrap().is_none(), "nothing adopted");
// Already following the build's own console: it stays on that one.
*state.console.lock().unwrap() = Some(following_the_build());
assert!(!take_announced(&state, &notice("test-console"), app_origin().to_string(), |_| false));
assert_eq!(sid_followed(&state), "build");
let_go(&state);
}
#[test]
fn a_page_from_the_console_store_is_followed() {
let state = state_for("project-a");
*state.console.lock().unwrap() = Some(following_the_build());
assert!(take_announced(&state, &notice("next"), app_origin().to_string(), |_| true));
assert_eq!(sid_followed(&state), "next");
let_go(&state);
}
// Covers the folder-matching rule itself (Task 9.5's fix); a genuinely
// *active* agent for the old folder needs a real spawned process to
// prove against, which only the `tests/agent_manager.rs` harness (the
@@ -618,7 +739,7 @@ mod tests {
#[test]
fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own() {
let state = state_for("project-a");
let server = AnnounceServer::start(Arc::new(|_| {})).unwrap();
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap();
*state.announce.lock().unwrap() = Some(server);
let body = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#;
@@ -672,6 +793,11 @@ mod tests {
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console_dir);
std::env::set_var("PLAN2CODE_CONSOLE_HOME", std::env::temp_dir().join(format!("p2c-main-test-home-{pid}")));
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
// Run inside the desktop app, the agent's in-app variables would have this
// console announce itself to the live window and take it over.
for name in ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"] {
std::env::remove_var(name);
}
Some(
plan2code_app_lib::console_supervisor::ConsoleSupervisor::start(
project,
@@ -37,6 +37,11 @@ fn setup() -> Option<PathBuf> {
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console);
std::env::set_var("PLAN2CODE_CONSOLE_HOME", temp_dir("home"));
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
// Run inside the desktop app, the agent's in-app variables would have this
// console announce itself to the live window and take it over.
for name in ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"] {
std::env::remove_var(name);
}
Some(temp_dir("project"))
}