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

+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,