// Hide the extra console window on Windows release builds. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink}; use plan2code_app_lib::agents::{self, Agent, PermissionMode}; use plan2code_app_lib::announce::{AnnounceServer, PageNotice}; use plan2code_app_lib::attention::{self, Badge, Signal}; use plan2code_app_lib::console_supervisor::{ app_origin, origin_of, session_on_disk, ConsoleSupervisor, }; use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot}; use plan2code_app_lib::models; use plan2code_app_lib::node_check; use plan2code_app_lib::project::{self, ProjectDir}; use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase}; use plan2code_app_lib::restart_brief; use plan2code_app_lib::review_loop::{self, ReviewSlot}; use plan2code_app_lib::session_reader; use plan2code_app_lib::settings; #[cfg(windows)] use plan2code_app_lib::task_dialog; use plan2code_app_lib::ui_confirm; use plan2code_app_lib::versions; use tauri::ipc::{Channel, InvokeResponseBody}; use tauri::{Emitter, Manager, State}; use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind}; type PageChannel = Arc>>>; // The project the app is working on, the console it supervises for it and the // agent it runs there. #[derive(Default)] struct AppState { project: Mutex>, // The agent and model the launcher chose, from its arguments. launch: project::LaunchChoice, console: Arc>>, agent: Mutex>>, // Where the agent's output and state changes go: the page's latest channel. page: PageChannel, // This window's endpoint for pages the agent's `console.mjs open` wants shown here. announce: Arc>>, // The Node check's result: it runs on a background thread after the // window opens (Task 9.10), so this is unchecked until it reports. node: Mutex, // What the taskbar entry last said, and whether it may say anything. attention: Mutex, // The app itself, once it is set up: the agent's sink clears the taskbar // through it when the agent ends. app: Arc>, // The Implementation Loop running now, if any: in memory only, so an app // restart ends it (NFR-5). loop_run: LoopSlot, // The Review Loop running now, or the one that stopped and waits for // Continue or its report: in memory only, so an app restart ends it. review_run: ReviewSlot, // The last loop's project, spec, launch choice and confirmed quick check, // kept after the running record is gone so Resume, Fix together with an agent and // Finalize still work. Memory only. last_loop: Mutex>, // The version this app was running before an "Update and restart" brought it up: read // from app.json once at launch (and cleared there), for the page to say "Updated to vX". updated_from: Option, // Confirms the shell's own modal is asked (ui_confirm.rs): the answers still to come, and // whether the page has begun listening for requests (until then the OS box asks instead). confirms: ui_confirm::Pending, confirm_ready: AtomicBool, } /// What the Node check found, as the page reads it (`app_state` and the /// `node-status` event share this shape). `checked` is false until the check /// has finished; `problem` is the failure message, if any. #[derive(Clone, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] struct NodeReport { checked: bool, version: Option, binary: Option, problem: Option, } /// Run the Node check off the main thread and publish its result: store it, /// tell the page, and on a failure show the dialog and end the app, as /// `main()` did before the window existed (FR-13). fn spawn_node_check(app: tauri::AppHandle) { std::thread::spawn(move || { let status = node_check::check_node(); let problem = node_check::problem_message(&status); let version = match &status { node_check::NodeStatus::Ok(version) => Some(version.clone()), _ => None, }; let binary = version .as_ref() .and_then(|_| node_check::node_binary_path()); let report = NodeReport { checked: true, version, binary, problem: problem.clone(), }; if let Ok(mut slot) = app.state::().node.lock() { *slot = report.clone(); } let _ = app.emit("node-status", &report); if let Some(message) = problem { // The first button is the default: Open nodejs.org, then the app ends either way. let open_site = app .dialog() .message(&message) .title("Plan2Code needs Node.js") .kind(MessageDialogKind::Error) .buttons(MessageDialogButtons::OkCancelCustom( "Open nodejs.org".to_string(), "Quit".to_string(), )) .blocking_show(); if open_site { let _ = open_url("https://nodejs.org"); } std::process::exit(1); } }); } // The console page's last state as the taskbar shows it (attention.rs), and // the Desktop app switch, `taskbarSignal` in app.json. struct AttentionState { last: Option, enabled: bool, } impl Default for AttentionState { fn default() -> Self { AttentionState { last: None, enabled: true, } } } // The operating system and, on Windows, the build number xterm needs for ConPTY. #[tauri::command] fn platform_info() -> serde_json::Value { let build = if cfg!(windows) { windows_build() } else { None }; serde_json::json!({ "os": std::env::consts::OS, "windowsBuild": build }) } // What the launch card offers per agent: whether its CLI is on PATH (else how // to install it), and whether it takes its own reasoning effort; plus the // warnings about agents.json. #[tauri::command] fn agent_availability(refresh: Option) -> serde_json::Value { // "Check again" also works the PATH out again and re-reads the shipped // agent list, so a CLI whose installer added a new folder to PATH, or a // list an update rewrote, is seen without restarting the app. if refresh == Some(true) { node_check::refresh_path(); agents::refresh_agent_list(); } // Built-ins from the shipped list first, then the custom agents, read // afresh on every call so "Check again" sees a change to agents.json. // `state` is the shared lookup's answer: found (on PATH), outside (on // the saved PATH, in npm's folder or an install folder: needs setup, // not missing) or missing. `folder` names where an outside hit lives. let mut entries: Vec<_> = agents::builtin_entries() .iter() .map(|entry| { let hit = agents::lookup_agent(entry); serde_json::json!({ "id": entry.id, "label": entry.name, "installed": hit.state == "found", "state": hit.state, "path": hit.path.map(|p| p.to_string_lossy().into_owned()), "folder": hit.folder.map(|p| p.to_string_lossy().into_owned()), "installHint": agents::install_hint(entry), "installUrl": entry.install_url, "hasEffort": agents::has_effort(&entry.id), "custom": false, "models": models::models_for_builtin(&entry.id), }) }) .collect(); let (customs, warnings) = agents::custom_agents(); for custom in customs { let at = Agent::Custom(custom.clone()).installed_at(); entries.push(serde_json::json!({ "id": custom.id, "label": custom.name, "installed": at.is_some(), "state": if at.is_some() { "found" } else { "missing" }, "path": at.map(|p| p.to_string_lossy().into_owned()), "installHint": null, "installUrl": null, "hasEffort": false, "custom": true, "models": custom.models, })); } // What was skipped in agents.json, so a custom agent that vanished from // the picker is explained, as the launcher and the console do. serde_json::json!({ "agents": entries, "warnings": warnings }) } // 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> { open_url(&agents::install_page_url(&id)?) } // Opens a web address in the default browser, with the same switches as the console // open-link.mjs. fn open_url(url: &str) -> Result<(), String> { // 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 { let mut command = std::process::Command::new("cmd"); command.args(["/c", "ver"]); #[cfg(windows)] { use std::os::windows::process::CommandExt; command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW } let out = command.output().ok()?; let text = String::from_utf8_lossy(&out.stdout); let version = text.split("Version ").nth(1)?; version.split('.').nth(2)?.trim().parse().ok() } // Sends the agent's output as raw bytes and its state changes as JSON, on the // page's latest channel. Nothing is sent while no page has registered one. An // agent that ends takes the taskbar's dot with it, page or no page. fn page_sink(page: PageChannel, app: Arc>) -> Sink { Arc::new(move |event| { if let AgentEvent::State(snapshot) = &event { if let (AgentState::Ended { .. }, Some(app)) = (&snapshot.state, app.get()) { clear_attention(app); } } let Ok(guard) = page.lock() else { return }; let Some(channel) = guard.as_ref() else { return; }; let body = match event { AgentEvent::Output(bytes) => InvokeResponseBody::Raw(bytes), AgentEvent::State(snapshot) => match serde_json::to_string(&snapshot) { Ok(json) => InvokeResponseBody::Json(json), Err(_) => return, }, }; let _ = channel.send(body); }) } // The manager for the current project, made on first use. A manager for a // different folder replaces an idle one. fn agent_for_project(state: &AppState) -> Result, String> { let dir = { let project = state.project.lock().map_err(|e| e.to_string())?; project .as_ref() .map(|p| p.dir.clone()) .ok_or("no project folder chosen")? }; let mut guard = state.agent.lock().map_err(|e| e.to_string())?; if let Some(agent) = guard.as_ref() { // Only the same folder's manager is reused: an active agent for a // folder the project has since moved away from must not be handed // back as if it belonged to the new one. if agent.folder() == &dir { return Ok(Arc::clone(agent)); } } let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.app)); let agent = Arc::new(AgentManager::new(dir, sink)); agent.set_before_fresh(before_fresh_hook(state)); agent.set_forget_session(forget_session_hook(state)); *guard = Some(Arc::clone(&agent)); Ok(agent) } // What New Session does before the fresh agent starts. It leaves the brief for // the dashboard, from the console session running now, then forgets that // session, so the fresh agent's `open` starts one of its own: a session that // joined the old one would carry its meter along, still red after the very // press the red meter asks for. The old console is left to shut itself down // once the frame moves on to the new page. fn before_fresh_hook(state: &AppState) -> BeforeFresh { let console = Arc::clone(&state.console); let announce = Arc::clone(&state.announce); Arc::new(move || { let sid = console .lock() .ok() .and_then(|guard| guard.as_ref().map(|sup| sup.session().sid.clone())); if let (Some(sid), Some(home)) = (sid.as_deref(), session_reader::console_home()) { restart_brief::leave_spec(&home, sid, chrono::Utc::now().timestamp_millis()); } let note = sid.and_then(|sid| restart_brief::note_for_restart(&sid)); if let Ok(guard) = announce.lock() { if let Some(server) = guard.as_ref() { server.forget_current(); } } note }) } // What the loop does before a phase's fresh agent starts: forget the console // session the window follows, so the new agent's `open` starts its own. fn forget_session_hook(state: &AppState) -> plan2code_app_lib::agent_manager::ForgetSession { let announce = Arc::clone(&state.announce); Arc::new(move || { if let Ok(guard) = announce.lock() { if let Some(server) = guard.as_ref() { server.forget_current(); } } }) } fn current_agent(state: &AppState) -> Option> { state.agent.lock().ok().and_then(|guard| guard.clone()) } // 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(¬ice.sid) { return false; } // An agent-less setup session never takes the window by announcing // itself (NFR-2): the only setup console allowed here is the one the app // itself started for Set up an agent, which carries no announce // variables and drives the frame through console_setup_start instead. if notice.workflow == "setup" { return false; } if let Ok(mut guard) = state.console.lock() { match guard.as_mut() { Some(sup) => sup.follow(¬ice.url, ¬ice.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, ¬ice.url, ¬ice.sid) { *guard = Some(sup); } } } } } true } fn window_origin(app: &tauri::AppHandle) -> String { app.get_webview_window("main") .and_then(|window| window.url().ok()) .and_then(|url| origin_of(url.as_str())) .unwrap_or_else(|| app_origin().to_string()) } // Gives the agent the in-app signal: this window's announce endpoint and the // origin its console must allow. The agent's own `open` then shows its pages // here (it asks the window which session is current). Without an endpoint the // agent gets nothing and opens pages the plain way. fn sync_agent_env(app: &tauri::AppHandle) { let state = app.state::(); let Some(agent) = current_agent(&state) else { return; }; let env = match state.announce.lock().ok() { Some(guard) => guard .as_ref() .map(|server| { server.agent_env(&window_origin(app), &app.package_info().version.to_string()) }) .unwrap_or_default(), None => Vec::new(), }; agent.set_env(env); } // `on_output` is deliberately not a parameter here: `agent_reattach` already // registered `state.page` when the page mounted (`main()` on the frontend // calls it before this), and that registration must stay the only one. Every // Channel argument Tauri deserializes for an invoke is a fresh wrapper around // the same frontend id; dropping one (as happened here when it replaced the // reattach registration) sends the frontend an "end" message that // unregisters that id for good, breaking all future sends through it. // The window's own commands that would end or replace the loop's agent refuse // while a loop runs, between phases too (the slot holds a record then). The // loop's own agent starts go through `loop_driver::start_with`, not these // commands, and `agent_input` stays open so a trust or login prompt can be // answered. fn refuse_while_looping(state: &AppState, what: &str) -> Result<(), String> { if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { return Err(format!( "A loop is running. Stop it before you change the {what}." )); } Ok(()) } #[tauri::command] #[allow(clippy::too_many_arguments)] // one argument per key the frontend passes to invoke fn agent_start( app: tauri::AppHandle, state: State<'_, AppState>, kind: String, model: Option, effort: Option, mode: String, cols: u16, rows: u16, ) -> Result<(), String> { refuse_while_looping(&state, "agent")?; 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.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.id()); } Ok(()) } #[tauri::command] fn agent_input(state: State<'_, AppState>, data: String) -> Result<(), String> { match current_agent(&state) { Some(agent) => agent.input(data.as_bytes()), None => Ok(()), } } #[tauri::command] fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(), String> { match current_agent(&state) { Some(agent) => agent.resize(cols, rows), None => Ok(()), } } #[tauri::command] fn agent_restart(state: State<'_, AppState>) -> Result<(), String> { refuse_while_looping(&state, "agent")?; current_agent(&state) .ok_or("no agent has been started")? .restart() } fn idle_snapshot_json() -> serde_json::Value { serde_json::json!({ "state": "idle", "kind": null, "mode": null, "generation": 0 }) } /// A page that just mounted (a reload, or this window's first paint while an /// agent survived it) registers its output channel here instead of through /// `agent_start`, which would try to start a second agent. Replays the /// current generation's recent output on it at once, so the terminal does /// not come up blank. #[tauri::command] fn agent_reattach( state: State<'_, AppState>, on_output: Channel, ) -> Result { let agent = current_agent(&state); *state.page.lock().map_err(|e| e.to_string())? = Some(on_output.clone()); if let Some(agent) = &agent { let replay = agent.replay(); if !replay.is_empty() { let _ = on_output.send(InvokeResponseBody::Raw(replay)); } } Ok(match &agent { Some(agent) => serde_json::to_value(agent.snapshot()).unwrap_or_default(), None => idle_snapshot_json(), }) } // Set while a quit box is open, so a second close or quit does not stack another. static QUIT_OPEN: AtomicBool = AtomicBool::new(false); // Clears QUIT_OPEN when the box closes, however its handler ends. struct QuitOpen; impl Drop for QuitOpen { fn drop(&mut self) { QUIT_OPEN.store(false, Ordering::SeqCst); // Stay was the answer (a Quit has already taken the plan): no restart is pending. if let Ok(mut plan) = RESTART_ON_QUIT.lock() { *plan = None; } } } // What an "Update and restart" starts once the app has shut down: the app file to run, the // project folder to hand it, and this app's version for the "Updated to vX" note. struct RestartPlan { exe: PathBuf, project: Option, from_version: String, } // Set by `restart_app`, taken by `quit_app`. A Stay answer to the quit check clears it // (`QuitOpen`'s drop), so a later ordinary quit never restarts. static RESTART_ON_QUIT: Mutex> = Mutex::new(None); // Starts the new app, detached so it outlives this process. The note for its first page goes // to app.json first. fn spawn_restart(plan: &RestartPlan) -> Result<(), String> { if let Some(file) = settings::settings_file() { let _ = settings::save_updated_from(&file, &plan.from_version); } let mut command = std::process::Command::new(&plan.exe); command .args(versions::restart_args(plan.project.as_deref())) .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(0x0000_0008 | 0x0000_0200); // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP } #[cfg(unix)] { use std::os::unix::process::CommandExt; command.process_group(0); } command .spawn() .map(|_| ()) .map_err(|e| format!("could not start {}: {e}", plan.exe.display())) } // Asks through the shell's own modal and waits for the answer: one look for every confirm, with the // safe button first and focused. None when the page cannot show it (no window yet, or its modal is // not listening): the caller then asks with the OS box. Blocks, so never call it on the event loop. fn ask_in_window( app: &tauri::AppHandle, build: impl FnOnce(String) -> ui_confirm::ConfirmRequest, ) -> Option { let state = app.state::(); if !state.confirm_ready.load(Ordering::SeqCst) || app.get_webview_window("main").is_none() { return None; } let (id, rx) = state.confirms.register(); let request = build(id.clone()); if app.emit("confirm-request", &request).is_err() { state.confirms.forget(&id); return None; } let yes = ui_confirm::wait_for(&rx, ui_confirm::ANSWER_TIMEOUT); state.confirms.forget(&id); // Whatever the page still shows for this request goes away with it. let _ = app.emit("confirm-cancel", &id); Some(yes) } // The modal's answer, by the id the request carried. A stale or invented id changes nothing. #[tauri::command] fn confirm_answer(state: State<'_, AppState>, id: String, yes: bool) { state.confirms.answer(&id, yes); } // The page is listening for `confirm-request` from now on. #[tauri::command] fn confirm_ready(state: State<'_, AppState>) { state.confirm_ready.store(true, Ordering::SeqCst); // A page that has only now started listening (a reload) shows no older modal: whatever was // asked before it listened is Cancel, not a thread waiting out the timeout with the quit // check (QUIT_OPEN) held. state.confirms.cancel_all(); } // The bar's "..." menu and the macOS menu's Quit: the same quit check as closing the window. #[tauri::command] fn request_quit(app: tauri::AppHandle) { if agent_is_active(&app) { confirm_quit(&app); } else { quit_app(&app); } } // Asks before quitting while an agent runs; anything but Quit keeps the app // open. The words follow whose turn the page last reported (quit_prompt.rs). fn confirm_quit(app: &tauri::AppHandle) { if QUIT_OPEN.swap(true, Ordering::SeqCst) { return; } let open = QuitOpen; let last = app .state::() .attention .lock() .ok() .and_then(|guard| guard.last); // A running loop has its own words, naming what is committed. let prompt = match loop_driver::quit_facts(&app.state::().loop_run) { Some((phase, phases, committed)) => loop_quit_prompt(phase, phases, &committed), None => quit_prompt(last), }; #[cfg(windows)] { if let Some(parent) = app .get_webview_window("main") .and_then(|window| window.hwnd().ok()) { // TaskDialog blocks until it closes, so it runs off the event loop. let app = app.clone(); let parent = parent.0 as isize; std::thread::spawn(move || { let _open = open; if task_dialog::ask(parent as _, &prompt) { quit_app(&app); } }); return; } } let kind = match prompt.case { QuitCase::Waiting => MessageDialogKind::Info, QuitCase::Working => MessageDialogKind::Warning, }; // Off Windows the shell's own modal asks, with Stay first and focused, so Stay is the default // answer everywhere (the plugin's box makes Quit the default). The OS box is the fallback for a // page that cannot show it. Both wait off the event loop. let app = app.clone(); std::thread::spawn(move || { let _open = open; #[cfg(not(windows))] { let asked = ask_in_window(&app, |id| { ui_confirm::quit_request( id, &prompt.heading, &prompt.message, &prompt.quit, &prompt.stay, ) }); if let Some(quit) = asked { if quit { quit_app(&app); } return; } } // The plugin makes its first button the default, so here Enter means Quit. Stay first // would make Esc quit instead, since the plugin reads Esc as "not the first button". let quit = app .dialog() .message(prompt.message.clone()) .title(prompt.heading.clone()) .kind(kind) .buttons(MessageDialogButtons::OkCancelCustom( prompt.quit.clone(), prompt.stay.clone(), )) .blocking_show(); if quit { quit_app(&app); } }); } // A running loop counts even between two phases, when no agent runs for a moment. fn agent_is_active(app: &tauri::AppHandle) -> bool { let state = app.state::(); loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) || current_agent(&state).is_some_and(|agent| agent.is_active()) } // Stops the loop, the agent, then the console, then exits. The loop goes first: // its record is dropped without a word to the page, so its watch thread never // takes the ended agent for a crash. fn quit_app(app: &tauri::AppHandle) { let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take()); let state = app.state::(); loop_driver::abandon(&state.loop_run); review_loop::abandon(&state.review_run); if let Some(agent) = current_agent(&state) { agent.stop(); } if let Ok(mut guard) = state.console.lock() { if let Some(mut console) = guard.take() { let _ = console.stop(); } } if let Some(plan) = restart { if let Err(error) = spawn_restart(&plan) { eprintln!("plan2code: restart failed: {error}"); } } app.exit(0); } // The console page's state, told on every change (`attention` from the page): // the taskbar's dot for this system, and one flash on a change into the // person's move or needs attention while the window is not focused. An // unknown word does nothing. #[tauri::command] fn set_attention(app: tauri::AppHandle, signal: String) { if let Some(next) = Signal::from_id(&signal) { apply_signal(&app, next); } } // The dot and the flash for a state. The page's `attention` message comes here, // and so does the loop when a question starts holding it: the dot and flash // then do not depend on the page, which is locked while the loop drives. fn apply_signal(app: &tauri::AppHandle, next: Signal) { let state = app.state::(); let Some(window) = app.get_webview_window("main") else { return; }; let (prev, enabled) = { let Ok(mut guard) = state.attention.lock() else { return; }; (guard.last.replace(next), guard.enabled) }; apply_badge( &window, attention::badge_for(next, std::env::consts::OS, enabled), ); if attention::should_flash(prev, next, window.is_focused().unwrap_or(true), enabled) { let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational)); } } // The one place a badge reaches the window, in each system's own form. A call // that fails changes nothing else: the taskbar is a hint, never a blocker. #[cfg_attr( not(any(target_os = "windows", target_os = "macos", target_os = "linux")), allow(unused_variables) )] fn apply_badge(window: &tauri::WebviewWindow, badge: Badge) { #[cfg(target_os = "windows")] { let icon = match badge { Badge::Dot(color) => Some(tauri::image::Image::new_owned( attention::dot_rgba(color, attention::DOT_SIZE), attention::DOT_SIZE, attention::DOT_SIZE, )), _ => None, }; let _ = window.set_overlay_icon(icon); } #[cfg(target_os = "macos")] { let label = match badge { Badge::Label(text) => Some(text.to_string()), _ => None, }; let _ = window.set_badge_label(label); } #[cfg(target_os = "linux")] { let count = match badge { Badge::Count(count) => Some(count), _ => None, }; let _ = window.set_badge_count(count); } } // No dot and no flash: the agent ended, the page went away, or the switch was // turned off. Whose turn it is is unknown until the page tells again, so the // quit check uses its working words meanwhile (the agent may be mid-step). fn clear_attention(app: &tauri::AppHandle) { if let Ok(mut guard) = app.state::().attention.lock() { guard.last = None; } let Some(window) = app.get_webview_window("main") else { return; }; apply_badge(&window, Badge::None); let _ = window.request_user_attention(None); } // The app page clears it when a new page loads in the frame or none answers. #[tauri::command] fn clear_attention_cmd(app: tauri::AppHandle) { clear_attention(&app); } // The Desktop app switch in the console's User Preferences (`taskbar` from the // page). Off clears the dot and stops flashes; on shows the dot for the state // the page last told at once, since the page only tells it again on a change. // Either way the last state is kept. Saved in the app's own app.json, never // in the console's files. #[tauri::command] fn set_taskbar_signal( app: tauri::AppHandle, state: State<'_, AppState>, on: bool, ) -> Result<(), String> { let saved = settings::settings_file() .ok_or_else(|| "no home folder found".to_string()) .and_then(|file| settings::save_taskbar_signal(&file, on)); let last = { let Ok(mut guard) = state.attention.lock() else { return saved; }; guard.enabled = on; guard.last.unwrap_or(Signal::Plain) }; if let Some(window) = app.get_webview_window("main") { apply_badge( &window, attention::badge_for(last, std::env::consts::OS, on), ); if !on { let _ = window.request_user_attention(None); } } saved } /// What the page draws its bar from: the folder (or that none is chosen yet) /// and the agent the picker starts on. #[tauri::command] 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 .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)); // Null until the person has docked, dragged or collapsed the pane: the // page then starts it docked right. let term_panel = settings_file .as_ref() .and_then(|file| settings::load_term_panel(file)); let first_run_done = settings_file .as_ref() .is_some_and(|file| settings::load_first_run_done(file)); let node = state.node.lock().map(|n| n.clone()).unwrap_or_default(); let terminal_font_size = settings_file .as_ref() .map_or(settings::DEFAULT_TERMINAL_FONT_SIZE, |file| { settings::load_terminal_font_size(file) }); 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, "launchModel": state.launch.model, // The Node check runs after the window opens: `nodeChecked` is false // until it finishes, then `node-status` is emitted with the same // fields. A failure shows its dialog and ends the app. "nodeChecked": node.checked, "nodeVersion": node.version, "nodeBinary": node.binary, "nodeProblem": node.problem, "skillsVersion": versions::installed_skills_version(), "firstRunDone": first_run_done, // 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, "termPanel": term_panel, "terminalFontSize": terminal_font_size, "copyOnSelect": settings_file.as_ref().map_or_else( settings::default_copy_on_select, |file| settings::load_copy_on_select(file), ), // Set only on the launch right after an "Update and restart": the version the old app // ran. The page says "Updated to v" once. "updatedFrom": state.updated_from, // The Desktop app switch, for the page's User Preferences. "taskbarSignal": state.attention.lock().map_or(true, |guard| guard.enabled), }) } /// The terminal pane's toolbar remembers its shape here: dock side, size and /// whether it was left collapsed. A settings file that cannot be written is /// reported to the caller; the pane itself keeps working either way. #[tauri::command] fn save_term_panel(dock: String, fraction: f64, collapsed: bool) -> Result<(), String> { let file = settings::settings_file().ok_or("no home folder found")?; settings::save_term_panel(&file, &dock, fraction, collapsed) } /// The terminal's font size (Ctrl/Cmd plus, minus and 0), kept in app.json. /// A size outside 8 to 32 is refused. #[tauri::command] fn save_terminal_font_size(size: u32) -> Result<(), String> { let file = settings::settings_file().ok_or("no home folder found")?; settings::save_terminal_font_size(&file, size) } /// Copy-on-select for the terminal (Task 10.6): whether selecting text copies it at once. /// The saved choice, or the OS default (on for Linux, off on Windows and macOS). #[tauri::command] fn get_copy_on_select() -> bool { settings::settings_file().map_or_else(settings::default_copy_on_select, |file| { settings::load_copy_on_select(&file) }) } /// Save the copy-on-select choice in app.json. #[tauri::command] fn set_copy_on_select(on: bool) -> Result<(), String> { let file = settings::settings_file().ok_or("no home folder found")?; settings::save_copy_on_select(&file, on) } /// The first-run checklist passed once: later launches go straight to the /// launch card (Task 9.4). #[tauri::command] fn save_first_run_done() -> Result<(), String> { let file = settings::settings_file().ok_or("no home folder found")?; settings::save_first_run_done(&file) } /// The app's version (`tauri.conf.json`'s, which Tauri puts in the package info) beside the /// installed skills' version. The bar shows its Update line when they differ (FR-14). #[tauri::command] fn version_status(app: tauri::AppHandle) -> versions::VersionStatus { versions::status( &app.package_info().version.to_string(), versions::installed_skills_version(), ) } /// The release check: `{ latest, problem }`. `latest` is the newest GitHub release's version /// when it is newer than this app, else null; `problem` is a short sentence when the check /// could not run (git missing, no network), else null. The page asks at start and again every /// few hours, and never waits on it. #[tauri::command] async fn check_new_release(app: tauri::AppHandle) -> versions::ReleaseCheck { let version = app.package_info().version.to_string(); tauri::async_runtime::spawn_blocking(move || versions::check_new_release(&version)) .await .unwrap_or_else(|_| versions::ReleaseCheck { latest: None, problem: Some("Could not check for updates: the check did not finish.".to_string()), }) } /// What `update_skills` resolves with: the installer's last line, and the version status /// re-read afterwards, so the bar can say plainly whether the mismatch is actually gone. #[derive(serde::Serialize)] struct UpdateOutcome { message: String, status: versions::VersionStatus, } /// Run the existing installer's update, pinned to this app's own release tag. Only the bar's /// button asks for it: never silently. `progress` carries each line of the installer's own /// output live, for the bar to show while it runs. #[tauri::command] async fn update_skills( app: tauri::AppHandle, progress: Channel, ) -> Result { let version = app.package_info().version.to_string(); let message = tauri::async_runtime::spawn_blocking(move || { versions::run_update(&version, |line| { let _ = progress.send(line.to_string()); }) }) .await .map_err(|e| e.to_string())??; let status = versions::status( &app.package_info().version.to_string(), versions::installed_skills_version(), ); Ok(UpdateOutcome { message, status }) } /// "Update and restart", step one: the installer unpinned (the newest release, not this app's /// own tag), with its output live on `progress`. On success the old app keeps running until /// `restart_app`; on failure it stays as it was and the error is a readable reason. #[tauri::command] async fn update_to_newest( app: tauri::AppHandle, progress: Channel, ) -> Result { let message = tauri::async_runtime::spawn_blocking(move || { versions::run_update_newest(|line| { let _ = progress.send(line.to_string()); }) }) .await .map_err(|e| e.to_string())??; let status = versions::status( &app.package_info().version.to_string(), versions::installed_skills_version(), ); Ok(UpdateOutcome { message, status }) } /// "Update and restart", step two: start the freshly installed app with this one's `--project` /// and end this one. With an agent or loop running it first asks through the existing quit /// check (Windows TaskDialog, or the shell's own modal elsewhere; the plugin box only while the page is not listening) and answers "asking"; Stay leaves /// everything as it was. `confirmed: true` skips that check, for a page that has already asked /// in its own confirm. Answers "restarting" when it goes ahead. Fails, leaving this app /// running, when the installed app file is missing. #[tauri::command] fn restart_app( app: tauri::AppHandle, state: State<'_, AppState>, confirmed: bool, ) -> Result<&'static str, String> { let exe = versions::installed_app_path() .ok_or("the new app file was not found, so Plan2Code was not restarted")?; let project = state .project .lock() .ok() .and_then(|p| p.as_ref().map(|p| p.dir.clone())); *RESTART_ON_QUIT.lock().map_err(|e| e.to_string())? = Some(RestartPlan { exe, project, from_version: app.package_info().version.to_string(), }); if !confirmed && agent_is_active(&app) { confirm_quit(&app); return Ok("asking"); } quit_app(&app); Ok("restarting") } /// The OS folder picker, the folder picker's Choose a folder row on a bare /// start; a choice goes to the top of the recent folders. #[tauri::command(async)] fn pick_project_folder( app: tauri::AppHandle, state: State<'_, AppState>, ) -> Result, String> { refuse_while_looping(&state, "project")?; let picked = app .dialog() .file() .blocking_pick_folder() .and_then(|p| p.as_path().map(|dir| dir.to_path_buf())); let Some(dir) = picked else { return Ok(None); }; let choice = project::remember_folder(&dir)?; let text = choice.dir.to_string_lossy().into_owned(); *state.project.lock().map_err(|e| e.to_string())? = Some(choice); Ok(Some(text)) } /// Stops the old project's agent and console and clears both from state, so /// neither `agent_for_project` nor `console_start` can hand either back once /// the project has moved on (Task 9.5). `state.page` is deliberately left /// alone: it is the page's own output channel, not the project's, and it must /// stay the single live registration for `agentChannel`'s id for the page's /// whole lifetime. Dropping it here (even briefly, to `None`) sends the /// frontend an "end" message that unregisters that id for good — no later /// command can ever re-register the same frontend `Channel` object after /// that, whatever it passes, so a project switch would silently and /// permanently cut the new agent's output off from the page. fn teardown_project(state: &AppState) -> Result<(), String> { if let Some(agent) = current_agent(state) { agent.stop(); } *state.agent.lock().map_err(|e| e.to_string())? = None; if let Ok(mut guard) = state.console.lock() { if let Some(mut sup) = guard.take() { let _ = sup.stop(); } } // The new project's agent asks the window which session is current and // joins it; left at the old project's (its console just stopped), its // `open` joined a dead page and the dashboard never showed. if let Ok(guard) = state.announce.lock() { if let Some(server) = guard.as_ref() { server.forget_current(); } } Ok(()) } /// Switch to a different project folder, picked fresh: a clean teardown of /// the old one (its agent stopped, its console stopped) before the new /// folder is remembered, so `agent_for_project` and `console_start` start /// fresh for it rather than reusing anything from the one just left. Picking /// nothing (canceled) leaves the current project untouched. One project per /// window stays; this replaces it, it does not add a second. #[tauri::command(async)] fn change_project( app: tauri::AppHandle, state: State<'_, AppState>, ) -> Result, String> { refuse_while_looping(&state, "project")?; let picked = app .dialog() .file() .blocking_pick_folder() .and_then(|p| p.as_path().map(|dir| dir.to_path_buf())); let Some(dir) = picked else { return Ok(None); }; teardown_project(&state)?; let choice = project::remember_folder(&dir)?; let text = choice.dir.to_string_lossy().into_owned(); *state.project.lock().map_err(|e| e.to_string())? = Some(choice); Ok(Some(text)) } /// The recent project folders that still exist, newest first, for the page's /// folder picker: `{ dir, name }` each, `name` the folder's own name (the full /// path for a root, which has none). The project already open is left out /// (none on a bare start), since picking it would change nothing. Off the /// main thread: each row checks the disk, and a saved folder on an /// unreachable share must not freeze the window. #[tauri::command(async)] fn recent_folders(state: State<'_, AppState>) -> Vec { let current = state .project .lock() .ok() .and_then(|p| p.as_ref().map(|p| p.dir.clone())); project::recent_folders(current.as_deref()) .into_iter() .map(|dir| { let full = dir.to_string_lossy().into_owned(); let name = dir .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_else(|| full.clone()); serde_json::json!({ "dir": full, "name": name }) }) .collect() } /// Whether opening `dir` must first tear the current project down: only when /// a project is set and it is a different folder (`same_folder`'s rule, so a /// trailing separator, and case on Windows, do not count). fn needs_teardown(current: Option<&Path>, dir: &Path, windows: bool) -> bool { current.is_some_and(|cur| { !project::same_folder(&cur.to_string_lossy(), &dir.to_string_lossy(), windows) }) } /// Open one of the recent folders from the folder picker. A different folder /// than the open project tears the old one down first (as `change_project` /// does) and goes to the top of the recent folders; the same folder is kept /// as it is, with nothing torn down. #[tauri::command(async)] fn open_recent_folder(state: State<'_, AppState>, dir: String) -> Result, String> { refuse_while_looping(&state, "project")?; let path = Path::new(&dir); if !path.is_dir() { return Err(format!("{dir} is not a folder")); } let current = state .project .lock() .map_err(|e| e.to_string())? .as_ref() .map(|p| p.dir.clone()); match current { Some(cur) if !needs_teardown(Some(&cur), path, cfg!(windows)) => return Ok(Some(dir)), Some(_) => teardown_project(&state)?, None => {} } let choice = project::remember_folder(path)?; *state.project.lock().map_err(|e| e.to_string())? = Some(choice); Ok(Some(dir)) } /// The console the agent opened, alive and as it is now, or restarted on the /// same session when it died. The app never starts a dashboard of its own: /// the agent does, by running the skill, and announces it. The one exception /// is `console_setup_start` below: the agent-less `setup` page, which is no /// dashboard and has no agent to announce it, so the app opens it itself. /// Nothing to show yet is an error the page words for the person. #[tauri::command(async)] fn console_start(state: State<'_, AppState>) -> Result { console_start_impl(&state) } /// What `console_start` says before the agent has announced any page. const NO_DASHBOARD_YET: &str = "The agent has not opened the dashboard yet."; /// The health check runs with the console lock released (the announce thread /// takes it to follow a new page); a console the person stopped, or one found /// dead, is opened again on its session, unless a new page was followed /// meanwhile. fn console_start_impl(state: &AppState) -> Result { let probe = { let guard = state.console.lock().map_err(|e| e.to_string())?; guard.as_ref().ok_or(NO_DASHBOARD_YET)?.probe() }; let alive = !probe.stopped() && probe.alive(); let mut guard = state.console.lock().map_err(|e| e.to_string())?; let sup = guard.as_mut().ok_or(NO_DASHBOARD_YET)?; if !alive && sup.probe() == probe { sup.reopen()?; } serde_json::to_value(sup.session()).map_err(|e| e.to_string()) } /// The bar's poll: none (never started or stopped on purpose), running, or /// dead (started but not answering). #[tauri::command(async)] fn console_status(state: State<'_, AppState>) -> serde_json::Value { console_status_impl(&state) } /// The health check runs with the console lock released, as in `console_start`. fn console_status_impl(state: &AppState) -> serde_json::Value { let none = serde_json::json!({ "state": "none", "url": null }); let seen = state.console.lock().ok().and_then(|guard| { guard .as_ref() .map(|sup| (sup.probe(), sup.session().url.clone())) }); match seen { Some((probe, _)) if probe.stopped() => none, Some((probe, url)) if probe.health() => { serde_json::json!({ "state": "running", "url": url }) } Some((_, url)) => serde_json::json!({ "state": "dead", "url": url }), None => none, } } #[tauri::command] fn console_stop(state: State<'_, AppState>) -> Result<(), String> { console_stop_impl(&state) } /// Stop the console but keep its supervisor, so a start after a stop opens /// the same session again instead of finding nothing to start. fn console_stop_impl(state: &AppState) -> Result<(), String> { let mut guard = state.console.lock().map_err(|e| e.to_string())?; if let Some(sup) = guard.as_mut() { sup.stop()?; } Ok(()) } /// Set up an agent: the agent-less `setup` page shown in this window. This /// is the one exception to the app never starting a console of its own (see /// `console_start` above): the setup page is not a dashboard and has no /// agent behind it, and nothing else can open it here. The console is /// started the way the `plan2code` command starts it (`console.mjs open /// --workflow setup`, no announce variables, so it never claims the window /// on its own), and the URL comes back for the page to frame. When /// `console.mjs` cannot be found the error names it, and the page shows its /// plain "skills are missing" checklist row. #[tauri::command(async)] fn console_setup_start( app: tauri::AppHandle, state: State<'_, AppState>, ) -> Result { let origin = window_origin(&app); console_setup_start_impl(&state, &origin) } fn console_setup_start_impl(state: &AppState, origin: &str) -> Result { refuse_while_looping(state, "console")?; let dir = state .project .lock() .ok() .and_then(|p| p.as_ref().map(|p| p.dir.clone())) .ok_or("no project folder chosen")?; // The setup console starts before the old one is stopped: a failed open // (a missing console.mjs, a dead session store) leaves what was showing. let sup = ConsoleSupervisor::start_with_workflow(dir, origin.to_string(), "setup")?; let mut guard = state.console.lock().map_err(|e| e.to_string())?; if let Some(mut old) = guard.take() { let _ = old.stop(); } let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?; *guard = Some(sup); Ok(session) } // What the setup screen shows about the agent a loop would use: the running // agent's launch choice, else what the launcher chose. #[tauri::command] fn loop_facts(state: State<'_, AppState>) -> LoopFacts { let running = state .loop_run .lock() .map(|guard| guard.is_some()) .unwrap_or(false); if let Some((agent, model, effort, mode)) = current_agent(&state).and_then(|a| a.launch_choice()) { return LoopFacts { agent: Some(agent.id().to_string()), agent_label: Some(agent.label().to_string()), model, effort, permission_mode: Some(mode.id().to_string()), prompt_support: loop_driver::prompt_support(&agent), running, }; } let agent = state.launch.agent.as_deref().and_then(agents::find_agent); LoopFacts { agent: agent.as_ref().map(|a| a.id().to_string()), agent_label: agent.as_ref().map(|a| a.label().to_string()), model: state.launch.model.clone(), effort: None, permission_mode: None, prompt_support: agent.as_ref().is_none_or(loop_driver::prompt_support), running, } } // What the loop tells the window and the taskbar: the strip's state on every // change, and the app's own attention when a question holds it. fn loop_hooks(app: &tauri::AppHandle) -> Hooks { let for_strip = app.clone(); let for_attention = app.clone(); Hooks { emit: Box::new(move |event| { let _ = for_strip.emit("loop-state", &event); }), attention: Box::new(move || apply_signal(&for_attention, Signal::Attention)), } } // Starts a loop on `spec`: checks, the app's own confirm, then the first phase. // Async so the confirm's blocking dialog never waits on the main thread. The // setup comes from `loop-setup.json`, never from the page's message. With // `skip_confirm_if_same`, the confirm is skipped when the quick check and the // web address are the ones the person last confirmed (Resume): a changed one is // asked again. async fn start_loop( app: &tauri::AppHandle, state: &AppState, spec: String, skip_confirm_if_same: bool, ) -> Result { if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { return Err("A loop is already running in this window.".to_string()); } let project = state .project .lock() .map_err(|e| e.to_string())? .as_ref() .map(|p| p.dir.clone()) .ok_or("no project folder chosen")?; let agent = current_agent(state) .filter(|a| a.folder() == &project) .ok_or("Start an agent first, with permission checks off.")?; // A stopped agent has forgotten its launch choice; the last loop kept it. let launch = agent .launch_choice() .or_else(|| { state .last_loop .lock() .ok() .and_then(|last| last.as_ref().map(|l| l.launch.clone())) }) .ok_or("Start an agent first, with permission checks off.")?; // Resume (the only caller that skips the confirm) on a spec this app // stopped: the stopped phase's uncommitted work is expected in the tree. let resuming = skip_confirm_if_same && state.last_loop.lock().ok().is_some_and(|last| { last.as_ref() .is_some_and(|l| l.project == project && l.spec == spec) }); let record = loop_driver::prepare( &project, &spec, launch.3, loop_driver::prompt_support(&launch.0), resuming, )?; let check = record.setup.quick_check.clone(); let notify = loop_driver::confirmed_notify(&record.setup); // A Resume that rebuilds a phase or takes uncommitted files into its commit // is asked again: the confirm is where the person is told. let unchanged = skip_confirm_if_same && record.rebuilt.is_empty() && record.resumed_files.is_none() && !loop_driver::commits_to_trunk(&record) && state .last_loop .lock() .map_err(|e| e.to_string())? .as_ref() .is_some_and(|last| { last.project == project && last.spec == spec && last.confirmed_check == check && last.confirmed_notify == notify }); if !unchanged { // The shell's modal: the quick check in a code block, the trunk warning as a callout. let lines = loop_driver::confirm_lines(&record); let asker = app.clone(); let asked = tauri::async_runtime::spawn_blocking(move || { ask_in_window(&asker, |id| ui_confirm::ConfirmRequest { id, title: "Start the Implementation Loop?".to_string(), lines, primary: "Start".to_string(), cancel: "Cancel".to_string(), danger: false, safe_first: true, }) }) .await .map_err(|e| e.to_string())?; let go = match asked { Some(go) => go, // The page cannot show it: the OS box, with the same words as one paragraph. None => app .dialog() .message(loop_driver::confirm_text(&record)) .title("Implementation Loop") .kind(MessageDialogKind::Info) .buttons(MessageDialogButtons::OkCancelCustom( "Start".to_string(), "Cancel".to_string(), )) .blocking_show(), }; if !go { return Ok(false); } } loop_driver::reopen_rebuilt(&record)?; loop_driver::begin( &state.loop_run, agent, record, launch.clone(), loop_hooks(app), )?; if let Ok(mut last) = state.last_loop.lock() { *last = Some(LastLoop { project, spec, launch, confirmed_check: check, confirmed_notify: notify, }); } Ok(true) } #[tauri::command] async fn loop_start( app: tauri::AppHandle, state: State<'_, AppState>, spec: String, ) -> Result { start_loop(&app, &state, spec, false).await } // Send a test: the setup screen saved first, and the address comes from // `loop-setup.json`, never from the page's message. The app names it in its own // confirm. Answers whether a test was sent: false when the person said no. #[tauri::command] async fn loop_notify_test( app: tauri::AppHandle, state: State<'_, AppState>, ) -> Result { let project = state .project .lock() .map_err(|e| e.to_string())? .as_ref() .map(|p| p.dir.clone()) .ok_or("no project folder chosen")?; let setup = loop_driver::read_setup(&project)?; let text = loop_driver::notify_test_confirm(&setup)?; let go = app .dialog() .message(text) .title("Implementation Loop") .kind(MessageDialogKind::Info) .buttons(MessageDialogButtons::OkCancelCustom( "Send".to_string(), "Cancel".to_string(), )) .blocking_show(); if !go { return Ok(false); } // The HTTP client blocks, and panics on an async runtime's own thread. tauri::async_runtime::spawn_blocking(move || loop_driver::send_notify_test(&setup)) .await .map_err(|e| e.to_string())??; Ok(true) } // Stop after this phase: it finishes its review, mark and commit, then the // loop stops instead of starting the next. #[tauri::command] fn loop_stop_after_phase( app: tauri::AppHandle, state: State<'_, AppState>, on: bool, ) -> Result<(), String> { let event = loop_driver::request_stop_after(&state.loop_run, on)?; let _ = app.emit("loop-state", &event); Ok(()) } // Stop now: the flag is set first, then the agent (if one is running) ends at // once. The page asked the person first ("End the agent now? This phase's // changes stay uncommitted."); the strip says Stopping, and the driver tells // the stop screen on its next look. #[tauri::command] fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> { let agent = current_agent(&state); // The event goes out before the agent is ended (which can take a while), so // the strip's "ended" can never be followed by an older "Stopping". loop_driver::request_stop_now(&state.loop_run, agent.as_deref(), |event| { let _ = app.emit("loop-state", event); })?; Ok(()) } // What the loop is doing, for a window that just loaded or just started // listening: the strip event, or nothing when no loop runs. #[tauri::command] fn loop_state(state: State<'_, AppState>) -> Option { loop_driver::current_event(&state.loop_run) .or_else(|| review_loop::current_event(&state.review_run)) } // The project folder and the agent a Review Loop would use, or why there is none. fn review_target( state: &AppState, ) -> Result<(std::path::PathBuf, Arc, loop_driver::Launch), String> { let project = state .project .lock() .map_err(|e| e.to_string())? .as_ref() .map(|p| p.dir.clone()) .ok_or("no project folder chosen")?; let agent = current_agent(state) .filter(|a| a.folder() == &project) .ok_or("Start an agent first, with permission checks off.")?; // A stopped agent has forgotten its launch choice; the run kept its own. let launch = agent .launch_choice() .or_else(|| { state .review_run .lock() .ok() .and_then(|run| run.as_ref().map(|r| r.launch.clone())) }) .ok_or("Start an agent first, with permission checks off.")?; Ok((project, agent, launch)) } // What the Review Loop's setup screen shows about the agent a run would use, // and the notification settings the Implementation Loop's setup holds. #[tauri::command] fn review_loop_facts(state: State<'_, AppState>) -> review_loop::ReviewFacts { let running = loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run); let project = state .project .lock() .ok() .and_then(|guard| guard.as_ref().map(|p| p.dir.clone())); let setup = project .as_deref() .and_then(|dir| loop_driver::read_setup(dir).ok()) .unwrap_or_default(); let agent = current_agent(&state) .and_then(|a| a.launch_choice()) .map(|choice| choice.0) .or_else(|| state.launch.agent.as_deref().and_then(agents::find_agent)); review_loop::facts(agent.as_ref(), running, &setup) } // Starts a Review Loop. Async and off the main thread: the pre-run commit and // the start boundary run git. The notification comes from the Implementation // Loop's setup file, never from the page's message. #[tauri::command] async fn review_loop_start( app: tauri::AppHandle, state: State<'_, AppState>, setup: review_loop::ReviewRequest, ) -> Result { let (project, agent, launch) = review_target(&state)?; let loop_setup = loop_driver::read_setup(&project).unwrap_or_default(); let setup = setup.into_setup(&loop_setup); let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); let hooks = loop_hooks(&app); tauri::async_runtime::spawn_blocking(move || { review_loop::start_review_loop(&slot, &phases, agent, launch, project, setup, hooks) }) .await .map_err(|e| e.to_string())??; Ok(true) } // Stop after this round: it finishes, is judged and committed, then the run stops. #[tauri::command] fn review_loop_stop_after( app: tauri::AppHandle, state: State<'_, AppState>, on: bool, ) -> Result<(), String> { let event = review_loop::request_stop_after(&state.review_run, on)?; let _ = app.emit("loop-state", &event); Ok(()) } // Stop now: the flag first, then the agent ends at once. Nothing more is // committed; the stop screen offers Keep or Discard for the partial changes. #[tauri::command] fn review_loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> { let agent = current_agent(&state); review_loop::request_stop_now(&state.review_run, agent.as_deref(), |event| { let _ = app.emit("loop-state", event); })?; Ok(()) } // Keep the partial changes of a Stop now, or put the tree back to the last // finished round. #[tauri::command] async fn review_loop_partial(state: State<'_, AppState>, keep: bool) -> Result<(), String> { let home = session_reader::console_home().ok_or("no home folder found")?; let slot = state.review_run.clone(); // The end screen is posted through node, so this is not main-thread work. tauri::async_runtime::spawn_blocking(move || review_loop::settle_partial(&slot, keep, &home)) .await .map_err(|e| e.to_string())? } // Sign off a finished Review Loop: fix the Suggestions the person ticked (one // fixer session and its fresh check), squash the round commits when asked, and // show the finished screen. Async and off the main thread: it runs git. #[tauri::command] async fn review_loop_sign_off( app: tauri::AppHandle, state: State<'_, AppState>, picks: Vec, squash: bool, ) -> Result<(), String> { let (project, agent, _) = review_target(&state)?; let same_project = state .review_run .lock() .ok() .and_then(|run| run.as_ref().map(|r| r.project == project)); if same_project != Some(true) { return Err("The project changed since that Review Loop.".to_string()); } let home = session_reader::console_home().ok_or("no home folder found")?; let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); let hooks = loop_hooks(&app); tauri::async_runtime::spawn_blocking(move || { review_loop::sign_off( &slot, &phases, agent, hooks, loop_driver::Limits::default(), home, &picks, squash, true, ) }) .await .map_err(|e| e.to_string())? } // The finished screen's PR Prep and Fix what's left by hand: an ordinary // session on the skill, with no `--loop`, so the person talks to the agent. #[tauri::command] fn review_loop_next(state: State<'_, AppState>, next: String) -> Result<(), String> { let prompt = review_loop::next_prompt(&state.review_run, &next)?; let (_, agent, launch) = review_target(&state)?; loop_driver::start_with(&agent, &launch, prompt) } // Continue a stopped Review Loop: the next round from the last boundary; past // the cap one round at a time, never above six in all. #[tauri::command] async fn review_loop_continue( app: tauri::AppHandle, state: State<'_, AppState>, ) -> Result<(), String> { let (project, agent, _) = review_target(&state)?; // A stopped run stays after a change of project: its git work would run // in the old folder while the agent works in the new one. let same_project = state .review_run .lock() .ok() .and_then(|run| run.as_ref().map(|r| r.project == project)); if same_project != Some(true) { return Err("The project changed since that Review Loop.".to_string()); } let home = session_reader::console_home().ok_or("no home folder found")?; let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); let hooks = loop_hooks(&app); tauri::async_runtime::spawn_blocking(move || { review_loop::continue_run( &slot, &phases, agent, hooks, loop_driver::Limits::default(), home, true, ) }) .await .map_err(|e| e.to_string())? } // The last loop, for the stop and finish screens' buttons. fn last_loop(state: &AppState) -> Result { if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { return Err("A loop is running".to_string()); } let last = state .last_loop .lock() .map_err(|e| e.to_string())? .clone() .ok_or("No loop has run in this session")?; let here = state .project .lock() .map_err(|e| e.to_string())? .as_ref() .map(|p| p.dir.clone()); if here.as_ref() != Some(&last.project) { return Err("The project changed since that loop".to_string()); } Ok(last) } // Resume: start again on the same spec. The app reads the setup and the // spec's marks afresh; the Start dialog is skipped only while the quick check // is the one the person last confirmed. #[tauri::command] async fn loop_resume(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> { let last = last_loop(&state)?; start_loop(&app, &state, last.spec, true).await.map(|_| ()) } // Fix together with an agent: an ordinary Implement session on the stopped phase, with no // `--loop`, so the person talks to the agent as usual. #[tauri::command] fn loop_fix(state: State<'_, AppState>) -> Result<(), String> { let last = last_loop(&state)?; let agent = current_agent(&state).ok_or("No agent is available")?; loop_driver::start_with(&agent, &last.launch, loop_driver::fix_prompt(&last.spec)) } // Ask a question: an ordinary agent on the stopped phase that changes nothing. // It starts without the forget step, so its `open` joins the stopped screen's // session and the Ask tab comes online beside the buttons. #[tauri::command] fn loop_ask(state: State<'_, AppState>) -> Result<(), String> { let last = last_loop(&state)?; let agent = current_agent(&state).ok_or("No agent is available")?; loop_driver::start_asking(&agent, &last.launch, loop_driver::ask_prompt(&last.spec)) } #[tauri::command] fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> { let last = last_loop(&state)?; let agent = current_agent(&state).ok_or("No agent is available")?; loop_driver::start_with( &agent, &last.launch, loop_driver::finalize_prompt(&last.spec), ) } /// The loop end screen's way home: stop the session it ended on and open a /// fresh dashboard console in its place. Needs no agent: a dashboard session /// is only `console.mjs open --workflow dashboard`, which the supervisor runs /// itself. #[tauri::command(async)] fn loop_dashboard(state: State<'_, AppState>) -> Result { let app = state.app.get().cloned().ok_or("no window yet")?; let origin = window_origin(&app); let dir = state .project .lock() .ok() .and_then(|p| p.as_ref().map(|p| p.dir.clone())) .ok_or("no project yet")?; // An Ask or Fix agent started from the stopped screen would go on answering // a session that is about to end: stop it first. if let Some(agent) = current_agent(&state) { agent.stop(); } let mut guard = state.console.lock().map_err(|e| e.to_string())?; if let Some(mut sup) = guard.take() { let _ = sup.stop(); } let sup = ConsoleSupervisor::start(dir, origin)?; let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?; *guard = Some(sup); Ok(session) } /// True when the window-state plugin's file does not exist yet. fn first_launch(app: &tauri::AppHandle) -> bool { use tauri_plugin_window_state::AppHandleExt; app.path() .app_config_dir() .map(|dir| !dir.join(app.filename()).exists()) .unwrap_or(false) } // macOS gets a real menu bar: Plan2Code (About, Check for Updates, Help, Quit) and the standard Edit // menu, so Copy, Paste and Select All work in the page's fields. The three custom items tell the // page (the same actions as the bar's "..." menu); Quit is the predefined one, and the exit it asks // for goes through the quit check in the run loop below. #[cfg(target_os = "macos")] fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> { use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder}; let about = MenuItemBuilder::with_id("about", "About Plan2Code").build(app)?; let check = MenuItemBuilder::with_id("check-updates", "Check for Updates...").build(app)?; let help = MenuItemBuilder::with_id("help", "Plan2Code Help").build(app)?; let app_menu = SubmenuBuilder::new(app, "Plan2Code") .item(&about) .item(&check) .separator() .item(&help) .separator() .quit() .build()?; let edit = SubmenuBuilder::new(app, "Edit") .undo() .redo() .separator() .cut() .copy() .paste() .select_all() .build()?; let menu = MenuBuilder::new(app).items(&[&app_menu, &edit]).build()?; app.set_menu(menu)?; app.on_menu_event(|app, event| { let id = event.id().as_ref(); if matches!(id, "about" | "check-updates" | "help") { let _ = app.emit("app-menu", id); } }); Ok(()) } fn main() { let args = std::env::args().collect::>(); tauri::Builder::default() .plugin(tauri_plugin_dialog::init()) // Opens the terminal's http and https links (the capability scopes it to those). .plugin(tauri_plugin_opener::init()) // Size and position come back on the next launch. Not VISIBLE (the // window stays hidden until the page shows it), nor DECORATIONS or // FULLSCREEN (an Activities game's full screen must not stick). .plugin( tauri_plugin_window_state::Builder::default() .with_state_flags( tauri_plugin_window_state::StateFlags::SIZE | tauri_plugin_window_state::StateFlags::POSITION | tauri_plugin_window_state::StateFlags::MAXIMIZED, ) .build(), ) .manage(AppState { project: Mutex::new(project::resolve(&args)), launch: project::launch_choice(&args), updated_from: settings::settings_file() .and_then(|file| settings::take_updated_from(&file)), attention: Mutex::new(AttentionState { last: None, enabled: settings::settings_file() .is_none_or(|file| settings::load_taskbar_signal(&file)), }), ..AppState::default() }) .invoke_handler(tauri::generate_handler![ platform_info, confirm_answer, confirm_ready, request_quit, agent_availability, open_install_page, agent_start, agent_input, agent_resize, agent_restart, agent_reattach, app_state, save_term_panel, save_terminal_font_size, save_first_run_done, version_status, check_new_release, update_skills, update_to_newest, restart_app, get_copy_on_select, set_copy_on_select, pick_project_folder, recent_folders, open_recent_folder, change_project, console_start, console_status, console_stop, console_setup_start, loop_start, loop_notify_test, loop_facts, loop_stop_after_phase, loop_stop_now, loop_state, review_loop_facts, review_loop_start, review_loop_stop_after, review_loop_stop_now, review_loop_partial, review_loop_sign_off, review_loop_next, review_loop_continue, loop_resume, loop_fix, loop_ask, loop_finalize, loop_dashboard, set_attention, clear_attention_cmd, set_taskbar_signal ]) .on_window_event(|window, event| { // Looking at the window is the answer to its flash. if let tauri::WindowEvent::Focused(true) = event { let _ = window.request_user_attention(None); } // Closing with an agent running asks first; "no" keeps the window open. if let tauri::WindowEvent::CloseRequested { api, .. } = event { let app = window.app_handle().clone(); if agent_is_active(&app) { api.prevent_close(); confirm_quit(&app); } } }) .setup(move |app| { let _ = app.state::().app.set(app.handle().clone()); // Pages the agent's `open` announces: the supervisor and the agent's // environment follow the console, and the page frame shows it. let handle = app.handle().clone(); let server = AnnounceServer::start(Arc::new(move |notice| { let state = handle.state::(); let taken = take_announced(&state, ¬ice, window_origin(&handle), session_on_disk); if taken { // A running loop follows its phase's session from here, // once the agent's `open --loop` has locked it. let page = session_reader::console_home() .and_then(|home| session_reader::load(&home, ¬ice.sid).ok()) .map(|session| session.state) .unwrap_or(serde_json::Value::Null); loop_driver::note_page(&state.loop_run, ¬ice.workflow, ¬ice.sid, &page); review_loop::note_page(&state.review_run, ¬ice.workflow, ¬ice.sid, &page); let _ = handle.emit("console-page", ¬ice); } else { eprintln!( "plan2code: ignored a page outside the console store: {}", notice.sid ); } taken })); match server { Ok(server) => { if let Ok(mut slot) = app.state::().announce.lock() { *slot = Some(server); } } // Without it the agent opens pages the plain way; nothing else breaks. Err(error) => eprintln!("plan2code: no announce endpoint: {error}"), } // First launch ever (the window-state plugin has saved nothing yet): // open maximized. Later launches get the saved size, position and // maximized state from the plugin. if first_launch(app.handle()) { if let Some(window) = app.get_webview_window("main") { let _ = window.maximize(); } } #[cfg(target_os = "macos")] build_mac_menu(app)?; spawn_node_check(app.handle().clone()); Ok(()) }) .build(tauri::generate_context!()) .expect("error while building the Plan2Code app") .run(|app, event| { // Cmd+Q and the app menu's Quit on macOS end the app without closing the // window first. An exit asked for in code (`code` is set) is `quit_app`'s own. if let tauri::RunEvent::ExitRequested { api, code: None, .. } = event { if agent_is_active(app) { api.prevent_exit(); confirm_quit(app); } } }); } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; use std::time::{Duration, Instant}; fn state_for(dir: &str) -> AppState { AppState { project: Mutex::new(Some(ProjectDir { dir: PathBuf::from(dir), source: project::ProjectSource::Picked, })), ..AppState::default() } } 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, ¬ice("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, ¬ice("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, ¬ice("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 // fake agent) can build — out of reach for an inline test here. The // by-hand "Change project" check (RELEASE-CHECKLIST.md) covers that case. #[test] fn a_different_folder_never_gets_the_old_manager_back() { let state = state_for("project-a"); let first = agent_for_project(&state).expect("a manager for project-a"); assert_eq!(first.folder(), &PathBuf::from("project-a")); // The project moved on; the slot still holds project-a's manager // until a fresh call replaces it. *state.project.lock().unwrap() = Some(ProjectDir { dir: PathBuf::from("project-b"), source: project::ProjectSource::Picked, }); let second = agent_for_project(&state).expect("a manager for project-b"); assert_eq!(second.folder(), &PathBuf::from("project-b")); assert!( !Arc::ptr_eq(&first, &second), "project-a's manager must never stand in for project-b's" ); } #[test] fn changing_project_forgets_the_old_projects_session_so_the_new_agent_starts_its_own() { // The new agent's `open` asks the window which session is current; left // at the old project's (its console torn down) it joined a dead page // and never showed its dashboard. let state = state_for("project-a"); announce_page(&state, "s1"); teardown_project(&state).unwrap(); assert_eq!( state.announce.lock().unwrap().as_ref().unwrap().current(), None, "the new project's agent must not join the old project's s1" ); } /// Starts the announce server on `state` and announces page `sid` to it. fn announce_page(state: &AppState, sid: &str) { 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 = format!(r#"{{"url":"http://127.0.0.1:5000/s/abc/","sid":"{sid}","workflow":"plan"}}"#); let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); let token = state .announce .lock() .unwrap() .as_ref() .unwrap() .token() .to_string(); use std::io::{Read, Write}; write!( stream, "POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}\r\nConnection: close\r\n\r\n{body}", body.len() ) .unwrap(); let mut answer = String::new(); stream.read_to_string(&mut answer).unwrap(); assert!( answer.starts_with("HTTP/1.1 204"), "the page was announced: {answer}" ); assert_eq!( state .announce .lock() .unwrap() .as_ref() .unwrap() .current() .map(|n| n.sid), Some(sid.to_string()) ); } #[test] fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own() { let state = state_for("project-a"); announce_page(&state, "s1"); // No console supervised here, so no brief to write: only the forgetting. assert_eq!(before_fresh_hook(&state)(), None); assert_eq!( state.announce.lock().unwrap().as_ref().unwrap().current(), None, "the fresh agent's open must not join s1" ); } #[test] fn the_same_folder_reuses_the_same_manager() { let state = state_for("project-a"); let first = agent_for_project(&state).unwrap(); let second = agent_for_project(&state).unwrap(); assert!( Arc::ptr_eq(&first, &second), "the same folder should not make a second manager" ); } fn have_node() -> bool { std::process::Command::new("node") .arg("--version") .output() .map(|o| o.status.success()) .unwrap_or(false) } #[test] fn a_setup_session_is_never_taken_from_an_announce() { // NFR-2: the only setup page in the window is the one the app itself // opened for Set up an agent. Whatever announces "setup" is refused, // even a session the console store really holds. let state = state_for("project-a"); let mut setup = notice("setup-console"); setup.workflow = "setup".into(); assert!(!take_announced( &state, &setup, app_origin().to_string(), |_| true )); assert!(state.console.lock().unwrap().is_none(), "nothing adopted"); } #[test] fn the_setup_console_needs_a_project_to_open_in() { let state = AppState::default(); let error = console_setup_start_impl(&state, "http://127.0.0.1:1430") .expect_err("no project, no setup page"); assert!(error.contains("project"), "{error}"); } /// Held by every test that starts a real console. The console's variables /// are process-wide and tests run on parallel threads: when two tests set /// `PLAN2CODE_CONSOLE_HOME` to different folders, one test's session was /// looked for in the other's home, found gone, and replaced with a fresh /// one (a Linux CI failure Windows timing hid). static CONSOLE_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// Take the lock, then point the console at the repo's own source and one /// throwaway session home shared by these tests (sids keep them apart), /// with no browser and no in-app variables. `None` (lock released) when /// node or the console source is not here. fn console_test_env() -> Option> { let guard = CONSOLE_ENV.lock().unwrap_or_else(|e| e.into_inner()); if !have_node() { eprintln!("skipping: node is not on PATH"); return None; } let console_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"); if !console_dir.join("console.mjs").is_file() { eprintln!( "skipping: console source missing at {}", console_dir.display() ); return None; } let pid = std::process::id(); 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(guard) } #[test] fn the_setup_console_starts_on_the_setup_workflow() { let Some(_env) = console_test_env() else { return; }; let pid = std::process::id(); let project = std::env::temp_dir().join(format!("p2c-setup-test-project-{pid}")); std::fs::create_dir_all(&project).unwrap(); let state = state_for("project-a"); state.project.lock().unwrap().as_mut().unwrap().dir = project.clone(); let session = console_setup_start_impl(&state, "http://127.0.0.1:1430") .expect("the setup page opens"); let url = session["url"].as_str().unwrap(); assert!(url.starts_with("http://127.0.0.1:"), "{url}"); let sid = session["sid"].as_str().unwrap(); // It is an agent-less setup session on disk, not a dashboard. let home = std::env::var("PLAN2CODE_CONSOLE_HOME").unwrap(); let on_disk: serde_json::Value = serde_json::from_str( &std::fs::read_to_string( PathBuf::from(home) .join("sessions") .join(sid) .join("state.json"), ) .expect("the session's own state"), ) .unwrap(); assert_eq!(on_disk["workflow"].as_str(), Some("setup"), "{on_disk}"); let _ = state.console.lock().unwrap().take().unwrap().stop(); } #[test] fn availability_reports_each_builtins_lookup_state() { // Every entry carries the shared lookup's state: found (on PATH), // outside (needing setup, not missing) or missing, with `folder` for // where an outside hit lives. let json = agent_availability(None); let entries = json["agents"].as_array().unwrap(); assert!(!entries.is_empty()); let mut builtins = 0; for entry in entries { let state = entry["state"].as_str().unwrap(); assert!(["found", "outside", "missing"].contains(&state), "{entry}"); if entry["custom"] == false { builtins += 1; assert!(entry["installUrl"].is_string() || entry["installUrl"].is_null()); } if state == "found" { assert_eq!(entry["installed"], true, "{entry}"); assert!(entry["path"].is_string(), "{entry}"); } } assert!(builtins >= 3, "claude, devin and codex are listed"); } /// A real console, the same way `tests/console_supervisor.rs` sets one /// up (see `console_test_env`). Keep the guard until the test ends: the /// console's variables must not change while its session is in use. fn real_console() -> Option<( std::sync::MutexGuard<'static, ()>, plan2code_app_lib::console_supervisor::ConsoleSupervisor, )> { let guard = console_test_env()?; let pid = std::process::id(); let project = std::env::temp_dir().join(format!("p2c-main-test-project-{pid}")); std::fs::create_dir_all(&project).unwrap(); let sup = plan2code_app_lib::console_supervisor::ConsoleSupervisor::start( project, plan2code_app_lib::console_supervisor::app_origin().to_string(), ) .expect("start a real console for the test"); Some((guard, sup)) } fn state_with_loop(running: bool) -> AppState { let state = state_for("project-a"); if running { *state.loop_run.lock().unwrap() = Some(loop_driver::RunningRecord::new( PathBuf::from("project-a"), "specs/x".into(), loop_driver::LoopSetup::default(), vec![], )); } state } #[test] fn the_window_refuses_to_change_project_or_agent_while_a_loop_runs() { let state = state_with_loop(true); let project = refuse_while_looping(&state, "project").expect_err("a loop is running"); assert!(project.contains("A loop is running"), "{project:?}"); assert!(project.contains("project"), "{project:?}"); let agent = refuse_while_looping(&state, "agent").expect_err("a loop is running"); assert!(agent.contains("change the agent."), "{agent:?}"); } #[test] fn the_window_changes_project_and_agent_freely_with_no_loop() { let state = state_with_loop(false); assert!(refuse_while_looping(&state, "project").is_ok()); assert!(refuse_while_looping(&state, "agent").is_ok()); } #[test] fn loop_state_data_is_none_with_no_loop_and_the_strip_event_with_one() { let idle = state_with_loop(false); assert!(loop_driver::current_event(&idle.loop_run).is_none()); let busy = state_with_loop(true); let event = loop_driver::current_event(&busy.loop_run).expect("a loop runs"); assert!(event.running); assert_eq!(event.spec_name, "x"); } #[test] fn a_start_after_a_stop_opens_the_same_session_again() { let Some((_env, sup)) = real_console() else { return; }; let state = state_for("project-a"); let sid = sup.session().sid.clone(); *state.console.lock().unwrap() = Some(sup); assert_eq!(console_status_impl(&state)["state"], "running"); console_stop_impl(&state).unwrap(); assert_eq!(console_status_impl(&state)["state"], "none"); assert!( state.console.lock().unwrap().is_some(), "the supervisor stays" ); let session = console_start_impl(&state).expect("a start after a stop works"); assert_eq!( session["sid"].as_str(), Some(sid.as_str()), "the same session" ); assert_eq!(console_status_impl(&state)["state"], "running"); let _ = state.console.lock().unwrap().take().unwrap().stop(); } #[test] fn a_slow_health_check_never_holds_the_console_lock() { // A server that takes the connection and never answers: the check // waits out its whole timeout. let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); std::env::set_var( "PLAN2CODE_CONSOLE_DIR", PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"), ); let sup = ConsoleSupervisor::adopt( PathBuf::from("."), app_origin().to_string(), &format!("http://127.0.0.1:{port}/s/slow/"), "slow", ) .expect("adopt"); let state = state_for("project-a"); *state.console.lock().unwrap() = Some(sup); std::thread::scope(|scope| { let poll = scope.spawn(|| console_status_impl(&state)); // The poll is in its health check by now; the announce thread's // lock must not wait for it. std::thread::sleep(Duration::from_millis(300)); let asked = Instant::now(); drop(state.console.lock().unwrap()); assert!( asked.elapsed() < Duration::from_millis(500), "the lock waited {:?} on the health check", asked.elapsed() ); assert_eq!(poll.join().unwrap()["state"], "dead"); }); drop(listener); // Leave nothing to stop: the adopted console was never started. std::mem::forget(state.console.lock().unwrap().take()); } #[test] fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() { let Some((_env, sup)) = real_console() else { return; }; let state = state_for("project-a"); *state.console.lock().unwrap() = Some(sup); assert!( console_start_impl(&state).is_ok(), "console_start should work before the project changes" ); teardown_project(&state).unwrap(); let err = console_start_impl(&state) .expect_err("console_start must refuse, not reconnect to the old session"); assert!( err.contains("has not opened the dashboard"), "unexpected message: {err:?}" ); } #[test] fn opening_a_recent_folder_tears_down_only_a_different_project() { let dir = Path::new("/work/b"); // No project yet: nothing to tear down. assert!(!needs_teardown(None, dir, false)); // The same folder, as written or with a trailing separator. assert!(!needs_teardown(Some(Path::new("/work/b")), dir, false)); assert!(!needs_teardown(Some(Path::new("/work/b/")), dir, false)); // A different folder. assert!(needs_teardown(Some(Path::new("/work/a")), dir, false)); // Case counts outside Windows, not on it. assert!(needs_teardown(Some(Path::new("/work/B")), dir, false)); let win = Path::new(r"C:\Work\B"); assert!(!needs_teardown(Some(Path::new(r"c:\work\b\")), win, true)); assert!(needs_teardown(Some(Path::new(r"C:\Work\A")), win, true)); } }