2026-10-23 10:09:18 -07:00
// Hide the extra console window on Windows release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows" )]
2026-11-17 18:07:59 -08:00
use std ::path ::{ Path , PathBuf };
2026-10-28 01:14:50 -07:00
use std ::sync ::atomic ::{ AtomicBool , Ordering };
2026-10-26 06:36:45 -07:00
use std ::sync ::{ Arc , Mutex , OnceLock };
2026-10-23 10:09:18 -07:00
2026-10-26 06:36:45 -07:00
use plan2code_app_lib ::agent_manager ::{ AgentEvent , AgentManager , AgentState , BeforeFresh , Sink };
2026-11-03 04:08:27 -08:00
use plan2code_app_lib ::agents ::{ self , Agent , PermissionMode };
2026-10-26 20:20:35 -07:00
use plan2code_app_lib ::announce ::{ AnnounceServer , PageNotice };
2026-10-26 06:36:45 -07:00
use plan2code_app_lib ::attention ::{ self , Badge , Signal };
2026-10-26 20:20:35 -07:00
use plan2code_app_lib ::console_supervisor ::{
app_origin , origin_of , session_on_disk , ConsoleSupervisor ,
};
2026-11-02 12:00:10 -08:00
use plan2code_app_lib ::loop_driver ::{ self , Hooks , LastLoop , LoopFacts , LoopSlot };
2026-11-03 04:08:27 -08:00
use plan2code_app_lib ::models ;
2026-10-23 10:09:18 -07:00
use plan2code_app_lib ::node_check ;
use plan2code_app_lib ::project ::{ self , ProjectDir };
2026-11-02 12:00:10 -08:00
use plan2code_app_lib ::quit_prompt ::{ loop_quit_prompt , quit_prompt , QuitCase };
2026-10-23 10:09:18 -07:00
use plan2code_app_lib ::restart_brief ;
2026-11-08 13:48:28 -08:00
use plan2code_app_lib ::session_reader ;
2026-10-23 10:09:18 -07:00
use plan2code_app_lib ::settings ;
2026-10-28 01:14:50 -07:00
#[cfg(windows)]
use plan2code_app_lib ::task_dialog ;
2026-11-17 18:07:59 -08:00
use plan2code_app_lib ::ui_confirm ;
2026-10-23 10:09:18 -07:00
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 < Mutex < Option < Channel < InvokeResponseBody >>>> ;
// 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 < Option < ProjectDir >> ,
// The agent and model the launcher chose, from its arguments.
launch : project ::LaunchChoice ,
console : Arc < Mutex < Option < ConsoleSupervisor >>> ,
agent : Mutex < Option < Arc < AgentManager >>> ,
// 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.
2026-10-25 12:48:14 -07:00
announce : Arc < Mutex < Option < AnnounceServer >>> ,
2026-11-17 18:07:59 -08:00
// 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 < NodeReport > ,
2026-10-26 06:36:45 -07:00
// What the taskbar entry last said, and whether it may say anything.
attention : Mutex < AttentionState > ,
// The app itself, once it is set up: the agent's sink clears the taskbar
// through it when the agent ends.
app : Arc < OnceLock < tauri ::AppHandle >> ,
2026-11-02 12:00:10 -08:00
// The Implementation Loop running now, if any: in memory only, so an app
// restart ends it (NFR-5).
loop_run : LoopSlot ,
// The last loop's project, spec, launch choice and confirmed quick check,
2026-11-09 15:32:04 -08:00
// kept after the running record is gone so Resume, Fix together with an agent and
2026-11-02 12:00:10 -08:00
// Finalize still work. Memory only.
last_loop : Mutex < Option < LastLoop >> ,
2026-11-17 18:07:59 -08:00
// 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 < String > ,
// 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 < String > ,
binary : Option < String > ,
problem : Option < String > ,
}
/// 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 ::< AppState > (). 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 );
}
});
2026-10-26 06:36:45 -07:00
}
// 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 < Signal > ,
enabled : bool ,
}
impl Default for AttentionState {
fn default () -> Self {
2026-10-26 20:20:35 -07:00
AttentionState {
last : None ,
enabled : true ,
}
2026-10-26 06:36:45 -07:00
}
2026-10-23 10:09:18 -07:00
}
// 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
2026-10-26 06:36:45 -07:00
// to install it), and whether it takes its own reasoning effort; plus the
// warnings about agents.json.
2026-10-23 10:09:18 -07:00
#[tauri::command]
2026-10-26 06:36:45 -07:00
fn agent_availability ( refresh : Option < bool > ) -> serde_json ::Value {
2026-11-03 04:08:27 -08:00
// "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.
2026-10-26 06:36:45 -07:00
if refresh == Some ( true ) {
node_check ::refresh_path ();
2026-11-03 04:08:27 -08:00
agents ::refresh_agent_list ();
2026-10-26 06:36:45 -07:00
}
2026-11-03 04:08:27 -08:00
// 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 ()
2026-10-23 10:09:18 -07:00
. iter ()
2026-11-03 04:08:27 -08:00
. map ( | entry | {
let hit = agents ::lookup_agent ( entry );
2026-10-23 10:09:18 -07:00
serde_json ::json! ({
2026-11-03 04:08:27 -08:00
"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 ),
2026-10-25 21:26:11 -07:00
"custom" : false ,
2026-11-03 04:08:27 -08:00
"models" : models ::models_for_builtin ( & entry . id ),
2026-10-23 10:09:18 -07:00
})
})
. collect ();
2026-10-26 06:36:45 -07:00
let ( customs , warnings ) = agents ::custom_agents ();
for custom in customs {
2026-10-25 21:26:11 -07:00
let at = Agent ::Custom ( custom . clone ()). installed_at ();
entries . push ( serde_json ::json! ({
"id" : custom . id ,
"label" : custom . name ,
"installed" : at . is_some (),
2026-11-03 04:08:27 -08:00
"state" : if at . is_some () { "found" } else { "missing" },
2026-10-25 21:26:11 -07:00
"path" : at . map ( | p | p . to_string_lossy (). into_owned ()),
"installHint" : null ,
"installUrl" : null ,
"hasEffort" : false ,
"custom" : true ,
"models" : custom . models ,
}));
}
2026-10-26 06:36:45 -07:00
// 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 })
2026-10-23 10:09:18 -07:00
}
2026-10-25 21:26:11 -07:00
// 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 > {
2026-11-17 18:07:59 -08:00
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 > {
2026-10-25 21:26:11 -07:00
// 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" );
2026-11-17 18:07:59 -08:00
c . args ([ "url.dll,FileProtocolHandler" , url ]);
2026-10-25 21:26:11 -07:00
c
} else if cfg! ( target_os = "macos" ) {
let mut c = std ::process ::Command ::new ( "open" );
2026-11-17 18:07:59 -08:00
c . arg ( url );
2026-10-25 21:26:11 -07:00
c
} else {
2026-10-26 20:20:35 -07:00
let browser = std ::env ::var ( "BROWSER" )
. ok ()
. filter ( | b | ! b . is_empty ())
. unwrap_or_else ( || "xdg-open" . to_string ());
2026-10-25 21:26:11 -07:00
let mut c = std ::process ::Command ::new ( browser );
2026-11-17 18:07:59 -08:00
c . arg ( url );
2026-10-25 21:26:11 -07:00
c
};
2026-10-26 20:20:35 -07:00
command
. stdin ( std ::process ::Stdio ::null ())
. stdout ( std ::process ::Stdio ::null ())
. stderr ( std ::process ::Stdio ::null ());
2026-10-25 21:26:11 -07:00
#[cfg(windows)]
{
use std ::os ::windows ::process ::CommandExt ;
command . creation_flags ( 0x0800_0000 ); // CREATE_NO_WINDOW
}
2026-10-26 20:20:35 -07:00
command
. spawn ()
. map ( | _ | ())
. map_err ( | e | format! ( "could not open {url} : {e} " ))
2026-10-25 21:26:11 -07:00
}
2026-10-23 10:09:18 -07:00
// `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`.
fn windows_build () -> Option < u32 > {
2026-11-08 13:48:28 -08:00
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 () ? ;
2026-10-23 10:09:18 -07:00
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
2026-10-26 06:36:45 -07:00
// 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 < OnceLock < tauri ::AppHandle >> ) -> Sink {
2026-10-23 10:09:18 -07:00
Arc ::new ( move | event | {
2026-10-26 06:36:45 -07:00
if let AgentEvent ::State ( snapshot ) = & event {
if let ( AgentState ::Ended { .. }, Some ( app )) = ( & snapshot . state , app . get ()) {
clear_attention ( app );
}
}
2026-10-23 10:09:18 -07:00
let Ok ( guard ) = page . lock () else { return };
2026-10-26 20:20:35 -07:00
let Some ( channel ) = guard . as_ref () else {
return ;
};
2026-10-23 10:09:18 -07:00
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 < Arc < AgentManager > , String > {
let dir = {
let project = state . project . lock (). map_err ( | e | e . to_string ()) ? ;
2026-10-26 20:20:35 -07:00
project
. as_ref ()
. map ( | p | p . dir . clone ())
. ok_or ( "no project folder chosen" ) ?
2026-10-23 10:09:18 -07:00
};
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 ));
}
}
2026-10-26 06:36:45 -07:00
let sink = page_sink ( Arc ::clone ( & state . page ), Arc ::clone ( & state . app ));
2026-10-23 10:09:18 -07:00
let agent = Arc ::new ( AgentManager ::new ( dir , sink ));
2026-10-25 12:48:14 -07:00
agent . set_before_fresh ( before_fresh_hook ( state ));
2026-11-02 12:00:10 -08:00
agent . set_forget_session ( forget_session_hook ( state ));
2026-10-23 10:09:18 -07:00
* guard = Some ( Arc ::clone ( & agent ));
Ok ( agent )
}
2026-10-25 12:48:14 -07:00
// 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 || {
2026-10-26 20:20:35 -07:00
let sid = console
. lock ()
. ok ()
. and_then ( | guard | guard . as_ref (). map ( | sup | sup . session (). sid . clone ()));
2026-11-09 22:09:03 -08:00
if let ( Some ( sid ), Some ( home )) = ( sid . as_deref (), session_reader ::console_home ()) {
restart_brief ::leave_spec ( & home , sid , chrono ::Utc ::now (). timestamp_millis ());
}
2026-10-25 12:48:14 -07:00
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
})
}
2026-11-02 12:00:10 -08:00
// 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 ();
}
}
})
}
2026-10-23 10:09:18 -07:00
fn current_agent ( state : & AppState ) -> Option < Arc < AgentManager >> {
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.
2026-10-25 21:26:11 -07:00
/// 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.
2026-10-26 20:20:35 -07:00
fn take_announced (
state : & AppState ,
notice : & PageNotice ,
origin : String ,
on_disk : impl Fn ( & str ) -> bool ,
) -> bool {
2026-10-25 21:26:11 -07:00
if ! on_disk ( & notice . sid ) {
return false ;
}
2026-11-03 04:08:27 -08:00
// 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 ;
}
2026-10-25 21:26:11 -07:00
if let Ok ( mut guard ) = state . console . lock () {
match guard . as_mut () {
Some ( sup ) => sup . follow ( & notice . url , & notice . sid ),
None => {
2026-10-26 20:20:35 -07:00
let dir = state
. project
. lock ()
. ok ()
. and_then ( | p | p . as_ref (). map ( | p | p . dir . clone ()));
2026-10-25 21:26:11 -07:00
if let Some ( dir ) = dir {
2026-10-26 20:20:35 -07:00
if let Ok ( sup ) = ConsoleSupervisor ::adopt ( dir , origin , & notice . url , & notice . sid )
{
2026-10-25 21:26:11 -07:00
* guard = Some ( sup );
}
}
}
}
}
true
}
2026-10-23 10:09:18 -07:00
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 ::< AppState > ();
2026-10-26 20:20:35 -07:00
let Some ( agent ) = current_agent ( & state ) else {
return ;
};
2026-10-23 10:09:18 -07:00
let env = match state . announce . lock (). ok () {
Some ( guard ) => guard
. as_ref ()
2026-10-26 20:20:35 -07:00
. map ( | server | {
server . agent_env ( & window_origin ( app ), & app . package_info (). version . to_string ())
})
2026-10-23 10:09:18 -07:00
. unwrap_or_default (),
None => Vec ::new (),
};
agent . set_env ( env );
}
2026-10-23 15:56:51 -07:00
// `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.
2026-11-02 12:00:10 -08:00
// 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 ) {
return Err ( format! (
"A loop is running. Stop it before you change the {what} ."
));
}
Ok (())
}
2026-10-23 10:09:18 -07:00
#[tauri::command]
2026-10-26 20:20:35 -07:00
#[allow(clippy::too_many_arguments)] // one argument per key the frontend passes to invoke
2026-10-23 10:09:18 -07:00
fn agent_start (
app : tauri ::AppHandle ,
state : State < '_ , AppState > ,
kind : String ,
model : Option < String > ,
effort : Option < String > ,
mode : String ,
cols : u16 ,
rows : u16 ,
) -> Result < (), String > {
2026-11-02 12:00:10 -08:00
refuse_while_looping ( & state , "agent" ) ? ;
2026-10-25 21:26:11 -07:00
let kind = agents ::find_agent ( & kind ). ok_or_else ( || format! ( "unknown agent: {kind} " )) ? ;
2026-10-26 20:20:35 -07:00
let mode =
PermissionMode ::from_id ( & mode ). ok_or_else ( || format! ( "unknown permission mode: {mode} " )) ? ;
2026-10-23 10:09:18 -07:00
let agent = agent_for_project ( & state ) ? ;
agent . resize ( cols , rows ) ? ;
sync_agent_env ( & app );
2026-10-25 21:26:11 -07:00
agent . start ( kind . clone (), model , effort , mode , None ) ? ;
2026-10-23 10:09:18 -07:00
// A settings file that cannot be written must not stop the agent.
if let Some ( file ) = settings ::settings_file () {
2026-10-25 21:26:11 -07:00
let _ = settings ::save_last_agent ( & file , kind . id ());
2026-10-23 10:09:18 -07:00
}
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 > {
2026-11-02 12:00:10 -08:00
refuse_while_looping ( & state , "agent" ) ? ;
2026-10-26 20:20:35 -07:00
current_agent ( & state )
. ok_or ( "no agent has been started" ) ?
. restart ()
2026-10-23 10:09:18 -07:00
}
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
2026-10-25 12:50:11 -07:00
/// not come up blank.
2026-10-23 10:09:18 -07:00
#[tauri::command]
2026-10-26 20:20:35 -07:00
fn agent_reattach (
state : State < '_ , AppState > ,
on_output : Channel < InvokeResponseBody > ,
) -> Result < serde_json ::Value , String > {
2026-10-23 10:09:18 -07:00
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 (),
})
}
2026-10-28 01:14:50 -07:00
// 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 );
2026-11-17 18:07:59 -08:00
// 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 < PathBuf > ,
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 < Option < RestartPlan >> = 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 < bool > {
let state = app . state ::< AppState > ();
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 );
2026-10-28 01:14:50 -07:00
}
}
// 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).
2026-10-23 10:09:18 -07:00
fn confirm_quit ( app : & tauri ::AppHandle ) {
2026-10-28 01:14:50 -07:00
if QUIT_OPEN . swap ( true , Ordering ::SeqCst ) {
return ;
}
let open = QuitOpen ;
let last = app
. state ::< AppState > ()
. attention
. lock ()
. ok ()
. and_then ( | guard | guard . last );
2026-11-02 12:00:10 -08:00
// A running loop has its own words, naming what is committed.
let prompt = match loop_driver ::quit_facts ( & app . state ::< AppState > (). loop_run ) {
Some (( phase , phases , committed )) => loop_quit_prompt ( phase , phases , & committed ),
None => quit_prompt ( last ),
};
2026-10-28 01:14:50 -07:00
#[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 ,
};
2026-11-17 18:07:59 -08:00
// 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.
2026-10-23 10:09:18 -07:00
let app = app . clone ();
2026-11-17 18:07:59 -08:00
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 {
2026-10-23 10:09:18 -07:00
if quit {
quit_app ( & app );
}
2026-11-17 18:07:59 -08:00
return ;
2026-10-23 10:09:18 -07:00
}
2026-11-17 18:07:59 -08:00
}
// 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 );
}
});
2026-10-23 10:09:18 -07:00
}
2026-11-02 12:00:10 -08:00
// A running loop counts even between two phases, when no agent runs for a moment.
2026-10-23 10:09:18 -07:00
fn agent_is_active ( app : & tauri ::AppHandle ) -> bool {
2026-11-02 12:00:10 -08:00
let state = app . state ::< AppState > ();
loop_driver ::is_running ( & state . loop_run )
|| current_agent ( & state ). is_some_and ( | agent | agent . is_active ())
2026-10-23 10:09:18 -07:00
}
2026-11-02 12:00:10 -08:00
// 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.
2026-10-23 10:09:18 -07:00
fn quit_app ( app : & tauri ::AppHandle ) {
2026-11-17 18:07:59 -08:00
let restart = RESTART_ON_QUIT . lock (). ok (). and_then ( | mut plan | plan . take ());
2026-10-23 10:09:18 -07:00
let state = app . state ::< AppState > ();
2026-11-02 12:00:10 -08:00
loop_driver ::abandon ( & state . loop_run );
2026-10-23 10:09:18 -07:00
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 ();
}
}
2026-11-17 18:07:59 -08:00
if let Some ( plan ) = restart {
if let Err ( error ) = spawn_restart ( & plan ) {
eprintln! ( "plan2code: restart failed: {error} " );
}
}
2026-10-23 10:09:18 -07:00
app . exit ( 0 );
}
2026-10-26 06:36:45 -07:00
// 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]
2026-11-02 12:00:10 -08:00
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 ::< AppState > ();
2026-10-26 20:20:35 -07:00
let Some ( window ) = app . get_webview_window ( "main" ) else {
return ;
};
2026-10-26 06:36:45 -07:00
let ( prev , enabled ) = {
2026-10-26 20:20:35 -07:00
let Ok ( mut guard ) = state . attention . lock () else {
return ;
};
2026-10-26 06:36:45 -07:00
( guard . last . replace ( next ), guard . enabled )
};
2026-10-26 20:20:35 -07:00
apply_badge (
& window ,
attention ::badge_for ( next , std ::env ::consts ::OS , enabled ),
);
2026-10-26 06:36:45 -07:00
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.
2026-10-26 20:20:35 -07:00
#[cfg_attr(
not(any(target_os = "windows" , target_os = "macos" , target_os = "linux" )),
allow(unused_variables)
)]
2026-10-26 06:36:45 -07:00
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
2026-10-28 01:14:50 -07:00
// 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).
2026-10-26 06:36:45 -07:00
fn clear_attention ( app : & tauri ::AppHandle ) {
if let Ok ( mut guard ) = app . state ::< AppState > (). attention . lock () {
2026-10-28 01:14:50 -07:00
guard . last = None ;
2026-10-26 06:36:45 -07:00
}
2026-10-26 20:20:35 -07:00
let Some ( window ) = app . get_webview_window ( "main" ) else {
return ;
};
2026-10-26 06:36:45 -07:00
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]
2026-10-26 20:20:35 -07:00
fn set_taskbar_signal (
app : tauri ::AppHandle ,
state : State < '_ , AppState > ,
on : bool ,
) -> Result < (), String > {
2026-10-26 06:36:45 -07:00
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 = {
2026-10-26 20:20:35 -07:00
let Ok ( mut guard ) = state . attention . lock () else {
return saved ;
};
2026-10-26 06:36:45 -07:00
guard . enabled = on ;
guard . last . unwrap_or ( Signal ::Plain )
};
if let Some ( window ) = app . get_webview_window ( "main" ) {
2026-10-26 20:20:35 -07:00
apply_badge (
& window ,
attention ::badge_for ( last , std ::env ::consts ::OS , on ),
);
2026-10-26 06:36:45 -07:00
if ! on {
let _ = window . request_user_attention ( None );
}
}
saved
}
2026-10-23 10:09:18 -07:00
/// 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.
2026-10-25 21:26:11 -07:00
// An id that no longer resolves (a removed custom agent) is skipped.
let known = | id : & String | agents ::find_agent ( id ). is_some ();
2026-10-23 10:09:18 -07:00
let last_agent = state
. launch
. agent
2026-10-25 21:26:11 -07:00
. clone ()
. filter ( known )
2026-10-26 20:20:35 -07:00
. or_else ( || {
settings_file
. as_ref ()
. and_then ( | file | settings ::load_last_agent ( file ))
. filter ( known )
})
2026-10-25 21:26:11 -07:00
. or_else ( || project ::remembered_agent (). filter ( known ));
2026-11-06 13:38:13 -08:00
// 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 ));
2026-10-26 20:20:35 -07:00
let first_run_done = settings_file
. as_ref ()
. is_some_and ( | file | settings ::load_first_run_done ( file ));
2026-11-17 18:07:59 -08:00
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 )
});
2026-10-23 10:09:18 -07:00
serde_json ::json! ({
"projectDir" : project . as_ref (). map ( | p | p . dir . to_string_lossy (). into_owned ()),
"projectDirSource" : project . as_ref (). map ( | p | p . source ),
2026-10-25 21:26:11 -07:00
"lastAgent" : last_agent ,
2026-10-23 10:09:18 -07:00
"launchModel" : state . launch . model ,
2026-11-17 18:07:59 -08:00
// 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 ,
2026-10-23 10:09:18 -07:00
"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.
2026-10-25 21:26:11 -07:00
"autoStart" : state . launch . agent ,
2026-10-23 10:09:18 -07:00
"termPanel" : term_panel ,
2026-11-17 18:07:59 -08:00
"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<this app's version>" once.
"updatedFrom" : state . updated_from ,
2026-10-26 06:36:45 -07:00
// The Desktop app switch, for the page's User Preferences.
"taskbarSignal" : state . attention . lock (). map_or ( true , | guard | guard . enabled ),
2026-10-23 10:09:18 -07:00
})
}
/// 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 )
}
2026-11-17 18:07:59 -08:00
/// 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 )
}
2026-10-23 10:09:18 -07:00
/// 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 {
2026-10-26 20:20:35 -07:00
versions ::status (
& app . package_info (). version . to_string (),
versions ::installed_skills_version (),
)
2026-10-23 10:09:18 -07:00
}
2026-11-17 18:07:59 -08:00
/// 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.
2026-11-06 11:01:08 -08:00
#[tauri::command]
2026-11-17 18:07:59 -08:00
async fn check_new_release ( app : tauri ::AppHandle ) -> versions ::ReleaseCheck {
2026-11-06 11:01:08 -08:00
let version = app . package_info (). version . to_string ();
tauri ::async_runtime ::spawn_blocking ( move || versions ::check_new_release ( & version ))
. await
2026-11-17 18:07:59 -08:00
. unwrap_or_else ( | _ | versions ::ReleaseCheck {
latest : None ,
problem : Some ( "Could not check for updates: the check did not finish." . to_string ()),
})
2026-11-06 11:01:08 -08:00
}
2026-10-23 10:09:18 -07:00
/// 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]
2026-10-26 20:20:35 -07:00
async fn update_skills (
app : tauri ::AppHandle ,
progress : Channel < String > ,
) -> Result < UpdateOutcome , String > {
2026-10-23 10:09:18 -07:00
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 ()) ?? ;
2026-10-26 20:20:35 -07:00
let status = versions ::status (
& app . package_info (). version . to_string (),
versions ::installed_skills_version (),
);
2026-10-23 10:09:18 -07:00
Ok ( UpdateOutcome { message , status })
}
2026-11-17 18:07:59 -08:00
/// "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 < String > ,
) -> Result < UpdateOutcome , String > {
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" )
}
2026-11-15 11:22:58 -08:00
/// 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.
2026-11-05 11:38:57 -08:00
#[tauri::command(async)]
2026-10-26 20:20:35 -07:00
fn pick_project_folder (
app : tauri ::AppHandle ,
state : State < '_ , AppState > ,
) -> Result < Option < String > , String > {
2026-11-02 12:00:10 -08:00
refuse_while_looping ( & state , "project" ) ? ;
2026-10-23 10:09:18 -07:00
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
2026-10-23 15:56:51 -07:00
/// 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.
2026-10-23 10:09:18 -07:00
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 ();
}
}
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
2026-10-26 06:36:45 -07:00
/// nothing (canceled) leaves the current project untouched. One project per
2026-10-23 10:09:18 -07:00
/// window stays; this replaces it, it does not add a second.
2026-11-05 11:38:57 -08:00
#[tauri::command(async)]
2026-10-26 20:20:35 -07:00
fn change_project (
app : tauri ::AppHandle ,
state : State < '_ , AppState > ,
) -> Result < Option < String > , String > {
2026-11-02 12:00:10 -08:00
refuse_while_looping ( & state , "project" ) ? ;
2026-10-23 10:09:18 -07:00
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 ))
}
2026-11-15 11:22:58 -08:00
/// 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 < serde_json ::Value > {
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 < Option < String > , 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 ))
}
2026-10-23 10:09:18 -07:00
/// The console the agent opened, alive and as it is now, or restarted on the
2026-10-26 20:20:35 -07:00
/// same session when it died. The app never starts a dashboard of its own:
2026-11-03 04:08:27 -08:00
/// 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.
2026-11-05 11:38:57 -08:00
#[tauri::command(async)]
2026-10-23 10:09:18 -07:00
fn console_start ( state : State < '_ , AppState > ) -> Result < serde_json ::Value , String > {
console_start_impl ( & state )
}
2026-11-08 13:48:28 -08:00
/// 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.
2026-10-23 10:09:18 -07:00
fn console_start_impl ( state : & AppState ) -> Result < serde_json ::Value , String > {
2026-11-08 13:48:28 -08:00
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 ();
2026-10-23 10:09:18 -07:00
let mut guard = state . console . lock (). map_err ( | e | e . to_string ()) ? ;
2026-11-08 13:48:28 -08:00
let sup = guard . as_mut (). ok_or ( NO_DASHBOARD_YET ) ? ;
if ! alive && sup . probe () == probe {
sup . reopen () ? ;
2026-10-23 10:09:18 -07:00
}
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).
2026-11-05 11:38:57 -08:00
#[tauri::command(async)]
2026-10-23 10:09:18 -07:00
fn console_status ( state : State < '_ , AppState > ) -> serde_json ::Value {
2026-11-08 13:48:28 -08:00
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 })
2026-10-26 20:20:35 -07:00
}
2026-11-08 13:48:28 -08:00
Some (( _ , url )) => serde_json ::json! ({ "state" : "dead" , "url" : url }),
None => none ,
2026-10-23 10:09:18 -07:00
}
}
#[tauri::command]
fn console_stop ( state : State < '_ , AppState > ) -> Result < (), String > {
2026-11-08 13:48:28 -08:00
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 > {
2026-10-23 10:09:18 -07:00
let mut guard = state . console . lock (). map_err ( | e | e . to_string ()) ? ;
2026-11-08 13:48:28 -08:00
if let Some ( sup ) = guard . as_mut () {
2026-10-23 10:09:18 -07:00
sup . stop () ? ;
}
Ok (())
}
2026-11-03 04:08:27 -08:00
/// 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.
2026-11-05 11:38:57 -08:00
#[tauri::command(async)]
2026-11-03 04:08:27 -08:00
fn console_setup_start (
app : tauri ::AppHandle ,
state : State < '_ , AppState > ,
) -> Result < serde_json ::Value , String > {
let origin = window_origin ( & app );
console_setup_start_impl ( & state , & origin )
}
fn console_setup_start_impl ( state : & AppState , origin : & str ) -> Result < serde_json ::Value , String > {
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 )
}
2026-11-02 12:00:10 -08:00
// 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 < bool , String > {
if loop_driver ::is_running ( & state . loop_run ) {
return Err ( "A loop is already running" . 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 {
2026-11-17 18:07:59 -08:00
// 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 (),
};
2026-11-02 12:00:10 -08:00
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 < bool , String > {
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 < bool , 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 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 ::LoopStateEvent > {
loop_driver ::current_event ( & state . loop_run )
}
// The last loop, for the stop and finish screens' buttons.
fn last_loop ( state : & AppState ) -> Result < LastLoop , String > {
if loop_driver ::is_running ( & state . loop_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 ( | _ | ())
}
2026-11-09 15:32:04 -08:00
// Fix together with an agent: an ordinary Implement session on the stopped phase, with no
2026-11-02 12:00:10 -08:00
// `--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 ))
}
2026-11-04 20:13:43 -08:00
// 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 ))
}
2026-11-02 12:00:10 -08:00
#[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 ),
)
}
2026-11-02 13:23:13 -08:00
/// 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.
2026-11-05 11:38:57 -08:00
#[tauri::command(async)]
2026-11-02 13:23:13 -08:00
fn loop_dashboard ( state : State < '_ , AppState > ) -> Result < serde_json ::Value , String > {
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" ) ? ;
2026-11-04 20:13:43 -08:00
// 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 ();
}
2026-11-02 13:23:13 -08:00
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 )
}
2026-11-17 18:07:59 -08:00
/// 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 )
}
2026-10-23 10:09:18 -07:00
2026-11-17 18:07:59 -08:00
// 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 () {
2026-10-23 10:09:18 -07:00
let args = std ::env ::args (). collect ::< Vec < _ >> ();
tauri ::Builder ::default ()
. plugin ( tauri_plugin_dialog ::init ())
2026-11-17 18:07:59 -08:00
// 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 (),
)
2026-10-23 10:09:18 -07:00
. manage ( AppState {
project : Mutex ::new ( project ::resolve ( & args )),
launch : project ::launch_choice ( & args ),
2026-11-17 18:07:59 -08:00
updated_from : settings ::settings_file ()
. and_then ( | file | settings ::take_updated_from ( & file )),
2026-10-26 06:36:45 -07:00
attention : Mutex ::new ( AttentionState {
last : None ,
2026-10-26 20:20:35 -07:00
enabled : settings ::settings_file ()
. is_none_or ( | file | settings ::load_taskbar_signal ( & file )),
2026-10-26 06:36:45 -07:00
}),
2026-10-23 10:09:18 -07:00
.. AppState ::default ()
})
. invoke_handler ( tauri ::generate_handler! [
platform_info ,
2026-11-17 18:07:59 -08:00
confirm_answer ,
confirm_ready ,
request_quit ,
2026-10-23 10:09:18 -07:00
agent_availability ,
2026-10-25 21:26:11 -07:00
open_install_page ,
2026-10-23 10:09:18 -07:00
agent_start ,
agent_input ,
agent_resize ,
agent_restart ,
agent_reattach ,
app_state ,
save_term_panel ,
2026-11-17 18:07:59 -08:00
save_terminal_font_size ,
2026-10-23 10:09:18 -07:00
save_first_run_done ,
version_status ,
2026-11-06 11:01:08 -08:00
check_new_release ,
2026-10-23 10:09:18 -07:00
update_skills ,
2026-11-17 18:07:59 -08:00
update_to_newest ,
restart_app ,
get_copy_on_select ,
set_copy_on_select ,
2026-10-23 10:09:18 -07:00
pick_project_folder ,
2026-11-15 11:22:58 -08:00
recent_folders ,
open_recent_folder ,
2026-10-23 10:09:18 -07:00
change_project ,
console_start ,
console_status ,
2026-10-26 06:36:45 -07:00
console_stop ,
2026-11-03 04:08:27 -08:00
console_setup_start ,
2026-11-02 12:00:10 -08:00
loop_start ,
loop_notify_test ,
loop_facts ,
loop_stop_after_phase ,
loop_stop_now ,
loop_state ,
loop_resume ,
loop_fix ,
2026-11-04 20:13:43 -08:00
loop_ask ,
2026-11-02 12:00:10 -08:00
loop_finalize ,
2026-11-02 13:23:13 -08:00
loop_dashboard ,
2026-10-26 06:36:45 -07:00
set_attention ,
clear_attention_cmd ,
set_taskbar_signal
2026-10-23 10:09:18 -07:00
])
. on_window_event ( | window , event | {
2026-10-26 06:36:45 -07:00
// Looking at the window is the answer to its flash.
if let tauri ::WindowEvent ::Focused ( true ) = event {
let _ = window . request_user_attention ( None );
}
2026-10-23 10:09:18 -07:00
// 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 | {
2026-10-26 06:36:45 -07:00
let _ = app . state ::< AppState > (). app . set ( app . handle (). clone ());
2026-10-23 10:09:18 -07:00
// 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 ::< AppState > ();
2026-10-26 20:20:35 -07:00
let taken =
take_announced ( & state , & notice , window_origin ( & handle ), session_on_disk );
2026-10-25 21:26:11 -07:00
if taken {
2026-11-08 13:48:28 -08:00
// 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 , & notice . sid ). ok ())
. map ( | session | session . state )
. unwrap_or ( serde_json ::Value ::Null );
loop_driver ::note_page ( & state . loop_run , & notice . workflow , & notice . sid , & page );
2026-10-25 21:26:11 -07:00
let _ = handle . emit ( "console-page" , & notice );
} else {
2026-10-26 20:20:35 -07:00
eprintln! (
"plan2code: ignored a page outside the console store: {} " ,
notice . sid
);
2026-10-23 10:09:18 -07:00
}
2026-10-25 21:26:11 -07:00
taken
2026-10-23 10:09:18 -07:00
}));
match server {
Ok ( server ) => {
if let Ok ( mut slot ) = app . state ::< AppState > (). 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} " ),
}
2026-11-17 18:07:59 -08:00
// 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 ();
}
2026-10-23 10:09:18 -07:00
}
2026-11-17 18:07:59 -08:00
#[cfg(target_os = "macos" )]
build_mac_menu ( app ) ? ;
spawn_node_check ( app . handle (). clone ());
2026-10-23 10:09:18 -07:00
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.
2026-10-26 20:20:35 -07:00
if let tauri ::RunEvent ::ExitRequested {
api , code : None , ..
} = event
{
2026-10-23 10:09:18 -07:00
if agent_is_active ( app ) {
api . prevent_exit ();
confirm_quit ( app );
}
}
});
}
#[cfg(test)]
mod tests {
use super ::* ;
use std ::path ::PathBuf ;
2026-11-08 13:48:28 -08:00
use std ::time ::{ Duration , Instant };
2026-10-23 10:09:18 -07:00
fn state_for ( dir : & str ) -> AppState {
AppState {
2026-10-26 20:20:35 -07:00
project : Mutex ::new ( Some ( ProjectDir {
dir : PathBuf ::from ( dir ),
source : project ::ProjectSource ::Picked ,
})),
2026-10-23 10:09:18 -07:00
.. AppState ::default ()
}
}
2026-10-25 21:26:11 -07:00
fn notice ( sid : & str ) -> PageNotice {
2026-10-26 20:20:35 -07:00
PageNotice {
url : "http://127.0.0.1:5555/s/t/" . into (),
sid : sid . into (),
workflow : "dashboard" . into (),
}
2026-10-25 21:26:11 -07:00
}
/// 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 {
2026-10-26 20:20:35 -07:00
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" )
2026-10-25 21:26:11 -07:00
}
fn sid_followed ( state : & AppState ) -> String {
2026-10-26 20:20:35 -07:00
state
. console
. lock ()
. unwrap ()
. as_ref ()
. unwrap ()
. session ()
. sid
. clone ()
2026-10-25 21:26:11 -07:00
}
/// 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" );
2026-10-26 20:20:35 -07:00
assert! ( ! take_announced (
& state ,
& notice ( "test-console" ),
app_origin (). to_string (),
| _ | false
));
2026-10-25 21:26:11 -07:00
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 ());
2026-10-26 20:20:35 -07:00
assert! ( ! take_announced (
& state ,
& notice ( "test-console" ),
app_origin (). to_string (),
| _ | false
));
2026-10-25 21:26:11 -07:00
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 ());
2026-10-26 20:20:35 -07:00
assert! ( take_announced (
& state ,
& notice ( "next" ),
app_origin (). to_string (),
| _ | true
));
2026-10-25 21:26:11 -07:00
assert_eq! ( sid_followed ( & state ), "next" );
let_go ( & state );
}
2026-10-23 10:09:18 -07:00
// 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.
2026-10-26 20:20:35 -07:00
* state . project . lock (). unwrap () = Some ( ProjectDir {
dir : PathBuf ::from ( "project-b" ),
source : project ::ProjectSource ::Picked ,
});
2026-10-23 10:09:18 -07:00
let second = agent_for_project ( & state ). expect ( "a manager for project-b" );
assert_eq! ( second . folder (), & PathBuf ::from ( "project-b" ));
2026-10-26 20:20:35 -07:00
assert! (
! Arc ::ptr_eq ( & first , & second ),
"project-a's manager must never stand in for project-b's"
);
2026-10-23 10:09:18 -07:00
}
2026-10-25 12:48:14 -07:00
#[test]
fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own () {
let state = state_for ( "project-a" );
2026-10-25 21:26:11 -07:00
let server = AnnounceServer ::start ( Arc ::new ( | _ | true )). unwrap ();
2026-10-26 20:20:35 -07:00
let port : u16 = server
. url ()
. rsplit_once ( ':' )
. unwrap ()
. 1
. trim_end_matches ( "/page" )
. parse ()
. unwrap ();
2026-10-25 12:48:14 -07:00
* state . announce . lock (). unwrap () = Some ( server );
let body = r #"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"# ;
let mut stream = std ::net ::TcpStream ::connect (( "127.0.0.1" , port )). unwrap ();
2026-10-26 20:20:35 -07:00
let token = state
. announce
. lock ()
. unwrap ()
. as_ref ()
. unwrap ()
. token ()
. to_string ();
2026-10-25 12:48:14 -07:00
use std ::io ::{ Read , Write };
write! (
stream ,
"POST /page HTTP/1.1 \r\n Host: 127.0.0.1 \r\n x-plan2code-token: {token} \r\n content-length: {} \r\n Connection: close \r\n\r\n {body}" ,
body . len ()
)
. unwrap ();
let mut answer = String ::new ();
stream . read_to_string ( & mut answer ). unwrap ();
2026-10-26 20:20:35 -07:00
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 ( "s1" . to_string ())
);
2026-10-25 12:48:14 -07:00
// No console supervised here, so no brief to write: only the forgetting.
assert_eq! ( before_fresh_hook ( & state )(), None );
2026-10-26 20:20:35 -07:00
assert_eq! (
state . announce . lock (). unwrap (). as_ref (). unwrap (). current (),
None ,
"the fresh agent's open must not join s1"
);
2026-10-25 12:48:14 -07:00
}
2026-10-23 10:09:18 -07:00
#[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 ();
2026-10-26 20:20:35 -07:00
assert! (
Arc ::ptr_eq ( & first , & second ),
"the same folder should not make a second manager"
);
2026-10-23 10:09:18 -07:00
}
fn have_node () -> bool {
2026-10-26 20:20:35 -07:00
std ::process ::Command ::new ( "node" )
. arg ( "--version" )
. output ()
. map ( | o | o . status . success ())
. unwrap_or ( false )
2026-10-23 10:09:18 -07:00
}
2026-11-03 04:08:27 -08:00
#[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}" );
}
2026-11-08 19:28:54 -08:00
/// 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 < std ::sync ::MutexGuard < 'static , () >> {
let guard = CONSOLE_ENV . lock (). unwrap_or_else ( | e | e . into_inner ());
if ! have_node () {
eprintln! ( "skipping: node is not on PATH" );
return None ;
}
2026-11-03 04:08:27 -08:00
let console_dir = PathBuf ::from ( env! ( "CARGO_MANIFEST_DIR" )). join ( "../../src/web-console" );
2026-11-08 19:28:54 -08:00
if ! console_dir . join ( "console.mjs" ). is_file () {
eprintln! (
"skipping: console source missing at {} " ,
console_dir . display ()
);
return None ;
2026-11-03 04:08:27 -08:00
}
let pid = std ::process ::id ();
std ::env ::set_var ( "PLAN2CODE_CONSOLE_DIR" , & console_dir );
std ::env ::set_var (
"PLAN2CODE_CONSOLE_HOME" ,
2026-11-08 19:28:54 -08:00
std ::env ::temp_dir (). join ( format! ( "p2c-main-test-home- {pid} " )),
2026-11-03 04:08:27 -08:00
);
std ::env ::set_var ( "PLAN2CODE_NO_BROWSER" , "1" );
2026-11-08 19:28:54 -08:00
// 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.
2026-11-03 04:08:27 -08:00
for name in [
"PLAN2CODE_IN_APP" ,
"PLAN2CODE_APP_ANNOUNCE" ,
"PLAN2CODE_APP_TOKEN" ,
"PLAN2CODE_CONSOLE_SID" ,
] {
std ::env ::remove_var ( name );
}
2026-11-08 19:28:54 -08:00
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 ();
2026-11-03 04:08:27 -08:00
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" );
}
2026-10-23 10:09:18 -07:00
/// A real console, the same way `tests/console_supervisor.rs` sets one
2026-11-08 19:28:54 -08:00
/// 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 () ? ;
2026-10-23 10:09:18 -07:00
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 ();
2026-11-08 19:28:54 -08:00
let sup = plan2code_app_lib ::console_supervisor ::ConsoleSupervisor ::start (
project ,
plan2code_app_lib ::console_supervisor ::app_origin (). to_string (),
2026-10-23 10:09:18 -07:00
)
2026-11-08 19:28:54 -08:00
. expect ( "start a real console for the test" );
Some (( guard , sup ))
2026-10-23 10:09:18 -07:00
}
2026-11-02 12:00:10 -08:00
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" );
}
2026-11-08 13:48:28 -08:00
#[test]
fn a_start_after_a_stop_opens_the_same_session_again () {
2026-11-08 19:28:54 -08:00
let Some (( _env , sup )) = real_console () else {
return ;
};
2026-11-08 13:48:28 -08:00
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 ());
}
2026-10-23 10:09:18 -07:00
#[test]
fn teardown_clears_the_console_so_console_start_refuses_not_reconnects () {
2026-11-08 19:28:54 -08:00
let Some (( _env , sup )) = real_console () else {
return ;
};
2026-10-23 10:09:18 -07:00
let state = state_for ( "project-a" );
* state . console . lock (). unwrap () = Some ( sup );
2026-10-26 20:20:35 -07:00
assert! (
console_start_impl ( & state ). is_ok (),
"console_start should work before the project changes"
);
2026-10-23 10:09:18 -07:00
teardown_project ( & state ). unwrap ();
2026-10-26 20:20:35 -07:00
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:?}"
);
2026-10-23 10:09:18 -07:00
}
2026-11-15 11:22:58 -08:00
#[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 ));
}
2026-10-23 10:09:18 -07:00
}