From 78153576a991bed390b1114cfce52d020f5be3b0 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Mon, 26 Oct 2026 20:20:35 -0700 Subject: [PATCH] Format the desktop app's Rust code, clear its clippy errors, and allow the backticked greyed field name in the US English check so PR checks pass AI Assisted --- plan2code-app/fake-agent/src/main.rs | 10 +- plan2code-app/src-tauri/src/agent_manager.rs | 51 +- plan2code-app/src-tauri/src/agents.rs | 578 +++++++++++++++--- plan2code-app/src-tauri/src/announce.rs | 153 ++++- plan2code-app/src-tauri/src/attention.rs | 75 ++- plan2code-app/src-tauri/src/brief.rs | 135 +++- .../src-tauri/src/console_supervisor.rs | 122 +++- plan2code-app/src-tauri/src/handoff.rs | 80 ++- plan2code-app/src-tauri/src/main.rs | 337 ++++++++-- plan2code-app/src-tauri/src/node_check.rs | 100 ++- plan2code-app/src-tauri/src/project.rs | 114 +++- plan2code-app/src-tauri/src/pty_host.rs | 22 +- plan2code-app/src-tauri/src/restart_brief.rs | 100 ++- plan2code-app/src-tauri/src/session_reader.rs | 36 +- plan2code-app/src-tauri/src/settings.rs | 92 ++- plan2code-app/src-tauri/src/versions.rs | 56 +- .../src-tauri/tests/agent_manager.rs | 170 +++++- plan2code-app/src-tauri/tests/common/mod.rs | 21 +- .../src-tauri/tests/console_supervisor.rs | 39 +- plan2code-app/src-tauri/tests/pty_host.rs | 31 +- scripts/test-us-english.mjs | 1 + 21 files changed, 1898 insertions(+), 425 deletions(-) diff --git a/plan2code-app/fake-agent/src/main.rs b/plan2code-app/fake-agent/src/main.rs index 24a3b06..63f4a19 100644 --- a/plan2code-app/fake-agent/src/main.rs +++ b/plan2code-app/fake-agent/src/main.rs @@ -102,7 +102,10 @@ fn main() { } Command::Size => say(&size_text().unwrap_or_else(|| "SIZE unknown".into())), Command::Pid => say(&format!("PID {}", std::process::id())), - Command::Env(name) => say(&format!("ENV {name}={}", std::env::var(&name).unwrap_or_default())), + Command::Env(name) => say(&format!( + "ENV {name}={}", + std::env::var(&name).unwrap_or_default() + )), Command::Echo(text) => say(&format!("echo: {text}")), } } @@ -118,7 +121,10 @@ mod tests { assert_eq!(parse("EXIT 7\r\n"), Command::Exit(7)); assert_eq!(parse("SIZE"), Command::Size); assert_eq!(parse("PID"), Command::Pid); - assert_eq!(parse("ENV PLAN2CODE_IN_APP"), Command::Env("PLAN2CODE_IN_APP".into())); + assert_eq!( + parse("ENV PLAN2CODE_IN_APP"), + Command::Env("PLAN2CODE_IN_APP".into()) + ); assert_eq!(parse("hello there"), Command::Echo("hello there".into())); } diff --git a/plan2code-app/src-tauri/src/agent_manager.rs b/plan2code-app/src-tauri/src/agent_manager.rs index ca842f7..bd403b8 100644 --- a/plan2code-app/src-tauri/src/agent_manager.rs +++ b/plan2code-app/src-tauri/src/agent_manager.rs @@ -19,7 +19,9 @@ pub enum AgentState { Idle, Running, /// The agent ended without a Restart press, or could not be started. - Ended { reason: String }, + Ended { + reason: String, + }, } /// Runs just before a Restart starts the fresh agent, and returns the line the @@ -114,7 +116,9 @@ pub struct AgentManager { fn lock(inner: &Mutex) -> MutexGuard<'_, Inner> { // A panic in another thread must not take the whole app's agent control down. - inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + inner + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) } impl AgentManager { @@ -173,7 +177,15 @@ impl AgentManager { return Err("an agent is already running for this project".to_string()); } inner.brief_note = None; - let previous = inner.last_start.replace((StartChoice { kind, model, effort, mode }, brief)); + let previous = inner.last_start.replace(( + StartChoice { + kind, + model, + effort, + mode, + }, + brief, + )); match self.shared.spawn(&mut inner) { Ok(()) => Ok(()), Err(e) => { @@ -210,7 +222,10 @@ impl AgentManager { } pub fn input(&self, bytes: &[u8]) -> Result<(), String> { - let host = lock(&self.shared.inner).running.as_ref().map(|r| Arc::clone(&r.host)); + let host = lock(&self.shared.inner) + .running + .as_ref() + .map(|r| Arc::clone(&r.host)); match host { Some(host) => host.write(bytes), None => Ok(()), @@ -271,7 +286,10 @@ impl Shared { fn snapshot(&self, inner: &Inner) -> AgentSnapshot { AgentSnapshot { state: inner.state.clone(), - kind: inner.last_start.as_ref().map(|(choice, _)| choice.kind.id().to_string()), + kind: inner + .last_start + .as_ref() + .map(|(choice, _)| choice.kind.id().to_string()), mode: inner.last_start.as_ref().map(|(choice, _)| choice.mode), generation: self.generation.load(Ordering::SeqCst), brief_note: inner.brief_note.clone(), @@ -284,10 +302,19 @@ impl Shared { /// Start the agent in `inner.last_start` and watch for it to end. fn spawn(self: &Arc, inner: &mut Inner) -> Result<(), String> { - let (choice, brief) = inner.last_start.clone().ok_or("no agent has been started")?; + let (choice, brief) = inner + .last_start + .clone() + .ok_or("no agent has been started")?; let prompt = brief.unwrap_or_else(|| choice.kind.default_prompt().to_string()); - let mut spec = - agent_launch_spec(&choice.kind, &self.folder, choice.model.as_deref(), choice.effort.as_deref(), choice.mode, &prompt); + let mut spec = agent_launch_spec( + &choice.kind, + &self.folder, + choice.model.as_deref(), + choice.effort.as_deref(), + choice.mode, + &prompt, + ); if let Ok(extra) = self.extra_env.lock() { spec.env.extend(extra.iter().cloned()); } @@ -329,7 +356,9 @@ impl Shared { on_output, )?); - inner.running = Some(Running { host: Arc::clone(&host) }); + inner.running = Some(Running { + host: Arc::clone(&host), + }); inner.state = AgentState::Running; // A fresh agent starts on a clean screen; its replay must too. inner.replay.clear(); @@ -360,7 +389,9 @@ impl Shared { match self.spawn(inner) { Ok(()) => Ok(()), Err(e) => { - inner.state = AgentState::Ended { reason: format!("could not start the agent: {e}") }; + inner.state = AgentState::Ended { + reason: format!("could not start the agent: {e}"), + }; self.emit(inner); Err(e) } diff --git a/plan2code-app/src-tauri/src/agents.rs b/plan2code-app/src-tauri/src/agents.rs index 26e082c..9925d6c 100644 --- a/plan2code-app/src-tauri/src/agents.rs +++ b/plan2code-app/src-tauri/src/agents.rs @@ -124,14 +124,25 @@ impl PermissionMode { /// or with `.exe`, `.cmd` or `.bat` on Windows (as `windows_command` resolves /// a program to run). pub fn find_on_path(program: &str, path_var: &str) -> Option { - let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[""] }; - path_var.split(if cfg!(windows) { ';' } else { ':' }).filter(|dir| !dir.is_empty()).find_map(|dir| { - exts.iter().find_map(|ext| { - let name = if ext.is_empty() { program.to_string() } else { format!("{program}.{ext}") }; - let candidate = Path::new(dir).join(name); - candidate.is_file().then_some(candidate) + let exts: &[&str] = if cfg!(windows) { + &["exe", "cmd", "bat"] + } else { + &[""] + }; + path_var + .split(if cfg!(windows) { ';' } else { ':' }) + .filter(|dir| !dir.is_empty()) + .find_map(|dir| { + exts.iter().find_map(|ext| { + let name = if ext.is_empty() { + program.to_string() + } else { + format!("{program}.{ext}") + }; + let candidate = Path::new(dir).join(name); + candidate.is_file().then_some(candidate) + }) }) - }) } /// Where `kind`'s CLI runs from: the test override when it is set, else its @@ -166,11 +177,17 @@ pub fn launch_spec( mode: PermissionMode, prompt: &str, ) -> LaunchSpec { - let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|bin| !bin.is_empty()); + let bin = std::env::var(AGENT_BIN_ENV) + .ok() + .filter(|bin| !bin.is_empty()); let mut spec = launch_spec_with(kind, folder, model, effort, mode, prompt, bin.as_deref()); // The override names a program to run as it is; a real agent is looked up on PATH. if cfg!(windows) && bin.is_none() { - let (program, args) = windows_command(&spec.program, spec.args, &std::env::var("PATH").unwrap_or_default()); + let (program, args) = windows_command( + &spec.program, + spec.args, + &std::env::var("PATH").unwrap_or_default(), + ); spec.program = program; spec.args = args; } @@ -188,7 +205,12 @@ fn launch_spec_with( ) -> LaunchSpec { let cwd = folder.to_path_buf(); if let Some(bin) = bin_override { - return LaunchSpec { program: bin.to_string(), args: vec![], env: vec![], cwd }; + return LaunchSpec { + program: bin.to_string(), + args: vec![], + env: vec![], + cwd, + }; } let strings = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::>(); @@ -245,7 +267,12 @@ fn launch_spec_with( // directories (Task 9.9): the agent CLI itself, and anything it shells // out to, needs a PATH that finds them anyway. let env = vec![("PATH".to_string(), crate::node_check::resolved_path())]; - LaunchSpec { program: program.to_string(), args, env, cwd } + LaunchSpec { + program: program.to_string(), + args, + env, + cwd, + } } /// An agent installed with npm is, on Windows, a `.cmd` shim beside an @@ -330,7 +357,12 @@ pub fn load_custom_agents(file: &Path) -> (Vec, Vec) { match std::fs::read_to_string(file) { Ok(text) => parse_agents_file(&text), Err(e) if e.kind() == std::io::ErrorKind::NotFound => (Vec::new(), Vec::new()), - Err(e) => (Vec::new(), vec![format!("agents.json could not be read ({e}), so no custom agents are used")]), + Err(e) => ( + Vec::new(), + vec![format!( + "agents.json could not be read ({e}), so no custom agents are used" + )], + ), } } @@ -344,19 +376,30 @@ pub fn parse_agents_file(text: &str) -> (Vec, Vec) { return none("agents.json is not an object, so no custom agents are used".to_string()); }; if file.get("schema").and_then(Value::as_f64) != Some(1.0) { - let shown = file.get("schema").map_or("undefined".to_string(), |v| v.to_string()); - return none(format!("agents.json has schema {shown}, not 1, so no custom agents are used")); + let shown = file + .get("schema") + .map_or("undefined".to_string(), |v| v.to_string()); + return none(format!( + "agents.json has schema {shown}, not 1, so no custom agents are used" + )); } let list = match file.get("agents") { None | Some(Value::Null) => return (Vec::new(), Vec::new()), Some(Value::Array(list)) => list, - Some(_) => return none("agents.json: agents is not a list, so no custom agents are used".to_string()), + Some(_) => { + return none( + "agents.json: agents is not a list, so no custom agents are used".to_string(), + ) + } }; let mut warnings = Vec::new(); let mut list: &[Value] = list; if list.len() > MAX_CUSTOM_AGENTS { - warnings.push(format!("agents.json lists {} agents; only the first {MAX_CUSTOM_AGENTS} are used", list.len())); + warnings.push(format!( + "agents.json lists {} agents; only the first {MAX_CUSTOM_AGENTS} are used", + list.len() + )); list = &list[..MAX_CUSTOM_AGENTS]; } let mut agents: Vec = Vec::new(); @@ -377,8 +420,12 @@ pub fn parse_agents_file(text: &str) -> (Vec, Vec) { fn valid_agent_id(id: &str) -> bool { let mut chars = id.chars(); - let first_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); - first_ok && id.len() <= 32 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') + let first_ok = chars + .next() + .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); + first_ok + && id.len() <= 32 + && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') } fn text_list(entry: &Value, field: &str, default: Vec) -> Result, String> { @@ -394,8 +441,14 @@ fn text_list(entry: &Value, field: &str, default: Vec) -> Result, names: &HashSet) -> Result { - let Some(object) = entry.as_object() else { return Err("not an object".to_string()) }; +fn check_entry( + entry: &Value, + ids: &HashSet, + names: &HashSet, +) -> Result { + let Some(object) = entry.as_object() else { + return Err("not an object".to_string()); + }; let id = match object.get("id").and_then(Value::as_str) { Some(id) if !id.is_empty() => id, _ => return Err("id is missing".to_string()), @@ -412,7 +465,10 @@ fn check_entry(entry: &Value, ids: &HashSet, names: &HashSet) -> return Err(format!("id \"{id}\" is already used")); } - let name = object.get("name").and_then(Value::as_str).map_or("", str::trim); + let name = object + .get("name") + .and_then(Value::as_str) + .map_or("", str::trim); if name.is_empty() { return Err("name is missing".to_string()); } @@ -423,7 +479,10 @@ fn check_entry(entry: &Value, ids: &HashSet, names: &HashSet) -> return Err(format!("name \"{name}\" is already used")); } - let command = object.get("command").and_then(Value::as_str).map_or("", str::trim); + let command = object + .get("command") + .and_then(Value::as_str) + .map_or("", str::trim); if command.is_empty() { return Err("command is missing".to_string()); } @@ -451,8 +510,15 @@ fn check_entry(entry: &Value, ids: &HashSet, names: &HashSet) -> if model_id.is_empty() || !seen.insert(model_id.to_string()) { continue; } - let label = item.get("label").and_then(Value::as_str).map(str::trim).filter(|l| !l.is_empty()); - models.push(CustomModel { id: model_id.to_string(), label: label.map(str::to_string) }); + let label = item + .get("label") + .and_then(Value::as_str) + .map(str::trim) + .filter(|l| !l.is_empty()); + models.push(CustomModel { + id: model_id.to_string(), + label: label.map(str::to_string), + }); } } Some(_) => return Err("models must be a list".to_string()), @@ -475,7 +541,12 @@ fn check_entry(entry: &Value, ids: &HashSet, names: &HashSet) -> /// argument holds it), then `model_args` when a model is chosen, then /// `bypass_args` when checks are off. `prompt` defaults to the entry's own; a /// blank one drops an argument that is exactly `{prompt}`. Plain text only. -pub fn build_custom_args(agent: &CustomAgent, prompt: Option<&str>, model: Option<&str>, bypass: bool) -> Vec { +pub fn build_custom_args( + agent: &CustomAgent, + prompt: Option<&str>, + model: Option<&str>, + bypass: bool, +) -> Vec { let text = prompt.unwrap_or(&agent.prompt); let blank = text.trim().is_empty(); let mut out = Vec::new(); @@ -495,7 +566,12 @@ pub fn build_custom_args(agent: &CustomAgent, prompt: Option<&str>, model: Optio out.push(text.to_string()); } if let Some(model) = model.filter(|m| !m.is_empty()) { - out.extend(agent.model_args.iter().map(|arg| arg.replace("{model}", model))); + out.extend( + agent + .model_args + .iter() + .map(|arg| arg.replace("{model}", model)), + ); } if bypass { out.extend(agent.bypass_args.iter().cloned()); @@ -563,18 +639,26 @@ pub fn find_agent_in(id: &str, file: Option<&Path>) -> Option { return Some(Agent::Builtin(kind)); } let (agents, _) = load_custom_agents(file?); - agents.into_iter().find(|agent| agent.id == id).map(Agent::Custom) + agents + .into_iter() + .find(|agent| agent.id == id) + .map(Agent::Custom) } /// Every custom agent in `~/.plan2code/agents.json`, read afresh, with the /// warnings about anything in the file that was skipped. pub fn custom_agents() -> (Vec, Vec) { - agents_file().map(|file| load_custom_agents(&file)).unwrap_or_default() + agents_file() + .map(|file| load_custom_agents(&file)) + .unwrap_or_default() } fn clean_command(command: &str) -> &str { let command = command.trim(); - command.strip_prefix('"').and_then(|c| c.strip_suffix('"')).unwrap_or(command) + command + .strip_prefix('"') + .and_then(|c| c.strip_suffix('"')) + .unwrap_or(command) } fn has_separator(command: &str, windows: bool) -> bool { @@ -634,8 +718,16 @@ pub fn agent_launch_spec( match agent { Agent::Builtin(kind) => launch_spec(*kind, folder, model, effort, mode, prompt), Agent::Custom(custom) => { - if let Some(bin) = std::env::var(AGENT_BIN_ENV).ok().filter(|bin| !bin.is_empty()) { - return LaunchSpec { program: bin, args: vec![], env: vec![], cwd: folder.to_path_buf() }; + if let Some(bin) = std::env::var(AGENT_BIN_ENV) + .ok() + .filter(|bin| !bin.is_empty()) + { + return LaunchSpec { + program: bin, + args: vec![], + env: vec![], + cwd: folder.to_path_buf(), + }; } let resolved = agent.installed_at(); custom_launch_spec( @@ -667,13 +759,21 @@ fn custom_launch_spec( ) -> LaunchSpec { let mut args = build_custom_args(custom, Some(prompt), model, mode == PermissionMode::Bypass); let mut path = base_path.to_string(); - let mut program = - resolved.map_or_else(|| clean_command(&custom.command).to_string(), |p| p.to_string_lossy().into_owned()); + let mut program = resolved.map_or_else( + || clean_command(&custom.command).to_string(), + |p| p.to_string_lossy().into_owned(), + ); let mut extra_env = Vec::new(); if windows { - let ext = resolved.and_then(|p| p.extension()).map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default(); + let ext = resolved + .and_then(|p| p.extension()) + .map(|e| e.to_string_lossy().to_lowercase()) + .unwrap_or_default(); if let (true, Some(file)) = (ext == "cmd" || ext == "bat", resolved) { - let file_name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let file_name = file + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); // A full path may have a space in its folder, and `cmd /c` mangles a // command line that starts with a quote: run the bare file name with // its folder at the front of the child's PATH instead. @@ -687,18 +787,33 @@ fn custom_launch_spec( // quoted as the launcher's `quoteForCmd` does and handed over in a // variable: `cmd` expands it once and then parses it, so its quotes // hold and a `%` inside it is not expanded again. - let line: Vec = std::iter::once(file_name).chain(args).map(|arg| quote_for_cmd(&arg)).collect(); + let line: Vec = std::iter::once(file_name) + .chain(args) + .map(|arg| quote_for_cmd(&arg)) + .collect(); extra_env.push((CMD_LINE_ENV.to_string(), line.join(" "))); // `cmd` looks in the current folder (the project) before PATH: a // same-named file there must not run in the agent's place. - extra_env.push(("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string())); - args = vec!["/d".to_string(), "/c".to_string(), format!("%{CMD_LINE_ENV}%")]; + extra_env.push(( + "NoDefaultCurrentDirectoryInExePath".to_string(), + "1".to_string(), + )); + args = vec![ + "/d".to_string(), + "/c".to_string(), + format!("%{CMD_LINE_ENV}%"), + ]; program = "cmd".to_string(); } } let mut env = vec![("PATH".to_string(), path)]; env.append(&mut extra_env); - LaunchSpec { program, args, env, cwd: folder.to_path_buf() } + LaunchSpec { + program, + args, + env, + cwd: folder.to_path_buf(), + } } /// The variable a custom `.cmd` or `.bat` agent's command line reaches `cmd` in. @@ -716,7 +831,9 @@ fn quote_for_cmd(arg: &str) -> String { /// The page a built-in agent installs from; any other id is an error. pub fn install_page_url(id: &str) -> Result<&'static str, String> { - AgentKind::from_id(id).map(AgentKind::install_url).ok_or_else(|| format!("no install page for agent: {id}")) + AgentKind::from_id(id) + .map(AgentKind::install_url) + .ok_or_else(|| format!("no install page for agent: {id}")) } #[cfg(test)] @@ -727,15 +844,31 @@ mod tests { PathBuf::from("project") } - fn args(kind: AgentKind, model: Option<&str>, mode: PermissionMode, prompt: &str) -> Vec { + fn args( + kind: AgentKind, + model: Option<&str>, + mode: PermissionMode, + prompt: &str, + ) -> Vec { launch_spec_with(kind, &folder(), model, None, mode, prompt, None).args } #[test] fn claude_puts_the_prompt_first() { - let spec = launch_spec_with(AgentKind::Claude, &folder(), None, None, PermissionMode::Bypass, "/plan2code", None); + let spec = launch_spec_with( + AgentKind::Claude, + &folder(), + None, + None, + PermissionMode::Bypass, + "/plan2code", + None, + ); assert_eq!(spec.program, "claude"); - assert_eq!(spec.args, ["/plan2code", "--permission-mode", "bypassPermissions"]); + assert_eq!( + spec.args, + ["/plan2code", "--permission-mode", "bypassPermissions"] + ); assert_eq!(spec.cwd, folder()); // A PATH that can still find nvm, Homebrew or Volta's directories (Task 9.9). assert_eq!(spec.env.iter().filter(|(k, _)| k == "PATH").count(), 1); @@ -744,21 +877,56 @@ mod tests { #[test] fn claude_with_a_model() { assert_eq!( - args(AgentKind::Claude, Some("sonnet"), PermissionMode::Bypass, "/plan2code"), - ["/plan2code", "--permission-mode", "bypassPermissions", "--model", "sonnet"] + args( + AgentKind::Claude, + Some("sonnet"), + PermissionMode::Bypass, + "/plan2code" + ), + [ + "/plan2code", + "--permission-mode", + "bypassPermissions", + "--model", + "sonnet" + ] ); } #[test] fn claude_checked_mode_skips_the_bypass_flag() { - assert_eq!(args(AgentKind::Claude, None, PermissionMode::Checked, "/plan2code"), ["/plan2code"]); + assert_eq!( + args( + AgentKind::Claude, + None, + PermissionMode::Checked, + "/plan2code" + ), + ["/plan2code"] + ); } #[test] fn claude_with_an_effort() { - let spec = - launch_spec_with(AgentKind::Claude, &folder(), None, Some("high"), PermissionMode::Bypass, "/plan2code", None); - assert_eq!(spec.args, ["/plan2code", "--permission-mode", "bypassPermissions", "--effort", "high"]); + let spec = launch_spec_with( + AgentKind::Claude, + &folder(), + None, + Some("high"), + PermissionMode::Bypass, + "/plan2code", + None, + ); + assert_eq!( + spec.args, + [ + "/plan2code", + "--permission-mode", + "bypassPermissions", + "--effort", + "high" + ] + ); } #[test] @@ -774,7 +942,15 @@ mod tests { ); assert_eq!( spec.args, - ["/plan2code", "--permission-mode", "bypassPermissions", "--model", "opus", "--effort", "xhigh"] + [ + "/plan2code", + "--permission-mode", + "bypassPermissions", + "--model", + "opus", + "--effort", + "xhigh" + ] ); let checked = launch_spec_with( AgentKind::Codex, @@ -785,72 +961,171 @@ mod tests { "$plan2code", None, ); - assert_eq!(checked.args, ["--model", "gpt-5", "-c", "model_reasoning_effort=medium", "$plan2code"]); + assert_eq!( + checked.args, + [ + "--model", + "gpt-5", + "-c", + "model_reasoning_effort=medium", + "$plan2code" + ] + ); } #[test] fn devin_puts_the_prompt_after_a_double_dash() { - let spec = launch_spec_with(AgentKind::Devin, &folder(), None, None, PermissionMode::Bypass, "/plan2code", None); + let spec = launch_spec_with( + AgentKind::Devin, + &folder(), + None, + None, + PermissionMode::Bypass, + "/plan2code", + None, + ); assert_eq!(spec.program, "devin"); - assert_eq!(spec.args, ["--permission-mode", "bypass", "--", "/plan2code"]); + assert_eq!( + spec.args, + ["--permission-mode", "bypass", "--", "/plan2code"] + ); } #[test] fn devin_with_a_model_keeps_the_prompt_last() { assert_eq!( - args(AgentKind::Devin, Some("opus"), PermissionMode::Bypass, "/plan2code"), - ["--permission-mode", "bypass", "--model", "opus", "--", "/plan2code"] + args( + AgentKind::Devin, + Some("opus"), + PermissionMode::Bypass, + "/plan2code" + ), + [ + "--permission-mode", + "bypass", + "--model", + "opus", + "--", + "/plan2code" + ] ); } #[test] fn devin_checked_mode_skips_the_bypass_flag() { - assert_eq!(args(AgentKind::Devin, None, PermissionMode::Checked, "/plan2code"), ["--", "/plan2code"]); + assert_eq!( + args( + AgentKind::Devin, + None, + PermissionMode::Checked, + "/plan2code" + ), + ["--", "/plan2code"] + ); } #[test] fn codex_uses_its_own_flag_and_dollar_prompt() { let prompt = AgentKind::Codex.default_prompt(); - let spec = launch_spec_with(AgentKind::Codex, &folder(), None, None, PermissionMode::Bypass, prompt, None); + let spec = launch_spec_with( + AgentKind::Codex, + &folder(), + None, + None, + PermissionMode::Bypass, + prompt, + None, + ); assert_eq!(spec.program, "codex"); - assert_eq!(spec.args, ["--dangerously-bypass-approvals-and-sandbox", "$plan2code"]); + assert_eq!( + spec.args, + ["--dangerously-bypass-approvals-and-sandbox", "$plan2code"] + ); } #[test] fn codex_with_a_model() { assert_eq!( - args(AgentKind::Codex, Some("gpt-5"), PermissionMode::Bypass, "$plan2code"), - ["--dangerously-bypass-approvals-and-sandbox", "--model", "gpt-5", "$plan2code"] + args( + AgentKind::Codex, + Some("gpt-5"), + PermissionMode::Bypass, + "$plan2code" + ), + [ + "--dangerously-bypass-approvals-and-sandbox", + "--model", + "gpt-5", + "$plan2code" + ] ); } #[test] fn codex_with_an_effort_uses_a_config_override() { - let spec = - launch_spec_with(AgentKind::Codex, &folder(), None, Some("low"), PermissionMode::Bypass, "$plan2code", None); + let spec = launch_spec_with( + AgentKind::Codex, + &folder(), + None, + Some("low"), + PermissionMode::Bypass, + "$plan2code", + None, + ); assert_eq!( spec.args, - ["--dangerously-bypass-approvals-and-sandbox", "-c", "model_reasoning_effort=low", "$plan2code"] + [ + "--dangerously-bypass-approvals-and-sandbox", + "-c", + "model_reasoning_effort=low", + "$plan2code" + ] ); } #[test] fn codex_checked_mode_skips_the_bypass_flag() { - assert_eq!(args(AgentKind::Codex, None, PermissionMode::Checked, "$plan2code"), ["$plan2code"]); + assert_eq!( + args( + AgentKind::Codex, + None, + PermissionMode::Checked, + "$plan2code" + ), + ["$plan2code"] + ); } #[test] fn no_prompt_means_nothing_typed() { - assert_eq!(args(AgentKind::Claude, None, PermissionMode::Bypass, ""), ["--permission-mode", "bypassPermissions"]); - assert_eq!(args(AgentKind::Devin, None, PermissionMode::Bypass, ""), ["--permission-mode", "bypass"]); - assert_eq!(args(AgentKind::Codex, None, PermissionMode::Bypass, ""), ["--dangerously-bypass-approvals-and-sandbox"]); + assert_eq!( + args(AgentKind::Claude, None, PermissionMode::Bypass, ""), + ["--permission-mode", "bypassPermissions"] + ); + assert_eq!( + args(AgentKind::Devin, None, PermissionMode::Bypass, ""), + ["--permission-mode", "bypass"] + ); + assert_eq!( + args(AgentKind::Codex, None, PermissionMode::Bypass, ""), + ["--dangerously-bypass-approvals-and-sandbox"] + ); } #[test] fn a_custom_prompt_is_passed_through() { assert_eq!( - args(AgentKind::Claude, None, PermissionMode::Bypass, "/plan2code pick up the brief"), - ["/plan2code pick up the brief", "--permission-mode", "bypassPermissions"] + args( + AgentKind::Claude, + None, + PermissionMode::Bypass, + "/plan2code pick up the brief" + ), + [ + "/plan2code pick up the brief", + "--permission-mode", + "bypassPermissions" + ] ); } @@ -912,13 +1187,23 @@ mod tests { let (program, wrapped) = windows_command("tool", args.clone(), &path); assert_eq!(program, "cmd"); - assert_eq!(wrapped, ["/c".to_string(), "tool.cmd".to_string(), "--flag".to_string()]); + assert_eq!( + wrapped, + [ + "/c".to_string(), + "tool.cmd".to_string(), + "--flag".to_string() + ] + ); let (program, same) = windows_command("real", args.clone(), &path); assert_eq!(program, dir.join("real.exe").to_string_lossy()); assert_eq!(same, args); - assert_eq!(windows_command("missing", args.clone(), &path), ("missing".to_string(), args)); + assert_eq!( + windows_command("missing", args.clone(), &path), + ("missing".to_string(), args) + ); let _ = std::fs::remove_dir_all(&dir); } @@ -957,7 +1242,10 @@ mod tests { } for part in parts { let part = part.as_str().unwrap(); - assert!(warnings.iter().any(|w| w.contains(part)), "{name}: no warning names {part}: {warnings:?}"); + assert!( + warnings.iter().any(|w| w.contains(part)), + "{name}: no warning names {part}: {warnings:?}" + ); } } } @@ -983,7 +1271,8 @@ mod tests { } fn temp_dir(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("plan2code-agents-{}-{name}", std::process::id())); + let dir = + std::env::temp_dir().join(format!("plan2code-agents-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir @@ -994,7 +1283,10 @@ mod tests { #[test] fn a_missing_file_is_empty_and_a_bad_one_warns() { let dir = temp_dir("load"); - assert_eq!(load_custom_agents(&dir.join("agents.json")), (Vec::new(), Vec::new())); + assert_eq!( + load_custom_agents(&dir.join("agents.json")), + (Vec::new(), Vec::new()) + ); std::fs::write(dir.join("agents.json"), "{ nope").unwrap(); let (agents, warnings) = load_custom_agents(&dir.join("agents.json")); assert!(agents.is_empty() && warnings.len() == 1); @@ -1006,9 +1298,20 @@ mod tests { let dir = temp_dir("find"); let file = dir.join("agents.json"); std::fs::write(&file, GOOSE).unwrap(); - assert_eq!(find_agent_in("claude", Some(&file)), Some(Agent::Builtin(AgentKind::Claude))); + assert_eq!( + find_agent_in("claude", Some(&file)), + Some(Agent::Builtin(AgentKind::Claude)) + ); let goose = find_agent_in("goose", Some(&file)).unwrap(); - assert_eq!((goose.id(), goose.label(), goose.has_effort(), goose.default_prompt()), ("goose", "Goose", false, "/plan2code")); + assert_eq!( + ( + goose.id(), + goose.label(), + goose.has_effort(), + goose.default_prompt() + ), + ("goose", "Goose", false, "/plan2code") + ); assert_eq!(find_agent_in("goose", None), None); assert_eq!(find_agent_in("nope", Some(&file)), None); let _ = std::fs::remove_dir_all(&dir); @@ -1021,13 +1324,40 @@ mod tests { #[test] fn a_custom_launch_spec_has_its_program_and_arguments() { let bin = Path::new("tools").join("goose"); - let spec = custom_launch_spec(&goose(), Some(&bin), &folder(), None, PermissionMode::Checked, "/plan2code", "P", false); + let spec = custom_launch_spec( + &goose(), + Some(&bin), + &folder(), + None, + PermissionMode::Checked, + "/plan2code", + "P", + false, + ); assert_eq!(spec.program, bin.to_string_lossy()); assert_eq!(spec.args, ["/plan2code"]); assert_eq!(spec.env, [("PATH".to_string(), "P".to_string())]); - let spec = custom_launch_spec(&goose(), Some(&bin), &folder(), Some("m"), PermissionMode::Bypass, "/plan2code", "P", false); + let spec = custom_launch_spec( + &goose(), + Some(&bin), + &folder(), + Some("m"), + PermissionMode::Bypass, + "/plan2code", + "P", + false, + ); assert_eq!(spec.args, ["/plan2code", "--model", "m", "--yes"]); - let spec = custom_launch_spec(&goose(), None, &folder(), None, PermissionMode::Checked, "", "P", false); + let spec = custom_launch_spec( + &goose(), + None, + &folder(), + None, + PermissionMode::Checked, + "", + "P", + false, + ); assert_eq!((spec.program.as_str(), spec.args.len()), ("goose", 0)); } @@ -1036,15 +1366,51 @@ mod tests { let mut full = goose(); full.command = "C:\\with space\\goose.cmd".to_string(); let found = Path::new("C:\\with space").join("goose.cmd"); - let spec = custom_launch_spec(&full, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true); + let spec = custom_launch_spec( + &full, + Some(&found), + &folder(), + None, + PermissionMode::Checked, + "/p", + "BASE", + true, + ); assert_eq!(spec.program, "cmd"); assert_eq!(spec.args, ["/d", "/c", "%PLAN2CODE_AGENT_LINE%"]); - assert_eq!(spec.env[0].1, format!("{};BASE", found.parent().unwrap().to_string_lossy())); - assert_eq!(spec.env[1], ("PLAN2CODE_AGENT_LINE".to_string(), "goose.cmd /p".to_string())); - assert_eq!(spec.env[2], ("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string())); + assert_eq!( + spec.env[0].1, + format!("{};BASE", found.parent().unwrap().to_string_lossy()) + ); + assert_eq!( + spec.env[1], + ( + "PLAN2CODE_AGENT_LINE".to_string(), + "goose.cmd /p".to_string() + ) + ); + assert_eq!( + spec.env[2], + ( + "NoDefaultCurrentDirectoryInExePath".to_string(), + "1".to_string() + ) + ); // A bare name keeps the plain PATH. - let bare = custom_launch_spec(&goose(), Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true); - assert_eq!((bare.program.as_str(), bare.env[0].1.as_str()), ("cmd", "BASE")); + let bare = custom_launch_spec( + &goose(), + Some(&found), + &folder(), + None, + PermissionMode::Checked, + "/p", + "BASE", + true, + ); + assert_eq!( + (bare.program.as_str(), bare.env[0].1.as_str()), + ("cmd", "BASE") + ); } #[test] @@ -1057,7 +1423,16 @@ mod tests { let mut agent = goose(); agent.args = vec!["--filter=a|b".to_string(), "{prompt}".to_string()]; let found = Path::new("C:\\tools").join("goose.cmd"); - let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p & x", "BASE", true); + let spec = custom_launch_spec( + &agent, + Some(&found), + &folder(), + None, + PermissionMode::Checked, + "/p & x", + "BASE", + true, + ); assert_eq!(spec.env[1].1, "goose.cmd \"--filter=a|b\" \"/p & x\""); } @@ -1069,17 +1444,35 @@ mod tests { let project = root.join("project"); std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&project).unwrap(); - std::fs::write(dir.join("goose.cmd"), "@echo off\r\necho REAL [%1] [%2]\r\n").unwrap(); + std::fs::write( + dir.join("goose.cmd"), + "@echo off\r\necho REAL [%1] [%2]\r\n", + ) + .unwrap(); // A same-named file in the project folder must not run instead. std::fs::write(project.join("goose.cmd"), "@echo off\r\necho DECOY\r\n").unwrap(); let mut agent = goose(); agent.command = dir.join("goose.cmd").to_string_lossy().into_owned(); agent.args = vec!["a|b".to_string(), "%PATH%".to_string()]; - let found = Agent::Custom(agent.clone()).installed_at().expect("resolves"); - let spec = custom_launch_spec(&agent, Some(&found), &project, None, PermissionMode::Checked, "", &std::env::var("PATH").unwrap_or_default(), true); + let found = Agent::Custom(agent.clone()) + .installed_at() + .expect("resolves"); + let spec = custom_launch_spec( + &agent, + Some(&found), + &project, + None, + PermissionMode::Checked, + "", + &std::env::var("PATH").unwrap_or_default(), + true, + ); let mut command = std::process::Command::new(&spec.program); // Some shells already set the switch the spec sets; start without it. - command.args(&spec.args).current_dir(&spec.cwd).env_remove("NoDefaultCurrentDirectoryInExePath"); + command + .args(&spec.args) + .current_dir(&spec.cwd) + .env_remove("NoDefaultCurrentDirectoryInExePath"); for (key, value) in &spec.env { command.env(key, value); } @@ -1091,7 +1484,10 @@ mod tests { #[test] fn install_pages_are_for_built_ins_only() { - assert_eq!(install_page_url("codex").unwrap(), "https://github.com/openai/codex"); + assert_eq!( + install_page_url("codex").unwrap(), + "https://github.com/openai/codex" + ); assert!(install_page_url("goose").is_err()); for kind in AgentKind::ALL { assert!(kind.install_url().starts_with("https://")); diff --git a/plan2code-app/src-tauri/src/announce.rs b/plan2code-app/src-tauri/src/announce.rs index f50f40f..a6852cd 100644 --- a/plan2code-app/src-tauri/src/announce.rs +++ b/plan2code-app/src-tauri/src/announce.rs @@ -90,7 +90,9 @@ pub fn acceptable_url(url: &str) -> bool { let Some((port, path)) = rest.split_once('/') else { return false; }; - port.parse::().is_ok_and(|p| p > 0) && path.starts_with("s/") && !url.contains(char::is_whitespace) + port.parse::().is_ok_and(|p| p > 0) + && path.starts_with("s/") + && !url.contains(char::is_whitespace) } /// Check one request (its head as text, its body as bytes) against `token`. @@ -103,7 +105,9 @@ pub fn check_request(head: &str, body: &[u8], token: &str) -> Result given = Some(value.trim().to_string()), // A browser page sending this would be some site guessing at the port. @@ -186,7 +190,8 @@ impl AnnounceServer { /// Listen on a random loopback port. `on_page` runs on the server's own /// thread for every accepted notice. pub fn start(on_page: OnPage) -> Result { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).map_err(|e| e.to_string())?; + let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))) + .map_err(|e| e.to_string())?; let port = listener.local_addr().map_err(|e| e.to_string())?.port(); let token = random_token(); let expected = token.clone(); @@ -211,14 +216,21 @@ impl AnnounceServer { } Ok(Request::Session) => { let now = shared.lock().ok().and_then(|slot| slot.clone()); - (200, serde_json::to_string(&now).unwrap_or_else(|_| "null".to_string())) + ( + 200, + serde_json::to_string(&now).unwrap_or_else(|_| "null".to_string()), + ) } Err(Refused(status, _)) => (status, String::new()), }; respond(&mut stream, status, &body); } }); - Ok(AnnounceServer { port, token, current }) + Ok(AnnounceServer { + port, + token, + current, + }) } pub fn url(&self) -> String { @@ -250,7 +262,10 @@ impl AnnounceServer { vec![ ("PLAN2CODE_IN_APP".to_string(), "1".to_string()), ("PLAN2CODE_APP_VERSION".to_string(), app_version.to_string()), - ("PLAN2CODE_EMBED_ORIGIN".to_string(), embed_origin.to_string()), + ( + "PLAN2CODE_EMBED_ORIGIN".to_string(), + embed_origin.to_string(), + ), ("PLAN2CODE_APP_ANNOUNCE".to_string(), self.url()), ("PLAN2CODE_APP_TOKEN".to_string(), self.token.clone()), ] @@ -275,39 +290,76 @@ mod tests { #[test] fn accepts_a_good_notice() { let (head, body) = request("t", GOOD); - let Ok(Request::Page(notice)) = check_request(&head, &body, "t") else { panic!("not accepted") }; - assert_eq!((notice.sid.as_str(), notice.workflow.as_str()), ("s1", "plan")); + let Ok(Request::Page(notice)) = check_request(&head, &body, "t") else { + panic!("not accepted") + }; + assert_eq!( + (notice.sid.as_str(), notice.workflow.as_str()), + ("s1", "plan") + ); let get = "GET /session HTTP/1.1\r\nx-plan2code-token: t"; assert_eq!(check_request(get, b"", "t"), Ok(Request::Session)); - assert_eq!(check_request(get, b"", "other"), Err(Refused(403, "bad token"))); + assert_eq!( + check_request(get, b"", "other"), + Err(Refused(403, "bad token")) + ); } #[test] fn refuses_a_wrong_or_missing_token() { let (head, body) = request("nope", GOOD); - assert_eq!(check_request(&head, &body, "t"), Err(Refused(403, "bad token"))); + assert_eq!( + check_request(&head, &body, "t"), + Err(Refused(403, "bad token")) + ); let head = "POST /page HTTP/1.1\r\nHost: x"; - assert_eq!(check_request(head, GOOD.as_bytes(), "t"), Err(Refused(403, "bad token"))); + assert_eq!( + check_request(head, GOOD.as_bytes(), "t"), + Err(Refused(403, "bad token")) + ); } #[test] fn refuses_a_browser_origin_and_other_routes() { let (head, body) = request("t", GOOD); let with_origin = format!("{head}\r\nOrigin: http://evil.example"); - assert_eq!(check_request(&with_origin, &body, "t"), Err(Refused(403, "not from a page"))); + assert_eq!( + check_request(&with_origin, &body, "t"), + Err(Refused(403, "not from a page")) + ); let other = head.replace("/page", "/other"); - assert_eq!(check_request(&other, &body, "t"), Err(Refused(404, "not found"))); + assert_eq!( + check_request(&other, &body, "t"), + Err(Refused(404, "not found")) + ); let get = head.replace("POST", "GET"); - assert_eq!(check_request(&get, &body, "t"), Err(Refused(404, "not found")), "GET is for /session only"); + assert_eq!( + check_request(&get, &body, "t"), + Err(Refused(404, "not found")), + "GET is for /session only" + ); } #[test] fn refuses_a_bad_body_and_a_url_that_is_not_the_console() { let (head, _) = request("t", "x"); - assert_eq!(check_request(&head, b"not json", "t"), Err(Refused(400, "bad body"))); - for url in ["http://example.com/s/abc/", "https://127.0.0.1:5/s/a/", "http://127.0.0.1:5/other", "javascript:alert(1)", "http://127.0.0.1:0/s/a/"] { + assert_eq!( + check_request(&head, b"not json", "t"), + Err(Refused(400, "bad body")) + ); + for url in [ + "http://example.com/s/abc/", + "https://127.0.0.1:5/s/a/", + "http://127.0.0.1:5/other", + "javascript:alert(1)", + "http://127.0.0.1:0/s/a/", + ] { let body = format!(r#"{{"url":"{url}","sid":"s","workflow":"w"}}"#); - assert_eq!(check_request(&head, body.as_bytes(), "t"), Err(Refused(400, "bad page")), "{url}"); + assert_eq!( + check_request(&head, body.as_bytes(), "t"), + Err(Refused(400, "bad page")), + "{url}" + ); } } @@ -336,13 +388,27 @@ mod tests { let (tx_a, rx_a) = channel(); let (tx_b, rx_b) = channel(); let (tx_a, tx_b) = (Mutex::new(tx_a), Mutex::new(tx_b)); - let a = AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).is_ok())).unwrap(); - let b = AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).is_ok())).unwrap(); + let a = + AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).is_ok())).unwrap(); + let b = + AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).is_ok())).unwrap(); assert_ne!(a.url(), b.url()); - let port = |s: &AnnounceServer| s.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse::().unwrap(); + let port = |s: &AnnounceServer| { + s.url() + .rsplit_once(':') + .unwrap() + .1 + .trim_end_matches("/page") + .parse::() + .unwrap() + }; assert_eq!(post(port(&a), a.token(), GOOD), 204); - assert_eq!(post(port(&b), a.token(), GOOD), 403, "window A's token does nothing in window B"); + assert_eq!( + post(port(&b), a.token(), GOOD), + 403, + "window A's token does nothing in window B" + ); assert_eq!(rx_a.recv_timeout(Duration::from_secs(3)).unwrap().sid, "s1"); assert!(rx_b.recv_timeout(Duration::from_millis(300)).is_err()); } @@ -353,17 +419,31 @@ mod tests { let env = server.agent_env("http://127.0.0.1:1430", "3.0.0"); let get = |key: &str| env.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()); assert_eq!(get("PLAN2CODE_IN_APP").as_deref(), Some("1")); - assert_eq!(get("PLAN2CODE_EMBED_ORIGIN").as_deref(), Some("http://127.0.0.1:1430")); + assert_eq!( + get("PLAN2CODE_EMBED_ORIGIN").as_deref(), + Some("http://127.0.0.1:1430") + ); assert_eq!(get("PLAN2CODE_APP_VERSION").as_deref(), Some("3.0.0")); assert_eq!(get("PLAN2CODE_APP_ANNOUNCE"), Some(server.url())); assert_eq!(get("PLAN2CODE_APP_TOKEN").as_deref(), Some(server.token())); - assert_eq!(get("PLAN2CODE_CONSOLE_SID"), None, "the window's session is asked for, not fixed at start"); + assert_eq!( + get("PLAN2CODE_CONSOLE_SID"), + None, + "the window's session is asked for, not fixed at start" + ); } #[test] fn the_current_session_is_what_was_announced_last() { let server = AnnounceServer::start(Arc::new(|_| true)).unwrap(); - let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap(); + let port: u16 = server + .url() + .rsplit_once(':') + .unwrap() + .1 + .trim_end_matches("/page") + .parse() + .unwrap(); let ask = |token: &str| { let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); write!(stream, "GET /session HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\nConnection: close\r\n\r\n").unwrap(); @@ -371,13 +451,19 @@ mod tests { stream.read_to_string(&mut answer).unwrap(); answer }; - assert!(ask(server.token()).ends_with("null"), "nothing announced yet"); + assert!( + ask(server.token()).ends_with("null"), + "nothing announced yet" + ); assert_eq!(post(port, server.token(), GOOD), 204); assert!(ask(server.token()).contains(r#""sid":"s1""#)); assert!(ask("wrong").starts_with("HTTP/1.1 403")); assert_eq!(server.current().unwrap().workflow, "plan"); server.forget_current(); - assert!(ask(server.token()).ends_with("null"), "forgotten: the next open starts its own session"); + assert!( + ask(server.token()).ends_with("null"), + "forgotten: the next open starts its own session" + ); assert_eq!(server.current(), None); } @@ -386,8 +472,19 @@ mod tests { // A test's throwaway console: remembered, it would steer the next // agent `open` away from the window's real session. let server = AnnounceServer::start(Arc::new(|_| false)).unwrap(); - let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap(); - assert_eq!(post(port, server.token(), GOOD), 409, "open hears that the app did not take it"); + let port: u16 = server + .url() + .rsplit_once(':') + .unwrap() + .1 + .trim_end_matches("/page") + .parse() + .unwrap(); + assert_eq!( + post(port, server.token(), GOOD), + 409, + "open hears that the app did not take it" + ); assert_eq!(server.current(), None); } } diff --git a/plan2code-app/src-tauri/src/attention.rs b/plan2code-app/src-tauri/src/attention.rs index 121c01a..8a757aa 100644 --- a/plan2code-app/src-tauri/src/attention.rs +++ b/plan2code-app/src-tauri/src/attention.rs @@ -121,7 +121,12 @@ fn parse_hex(hex: &str) -> [u8; 3] { mod tests { use super::*; - const SIGNALS: [Signal; 4] = [Signal::Busy, Signal::Ready, Signal::Attention, Signal::Plain]; + const SIGNALS: [Signal; 4] = [ + Signal::Busy, + Signal::Ready, + Signal::Attention, + Signal::Plain, + ]; fn pixel(buf: &[u8], size: u32, x: u32, y: u32) -> [u8; 4] { let i = ((y * size + x) * 4) as usize; @@ -149,8 +154,16 @@ mod tests { (Signal::Plain, "freebsd", Badge::None), ]; for (signal, os, want) in table { - assert_eq!(badge_for(signal, os, true), want, "{signal:?} on {os}, enabled"); - assert_eq!(badge_for(signal, os, false), Badge::None, "{signal:?} on {os}, disabled"); + assert_eq!( + badge_for(signal, os, true), + want, + "{signal:?} on {os}, enabled" + ); + assert_eq!( + badge_for(signal, os, false), + Badge::None, + "{signal:?} on {os}, disabled" + ); } } @@ -177,22 +190,41 @@ mod tests { #[test] fn no_flash_for_a_repeat_of_the_same_signal() { - assert!(!should_flash(Some(Signal::Ready), Signal::Ready, false, true)); - assert!(!should_flash(Some(Signal::Attention), Signal::Attention, false, true)); + assert!(!should_flash( + Some(Signal::Ready), + Signal::Ready, + false, + true + )); + assert!(!should_flash( + Some(Signal::Attention), + Signal::Attention, + false, + true + )); } #[test] fn no_flash_for_busy_or_plain() { for prev in [None, Some(Signal::Ready), Some(Signal::Attention)] { - assert!(!should_flash(prev, Signal::Busy, false, true), "busy from {prev:?}"); - assert!(!should_flash(prev, Signal::Plain, false, true), "plain from {prev:?}"); + assert!( + !should_flash(prev, Signal::Busy, false, true), + "busy from {prev:?}" + ); + assert!( + !should_flash(prev, Signal::Plain, false, true), + "plain from {prev:?}" + ); } } #[test] fn no_flash_when_flashing_is_turned_off() { for signal in SIGNALS.iter().copied() { - assert!(!should_flash(Some(Signal::Busy), signal, false, false), "{signal:?} while disabled"); + assert!( + !should_flash(Some(Signal::Busy), signal, false, false), + "{signal:?} while disabled" + ); } } @@ -210,7 +242,11 @@ mod tests { assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent"); let center = pixel(&buf, size, 8, 8); assert_eq!(center[3], 255, "the middle is opaque"); - assert_eq!(¢er[..3], &parse_hex(GREEN_HEX)[..], "the middle is the green fill"); + assert_eq!( + ¢er[..3], + &parse_hex(GREEN_HEX)[..], + "the middle is the green fill" + ); } #[test] @@ -221,14 +257,27 @@ mod tests { assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent"); let center = pixel(&buf, size, 8, 8); assert_eq!(center[3], 255, "the middle is opaque"); - assert_eq!(¢er[..3], &parse_hex(RED_HEX)[..], "the middle is the red fill"); + assert_eq!( + ¢er[..3], + &parse_hex(RED_HEX)[..], + "the middle is the red fill" + ); } #[test] fn the_fill_colors_match_the_web_console_favicon() { - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../src/web-console/public/favicon.js"); + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../src/web-console/public/favicon.js" + ); let text = std::fs::read_to_string(path).unwrap(); - assert!(text.contains(&format!("ready: \"{GREEN_HEX}\"")), "ready color in favicon.js"); - assert!(text.contains(&format!("attention: \"{RED_HEX}\"")), "attention color in favicon.js"); + assert!( + text.contains(&format!("ready: \"{GREEN_HEX}\"")), + "ready color in favicon.js" + ); + assert!( + text.contains(&format!("attention: \"{RED_HEX}\"")), + "attention color in favicon.js" + ); } } diff --git a/plan2code-app/src-tauri/src/brief.rs b/plan2code-app/src-tauri/src/brief.rs index b47fc4c..f1bdd6f 100644 --- a/plan2code-app/src-tauri/src/brief.rs +++ b/plan2code-app/src-tauri/src/brief.rs @@ -66,7 +66,12 @@ const GIT_TIMEOUT: Duration = Duration::from_secs(2); fn git(folder: &Path, args: &[&str]) -> Option { let mut command = Command::new("git"); - command.arg("-C").arg(folder).args(args).stdout(Stdio::piped()).stderr(Stdio::null()); + command + .arg("-C") + .arg(folder) + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); #[cfg(windows)] { use std::os::windows::process::CommandExt; @@ -92,14 +97,21 @@ fn git(folder: &Path, args: &[&str]) -> Option { thread::sleep(Duration::from_millis(20)); }; let bytes = reader.join().ok()?; - status.success().then(|| String::from_utf8_lossy(&bytes).trim_end().to_string()) + status + .success() + .then(|| String::from_utf8_lossy(&bytes).trim_end().to_string()) } /// The brief as Markdown. `state` is a session's `state.json`; `spec_dir` is /// the spec folder on disk, when the session has one; `git` is the repository /// summary, when the folder is one; `events` is the session's `events.ndjson`, /// oldest first. -pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSummary>, events: &[Value]) -> String { +pub fn build_brief( + state: &Value, + spec_dir: Option<&Path>, + git: Option<&GitSummary>, + events: &[Value], +) -> String { let workflow = str_field(state, "workflow").unwrap_or(""); let skill = skill_for_workflow(workflow); let spec = str_field(state, "specDir"); @@ -119,9 +131,19 @@ pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSumma out.push_str("## Progress\n\n"); let headline = state.get("headline"); let stage = headline.and_then(|h| str_field(h, "stage")).unwrap_or(""); - let cleared = headline.and_then(|h| h.get("cleared")).and_then(Value::as_u64).unwrap_or(0); - let total = headline.and_then(|h| h.get("total")).and_then(Value::as_u64).unwrap_or(0); - let activity = state.get("agent").and_then(|a| str_field(a, "activity")).map(str::trim).filter(|a| !a.is_empty()); + let cleared = headline + .and_then(|h| h.get("cleared")) + .and_then(Value::as_u64) + .unwrap_or(0); + let total = headline + .and_then(|h| h.get("total")) + .and_then(Value::as_u64) + .unwrap_or(0); + let activity = state + .get("agent") + .and_then(|a| str_field(a, "activity")) + .map(str::trim) + .filter(|a| !a.is_empty()); if !stage.is_empty() { out.push_str(&format!("{stage}: {cleared} of {total} done.\n")); if let Some(activity) = activity { @@ -134,10 +156,17 @@ pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSumma out.push_str("No progress posted yet.\n\n"); } - let items = state.get("items").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]); + let items = state + .get("items") + .and_then(Value::as_array) + .map(Vec::as_slice) + .unwrap_or(&[]); out.push_str("### Open questions\n\n"); - let open: Vec<&Value> = items.iter().filter(|i| matches!(str_field(i, "status"), Some("open" | "reopened"))).collect(); + let open: Vec<&Value> = items + .iter() + .filter(|i| matches!(str_field(i, "status"), Some("open" | "reopened"))) + .collect(); if open.is_empty() { out.push_str("None.\n\n"); } else { @@ -148,14 +177,21 @@ pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSumma } out.push_str("## Recent answers and decisions\n\n"); - let answered: Vec<&Value> = items.iter().filter(|i| str_field(i, "status") == Some("answered")).collect(); + let answered: Vec<&Value> = items + .iter() + .filter(|i| str_field(i, "status") == Some("answered")) + .collect(); let recent = &answered[answered.len().saturating_sub(RECENT_ANSWERS)..]; if recent.is_empty() { out.push_str("None yet.\n\n"); } else { for item in recent { let answer = answer_text(item); - let answer = if answer.is_empty() { "answered".to_string() } else { answer }; + let answer = if answer.is_empty() { + "answered".to_string() + } else { + answer + }; out.push_str(&format!("- {}: {answer}\n", title_of(item))); } out.push('\n'); @@ -164,7 +200,11 @@ pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSumma if let Some(git) = git { out.push_str("## Git\n\n"); out.push_str("Changes:\n\n```\n"); - out.push_str(if git.status.is_empty() { "clean" } else { &git.status }); + out.push_str(if git.status.is_empty() { + "clean" + } else { + &git.status + }); out.push_str("\n```\n\n"); if !git.log.is_empty() { out.push_str("Last commits:\n\n```\n"); @@ -202,7 +242,11 @@ fn render_event(event: &Value) -> String { None => "consume".to_string(), }, "open" => { - if event.get("resumed").and_then(Value::as_bool).unwrap_or(false) { + if event + .get("resumed") + .and_then(Value::as_bool) + .unwrap_or(false) + { "open (resumed)".to_string() } else { "open".to_string() @@ -230,7 +274,10 @@ fn open_task(spec_dir: &Path) -> Option { let overview = fs::read_to_string(spec_dir.join("overview.md")).ok()?; let phase = active_phase(&overview)?; let text = fs::read_to_string(spec_dir.join(format!("phase-{phase}.md"))).ok()?; - let line = text.lines().map(str::trim_start).find(|l| l.starts_with("- [ ]"))?; + let line = text + .lines() + .map(str::trim_start) + .find(|l| l.starts_with("- [ ]"))?; Some(line.trim_start_matches("- [ ]").trim().replace("**", "")) } @@ -242,8 +289,16 @@ fn active_phase(overview: &str) -> Option { let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); digits.parse::().ok() }; - let rows = || overview.lines().map(str::trim_start).filter(|l| l.starts_with("- [")); - rows().find(|l| l.starts_with("- [/]")).and_then(phase_of).or_else(|| rows().find(|l| l.starts_with("- [ ]")).and_then(phase_of)) + let rows = || { + overview + .lines() + .map(str::trim_start) + .filter(|l| l.starts_with("- [")) + }; + rows() + .find(|l| l.starts_with("- [/]")) + .and_then(phase_of) + .or_else(|| rows().find(|l| l.starts_with("- [ ]")).and_then(phase_of)) } fn cut(text: &str) -> String { @@ -259,14 +314,18 @@ fn str_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> { } fn title_of(item: &Value) -> String { - let title = str_field(item, "title").or_else(|| str_field(item, "id")).unwrap_or("(untitled)"); + let title = str_field(item, "title") + .or_else(|| str_field(item, "id")) + .unwrap_or("(untitled)"); title.trim().to_string() } /// An answer as the person gave it: the option's label for a pick, plus any /// words they typed. Empty when the answer carries nothing to show. fn answer_text(item: &Value) -> String { - let Some(answer) = item.get("answer") else { return String::new() }; + let Some(answer) = item.get("answer") else { + return String::new(); + }; let options = item.get("options").and_then(Value::as_array); let label = |k: &str| { options @@ -291,7 +350,10 @@ fn answer_text(item: &Value) -> String { if let Some(verdict) = str_field(answer, "verdict") { parts.push(verdict.to_string()); } - if let Some(text) = str_field(answer, "text").map(str::trim).filter(|t| !t.is_empty()) { + if let Some(text) = str_field(answer, "text") + .map(str::trim) + .filter(|t| !t.is_empty()) + { parts.push(text.to_string()); } parts.join("; ") @@ -303,7 +365,8 @@ mod tests { use serde_json::json; fn fixture(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("plan2code-brief-{}-{name}", std::process::id())); + let dir = + std::env::temp_dir().join(format!("plan2code-brief-{}-{name}", std::process::id())); let _ = fs::remove_dir_all(&dir); fs::create_dir_all(&dir).unwrap(); dir @@ -340,7 +403,10 @@ mod tests { #[test] fn a_mid_implement_session_carries_every_section() { let spec = mid_implement_spec(); - let git = GitSummary { status: " M src/lib.rs".to_string(), log: "abc1234 Add the reader".to_string() }; + let git = GitSummary { + status: " M src/lib.rs".to_string(), + log: "abc1234 Add the reader".to_string(), + }; let brief = build_brief(&mid_implement_state(), Some(&spec), Some(&git), &[]); assert!(brief.contains("Skill: plan2code-3-implement (workflow `implement`)")); assert!(brief.contains("Spec: specs/feature")); @@ -379,7 +445,9 @@ mod tests { #[test] fn a_session_with_no_spec_and_no_skill_opens_the_dashboard() { let state = json!({ "schema": 1, "workflow": "dashboard" }); - assert!(build_brief(&state, None, None, &[]).ends_with("## Next task\n\nOpen the dashboard\n")); + assert!( + build_brief(&state, None, None, &[]).ends_with("## Next task\n\nOpen the dashboard\n") + ); } #[test] @@ -387,8 +455,16 @@ mod tests { let home = fixture("chat"); let dir = home.join("sessions").join("s1"); fs::create_dir_all(&dir).unwrap(); - fs::write(dir.join("state.json"), r#"{"schema": 1, "workflow": "implement"}"#).unwrap(); - fs::write(dir.join("chat.ndjson"), "{\"kind\":\"ask\",\"text\":\"CHAT-ONLY-WORDS\"}\n").unwrap(); + fs::write( + dir.join("state.json"), + r#"{"schema": 1, "workflow": "implement"}"#, + ) + .unwrap(); + fs::write( + dir.join("chat.ndjson"), + "{\"kind\":\"ask\",\"text\":\"CHAT-ONLY-WORDS\"}\n", + ) + .unwrap(); let session = crate::session_reader::load(&home, "s1").unwrap(); let brief = build_brief(&session.state, None, None, &[]); assert!(!brief.contains("CHAT-ONLY-WORDS")); @@ -408,7 +484,9 @@ mod tests { "agent": { "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" }, }); let brief = build_brief(&state, None, None, &[]); - assert!(brief.contains("Phase 2: Restart: 1 of 3 done.\nDoing: Spiking Claude's context signal (Task 10.1)\n")); + assert!(brief.contains( + "Phase 2: Restart: 1 of 3 done.\nDoing: Spiking Claude's context signal (Task 10.1)\n" + )); } #[test] @@ -442,7 +520,9 @@ mod tests { #[test] fn only_the_last_five_events_are_named() { let state = json!({ "schema": 1, "workflow": "implement" }); - let events: Vec = (0..8).map(|n| json!({ "type": "upload", "id": format!("f{n}") })).collect(); + let events: Vec = (0..8) + .map(|n| json!({ "type": "upload", "id": format!("f{n}") })) + .collect(); let brief = build_brief(&state, None, None, &events); assert_eq!(brief.matches("- upload\n").count(), RECENT_EVENTS); } @@ -455,7 +535,10 @@ mod tests { #[test] fn a_skill_name_maps_to_its_workflow() { - assert_eq!(skill_for_workflow("quick-task"), Some("plan2code-quick-task")); + assert_eq!( + skill_for_workflow("quick-task"), + Some("plan2code-quick-task") + ); assert_eq!(skill_for_workflow("unknown"), None); } } diff --git a/plan2code-app/src-tauri/src/console_supervisor.rs b/plan2code-app/src-tauri/src/console_supervisor.rs index ada8978..5e40c99 100644 --- a/plan2code-app/src-tauri/src/console_supervisor.rs +++ b/plan2code-app/src-tauri/src/console_supervisor.rs @@ -156,7 +156,9 @@ fn parse_open_output(stdout: &[u8]) -> Result { /// Split `http://:` into its parts; the console only ever /// listens on loopback http. fn split_url(url: &str) -> Result<(String, u16, String), String> { - let rest = url.strip_prefix("http://").ok_or_else(|| format!("not an http url: {url}"))?; + let rest = url + .strip_prefix("http://") + .ok_or_else(|| format!("not an http url: {url}"))?; let (authority, path) = match rest.split_once('/') { Some((a, p)) => (a, format!("/{p}")), None => (rest, "/".to_string()), @@ -164,7 +166,9 @@ fn split_url(url: &str) -> Result<(String, u16, String), String> { let (host, port) = authority .rsplit_once(':') .ok_or_else(|| format!("no port in url: {url}"))?; - let port: u16 = port.parse().map_err(|_| format!("bad port in url: {url}"))?; + let port: u16 = port + .parse() + .map_err(|_| format!("bad port in url: {url}"))?; Ok((host.to_string(), port, path)) } @@ -175,7 +179,13 @@ impl ConsoleSupervisor { pub fn start(project_dir: PathBuf, embed_origin: String) -> Result { let console_dir = find_console_dir()?; let session = Self::open_session(&console_dir, &project_dir, &embed_origin, None)?; - Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, session, stopped: false }) + Ok(ConsoleSupervisor { + console_dir, + project_dir, + embed_origin, + session, + stopped: false, + }) } /// `open` for the dashboard, or, with `resume`, the same session again on @@ -190,8 +200,20 @@ impl ConsoleSupervisor { ) -> Result { let console_dir = find_console_dir()?; let (_, port, _) = split_url(url)?; - let session = ConsoleSession { sid: sid.to_string(), url: url.to_string(), pid: 0, port, embed: true }; - Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, session, stopped: false }) + let session = ConsoleSession { + sid: sid.to_string(), + url: url.to_string(), + pid: 0, + port, + embed: true, + }; + Ok(ConsoleSupervisor { + console_dir, + project_dir, + embed_origin, + session, + stopped: false, + }) } fn open_session( @@ -264,7 +286,10 @@ impl ConsoleSupervisor { let Ok((host, port, path)) = split_url(&self.session.url) else { return false; }; - let Some(addr) = (host.as_str(), port).to_socket_addrs().ok().and_then(|mut a| a.next()) + let Some(addr) = (host.as_str(), port) + .to_socket_addrs() + .ok() + .and_then(|mut a| a.next()) else { return false; }; @@ -293,7 +318,8 @@ impl ConsoleSupervisor { } let sid = self.session.sid.clone(); let on_disk = session_on_disk(&sid); - let (console_dir, project_dir, embed_origin) = (&self.console_dir, &self.project_dir, &self.embed_origin); + let (console_dir, project_dir, embed_origin) = + (&self.console_dir, &self.project_dir, &self.embed_origin); self.session = resume_or_fresh(&sid, on_disk, |resume| { Self::open_session(console_dir, project_dir, embed_origin, resume) })?; @@ -329,7 +355,8 @@ pub fn session_on_disk(sid: &str) -> bool { if Path::new(sid).file_name() != Some(std::ffi::OsStr::new(sid)) { return false; } - session_reader::console_home().map_or(true, |home| session_reader::session_dir(&home, sid).is_dir()) + session_reader::console_home() + .is_none_or(|home| session_reader::session_dir(&home, sid).is_dir()) } /// The same session, so the page and a skill's place in it survive, tried @@ -362,7 +389,10 @@ mod tests { #[test] fn splits_the_session_url() { let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap(); - assert_eq!((host.as_str(), port, path.as_str()), ("127.0.0.1", 51617, "/s/abc/")); + assert_eq!( + (host.as_str(), port, path.as_str()), + ("127.0.0.1", 51617, "/s/abc/") + ); let (_, _, path) = split_url("http://localhost:9").unwrap(); assert_eq!(path, "/"); assert!(split_url("https://127.0.0.1:1/x").is_err()); @@ -371,10 +401,22 @@ mod tests { #[test] fn origin_comes_from_the_pages_own_url() { - assert_eq!(origin_of("http://127.0.0.1:1430/index.html").as_deref(), Some("http://127.0.0.1:1430")); - assert_eq!(origin_of("http://tauri.localhost/").as_deref(), Some("http://tauri.localhost")); - assert_eq!(origin_of("https://tauri.localhost").as_deref(), Some("https://tauri.localhost")); - assert_eq!(origin_of("tauri://localhost/index.html?x=1").as_deref(), Some("tauri://localhost")); + assert_eq!( + origin_of("http://127.0.0.1:1430/index.html").as_deref(), + Some("http://127.0.0.1:1430") + ); + assert_eq!( + origin_of("http://tauri.localhost/").as_deref(), + Some("http://tauri.localhost") + ); + assert_eq!( + origin_of("https://tauri.localhost").as_deref(), + Some("https://tauri.localhost") + ); + assert_eq!( + origin_of("tauri://localhost/index.html?x=1").as_deref(), + Some("tauri://localhost") + ); assert_eq!(origin_of("file:///x"), None); assert_eq!(origin_of("not a url"), None); assert_eq!(origin_of("http:///x"), None); @@ -385,18 +427,38 @@ mod tests { // Only needs a console to be installed; skipped where there is none. let Ok(dir) = find_console_dir() else { return }; let _ = dir; - let mut sup = ConsoleSupervisor::adopt(PathBuf::from("."), "http://tauri.localhost".into(), "http://127.0.0.1:5555/s/t/", "sid-9").unwrap(); - assert_eq!((sup.session().port, sup.session().sid.as_str()), (5555, "sid-9")); + let mut sup = ConsoleSupervisor::adopt( + PathBuf::from("."), + "http://tauri.localhost".into(), + "http://127.0.0.1:5555/s/t/", + "sid-9", + ) + .unwrap(); + assert_eq!( + (sup.session().port, sup.session().sid.as_str()), + (5555, "sid-9") + ); assert!(sup.session().embed); - assert!(ConsoleSupervisor::adopt(PathBuf::from("."), String::new(), "https://x/", "s").is_err()); + assert!( + ConsoleSupervisor::adopt(PathBuf::from("."), String::new(), "https://x/", "s").is_err() + ); sup.follow("http://127.0.0.1:6000/s/u/", "sid-10"); - assert_eq!((sup.session().port, sup.session().sid.as_str()), (6000, "sid-10")); + assert_eq!( + (sup.session().port, sup.session().sid.as_str()), + (6000, "sid-10") + ); // Never started a server here: nothing for Drop to stop. sup.stopped = true; } fn opened(sid: &str) -> ConsoleSession { - ConsoleSession { sid: sid.to_string(), url: "http://127.0.0.1:5/s/t/".into(), pid: 1, port: 5, embed: true } + ConsoleSession { + sid: sid.to_string(), + url: "http://127.0.0.1:5/s/t/".into(), + pid: 1, + port: 5, + embed: true, + } } #[test] @@ -417,7 +479,10 @@ mod tests { Err("busy".to_string()) }); assert!(result.is_err(), "the failure is reported, not papered over"); - assert!(calls.iter().all(|c| c.as_deref() == Some("s1")), "only ever resumed: {calls:?}"); + assert!( + calls.iter().all(|c| c.as_deref() == Some("s1")), + "only ever resumed: {calls:?}" + ); assert_eq!(calls.len(), 2, "the resume is tried twice"); } @@ -427,7 +492,11 @@ mod tests { let session = resume_or_fresh("s1", true, |resume| { tries += 1; assert_eq!(resume, Some("s1")); - if tries == 1 { Err("busy".to_string()) } else { Ok(opened("s1")) } + if tries == 1 { + Err("busy".to_string()) + } else { + Ok(opened("s1")) + } }) .unwrap(); assert_eq!(session.sid, "s1"); @@ -447,13 +516,20 @@ mod tests { #[test] fn parses_open_output() { - let json = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1} + let json = + br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1} "#; let session = parse_open_output(json).unwrap(); - assert_eq!((session.sid.as_str(), session.port, session.pid), ("s1", 5, 42)); + assert_eq!( + (session.sid.as_str(), session.port, session.pid), + ("s1", 5, 42) + ); assert!(session.embed); let old = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42}"#; - assert!(!parse_open_output(old).unwrap().embed, "a console that does not say it embeds is too old"); + assert!( + !parse_open_output(old).unwrap().embed, + "a console that does not say it embeds is too old" + ); assert!(parse_open_output(b"not json\n").is_err()); assert!(parse_open_output(br#"{"ok":true,"sid":"s1"}"#).is_err()); } diff --git a/plan2code-app/src-tauri/src/handoff.rs b/plan2code-app/src-tauri/src/handoff.rs index 240809c..a4ecd33 100644 --- a/plan2code-app/src-tauri/src/handoff.rs +++ b/plan2code-app/src-tauri/src/handoff.rs @@ -34,7 +34,12 @@ pub struct Record<'a> { /// id made from `when`'s local minute. Returns the id. The record is claimed /// exclusively, so two writes in the same minute never share an id; a failed /// write leaves nothing behind. -pub fn write(dir: &Path, when: DateTime, record: &Record, body: &str) -> Result { +pub fn write( + dir: &Path, + when: DateTime, + record: &Record, + body: &str, +) -> Result { validate(record)?; fs::create_dir_all(dir).map_err(|e| e.to_string())?; let base = format!( @@ -45,15 +50,25 @@ pub fn write(dir: &Path, when: DateTime, record: &Record, body: &str) -> when.hour(), when.minute() ); - let written = when.with_timezone(&Utc).to_rfc3339_opts(SecondsFormat::Millis, true); + let written = when + .with_timezone(&Utc) + .to_rfc3339_opts(SecondsFormat::Millis, true); for n in 1.. { - let id = if n == 1 { base.clone() } else { format!("{base}-{n}") }; + let id = if n == 1 { + base.clone() + } else { + format!("{base}-{n}") + }; let md = dir.join(format!("{id}.md")); let json_file = dir.join(format!("{id}.json")); if md.exists() { continue; } - let mut claim = match OpenOptions::new().write(true).create_new(true).open(&json_file) { + let mut claim = match OpenOptions::new() + .write(true) + .create_new(true) + .open(&json_file) + { Ok(file) => file, Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(e.to_string()), @@ -86,8 +101,13 @@ pub fn write(dir: &Path, when: DateTime, record: &Record, body: &str) -> } fn write_document(md: &Path, heading: &str, body: &str) -> Result<(), String> { - let mut file = OpenOptions::new().write(true).create_new(true).open(md).map_err(|e| e.to_string())?; - file.write_all(format!("{heading}\n\n{body}").as_bytes()).map_err(|e| e.to_string()) + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(md) + .map_err(|e| e.to_string())?; + file.write_all(format!("{heading}\n\n{body}").as_bytes()) + .map_err(|e| e.to_string()) } fn title_line(title: &str) -> String { @@ -98,8 +118,12 @@ fn title_line(title: &str) -> String { /// both files. A picked-up one, or one already gone, is left alone. pub fn retire_if_unused(dir: &Path, id: &str) -> Result<(), String> { let json_file = dir.join(format!("{id}.json")); - let Ok(text) = fs::read_to_string(&json_file) else { return Ok(()) }; - let used = serde_json::from_str::(&text).ok().is_some_and(|meta| !meta["usedAt"].is_null()); + let Ok(text) = fs::read_to_string(&json_file) else { + return Ok(()); + }; + let used = serde_json::from_str::(&text) + .ok() + .is_some_and(|meta| !meta["usedAt"].is_null()); if used { return Ok(()); } @@ -116,17 +140,30 @@ pub fn retire_if_unused(dir: &Path, id: &str) -> Result<(), String> { /// The same rules the console applies to the record, so a bad field is refused /// here rather than written and then ignored. fn validate(record: &Record) -> Result<(), String> { - let lower_dashes = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c == '-'); + let lower_dashes = + |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c == '-'); if !lower_dashes(record.workflow) { - return Err(format!("workflow must be lowercase letters and dashes, got {:?}", record.workflow)); + return Err(format!( + "workflow must be lowercase letters and dashes, got {:?}", + record.workflow + )); } - let skill_ok = !record.skill.is_empty() && record.skill.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + let skill_ok = !record.skill.is_empty() + && record + .skill + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); if !skill_ok { - return Err(format!("skill must be a skill name, got {:?}", record.skill)); + return Err(format!( + "skill must be a skill name, got {:?}", + record.skill + )); } if let Some(spec) = record.spec { let name = spec.strip_prefix("specs/"); - if name.is_none_or(|n| n.is_empty() || n == "." || n == ".." || n.contains('/') || n.contains('\\')) { + if name.is_none_or(|n| { + n.is_empty() || n == "." || n == ".." || n.contains('/') || n.contains('\\') + }) { return Err(format!("spec must be specs/, got {spec:?}")); } } @@ -144,7 +181,8 @@ mod tests { use chrono::TimeZone; fn fixture(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("plan2code-handoff-{}-{name}", std::process::id())); + let dir = + std::env::temp_dir().join(format!("plan2code-handoff-{}-{name}", std::process::id())); let _ = fs::remove_dir_all(&dir); dir } @@ -161,7 +199,9 @@ mod tests { } fn at(hour: u32, minute: u32) -> DateTime { - Local.with_ymd_and_hms(2026, 10, 21, hour, minute, 0).unwrap() + Local + .with_ymd_and_hms(2026, 10, 21, hour, minute, 0) + .unwrap() } #[test] @@ -169,7 +209,9 @@ mod tests { let dir = fixture("shape"); let id = write(&dir, at(13, 52), &record(), "## Next task\n\nTask 5.2").unwrap(); assert_eq!(id, "2026-10-21-1352-handoff"); - let meta: serde_json::Value = serde_json::from_str(&fs::read_to_string(dir.join(format!("{id}.json"))).unwrap()).unwrap(); + let meta: serde_json::Value = + serde_json::from_str(&fs::read_to_string(dir.join(format!("{id}.json"))).unwrap()) + .unwrap(); assert_eq!(meta["v"], 1); assert_eq!(meta["id"], id.as_str()); assert_eq!(meta["workflow"], "implement"); @@ -206,7 +248,11 @@ mod tests { let dir = fixture("retire"); let unused = write(&dir, at(10, 0), &record(), "one").unwrap(); let used = write(&dir, at(10, 1), &record(), "two").unwrap(); - fs::write(dir.join(format!("{used}.json")), r#"{"v":1,"usedAt":"2026-10-21T10:02:00.000Z"}"#).unwrap(); + fs::write( + dir.join(format!("{used}.json")), + r#"{"v":1,"usedAt":"2026-10-21T10:02:00.000Z"}"#, + ) + .unwrap(); retire_if_unused(&dir, &unused).unwrap(); retire_if_unused(&dir, &used).unwrap(); assert!(!dir.join(format!("{unused}.json")).exists()); diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index 1baeb6c..97b5485 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -3,11 +3,13 @@ use std::sync::{Arc, Mutex, OnceLock}; -use plan2code_app_lib::announce::{AnnounceServer, PageNotice}; use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink}; use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode}; +use plan2code_app_lib::announce::{AnnounceServer, PageNotice}; use plan2code_app_lib::attention::{self, Badge, Signal}; -use plan2code_app_lib::console_supervisor::{app_origin, origin_of, session_on_disk, ConsoleSupervisor}; +use plan2code_app_lib::console_supervisor::{ + app_origin, origin_of, session_on_disk, ConsoleSupervisor, +}; use plan2code_app_lib::node_check; use plan2code_app_lib::project::{self, ProjectDir}; use plan2code_app_lib::restart_brief; @@ -54,7 +56,10 @@ struct AttentionState { impl Default for AttentionState { fn default() -> Self { - AttentionState { last: None, enabled: true } + AttentionState { + last: None, + enabled: true, + } } } @@ -135,23 +140,35 @@ fn open_install_page(id: String) -> Result<(), String> { c.arg(url); c } else { - let browser = std::env::var("BROWSER").ok().filter(|b| !b.is_empty()).unwrap_or_else(|| "xdg-open".to_string()); + let browser = std::env::var("BROWSER") + .ok() + .filter(|b| !b.is_empty()) + .unwrap_or_else(|| "xdg-open".to_string()); let mut c = std::process::Command::new(browser); c.arg(url); c }; - command.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); + command + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); #[cfg(windows)] { use std::os::windows::process::CommandExt; command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW } - command.spawn().map(|_| ()).map_err(|e| format!("could not open {url}: {e}")) + command + .spawn() + .map(|_| ()) + .map_err(|e| format!("could not open {url}: {e}")) } // `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`. fn windows_build() -> Option { - let out = std::process::Command::new("cmd").args(["/c", "ver"]).output().ok()?; + let out = std::process::Command::new("cmd") + .args(["/c", "ver"]) + .output() + .ok()?; let text = String::from_utf8_lossy(&out.stdout); let version = text.split("Version ").nth(1)?; version.split('.').nth(2)?.trim().parse().ok() @@ -168,7 +185,9 @@ fn page_sink(page: PageChannel, app: Arc>) -> Sink { } } let Ok(guard) = page.lock() else { return }; - let Some(channel) = guard.as_ref() else { return }; + let Some(channel) = guard.as_ref() else { + return; + }; let body = match event { AgentEvent::Output(bytes) => InvokeResponseBody::Raw(bytes), AgentEvent::State(snapshot) => match serde_json::to_string(&snapshot) { @@ -185,7 +204,10 @@ fn page_sink(page: PageChannel, app: Arc>) -> Sink { fn agent_for_project(state: &AppState) -> Result, String> { let dir = { let project = state.project.lock().map_err(|e| e.to_string())?; - project.as_ref().map(|p| p.dir.clone()).ok_or("no project folder chosen")? + project + .as_ref() + .map(|p| p.dir.clone()) + .ok_or("no project folder chosen")? }; let mut guard = state.agent.lock().map_err(|e| e.to_string())?; if let Some(agent) = guard.as_ref() { @@ -213,7 +235,10 @@ fn before_fresh_hook(state: &AppState) -> BeforeFresh { let console = Arc::clone(&state.console); let announce = Arc::clone(&state.announce); Arc::new(move || { - let sid = console.lock().ok().and_then(|guard| guard.as_ref().map(|sup| sup.session().sid.clone())); + let sid = console + .lock() + .ok() + .and_then(|guard| guard.as_ref().map(|sup| sup.session().sid.clone())); 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() { @@ -238,7 +263,12 @@ fn current_agent(state: &AppState) -> Option> { /// once announced a test's throwaway console, the window followed it, and /// when the test shut it down the reconnect opened an empty dashboard, so the /// build's own page was never seen again. -fn take_announced(state: &AppState, notice: &PageNotice, origin: String, on_disk: impl Fn(&str) -> bool) -> bool { +fn take_announced( + state: &AppState, + notice: &PageNotice, + origin: String, + on_disk: impl Fn(&str) -> bool, +) -> bool { if !on_disk(¬ice.sid) { return false; } @@ -246,9 +276,14 @@ fn take_announced(state: &AppState, notice: &PageNotice, origin: String, on_disk match guard.as_mut() { Some(sup) => sup.follow(¬ice.url, ¬ice.sid), None => { - let dir = state.project.lock().ok().and_then(|p| p.as_ref().map(|p| p.dir.clone())); + let dir = state + .project + .lock() + .ok() + .and_then(|p| p.as_ref().map(|p| p.dir.clone())); if let Some(dir) = dir { - if let Ok(sup) = ConsoleSupervisor::adopt(dir, origin, ¬ice.url, ¬ice.sid) { + if let Ok(sup) = ConsoleSupervisor::adopt(dir, origin, ¬ice.url, ¬ice.sid) + { *guard = Some(sup); } } @@ -271,11 +306,15 @@ fn window_origin(app: &tauri::AppHandle) -> String { // agent gets nothing and opens pages the plain way. fn sync_agent_env(app: &tauri::AppHandle) { let state = app.state::(); - let Some(agent) = current_agent(&state) else { return }; + let Some(agent) = current_agent(&state) else { + return; + }; let env = match state.announce.lock().ok() { Some(guard) => guard .as_ref() - .map(|server| server.agent_env(&window_origin(app), &app.package_info().version.to_string())) + .map(|server| { + server.agent_env(&window_origin(app), &app.package_info().version.to_string()) + }) .unwrap_or_default(), None => Vec::new(), }; @@ -290,6 +329,7 @@ fn sync_agent_env(app: &tauri::AppHandle) { // reattach registration) sends the frontend an "end" message that // unregisters that id for good, breaking all future sends through it. #[tauri::command] +#[allow(clippy::too_many_arguments)] // one argument per key the frontend passes to invoke fn agent_start( app: tauri::AppHandle, state: State<'_, AppState>, @@ -301,7 +341,8 @@ fn agent_start( rows: u16, ) -> Result<(), String> { let kind = agents::find_agent(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?; - let mode = PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?; + let mode = + PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?; let agent = agent_for_project(&state)?; agent.resize(cols, rows)?; sync_agent_env(&app); @@ -331,7 +372,9 @@ fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(), #[tauri::command] fn agent_restart(state: State<'_, AppState>) -> Result<(), String> { - current_agent(&state).ok_or("no agent has been started")?.restart() + current_agent(&state) + .ok_or("no agent has been started")? + .restart() } fn idle_snapshot_json() -> serde_json::Value { @@ -344,7 +387,10 @@ fn idle_snapshot_json() -> serde_json::Value { /// current generation's recent output on it at once, so the terminal does /// not come up blank. #[tauri::command] -fn agent_reattach(state: State<'_, AppState>, on_output: Channel) -> Result { +fn agent_reattach( + state: State<'_, AppState>, + on_output: Channel, +) -> Result { let agent = current_agent(&state); *state.page.lock().map_err(|e| e.to_string())? = Some(on_output.clone()); if let Some(agent) = &agent { @@ -401,13 +447,22 @@ fn quit_app(app: &tauri::AppHandle) { // unknown word does nothing. #[tauri::command] fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: String) { - let Some(next) = Signal::from_id(&signal) else { return }; - let Some(window) = app.get_webview_window("main") else { return }; + let Some(next) = Signal::from_id(&signal) else { + return; + }; + let Some(window) = app.get_webview_window("main") else { + return; + }; let (prev, enabled) = { - let Ok(mut guard) = state.attention.lock() else { return }; + let Ok(mut guard) = state.attention.lock() else { + return; + }; (guard.last.replace(next), guard.enabled) }; - apply_badge(&window, attention::badge_for(next, std::env::consts::OS, enabled)); + apply_badge( + &window, + attention::badge_for(next, std::env::consts::OS, enabled), + ); if attention::should_flash(prev, next, window.is_focused().unwrap_or(true), enabled) { let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational)); } @@ -415,7 +470,10 @@ fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: Stri // The one place a badge reaches the window, in each system's own form. A call // that fails changes nothing else: the taskbar is a hint, never a blocker. -#[cfg_attr(not(any(target_os = "windows", target_os = "macos", target_os = "linux")), allow(unused_variables))] +#[cfg_attr( + not(any(target_os = "windows", target_os = "macos", target_os = "linux")), + allow(unused_variables) +)] fn apply_badge(window: &tauri::WebviewWindow, badge: Badge) { #[cfg(target_os = "windows")] { @@ -453,7 +511,9 @@ fn clear_attention(app: &tauri::AppHandle) { if let Ok(mut guard) = app.state::().attention.lock() { guard.last = Some(Signal::Plain); } - let Some(window) = app.get_webview_window("main") else { return }; + let Some(window) = app.get_webview_window("main") else { + return; + }; apply_badge(&window, Badge::None); let _ = window.request_user_attention(None); } @@ -470,17 +530,26 @@ fn clear_attention_cmd(app: tauri::AppHandle) { // Either way the last state is kept. Saved in the app's own app.json, never // in the console's files. #[tauri::command] -fn set_taskbar_signal(app: tauri::AppHandle, state: State<'_, AppState>, on: bool) -> Result<(), String> { +fn set_taskbar_signal( + app: tauri::AppHandle, + state: State<'_, AppState>, + on: bool, +) -> Result<(), String> { let saved = settings::settings_file() .ok_or_else(|| "no home folder found".to_string()) .and_then(|file| settings::save_taskbar_signal(&file, on)); let last = { - let Ok(mut guard) = state.attention.lock() else { return saved }; + let Ok(mut guard) = state.attention.lock() else { + return saved; + }; guard.enabled = on; guard.last.unwrap_or(Signal::Plain) }; if let Some(window) = app.get_webview_window("main") { - apply_badge(&window, attention::badge_for(last, std::env::consts::OS, on)); + apply_badge( + &window, + attention::badge_for(last, std::env::consts::OS, on), + ); if !on { let _ = window.request_user_attention(None); } @@ -502,7 +571,12 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value { .agent .clone() .filter(known) - .or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file)).filter(known)) + .or_else(|| { + settings_file + .as_ref() + .and_then(|file| settings::load_last_agent(file)) + .filter(known) + }) .or_else(|| project::remembered_agent().filter(known)); let term_panel = settings_file.as_ref().map_or( settings::TermPanelSettings { @@ -512,7 +586,9 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value { }, |file| settings::load_term_panel(file), ); - let first_run_done = settings_file.as_ref().is_some_and(|file| settings::load_first_run_done(file)); + let first_run_done = settings_file + .as_ref() + .is_some_and(|file| settings::load_first_run_done(file)); serde_json::json!({ "projectDir": project.as_ref().map(|p| p.dir.to_string_lossy().into_owned()), "projectDirSource": project.as_ref().map(|p| p.source), @@ -555,7 +631,10 @@ fn save_first_run_done() -> Result<(), String> { /// installed skills' version. The bar shows its Update line when they differ (FR-14). #[tauri::command] fn version_status(app: tauri::AppHandle) -> versions::VersionStatus { - versions::status(&app.package_info().version.to_string(), versions::installed_skills_version()) + versions::status( + &app.package_info().version.to_string(), + versions::installed_skills_version(), + ) } /// What `update_skills` resolves with: the installer's last line, and the version status @@ -570,7 +649,10 @@ struct UpdateOutcome { /// button asks for it: never silently. `progress` carries each line of the installer's own /// output live, for the bar to show while it runs. #[tauri::command] -async fn update_skills(app: tauri::AppHandle, progress: Channel) -> Result { +async fn update_skills( + app: tauri::AppHandle, + progress: Channel, +) -> Result { let version = app.package_info().version.to_string(); let message = tauri::async_runtime::spawn_blocking(move || { versions::run_update(&version, |line| { @@ -579,14 +661,20 @@ async fn update_skills(app: tauri::AppHandle, progress: Channel) -> Resu }) .await .map_err(|e| e.to_string())??; - let status = versions::status(&app.package_info().version.to_string(), versions::installed_skills_version()); + let status = versions::status( + &app.package_info().version.to_string(), + versions::installed_skills_version(), + ); Ok(UpdateOutcome { message, status }) } /// The OS folder picker, shown when no folder is known; a choice becomes the /// launcher's remembered folder. #[tauri::command] -fn pick_project_folder(app: tauri::AppHandle, state: State<'_, AppState>) -> Result, String> { +fn pick_project_folder( + app: tauri::AppHandle, + state: State<'_, AppState>, +) -> Result, String> { let picked = app .dialog() .file() @@ -631,7 +719,10 @@ fn teardown_project(state: &AppState) -> Result<(), String> { /// nothing (canceled) leaves the current project untouched. One project per /// window stays; this replaces it, it does not add a second. #[tauri::command] -fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result, String> { +fn change_project( + app: tauri::AppHandle, + state: State<'_, AppState>, +) -> Result, String> { let picked = app .dialog() .file() @@ -650,7 +741,7 @@ fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result) -> Result Result { let mut guard = state.console.lock().map_err(|e| e.to_string())?; - let sup = guard.as_mut().ok_or("The agent has not opened the dashboard yet.")?; + let sup = guard + .as_mut() + .ok_or("The agent has not opened the dashboard yet.")?; if !sup.health() { sup.restart_if_dead()?; } @@ -676,7 +769,9 @@ fn console_status(state: State<'_, AppState>) -> serde_json::Value { }; match guard.as_ref() { Some(sup) if sup.stopped() => serde_json::json!({ "state": "none", "url": null }), - Some(sup) if sup.health() => serde_json::json!({ "state": "running", "url": sup.session().url }), + Some(sup) if sup.health() => { + serde_json::json!({ "state": "running", "url": sup.session().url }) + } Some(sup) => serde_json::json!({ "state": "dead", "url": sup.session().url }), None => serde_json::json!({ "state": "none", "url": null }), } @@ -699,7 +794,9 @@ fn main() { node_check::NodeStatus::Ok(version) => Some(version.clone()), _ => None, }; - let node_binary = node_version.as_ref().and_then(|_| node_check::node_binary_path()); + let node_binary = node_version + .as_ref() + .and_then(|_| node_check::node_binary_path()); let args = std::env::args().collect::>(); tauri::Builder::default() @@ -711,7 +808,8 @@ fn main() { node_binary, attention: Mutex::new(AttentionState { last: None, - enabled: settings::settings_file().map_or(true, |file| settings::load_taskbar_signal(&file)), + enabled: settings::settings_file() + .is_none_or(|file| settings::load_taskbar_signal(&file)), }), ..AppState::default() }) @@ -759,11 +857,15 @@ fn main() { let handle = app.handle().clone(); let server = AnnounceServer::start(Arc::new(move |notice| { let state = handle.state::(); - let taken = take_announced(&state, ¬ice, window_origin(&handle), session_on_disk); + let taken = + take_announced(&state, ¬ice, window_origin(&handle), session_on_disk); if taken { let _ = handle.emit("console-page", ¬ice); } else { - eprintln!("plan2code: ignored a page outside the console store: {}", notice.sid); + eprintln!( + "plan2code: ignored a page outside the console store: {}", + notice.sid + ); } taken })); @@ -791,7 +893,10 @@ fn main() { .run(|app, event| { // Cmd+Q and the app menu's Quit on macOS end the app without closing the // window first. An exit asked for in code (`code` is set) is `quit_app`'s own. - if let tauri::RunEvent::ExitRequested { api, code: None, .. } = event { + if let tauri::RunEvent::ExitRequested { + api, code: None, .. + } = event + { if agent_is_active(app) { api.prevent_exit(); confirm_quit(app); @@ -807,25 +912,48 @@ mod tests { fn state_for(dir: &str) -> AppState { AppState { - project: Mutex::new(Some(ProjectDir { dir: PathBuf::from(dir), source: project::ProjectSource::Picked })), + project: Mutex::new(Some(ProjectDir { + dir: PathBuf::from(dir), + source: project::ProjectSource::Picked, + })), ..AppState::default() } } fn notice(sid: &str) -> PageNotice { - PageNotice { url: "http://127.0.0.1:5555/s/t/".into(), sid: sid.into(), workflow: "dashboard".into() } + PageNotice { + url: "http://127.0.0.1:5555/s/t/".into(), + sid: sid.into(), + workflow: "dashboard".into(), + } } /// A supervisor following the build's console, adopted with the repo's own /// console source so it never depends on an installed one. fn following_the_build() -> ConsoleSupervisor { - std::env::set_var("PLAN2CODE_CONSOLE_DIR", PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console")); - ConsoleSupervisor::adopt(PathBuf::from("."), app_origin().to_string(), "http://127.0.0.1:4444/s/b/", "build") - .expect("adopt with the repo's console") + std::env::set_var( + "PLAN2CODE_CONSOLE_DIR", + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"), + ); + ConsoleSupervisor::adopt( + PathBuf::from("."), + app_origin().to_string(), + "http://127.0.0.1:4444/s/b/", + "build", + ) + .expect("adopt with the repo's console") } fn sid_followed(state: &AppState) -> String { - state.console.lock().unwrap().as_ref().unwrap().session().sid.clone() + state + .console + .lock() + .unwrap() + .as_ref() + .unwrap() + .session() + .sid + .clone() } /// Adopted, never started here: skip Drop's `stop`. @@ -839,12 +967,22 @@ mod tests { // the agent's in-app variables: following it swapped a build's page for // the test's, then for an empty dashboard once the test shut it down. let state = state_for("project-a"); - assert!(!take_announced(&state, ¬ice("test-console"), app_origin().to_string(), |_| false)); + assert!(!take_announced( + &state, + ¬ice("test-console"), + app_origin().to_string(), + |_| false + )); assert!(state.console.lock().unwrap().is_none(), "nothing adopted"); // Already following the build's own console: it stays on that one. *state.console.lock().unwrap() = Some(following_the_build()); - assert!(!take_announced(&state, ¬ice("test-console"), app_origin().to_string(), |_| false)); + assert!(!take_announced( + &state, + ¬ice("test-console"), + app_origin().to_string(), + |_| false + )); assert_eq!(sid_followed(&state), "build"); let_go(&state); } @@ -853,7 +991,12 @@ mod tests { fn a_page_from_the_console_store_is_followed() { let state = state_for("project-a"); *state.console.lock().unwrap() = Some(following_the_build()); - assert!(take_announced(&state, ¬ice("next"), app_origin().to_string(), |_| true)); + assert!(take_announced( + &state, + ¬ice("next"), + app_origin().to_string(), + |_| true + )); assert_eq!(sid_followed(&state), "next"); let_go(&state); } @@ -871,21 +1014,41 @@ mod tests { // The project moved on; the slot still holds project-a's manager // until a fresh call replaces it. - *state.project.lock().unwrap() = Some(ProjectDir { dir: PathBuf::from("project-b"), source: project::ProjectSource::Picked }); + *state.project.lock().unwrap() = Some(ProjectDir { + dir: PathBuf::from("project-b"), + source: project::ProjectSource::Picked, + }); let second = agent_for_project(&state).expect("a manager for project-b"); assert_eq!(second.folder(), &PathBuf::from("project-b")); - assert!(!Arc::ptr_eq(&first, &second), "project-a's manager must never stand in for project-b's"); + assert!( + !Arc::ptr_eq(&first, &second), + "project-a's manager must never stand in for project-b's" + ); } #[test] fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own() { let state = state_for("project-a"); let server = AnnounceServer::start(Arc::new(|_| true)).unwrap(); - let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap(); + let port: u16 = server + .url() + .rsplit_once(':') + .unwrap() + .1 + .trim_end_matches("/page") + .parse() + .unwrap(); *state.announce.lock().unwrap() = Some(server); let body = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#; let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); - let token = state.announce.lock().unwrap().as_ref().unwrap().token().to_string(); + let token = state + .announce + .lock() + .unwrap() + .as_ref() + .unwrap() + .token() + .to_string(); use std::io::{Read, Write}; write!( stream, @@ -895,12 +1058,29 @@ mod tests { .unwrap(); let mut answer = String::new(); stream.read_to_string(&mut answer).unwrap(); - assert!(answer.starts_with("HTTP/1.1 204"), "the page was announced: {answer}"); - assert_eq!(state.announce.lock().unwrap().as_ref().unwrap().current().map(|n| n.sid), Some("s1".to_string())); + 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()) + ); // No console supervised here, so no brief to write: only the forgetting. assert_eq!(before_fresh_hook(&state)(), None); - assert_eq!(state.announce.lock().unwrap().as_ref().unwrap().current(), None, "the fresh agent's open must not join s1"); + assert_eq!( + state.announce.lock().unwrap().as_ref().unwrap().current(), + None, + "the fresh agent's open must not join s1" + ); } #[test] @@ -908,11 +1088,18 @@ mod tests { let state = state_for("project-a"); let first = agent_for_project(&state).unwrap(); let second = agent_for_project(&state).unwrap(); - assert!(Arc::ptr_eq(&first, &second), "the same folder should not make a second manager"); + assert!( + Arc::ptr_eq(&first, &second), + "the same folder should not make a second manager" + ); } fn have_node() -> bool { - std::process::Command::new("node").arg("--version").output().map(|o| o.status.success()).unwrap_or(false) + std::process::Command::new("node") + .arg("--version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) } /// A real console, the same way `tests/console_supervisor.rs` sets one @@ -925,18 +1112,29 @@ mod tests { } let console_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"); if !console_dir.join("console.mjs").is_file() { - eprintln!("skipping: console source missing at {}", console_dir.display()); + eprintln!( + "skipping: console source missing at {}", + console_dir.display() + ); return None; } 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(); std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console_dir); - std::env::set_var("PLAN2CODE_CONSOLE_HOME", std::env::temp_dir().join(format!("p2c-main-test-home-{pid}"))); + std::env::set_var( + "PLAN2CODE_CONSOLE_HOME", + std::env::temp_dir().join(format!("p2c-main-test-home-{pid}")), + ); std::env::set_var("PLAN2CODE_NO_BROWSER", "1"); // Run inside the desktop app, the agent's in-app variables would have this // console announce itself to the live window and take it over. - for name in ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"] { + for name in [ + "PLAN2CODE_IN_APP", + "PLAN2CODE_APP_ANNOUNCE", + "PLAN2CODE_APP_TOKEN", + "PLAN2CODE_CONSOLE_SID", + ] { std::env::remove_var(name); } Some( @@ -953,11 +1151,18 @@ mod tests { let Some(sup) = real_console() else { return }; let state = state_for("project-a"); *state.console.lock().unwrap() = Some(sup); - assert!(console_start_impl(&state).is_ok(), "console_start should work before the project changes"); + assert!( + console_start_impl(&state).is_ok(), + "console_start should work before the project changes" + ); teardown_project(&state).unwrap(); - let err = console_start_impl(&state).expect_err("console_start must refuse, not reconnect to the old session"); - assert!(err.contains("has not opened the dashboard"), "unexpected message: {err:?}"); + 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:?}" + ); } } diff --git a/plan2code-app/src-tauri/src/node_check.rs b/plan2code-app/src-tauri/src/node_check.rs index 57e3a97..289acfe 100644 --- a/plan2code-app/src-tauri/src/node_check.rs +++ b/plan2code-app/src-tauri/src/node_check.rs @@ -37,7 +37,11 @@ pub fn classify(output: &str) -> NodeStatus { } pub fn check_node() -> NodeStatus { - match Command::new("node").env("PATH", resolved_path()).arg("--version").output() { + match Command::new("node") + .env("PATH", resolved_path()) + .arg("--version") + .output() + { Ok(out) if out.status.success() => classify(&String::from_utf8_lossy(&out.stdout)), _ => NodeStatus::Missing, } @@ -55,7 +59,9 @@ fn node_override_dir(args: &[String]) -> Option { args[i].strip_prefix("--node=").map(str::to_string) }; if let Some(path) = value.filter(|v| !v.is_empty()) { - return std::path::Path::new(&path).parent().map(|dir| dir.to_string_lossy().into_owned()); + return std::path::Path::new(&path) + .parent() + .map(|dir| dir.to_string_lossy().into_owned()); } i += 1; } @@ -68,7 +74,10 @@ fn node_override_dir(args: &[String]) -> Option { #[cfg(unix)] fn login_shell_path() -> Option { let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()); - let out = Command::new(&shell).args(["-lc", "echo $PATH"]).output().ok()?; + let out = Command::new(&shell) + .args(["-lc", "echo $PATH"]) + .output() + .ok()?; let path = String::from_utf8_lossy(&out.stdout).trim().to_string(); (out.status.success() && !path.is_empty()).then_some(path) } @@ -123,7 +132,10 @@ fn build_path(fresh: bool) -> String { #[cfg(windows)] fn saved_windows_path() -> Vec { use std::os::windows::process::CommandExt; - let keys = [r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", r"HKCU\Environment"]; + let keys = [ + r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", + r"HKCU\Environment", + ]; keys.iter() .filter_map(|key| { let out = Command::new("reg") @@ -142,7 +154,9 @@ fn saved_windows_path() -> Vec { #[cfg_attr(not(windows), allow(dead_code))] fn parse_reg_query_value(output: &str) -> Option { output.lines().find_map(|line| { - let (_, rest) = line.split_once("REG_EXPAND_SZ").or_else(|| line.split_once("REG_SZ"))?; + let (_, rest) = line + .split_once("REG_EXPAND_SZ") + .or_else(|| line.split_once("REG_SZ"))?; let value = rest.trim(); (!value.is_empty()).then(|| value.to_string()) }) @@ -180,12 +194,25 @@ fn expand_percent_vars(text: &str, lookup: impl Fn(&str) -> Option) -> S /// Where `node` actually resolves, with `resolved_path`: for the first-run /// checklist to name (Task 9.9), not for `check_node` itself to decide with. pub fn node_binary_path() -> Option { - let (program, arg) = if cfg!(windows) { ("where", "node") } else { ("which", "node") }; - let out = Command::new(program).env("PATH", resolved_path()).arg(arg).output().ok()?; + let (program, arg) = if cfg!(windows) { + ("where", "node") + } else { + ("which", "node") + }; + let out = Command::new(program) + .env("PATH", resolved_path()) + .arg(arg) + .output() + .ok()?; if !out.status.success() { return None; } - String::from_utf8_lossy(&out.stdout).lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string) + String::from_utf8_lossy(&out.stdout) + .lines() + .next() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) } /// The plain message shown when the check fails; `None` when Node is fine. @@ -229,20 +256,41 @@ mod tests { #[test] fn message_only_for_a_problem() { assert!(problem_message(&NodeStatus::Ok("v20.0.0".into())).is_none()); - assert!(problem_message(&NodeStatus::Missing).unwrap().contains("nodejs.org")); - assert!(problem_message(&NodeStatus::TooOld("v16.0.0".into())).unwrap().contains("v16.0.0")); + assert!(problem_message(&NodeStatus::Missing) + .unwrap() + .contains("nodejs.org")); + assert!(problem_message(&NodeStatus::TooOld("v16.0.0".into())) + .unwrap() + .contains("v16.0.0")); } fn args(list: &[&str]) -> Vec { - std::iter::once("plan2code-app").chain(list.iter().copied()).map(str::to_string).collect() + std::iter::once("plan2code-app") + .chain(list.iter().copied()) + .map(str::to_string) + .collect() } #[test] fn the_node_override_names_its_directory_in_both_forms() { - let want = if cfg!(windows) { "C:\\nvm\\v20" } else { "/home/x/.nvm/v20" }; - let bin = if cfg!(windows) { "C:\\nvm\\v20\\node.exe" } else { "/home/x/.nvm/v20/node" }; - assert_eq!(node_override_dir(&args(&["--node", bin])).as_deref(), Some(want)); - assert_eq!(node_override_dir(&args(&[&format!("--node={bin}")])).as_deref(), Some(want)); + let want = if cfg!(windows) { + "C:\\nvm\\v20" + } else { + "/home/x/.nvm/v20" + }; + let bin = if cfg!(windows) { + "C:\\nvm\\v20\\node.exe" + } else { + "/home/x/.nvm/v20/node" + }; + assert_eq!( + node_override_dir(&args(&["--node", bin])).as_deref(), + Some(want) + ); + assert_eq!( + node_override_dir(&args(&[&format!("--node={bin}")])).as_deref(), + Some(want) + ); } #[test] @@ -256,17 +304,31 @@ mod tests { #[test] fn reads_the_saved_path_out_of_reg_query_output() { let out = "\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ %USERPROFILE%\\.local\\bin;C:\\Tools\r\n\r\n"; - assert_eq!(parse_reg_query_value(out).as_deref(), Some("%USERPROFILE%\\.local\\bin;C:\\Tools")); + assert_eq!( + parse_reg_query_value(out).as_deref(), + Some("%USERPROFILE%\\.local\\bin;C:\\Tools") + ); let plain = "HKEY_LOCAL_MACHINE\\x\r\n Path REG_SZ C:\\Windows\r\n"; assert_eq!(parse_reg_query_value(plain).as_deref(), Some("C:\\Windows")); - assert_eq!(parse_reg_query_value("ERROR: The system was unable to find the specified registry key or value.\r\n"), None); + assert_eq!( + parse_reg_query_value( + "ERROR: The system was unable to find the specified registry key or value.\r\n" + ), + None + ); } #[test] fn expands_known_percent_names_and_keeps_the_rest() { let lookup = |name: &str| (name == "USERPROFILE").then(|| "C:\\Users\\sam".to_string()); - assert_eq!(expand_percent_vars("%USERPROFILE%\\.local\\bin;C:\\x", lookup), "C:\\Users\\sam\\.local\\bin;C:\\x"); - assert_eq!(expand_percent_vars("%NOPE%\\bin;%USERPROFILE%", lookup), "%NOPE%\\bin;C:\\Users\\sam"); + assert_eq!( + expand_percent_vars("%USERPROFILE%\\.local\\bin;C:\\x", lookup), + "C:\\Users\\sam\\.local\\bin;C:\\x" + ); + assert_eq!( + expand_percent_vars("%NOPE%\\bin;%USERPROFILE%", lookup), + "%NOPE%\\bin;C:\\Users\\sam" + ); assert_eq!(expand_percent_vars("50%", lookup), "50%"); assert_eq!(expand_percent_vars("a%%b", lookup), "a%%b"); } diff --git a/plan2code-app/src-tauri/src/project.rs b/plan2code-app/src-tauri/src/project.rs index 6a12117..01d41c3 100644 --- a/plan2code-app/src-tauri/src/project.rs +++ b/plan2code-app/src-tauri/src/project.rs @@ -29,7 +29,11 @@ fn err(e: E) -> String { } fn launcher_file() -> Option { - Some(std::env::home_dir()?.join(".plan2code").join("launcher.json")) + Some( + std::env::home_dir()? + .join(".plan2code") + .join("launcher.json"), + ) } fn read_launcher() -> serde_json::Map { @@ -97,7 +101,10 @@ fn flag_value(args: &[String], flag: &str) -> Option { while i < args.len() { let arg = &args[i]; if arg == flag { - return args.get(i + 1).filter(|v| !v.is_empty() && !v.starts_with('-')).cloned(); + return args + .get(i + 1) + .filter(|v| !v.is_empty() && !v.starts_with('-')) + .cloned(); } if let Some(value) = arg.strip_prefix(&prefix) { return (!value.is_empty()).then(|| value.to_string()); @@ -124,9 +131,15 @@ pub fn launch_choice_in(args: &[String], agents_file: Option<&Path>) -> LaunchCh /// nothing (the page asks with the folder picker). pub fn resolve(args: &[String]) -> Option { if let Some(dir) = argument_folder(args) { - return Some(ProjectDir { dir, source: ProjectSource::Argument }); + return Some(ProjectDir { + dir, + source: ProjectSource::Argument, + }); } - remembered_folder().map(|dir| ProjectDir { dir, source: ProjectSource::Remembered }) + remembered_folder().map(|dir| ProjectDir { + dir, + source: ProjectSource::Remembered, + }) } /// A folder the person picked becomes the remembered one, so the next start @@ -143,7 +156,10 @@ pub fn remember_folder(dir: &Path) -> Result { } let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?; std::fs::write(file, json).map_err(err)?; - Ok(ProjectDir { dir: dir.to_path_buf(), source: ProjectSource::Picked }) + Ok(ProjectDir { + dir: dir.to_path_buf(), + source: ProjectSource::Picked, + }) } #[cfg(test)] @@ -156,36 +172,76 @@ mod tests { } fn args(list: &[&str]) -> Vec { - std::iter::once("plan2code-app").chain(list.iter().copied()).map(str::to_string).collect() + std::iter::once("plan2code-app") + .chain(list.iter().copied()) + .map(str::to_string) + .collect() } #[test] fn the_launcher_choice_reads_agent_and_model_in_both_forms() { - let want = LaunchChoice { agent: Some(AgentKind::Codex.id().to_string()), model: Some("gpt-5".into()) }; - assert_eq!(launch_choice(&args(&["--project", ".", "--agent", "codex", "--model", "gpt-5"])), want); - assert_eq!(launch_choice(&args(&["--agent=codex", "--model=gpt-5"])), want); - assert_eq!(launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])), want); + let want = LaunchChoice { + agent: Some(AgentKind::Codex.id().to_string()), + model: Some("gpt-5".into()), + }; + assert_eq!( + launch_choice(&args(&[ + "--project", + ".", + "--agent", + "codex", + "--model", + "gpt-5" + ])), + want + ); + assert_eq!( + launch_choice(&args(&["--agent=codex", "--model=gpt-5"])), + want + ); + assert_eq!( + launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])), + want + ); } #[test] fn an_agent_alone_is_a_choice_and_a_model_alone_is_not() { assert_eq!( launch_choice(&args(&["--agent", "claude"])), - LaunchChoice { agent: Some(AgentKind::Claude.id().to_string()), model: None } + LaunchChoice { + agent: Some(AgentKind::Claude.id().to_string()), + model: None + } + ); + assert_eq!( + launch_choice(&args(&["--model", "opus"])), + LaunchChoice::default() ); - assert_eq!(launch_choice(&args(&["--model", "opus"])), LaunchChoice::default()); } #[test] fn an_unknown_agent_or_a_missing_value_is_ignored() { - assert_eq!(launch_choice(&args(&["--agent", "emacs", "--model", "x"])), LaunchChoice::default()); + assert_eq!( + launch_choice(&args(&["--agent", "emacs", "--model", "x"])), + LaunchChoice::default() + ); assert_eq!(launch_choice(&args(&["--agent"])), LaunchChoice::default()); - assert_eq!(launch_choice(&args(&["--agent", "--model", "x"])), LaunchChoice::default()); - assert_eq!(launch_choice(&args(&["--agent=", "--model=x"])), LaunchChoice::default()); + assert_eq!( + launch_choice(&args(&["--agent", "--model", "x"])), + LaunchChoice::default() + ); + assert_eq!( + launch_choice(&args(&["--agent=", "--model=x"])), + LaunchChoice::default() + ); assert_eq!(launch_choice(&args(&[])), LaunchChoice::default()); assert_eq!( launch_choice(&args(&["--agent", "devin", "--model"])), - LaunchChoice { agent: Some(AgentKind::Devin.id().to_string()), model: None } + LaunchChoice { + agent: Some(AgentKind::Devin.id().to_string()), + model: None + } ); } @@ -194,11 +250,27 @@ mod tests { let dir = std::env::temp_dir().join(format!("p2c-project-custom-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("agents.json"); - std::fs::write(&file, r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose"}]}"#).unwrap(); - let want = LaunchChoice { agent: Some("goose".into()), model: Some("m1".into()) }; - assert_eq!(launch_choice_in(&args(&["--agent", "goose", "--model", "m1"]), Some(&file)), want); - assert_eq!(launch_choice_in(&args(&["--agent", "other", "--model", "m1"]), Some(&file)), LaunchChoice::default()); - assert_eq!(launch_choice_in(&args(&["--agent", "goose"]), None), LaunchChoice::default()); + std::fs::write( + &file, + r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose"}]}"#, + ) + .unwrap(); + let want = LaunchChoice { + agent: Some("goose".into()), + model: Some("m1".into()), + }; + assert_eq!( + launch_choice_in(&args(&["--agent", "goose", "--model", "m1"]), Some(&file)), + want + ); + assert_eq!( + launch_choice_in(&args(&["--agent", "other", "--model", "m1"]), Some(&file)), + LaunchChoice::default() + ); + assert_eq!( + launch_choice_in(&args(&["--agent", "goose"]), None), + LaunchChoice::default() + ); let _ = std::fs::remove_dir_all(&dir); } diff --git a/plan2code-app/src-tauri/src/pty_host.rs b/plan2code-app/src-tauri/src/pty_host.rs index 6b9dc4d..e3a3555 100644 --- a/plan2code-app/src-tauri/src/pty_host.rs +++ b/plan2code-app/src-tauri/src/pty_host.rs @@ -55,7 +55,12 @@ pub struct PtyHost { } fn size(cols: u16, rows: u16) -> PtySize { - PtySize { rows, cols, pixel_width: 0, pixel_height: 0 } + PtySize { + rows, + cols, + pixel_width: 0, + pixel_height: 0, + } } fn err(e: E) -> String { @@ -159,7 +164,11 @@ impl PtyHost { /// Tell the command the terminal changed size. pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> { - self.master.lock().map_err(err)?.resize(size(cols, rows)).map_err(err) + self.master + .lock() + .map_err(err)? + .resize(size(cols, rows)) + .map_err(err) } /// End the command. Safe to call while `wait` is blocked in another thread. @@ -236,8 +245,13 @@ mod windows_job { use winapi::shared::minwindef::DWORD; use winapi::shared::ntdef::HANDLE; use winapi::um::handleapi::CloseHandle; - use winapi::um::jobapi2::{AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject, TerminateJobObject}; - use winapi::um::winnt::{JobObjectExtendedLimitInformation, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE}; + use winapi::um::jobapi2::{ + AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject, TerminateJobObject, + }; + use winapi::um::winnt::{ + JobObjectExtendedLimitInformation, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + }; /// Create a job, set it to kill everything in it when its last handle /// closes, and assign `child` to it. `None` on any failure (an older diff --git a/plan2code-app/src-tauri/src/restart_brief.rs b/plan2code-app/src-tauri/src/restart_brief.rs index a33caab..a191128 100644 --- a/plan2code-app/src-tauri/src/restart_brief.rs +++ b/plan2code-app/src-tauri/src/restart_brief.rs @@ -28,11 +28,18 @@ static LAST_BRIEF: Mutex> = Mutex::new(None); /// whose brief would only repeat the skill's name. A session /// that names no worktree is an error, not a `None`, since that is a broken /// session rather than an empty one. -pub fn leave_brief(console_home: &Path, handoffs: &Path, sid: &str, when: DateTime) -> Result, String> { +pub fn leave_brief( + console_home: &Path, + handoffs: &Path, + sid: &str, + when: DateTime, +) -> Result, String> { let session = session_reader::load(console_home, sid).map_err(|e| e.to_string())?; let state = &session.state; let workflow = text(state, "workflow").unwrap_or(""); - let Some(skill) = brief::skill_for_workflow(workflow) else { return Ok(None) }; + let Some(skill) = brief::skill_for_workflow(workflow) else { + return Ok(None); + }; if finished(state) || empty(state) { return Ok(None); } @@ -47,7 +54,14 @@ pub fn leave_brief(console_home: &Path, handoffs: &Path, sid: &str, when: DateTi Some(spec) => format!("Restart of {skill} on {spec}"), None => format!("Restart of {skill}"), }; - let record = handoff::Record { title: &title, worktree, project, spec, workflow, skill }; + let record = handoff::Record { + title: &title, + worktree, + project, + spec, + workflow, + skill, + }; handoff::write(handoffs, when, &record, &body).map(Some) } @@ -58,7 +72,10 @@ pub fn note_for_restart(sid: &str) -> Option { let handoffs = handoff::handoffs_dir()?; match leave_brief(&console_home, &handoffs, sid, handoff::now()) { Ok(Some(id)) => { - let previous = LAST_BRIEF.lock().ok().and_then(|mut last| last.replace(id.clone())); + let previous = LAST_BRIEF + .lock() + .ok() + .and_then(|mut last| last.replace(id.clone())); if let Some(previous) = previous.filter(|p| *p != id) { let _ = handoff::retire_if_unused(&handoffs, &previous); } @@ -70,27 +87,46 @@ pub fn note_for_restart(sid: &str) -> Option { } fn text<'a>(state: &'a Value, key: &str) -> Option<&'a str> { - state.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()) + state + .get(key) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) } /// The session posted a `finish` that is not a pause. A pause's headline starts /// with "Paused" (the page's `finishPaused`) and keeps a place worth picking up. fn finished(state: &Value) -> bool { - let Some(finish) = state.get("finish").filter(|f| f.is_object()) else { return false }; - let headline = finish.get("headline").and_then(Value::as_str).unwrap_or("").trim_start(); - !headline.get(..6).is_some_and(|word| word.eq_ignore_ascii_case("paused")) + let Some(finish) = state.get("finish").filter(|f| f.is_object()) else { + return false; + }; + let headline = finish + .get("headline") + .and_then(Value::as_str) + .unwrap_or("") + .trim_start(); + !headline + .get(..6) + .is_some_and(|word| word.eq_ignore_ascii_case("paused")) } /// Nothing a fresh agent could pick up beyond the skill's name. fn empty(state: &Value) -> bool { let stage = state.get("headline").and_then(|h| text(h, "stage")); - let activity = state.get("agent").and_then(|a| text(a, "activity")).filter(|a| !a.trim().is_empty()); - let items = state.get("items").and_then(Value::as_array).is_some_and(|items| !items.is_empty()); + let activity = state + .get("agent") + .and_then(|a| text(a, "activity")) + .filter(|a| !a.trim().is_empty()); + let items = state + .get("items") + .and_then(Value::as_array) + .is_some_and(|items| !items.is_empty()); text(state, "specDir").is_none() && stage.is_none() && activity.is_none() && !items } fn valid_spec(spec: &str) -> bool { - spec.strip_prefix("specs/").is_some_and(|name| !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\'])) + spec.strip_prefix("specs/").is_some_and(|name| { + !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\']) + }) } #[cfg(test)] @@ -101,7 +137,8 @@ mod tests { use std::path::PathBuf; fn fixture(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("plan2code-restart-{}-{name}", std::process::id())); + let dir = + std::env::temp_dir().join(format!("plan2code-restart-{}-{name}", std::process::id())); let _ = fs::remove_dir_all(&dir); fs::create_dir_all(&dir).unwrap(); dir @@ -137,12 +174,24 @@ mod tests { let (home, project, handoffs) = session("pickup", "implement", Some("specs/feature")); let spec = project.join("specs").join("feature"); fs::create_dir_all(&spec).unwrap(); - fs::write(spec.join("overview.md"), "- [/] [Phase 5: Restart](./phase-5.md)\n").unwrap(); - fs::write(spec.join("phase-5.md"), "- [ ] **Task 5.1:** Create the reader\n").unwrap(); + fs::write( + spec.join("overview.md"), + "- [/] [Phase 5: Restart](./phase-5.md)\n", + ) + .unwrap(); + fs::write( + spec.join("phase-5.md"), + "- [ ] **Task 5.1:** Create the reader\n", + ) + .unwrap(); - let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff"); + let id = leave_brief(&home, &handoffs, "s1", when()) + .unwrap() + .expect("a handoff"); assert_eq!(id, "2026-10-21-1405-handoff"); - let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap(); + let record: Value = + serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()) + .unwrap(); assert_eq!(record["workflow"], "implement"); assert_eq!(record["spec"], "specs/feature"); let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap(); @@ -178,14 +227,17 @@ mod tests { state["finish"] = serde_json::json!({ "headline": "Paused at Phase 5" }); fs::write(&file, state.to_string()).unwrap(); - assert!(leave_brief(&home, &handoffs, "s1", when()).unwrap().is_some()); + assert!(leave_brief(&home, &handoffs, "s1", when()) + .unwrap() + .is_some()); } #[test] fn the_brief_carries_the_agent_activity_and_recent_events() { let (home, _project, handoffs) = session("activity", "implement", None); let dir = home.join("sessions").join("s1"); - let mut state: Value = serde_json::from_str(&fs::read_to_string(dir.join("state.json")).unwrap()).unwrap(); + let mut state: Value = + serde_json::from_str(&fs::read_to_string(dir.join("state.json")).unwrap()).unwrap(); state["agent"] = serde_json::json!({ "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" }); fs::write(dir.join("state.json"), state.to_string()).unwrap(); fs::write( @@ -194,7 +246,9 @@ mod tests { ) .unwrap(); - let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff"); + let id = leave_brief(&home, &handoffs, "s1", when()) + .unwrap() + .expect("a handoff"); let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap(); assert!(doc.contains("Doing: Spiking Claude's context signal (Task 10.1)")); assert!(doc.contains("## Recent activity\n\n- post (0 items)\n- consume: submit\n")); @@ -209,8 +263,12 @@ mod tests { #[test] fn a_spec_that_is_not_one_folder_is_left_out_of_the_record() { let (home, _, handoffs) = session("badspec", "pathfinder", Some("specs/a/b")); - let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().unwrap(); - let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap(); + let id = leave_brief(&home, &handoffs, "s1", when()) + .unwrap() + .unwrap(); + let record: Value = + serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()) + .unwrap(); assert!(record["spec"].is_null()); } } diff --git a/plan2code-app/src-tauri/src/session_reader.rs b/plan2code-app/src-tauri/src/session_reader.rs index 14bbac0..407f75b 100644 --- a/plan2code-app/src-tauri/src/session_reader.rs +++ b/plan2code-app/src-tauri/src/session_reader.rs @@ -43,7 +43,10 @@ impl std::fmt::Display for ReadError { ReadError::Unreadable(why) => write!(f, "could not read the session: {why}"), ReadError::Malformed(why) => write!(f, "the session file is not valid: {why}"), ReadError::Schema(found) => { - write!(f, "session schema {found} is not supported (this app reads schema {SCHEMA})") + write!( + f, + "session schema {found} is not supported (this app reads schema {SCHEMA})" + ) } } } @@ -73,7 +76,9 @@ pub fn session_dir(console_home: &Path, sid: &str) -> PathBuf { /// Open and parse the session `sid` under `console_home`. pub fn load(console_home: &Path, sid: &str) -> Result { let dir = session_dir(console_home, sid); - let text = read_with_retry(&dir.join("state.json"), |file| std::fs::read_to_string(file))?; + let text = read_with_retry(&dir.join("state.json"), |file| { + std::fs::read_to_string(file) + })?; let state = parse_state(&text)?; Ok(Session { dir, state }) } @@ -90,7 +95,9 @@ where loop { match read(file) { Ok(text) => return Ok(text), - Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(ReadError::Missing(file.to_path_buf())), + Err(e) if e.kind() == io::ErrorKind::NotFound => { + return Err(ReadError::Missing(file.to_path_buf())) + } Err(e) if is_locked(&e) => { if retries == LOCKED_RETRIES { return Err(ReadError::Busy); @@ -104,12 +111,15 @@ where } fn is_locked(e: &io::Error) -> bool { - e.kind() == io::ErrorKind::PermissionDenied || e.raw_os_error().is_some_and(|code| WINDOWS_SHARING.contains(&code)) + e.kind() == io::ErrorKind::PermissionDenied + || e.raw_os_error() + .is_some_and(|code| WINDOWS_SHARING.contains(&code)) } /// Parse `state.json` text: a JSON object whose `schema` is `SCHEMA`. pub fn parse_state(text: &str) -> Result { - let state: Value = serde_json::from_str(text).map_err(|e| ReadError::Malformed(e.to_string()))?; + let state: Value = + serde_json::from_str(text).map_err(|e| ReadError::Malformed(e.to_string()))?; if !state.is_object() { return Err(ReadError::Malformed("not a JSON object".to_string())); } @@ -134,7 +144,10 @@ pub fn read_ndjson(file: &Path) -> Vec { } pub fn parse_ndjson(text: &str) -> Vec { - text.lines().filter(|line| !line.trim().is_empty()).filter_map(|line| serde_json::from_str(line).ok()).collect() + text.lines() + .filter(|line| !line.trim().is_empty()) + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() } #[cfg(test)] @@ -143,13 +156,15 @@ mod tests { use std::cell::Cell; fn fixture(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("plan2code-reader-{}-{name}", std::process::id())); + let dir = + std::env::temp_dir().join(format!("plan2code-reader-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir } - const STATE: &str = r#"{"schema": 1, "sid": "s1", "workflow": "implement", "specDir": "specs/x"}"#; + const STATE: &str = + r#"{"schema": 1, "sid": "s1", "workflow": "implement", "specDir": "specs/x"}"#; #[test] fn a_complete_session_loads() { @@ -165,7 +180,10 @@ mod tests { #[test] fn a_partial_last_line_is_dropped() { let lines = parse_ndjson("{\"a\":1}\n{\"b\":2}\n{\"c\":"); - assert_eq!(lines, vec![serde_json::json!({"a": 1}), serde_json::json!({"b": 2})]); + assert_eq!( + lines, + vec![serde_json::json!({"a": 1}), serde_json::json!({"b": 2})] + ); } #[test] diff --git a/plan2code-app/src-tauri/src/settings.rs b/plan2code-app/src-tauri/src/settings.rs index 34e5040..9f91f2e 100644 --- a/plan2code-app/src-tauri/src/settings.rs +++ b/plan2code-app/src-tauri/src/settings.rs @@ -46,7 +46,10 @@ pub fn load_last_agent(file: &Path) -> Option { /// Save the pick, keeping any other key the file holds. pub fn save_last_agent(file: &Path, id: &str) -> Result<(), String> { let mut settings = read(file); - settings.insert(LAST_AGENT_KEY.to_string(), serde_json::Value::String(id.to_string())); + settings.insert( + LAST_AGENT_KEY.to_string(), + serde_json::Value::String(id.to_string()), + ); write(file, settings) } @@ -65,13 +68,25 @@ pub fn load_term_panel(file: &Path) -> TermPanelSettings { .and_then(|v| v.as_f64()) .filter(|f| (TERM_FRACTION_MIN..=TERM_FRACTION_MAX).contains(f)) .unwrap_or(DEFAULT_TERM_FRACTION); - let collapsed = settings.get(TERM_COLLAPSED_KEY).and_then(|v| v.as_bool()).unwrap_or(false); - TermPanelSettings { dock, fraction, collapsed } + let collapsed = settings + .get(TERM_COLLAPSED_KEY) + .and_then(|v| v.as_bool()) + .unwrap_or(false); + TermPanelSettings { + dock, + fraction, + collapsed, + } } /// Save the terminal pane's shape, keeping any other key the file holds. An /// invalid dock or an out-of-range fraction is rejected rather than saved. -pub fn save_term_panel(file: &Path, dock: &str, fraction: f64, collapsed: bool) -> Result<(), String> { +pub fn save_term_panel( + file: &Path, + dock: &str, + fraction: f64, + collapsed: bool, +) -> Result<(), String> { if dock != "bottom" && dock != "right" { return Err(format!("unknown dock: {dock}")); } @@ -79,25 +94,39 @@ pub fn save_term_panel(file: &Path, dock: &str, fraction: f64, collapsed: bool) return Err(format!("fraction out of range: {fraction}")); } let mut settings = read(file); - settings.insert(TERM_DOCK_KEY.to_string(), serde_json::Value::String(dock.to_string())); + settings.insert( + TERM_DOCK_KEY.to_string(), + serde_json::Value::String(dock.to_string()), + ); settings.insert( TERM_FRACTION_KEY.to_string(), - serde_json::Number::from_f64(fraction).map(serde_json::Value::Number).unwrap_or(serde_json::Value::Null), + serde_json::Number::from_f64(fraction) + .map(serde_json::Value::Number) + .unwrap_or(serde_json::Value::Null), + ); + settings.insert( + TERM_COLLAPSED_KEY.to_string(), + serde_json::Value::Bool(collapsed), ); - settings.insert(TERM_COLLAPSED_KEY.to_string(), serde_json::Value::Bool(collapsed)); write(file, settings) } /// Whether the first-run checklist has already passed once. Once it has, /// later launches go straight to the launch card (Task 9.4). pub fn load_first_run_done(file: &Path) -> bool { - read(file).get(FIRST_RUN_DONE_KEY).and_then(|v| v.as_bool()).unwrap_or(false) + read(file) + .get(FIRST_RUN_DONE_KEY) + .and_then(|v| v.as_bool()) + .unwrap_or(false) } /// Remember that the checklist passed, keeping any other key the file holds. pub fn save_first_run_done(file: &Path) -> Result<(), String> { let mut settings = read(file); - settings.insert(FIRST_RUN_DONE_KEY.to_string(), serde_json::Value::Bool(true)); + settings.insert( + FIRST_RUN_DONE_KEY.to_string(), + serde_json::Value::Bool(true), + ); write(file, settings) } @@ -105,7 +134,10 @@ pub fn save_first_run_done(file: &Path) -> Result<(), String> { /// Desktop app switch in the console's User Preferences). On unless the file /// says `false`; anything but a boolean reads as on. pub fn load_taskbar_signal(file: &Path) -> bool { - read(file).get(TASKBAR_SIGNAL_KEY).and_then(|v| v.as_bool()).unwrap_or(true) + read(file) + .get(TASKBAR_SIGNAL_KEY) + .and_then(|v| v.as_bool()) + .unwrap_or(true) } /// Save the switch, keeping any other key the file holds. @@ -119,7 +151,8 @@ fn write(file: &Path, settings: serde_json::Map) -> R if let Some(parent) = file.parent() { std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; } - let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings)).map_err(|e| e.to_string())?; + let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings)) + .map_err(|e| e.to_string())?; std::fs::write(file, json).map_err(|e| e.to_string()) } @@ -128,7 +161,8 @@ mod tests { use super::*; fn temp_file(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("plan2code-settings-{}-{name}", std::process::id())); + let dir = + std::env::temp_dir().join(format!("plan2code-settings-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); dir.join("app.json") } @@ -146,8 +180,14 @@ mod tests { save_last_agent(&file, "devin").unwrap(); assert_eq!(load_last_agent(&file), Some("devin".to_string())); save_last_agent(&file, "goose").unwrap(); - assert_eq!(load_last_agent(&file), Some("goose".to_string()), "a custom id round-trips"); - assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\"")); + assert_eq!( + load_last_agent(&file), + Some("goose".to_string()), + "a custom id round-trips" + ); + assert!(std::fs::read_to_string(&file) + .unwrap() + .contains("\"other\"")); let _ = std::fs::remove_dir_all(file.parent().unwrap()); } @@ -163,7 +203,11 @@ mod tests { #[test] fn the_term_panel_defaults_to_bottom_at_a_quarter() { - let want = TermPanelSettings { dock: "bottom".into(), fraction: 0.25, collapsed: false }; + let want = TermPanelSettings { + dock: "bottom".into(), + fraction: 0.25, + collapsed: false, + }; assert_eq!(load_term_panel(&temp_file("term-missing")), want); } @@ -175,9 +219,15 @@ mod tests { save_term_panel(&file, "right", 0.4, true).unwrap(); assert_eq!( load_term_panel(&file), - TermPanelSettings { dock: "right".into(), fraction: 0.4, collapsed: true } + TermPanelSettings { + dock: "right".into(), + fraction: 0.4, + collapsed: true + } ); - assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\"")); + assert!(std::fs::read_to_string(&file) + .unwrap() + .contains("\"other\"")); let _ = std::fs::remove_dir_all(file.parent().unwrap()); } @@ -198,7 +248,9 @@ mod tests { std::fs::write(&file, r#"{"other": 1}"#).unwrap(); save_first_run_done(&file).unwrap(); assert!(load_first_run_done(&file)); - assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\"")); + assert!(std::fs::read_to_string(&file) + .unwrap() + .contains("\"other\"")); let _ = std::fs::remove_dir_all(file.parent().unwrap()); } @@ -213,7 +265,9 @@ mod tests { assert!(!load_taskbar_signal(&file)); save_taskbar_signal(&file, true).unwrap(); assert!(load_taskbar_signal(&file)); - assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\"")); + assert!(std::fs::read_to_string(&file) + .unwrap() + .contains("\"other\"")); let _ = std::fs::remove_dir_all(file.parent().unwrap()); } diff --git a/plan2code-app/src-tauri/src/versions.rs b/plan2code-app/src-tauri/src/versions.rs index 0f7d607..ab9a432 100644 --- a/plan2code-app/src-tauri/src/versions.rs +++ b/plan2code-app/src-tauri/src/versions.rs @@ -65,7 +65,12 @@ pub fn status(app: &str, skills: Option) -> VersionStatus { (Some(a), Some(s)) => (a != s, s > a), _ => (false, false), }; - VersionStatus { app: app.to_string(), skills, mismatch, skills_ahead } + VersionStatus { + app: app.to_string(), + skills, + mismatch, + skills_ahead, + } } /// Run the existing installer's update (`plan2code update`, through the launcher's own copy), @@ -80,10 +85,19 @@ pub fn run_update(app_version: &str, on_line: impl FnMut(&str)) -> Result Result { - let launcher = launcher_dir().ok_or("no home folder found")?.join("plan2code.js"); +fn run_update_within( + app_version: &str, + timeout: Duration, + mut on_line: impl FnMut(&str), +) -> Result { + let launcher = launcher_dir() + .ok_or("no home folder found")? + .join("plan2code.js"); if !launcher.is_file() { - return Err(format!("the plan2code command is not installed ({} is missing)", launcher.display())); + return Err(format!( + "the plan2code command is not installed ({} is missing)", + launcher.display() + )); } let mut command = Command::new("node"); // A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's @@ -103,7 +117,9 @@ fn run_update_within(app_version: &str, timeout: Duration, mut on_line: impl FnM use std::os::windows::process::CommandExt; command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are } - let mut child = command.spawn().map_err(|e| format!("could not run node: {e}"))?; + let mut child = command + .spawn() + .map_err(|e| format!("could not run node: {e}"))?; let stdout = child.stdout.take().ok_or("no stdout from the update")?; let stderr = child.stderr.take().ok_or("no stderr from the update")?; let (tx, rx) = mpsc::channel::(); @@ -169,7 +185,12 @@ mod tests { let s = status("3.0.0", Some("3.0.0".into())); assert_eq!( s, - VersionStatus { app: "3.0.0".into(), skills: Some("3.0.0".into()), mismatch: false, skills_ahead: false } + VersionStatus { + app: "3.0.0".into(), + skills: Some("3.0.0".into()), + mismatch: false, + skills_ahead: false + } ); } @@ -202,7 +223,9 @@ mod tests { #[test] fn a_missing_or_broken_version_file_reads_as_none() { - let missing = std::env::temp_dir().join("p2c-versions-does-not-exist").join("version.json"); + let missing = std::env::temp_dir() + .join("p2c-versions-does-not-exist") + .join("version.json"); assert_eq!(version_in(&missing), None); assert_eq!(version_in(&temp_file("broken", "{ not json")), None); assert_eq!(version_in(&temp_file("nover", r#"{ "name": "x" }"#)), None); @@ -215,7 +238,10 @@ mod tests { /// source, no quoting needed), runs `body`, then restores the environment. fn with_fake_launcher(name: &str, script: &str, body: impl FnOnce() -> T) -> T { let _guard = ENV_LOCK.lock().unwrap(); - let dir = std::env::temp_dir().join(format!("p2c-versions-launcher-{}-{name}", std::process::id())); + let dir = std::env::temp_dir().join(format!( + "p2c-versions-launcher-{}-{name}", + std::process::id() + )); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("plan2code.js"), script).unwrap(); @@ -229,11 +255,17 @@ mod tests { #[test] fn run_update_streams_lines_live_and_returns_the_last_one_on_success() { let lines = std::sync::Mutex::new(Vec::::new()); - let result = with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || { - run_update_within("9.9.9", Duration::from_secs(10), |line| lines.lock().unwrap().push(line.to_string())) - }); + let result = + with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || { + run_update_within("9.9.9", Duration::from_secs(10), |line| { + lines.lock().unwrap().push(line.to_string()) + }) + }); assert_eq!(result, Ok("line2".to_string())); - assert_eq!(*lines.lock().unwrap(), vec!["line1".to_string(), "line2".to_string()]); + assert_eq!( + *lines.lock().unwrap(), + vec!["line1".to_string(), "line2".to_string()] + ); } #[test] diff --git a/plan2code-app/src-tauri/tests/agent_manager.rs b/plan2code-app/src-tauri/tests/agent_manager.rs index 4cc6f25..4d721a6 100644 --- a/plan2code-app/src-tauri/tests/agent_manager.rs +++ b/plan2code-app/src-tauri/tests/agent_manager.rs @@ -8,7 +8,9 @@ use std::sync::{Arc, Mutex, Once}; use std::time::{Duration, Instant}; use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState}; -use plan2code_app_lib::agents::{agent_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV}; +use plan2code_app_lib::agents::{ + agent_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV, +}; mod common; use common::process_alive; @@ -36,7 +38,13 @@ impl Harness { let sink = Arc::new(move |event| { let _ = tx.lock().unwrap().send(event); }); - Harness { manager: AgentManager::new(PathBuf::from("."), sink), rx, seen: String::new(), states: Vec::new(), cursor: 0 } + Harness { + manager: AgentManager::new(PathBuf::from("."), sink), + rx, + seen: String::new(), + states: Vec::new(), + cursor: 0, + } } fn take(&mut self, event: AgentEvent) { @@ -80,7 +88,11 @@ impl Harness { } /// The next state change (after the last one this returned) that matches. - fn wait_state(&mut self, what: &str, matches: impl Fn(&AgentSnapshot) -> bool) -> AgentSnapshot { + fn wait_state( + &mut self, + what: &str, + matches: impl Fn(&AgentSnapshot) -> bool, + ) -> AgentSnapshot { let deadline = Instant::now() + TIMEOUT; loop { while self.cursor < self.states.len() { @@ -99,7 +111,15 @@ impl Harness { } fn start_and_wait_ready(&mut self) { - self.manager.start(Agent::Builtin(AgentKind::Claude), None, None, PermissionMode::Bypass, None).expect("start the fake agent"); + self.manager + .start( + Agent::Builtin(AgentKind::Claude), + None, + None, + PermissionMode::Bypass, + None, + ) + .expect("start the fake agent"); self.wait_for_output(READY, 1); } @@ -118,11 +138,20 @@ fn a_second_start_while_running_is_refused() { h.start_and_wait_ready(); let generation = h.manager.snapshot().generation; - let refused = h.manager.start(Agent::Builtin(AgentKind::Devin), None, None, PermissionMode::Bypass, None); + let refused = h.manager.start( + Agent::Builtin(AgentKind::Devin), + None, + None, + PermissionMode::Bypass, + None, + ); assert!(refused.is_err(), "a second start must be refused"); let after = h.manager.snapshot(); assert_eq!(after.state, AgentState::Running); - assert_eq!(after.generation, generation, "the running agent was replaced"); + assert_eq!( + after.generation, generation, + "the running agent was replaced" + ); h.manager.stop(); } @@ -130,19 +159,36 @@ fn a_second_start_while_running_is_refused() { fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() { let mut h = Harness::new(); h.manager - .start(Agent::Builtin(AgentKind::Codex), Some("gpt-5".to_string()), Some("high".to_string()), PermissionMode::Checked, None) + .start( + Agent::Builtin(AgentKind::Codex), + Some("gpt-5".to_string()), + Some("high".to_string()), + PermissionMode::Checked, + None, + ) .expect("start the fake agent"); h.wait_for_output(READY, 1); let before = h.manager.snapshot(); assert_eq!(before.kind, Some("codex".to_string())); assert_eq!(before.mode, Some(PermissionMode::Checked)); - assert_eq!(h.manager.model_and_effort(), (Some("gpt-5".to_string()), Some("high".to_string()))); + assert_eq!( + h.manager.model_and_effort(), + (Some("gpt-5".to_string()), Some("high".to_string())) + ); h.manager.restart().unwrap(); h.wait_for_output(READY, 2); let after = h.manager.snapshot(); - assert_eq!(after.kind, Some("codex".to_string()), "restart must keep the same agent"); - assert_eq!(after.mode, Some(PermissionMode::Checked), "restart must keep the same permission mode"); + assert_eq!( + after.kind, + Some("codex".to_string()), + "restart must keep the same agent" + ); + assert_eq!( + after.mode, + Some(PermissionMode::Checked), + "restart must keep the same permission mode" + ); assert_eq!( h.manager.model_and_effort(), (Some("gpt-5".to_string()), Some("high".to_string())), @@ -179,8 +225,15 @@ fn restart_mid_step_kills_the_step_at_once_instead_of_waiting_for_it() { // Running again straight away: no wait for the step to finish. h.wait_state("Running again", is_running); h.wait_for_output(READY, 2); - assert!(started.elapsed() < Duration::from_secs(5), "restart must not wait on the step; took {:?}", started.elapsed()); - assert!(!h.seen.contains("STEP DONE"), "the step should have been cut short, not finished"); + assert!( + started.elapsed() < Duration::from_secs(5), + "restart must not wait on the step; took {:?}", + started.elapsed() + ); + assert!( + !h.seen.contains("STEP DONE"), + "the step should have been cut short, not finished" + ); h.manager.stop(); } @@ -198,8 +251,15 @@ fn an_agent_that_exits_by_itself_ends_with_its_code_and_nothing_restarts() { // Nothing starts without a press. h.pump_for(Duration::from_millis(1500)); - assert!(matches!(h.manager.snapshot().state, AgentState::Ended { .. })); - assert_eq!(h.seen.matches(READY).count(), 1, "an agent started by itself"); + assert!(matches!( + h.manager.snapshot().state, + AgentState::Ended { .. } + )); + assert_eq!( + h.seen.matches(READY).count(), + 1, + "an agent started by itself" + ); assert!(!h.manager.is_active()); // A press of Restart starts a fresh one on the same brief. @@ -216,8 +276,21 @@ fn quitting_with_a_running_agent_stops_it() { assert!(h.manager.is_active()); h.type_line("PID"); h.wait_for_output("PID ", 1); - let pid = h.seen.rsplit("PID ").next().unwrap().trim_start().split(|c: char| !c.is_ascii_digit()).next().unwrap().parse::().expect("the agent's pid"); - assert!(process_alive(pid), "the agent should be running before the stop"); + let pid = h + .seen + .rsplit("PID ") + .next() + .unwrap() + .trim_start() + .split(|c: char| !c.is_ascii_digit()) + .next() + .unwrap() + .parse::() + .expect("the agent's pid"); + assert!( + process_alive(pid), + "the agent should be running before the stop" + ); h.manager.stop(); @@ -228,8 +301,14 @@ fn quitting_with_a_running_agent_stops_it() { // The stopped agent does not come back or print again. let before = h.seen.len(); h.pump_for(Duration::from_millis(1000)); - assert!(!h.seen[before..].contains(READY), "an agent started after the stop"); - assert!(h.manager.restart().is_err(), "there is nothing left to restart"); + assert!( + !h.seen[before..].contains(READY), + "an agent started after the stop" + ); + assert!( + h.manager.restart().is_err(), + "there is nothing left to restart" + ); } #[test] @@ -237,12 +316,19 @@ fn the_replay_buffer_holds_recent_output_and_clears_on_a_fresh_agent() { let mut h = Harness::new(); h.start_and_wait_ready(); let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned(); - assert!(replay.contains(READY), "replay should hold what was just printed; got {replay:?}"); + assert!( + replay.contains(READY), + "replay should hold what was just printed; got {replay:?}" + ); h.manager.restart().unwrap(); h.wait_for_output(READY, 2); let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned(); - assert_eq!(replay.matches(READY).count(), 1, "a fresh agent's replay must not carry the old one's output"); + assert_eq!( + replay.matches(READY).count(), + 1, + "a fresh agent's replay must not carry the old one's output" + ); h.manager.stop(); } @@ -261,8 +347,15 @@ fn a_restart_runs_the_brief_hook_and_the_bar_gets_its_note() { h.manager.restart().unwrap(); - assert_eq!(*runs.lock().unwrap(), 1, "the restart did not run the brief once"); - assert_eq!(h.manager.snapshot().brief_note.as_deref(), Some("Brief ready on the dashboard")); + assert_eq!( + *runs.lock().unwrap(), + 1, + "the restart did not run the brief once" + ); + assert_eq!( + h.manager.snapshot().brief_note.as_deref(), + Some("Brief ready on the dashboard") + ); h.manager.stop(); } @@ -271,7 +364,10 @@ fn the_agent_gets_the_in_app_signal_and_a_restart_keeps_it() { let mut h = Harness::new(); h.manager.set_env(vec![ ("PLAN2CODE_IN_APP".to_string(), "1".to_string()), - ("PLAN2CODE_CONSOLE_SID".to_string(), "sid-window-a".to_string()), + ( + "PLAN2CODE_CONSOLE_SID".to_string(), + "sid-window-a".to_string(), + ), ]); h.start_and_wait_ready(); h.type_line("ENV PLAN2CODE_IN_APP"); @@ -280,7 +376,10 @@ fn the_agent_gets_the_in_app_signal_and_a_restart_keeps_it() { h.wait_for_output("ENV PLAN2CODE_CONSOLE_SID=sid-window-a", 1); // The signal changes with the console; a Restart starts on the newest. - h.manager.set_env(vec![("PLAN2CODE_CONSOLE_SID".to_string(), "sid-window-b".to_string())]); + h.manager.set_env(vec![( + "PLAN2CODE_CONSOLE_SID".to_string(), + "sid-window-b".to_string(), + )]); h.manager.restart().unwrap(); h.wait_for_output(READY, 2); h.type_line("ENV PLAN2CODE_CONSOLE_SID"); @@ -304,17 +403,32 @@ fn an_agent_with_no_signal_set_gets_none() { fn a_custom_agent_runs_the_override_too_and_restart_keeps_its_id() { let mut h = Harness::new(); // Its command is nowhere on PATH: the override replaces it, as for a built-in. - let (mut agents, warnings) = parse_agents_file(r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose-not-installed","bypassArgs":["--yes"]}]}"#); + let (mut agents, warnings) = parse_agents_file( + r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose-not-installed","bypassArgs":["--yes"]}]}"#, + ); assert!(warnings.is_empty(), "{warnings:?}"); let goose = Agent::Custom(agents.remove(0)); - let spec = agent_launch_spec(&goose, &std::env::temp_dir(), Some("m"), None, PermissionMode::Bypass, "/plan2code"); + let spec = agent_launch_spec( + &goose, + &std::env::temp_dir(), + Some("m"), + None, + PermissionMode::Bypass, + "/plan2code", + ); assert_eq!(PathBuf::from(&spec.program), common::fake_agent()); assert!(spec.args.is_empty()); - h.manager.start(goose, None, None, PermissionMode::Checked, None).expect("start the custom agent"); + h.manager + .start(goose, None, None, PermissionMode::Checked, None) + .expect("start the custom agent"); h.wait_for_output(READY, 1); assert_eq!(h.manager.snapshot().kind, Some("goose".to_string())); h.manager.restart().unwrap(); h.wait_for_output(READY, 2); - assert_eq!(h.manager.snapshot().kind, Some("goose".to_string()), "restart must keep the custom agent"); + assert_eq!( + h.manager.snapshot().kind, + Some("goose".to_string()), + "restart must keep the custom agent" + ); h.manager.stop(); } diff --git a/plan2code-app/src-tauri/tests/common/mod.rs b/plan2code-app/src-tauri/tests/common/mod.rs index 939cbcb..f8723bc 100644 --- a/plan2code-app/src-tauri/tests/common/mod.rs +++ b/plan2code-app/src-tauri/tests/common/mod.rs @@ -9,10 +9,19 @@ use std::sync::Once; #[allow(dead_code)] pub fn process_alive(pid: u32) -> bool { if cfg!(windows) { - let out = Command::new("tasklist").args(["/FI", &format!("PID eq {pid}"), "/NH"]).output().unwrap(); - String::from_utf8_lossy(&out.stdout).split_whitespace().any(|word| word == pid.to_string()) + let out = Command::new("tasklist") + .args(["/FI", &format!("PID eq {pid}"), "/NH"]) + .output() + .unwrap(); + String::from_utf8_lossy(&out.stdout) + .split_whitespace() + .any(|word| word == pid.to_string()) } else { - Command::new("kill").args(["-0", &pid.to_string()]).status().map(|s| s.success()).unwrap_or(false) + Command::new("kill") + .args(["-0", &pid.to_string()]) + .status() + .map(|s| s.success()) + .unwrap_or(false) } } @@ -33,6 +42,10 @@ pub fn fake_agent() -> PathBuf { .and_then(|deps| deps.parent()) .unwrap() .join(format!("fake-agent{}", std::env::consts::EXE_SUFFIX)); - assert!(path.exists(), "{} is missing after building the fake agent", path.display()); + assert!( + path.exists(), + "{} is missing after building the fake agent", + path.display() + ); path } diff --git a/plan2code-app/src-tauri/tests/console_supervisor.rs b/plan2code-app/src-tauri/tests/console_supervisor.rs index ce71e61..8293547 100644 --- a/plan2code-app/src-tauri/tests/console_supervisor.rs +++ b/plan2code-app/src-tauri/tests/console_supervisor.rs @@ -33,13 +33,22 @@ fn setup() -> Option { return None; } let console = repo_console_dir(); - assert!(console.join("console.mjs").is_file(), "console source missing at {}", console.display()); + assert!( + console.join("console.mjs").is_file(), + "console source missing at {}", + console.display() + ); std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console); std::env::set_var("PLAN2CODE_CONSOLE_HOME", temp_dir("home")); std::env::set_var("PLAN2CODE_NO_BROWSER", "1"); // Run inside the desktop app, the agent's in-app variables would have this // console announce itself to the live window and take it over. - for name in ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"] { + for name in [ + "PLAN2CODE_IN_APP", + "PLAN2CODE_APP_ANNOUNCE", + "PLAN2CODE_APP_TOKEN", + "PLAN2CODE_CONSOLE_SID", + ] { std::env::remove_var(name); } Some(temp_dir("project")) @@ -76,7 +85,10 @@ fn starts_answers_and_stops() { assert!(until_health(&sup, true), "the console URL never answered"); sup.stop().expect("stop"); - assert!(until_health(&sup, false), "the console still answered after stop()"); + assert!( + until_health(&sup, false), + "the console still answered after stop()" + ); } #[test] @@ -87,11 +99,24 @@ fn a_killed_console_is_dead_and_restarts() { let first_sid = sup.session().sid.clone(); kill_pid(sup.session().pid); - assert!(until_health(&sup, false), "a killed console still looked alive"); + assert!( + until_health(&sup, false), + "a killed console still looked alive" + ); - assert!(sup.restart_if_dead().expect("restart"), "restart_if_dead did nothing"); - assert_eq!(sup.session().sid, first_sid, "a dead console comes back on the same session, so its page and place survive"); - assert!(until_health(&sup, true), "the restarted console never answered"); + assert!( + sup.restart_if_dead().expect("restart"), + "restart_if_dead did nothing" + ); + assert_eq!( + sup.session().sid, + first_sid, + "a dead console comes back on the same session, so its page and place survive" + ); + assert!( + until_health(&sup, true), + "the restarted console never answered" + ); sup.stop().expect("stop"); } diff --git a/plan2code-app/src-tauri/tests/pty_host.rs b/plan2code-app/src-tauri/tests/pty_host.rs index af094d0..c953191 100644 --- a/plan2code-app/src-tauri/tests/pty_host.rs +++ b/plan2code-app/src-tauri/tests/pty_host.rs @@ -97,7 +97,10 @@ fn kill_ends_a_running_step() { let started = Instant::now(); host.kill().unwrap(); host.wait().unwrap(); - assert!(started.elapsed() < Duration::from_secs(10), "kill took too long"); + assert!( + started.elapsed() < Duration::from_secs(10), + "kill took too long" + ); } /// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real @@ -113,15 +116,30 @@ fn kill_ends_a_cmd_wrapped_grandchild_too() { let _ = fs::remove_dir_all(&dir); fs::create_dir_all(&dir).unwrap(); let shim = dir.join("shim.cmd"); - fs::write(&shim, format!("@echo off\r\n\"{}\" %*\r\n", fake_agent().display())).unwrap(); + fs::write( + &shim, + format!("@echo off\r\n\"{}\" %*\r\n", fake_agent().display()), + ) + .unwrap(); let (program, args) = windows_command("shim", vec![], &dir.to_string_lossy()); - let path = format!("{};{}", dir.to_string_lossy(), std::env::var("PATH").unwrap_or_default()); + let path = format!( + "{};{}", + dir.to_string_lossy(), + std::env::var("PATH").unwrap_or_default() + ); let (tx, rx) = channel(); let host = PtyHost::start( // `cmd /c shim.cmd` is a bare name: like a real npm shim, cmd.exe // only finds it on PATH, never by the current directory alone. - StartOptions { program, args, env: vec![("PATH".to_string(), path)], cwd: None, cols: 80, rows: 24 }, + StartOptions { + program, + args, + env: vec![("PATH".to_string(), path)], + cwd: None, + cols: 80, + rows: 24, + }, move |bytes| { let _ = tx.send(bytes); }, @@ -142,7 +160,10 @@ fn kill_ends_a_cmd_wrapped_grandchild_too() { .unwrap() .parse() .expect("the grandchild's pid"); - assert!(process_alive(pid), "the grandchild should be running before kill"); + assert!( + process_alive(pid), + "the grandchild should be running before kill" + ); host.kill().unwrap(); let deadline = Instant::now() + Duration::from_secs(10); diff --git a/scripts/test-us-english.mjs b/scripts/test-us-english.mjs index 6fa128a..7a4682c 100644 --- a/scripts/test-us-english.mjs +++ b/scripts/test-us-english.mjs @@ -39,6 +39,7 @@ const CONTRACTS = [ /\bconst greyed\b/g, /\bgreyed(?=, card)/g, /^\/\/\s+greyed\b/gm, + /`greyed`/g, /\bcancelled(?=\s*:)/g, /\.cancelled\b/g, /"cancelled"/g,