Review fixes: name a slow shell, stop orphaned dashboards, bound quit stops, serialize pty tests

AI Assisted
This commit is contained in:
Seth committed 2026-12-05 14:37:34 -08:00
1 parent 0bd721fc27
commit f640f890f4
10 files changed
+412 -75

No files matched your search

+2
View File
@@ -16,6 +16,8 @@ The app is optional. The Node web console and the skills never depend on it, so
**No agent installed.** The first-run checklist and the launch card show what an agent CLI is, each built-in's install command and an **Install page** link, and a note that other agents are added under Agents. Install one, press **Check again** (the app looks at `PATH` and `agents.json` again), and Start works without restarting the app.
**Started from the Dock, Finder or a desktop entry (macOS, Linux).** The app asks your login shell for its `PATH` (up to 5 s), and reads your interactive config too (`~/.zshrc`, up to 10 s) only when Node or every agent is still missing, and on **Check again**. So an agent installed by npm under nvm in `~/.zshrc` shows up at start only when no other agent was already found; press **Check again** to see it. Every shell the app starts this way has `PLAN2CODE_RESOLVING_ENVIRONMENT=1` set, so a slow or terminal-only line in a startup file can skip itself: `[ -n "$PLAN2CODE_RESOLVING_ENVIRONMENT" ] || eval "$(ssh-agent)"`. A shell that runs past its limit is named in the Node check, which offers **Check again** instead of sending you to install Node.
**Taskbar signal.** The console page tells the app when it is busy, your move, or needs attention (the same states as its tab icon), and the app shows it:
| System | Your move | Needs attention |
+7 -2
View File
@@ -48,8 +48,13 @@ file directly after checking it against the release's checksum list.
Node and the agent are still found. With Node and an agent on the login PATH instead
(Homebrew, or nvm in `~/.zprofile`), `~/.zshrc` is read only on Check again, not at start;
with Homebrew's Node but the agent installed by npm under nvm in `~/.zshrc`, the agent is
still found at start. A hung `~/.zprofile` delays the start by 3 s at most and a hung
`~/.zshrc` by 2 s; only a slow `~/.zprofile` followed by a hung `~/.zshrc` reaches 5 s
still found at start. The window opens at once either way; a hung `~/.zprofile` is given
up on after 5 s and a hung `~/.zshrc` after 10 s, and with Node found nowhere the Node
check names the shell that timed out and offers Check again, not the install message
- [ ] macOS and Linux: `PLAN2CODE_RESOLVING_ENVIRONMENT` is `1` inside the shells that lookup
starts (a `~/.zshrc` line that writes it to a file shows it), and unset in the agent's terminal
- [ ] macOS and Linux: after the app is force quit (Activity Monitor, or `kill -9`) with a dashboard
showing, `ps -Ao pid,command | grep server.mjs` lists no console two minutes later
- [ ] macOS and Linux: when the installer puts the `plan2code` command in a folder that is not on
PATH, its closing steps say so and name the line to add and the startup file to add it to;
done as written, `plan2code` runs in a new terminal
@@ -5,9 +5,9 @@
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use std::time::{Duration, Instant};
use serde::Serialize;
@@ -620,16 +620,59 @@ impl StopError {
}
}
/// How long one `console.mjs stop` may run. Its own checks give a busy server
/// a 1.5 s and then a 5 s look (`cmd-small.mjs`), so this sits above both; past
/// it the stop is ended and reported, so a quit never hangs on one console.
const STOP_TIMEOUT: Duration = Duration::from_secs(10);
fn run_stop(console_dir: &Path, project_dir: &Path, sid: &str) -> Result<(), StopError> {
let output = node_command(console_dir)
run_stop_within(console_dir, project_dir, sid, STOP_TIMEOUT)
}
fn run_stop_within(
console_dir: &Path,
project_dir: &Path,
sid: &str,
timeout: Duration,
) -> Result<(), StopError> {
let mut child = node_command(console_dir)
.args(stop_args(sid))
.current_dir(project_dir)
.output()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| StopError::NotRun(err(e)))?;
if !output.status.success() {
// Read on a thread of its own, so a full pipe never blocks the stop.
let stderr = child.stderr.take().map(|mut pipe| {
std::thread::spawn(move || {
let mut text = String::new();
let _ = pipe.read_to_string(&mut text);
text
})
});
let deadline = Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)),
waited => {
let _ = child.kill();
let _ = child.wait();
return Err(StopError::Failed(match waited {
Err(e) => format!("console stop failed: {e}"),
_ => format!("console stop took over {timeout:?} and was ended"),
}));
}
}
};
if !status.success() {
let text = stderr
.and_then(|reader| reader.join().ok())
.unwrap_or_default();
return Err(StopError::Failed(format!(
"console stop failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
text.trim()
)));
}
Ok(())
@@ -896,6 +939,24 @@ mod tests {
assert_eq!(*stopped.lock().unwrap(), vec!["s1"]);
}
#[test]
fn a_stop_that_hangs_is_ended_at_its_deadline() {
// A console whose `stop` never finishes: the quit must not wait on it.
let dir = std::env::temp_dir().join(format!("p2c-hung-stop-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("console.mjs"), "setInterval(() => {}, 1000);\n").unwrap();
let started = Instant::now();
let result = run_stop_within(&dir, &dir, "s1", Duration::from_millis(800));
let took = started.elapsed();
let _ = std::fs::remove_dir_all(&dir);
match result {
Err(StopError::Failed(message)) => assert!(message.contains("took over"), "{message}"),
Err(StopError::NotRun(message)) => panic!("node did not start: {message}"),
Ok(()) => panic!("a stop that never finished passed"),
}
assert!(took < Duration::from_secs(3), "took {took:?}");
}
#[cfg(unix)]
#[test]
fn a_console_call_runs_in_a_process_group_of_its_own() {
+73 -22
View File
@@ -95,11 +95,15 @@ struct NodeReport {
/// Run the Node check off the main thread and publish its result: store it,
/// tell the page, and on a failure show the dialog and end the app, as
/// `main()` did before the window existed (FR-13).
/// `main()` did before the window existed (FR-13). When the person's shell
/// timed out while asked for its PATH, Node may well be installed, so that
/// dialog offers Check again, which asks the shell once more.
fn spawn_node_check(app: tauri::AppHandle) {
std::thread::spawn(move || {
std::thread::spawn(move || loop {
let status = node_check::check_node();
let problem = node_check::problem_message(&status);
let shell_timed_out =
status == node_check::NodeStatus::Missing && node_check::shell_timed_out().is_some();
let version = match &status {
node_check::NodeStatus::Ok(version) => Some(version.clone()),
_ => None,
@@ -117,23 +121,42 @@ fn spawn_node_check(app: tauri::AppHandle) {
*slot = report.clone();
}
let _ = app.emit("node-status", &report);
if let Some(message) = problem {
// The first button is the default: Open nodejs.org, then the app ends either way.
let open_site = app
let Some(message) = problem else {
return;
};
if shell_timed_out {
// Check again is the default; Quit ends the app.
let again = app
.dialog()
.message(&message)
.title("Plan2Code needs Node.js")
.kind(MessageDialogKind::Error)
.title("Plan2Code could not look for Node.js")
.kind(MessageDialogKind::Warning)
.buttons(MessageDialogButtons::OkCancelCustom(
"Open nodejs.org".to_string(),
"Check again".to_string(),
"Quit".to_string(),
))
.blocking_show();
if open_site {
let _ = open_url("https://nodejs.org");
if again {
node_check::refresh_path();
continue;
}
std::process::exit(1);
}
// The first button is the default: Open nodejs.org, then the app ends either way.
let open_site = app
.dialog()
.message(&message)
.title("Plan2Code needs Node.js")
.kind(MessageDialogKind::Error)
.buttons(MessageDialogButtons::OkCancelCustom(
"Open nodejs.org".to_string(),
"Quit".to_string(),
))
.blocking_show();
if open_site {
let _ = open_url("https://nodejs.org");
}
std::process::exit(1);
});
}
@@ -540,7 +563,10 @@ fn refuse_while_looping(state: &AppState, what: &str) -> Result<(), String> {
Ok(())
}
#[tauri::command]
// Async, like the other commands that may wait on the PATH lookup: the first start
// can wait for the person's shell (node_check::resolved_path), and must not freeze
// the window meanwhile.
#[tauri::command(async)]
#[allow(clippy::too_many_arguments)] // one argument per key the frontend passes to invoke
fn agent_start(
app: tauri::AppHandle,
@@ -583,7 +609,7 @@ fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(),
}
}
#[tauri::command]
#[tauri::command(async)]
fn agent_restart(state: State<'_, AppState>) -> Result<(), String> {
refuse_while_looping(&state, "agent")?;
current_agent(&state)
@@ -831,7 +857,7 @@ fn quit_app(app: &tauri::AppHandle) {
shutdown(app);
if let Some(plan) = restart {
if let Err(error) = spawn_restart(&plan) {
eprintln!("plan2code: restart failed: {error}");
log::line(&format!("plan2code: restart failed: {error}"));
}
}
app.exit(0);
@@ -874,11 +900,17 @@ fn shutdown_with(state: &AppState) {
// After `shutdown_with`, stops every announced console still recorded, each
// before returning. On Windows the agent's Job Object ends those consoles.
/// The stops run side by side, each on its own thread and each bounded by the
/// console stop's deadline, so a quit waits for the slowest one, not their sum.
#[cfg(unix)]
fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) {
for sid in state.announced.take_all() {
stop_sid(&sid);
}
fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str) + Sync) {
let sids = state.announced.take_all();
let stop_sid = &stop_sid;
std::thread::scope(|scope| {
for sid in &sids {
scope.spawn(move || stop_sid(sid));
}
});
}
// Waits for the threads an agent's end or a new page started (macOS and Linux)
@@ -2462,11 +2494,10 @@ mod tests {
shutdown_with(&state);
stop_other_announced(&state, stop);
assert_eq!(
*stopped.lock().unwrap(),
vec!["s1", "s2"],
"both, before returning"
);
// Side by side, so in no set order.
let mut both = stopped.lock().unwrap().clone();
both.sort();
assert_eq!(both, vec!["s1", "s2"], "both, before returning");
shutdown_with(&state);
stop_other_announced(&state, stop);
@@ -2477,6 +2508,26 @@ mod tests {
);
}
#[cfg(unix)]
#[test]
fn the_quit_stops_announced_consoles_side_by_side() {
// Each stop runs `node`: one after another, three slow ones would cost
// the quit three times as long.
let state = state_for("project-a");
for sid in ["s1", "s2", "s3"] {
state.announced.record(sid);
}
let started = std::time::Instant::now();
stop_other_announced(&state, |_| {
std::thread::sleep(std::time::Duration::from_millis(600))
});
let took = started.elapsed();
assert!(
took < std::time::Duration::from_millis(1500),
"took {took:?}, not side by side"
);
}
#[cfg(unix)]
#[test]
fn shutdown_never_stops_the_followed_console_a_second_time() {
+202 -42
View File
@@ -88,7 +88,7 @@ fn node_override_dir(args: &[String]) -> Option<String> {
/// because its terminal-only lines can start daemons that leave the shell's
/// process group, out of reach of the kill.
#[cfg(unix)]
fn login_shell_path(args: &[String], inherited: &str, always_interactive: bool) -> Option<String> {
fn login_shell_path(args: &[String], inherited: &str, always_interactive: bool) -> ShellLookup {
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
let agents = crate::agents::path_agent_commands();
login_shell_path_for(
@@ -110,19 +110,46 @@ fn login_shell_path_for(
inherited: &str,
agents: &[String],
always_interactive: bool,
) -> Option<String> {
) -> ShellLookup {
let known = match node_override_dir(args) {
Some(dir) => format!("{dir}:{inherited}"),
None => inherited.to_string(),
};
path_from_shell(shell, &known, agents, always_interactive)
shell_lookup(shell, &known, agents, always_interactive, SHELL_BUDGET)
}
/// How long the login run, and the interactive config run, may each take.
#[cfg(unix)]
const LOGIN_PATH_TIMEOUT: Duration = Duration::from_secs(3);
#[derive(Clone, Copy, Debug)]
struct ShellBudget {
login: Duration,
interactive: Duration,
}
/// Generous, since the lookup runs on a background thread after the window
/// opens: a slow but working profile (nvm and a prompt theme in `.zshrc` on a
/// cold start can take seconds) must not read as Node missing. Only a hung
/// profile waits the budget out, and the Node check then says it timed out.
#[cfg(unix)]
const INTERACTIVE_PATH_TIMEOUT: Duration = Duration::from_secs(2);
const SHELL_BUDGET: ShellBudget = ShellBudget {
login: Duration::from_secs(5),
interactive: Duration::from_secs(10),
};
/// Set in the environment of every shell the lookup starts, so a startup
/// file can skip lines that only make sense in a terminal (a daemon, a
/// prompt theme): `[ -n "$PLAN2CODE_RESOLVING_ENVIRONMENT" ] || ...`.
#[cfg(unix)]
pub const RESOLVING_ENV_VAR: &str = "PLAN2CODE_RESOLVING_ENVIRONMENT";
/// What the shell lookup found: the PATH, if any, and how long the shell ran
/// before it was given up on, if it never answered.
#[cfg(unix)]
#[derive(Clone, Debug, PartialEq, Eq)]
struct ShellLookup {
path: Option<String>,
timed_out: Option<Duration>,
}
/// The most of a shell's output kept while looking for the markers.
#[cfg(unix)]
@@ -157,20 +184,21 @@ fn kill_process_group(child: &mut std::process::Child) {
/// so it is used whole; if it fails, the login answer is kept. bash reads its
/// profile files either way, not `.bashrc`, as Terminal's login shells do.
/// `inherited` is this app's PATH plus any `--node` folder, `agents` the agent
/// commands to look for (an empty list requires none), and
/// `always_interactive` is Check again.
/// commands to look for (an empty list requires none), `always_interactive`
/// is Check again, and `budget` how long each run may take.
#[cfg(unix)]
fn path_from_shell(
fn shell_lookup(
shell: &Path,
inherited: &str,
agents: &[String],
always_interactive: bool,
) -> Option<String> {
budget: ShellBudget,
) -> ShellLookup {
let started = Instant::now();
let login = shell_path(shell, false, LOGIN_PATH_TIMEOUT);
let login = shell_path(shell, false, budget.login);
// `shell_path` returns at its limit only for a shell that never answered;
// one that fails returns well before it.
let timed_out = login.is_none() && started.elapsed() >= LOGIN_PATH_TIMEOUT;
let timed_out = login.is_none() && started.elapsed() >= budget.login;
let found = |program: &str| {
login.as_deref().is_some_and(|p| holds_program(p, program))
|| holds_program(inherited, program)
@@ -181,32 +209,45 @@ fn path_from_shell(
let ready = found("node") && (agents.is_empty() || agents.iter().any(|agent| found(agent)));
if is_csh(shell) || timed_out || (ready && !always_interactive) {
if login.is_none() {
eprintln!(
crate::log::line(&format!(
"plan2code: {} gave no PATH from its login config (it {}); using the PATH this app started with",
shell.display(),
if timed_out {
format!("took over {LOGIN_PATH_TIMEOUT:?}")
format!("took over {:?}", budget.login)
} else {
"failed".to_string()
}
);
));
}
return login;
return ShellLookup {
path: login,
timed_out: timed_out.then_some(budget.login),
};
}
let found = shell_path(shell, true, INTERACTIVE_PATH_TIMEOUT);
let asked = Instant::now();
let found = shell_path(shell, true, budget.interactive);
// Like the login run: only a shell that never answered reaches the limit.
let interactive_timed_out = found.is_none() && asked.elapsed() >= budget.interactive;
if found.is_none() {
eprintln!(
"plan2code: {} gave no PATH with its interactive config (it failed or took over {:?}); using {}",
crate::log::line(&format!(
"plan2code: {} gave no PATH with its interactive config (it {}); using {}",
shell.display(),
INTERACTIVE_PATH_TIMEOUT,
if interactive_timed_out {
format!("took over {:?}", budget.interactive)
} else {
"failed".to_string()
},
if login.is_some() {
"its login PATH"
} else {
"the PATH this app started with"
}
);
));
}
ShellLookup {
path: found.or(login),
timed_out: interactive_timed_out.then_some(budget.interactive),
}
found.or(login)
}
/// Whether one of `path`'s absolute folders holds an executable regular file
@@ -273,7 +314,9 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<Stri
}
cmd.arg("-c").arg(&command).stdin(Stdio::null());
}
cmd.stdout(Stdio::piped()).stderr(Stdio::null());
cmd.env(RESOLVING_ENV_VAR, "1")
.stdout(Stdio::piped())
.stderr(Stdio::null());
// SAFETY: setsid(2) is async-signal-safe and touches no memory of this
// process, so it may run between fork and exec. The new session has no
// controlling terminal, so an interactive shell cannot take the launcher's
@@ -401,15 +444,33 @@ fn shell_name(shell: &str) -> String {
}
}
static RESOLVED_PATH: Mutex<Option<String>> = Mutex::new(None);
/// The worked-out PATH, and whether the person's shell timed out while it was
/// asked for its own (macOS and Linux; never on Windows).
#[derive(Clone, Debug)]
struct Resolved {
path: String,
shell_timed_out: Option<std::time::Duration>,
}
static RESOLVED: Mutex<Option<Resolved>> = Mutex::new(None);
fn resolved() -> Resolved {
let mut cached = RESOLVED.lock().unwrap_or_else(|e| e.into_inner());
cached.get_or_insert_with(|| build_path(false)).clone()
}
/// The PATH every process this app spawns should run with: an explicit
/// `--node`'s directory first, then (macOS and Linux) the login shell's own
/// PATH, then this process's own PATH, each included only once. Worked out
/// once per launch, and again only on `refresh_path`.
pub fn resolved_path() -> String {
let mut cached = RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner());
cached.get_or_insert_with(|| build_path(false)).clone()
resolved().path
}
/// How long the person's shell ran before the PATH lookup gave up on it, when
/// it never answered: the Node check then says so instead of "not found".
pub fn shell_timed_out() -> Option<std::time::Duration> {
resolved().shell_timed_out
}
/// Work the PATH out again, for "Check again" after an agent CLI was
@@ -419,10 +480,10 @@ pub fn resolved_path() -> String {
/// PATH has never had.
pub fn refresh_path() {
let fresh = build_path(true);
*RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh);
*RESOLVED.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh);
}
fn build_path(fresh: bool) -> String {
fn build_path(fresh: bool) -> Resolved {
let args: Vec<String> = std::env::args().collect();
let inherited = std::env::var("PATH").unwrap_or_default();
let mut parts = Vec::new();
@@ -432,9 +493,13 @@ fn build_path(fresh: bool) -> String {
// A refresh is Check again, usually right after an install edited the
// shell's interactive config, so it always reads that config too.
#[cfg(unix)]
if let Some(login) = login_shell_path(&args, &inherited, fresh) {
parts.push(login);
}
let shell_timed_out = {
let lookup = login_shell_path(&args, &inherited, fresh);
parts.extend(lookup.path);
lookup.timed_out
};
#[cfg(not(unix))]
let shell_timed_out = None;
// This process's PATH is whatever its parent had, which is stale when
// that parent (a terminal, the launcher) started before an installer
// added a folder: a custom agent was then offered only some of the time.
@@ -453,7 +518,10 @@ fn build_path(fresh: bool) -> String {
if !fresh {
parts.extend(saved);
}
parts.join(if cfg!(windows) { ";" } else { ":" })
Resolved {
path: parts.join(if cfg!(windows) { ";" } else { ":" }),
shell_timed_out,
}
}
/// The system then the user PATH as saved in the registry, with `%NAME%`
@@ -567,12 +635,31 @@ pub fn node_binary_path() -> Option<String> {
/// The plain message shown when the check fails; `None` when Node is fine.
pub fn problem_message(status: &NodeStatus) -> Option<String> {
problem_message_from(status, &path_source_label())
problem_message_with(status, &path_source_label(), shell_timed_out())
}
/// `problem_message` with the PATH source named by the caller, so a test need
/// not depend on this machine's shell.
pub fn problem_message_from(status: &NodeStatus, source: &str) -> Option<String> {
problem_message_with(status, source, None)
}
/// `problem_message_from`, told whether the shell timed out. A Node that was
/// not found while the shell never answered may well be installed, so that
/// message names the slow shell instead of sending the person to install Node.
pub fn problem_message_with(
status: &NodeStatus,
source: &str,
shell_timed_out: Option<std::time::Duration>,
) -> Option<String> {
if let (NodeStatus::Missing, Some(limit)) = (status, shell_timed_out) {
return Some(format!(
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and could not look for it: {source} took over {} s to report its PATH.
If Node.js is installed, make your shell's startup files quicker (a line can check PLAN2CODE_RESOLVING_ENVIRONMENT to skip itself here), then choose Check again.",
limit.as_secs()
));
}
let advice = format!(
"Install the current LTS release from https://nodejs.org and start Plan2Code again.
@@ -713,6 +800,26 @@ mod tests {
assert!(problem_message_from(&NodeStatus::Ok("v20.0.0".into()), "fish").is_none());
}
#[test]
fn a_shell_that_timed_out_is_named_instead_of_a_missing_node() {
let limit = Some(std::time::Duration::from_secs(10));
let text = problem_message_with(&NodeStatus::Missing, "zsh", limit).unwrap();
assert!(text.contains("zsh took over 10 s"), "{text}");
assert!(text.contains("Check again"), "{text}");
assert!(
text.contains("PLAN2CODE_RESOLVING_ENVIRONMENT"),
"names the variable a startup file can check: {text}"
);
assert!(!text.contains("it was not found"), "{text}");
// A Node that was found, too old or fine, says what it always said.
let old = NodeStatus::TooOld("v16.0.0".into());
assert_eq!(
problem_message_with(&old, "zsh", limit),
problem_message_from(&old, "zsh")
);
assert!(problem_message_with(&NodeStatus::Ok("v20.0.0".into()), "zsh", limit).is_none());
}
#[test]
fn shell_names_come_from_the_last_path_part() {
assert_eq!(shell_name("/usr/bin/fish"), "fish");
@@ -1167,15 +1274,19 @@ mod tests {
);
let started = std::time::Instant::now();
// No node on either PATH, so the interactive config is asked for and
// hangs: the login answer it was asked after is kept.
// hangs: the login answer it was asked after is kept, and the lookup
// says how long the shell was given.
assert_eq!(
path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(),
Some("/login/bin")
shell_lookup(&shell, "/usr/bin", NO_AGENTS, false, TEST_BUDGET),
ShellLookup {
path: Some("/login/bin".to_string()),
timed_out: Some(TEST_BUDGET.interactive),
}
);
// A quick login answer, then the interactive timeout: room for a busy
// runner, and far short of the 30 s sleep the hung config would take.
assert!(
started.elapsed() < INTERACTIVE_PATH_TIMEOUT + std::time::Duration::from_millis(1400),
started.elapsed() < TEST_BUDGET.interactive + std::time::Duration::from_millis(1400),
"took {:?}",
started.elapsed()
);
@@ -1185,6 +1296,40 @@ mod tests {
#[cfg(unix)]
const NO_AGENTS: &[String] = &[];
/// Short limits for the tests that wait one out on a hung shell.
#[cfg(unix)]
const TEST_BUDGET: ShellBudget = ShellBudget {
login: std::time::Duration::from_secs(2),
interactive: std::time::Duration::from_secs(2),
};
/// The PATH the lookup finds with the app's own limits.
#[cfg(unix)]
fn path_from_shell(
shell: &std::path::Path,
inherited: &str,
agents: &[String],
always_interactive: bool,
) -> Option<String> {
shell_lookup(shell, inherited, agents, always_interactive, SHELL_BUDGET).path
}
#[cfg(unix)]
#[test]
fn every_shell_the_lookup_starts_is_told_it_is_being_asked_for_its_path() {
let dir = scratch("marker");
// The startup file a person writes: it reads the variable to decide.
let shell = fake_shell(
&dir,
"zsh",
&format!("PATH=/marker/${RESOLVING_ENV_VAR}\neval \"$last\""),
);
assert_eq!(
path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(),
Some("/marker/1")
);
}
/// A folder in `dir` holding an executable file named `node`.
#[cfg(unix)]
fn node_in(dir: &std::path::Path, folder: &str) -> String {
@@ -1431,11 +1576,20 @@ mod tests {
let _ = std::fs::remove_file(&pids);
let started = std::time::Instant::now();
assert_eq!(
path_from_shell(&shell, "/usr/bin", NO_AGENTS, always_interactive),
None
shell_lookup(
&shell,
"/usr/bin",
NO_AGENTS,
always_interactive,
TEST_BUDGET
),
ShellLookup {
path: None,
timed_out: Some(TEST_BUDGET.login),
}
);
assert!(
started.elapsed() < LOGIN_PATH_TIMEOUT + std::time::Duration::from_millis(1500),
started.elapsed() < TEST_BUDGET.login + std::time::Duration::from_millis(1500),
"took {:?}",
started.elapsed()
);
@@ -1463,13 +1617,17 @@ mod tests {
let args = vec!["plan2code".to_string()];
// At start, node on the login PATH is enough.
assert_eq!(
login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, false).as_deref(),
login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, false)
.path
.as_deref(),
Some(login.as_str())
);
assert!(!ran.exists(), "the interactive config ran at start");
// Check again reads it anyway: an install has usually just edited it.
assert_eq!(
login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, true).as_deref(),
login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, true)
.path
.as_deref(),
Some(interactive.as_str())
);
assert!(
@@ -1493,7 +1651,9 @@ mod tests {
vec!["plan2code".to_string(), format!("--node={given}/node")],
] {
assert_eq!(
login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, false).as_deref(),
login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, false)
.path
.as_deref(),
Some("/usr/bin")
);
assert!(!ran.exists(), "the interactive config ran: {args:?}");
+13 -1
View File
@@ -4,7 +4,7 @@
use std::path::PathBuf;
use std::sync::mpsc::{channel, Receiver, RecvTimeoutError};
use std::sync::{Arc, Mutex, Once};
use std::sync::{Arc, Mutex, MutexGuard, Once};
use std::time::{Duration, Instant};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
@@ -27,10 +27,21 @@ struct Harness {
states: Vec<AgentSnapshot>,
/// How many of `states` `wait_state` has already looked at.
cursor: usize,
/// Held for the whole test, and dropped last: see `PTY_LOCK`.
_pty: MutexGuard<'static, ()>,
}
/// One test at a time opens pseudo-terminals here. Run side by side, macOS
/// `openpty` fails now and then (`Unknown error: -6`, a different test each
/// run), which reads as a broken agent start. Every test takes it through
/// `Harness::new`; a panicked test leaves it poisoned, which is harmless.
static PTY_LOCK: Mutex<()> = Mutex::new(());
impl Harness {
fn new() -> Harness {
let pty = PTY_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
static BIN: Once = Once::new();
BIN.call_once(|| std::env::set_var(AGENT_BIN_ENV, common::fake_agent()));
let (tx, rx) = channel();
@@ -44,6 +55,7 @@ impl Harness {
seen: String::new(),
states: Vec::new(),
cursor: 0,
_pty: pty,
}
}