mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Harden the shared console install, launcher, Loop staging, spec state and prompts
AI Assisted
This commit is contained in:
1 parent
120c259d9c
commit
3ee96834bf
130 files changed
+5988
-1434
No files matched your search
@@ -1,3 +1,10 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["src-tauri", "fake-agent"]
|
||||
|
||||
# Release builds: whole-program optimization, no symbols in the shipped
|
||||
# binary, and a panic ends the process instead of unwinding.
|
||||
[profile.release]
|
||||
lto = true
|
||||
strip = true
|
||||
panic = "abort"
|
||||
@@ -50,6 +50,6 @@ cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
```
|
||||
|
||||
The `app` workflow runs all three on Windows, macOS and Linux, and fails on any rustfmt difference or clippy warning, so run them before pushing, not only `cargo test`. Clippy on one system does not see code for another: an import used only inside a `#[cfg(windows)]` test is clean on Windows and an unused-import error on macOS and Linux, so put such imports inside the `cfg`'d item.
|
||||
The `app` workflow runs all three on Ubuntu for every pull request and push to main (and on Windows and macOS too for a manual run or a pull request labeled `full-matrix`), and fails on any rustfmt difference or clippy warning, so run them before pushing, not only `cargo test`. Clippy on one system does not see code for another: an import used only inside a `#[cfg(windows)]` test is clean on Windows and an unused-import error on macOS and Linux, so put such imports inside the `cfg`'d item.
|
||||
|
||||
Real Claude, Devin and Codex are never started by a test. The real window and terminal panel are checked by hand before each release.
|
||||
@@ -414,13 +414,19 @@ fn npm_global_bin_uncached(windows: bool) -> Option<String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let child = std::process::Command::new("npm")
|
||||
let mut command = std::process::Command::new("npm");
|
||||
command
|
||||
.args(["config", "get", "prefix"])
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.env("PATH", crate::node_check::resolved_path())
|
||||
.spawn();
|
||||
.env("PATH", crate::node_check::resolved_path());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
}
|
||||
let child = command.spawn();
|
||||
let child = match child {
|
||||
Ok(child) => child,
|
||||
Err(_) => return None,
|
||||
|
||||
@@ -37,6 +37,61 @@ pub struct ConsoleSession {
|
||||
pub const OLD_CONSOLE: &str =
|
||||
"The installed Plan2Code console is too old to show inside the app. Press Update skills, then try again.";
|
||||
|
||||
/// A supervisor's health check, copied out of it (`ConsoleSupervisor::probe`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ConsoleProbe {
|
||||
url: String,
|
||||
stopped: bool,
|
||||
}
|
||||
|
||||
impl ConsoleProbe {
|
||||
/// Was the supervisor stopped on purpose when the probe was taken.
|
||||
pub fn stopped(&self) -> bool {
|
||||
self.stopped
|
||||
}
|
||||
|
||||
/// A GET on the session URL: any HTTP answer means the server is alive.
|
||||
pub fn health(&self) -> bool {
|
||||
self.health_within(HEALTH_TIMEOUT)
|
||||
}
|
||||
|
||||
/// `health`, then once more with the longer timeout: a machine busy with
|
||||
/// a test run can keep a healthy server from answering inside the first.
|
||||
pub fn alive(&self) -> bool {
|
||||
self.health() || self.health_within(BUSY_HEALTH_TIMEOUT)
|
||||
}
|
||||
|
||||
fn health_within(&self, timeout: Duration) -> bool {
|
||||
if self.stopped {
|
||||
return false;
|
||||
}
|
||||
let Ok((host, port, path)) = split_url(&self.url) else {
|
||||
return false;
|
||||
};
|
||||
let Some(addr) = (host.as_str(), port)
|
||||
.to_socket_addrs()
|
||||
.ok()
|
||||
.and_then(|mut a| a.next())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) else {
|
||||
return false;
|
||||
};
|
||||
let _ = stream.set_read_timeout(Some(timeout));
|
||||
let _ = stream.set_write_timeout(Some(timeout));
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
|
||||
if stream.write_all(request.as_bytes()).is_err() {
|
||||
return false;
|
||||
}
|
||||
let mut status = [0u8; 64];
|
||||
match stream.read(&mut status) {
|
||||
Ok(n) => String::from_utf8_lossy(&status[..n]).starts_with("HTTP/"),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One supervised console for one project folder.
|
||||
pub struct ConsoleSupervisor {
|
||||
console_dir: PathBuf,
|
||||
@@ -273,8 +328,10 @@ impl ConsoleSupervisor {
|
||||
|
||||
/// The console moved to another address or session (an announced page that
|
||||
/// is not the one this supervisor opened): health, stop and the restart
|
||||
/// brief follow it from now on.
|
||||
/// brief follow it from now on. An announced page is a running console, so
|
||||
/// a supervisor the person stopped is no longer stopped.
|
||||
pub fn follow(&mut self, url: &str, sid: &str) {
|
||||
self.stopped = false;
|
||||
if self.session.url == url && self.session.sid == sid {
|
||||
return;
|
||||
}
|
||||
@@ -296,32 +353,16 @@ impl ConsoleSupervisor {
|
||||
}
|
||||
|
||||
fn health_within(&self, timeout: Duration) -> bool {
|
||||
if self.stopped {
|
||||
return false;
|
||||
}
|
||||
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())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) else {
|
||||
return false;
|
||||
};
|
||||
let _ = stream.set_read_timeout(Some(timeout));
|
||||
let _ = stream.set_write_timeout(Some(timeout));
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
|
||||
if stream.write_all(request.as_bytes()).is_err() {
|
||||
return false;
|
||||
}
|
||||
let mut status = [0u8; 64];
|
||||
match stream.read(&mut status) {
|
||||
Ok(n) => String::from_utf8_lossy(&status[..n]).starts_with("HTTP/"),
|
||||
Err(_) => false,
|
||||
self.probe().health_within(timeout)
|
||||
}
|
||||
|
||||
/// What a health check needs, copied out, so a caller can check with the
|
||||
/// app's console lock released: the announce thread takes that lock to
|
||||
/// follow a new page, and a check can wait seconds on a busy machine.
|
||||
pub fn probe(&self) -> ConsoleProbe {
|
||||
ConsoleProbe {
|
||||
url: self.session.url.clone(),
|
||||
stopped: self.stopped,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,9 +370,17 @@ impl ConsoleSupervisor {
|
||||
/// when a new session was started. Never loops: the caller (the bar) asks
|
||||
/// and shows the outcome.
|
||||
pub fn restart_if_dead(&mut self) -> Result<bool, String> {
|
||||
if self.stopped || self.health() || self.health_within(BUSY_HEALTH_TIMEOUT) {
|
||||
if self.stopped || self.probe().alive() {
|
||||
return Ok(false);
|
||||
}
|
||||
self.reopen()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A fresh `open` on the same session (a new one only when it is gone from
|
||||
/// disk), with no health check: for a console the caller already found
|
||||
/// dead, or one the person stopped and now starts again. Clears `stopped`.
|
||||
pub fn reopen(&mut self) -> Result<(), String> {
|
||||
let sid = self.session.sid.clone();
|
||||
let on_disk = session_on_disk(&sid);
|
||||
let (console_dir, project_dir, embed_origin, workflow) = (
|
||||
@@ -344,7 +393,7 @@ impl ConsoleSupervisor {
|
||||
Self::open_session(console_dir, project_dir, embed_origin, resume, workflow)
|
||||
})?;
|
||||
self.stopped = false;
|
||||
Ok(true)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `console.mjs stop --session <sid> --force`: the console's own orderly
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! The commit step of the Implementation Loop: its order, and nothing else.
|
||||
//!
|
||||
//! A passed phase goes through five calls, in this order: `prepare` (everything
|
||||
//! that can fail, before any file is touched), `stage_and_check` (stage, then
|
||||
//! refuse a secret or an oversized file), `mark` (save the files, mark the
|
||||
//! that can fail, before any file is touched), `stage_and_check` (stage the
|
||||
//! files the phase changed, then refuse a secret or an oversized file), `mark` (save the files, mark the
|
||||
//! phase done, write the approval line), `commit` (stage the marked files and
|
||||
//! commit) and, when the commit fails, `undo` (put the saved text back). The
|
||||
//! driver decides what to say and where to stop; this module only does the work
|
||||
@@ -252,6 +252,22 @@ pub fn too_big(file: &StagedFile) -> bool {
|
||||
file.bytes > MAX_STAGED_BYTES
|
||||
}
|
||||
|
||||
/// A staged file's size from its `symlink_metadata` result: a file that is
|
||||
/// gone is a deletion and counts as 0 bytes; any other error means the size is
|
||||
/// not known, so the gate refuses it (`None`) rather than counting 0.
|
||||
pub fn staged_size(meta: std::io::Result<u64>) -> Option<u64> {
|
||||
match meta {
|
||||
Ok(bytes) => Some(bytes),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(0),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a stop says when the files this phase changed cannot be listed, so the
|
||||
/// loop cannot tell its own files from the person's.
|
||||
pub const OWN_FILES_UNKNOWN: &str =
|
||||
"the files this phase changed could not be listed, so nothing was staged";
|
||||
|
||||
/// Staged files the loop refuses to commit, by their names.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StagedProblem {
|
||||
@@ -270,11 +286,47 @@ pub enum StageError {
|
||||
Problem(StagedProblem),
|
||||
}
|
||||
|
||||
/// Stage everything and look at the list before anything is marked. Any
|
||||
/// secret-looking or oversized file takes everything out of the index again and
|
||||
/// Stage the files this phase changed and look at the list before anything is
|
||||
/// marked. `baseline` is what `git status` listed when the phase began (the
|
||||
/// person's own changes, left out); `None` when it could not be read. The
|
||||
/// phase's files are what `git status` lists now less the baseline, staged by
|
||||
/// name, never with `git add -A`. A baseline or a list that cannot be read
|
||||
/// stops here with nothing staged. Any secret-looking or oversized file, or
|
||||
/// one whose size cannot be read, takes everything out of the index again and
|
||||
/// returns every offending path.
|
||||
pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
|
||||
let added = loop_tools::git_add_all(project);
|
||||
pub fn stage_and_check(project: &Path, baseline: Option<&[String]>) -> Result<(), StageError> {
|
||||
let unknown = |output: String| {
|
||||
StageError::Add(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
first_line: OWN_FILES_UNKNOWN.to_string(),
|
||||
output,
|
||||
})
|
||||
};
|
||||
let baseline = baseline
|
||||
.ok_or_else(|| unknown("git status could not be read when the phase began".to_string()))?;
|
||||
// Changed names are relative to the repository's top folder.
|
||||
let top = loop_tools::git_toplevel(project)
|
||||
.ok_or_else(|| unknown("the repository's top folder could not be found".to_string()))?;
|
||||
// A list over the cap keeps its own advice (add generated folders to
|
||||
// .gitignore) as the stop line; any other failure is the generic one.
|
||||
let changed = loop_tools::git_changed(project).map_err(|output| {
|
||||
if output == loop_tools::STAGED_TOO_LONG {
|
||||
StageError::Add(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
first_line: output.clone(),
|
||||
output,
|
||||
})
|
||||
} else {
|
||||
unknown(output)
|
||||
}
|
||||
})?;
|
||||
// A set, not a slice scan: with every untracked file listed, a big folder makes both lists long.
|
||||
let before: std::collections::HashSet<&str> = baseline.iter().map(String::as_str).collect();
|
||||
let own: Vec<loop_tools::GitPath> = changed
|
||||
.into_iter()
|
||||
.filter(|path| !before.contains(path.shown.as_str()))
|
||||
.collect();
|
||||
let added = loop_tools::git_add_listed(&top, &own);
|
||||
if !added.ok {
|
||||
return Err(StageError::Add(CommitFailure {
|
||||
stage: Stage::Add,
|
||||
@@ -289,20 +341,25 @@ pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
|
||||
output,
|
||||
})
|
||||
})?;
|
||||
// Staged names are relative to the repository's top folder.
|
||||
let top = loop_tools::git_toplevel(project).unwrap_or_else(|| project.to_path_buf());
|
||||
let mut secrets = false;
|
||||
let mut big = false;
|
||||
let mut unreadable = false;
|
||||
let mut files = Vec::new();
|
||||
for path in staged {
|
||||
// A deleted file is gone from the tree: it counts as 0 bytes.
|
||||
let bytes = std::fs::symlink_metadata(top.join(&path)).map_or(0, |m| m.len());
|
||||
let file = StagedFile { path, bytes };
|
||||
// Sized by the exact bytes git wrote, so a name that is not UTF-8 is
|
||||
// still the real file. A deleted file counts as 0 bytes.
|
||||
let size = staged_size(std::fs::symlink_metadata(path.under(&top)).map(|m| m.len()));
|
||||
let file = StagedFile {
|
||||
path: path.shown,
|
||||
bytes: size.unwrap_or(0),
|
||||
};
|
||||
let is_secret = denied(&file.path).is_some();
|
||||
let is_big = too_big(&file);
|
||||
if is_secret || is_big {
|
||||
let is_unsized = size.is_none();
|
||||
if is_secret || is_big || is_unsized {
|
||||
secrets |= is_secret;
|
||||
big |= is_big;
|
||||
unreadable |= is_unsized;
|
||||
files.push(file.path);
|
||||
}
|
||||
}
|
||||
@@ -311,10 +368,14 @@ pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
|
||||
}
|
||||
let unstaged = loop_tools::git_unstage_all(project);
|
||||
let left_staged = (!unstaged.ok).then(|| first_line(&unstaged.output));
|
||||
let why = match (secrets, big) {
|
||||
(true, true) => "look like secrets or are over 5 MB",
|
||||
(true, false) => "look like secrets",
|
||||
_ => "are over 5 MB",
|
||||
let why = match (secrets, big, unreadable) {
|
||||
(true, true, false) => "look like secrets or are over 5 MB",
|
||||
(true, false, false) => "look like secrets",
|
||||
(false, true, false) => "are over 5 MB",
|
||||
(false, false, true) => "could not be sized",
|
||||
(true, false, true) => "look like secrets or could not be sized",
|
||||
(false, true, true) => "are over 5 MB or could not be sized",
|
||||
_ => "look like secrets, are over 5 MB or could not be sized",
|
||||
};
|
||||
Err(StageError::Problem(StagedProblem {
|
||||
files,
|
||||
@@ -751,7 +812,7 @@ mod tests {
|
||||
let big = std::fs::File::create(repo.join("big.bin")).unwrap();
|
||||
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
|
||||
// No commit yet: unstaging must work without a HEAD.
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo, Some(&[])) else {
|
||||
panic!("expected a problem");
|
||||
};
|
||||
let mut files = problem.files.clone();
|
||||
@@ -764,7 +825,7 @@ mod tests {
|
||||
std::fs::remove_file(repo.join(".env")).unwrap();
|
||||
std::fs::remove_file(repo.join("big.bin")).unwrap();
|
||||
std::fs::remove_file(repo.join("sub/server.pem")).unwrap();
|
||||
stage_and_check(&repo).expect("a clean list passes");
|
||||
stage_and_check(&repo, Some(&[])).expect("a clean list passes");
|
||||
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
|
||||
assert!(staged.contains("ok.txt") && staged.contains(".env.example"));
|
||||
}
|
||||
@@ -779,11 +840,11 @@ mod tests {
|
||||
git_in(&repo, &["add", "-A"]);
|
||||
git_in(&repo, &["commit", "-q", "-m", "First"]);
|
||||
std::fs::remove_file(repo.join("a.txt")).unwrap();
|
||||
stage_and_check(&repo).expect("a deletion of an ordinary file passes");
|
||||
stage_and_check(&repo, Some(&[])).expect("a deletion of an ordinary file passes");
|
||||
git_in(&repo, &["reset", "-q"]);
|
||||
let big = std::fs::File::create(repo.join("huge.dat")).unwrap();
|
||||
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo, Some(&[])) else {
|
||||
panic!("expected a problem");
|
||||
};
|
||||
assert_eq!(problem.files, vec!["huge.dat"]);
|
||||
@@ -811,7 +872,7 @@ mod tests {
|
||||
message: "Add it\n\nAI Assisted".to_string(),
|
||||
phase_file: spec.join("phase-2.md"),
|
||||
};
|
||||
stage_and_check(&repo).unwrap();
|
||||
stage_and_check(&repo, Some(&[])).unwrap();
|
||||
let marked = mark(&prepared, &repo, "specs/lunch", 2, "Approved.").unwrap();
|
||||
let head = commit(&repo, &prepared, &marked, Duration::from_secs(30)).unwrap();
|
||||
assert!(head.is_some());
|
||||
@@ -863,4 +924,119 @@ mod tests {
|
||||
// A phase the spec no longer shows done is not listed.
|
||||
assert!(marks_without_commits(&base, "specs/lunch", &[2], &report).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_phases_own_files_are_staged_and_the_baseline_is_left_alone() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("stage-own");
|
||||
// A setting that hides untracked files from a plain `git status`.
|
||||
git_in(&repo, &["config", "status.showUntrackedFiles", "no"]);
|
||||
std::fs::create_dir_all(repo.join("app")).unwrap();
|
||||
std::fs::write(repo.join("tracked.txt"), "a").unwrap();
|
||||
std::fs::write(repo.join("app/keep.tsx"), "k").unwrap();
|
||||
git_in(&repo, &["add", "tracked.txt", "app/keep.tsx"]);
|
||||
git_in(&repo, &["commit", "-q", "-m", "First"]);
|
||||
// When the phase began, the person already had two files of their
|
||||
// own: one of them a name a glob reading of `app/[id].tsx` matches.
|
||||
std::fs::write(repo.join("mine.txt"), "the person's").unwrap();
|
||||
std::fs::write(repo.join("app/i.tsx"), "decoy").unwrap();
|
||||
let mut baseline = loop_tools::git_status_porcelain(&repo).unwrap();
|
||||
baseline.sort_unstable();
|
||||
assert_eq!(baseline, vec!["app/i.tsx", "mine.txt"]);
|
||||
// The agent then edits a tracked file and adds files, one with a
|
||||
// name that reads as a pattern (listed on its own line, since `app/`
|
||||
// is tracked).
|
||||
std::fs::write(repo.join("tracked.txt"), "b").unwrap();
|
||||
std::fs::write(repo.join("app/[id].tsx"), "x").unwrap();
|
||||
std::fs::write(repo.join("new.rs"), "y").unwrap();
|
||||
stage_and_check(&repo, Some(&baseline)).expect("the agent's files pass");
|
||||
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
|
||||
let mut staged: Vec<&str> = staged.lines().collect();
|
||||
staged.sort_unstable();
|
||||
assert_eq!(staged, vec!["app/[id].tsx", "new.rs", "tracked.txt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untracked_folder_from_before_the_phase_neither_hides_nor_swallows_files() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("stage-untracked-dir");
|
||||
std::fs::write(repo.join("tracked.txt"), "a").unwrap();
|
||||
git_in(&repo, &["add", "tracked.txt"]);
|
||||
git_in(&repo, &["commit", "-q", "-m", "First"]);
|
||||
// The person's scratch folder was untracked when the phase began.
|
||||
std::fs::create_dir_all(repo.join("scratch")).unwrap();
|
||||
std::fs::write(repo.join("scratch/mine.txt"), "the person's").unwrap();
|
||||
let mut baseline = loop_tools::git_status_porcelain(&repo).unwrap();
|
||||
baseline.sort_unstable();
|
||||
assert_eq!(baseline, vec!["scratch/mine.txt"]);
|
||||
// The agent adds a file beside it, and a folder of its own.
|
||||
std::fs::write(repo.join("scratch/new.txt"), "the agent's").unwrap();
|
||||
std::fs::create_dir_all(repo.join("made")).unwrap();
|
||||
std::fs::write(repo.join("made/a.txt"), "the agent's").unwrap();
|
||||
stage_and_check(&repo, Some(&baseline)).expect("the agent's files pass");
|
||||
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
|
||||
let mut staged: Vec<&str> = staged.lines().collect();
|
||||
staged.sort_unstable();
|
||||
assert_eq!(staged, vec!["made/a.txt", "scratch/new.txt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_fails_closed_when_the_phases_files_cannot_be_listed() {
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("stage-unknown");
|
||||
std::fs::write(repo.join("a.txt"), "a").unwrap();
|
||||
// No baseline from the phase's start: nothing is staged.
|
||||
let Err(StageError::Add(failure)) = stage_and_check(&repo, None) else {
|
||||
panic!("expected a refusal");
|
||||
};
|
||||
assert_eq!(failure.first_line, OWN_FILES_UNKNOWN);
|
||||
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
|
||||
// Outside any repository the list cannot be read either.
|
||||
let (plain, _) = temp_spec("stage-no-repo");
|
||||
let Err(StageError::Add(failure)) = stage_and_check(&plain, Some(&[])) else {
|
||||
panic!("expected a refusal");
|
||||
};
|
||||
assert_eq!(failure.first_line, OWN_FILES_UNKNOWN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_size_that_cannot_be_read_is_refused_and_a_deletion_is_zero() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
assert_eq!(staged_size(Ok(12)), Some(12));
|
||||
assert_eq!(staged_size(Err(Error::from(ErrorKind::NotFound))), Some(0));
|
||||
assert_eq!(
|
||||
staged_size(Err(Error::from(ErrorKind::PermissionDenied))),
|
||||
None
|
||||
);
|
||||
assert_eq!(staged_size(Err(Error::other("odd"))), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_big_file_whose_name_is_not_utf8_hits_the_size_gate() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
if !git_ready() {
|
||||
return;
|
||||
}
|
||||
let repo = init_repo("stage-non-utf8");
|
||||
let name = std::ffi::OsStr::from_bytes(b"caf\xe9.bin");
|
||||
let big = match std::fs::File::create(repo.join(name)) {
|
||||
Ok(file) => file,
|
||||
// A file system that refuses such a name (some macOS volumes) has nothing to check.
|
||||
Err(_) => return,
|
||||
};
|
||||
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
|
||||
let Err(StageError::Problem(problem)) = stage_and_check(&repo, Some(&[])) else {
|
||||
panic!("expected the size gate to stop it");
|
||||
};
|
||||
assert_eq!(problem.files, vec!["caf\u{fffd}.bin"]);
|
||||
assert_eq!(problem.why, "are over 5 MB");
|
||||
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
|
||||
}
|
||||
}
|
||||
@@ -389,6 +389,15 @@ pub struct RunningRecord {
|
||||
/// The launch choice's model and effort, which a Match my session phase runs on.
|
||||
pub launch_model: Option<String>,
|
||||
pub launch_effort: Option<String>,
|
||||
/// What `git status` listed when the current phase began: changes that
|
||||
/// are not the phase's, left out of its commit. `None` when it could not
|
||||
/// be read, and the commit then stages nothing. A retry keeps the first
|
||||
/// try's baseline, so the work the crashed try left is still the phase's.
|
||||
pub phase_baseline: Option<Vec<String>>,
|
||||
/// An Implement page announced while the phase had no session yet, but
|
||||
/// not yet locked by the agent's `open --loop`: adopted on a later look
|
||||
/// once its state shows the lock (`note_page`).
|
||||
pub page_candidate: Option<String>,
|
||||
}
|
||||
|
||||
/// What one phase runs on, for its start, the strip and the report.
|
||||
@@ -471,6 +480,8 @@ impl RunningRecord {
|
||||
strength_rows: BTreeMap::new(),
|
||||
launch_model: None,
|
||||
launch_effort: None,
|
||||
phase_baseline: None,
|
||||
page_candidate: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -897,16 +908,39 @@ pub fn should_retry(cause: &StopCause, setup: &LoopSetup, retries_used_this_phas
|
||||
/// Whether the session state holds a question for the person: an item still
|
||||
/// open or reopened, required, not handled by the loop and not just a notice.
|
||||
pub fn open_question(state: &Value) -> bool {
|
||||
state["items"].as_array().is_some_and(|items| {
|
||||
items.iter().any(|item| {
|
||||
matches!(item["status"].as_str(), Some("open" | "reopened"))
|
||||
&& item["required"].as_bool() != Some(false)
|
||||
&& item["kind"].as_str() != Some("notice")
|
||||
&& item.get("handledBy").is_none_or(Value::is_null)
|
||||
})
|
||||
first_open_question(state).is_some()
|
||||
}
|
||||
|
||||
/// The first question `open_question` would count, as its title (the
|
||||
/// question's body when it has no title), or `None`.
|
||||
pub fn first_open_question(state: &Value) -> Option<String> {
|
||||
state["items"].as_array()?.iter().find_map(|item| {
|
||||
let open = matches!(item["status"].as_str(), Some("open" | "reopened"))
|
||||
&& item["required"].as_bool() != Some(false)
|
||||
&& item["kind"].as_str() != Some("notice")
|
||||
&& item.get("handledBy").is_none_or(Value::is_null);
|
||||
if !open {
|
||||
return None;
|
||||
}
|
||||
let title = item["title"].as_str().map(str::trim).unwrap_or_default();
|
||||
let text = if title.is_empty() {
|
||||
item["body"].as_str().map(str::trim).unwrap_or_default()
|
||||
} else {
|
||||
title
|
||||
};
|
||||
Some(one_line(text))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an announced page can be the running phase's session: the agent
|
||||
/// has locked it with `open --loop` (`loop.driving`) and it holds no report
|
||||
/// yet. A page without the lock is a plain `open` (or not a loop page at all),
|
||||
/// and a report already there belongs to an older run.
|
||||
pub fn page_is_this_phase(state: &Value) -> bool {
|
||||
state["loop"]["driving"].as_bool().unwrap_or(false)
|
||||
&& state.get("loopOutcome").is_none_or(Value::is_null)
|
||||
}
|
||||
|
||||
/// The line the stop screen leads with. `detail` is the exit reason for a
|
||||
/// crash, the minutes for silence and the whole clause for a refused commit.
|
||||
pub fn stop_line(cause: &StopCause, phase: u32, detail: &str, retried: bool) -> String {
|
||||
@@ -946,7 +980,13 @@ pub fn stop_line(cause: &StopCause, phase: u32, detail: &str, retried: bool) ->
|
||||
shown.join(", ")
|
||||
)
|
||||
}
|
||||
StopCause::Question => format!("Phase {phase} stopped: it asked a question"),
|
||||
StopCause::Question if detail.is_empty() => {
|
||||
format!("Phase {phase} stopped: it asked a question")
|
||||
}
|
||||
StopCause::Question => {
|
||||
let asked: String = one_line(detail).chars().take(100).collect();
|
||||
format!("Phase {phase} stopped: it asked a question, \"{asked}\"")
|
||||
}
|
||||
StopCause::StoppedByPerson => {
|
||||
format!("Stopped during Phase {phase}. This phase's changes stay uncommitted.")
|
||||
}
|
||||
@@ -1228,7 +1268,10 @@ pub fn commits_to_trunk(rec: &RunningRecord) -> bool {
|
||||
/// that were already changed when the loop started. A file both the person and
|
||||
/// the agent changed is hidden from the list, a known limit.
|
||||
pub fn agent_work(now: Vec<String>, own: &[String]) -> Vec<String> {
|
||||
now.into_iter().filter(|file| !own.contains(file)).collect()
|
||||
let before: std::collections::HashSet<&str> = own.iter().map(String::as_str).collect();
|
||||
now.into_iter()
|
||||
.filter(|file| !before.contains(file.as_str()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The app's own Start confirm.
|
||||
@@ -1495,20 +1538,59 @@ pub fn begin_with_limits(
|
||||
}
|
||||
|
||||
/// A page the app took: while a loop waits for its phase's session, an
|
||||
/// Implement or Implement + Review page is that session.
|
||||
pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str) {
|
||||
/// Implement or Implement + Review page whose `state` the agent has locked
|
||||
/// with `open --loop`, and that holds no report yet, is that session
|
||||
/// (`page_is_this_phase`). One without the lock is kept as a candidate the
|
||||
/// watch adopts once the lock shows; one with a report is ignored.
|
||||
pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str, state: &Value) {
|
||||
if !matches!(workflow, "implement" | "implement-review") {
|
||||
return;
|
||||
}
|
||||
if let Some(rec) = lock(slot).as_mut() {
|
||||
if rec.sid.is_none() {
|
||||
rec.sid = Some(sid.to_string());
|
||||
rec.last_sid = Some(sid.to_string());
|
||||
rec.last_activity = SystemTime::now();
|
||||
if rec.sid.is_some() {
|
||||
return;
|
||||
}
|
||||
if page_is_this_phase(state) {
|
||||
adopt_page(rec, sid);
|
||||
} else if state.is_object() && state.get("loopOutcome").is_none_or(Value::is_null) {
|
||||
// An unreadable page (no state) is no candidate: it must not replace a real one.
|
||||
rec.page_candidate = Some(sid.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Follow `sid` as the phase's session from here.
|
||||
fn adopt_page(rec: &mut RunningRecord, sid: &str) {
|
||||
rec.sid = Some(sid.to_string());
|
||||
rec.last_sid = Some(sid.to_string());
|
||||
rec.last_activity = SystemTime::now();
|
||||
rec.page_candidate = None;
|
||||
}
|
||||
|
||||
/// The candidate `note_page` held back, adopted once its state shows the
|
||||
/// agent's lock; the session to follow, or `None` while there is none yet.
|
||||
fn adopt_candidate(ctx: &Ctx, candidate: Option<&str>) -> Option<String> {
|
||||
let sid = candidate?;
|
||||
let session = session_reader::load(&ctx.home, sid).ok()?;
|
||||
if !page_is_this_phase(&session.state) {
|
||||
return None;
|
||||
}
|
||||
let mut guard = lock(&ctx.slot);
|
||||
let rec = guard.as_mut().filter(|r| r.run_id == ctx.run_id)?;
|
||||
if rec.sid.is_none() && rec.page_candidate.as_deref() == Some(sid) {
|
||||
adopt_page(rec, sid);
|
||||
}
|
||||
rec.sid.clone()
|
||||
}
|
||||
|
||||
/// What `git status` lists as the phase begins, as its commit's baseline.
|
||||
/// The first phase of a resumed run leaves out the stopped phase's files: that
|
||||
/// work is this phase's to commit.
|
||||
fn phase_baseline(project: &Path, carried: &[String]) -> Option<Vec<String>> {
|
||||
let now = loop_tools::git_status_porcelain(project).ok()?;
|
||||
Some(agent_work(now, carried))
|
||||
}
|
||||
|
||||
/// Start a fresh agent on `prompt`: on the agent's stored launch choice when it
|
||||
/// has one, else on `launch` (an agent the loop stopped has forgotten it). The
|
||||
/// prompt is transient either way: a later New Session opens the dashboard, it
|
||||
@@ -1593,9 +1675,29 @@ fn emit(ctx: &Ctx) {
|
||||
}
|
||||
|
||||
fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> {
|
||||
// The baseline is read before the agent starts, outside the lock; a retry
|
||||
// keeps the first try's.
|
||||
let baseline = {
|
||||
let guard = lock(&ctx.slot);
|
||||
let rec = guard.as_ref().ok_or("the loop ended")?;
|
||||
let first_try = rec.phases.get(index).is_some_and(|p| p.retries == 0);
|
||||
first_try.then(|| {
|
||||
let carried = if index == 0 && rec.resumed_files.is_some() {
|
||||
rec.own_dirty.clone()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
(rec.project.clone(), carried)
|
||||
})
|
||||
}
|
||||
.map(|(project, carried)| phase_baseline(&project, &carried));
|
||||
let prompt = {
|
||||
let mut guard = lock(&ctx.slot);
|
||||
let rec = guard.as_mut().ok_or("the loop ended")?;
|
||||
if let Some(baseline) = baseline {
|
||||
rec.phase_baseline = baseline;
|
||||
}
|
||||
rec.page_candidate = None;
|
||||
rec.current = index;
|
||||
rec.phases[index].status = PhaseStatus::Running;
|
||||
rec.step = Step::Starting;
|
||||
@@ -1677,6 +1779,7 @@ struct Snapshot {
|
||||
phase_retries: u32,
|
||||
last_activity: SystemTime,
|
||||
activity_due: bool,
|
||||
page_candidate: Option<String>,
|
||||
}
|
||||
|
||||
/// The running loop as one look sees it, or `None` when this loop is over.
|
||||
@@ -1696,6 +1799,7 @@ fn take_snapshot(ctx: &Ctx) -> Option<Snapshot> {
|
||||
phase_retries: rec.phases[rec.current].retries,
|
||||
last_activity: rec.last_activity,
|
||||
activity_due: rec.activity_checked.elapsed() >= ctx.limits.activity_every,
|
||||
page_candidate: rec.page_candidate.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
@@ -1710,7 +1814,8 @@ fn tick(ctx: &Ctx) -> bool {
|
||||
stop_by_person(ctx, &snap);
|
||||
return false;
|
||||
}
|
||||
let Some(sid) = snap.sid.clone() else {
|
||||
let adopted = || adopt_candidate(ctx, snap.page_candidate.as_deref());
|
||||
let Some(sid) = snap.sid.clone().or_else(adopted) else {
|
||||
if let Some(reason) = crashed(ctx, &snap) {
|
||||
return fail(ctx, &snap, StopCause::Crash, reason);
|
||||
}
|
||||
@@ -1766,6 +1871,16 @@ fn tick(ctx: &Ctx) -> bool {
|
||||
if let Some(go) = crash_or_outcome(ctx, &snap, &sid) {
|
||||
return go;
|
||||
}
|
||||
// Under best guess a question is one the agent could not guess: the phase
|
||||
// stops on it at once, the stop card naming it, rather than waiting.
|
||||
if snap.setup.on_question == OnQuestion::Guess {
|
||||
if let Some(question) = first_open_question(state) {
|
||||
let cause = StopCause::Question;
|
||||
let line = stop_line(&cause, snap.phase_n, &question, false);
|
||||
stop_loop(ctx, cause, line, &["resume", "fix"]);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let asked = snap.setup.on_question != OnQuestion::Guess && open_question(state);
|
||||
if asked && snap.setup.on_question == OnQuestion::Stop {
|
||||
let cause = StopCause::Question;
|
||||
@@ -2103,13 +2218,19 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
|
||||
// a secret or an oversized file stops the phase with nothing to undo.
|
||||
if snap.setup.commit {
|
||||
set_step(ctx, Step::Commit);
|
||||
match loop_commit::stage_and_check(&snap.project) {
|
||||
let baseline = lock(&ctx.slot)
|
||||
.as_ref()
|
||||
.filter(|r| r.run_id == ctx.run_id)
|
||||
.and_then(|r| r.phase_baseline.clone());
|
||||
match loop_commit::stage_and_check(&snap.project, baseline.as_deref()) {
|
||||
Ok(()) => {}
|
||||
Err(loop_commit::StageError::Add(failure)) => {
|
||||
keep_output(ctx, &failure.output);
|
||||
let left_staged = loop_commit::unstage(&snap.project);
|
||||
let cause = StopCause::Commit;
|
||||
let detail = if failure.first_line == loop_tools::STAGED_TOO_LONG {
|
||||
let detail = if failure.first_line == loop_tools::STAGED_TOO_LONG
|
||||
|| failure.first_line == loop_commit::OWN_FILES_UNKNOWN
|
||||
{
|
||||
failure.first_line.clone()
|
||||
} else {
|
||||
format!("git add failed: {}", failure.first_line)
|
||||
@@ -2703,7 +2824,8 @@ pub fn evidence_markdown(cause: &StopCause, line: &str, rec: &RunningRecord) ->
|
||||
StopCause::UnsafeFiles(files) => {
|
||||
md.push_str("\n## The files\n\n");
|
||||
for file in files {
|
||||
let reason = loop_commit::denied(file).unwrap_or("over 5 MB");
|
||||
let reason =
|
||||
loop_commit::denied(file).unwrap_or("over 5 MB, or its size could not be read");
|
||||
md.push_str(&format!("- `{file}` ({reason})\n"));
|
||||
}
|
||||
md.push_str(
|
||||
@@ -2732,6 +2854,9 @@ pub fn evidence_markdown(cause: &StopCause, line: &str, rec: &RunningRecord) ->
|
||||
"\nThe loop's own watcher stopped working, so the agent was ended. Whatever was committed stays committed; nothing more was. Press Resume to carry on from the spec.\n",
|
||||
);
|
||||
}
|
||||
StopCause::Question if rec.setup.on_question == OnQuestion::Guess => {
|
||||
md.push_str("\nBest guess was on, but the phase asked a question it could not guess, so the loop stopped rather than wait. Answer it with Fix it by hand, or settle it in the spec, then press Resume.\n");
|
||||
}
|
||||
StopCause::Question => {
|
||||
md.push_str("\nThe setup says to stop when a phase asks something.\n");
|
||||
}
|
||||
@@ -3801,15 +3926,97 @@ second line"
|
||||
fn the_first_phase_page_wins_and_other_workflows_are_ignored() {
|
||||
let rec = record("specs/x", vec![]);
|
||||
let slot: LoopSlot = Arc::new(Mutex::new(Some(rec)));
|
||||
note_page(&slot, "dashboard", "s0");
|
||||
let locked = json!({ "loop": { "driving": true } });
|
||||
note_page(&slot, "dashboard", "s0", &locked);
|
||||
assert!(lock(&slot).as_ref().unwrap().sid.is_none());
|
||||
note_page(&slot, "implement-review", "s1");
|
||||
note_page(&slot, "implement", "s2");
|
||||
note_page(&slot, "implement-review", "s1", &locked);
|
||||
note_page(&slot, "implement", "s2", &locked);
|
||||
let guard = lock(&slot);
|
||||
assert_eq!(guard.as_ref().unwrap().sid.as_deref(), Some("s1"));
|
||||
assert_eq!(guard.as_ref().unwrap().last_sid.as_deref(), Some("s1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_without_the_loops_lock_or_with_a_stale_report_is_never_the_phases() {
|
||||
let rec = record("specs/x", vec![]);
|
||||
let slot: LoopSlot = Arc::new(Mutex::new(Some(rec)));
|
||||
// A plain open (no lock yet): held as a candidate, not followed.
|
||||
note_page(
|
||||
&slot,
|
||||
"implement-review",
|
||||
"plain",
|
||||
&json!({ "workflow": "implement-review" }),
|
||||
);
|
||||
assert!(lock(&slot).as_ref().unwrap().sid.is_none());
|
||||
assert_eq!(
|
||||
lock(&slot).as_ref().unwrap().page_candidate.as_deref(),
|
||||
Some("plain")
|
||||
);
|
||||
// A locked page that already holds a report belongs to an older run.
|
||||
let stale = json!({ "loop": { "driving": true }, "loopOutcome": { "phase": 1 } });
|
||||
note_page(&slot, "implement", "stale", &stale);
|
||||
assert!(lock(&slot).as_ref().unwrap().sid.is_none());
|
||||
assert_eq!(
|
||||
lock(&slot).as_ref().unwrap().page_candidate.as_deref(),
|
||||
Some("plain"),
|
||||
"a stale page is not even a candidate"
|
||||
);
|
||||
// An unreadable page (no state) is no session either.
|
||||
note_page(&slot, "implement", "gone", &Value::Null);
|
||||
assert!(lock(&slot).as_ref().unwrap().sid.is_none());
|
||||
assert_eq!(
|
||||
lock(&slot).as_ref().unwrap().page_candidate.as_deref(),
|
||||
Some("plain"),
|
||||
"an unreadable page does not replace the candidate"
|
||||
);
|
||||
// The locked page with no report is the phase's session.
|
||||
note_page(
|
||||
&slot,
|
||||
"implement",
|
||||
"s1",
|
||||
&json!({ "loop": { "driving": true } }),
|
||||
);
|
||||
let guard = lock(&slot);
|
||||
let rec = guard.as_ref().unwrap();
|
||||
assert_eq!(rec.sid.as_deref(), Some("s1"));
|
||||
assert_eq!(rec.page_candidate, None);
|
||||
assert!(page_is_this_phase(
|
||||
&json!({ "loop": { "driving": true }, "loopOutcome": null })
|
||||
));
|
||||
assert!(!page_is_this_phase(
|
||||
&json!({ "loop": { "driving": false } })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_open_question_is_named_by_its_title_or_its_body() {
|
||||
let state = json!({ "items": [
|
||||
{ "id": "a", "kind": "notice", "status": "open", "title": "Just so you know" },
|
||||
{ "id": "b", "kind": "choice", "status": "answered", "title": "Old one" },
|
||||
{ "id": "c", "kind": "multi", "status": "open", "title": "Which to fix", "handledBy": "loop" },
|
||||
{ "id": "d", "kind": "text", "status": "open", "required": false, "title": "Optional" },
|
||||
{ "id": "e", "kind": "choice", "status": "open", "title": " Which database " },
|
||||
] });
|
||||
assert_eq!(
|
||||
first_open_question(&state).as_deref(),
|
||||
Some("Which database")
|
||||
);
|
||||
let untitled = json!({ "items": [{ "id": "f", "kind": "text", "status": "reopened", "body": "Where do\nthe files go?" }] });
|
||||
assert_eq!(
|
||||
first_open_question(&untitled).as_deref(),
|
||||
Some("Where do the files go?")
|
||||
);
|
||||
assert_eq!(first_open_question(&json!({ "items": [] })), None);
|
||||
assert_eq!(
|
||||
stop_line(&StopCause::Question, 2, "Which database", false),
|
||||
"Phase 2 stopped: it asked a question, \"Which database\""
|
||||
);
|
||||
assert_eq!(
|
||||
stop_line(&StopCause::Question, 2, "", false),
|
||||
"Phase 2 stopped: it asked a question"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_headline_stage_picks_the_step() {
|
||||
assert_eq!(step_for_stage("Phase 3: Review"), Step::Review);
|
||||
@@ -4576,6 +4783,8 @@ second line"
|
||||
);
|
||||
rec.sid = Some("s1".into());
|
||||
rec.last_sid = Some("s1".into());
|
||||
// What a phase start reads from the clean throwaway repo.
|
||||
rec.phase_baseline = Some(Vec::new());
|
||||
let run_id = rec.run_id;
|
||||
let ctx = Ctx {
|
||||
slot: Arc::new(Mutex::new(Some(rec))),
|
||||
@@ -4656,7 +4865,7 @@ second line"
|
||||
assert_eq!(status["phases"][0]["tasks"]["open"], 2);
|
||||
add_failing_hook(&repo, "hook says no");
|
||||
std::fs::write(repo.join("new.txt"), "x").unwrap();
|
||||
let added = loop_tools::git_add_all(&repo);
|
||||
let added = loop_tools::git_add_listed(&repo, &loop_tools::git_changed(&repo).unwrap());
|
||||
assert!(added.ok);
|
||||
let done = loop_tools::git_commit(&repo, "Add new\n\nAI Assisted");
|
||||
assert!(!done.ok);
|
||||
@@ -4690,6 +4899,129 @@ second line"
|
||||
end_the_test(&ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_best_guess_a_question_stops_the_phase_at_once_naming_it() {
|
||||
if !git_ready("guess question") {
|
||||
return;
|
||||
}
|
||||
let repo = throwaway_repo("guess-question");
|
||||
let (ctx, home) = running_loop(&repo, Limits::default());
|
||||
lock(&ctx.slot).as_mut().unwrap().setup.on_question = OnQuestion::Guess;
|
||||
// The loop's own cards never stop it.
|
||||
write_session(
|
||||
&home,
|
||||
json!({ "loop": { "driving": true }, "items": [
|
||||
{ "id": "fixes", "kind": "multi", "status": "answered", "title": "Which to fix", "handledBy": "loop" },
|
||||
] }),
|
||||
);
|
||||
assert!(tick(&ctx), "nothing to answer yet");
|
||||
write_session(
|
||||
&home,
|
||||
json!({ "loop": { "driving": true }, "items": [
|
||||
{ "id": "q1", "kind": "choice", "status": "open", "title": "Which database" },
|
||||
] }),
|
||||
);
|
||||
assert!(!tick(&ctx), "the question stops the loop on the first look");
|
||||
assert!(lock(&ctx.slot).is_none());
|
||||
let entry = last_entry_saved(&home, &repo);
|
||||
assert_eq!(entry.result, EntryResult::Stopped);
|
||||
assert_eq!(
|
||||
entry.line,
|
||||
"Phase 2 stopped: it asked a question, \"Which database\""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_announced_before_the_lock_is_followed_once_the_lock_shows() {
|
||||
if !git_ready("candidate page") {
|
||||
return;
|
||||
}
|
||||
let repo = throwaway_repo("candidate-page");
|
||||
let (ctx, home) = running_loop(&repo, Limits::default());
|
||||
lock(&ctx.slot).as_mut().unwrap().sid = None;
|
||||
// The skill's first, plain open announces the page before `open --loop`.
|
||||
write_session(&home, json!({ "workflow": "implement-review" }));
|
||||
note_page(
|
||||
&ctx.slot,
|
||||
"implement-review",
|
||||
"s1",
|
||||
&json!({ "workflow": "implement-review" }),
|
||||
);
|
||||
assert!(tick(&ctx));
|
||||
assert!(
|
||||
lock(&ctx.slot).as_ref().unwrap().sid.is_none(),
|
||||
"not locked yet"
|
||||
);
|
||||
// `open --loop` locks it: the next look follows it.
|
||||
write_session(
|
||||
&home,
|
||||
json!({ "workflow": "implement-review", "loop": { "driving": true } }),
|
||||
);
|
||||
assert!(tick(&ctx));
|
||||
assert_eq!(lock(&ctx.slot).as_ref().unwrap().sid.as_deref(), Some("s1"));
|
||||
end_the_test(&ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_commit_takes_only_the_files_the_phase_changed() {
|
||||
if !harness_ready("own files") {
|
||||
return;
|
||||
}
|
||||
let repo = throwaway_repo("own-files");
|
||||
let (ctx, home) = running_loop(&repo, Limits::default());
|
||||
// The person's own change, there before the phase began.
|
||||
std::fs::write(repo.join("mine.txt"), "the person's").unwrap();
|
||||
start_phase(&ctx, 0).expect("start the fake agent");
|
||||
assert_eq!(
|
||||
lock(&ctx.slot).as_ref().unwrap().phase_baseline.as_deref(),
|
||||
Some(&["mine.txt".to_string()][..])
|
||||
);
|
||||
let locked = json!({ "loop": { "driving": true } });
|
||||
write_session(&home, locked.clone());
|
||||
note_page(&ctx.slot, "implement-review", "s1", &locked);
|
||||
// The agent's work.
|
||||
finish_phase_tasks(&repo, 2);
|
||||
std::fs::write(repo.join("agent.txt"), "built").unwrap();
|
||||
write_session(
|
||||
&home,
|
||||
json!({ "loop": { "driving": true }, "loopOutcome": good_report(2) }),
|
||||
);
|
||||
assert!(tick(&ctx), "the loop goes on to Phase 3");
|
||||
let shown = git_in(&repo, &["show", "--name-only", "--format=", "HEAD"]);
|
||||
assert!(shown.contains("agent.txt"), "{shown}");
|
||||
assert!(shown.contains("specs/lunch/phase-2.md"), "{shown}");
|
||||
assert!(!shown.contains("mine.txt"), "{shown}");
|
||||
assert_eq!(git_in(&repo, &["status", "--porcelain"]), "?? mine.txt");
|
||||
end_the_test(&ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_whose_start_could_not_list_the_tree_commits_nothing() {
|
||||
if !harness_ready("no baseline") {
|
||||
return;
|
||||
}
|
||||
let repo = throwaway_repo("no-baseline");
|
||||
let (ctx, home) = running_loop(&repo, Limits::default());
|
||||
lock(&ctx.slot).as_mut().unwrap().phase_baseline = None;
|
||||
finish_phase_tasks(&repo, 2);
|
||||
std::fs::write(repo.join("agent.txt"), "built").unwrap();
|
||||
write_session(&home, json!({ "loopOutcome": good_report(2) }));
|
||||
let head = git_in(&repo, &["rev-parse", "HEAD"]);
|
||||
assert!(!tick(&ctx), "the commit stops the loop");
|
||||
assert_eq!(
|
||||
git_in(&repo, &["rev-parse", "HEAD"]),
|
||||
head,
|
||||
"nothing committed"
|
||||
);
|
||||
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
|
||||
let entry = last_entry_saved(&home, &repo);
|
||||
assert!(
|
||||
entry.line.contains(loop_commit::OWN_FILES_UNKNOWN),
|
||||
"{}",
|
||||
entry.line
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_that_never_opens_its_console_stops_with_that_cause() {
|
||||
if !git_ready("no session") {
|
||||
@@ -5260,7 +5592,7 @@ second line"
|
||||
assert!(md.contains("(a key or certificate)"), "{md}");
|
||||
assert!(md.contains("## Your own files") && md.contains("`mine.txt`"));
|
||||
let big = evidence_markdown(&StopCause::UnsafeFiles(vec!["dump.bin".into()]), "l", &rec);
|
||||
assert!(big.contains("`dump.bin` (over 5 MB)"), "{big}");
|
||||
assert!(big.contains("`dump.bin` (over 5 MB"), "{big}");
|
||||
// The line is never sent as a notification for a stop by the person.
|
||||
assert!(stop_message(&cause, "specs/lunch", 4, "x").is_some());
|
||||
}
|
||||
|
||||
@@ -106,12 +106,26 @@ enum Keep {
|
||||
|
||||
/// `run_limited_with` with the part kept chosen, and whether output was dropped.
|
||||
fn run_capped(
|
||||
mut cmd: Command,
|
||||
cmd: Command,
|
||||
stdin: Option<&str>,
|
||||
limit: Duration,
|
||||
keep_stderr: bool,
|
||||
keep: Keep,
|
||||
) -> (ToolRun, bool) {
|
||||
let (run, cut, _) = run_capped_bytes(cmd, stdin.map(str::as_bytes), limit, keep_stderr, keep);
|
||||
(run, cut)
|
||||
}
|
||||
|
||||
/// `run_capped` that also hands back the kept output as the bytes the child
|
||||
/// wrote: a path list read from git must not pass through a lossy decode, or a
|
||||
/// name that is not UTF-8 no longer names its file.
|
||||
fn run_capped_bytes(
|
||||
mut cmd: Command,
|
||||
stdin: Option<&[u8]>,
|
||||
limit: Duration,
|
||||
keep_stderr: bool,
|
||||
keep: Keep,
|
||||
) -> (ToolRun, bool, Vec<u8>) {
|
||||
let cut = Arc::new(AtomicBool::new(false));
|
||||
cmd.env("PATH", crate::node_check::resolved_path());
|
||||
#[cfg(windows)]
|
||||
@@ -146,6 +160,7 @@ fn run_capped(
|
||||
output: format!("could not start: {e}"),
|
||||
},
|
||||
false,
|
||||
Vec::new(),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -162,7 +177,7 @@ fn run_capped(
|
||||
];
|
||||
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
|
||||
// A child that exits before reading closes the pipe: not an error here.
|
||||
let _ = pipe.write_all(text.as_bytes());
|
||||
let _ = pipe.write_all(text);
|
||||
}
|
||||
let pid = child.id();
|
||||
let started = Instant::now();
|
||||
@@ -194,10 +209,8 @@ fn run_capped(
|
||||
let _ = reader.join();
|
||||
}
|
||||
}
|
||||
let mut output = sink
|
||||
.lock()
|
||||
.map(|buf| String::from_utf8_lossy(&buf).into_owned())
|
||||
.unwrap_or_default();
|
||||
let raw = sink.lock().map(|buf| buf.clone()).unwrap_or_default();
|
||||
let mut output = String::from_utf8_lossy(&raw).into_owned();
|
||||
if timed_out {
|
||||
if !output.is_empty() && !output.ends_with('\n') {
|
||||
output.push('\n');
|
||||
@@ -211,6 +224,7 @@ fn run_capped(
|
||||
output,
|
||||
},
|
||||
cut.load(Ordering::Relaxed),
|
||||
raw,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -332,12 +346,13 @@ pub fn specs_mark(project: &Path, spec: &str, phase: u32, to: &str) -> ToolRun {
|
||||
)
|
||||
}
|
||||
|
||||
/// `commit-msg.mjs --subject <subject> --add-all`: the checked message. The
|
||||
/// `commit-msg.mjs --subject <subject>`: the checked message (the Loop stages
|
||||
/// its own files through `git_add_listed`, so no add is asked for). The
|
||||
/// script's own subject checks are the only ones.
|
||||
pub fn commit_message(project: &Path, subject: &str) -> Result<String, String> {
|
||||
let script = script_or_err("commit-msg.mjs")?;
|
||||
let run = run_limited(
|
||||
node_script(&script, project, &["--subject", subject, "--add-all"]),
|
||||
node_script(&script, project, &["--subject", subject]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
);
|
||||
@@ -366,8 +381,40 @@ fn parse_commit_msg(stdout: &str) -> Result<String, String> {
|
||||
.unwrap_or_else(|| stdout.trim().to_string()))
|
||||
}
|
||||
|
||||
pub fn git_add_all(project: &Path) -> ToolRun {
|
||||
run_limited(git(project, &["add", "-A"]), None, QUICK_LIMIT)
|
||||
/// `git add` of exactly `paths` (relative to the repository's top folder
|
||||
/// `top`), read from stdin NUL-separated and taken literally: no command line
|
||||
/// to outgrow, no quoting, and a name such as `[id].tsx` is a file, not a
|
||||
/// pattern. Nothing to stage is a success.
|
||||
pub fn git_add_listed(top: &Path, paths: &[GitPath]) -> ToolRun {
|
||||
if paths.is_empty() {
|
||||
return ToolRun {
|
||||
ok: true,
|
||||
code: Some(0),
|
||||
output: String::new(),
|
||||
};
|
||||
}
|
||||
let mut list = Vec::new();
|
||||
for path in paths {
|
||||
list.extend_from_slice(&path.bytes);
|
||||
list.push(0);
|
||||
}
|
||||
let cmd = git(
|
||||
top,
|
||||
&[
|
||||
"--literal-pathspecs",
|
||||
"add",
|
||||
"--pathspec-from-file=-",
|
||||
"--pathspec-file-nul",
|
||||
],
|
||||
);
|
||||
run_capped_bytes(
|
||||
cmd,
|
||||
Some(&list),
|
||||
QUICK_LIMIT,
|
||||
true,
|
||||
Keep::Tail(OUTPUT_LIMIT),
|
||||
)
|
||||
.0
|
||||
}
|
||||
|
||||
/// `git commit -F -` with the message on stdin: no shell, nothing quoted.
|
||||
@@ -406,17 +453,49 @@ pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun {
|
||||
run_limited(cmd, None, QUICK_LIMIT)
|
||||
}
|
||||
|
||||
/// A path git printed, relative to the repository's top folder: the bytes as
|
||||
/// git wrote them (so a name that is not UTF-8 still reaches its file) and the
|
||||
/// same name made readable, for messages and for comparing with name lists.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GitPath {
|
||||
pub bytes: Vec<u8>,
|
||||
pub shown: String,
|
||||
}
|
||||
|
||||
impl GitPath {
|
||||
pub fn from_bytes(bytes: &[u8]) -> GitPath {
|
||||
GitPath {
|
||||
bytes: bytes.to_vec(),
|
||||
shown: String::from_utf8_lossy(bytes).into_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file on disk under `top`. On Unix the name is the exact bytes; git
|
||||
/// writes UTF-8 names on Windows, where a file name cannot be anything else.
|
||||
pub fn under(&self, top: &Path) -> PathBuf {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
top.join(std::ffi::OsStr::from_bytes(&self.bytes))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
top.join(&self.shown)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the staged files, as `git diff --cached --name-only -z` prints
|
||||
/// them: NUL-separated, so no path is quoted.
|
||||
pub fn git_staged(project: &Path) -> Result<Vec<String>, String> {
|
||||
/// them: NUL-separated, so no path is quoted, and read as bytes.
|
||||
pub fn git_staged(project: &Path) -> Result<Vec<GitPath>, String> {
|
||||
git_staged_capped(project, STAGED_LIST_LIMIT)
|
||||
}
|
||||
|
||||
/// `git_staged` with the size the list may reach. The secret and size gate
|
||||
/// reads every staged name, so a list over the cap fails closed rather than
|
||||
/// being checked in part.
|
||||
fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<String>, String> {
|
||||
let (run, cut) = run_capped(
|
||||
fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<GitPath>, String> {
|
||||
let (run, cut, raw) = run_capped_bytes(
|
||||
git(project, &["diff", "--cached", "--name-only", "-z"]),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
@@ -429,13 +508,14 @@ fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<String>, String>
|
||||
if cut {
|
||||
return Err(STAGED_TOO_LONG.to_string());
|
||||
}
|
||||
Ok(split_nul(&run.output))
|
||||
Ok(split_nul(&raw))
|
||||
}
|
||||
|
||||
fn split_nul(text: &str) -> Vec<String> {
|
||||
text.split('\0')
|
||||
fn split_nul(bytes: &[u8]) -> Vec<GitPath> {
|
||||
bytes
|
||||
.split(|b| *b == 0)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string)
|
||||
.map(GitPath::from_bytes)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -529,39 +609,67 @@ pub fn git_head_full(project: &Path) -> Option<String> {
|
||||
|
||||
/// The paths `git status --porcelain=v1 -z` lists (renames name the new path).
|
||||
pub fn git_status_porcelain(project: &Path) -> Result<Vec<String>, String> {
|
||||
let run = run_limited_with(
|
||||
git(project, &["status", "--porcelain=v1", "-z"]),
|
||||
Ok(git_changed(project)?
|
||||
.into_iter()
|
||||
.map(|path| path.shown)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `git_status_porcelain` with each path kept as git wrote it, relative to the
|
||||
/// repository's top folder: the list the loop stages from.
|
||||
pub fn git_changed(project: &Path) -> Result<Vec<GitPath>, String> {
|
||||
let (run, cut, raw) = run_capped_bytes(
|
||||
// Untracked files are listed whatever `status.showUntrackedFiles`
|
||||
// says: with it at `no`, the agent's new files would miss the commit. `all` lists each file,
|
||||
// not a folder, so a folder that was untracked before the phase never hides or swallows files.
|
||||
git(
|
||||
project,
|
||||
&["status", "--porcelain=v1", "-z", "--untracked-files=all"],
|
||||
),
|
||||
None,
|
||||
QUICK_LIMIT,
|
||||
false,
|
||||
Keep::Head(STAGED_LIST_LIMIT),
|
||||
);
|
||||
if !run.ok {
|
||||
return Err(run.output.trim().to_string());
|
||||
}
|
||||
Ok(parse_porcelain(&run.output))
|
||||
// A list cut short would name only some of the files: never stage from it.
|
||||
if cut {
|
||||
return Err(STAGED_TOO_LONG.to_string());
|
||||
}
|
||||
Ok(porcelain_paths(&raw)
|
||||
.into_iter()
|
||||
.map(GitPath::from_bytes)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Read `git status --porcelain=v1 -z`: NUL-separated records of `XY path`, no
|
||||
/// quoting. A rename or copy record is followed by one more field, the old
|
||||
/// path, which is skipped (the new path is the one listed).
|
||||
pub fn parse_porcelain(text: &str) -> Vec<String> {
|
||||
porcelain_paths(text.as_bytes())
|
||||
.into_iter()
|
||||
.map(|path| String::from_utf8_lossy(path).into_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `parse_porcelain` over the bytes git wrote. The two status letters and the
|
||||
/// space are ASCII, so the path is whatever follows them.
|
||||
fn porcelain_paths(bytes: &[u8]) -> Vec<&[u8]> {
|
||||
let mut paths = Vec::new();
|
||||
let mut fields = text.split('\0');
|
||||
let mut fields = bytes.split(|b| *b == 0);
|
||||
while let Some(record) = fields.next() {
|
||||
let mut chars = record.chars();
|
||||
let (Some(x), Some(y), Some(' ')) = (chars.next(), chars.next(), chars.next()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(path) = record.get(x.len_utf8() + y.len_utf8() + 1..) else {
|
||||
let [x, y, b' ', path @ ..] = record else {
|
||||
continue;
|
||||
};
|
||||
if path.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if matches!(x, 'R' | 'C') || matches!(y, 'R' | 'C') {
|
||||
if matches!(x, b'R' | b'C') || matches!(y, b'R' | b'C') {
|
||||
fields.next();
|
||||
}
|
||||
paths.push(path.to_string());
|
||||
paths.push(path);
|
||||
}
|
||||
paths
|
||||
}
|
||||
@@ -682,7 +790,11 @@ mod tests {
|
||||
git_staged_capped(&repo, 8),
|
||||
Err(STAGED_TOO_LONG.to_string())
|
||||
);
|
||||
let all = git_staged_capped(&repo, 1024).unwrap();
|
||||
let all: Vec<String> = git_staged_capped(&repo, 1024)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|path| path.shown)
|
||||
.collect();
|
||||
assert_eq!(all, [".env", "a.txt", "b.txt"]);
|
||||
let _ = std::fs::remove_dir_all(&repo);
|
||||
}
|
||||
@@ -749,11 +861,28 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn staged_names_are_split_on_nul() {
|
||||
assert_eq!(
|
||||
split_nul("a b.txt\0dir/c.rs\0"),
|
||||
vec!["a b.txt", "dir/c.rs"]
|
||||
);
|
||||
assert!(split_nul("").is_empty());
|
||||
let shown: Vec<String> = split_nul(b"a b.txt\0dir/c.rs\0")
|
||||
.into_iter()
|
||||
.map(|path| path.shown)
|
||||
.collect();
|
||||
assert_eq!(shown, vec!["a b.txt", "dir/c.rs"]);
|
||||
assert!(split_nul(b"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_not_utf8_keeps_its_bytes() {
|
||||
let names = split_nul(b"caf\xe9.bin\0ok.txt\0");
|
||||
assert_eq!(names[0].bytes, b"caf\xe9.bin");
|
||||
assert_eq!(names[0].shown, "caf\u{fffd}.bin");
|
||||
// The porcelain reader keeps the bytes too, and still skips a rename's old path.
|
||||
let paths = porcelain_paths(b"?? caf\xe9.bin\0R new.rs\0old.rs\0");
|
||||
assert_eq!(paths, vec![&b"caf\xe9.bin"[..], &b"new.rs"[..]]);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let file = names[0].under(Path::new("/top"));
|
||||
assert_eq!(file.as_os_str().as_bytes(), b"/top/caf\xe9.bin");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -17,6 +17,7 @@ use plan2code_app_lib::node_check;
|
||||
use plan2code_app_lib::project::{self, ProjectDir};
|
||||
use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase};
|
||||
use plan2code_app_lib::restart_brief;
|
||||
use plan2code_app_lib::session_reader;
|
||||
use plan2code_app_lib::settings;
|
||||
#[cfg(windows)]
|
||||
use plan2code_app_lib::task_dialog;
|
||||
@@ -185,10 +186,14 @@ fn open_install_page(id: String) -> Result<(), String> {
|
||||
|
||||
// `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`.
|
||||
fn windows_build() -> Option<u32> {
|
||||
let out = std::process::Command::new("cmd")
|
||||
.args(["/c", "ver"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let mut command = std::process::Command::new("cmd");
|
||||
command.args(["/c", "ver"]);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
}
|
||||
let out = command.output().ok()?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let version = text.split("Version ").nth(1)?;
|
||||
version.split('.').nth(2)?.trim().parse().ok()
|
||||
@@ -889,13 +894,23 @@ fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String
|
||||
console_start_impl(&state)
|
||||
}
|
||||
|
||||
/// What `console_start` says before the agent has announced any page.
|
||||
const NO_DASHBOARD_YET: &str = "The agent has not opened the dashboard yet.";
|
||||
|
||||
/// The health check runs with the console lock released (the announce thread
|
||||
/// takes it to follow a new page); a console the person stopped, or one found
|
||||
/// dead, is opened again on its session, unless a new page was followed
|
||||
/// meanwhile.
|
||||
fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
|
||||
let probe = {
|
||||
let guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
guard.as_ref().ok_or(NO_DASHBOARD_YET)?.probe()
|
||||
};
|
||||
let alive = !probe.stopped() && probe.alive();
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
let sup = guard
|
||||
.as_mut()
|
||||
.ok_or("The agent has not opened the dashboard yet.")?;
|
||||
if !sup.health() {
|
||||
sup.restart_if_dead()?;
|
||||
let sup = guard.as_mut().ok_or(NO_DASHBOARD_YET)?;
|
||||
if !alive && sup.probe() == probe {
|
||||
sup.reopen()?;
|
||||
}
|
||||
serde_json::to_value(sup.session()).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -904,23 +919,37 @@ fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
|
||||
/// dead (started but not answering).
|
||||
#[tauri::command(async)]
|
||||
fn console_status(state: State<'_, AppState>) -> serde_json::Value {
|
||||
let Ok(guard) = state.console.lock() else {
|
||||
return serde_json::json!({ "state": "none", "url": null });
|
||||
};
|
||||
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 })
|
||||
console_status_impl(&state)
|
||||
}
|
||||
|
||||
/// The health check runs with the console lock released, as in `console_start`.
|
||||
fn console_status_impl(state: &AppState) -> serde_json::Value {
|
||||
let none = serde_json::json!({ "state": "none", "url": null });
|
||||
let seen = state.console.lock().ok().and_then(|guard| {
|
||||
guard
|
||||
.as_ref()
|
||||
.map(|sup| (sup.probe(), sup.session().url.clone()))
|
||||
});
|
||||
match seen {
|
||||
Some((probe, _)) if probe.stopped() => none,
|
||||
Some((probe, url)) if probe.health() => {
|
||||
serde_json::json!({ "state": "running", "url": url })
|
||||
}
|
||||
Some(sup) => serde_json::json!({ "state": "dead", "url": sup.session().url }),
|
||||
None => serde_json::json!({ "state": "none", "url": null }),
|
||||
Some((_, url)) => serde_json::json!({ "state": "dead", "url": url }),
|
||||
None => none,
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
|
||||
console_stop_impl(&state)
|
||||
}
|
||||
|
||||
/// Stop the console but keep its supervisor, so a start after a stop opens
|
||||
/// the same session again instead of finding nothing to start.
|
||||
fn console_stop_impl(state: &AppState) -> Result<(), String> {
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
if let Some(mut sup) = guard.take() {
|
||||
if let Some(sup) = guard.as_mut() {
|
||||
sup.stop()?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -1374,8 +1403,13 @@ fn main() {
|
||||
let taken =
|
||||
take_announced(&state, ¬ice, window_origin(&handle), session_on_disk);
|
||||
if taken {
|
||||
// A running loop follows its phase's session from here.
|
||||
loop_driver::note_page(&state.loop_run, ¬ice.workflow, ¬ice.sid);
|
||||
// A running loop follows its phase's session from here,
|
||||
// once the agent's `open --loop` has locked it.
|
||||
let page = session_reader::console_home()
|
||||
.and_then(|home| session_reader::load(&home, ¬ice.sid).ok())
|
||||
.map(|session| session.state)
|
||||
.unwrap_or(serde_json::Value::Null);
|
||||
loop_driver::note_page(&state.loop_run, ¬ice.workflow, ¬ice.sid, &page);
|
||||
let _ = handle.emit("console-page", ¬ice);
|
||||
} else {
|
||||
eprintln!(
|
||||
@@ -1425,6 +1459,7 @@ fn main() {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn state_for(dir: &str) -> AppState {
|
||||
AppState {
|
||||
@@ -1801,6 +1836,69 @@ mod tests {
|
||||
assert_eq!(event.spec_name, "x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_start_after_a_stop_opens_the_same_session_again() {
|
||||
let Some(sup) = real_console() else { return };
|
||||
let state = state_for("project-a");
|
||||
let sid = sup.session().sid.clone();
|
||||
*state.console.lock().unwrap() = Some(sup);
|
||||
assert_eq!(console_status_impl(&state)["state"], "running");
|
||||
|
||||
console_stop_impl(&state).unwrap();
|
||||
assert_eq!(console_status_impl(&state)["state"], "none");
|
||||
assert!(
|
||||
state.console.lock().unwrap().is_some(),
|
||||
"the supervisor stays"
|
||||
);
|
||||
|
||||
let session = console_start_impl(&state).expect("a start after a stop works");
|
||||
assert_eq!(
|
||||
session["sid"].as_str(),
|
||||
Some(sid.as_str()),
|
||||
"the same session"
|
||||
);
|
||||
assert_eq!(console_status_impl(&state)["state"], "running");
|
||||
let _ = state.console.lock().unwrap().take().unwrap().stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_health_check_never_holds_the_console_lock() {
|
||||
// A server that takes the connection and never answers: the check
|
||||
// waits out its whole timeout.
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
std::env::set_var(
|
||||
"PLAN2CODE_CONSOLE_DIR",
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"),
|
||||
);
|
||||
let sup = ConsoleSupervisor::adopt(
|
||||
PathBuf::from("."),
|
||||
app_origin().to_string(),
|
||||
&format!("http://127.0.0.1:{port}/s/slow/"),
|
||||
"slow",
|
||||
)
|
||||
.expect("adopt");
|
||||
let state = state_for("project-a");
|
||||
*state.console.lock().unwrap() = Some(sup);
|
||||
std::thread::scope(|scope| {
|
||||
let poll = scope.spawn(|| console_status_impl(&state));
|
||||
// The poll is in its health check by now; the announce thread's
|
||||
// lock must not wait for it.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
let asked = Instant::now();
|
||||
drop(state.console.lock().unwrap());
|
||||
assert!(
|
||||
asked.elapsed() < Duration::from_millis(500),
|
||||
"the lock waited {:?} on the health check",
|
||||
asked.elapsed()
|
||||
);
|
||||
assert_eq!(poll.join().unwrap()["state"], "dead");
|
||||
});
|
||||
drop(listener);
|
||||
// Leave nothing to stop: the adopted console was never started.
|
||||
std::mem::forget(state.console.lock().unwrap().take());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() {
|
||||
let Some(sup) = real_console() else { return };
|
||||
|
||||
@@ -37,11 +37,14 @@ pub fn classify(output: &str) -> NodeStatus {
|
||||
}
|
||||
|
||||
pub fn check_node() -> NodeStatus {
|
||||
match Command::new("node")
|
||||
.env("PATH", resolved_path())
|
||||
.arg("--version")
|
||||
.output()
|
||||
let mut command = Command::new("node");
|
||||
command.env("PATH", resolved_path()).arg("--version");
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
}
|
||||
match command.output() {
|
||||
Ok(out) if out.status.success() => classify(&String::from_utf8_lossy(&out.stdout)),
|
||||
_ => NodeStatus::Missing,
|
||||
}
|
||||
@@ -226,11 +229,14 @@ pub fn node_binary_path() -> Option<String> {
|
||||
} else {
|
||||
("which", "node")
|
||||
};
|
||||
let out = Command::new(program)
|
||||
.env("PATH", resolved_path())
|
||||
.arg(arg)
|
||||
.output()
|
||||
.ok()?;
|
||||
let mut command = Command::new(program);
|
||||
command.env("PATH", resolved_path()).arg(arg);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
}
|
||||
let out = command.output().ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user