Compare commits
55
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9829bc56f | ||
|
|
9f582263b8 | ||
|
|
b5cbf94fa8 | ||
|
|
8376122dfe | ||
|
|
4a814d5b17 | ||
|
|
1809f5d581 | ||
|
|
ec51b0221c | ||
|
|
ca585447ff | ||
|
|
71301861c0 | ||
|
|
33fb50be6e | ||
|
|
2ce1dc43fe | ||
|
|
b6cf87244f | ||
|
|
e99e21260b | ||
|
|
cea06f9204 | ||
|
|
1199596528 | ||
|
|
6d21061799 | ||
|
|
431f9def6b | ||
|
|
d8acc3adde | ||
|
|
95f0e42df5 | ||
|
|
6f8de8de7c | ||
|
|
018f44727c | ||
|
|
85e7749e5a | ||
|
|
35bc5bfb40 | ||
|
|
059ae86fb8 | ||
|
|
e3996dec76 | ||
|
|
503f01ae26 | ||
|
|
790d1e2075 | ||
|
|
cbfd5eee12 | ||
|
|
10cb47c50b | ||
|
|
dfc4ee91e1 | ||
|
|
d5485b8f5d | ||
|
|
53660407e3 | ||
|
|
a51809f25a | ||
|
|
135152e930 | ||
|
|
9d777e2a22 | ||
|
|
cd7e76d911 | ||
|
|
5c3997d1d3 | ||
|
|
dbbe330159 | ||
|
|
1d611ee402 | ||
|
|
f31377c34f | ||
|
|
812861f883 | ||
|
|
745e9fde8b | ||
|
|
30bd9d9042 | ||
|
|
6596104789 | ||
|
|
b20651c33e | ||
|
|
031c80a40b | ||
|
|
db44650a17 | ||
|
|
f01771568b | ||
|
|
63898cef25 | ||
|
|
fc53d74850 | ||
|
|
ef3d314296 | ||
|
|
148f97fa71 | ||
|
|
39cfa50d68 | ||
|
|
02356f84ab | ||
|
|
01a1073943 |
@@ -52,3 +52,48 @@ jobs:
|
||||
|
||||
- name: test
|
||||
run: cargo test --all
|
||||
|
||||
# NAP-271: the umbrella `maestro` binary is feature-gated (cli / daemon /
|
||||
# tui). Verify each subset compiles and its tests pass on its own, and
|
||||
# that building with no features at all is rejected.
|
||||
- name: feature-gate matrix
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for f in cli daemon tui; do
|
||||
echo "::group::maestro --no-default-features --features $f"
|
||||
cargo build -p maestro --no-default-features --features "$f"
|
||||
cargo test -p maestro --no-default-features --features "$f"
|
||||
echo "::endgroup::"
|
||||
done
|
||||
echo "::group::maestro with no features must fail to compile"
|
||||
if cargo build -p maestro --no-default-features 2>/dev/null; then
|
||||
echo "expected build with no features to fail, but it succeeded" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
|
||||
web:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Node.js + pnpm
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends curl ca-certificates
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt-get install -y --no-install-recommends nodejs
|
||||
corepack enable
|
||||
corepack prepare pnpm@9.15.4 --activate
|
||||
|
||||
- name: Install deps
|
||||
run: pnpm -C web install --frozen-lockfile
|
||||
|
||||
- name: typecheck
|
||||
run: pnpm -C web typecheck
|
||||
|
||||
- name: test
|
||||
run: pnpm -C web test
|
||||
|
||||
- name: build
|
||||
run: pnpm -C web build
|
||||
|
||||
@@ -9,3 +9,9 @@ worktrees/
|
||||
# nix build output symlinks
|
||||
/result
|
||||
/result-*
|
||||
|
||||
# direnv (`use flake`)
|
||||
/.direnv/
|
||||
|
||||
# `nix run .#dev` scratch state (tmux socket)
|
||||
/.dev/
|
||||
|
||||
@@ -56,12 +56,19 @@ crates/
|
||||
├── maestro-installer/ # `maestro-install` wizard: cargo install + systemd (NAP-225)
|
||||
└── maestro-e2e/ # cross-process integration tests (NAP-217)
|
||||
web/ # browser SPA (NAP-218)
|
||||
flake.nix # Nix flake: `maestro`, `maestro-web`, `webFrontend`
|
||||
flake.nix # Nix flake: packages, checks, dev shell, `nix run .#dev`
|
||||
nix/ # Home Manager module (`services.maestro`)
|
||||
```
|
||||
|
||||
See `docs/INSTALL.md` for end-user install instructions.
|
||||
|
||||
`nix run .#dev` (or `just dev`) brings up the whole local stack under
|
||||
process-compose: a debug daemon on 127.0.0.1:7071, then Vite on :5173 once the
|
||||
daemon answers `/api/info`. The SPA proxies `/api/*` back to the daemon, so only
|
||||
the UI is exposed on the network. The dev port is deliberately not the daemon's
|
||||
own default 7070 (`devDaemonPort` in `flake.nix`), so the stack never fights a
|
||||
real daemon on the same host.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **TDD by default.** Failing test first, then minimal impl. Commit test + impl together.
|
||||
|
||||
Generated
+23
-4
@@ -1066,9 +1066,8 @@ dependencies = [
|
||||
"libc",
|
||||
"maestro-config",
|
||||
"maestro-protocol",
|
||||
"maestro-testing",
|
||||
"nix",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
@@ -1085,6 +1084,7 @@ name = "maestro-config"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"maestro-protocol",
|
||||
"serde",
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
@@ -1123,8 +1123,8 @@ dependencies = [
|
||||
"chrono",
|
||||
"futures-util",
|
||||
"maestro-protocol",
|
||||
"maestro-testing",
|
||||
"maestro-tui",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
@@ -1151,8 +1151,24 @@ name = "maestro-protocol"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 1.0.69",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maestro-testing"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
"futures-util",
|
||||
"maestro-protocol",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
@@ -1167,8 +1183,8 @@ dependencies = [
|
||||
"futures-util",
|
||||
"maestro-config",
|
||||
"maestro-protocol",
|
||||
"maestro-testing",
|
||||
"ratatui",
|
||||
"reqwest",
|
||||
"serde_json",
|
||||
"thiserror 1.0.69",
|
||||
"tokio",
|
||||
@@ -1189,6 +1205,8 @@ dependencies = [
|
||||
"futures-util",
|
||||
"include_dir",
|
||||
"maestro-config",
|
||||
"maestro-protocol",
|
||||
"maestro-testing",
|
||||
"mime_guess",
|
||||
"reqwest",
|
||||
"serde_json",
|
||||
@@ -1198,6 +1216,7 @@ dependencies = [
|
||||
"tokio-tungstenite 0.21.0",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -19,6 +19,7 @@ futures-util = { version = "0.3", default-features = false, features = ["sink",
|
||||
libc = "0.2"
|
||||
maestro-config = { path = "crates/maestro-config" }
|
||||
maestro-protocol = { path = "crates/maestro-protocol" }
|
||||
maestro-testing = { path = "crates/maestro-testing" }
|
||||
maestro-tui = { path = "crates/maestro-tui" }
|
||||
nix = { version = "0.29", default-features = false, features = ["term", "signal"] }
|
||||
rand = "0.8"
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# Common dev / build entry points. Run `just` with no args to list.
|
||||
|
||||
# Run the full local stack — daemon on 127.0.0.1:7071 plus Vite on :5173,
|
||||
# ordered and health-gated by process-compose. Ctrl-C stops everything.
|
||||
dev:
|
||||
nix run .#dev
|
||||
|
||||
# Build the maestro-web binary together with the SPA bundle it embeds.
|
||||
web:
|
||||
pnpm -C web install --frozen-lockfile
|
||||
|
||||
@@ -17,10 +17,8 @@ dirs.workspace = true
|
||||
futures-util.workspace = true
|
||||
libc.workspace = true
|
||||
maestro-config.workspace = true
|
||||
maestro-protocol.workspace = true
|
||||
maestro-protocol = { workspace = true, features = ["client"] }
|
||||
nix.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio = { workspace = true, features = ["macros", "rt", "sync", "time", "io-util", "io-std", "signal"] }
|
||||
@@ -31,4 +29,7 @@ tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
maestro-testing.workspace = true
|
||||
tempfile.workspace = true
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
uuid.workspace = true
|
||||
|
||||
@@ -13,7 +13,6 @@ use maestro_protocol::ClientControl;
|
||||
use nix::sys::termios::{cfmakeraw, tcgetattr, tcsetattr, SetArg, Termios};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[allow(clippy::result_large_err)]
|
||||
@@ -24,8 +23,8 @@ pub enum AttachError {
|
||||
Io(#[from] io::Error),
|
||||
#[error("termios: {0}")]
|
||||
Termios(#[from] nix::Error),
|
||||
#[error("invalid daemon_url: {0}")]
|
||||
InvalidDaemonUrl(String),
|
||||
#[error(transparent)]
|
||||
Url(#[from] maestro_protocol::routes::UrlError),
|
||||
#[error("invalid detach key: {0}")]
|
||||
InvalidDetachKey(String),
|
||||
#[error("stdin must be a TTY for attach")]
|
||||
@@ -63,26 +62,6 @@ pub fn parse_detach_key(spec: &str) -> Result<u8, AttachError> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the attach WS URL from the daemon's HTTP base.
|
||||
///
|
||||
/// The endpoint (`WS /api/attach/:id`) lives on the daemon's `bind_addr`, so we
|
||||
/// take the HTTP base (`http://127.0.0.1:7070`), swap the scheme to its WS
|
||||
/// equivalent, and append the route.
|
||||
#[allow(clippy::result_large_err)]
|
||||
pub fn attach_url(daemon_http_base: &str, session_id: Uuid) -> Result<String, AttachError> {
|
||||
let base = daemon_http_base.trim_end_matches('/');
|
||||
let ws_base = if let Some(rest) = base.strip_prefix("https://") {
|
||||
format!("wss://{rest}")
|
||||
} else if let Some(rest) = base.strip_prefix("http://") {
|
||||
format!("ws://{rest}")
|
||||
} else if base.starts_with("ws://") || base.starts_with("wss://") {
|
||||
base.to_string()
|
||||
} else {
|
||||
return Err(AttachError::InvalidDaemonUrl(daemon_http_base.to_string()));
|
||||
};
|
||||
Ok(format!("{ws_base}/api/attach/{session_id}"))
|
||||
}
|
||||
|
||||
/// RAII guard that puts the terminal into raw mode and restores on drop.
|
||||
#[derive(Debug)]
|
||||
struct RawTty {
|
||||
@@ -234,7 +213,6 @@ pub async fn run_attach_url(url: &str, detach_byte: u8) -> Result<(), AttachErro
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[test]
|
||||
fn parse_detach_key_handles_caret_form() {
|
||||
@@ -255,30 +233,4 @@ mod tests {
|
||||
Err(AttachError::InvalidDetachKey(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_url_swaps_scheme_and_appends_route() {
|
||||
let id = Uuid::from_u128(0xabcd);
|
||||
assert_eq!(
|
||||
attach_url("http://127.0.0.1:7070", id).unwrap(),
|
||||
format!("ws://127.0.0.1:7070/api/attach/{id}")
|
||||
);
|
||||
assert_eq!(
|
||||
attach_url("https://laptop.lan:7070/", id).unwrap(),
|
||||
format!("wss://laptop.lan:7070/api/attach/{id}")
|
||||
);
|
||||
// already-ws bases pass through
|
||||
assert_eq!(
|
||||
attach_url("ws://10.0.0.1:7070", id).unwrap(),
|
||||
format!("ws://10.0.0.1:7070/api/attach/{id}")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_url_rejects_unknown_scheme() {
|
||||
assert!(matches!(
|
||||
attach_url("ftp://x", Uuid::nil()),
|
||||
Err(AttachError::InvalidDaemonUrl(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,8 +67,15 @@ pub struct SpawnArgs {
|
||||
/// Branch name for the worktree (required with --worktree-from).
|
||||
#[arg(long)]
|
||||
pub branch: Option<String>,
|
||||
/// Remove the worktree when the session is killed.
|
||||
/// Check out an existing branch instead of creating one. Without it the
|
||||
/// daemon runs `worktree add -b`, which fails if the branch is already
|
||||
/// there.
|
||||
#[arg(long)]
|
||||
pub existing_branch: bool,
|
||||
/// Remove the worktree when the session is killed. Kept for wire
|
||||
/// compatibility (#56): the daemon now always cleans up on kill, guarded
|
||||
/// against unsaved work.
|
||||
#[arg(long, default_value_t = true)]
|
||||
pub cleanup_on_kill: bool,
|
||||
/// After spawning, attach immediately.
|
||||
#[arg(long, short = 'a')]
|
||||
@@ -147,6 +154,52 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_on_kill_defaults_true_for_the_wire() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"maestro",
|
||||
"spawn",
|
||||
"--cwd",
|
||||
"/tmp",
|
||||
"--command",
|
||||
"bash",
|
||||
"--worktree-from",
|
||||
"/repos/foo",
|
||||
"--branch",
|
||||
"feat/x",
|
||||
])
|
||||
.unwrap();
|
||||
match cli.command {
|
||||
Command::Spawn(a) => assert!(a.cleanup_on_kill),
|
||||
_ => panic!("wrong subcommand"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Review fix: without a flag the CLI always sent `create_branch: true`,
|
||||
/// so the daemon's existing-branch path was unreachable and spawning onto
|
||||
/// a branch that already existed just failed.
|
||||
#[test]
|
||||
fn parses_spawn_onto_an_existing_branch() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"maestro",
|
||||
"spawn",
|
||||
"--cwd",
|
||||
"/tmp",
|
||||
"--command",
|
||||
"bash",
|
||||
"--worktree-from",
|
||||
"/repo",
|
||||
"--branch",
|
||||
"feat/existing",
|
||||
"--existing-branch",
|
||||
])
|
||||
.unwrap();
|
||||
let Command::Spawn(a) = cli.command else {
|
||||
panic!("expected spawn")
|
||||
};
|
||||
assert!(a.existing_branch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_worktree_requires_branch() {
|
||||
let err = Cli::try_parse_from([
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
//! CLI view over the unified Maestro config at `~/.config/maestro/config.toml`.
|
||||
//!
|
||||
//! Reads `[cli].daemon_url` and, as a fallback, `[daemon].bind_addr`.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use maestro_config::MaestroConfigFile;
|
||||
|
||||
pub use maestro_config::CONFIG_PATH_ENV;
|
||||
|
||||
/// Last-resort daemon HTTP base when neither config nor a local
|
||||
/// `[daemon].bind_addr` tells us otherwise. Matches the daemon's default
|
||||
/// `bind_addr`.
|
||||
pub const DEFAULT_DAEMON_URL: &str = "http://127.0.0.1:7070";
|
||||
|
||||
/// `~/.config/maestro/config.toml` (XDG-aware).
|
||||
pub fn default_config_path() -> Result<PathBuf, ConfigError> {
|
||||
Ok(maestro_config::default_config_path()?)
|
||||
}
|
||||
|
||||
/// `$MAESTRO_CONFIG` if set, else [`default_config_path`].
|
||||
pub fn resolve_config_path() -> Result<PathBuf, ConfigError> {
|
||||
Ok(maestro_config::resolve_config_path()?)
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
#[error(transparent)]
|
||||
Inner(#[from] maestro_config::ConfigError),
|
||||
}
|
||||
|
||||
/// Resolved CLI config — the subset of the unified file that this binary
|
||||
/// actually consumes.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct CliConfig {
|
||||
/// `[cli].daemon_url` — explicit daemon HTTP base.
|
||||
pub daemon_url: Option<String>,
|
||||
/// `[daemon].bind_addr` if a daemon is configured on this host. Used to
|
||||
/// derive the default daemon URL when `daemon_url` is unset.
|
||||
pub daemon_bind_addr: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl CliConfig {
|
||||
/// Load the subset of the unified file the CLI consumes. A missing file is
|
||||
/// fine — every field has a default.
|
||||
pub fn load(path: &Path) -> Result<Self, ConfigError> {
|
||||
let file = MaestroConfigFile::load(path)?;
|
||||
Ok(Self {
|
||||
daemon_url: file.cli.daemon_url,
|
||||
daemon_bind_addr: file.daemon.bind_addr,
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve the daemon HTTP base to talk to.
|
||||
///
|
||||
/// Precedence: explicit `override_url` (CLI flag / env) → `[cli].daemon_url`
|
||||
/// → `http://<[daemon].bind_addr>` → [`DEFAULT_DAEMON_URL`]. Always returns
|
||||
/// a value; reachability is decided by whether the connection succeeds.
|
||||
pub fn resolve_daemon_url(&self, override_url: Option<String>) -> String {
|
||||
override_url
|
||||
.or_else(|| self.daemon_url.clone())
|
||||
.or_else(|| self.daemon_bind_addr.map(|a| format!("http://{a}")))
|
||||
.unwrap_or_else(|| DEFAULT_DAEMON_URL.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write_file(path: &Path, body: &str) {
|
||||
std::fs::write(path, body).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_file_returns_empty() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cfg = CliConfig::load(&dir.path().join("config.toml")).unwrap();
|
||||
assert_eq!(cfg, CliConfig::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_daemon_url_precedence() {
|
||||
// override wins over everything
|
||||
let cfg = CliConfig {
|
||||
daemon_url: Some("http://from-cli-section:7070".into()),
|
||||
daemon_bind_addr: Some("127.0.0.1:9999".parse().unwrap()),
|
||||
};
|
||||
assert_eq!(
|
||||
cfg.resolve_daemon_url(Some("http://override:1".into())),
|
||||
"http://override:1"
|
||||
);
|
||||
// [cli].daemon_url next
|
||||
assert_eq!(cfg.resolve_daemon_url(None), "http://from-cli-section:7070");
|
||||
// derive from [daemon].bind_addr when no explicit url
|
||||
let cfg = CliConfig {
|
||||
daemon_bind_addr: Some("10.0.0.7:7070".parse().unwrap()),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(cfg.resolve_daemon_url(None), "http://10.0.0.7:7070");
|
||||
// built-in default when nothing is configured
|
||||
let cfg = CliConfig::default();
|
||||
assert_eq!(cfg.resolve_daemon_url(None), DEFAULT_DAEMON_URL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_reads_daemon_url_and_daemon_bind_addr() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
write_file(
|
||||
&path,
|
||||
r#"
|
||||
[cli]
|
||||
daemon_url = "http://laptop:7070"
|
||||
|
||||
[daemon]
|
||||
bind_addr = "127.0.0.1:7071"
|
||||
"#,
|
||||
);
|
||||
let cfg = CliConfig::load(&path).unwrap();
|
||||
assert_eq!(cfg.daemon_url.as_deref(), Some("http://laptop:7070"));
|
||||
assert_eq!(
|
||||
cfg.daemon_bind_addr,
|
||||
Some("127.0.0.1:7071".parse().unwrap())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,19 +6,20 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::attach::{attach_url, parse_detach_key, run_attach_url};
|
||||
use crate::cli::{AttachArgs, Command, KillArgs, ListArgs, SpawnArgs};
|
||||
use crate::config::{default_config_path, CliConfig, ConfigError};
|
||||
use crate::http::DaemonClient;
|
||||
use maestro_protocol::DaemonClient;
|
||||
|
||||
use crate::attach::{parse_detach_key, run_attach_url};
|
||||
use crate::cli::Command;
|
||||
use crate::sessions::{run_kill, run_list, run_spawn};
|
||||
use maestro_config::{default_config_path, MaestroConfigFile};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[allow(clippy::result_large_err)]
|
||||
pub enum CliError {
|
||||
#[error("config: {0}")]
|
||||
Config(#[from] ConfigError),
|
||||
Config(#[from] maestro_config::ConfigError),
|
||||
#[error("{0}")]
|
||||
Http(#[from] crate::http::HttpError),
|
||||
Client(#[from] maestro_protocol::ClientError),
|
||||
#[error("{0}")]
|
||||
Attach(#[from] crate::attach::AttachError),
|
||||
#[error("{0}")]
|
||||
@@ -38,76 +39,42 @@ pub async fn dispatch(
|
||||
None => default_config_path()?,
|
||||
};
|
||||
|
||||
let daemon = client(&config_path, daemon_url_override)?;
|
||||
|
||||
match command {
|
||||
Command::List(args) => list(&config_path, daemon_url_override, args).await,
|
||||
Command::Spawn(args) => spawn(&config_path, daemon_url_override, args).await,
|
||||
Command::Attach(args) => attach(&config_path, daemon_url_override, args).await,
|
||||
Command::Kill(args) => kill(&config_path, daemon_url_override, args).await,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
async fn list(
|
||||
config_path: &Path,
|
||||
daemon_url_override: Option<String>,
|
||||
args: ListArgs,
|
||||
) -> Result<(), CliError> {
|
||||
let daemon = client(config_path, daemon_url_override)?;
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
run_list(&daemon, &args, &mut stdout).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
async fn spawn(
|
||||
config_path: &Path,
|
||||
daemon_url_override: Option<String>,
|
||||
args: SpawnArgs,
|
||||
) -> Result<(), CliError> {
|
||||
let daemon = client(config_path, daemon_url_override)?;
|
||||
let attach_after = args.attach;
|
||||
// `spawn --attach` has no detach-key flag; use the attach default (Ctrl-q).
|
||||
let detach_key = 0x11;
|
||||
|
||||
let session = run_spawn(&daemon, args).await?;
|
||||
println!("spawned {}", session.id);
|
||||
|
||||
if attach_after {
|
||||
let url = attach_url(daemon.base(), session.id)?;
|
||||
run_attach_url(&url, detach_key).await?;
|
||||
Command::List(args) => {
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
run_list(&daemon, &args, &mut stdout).await?;
|
||||
}
|
||||
Command::Spawn(args) => {
|
||||
let attach_after = args.attach;
|
||||
let session = run_spawn(&daemon, args).await?;
|
||||
println!("spawned {}", session.id);
|
||||
if attach_after {
|
||||
// `spawn --attach` has no detach-key flag; use the attach
|
||||
// default (Ctrl-q).
|
||||
run_attach_url(&daemon.attach_url(session.id)?, CTRL_Q).await?;
|
||||
}
|
||||
}
|
||||
Command::Attach(args) => {
|
||||
let detach = parse_detach_key(&args.detach_key)?;
|
||||
run_attach_url(&daemon.attach_url(args.session_id)?, detach).await?;
|
||||
}
|
||||
Command::Kill(args) => {
|
||||
run_kill(&daemon, &args).await?;
|
||||
println!("killed {}", args.session_id);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
async fn attach(
|
||||
config_path: &Path,
|
||||
daemon_url_override: Option<String>,
|
||||
args: AttachArgs,
|
||||
) -> Result<(), CliError> {
|
||||
let daemon = client(config_path, daemon_url_override)?;
|
||||
let detach = parse_detach_key(&args.detach_key)?;
|
||||
let url = attach_url(daemon.base(), args.session_id)?;
|
||||
run_attach_url(&url, detach).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
async fn kill(
|
||||
config_path: &Path,
|
||||
daemon_url_override: Option<String>,
|
||||
args: KillArgs,
|
||||
) -> Result<(), CliError> {
|
||||
let daemon = client(config_path, daemon_url_override)?;
|
||||
run_kill(&daemon, &args).await?;
|
||||
println!("killed {}", args.session_id);
|
||||
Ok(())
|
||||
}
|
||||
/// Default detach byte, matching `maestro attach --detach-key`'s `^q`.
|
||||
const CTRL_Q: u8 = 0x11;
|
||||
|
||||
/// HTTP client pointed at the daemon's API. That surface needs no auth —
|
||||
/// reaching `bind_addr` is the authorization.
|
||||
#[allow(clippy::result_large_err)]
|
||||
fn client(config_path: &Path, override_url: Option<String>) -> Result<DaemonClient, CliError> {
|
||||
let cfg = CliConfig::load(config_path)?;
|
||||
let cfg = MaestroConfigFile::load(config_path)?;
|
||||
Ok(DaemonClient::new(cfg.resolve_daemon_url(override_url)))
|
||||
}
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
//! Thin HTTP client wrapper around `reqwest` for the daemon's `/api/*` surface.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use reqwest::{Method, Response, StatusCode};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::config::ConfigError;
|
||||
|
||||
/// Time budget for establishing a TCP connection to the daemon.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Total time budget for a single request (connect + send + receive). Bounds
|
||||
/// the case where the peer is TCP-alive but never makes forward progress.
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Build a `reqwest::Client` with the CLI's standard timeouts and user-agent.
|
||||
///
|
||||
/// Centralizing construction here guarantees every client the CLI uses gets a
|
||||
/// connect *and* request timeout, so `maestro` never hangs forever on an
|
||||
/// unhealthy daemon (NAP-262).
|
||||
pub fn build_client() -> reqwest::Client {
|
||||
build_client_with_timeouts(CONNECT_TIMEOUT, REQUEST_TIMEOUT)
|
||||
}
|
||||
|
||||
fn build_client_with_timeouts(connect: Duration, request: Duration) -> reqwest::Client {
|
||||
reqwest::Client::builder()
|
||||
.user_agent(concat!("maestro-cli/", env!("CARGO_PKG_VERSION")))
|
||||
.connect_timeout(connect)
|
||||
.timeout(request)
|
||||
.build()
|
||||
.expect("build reqwest client")
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum HttpError {
|
||||
#[error("http: {0}")]
|
||||
Reqwest(#[from] reqwest::Error),
|
||||
#[error("server returned {status}: {body}")]
|
||||
ServerError { status: StatusCode, body: String },
|
||||
#[error("decode: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("config: {0}")]
|
||||
Config(#[from] ConfigError),
|
||||
}
|
||||
|
||||
impl HttpError {
|
||||
/// True when the error is a transport-level failure to reach the host
|
||||
/// (connection refused / connect error) rather than an HTTP-level
|
||||
/// rejection.
|
||||
pub fn is_unreachable(&self) -> bool {
|
||||
matches!(self, HttpError::Reqwest(e) if e.is_connect())
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP client bound to one daemon's `/api/*` base URL. The daemon's surface
|
||||
/// needs no auth — reaching its bind address is the authorization.
|
||||
#[derive(Debug)]
|
||||
pub struct DaemonClient {
|
||||
base: String,
|
||||
inner: reqwest::Client,
|
||||
}
|
||||
|
||||
impl DaemonClient {
|
||||
pub fn new(base: String) -> Self {
|
||||
Self {
|
||||
base: base.trim_end_matches('/').to_string(),
|
||||
inner: build_client(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn base(&self) -> &str {
|
||||
&self.base
|
||||
}
|
||||
|
||||
async fn send(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
body: Option<serde_json::Value>,
|
||||
) -> Result<Response, HttpError> {
|
||||
let url = format!("{}{}", self.base, path);
|
||||
let mut req = self.inner.request(method, &url);
|
||||
if let Some(b) = body {
|
||||
req = req.json(&b);
|
||||
}
|
||||
Ok(req.send().await?)
|
||||
}
|
||||
|
||||
pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T, HttpError> {
|
||||
let resp = self.send(Method::GET, path, None).await?;
|
||||
ok_or_body(resp)
|
||||
.await?
|
||||
.json::<T>()
|
||||
.await
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub async fn post_json<B: Serialize, T: DeserializeOwned>(
|
||||
&self,
|
||||
path: &str,
|
||||
body: &B,
|
||||
) -> Result<T, HttpError> {
|
||||
let v = serde_json::to_value(body)?;
|
||||
let resp = self.send(Method::POST, path, Some(v)).await?;
|
||||
ok_or_body(resp)
|
||||
.await?
|
||||
.json::<T>()
|
||||
.await
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub async fn delete(&self, path: &str) -> Result<(), HttpError> {
|
||||
let resp = self.send(Method::DELETE, path, None).await?;
|
||||
ok_or_body(resp).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn ok_or_body(resp: Response) -> Result<Response, HttpError> {
|
||||
let status = resp.status();
|
||||
if status.is_success() {
|
||||
return Ok(resp);
|
||||
}
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
Err(HttpError::ServerError { status, body })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A peer that accepts the TCP connection but never sends a response must
|
||||
/// not hang the client forever: the request timeout has to fire (NAP-262).
|
||||
#[tokio::test]
|
||||
async fn request_timeout_fires_when_peer_never_responds() {
|
||||
use std::io::Read;
|
||||
use std::net::TcpListener;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
// Accept one connection and sit on it without ever writing a response.
|
||||
let handle = std::thread::spawn(move || {
|
||||
if let Ok((mut sock, _)) = listener.accept() {
|
||||
let mut buf = [0u8; 1024];
|
||||
let _ = sock.read(&mut buf);
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
}
|
||||
});
|
||||
|
||||
let client = build_client_with_timeouts(Duration::from_secs(5), Duration::from_millis(300));
|
||||
let err = client
|
||||
.get(format!("http://{addr}/"))
|
||||
.send()
|
||||
.await
|
||||
.expect_err("request should time out, not hang");
|
||||
assert!(err.is_timeout(), "expected timeout error, got: {err}");
|
||||
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,7 @@
|
||||
|
||||
pub mod attach;
|
||||
pub mod cli;
|
||||
pub mod config;
|
||||
pub mod dispatch;
|
||||
pub mod http;
|
||||
pub mod sessions;
|
||||
|
||||
pub use dispatch::{dispatch, CliError};
|
||||
|
||||
@@ -3,31 +3,22 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
|
||||
use maestro_protocol::{ActivityState, CreateSessionRequest, Session, SessionStatus, WorktreeSpec};
|
||||
use serde::Deserialize;
|
||||
use maestro_protocol::{
|
||||
ActivityState, ClientError, CreateSessionRequest, DaemonClient, DaemonInfo, Session,
|
||||
SessionStatus, WorktreeSpec,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::cli::{KillArgs, ListArgs, SpawnArgs};
|
||||
use crate::http::{DaemonClient, HttpError};
|
||||
|
||||
/// The bits of `GET /api/info` the CLI renders. Deserialized structurally so
|
||||
/// the CLI doesn't depend on the daemon crate.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct DaemonInfo {
|
||||
#[serde(default)]
|
||||
pub hostname: String,
|
||||
#[serde(default)]
|
||||
pub home_dir: String,
|
||||
}
|
||||
|
||||
/// `maestro list`
|
||||
pub async fn run_list(
|
||||
client: &DaemonClient,
|
||||
args: &ListArgs,
|
||||
out: &mut impl Write,
|
||||
) -> Result<(), HttpError> {
|
||||
let sessions: Vec<Session> = client.get_json("/api/sessions").await?;
|
||||
let info: DaemonInfo = client.get_json("/api/info").await.unwrap_or_default();
|
||||
) -> Result<(), ClientError> {
|
||||
let sessions = client.list_sessions().await?;
|
||||
let info = client.daemon_info().await.unwrap_or_default();
|
||||
|
||||
if args.json {
|
||||
let body = serde_json::json!({ "sessions": sessions });
|
||||
@@ -40,7 +31,7 @@ pub async fn run_list(
|
||||
}
|
||||
|
||||
/// `maestro spawn`
|
||||
pub async fn run_spawn(client: &DaemonClient, args: SpawnArgs) -> Result<Session, HttpError> {
|
||||
pub async fn run_spawn(client: &DaemonClient, args: SpawnArgs) -> Result<Session, ClientError> {
|
||||
let mut env: HashMap<String, String> = HashMap::new();
|
||||
for (k, v) in args.env.iter() {
|
||||
env.insert(k.clone(), v.clone());
|
||||
@@ -53,6 +44,7 @@ pub async fn run_spawn(client: &DaemonClient, args: SpawnArgs) -> Result<Session
|
||||
base_repo: repo.clone(),
|
||||
branch: branch.clone(),
|
||||
cleanup_on_kill: args.cleanup_on_kill,
|
||||
create_branch: !args.existing_branch,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
@@ -64,15 +56,12 @@ pub async fn run_spawn(client: &DaemonClient, args: SpawnArgs) -> Result<Session
|
||||
metadata,
|
||||
worktree,
|
||||
};
|
||||
let session: Session = client.post_json("/api/sessions", &body).await?;
|
||||
Ok(session)
|
||||
client.create_session(&body).await
|
||||
}
|
||||
|
||||
/// `maestro kill`
|
||||
pub async fn run_kill(client: &DaemonClient, args: &KillArgs) -> Result<(), HttpError> {
|
||||
client
|
||||
.delete(&format!("/api/sessions/{}", args.session_id))
|
||||
.await
|
||||
pub async fn run_kill(client: &DaemonClient, args: &KillArgs) -> Result<(), ClientError> {
|
||||
client.kill_session(args.session_id).await
|
||||
}
|
||||
|
||||
#[allow(clippy::write_literal)]
|
||||
@@ -86,7 +75,17 @@ fn print_session_table(out: &mut impl Write, sessions: &[Session], info: &Daemon
|
||||
sorted.sort_by_key(|s| s.created_at);
|
||||
|
||||
if !info.hostname.is_empty() {
|
||||
writeln!(out, "\n{}", info.hostname).ok();
|
||||
let warn = if maestro_protocol::is_compatible(&info.version) {
|
||||
""
|
||||
} else {
|
||||
" (protocol mismatch)"
|
||||
};
|
||||
let version = if info.version.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" maestro {}{warn}", info.version)
|
||||
};
|
||||
writeln!(out, "\n{}{version}", info.hostname).ok();
|
||||
}
|
||||
writeln!(
|
||||
out,
|
||||
@@ -167,6 +166,7 @@ mod tests {
|
||||
DaemonInfo {
|
||||
hostname: "naps-laptop".into(),
|
||||
home_dir: home.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! The CLI against a daemon. It had no such tests: `maestro list`'s formatting
|
||||
//! was unit-tested, but nothing exercised the client, the error decoding, or
|
||||
//! the unreachable-daemon path without compiling and forking a real daemon.
|
||||
|
||||
use maestro_protocol::{DaemonClient, DaemonInfo};
|
||||
use maestro_testing::{session, MockDaemon};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_reads_the_daemon_catalog() {
|
||||
let mock = MockDaemon::start().await;
|
||||
mock.add_session(session(Uuid::from_u128(1), "/home/mock/work", "claude"));
|
||||
|
||||
let sessions = mock.client().list_sessions().await.expect("list");
|
||||
|
||||
assert_eq!(sessions.len(), 1);
|
||||
assert_eq!(sessions[0].command, "claude");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn info_carries_version_and_presets() {
|
||||
let mock = MockDaemon::start().await;
|
||||
mock.set_info(DaemonInfo {
|
||||
hostname: "konishi".into(),
|
||||
version: "9.9.9".into(),
|
||||
home_dir: "/home/naps".into(),
|
||||
presets: vec![maestro_protocol::SpawnPreset {
|
||||
id: "claude".into(),
|
||||
label: "Claude".into(),
|
||||
command: "claude".into(),
|
||||
}],
|
||||
});
|
||||
|
||||
let info = mock.client().daemon_info().await.expect("info");
|
||||
|
||||
// The CLI's own DaemonInfo used to drop both of these fields.
|
||||
assert_eq!(info.version, "9.9.9");
|
||||
assert_eq!(info.presets.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_structured_failure_surfaces_the_daemon_message() {
|
||||
let mock = MockDaemon::start().await;
|
||||
mock.force_error(502, "tmux_failed", "no server running");
|
||||
|
||||
let err = mock
|
||||
.client()
|
||||
.list_sessions()
|
||||
.await
|
||||
.expect_err("should fail");
|
||||
|
||||
assert_eq!(
|
||||
err.daemon_message(),
|
||||
Some("no server running"),
|
||||
"the daemon's own message must survive: {err}"
|
||||
);
|
||||
assert!(!err.is_unreachable());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unreachable_daemon_is_distinguishable_from_a_rejection() {
|
||||
// Port 1 has nothing listening on it.
|
||||
let client = DaemonClient::new("http://127.0.0.1:1");
|
||||
|
||||
let err = client.list_sessions().await.expect_err("should fail");
|
||||
|
||||
assert!(
|
||||
err.is_unreachable(),
|
||||
"connection refused must not read as an HTTP rejection: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn killing_an_unknown_session_reports_the_daemon_reason() {
|
||||
let mock = MockDaemon::start().await;
|
||||
|
||||
let err = mock
|
||||
.client()
|
||||
.kill_session(Uuid::new_v4())
|
||||
.await
|
||||
.expect_err("should fail");
|
||||
|
||||
assert_eq!(err.daemon_message(), Some("no such session on this daemon"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_round_trips_through_the_daemon() {
|
||||
let mock = MockDaemon::start().await;
|
||||
|
||||
let created = mock
|
||||
.client()
|
||||
.create_session(&maestro_protocol::CreateSessionRequest {
|
||||
cwd: "/home/mock".into(),
|
||||
command: "bash".into(),
|
||||
env: Default::default(),
|
||||
metadata: Default::default(),
|
||||
worktree: None,
|
||||
})
|
||||
.await
|
||||
.expect("create");
|
||||
|
||||
assert_eq!(created.command, "bash");
|
||||
assert_eq!(mock.session_count(), 1);
|
||||
|
||||
mock.client().kill_session(created.id).await.expect("kill");
|
||||
assert_eq!(mock.session_count(), 0);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dirs.workspace = true
|
||||
maestro-protocol.workspace = true
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
toml.workspace = true
|
||||
|
||||
+116
-210
@@ -22,14 +22,15 @@ use std::collections::BTreeMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Directory name under `$XDG_CONFIG_HOME` (default `~/.config`).
|
||||
pub const DIR_NAME: &str = "maestro";
|
||||
/// File name inside [`DIR_NAME`].
|
||||
pub const FILE_NAME: &str = "config.toml";
|
||||
/// Env var that, when set, overrides the resolved config-file path.
|
||||
pub const CONFIG_PATH_ENV: &str = "MAESTRO_CONFIG";
|
||||
|
||||
/// Last-resort daemon HTTP base, matching the daemon's own default `bind_addr`.
|
||||
pub const DEFAULT_DAEMON_URL: &str = "http://127.0.0.1:7070";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
@@ -51,55 +52,50 @@ pub enum ConfigError {
|
||||
|
||||
/// On-disk representation of the unified config. Every section is optional
|
||||
/// so a partial file (e.g. just `[daemon]`) is valid.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct MaestroConfigFile {
|
||||
#[serde(default, skip_serializing_if = "CliSection::is_empty")]
|
||||
#[serde(default)]
|
||||
pub cli: CliSection,
|
||||
#[serde(default, skip_serializing_if = "DaemonSection::is_empty")]
|
||||
#[serde(default)]
|
||||
pub daemon: DaemonSection,
|
||||
#[serde(default, skip_serializing_if = "WebSection::is_empty")]
|
||||
#[serde(default)]
|
||||
pub web: WebSection,
|
||||
#[serde(default, skip_serializing_if = "TuiSection::is_empty")]
|
||||
#[serde(default)]
|
||||
pub tui: TuiSection,
|
||||
#[serde(default, skip_serializing_if = "SpawnSection::is_empty")]
|
||||
#[serde(default)]
|
||||
pub spawn: SpawnSection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct CliSection {
|
||||
/// HTTP base URL of the daemon the CLI talks to, e.g.
|
||||
/// `http://127.0.0.1:7070`. When unset, the CLI derives it from
|
||||
/// `[daemon].bind_addr` if a daemon is configured locally, else falls
|
||||
/// back to `http://127.0.0.1:7070`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub daemon_url: Option<String>,
|
||||
}
|
||||
|
||||
impl CliSection {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.daemon_url.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct DaemonSection {
|
||||
/// Hostname advertised to clients, purely for display. Defaults to
|
||||
/// `gethostname(2)`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub hostname: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub bind_addr: Option<SocketAddr>,
|
||||
/// Root for everything daemon-local: sidecars, FIFOs, etc.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub state_dir: Option<PathBuf>,
|
||||
/// Root for ephemeral worktrees the daemon creates on `CreateSession`
|
||||
/// with a `worktree` spec.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
/// Override root for ephemeral worktrees the daemon creates on
|
||||
/// `CreateSession` with a `worktree` spec. Unset by default: worktrees
|
||||
/// then live inside their base repo at `<repo>/worktrees/<branch>` (#56).
|
||||
#[serde(default)]
|
||||
pub worktree_root: Option<PathBuf>,
|
||||
/// Per-session PTY replay buffer cap in bytes (NAP-229). Each new attach
|
||||
/// receives this much of the prior PTY output before the live stream.
|
||||
/// `None` ⇒ daemon default (~64 KB); `Some(0)` disables replay.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub pty_replay_bytes: Option<usize>,
|
||||
/// `TMUX_TMPDIR` the daemon exports for every `tmux` invocation (NAP-234).
|
||||
/// When unset, the daemon defaults to `$XDG_RUNTIME_DIR` so that bare
|
||||
@@ -107,50 +103,27 @@ pub struct DaemonSection {
|
||||
/// maestro sessions. Set to `/tmp` to opt back into tmux's own default —
|
||||
/// useful if the daemon outlives the user's login session and you can't
|
||||
/// enable `loginctl enable-linger`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub tmux_tmpdir: Option<PathBuf>,
|
||||
/// Recency cap in days for the durable spawn history that backs the spawn
|
||||
/// form's "recent dirs" picker (#24). `None` ⇒ daemon default (30 days);
|
||||
/// `Some(0)` disables history entirely (no log written, no recents read).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub spawn_history_days: Option<u32>,
|
||||
}
|
||||
|
||||
impl DaemonSection {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.hostname.is_none()
|
||||
&& self.bind_addr.is_none()
|
||||
&& self.state_dir.is_none()
|
||||
&& self.worktree_root.is_none()
|
||||
&& self.pty_replay_bytes.is_none()
|
||||
&& self.tmux_tmpdir.is_none()
|
||||
&& self.spawn_history_days.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// `[web]` — `maestro-web` binary settings (NAP-241).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct WebSection {
|
||||
/// Address `maestro-web` binds. Default `127.0.0.1:8080`. Bind a LAN/VPN
|
||||
/// address to share with your own devices on a trusted segment; there is no
|
||||
/// auth layer, so never bind a public address.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub bind_addr: Option<SocketAddr>,
|
||||
/// HTTP base URL of the co-located daemon `maestro-web` proxies to.
|
||||
/// Default `http://127.0.0.1:7070`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub daemon_url: Option<String>,
|
||||
/// When set, requests for `/` are proxied to a Vite dev server at this
|
||||
/// URL instead of being served from the embedded bundle. Use it during
|
||||
/// frontend development so live reload works.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub dev_proxy_target: Option<String>,
|
||||
}
|
||||
|
||||
impl WebSection {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.bind_addr.is_none() && self.daemon_url.is_none() && self.dev_proxy_target.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// `[tui]` — `maestro tui` settings (NAP-275 epic, phase 2 NAP-277).
|
||||
@@ -158,53 +131,49 @@ impl WebSection {
|
||||
/// Leader key, chord timeout, and per-mode keymap overrides. The TUI ships
|
||||
/// with a default keymap; entries in `keymap_normal` / `keymap_insert` are
|
||||
/// applied **over** the defaults, so a partial override is enough.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct TuiSection {
|
||||
/// Canonical key form, e.g. `"ctrl-a"`. Default `ctrl-a`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub leader: Option<String>,
|
||||
/// Maximum interval between chord keys before a held prefix is dropped.
|
||||
/// Default `1000`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub chord_timeout_ms: Option<u64>,
|
||||
/// Normal-mode bindings: canonical input → action string. Applied over
|
||||
/// the shipped defaults.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[serde(default)]
|
||||
pub keymap_normal: BTreeMap<String, String>,
|
||||
/// Insert-mode bindings, same semantics as `keymap_normal`.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[serde(default)]
|
||||
pub keymap_insert: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl TuiSection {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.leader.is_none()
|
||||
&& self.chord_timeout_ms.is_none()
|
||||
&& self.keymap_normal.is_empty()
|
||||
&& self.keymap_insert.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// `[spawn]` — command presets for the spawn form (#22, part of #21).
|
||||
///
|
||||
/// Defined in shared config so every binary sees the same list: the web reads
|
||||
/// it via the daemon's catalog advertisement (#26), the TUI adopts it later.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct SpawnSection {
|
||||
/// Command presets offered as one-click tiles. When present, this list
|
||||
/// **replaces** the [`builtin_presets`] defaults (the implicit `custom`
|
||||
/// escape hatch is still appended by [`SpawnSection::resolve`]); when
|
||||
/// absent, the built-ins are used. `presets = []` is "present but empty" —
|
||||
/// it resolves to just the `custom` tile.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub presets: Option<Vec<SpawnPreset>>,
|
||||
/// Root directories the daemon scans for git repositories (#54), `~`
|
||||
/// expanded by the daemon against its own home. When absent the daemon
|
||||
/// scans `["~"]`.
|
||||
#[serde(default)]
|
||||
pub project_roots: Option<Vec<String>>,
|
||||
/// How many directory levels below each [`Self::project_roots`] entry the
|
||||
/// scanner descends (#54). When absent the daemon uses `3`.
|
||||
#[serde(default)]
|
||||
pub project_scan_depth: Option<u32>,
|
||||
}
|
||||
|
||||
impl SpawnSection {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.presets.is_none()
|
||||
}
|
||||
|
||||
/// The presets to show, in order, with the implicit `custom` tile appended.
|
||||
///
|
||||
/// Resolution: configured `presets` if present, else [`builtin_presets`];
|
||||
@@ -226,12 +195,10 @@ impl SpawnSection {
|
||||
/// tile, and the `command` to run. The implicit `custom` tile (see
|
||||
/// [`custom_preset`]) reuses this shape with an empty `command` the client
|
||||
/// fills from free-text input.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpawnPreset {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub command: String,
|
||||
}
|
||||
///
|
||||
/// Defined in `maestro-protocol` because it also rides `GET /api/info`; the
|
||||
/// on-disk `[spawn].presets` schema and the wire payload are one type.
|
||||
pub use maestro_protocol::SpawnPreset;
|
||||
|
||||
/// Reserved id for the implicit free-text tile. A user-defined preset may not
|
||||
/// claim it (see [`SpawnConfigError::ReservedCustomId`]) since it's always
|
||||
@@ -319,27 +286,20 @@ impl MaestroConfigFile {
|
||||
Ok(toml::from_str(s)?)
|
||||
}
|
||||
|
||||
/// Atomic write (tmp + rename). Creates parent dirs on demand.
|
||||
pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let body = toml::to_string_pretty(self)?;
|
||||
let tmp = path.with_extension("toml.tmp");
|
||||
std::fs::write(&tmp, body)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
/// Daemon HTTP base a client should talk to.
|
||||
///
|
||||
/// Precedence: explicit `override_url` (flag or env), then
|
||||
/// `[cli].daemon_url`, then `http://<[daemon].bind_addr>`, then
|
||||
/// [`DEFAULT_DAEMON_URL`]. Always yields a value — reachability is decided
|
||||
/// by whether the connection succeeds.
|
||||
pub fn resolve_daemon_url(&self, override_url: Option<String>) -> String {
|
||||
override_url
|
||||
.or_else(|| self.cli.daemon_url.clone())
|
||||
.or_else(|| self.daemon.bind_addr.map(|a| format!("http://{a}")))
|
||||
.unwrap_or_else(|| DEFAULT_DAEMON_URL.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// `$MAESTRO_CONFIG` if set, else [`default_config_path`].
|
||||
pub fn resolve_config_path() -> Result<PathBuf, ConfigError> {
|
||||
if let Some(p) = std::env::var_os(CONFIG_PATH_ENV) {
|
||||
return Ok(PathBuf::from(p));
|
||||
}
|
||||
default_config_path()
|
||||
}
|
||||
|
||||
/// `~/.config/maestro/config.toml` (XDG-aware).
|
||||
pub fn default_config_path() -> Result<PathBuf, ConfigError> {
|
||||
let base = dirs::config_dir().ok_or(ConfigError::NoConfigDir)?;
|
||||
@@ -368,32 +328,10 @@ pub fn default_state_dir(subdir: &str) -> Result<PathBuf, ConfigError> {
|
||||
.ok_or(ConfigError::NoConfigDir)?;
|
||||
Ok(base.join(subdir))
|
||||
}
|
||||
|
||||
/// Capacities for the daemon's broadcast channels (session events and PTY byte
|
||||
/// fan-out). These were independent `= 256` constants scattered across the
|
||||
/// daemon; centralizing them here makes the coincidence explicit and gives a
|
||||
/// single home for per-deployment tuning later (NAP-273).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BroadcastTuning {
|
||||
/// Session event channels (`SessionEvent`, `CatalogEvent`).
|
||||
pub events_capacity: usize,
|
||||
/// Per-session PTY byte broadcast channel.
|
||||
pub pty_capacity: usize,
|
||||
}
|
||||
|
||||
impl BroadcastTuning {
|
||||
/// The historical defaults — every channel was 256 by coincidence.
|
||||
pub const DEFAULT: Self = Self {
|
||||
events_capacity: 256,
|
||||
pty_capacity: 256,
|
||||
};
|
||||
}
|
||||
|
||||
impl Default for BroadcastTuning {
|
||||
fn default() -> Self {
|
||||
Self::DEFAULT
|
||||
}
|
||||
}
|
||||
/// Capacity of the session-event broadcast channel (`CatalogEvent`).
|
||||
pub const EVENTS_CAPACITY: usize = 256;
|
||||
/// Capacity of the per-session PTY byte broadcast channel.
|
||||
pub const PTY_CAPACITY: usize = 256;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -424,10 +362,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broadcast_tuning_defaults_to_256() {
|
||||
assert_eq!(BroadcastTuning::default(), BroadcastTuning::DEFAULT);
|
||||
assert_eq!(BroadcastTuning::DEFAULT.events_capacity, 256);
|
||||
assert_eq!(BroadcastTuning::DEFAULT.pty_capacity, 256);
|
||||
fn broadcast_capacities_are_the_historical_defaults() {
|
||||
assert_eq!(EVENTS_CAPACITY, 256);
|
||||
assert_eq!(PTY_CAPACITY, 256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -438,46 +375,6 @@ mod tests {
|
||||
assert_eq!(cfg, MaestroConfigFile::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_file_round_trips() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
let cfg = MaestroConfigFile {
|
||||
cli: CliSection {
|
||||
daemon_url: Some("http://127.0.0.1:7070".into()),
|
||||
},
|
||||
daemon: DaemonSection {
|
||||
hostname: Some("laptop.lan".into()),
|
||||
bind_addr: Some("127.0.0.1:7070".parse().unwrap()),
|
||||
state_dir: Some(PathBuf::from("/var/lib/maestrod")),
|
||||
worktree_root: Some(PathBuf::from("/var/lib/maestrod/wt")),
|
||||
pty_replay_bytes: Some(131_072),
|
||||
tmux_tmpdir: Some(PathBuf::from("/run/user/1000")),
|
||||
spawn_history_days: Some(14),
|
||||
},
|
||||
web: WebSection {
|
||||
bind_addr: Some("127.0.0.1:8080".parse().unwrap()),
|
||||
daemon_url: Some("http://127.0.0.1:7070".into()),
|
||||
dev_proxy_target: Some("http://127.0.0.1:5173".into()),
|
||||
},
|
||||
tui: TuiSection {
|
||||
leader: Some("ctrl-b".into()),
|
||||
chord_timeout_ms: Some(750),
|
||||
keymap_normal: BTreeMap::from([("i".into(), "ShowHelp".into())]),
|
||||
keymap_insert: BTreeMap::new(),
|
||||
},
|
||||
spawn: SpawnSection {
|
||||
presets: Some(vec![SpawnPreset {
|
||||
id: "claude".into(),
|
||||
label: "Claude".into(),
|
||||
command: "claude --resume".into(),
|
||||
}]),
|
||||
},
|
||||
};
|
||||
cfg.save(&path).unwrap();
|
||||
assert_eq!(MaestroConfigFile::load(&path).unwrap(), cfg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_presets_default_to_builtins_plus_custom() {
|
||||
// Absent [spawn].presets → built-ins, with the implicit custom tile last.
|
||||
@@ -499,6 +396,7 @@ mod tests {
|
||||
label: "fish".into(),
|
||||
command: "fish".into(),
|
||||
}]),
|
||||
..Default::default()
|
||||
};
|
||||
let ids: Vec<String> = section
|
||||
.resolve()
|
||||
@@ -515,6 +413,7 @@ mod tests {
|
||||
// only the implicit custom tile.
|
||||
let section = SpawnSection {
|
||||
presets: Some(vec![]),
|
||||
..Default::default()
|
||||
};
|
||||
let ids: Vec<String> = section
|
||||
.resolve()
|
||||
@@ -533,6 +432,7 @@ mod tests {
|
||||
label: "x".into(),
|
||||
command: "x".into(),
|
||||
}]),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(empty_id.resolve().unwrap_err(), SpawnConfigError::EmptyId);
|
||||
|
||||
@@ -542,6 +442,7 @@ mod tests {
|
||||
label: "x".into(),
|
||||
command: "".into(),
|
||||
}]),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
empty_cmd.resolve().unwrap_err(),
|
||||
@@ -564,6 +465,7 @@ mod tests {
|
||||
command: "a2".into(),
|
||||
},
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
dup.resolve().unwrap_err(),
|
||||
@@ -576,6 +478,7 @@ mod tests {
|
||||
label: "Custom".into(),
|
||||
command: "whatever".into(),
|
||||
}]),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
reserved.resolve().unwrap_err(),
|
||||
@@ -610,20 +513,27 @@ presets = [
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_omits_empty_spawn_section() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
MaestroConfigFile {
|
||||
daemon: DaemonSection {
|
||||
hostname: Some("laptop".into()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
.save(&path)
|
||||
.unwrap();
|
||||
let body = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(!body.contains("[spawn]"), "body: {body}");
|
||||
fn spawn_project_scan_fields_default_to_none() {
|
||||
// Absent [spawn].project_* → None; the daemon applies its own defaults.
|
||||
assert_eq!(SpawnSection::default().project_roots, None);
|
||||
assert_eq!(SpawnSection::default().project_scan_depth, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_project_scan_fields_parse_from_toml() {
|
||||
let cfg = toml::from_str::<MaestroConfigFile>(
|
||||
r#"
|
||||
[spawn]
|
||||
project_roots = ["~/code", "/srv/work"]
|
||||
project_scan_depth = 5
|
||||
"#,
|
||||
)
|
||||
.expect("parse");
|
||||
assert_eq!(
|
||||
cfg.spawn.project_roots,
|
||||
Some(vec!["~/code".to_string(), "/srv/work".to_string()])
|
||||
);
|
||||
assert_eq!(cfg.spawn.project_scan_depth, Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -648,40 +558,36 @@ bind_addr = "127.0.0.1:9090"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_omits_empty_sections() {
|
||||
// Avoid littering the file with empty `[cli]` / `[daemon]` tables
|
||||
// when only one component is configured.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
let cfg = MaestroConfigFile {
|
||||
daemon: DaemonSection {
|
||||
hostname: Some("laptop".into()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
cfg.save(&path).unwrap();
|
||||
let body = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(body.contains("[daemon]"), "body: {body}");
|
||||
assert!(!body.contains("[cli]"), "body: {body}");
|
||||
assert!(!body.contains("[web]"), "body: {body}");
|
||||
fn file_with(body: &str) -> MaestroConfigFile {
|
||||
toml::from_str(body).expect("parse")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_atomic_creates_parent_dirs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("nested/here/config.toml");
|
||||
MaestroConfigFile::default().save(&path).unwrap();
|
||||
assert!(path.exists());
|
||||
fn daemon_url_prefers_an_explicit_override() {
|
||||
let cfg = file_with("[cli]\ndaemon_url = \"http://from-file:1\"\n");
|
||||
assert_eq!(
|
||||
cfg.resolve_daemon_url(Some("http://override:2".into())),
|
||||
"http://override:2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_config_path_respects_env_var() {
|
||||
// We can't safely tweak the process env in a unit test (it races with
|
||||
// other tests). Exercise the default path branch instead and rely on
|
||||
// an integration-level smoke that env-override works.
|
||||
let p = default_config_path().unwrap();
|
||||
assert!(p.ends_with(format!("{DIR_NAME}/{FILE_NAME}")));
|
||||
fn daemon_url_falls_back_through_cli_then_bind_addr_then_default() {
|
||||
let from_cli = file_with("[cli]\ndaemon_url = \"http://from-cli:1\"\n");
|
||||
assert_eq!(from_cli.resolve_daemon_url(None), "http://from-cli:1");
|
||||
|
||||
let from_bind = file_with("[daemon]\nbind_addr = \"10.0.0.1:7070\"\n");
|
||||
assert_eq!(from_bind.resolve_daemon_url(None), "http://10.0.0.1:7070");
|
||||
|
||||
let empty = MaestroConfigFile::default();
|
||||
assert_eq!(empty.resolve_daemon_url(None), DEFAULT_DAEMON_URL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_daemon_url_beats_a_locally_configured_bind_addr() {
|
||||
let cfg = file_with(
|
||||
"[cli]\ndaemon_url = \"http://explicit:1\"\n[daemon]\nbind_addr = \"10.0.0.1:7070\"\n",
|
||||
);
|
||||
assert_eq!(cfg.resolve_daemon_url(None), "http://explicit:1");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,29 +6,26 @@
|
||||
use axum::extract::ws::{Message, WebSocket};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use maestro_protocol::ClientControl;
|
||||
use tokio::sync::broadcast;
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::session::SessionManager;
|
||||
|
||||
/// Pump a WebSocket against a session's PTY, behind `WS /api/attach/:id`.
|
||||
///
|
||||
/// The subscription is acquired by the handler *before* the upgrade and handed
|
||||
/// in here, so there is no window in which the session can disappear between
|
||||
/// the existence check and the subscribe.
|
||||
pub(crate) async fn serve(
|
||||
socket: WebSocket,
|
||||
manager: SessionManager,
|
||||
id: Uuid,
|
||||
replay: Vec<u8>,
|
||||
mut rx: broadcast::Receiver<Vec<u8>>,
|
||||
) -> Result<(), axum::Error> {
|
||||
let (mut sink, mut stream) = socket.split();
|
||||
|
||||
let (replay, mut rx) = match manager.subscribe_pty_with_replay(id).await {
|
||||
Some(pair) => pair,
|
||||
None => {
|
||||
// session was killed between the existence check and now — let the
|
||||
// client see a clean close instead of a dropped socket.
|
||||
let _ = sink.send(Message::Close(None)).await;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
// NAP-229: send buffered scrollback up-front so the client sees the last
|
||||
// screenful immediately instead of a blank terminal. The replay lock the
|
||||
// bridge held during snapshot+subscribe guarantees no byte appears both
|
||||
|
||||
@@ -12,8 +12,7 @@ use crate::sidecar::SidecarStore;
|
||||
use crate::tmux::Tmux;
|
||||
use crate::worktree::WorktreeManager;
|
||||
use crate::{
|
||||
default_config_path, default_state_dir, load_config, local_api, spawn_session_publisher,
|
||||
EnvOverrides, LocalEventBus, SessionManager,
|
||||
default_config_path, default_state_dir, load_config, local_api, EnvOverrides, SessionManager,
|
||||
};
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
@@ -48,7 +47,8 @@ async fn run(config_override: Option<PathBuf>) -> Result<(), Box<dyn Error>> {
|
||||
let _ = default_state_dir();
|
||||
std::fs::create_dir_all(config.sidecar_dir())?;
|
||||
std::fs::create_dir_all(config.fifo_dir())?;
|
||||
std::fs::create_dir_all(&config.worktree_root)?;
|
||||
// No worktree dir to pre-create: without an override the worktrees live
|
||||
// under their base repos, created on demand (#56).
|
||||
|
||||
let sidecar = SidecarStore::new(config.sidecar_dir());
|
||||
let worktree_mgr = WorktreeManager::new(config.worktree_root.clone());
|
||||
@@ -57,7 +57,7 @@ async fn run(config_override: Option<PathBuf>) -> Result<(), Box<dyn Error>> {
|
||||
None => Tmux::new(),
|
||||
};
|
||||
let manager = SessionManager::new_with_replay(
|
||||
tmux,
|
||||
std::sync::Arc::new(tmux),
|
||||
sidecar,
|
||||
worktree_mgr,
|
||||
config.fifo_dir(),
|
||||
@@ -72,15 +72,19 @@ async fn run(config_override: Option<PathBuf>) -> Result<(), Box<dyn Error>> {
|
||||
tracing::info!(recovered, "adopted existing tmux sessions");
|
||||
manager.start_liveness_watcher(DEFAULT_LIVENESS_INTERVAL);
|
||||
|
||||
let events = LocalEventBus::new();
|
||||
spawn_session_publisher(manager.clone(), events.clone());
|
||||
let projects = std::sync::Arc::new(crate::projects::ProjectScanner::new(
|
||||
config.project_roots.clone(),
|
||||
config.project_scan_depth,
|
||||
PathBuf::from(&config.home_dir),
|
||||
));
|
||||
projects.start_background_refresh();
|
||||
|
||||
let router = local_api::router(local_api::state_for(
|
||||
manager,
|
||||
config.hostname.clone(),
|
||||
config.home_dir.clone(),
|
||||
config.spawn_presets.clone(),
|
||||
events,
|
||||
projects,
|
||||
));
|
||||
|
||||
let listener = TcpListener::bind(config.bind_addr).await?;
|
||||
|
||||
@@ -14,9 +14,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use maestro_config::MaestroConfigFile;
|
||||
|
||||
pub use maestro_config::{
|
||||
default_config_path, resolve_config_path, DaemonSection, CONFIG_PATH_ENV,
|
||||
};
|
||||
pub use maestro_config::default_config_path;
|
||||
|
||||
/// Default bind address when neither env nor file specify one.
|
||||
pub const DEFAULT_BIND_ADDR: &str = "127.0.0.1:7070";
|
||||
@@ -25,6 +23,14 @@ pub const DEFAULT_BIND_ADDR: &str = "127.0.0.1:7070";
|
||||
/// `[daemon].spawn_history_days` is unset. `0` in config disables history.
|
||||
pub const DEFAULT_SPAWN_HISTORY_DAYS: u32 = 30;
|
||||
|
||||
/// Default scan roots for project discovery (#54) when `[spawn].project_roots`
|
||||
/// is unset: the whole home directory, with the scanner's own ignore list
|
||||
/// keeping it cheap.
|
||||
pub const DEFAULT_PROJECT_ROOTS: [&str; 1] = ["~"];
|
||||
/// Default directory depth for project discovery (#54) when
|
||||
/// `[spawn].project_scan_depth` is unset.
|
||||
pub const DEFAULT_PROJECT_SCAN_DEPTH: u32 = 3;
|
||||
|
||||
/// Env var that overrides `[daemon].bind_addr`.
|
||||
pub const ENV_DAEMON_BIND_ADDR: &str = "MAESTRO_DAEMON_BIND_ADDR";
|
||||
/// Env var that overrides `[daemon].tmux_tmpdir`.
|
||||
@@ -55,7 +61,10 @@ pub struct DaemonConfig {
|
||||
pub home_dir: String,
|
||||
pub bind_addr: SocketAddr,
|
||||
pub state_dir: PathBuf,
|
||||
pub worktree_root: PathBuf,
|
||||
/// `[daemon].worktree_root` override (#56). `None` — the default — places
|
||||
/// worktrees inside their base repo at `<repo>/worktrees/<branch>`;
|
||||
/// operators who want them elsewhere set this.
|
||||
pub worktree_root: Option<PathBuf>,
|
||||
/// Per-session PTY replay buffer cap in bytes (NAP-229). Each new attach
|
||||
/// receives this much of the prior PTY output before the live stream.
|
||||
/// Default `pty::DEFAULT_REPLAY_BYTES`; `0` disables.
|
||||
@@ -73,6 +82,12 @@ pub struct DaemonConfig {
|
||||
/// built-ins) with the implicit `custom` tile appended. Advertised to
|
||||
/// clients in `GET /api/info`.
|
||||
pub spawn_presets: Vec<maestro_config::SpawnPreset>,
|
||||
/// Project-discovery scan roots (#54): `[spawn].project_roots` (default
|
||||
/// [`DEFAULT_PROJECT_ROOTS`]) with `~` expanded against the daemon's home.
|
||||
pub project_roots: Vec<PathBuf>,
|
||||
/// Project-discovery depth (#54): `[spawn].project_scan_depth`, default
|
||||
/// [`DEFAULT_PROJECT_SCAN_DEPTH`].
|
||||
pub project_scan_depth: u32,
|
||||
}
|
||||
|
||||
impl DaemonConfig {
|
||||
@@ -133,9 +148,6 @@ pub fn load_config(path: &Path, env: EnvOverrides) -> Result<DaemonConfig, Confi
|
||||
Some(p) => p,
|
||||
None => default_state_dir()?,
|
||||
};
|
||||
let worktree_root = daemon
|
||||
.worktree_root
|
||||
.unwrap_or_else(|| state_dir.join("worktrees"));
|
||||
|
||||
let pty_replay_bytes = daemon
|
||||
.pty_replay_bytes
|
||||
@@ -149,19 +161,53 @@ pub fn load_config(path: &Path, env: EnvOverrides) -> Result<DaemonConfig, Confi
|
||||
.spawn_history_days
|
||||
.unwrap_or(DEFAULT_SPAWN_HISTORY_DAYS);
|
||||
|
||||
// `~` in scan roots means the daemon's own home; an unresolvable home
|
||||
// leaves the tilde as-is and the scanner treats the root as missing.
|
||||
let project_roots: Vec<PathBuf> = file
|
||||
.spawn
|
||||
.project_roots
|
||||
.unwrap_or_else(|| {
|
||||
DEFAULT_PROJECT_ROOTS
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
})
|
||||
.iter()
|
||||
.map(|root| expand_tilde(root, &home_dir))
|
||||
.collect();
|
||||
let project_scan_depth = file
|
||||
.spawn
|
||||
.project_scan_depth
|
||||
.unwrap_or(DEFAULT_PROJECT_SCAN_DEPTH);
|
||||
|
||||
Ok(DaemonConfig {
|
||||
hostname,
|
||||
home_dir,
|
||||
bind_addr,
|
||||
state_dir,
|
||||
worktree_root,
|
||||
worktree_root: daemon.worktree_root,
|
||||
pty_replay_bytes,
|
||||
tmux_tmpdir,
|
||||
spawn_history_days,
|
||||
spawn_presets,
|
||||
project_roots,
|
||||
project_scan_depth,
|
||||
})
|
||||
}
|
||||
|
||||
/// Expand a leading `~` (or `~/…`) against `home`. Other paths pass through.
|
||||
fn expand_tilde(path: &str, home: &str) -> PathBuf {
|
||||
match path.strip_prefix("~") {
|
||||
Some(_) if home.is_empty() => PathBuf::from(path),
|
||||
Some(rest) => {
|
||||
let mut p = PathBuf::from(home);
|
||||
p.push(rest.trim_start_matches('/'));
|
||||
p
|
||||
}
|
||||
None => PathBuf::from(path),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_state_dir() -> Result<PathBuf, ConfigError> {
|
||||
Ok(maestro_config::default_state_dir("maestro")?)
|
||||
}
|
||||
@@ -190,7 +236,7 @@ mod tests {
|
||||
let cfg = load_config(&path, EnvOverrides::default()).unwrap();
|
||||
assert_eq!(cfg.bind_addr, default_bind_addr());
|
||||
assert!(cfg.state_dir.ends_with("maestro"));
|
||||
assert!(cfg.worktree_root.ends_with("worktrees"));
|
||||
assert!(cfg.worktree_root.is_none());
|
||||
assert!(!cfg.hostname.is_empty());
|
||||
}
|
||||
|
||||
@@ -282,6 +328,56 @@ spawn_history_days = 0
|
||||
assert_eq!(cfg.spawn_history_days, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_scan_defaults_to_home_root_at_depth_3() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
std::fs::write(&path, "").unwrap();
|
||||
let cfg = load_config(&path, EnvOverrides::default()).unwrap();
|
||||
assert_eq!(cfg.project_scan_depth, DEFAULT_PROJECT_SCAN_DEPTH);
|
||||
assert_eq!(
|
||||
cfg.project_roots,
|
||||
vec![PathBuf::from(cfg.home_dir.clone())],
|
||||
"bare ~ must expand to the daemon's home"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_scan_roots_expand_tilde_and_pass_through_absolutes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
std::fs::write(
|
||||
&path,
|
||||
r#"
|
||||
[spawn]
|
||||
project_roots = ["~/code", "/srv/work"]
|
||||
project_scan_depth = 5
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let cfg = load_config(&path, EnvOverrides::default()).unwrap();
|
||||
assert_eq!(cfg.project_scan_depth, 5);
|
||||
assert_eq!(
|
||||
cfg.project_roots,
|
||||
vec![
|
||||
PathBuf::from(cfg.home_dir.clone()).join("code"),
|
||||
PathBuf::from("/srv/work"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tilde_expansion_handles_bare_and_nested_forms() {
|
||||
assert_eq!(expand_tilde("~", "/home/u"), PathBuf::from("/home/u"));
|
||||
assert_eq!(
|
||||
expand_tilde("~/a/b", "/home/u"),
|
||||
PathBuf::from("/home/u/a/b")
|
||||
);
|
||||
assert_eq!(expand_tilde("/abs", "/home/u"), PathBuf::from("/abs"));
|
||||
// Unresolvable home leaves the tilde as-is rather than mangling it.
|
||||
assert_eq!(expand_tilde("~", ""), PathBuf::from("~"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_hostname_is_nonempty() {
|
||||
let h = system_hostname();
|
||||
|
||||
@@ -14,8 +14,9 @@ pub mod config;
|
||||
pub mod dirlist;
|
||||
pub mod gitroot;
|
||||
pub mod local_api;
|
||||
pub mod local_events;
|
||||
pub mod panes;
|
||||
pub mod proc;
|
||||
pub mod projects;
|
||||
pub mod pty;
|
||||
pub mod session;
|
||||
pub mod sidecar;
|
||||
@@ -24,5 +25,4 @@ pub mod tmux;
|
||||
pub mod worktree;
|
||||
|
||||
pub use config::{default_config_path, default_state_dir, load_config, DaemonConfig, EnvOverrides};
|
||||
pub use local_events::{spawn_session_publisher, LocalEventBus};
|
||||
pub use session::{SessionError, SessionEvent, SessionManager};
|
||||
pub use session::{SessionError, SessionManager};
|
||||
|
||||
@@ -19,31 +19,14 @@ use axum::routing::{any, delete, get};
|
||||
use axum::{Json, Router};
|
||||
use maestro_config::SpawnPreset;
|
||||
use maestro_protocol::{
|
||||
CatalogEvent, CreateSessionRequest, ErrorInfo, GitRoot, Session, PROTOCOL_VERSION,
|
||||
routes, ApiError, CatalogEvent, CreateSessionRequest, DaemonInfo, GitRoot, Session,
|
||||
PROTOCOL_VERSION,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::Deserialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::local_events::LocalEventBus;
|
||||
use crate::session::SessionManager;
|
||||
|
||||
/// Daemon identity returned by `GET /api/info`. Clients render this in the
|
||||
/// header ("you're connected to konishi"), plus the daemon's protocol version
|
||||
/// and its spawn presets (#26).
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DaemonInfo {
|
||||
pub hostname: String,
|
||||
pub version: String,
|
||||
/// Home directory of the OS user this daemon runs as, so clients can
|
||||
/// prefill a spawn form's working directory. Empty if unresolved.
|
||||
pub home_dir: String,
|
||||
/// Spawn-form command presets resolved from `[spawn].presets` (#22), with
|
||||
/// the implicit `custom` tile appended. Clients render these as one-click
|
||||
/// tiles; it rides this existing payload so opening the form needs no extra
|
||||
/// round-trip (#26).
|
||||
pub presets: Vec<SpawnPreset>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LocalApiState {
|
||||
pub manager: SessionManager,
|
||||
@@ -53,21 +36,21 @@ pub struct LocalApiState {
|
||||
pub home_dir: Arc<String>,
|
||||
/// Resolved spawn presets (#22/#26) advertised in `GET /api/info`.
|
||||
pub presets: Arc<Vec<SpawnPreset>>,
|
||||
/// Fan-out of session deltas (NAP-248). The `/api/events` WS subscribes
|
||||
/// here; everything else just reads REST.
|
||||
pub events: LocalEventBus,
|
||||
/// Project discovery (#54) backing `GET /api/projects`.
|
||||
pub projects: Arc<crate::projects::ProjectScanner>,
|
||||
}
|
||||
|
||||
pub fn router(state: LocalApiState) -> Router {
|
||||
Router::new()
|
||||
.route("/api/sessions", get(list_sessions).post(create_session))
|
||||
.route("/api/sessions/:id", delete(kill_session))
|
||||
.route("/api/dirs", get(list_dir))
|
||||
.route("/api/recent-dirs", get(recent_dirs))
|
||||
.route("/api/gitroot", get(git_root))
|
||||
.route("/api/info", get(daemon_info))
|
||||
.route("/api/events", any(events_ws))
|
||||
.route("/api/attach/:id", any(attach_ws))
|
||||
.route(routes::SESSIONS, get(list_sessions).post(create_session))
|
||||
.route(routes::patterns::SESSION, delete(kill_session))
|
||||
.route(routes::DIRS, get(list_dir))
|
||||
.route(routes::RECENT_DIRS, get(recent_dirs))
|
||||
.route(routes::PROJECTS, get(projects))
|
||||
.route(routes::GITROOT, get(git_root))
|
||||
.route(routes::INFO, get(daemon_info))
|
||||
.route(routes::EVENTS, any(events_ws))
|
||||
.route(routes::patterns::ATTACH, any(attach_ws))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
@@ -103,11 +86,30 @@ fn dir_error_status(code: &str) -> StatusCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP status for a [`crate::session::SessionError`] code. Everything used to
|
||||
/// collapse to 502, which reports a client mistake as a daemon failure.
|
||||
fn session_error_status(code: &str) -> StatusCode {
|
||||
match code {
|
||||
"not_found" => StatusCode::NOT_FOUND,
|
||||
"invalid_env" => StatusCode::BAD_REQUEST,
|
||||
_ => StatusCode::BAD_GATEWAY,
|
||||
}
|
||||
}
|
||||
|
||||
/// Recent working dirs for the spawn form's recents picker (#26).
|
||||
async fn recent_dirs(State(s): State<LocalApiState>) -> Response {
|
||||
Json(crate::spawn_history::to_wire(s.manager.recent_dirs())).into_response()
|
||||
}
|
||||
|
||||
/// Discovered git repositories and worktrees, newest activity first (#54).
|
||||
/// `last_activity` is the later of the repo's git HEAD mtime and the newest
|
||||
/// spawn-history use of any directory inside it.
|
||||
async fn projects(State(s): State<LocalApiState>) -> Response {
|
||||
let repos = s.projects.repos().await;
|
||||
let history = s.manager.all_recent_dirs();
|
||||
Json(crate::projects::to_projects(&repos, &history)).into_response()
|
||||
}
|
||||
|
||||
/// Probe the enclosing git repo of `path`, to infer the worktree `base_repo`
|
||||
/// for the spawn form (#26). `path` is resolved against the daemon's home dir
|
||||
/// (empty/`~`/relative), like [`list_dir`].
|
||||
@@ -137,7 +139,7 @@ async fn create_session(
|
||||
Err(e) => {
|
||||
let info = e.to_error_info();
|
||||
error_response(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
session_error_status(&info.code),
|
||||
info.code.as_str(),
|
||||
info.message.as_str(),
|
||||
)
|
||||
@@ -145,20 +147,16 @@ async fn create_session(
|
||||
}
|
||||
}
|
||||
|
||||
/// `kill` already reports a missing session as `SessionError::NotFound`, which
|
||||
/// maps to 404. Checking first would only add a window in which the liveness
|
||||
/// watcher reaps the session between the two awaits, turning a 404 into a 502.
|
||||
async fn kill_session(State(s): State<LocalApiState>, Path(id): Path<Uuid>) -> Response {
|
||||
if !s.manager.has(id).await {
|
||||
return error_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
"unknown_session",
|
||||
"no such session on this daemon",
|
||||
);
|
||||
}
|
||||
match s.manager.kill(id).await {
|
||||
Ok(()) => StatusCode::NO_CONTENT.into_response(),
|
||||
Err(e) => {
|
||||
let info = e.to_error_info();
|
||||
error_response(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
session_error_status(&info.code),
|
||||
info.code.as_str(),
|
||||
info.message.as_str(),
|
||||
)
|
||||
@@ -167,33 +165,27 @@ async fn kill_session(State(s): State<LocalApiState>, Path(id): Path<Uuid>) -> R
|
||||
}
|
||||
|
||||
fn error_response(status: StatusCode, code: &str, message: &str) -> Response {
|
||||
(
|
||||
status,
|
||||
Json(serde_json::json!({
|
||||
"error": ErrorInfo {
|
||||
code: code.into(),
|
||||
message: message.into(),
|
||||
},
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
(status, Json(ApiError::new(code, message))).into_response()
|
||||
}
|
||||
|
||||
/// Convenience constructor — pulls the bits `LocalApiState` needs from
|
||||
/// `DaemonConfig` so callers don't have to assemble it by hand.
|
||||
/// `DaemonConfig` so callers don't have to assemble it by hand. The project
|
||||
/// scanner starts with its cache cold; wire
|
||||
/// [`ProjectScanner::start_background_refresh`](crate::projects::ProjectScanner::start_background_refresh)
|
||||
/// on the returned handle's scanner to keep it eventually fresh.
|
||||
pub fn state_for(
|
||||
manager: SessionManager,
|
||||
hostname: impl Into<String>,
|
||||
home_dir: impl Into<String>,
|
||||
presets: Vec<SpawnPreset>,
|
||||
events: LocalEventBus,
|
||||
projects: Arc<crate::projects::ProjectScanner>,
|
||||
) -> LocalApiState {
|
||||
LocalApiState {
|
||||
manager,
|
||||
hostname: Arc::new(hostname.into()),
|
||||
home_dir: Arc::new(home_dir.into()),
|
||||
presets: Arc::new(presets),
|
||||
events,
|
||||
projects,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,21 +194,25 @@ pub fn state_for(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
/// Subscribing *before* the upgrade makes the 404 and the subscription one
|
||||
/// atomic step. Checking existence and then subscribing inside the callback
|
||||
/// left a window in which the liveness watcher could reap the session, so a
|
||||
/// client that passed the check still got a socket that immediately closed.
|
||||
async fn attach_ws(
|
||||
Path(id): Path<Uuid>,
|
||||
State(s): State<LocalApiState>,
|
||||
ws: axum::extract::WebSocketUpgrade,
|
||||
) -> Result<Response, Response> {
|
||||
if !s.manager.has(id).await {
|
||||
let Some((replay, rx)) = s.manager.subscribe_pty_with_replay(id).await else {
|
||||
return Err(error_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
"unknown_session",
|
||||
"no such session on this daemon",
|
||||
));
|
||||
}
|
||||
};
|
||||
let manager = s.manager.clone();
|
||||
Ok(ws.on_upgrade(move |socket| async move {
|
||||
let _ = crate::attach::serve(socket, manager, id).await;
|
||||
let _ = crate::attach::serve(socket, manager, id, replay, rx).await;
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -246,7 +242,7 @@ async fn pump_events(
|
||||
// Subscribe BEFORE building the snapshot so deltas applied while we're
|
||||
// marshaling can't slip between the two and disappear. The UI is
|
||||
// idempotent for repeated *Added events, so any overlap is harmless.
|
||||
let mut rx = s.events.subscribe();
|
||||
let mut rx = s.manager.events();
|
||||
|
||||
let snapshot = CatalogEvent::Snapshot {
|
||||
sessions: s.manager.snapshot().await,
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
//! Fan-out of session deltas for the `WS /api/events` endpoint (NAP-248).
|
||||
//!
|
||||
//! [`spawn_session_publisher`] translates the `SessionManager::events()` stream
|
||||
//! from `SessionEvent` into the matching [`CatalogEvent`] variant and publishes
|
||||
//! it here. The `WS /api/events` handler sends a one-shot `Snapshot` on connect,
|
||||
//! then forwards live deltas until the client disconnects. `Lagged` tells
|
||||
//! clients to resync via REST.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use maestro_protocol::CatalogEvent;
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
use crate::session::{SessionEvent, SessionManager};
|
||||
|
||||
/// Capacity of the per-bus broadcast channel. Sourced from the shared
|
||||
/// [`maestro_config::BroadcastTuning`] (NAP-273).
|
||||
const BUS_CAPACITY: usize = maestro_config::BroadcastTuning::DEFAULT.events_capacity;
|
||||
|
||||
/// Cheap-to-clone handle around a `broadcast::Sender<CatalogEvent>`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LocalEventBus {
|
||||
sender: Arc<broadcast::Sender<CatalogEvent>>,
|
||||
}
|
||||
|
||||
impl LocalEventBus {
|
||||
pub fn new() -> Self {
|
||||
let (sender, _) = broadcast::channel(BUS_CAPACITY);
|
||||
Self {
|
||||
sender: Arc::new(sender),
|
||||
}
|
||||
}
|
||||
|
||||
/// Push an event onto the bus. No-op if there are no subscribers.
|
||||
pub fn publish(&self, event: CatalogEvent) {
|
||||
let _ = self.sender.send(event);
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<CatalogEvent> {
|
||||
self.sender.subscribe()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for LocalEventBus {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn a task that converts each `SessionEvent` from `manager` into the
|
||||
/// matching `CatalogEvent` and publishes it on `bus`. Exits when the
|
||||
/// `SessionManager` is dropped (the events channel closes).
|
||||
pub fn spawn_session_publisher(manager: SessionManager, bus: LocalEventBus) {
|
||||
tokio::spawn(async move {
|
||||
let mut rx = manager.events();
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(SessionEvent::Added(session)) => {
|
||||
bus.publish(CatalogEvent::SessionAdded { session });
|
||||
}
|
||||
Ok(SessionEvent::Updated(session)) => {
|
||||
bus.publish(CatalogEvent::SessionUpdated { session });
|
||||
}
|
||||
Ok(SessionEvent::Removed(id)) => {
|
||||
bus.publish(CatalogEvent::SessionRemoved { id });
|
||||
}
|
||||
Err(broadcast::error::RecvError::Lagged(skipped)) => {
|
||||
bus.publish(CatalogEvent::Lagged { skipped });
|
||||
}
|
||||
Err(broadcast::error::RecvError::Closed) => return,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn publish_visible_to_subscriber() {
|
||||
let bus = LocalEventBus::new();
|
||||
let mut rx = bus.subscribe();
|
||||
bus.publish(CatalogEvent::Lagged { skipped: 7 });
|
||||
match rx.recv().await {
|
||||
Ok(CatalogEvent::Lagged { skipped }) => assert_eq!(skipped, 7),
|
||||
other => panic!("unexpected: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_subscribers_swallows_event() {
|
||||
let bus = LocalEventBus::new();
|
||||
// No one's listening — `publish` must not panic and must not block.
|
||||
bus.publish(CatalogEvent::Lagged { skipped: 1 });
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clones_share_state() {
|
||||
let a = LocalEventBus::new();
|
||||
let b = a.clone();
|
||||
let mut rx = a.subscribe();
|
||||
b.publish(CatalogEvent::Lagged { skipped: 3 });
|
||||
match rx.recv().await {
|
||||
Ok(CatalogEvent::Lagged { skipped }) => assert_eq!(skipped, 3),
|
||||
other => panic!("unexpected: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//! The tmux operations [`crate::session::SessionManager`] depends on.
|
||||
//!
|
||||
//! Behind a trait so the manager's *decisions* — spawn rollback ordering,
|
||||
//! liveness diffing, activity change-detection — can be exercised without
|
||||
//! forking a tmux server. [`Tmux`] is the production adapter; [`FakePanes`] is
|
||||
//! the one tests drive.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::tmux::{PaneInfo, Tmux, TmuxError};
|
||||
|
||||
/// Every tmux call the session manager makes.
|
||||
///
|
||||
/// Object-safe on purpose: `Inner` holds an `Arc<dyn Panes>` rather than a type
|
||||
/// parameter, which would otherwise spread through `LocalApiState`, `attach`
|
||||
/// and `cli`. One vtable hop is free next to a `fork`+`exec`.
|
||||
pub trait Panes: std::fmt::Debug + Send + Sync + 'static {
|
||||
fn new_session_piped(
|
||||
&self,
|
||||
id: Uuid,
|
||||
cwd: &Path,
|
||||
command: &str,
|
||||
session_env: &BTreeMap<String, String>,
|
||||
sink_command: &str,
|
||||
) -> Result<(), TmuxError>;
|
||||
|
||||
fn kill_session(&self, id: Uuid) -> Result<(), TmuxError>;
|
||||
|
||||
fn list_sessions(&self) -> Result<Vec<Uuid>, TmuxError>;
|
||||
|
||||
fn pane_info(&self, id: Uuid) -> Result<Option<PaneInfo>, TmuxError>;
|
||||
|
||||
fn send_keys(&self, id: Uuid, bytes: &[u8]) -> Result<(), TmuxError>;
|
||||
|
||||
fn pipe_pane(&self, id: Uuid, sink_command: &str) -> Result<(), TmuxError>;
|
||||
|
||||
fn resize_window(&self, id: Uuid, cols: u16, rows: u16) -> Result<(), TmuxError>;
|
||||
}
|
||||
|
||||
impl Panes for Tmux {
|
||||
fn new_session_piped(
|
||||
&self,
|
||||
id: Uuid,
|
||||
cwd: &Path,
|
||||
command: &str,
|
||||
session_env: &BTreeMap<String, String>,
|
||||
sink_command: &str,
|
||||
) -> Result<(), TmuxError> {
|
||||
Tmux::new_session_piped(self, id, cwd, command, session_env, sink_command)
|
||||
}
|
||||
|
||||
fn kill_session(&self, id: Uuid) -> Result<(), TmuxError> {
|
||||
Tmux::kill_session(self, id)
|
||||
}
|
||||
|
||||
fn list_sessions(&self) -> Result<Vec<Uuid>, TmuxError> {
|
||||
Tmux::list_sessions(self)
|
||||
}
|
||||
|
||||
fn pane_info(&self, id: Uuid) -> Result<Option<PaneInfo>, TmuxError> {
|
||||
Tmux::pane_info(self, id)
|
||||
}
|
||||
|
||||
fn send_keys(&self, id: Uuid, bytes: &[u8]) -> Result<(), TmuxError> {
|
||||
Tmux::send_keys(self, id, bytes)
|
||||
}
|
||||
|
||||
fn pipe_pane(&self, id: Uuid, sink_command: &str) -> Result<(), TmuxError> {
|
||||
Tmux::pipe_pane(self, id, sink_command)
|
||||
}
|
||||
|
||||
fn resize_window(&self, id: Uuid, cols: u16, rows: u16) -> Result<(), TmuxError> {
|
||||
Tmux::resize_window(self, id, cols, rows)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test adapter
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Which [`Panes`] call a [`FakePanes`] expectation targets.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Op {
|
||||
NewSessionPiped,
|
||||
KillSession,
|
||||
ListSessions,
|
||||
PaneInfo,
|
||||
SendKeys,
|
||||
PipePane,
|
||||
ResizeWindow,
|
||||
}
|
||||
|
||||
/// One recorded call, in the order the manager made it. Rollback ordering is a
|
||||
/// sequence property, so the tests that matter assert on this.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Call {
|
||||
NewSessionPiped {
|
||||
id: Uuid,
|
||||
command: String,
|
||||
env: BTreeMap<String, String>,
|
||||
},
|
||||
KillSession(Uuid),
|
||||
ListSessions,
|
||||
PaneInfo(Uuid),
|
||||
SendKeys {
|
||||
id: Uuid,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
PipePane(Uuid),
|
||||
ResizeWindow {
|
||||
id: Uuid,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
},
|
||||
}
|
||||
|
||||
/// In-memory [`Panes`] for tests.
|
||||
///
|
||||
/// Lives in `src/` rather than a test module because the daemon's integration
|
||||
/// tests are separate crates, which `#[cfg(test)]` cannot reach and which
|
||||
/// cannot enable a feature on their own crate.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FakePanes {
|
||||
state: Mutex<FakeState>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct FakeState {
|
||||
live: HashSet<Uuid>,
|
||||
panes: HashMap<Uuid, PaneInfo>,
|
||||
calls: Vec<Call>,
|
||||
fail: HashMap<Op, String>,
|
||||
}
|
||||
|
||||
impl FakePanes {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Make every call to `op` fail with `stderr`.
|
||||
pub fn fail(&self, op: Op, stderr: impl Into<String>) {
|
||||
self.lock().fail.insert(op, stderr.into());
|
||||
}
|
||||
|
||||
/// Pretend a session exists without the manager having created it — the
|
||||
/// recovery path's starting condition.
|
||||
pub fn add_live(&self, id: Uuid) {
|
||||
self.lock().live.insert(id);
|
||||
}
|
||||
|
||||
/// Drop a session behind the manager's back, the way a command exiting or
|
||||
/// an external `tmux kill-session` would.
|
||||
pub fn remove_live(&self, id: Uuid) {
|
||||
self.lock().live.remove(&id);
|
||||
}
|
||||
|
||||
pub fn is_live(&self, id: Uuid) -> bool {
|
||||
self.lock().live.contains(&id)
|
||||
}
|
||||
|
||||
pub fn set_pane_info(&self, id: Uuid, info: PaneInfo) {
|
||||
self.lock().panes.insert(id, info);
|
||||
}
|
||||
|
||||
/// Every call so far, in order.
|
||||
pub fn calls(&self) -> Vec<Call> {
|
||||
self.lock().calls.clone()
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, FakeState> {
|
||||
self.state.lock().expect("FakePanes mutex poisoned")
|
||||
}
|
||||
|
||||
fn record(&self, call: Call, op: Op) -> Result<(), TmuxError> {
|
||||
let mut st = self.lock();
|
||||
st.calls.push(call);
|
||||
match st.fail.get(&op) {
|
||||
Some(stderr) => Err(TmuxError::NonZero {
|
||||
code: 1,
|
||||
stderr: stderr.clone(),
|
||||
}),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Panes for FakePanes {
|
||||
fn new_session_piped(
|
||||
&self,
|
||||
id: Uuid,
|
||||
_cwd: &Path,
|
||||
command: &str,
|
||||
session_env: &BTreeMap<String, String>,
|
||||
_sink_command: &str,
|
||||
) -> Result<(), TmuxError> {
|
||||
self.record(
|
||||
Call::NewSessionPiped {
|
||||
id,
|
||||
command: command.to_owned(),
|
||||
env: session_env.clone(),
|
||||
},
|
||||
Op::NewSessionPiped,
|
||||
)?;
|
||||
self.lock().live.insert(id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kill_session(&self, id: Uuid) -> Result<(), TmuxError> {
|
||||
self.record(Call::KillSession(id), Op::KillSession)?;
|
||||
self.lock().live.remove(&id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_sessions(&self) -> Result<Vec<Uuid>, TmuxError> {
|
||||
self.record(Call::ListSessions, Op::ListSessions)?;
|
||||
Ok(self.lock().live.iter().copied().collect())
|
||||
}
|
||||
|
||||
fn pane_info(&self, id: Uuid) -> Result<Option<PaneInfo>, TmuxError> {
|
||||
self.record(Call::PaneInfo(id), Op::PaneInfo)?;
|
||||
Ok(self.lock().panes.get(&id).cloned())
|
||||
}
|
||||
|
||||
fn send_keys(&self, id: Uuid, bytes: &[u8]) -> Result<(), TmuxError> {
|
||||
self.record(
|
||||
Call::SendKeys {
|
||||
id,
|
||||
bytes: bytes.to_vec(),
|
||||
},
|
||||
Op::SendKeys,
|
||||
)
|
||||
}
|
||||
|
||||
fn pipe_pane(&self, id: Uuid, _sink_command: &str) -> Result<(), TmuxError> {
|
||||
self.record(Call::PipePane(id), Op::PipePane)
|
||||
}
|
||||
|
||||
fn resize_window(&self, id: Uuid, cols: u16, rows: u16) -> Result<(), TmuxError> {
|
||||
self.record(Call::ResizeWindow { id, cols, rows }, Op::ResizeWindow)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn records_calls_in_order_and_tracks_liveness() {
|
||||
let fake = FakePanes::new();
|
||||
let id = Uuid::new_v4();
|
||||
|
||||
fake.new_session_piped(id, Path::new("/tmp"), "bash", &BTreeMap::new(), "cat >> /x")
|
||||
.unwrap();
|
||||
assert!(fake.is_live(id));
|
||||
fake.kill_session(id).unwrap();
|
||||
assert!(!fake.is_live(id));
|
||||
|
||||
assert_eq!(
|
||||
fake.calls(),
|
||||
vec![
|
||||
Call::NewSessionPiped {
|
||||
id,
|
||||
command: "bash".into(),
|
||||
env: BTreeMap::new(),
|
||||
},
|
||||
Call::KillSession(id),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn injected_failure_still_records_the_attempt() {
|
||||
let fake = FakePanes::new();
|
||||
let id = Uuid::new_v4();
|
||||
fake.fail(Op::NewSessionPiped, "boom");
|
||||
|
||||
assert!(fake
|
||||
.new_session_piped(id, Path::new("/tmp"), "bash", &BTreeMap::new(), "cat")
|
||||
.is_err());
|
||||
assert!(
|
||||
!fake.is_live(id),
|
||||
"a failed spawn must not register a session"
|
||||
);
|
||||
assert_eq!(fake.calls().len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Best-effort `/proc` inspection for the activity watcher (NAP-340, Linux).
|
||||
//!
|
||||
//! Decides whether a session is **blocked waiting on the user**: walk from the
|
||||
//! pane's process down to the deepest descendant (the agent/shell actually on
|
||||
//! the terminal) and check it's parked waiting on terminal input.
|
||||
//! Decides whether a session is **blocked waiting on the user**: ask the kernel
|
||||
//! which process group owns the terminal, then check whether any live member of
|
||||
//! that group is parked on the terminal.
|
||||
//!
|
||||
//! `/proc/<pid>/syscall` would say so exactly, but it's ptrace-gated and
|
||||
//! unreadable for our own sessions on a default kernel, so we combine three
|
||||
@@ -16,55 +16,120 @@
|
||||
//! Every step degrades to `false` on a read failure, so a non-Linux host or a
|
||||
//! denied `/proc` read falls back to `Idle`.
|
||||
|
||||
/// Whether the process tree under `pane_pid` looks blocked on terminal input
|
||||
/// from `tty` (e.g. `/dev/pts/3`) — the signal for `AwaitingInput`.
|
||||
pub fn awaiting_input(pane_pid: i32, tty: &str) -> bool {
|
||||
let leaf = deepest_descendant(pane_pid);
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// One walk of `/proc`, shared by every session in an activity pass.
|
||||
///
|
||||
/// The foreground process group is the unit that matters, and its members are
|
||||
/// not reliably reachable from the pane: the group leader can exit while others
|
||||
/// run on, and a stage that forks a terminal-reading child and exits leaves
|
||||
/// that child reparented to init. Walking the pane's process tree misses both.
|
||||
///
|
||||
/// Snapshotting once per pass costs one `/proc` walk however many sessions the
|
||||
/// daemon owns — cheaper than the per-session `tmux list-panes` fork that
|
||||
/// already runs on the same tick.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ProcGroups {
|
||||
stats: HashMap<i32, Stat>,
|
||||
by_pgid: HashMap<i32, Vec<i32>>,
|
||||
}
|
||||
|
||||
impl ProcGroups {
|
||||
pub fn snapshot() -> Self {
|
||||
let mut stats = HashMap::new();
|
||||
let mut by_pgid: HashMap<i32, Vec<i32>> = HashMap::new();
|
||||
let Ok(entries) = std::fs::read_dir("/proc") else {
|
||||
return Self::default();
|
||||
};
|
||||
for pid in entries
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().to_str()?.parse::<i32>().ok())
|
||||
{
|
||||
// A process can exit mid-walk; skipping it is the correct answer.
|
||||
if let Some(stat) = read_stat(pid) {
|
||||
by_pgid.entry(stat.pgrp).or_default().push(pid);
|
||||
stats.insert(pid, stat);
|
||||
}
|
||||
}
|
||||
Self { stats, by_pgid }
|
||||
}
|
||||
|
||||
/// The process group the terminal considers foreground, per `tpgid`.
|
||||
fn foreground_pgid(&self, pane_pid: i32) -> Option<i32> {
|
||||
let tpgid = self.stats.get(&pane_pid)?.tpgid;
|
||||
// -1 when the process has no controlling terminal.
|
||||
(tpgid > 0).then_some(tpgid)
|
||||
}
|
||||
|
||||
fn members(&self, pgid: i32) -> &[i32] {
|
||||
self.by_pgid.get(&pgid).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
fn state(&self, pid: i32) -> Option<char> {
|
||||
self.stats.get(&pid).map(|s| s.state)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the session on `tty` (e.g. `/dev/pts/3`) is blocked waiting on the
|
||||
/// user — the signal for `AwaitingInput`.
|
||||
///
|
||||
/// True when *any* member of the terminal's foreground group is parked on it: a
|
||||
/// group can hold a busy or timer-sleeping stage alongside the one actually
|
||||
/// reading, and either can be the reparented one.
|
||||
pub fn awaiting_input(pane_pid: i32, tty: &str, groups: &ProcGroups) -> bool {
|
||||
let Some(pgid) = groups.foreground_pgid(pane_pid) else {
|
||||
return false;
|
||||
};
|
||||
groups
|
||||
.members(pgid)
|
||||
.iter()
|
||||
.any(|pid| parked_on_tty(*pid, tty, groups))
|
||||
}
|
||||
|
||||
/// Whether `pid` is parked on `tty` rather than busy or sleeping on a timer.
|
||||
fn parked_on_tty(pid: i32, tty: &str, groups: &ProcGroups) -> bool {
|
||||
// Interruptible sleep is where a blocking read parks; anything else
|
||||
// (running, uninterruptible) is busy, not waiting on us.
|
||||
if read_state(leaf) != Some('S') {
|
||||
if groups.state(pid) != Some('S') {
|
||||
return false;
|
||||
}
|
||||
// A pure timer sleep (`sleep`, `usleep`) also sits in 'S' with the terminal
|
||||
// inherited — exclude it so it reads as Idle, not AwaitingInput.
|
||||
if is_timer_sleep(leaf) {
|
||||
if is_timer_sleep(pid) {
|
||||
return false;
|
||||
}
|
||||
fd_points_at_tty(leaf, tty)
|
||||
fd_points_at_tty(pid, tty)
|
||||
}
|
||||
|
||||
/// Follow the (last) child link down the process tree to the deepest
|
||||
/// descendant. Bounded so a pathological/cyclic tree can't loop.
|
||||
fn deepest_descendant(pid: i32) -> i32 {
|
||||
let mut cur = pid;
|
||||
for _ in 0..64 {
|
||||
match last_child(cur) {
|
||||
Some(child) if child != cur => cur = child,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
cur
|
||||
/// The fields of `/proc/<pid>/stat` this module needs.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct Stat {
|
||||
state: char,
|
||||
/// The process group this process belongs to.
|
||||
pgrp: i32,
|
||||
/// Foreground process group of the controlling terminal.
|
||||
tpgid: i32,
|
||||
}
|
||||
|
||||
/// The most-recently-created child of `pid`, via
|
||||
/// `/proc/<pid>/task/<pid>/children` (a space-separated pid list). The last
|
||||
/// entry is the newest child — typically the foreground one an agent spawned.
|
||||
fn last_child(pid: i32) -> Option<i32> {
|
||||
let contents = std::fs::read_to_string(format!("/proc/{pid}/task/{pid}/children")).ok()?;
|
||||
contents.split_whitespace().last()?.parse().ok()
|
||||
fn read_stat(pid: i32) -> Option<Stat> {
|
||||
parse_stat(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)
|
||||
}
|
||||
|
||||
/// Read the process state char from `/proc/<pid>/stat`.
|
||||
fn read_state(pid: i32) -> Option<char> {
|
||||
parse_stat_state(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)
|
||||
}
|
||||
|
||||
/// Extract the state field from a `/proc/<pid>/stat` line. The format is
|
||||
/// `pid (comm) STATE ...`; `comm` can itself contain spaces and parens, so the
|
||||
/// state is the first non-space char *after the final `)`*.
|
||||
fn parse_stat_state(stat: &str) -> Option<char> {
|
||||
/// Parse the fields after `comm` from a `/proc/<pid>/stat` line.
|
||||
///
|
||||
/// The format is `pid (comm) state ppid pgrp session tty_nr tpgid ...`, and
|
||||
/// `comm` can itself contain spaces and parens — so everything is indexed from
|
||||
/// the *final* `)`, never by splitting the whole line.
|
||||
fn parse_stat(stat: &str) -> Option<Stat> {
|
||||
let close = stat.rfind(')')?;
|
||||
stat[close + 1..].trim_start().chars().next()
|
||||
let mut rest = stat[close + 1..].split_whitespace();
|
||||
let state = rest.next()?.chars().next()?;
|
||||
let _ppid = rest.next()?;
|
||||
let pgrp = rest.next()?.parse().ok()?;
|
||||
let _session = rest.next()?;
|
||||
let _tty_nr = rest.next()?;
|
||||
let tpgid = rest.next()?.parse().ok()?;
|
||||
Some(Stat { state, pgrp, tpgid })
|
||||
}
|
||||
|
||||
/// Whether `pid`'s `wchan` (the kernel symbol it's blocked in) is a timer
|
||||
@@ -94,19 +159,51 @@ fn fd_points_at_tty(pid: i32, tty: &str) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_stat_state_handles_simple_and_tricky_comm() {
|
||||
assert_eq!(parse_stat_state("1234 (bash) S 1 1234 ..."), Some('S'));
|
||||
assert_eq!(parse_stat_state("1234 (sleep) S 1 ..."), Some('S'));
|
||||
assert_eq!(parse_stat_state("99 (cat) R 1 ..."), Some('R'));
|
||||
// comm with spaces and a paren — only the final ')' delimits it.
|
||||
assert_eq!(parse_stat_state("42 (weird (name)) D 1 42 ..."), Some('D'));
|
||||
/// `pid (comm) state ppid pgrp session tty_nr tpgid …`
|
||||
fn stat_line(comm: &str, state: char, tpgid: i32) -> String {
|
||||
stat_line_pgrp(comm, state, 1234, tpgid)
|
||||
}
|
||||
|
||||
fn stat_line_pgrp(comm: &str, state: char, pgrp: i32, tpgid: i32) -> String {
|
||||
format!("1234 ({comm}) {state} 1000 {pgrp} 1234 34816 {tpgid} 4194304 …")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_stat_state_rejects_garbage() {
|
||||
assert_eq!(parse_stat_state("not a stat line"), None);
|
||||
assert_eq!(parse_stat_state("123 (comm)"), None);
|
||||
fn parse_stat_reads_state_pgrp_and_tpgid() {
|
||||
let s = parse_stat(&stat_line_pgrp("bash", 'S', 500, 4321)).unwrap();
|
||||
assert_eq!(s.state, 'S');
|
||||
assert_eq!(s.pgrp, 500);
|
||||
assert_eq!(s.tpgid, 4321);
|
||||
|
||||
let r = parse_stat(&stat_line_pgrp("cat", 'R', 7, 99)).unwrap();
|
||||
assert_eq!(r.state, 'R');
|
||||
assert_eq!(r.pgrp, 7);
|
||||
assert_eq!(r.tpgid, 99);
|
||||
}
|
||||
|
||||
/// `comm` is attacker-adjacent: it is the process name, it can contain
|
||||
/// spaces and parens, and splitting the whole line on whitespace would put
|
||||
/// every later field at the wrong index.
|
||||
#[test]
|
||||
fn parse_stat_indexes_from_the_final_paren() {
|
||||
let s = parse_stat(&stat_line_pgrp("weird (name) with spaces", 'D', 42, 777)).unwrap();
|
||||
assert_eq!(s.state, 'D');
|
||||
assert_eq!(s.pgrp, 42);
|
||||
assert_eq!(s.tpgid, 777);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_stat_carries_the_no_terminal_sentinel() {
|
||||
// -1 means no controlling terminal; `foreground_pid` rejects it.
|
||||
assert_eq!(parse_stat(&stat_line("daemon", 'S', -1)).unwrap().tpgid, -1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_stat_rejects_garbage() {
|
||||
assert!(parse_stat("not a stat line").is_none());
|
||||
assert!(parse_stat("123 (comm)").is_none());
|
||||
// Truncated before tpgid.
|
||||
assert!(parse_stat("123 (comm) S 1 1 1").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -121,9 +218,46 @@ mod tests {
|
||||
assert!(!is_timer_wchan("0"));
|
||||
}
|
||||
|
||||
/// The snapshot indexes by process group, not by parentage — that is the
|
||||
/// whole point, since a group member need not be under the pane. Checked
|
||||
/// against this process's own group, which certainly has a live member.
|
||||
#[test]
|
||||
fn snapshot_indexes_this_process_under_its_group() {
|
||||
// SAFETY: argument-less query of the caller's own process group.
|
||||
let own = unsafe { libc::getpgid(0) };
|
||||
assert!(own > 0, "expected a real process group, got {own}");
|
||||
|
||||
let groups = ProcGroups::snapshot();
|
||||
let me = std::process::id() as i32;
|
||||
assert!(
|
||||
groups.members(own).contains(&me),
|
||||
"snapshot missed this process ({me}) in group {own}: {:?}",
|
||||
groups.members(own)
|
||||
);
|
||||
assert!(
|
||||
groups.state(me).is_some(),
|
||||
"a process in the snapshot must carry its state"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_has_no_members_for_a_group_that_cannot_exist() {
|
||||
assert!(ProcGroups::snapshot().members(i32::MAX).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pid_with_no_controlling_terminal_has_no_foreground_group() {
|
||||
let groups = ProcGroups::snapshot();
|
||||
assert_eq!(groups.foreground_pgid(i32::MAX), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn awaiting_input_is_false_for_nonexistent_pid() {
|
||||
// A pid that can't exist → every read fails → false (fall back to Idle).
|
||||
assert!(!awaiting_input(i32::MAX, "/dev/pts/0"));
|
||||
// A pid that can't exist → not in the snapshot → false (falls back to Idle).
|
||||
assert!(!awaiting_input(
|
||||
i32::MAX,
|
||||
"/dev/pts/0",
|
||||
&ProcGroups::snapshot()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,530 @@
|
||||
//! Project discovery for `GET /api/projects` (#54).
|
||||
//!
|
||||
//! Scans `[spawn].project_roots` (default the whole home) for `.git` entries —
|
||||
//! directory or file, so linked worktrees count too — up to
|
||||
//! `[spawn].project_scan_depth` levels. Descent stops at the first repo found:
|
||||
//! nested independent repos are not discovered, but worktrees of every hit
|
||||
//! still are, via `git worktree list`, which also catches linked worktrees
|
||||
//! living outside the roots.
|
||||
//!
|
||||
//! Hidden directories are skipped everywhere; heavy well-known directories
|
||||
//! (`node_modules`, `Downloads`, …) are skipped when they sit directly in the
|
||||
//! home directory, so scanning all of home stays cheap.
|
||||
//!
|
||||
//! Results are cached behind a short TTL and refreshed on a slow background
|
||||
//! timer ([`ProjectScanner::start_background_refresh`]) — repositories appear
|
||||
//! rarely, and `/api/projects` may be polled.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::spawn_history::RecentDir;
|
||||
|
||||
/// Directory names never descended when they sit directly in the home dir, so
|
||||
/// scanning all of home stays cheap (#54). Hidden dirs are skipped everywhere
|
||||
/// regardless.
|
||||
pub const DEFAULT_HOME_IGNORE: &[&str] =
|
||||
&["node_modules", "Downloads", "Library", "go", "snap", "opt"];
|
||||
|
||||
/// How long a discovery snapshot is served as-is before the next request
|
||||
/// triggers a rescan. Short: a scan is a bounded filesystem walk plus one
|
||||
/// `git worktree list` per hit.
|
||||
pub const CACHE_TTL: Duration = Duration::from_secs(5);
|
||||
/// Background refresh cadence. Repositories appear rarely; this keeps the
|
||||
/// served list eventually fresh without anyone asking.
|
||||
pub const REFRESH_INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
/// One repository or linked worktree found by [`discover`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DiscoveredRepo {
|
||||
pub path: PathBuf,
|
||||
/// Basename of `path`.
|
||||
pub name: String,
|
||||
pub is_worktree: bool,
|
||||
/// The main checkout this worktree belongs to; set only when
|
||||
/// [`Self::is_worktree`].
|
||||
pub base_repo: Option<PathBuf>,
|
||||
/// Mtime of the checkout's git HEAD — "someone committed / checked out
|
||||
/// here". The later-of merge with spawn history happens in
|
||||
/// [`to_projects`], which also sorts.
|
||||
pub head_mtime: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// Repo toplevels under each root of `roots`, at most `max_depth` levels deep.
|
||||
/// A dir holding `.git` (dir *or* file) is a hit and is not descended into;
|
||||
/// hidden directories are never entered, and `DEFAULT_HOME_IGNORE` names are
|
||||
/// skipped directly under `home`.
|
||||
pub fn scan_roots(roots: &[PathBuf], max_depth: u32, home: &Path) -> Vec<PathBuf> {
|
||||
let mut found = Vec::new();
|
||||
for root in roots {
|
||||
walk(root, 0, max_depth, home, &mut found);
|
||||
}
|
||||
found.sort();
|
||||
found.dedup();
|
||||
found
|
||||
}
|
||||
|
||||
fn walk(dir: &Path, depth: u32, max_depth: u32, home: &Path, found: &mut Vec<PathBuf>) {
|
||||
let entries = match std::fs::read_dir(dir) {
|
||||
Ok(e) => e,
|
||||
Err(_) => return,
|
||||
};
|
||||
let mut subdirs = Vec::new();
|
||||
let mut has_git = false;
|
||||
for entry in entries.flatten() {
|
||||
match entry.file_name().to_string_lossy().into_owned() {
|
||||
name if name == ".git" => has_git = true,
|
||||
name if name.starts_with('.') => {}
|
||||
name if dir == home && DEFAULT_HOME_IGNORE.contains(&name.as_str()) => {}
|
||||
_ => {
|
||||
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
|
||||
subdirs.push(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if has_git {
|
||||
// Match `git worktree list` output, which prints real paths.
|
||||
found.push(std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()));
|
||||
return;
|
||||
}
|
||||
if depth >= max_depth {
|
||||
return;
|
||||
}
|
||||
for sub in subdirs {
|
||||
walk(&sub, depth + 1, max_depth, home, found);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every discovered project: the scanned repos plus all worktrees their
|
||||
/// `git worktree list` reports (linked worktrees can live outside the roots).
|
||||
/// A hit whose git invocation fails still lists, un-worktreed.
|
||||
pub fn discover(roots: &[PathBuf], max_depth: u32, home: &Path) -> Vec<DiscoveredRepo> {
|
||||
let scanned = scan_roots(roots, max_depth, home);
|
||||
let mut map: Vec<(PathBuf, PathBuf)> = Vec::new(); // (checkout, main)
|
||||
for repo in scanned {
|
||||
if map.iter().any(|(c, _)| c == &repo) {
|
||||
continue;
|
||||
}
|
||||
let worktrees = list_worktrees(&repo).unwrap_or_else(|| vec![repo.clone()]);
|
||||
let main = worktrees[0].clone();
|
||||
for wt in worktrees {
|
||||
if !map.iter().any(|(c, _)| c == &wt) {
|
||||
map.push((wt, main.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
map.into_iter()
|
||||
.map(|(path, main)| {
|
||||
let is_worktree = path != main;
|
||||
DiscoveredRepo {
|
||||
name: path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default(),
|
||||
is_worktree,
|
||||
base_repo: is_worktree.then_some(main),
|
||||
head_mtime: head_mtime(&path),
|
||||
path,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `git worktree list --porcelain` from `repo`: absolute paths, main first.
|
||||
/// `None` when git fails (broken/bare checkout).
|
||||
fn list_worktrees(repo: &Path) -> Option<Vec<PathBuf>> {
|
||||
let out = std::process::Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo)
|
||||
.args(["worktree", "list", "--porcelain"])
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let mut paths = Vec::new();
|
||||
for line in String::from_utf8_lossy(&out.stdout).lines() {
|
||||
if let Some(p) = line.strip_prefix("worktree ") {
|
||||
paths.push(PathBuf::from(p));
|
||||
}
|
||||
}
|
||||
(!paths.is_empty()).then_some(paths)
|
||||
}
|
||||
|
||||
/// Mtime of the checkout's HEAD file. For a linked worktree `.git` is a file
|
||||
/// holding a `gitdir:` pointer; resolve it so worktrees report their own HEAD
|
||||
/// rather than nothing.
|
||||
fn head_mtime(repo: &Path) -> Option<DateTime<Utc>> {
|
||||
let dot_git = repo.join(".git");
|
||||
let head = if dot_git.is_dir() {
|
||||
dot_git.join("HEAD")
|
||||
} else {
|
||||
let ptr = std::fs::read_to_string(&dot_git).ok()?;
|
||||
let gitdir = ptr.trim().strip_prefix("gitdir:")?.trim();
|
||||
// Relative pointers are relative to the worktree.
|
||||
let p = Path::new(gitdir);
|
||||
let p = if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
repo.join(p)
|
||||
};
|
||||
p.join("HEAD")
|
||||
};
|
||||
let mtime = std::fs::metadata(head).ok()?.modified().ok()?;
|
||||
Some(DateTime::<Utc>::from(mtime))
|
||||
}
|
||||
|
||||
/// Fold spawn history into the discovery snapshot and produce the wire list,
|
||||
/// sorted newest-activity-first. `history` must be newest-first (what
|
||||
/// [`SpawnHistory::all_recent_dirs`](crate::spawn_history::SpawnHistory)
|
||||
/// returns): the first entry whose cwd sits inside a project is its most
|
||||
/// recent use.
|
||||
pub fn to_projects(
|
||||
repos: &[DiscoveredRepo],
|
||||
history: &[RecentDir],
|
||||
) -> Vec<maestro_protocol::Project> {
|
||||
let mut projects: Vec<maestro_protocol::Project> = repos
|
||||
.iter()
|
||||
.map(|repo| {
|
||||
let last_use = history.iter().find(|h| contains(&repo.path, &h.cwd));
|
||||
maestro_protocol::Project {
|
||||
path: repo.path.clone(),
|
||||
name: repo.name.clone(),
|
||||
is_worktree: repo.is_worktree,
|
||||
base_repo: repo.base_repo.clone(),
|
||||
last_activity: max_opt(repo.head_mtime, last_use.map(|u| u.last_used)),
|
||||
last_command: last_use.map(|u| u.last_command.clone()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
projects.sort_by_key(|p| std::cmp::Reverse(p.last_activity));
|
||||
projects
|
||||
}
|
||||
|
||||
/// Whether `dir` is `project` itself or anywhere inside it.
|
||||
fn contains(project: &Path, dir: &Path) -> bool {
|
||||
dir == project || dir.starts_with(project)
|
||||
}
|
||||
|
||||
fn max_opt(a: Option<DateTime<Utc>>, b: Option<DateTime<Utc>>) -> Option<DateTime<Utc>> {
|
||||
match (a, b) {
|
||||
(Some(a), Some(b)) => Some(a.max(b)),
|
||||
(a, b) => a.or(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cached discovery behind a short TTL plus an optional slow background
|
||||
/// refresh. Clone-free shared handle via `Arc` in [`crate::local_api`].
|
||||
#[derive(Debug)]
|
||||
pub struct ProjectScanner {
|
||||
roots: Vec<PathBuf>,
|
||||
max_depth: u32,
|
||||
home: PathBuf,
|
||||
ttl: Duration,
|
||||
cache: tokio::sync::Mutex<Option<(Instant, std::sync::Arc<Vec<DiscoveredRepo>>)>>,
|
||||
}
|
||||
|
||||
impl ProjectScanner {
|
||||
/// Scanner over the resolved config roots. An empty `roots` list scans
|
||||
/// nothing and always serves an empty list.
|
||||
pub fn new(roots: Vec<PathBuf>, max_depth: u32, home: PathBuf) -> Self {
|
||||
Self {
|
||||
roots,
|
||||
max_depth,
|
||||
home,
|
||||
ttl: CACHE_TTL,
|
||||
cache: tokio::sync::Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scanner that never discovers anything — tests and embedders that don't
|
||||
/// want the endpoint populated.
|
||||
pub fn disabled() -> Self {
|
||||
Self::new(Vec::new(), 0, PathBuf::new())
|
||||
}
|
||||
|
||||
/// Cached snapshot, rescanning (off-thread) when the TTL has lapsed.
|
||||
pub async fn repos(&self) -> std::sync::Arc<Vec<DiscoveredRepo>> {
|
||||
let mut cache = self.cache.lock().await;
|
||||
if let Some((at, repos)) = cache.as_ref() {
|
||||
if at.elapsed() < self.ttl {
|
||||
return repos.clone();
|
||||
}
|
||||
}
|
||||
let roots = self.roots.clone();
|
||||
let max_depth = self.max_depth;
|
||||
let home = self.home.clone();
|
||||
// Blocking fs walk + git subprocesses must not stall the reactor.
|
||||
let repos = std::sync::Arc::new(
|
||||
tokio::task::spawn_blocking(move || discover(&roots, max_depth, &home))
|
||||
.await
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
*cache = Some((Instant::now(), repos.clone()));
|
||||
repos
|
||||
}
|
||||
|
||||
/// Rescan now, ignoring the TTL. Called by the background timer.
|
||||
async fn refresh(&self) {
|
||||
self.repos().await;
|
||||
}
|
||||
|
||||
/// Spawn the slow background refresh task. Drop the returned handle to
|
||||
/// detach it; it stops when the runtime shuts down.
|
||||
pub fn start_background_refresh(self: &std::sync::Arc<Self>) -> tokio::task::JoinHandle<()> {
|
||||
let scanner = std::sync::Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
let mut ticker = tokio::time::interval(REFRESH_INTERVAL);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
ticker.tick().await; // the immediate first tick — wait a full interval
|
||||
loop {
|
||||
scanner.refresh().await;
|
||||
ticker.tick().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::spawn_history::RecentDir;
|
||||
|
||||
/// Real git repo at `<root>/<name>`, one initial commit so HEAD exists.
|
||||
fn make_repo(root: &Path, name: &str) -> PathBuf {
|
||||
let path = root.join(name);
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
run_git(&path, &["init", "-q"]);
|
||||
std::fs::write(path.join("f.txt"), "x\n").unwrap();
|
||||
run_git(&path, &["add", "-A"]);
|
||||
run_git(
|
||||
&path,
|
||||
&[
|
||||
"-c",
|
||||
"user.email=t@t",
|
||||
"-c",
|
||||
"user.name=t",
|
||||
"commit",
|
||||
"-qm",
|
||||
"init",
|
||||
],
|
||||
);
|
||||
path
|
||||
}
|
||||
|
||||
fn run_git(dir: &Path, args: &[&str]) {
|
||||
let out = std::process::Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(dir)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?} failed: {} | {}",
|
||||
String::from_utf8_lossy(&out.stderr),
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
);
|
||||
}
|
||||
|
||||
fn names(repos: &[DiscoveredRepo]) -> Vec<String> {
|
||||
let mut v: Vec<String> = repos.iter().map(|r| r.name.clone()).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_finds_repos_and_stops_at_the_first_hit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outer = make_repo(tmp.path(), "outer");
|
||||
// A nested independent repo inside `outer` is NOT discovered
|
||||
// separately: descent stops once a repo is found.
|
||||
make_repo(&outer, "vendored");
|
||||
std::fs::create_dir_all(tmp.path().join("plain/deep/deeper")).unwrap();
|
||||
|
||||
let found = scan_roots(
|
||||
&[tmp.path().to_path_buf()],
|
||||
3,
|
||||
Path::new("/nonexistent-home"),
|
||||
);
|
||||
assert_eq!(found, vec![outer]);
|
||||
|
||||
let discovered = discover(
|
||||
&[tmp.path().to_path_buf()],
|
||||
3,
|
||||
Path::new("/nonexistent-home"),
|
||||
);
|
||||
assert_eq!(names(&discovered), ["outer"]);
|
||||
assert!(!discovered[0].is_worktree);
|
||||
assert_eq!(discovered[0].base_repo, None);
|
||||
assert!(discovered[0].head_mtime.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_respects_depth_hidden_dirs_and_home_ignore() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
|
||||
// Hidden dirs are never entered, at any depth.
|
||||
std::fs::create_dir_all(home.join(".secret/.git")).unwrap();
|
||||
// node_modules directly under home is not descended…
|
||||
let _ignored = make_repo(&home.join("node_modules"), "dep");
|
||||
// …but the same name deeper down is fair game.
|
||||
let kept = make_repo(&home.join("code/node_modules"), "dep2");
|
||||
|
||||
// Depth cap: a repo three levels below the root is the last tier —
|
||||
// found at depth 3, but a fourth-level repo isn't.
|
||||
let at_three = home.join("a/b/c");
|
||||
std::fs::create_dir_all(at_three.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(home.join("a/b/c/d/.git")).unwrap();
|
||||
|
||||
let found = scan_roots(std::slice::from_ref(&home), 3, &home);
|
||||
assert!(found.iter().all(|p| !p.starts_with(home.join(".secret"))));
|
||||
assert!(found
|
||||
.iter()
|
||||
.all(|p| !p.starts_with(home.join("node_modules"))));
|
||||
assert!(found.contains(&kept.canonicalize().unwrap()));
|
||||
assert!(found.contains(&at_three.canonicalize().unwrap()));
|
||||
assert!(!found.iter().any(|p| p.ends_with("d")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktrees_outside_the_roots_are_discovered_via_git_worktree_list() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("scan-root");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let main = make_repo(&root, "main-repo");
|
||||
// Linked worktree deliberately outside the scan root.
|
||||
let wt = tmp.path().join("elsewhere/wt-of-main");
|
||||
std::fs::create_dir_all(wt.parent().unwrap()).unwrap();
|
||||
run_git(
|
||||
&main,
|
||||
&[
|
||||
"worktree",
|
||||
"add",
|
||||
"-q",
|
||||
"-b",
|
||||
"feature",
|
||||
&wt.to_string_lossy(),
|
||||
],
|
||||
);
|
||||
|
||||
let discovered = discover(&[root], 3, Path::new("/nonexistent-home"));
|
||||
assert_eq!(names(&discovered), ["main-repo", "wt-of-main"]);
|
||||
let wt_entry = discovered.iter().find(|d| d.name == "wt-of-main").unwrap();
|
||||
assert!(wt_entry.is_worktree);
|
||||
assert_eq!(
|
||||
wt_entry.base_repo.as_deref(),
|
||||
Some(main.canonicalize().unwrap().as_path())
|
||||
);
|
||||
let main_entry = discovered.iter().find(|d| d.name == "main-repo").unwrap();
|
||||
assert!(!main_entry.is_worktree);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_mtime_resolves_a_worktrees_git_file_pointer() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let main = make_repo(tmp.path(), "m");
|
||||
let wt = tmp.path().join("wt");
|
||||
run_git(
|
||||
&main,
|
||||
&["worktree", "add", "-q", "-b", "b2", &wt.to_string_lossy()],
|
||||
);
|
||||
assert!(head_mtime(&wt).is_some());
|
||||
}
|
||||
|
||||
fn recent(cwd: &str, cmd: &str, at: &str) -> RecentDir {
|
||||
RecentDir {
|
||||
cwd: PathBuf::from(cwd),
|
||||
last_command: cmd.into(),
|
||||
last_used: DateTime::parse_from_rfc3339(at)
|
||||
.unwrap()
|
||||
.with_timezone(&Utc),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_projects_merges_history_and_sorts_newest_first() {
|
||||
let repo_old = DiscoveredRepo {
|
||||
path: PathBuf::from("/w/old"),
|
||||
name: "old".into(),
|
||||
is_worktree: false,
|
||||
base_repo: None,
|
||||
// Committed recently but never spawned in.
|
||||
head_mtime: Some(t("2026-08-23T10:00:00Z")),
|
||||
};
|
||||
let repo_hist = DiscoveredRepo {
|
||||
path: PathBuf::from("/w/hist"),
|
||||
name: "hist".into(),
|
||||
is_worktree: false,
|
||||
base_repo: None,
|
||||
// Old commit…
|
||||
head_mtime: Some(t("2026-08-01T10:00:00Z")),
|
||||
};
|
||||
let repo_stale = DiscoveredRepo {
|
||||
path: PathBuf::from("/w/stale"),
|
||||
name: "stale".into(),
|
||||
is_worktree: false,
|
||||
base_repo: None,
|
||||
head_mtime: None,
|
||||
};
|
||||
|
||||
let history = vec![
|
||||
// Newest overall: a subdir of /w/hist (first match wins for it).
|
||||
recent("/w/hist/crates", "opencode", "2026-08-22T09:00:00Z"),
|
||||
recent("/w/hist", "claude", "2026-08-20T09:00:00Z"),
|
||||
];
|
||||
let projects = to_projects(&[repo_old, repo_hist, repo_stale], &history);
|
||||
|
||||
let paths: Vec<&str> = projects.iter().map(|p| p.path.to_str().unwrap()).collect();
|
||||
assert_eq!(paths, ["/w/old", "/w/hist", "/w/stale"]);
|
||||
|
||||
// old: git activity wins (never spawned).
|
||||
assert_eq!(projects[0].last_activity, Some(t("2026-08-23T10:00:00Z")));
|
||||
assert_eq!(projects[0].last_command, None);
|
||||
// hist: spawn history beats the old commit; command from the newest
|
||||
// matching entry (the crates/ one, not the repo root one).
|
||||
assert_eq!(projects[1].last_activity, Some(t("2026-08-22T09:00:00Z")));
|
||||
assert_eq!(projects[1].last_command.as_deref(), Some("opencode"));
|
||||
// stale: neither source knows anything.
|
||||
assert_eq!(projects[2].last_activity, None);
|
||||
assert_eq!(projects[2].last_command, None);
|
||||
}
|
||||
|
||||
fn t(s: &str) -> DateTime<Utc> {
|
||||
DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scanner_caches_within_ttl_and_rescans_after() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut scanner = ProjectScanner::new(
|
||||
vec![tmp.path().to_path_buf()],
|
||||
3,
|
||||
PathBuf::from("/nonexistent"),
|
||||
);
|
||||
|
||||
let empty = scanner.repos().await;
|
||||
assert!(empty.is_empty());
|
||||
|
||||
make_repo(tmp.path(), "late");
|
||||
// Within the TTL the cached (empty) snapshot is still served.
|
||||
let still_empty = scanner.repos().await;
|
||||
assert!(still_empty.is_empty());
|
||||
|
||||
// After the TTL lapses the rescan sees the new repo.
|
||||
scanner.ttl = Duration::ZERO;
|
||||
let fresh = scanner.repos().await;
|
||||
assert_eq!(fresh.len(), 1);
|
||||
assert_eq!(fresh[0].name, "late");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_scanner_always_serves_empty() {
|
||||
let scanner = ProjectScanner::disabled();
|
||||
assert_eq!(scanner.roots, Vec::<PathBuf>::new());
|
||||
}
|
||||
}
|
||||
@@ -39,9 +39,9 @@ use tokio::task::JoinHandle;
|
||||
|
||||
/// How many recent PTY frames each new subscriber inherits before starting to
|
||||
/// receive live frames. A small buffer is fine — clients render a fresh
|
||||
/// terminal anyway. Sourced from the shared [`maestro_config::BroadcastTuning`]
|
||||
/// terminal anyway. Sourced from [`maestro_config::PTY_CAPACITY`]
|
||||
/// (NAP-273).
|
||||
pub const PTY_BROADCAST_CAPACITY: usize = maestro_config::BroadcastTuning::DEFAULT.pty_capacity;
|
||||
pub const PTY_BROADCAST_CAPACITY: usize = maestro_config::PTY_CAPACITY;
|
||||
|
||||
/// Default replay-buffer size — roughly one screenful for a typical 24×80
|
||||
/// terminal plus reasonable scrollback. Override via
|
||||
@@ -58,7 +58,9 @@ const READ_BUF_BYTES: usize = 4096;
|
||||
#[derive(Debug)]
|
||||
pub struct PtyBridge {
|
||||
fifo_path: PathBuf,
|
||||
sender: broadcast::Sender<Vec<u8>>,
|
||||
/// `None` once [`Self::seal`] has run: live subscribers see the channel
|
||||
/// close, but the replay buffer stays readable.
|
||||
sender: Option<broadcast::Sender<Vec<u8>>>,
|
||||
replay: ReplayBuffer,
|
||||
/// Monotonic timestamp of the last non-empty read off the FIFO, bumped by
|
||||
/// `run_reader`. The activity watcher reads it to gauge PTY quiescence
|
||||
@@ -100,7 +102,7 @@ impl PtyBridge {
|
||||
});
|
||||
Ok(Self {
|
||||
fifo_path,
|
||||
sender,
|
||||
sender: Some(sender),
|
||||
replay,
|
||||
last_activity,
|
||||
task,
|
||||
@@ -123,7 +125,14 @@ impl PtyBridge {
|
||||
/// Subscribe to live PTY frames. Use [`Self::subscribe_with_replay`] for
|
||||
/// new attaches that want the buffered scrollback first.
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<Vec<u8>> {
|
||||
self.sender.subscribe()
|
||||
match &self.sender {
|
||||
Some(tx) => tx.subscribe(),
|
||||
None => {
|
||||
let (tx, rx) = broadcast::channel(1);
|
||||
drop(tx);
|
||||
rx
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Atomically snapshot the replay buffer and return a fresh subscriber
|
||||
@@ -134,10 +143,30 @@ impl PtyBridge {
|
||||
pub fn subscribe_with_replay(&self) -> (Vec<u8>, broadcast::Receiver<Vec<u8>>) {
|
||||
let guard = self.replay.lock_for_snapshot();
|
||||
let snapshot = guard.snapshot();
|
||||
let rx = self.sender.subscribe();
|
||||
let rx = match &self.sender {
|
||||
Some(tx) => tx.subscribe(),
|
||||
// Sealed: hand back the scrollback plus a receiver that is already
|
||||
// closed, so the client renders the final output and then sees the
|
||||
// stream end rather than hanging.
|
||||
None => {
|
||||
let (tx, rx) = broadcast::channel(1);
|
||||
drop(tx);
|
||||
rx
|
||||
}
|
||||
};
|
||||
drop(guard);
|
||||
(snapshot, rx)
|
||||
}
|
||||
|
||||
/// Stop reading and close the live stream, keeping the replay buffer.
|
||||
///
|
||||
/// Attached clients see the channel close — without that a `maestro attach`
|
||||
/// sits in raw mode against a shell that has exited (NAP-226) — while the
|
||||
/// buffered output survives for anyone who attaches later.
|
||||
pub fn seal(&mut self) {
|
||||
self.task.abort();
|
||||
self.sender = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PtyBridge {
|
||||
|
||||
@@ -12,46 +12,38 @@ use std::time::Duration;
|
||||
|
||||
use chrono::Utc;
|
||||
use maestro_protocol::{
|
||||
ActivityState, CreateSessionRequest, ErrorInfo, Session, SessionStatus, WorktreeSpec,
|
||||
ActivityState, CatalogEvent, CreateSessionRequest, ErrorInfo, Session, SessionStatus,
|
||||
WorktreeSpec,
|
||||
};
|
||||
use tokio::sync::{broadcast, Mutex};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::panes::Panes;
|
||||
use crate::pty::{pipe_pane_command, PtyBridge};
|
||||
use crate::sidecar::{SidecarError, SidecarStore};
|
||||
use crate::spawn_history::{RecentDir, SpawnHistory, SpawnHistoryRecord};
|
||||
use crate::tmux::{Tmux, TmuxError};
|
||||
use crate::tmux::TmuxError;
|
||||
use crate::worktree::{WorktreeError, WorktreeManager};
|
||||
|
||||
/// Capacity of the session-events broadcast channel. The `/api/events`
|
||||
/// publisher listens; if it lags by this much we just drop frames (clients
|
||||
/// reconciles on `Hello` via the snapshot). Sourced from the shared
|
||||
/// [`maestro_config::BroadcastTuning`] so all broadcast channels track one
|
||||
/// definition (NAP-273).
|
||||
pub const EVENTS_CAPACITY: usize = maestro_config::BroadcastTuning::DEFAULT.events_capacity;
|
||||
/// Capacity of the session-events broadcast channel. A subscriber that falls
|
||||
/// this far behind gets `RecvError::Lagged`, which `/api/events` forwards as
|
||||
/// [`maestro_protocol::CatalogEvent::Lagged`] so that client re-fetches.
|
||||
pub const EVENTS_CAPACITY: usize = maestro_config::EVENTS_CAPACITY;
|
||||
|
||||
/// How often the liveness watcher polls tmux for sessions that disappeared.
|
||||
pub const DEFAULT_LIVENESS_INTERVAL: Duration = Duration::from_secs(2);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SessionEvent {
|
||||
Added(Session),
|
||||
Removed(Uuid),
|
||||
Updated(Session),
|
||||
}
|
||||
|
||||
/// Per-session daemon-local bookkeeping that complements the public `Session`.
|
||||
#[derive(Debug)]
|
||||
pub struct SessionRecord {
|
||||
pub session: Session,
|
||||
pub fifo_path: PathBuf,
|
||||
/// Worktree we created at spawn time and that should be cleaned up on
|
||||
/// kill (if `cleanup_worktree_on_kill`).
|
||||
/// Worktree we created at spawn time; removed on kill unless the
|
||||
/// dirty-work guard refuses (#56).
|
||||
pub worktree_path: Option<PathBuf>,
|
||||
/// `base_repo` from the original `WorktreeSpec`. Needed because `git
|
||||
/// worktree remove` is invoked from the base repo.
|
||||
pub worktree_base_repo: Option<PathBuf>,
|
||||
pub cleanup_worktree_on_kill: bool,
|
||||
pub bridge: PtyBridge,
|
||||
}
|
||||
|
||||
@@ -67,6 +59,8 @@ pub enum SessionError {
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("session not found: {0}")]
|
||||
NotFound(Uuid),
|
||||
#[error("invalid environment variable name: {0:?}")]
|
||||
InvalidEnv(String),
|
||||
}
|
||||
|
||||
impl SessionError {
|
||||
@@ -77,6 +71,7 @@ impl SessionError {
|
||||
SessionError::Sidecar(_) => "sidecar_failed",
|
||||
SessionError::Io(_) => "io_failed",
|
||||
SessionError::NotFound(_) => "not_found",
|
||||
SessionError::InvalidEnv(_) => "invalid_env",
|
||||
};
|
||||
ErrorInfo {
|
||||
code: code.into(),
|
||||
@@ -93,7 +88,7 @@ pub struct SessionManager {
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
tmux: Tmux,
|
||||
tmux: Arc<dyn Panes>,
|
||||
sidecar: SidecarStore,
|
||||
worktree_mgr: WorktreeManager,
|
||||
fifo_dir: PathBuf,
|
||||
@@ -105,12 +100,12 @@ struct Inner {
|
||||
/// but disabled (`0`-day) history no-ops internally.
|
||||
spawn_history: Option<SpawnHistory>,
|
||||
sessions: Mutex<HashMap<Uuid, SessionRecord>>,
|
||||
events: broadcast::Sender<SessionEvent>,
|
||||
events: broadcast::Sender<CatalogEvent>,
|
||||
}
|
||||
|
||||
impl SessionManager {
|
||||
pub fn new(
|
||||
tmux: Tmux,
|
||||
tmux: Arc<dyn Panes>,
|
||||
sidecar: SidecarStore,
|
||||
worktree_mgr: WorktreeManager,
|
||||
fifo_dir: PathBuf,
|
||||
@@ -127,7 +122,7 @@ impl SessionManager {
|
||||
/// Variant that lets the caller override the per-session replay buffer
|
||||
/// cap. Pass `0` to disable replay (subscribers see only live frames).
|
||||
pub fn new_with_replay(
|
||||
tmux: Tmux,
|
||||
tmux: Arc<dyn Panes>,
|
||||
sidecar: SidecarStore,
|
||||
worktree_mgr: WorktreeManager,
|
||||
fifo_dir: PathBuf,
|
||||
@@ -149,16 +144,18 @@ impl SessionManager {
|
||||
}
|
||||
|
||||
/// Attach a durable spawn-history log (#24). Builder, called once right
|
||||
/// after construction while the `Arc<Inner>` is uniquely owned — so
|
||||
/// [`Arc::get_mut`] succeeds. A no-op (logged) on the off chance the handle
|
||||
/// was already cloned.
|
||||
/// after construction while the `Arc<Inner>` is uniquely owned.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If the handle has already been cloned. That is a construction-order
|
||||
/// mistake, and the alternative — logging and carrying on — produces a
|
||||
/// daemon whose "recent dirs" picker is permanently empty with nothing to
|
||||
/// show for it.
|
||||
pub fn with_spawn_history(mut self, history: SpawnHistory) -> Self {
|
||||
match Arc::get_mut(&mut self.inner) {
|
||||
Some(inner) => inner.spawn_history = Some(history),
|
||||
None => tracing::error!(
|
||||
"with_spawn_history called after the SessionManager was cloned; ignoring"
|
||||
),
|
||||
}
|
||||
let inner = Arc::get_mut(&mut self.inner)
|
||||
.expect("with_spawn_history must be called before the SessionManager is cloned");
|
||||
inner.spawn_history = Some(history);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -172,7 +169,19 @@ impl SessionManager {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn events(&self) -> broadcast::Receiver<SessionEvent> {
|
||||
/// Every deduped recent dir, newest-first, without the picker's result
|
||||
/// cap (#54): project enrichment folds the whole history.
|
||||
pub fn all_recent_dirs(&self) -> Vec<RecentDir> {
|
||||
self.inner
|
||||
.spawn_history
|
||||
.as_ref()
|
||||
.map(|h| h.all_recent_dirs())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Subscribe to session deltas. Each subscriber gets its own lag domain —
|
||||
/// a slow client makes only itself resync.
|
||||
pub fn events(&self) -> broadcast::Receiver<CatalogEvent> {
|
||||
self.inner.events.subscribe()
|
||||
}
|
||||
|
||||
@@ -204,27 +213,29 @@ impl SessionManager {
|
||||
self.inner.sessions.lock().await.contains_key(&id)
|
||||
}
|
||||
|
||||
/// Current status of a session, or `None` if we do not know it.
|
||||
pub async fn status(&self, id: Uuid) -> Option<SessionStatus> {
|
||||
let sessions = self.inner.sessions.lock().await;
|
||||
sessions.get(&id).map(|r| r.session.status)
|
||||
}
|
||||
|
||||
/// Spawn a new session. On success returns the freshly-created `Session`.
|
||||
pub async fn create(&self, req: CreateSessionRequest) -> Result<Session, SessionError> {
|
||||
let (effective_cwd, worktree_path, worktree_base_repo) = match &req.worktree {
|
||||
Some(WorktreeSpec {
|
||||
base_repo, branch, ..
|
||||
}) => {
|
||||
let path = self
|
||||
.inner
|
||||
.worktree_mgr
|
||||
.add(base_repo, branch)
|
||||
.map_err(SessionError::Worktree)?;
|
||||
Some(spec) => {
|
||||
let WorktreeSpec {
|
||||
base_repo, branch, ..
|
||||
} = spec;
|
||||
let path = if spec.create_branch {
|
||||
self.inner.worktree_mgr.add_new(base_repo, branch)
|
||||
} else {
|
||||
self.inner.worktree_mgr.add_existing(base_repo, branch)
|
||||
}
|
||||
.map_err(SessionError::Worktree)?;
|
||||
(path.clone(), Some(path), Some(base_repo.clone()))
|
||||
}
|
||||
None => (req.cwd.clone(), None, None),
|
||||
};
|
||||
let cleanup_worktree_on_kill = req
|
||||
.worktree
|
||||
.as_ref()
|
||||
.map(|w| w.cleanup_on_kill)
|
||||
.unwrap_or(false);
|
||||
|
||||
let id = Uuid::new_v4();
|
||||
// Build the FIFO + reader task *before* asking tmux to spawn the
|
||||
// command — otherwise the child's first bytes race the separate
|
||||
@@ -243,12 +254,21 @@ impl SessionManager {
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
let session_env = match sanitize_env(&req.env) {
|
||||
Ok(env) => env,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&fifo_path);
|
||||
self.rollback_worktree(&worktree_base_repo, &worktree_path);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let spawned = {
|
||||
let tmux = self.inner.tmux.clone();
|
||||
let cwd = effective_cwd.clone();
|
||||
let command = req.command.clone();
|
||||
let sink = pipe_pane_command(&fifo_path);
|
||||
tmux_blocking(move || tmux.new_session_piped(id, &cwd, &command, &sink)).await
|
||||
let env = session_env.clone();
|
||||
tmux_blocking(move || tmux.new_session_piped(id, &cwd, &command, &env, &sink)).await
|
||||
};
|
||||
if let Err(e) = spawned {
|
||||
// `bridge` drops at the end of this block, closing the FIFO reader.
|
||||
@@ -300,12 +320,13 @@ impl SessionManager {
|
||||
fifo_path,
|
||||
worktree_path,
|
||||
worktree_base_repo,
|
||||
cleanup_worktree_on_kill,
|
||||
bridge,
|
||||
},
|
||||
);
|
||||
}
|
||||
let _ = self.inner.events.send(SessionEvent::Added(session.clone()));
|
||||
let _ = self.inner.events.send(CatalogEvent::SessionAdded {
|
||||
session: session.clone(),
|
||||
});
|
||||
|
||||
// Best-effort: log the spawn for the recents picker (#24). A log-write
|
||||
// failure must never fail an otherwise-successful spawn, so the error
|
||||
@@ -340,15 +361,21 @@ impl SessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Kill a session and remove its on-disk artifacts. The worktree is only
|
||||
/// pruned if the create request set `cleanup_on_kill: true`.
|
||||
/// Kill a session and remove its on-disk artifacts. The worktree is
|
||||
/// always pruned -- unless it holds uncommitted changes or commits not on
|
||||
/// any other ref, in which case the guard leaves it on disk (#56).
|
||||
///
|
||||
/// This is also how an already-dead session is dismissed. tmux is only
|
||||
/// asked to kill something it still has — calling `kill-session` on a
|
||||
/// session tmux already lost fails, and that failure is not interesting.
|
||||
pub async fn kill(&self, id: Uuid) -> Result<(), SessionError> {
|
||||
let removed = {
|
||||
let mut sessions = self.inner.sessions.lock().await;
|
||||
sessions.remove(&id)
|
||||
};
|
||||
let record = removed.ok_or(SessionError::NotFound(id))?;
|
||||
cleanup_record(&self.inner, id, record, true).await;
|
||||
let alive = record.session.status == SessionStatus::Running;
|
||||
cleanup_record(&self.inner, id, record, alive).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -432,19 +459,26 @@ impl SessionManager {
|
||||
fifo_path,
|
||||
worktree_path: None,
|
||||
worktree_base_repo: None,
|
||||
cleanup_worktree_on_kill: false,
|
||||
bridge,
|
||||
},
|
||||
);
|
||||
let _ = self.inner.events.send(SessionEvent::Added(session));
|
||||
let _ = self
|
||||
.inner
|
||||
.events
|
||||
.send(CatalogEvent::SessionAdded { session });
|
||||
adopted += 1;
|
||||
}
|
||||
Ok(adopted)
|
||||
}
|
||||
|
||||
/// Forward keystrokes to a session's pane. A dead session is read-only —
|
||||
/// its pane is gone, so this is a no-op rather than a tmux failure the
|
||||
/// client would have to interpret.
|
||||
pub async fn send_keys(&self, id: Uuid, bytes: &[u8]) -> Result<(), SessionError> {
|
||||
if !self.has(id).await {
|
||||
return Err(SessionError::NotFound(id));
|
||||
match self.status(id).await {
|
||||
None => return Err(SessionError::NotFound(id)),
|
||||
Some(SessionStatus::Dead) => return Ok(()),
|
||||
Some(SessionStatus::Running) => {}
|
||||
}
|
||||
let tmux = self.inner.tmux.clone();
|
||||
let bytes = bytes.to_vec();
|
||||
@@ -453,9 +487,13 @@ impl SessionManager {
|
||||
.map_err(SessionError::Tmux)
|
||||
}
|
||||
|
||||
/// Resize a session's window. No-op for a dead session, as with
|
||||
/// [`Self::send_keys`].
|
||||
pub async fn resize(&self, id: Uuid, cols: u16, rows: u16) -> Result<(), SessionError> {
|
||||
if !self.has(id).await {
|
||||
return Err(SessionError::NotFound(id));
|
||||
match self.status(id).await {
|
||||
None => return Err(SessionError::NotFound(id)),
|
||||
Some(SessionStatus::Dead) => return Ok(()),
|
||||
Some(SessionStatus::Running) => {}
|
||||
}
|
||||
let tmux = self.inner.tmux.clone();
|
||||
tmux_blocking(move || tmux.resize_window(id, cols, rows))
|
||||
@@ -469,6 +507,24 @@ impl SessionManager {
|
||||
/// milliseconds on a loaded host, and `send_keys` rides the per-keystroke hot
|
||||
/// path — running it inline would starve HTTP handlers, the events WS, the
|
||||
/// liveness watcher, and PTY readers (NAP-256).
|
||||
/// Turn a request's environment into tmux `-e KEY=VAL` material.
|
||||
///
|
||||
/// A key containing `=` or NUL would be parsed by tmux as a different
|
||||
/// assignment than the caller wrote, so it is rejected rather than silently
|
||||
/// reinterpreted. `BTreeMap` so the resulting argv is deterministic.
|
||||
fn sanitize_env(
|
||||
env: &std::collections::HashMap<String, String>,
|
||||
) -> Result<std::collections::BTreeMap<String, String>, SessionError> {
|
||||
let mut out = std::collections::BTreeMap::new();
|
||||
for (k, v) in env {
|
||||
if k.is_empty() || k.contains('=') || k.contains('\0') || v.contains('\0') {
|
||||
return Err(SessionError::InvalidEnv(k.clone()));
|
||||
}
|
||||
out.insert(k.clone(), v.clone());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn tmux_blocking<T, F>(f: F) -> T
|
||||
where
|
||||
F: FnOnce() -> T + Send + 'static,
|
||||
@@ -486,13 +542,22 @@ async fn run_liveness_pass(inner: &Arc<Inner>) {
|
||||
// nothing to reap and no reason to spawn a tmux subprocess (this also
|
||||
// avoids racing with the very first `new-session` that would otherwise
|
||||
// be competing to start the tmux server).
|
||||
// Only sessions we still believe are running can transition; a session
|
||||
// already marked Dead must not re-emit an update on every 2s tick.
|
||||
let known: Vec<Uuid> = {
|
||||
let sessions = inner.sessions.lock().await;
|
||||
if sessions.is_empty() {
|
||||
return;
|
||||
}
|
||||
sessions.keys().copied().collect()
|
||||
sessions
|
||||
.iter()
|
||||
.filter(|(_, r)| r.session.status == SessionStatus::Running)
|
||||
.map(|(id, _)| *id)
|
||||
.collect()
|
||||
};
|
||||
if known.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let live_ids = {
|
||||
let tmux = inner.tmux.clone();
|
||||
@@ -508,7 +573,7 @@ async fn run_liveness_pass(inner: &Arc<Inner>) {
|
||||
|
||||
for id in known {
|
||||
if !live.contains(&id) {
|
||||
reap_dead_session(inner, id).await;
|
||||
mark_session_dead(inner, id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -522,8 +587,22 @@ async fn run_activity_pass(inner: &Arc<Inner>) {
|
||||
if sessions.is_empty() {
|
||||
return;
|
||||
}
|
||||
sessions.keys().copied().collect()
|
||||
// A dead session has no pane to inspect; its last observed activity is
|
||||
// kept as-is so the UI can still show what it was doing when it died.
|
||||
sessions
|
||||
.iter()
|
||||
.filter(|(_, r)| r.session.status == SessionStatus::Running)
|
||||
.map(|(id, _)| *id)
|
||||
.collect()
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// One `/proc` walk for the whole pass, rather than one per session. Reading
|
||||
// it is pure filesystem work, so it goes on the blocking pool alongside the
|
||||
// tmux calls below.
|
||||
let groups = tmux_blocking(crate::proc::ProcGroups::snapshot).await;
|
||||
|
||||
for id in ids {
|
||||
// The tmux pane lookup is a subprocess — keep it off the runtime worker
|
||||
@@ -541,7 +620,7 @@ async fn run_activity_pass(inner: &Arc<Inner>) {
|
||||
}
|
||||
};
|
||||
// `/proc` inspection is cheap, but still done off the async lock.
|
||||
let awaiting = crate::proc::awaiting_input(pane.pane_pid, &pane.tty);
|
||||
let awaiting = crate::proc::awaiting_input(pane.pane_pid, &pane.tty, &groups);
|
||||
|
||||
let updated = {
|
||||
let mut sessions = inner.sessions.lock().await;
|
||||
@@ -573,24 +652,41 @@ async fn run_activity_pass(inner: &Arc<Inner>) {
|
||||
}
|
||||
};
|
||||
if let Some(session) = updated {
|
||||
let _ = inner.events.send(SessionEvent::Updated(session));
|
||||
let _ = inner.events.send(CatalogEvent::SessionUpdated { session });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a session whose tmux session is already gone: drop the in-memory
|
||||
/// record, delete the sidecar + FIFO, clean up its worktree if requested, and
|
||||
/// fire `SessionEvent::Removed`. No tmux kill — there is nothing left to kill.
|
||||
async fn reap_dead_session(inner: &Arc<Inner>, id: Uuid) {
|
||||
let record = {
|
||||
/// Mark a session whose tmux session has disappeared as [`SessionStatus::Dead`]
|
||||
/// and announce it, keeping everything else intact.
|
||||
///
|
||||
/// The record, its [`PtyBridge`] and its sidecar all survive, so a client can
|
||||
/// still attach and read the replay buffer — the last thing a crashed agent
|
||||
/// printed. Artifacts are only released when the operator dismisses the session
|
||||
/// via [`SessionManager::kill`].
|
||||
///
|
||||
/// Dead sessions do not survive a daemon restart: [`SessionManager::recover`]
|
||||
/// adopts only what tmux still holds.
|
||||
async fn mark_session_dead(inner: &Arc<Inner>, id: Uuid) {
|
||||
let updated = {
|
||||
let mut sessions = inner.sessions.lock().await;
|
||||
sessions.remove(&id)
|
||||
match sessions.get_mut(&id) {
|
||||
Some(record) if record.session.status == SessionStatus::Running => {
|
||||
record.session.status = SessionStatus::Dead;
|
||||
// Release anyone attached; the scrollback survives for a later
|
||||
// attach.
|
||||
record.bridge.seal();
|
||||
Some(record.session.clone())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let Some(record) = record else {
|
||||
let Some(session) = updated else {
|
||||
return;
|
||||
};
|
||||
tracing::info!(%id, "session vanished from tmux — reaping");
|
||||
cleanup_record(inner, id, record, false).await;
|
||||
tracing::info!(%id, "session vanished from tmux — marking dead");
|
||||
let _ = inner.sidecar.write(&session);
|
||||
let _ = inner.events.send(CatalogEvent::SessionUpdated { session });
|
||||
}
|
||||
|
||||
/// Tear down a session's artifacts after it has already been removed from the
|
||||
@@ -611,10 +707,19 @@ async fn cleanup_record(inner: &Arc<Inner>, id: Uuid, record: SessionRecord, kil
|
||||
if let Err(e) = inner.sidecar.delete(id) {
|
||||
tracing::warn!(error = ?e, %id, "cleanup: failed to delete sidecar");
|
||||
}
|
||||
if record.cleanup_worktree_on_kill {
|
||||
if let (Some(base), Some(path)) = (&record.worktree_base_repo, &record.worktree_path) {
|
||||
let _ = inner.worktree_mgr.remove(base, path);
|
||||
// Cleanup is unconditional now (#56): `cleanup_on_kill` is no longer a
|
||||
// user-facing choice. The manager's guard is what protects unsaved work --
|
||||
// when it refuses, leave the tree on disk and say where it is so the
|
||||
// operator can find it.
|
||||
if let (Some(base), Some(path)) = (&record.worktree_base_repo, &record.worktree_path) {
|
||||
if let Err(e) = inner.worktree_mgr.remove(base, path) {
|
||||
tracing::warn!(
|
||||
%id,
|
||||
path = %path.display(),
|
||||
error = %e,
|
||||
"left worktree on disk"
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = inner.events.send(SessionEvent::Removed(id));
|
||||
let _ = inner.events.send(CatalogEvent::SessionRemoved { id });
|
||||
}
|
||||
|
||||
@@ -143,11 +143,23 @@ impl SpawnHistory {
|
||||
/// Recent working dirs, newest use first, deduped by `cwd`, within the
|
||||
/// recency cap, capped at `max_results`. Empty when disabled or unreadable.
|
||||
pub fn recent_dirs(&self) -> Vec<RecentDir> {
|
||||
self.recent_dirs_as_of(Utc::now())
|
||||
self.recent_dirs_capped(Utc::now(), self.max_results)
|
||||
}
|
||||
|
||||
/// Every deduped recent dir, newest-first, without the picker's result
|
||||
/// cap (#54): project enrichment folds the whole history, not its first
|
||||
/// page, so a project spawned in long ago still reads as fresh.
|
||||
pub fn all_recent_dirs(&self) -> Vec<RecentDir> {
|
||||
self.recent_dirs_capped(Utc::now(), usize::MAX)
|
||||
}
|
||||
|
||||
/// [`recent_dirs`](Self::recent_dirs) with an explicit clock for testing.
|
||||
#[cfg(test)]
|
||||
fn recent_dirs_as_of(&self, now: DateTime<Utc>) -> Vec<RecentDir> {
|
||||
self.recent_dirs_capped(now, self.max_results)
|
||||
}
|
||||
|
||||
fn recent_dirs_capped(&self, now: DateTime<Utc>, max_results: usize) -> Vec<RecentDir> {
|
||||
if !self.is_enabled() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -168,7 +180,7 @@ impl SpawnHistory {
|
||||
last_command: rec.command,
|
||||
last_used: rec.at,
|
||||
});
|
||||
if out.len() >= self.max_results {
|
||||
if out.len() >= max_results {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -362,4 +374,28 @@ mod tests {
|
||||
assert_eq!(recents[0].cwd, PathBuf::from("/d4"));
|
||||
assert_eq!(recents[1].cwd, PathBuf::from("/d3"));
|
||||
}
|
||||
|
||||
/// Project enrichment (#54) folds the whole log, not just the picker's
|
||||
/// first page.
|
||||
#[test]
|
||||
fn all_recent_dirs_skips_the_result_cap() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut h = SpawnHistory::new(tmp.path().join("h.jsonl"), 30);
|
||||
h.max_results = 2;
|
||||
// Recent enough to survive the 30-day cap against the real clock.
|
||||
let base = Utc::now() - Duration::hours(1);
|
||||
for i in 0..5 {
|
||||
h.append(&rec(
|
||||
&format!("/d{i}"),
|
||||
"claude",
|
||||
base + Duration::minutes(i),
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(h.recent_dirs().len(), 2);
|
||||
let all = h.all_recent_dirs();
|
||||
assert_eq!(all.len(), 5);
|
||||
assert_eq!(all[0].cwd, PathBuf::from("/d4"));
|
||||
assert_eq!(all[4].cwd, PathBuf::from("/d0"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! All sessions managed through this wrapper are named `maestro-<uuid>` so that
|
||||
//! the daemon can recover its own sessions on restart (and ignore foreign ones).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::env;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
@@ -75,6 +76,10 @@ impl Tmux {
|
||||
if let Some(d) = &self.tmpdir {
|
||||
c.env("TMUX_TMPDIR", d);
|
||||
}
|
||||
// A daemon started from inside a tmux pane inherits `TMUX`, and tmux
|
||||
// resolves that ahead of `TMUX_TMPDIR` — so without this the daemon
|
||||
// drives the developer's own server and `tmux_tmpdir` does nothing.
|
||||
c.env_remove("TMUX");
|
||||
c
|
||||
}
|
||||
|
||||
@@ -96,7 +101,13 @@ impl Tmux {
|
||||
let command = login_shell_command(env::var_os("SHELL").as_deref(), command);
|
||||
let out = self
|
||||
.cmd()
|
||||
.args(new_session_args(&name, cwd, &command, None))
|
||||
.args(new_session_args(
|
||||
&name,
|
||||
cwd,
|
||||
&command,
|
||||
&BTreeMap::new(),
|
||||
None,
|
||||
))
|
||||
.output()?;
|
||||
check(out)
|
||||
}
|
||||
@@ -112,13 +123,20 @@ impl Tmux {
|
||||
id: Uuid,
|
||||
cwd: &Path,
|
||||
command: &str,
|
||||
session_env: &BTreeMap<String, String>,
|
||||
sink_command: &str,
|
||||
) -> Result<(), TmuxError> {
|
||||
let name = session_name(id);
|
||||
let command = login_shell_command(env::var_os("SHELL").as_deref(), command);
|
||||
let out = self
|
||||
.cmd()
|
||||
.args(new_session_args(&name, cwd, &command, Some(sink_command)))
|
||||
.args(new_session_args(
|
||||
&name,
|
||||
cwd,
|
||||
&command,
|
||||
session_env,
|
||||
Some(sink_command),
|
||||
))
|
||||
.output()?;
|
||||
check(out)
|
||||
}
|
||||
@@ -263,12 +281,22 @@ impl Tmux {
|
||||
}
|
||||
}
|
||||
|
||||
/// Phrasings tmux uses for "there is no server on this socket". They vary by
|
||||
/// version, and `list_sessions` turning one of these into an `Err` stops the
|
||||
/// liveness watcher reaping for that pass — so a missing phrasing is silent.
|
||||
const NO_SERVER_PHRASES: &[&str] = &[
|
||||
"no server running",
|
||||
"no sessions",
|
||||
"error connecting",
|
||||
// tmux >= 3.7 when the server shuts down while this client is connected,
|
||||
// which is exactly what killing the last session does.
|
||||
"server exited unexpectedly",
|
||||
];
|
||||
|
||||
/// True if tmux's stderr indicates "there is no tmux server running on this
|
||||
/// socket" (multiple phrasings across versions).
|
||||
fn is_no_server_error(stderr: &str) -> bool {
|
||||
stderr.contains("no server running")
|
||||
|| stderr.contains("no sessions")
|
||||
|| stderr.contains("error connecting")
|
||||
NO_SERVER_PHRASES.iter().any(|p| stderr.contains(p))
|
||||
}
|
||||
|
||||
/// A session pane's process id, foreground command, controlling tty, and
|
||||
@@ -360,6 +388,7 @@ fn new_session_args(
|
||||
name: &str,
|
||||
cwd: &Path,
|
||||
command: &str,
|
||||
env: &BTreeMap<String, String>,
|
||||
pipe_sink: Option<&str>,
|
||||
) -> Vec<OsString> {
|
||||
let mut args = vec![
|
||||
@@ -378,8 +407,14 @@ fn new_session_args(
|
||||
OsString::from(name),
|
||||
OsString::from("-c"),
|
||||
cwd.as_os_str().to_os_string(),
|
||||
OsString::from(command),
|
||||
];
|
||||
// Caller-supplied environment. Sorted so the argv is deterministic, and
|
||||
// therefore assertable.
|
||||
for (k, v) in env {
|
||||
args.push(OsString::from("-e"));
|
||||
args.push(OsString::from(format!("{k}={v}")));
|
||||
}
|
||||
args.push(OsString::from(command));
|
||||
if let Some(sink) = pipe_sink {
|
||||
args.extend([
|
||||
OsString::from(";"),
|
||||
@@ -407,6 +442,82 @@ fn check(out: Output) -> Result<(), TmuxError> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every phrasing must be recognised: an unmatched one makes
|
||||
/// `list_sessions` fail, and a failed pass reaps nothing.
|
||||
#[test]
|
||||
fn new_session_args_emit_sorted_env_flags_before_the_command() {
|
||||
let env: BTreeMap<String, String> = [
|
||||
("ZED".to_string(), "9".to_string()),
|
||||
("ALPHA".to_string(), "1".to_string()),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let args = new_session_args("maestro-x", Path::new("/tmp"), "bash", &env, None);
|
||||
let flat: Vec<String> = args
|
||||
.iter()
|
||||
.map(|a| a.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
|
||||
let alpha = flat.iter().position(|a| a == "ALPHA=1").expect("ALPHA");
|
||||
let zed = flat.iter().position(|a| a == "ZED=9").expect("ZED");
|
||||
let command = flat.iter().rposition(|a| a == "bash").expect("command");
|
||||
assert!(alpha < zed, "env flags must be sorted for a stable argv");
|
||||
assert!(zed < command, "env must precede the command argument");
|
||||
assert_eq!(flat[alpha - 1], "-e");
|
||||
assert_eq!(flat[zed - 1], "-e");
|
||||
}
|
||||
|
||||
/// `TMUX` beats `TMUX_TMPDIR` when tmux looks for a server, so leaving an
|
||||
/// inherited one in place would silently ignore the configured tmpdir.
|
||||
#[test]
|
||||
fn cmd_clears_an_inherited_tmux_and_sets_the_configured_tmpdir() {
|
||||
let tmux = Tmux::new().with_tmpdir("/run/maestro-dev");
|
||||
let cmd = tmux.cmd();
|
||||
let envs: Vec<_> = cmd.get_envs().collect();
|
||||
|
||||
assert!(
|
||||
envs.contains(&(OsStr::new("TMUX"), None)),
|
||||
"TMUX must be removed, got {envs:?}"
|
||||
);
|
||||
assert!(
|
||||
envs.contains(&(
|
||||
OsStr::new("TMUX_TMPDIR"),
|
||||
Some(OsStr::new("/run/maestro-dev"))
|
||||
)),
|
||||
"TMUX_TMPDIR must be set, got {envs:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The removal is unconditional: a daemon manages its own server whether or
|
||||
/// not a tmpdir was configured.
|
||||
#[test]
|
||||
fn cmd_clears_an_inherited_tmux_without_a_configured_tmpdir() {
|
||||
let cmd = Tmux::new().cmd();
|
||||
let envs: Vec<_> = cmd.get_envs().collect();
|
||||
assert!(
|
||||
envs.contains(&(OsStr::new("TMUX"), None)),
|
||||
"TMUX must be removed, got {envs:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_no_server_error_matches_every_known_phrasing() {
|
||||
for phrase in NO_SERVER_PHRASES {
|
||||
assert!(is_no_server_error(phrase), "unmatched: {phrase}");
|
||||
assert!(
|
||||
is_no_server_error(&format!("{phrase}\n")),
|
||||
"unmatched with trailing newline: {phrase}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_no_server_error_rejects_unrelated_failures() {
|
||||
assert!(!is_no_server_error("can't find session: maestro-x"));
|
||||
assert!(!is_no_server_error("usage: kill-session"));
|
||||
assert!(!is_no_server_error(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_pane_line_splits_pid_command_tty_path() {
|
||||
let p = parse_pane_line("12345 claude /dev/pts/3 /home/naps62/maestro").unwrap();
|
||||
@@ -440,7 +551,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn new_session_args_pass_256color_env_and_default_terminal() {
|
||||
let args = new_session_args("maestro-abc", Path::new("/tmp/proj"), "sleep 30", None);
|
||||
let args = new_session_args(
|
||||
"maestro-abc",
|
||||
Path::new("/tmp/proj"),
|
||||
"sleep 30",
|
||||
&BTreeMap::new(),
|
||||
None,
|
||||
);
|
||||
let strs: Vec<&str> = args.iter().map(|s| s.to_str().unwrap()).collect();
|
||||
assert_eq!(
|
||||
strs,
|
||||
@@ -496,6 +613,7 @@ mod tests {
|
||||
"maestro-abc",
|
||||
Path::new("/tmp/proj"),
|
||||
"sleep 30",
|
||||
&BTreeMap::new(),
|
||||
Some("cat >> '/tmp/fifo'"),
|
||||
);
|
||||
let strs: Vec<&str> = args.iter().map(|s| s.to_str().unwrap()).collect();
|
||||
|
||||
@@ -4,64 +4,124 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum WorktreeError {
|
||||
#[error("failed to spawn git: {0}")]
|
||||
Spawn(#[from] std::io::Error),
|
||||
#[error("git exited with code {code}: {stderr}")]
|
||||
NonZero { code: i32, stderr: String },
|
||||
/// A worktree already occupies the target path. The caller decides what
|
||||
/// to do; the daemon never relocates to a different directory (#56).
|
||||
#[error("worktree path already exists: {}", .path.display())]
|
||||
PathExists { path: PathBuf },
|
||||
/// The worktree holds unsaved work; removal was refused (#56).
|
||||
#[error("left {} on disk: {}", .path.display(), .reason)]
|
||||
Guarded { path: PathBuf, reason: String },
|
||||
}
|
||||
|
||||
/// Generates a unique path under `root` and runs `git worktree add` rooted at
|
||||
/// `base_repo`. Each call appends a UUID-suffixed directory so concurrent
|
||||
/// `add()`s never collide.
|
||||
/// Runs `git worktree add` rooted at `base_repo`. By default worktrees land
|
||||
/// inside the repository itself at `<repo>/worktrees/<branch>` (#56) so they
|
||||
/// are findable from the repo; an operator-set root overrides that.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WorktreeManager {
|
||||
root: PathBuf,
|
||||
/// `[daemon].worktree_root` override. `None` uses the default
|
||||
/// `<repo>/worktrees/<branch>` placement.
|
||||
root_override: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl WorktreeManager {
|
||||
pub fn new(root: impl Into<PathBuf>) -> Self {
|
||||
Self { root: root.into() }
|
||||
pub fn new(root_override: Option<PathBuf>) -> Self {
|
||||
Self { root_override }
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
self.root_override.as_deref()
|
||||
}
|
||||
|
||||
/// `git -C <base_repo> worktree add -b <branch> <generated-path>`.
|
||||
/// Returns the path of the new worktree on success.
|
||||
pub fn add(&self, base_repo: &Path, branch: &str) -> Result<PathBuf, WorktreeError> {
|
||||
std::fs::create_dir_all(&self.root)?;
|
||||
let path = self.generate_path(branch);
|
||||
let out = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(base_repo)
|
||||
.args(["worktree", "add", "-b", branch])
|
||||
.arg(&path)
|
||||
.output()?;
|
||||
/// Where a worktree for `branch` will be created: the override root, or
|
||||
/// `<base_repo>/worktrees/<sanitized branch>` by default. The path is
|
||||
/// predictable (no UUID suffix), so an existing directory at the target
|
||||
/// is an error rather than a silently different location.
|
||||
fn target_path(&self, base_repo: &Path, branch: &str) -> PathBuf {
|
||||
let slug = sanitize_branch_for_path(branch);
|
||||
match &self.root_override {
|
||||
Some(root) => root.join(slug),
|
||||
None => base_repo.join("worktrees").join(slug),
|
||||
}
|
||||
}
|
||||
|
||||
/// `git -C <base_repo> worktree add -b <branch> <path>` — creates the
|
||||
/// branch. Returns the path of the new worktree on success.
|
||||
pub fn add_new(&self, base_repo: &Path, branch: &str) -> Result<PathBuf, WorktreeError> {
|
||||
self.run_add(base_repo, branch, true)
|
||||
}
|
||||
|
||||
/// `git -C <base_repo> worktree add <path> <branch>` — checks out a branch
|
||||
/// that must already exist (#56).
|
||||
pub fn add_existing(&self, base_repo: &Path, branch: &str) -> Result<PathBuf, WorktreeError> {
|
||||
self.run_add(base_repo, branch, false)
|
||||
}
|
||||
|
||||
fn run_add(
|
||||
&self,
|
||||
base_repo: &Path,
|
||||
branch: &str,
|
||||
create_branch: bool,
|
||||
) -> Result<PathBuf, WorktreeError> {
|
||||
let path = self.target_path(base_repo, branch);
|
||||
// Clear registrations whose directory is gone before testing the
|
||||
// path, so a previously-leaked entry doesn't block this branch.
|
||||
prune(base_repo)?;
|
||||
if path.symlink_metadata().is_ok() {
|
||||
return Err(WorktreeError::PathExists { path });
|
||||
}
|
||||
// The parent (`<repo>/worktrees` or the override root) may not exist
|
||||
// yet; the target itself must not.
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.arg("-C").arg(base_repo).args(["worktree", "add"]);
|
||||
if create_branch {
|
||||
cmd.arg("-b").arg(branch).arg(&path);
|
||||
} else {
|
||||
// Existing branch: `worktree add <path> <branch>` with no `-b`.
|
||||
cmd.arg(&path).arg(branch);
|
||||
}
|
||||
let out = cmd.output()?;
|
||||
check(out)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// `git -C <base_repo> worktree remove --force <path>`.
|
||||
/// `git -C <base_repo> worktree remove <path>` — but only when the
|
||||
/// worktree holds nothing unique (#56). A worktree with uncommitted
|
||||
/// changes, or with commits reachable from no other ref, is refused and
|
||||
/// left on disk so the operator can rescue it; cleanup is unconditional,
|
||||
/// which makes this guard the only thing standing between a stray kill
|
||||
/// and destroyed work.
|
||||
pub fn remove(&self, base_repo: &Path, path: &Path) -> Result<(), WorktreeError> {
|
||||
// Gone from disk already (operator `rm -rf`, or a create that failed
|
||||
// half-way). Probing it with git would fail and be misread as unsaved
|
||||
// work, stranding the registration — and since paths are
|
||||
// deterministic, `worktree add` would then refuse that branch forever
|
||||
// with "missing but already registered" (#56 review).
|
||||
if !path.exists() {
|
||||
return prune(base_repo);
|
||||
}
|
||||
if let Some(reason) = unsafe_to_remove(path)? {
|
||||
return Err(WorktreeError::Guarded {
|
||||
path: path.to_path_buf(),
|
||||
reason,
|
||||
});
|
||||
}
|
||||
let out = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(base_repo)
|
||||
.args(["worktree", "remove", "--force"])
|
||||
.args(["worktree", "remove"])
|
||||
.arg(path)
|
||||
.output()?;
|
||||
check(out)
|
||||
}
|
||||
|
||||
fn generate_path(&self, branch: &str) -> PathBuf {
|
||||
let slug = sanitize_branch_for_path(branch);
|
||||
let unique = Uuid::new_v4().simple();
|
||||
self.root.join(format!("{slug}-{unique}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize_branch_for_path(branch: &str) -> String {
|
||||
@@ -79,6 +139,51 @@ fn sanitize_branch_for_path(branch: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// `Some(reason)` when deleting `path` would destroy work.
|
||||
///
|
||||
/// Only an unclean working tree qualifies. `git worktree remove` deletes the
|
||||
/// checkout but keeps `refs/heads/<branch>`, so committed work — pushed or
|
||||
/// not — stays reachable and is never at risk. Guarding on "commits on no
|
||||
/// other ref" instead would refuse every ordinary unpushed feature branch,
|
||||
/// and because the path is deterministic that branch could then never be
|
||||
/// spawned again (#56 review).
|
||||
fn unsafe_to_remove(path: &Path) -> Result<Option<String>, WorktreeError> {
|
||||
// `--ignored=no` keeps build output out of it; untracked sources count,
|
||||
// since removal would delete them.
|
||||
let status = run_git(path, ["status", "--porcelain", "--ignored=no"])?;
|
||||
if !status.stdout.is_empty() {
|
||||
return Ok(Some("has uncommitted changes".into()));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// `git -C <base_repo> worktree prune` — drops registrations whose directory
|
||||
/// no longer exists.
|
||||
fn prune(base_repo: &Path) -> Result<(), WorktreeError> {
|
||||
let out = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(base_repo)
|
||||
.args(["worktree", "prune"])
|
||||
.output()?;
|
||||
check(out)
|
||||
}
|
||||
|
||||
fn run_git(
|
||||
dir: &Path,
|
||||
args: impl IntoIterator<Item = &'static str>,
|
||||
) -> Result<Output, WorktreeError> {
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.arg("-C").arg(dir).args(args);
|
||||
let out = cmd.output()?;
|
||||
if !out.status.success() {
|
||||
return Err(WorktreeError::NonZero {
|
||||
code: out.status.code().unwrap_or(-1),
|
||||
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn check(out: Output) -> Result<(), WorktreeError> {
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Activity detection against real processes on a real tty.
|
||||
//!
|
||||
//! The review noted this pipeline had no end-to-end coverage — `activity::decide`
|
||||
//! was unit-tested, but nothing exercised the `/proc` inspection that feeds it.
|
||||
//! These use a real tmux pane because that is the only way to get a controlling
|
||||
//! terminal with a genuine foreground process group.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use common::TmuxFixture;
|
||||
use maestro_daemon::proc::{awaiting_input, ProcGroups};
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Poll `awaiting_input` until it reports `want`, so we don't race the shell
|
||||
/// reaching its blocking read. Reports what it last saw — the useful half of
|
||||
/// the failure.
|
||||
fn wait_for_awaiting(fx: &TmuxFixture, id: Uuid, want: bool, label: &str) {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let mut last = None;
|
||||
while std::time::Instant::now() < deadline {
|
||||
if let Ok(Some(pane)) = fx.tmux.pane_info(id) {
|
||||
// Fresh each poll: the tree is still settling.
|
||||
let got = awaiting_input(pane.pane_pid, &pane.tty, &ProcGroups::snapshot());
|
||||
if got == want {
|
||||
return;
|
||||
}
|
||||
last = Some(got);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
}
|
||||
panic!("{label}: wanted awaiting_input={want}, last saw {last:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_shell_is_awaiting_input() {
|
||||
let fx = TmuxFixture::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
let id = Uuid::new_v4();
|
||||
fx.tmux
|
||||
.new_session(id, cwd.path(), "bash --noprofile --norc")
|
||||
.expect("new_session");
|
||||
|
||||
wait_for_awaiting(&fx, id, true, "an idle shell sits in read()");
|
||||
}
|
||||
|
||||
/// The case the old heuristic got wrong. It walked `children` to the deepest
|
||||
/// descendant, so it landed on the background `sleep` — which is not on the
|
||||
/// terminal — and reported the session as *not* awaiting input, while the
|
||||
/// foreground process was blocked on `read`.
|
||||
#[test]
|
||||
fn a_foreground_reader_with_a_background_helper_is_awaiting_input() {
|
||||
let fx = TmuxFixture::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
let script = cwd.path().join("agentish.sh");
|
||||
std::fs::write(&script, "#!/bin/bash\nsleep 300 &\nread -r line\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
let id = Uuid::new_v4();
|
||||
fx.tmux
|
||||
.new_session(
|
||||
id,
|
||||
cwd.path(),
|
||||
&format!("bash --noprofile --norc {}", script.display()),
|
||||
)
|
||||
.expect("new_session");
|
||||
|
||||
// Wait for the helper itself. Asserting before it exists would pass
|
||||
// against a deepest-descendant walk too, because until then the newest
|
||||
// process in the tree *is* the one blocked on read.
|
||||
let pane = fx.tmux.pane_info(id).expect("pane_info").expect("pane");
|
||||
wait_until(
|
||||
|| subtree_has_comm(pane.pane_pid, "sleep"),
|
||||
"the background helper to be spawned",
|
||||
);
|
||||
|
||||
wait_for_awaiting(
|
||||
&fx,
|
||||
id,
|
||||
true,
|
||||
"a foreground reader must win over a newer background child",
|
||||
);
|
||||
}
|
||||
|
||||
/// A pure timer sleep also parks in 'S' with the terminal inherited; it must
|
||||
/// read as idle, not as waiting on the user.
|
||||
#[test]
|
||||
fn a_foreground_sleep_is_not_awaiting_input() {
|
||||
let fx = TmuxFixture::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
let id = Uuid::new_v4();
|
||||
fx.tmux
|
||||
.new_session(id, cwd.path(), "sleep 300")
|
||||
.expect("new_session");
|
||||
|
||||
wait_for_awaiting(&fx, id, false, "a timer sleep is not user input");
|
||||
}
|
||||
|
||||
/// Whether any process under `root` (inclusive) has this `comm`.
|
||||
fn subtree_has_comm(root: i32, comm: &str) -> bool {
|
||||
let mut queue = vec![root];
|
||||
while let Some(pid) = queue.pop() {
|
||||
if std::fs::read_to_string(format!("/proc/{pid}/comm")).is_ok_and(|c| c.trim() == comm) {
|
||||
return true;
|
||||
}
|
||||
queue.extend(
|
||||
std::fs::read_to_string(format!("/proc/{pid}/task/{pid}/children"))
|
||||
.map(|s| {
|
||||
s.split_whitespace()
|
||||
.filter_map(|x| x.parse::<i32>().ok())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Block until `cond` holds, so a test asserts on the state it means to
|
||||
/// exercise rather than on whatever the tree looked like first.
|
||||
fn wait_until(cond: impl Fn() -> bool, what: &str) {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while std::time::Instant::now() < deadline {
|
||||
if cond() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
panic!("timed out waiting for {what}");
|
||||
}
|
||||
|
||||
/// Read `pgrp` and `tpgid` for a pid straight from `/proc`, so the test can
|
||||
/// wait for the exact condition it means to exercise rather than a proxy.
|
||||
fn pgrp_and_tpgid(pid: i32) -> Option<(i32, i32)> {
|
||||
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
|
||||
let close = stat.rfind(')')?;
|
||||
let f: Vec<&str> = stat[close + 1..].split_whitespace().collect();
|
||||
Some((f.get(2)?.parse().ok()?, f.get(5)?.parse().ok()?))
|
||||
}
|
||||
|
||||
/// `tpgid` names a process *group*, and its leader can exit while another
|
||||
/// member still holds the terminal — a foreground pipeline whose first stage
|
||||
/// finished. Reading `/proc/<tpgid>` directly then finds nothing and reports
|
||||
/// idle, so the group has to be searched for a live member.
|
||||
///
|
||||
/// Needs an interactive shell: job control is what puts a pipeline in its own
|
||||
/// process group, and that is how the daemon spawns commands
|
||||
/// (`$SHELL -lic '<cmd>'`).
|
||||
#[test]
|
||||
fn a_foreground_pipeline_whose_leader_exited_is_still_awaiting_input() {
|
||||
let fx = TmuxFixture::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
let id = Uuid::new_v4();
|
||||
fx.tmux
|
||||
.new_session(id, cwd.path(), "bash --noprofile --norc -i")
|
||||
.expect("new_session");
|
||||
wait_for_awaiting(&fx, id, true, "the shell must settle first");
|
||||
|
||||
// `true` leads the group and exits immediately; the right-hand stage
|
||||
// survives, blocked reading the terminal.
|
||||
fx.tmux
|
||||
.send_keys(id, b"true | { read -r line < /dev/tty; }\n")
|
||||
.expect("send_keys");
|
||||
|
||||
// Wait for the state this test exists for: the foreground group is no
|
||||
// longer the shell's own, and its leader is gone. Asserting before that
|
||||
// would pass against a leader-only lookup, because the shell is still
|
||||
// foreground and alive.
|
||||
let pane = fx.tmux.pane_info(id).expect("pane_info").expect("pane");
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let mut reached = false;
|
||||
while std::time::Instant::now() < deadline {
|
||||
if let Some((pgrp, tpgid)) = pgrp_and_tpgid(pane.pane_pid) {
|
||||
if tpgid > 0 && tpgid != pgrp && pgrp_and_tpgid(tpgid).is_none() {
|
||||
reached = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(
|
||||
reached,
|
||||
"never observed a foreground group whose leader had exited"
|
||||
);
|
||||
|
||||
assert!(
|
||||
awaiting_input(pane.pane_pid, &pane.tty, &ProcGroups::snapshot()),
|
||||
"a surviving pipeline member still holds the tty"
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use std::time::Duration;
|
||||
|
||||
use common::DaemonFixture;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use maestro_daemon::{local_api, LocalEventBus, SessionManager};
|
||||
use maestro_daemon::{local_api, SessionManager};
|
||||
use maestro_protocol::CreateSessionRequest;
|
||||
use tempfile::TempDir;
|
||||
use tokio::net::TcpListener;
|
||||
@@ -37,7 +37,7 @@ async fn spawn_daemon_ws() -> Harness {
|
||||
"test-host",
|
||||
"/home/test",
|
||||
Vec::new(),
|
||||
LocalEventBus::new(),
|
||||
std::sync::Arc::new(maestro_daemon::projects::ProjectScanner::disabled()),
|
||||
));
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
@@ -326,3 +326,57 @@ async fn second_attach_sees_replay_buffer_of_prior_output() {
|
||||
"fresh attach did not receive replay containing prior output"
|
||||
);
|
||||
}
|
||||
|
||||
/// The point of keeping a dead session: attach afterwards and read what it
|
||||
/// printed before it died. The stream then ends rather than hanging.
|
||||
#[tokio::test]
|
||||
async fn attaching_to_a_dead_session_replays_its_final_output() {
|
||||
let h = spawn_daemon_ws().await;
|
||||
let id = create_bash_session(&h).await;
|
||||
|
||||
// Produce output, then let the session die out-of-band.
|
||||
{
|
||||
let mut ws = connect_attach(h.addr, id).await.unwrap();
|
||||
ws.send(WsMessage::Binary(b"echo last-words\n".to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
}
|
||||
h.manager.start_liveness_watcher(Duration::from_millis(50));
|
||||
h._fx.tmux.tmux.kill_session(id).expect("kill tmux");
|
||||
|
||||
// Wait for the daemon to notice.
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(3);
|
||||
while std::time::Instant::now() < deadline {
|
||||
if h.manager.status(id).await == Some(maestro_protocol::SessionStatus::Dead) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
assert_eq!(
|
||||
h.manager.status(id).await,
|
||||
Some(maestro_protocol::SessionStatus::Dead),
|
||||
"session should be marked dead, not removed"
|
||||
);
|
||||
|
||||
let mut ws = connect_attach(h.addr, id)
|
||||
.await
|
||||
.expect("a dead session must still accept an attach");
|
||||
|
||||
let mut seen = Vec::new();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(3);
|
||||
while std::time::Instant::now() < deadline {
|
||||
match tokio::time::timeout(Duration::from_millis(200), ws.next()).await {
|
||||
Ok(Some(Ok(WsMessage::Binary(b)))) => seen.extend_from_slice(&b),
|
||||
Ok(Some(Ok(WsMessage::Close(_)))) | Ok(None) => break,
|
||||
Ok(Some(Ok(_))) => continue,
|
||||
Ok(Some(Err(_))) => break,
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
let text = String::from_utf8_lossy(&seen);
|
||||
assert!(
|
||||
text.contains("last-words"),
|
||||
"replay of a dead session lost its final output: {text:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -114,7 +115,6 @@ pub struct DaemonFixture {
|
||||
pub tmux: TmuxFixture,
|
||||
pub manager: SessionManager,
|
||||
pub state_dir: TempDir,
|
||||
pub worktree_root: TempDir,
|
||||
}
|
||||
|
||||
impl DaemonFixture {
|
||||
@@ -131,11 +131,11 @@ impl DaemonFixture {
|
||||
fn build(history_days: Option<u32>) -> Self {
|
||||
let tmux = TmuxFixture::new();
|
||||
let state_dir = TempDir::new().unwrap();
|
||||
let worktree_root = TempDir::new().unwrap();
|
||||
let sidecar = SidecarStore::new(state_dir.path().join("sessions"));
|
||||
let worktree_mgr = WorktreeManager::new(worktree_root.path().to_path_buf());
|
||||
// Default placement: worktrees land under their base repo (#56).
|
||||
let worktree_mgr = WorktreeManager::new(None);
|
||||
let mut manager = SessionManager::new(
|
||||
tmux.tmux.clone(),
|
||||
Arc::new(tmux.tmux.clone()),
|
||||
sidecar,
|
||||
worktree_mgr,
|
||||
state_dir.path().join("fifos"),
|
||||
@@ -148,7 +148,6 @@ impl DaemonFixture {
|
||||
tmux,
|
||||
manager,
|
||||
state_dir,
|
||||
worktree_root,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::time::Duration;
|
||||
|
||||
use common::DaemonFixture;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use maestro_daemon::{local_api, LocalEventBus};
|
||||
use maestro_daemon::local_api;
|
||||
use maestro_protocol::{CreateSessionRequest, Session};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::oneshot;
|
||||
@@ -26,9 +26,19 @@ struct Harness {
|
||||
}
|
||||
|
||||
async fn spawn(hostname: &str) -> Harness {
|
||||
spawn_with(
|
||||
hostname,
|
||||
std::sync::Arc::new(maestro_daemon::projects::ProjectScanner::disabled()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn spawn_with(
|
||||
hostname: &str,
|
||||
projects: std::sync::Arc<maestro_daemon::projects::ProjectScanner>,
|
||||
) -> Harness {
|
||||
let fx = DaemonFixture::new();
|
||||
let manager = fx.manager.clone();
|
||||
let events = LocalEventBus::new();
|
||||
// Built-in presets (claude/opencode/zsh + custom) so `/api/info` advertises
|
||||
// a known set (#26).
|
||||
let presets = maestro_config::SpawnSection::default().resolve().unwrap();
|
||||
@@ -37,7 +47,7 @@ async fn spawn(hostname: &str) -> Harness {
|
||||
hostname,
|
||||
"/home/test",
|
||||
presets,
|
||||
events,
|
||||
projects,
|
||||
));
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
@@ -63,6 +73,10 @@ fn url(addr: SocketAddr, path: &str) -> String {
|
||||
format!("http://{addr}{path}")
|
||||
}
|
||||
|
||||
fn ws_url(addr: SocketAddr, path: &str) -> String {
|
||||
format!("ws://{addr}{path}")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn info_returns_daemon_identity() {
|
||||
let h = spawn("naps-laptop").await;
|
||||
@@ -151,6 +165,73 @@ async fn recent_dirs_returns_empty_without_history() {
|
||||
assert_eq!(resp["truncated"], false);
|
||||
}
|
||||
|
||||
/// #54: `GET /api/projects` lists every git repo under the scan roots, with
|
||||
/// real git checkouts — not mocks.
|
||||
#[tokio::test]
|
||||
async fn projects_lists_repos_under_the_scan_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for name in ["alpha", "beta"] {
|
||||
let repo = tmp.path().join(name);
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
for args in [
|
||||
vec!["init", "-q"],
|
||||
vec![
|
||||
"-c",
|
||||
"user.email=t@t",
|
||||
"-c",
|
||||
"user.name=t",
|
||||
"commit",
|
||||
"-qm",
|
||||
"init",
|
||||
"--allow-empty",
|
||||
],
|
||||
] {
|
||||
let out = std::process::Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(&repo)
|
||||
.args(&args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success());
|
||||
}
|
||||
}
|
||||
|
||||
let scanner = std::sync::Arc::new(maestro_daemon::projects::ProjectScanner::new(
|
||||
vec![tmp.path().to_path_buf()],
|
||||
3,
|
||||
tmp.path().to_path_buf(),
|
||||
));
|
||||
let h = spawn_with("naps-laptop", scanner).await;
|
||||
|
||||
let projects: Vec<maestro_protocol::Project> = reqwest::get(url(h.addr, "/api/projects"))
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut names: Vec<&str> = projects.iter().map(|p| p.name.as_str()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["alpha", "beta"]);
|
||||
for p in &projects {
|
||||
assert!(!p.is_worktree);
|
||||
assert_eq!(p.base_repo, None);
|
||||
assert!(p.last_activity.is_some(), "fresh commit ⇒ HEAD mtime known");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn projects_returns_empty_for_a_disabled_scanner() {
|
||||
let h = spawn("naps-laptop").await;
|
||||
let projects: Vec<maestro_protocol::Project> = reqwest::get(url(h.addr, "/api/projects"))
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(projects.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gitroot_probes_path() {
|
||||
// #26: resolves the query against the daemon home dir and walks up for a
|
||||
@@ -260,3 +341,103 @@ async fn attach_ws_for_unknown_session_returns_404() {
|
||||
"{msg}"
|
||||
);
|
||||
}
|
||||
|
||||
/// `WS /api/events` had no daemon-level test: the Snapshot-then-deltas contract
|
||||
/// and the subscribe-before-snapshot ordering were only described in a comment.
|
||||
#[tokio::test]
|
||||
async fn events_ws_sends_a_snapshot_then_streams_deltas() {
|
||||
let h = spawn("konishi").await;
|
||||
let cwd = tempfile::TempDir::new().unwrap();
|
||||
|
||||
let (mut ws, _) = connect_async(ws_url(h.addr, "/api/events"))
|
||||
.await
|
||||
.expect("events ws");
|
||||
|
||||
match next_event(&mut ws).await {
|
||||
maestro_protocol::CatalogEvent::Snapshot { sessions } => assert!(sessions.is_empty()),
|
||||
other => panic!("first frame must be a Snapshot, got {other:?}"),
|
||||
}
|
||||
|
||||
let created = h
|
||||
.manager
|
||||
.create(CreateSessionRequest {
|
||||
cwd: cwd.path().to_path_buf(),
|
||||
command: "sleep 30".into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: None,
|
||||
})
|
||||
.await
|
||||
.expect("create");
|
||||
|
||||
match next_event(&mut ws).await {
|
||||
maestro_protocol::CatalogEvent::SessionAdded { session } => {
|
||||
assert_eq!(session.id, created.id);
|
||||
}
|
||||
other => panic!("expected SessionAdded, got {other:?}"),
|
||||
}
|
||||
|
||||
h.manager.kill(created.id).await.expect("kill");
|
||||
|
||||
// Activity ticks may interleave; the removal is what we are waiting for.
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
assert!(
|
||||
tokio::time::Instant::now() < deadline,
|
||||
"timed out waiting for SessionRemoved"
|
||||
);
|
||||
if let maestro_protocol::CatalogEvent::SessionRemoved { id } = next_event(&mut ws).await {
|
||||
assert_eq!(id, created.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each subscriber has its own lag domain now that the publisher task is gone:
|
||||
/// two clients connected at different times both get their own Snapshot.
|
||||
#[tokio::test]
|
||||
async fn every_events_subscriber_gets_its_own_snapshot() {
|
||||
let h = spawn("konishi").await;
|
||||
let cwd = tempfile::TempDir::new().unwrap();
|
||||
|
||||
let (mut first, _) = connect_async(ws_url(h.addr, "/api/events")).await.unwrap();
|
||||
let _ = next_event(&mut first).await;
|
||||
|
||||
h.manager
|
||||
.create(CreateSessionRequest {
|
||||
cwd: cwd.path().to_path_buf(),
|
||||
command: "sleep 30".into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: None,
|
||||
})
|
||||
.await
|
||||
.expect("create");
|
||||
|
||||
let (mut second, _) = connect_async(ws_url(h.addr, "/api/events")).await.unwrap();
|
||||
match next_event(&mut second).await {
|
||||
maestro_protocol::CatalogEvent::Snapshot { sessions } => {
|
||||
assert_eq!(
|
||||
sessions.len(),
|
||||
1,
|
||||
"a late subscriber must see current state"
|
||||
);
|
||||
}
|
||||
other => panic!("expected Snapshot, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn next_event(ws: &mut WsClient) -> maestro_protocol::CatalogEvent {
|
||||
loop {
|
||||
match tokio::time::timeout(Duration::from_secs(5), ws.next())
|
||||
.await
|
||||
.expect("events ws timed out")
|
||||
{
|
||||
Some(Ok(WsMessage::Text(t))) => {
|
||||
return serde_json::from_str(&t).expect("decode catalog event")
|
||||
}
|
||||
Some(Ok(_)) => continue,
|
||||
other => panic!("unexpected events frame: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
//! The session manager's decisions, driven through [`FakePanes`].
|
||||
//!
|
||||
//! These are the branches that used to need a forked tmux server to reach:
|
||||
//! spawn rollback ordering, liveness diffing, and activity change-detection.
|
||||
//! Nothing here spawns a process, so they run everywhere and in milliseconds.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use maestro_daemon::panes::{Call, FakePanes, Op};
|
||||
use maestro_daemon::session::{SessionError, SessionManager};
|
||||
use maestro_daemon::sidecar::SidecarStore;
|
||||
use maestro_daemon::tmux::PaneInfo;
|
||||
use maestro_daemon::worktree::WorktreeManager;
|
||||
use maestro_protocol::{ActivityState, CatalogEvent, CreateSessionRequest, SessionStatus};
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::broadcast::error::TryRecvError;
|
||||
use uuid::Uuid;
|
||||
|
||||
struct Fx {
|
||||
manager: SessionManager,
|
||||
fake: Arc<FakePanes>,
|
||||
tmp: TempDir,
|
||||
}
|
||||
|
||||
impl Fx {
|
||||
fn new() -> Self {
|
||||
Self::with_sidecar_dir(|tmp| tmp.join("sidecars"))
|
||||
}
|
||||
|
||||
fn with_sidecar_dir(pick: impl Fn(&std::path::Path) -> PathBuf) -> Self {
|
||||
let tmp = TempDir::new().expect("tempdir");
|
||||
let fake = Arc::new(FakePanes::new());
|
||||
let fifo_dir = tmp.path().join("fifos");
|
||||
std::fs::create_dir_all(&fifo_dir).expect("fifo dir");
|
||||
let manager = SessionManager::new(
|
||||
fake.clone(),
|
||||
SidecarStore::new(pick(tmp.path())),
|
||||
WorktreeManager::new(Some(tmp.path().join("worktrees"))),
|
||||
fifo_dir,
|
||||
);
|
||||
Self { manager, fake, tmp }
|
||||
}
|
||||
|
||||
fn request(&self, command: &str) -> CreateSessionRequest {
|
||||
CreateSessionRequest {
|
||||
cwd: self.tmp.path().to_path_buf(),
|
||||
command: command.into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Poll until `id` reaches `want`.
|
||||
async fn wait_for_status(manager: &SessionManager, id: uuid::Uuid, want: SessionStatus) {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
|
||||
while tokio::time::Instant::now() < deadline {
|
||||
if manager.status(id).await == Some(want) {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("timed out waiting for {id} to become {want:?}");
|
||||
}
|
||||
|
||||
/// NAP-260 rollback, asserted as an *ordering* rather than an end state.
|
||||
///
|
||||
/// Replaces a test that forced the sidecar failure with `chmod 0o500` and then
|
||||
/// returned early when it detected root — so on CI it asserted nothing. Here
|
||||
/// the sidecar directory cannot be created because a regular file sits where
|
||||
/// its parent must be, which no uid can work around.
|
||||
#[tokio::test]
|
||||
async fn create_kills_the_tmux_session_when_the_sidecar_write_fails() {
|
||||
let fx = Fx::with_sidecar_dir(|tmp| {
|
||||
let blocker = tmp.join("blocker");
|
||||
std::fs::write(&blocker, b"not a directory").expect("blocker file");
|
||||
blocker.join("sidecars")
|
||||
});
|
||||
|
||||
let res = fx.manager.create(fx.request("sleep 30")).await;
|
||||
|
||||
assert!(
|
||||
matches!(res, Err(SessionError::Sidecar(_))),
|
||||
"expected the sidecar write to fail, got {res:?}"
|
||||
);
|
||||
|
||||
let calls = fx.fake.calls();
|
||||
assert_eq!(
|
||||
calls.len(),
|
||||
2,
|
||||
"expected spawn then rollback kill, got {calls:?}"
|
||||
);
|
||||
assert!(matches!(calls[0], Call::NewSessionPiped { .. }));
|
||||
let Call::NewSessionPiped { id, .. } = calls[0] else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(
|
||||
calls[1],
|
||||
Call::KillSession(id),
|
||||
"the rollback must kill the session it just spawned"
|
||||
);
|
||||
|
||||
assert!(!fx.fake.is_live(id), "create left a ghost tmux session");
|
||||
assert!(fx.manager.snapshot().await.is_empty());
|
||||
}
|
||||
|
||||
/// A failed spawn must not roll back anything, least of all kill a session id
|
||||
/// tmux never accepted.
|
||||
#[tokio::test]
|
||||
async fn create_does_not_roll_back_when_the_spawn_itself_fails() {
|
||||
let fx = Fx::new();
|
||||
fx.fake.fail(Op::NewSessionPiped, "no server running");
|
||||
|
||||
let res = fx.manager.create(fx.request("sleep 30")).await;
|
||||
assert!(res.is_err(), "expected the spawn to fail, got {res:?}");
|
||||
|
||||
assert_eq!(
|
||||
fx.fake.calls().len(),
|
||||
1,
|
||||
"only the failed spawn should have been attempted: {:?}",
|
||||
fx.fake.calls()
|
||||
);
|
||||
assert!(fx.manager.snapshot().await.is_empty());
|
||||
}
|
||||
|
||||
/// A restarted daemon adopts whatever tmux still holds, and must re-pipe each
|
||||
/// one — without that the adopted session produces no output.
|
||||
#[tokio::test]
|
||||
async fn recover_adopts_live_sessions_and_repipes_them() {
|
||||
let fx = Fx::new();
|
||||
let orphan = Uuid::new_v4();
|
||||
fx.fake.add_live(orphan);
|
||||
|
||||
let adopted = fx.manager.recover().await.expect("recover");
|
||||
assert_eq!(adopted, 1);
|
||||
|
||||
let snap = fx.manager.snapshot().await;
|
||||
assert_eq!(snap.len(), 1);
|
||||
assert_eq!(snap[0].id, orphan);
|
||||
|
||||
assert!(
|
||||
fx.fake.calls().contains(&Call::PipePane(orphan)),
|
||||
"adopted session was never re-piped: {:?}",
|
||||
fx.fake.calls()
|
||||
);
|
||||
}
|
||||
|
||||
/// A session tmux lost is marked `Dead` and kept, so the operator can still see
|
||||
/// it exited and read what it printed. It is not removed.
|
||||
#[tokio::test]
|
||||
async fn liveness_marks_the_lost_session_dead_and_keeps_it() {
|
||||
let fx = Fx::new();
|
||||
let keep = fx.manager.create(fx.request("keep")).await.expect("keep");
|
||||
let lose = fx.manager.create(fx.request("lose")).await.expect("lose");
|
||||
let mut events = fx.manager.events();
|
||||
|
||||
fx.fake.remove_live(lose.id);
|
||||
fx.manager.start_liveness_watcher(Duration::from_millis(25));
|
||||
wait_for_status(&fx.manager, lose.id, SessionStatus::Dead).await;
|
||||
|
||||
let all = fx.manager.snapshot().await;
|
||||
assert_eq!(all.len(), 2, "the dead session must stay in the catalog");
|
||||
let survivor = all.iter().find(|s| s.id == keep.id).expect("keep");
|
||||
assert_eq!(survivor.status, SessionStatus::Running);
|
||||
|
||||
let mut removed = Vec::new();
|
||||
while let Ok(ev) = events.try_recv() {
|
||||
if let CatalogEvent::SessionRemoved { id } = ev {
|
||||
removed.push(id);
|
||||
}
|
||||
}
|
||||
assert!(removed.is_empty(), "nothing should be removed: {removed:?}");
|
||||
}
|
||||
|
||||
/// The transition fires once. Without the Running filter the pass re-announces
|
||||
/// the same dead session on every tick, forever.
|
||||
#[tokio::test]
|
||||
async fn a_dead_session_is_announced_only_once() {
|
||||
let fx = Fx::new();
|
||||
let s = fx.manager.create(fx.request("bash")).await.expect("create");
|
||||
let mut events = fx.manager.events();
|
||||
|
||||
fx.fake.remove_live(s.id);
|
||||
fx.manager.start_liveness_watcher(Duration::from_millis(25));
|
||||
wait_for_status(&fx.manager, s.id, SessionStatus::Dead).await;
|
||||
|
||||
let mut dead_updates = 0;
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_millis(300);
|
||||
while tokio::time::Instant::now() < deadline {
|
||||
if let Ok(CatalogEvent::SessionUpdated { session }) = events.try_recv() {
|
||||
if session.status == SessionStatus::Dead {
|
||||
dead_updates += 1;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(dead_updates, 1, "expected exactly one Dead announcement");
|
||||
}
|
||||
|
||||
/// Dismissing a dead session releases it — without asking tmux to kill
|
||||
/// something tmux already lost.
|
||||
#[tokio::test]
|
||||
async fn killing_a_dead_session_dismisses_it_without_touching_tmux() {
|
||||
let fx = Fx::new();
|
||||
let s = fx.manager.create(fx.request("bash")).await.expect("create");
|
||||
fx.fake.remove_live(s.id);
|
||||
fx.manager.start_liveness_watcher(Duration::from_millis(25));
|
||||
wait_for_status(&fx.manager, s.id, SessionStatus::Dead).await;
|
||||
|
||||
fx.manager.kill(s.id).await.expect("dismiss");
|
||||
|
||||
assert!(fx.manager.snapshot().await.is_empty());
|
||||
assert!(
|
||||
!fx.fake
|
||||
.calls()
|
||||
.iter()
|
||||
.any(|c| matches!(c, Call::KillSession(k) if *k == s.id)),
|
||||
"kill-session was called on a session tmux had already lost: {:?}",
|
||||
fx.fake.calls()
|
||||
);
|
||||
}
|
||||
|
||||
/// A dead session has no pane, so input is dropped rather than surfacing as a
|
||||
/// tmux failure the client would have to interpret.
|
||||
#[tokio::test]
|
||||
async fn a_dead_session_is_read_only() {
|
||||
let fx = Fx::new();
|
||||
let s = fx.manager.create(fx.request("bash")).await.expect("create");
|
||||
fx.fake.remove_live(s.id);
|
||||
fx.manager.start_liveness_watcher(Duration::from_millis(25));
|
||||
wait_for_status(&fx.manager, s.id, SessionStatus::Dead).await;
|
||||
|
||||
fx.manager
|
||||
.send_keys(s.id, b"ls\n")
|
||||
.await
|
||||
.expect("send_keys");
|
||||
fx.manager.resize(s.id, 80, 24).await.expect("resize");
|
||||
|
||||
assert!(
|
||||
!fx.fake
|
||||
.calls()
|
||||
.iter()
|
||||
.any(|c| matches!(c, Call::SendKeys { .. } | Call::ResizeWindow { .. })),
|
||||
"input reached tmux for a dead session: {:?}",
|
||||
fx.fake.calls()
|
||||
);
|
||||
}
|
||||
|
||||
/// `CreateSessionRequest.env` was accepted, stored, echoed back to clients, and
|
||||
/// then dropped: `new_session_piped` had no env parameter at all.
|
||||
#[tokio::test]
|
||||
async fn requested_env_reaches_tmux() {
|
||||
let fx = Fx::new();
|
||||
let mut req = fx.request("bash");
|
||||
req.env.insert("FOO".into(), "bar".into());
|
||||
req.env.insert("EMPTY".into(), String::new());
|
||||
|
||||
fx.manager.create(req).await.expect("create");
|
||||
|
||||
let want: BTreeMap<String, String> = [
|
||||
("EMPTY".to_string(), String::new()),
|
||||
("FOO".to_string(), "bar".to_string()),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
match fx.fake.calls().first() {
|
||||
Some(Call::NewSessionPiped { env, .. }) => assert_eq!(env, &want),
|
||||
other => panic!("expected a spawn call, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_env_key_tmux_would_misparse_is_rejected() {
|
||||
let fx = Fx::new();
|
||||
let mut req = fx.request("bash");
|
||||
req.env.insert("A=B".into(), "x".into());
|
||||
|
||||
let err = fx.manager.create(req).await.expect_err("should reject");
|
||||
assert_eq!(err.to_error_info().code, "invalid_env");
|
||||
assert!(
|
||||
fx.fake.calls().is_empty(),
|
||||
"nothing should have been spawned: {:?}",
|
||||
fx.fake.calls()
|
||||
);
|
||||
}
|
||||
|
||||
/// If `list_sessions` fails the pass has no idea what is alive. Reaping on that
|
||||
/// basis would kill the whole catalog.
|
||||
#[tokio::test]
|
||||
async fn liveness_reaps_nothing_when_tmux_cannot_be_listed() {
|
||||
let fx = Fx::new();
|
||||
let alive = fx.manager.create(fx.request("bash")).await.expect("create");
|
||||
|
||||
fx.fake.fail(Op::ListSessions, "connection refused");
|
||||
fx.manager.start_liveness_watcher(Duration::from_millis(25));
|
||||
|
||||
// Give the watcher several passes to do the wrong thing.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
|
||||
let snap = fx.manager.snapshot().await;
|
||||
assert_eq!(
|
||||
snap.len(),
|
||||
1,
|
||||
"a failed list must not be read as 'everything died'"
|
||||
);
|
||||
assert_eq!(snap[0].id, alive.id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn activity_pass_emits_updated_only_when_something_changed() {
|
||||
let fx = Fx::new();
|
||||
let session = fx.manager.create(fx.request("zsh")).await.expect("create");
|
||||
let mut events = fx.manager.events();
|
||||
|
||||
fx.fake.set_pane_info(
|
||||
session.id,
|
||||
PaneInfo {
|
||||
// A pid nothing can be reading from, so `awaiting_input` is a
|
||||
// deterministic false rather than a probe of this machine.
|
||||
pane_pid: i32::MAX,
|
||||
command: "claude".into(),
|
||||
tty: "/dev/null".into(),
|
||||
current_path: "/srv/work".into(),
|
||||
},
|
||||
);
|
||||
fx.manager.start_liveness_watcher(Duration::from_millis(25));
|
||||
|
||||
let updated = wait_for_updated(&mut events).await;
|
||||
assert_eq!(updated.foreground.as_deref(), Some("claude"));
|
||||
assert_eq!(
|
||||
updated.current_cwd.as_deref(),
|
||||
Some(std::path::Path::new("/srv/work"))
|
||||
);
|
||||
// Still inside `activity::ACTIVE_WINDOW` (3s) since the spawn, so the
|
||||
// change here is `foreground`, not the activity state.
|
||||
assert_eq!(updated.activity, ActivityState::Active);
|
||||
|
||||
// Drain anything already queued, then confirm a steady pane stays quiet.
|
||||
// Stays well inside the 3s window, so no Active -> Idle transition either.
|
||||
while events.try_recv().is_ok() {}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert!(
|
||||
matches!(events.try_recv(), Err(TryRecvError::Empty)),
|
||||
"an unchanged pane must not re-emit SessionUpdated every tick"
|
||||
);
|
||||
}
|
||||
|
||||
async fn wait_for_updated(
|
||||
events: &mut tokio::sync::broadcast::Receiver<CatalogEvent>,
|
||||
) -> maestro_protocol::Session {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
|
||||
while tokio::time::Instant::now() < deadline {
|
||||
match events.try_recv() {
|
||||
Ok(CatalogEvent::SessionUpdated { session }) => return session,
|
||||
Ok(_) => continue,
|
||||
Err(_) => tokio::time::sleep(Duration::from_millis(10)).await,
|
||||
}
|
||||
}
|
||||
panic!("timed out waiting for SessionUpdated");
|
||||
}
|
||||
|
||||
/// The kill handler used to check `has()` first, which opened a window for the
|
||||
/// liveness watcher to reap the session in between — turning a 404 into a 502.
|
||||
/// `kill` reports the miss itself now.
|
||||
#[tokio::test]
|
||||
async fn killing_an_unknown_session_is_reported_as_not_found() {
|
||||
let fx = Fx::new();
|
||||
let err = fx
|
||||
.manager
|
||||
.kill(uuid::Uuid::new_v4())
|
||||
.await
|
||||
.expect_err("should fail");
|
||||
assert_eq!(err.to_error_info().code, "not_found");
|
||||
}
|
||||
|
||||
/// A construction-order mistake must be loud: a silently-ignored history leaves
|
||||
/// the recent-dirs picker permanently empty.
|
||||
#[test]
|
||||
#[should_panic(expected = "before the SessionManager is cloned")]
|
||||
fn attaching_spawn_history_after_cloning_panics() {
|
||||
let tmp = TempDir::new().expect("tempdir");
|
||||
let fake = Arc::new(FakePanes::new());
|
||||
let manager = SessionManager::new(
|
||||
fake,
|
||||
SidecarStore::new(tmp.path().join("sidecars")),
|
||||
WorktreeManager::new(Some(tmp.path().join("worktrees"))),
|
||||
tmp.path().join("fifos"),
|
||||
);
|
||||
let _clone = manager.clone();
|
||||
let _ = manager.with_spawn_history(maestro_daemon::spawn_history::SpawnHistory::new(
|
||||
tmp.path().join("history.jsonl"),
|
||||
7,
|
||||
));
|
||||
}
|
||||
@@ -4,11 +4,12 @@ mod common;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use common::{wait_for_async, DaemonFixture};
|
||||
use maestro_daemon::SessionEvent;
|
||||
use common::{init_repo, wait_for_async, DaemonFixture};
|
||||
use maestro_protocol::CreateSessionRequest;
|
||||
use maestro_protocol::{CatalogEvent, SessionStatus, WorktreeSpec};
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -101,63 +102,6 @@ async fn create_without_history_logs_nothing() {
|
||||
assert!(!fx.spawn_history_path().exists());
|
||||
}
|
||||
|
||||
/// NAP-260: when the sidecar write fails *after* tmux has spawned the session,
|
||||
/// `create` must roll back — no ghost tmux session, no in-memory record left
|
||||
/// behind. We force the failure by making the sidecar directory read-only (the
|
||||
/// FIFO + tmux steps use other dirs and still succeed).
|
||||
#[tokio::test]
|
||||
async fn create_rolls_back_tmux_session_when_sidecar_write_fails() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let fx = DaemonFixture::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
|
||||
let sidecar_dir = fx.sidecar_dir();
|
||||
std::fs::create_dir_all(&sidecar_dir).unwrap();
|
||||
std::fs::set_permissions(&sidecar_dir, std::fs::Permissions::from_mode(0o500)).unwrap();
|
||||
|
||||
// The failure is injected by making the sidecar dir read-only — but root
|
||||
// bypasses directory permission bits, so the write would succeed and the
|
||||
// rollback path never trigger. CI runs as root; detect that with a write
|
||||
// probe and skip rather than report a spurious failure (the rollback is
|
||||
// still covered in any non-root environment).
|
||||
let probe = sidecar_dir.join(".perm_probe");
|
||||
if std::fs::write(&probe, b"x").is_ok() {
|
||||
let _ = std::fs::remove_file(&probe);
|
||||
std::fs::set_permissions(&sidecar_dir, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
eprintln!("skipping: sidecar dir writable despite 0o500 (running as root?)");
|
||||
return;
|
||||
}
|
||||
|
||||
let res = fx
|
||||
.manager
|
||||
.create(CreateSessionRequest {
|
||||
cwd: cwd.path().to_path_buf(),
|
||||
command: "sleep 30".into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
// Restore perms so the TempDir can be cleaned up regardless of assertions.
|
||||
std::fs::set_permissions(&sidecar_dir, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
|
||||
assert!(
|
||||
matches!(res, Err(maestro_daemon::SessionError::Sidecar(_))),
|
||||
"expected the sidecar write to fail, got {res:?}"
|
||||
);
|
||||
|
||||
// The session tmux spawned must have been killed — no ghost left running.
|
||||
let live = fx.tmux.tmux.list_sessions().expect("list tmux sessions");
|
||||
assert!(
|
||||
live.is_empty(),
|
||||
"create left a ghost tmux session behind: {live:?}"
|
||||
);
|
||||
// And nothing in the in-memory catalog.
|
||||
assert!(fx.manager.snapshot().await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recover_adopts_existing_tmux_sessions() {
|
||||
let fx = DaemonFixture::new();
|
||||
@@ -179,10 +123,9 @@ async fn recover_adopts_existing_tmux_sessions() {
|
||||
|
||||
// build a parallel manager pointing at the same dirs + same tmux server
|
||||
let sidecar = maestro_daemon::sidecar::SidecarStore::new(fx.sidecar_dir());
|
||||
let worktree_mgr =
|
||||
maestro_daemon::worktree::WorktreeManager::new(fx.worktree_root.path().to_path_buf());
|
||||
let worktree_mgr = maestro_daemon::worktree::WorktreeManager::new(None);
|
||||
let revived = maestro_daemon::SessionManager::new(
|
||||
fx.tmux.tmux.clone(),
|
||||
Arc::new(fx.tmux.tmux.clone()),
|
||||
sidecar,
|
||||
worktree_mgr,
|
||||
fx.fifo_dir(),
|
||||
@@ -270,7 +213,6 @@ async fn recover_re_pipes_pane_so_output_reaches_subscribers() {
|
||||
let sidecar_dir = fx.sidecar_dir();
|
||||
let fifo_dir = fx.fifo_dir();
|
||||
let tmux = fx.tmux.tmux.clone();
|
||||
let worktree_root = fx.worktree_root.path().to_path_buf();
|
||||
|
||||
// Drop the original manager. Its PtyBridge closes the FIFO's only
|
||||
// reader, so tmux's `cat >> fifo` writer hits SIGPIPE and exits — but
|
||||
@@ -279,8 +221,9 @@ async fn recover_re_pipes_pane_so_output_reaches_subscribers() {
|
||||
drop(fx.manager);
|
||||
|
||||
let sidecar = maestro_daemon::sidecar::SidecarStore::new(sidecar_dir);
|
||||
let worktree_mgr = maestro_daemon::worktree::WorktreeManager::new(worktree_root);
|
||||
let revived = maestro_daemon::SessionManager::new(tmux, sidecar, worktree_mgr, fifo_dir);
|
||||
let worktree_mgr = maestro_daemon::worktree::WorktreeManager::new(None);
|
||||
let revived =
|
||||
maestro_daemon::SessionManager::new(Arc::new(tmux), sidecar, worktree_mgr, fifo_dir);
|
||||
assert_eq!(revived.recover().await.expect("recover"), 1);
|
||||
|
||||
let mut rx = revived.subscribe_pty(s.id).await.expect("subscribe");
|
||||
@@ -360,7 +303,7 @@ async fn pty_broadcast_delivers_bytes_to_subscribers() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn liveness_watcher_reaps_dead_sessions_and_emits_removed() {
|
||||
async fn liveness_watcher_marks_dead_sessions_and_keeps_them_until_dismissed() {
|
||||
let fx = DaemonFixture::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
|
||||
@@ -385,30 +328,105 @@ async fn liveness_watcher_reaps_dead_sessions_and_emits_removed() {
|
||||
// daemon never finds out through its normal channels.
|
||||
fx.tmux.tmux.kill_session(s.id).expect("kill tmux directly");
|
||||
|
||||
// Within a few watcher ticks the daemon should drop the session.
|
||||
wait_for_async(Duration::from_secs(3), || async {
|
||||
!fx.manager.has(s.id).await
|
||||
fx.manager.status(s.id).await == Some(SessionStatus::Dead)
|
||||
})
|
||||
.await;
|
||||
|
||||
// Sidecar + FIFO should be cleaned up too.
|
||||
assert!(!fx.sidecar_dir().join(format!("{}.json", s.id)).exists());
|
||||
assert!(!fx.fifo_dir().join(format!("{}.fifo", s.id)).exists());
|
||||
// Marked, not removed — the operator still sees it exited, and its
|
||||
// artifacts stay so the output can be replayed.
|
||||
assert!(fx.manager.has(s.id).await);
|
||||
assert!(fx.sidecar_dir().join(format!("{}.json", s.id)).exists());
|
||||
|
||||
// And we should have seen a Removed event for this id.
|
||||
let mut saw_removed = false;
|
||||
let mut saw_dead = false;
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(1);
|
||||
while std::time::Instant::now() < deadline && !saw_removed {
|
||||
while std::time::Instant::now() < deadline && !saw_dead {
|
||||
match tokio::time::timeout(Duration::from_millis(50), events.recv()).await {
|
||||
Ok(Ok(SessionEvent::Removed(id))) if id == s.id => saw_removed = true,
|
||||
Ok(Ok(CatalogEvent::SessionUpdated { session }))
|
||||
if session.id == s.id && session.status == SessionStatus::Dead =>
|
||||
{
|
||||
saw_dead = true
|
||||
}
|
||||
Ok(Ok(_)) => continue,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
saw_removed,
|
||||
"expected SessionEvent::Removed for dead session"
|
||||
saw_dead,
|
||||
"expected a SessionUpdated marking the session dead"
|
||||
);
|
||||
|
||||
// Dismissing it is what finally releases the artifacts.
|
||||
fx.manager.kill(s.id).await.expect("dismiss");
|
||||
assert!(!fx.manager.has(s.id).await);
|
||||
assert!(!fx.sidecar_dir().join(format!("{}.json", s.id)).exists());
|
||||
assert!(!fx.fifo_dir().join(format!("{}.fifo", s.id)).exists());
|
||||
}
|
||||
|
||||
/// Cleanup is unconditional (#56): even a spec that says "don't clean up"
|
||||
/// loses its worktree on kill — the guard, not the flag, protects work.
|
||||
#[tokio::test]
|
||||
async fn kill_removes_worktree_even_when_spec_says_keep() {
|
||||
let fx = DaemonFixture::new();
|
||||
let repo = TempDir::new().unwrap();
|
||||
init_repo(repo.path());
|
||||
let wt_path = repo.path().join("worktrees").join("feat-keep");
|
||||
|
||||
let s = fx
|
||||
.manager
|
||||
.create(CreateSessionRequest {
|
||||
cwd: repo.path().to_path_buf(),
|
||||
command: "sleep 30".into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: Some(WorktreeSpec {
|
||||
base_repo: repo.path().to_path_buf(),
|
||||
branch: "feat/keep".into(),
|
||||
cleanup_on_kill: false,
|
||||
create_branch: true,
|
||||
}),
|
||||
})
|
||||
.await
|
||||
.expect("create");
|
||||
assert!(wt_path.exists());
|
||||
|
||||
fx.manager.kill(s.id).await.expect("kill");
|
||||
assert!(!wt_path.exists(), "worktree must be removed on kill");
|
||||
}
|
||||
|
||||
/// The guard (#56): a worktree holding uncommitted changes survives the kill,
|
||||
/// left on disk where the operator can find it.
|
||||
#[tokio::test]
|
||||
async fn kill_leaves_worktree_with_unsaved_work_on_disk() {
|
||||
let fx = DaemonFixture::new();
|
||||
let repo = TempDir::new().unwrap();
|
||||
init_repo(repo.path());
|
||||
let wt_path = repo.path().join("worktrees").join("feat-guarded");
|
||||
|
||||
let s = fx
|
||||
.manager
|
||||
.create(CreateSessionRequest {
|
||||
cwd: repo.path().to_path_buf(),
|
||||
command: "sleep 30".into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: Some(WorktreeSpec {
|
||||
base_repo: repo.path().to_path_buf(),
|
||||
branch: "feat/guarded".into(),
|
||||
cleanup_on_kill: true,
|
||||
create_branch: true,
|
||||
}),
|
||||
})
|
||||
.await
|
||||
.expect("create");
|
||||
std::fs::write(wt_path.join("README"), b"unsaved edits\n").unwrap();
|
||||
|
||||
fx.manager.kill(s.id).await.expect("kill");
|
||||
assert!(
|
||||
wt_path.exists(),
|
||||
"dirty worktree must be left on disk, not destroyed"
|
||||
);
|
||||
assert!(fx.manager.snapshot().await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -31,9 +31,9 @@ fn add_creates_worktree_on_new_branch() {
|
||||
init_repo(&repo);
|
||||
|
||||
let wt_root = TempDir::new().unwrap();
|
||||
let mgr = WorktreeManager::new(wt_root.path());
|
||||
let mgr = WorktreeManager::new(Some(wt_root.path().to_path_buf()));
|
||||
|
||||
let path = mgr.add(&repo, "feat/example").expect("add worktree");
|
||||
let path = mgr.add_new(&repo, "feat/example").expect("add worktree");
|
||||
assert!(path.exists());
|
||||
assert!(path.join("README").exists());
|
||||
assert!(path.starts_with(wt_root.path()));
|
||||
@@ -42,6 +42,63 @@ fn add_creates_worktree_on_new_branch() {
|
||||
assert!(branches.iter().any(|b| b == "feat/example"), "{branches:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_places_worktree_inside_the_base_repo_by_default() {
|
||||
let repo_dir = TempDir::new().unwrap();
|
||||
let repo = repo_dir.path().to_path_buf();
|
||||
init_repo(&repo);
|
||||
|
||||
// No override: the worktree must land where the repository keeps its
|
||||
// own worktrees (#56), not under some daemon state dir.
|
||||
let mgr = WorktreeManager::new(None);
|
||||
|
||||
let path = mgr.add_new(&repo, "feat/example").expect("add worktree");
|
||||
assert_eq!(path, repo.join("worktrees").join("feat-example"));
|
||||
assert!(path.exists());
|
||||
assert!(path.join("README").exists());
|
||||
|
||||
let branches = worktree_branches(&repo);
|
||||
assert!(branches.iter().any(|b| b == "feat/example"), "{branches:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_root_override_redirects_placement() {
|
||||
let repo_dir = TempDir::new().unwrap();
|
||||
let repo = repo_dir.path().to_path_buf();
|
||||
init_repo(&repo);
|
||||
|
||||
let wt_root = TempDir::new().unwrap();
|
||||
let mgr = WorktreeManager::new(Some(wt_root.path().to_path_buf()));
|
||||
|
||||
let path = mgr.add_new(&repo, "feat/example").expect("add worktree");
|
||||
assert_eq!(path, wt_root.path().join("feat-example"));
|
||||
assert!(path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_directory_at_target_path_is_an_error_carrying_the_path() {
|
||||
let repo_dir = TempDir::new().unwrap();
|
||||
let repo = repo_dir.path().to_path_buf();
|
||||
init_repo(&repo);
|
||||
|
||||
// A predictable path means collisions are possible; they must be
|
||||
// reported, never silently relocated.
|
||||
std::fs::create_dir_all(repo.join("worktrees").join("feat-collide")).unwrap();
|
||||
|
||||
let mgr = WorktreeManager::new(None);
|
||||
let err = mgr.add_new(&repo, "feat/collide").unwrap_err();
|
||||
let msg = format!("{err}");
|
||||
assert!(
|
||||
msg.contains(
|
||||
repo.join("worktrees")
|
||||
.join("feat-collide")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
),
|
||||
"{msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_twice_generates_distinct_paths() {
|
||||
let repo_dir = TempDir::new().unwrap();
|
||||
@@ -49,10 +106,10 @@ fn add_twice_generates_distinct_paths() {
|
||||
init_repo(&repo);
|
||||
|
||||
let wt_root = TempDir::new().unwrap();
|
||||
let mgr = WorktreeManager::new(wt_root.path());
|
||||
let mgr = WorktreeManager::new(Some(wt_root.path().to_path_buf()));
|
||||
|
||||
let p1 = mgr.add(&repo, "feat/a").expect("add a");
|
||||
let p2 = mgr.add(&repo, "feat/b").expect("add b");
|
||||
let p1 = mgr.add_new(&repo, "feat/a").expect("add a");
|
||||
let p2 = mgr.add_new(&repo, "feat/b").expect("add b");
|
||||
assert_ne!(p1, p2);
|
||||
assert!(p1.exists());
|
||||
assert!(p2.exists());
|
||||
@@ -65,9 +122,9 @@ fn remove_prunes_worktree() {
|
||||
init_repo(&repo);
|
||||
|
||||
let wt_root = TempDir::new().unwrap();
|
||||
let mgr = WorktreeManager::new(wt_root.path());
|
||||
let mgr = WorktreeManager::new(Some(wt_root.path().to_path_buf()));
|
||||
|
||||
let path = mgr.add(&repo, "feat/gone").expect("add");
|
||||
let path = mgr.add_new(&repo, "feat/gone").expect("add");
|
||||
assert!(path.exists());
|
||||
|
||||
mgr.remove(&repo, &path).expect("remove");
|
||||
@@ -79,6 +136,136 @@ fn remove_prunes_worktree() {
|
||||
assert_eq!(branches, vec!["main".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_existing_checks_out_branch_without_creating_it() {
|
||||
let repo_dir = TempDir::new().unwrap();
|
||||
let repo = repo_dir.path().to_path_buf();
|
||||
init_repo(&repo);
|
||||
|
||||
// Pre-create the branch with its own commit so we can tell a checkout
|
||||
// from an accidental `-b`.
|
||||
let created = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(&repo)
|
||||
.args(["checkout", "-q", "-b", "feat/dup"])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(created.success());
|
||||
std::fs::write(repo.join("FEATURE"), b"dup\n").unwrap();
|
||||
let staged = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(&repo)
|
||||
.args(["add", "."])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(staged.success());
|
||||
let committed = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(&repo)
|
||||
.args(["commit", "-q", "-am", "wip"])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(committed.success());
|
||||
let back = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(&repo)
|
||||
.args(["checkout", "-q", "main"])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(back.success());
|
||||
|
||||
let wt_root = TempDir::new().unwrap();
|
||||
let mgr = WorktreeManager::new(Some(wt_root.path().to_path_buf()));
|
||||
|
||||
let path = mgr.add_existing(&repo, "feat/dup").expect("add existing");
|
||||
assert!(path.exists());
|
||||
assert!(path.join("README").exists());
|
||||
|
||||
// The branch set is unchanged: `feat/dup` was checked out, not recreated.
|
||||
let branches = worktree_branches(&repo);
|
||||
let mut sorted = branches.clone();
|
||||
sorted.sort();
|
||||
assert_eq!(
|
||||
sorted,
|
||||
vec!["feat/dup".to_string(), "main".to_string()],
|
||||
"{branches:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_refuses_worktree_with_uncommitted_changes() {
|
||||
let repo_dir = TempDir::new().unwrap();
|
||||
let repo = repo_dir.path().to_path_buf();
|
||||
init_repo(&repo);
|
||||
|
||||
let mgr = WorktreeManager::new(None);
|
||||
let path = mgr.add_new(&repo, "feat/dirty").expect("add");
|
||||
std::fs::write(path.join("README"), b"unsaved edits\n").unwrap();
|
||||
|
||||
mgr.remove(&repo, &path)
|
||||
.expect_err("dirty worktree must be refused");
|
||||
assert!(path.exists(), "guarded worktree must stay on disk");
|
||||
|
||||
// Committing it makes removal safe: `worktree remove` keeps
|
||||
// `refs/heads/feat/dirty`, so the work is still reachable. Refusing here
|
||||
// instead would make every unpushed branch a one-shot, since the path is
|
||||
// deterministic and the leftover tree blocks the next spawn (#56 review).
|
||||
run_git(&path, &["add", "."]);
|
||||
run_git(&path, &["commit", "-q", "-m", "saved"]);
|
||||
|
||||
mgr.remove(&repo, &path).expect("committed work can go");
|
||||
assert!(!path.exists());
|
||||
assert!(
|
||||
worktree_branches(&repo).contains(&"main".to_string()),
|
||||
"the branch survives removal"
|
||||
);
|
||||
let branches = String::from_utf8(
|
||||
Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(&repo)
|
||||
.args(["for-each-ref", "--format=%(refname:short)", "refs/heads"])
|
||||
.output()
|
||||
.unwrap()
|
||||
.stdout,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(branches.contains("feat/dirty"), "{branches}");
|
||||
}
|
||||
|
||||
/// A worktree whose directory vanished must be pruned, not misread as holding
|
||||
/// unsaved work — otherwise the registration is stranded and, because paths
|
||||
/// are deterministic, that branch can never be spawned again (#56 review).
|
||||
#[test]
|
||||
fn remove_prunes_a_worktree_whose_directory_vanished() {
|
||||
let repo_dir = TempDir::new().unwrap();
|
||||
let repo = repo_dir.path().to_path_buf();
|
||||
init_repo(&repo);
|
||||
|
||||
let mgr = WorktreeManager::new(None);
|
||||
let path = mgr.add_new(&repo, "feat/gone").expect("add");
|
||||
std::fs::remove_dir_all(&path).unwrap();
|
||||
|
||||
mgr.remove(&repo, &path)
|
||||
.expect("a vanished worktree prunes");
|
||||
// The registration is gone too, so the same branch can be spawned again.
|
||||
mgr.add_existing(&repo, "feat/gone")
|
||||
.expect("branch is spawnable again");
|
||||
}
|
||||
|
||||
fn run_git(dir: &std::path::Path, args: &[&str]) {
|
||||
let out = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(dir)
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("git spawn");
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?} failed: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_fails_when_branch_already_exists() {
|
||||
let repo_dir = TempDir::new().unwrap();
|
||||
@@ -95,9 +282,9 @@ fn add_fails_when_branch_already_exists() {
|
||||
assert!(status.success());
|
||||
|
||||
let wt_root = TempDir::new().unwrap();
|
||||
let mgr = WorktreeManager::new(wt_root.path());
|
||||
let mgr = WorktreeManager::new(Some(wt_root.path().to_path_buf()));
|
||||
|
||||
let err = mgr.add(&repo, "feat/dup").unwrap_err();
|
||||
let err = mgr.add_new(&repo, "feat/dup").unwrap_err();
|
||||
let msg = format!("{err}");
|
||||
assert!(msg.contains("git exited"), "{msg}");
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ path = "src/lib.rs"
|
||||
[dependencies]
|
||||
chrono.workspace = true
|
||||
futures-util.workspace = true
|
||||
maestro-protocol.workspace = true
|
||||
reqwest.workspace = true
|
||||
maestro-protocol = { workspace = true, features = ["client"] }
|
||||
maestro-testing.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
//! Thin HTTP+WS client used by tests to drive a daemon's `/api/*` surface.
|
||||
//! Thin test harness over [`maestro_protocol::DaemonClient`].
|
||||
//!
|
||||
//! HTTP calls delegate to the shared client so the harness exercises the same
|
||||
//! request building, timeouts and error decoding the CLI and TUI use. Only the
|
||||
//! WebSocket helpers are test-specific: they hand back a raw stream, or a
|
||||
//! handle that accumulates events in the background.
|
||||
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
@@ -6,8 +11,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use maestro_protocol::{CatalogEvent, CreateSessionRequest, Session};
|
||||
use reqwest::Client as HttpClient;
|
||||
use maestro_protocol::{CatalogEvent, CreateSessionRequest, DaemonClient, Session};
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::Message as WsMessage;
|
||||
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
|
||||
@@ -16,73 +20,46 @@ use uuid::Uuid;
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[allow(clippy::result_large_err)]
|
||||
pub enum ClientError {
|
||||
#[error("http: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error(transparent)]
|
||||
Api(#[from] maestro_protocol::ClientError),
|
||||
#[error("ws: {0}")]
|
||||
Ws(#[from] tokio_tungstenite::tungstenite::Error),
|
||||
#[error("json: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("unexpected status {status}: {body}")]
|
||||
Status { status: u16, body: String },
|
||||
}
|
||||
|
||||
/// HTTP client plus a few WS-aware helpers, bound to one daemon.
|
||||
/// Daemon client plus a few WS-aware helpers, bound to one daemon.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TestClient {
|
||||
http_base: String,
|
||||
ws_base: String,
|
||||
http: HttpClient,
|
||||
daemon: DaemonClient,
|
||||
}
|
||||
|
||||
/// Per-request budget. Well below the client default: a hung daemon should fail
|
||||
/// the test, not stall the suite for 30s.
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
impl TestClient {
|
||||
pub fn new(http_base: &str, ws_base: &str) -> Self {
|
||||
let http = HttpClient::builder()
|
||||
.timeout(Duration::from_secs(5))
|
||||
.build()
|
||||
.expect("reqwest client");
|
||||
pub fn new(http_base: &str) -> Self {
|
||||
Self {
|
||||
http_base: http_base.trim_end_matches('/').to_string(),
|
||||
ws_base: ws_base.trim_end_matches('/').to_string(),
|
||||
http,
|
||||
daemon: DaemonClient::with_timeouts(http_base, TEST_TIMEOUT, TEST_TIMEOUT),
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared client underneath, for calls this harness doesn't wrap.
|
||||
pub fn daemon(&self) -> &DaemonClient {
|
||||
&self.daemon
|
||||
}
|
||||
|
||||
pub async fn list_sessions(&self) -> Result<Vec<Session>, ClientError> {
|
||||
let r = self
|
||||
.http
|
||||
.get(format!("{}/api/sessions", self.http_base))
|
||||
.send()
|
||||
.await?;
|
||||
check_ok(&r)?;
|
||||
Ok(r.json().await?)
|
||||
Ok(self.daemon.list_sessions().await?)
|
||||
}
|
||||
|
||||
pub async fn spawn_session(&self, req: &CreateSessionRequest) -> Result<Session, ClientError> {
|
||||
let r = self
|
||||
.http
|
||||
.post(format!("{}/api/sessions", self.http_base))
|
||||
.json(req)
|
||||
.send()
|
||||
.await?;
|
||||
let status = r.status();
|
||||
if !status.is_success() {
|
||||
let body = r.text().await.unwrap_or_default();
|
||||
return Err(ClientError::Status {
|
||||
status: status.as_u16(),
|
||||
body,
|
||||
});
|
||||
}
|
||||
Ok(r.json().await?)
|
||||
Ok(self.daemon.create_session(req).await?)
|
||||
}
|
||||
|
||||
pub async fn kill_session(&self, id: Uuid) -> Result<(), ClientError> {
|
||||
let r = self
|
||||
.http
|
||||
.delete(format!("{}/api/sessions/{id}", self.http_base))
|
||||
.send()
|
||||
.await?;
|
||||
check_ok(&r)?;
|
||||
Ok(())
|
||||
Ok(self.daemon.kill_session(id).await?)
|
||||
}
|
||||
|
||||
/// Connect to the daemon's per-session WS and return the stream. The
|
||||
@@ -91,8 +68,7 @@ impl TestClient {
|
||||
&self,
|
||||
id: Uuid,
|
||||
) -> Result<WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>, ClientError> {
|
||||
let url = format!("{}/api/attach/{id}", self.ws_base);
|
||||
let request = url.into_client_request()?;
|
||||
let request = self.daemon.attach_url(id)?.into_client_request()?;
|
||||
let (ws, _resp) = connect_async(request).await?;
|
||||
Ok(ws)
|
||||
}
|
||||
@@ -100,7 +76,7 @@ impl TestClient {
|
||||
/// Subscribe to the daemon's `/api/events` WS. Returns a handle whose
|
||||
/// background task pushes parsed events into a shared vector.
|
||||
pub async fn subscribe_events(&self) -> EventStream {
|
||||
let url = format!("{}/api/events", self.ws_base);
|
||||
let url = self.daemon.events_url().expect("events url");
|
||||
let request = url.into_client_request().expect("ws req");
|
||||
let (ws, _resp) = connect_async(request).await.expect("events ws");
|
||||
|
||||
@@ -125,17 +101,6 @@ impl TestClient {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_ok(r: &reqwest::Response) -> Result<(), ClientError> {
|
||||
let status = r.status();
|
||||
if !status.is_success() {
|
||||
return Err(ClientError::Status {
|
||||
status: status.as_u16(),
|
||||
body: format!("HTTP {status}"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle to a background task draining the events WS into a vector.
|
||||
#[derive(Debug)]
|
||||
pub struct EventStream {
|
||||
|
||||
@@ -50,9 +50,11 @@ impl Daemon {
|
||||
format!("http://{}", self.bind_addr)
|
||||
}
|
||||
|
||||
/// WS base URL of this daemon's API.
|
||||
pub fn ws_base(&self) -> String {
|
||||
format!("ws://{}", self.bind_addr)
|
||||
/// Shared client bound to this daemon, with the harness's tighter budget.
|
||||
pub fn client(&self) -> maestro_protocol::DaemonClient {
|
||||
crate::client::TestClient::new(&self.http_base())
|
||||
.daemon()
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Stop the underlying process, but keep its state dirs around so we can
|
||||
|
||||
+101
-38
@@ -21,7 +21,7 @@ use tokio_tungstenite::tungstenite::Message as WsMessage;
|
||||
|
||||
async fn bring_up() -> (Daemon, TestClient) {
|
||||
let daemon = Daemon::spawn().await;
|
||||
let client = TestClient::new(&daemon.http_base(), &daemon.ws_base());
|
||||
let client = TestClient::new(&daemon.http_base());
|
||||
(daemon, client)
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ async fn multi_attach_sees_same_output() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cleanup_on_kill_removes_worktree() {
|
||||
async fn kill_removes_clean_worktree() {
|
||||
let (_daemon, client) = bring_up().await;
|
||||
|
||||
let base = TempDir::new().unwrap();
|
||||
@@ -129,18 +129,19 @@ async fn cleanup_on_kill_removes_worktree() {
|
||||
base_repo: base.path().to_path_buf(),
|
||||
branch: "feature/e2e".into(),
|
||||
cleanup_on_kill: true,
|
||||
create_branch: true,
|
||||
}),
|
||||
};
|
||||
|
||||
let s = client.spawn_session(&req).await.expect("spawn worktree");
|
||||
// The daemon's WorktreeManager puts new worktrees under
|
||||
// `<state_dir>/worktrees/<branch>`. We can't peek the daemon's state dir
|
||||
// directly from here, but we can verify by asking git: a worktree must
|
||||
// exist that lives outside the original repo.
|
||||
// Worktrees live inside the base repo at `<repo>/worktrees/<branch>`
|
||||
// (#56), so `git worktree list` must show the predictable in-repo path.
|
||||
let worktrees = git_worktree_list(base.path());
|
||||
assert!(
|
||||
worktrees.iter().any(|w| w.contains("feature/e2e")),
|
||||
"expected a worktree for feature/e2e branch, got: {worktrees:?}"
|
||||
worktrees
|
||||
.iter()
|
||||
.any(|w| w.contains("worktrees/feature-e2e")),
|
||||
"expected a worktree for feature/e2e under <repo>/worktrees, got: {worktrees:?}"
|
||||
);
|
||||
|
||||
client.kill_session(s.id).await.expect("kill");
|
||||
@@ -160,6 +161,85 @@ async fn cleanup_on_kill_removes_worktree() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The guard (#56): killing a session whose worktree holds uncommitted
|
||||
/// changes must leave the tree on disk — cleanup is unconditional, so this
|
||||
/// guard is what keeps a stray kill from destroying work.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn kill_spares_worktree_with_uncommitted_changes() {
|
||||
let (_daemon, client) = bring_up().await;
|
||||
|
||||
let base = TempDir::new().unwrap();
|
||||
init_repo(base.path());
|
||||
let wt_path = base.path().join("worktrees").join("feature-unsaved");
|
||||
|
||||
let req = CreateSessionRequest {
|
||||
cwd: base.path().to_path_buf(),
|
||||
command: "sleep 30".into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: Some(WorktreeSpec {
|
||||
base_repo: base.path().to_path_buf(),
|
||||
branch: "feature/unsaved".into(),
|
||||
cleanup_on_kill: true,
|
||||
create_branch: true,
|
||||
}),
|
||||
};
|
||||
|
||||
let s = client.spawn_session(&req).await.expect("spawn worktree");
|
||||
assert!(wt_path.exists());
|
||||
std::fs::write(wt_path.join("README"), b"unsaved edits\n").unwrap();
|
||||
|
||||
client.kill_session(s.id).await.expect("kill");
|
||||
|
||||
// The session is gone but the dirty worktree stays findable on disk.
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while Instant::now() < deadline {
|
||||
let sessions = client.list_sessions().await.unwrap_or_default();
|
||||
if sessions.is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
assert!(
|
||||
wt_path.exists(),
|
||||
"guarded worktree must be left on disk after kill"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn spawn_on_existing_branch_checks_it_out() {
|
||||
let (_daemon, client) = bring_up().await;
|
||||
|
||||
let base = TempDir::new().unwrap();
|
||||
init_repo(base.path());
|
||||
run_git(&["branch", "feature/existing"], base.path());
|
||||
|
||||
let req = CreateSessionRequest {
|
||||
cwd: base.path().to_path_buf(),
|
||||
command: "sleep 30".into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: Some(WorktreeSpec {
|
||||
base_repo: base.path().to_path_buf(),
|
||||
branch: "feature/existing".into(),
|
||||
cleanup_on_kill: true,
|
||||
create_branch: false,
|
||||
}),
|
||||
};
|
||||
|
||||
let s = client
|
||||
.spawn_session(&req)
|
||||
.await
|
||||
.expect("spawn on existing branch");
|
||||
let worktrees = git_worktree_list(base.path());
|
||||
assert!(
|
||||
worktrees.iter().any(|w| w.contains("feature/existing")),
|
||||
"expected a worktree checked out at feature/existing, got: {worktrees:?}"
|
||||
);
|
||||
|
||||
client.kill_session(s.id).await.expect("kill");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn daemon_restart_recovers_session() {
|
||||
let (mut daemon, client) = bring_up().await;
|
||||
@@ -230,7 +310,6 @@ async fn spawn_records_history_and_infers_gitroot_for_form() {
|
||||
// (#27's recents picker), and gitroot infers the worktree base_repo from the
|
||||
// same dir. Exercised end to end against real tmux + git.
|
||||
let (daemon, client) = bring_up().await;
|
||||
let daemon_base = daemon.http_base();
|
||||
|
||||
// A git repo as the working dir, so gitroot has a repo to infer.
|
||||
let repo = TempDir::new().unwrap();
|
||||
@@ -250,16 +329,11 @@ async fn spawn_records_history_and_infers_gitroot_for_form() {
|
||||
"recent-dirs surfaces the spawned cwd",
|
||||
Duration::from_secs(5),
|
||||
|| {
|
||||
let url = format!("{daemon_base}/api/recent-dirs");
|
||||
let client = daemon.client();
|
||||
let want = cwd.clone();
|
||||
async move {
|
||||
let resp = match reqwest::get(&url).await {
|
||||
Ok(r) => r,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let recents: maestro_protocol::RecentDirs = match resp.json().await {
|
||||
Ok(v) => v,
|
||||
Err(_) => return false,
|
||||
let Ok(recents) = client.recent_dirs().await else {
|
||||
return false;
|
||||
};
|
||||
recents
|
||||
.dirs
|
||||
@@ -272,15 +346,7 @@ async fn spawn_records_history_and_infers_gitroot_for_form() {
|
||||
|
||||
// gitroot infers the worktree base_repo from the same dir (#25/#26): the dir
|
||||
// is itself the repo toplevel (it holds `.git`).
|
||||
let gr: maestro_protocol::GitRoot = reqwest::Client::new()
|
||||
.get(format!("{daemon_base}/api/gitroot"))
|
||||
.query(&[("path", cwd.as_str())])
|
||||
.send()
|
||||
.await
|
||||
.expect("gitroot request")
|
||||
.json()
|
||||
.await
|
||||
.expect("gitroot json");
|
||||
let gr = daemon.client().git_root(&cwd).await.expect("gitroot");
|
||||
assert_eq!(
|
||||
gr.root.as_deref().map(|p| p.to_string_lossy().to_string()),
|
||||
Some(cwd.clone()),
|
||||
@@ -396,7 +462,7 @@ async fn daemon_events_ws_streams_snapshot_then_session_added() {
|
||||
let (daemon, client) = bring_up().await;
|
||||
let cwd = TempDir::new().unwrap();
|
||||
|
||||
let ws_url = format!("{}/api/events", daemon.ws_base());
|
||||
let ws_url = daemon.client().events_url().unwrap();
|
||||
let (mut ws, _) = tokio_tungstenite::connect_async(ws_url)
|
||||
.await
|
||||
.expect("events WS handshake");
|
||||
@@ -459,14 +525,13 @@ fn run_cli(args: &[&str], envs: &[(&str, &str)]) -> std::process::Output {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cli_list_reads_from_daemon() {
|
||||
let (daemon, client) = bring_up().await;
|
||||
let cwd = TempDir::new().unwrap();
|
||||
let session = client
|
||||
.spawn_session(&create_req(cwd.path(), "sleep 30"))
|
||||
.await
|
||||
.expect("spawn");
|
||||
// The subject is the shipped `maestro` binary — arg parsing, config
|
||||
// precedence, output. It needs a daemon to talk to, not tmux, so this runs
|
||||
// against an in-memory one.
|
||||
let mock = maestro_testing::MockDaemon::start().await;
|
||||
let id = uuid::Uuid::new_v4();
|
||||
mock.add_session(maestro_testing::session(id, "/home/mock/work", "sleep 30"));
|
||||
|
||||
let daemon_url = daemon.http_base();
|
||||
let home = TempDir::new().unwrap();
|
||||
let cfg_path = home.path().join("config.toml");
|
||||
let out = run_cli(
|
||||
@@ -474,18 +539,16 @@ async fn cli_list_reads_from_daemon() {
|
||||
&[
|
||||
("HOME", home.path().to_str().unwrap()),
|
||||
("MAESTRO_CONFIG", cfg_path.to_str().unwrap()),
|
||||
("MAESTRO_DAEMON_URL", &daemon_url),
|
||||
("MAESTRO_DAEMON_URL", &mock.http_base()),
|
||||
],
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "list failed: {stderr}\n{stdout}");
|
||||
assert!(
|
||||
stdout.contains(&session.id.to_string()),
|
||||
stdout.contains(&id.to_string()),
|
||||
"session not listed: {stdout}"
|
||||
);
|
||||
|
||||
client.kill_session(session.id).await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
//! TUI integration tests (NAP-282).
|
||||
//!
|
||||
//! Exercises `CatalogStore` and the per-session `SessionTask` against a real
|
||||
//! daemon subprocess. We don't spin the full ratatui frontend
|
||||
//! here — those interactions are best tested with `TestBackend` unit tests in
|
||||
//! `crates/maestro-tui/src/*.rs`. This file fills the gap between those
|
||||
//! and the headless e2e suite by verifying that the TUI's wire layer plays
|
||||
//! nicely with a real daemon.
|
||||
//!
|
||||
//! Requires `tmux` and `git` on `$PATH`.
|
||||
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use maestro_e2e::Daemon;
|
||||
use maestro_protocol::CreateSessionRequest;
|
||||
use maestro_tui::catalog::CatalogStore;
|
||||
|
||||
async fn wait_until<F, Fut>(label: &str, deadline: Duration, mut check: F)
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = bool>,
|
||||
{
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if check().await {
|
||||
return;
|
||||
}
|
||||
if start.elapsed() >= deadline {
|
||||
panic!("timeout waiting for {label}");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn catalog_bootstrap_against_real_daemon() {
|
||||
let daemon = Daemon::spawn().await;
|
||||
let ws_url = format!("{}/api/events", daemon.ws_base());
|
||||
|
||||
let store = CatalogStore::default();
|
||||
let bg = store.clone();
|
||||
tokio::spawn(async move { bg.run_events_loop(ws_url).await });
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(3), store.wait_for_initial_snapshot())
|
||||
.await
|
||||
.expect("initial snapshot");
|
||||
|
||||
assert!(store.snapshot().sessions.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn post_session_propagates_through_events_ws() {
|
||||
let daemon = Daemon::spawn().await;
|
||||
let ws_url = format!("{}/api/events", daemon.ws_base());
|
||||
let http_base = daemon.http_base();
|
||||
|
||||
let store = CatalogStore::default();
|
||||
let bg = store.clone();
|
||||
tokio::spawn(async move { bg.run_events_loop(ws_url).await });
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(3), store.wait_for_initial_snapshot())
|
||||
.await
|
||||
.expect("initial snapshot");
|
||||
|
||||
let cwd = PathBuf::from(daemon.home());
|
||||
let req = CreateSessionRequest {
|
||||
cwd,
|
||||
command: "bash".into(),
|
||||
env: Default::default(),
|
||||
metadata: Default::default(),
|
||||
worktree: None,
|
||||
};
|
||||
let res = reqwest::Client::new()
|
||||
.post(format!("{http_base}/api/sessions"))
|
||||
.json(&req)
|
||||
.send()
|
||||
.await
|
||||
.expect("post sessions");
|
||||
assert!(res.status().is_success(), "POST /api/sessions: {res:?}");
|
||||
|
||||
wait_until(
|
||||
"session to surface in catalog",
|
||||
Duration::from_secs(2),
|
||||
|| async { store.snapshot().sessions.len() == 1 },
|
||||
)
|
||||
.await;
|
||||
|
||||
let snap = store.snapshot();
|
||||
assert_eq!(snap.sessions.len(), 1);
|
||||
assert_eq!(snap.sessions[0].command, "bash");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn delete_session_propagates_removal() {
|
||||
let daemon = Daemon::spawn().await;
|
||||
let ws_url = format!("{}/api/events", daemon.ws_base());
|
||||
let http_base = daemon.http_base();
|
||||
|
||||
let store = CatalogStore::default();
|
||||
let bg = store.clone();
|
||||
tokio::spawn(async move { bg.run_events_loop(ws_url).await });
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(3), store.wait_for_initial_snapshot())
|
||||
.await
|
||||
.expect("initial snapshot");
|
||||
|
||||
let cwd = PathBuf::from(daemon.home());
|
||||
let req = CreateSessionRequest {
|
||||
cwd,
|
||||
command: "bash".into(),
|
||||
env: Default::default(),
|
||||
metadata: Default::default(),
|
||||
worktree: None,
|
||||
};
|
||||
let client = reqwest::Client::new();
|
||||
let res = client
|
||||
.post(format!("{http_base}/api/sessions"))
|
||||
.json(&req)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(res.status().is_success());
|
||||
|
||||
wait_until("creation", Duration::from_secs(2), || async {
|
||||
store.snapshot().sessions.len() == 1
|
||||
})
|
||||
.await;
|
||||
|
||||
let sid = store.snapshot().sessions[0].id;
|
||||
let res = client
|
||||
.delete(format!("{http_base}/api/sessions/{sid}"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(res.status().is_success(), "DELETE /api/sessions: {res:?}");
|
||||
|
||||
wait_until("removal", Duration::from_secs(2), || async {
|
||||
store.snapshot().sessions.is_empty()
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -7,11 +7,20 @@ repository.workspace = true
|
||||
publish.workspace = true
|
||||
description = "Shared wire types for Maestro daemon/client communication"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# Opt-in `reqwest`-backed client. Off by default so `maestro-web`, which only
|
||||
# needs the wire types and route paths, does not pull an HTTP stack it has its
|
||||
# own copy of.
|
||||
client = ["dep:reqwest"]
|
||||
|
||||
[dependencies]
|
||||
chrono.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
uuid.workspace = true
|
||||
reqwest = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Typed client for the daemon's `/api/*` surface.
|
||||
//!
|
||||
//! Behind the `client` feature so consumers that only need the wire types and
|
||||
//! route paths — `maestro-web`, `maestro-config` — don't pull an HTTP stack.
|
||||
//!
|
||||
//! This is the one place that knows how to call the daemon: the CLI, the TUI and
|
||||
//! the end-to-end harness all go through it.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use reqwest::{Method, Response, StatusCode};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::routes::{self, UrlError};
|
||||
use crate::{
|
||||
ApiError, CreateSessionRequest, DaemonInfo, DirListing, ErrorInfo, GitRoot, Project,
|
||||
RecentDirs, Session,
|
||||
};
|
||||
|
||||
/// Time budget for establishing a TCP connection to the daemon.
|
||||
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Total budget for a single request. Bounds the case where the daemon is
|
||||
/// TCP-alive but never makes forward progress.
|
||||
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ClientError {
|
||||
#[error("http: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
/// The daemon answered with a structured [`ApiError`] envelope.
|
||||
#[error("daemon returned {status} ({}): {}", .info.code, .info.message)]
|
||||
Api { status: StatusCode, info: ErrorInfo },
|
||||
/// A non-success response whose body was not an [`ApiError`].
|
||||
#[error("daemon returned {status}: {body}")]
|
||||
Status { status: StatusCode, body: String },
|
||||
#[error("decode: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error(transparent)]
|
||||
Url(#[from] UrlError),
|
||||
}
|
||||
|
||||
impl ClientError {
|
||||
/// True when the daemon could not be reached at all, rather than reaching it
|
||||
/// and being refused. Drives "is the daemon running?" messaging.
|
||||
pub fn is_unreachable(&self) -> bool {
|
||||
matches!(self, ClientError::Http(e) if e.is_connect())
|
||||
}
|
||||
|
||||
/// The daemon's own message when it sent one, so callers can render the
|
||||
/// reason rather than a bare status code.
|
||||
pub fn daemon_message(&self) -> Option<&str> {
|
||||
match self {
|
||||
ClientError::Api { info, .. } => Some(&info.message),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP client bound to one daemon's base URL.
|
||||
///
|
||||
/// The daemon's surface needs no auth — reaching its bind address is the
|
||||
/// authorization, same trust model as tmux itself.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DaemonClient {
|
||||
base: String,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
impl DaemonClient {
|
||||
/// Client with the standard timeouts.
|
||||
pub fn new(base: impl Into<String>) -> Self {
|
||||
Self::with_timeouts(base, DEFAULT_CONNECT_TIMEOUT, DEFAULT_REQUEST_TIMEOUT)
|
||||
}
|
||||
|
||||
/// Client with explicit timeouts, for callers with a tighter budget than the
|
||||
/// default — the TUI's startup health probe wants to fail fast rather than
|
||||
/// hold the terminal for 30 seconds.
|
||||
pub fn with_timeouts(base: impl Into<String>, connect: Duration, request: Duration) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.user_agent(concat!("maestro/", env!("CARGO_PKG_VERSION")))
|
||||
.connect_timeout(connect)
|
||||
.timeout(request)
|
||||
.build()
|
||||
.expect("build reqwest client");
|
||||
Self {
|
||||
base: routes::normalize_base(&base.into()).to_string(),
|
||||
http,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn base(&self) -> &str {
|
||||
&self.base
|
||||
}
|
||||
|
||||
/// `WS /api/events` URL for this daemon.
|
||||
pub fn events_url(&self) -> Result<String, ClientError> {
|
||||
Ok(routes::events_url(&self.base)?)
|
||||
}
|
||||
|
||||
/// `WS /api/attach/:id` URL for this daemon.
|
||||
pub fn attach_url(&self, id: Uuid) -> Result<String, ClientError> {
|
||||
Ok(routes::attach_url(&self.base, id)?)
|
||||
}
|
||||
|
||||
// -- typed calls --------------------------------------------------------
|
||||
|
||||
pub async fn list_sessions(&self) -> Result<Vec<Session>, ClientError> {
|
||||
self.get(routes::SESSIONS, &[]).await
|
||||
}
|
||||
|
||||
pub async fn create_session(&self, req: &CreateSessionRequest) -> Result<Session, ClientError> {
|
||||
self.post(routes::SESSIONS, req).await
|
||||
}
|
||||
|
||||
pub async fn kill_session(&self, id: Uuid) -> Result<(), ClientError> {
|
||||
let resp = self
|
||||
.send(Method::DELETE, &routes::session(id), &[], None::<&()>)
|
||||
.await?;
|
||||
check(resp).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn daemon_info(&self) -> Result<DaemonInfo, ClientError> {
|
||||
self.get(routes::INFO, &[]).await
|
||||
}
|
||||
|
||||
pub async fn list_dir(&self, path: &str) -> Result<DirListing, ClientError> {
|
||||
self.get(routes::DIRS, &[(routes::PATH_QUERY, path)]).await
|
||||
}
|
||||
|
||||
pub async fn recent_dirs(&self) -> Result<RecentDirs, ClientError> {
|
||||
self.get(routes::RECENT_DIRS, &[]).await
|
||||
}
|
||||
|
||||
pub async fn git_root(&self, path: &str) -> Result<GitRoot, ClientError> {
|
||||
self.get(routes::GITROOT, &[(routes::PATH_QUERY, path)])
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_projects(&self) -> Result<Vec<Project>, ClientError> {
|
||||
self.get(routes::PROJECTS, &[]).await
|
||||
}
|
||||
|
||||
// -- plumbing -----------------------------------------------------------
|
||||
|
||||
async fn get<T: DeserializeOwned>(
|
||||
&self,
|
||||
path: &str,
|
||||
query: &[(&str, &str)],
|
||||
) -> Result<T, ClientError> {
|
||||
let resp = self.send(Method::GET, path, query, None::<&()>).await?;
|
||||
json(check(resp).await?).await
|
||||
}
|
||||
|
||||
async fn post<B: Serialize, T: DeserializeOwned>(
|
||||
&self,
|
||||
path: &str,
|
||||
body: &B,
|
||||
) -> Result<T, ClientError> {
|
||||
let resp = self.send(Method::POST, path, &[], Some(body)).await?;
|
||||
json(check(resp).await?).await
|
||||
}
|
||||
|
||||
async fn send<B: Serialize>(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
query: &[(&str, &str)],
|
||||
body: Option<&B>,
|
||||
) -> Result<Response, ClientError> {
|
||||
let mut req = self
|
||||
.http
|
||||
.request(method, routes::http_url(&self.base, path));
|
||||
if !query.is_empty() {
|
||||
req = req.query(query);
|
||||
}
|
||||
if let Some(b) = body {
|
||||
req = req.json(b);
|
||||
}
|
||||
Ok(req.send().await?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn a non-success response into the richest error its body supports: the
|
||||
/// daemon's [`ApiError`] envelope when present, the raw body otherwise.
|
||||
async fn check(resp: Response) -> Result<Response, ClientError> {
|
||||
let status = resp.status();
|
||||
if status.is_success() {
|
||||
return Ok(resp);
|
||||
}
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
match serde_json::from_str::<ApiError>(&body) {
|
||||
Ok(api) => Err(ClientError::Api {
|
||||
status,
|
||||
info: api.error,
|
||||
}),
|
||||
Err(_) => Err(ClientError::Status { status, body }),
|
||||
}
|
||||
}
|
||||
|
||||
async fn json<T: DeserializeOwned>(resp: Response) -> Result<T, ClientError> {
|
||||
// `204 No Content` is a valid success for the calls that return `()`; the
|
||||
// typed getters never hit it.
|
||||
Ok(resp.json::<T>().await?)
|
||||
}
|
||||
@@ -7,6 +7,13 @@
|
||||
|
||||
#![deny(missing_debug_implementations)]
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
pub mod client;
|
||||
pub mod routes;
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
pub use client::{ClientError, DaemonClient};
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -18,6 +25,24 @@ use uuid::Uuid;
|
||||
/// The protocol version this crate implements. Advertised in `GET /api/info`.
|
||||
pub const PROTOCOL_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// True when a daemon advertising `daemon_version` speaks the same protocol as
|
||||
/// this build.
|
||||
///
|
||||
/// Compared on the major component only, per semver: within a major, added
|
||||
/// fields are `#[serde(default)]` and so are forward-compatible. An empty or
|
||||
/// unparseable version is treated as compatible — daemons that predate the
|
||||
/// field should not trip a warning.
|
||||
pub fn is_compatible(daemon_version: &str) -> bool {
|
||||
fn major(v: &str) -> Option<&str> {
|
||||
let m = v.split('.').next()?;
|
||||
(!m.is_empty() && m.bytes().all(|b| b.is_ascii_digit())).then_some(m)
|
||||
}
|
||||
match (major(daemon_version), major(PROTOCOL_VERSION)) {
|
||||
(Some(theirs), Some(ours)) => theirs == ours,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A live or recently-dead tmux session managed by the daemon.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Session {
|
||||
@@ -86,8 +111,20 @@ pub enum ActivityState {
|
||||
pub struct WorktreeSpec {
|
||||
pub base_repo: PathBuf,
|
||||
pub branch: String,
|
||||
#[serde(default)]
|
||||
/// Kept on the wire for CLI compatibility (#56) but no longer a
|
||||
/// user-facing choice: the daemon always cleans up on kill, guarded
|
||||
/// against unsaved work. Defaults to `true`.
|
||||
#[serde(default = "default_true")]
|
||||
pub cleanup_on_kill: bool,
|
||||
/// When false, `branch` must already exist and is checked out as-is
|
||||
/// (#56); when true (the default, and what every payload meant before
|
||||
/// the field existed) the daemon creates it with `worktree add -b`.
|
||||
#[serde(default = "default_true")]
|
||||
pub create_branch: bool,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// HTTP `POST /api/sessions` body.
|
||||
@@ -151,6 +188,30 @@ pub struct GitRoot {
|
||||
pub root: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// One discovered git repository (or linked worktree) for `GET /api/projects`
|
||||
/// (#54). The daemon reports the timestamp; clients decide what "stale" means
|
||||
/// (the web UI dims entries older than 7 days).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Project {
|
||||
/// Absolute path of the repository/worktree toplevel.
|
||||
pub path: PathBuf,
|
||||
/// Basename of `path`.
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub is_worktree: bool,
|
||||
/// The main checkout this worktree belongs to. Set only when
|
||||
/// [`Self::is_worktree`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base_repo: Option<PathBuf>,
|
||||
/// Later of the repo's git HEAD mtime and the newest spawn-history use of
|
||||
/// any directory inside it. `None` when neither is known.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_activity: Option<DateTime<Utc>>,
|
||||
/// Command last spawned in this project, from spawn history.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_command: Option<String>,
|
||||
}
|
||||
|
||||
/// Structured failure used everywhere we don't want to leak a string-only error.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ErrorInfo {
|
||||
@@ -158,6 +219,66 @@ pub struct ErrorInfo {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// The envelope every `/api/*` failure is wrapped in: `{"error": {…}}`.
|
||||
///
|
||||
/// The daemon builds it, the CLI and TUI decode it to surface the daemon's own
|
||||
/// message, and `maestro-web` uses it both to report proxy failures and to
|
||||
/// recover the rejection reason from an upstream WebSocket handshake. Before it
|
||||
/// lived here that shape was hand-rolled in four places, one of them by
|
||||
/// escaping quotes into a format string.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ApiError {
|
||||
pub error: ErrorInfo,
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
error: ErrorInfo {
|
||||
code: code.into(),
|
||||
message: message.into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The daemon's human-readable reason, for clients that only render text.
|
||||
pub fn message(&self) -> &str {
|
||||
&self.error.message
|
||||
}
|
||||
}
|
||||
|
||||
/// One command tile offered by the spawn form.
|
||||
///
|
||||
/// Lives here rather than in `maestro-config` because it is on the wire inside
|
||||
/// [`DaemonInfo`]; `maestro-config` re-exports it so the on-disk `[spawn]`
|
||||
/// schema and the payload stay one type.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SpawnPreset {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub command: String,
|
||||
}
|
||||
|
||||
/// Payload of `GET /api/info` — daemon identity, protocol version, and the
|
||||
/// spawn presets clients render as one-click tiles.
|
||||
///
|
||||
/// Previously declared three times (daemon, CLI, TypeScript), and the CLI's
|
||||
/// copy silently dropped `version` and `presets`.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DaemonInfo {
|
||||
#[serde(default)]
|
||||
pub hostname: String,
|
||||
/// The `PROTOCOL_VERSION` the daemon implements.
|
||||
#[serde(default)]
|
||||
pub version: String,
|
||||
/// Home directory of the OS user the daemon runs as, so clients can prefill
|
||||
/// a spawn form's working directory. Empty if unresolved.
|
||||
#[serde(default)]
|
||||
pub home_dir: String,
|
||||
#[serde(default)]
|
||||
pub presets: Vec<SpawnPreset>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Catalog events (`WS /api/events`)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -208,6 +329,22 @@ pub enum ClientControl {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn version_compatibility_is_major_only() {
|
||||
assert!(is_compatible(PROTOCOL_VERSION));
|
||||
let ours_major = PROTOCOL_VERSION.split('.').next().unwrap();
|
||||
assert!(is_compatible(&format!("{ours_major}.99.99")));
|
||||
assert!(!is_compatible("99.0.0"));
|
||||
}
|
||||
|
||||
/// A daemon predating the field sends nothing; that must not read as a
|
||||
/// mismatch.
|
||||
#[test]
|
||||
fn version_compatibility_tolerates_unknown_versions() {
|
||||
assert!(is_compatible(""));
|
||||
assert!(is_compatible("unknown"));
|
||||
}
|
||||
|
||||
fn round_trip<T>(value: &T) -> T
|
||||
where
|
||||
T: Serialize + for<'de> Deserialize<'de>,
|
||||
@@ -216,6 +353,34 @@ mod tests {
|
||||
serde_json::from_str(&json).expect("deserialize")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_round_trips_and_defaults_on_legacy_payload() {
|
||||
let full = Project {
|
||||
path: PathBuf::from("/home/u/tea/maestro"),
|
||||
name: "maestro".into(),
|
||||
is_worktree: true,
|
||||
base_repo: Some(PathBuf::from("/home/u/tea/maestro-main")),
|
||||
last_activity: Some(
|
||||
DateTime::parse_from_rfc3339("2026-08-23T12:00:00Z")
|
||||
.unwrap()
|
||||
.with_timezone(&Utc),
|
||||
),
|
||||
last_command: Some("claude".into()),
|
||||
};
|
||||
assert_eq!(full, round_trip(&full));
|
||||
|
||||
// A payload from a daemon predating the optional fields still decodes.
|
||||
let legacy = serde_json::json!({
|
||||
"path": "/home/u/proj",
|
||||
"name": "proj",
|
||||
});
|
||||
let p: Project = serde_json::from_value(legacy).unwrap();
|
||||
assert!(!p.is_worktree);
|
||||
assert_eq!(p.base_repo, None);
|
||||
assert_eq!(p.last_activity, None);
|
||||
assert_eq!(p.last_command, None);
|
||||
}
|
||||
|
||||
fn sample_session() -> Session {
|
||||
Session {
|
||||
id: Uuid::from_u128(0x0123_4567_89ab_cdef_0123_4567_89ab_cdef),
|
||||
@@ -292,6 +457,7 @@ mod tests {
|
||||
base_repo: PathBuf::from("/home/naps62/projects/maestro"),
|
||||
branch: "feat/foo".into(),
|
||||
cleanup_on_kill: true,
|
||||
create_branch: true,
|
||||
}),
|
||||
};
|
||||
assert_eq!(req, round_trip(&req));
|
||||
@@ -309,6 +475,31 @@ mod tests {
|
||||
assert!(req.metadata.is_empty());
|
||||
}
|
||||
|
||||
/// A client that predates the new/existing discriminator sends no
|
||||
/// `create_branch`; the daemon must read that as "create a new branch" —
|
||||
/// exactly what every payload meant before the field existed (#56).
|
||||
#[test]
|
||||
fn worktree_spec_defaults_on_legacy_payload() {
|
||||
let json = serde_json::json!({
|
||||
"base_repo": "/home/naps62/projects/maestro",
|
||||
"branch": "feat/foo",
|
||||
});
|
||||
let spec: WorktreeSpec = serde_json::from_value(json).unwrap();
|
||||
assert!(spec.create_branch);
|
||||
assert!(spec.cleanup_on_kill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_spec_round_trips_existing_branch_mode() {
|
||||
let spec = WorktreeSpec {
|
||||
base_repo: PathBuf::from("/work"),
|
||||
branch: "feat/foo".into(),
|
||||
cleanup_on_kill: true,
|
||||
create_branch: false,
|
||||
};
|
||||
assert_eq!(spec, round_trip(&spec));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_event_round_trips_and_tags() {
|
||||
let session = sample_session();
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
//! The daemon's `/api/*` surface: paths, and the scheme swap every client
|
||||
//! needs to reach the WebSocket endpoints.
|
||||
//!
|
||||
//! Everything that knows what the daemon's URLs look like lives here.
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Prefix every daemon route shares. `maestro-web` uses it to decide whether a
|
||||
/// request is proxied to the daemon or served from the SPA bundle.
|
||||
pub const API_PREFIX: &str = "/api";
|
||||
|
||||
/// `GET` list / `POST` spawn.
|
||||
pub const SESSIONS: &str = "/api/sessions";
|
||||
/// `GET` daemon identity, version, and spawn presets.
|
||||
pub const INFO: &str = "/api/info";
|
||||
/// `GET` one directory's immediate subdirectories. Takes a `path` query param.
|
||||
pub const DIRS: &str = "/api/dirs";
|
||||
/// `GET` spawn history.
|
||||
pub const RECENT_DIRS: &str = "/api/recent-dirs";
|
||||
/// `GET` discovered git repositories and worktrees, newest activity first.
|
||||
pub const PROJECTS: &str = "/api/projects";
|
||||
/// `GET` the enclosing repository of a path. Takes a `path` query param.
|
||||
pub const GITROOT: &str = "/api/gitroot";
|
||||
/// `WS` catalog snapshot + session deltas.
|
||||
pub const EVENTS: &str = "/api/events";
|
||||
|
||||
/// Name of the query parameter [`DIRS`] and [`GITROOT`] both take.
|
||||
pub const PATH_QUERY: &str = "path";
|
||||
|
||||
/// `DELETE /api/sessions/:id`.
|
||||
pub fn session(id: Uuid) -> String {
|
||||
format!("{SESSIONS}/{id}")
|
||||
}
|
||||
|
||||
/// `WS /api/attach/:id` — raw PTY bytes.
|
||||
pub fn attach(id: Uuid) -> String {
|
||||
format!("{API_PREFIX}/attach/{id}")
|
||||
}
|
||||
|
||||
/// Axum-style patterns for the two parameterised routes, so the server
|
||||
/// registers the same paths [`session`] and [`attach`] build.
|
||||
pub mod patterns {
|
||||
pub const SESSION: &str = "/api/sessions/:id";
|
||||
pub const ATTACH: &str = "/api/attach/:id";
|
||||
}
|
||||
|
||||
/// A daemon base URL that could not be turned into a WebSocket base.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum UrlError {
|
||||
#[error("daemon url has no supported scheme (want http/https/ws/wss): {0}")]
|
||||
UnsupportedScheme(String),
|
||||
}
|
||||
|
||||
/// Strip a trailing slash so `{base}{path}` never doubles up.
|
||||
pub fn normalize_base(base: &str) -> &str {
|
||||
base.trim_end_matches('/')
|
||||
}
|
||||
|
||||
/// Join a daemon base URL and one of this module's paths.
|
||||
pub fn http_url(base: &str, path: &str) -> String {
|
||||
format!("{}{}", normalize_base(base), path)
|
||||
}
|
||||
|
||||
/// Swap an HTTP base URL for its WebSocket equivalent.
|
||||
///
|
||||
/// `http://` becomes `ws://`, `https://` becomes `wss://`, and a base that is
|
||||
/// already `ws://`/`wss://` passes through. Anything else is an error — a
|
||||
/// scheme-less base would otherwise produce a URL that fails much later, at
|
||||
/// connect time, with nothing pointing back at the configuration that caused
|
||||
/// it.
|
||||
pub fn ws_base(http_base: &str) -> Result<String, UrlError> {
|
||||
let base = normalize_base(http_base);
|
||||
if let Some(rest) = base.strip_prefix("https://") {
|
||||
Ok(format!("wss://{rest}"))
|
||||
} else if let Some(rest) = base.strip_prefix("http://") {
|
||||
Ok(format!("ws://{rest}"))
|
||||
} else if base.starts_with("wss://") || base.starts_with("ws://") {
|
||||
Ok(base.to_string())
|
||||
} else {
|
||||
Err(UrlError::UnsupportedScheme(http_base.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Full `WS /api/events` URL for a daemon reachable at `http_base`.
|
||||
pub fn events_url(http_base: &str) -> Result<String, UrlError> {
|
||||
Ok(format!("{}{}", ws_base(http_base)?, EVENTS))
|
||||
}
|
||||
|
||||
/// Full `WS /api/attach/:id` URL for a daemon reachable at `http_base`.
|
||||
pub fn attach_url(http_base: &str, id: Uuid) -> Result<String, UrlError> {
|
||||
Ok(format!("{}{}", ws_base(http_base)?, attach(id)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn id() -> Uuid {
|
||||
Uuid::parse_str("6f1a7c0e-0f5e-4a2b-9a3d-6b1c2d3e4f50").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ws_base_swaps_http_and_https() {
|
||||
assert_eq!(
|
||||
ws_base("http://127.0.0.1:7070").unwrap(),
|
||||
"ws://127.0.0.1:7070"
|
||||
);
|
||||
assert_eq!(
|
||||
ws_base("https://laptop.lan:7070").unwrap(),
|
||||
"wss://laptop.lan:7070"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ws_base_passes_through_websocket_schemes() {
|
||||
assert_eq!(ws_base("ws://10.0.0.1:7070").unwrap(), "ws://10.0.0.1:7070");
|
||||
assert_eq!(
|
||||
ws_base("wss://10.0.0.1:7070").unwrap(),
|
||||
"wss://10.0.0.1:7070"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ws_base_rejects_an_unknown_scheme() {
|
||||
assert_eq!(
|
||||
ws_base("127.0.0.1:7070"),
|
||||
Err(UrlError::UnsupportedScheme("127.0.0.1:7070".into()))
|
||||
);
|
||||
assert!(ws_base("ftp://host:7070").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_slashes_never_double_up() {
|
||||
assert_eq!(ws_base("http://host:7070/").unwrap(), "ws://host:7070");
|
||||
assert_eq!(
|
||||
http_url("http://host:7070/", SESSIONS),
|
||||
"http://host:7070/api/sessions"
|
||||
);
|
||||
assert_eq!(
|
||||
events_url("http://host:7070/").unwrap(),
|
||||
"ws://host:7070/api/events"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_per_session_paths() {
|
||||
assert_eq!(
|
||||
session(id()),
|
||||
"/api/sessions/6f1a7c0e-0f5e-4a2b-9a3d-6b1c2d3e4f50"
|
||||
);
|
||||
assert_eq!(
|
||||
attach(id()),
|
||||
"/api/attach/6f1a7c0e-0f5e-4a2b-9a3d-6b1c2d3e4f50"
|
||||
);
|
||||
assert_eq!(
|
||||
attach_url("https://laptop.lan:7070", id()).unwrap(),
|
||||
"wss://laptop.lan:7070/api/attach/6f1a7c0e-0f5e-4a2b-9a3d-6b1c2d3e4f50"
|
||||
);
|
||||
}
|
||||
|
||||
/// The server registers `patterns::*` while clients call `session`/`attach`;
|
||||
/// nothing but this test keeps the two spellings in step.
|
||||
#[test]
|
||||
fn patterns_and_builders_agree() {
|
||||
assert_eq!(
|
||||
patterns::SESSION.trim_end_matches(":id"),
|
||||
session(id()).trim_end_matches(&id().to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
patterns::ATTACH.trim_end_matches(":id"),
|
||||
attach(id()).trim_end_matches(&id().to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_route_sits_under_the_api_prefix() {
|
||||
for path in [SESSIONS, INFO, DIRS, RECENT_DIRS, PROJECTS, GITROOT, EVENTS] {
|
||||
assert!(path.starts_with(API_PREFIX), "{path} escapes {API_PREFIX}");
|
||||
}
|
||||
assert!(attach(id()).starts_with(API_PREFIX));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "maestro-testing"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
description = "In-memory Maestro daemon for tests: the real /api/* surface without tmux"
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
chrono.workspace = true
|
||||
futures-util.workspace = true
|
||||
maestro-protocol = { workspace = true, features = ["client"] }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
uuid.workspace = true
|
||||
@@ -0,0 +1,364 @@
|
||||
//! An in-memory Maestro daemon for tests.
|
||||
//!
|
||||
//! Serves the real `/api/*` surface from `maestro-protocol` types, backed by a
|
||||
//! `Vec<Session>` instead of tmux. Use it whenever the subject under test is a
|
||||
//! client — request building, error decoding, the catalog reducer, the proxy —
|
||||
//! rather than session management itself. Tests that genuinely need tmux belong
|
||||
//! in `maestro-e2e` against a real daemon.
|
||||
|
||||
#![deny(missing_debug_implementations)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{any, delete, get};
|
||||
use axum::{Json, Router};
|
||||
use chrono::Utc;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use maestro_protocol::{
|
||||
routes, ApiError, CatalogEvent, CreateSessionRequest, DaemonClient, DaemonInfo, DirListing,
|
||||
GitRoot, RecentDirs, Session, SessionStatus, PROTOCOL_VERSION,
|
||||
};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::{broadcast, oneshot};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Build a plausible `Session` for a test to hand to [`MockDaemon::add_session`].
|
||||
pub fn session(id: Uuid, cwd: &str, command: &str) -> Session {
|
||||
Session {
|
||||
id,
|
||||
cwd: cwd.into(),
|
||||
command: command.into(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
status: SessionStatus::Running,
|
||||
created_at: Utc::now(),
|
||||
foreground: None,
|
||||
activity: Default::default(),
|
||||
last_activity_at: Utc::now(),
|
||||
current_cwd: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Inner {
|
||||
sessions: Vec<Session>,
|
||||
info: Option<DaemonInfo>,
|
||||
/// When set, every route answers with this instead of its normal response.
|
||||
forced_error: Option<(u16, ApiError)>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
inner: Arc<Mutex<Inner>>,
|
||||
events: broadcast::Sender<CatalogEvent>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AppState {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AppState").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// A running mock daemon. Shuts down when dropped.
|
||||
#[derive(Debug)]
|
||||
pub struct MockDaemon {
|
||||
addr: SocketAddr,
|
||||
state: AppState,
|
||||
_shutdown: oneshot::Sender<()>,
|
||||
}
|
||||
|
||||
impl MockDaemon {
|
||||
pub async fn start() -> Self {
|
||||
let state = AppState {
|
||||
inner: Arc::new(Mutex::new(Inner::default())),
|
||||
events: broadcast::channel(64).0,
|
||||
};
|
||||
let app = Router::new()
|
||||
.route(routes::SESSIONS, get(list_sessions).post(create_session))
|
||||
.route(routes::patterns::SESSION, delete(kill_session))
|
||||
.route(routes::INFO, get(daemon_info))
|
||||
.route(routes::DIRS, get(list_dir))
|
||||
.route(routes::RECENT_DIRS, get(recent_dirs))
|
||||
.route(routes::GITROOT, get(git_root))
|
||||
.route(routes::EVENTS, any(events_ws))
|
||||
.route(routes::patterns::ATTACH, any(attach_ws))
|
||||
.with_state(state.clone());
|
||||
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.expect("bind");
|
||||
let addr = listener.local_addr().expect("local_addr");
|
||||
let (tx, rx) = oneshot::channel::<()>();
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = rx.await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
|
||||
Self {
|
||||
addr,
|
||||
state,
|
||||
_shutdown: tx,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn addr(&self) -> SocketAddr {
|
||||
self.addr
|
||||
}
|
||||
|
||||
pub fn http_base(&self) -> String {
|
||||
format!("http://{}", self.addr)
|
||||
}
|
||||
|
||||
/// A client bound to this daemon.
|
||||
pub fn client(&self) -> DaemonClient {
|
||||
DaemonClient::new(self.http_base())
|
||||
}
|
||||
|
||||
/// Add a session and announce it, as a real spawn would.
|
||||
pub fn add_session(&self, session: Session) {
|
||||
self.state
|
||||
.inner
|
||||
.lock()
|
||||
.expect("poisoned")
|
||||
.sessions
|
||||
.push(session.clone());
|
||||
let _ = self
|
||||
.state
|
||||
.events
|
||||
.send(CatalogEvent::SessionAdded { session });
|
||||
}
|
||||
|
||||
/// Remove a session and announce it.
|
||||
pub fn remove_session(&self, id: Uuid) {
|
||||
self.state
|
||||
.inner
|
||||
.lock()
|
||||
.expect("poisoned")
|
||||
.sessions
|
||||
.retain(|s| s.id != id);
|
||||
let _ = self.state.events.send(CatalogEvent::SessionRemoved { id });
|
||||
}
|
||||
|
||||
pub fn set_info(&self, info: DaemonInfo) {
|
||||
self.state.inner.lock().expect("poisoned").info = Some(info);
|
||||
}
|
||||
|
||||
/// Make every route answer with this error, so clients' failure paths — and
|
||||
/// their [`ApiError`] decoding — can be exercised.
|
||||
pub fn force_error(&self, status: u16, code: &str, message: &str) {
|
||||
self.state.inner.lock().expect("poisoned").forced_error =
|
||||
Some((status, ApiError::new(code, message)));
|
||||
}
|
||||
|
||||
pub fn clear_error(&self) {
|
||||
self.state.inner.lock().expect("poisoned").forced_error = None;
|
||||
}
|
||||
|
||||
pub fn session_count(&self) -> usize {
|
||||
self.state.inner.lock().expect("poisoned").sessions.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn forced(state: &AppState) -> Option<Response> {
|
||||
let guard = state.inner.lock().expect("poisoned");
|
||||
guard.forced_error.as_ref().map(|(status, body)| {
|
||||
(
|
||||
StatusCode::from_u16(*status).expect("valid status"),
|
||||
Json(body.clone()),
|
||||
)
|
||||
.into_response()
|
||||
})
|
||||
}
|
||||
|
||||
async fn list_sessions(State(s): State<AppState>) -> Response {
|
||||
if let Some(r) = forced(&s) {
|
||||
return r;
|
||||
}
|
||||
let sessions = s.inner.lock().expect("poisoned").sessions.clone();
|
||||
Json(sessions).into_response()
|
||||
}
|
||||
|
||||
async fn create_session(
|
||||
State(s): State<AppState>,
|
||||
Json(req): Json<CreateSessionRequest>,
|
||||
) -> Response {
|
||||
if let Some(r) = forced(&s) {
|
||||
return r;
|
||||
}
|
||||
let mut created = session(Uuid::new_v4(), &req.cwd.to_string_lossy(), &req.command);
|
||||
created.env = req.env;
|
||||
created.metadata = req.metadata;
|
||||
s.inner
|
||||
.lock()
|
||||
.expect("poisoned")
|
||||
.sessions
|
||||
.push(created.clone());
|
||||
let _ = s.events.send(CatalogEvent::SessionAdded {
|
||||
session: created.clone(),
|
||||
});
|
||||
Json(created).into_response()
|
||||
}
|
||||
|
||||
async fn kill_session(State(s): State<AppState>, Path(id): Path<Uuid>) -> Response {
|
||||
if let Some(r) = forced(&s) {
|
||||
return r;
|
||||
}
|
||||
let existed = {
|
||||
let mut guard = s.inner.lock().expect("poisoned");
|
||||
let before = guard.sessions.len();
|
||||
guard.sessions.retain(|x| x.id != id);
|
||||
guard.sessions.len() != before
|
||||
};
|
||||
if !existed {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(ApiError::new("not_found", "no such session on this daemon")),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let _ = s.events.send(CatalogEvent::SessionRemoved { id });
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
|
||||
async fn daemon_info(State(s): State<AppState>) -> Response {
|
||||
if let Some(r) = forced(&s) {
|
||||
return r;
|
||||
}
|
||||
let info = s
|
||||
.inner
|
||||
.lock()
|
||||
.expect("poisoned")
|
||||
.info
|
||||
.clone()
|
||||
.unwrap_or_else(|| DaemonInfo {
|
||||
hostname: "mock-host".into(),
|
||||
version: PROTOCOL_VERSION.into(),
|
||||
home_dir: "/home/mock".into(),
|
||||
presets: Vec::new(),
|
||||
});
|
||||
Json(info).into_response()
|
||||
}
|
||||
|
||||
async fn list_dir(State(s): State<AppState>, Query(q): Query<PathQuery>) -> Response {
|
||||
if let Some(r) = forced(&s) {
|
||||
return r;
|
||||
}
|
||||
Json(DirListing {
|
||||
path: q.path.into(),
|
||||
entries: Vec::new(),
|
||||
truncated: false,
|
||||
})
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn recent_dirs(State(s): State<AppState>) -> Response {
|
||||
if let Some(r) = forced(&s) {
|
||||
return r;
|
||||
}
|
||||
Json(RecentDirs {
|
||||
dirs: Vec::new(),
|
||||
truncated: false,
|
||||
})
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn git_root(State(s): State<AppState>, Query(_q): Query<PathQuery>) -> Response {
|
||||
if let Some(r) = forced(&s) {
|
||||
return r;
|
||||
}
|
||||
Json(GitRoot { root: None }).into_response()
|
||||
}
|
||||
|
||||
/// Snapshot on connect, then live deltas — the same contract the daemon offers.
|
||||
async fn events_ws(State(s): State<AppState>, ws: WebSocketUpgrade) -> Response {
|
||||
ws.on_upgrade(move |socket| events_loop(s, socket))
|
||||
}
|
||||
|
||||
async fn events_loop(s: AppState, socket: WebSocket) {
|
||||
let (mut sink, mut stream) = socket.split();
|
||||
let mut rx = s.events.subscribe();
|
||||
let snapshot = CatalogEvent::Snapshot {
|
||||
sessions: s.inner.lock().expect("poisoned").sessions.clone(),
|
||||
};
|
||||
if sink
|
||||
.send(Message::Text(
|
||||
serde_json::to_string(&snapshot).expect("encode"),
|
||||
))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
tokio::select! {
|
||||
ev = rx.recv() => {
|
||||
let Ok(ev) = ev else { break };
|
||||
let text = serde_json::to_string(&ev).expect("encode");
|
||||
if sink.send(Message::Text(text)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
frame = stream.next() => {
|
||||
match frame {
|
||||
None | Some(Err(_)) | Some(Ok(Message::Close(_))) => break,
|
||||
Some(Ok(_)) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Echoes whatever it is sent, so a client's PTY plumbing can be exercised.
|
||||
async fn attach_ws(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<Uuid>,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
let known = s
|
||||
.inner
|
||||
.lock()
|
||||
.expect("poisoned")
|
||||
.sessions
|
||||
.iter()
|
||||
.any(|x| x.id == id);
|
||||
if !known {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(ApiError::new("not_found", "no such session on this daemon")),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
ws.on_upgrade(|mut socket| async move {
|
||||
while let Some(Ok(msg)) = socket.next().await {
|
||||
match msg {
|
||||
Message::Binary(b) => {
|
||||
if socket.send(Message::Binary(b)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Message::Text(t) => {
|
||||
if socket.send(Message::Text(t)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Message::Close(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct PathQuery {
|
||||
#[serde(default)]
|
||||
path: String,
|
||||
}
|
||||
@@ -12,9 +12,8 @@ clap.workspace = true
|
||||
crossterm.workspace = true
|
||||
futures-util.workspace = true
|
||||
maestro-config.workspace = true
|
||||
maestro-protocol.workspace = true
|
||||
maestro-protocol = { workspace = true, features = ["client"] }
|
||||
ratatui.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio = { workspace = true, features = ["sync", "time", "macros", "rt"] }
|
||||
@@ -24,6 +23,7 @@ uuid.workspace = true
|
||||
vt100.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
maestro-testing.workspace = true
|
||||
axum.workspace = true
|
||||
chrono.workspace = true
|
||||
tokio = { workspace = true, features = ["sync", "time", "macros", "rt-multi-thread", "net"] }
|
||||
|
||||
@@ -38,7 +38,7 @@ pub enum Action {
|
||||
// Catalog actions on the highlighted sidebar row
|
||||
AttachHighlighted,
|
||||
ToggleAttachHighlighted,
|
||||
OpenSpawnModal,
|
||||
NewDraftPane,
|
||||
KillHighlighted,
|
||||
|
||||
// Tabs
|
||||
@@ -78,7 +78,7 @@ impl Action {
|
||||
"SidebarPrev" => return Ok(Action::SidebarPrev),
|
||||
"AttachHighlighted" => return Ok(Action::AttachHighlighted),
|
||||
"ToggleAttachHighlighted" => return Ok(Action::ToggleAttachHighlighted),
|
||||
"OpenSpawnModal" => return Ok(Action::OpenSpawnModal),
|
||||
"NewDraftPane" => return Ok(Action::NewDraftPane),
|
||||
"KillHighlighted" => return Ok(Action::KillHighlighted),
|
||||
"NewTab" => return Ok(Action::NewTab),
|
||||
"CloseTab" => return Ok(Action::CloseTab),
|
||||
@@ -202,6 +202,7 @@ mod tests {
|
||||
for a in [
|
||||
Action::EnterInsert,
|
||||
Action::Quit,
|
||||
Action::NewDraftPane,
|
||||
Action::FocusPane(Direction::Right),
|
||||
Action::GotoTab(7),
|
||||
] {
|
||||
@@ -209,4 +210,14 @@ mod tests {
|
||||
assert_eq!(Action::parse(&s).unwrap(), a, "round-trip for {a:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The spawn modal is gone (issue #63); its old action string must not
|
||||
/// resolve to anything.
|
||||
#[test]
|
||||
fn the_removed_spawn_modal_action_no_longer_parses() {
|
||||
assert_eq!(
|
||||
Action::parse("OpenSpawnModal").unwrap_err(),
|
||||
ActionParseError::Unknown("OpenSpawnModal".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+409
-164
@@ -6,9 +6,9 @@
|
||||
//! changes, and a 30Hz heartbeat.
|
||||
//!
|
||||
//! Actions mutate `AppState` directly. Side effects that talk to the daemon
|
||||
//! (`AttachHighlighted` spawning a `SessionTask`, `OpenSpawnModal` submit
|
||||
//! firing a POST, `KillHighlighted` confirm firing a DELETE) live inline in
|
||||
//! `dispatch` / `handle_overlay_input`.
|
||||
//! (`AttachHighlighted` spawning a `SessionTask`, a draft-pane submit firing
|
||||
//! a POST, `KillHighlighted` confirm firing a DELETE) live inline in
|
||||
//! `dispatch` / the Insert-mode pane routing.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Stdout;
|
||||
@@ -16,7 +16,7 @@ use std::time::Duration;
|
||||
|
||||
use crossterm::event::{Event as CtEvent, EventStream};
|
||||
use futures_util::StreamExt;
|
||||
use maestro_protocol::CreateSessionRequest;
|
||||
use maestro_protocol::{CreateSessionRequest, DaemonClient};
|
||||
use ratatui::backend::CrosstermBackend;
|
||||
use ratatui::Terminal;
|
||||
use uuid::Uuid;
|
||||
@@ -24,15 +24,16 @@ use uuid::Uuid;
|
||||
use crate::action::Action;
|
||||
use crate::catalog::CatalogStore;
|
||||
use crate::config::TuiConfig;
|
||||
use crate::draft::DraftInputResult;
|
||||
use crate::emulators::SessionEmulators;
|
||||
use crate::input::{canonicalise, ChordResult, ChordState, InputKey};
|
||||
use crate::input::{canonicalise, ChordResult, ChordState, ClickTracker, InputKey};
|
||||
use crate::keymap::Mode;
|
||||
use crate::overlays::{HelpOverlay, SpawnModal};
|
||||
use crate::overlays::HelpOverlay;
|
||||
use crate::pane::{Pane, PaneStatus};
|
||||
use crate::render::{draw, RegionMap, RenderInputs};
|
||||
use crate::session_task::{SessionInput, SessionTask};
|
||||
use crate::sidebar::Sidebar;
|
||||
use crate::state::{AppState, Focus, OverlayKind};
|
||||
use crate::state::{AppState, Focus, OverlayKind, PaneRef};
|
||||
use crate::tabs::TabBar;
|
||||
use crate::TuiError;
|
||||
|
||||
@@ -49,26 +50,37 @@ pub struct App {
|
||||
catalog: CatalogStore,
|
||||
emulators: SessionEmulators,
|
||||
state: AppState,
|
||||
spawn: SpawnModal,
|
||||
help: HelpOverlay,
|
||||
chord: ChordState,
|
||||
daemon_base_url: String,
|
||||
daemon: DaemonClient,
|
||||
region: RegionMap,
|
||||
last_sent_size: HashMap<Uuid, (u16, u16)>,
|
||||
http: reqwest::Client,
|
||||
clicks: ClickTracker,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for App {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("App")
|
||||
.field("daemon_base_url", &self.daemon_base_url)
|
||||
.field("daemon", &self.daemon.base())
|
||||
.field("state", &self.state)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Something a keystroke decided to do that reaches outside `AppState`.
|
||||
///
|
||||
/// `dispatch` returns these instead of performing them, so every arm is
|
||||
/// assertable without a daemon on the other end.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Effect {
|
||||
Attach(Uuid),
|
||||
Spawn(CreateSessionRequest),
|
||||
Kill(Uuid),
|
||||
Forward { id: Uuid, bytes: Vec<u8> },
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(cfg: TuiConfig, catalog: CatalogStore, daemon_base_url: String) -> Self {
|
||||
pub fn new(cfg: TuiConfig, catalog: CatalogStore, daemon: DaemonClient) -> Self {
|
||||
let chord_timeout = cfg.chord_timeout;
|
||||
let help = HelpOverlay {
|
||||
lines: render_help_lines(&cfg),
|
||||
@@ -78,16 +90,12 @@ impl App {
|
||||
catalog,
|
||||
emulators: SessionEmulators::default(),
|
||||
state: AppState::new(),
|
||||
spawn: SpawnModal::default(),
|
||||
help,
|
||||
chord: ChordState::new(chord_timeout),
|
||||
daemon_base_url,
|
||||
daemon,
|
||||
region: RegionMap::default(),
|
||||
last_sent_size: HashMap::new(),
|
||||
http: reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(5))
|
||||
.build()
|
||||
.expect("reqwest client"),
|
||||
clicks: ClickTracker::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,9 +130,12 @@ impl App {
|
||||
let Some(key) = canonicalise(&ev, |c, r| map.region_at(c, r)) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let key = self.clicks.promote(key, std::time::Instant::now());
|
||||
|
||||
// Overlay intercept first.
|
||||
if self.handle_overlay_input(&key).await == OverlayDecision::Consumed {
|
||||
let (decision, effects) = self.handle_overlay_input(&key);
|
||||
self.perform(effects).await;
|
||||
if decision == OverlayDecision::Consumed {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@@ -136,52 +147,75 @@ impl App {
|
||||
if matches!(act, Action::Quit) {
|
||||
return Ok(true);
|
||||
}
|
||||
self.dispatch(act).await;
|
||||
let effects = self.dispatch(act);
|
||||
self.perform(effects).await;
|
||||
} else if self.state.mode == Mode::Insert && matches!(self.state.focus, Focus::Pane)
|
||||
{
|
||||
self.forward_to_session(&key).await;
|
||||
// Insert mode over a focused pane: a draft eats the key
|
||||
// into its form, a session gets the raw bytes.
|
||||
let effect = if matches!(self.state.active_tab().pane, Some(PaneRef::Draft(_)))
|
||||
{
|
||||
self.handle_draft_input(&key)
|
||||
} else {
|
||||
self.forward_to_session(&key)
|
||||
};
|
||||
if let Some(effect) = effect {
|
||||
self.perform(vec![effect]).await;
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_overlay_input(&mut self, key: &InputKey) -> OverlayDecision {
|
||||
use crate::overlays::SpawnInputResult;
|
||||
match self.state.overlay.clone() {
|
||||
Some(OverlayKind::Spawn) => {
|
||||
match self.spawn.on_input(key) {
|
||||
SpawnInputResult::Consumed => {}
|
||||
SpawnInputResult::Cancel => {
|
||||
self.state.overlay = None;
|
||||
}
|
||||
SpawnInputResult::Submit => {
|
||||
self.submit_spawn().await;
|
||||
/// Carry out what `dispatch` decided. The only place in `App` that talks to
|
||||
/// the daemon.
|
||||
async fn perform(&mut self, effects: Vec<Effect>) {
|
||||
for effect in effects {
|
||||
match effect {
|
||||
Effect::Attach(id) => self.attach(id),
|
||||
Effect::Spawn(req) => self.submit_spawn(req).await,
|
||||
Effect::Kill(id) => self.submit_kill(id).await,
|
||||
Effect::Forward { id, bytes } => {
|
||||
if let Some(handle) = self.emulators.get(id) {
|
||||
let _ = handle.tx.send(SessionInput::Bytes(bytes)).await;
|
||||
}
|
||||
}
|
||||
OverlayDecision::Consumed
|
||||
}
|
||||
Some(OverlayKind::KillConfirm(id)) => match key {
|
||||
InputKey::Char { c: 'y', .. } => {
|
||||
self.state.overlay = None;
|
||||
self.submit_kill(id).await;
|
||||
OverlayDecision::Consumed
|
||||
}
|
||||
InputKey::Char { c: 'n', .. } | InputKey::Esc => {
|
||||
self.state.overlay = None;
|
||||
OverlayDecision::Consumed
|
||||
}
|
||||
_ => OverlayDecision::Consumed,
|
||||
},
|
||||
Some(OverlayKind::Help) => {
|
||||
self.state.overlay = None;
|
||||
OverlayDecision::Consumed
|
||||
}
|
||||
Some(OverlayKind::Toast(_)) | None => OverlayDecision::Pass,
|
||||
}
|
||||
}
|
||||
|
||||
async fn dispatch(&mut self, act: Action) {
|
||||
fn handle_overlay_input(&mut self, key: &InputKey) -> (OverlayDecision, Vec<Effect>) {
|
||||
match self.state.overlay().cloned() {
|
||||
Some(OverlayKind::KillConfirm(id)) => match key {
|
||||
InputKey::Char { c: 'y', .. } => {
|
||||
self.state.dismiss_overlay();
|
||||
(OverlayDecision::Consumed, vec![Effect::Kill(id)])
|
||||
}
|
||||
InputKey::Char { c: 'n', .. } | InputKey::Esc => {
|
||||
self.state.dismiss_overlay();
|
||||
(OverlayDecision::Consumed, Vec::new())
|
||||
}
|
||||
_ => (OverlayDecision::Consumed, Vec::new()),
|
||||
},
|
||||
Some(OverlayKind::Help) => {
|
||||
self.state.dismiss_overlay();
|
||||
(OverlayDecision::Consumed, Vec::new())
|
||||
}
|
||||
// A toast is informational: clear it, but let the keystroke go on
|
||||
// and do its normal job rather than being swallowed.
|
||||
Some(OverlayKind::Toast(_)) => {
|
||||
self.state.dismiss_overlay();
|
||||
(OverlayDecision::Pass, Vec::new())
|
||||
}
|
||||
None => (OverlayDecision::Pass, Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold a resolved action into `AppState` and report anything it wants done
|
||||
/// outside it. Deliberately sync and side-effect-free.
|
||||
fn dispatch(&mut self, act: Action) -> Vec<Effect> {
|
||||
let mut effects = Vec::new();
|
||||
match act {
|
||||
Action::Noop | Action::Quit => {}
|
||||
Action::EnterInsert => self.state.mode = Mode::Insert,
|
||||
@@ -203,7 +237,11 @@ impl App {
|
||||
self.state.focus = Focus::Sidebar;
|
||||
}
|
||||
Action::NewTab => self.state.new_tab(),
|
||||
Action::CloseTab => self.state.close_tab(),
|
||||
Action::CloseTab => {
|
||||
if let Some(sid) = self.state.close_tab() {
|
||||
self.release_session(sid);
|
||||
}
|
||||
}
|
||||
Action::NextTab => self.state.next_tab(),
|
||||
Action::PrevTab => self.state.prev_tab(),
|
||||
Action::GotoTab(n) => self.state.goto_tab(n),
|
||||
@@ -212,32 +250,43 @@ impl App {
|
||||
self.help = HelpOverlay {
|
||||
lines: render_help_lines(&self.cfg),
|
||||
};
|
||||
self.state.overlay = Some(OverlayKind::Help);
|
||||
}
|
||||
Action::OpenSpawnModal => {
|
||||
self.spawn = SpawnModal {
|
||||
cwd: String::new(),
|
||||
command: String::new(),
|
||||
focused_field: Default::default(),
|
||||
};
|
||||
self.state.overlay = Some(OverlayKind::Spawn);
|
||||
self.state.show_overlay(OverlayKind::Help);
|
||||
}
|
||||
Action::NewDraftPane => self.state.open_draft_pane(),
|
||||
Action::AttachHighlighted | Action::ToggleAttachHighlighted => {
|
||||
if let Some(sid) = self.pick_sidebar_target() {
|
||||
if self.emulators.get(sid).is_none() {
|
||||
let ws_url = format!("{}/api/attach/{sid}", ws_base(&self.daemon_base_url));
|
||||
let handle = SessionTask::spawn(ws_url, 24, 80);
|
||||
self.emulators.insert(sid, handle);
|
||||
}
|
||||
effects.push(Effect::Attach(sid));
|
||||
self.state.attach_to_focused(sid);
|
||||
}
|
||||
}
|
||||
Action::KillHighlighted => {
|
||||
if let Some(sid) = self.pick_sidebar_target() {
|
||||
self.state.overlay = Some(OverlayKind::KillConfirm(sid));
|
||||
self.state.show_overlay(OverlayKind::KillConfirm(sid));
|
||||
}
|
||||
}
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// Open a stream for `sid` if one isn't already running.
|
||||
fn attach(&mut self, sid: Uuid) {
|
||||
if self.emulators.get(sid).is_some() {
|
||||
return;
|
||||
}
|
||||
match self.daemon.attach_url(sid) {
|
||||
Ok(ws_url) => {
|
||||
let handle = SessionTask::spawn(ws_url, 24, 80);
|
||||
self.emulators.insert(sid, handle);
|
||||
}
|
||||
Err(e) => self.state.toast(format!("attach failed: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tear down the emulator for `sid`, aborting its WebSocket task and
|
||||
/// dropping its vt100 parser.
|
||||
fn release_session(&mut self, sid: Uuid) {
|
||||
self.emulators.remove(sid);
|
||||
self.last_sent_size.remove(&sid);
|
||||
}
|
||||
|
||||
/// Return the session under the sidebar highlight, falling back to the
|
||||
@@ -250,81 +299,50 @@ impl App {
|
||||
snap.sessions.first().map(|s| s.id)
|
||||
}
|
||||
|
||||
async fn forward_to_session(&mut self, key: &InputKey) {
|
||||
let Some(sid) = self.state.active_tab().pane else {
|
||||
return;
|
||||
};
|
||||
let Some(handle) = self.emulators.get(sid) else {
|
||||
return;
|
||||
};
|
||||
let bytes = match key {
|
||||
InputKey::Char { c, ctrl, alt, .. } => {
|
||||
let mut out = Vec::with_capacity(8);
|
||||
if *alt {
|
||||
out.push(0x1b);
|
||||
}
|
||||
if *ctrl && c.is_ascii_alphabetic() {
|
||||
out.push((c.to_ascii_uppercase() as u8) - b'@');
|
||||
} else {
|
||||
let mut b = [0u8; 4];
|
||||
let s = c.encode_utf8(&mut b);
|
||||
out.extend_from_slice(s.as_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
InputKey::Enter => b"\r".to_vec(),
|
||||
InputKey::Tab => b"\t".to_vec(),
|
||||
InputKey::Backspace => vec![0x7f],
|
||||
InputKey::Esc => vec![0x1b],
|
||||
InputKey::Up => b"\x1b[A".to_vec(),
|
||||
InputKey::Down => b"\x1b[B".to_vec(),
|
||||
InputKey::Right => b"\x1b[C".to_vec(),
|
||||
InputKey::Left => b"\x1b[D".to_vec(),
|
||||
InputKey::Mouse { .. } => return,
|
||||
};
|
||||
let _ = handle.tx.send(SessionInput::Bytes(bytes)).await;
|
||||
/// Encode a keystroke for the focused pane. `None` when there is nothing
|
||||
/// attached to send it to.
|
||||
fn forward_to_session(&mut self, key: &InputKey) -> Option<Effect> {
|
||||
let sid = self.state.active_session()?;
|
||||
self.emulators.get(sid)?;
|
||||
let bytes = encode_key(key)?;
|
||||
Some(Effect::Forward { id: sid, bytes })
|
||||
}
|
||||
|
||||
async fn submit_spawn(&mut self) {
|
||||
let cwd = std::path::PathBuf::from(self.spawn.cwd.clone());
|
||||
let req = CreateSessionRequest {
|
||||
cwd,
|
||||
command: self.spawn.command.clone(),
|
||||
/// Feed one keystroke into the active tab's draft form. Returns the spawn
|
||||
/// effect when the user accepted the form.
|
||||
fn handle_draft_input(&mut self, key: &InputKey) -> Option<Effect> {
|
||||
let PaneRef::Draft(draft) = self.state.active_tab_mut().pane.as_mut()? else {
|
||||
return None;
|
||||
};
|
||||
if draft.on_input(key) != DraftInputResult::Submit {
|
||||
return None;
|
||||
}
|
||||
Some(Effect::Spawn(CreateSessionRequest {
|
||||
cwd: std::path::PathBuf::from(draft.cwd.value().to_string()),
|
||||
command: draft.command.value().to_string(),
|
||||
env: Default::default(),
|
||||
metadata: Default::default(),
|
||||
worktree: None,
|
||||
};
|
||||
let url = format!("{}/api/sessions", self.daemon_base_url);
|
||||
match self.http.post(&url).json(&req).send().await {
|
||||
Ok(res) if res.status().is_success() => {
|
||||
self.state.overlay = None;
|
||||
}
|
||||
Ok(res) => {
|
||||
let status = res.status();
|
||||
self.state.overlay =
|
||||
Some(OverlayKind::Toast(format!("spawn failed: HTTP {status}")));
|
||||
}
|
||||
Err(e) => {
|
||||
self.state.overlay = Some(OverlayKind::Toast(format!("spawn failed: {e}")));
|
||||
}))
|
||||
}
|
||||
|
||||
async fn submit_spawn(&mut self, req: CreateSessionRequest) {
|
||||
match self.daemon.create_session(&req).await {
|
||||
Ok(session) => {
|
||||
// Fill the pane in place with the new session (web parity,
|
||||
// #57) and attach to it right away.
|
||||
let sid = session.id;
|
||||
self.state.complete_spawn(sid);
|
||||
self.attach(sid);
|
||||
}
|
||||
Err(e) => self.state.toast(format!("spawn failed: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn submit_kill(&mut self, sid: Uuid) {
|
||||
let url = format!("{}/api/sessions/{sid}", self.daemon_base_url);
|
||||
match self.http.delete(&url).send().await {
|
||||
Ok(res) if res.status().is_success() => {
|
||||
self.emulators.remove(sid);
|
||||
self.last_sent_size.remove(&sid);
|
||||
}
|
||||
Ok(res) => {
|
||||
let status = res.status();
|
||||
self.state.overlay =
|
||||
Some(OverlayKind::Toast(format!("kill failed: HTTP {status}")));
|
||||
}
|
||||
Err(e) => {
|
||||
self.state.overlay = Some(OverlayKind::Toast(format!("kill failed: {e}")));
|
||||
}
|
||||
match self.daemon.kill_session(sid).await {
|
||||
Ok(()) => self.release_session(sid),
|
||||
Err(e) => self.state.toast(format!("kill failed: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,7 +351,12 @@ impl App {
|
||||
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
|
||||
) -> Result<(), TuiError> {
|
||||
let snap = self.catalog.snapshot();
|
||||
let attached: HashSet<Uuid> = self.state.tabs.iter().filter_map(|t| t.pane).collect();
|
||||
let attached: HashSet<Uuid> = self
|
||||
.state
|
||||
.tabs
|
||||
.iter()
|
||||
.filter_map(crate::state::Tab::session)
|
||||
.collect();
|
||||
let sidebar = Sidebar {
|
||||
sessions: snap.sessions.clone(),
|
||||
highlight: self.state.sidebar_highlight,
|
||||
@@ -343,7 +366,7 @@ impl App {
|
||||
tab_names: self.state.tabs.iter().map(|t| t.name.clone()).collect(),
|
||||
active_idx: self.state.active_tab_idx,
|
||||
};
|
||||
let active_sid = self.state.active_tab().pane;
|
||||
let active_sid = self.state.active_session();
|
||||
let pane = active_sid.and_then(|sid| {
|
||||
self.emulators.get(sid).map(|h| Pane {
|
||||
screen: h.screen.clone(),
|
||||
@@ -351,13 +374,17 @@ impl App {
|
||||
focused: matches!(self.state.focus, Focus::Pane),
|
||||
})
|
||||
});
|
||||
let draft = match self.state.active_tab().pane.as_ref() {
|
||||
Some(PaneRef::Draft(d)) => Some(d),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let inputs = RenderInputs {
|
||||
sidebar: &sidebar,
|
||||
tab_bar: &tab_bar,
|
||||
pane: pane.as_ref(),
|
||||
state: &self.state,
|
||||
spawn: &self.spawn,
|
||||
draft,
|
||||
help: &self.help,
|
||||
};
|
||||
|
||||
@@ -405,13 +432,49 @@ fn visible_sidebar_order(snap: &crate::catalog::CatalogSnapshot) -> Vec<Uuid> {
|
||||
snap.sessions.iter().map(|s| s.id).collect()
|
||||
}
|
||||
|
||||
fn ws_base(http: &str) -> String {
|
||||
if let Some(rest) = http.strip_prefix("http://") {
|
||||
format!("ws://{rest}")
|
||||
} else if let Some(rest) = http.strip_prefix("https://") {
|
||||
format!("wss://{rest}")
|
||||
} else {
|
||||
http.to_string()
|
||||
/// Wire encoding for a keystroke headed to a session's PTY. `None` for keys
|
||||
/// with no byte representation (mouse events). A bracketed paste is forwarded
|
||||
/// verbatim — the remote readline reassembles it, since the pane's PTY also
|
||||
/// has bracketed paste enabled.
|
||||
fn encode_key(key: &InputKey) -> Option<Vec<u8>> {
|
||||
match key {
|
||||
InputKey::Char { c, ctrl, alt, .. } => {
|
||||
let mut out = Vec::with_capacity(8);
|
||||
if *alt {
|
||||
out.push(0x1b);
|
||||
}
|
||||
if *ctrl && c.is_ascii_alphabetic() {
|
||||
out.push((c.to_ascii_uppercase() as u8) - b'@');
|
||||
} else {
|
||||
let mut b = [0u8; 4];
|
||||
let s = c.encode_utf8(&mut b);
|
||||
out.extend_from_slice(s.as_bytes());
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
InputKey::Enter => Some(b"\r".to_vec()),
|
||||
InputKey::Tab => Some(b"\t".to_vec()),
|
||||
InputKey::BackTab => Some(b"\x1b[Z".to_vec()),
|
||||
InputKey::Backspace => Some(vec![0x7f]),
|
||||
InputKey::Esc => Some(vec![0x1b]),
|
||||
InputKey::Up => Some(b"\x1b[A".to_vec()),
|
||||
InputKey::Down => Some(b"\x1b[B".to_vec()),
|
||||
InputKey::Right => Some(b"\x1b[C".to_vec()),
|
||||
InputKey::Left => Some(b"\x1b[D".to_vec()),
|
||||
InputKey::Home => Some(b"\x1b[H".to_vec()),
|
||||
InputKey::End => Some(b"\x1b[F".to_vec()),
|
||||
InputKey::Delete => Some(b"\x1b[3~".to_vec()),
|
||||
InputKey::Paste(text) => {
|
||||
// Wrap in the DECSET 2004 markers. Raw bytes look like typed keys
|
||||
// to an app that enabled bracketed paste, so a multi-line paste
|
||||
// would execute line by line instead of arriving as one block.
|
||||
let mut out = Vec::with_capacity(text.len() + 12);
|
||||
out.extend_from_slice(b"\x1b[200~");
|
||||
out.extend_from_slice(text.as_bytes());
|
||||
out.extend_from_slice(b"\x1b[201~");
|
||||
Some(out)
|
||||
}
|
||||
InputKey::Mouse { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,45 +510,227 @@ mod tests {
|
||||
|
||||
fn make_app() -> App {
|
||||
let cfg = TuiConfig::load(&TuiSection::default()).unwrap();
|
||||
App::new(cfg, CatalogStore::default(), "http://127.0.0.1:7070".into())
|
||||
App::new(
|
||||
cfg,
|
||||
CatalogStore::default(),
|
||||
DaemonClient::new("http://127.0.0.1:7070"),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enter_insert_then_leave() {
|
||||
#[test]
|
||||
fn enter_insert_then_leave() {
|
||||
let mut app = make_app();
|
||||
assert_eq!(app.state.mode, Mode::Normal);
|
||||
app.dispatch(Action::EnterInsert).await;
|
||||
app.dispatch(Action::EnterInsert);
|
||||
assert_eq!(app.state.mode, Mode::Insert);
|
||||
app.dispatch(Action::LeaveInsert).await;
|
||||
app.dispatch(Action::LeaveInsert);
|
||||
assert_eq!(app.state.mode, Mode::Normal);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn new_tab_action_extends_tabs() {
|
||||
#[test]
|
||||
fn new_tab_action_extends_tabs() {
|
||||
let mut app = make_app();
|
||||
app.dispatch(Action::NewTab).await;
|
||||
app.dispatch(Action::NewTab).await;
|
||||
app.dispatch(Action::NewTab);
|
||||
app.dispatch(Action::NewTab);
|
||||
assert_eq!(app.state.tabs.len(), 3);
|
||||
app.dispatch(Action::CloseTab).await;
|
||||
app.dispatch(Action::CloseTab);
|
||||
assert_eq!(app.state.tabs.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn show_help_opens_overlay() {
|
||||
#[test]
|
||||
fn show_help_opens_overlay() {
|
||||
let mut app = make_app();
|
||||
app.dispatch(Action::ShowHelp).await;
|
||||
assert!(matches!(app.state.overlay, Some(OverlayKind::Help)));
|
||||
app.dispatch(Action::ShowHelp);
|
||||
assert!(matches!(app.state.overlay(), Some(OverlayKind::Help)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_spawn_modal_sets_overlay() {
|
||||
#[test]
|
||||
fn new_draft_pane_opens_a_focused_draft_in_the_empty_tab() {
|
||||
let mut app = make_app();
|
||||
app.dispatch(Action::OpenSpawnModal).await;
|
||||
assert!(matches!(app.state.overlay, Some(OverlayKind::Spawn)));
|
||||
app.dispatch(Action::NewDraftPane);
|
||||
assert!(matches!(
|
||||
app.state.active_tab().pane,
|
||||
Some(PaneRef::Draft(_))
|
||||
));
|
||||
assert_eq!(app.state.focus, Focus::Pane);
|
||||
assert_eq!(app.state.mode, Mode::Insert);
|
||||
assert!(app.state.overlay().is_none(), "no overlay involved");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kill_highlighted_opens_confirm() {
|
||||
/// A tab already showing a session gets a new tab for the draft.
|
||||
#[test]
|
||||
fn new_draft_pane_over_a_session_opens_a_new_tab() {
|
||||
let sid = Uuid::from_u128(10);
|
||||
let mut app = app_with_highlighted_session(sid);
|
||||
app.dispatch(Action::AttachHighlighted);
|
||||
|
||||
app.dispatch(Action::NewDraftPane);
|
||||
assert_eq!(app.state.tabs.len(), 2);
|
||||
assert_eq!(app.state.active_tab_idx, 1);
|
||||
assert!(matches!(
|
||||
app.state.active_tab().pane,
|
||||
Some(PaneRef::Draft(_))
|
||||
));
|
||||
assert_eq!(app.state.tabs[0].session(), Some(sid));
|
||||
}
|
||||
|
||||
/// Seed the catalog with one session and highlight it.
|
||||
fn app_with_highlighted_session(sid: Uuid) -> App {
|
||||
use chrono::Utc;
|
||||
use maestro_protocol::{CatalogEvent, Session, SessionStatus};
|
||||
let mut app = make_app();
|
||||
app.catalog.apply_event(CatalogEvent::Snapshot {
|
||||
sessions: vec![Session {
|
||||
id: sid,
|
||||
command: "bash".into(),
|
||||
cwd: std::path::PathBuf::from("/"),
|
||||
env: Default::default(),
|
||||
metadata: Default::default(),
|
||||
status: SessionStatus::Running,
|
||||
created_at: Utc::now(),
|
||||
foreground: None,
|
||||
activity: Default::default(),
|
||||
last_activity_at: Utc::now(),
|
||||
current_cwd: None,
|
||||
}],
|
||||
});
|
||||
app.dispatch(Action::SidebarNext);
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_highlighted_asks_for_an_attach() {
|
||||
let sid = Uuid::from_u128(11);
|
||||
let mut app = app_with_highlighted_session(sid);
|
||||
assert_eq!(
|
||||
app.dispatch(Action::AttachHighlighted),
|
||||
vec![Effect::Attach(sid)]
|
||||
);
|
||||
assert_eq!(app.state.active_tab().session(), Some(sid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirming_a_kill_asks_for_the_kill() {
|
||||
let sid = Uuid::from_u128(12);
|
||||
let mut app = app_with_highlighted_session(sid);
|
||||
app.dispatch(Action::KillHighlighted);
|
||||
|
||||
let (decision, effects) = app.handle_overlay_input(&InputKey::Char {
|
||||
c: 'y',
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
});
|
||||
assert_eq!(decision, OverlayDecision::Consumed);
|
||||
assert_eq!(effects, vec![Effect::Kill(sid)]);
|
||||
assert!(app.state.overlay().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declining_a_kill_asks_for_nothing() {
|
||||
let sid = Uuid::from_u128(13);
|
||||
let mut app = app_with_highlighted_session(sid);
|
||||
app.dispatch(Action::KillHighlighted);
|
||||
|
||||
let (decision, effects) = app.handle_overlay_input(&InputKey::Esc);
|
||||
assert_eq!(decision, OverlayDecision::Consumed);
|
||||
assert!(effects.is_empty());
|
||||
assert!(app.state.overlay().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_into_the_draft_then_enter_carries_the_typed_fields() {
|
||||
let mut app = make_app();
|
||||
app.dispatch(Action::NewDraftPane);
|
||||
|
||||
for c in "/srv/work".chars() {
|
||||
app.handle_draft_input(&InputKey::char(c));
|
||||
}
|
||||
app.handle_draft_input(&InputKey::Tab); // cwd → command
|
||||
for c in "claude".chars() {
|
||||
app.handle_draft_input(&InputKey::char(c));
|
||||
}
|
||||
app.handle_draft_input(&InputKey::Tab); // command → submit
|
||||
|
||||
match app.handle_draft_input(&InputKey::Enter) {
|
||||
Some(Effect::Spawn(req)) => {
|
||||
assert_eq!(req.cwd, std::path::PathBuf::from("/srv/work"));
|
||||
assert_eq!(req.command, "claude");
|
||||
}
|
||||
other => panic!("expected a Spawn effect, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keys fed while no draft exists must be ignored, not panic.
|
||||
#[test]
|
||||
fn draft_input_is_a_no_op_without_a_draft() {
|
||||
let mut app = make_app();
|
||||
assert!(app.handle_draft_input(&InputKey::char('x')).is_none());
|
||||
}
|
||||
|
||||
/// Regression: `Toast` returned `Pass` and nothing ever cleared it, so a
|
||||
/// failure message stayed on screen until another overlay replaced it.
|
||||
#[test]
|
||||
fn a_toast_is_dismissed_by_the_next_key_without_eating_it() {
|
||||
let mut app = make_app();
|
||||
app.state.toast("spawn failed: nope");
|
||||
|
||||
let (decision, effects) = app.handle_overlay_input(&InputKey::Char {
|
||||
c: 'j',
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
});
|
||||
assert_eq!(
|
||||
decision,
|
||||
OverlayDecision::Pass,
|
||||
"the keystroke should still reach the keymap"
|
||||
);
|
||||
assert!(effects.is_empty());
|
||||
assert!(app.state.overlay().is_none(), "the toast must be gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarding_is_a_no_op_without_an_attached_pane() {
|
||||
let mut app = make_app();
|
||||
assert!(app.forward_to_session(&InputKey::Enter).is_none());
|
||||
}
|
||||
|
||||
/// A draft pane is not a session: forwarding must not try to reach it.
|
||||
#[test]
|
||||
fn forwarding_is_a_no_op_with_a_draft_pane() {
|
||||
let mut app = make_app();
|
||||
app.dispatch(Action::NewDraftPane);
|
||||
assert!(app.forward_to_session(&InputKey::Enter).is_none());
|
||||
}
|
||||
|
||||
/// Regression review fix: `Paste(_)` used to be silently dropped, so a
|
||||
/// paste into an attached session vanished once bracketed paste was
|
||||
/// enabled. It also has to keep its DECSET 2004 markers — without them a
|
||||
/// remote shell reads the payload as typed keys and runs a multi-line
|
||||
/// paste line by line.
|
||||
#[test]
|
||||
fn a_bracketed_paste_reaches_the_session_with_its_markers() {
|
||||
assert_eq!(
|
||||
encode_key(&InputKey::Paste("cd /tmp/foo\nls".into())),
|
||||
Some(b"\x1b[200~cd /tmp/foo\nls\x1b[201~".to_vec())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mouse_events_have_no_wire_encoding() {
|
||||
use crate::input::{MouseKind, Region};
|
||||
assert!(encode_key(&InputKey::Mouse {
|
||||
kind: MouseKind::Click,
|
||||
region: Region::Pane,
|
||||
col: 3,
|
||||
row: 4,
|
||||
})
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kill_highlighted_opens_confirm() {
|
||||
use chrono::Utc;
|
||||
use maestro_protocol::{CatalogEvent, Session, SessionStatus};
|
||||
let mut app = make_app();
|
||||
@@ -506,7 +751,7 @@ mod tests {
|
||||
current_cwd: None,
|
||||
}],
|
||||
});
|
||||
app.dispatch(Action::KillHighlighted).await;
|
||||
assert!(matches!(app.state.overlay, Some(OverlayKind::KillConfirm(s)) if s == sid));
|
||||
app.dispatch(Action::KillHighlighted);
|
||||
assert!(matches!(app.state.overlay(), Some(OverlayKind::KillConfirm(s)) if *s == sid));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ const DEFAULT_NORMAL: &[(&str, &str)] = &[
|
||||
("up", "SidebarPrev"),
|
||||
// Catalog actions
|
||||
("enter", "AttachHighlighted"),
|
||||
("s", "OpenSpawnModal"),
|
||||
("s", "NewDraftPane"),
|
||||
("x", "KillHighlighted"),
|
||||
// Tabs
|
||||
("ctrl-t", "NewTab"),
|
||||
@@ -155,6 +155,10 @@ mod tests {
|
||||
cfg.keymap.resolve(Mode::Normal, "g t"),
|
||||
Some(Action::NextTab),
|
||||
);
|
||||
assert_eq!(
|
||||
cfg.keymap.resolve(Mode::Normal, "s"),
|
||||
Some(Action::NewDraftPane),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Draft pane — the spawn form living in an ordinary pane (issue #63).
|
||||
//!
|
||||
//! An empty pane renders a [`DraftPane`] instead of nothing; submitting hands
|
||||
//! the caller a built request and the pane is replaced with the new session,
|
||||
//! matching the web client's inline draft panes (#57). Field editing goes
|
||||
//! through [`crate::text_input::TextInput`]; Tab / BackTab walk the fields.
|
||||
//!
|
||||
//! Scope note: presets, the project list, generated names, and the worktree
|
||||
//! section land with issues #64/#65 — this is cwd + command only.
|
||||
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Borders, Paragraph};
|
||||
use ratatui::Frame;
|
||||
|
||||
use crate::input::InputKey;
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DraftField {
|
||||
#[default]
|
||||
Cwd,
|
||||
Command,
|
||||
Submit,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct DraftPane {
|
||||
pub cwd: crate::text_input::TextInput,
|
||||
pub command: crate::text_input::TextInput,
|
||||
pub focused_field: DraftField,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DraftInputResult {
|
||||
Consumed,
|
||||
Submit,
|
||||
}
|
||||
|
||||
impl DraftPane {
|
||||
pub fn next_field(&mut self) {
|
||||
self.focused_field = match self.focused_field {
|
||||
DraftField::Cwd => DraftField::Command,
|
||||
DraftField::Command => DraftField::Submit,
|
||||
DraftField::Submit => DraftField::Cwd,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn prev_field(&mut self) {
|
||||
self.focused_field = match self.focused_field {
|
||||
DraftField::Cwd => DraftField::Submit,
|
||||
DraftField::Command => DraftField::Cwd,
|
||||
DraftField::Submit => DraftField::Command,
|
||||
};
|
||||
}
|
||||
|
||||
/// Handle one keystroke while this draft owns input (Insert mode, pane
|
||||
/// focused). Returns [`DraftInputResult::Submit`] when the user accepts;
|
||||
/// the caller fires the POST and replaces the draft with the session.
|
||||
pub fn on_input(&mut self, key: &InputKey) -> DraftInputResult {
|
||||
match key {
|
||||
InputKey::Tab => {
|
||||
self.next_field();
|
||||
DraftInputResult::Consumed
|
||||
}
|
||||
InputKey::BackTab => {
|
||||
self.prev_field();
|
||||
DraftInputResult::Consumed
|
||||
}
|
||||
InputKey::Enter => match self.focused_field {
|
||||
DraftField::Submit => DraftInputResult::Submit,
|
||||
_ => {
|
||||
self.next_field();
|
||||
DraftInputResult::Consumed
|
||||
}
|
||||
},
|
||||
// Everything else — characters, motion, editing, paste — goes to
|
||||
// the focused field's text input.
|
||||
other => {
|
||||
match self.focused_field {
|
||||
DraftField::Cwd => self.cwd.handle_key(other),
|
||||
DraftField::Command => self.command.handle_key(other),
|
||||
DraftField::Submit => {}
|
||||
}
|
||||
DraftInputResult::Consumed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw into the pane area. `pane_focused` gates the field highlight and
|
||||
/// cursor placement the same way a session pane hides its cursor when
|
||||
/// unfocused.
|
||||
pub fn render(&self, f: &mut Frame, area: Rect, pane_focused: bool) {
|
||||
let block = Block::default().title(" draft ").borders(Borders::ALL);
|
||||
let inner = block.inner(area);
|
||||
f.render_widget(block, area);
|
||||
let rows = Layout::vertical([
|
||||
Constraint::Length(2),
|
||||
Constraint::Length(2),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.split(inner);
|
||||
|
||||
let style_for = |field: DraftField| {
|
||||
if pane_focused && self.focused_field == field {
|
||||
Style::default().add_modifier(Modifier::REVERSED)
|
||||
} else {
|
||||
Style::default()
|
||||
}
|
||||
};
|
||||
|
||||
// Each text field renders through the shared `TextInput`, which
|
||||
// handles horizontal scrolling and reports where the terminal cursor
|
||||
// belongs. Label is fixed-width 8 chars + 1 space = column 9.
|
||||
let label = |text: &str| Paragraph::new(Line::from(Span::raw(format!("{text:8} "))));
|
||||
f.render_widget(label("cwd:"), rows[0]);
|
||||
f.render_widget(label("command:"), rows[1]);
|
||||
let draw_field =
|
||||
|f: &mut Frame, input: &crate::text_input::TextInput, row: Rect, style: Style| -> u16 {
|
||||
let area = Rect {
|
||||
x: row.x.saturating_add(9),
|
||||
y: row.y,
|
||||
width: row.width.saturating_sub(9),
|
||||
height: 1,
|
||||
};
|
||||
input.render(area, f.buffer_mut(), style)
|
||||
};
|
||||
let cwd_col = draw_field(f, &self.cwd, rows[0], style_for(DraftField::Cwd));
|
||||
let cmd_col = draw_field(f, &self.command, rows[1], style_for(DraftField::Command));
|
||||
|
||||
f.render_widget(
|
||||
Paragraph::new(Line::from(vec![Span::styled(
|
||||
"[ Spawn ]",
|
||||
style_for(DraftField::Submit),
|
||||
)])),
|
||||
rows[2],
|
||||
);
|
||||
|
||||
if pane_focused {
|
||||
match self.focused_field {
|
||||
DraftField::Cwd => f.set_cursor_position((cwd_col, rows[0].y)),
|
||||
DraftField::Command => f.set_cursor_position((cmd_col, rows[1].y)),
|
||||
DraftField::Submit => {
|
||||
// The submit button is indicated by the REVERSED style; no
|
||||
// cursor placement.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ratatui::backend::TestBackend;
|
||||
use ratatui::Terminal;
|
||||
|
||||
fn render_to_string(w: u16, h: u16, draw: impl FnOnce(&mut Frame)) -> String {
|
||||
let backend = TestBackend::new(w, h);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal.draw(draw).unwrap();
|
||||
let buf = terminal.backend().buffer().clone();
|
||||
let mut out = String::new();
|
||||
for y in 0..buf.area.height {
|
||||
for x in 0..buf.area.width {
|
||||
out.push_str(buf[(x, y)].symbol());
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_pane_renders_field_labels_and_values() {
|
||||
let draft = DraftPane {
|
||||
cwd: crate::text_input::TextInput::with_value("/x"),
|
||||
command: crate::text_input::TextInput::with_value("bash"),
|
||||
focused_field: DraftField::Cwd,
|
||||
};
|
||||
let rendered = render_to_string(80, 20, |f| draft.render(f, f.area(), true));
|
||||
for s in ["cwd", "command", "draft", "Spawn", "/x", "bash"] {
|
||||
assert!(rendered.contains(s), "missing {s:?}:\n{rendered}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_rotation_wraps_in_both_directions() {
|
||||
let mut draft = DraftPane::default();
|
||||
assert_eq!(draft.focused_field, DraftField::Cwd);
|
||||
draft.next_field();
|
||||
assert_eq!(draft.focused_field, DraftField::Command);
|
||||
draft.next_field();
|
||||
assert_eq!(draft.focused_field, DraftField::Submit);
|
||||
draft.next_field();
|
||||
assert_eq!(draft.focused_field, DraftField::Cwd);
|
||||
draft.prev_field();
|
||||
assert_eq!(draft.focused_field, DraftField::Submit);
|
||||
|
||||
draft.on_input(&InputKey::BackTab);
|
||||
assert_eq!(draft.focused_field, DraftField::Command);
|
||||
draft.on_input(&InputKey::Tab);
|
||||
draft.on_input(&InputKey::Tab);
|
||||
assert_eq!(draft.focused_field, DraftField::Cwd);
|
||||
}
|
||||
|
||||
/// Editing keys must reach the focused field's text input, not a bare
|
||||
/// String — this is what gives the operator cursor motion and word ops.
|
||||
#[test]
|
||||
fn editing_keys_reach_the_focused_text_input() {
|
||||
let mut draft = DraftPane::default();
|
||||
assert_eq!(draft.focused_field, DraftField::Cwd);
|
||||
for k in [
|
||||
InputKey::char('/'),
|
||||
InputKey::char('t'),
|
||||
InputKey::char('m'),
|
||||
InputKey::char('p'),
|
||||
] {
|
||||
draft.on_input(&k);
|
||||
}
|
||||
draft.on_input(&InputKey::Left);
|
||||
draft.on_input(&InputKey::Backspace);
|
||||
assert_eq!(draft.cwd.value(), "/tp");
|
||||
|
||||
// Tab to command, then a paste and ctrl-w land there, not in cwd.
|
||||
draft.on_input(&InputKey::Tab);
|
||||
assert_eq!(draft.focused_field, DraftField::Command);
|
||||
draft.on_input(&InputKey::Paste("/tmp/foo".into()));
|
||||
assert_eq!(draft.command.value(), "/tmp/foo");
|
||||
draft.on_input(&InputKey::ctrl_char('w'));
|
||||
assert_eq!(draft.command.value(), "");
|
||||
assert_eq!(draft.cwd.value(), "/tp", "cwd untouched while unfocused");
|
||||
}
|
||||
|
||||
/// Enter walks forward until the submit field, where it submits.
|
||||
#[test]
|
||||
fn enter_walks_fields_then_submits_from_submit() {
|
||||
let mut draft = DraftPane::default();
|
||||
assert_eq!(draft.on_input(&InputKey::Enter), DraftInputResult::Consumed);
|
||||
assert_eq!(draft.focused_field, DraftField::Command);
|
||||
assert_eq!(draft.on_input(&InputKey::Enter), DraftInputResult::Consumed);
|
||||
assert_eq!(draft.focused_field, DraftField::Submit);
|
||||
assert_eq!(draft.on_input(&InputKey::Enter), DraftInputResult::Submit);
|
||||
}
|
||||
|
||||
/// The terminal cursor must sit right after the typed text in the focused
|
||||
/// field (label is 8 chars + 1 space, block border takes column 0).
|
||||
#[test]
|
||||
fn render_places_the_cursor_after_the_typed_text_when_focused() {
|
||||
let draft = DraftPane {
|
||||
cwd: crate::text_input::TextInput::with_value("abc"),
|
||||
..DraftPane::default()
|
||||
};
|
||||
let backend = TestBackend::new(80, 20);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal.draw(|f| draft.render(f, f.area(), true)).unwrap();
|
||||
let pos = terminal.get_cursor_position().unwrap();
|
||||
assert_eq!(pos, ratatui::layout::Position::new(1 + 9 + 3, 1));
|
||||
|
||||
// Unfocused pane: no field highlight either.
|
||||
let rendered_unfocused = render_to_string(80, 20, |f| draft.render(f, f.area(), false));
|
||||
let backend = TestBackend::new(80, 20);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal.draw(|f| draft.render(f, f.area(), false)).unwrap();
|
||||
let buf = terminal.backend().buffer();
|
||||
assert!(
|
||||
!buf.content()
|
||||
.iter()
|
||||
.any(|c| c.modifier.contains(ratatui::style::Modifier::REVERSED)),
|
||||
"unfocused draft must not highlight fields:\n{rendered_unfocused}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,11 +27,19 @@ pub enum InputKey {
|
||||
Esc,
|
||||
Enter,
|
||||
Tab,
|
||||
/// Shift-Tab. crossterm reports it as its own key code, not a modified Tab.
|
||||
BackTab,
|
||||
Backspace,
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
Home,
|
||||
End,
|
||||
Delete,
|
||||
/// Bracketed paste: crossterm delivers the whole payload as one event, so
|
||||
/// text fields can insert it as a single operation.
|
||||
Paste(String),
|
||||
Mouse {
|
||||
kind: MouseKind,
|
||||
region: Region,
|
||||
@@ -54,11 +62,9 @@ pub enum MouseKind {
|
||||
/// NAP-280); for now only the enum is needed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Region {
|
||||
Sidebar,
|
||||
SidebarRow,
|
||||
Tab,
|
||||
Pane,
|
||||
SplitDivider,
|
||||
Modal,
|
||||
Unknown,
|
||||
}
|
||||
@@ -120,11 +126,18 @@ impl InputKey {
|
||||
InputKey::Esc => "esc".into(),
|
||||
InputKey::Enter => "enter".into(),
|
||||
InputKey::Tab => "tab".into(),
|
||||
InputKey::BackTab => "backtab".into(),
|
||||
InputKey::Backspace => "backspace".into(),
|
||||
InputKey::Up => "up".into(),
|
||||
InputKey::Down => "down".into(),
|
||||
InputKey::Left => "left".into(),
|
||||
InputKey::Right => "right".into(),
|
||||
InputKey::Home => "home".into(),
|
||||
InputKey::End => "end".into(),
|
||||
InputKey::Delete => "delete".into(),
|
||||
// Pastes are not bindable; the canonical form exists only to
|
||||
// satisfy exhaustiveness and never round-trips through `parse`.
|
||||
InputKey::Paste(_) => "paste".into(),
|
||||
InputKey::Mouse { kind, region, .. } => {
|
||||
let k = match kind {
|
||||
MouseKind::Click => "click",
|
||||
@@ -134,11 +147,9 @@ impl InputKey {
|
||||
MouseKind::ScrollDown => "scrolldown",
|
||||
};
|
||||
let r = match region {
|
||||
Region::Sidebar => "sidebar",
|
||||
Region::SidebarRow => "sidebar-row",
|
||||
Region::Tab => "tab",
|
||||
Region::Pane => "pane",
|
||||
Region::SplitDivider => "split-divider",
|
||||
Region::Modal => "modal",
|
||||
Region::Unknown => "unknown",
|
||||
};
|
||||
@@ -168,11 +179,9 @@ impl InputKey {
|
||||
other => return Err(InputParseError::UnknownMouseKind(other.into())),
|
||||
};
|
||||
let region = match r {
|
||||
"sidebar" => Region::Sidebar,
|
||||
"sidebar-row" => Region::SidebarRow,
|
||||
"tab" => Region::Tab,
|
||||
"pane" => Region::Pane,
|
||||
"split-divider" => Region::SplitDivider,
|
||||
"modal" => Region::Modal,
|
||||
"unknown" => Region::Unknown,
|
||||
other => return Err(InputParseError::UnknownRegion(other.into())),
|
||||
@@ -188,11 +197,15 @@ impl InputKey {
|
||||
"esc" => return Ok(InputKey::Esc),
|
||||
"enter" => return Ok(InputKey::Enter),
|
||||
"tab" => return Ok(InputKey::Tab),
|
||||
"backtab" => return Ok(InputKey::BackTab),
|
||||
"backspace" => return Ok(InputKey::Backspace),
|
||||
"up" => return Ok(InputKey::Up),
|
||||
"down" => return Ok(InputKey::Down),
|
||||
"left" => return Ok(InputKey::Left),
|
||||
"right" => return Ok(InputKey::Right),
|
||||
"home" => return Ok(InputKey::Home),
|
||||
"end" => return Ok(InputKey::End),
|
||||
"delete" => return Ok(InputKey::Delete),
|
||||
_ => {}
|
||||
}
|
||||
// Modifier chain: ctrl-, alt-, shift- prefixes, then a single char.
|
||||
@@ -258,14 +271,19 @@ where
|
||||
KeyCode::Esc => InputKey::Esc,
|
||||
KeyCode::Enter => InputKey::Enter,
|
||||
KeyCode::Tab => InputKey::Tab,
|
||||
KeyCode::BackTab => InputKey::BackTab,
|
||||
KeyCode::Backspace => InputKey::Backspace,
|
||||
KeyCode::Up => InputKey::Up,
|
||||
KeyCode::Down => InputKey::Down,
|
||||
KeyCode::Left => InputKey::Left,
|
||||
KeyCode::Right => InputKey::Right,
|
||||
KeyCode::Home => InputKey::Home,
|
||||
KeyCode::End => InputKey::End,
|
||||
KeyCode::Delete => InputKey::Delete,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
CtEvent::Paste(text) => Some(InputKey::Paste(text.clone())),
|
||||
CtEvent::Mouse(MouseEvent {
|
||||
kind, column, row, ..
|
||||
}) => {
|
||||
@@ -288,6 +306,63 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// How long after a click a second click at the same cell counts as a
|
||||
/// double-click. Matches the common desktop default.
|
||||
pub const DOUBLE_CLICK_WINDOW: Duration = Duration::from_millis(400);
|
||||
|
||||
/// Remembers the last click so a second one at the same cell can be promoted to
|
||||
/// [`MouseKind::DblClick`].
|
||||
///
|
||||
/// Kept out of [`canonicalise`], which stays a pure function of one event.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ClickTracker {
|
||||
last: Option<(u16, u16, Instant)>,
|
||||
}
|
||||
|
||||
impl ClickTracker {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Upgrade a `Click` to a `DblClick` when it *immediately* follows another
|
||||
/// click at the same cell inside [`DOUBLE_CLICK_WINDOW`].
|
||||
///
|
||||
/// Anything else passes through and clears the pending click: two clicks
|
||||
/// with a drag or a keystroke between them are two clicks, however fast.
|
||||
///
|
||||
/// A promoted click also resets the tracker, so three rapid clicks are a
|
||||
/// click then a double-click, not two double-clicks.
|
||||
pub fn promote(&mut self, key: InputKey, now: Instant) -> InputKey {
|
||||
let InputKey::Mouse {
|
||||
kind: MouseKind::Click,
|
||||
region,
|
||||
col,
|
||||
row,
|
||||
} = key
|
||||
else {
|
||||
self.last = None;
|
||||
return key;
|
||||
};
|
||||
|
||||
let is_double = matches!(
|
||||
self.last,
|
||||
Some((c, r, at))
|
||||
if c == col && r == row && now.duration_since(at) <= DOUBLE_CLICK_WINDOW
|
||||
);
|
||||
if is_double {
|
||||
self.last = None;
|
||||
return InputKey::Mouse {
|
||||
kind: MouseKind::DblClick,
|
||||
region,
|
||||
col,
|
||||
row,
|
||||
};
|
||||
}
|
||||
self.last = Some((col, row, now));
|
||||
key
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of feeding one key into [`ChordState`]. `Pending` = held because the
|
||||
/// current sequence is a strict prefix of some known binding; `Resolved` =
|
||||
/// dispatch this canonical string against the keymap.
|
||||
@@ -358,6 +433,151 @@ impl ChordState {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn click(col: u16, row: u16) -> InputKey {
|
||||
InputKey::Mouse {
|
||||
kind: MouseKind::Click,
|
||||
region: Region::SidebarRow,
|
||||
col,
|
||||
row,
|
||||
}
|
||||
}
|
||||
|
||||
/// The shipped default binds `mouse:dblclick(sidebar-row)`. Nothing could
|
||||
/// produce a DblClick, so that binding could never fire.
|
||||
#[test]
|
||||
fn a_second_click_at_the_same_cell_becomes_a_double_click() {
|
||||
let mut t = ClickTracker::new();
|
||||
let t0 = Instant::now();
|
||||
|
||||
assert_eq!(t.promote(click(3, 4), t0), click(3, 4));
|
||||
assert_eq!(
|
||||
t.promote(click(3, 4), t0 + Duration::from_millis(100)),
|
||||
InputKey::Mouse {
|
||||
kind: MouseKind::DblClick,
|
||||
region: Region::SidebarRow,
|
||||
col: 3,
|
||||
row: 4,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_second_click_stays_a_click() {
|
||||
let mut t = ClickTracker::new();
|
||||
let t0 = Instant::now();
|
||||
t.promote(click(3, 4), t0);
|
||||
let late = t0 + DOUBLE_CLICK_WINDOW + Duration::from_millis(1);
|
||||
assert_eq!(t.promote(click(3, 4), late), click(3, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_click_elsewhere_stays_a_click() {
|
||||
let mut t = ClickTracker::new();
|
||||
let t0 = Instant::now();
|
||||
t.promote(click(3, 4), t0);
|
||||
assert_eq!(
|
||||
t.promote(click(9, 4), t0 + Duration::from_millis(10)),
|
||||
click(9, 4)
|
||||
);
|
||||
}
|
||||
|
||||
/// Three fast clicks are click, double-click, click — not two doubles.
|
||||
#[test]
|
||||
fn a_promoted_click_resets_the_tracker() {
|
||||
let mut t = ClickTracker::new();
|
||||
let t0 = Instant::now();
|
||||
t.promote(click(1, 1), t0);
|
||||
let second = t.promote(click(1, 1), t0 + Duration::from_millis(50));
|
||||
assert!(matches!(
|
||||
second,
|
||||
InputKey::Mouse {
|
||||
kind: MouseKind::DblClick,
|
||||
..
|
||||
}
|
||||
));
|
||||
let third = t.promote(click(1, 1), t0 + Duration::from_millis(100));
|
||||
assert_eq!(third, click(1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_click_events_pass_through_untouched() {
|
||||
let mut t = ClickTracker::new();
|
||||
assert_eq!(t.promote(InputKey::Enter, Instant::now()), InputKey::Enter);
|
||||
}
|
||||
|
||||
/// A drag between two clicks means the user dragged, not double-clicked —
|
||||
/// even at the same cell and well inside the window.
|
||||
#[test]
|
||||
fn a_drag_between_two_clicks_breaks_the_double() {
|
||||
let mut t = ClickTracker::new();
|
||||
let t0 = Instant::now();
|
||||
t.promote(click(3, 4), t0);
|
||||
|
||||
let drag = InputKey::Mouse {
|
||||
kind: MouseKind::Drag,
|
||||
region: Region::SidebarRow,
|
||||
col: 3,
|
||||
row: 4,
|
||||
};
|
||||
assert_eq!(
|
||||
t.promote(drag.clone(), t0 + Duration::from_millis(20)),
|
||||
drag
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
t.promote(click(3, 4), t0 + Duration::from_millis(40)),
|
||||
click(3, 4),
|
||||
"a drag must clear the pending click"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keystroke_between_two_clicks_breaks_the_double() {
|
||||
let mut t = ClickTracker::new();
|
||||
let t0 = Instant::now();
|
||||
t.promote(click(3, 4), t0);
|
||||
t.promote(InputKey::Enter, t0 + Duration::from_millis(20));
|
||||
|
||||
assert_eq!(
|
||||
t.promote(click(3, 4), t0 + Duration::from_millis(40)),
|
||||
click(3, 4)
|
||||
);
|
||||
}
|
||||
|
||||
/// A scroll also counts as an intervening event.
|
||||
#[test]
|
||||
fn a_scroll_between_two_clicks_breaks_the_double() {
|
||||
let mut t = ClickTracker::new();
|
||||
let t0 = Instant::now();
|
||||
t.promote(click(3, 4), t0);
|
||||
let scroll = InputKey::Mouse {
|
||||
kind: MouseKind::ScrollUp,
|
||||
region: Region::SidebarRow,
|
||||
col: 3,
|
||||
row: 4,
|
||||
};
|
||||
t.promote(scroll, t0 + Duration::from_millis(20));
|
||||
|
||||
assert_eq!(
|
||||
t.promote(click(3, 4), t0 + Duration::from_millis(40)),
|
||||
click(3, 4)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn back_tab_round_trips_through_the_canonical_form() {
|
||||
assert_eq!(InputKey::BackTab.canonical(), "backtab");
|
||||
assert_eq!(InputKey::parse("backtab").unwrap(), InputKey::BackTab);
|
||||
}
|
||||
|
||||
/// The parser must not accept region names the renderer cannot produce.
|
||||
#[test]
|
||||
fn unproducible_region_names_are_rejected() {
|
||||
assert!(InputKey::parse("mouse:click(sidebar)").is_err());
|
||||
assert!(InputKey::parse("mouse:click(split-divider)").is_err());
|
||||
assert!(InputKey::parse("mouse:click(sidebar-row)").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_round_trips_simple_chars() {
|
||||
for s in ["a", "ctrl-a", "ctrl-w", "alt-x", "shift-A"] {
|
||||
@@ -377,12 +597,25 @@ mod tests {
|
||||
"down",
|
||||
"left",
|
||||
"right",
|
||||
"home",
|
||||
"end",
|
||||
"delete",
|
||||
] {
|
||||
let k = InputKey::parse(s).unwrap();
|
||||
assert_eq!(k.canonical(), s, "round-trip {s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A bracketed paste must arrive as one key carrying the whole payload,
|
||||
/// not a burst of per-character keys.
|
||||
#[test]
|
||||
fn canonicalise_paste_event_carries_the_whole_payload() {
|
||||
use crossterm::event::Event as CtEvent;
|
||||
let ev = CtEvent::Paste("/srv/work/maestro".into());
|
||||
let k = canonicalise(&ev, |_, _| Region::Unknown).unwrap();
|
||||
assert_eq!(k, InputKey::Paste("/srv/work/maestro".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_round_trips_mouse() {
|
||||
let s = "mouse:click(pane)";
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod app;
|
||||
pub mod catalog;
|
||||
pub mod cli;
|
||||
pub mod config;
|
||||
pub mod draft;
|
||||
pub mod emulators;
|
||||
pub mod input;
|
||||
pub mod keymap;
|
||||
@@ -18,10 +19,12 @@ pub mod sidebar;
|
||||
pub mod state;
|
||||
pub mod tabs;
|
||||
pub mod terminal;
|
||||
pub mod text_input;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use maestro_protocol::DaemonClient;
|
||||
use ratatui::backend::CrosstermBackend;
|
||||
use ratatui::Terminal;
|
||||
|
||||
@@ -37,7 +40,7 @@ pub struct RunConfig {
|
||||
/// No trailing slash.
|
||||
pub daemon_url: String,
|
||||
/// Explicit `--config <path>` override from the umbrella binary's global
|
||||
/// flag. When `None`, [`maestro_config::resolve_config_path`] picks the
|
||||
/// flag. When `None`, [`maestro_config::default_config_path`] picks the
|
||||
/// default (`$MAESTRO_CONFIG` or `~/.config/maestro/config.toml`).
|
||||
pub config_path: Option<PathBuf>,
|
||||
}
|
||||
@@ -62,13 +65,20 @@ pub async fn run(cfg: RunConfig) -> Result<(), TuiError> {
|
||||
let base_url = cfg.daemon_url.trim_end_matches('/').to_string();
|
||||
|
||||
// Health check — fail fast if no daemon is reachable.
|
||||
health_check(&base_url).await?;
|
||||
health_check(&DaemonClient::with_timeouts(
|
||||
&base_url,
|
||||
HEALTH_TIMEOUT,
|
||||
HEALTH_TIMEOUT,
|
||||
))
|
||||
.await?;
|
||||
|
||||
let daemon = DaemonClient::with_timeouts(&base_url, REQUEST_TIMEOUT, REQUEST_TIMEOUT);
|
||||
|
||||
// Load runtime config: explicit `--config <path>` wins, then
|
||||
// `$MAESTRO_CONFIG`, then the platform default. Missing file is fine —
|
||||
// we fall back to shipped defaults.
|
||||
let cfg_path = cfg.config_path.clone().map(Ok).unwrap_or_else(|| {
|
||||
maestro_config::resolve_config_path().map_err(|e| TuiError::Config(e.to_string()))
|
||||
maestro_config::default_config_path().map_err(|e| TuiError::Config(e.to_string()))
|
||||
});
|
||||
let cfg_file = match cfg_path {
|
||||
Ok(path) => maestro_config::MaestroConfigFile::load(&path)
|
||||
@@ -78,7 +88,9 @@ pub async fn run(cfg: RunConfig) -> Result<(), TuiError> {
|
||||
let tui_cfg = TuiConfig::load(&cfg_file.tui).map_err(|e| TuiError::Config(e.to_string()))?;
|
||||
|
||||
let catalog = CatalogStore::default();
|
||||
let ws_url = format!("{}/api/events", ws_base(&base_url));
|
||||
let ws_url = daemon
|
||||
.events_url()
|
||||
.map_err(|e| TuiError::Config(e.to_string()))?;
|
||||
let bg_catalog = catalog.clone();
|
||||
tokio::spawn(async move { bg_catalog.run_events_loop(ws_url).await });
|
||||
|
||||
@@ -92,33 +104,32 @@ pub async fn run(cfg: RunConfig) -> Result<(), TuiError> {
|
||||
let backend = CrosstermBackend::new(std::io::stdout());
|
||||
let mut terminal = Terminal::new(backend).map_err(|e| TuiError::Terminal(e.to_string()))?;
|
||||
|
||||
let app = App::new(tui_cfg, catalog, base_url);
|
||||
let app = App::new(tui_cfg, catalog, daemon);
|
||||
app.run(&mut terminal).await
|
||||
}
|
||||
|
||||
async fn health_check(base_url: &str) -> Result<(), TuiError> {
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_millis(500))
|
||||
.build()
|
||||
.expect("reqwest client");
|
||||
let url = format!("{base_url}/api/info");
|
||||
for _ in 0..3 {
|
||||
if let Ok(res) = client.get(&url).send().await {
|
||||
if res.status().is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
Err(TuiError::DaemonUnreachable(base_url.to_string()))
|
||||
}
|
||||
/// Startup probe budget, applied to connect *and* the whole request: the user is
|
||||
/// staring at a terminal, so an unreachable daemon must fail in under a second.
|
||||
const HEALTH_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
fn ws_base(http: &str) -> String {
|
||||
if let Some(rest) = http.strip_prefix("http://") {
|
||||
format!("ws://{rest}")
|
||||
} else if let Some(rest) = http.strip_prefix("https://") {
|
||||
format!("wss://{rest}")
|
||||
} else {
|
||||
http.to_string()
|
||||
/// Budget for the TUI's own calls once it is up. Tighter than the client
|
||||
/// default — a spawn or kill that stalls should surface as a toast, not hang
|
||||
/// the interface.
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
async fn health_check(daemon: &DaemonClient) -> Result<(), TuiError> {
|
||||
for _ in 0..3 {
|
||||
if let Ok(info) = daemon.daemon_info().await {
|
||||
if !maestro_protocol::is_compatible(&info.version) {
|
||||
tracing::warn!(
|
||||
daemon = %info.version,
|
||||
client = %maestro_protocol::PROTOCOL_VERSION,
|
||||
"daemon protocol version differs from this client's",
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
tokio::time::sleep(HEALTH_TIMEOUT).await;
|
||||
}
|
||||
Err(TuiError::DaemonUnreachable(daemon.base().to_string()))
|
||||
}
|
||||
|
||||
@@ -1,159 +1,16 @@
|
||||
//! Overlay widgets: spawn modal, kill-confirm prompt, help overlay,
|
||||
//! transient toast.
|
||||
//! Overlay widgets: kill-confirm prompt, help overlay, transient toast.
|
||||
//!
|
||||
//! The spawn form is no longer an overlay (issue #63) — it lives in draft
|
||||
//! panes ([`crate::draft::DraftPane`]).
|
||||
//!
|
||||
//! All overlays are centered popups drawn over the rest of the UI; the
|
||||
//! `Clear` widget wipes the underlying buffer before drawing.
|
||||
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph};
|
||||
use ratatui::Frame;
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SpawnField {
|
||||
#[default]
|
||||
Cwd,
|
||||
Command,
|
||||
Submit,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct SpawnModal {
|
||||
pub cwd: String,
|
||||
pub command: String,
|
||||
pub focused_field: SpawnField,
|
||||
}
|
||||
|
||||
impl SpawnModal {
|
||||
pub fn next_field(&mut self) {
|
||||
self.focused_field = match self.focused_field {
|
||||
SpawnField::Cwd => SpawnField::Command,
|
||||
SpawnField::Command => SpawnField::Submit,
|
||||
SpawnField::Submit => SpawnField::Cwd,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn prev_field(&mut self) {
|
||||
self.focused_field = match self.focused_field {
|
||||
SpawnField::Cwd => SpawnField::Submit,
|
||||
SpawnField::Command => SpawnField::Cwd,
|
||||
SpawnField::Submit => SpawnField::Command,
|
||||
};
|
||||
}
|
||||
|
||||
/// Handle one keystroke while this modal owns input. Returns
|
||||
/// [`SpawnInputResult::Submit`] when the user accepts; the caller fires
|
||||
/// the POST and dismisses the modal.
|
||||
pub fn on_input(&mut self, key: &crate::input::InputKey) -> SpawnInputResult {
|
||||
use crate::input::InputKey;
|
||||
match key {
|
||||
InputKey::Tab => {
|
||||
self.next_field();
|
||||
SpawnInputResult::Consumed
|
||||
}
|
||||
InputKey::Esc => SpawnInputResult::Cancel,
|
||||
InputKey::Enter => match self.focused_field {
|
||||
SpawnField::Submit => SpawnInputResult::Submit,
|
||||
_ => {
|
||||
self.next_field();
|
||||
SpawnInputResult::Consumed
|
||||
}
|
||||
},
|
||||
InputKey::Char { c, .. } => {
|
||||
match self.focused_field {
|
||||
SpawnField::Cwd => self.cwd.push(*c),
|
||||
SpawnField::Command => self.command.push(*c),
|
||||
SpawnField::Submit => {}
|
||||
}
|
||||
SpawnInputResult::Consumed
|
||||
}
|
||||
InputKey::Backspace => {
|
||||
match self.focused_field {
|
||||
SpawnField::Cwd => {
|
||||
self.cwd.pop();
|
||||
}
|
||||
SpawnField::Command => {
|
||||
self.command.pop();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
SpawnInputResult::Consumed
|
||||
}
|
||||
_ => SpawnInputResult::Consumed,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(&self, f: &mut Frame, parent: Rect) {
|
||||
let area = centered(parent, 60, 10);
|
||||
f.render_widget(Clear, area);
|
||||
let block = Block::default().title(" spawn ").borders(Borders::ALL);
|
||||
let inner = block.inner(area);
|
||||
f.render_widget(block, area);
|
||||
let rows = Layout::vertical([
|
||||
Constraint::Length(2),
|
||||
Constraint::Length(2),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.split(inner);
|
||||
let highlight = |field: SpawnField| {
|
||||
if self.focused_field == field {
|
||||
Style::default().add_modifier(Modifier::REVERSED)
|
||||
} else {
|
||||
Style::default()
|
||||
}
|
||||
};
|
||||
let field_row = |label: &str, value: &str, style: Style| {
|
||||
Paragraph::new(Line::from(vec![
|
||||
ratatui::text::Span::raw(format!("{label:8} ")),
|
||||
ratatui::text::Span::styled(value.to_string(), style),
|
||||
]))
|
||||
};
|
||||
f.render_widget(
|
||||
field_row("cwd:", &self.cwd, highlight(SpawnField::Cwd)),
|
||||
rows[0],
|
||||
);
|
||||
f.render_widget(
|
||||
field_row("command:", &self.command, highlight(SpawnField::Command)),
|
||||
rows[1],
|
||||
);
|
||||
f.render_widget(
|
||||
Paragraph::new(Line::from(vec![ratatui::text::Span::styled(
|
||||
"[ Spawn ]",
|
||||
highlight(SpawnField::Submit),
|
||||
)])),
|
||||
rows[2],
|
||||
);
|
||||
|
||||
// Place the cursor at the end of the currently-focused text field so
|
||||
// the user can see where their typing lands. Label is fixed-width
|
||||
// 8 chars + 1 space = column 9 inside the row.
|
||||
let cursor_col_for = |value: &str| -> u16 {
|
||||
inner
|
||||
.x
|
||||
.saturating_add(9)
|
||||
.saturating_add(value.chars().count() as u16)
|
||||
};
|
||||
match self.focused_field {
|
||||
SpawnField::Cwd => f.set_cursor_position((cursor_col_for(&self.cwd), rows[0].y)),
|
||||
SpawnField::Command => {
|
||||
f.set_cursor_position((cursor_col_for(&self.command), rows[1].y))
|
||||
}
|
||||
SpawnField::Submit => {
|
||||
// The submit button is indicated by the REVERSED style; no
|
||||
// cursor placement.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SpawnInputResult {
|
||||
Consumed,
|
||||
Cancel,
|
||||
Submit,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct KillConfirm {
|
||||
pub label: String,
|
||||
@@ -260,33 +117,6 @@ mod tests {
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_modal_renders_field_labels() {
|
||||
let modal = SpawnModal {
|
||||
cwd: "/x".into(),
|
||||
command: "bash".into(),
|
||||
focused_field: SpawnField::Cwd,
|
||||
};
|
||||
let rendered = render_to_string(80, 20, |f| modal.render(f, f.area()));
|
||||
for s in ["cwd", "command", "Spawn", "/x", "bash"] {
|
||||
assert!(rendered.contains(s), "missing {s:?}:\n{rendered}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawn_modal_field_rotation() {
|
||||
let mut modal = SpawnModal::default();
|
||||
assert_eq!(modal.focused_field, SpawnField::Cwd);
|
||||
modal.next_field();
|
||||
assert_eq!(modal.focused_field, SpawnField::Command);
|
||||
modal.next_field();
|
||||
assert_eq!(modal.focused_field, SpawnField::Submit);
|
||||
modal.next_field();
|
||||
assert_eq!(modal.focused_field, SpawnField::Cwd);
|
||||
modal.prev_field();
|
||||
assert_eq!(modal.focused_field, SpawnField::Submit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kill_confirm_renders_prompt() {
|
||||
let modal = KillConfirm {
|
||||
@@ -304,11 +134,11 @@ mod tests {
|
||||
let help = HelpOverlay {
|
||||
lines: vec![
|
||||
"i EnterInsert".into(),
|
||||
"s OpenSpawnModal".into(),
|
||||
"s NewDraftPane".into(),
|
||||
],
|
||||
};
|
||||
let rendered = render_to_string(80, 12, |f| help.render(f, f.area()));
|
||||
assert!(rendered.contains("EnterInsert"));
|
||||
assert!(rendered.contains("OpenSpawnModal"));
|
||||
assert!(rendered.contains("NewDraftPane"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use ratatui::Frame;
|
||||
|
||||
use crate::input::Region;
|
||||
use crate::keymap::Mode;
|
||||
use crate::overlays::{HelpOverlay, KillConfirm, SpawnModal, Toast};
|
||||
use crate::overlays::{HelpOverlay, KillConfirm, Toast};
|
||||
use crate::pane::Pane;
|
||||
use crate::sidebar::Sidebar;
|
||||
use crate::state::{AppState, Focus, OverlayKind};
|
||||
@@ -63,8 +63,9 @@ pub struct RenderInputs<'a> {
|
||||
pub sidebar: &'a Sidebar,
|
||||
pub tab_bar: &'a TabBar,
|
||||
pub pane: Option<&'a Pane>,
|
||||
/// Inline spawn form when the active tab's pane is a draft (issue #63).
|
||||
pub draft: Option<&'a crate::draft::DraftPane>,
|
||||
pub state: &'a AppState,
|
||||
pub spawn: &'a SpawnModal,
|
||||
pub help: &'a HelpOverlay,
|
||||
}
|
||||
|
||||
@@ -131,17 +132,16 @@ pub fn draw(f: &mut Frame, inputs: RenderInputs<'_>) -> RegionMap {
|
||||
if let Some(p) = inputs.pane {
|
||||
p.render(f, pane_area);
|
||||
}
|
||||
if let Some(d) = inputs.draft {
|
||||
d.render(f, pane_area, pane_focused);
|
||||
}
|
||||
map.pane = Some(pane_area);
|
||||
|
||||
// Status bar — always visible, never eclipsed by overlays so the user can
|
||||
// always see the current mode + key hints.
|
||||
render_status_bar(f, status_area, inputs.state);
|
||||
|
||||
match &inputs.state.overlay {
|
||||
Some(OverlayKind::Spawn) => {
|
||||
inputs.spawn.render(f, area);
|
||||
map.modal = Some(area);
|
||||
}
|
||||
match inputs.state.overlay() {
|
||||
Some(OverlayKind::KillConfirm(id)) => {
|
||||
let kc = KillConfirm {
|
||||
label: id.to_string(),
|
||||
@@ -186,7 +186,7 @@ fn render_status_bar(f: &mut Frame, area: Rect, state: &AppState) {
|
||||
Focus::Pane => "pane",
|
||||
};
|
||||
let hint = match state.mode {
|
||||
Mode::Normal => "j/k: nav • enter: attach • s: spawn • ?: help • ^Wq: quit",
|
||||
Mode::Normal => "j/k: nav • enter: attach • s: new draft • ?: help • ^Wq: quit",
|
||||
Mode::Insert => "^a: back to normal",
|
||||
};
|
||||
let mode_style = match state.mode {
|
||||
@@ -266,4 +266,57 @@ mod tests {
|
||||
assert_eq!(map.region_at(15, 10), Region::Modal);
|
||||
assert_eq!(map.region_at(3, 12), Region::SidebarRow); // outside modal
|
||||
}
|
||||
|
||||
/// Issue #63: an empty pane is a draft — the frame must show the spawn
|
||||
/// form where the terminal would otherwise be.
|
||||
#[test]
|
||||
fn a_draft_pane_renders_the_spawn_form_in_its_pane_area() {
|
||||
use crate::overlays::HelpOverlay;
|
||||
use crate::state::PaneRef;
|
||||
use std::collections::HashSet;
|
||||
|
||||
let mut state = AppState::new();
|
||||
state.open_draft_pane();
|
||||
let draft = match &state.tabs[0].pane {
|
||||
Some(PaneRef::Draft(d)) => d,
|
||||
other => panic!("expected a draft pane, got {other:?}"),
|
||||
};
|
||||
let sidebar = Sidebar {
|
||||
sessions: Vec::new(),
|
||||
highlight: None,
|
||||
attached: HashSet::new(),
|
||||
};
|
||||
let tab_bar = TabBar {
|
||||
tab_names: vec!["1".into()],
|
||||
active_idx: 0,
|
||||
};
|
||||
let help = HelpOverlay { lines: Vec::new() };
|
||||
let inputs = RenderInputs {
|
||||
sidebar: &sidebar,
|
||||
tab_bar: &tab_bar,
|
||||
pane: None,
|
||||
draft: Some(draft),
|
||||
state: &state,
|
||||
help: &help,
|
||||
};
|
||||
|
||||
let backend = ratatui::backend::TestBackend::new(80, 24);
|
||||
let mut terminal = ratatui::Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| {
|
||||
draw(f, inputs);
|
||||
})
|
||||
.unwrap();
|
||||
let buf = terminal.backend().buffer().clone();
|
||||
let mut out = String::new();
|
||||
for y in 0..buf.area.height {
|
||||
for x in 0..buf.area.width {
|
||||
out.push_str(buf[(x, y)].symbol());
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
for s in ["draft", "cwd:", "command:", "[ Spawn ]"] {
|
||||
assert!(out.contains(s), "missing {s:?}:\n{out}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+176
-12
@@ -1,14 +1,16 @@
|
||||
//! `AppState` — the top-level mutable state of the running TUI.
|
||||
//!
|
||||
//! v1 keeps it small on purpose: a list of tabs (each bound to at most one
|
||||
//! session), an active tab index, focus split between sidebar and pane, the
|
||||
//! current input mode, and an optional overlay (spawn modal, kill confirm,
|
||||
//! help, transient toast).
|
||||
//! session or a draft form), an active tab index, focus split between sidebar
|
||||
//! and pane, the current input mode, and an optional overlay (kill confirm,
|
||||
//! help, transient toast). The spawn form is no longer an overlay — an empty
|
||||
//! pane is a draft pane (issue #63).
|
||||
//!
|
||||
//! v1.5 will replace `Tab::pane: Option<SessionId>` with a split tree.
|
||||
//! v1.5 will replace `Tab::pane`'s single slot with a split tree.
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::draft::DraftPane;
|
||||
use crate::keymap::Mode;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -17,15 +19,31 @@ pub enum Focus {
|
||||
Pane,
|
||||
}
|
||||
|
||||
/// What a tab's pane slot holds: a live session, or an inline draft form.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum PaneRef {
|
||||
Session(Uuid),
|
||||
Draft(DraftPane),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Tab {
|
||||
pub name: String,
|
||||
pub pane: Option<Uuid>,
|
||||
pub pane: Option<PaneRef>,
|
||||
}
|
||||
|
||||
impl Tab {
|
||||
/// The session this tab shows, if it shows one. Draft panes have none.
|
||||
pub fn session(&self) -> Option<Uuid> {
|
||||
match &self.pane {
|
||||
Some(PaneRef::Session(sid)) => Some(*sid),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum OverlayKind {
|
||||
Spawn,
|
||||
KillConfirm(Uuid),
|
||||
Help,
|
||||
Toast(String),
|
||||
@@ -39,7 +57,11 @@ pub struct AppState {
|
||||
pub mode: Mode,
|
||||
pub sidebar_visible: bool,
|
||||
pub sidebar_highlight: Option<Uuid>,
|
||||
pub overlay: Option<OverlayKind>,
|
||||
/// Private: every transition goes through [`AppState::show_overlay`],
|
||||
/// [`AppState::dismiss_overlay`] or [`AppState::toast`]. Poking the field
|
||||
/// from four call sites is what left a toast on screen with no way to
|
||||
/// clear it.
|
||||
overlay: Option<OverlayKind>,
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
@@ -64,6 +86,24 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn overlay(&self) -> Option<&OverlayKind> {
|
||||
self.overlay.as_ref()
|
||||
}
|
||||
|
||||
pub fn show_overlay(&mut self, kind: OverlayKind) {
|
||||
self.overlay = Some(kind);
|
||||
}
|
||||
|
||||
/// Clear whatever overlay is up. Returns true if one was showing.
|
||||
pub fn dismiss_overlay(&mut self) -> bool {
|
||||
self.overlay.take().is_some()
|
||||
}
|
||||
|
||||
/// Surface a transient message. Replaces any overlay currently up.
|
||||
pub fn toast(&mut self, message: impl Into<String>) {
|
||||
self.overlay = Some(OverlayKind::Toast(message.into()));
|
||||
}
|
||||
|
||||
pub fn active_tab(&self) -> &Tab {
|
||||
&self.tabs[self.active_tab_idx]
|
||||
}
|
||||
@@ -83,14 +123,23 @@ impl AppState {
|
||||
|
||||
/// Drop the active tab. No-op if it's the only one — there must always
|
||||
/// be at least one tab.
|
||||
pub fn close_tab(&mut self) {
|
||||
///
|
||||
/// Returns the session that tab was showing, if any, so the caller can
|
||||
/// release its emulator. Without that the tab's WebSocket task and vt100
|
||||
/// parser outlive the tab forever. A draft pane holds no session and
|
||||
/// releases nothing.
|
||||
pub fn close_tab(&mut self) -> Option<Uuid> {
|
||||
if self.tabs.len() <= 1 {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
self.tabs.remove(self.active_tab_idx);
|
||||
let closed = self.tabs.remove(self.active_tab_idx);
|
||||
if self.active_tab_idx >= self.tabs.len() {
|
||||
self.active_tab_idx = self.tabs.len() - 1;
|
||||
}
|
||||
let sid = closed.session()?;
|
||||
// Only release it if no other tab still shows the same session.
|
||||
let still_shown = self.tabs.iter().any(|t| t.session() == Some(sid));
|
||||
(!still_shown).then_some(sid)
|
||||
}
|
||||
|
||||
pub fn next_tab(&mut self) {
|
||||
@@ -118,11 +167,37 @@ impl AppState {
|
||||
/// drop straight into Insert mode so keystrokes go to the session
|
||||
/// without an extra `i` press. The leader returns to Normal.
|
||||
pub fn attach_to_focused(&mut self, session_id: Uuid) {
|
||||
self.active_tab_mut().pane = Some(session_id);
|
||||
self.active_tab_mut().pane = Some(PaneRef::Session(session_id));
|
||||
self.focus = Focus::Pane;
|
||||
self.mode = Mode::Insert;
|
||||
}
|
||||
|
||||
/// Open a draft form in a pane (issue #63): reuse the empty active pane,
|
||||
/// otherwise open a fresh tab for it — v1 has no split tree, so "split"
|
||||
/// means a new tab. Focus lands in the pane, Insert mode on, so typing
|
||||
/// starts immediately, same flow as [`Self::attach_to_focused`].
|
||||
pub fn open_draft_pane(&mut self) {
|
||||
if self.active_tab().pane.is_some() {
|
||||
self.new_tab();
|
||||
}
|
||||
self.active_tab_mut().pane = Some(PaneRef::Draft(DraftPane::default()));
|
||||
self.focus = Focus::Pane;
|
||||
self.mode = Mode::Insert;
|
||||
}
|
||||
|
||||
/// A draft submit succeeded: replace whatever the active tab showed with
|
||||
/// the new session in place, matching the web client's behaviour (#57).
|
||||
pub fn complete_spawn(&mut self, sid: Uuid) {
|
||||
self.active_tab_mut().pane = Some(PaneRef::Session(sid));
|
||||
self.focus = Focus::Pane;
|
||||
self.mode = Mode::Insert;
|
||||
}
|
||||
|
||||
/// The session shown by the active tab's pane, if any.
|
||||
pub fn active_session(&self) -> Option<Uuid> {
|
||||
self.active_tab().session()
|
||||
}
|
||||
|
||||
/// Move the sidebar highlight by `delta` (positive = down) within the
|
||||
/// given ordered list of selectable session ids. Wraps. No-op on empty.
|
||||
pub fn move_sidebar_highlight(&mut self, order: &[Uuid], delta: i32) {
|
||||
@@ -259,7 +334,7 @@ mod tests {
|
||||
let mut state = AppState::new();
|
||||
let sid = Uuid::from_u128(7);
|
||||
state.attach_to_focused(sid);
|
||||
assert_eq!(state.tabs[0].pane, Some(sid));
|
||||
assert_eq!(state.tabs[0].session(), Some(sid));
|
||||
assert_eq!(state.focus, Focus::Pane);
|
||||
// The user expects to type into the session right away; the leader
|
||||
// (default ctrl-a) is the way back.
|
||||
@@ -277,4 +352,93 @@ mod tests {
|
||||
// Doesn't force focus back; sidebar shown but focus stays where it was.
|
||||
assert_eq!(state.focus, Focus::Pane);
|
||||
}
|
||||
|
||||
/// The emulator leak: a closed tab's session must come back so the caller
|
||||
/// can abort its WebSocket task.
|
||||
#[test]
|
||||
fn close_tab_reports_the_session_it_dropped() {
|
||||
let mut state = AppState::new();
|
||||
let sid = Uuid::from_u128(3);
|
||||
state.new_tab();
|
||||
state.active_tab_mut().pane = Some(PaneRef::Session(sid));
|
||||
|
||||
assert_eq!(state.close_tab(), Some(sid));
|
||||
}
|
||||
|
||||
/// ...but not while another tab still shows it.
|
||||
#[test]
|
||||
fn close_tab_keeps_a_session_another_tab_still_shows() {
|
||||
let mut state = AppState::new();
|
||||
let sid = Uuid::from_u128(4);
|
||||
state.active_tab_mut().pane = Some(PaneRef::Session(sid));
|
||||
state.new_tab();
|
||||
state.active_tab_mut().pane = Some(PaneRef::Session(sid));
|
||||
|
||||
assert_eq!(state.close_tab(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_tab_is_a_no_op_on_the_last_tab() {
|
||||
let mut state = AppState::new();
|
||||
state.active_tab_mut().pane = Some(PaneRef::Session(Uuid::from_u128(5)));
|
||||
assert_eq!(state.close_tab(), None);
|
||||
assert_eq!(state.tabs.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dismiss_overlay_reports_whether_one_was_showing() {
|
||||
let mut state = AppState::new();
|
||||
assert!(!state.dismiss_overlay());
|
||||
state.toast("boom");
|
||||
assert!(state.dismiss_overlay());
|
||||
assert!(state.overlay().is_none());
|
||||
}
|
||||
|
||||
/// Issue #63: `s` over an empty pane turns that pane into a draft —
|
||||
/// focused, Insert mode on, typing starts immediately.
|
||||
#[test]
|
||||
fn open_draft_reuses_the_empty_active_pane() {
|
||||
let mut state = AppState::new();
|
||||
state.open_draft_pane();
|
||||
assert!(matches!(state.active_tab().pane, Some(PaneRef::Draft(_))));
|
||||
assert_eq!(state.focus, Focus::Pane);
|
||||
assert_eq!(state.mode, Mode::Insert);
|
||||
assert_eq!(state.tabs.len(), 1);
|
||||
}
|
||||
|
||||
/// A tab already showing a session gets a fresh tab for the draft; v1
|
||||
/// has no split tree, so a new tab is the "split".
|
||||
#[test]
|
||||
fn open_draft_over_a_session_opens_a_new_tab() {
|
||||
let mut state = AppState::new();
|
||||
state.attach_to_focused(Uuid::from_u128(9));
|
||||
state.open_draft_pane();
|
||||
assert_eq!(state.tabs.len(), 2);
|
||||
assert_eq!(state.active_tab_idx, 1);
|
||||
assert!(matches!(state.active_tab().pane, Some(PaneRef::Draft(_))));
|
||||
// The session tab is untouched.
|
||||
assert_eq!(state.tabs[0].session(), Some(Uuid::from_u128(9)));
|
||||
}
|
||||
|
||||
/// Web parity (#57): submitting fills the pane in place.
|
||||
#[test]
|
||||
fn complete_spawn_replaces_the_draft_with_the_session() {
|
||||
let mut state = AppState::new();
|
||||
state.open_draft_pane();
|
||||
let sid = Uuid::from_u128(21);
|
||||
state.complete_spawn(sid);
|
||||
assert_eq!(state.active_tab().session(), Some(sid));
|
||||
assert_eq!(state.focus, Focus::Pane);
|
||||
assert_eq!(state.mode, Mode::Insert);
|
||||
}
|
||||
|
||||
/// A closed draft tab holds no session, so nothing is released.
|
||||
#[test]
|
||||
fn close_tab_reports_nothing_for_a_draft_pane() {
|
||||
let mut state = AppState::new();
|
||||
state.open_draft_pane();
|
||||
state.new_tab();
|
||||
state.active_tab_idx = 0;
|
||||
assert_eq!(state.close_tab(), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
|
||||
use std::io;
|
||||
|
||||
use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
|
||||
use crossterm::event::{
|
||||
DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
|
||||
};
|
||||
use crossterm::execute;
|
||||
use crossterm::terminal::{
|
||||
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
|
||||
@@ -26,7 +28,12 @@ impl TerminalGuard {
|
||||
pub fn enter() -> Result<Self, TerminalError> {
|
||||
enable_raw_mode()?;
|
||||
let mut out = io::stdout();
|
||||
execute!(out, EnterAlternateScreen, EnableMouseCapture)?;
|
||||
execute!(
|
||||
out,
|
||||
EnterAlternateScreen,
|
||||
EnableMouseCapture,
|
||||
EnableBracketedPaste
|
||||
)?;
|
||||
Ok(TerminalGuard)
|
||||
}
|
||||
|
||||
@@ -34,7 +41,12 @@ impl TerminalGuard {
|
||||
/// call it without producing weird errors.
|
||||
fn restore() {
|
||||
let mut out = io::stdout();
|
||||
let _ = execute!(out, DisableMouseCapture, LeaveAlternateScreen);
|
||||
let _ = execute!(
|
||||
out,
|
||||
DisableBracketedPaste,
|
||||
DisableMouseCapture,
|
||||
LeaveAlternateScreen
|
||||
);
|
||||
let _ = disable_raw_mode();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
//! Single-line text-input primitive shared by every TUI form field.
|
||||
//!
|
||||
//! Owns a `String`, a character-indexed cursor, and horizontal scroll state.
|
||||
//! All editing goes through [`TextInput::handle_key`] so callers feed the same
|
||||
//! canonical [`InputKey`] stream the rest of the app uses; bracketed paste
|
||||
//! arrives as one [`InputKey::Paste`] and is inserted as a single operation.
|
||||
//!
|
||||
//! This is the one piece of the TUI form layer that unit-tests without a
|
||||
//! terminal: drive it with `InputKey` sequences and inspect value/cursor.
|
||||
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::Style;
|
||||
|
||||
use crate::input::InputKey;
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct TextInput {
|
||||
value: String,
|
||||
/// Cursor position as a char offset into `value`.
|
||||
cursor: usize,
|
||||
/// Char offset of the leftmost visible cell. A `Cell` so `render` can
|
||||
/// re-clamp it without `&mut self` — widgets are drawn through shared
|
||||
/// references in this codebase.
|
||||
scroll: std::cell::Cell<usize>,
|
||||
}
|
||||
|
||||
impl TextInput {
|
||||
pub fn with_value(value: impl Into<String>) -> Self {
|
||||
let mut input = Self {
|
||||
value: value.into(),
|
||||
..Self::default()
|
||||
};
|
||||
input.cursor = input.value.chars().count();
|
||||
input
|
||||
}
|
||||
|
||||
pub fn value(&self) -> &str {
|
||||
&self.value
|
||||
}
|
||||
|
||||
pub fn cursor(&self) -> usize {
|
||||
self.cursor
|
||||
}
|
||||
|
||||
/// Char offset of the leftmost visible cell; only meaningful after
|
||||
/// [`TextInput::render`] has clamped it to the field width.
|
||||
pub fn scroll_offset(&self) -> usize {
|
||||
self.scroll.get()
|
||||
}
|
||||
|
||||
/// Insert `text` at the cursor as one operation. Used both for typed
|
||||
/// characters and for whole bracketed-paste payloads.
|
||||
pub fn insert(&mut self, text: &str) {
|
||||
let at = self.byte_offset(self.cursor);
|
||||
self.value.insert_str(at, text);
|
||||
self.cursor += text.chars().count();
|
||||
}
|
||||
|
||||
pub fn handle_key(&mut self, key: &InputKey) {
|
||||
match key {
|
||||
InputKey::Char {
|
||||
c,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
..
|
||||
} => self.insert(&c.to_string()),
|
||||
InputKey::Char {
|
||||
c: 'w', ctrl: true, ..
|
||||
} => self.delete_word_backwards(),
|
||||
InputKey::Char {
|
||||
c: 'k', ctrl: true, ..
|
||||
} => self.kill_to_end(),
|
||||
// Emacs-style word motion; ctrl-arrow reaches us as a plain
|
||||
// Left/Right today, so these are the dependable binding.
|
||||
InputKey::Char {
|
||||
c: 'b', ctrl: true, ..
|
||||
} => self.cursor = self.word_left(),
|
||||
InputKey::Char {
|
||||
c: 'f', ctrl: true, ..
|
||||
} => self.cursor = self.word_right(),
|
||||
InputKey::Left => {
|
||||
self.cursor = self.cursor.saturating_sub(1);
|
||||
}
|
||||
InputKey::Right => {
|
||||
if self.cursor < self.value.chars().count() {
|
||||
self.cursor += 1;
|
||||
}
|
||||
}
|
||||
InputKey::Home => self.cursor = 0,
|
||||
InputKey::End => self.cursor = self.value.chars().count(),
|
||||
InputKey::Backspace => {
|
||||
if self.cursor > 0 {
|
||||
let at = self.byte_offset(self.cursor - 1);
|
||||
let end = self.byte_offset(self.cursor);
|
||||
self.value.replace_range(at..end, "");
|
||||
self.cursor -= 1;
|
||||
}
|
||||
}
|
||||
InputKey::Delete => {
|
||||
if self.cursor < self.value.chars().count() {
|
||||
let at = self.byte_offset(self.cursor);
|
||||
let end = self.byte_offset(self.cursor + 1);
|
||||
self.value.replace_range(at..end, "");
|
||||
}
|
||||
}
|
||||
InputKey::Paste(text) => self.insert(text),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw into `area` (expected one row tall), scrolling horizontally so the
|
||||
/// cursor stays visible, and return the screen column where the caller
|
||||
/// should place the terminal cursor.
|
||||
pub fn render(&self, area: Rect, buf: &mut Buffer, style: Style) -> u16 {
|
||||
let width = area.width as usize;
|
||||
let len = self.value.chars().count();
|
||||
let scroll = self.scroll.get().min(len);
|
||||
let scroll = if self.cursor < scroll {
|
||||
self.cursor
|
||||
} else if width > 0 && self.cursor.saturating_sub(scroll) >= width {
|
||||
self.cursor + 1 - width
|
||||
} else {
|
||||
scroll
|
||||
};
|
||||
self.scroll.set(scroll);
|
||||
for (col, c) in self.value.chars().skip(scroll).take(width).enumerate() {
|
||||
buf[(area.x + col as u16, area.y)]
|
||||
.set_symbol(&c.to_string())
|
||||
.set_style(style);
|
||||
}
|
||||
area.x + self.cursor.saturating_sub(scroll) as u16
|
||||
}
|
||||
|
||||
fn byte_offset(&self, char_index: usize) -> usize {
|
||||
self.value
|
||||
.char_indices()
|
||||
.nth(char_index)
|
||||
.map(|(b, _)| b)
|
||||
.unwrap_or(self.value.len())
|
||||
}
|
||||
|
||||
fn is_word_char(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_'
|
||||
}
|
||||
|
||||
/// Start of the word before the cursor, skipping any separators first —
|
||||
/// emacs `backward-word`.
|
||||
fn word_left(&self) -> usize {
|
||||
let chars: Vec<char> = self.value.chars().collect();
|
||||
let mut i = self.cursor;
|
||||
while i > 0 && !Self::is_word_char(chars[i - 1]) {
|
||||
i -= 1;
|
||||
}
|
||||
while i > 0 && Self::is_word_char(chars[i - 1]) {
|
||||
i -= 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// Start of the word after the cursor, skipping the rest of the current
|
||||
/// word first — emacs `forward-word`.
|
||||
fn word_right(&self) -> usize {
|
||||
let chars: Vec<char> = self.value.chars().collect();
|
||||
let len = chars.len();
|
||||
let mut i = self.cursor;
|
||||
while i < len && !Self::is_word_char(chars[i]) {
|
||||
i += 1;
|
||||
}
|
||||
while i < len && Self::is_word_char(chars[i]) {
|
||||
i += 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn kill_to_end(&mut self) {
|
||||
let at = self.byte_offset(self.cursor);
|
||||
self.value.truncate(at);
|
||||
}
|
||||
|
||||
/// Shell-style ctrl-w: kill back to the previous whitespace, taking any
|
||||
/// trailing whitespace run with it — so `cd /tmp/foo` loses the whole
|
||||
/// path segment in one keystroke.
|
||||
fn delete_word_backwards(&mut self) {
|
||||
let chars: Vec<char> = self.value.chars().collect();
|
||||
let mut i = self.cursor;
|
||||
while i > 0 && chars[i - 1].is_whitespace() {
|
||||
i -= 1;
|
||||
}
|
||||
while i > 0 && !chars[i - 1].is_whitespace() {
|
||||
i -= 1;
|
||||
}
|
||||
let at = self.byte_offset(i);
|
||||
let end = self.byte_offset(self.cursor);
|
||||
self.value.replace_range(at..end, "");
|
||||
self.cursor = i;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use InputKey::{Backspace, Delete, End, Home, Left, Right};
|
||||
|
||||
fn typed(s: &str) -> Vec<InputKey> {
|
||||
s.chars().map(InputKey::char).collect()
|
||||
}
|
||||
|
||||
fn fed(keys: &[InputKey]) -> TextInput {
|
||||
let mut input = TextInput::default();
|
||||
for k in keys {
|
||||
input.handle_key(k);
|
||||
}
|
||||
input
|
||||
}
|
||||
|
||||
fn ctrl(c: char) -> InputKey {
|
||||
InputKey::ctrl_char(c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_lands_in_order() {
|
||||
let input = fed(&typed("hello"));
|
||||
assert_eq!(input.value(), "hello");
|
||||
assert_eq!(input.cursor(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_removes_the_last_typed_char() {
|
||||
let mut input = fed(&typed("hello"));
|
||||
input.handle_key(&Backspace);
|
||||
assert_eq!(input.value(), "hell");
|
||||
assert_eq!(input.cursor(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_then_insert_fixes_a_middle_typo() {
|
||||
let mut input = fed(&typed("helo"));
|
||||
input.handle_key(&Left);
|
||||
input.handle_key(&Left);
|
||||
input.handle_key(&InputKey::char('l'));
|
||||
assert_eq!(input.value(), "hello");
|
||||
assert_eq!(input.cursor(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn motion_keys_stop_at_the_edges() {
|
||||
let mut input = fed(&typed("abc"));
|
||||
for _ in 0..5 {
|
||||
input.handle_key(&Left);
|
||||
}
|
||||
assert_eq!(input.cursor(), 0);
|
||||
input.handle_key(&Left);
|
||||
assert_eq!(input.cursor(), 0);
|
||||
for _ in 0..5 {
|
||||
input.handle_key(&Right);
|
||||
}
|
||||
assert_eq!(input.cursor(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_and_end_jump_to_the_ends() {
|
||||
let mut input = fed(&typed("abcdef"));
|
||||
input.handle_key(&Home);
|
||||
assert_eq!(input.cursor(), 0);
|
||||
input.handle_key(&InputKey::char('x'));
|
||||
assert_eq!(input.value(), "xabcdef");
|
||||
input.handle_key(&End);
|
||||
input.handle_key(&InputKey::char('!'));
|
||||
assert_eq!(input.value(), "xabcdef!");
|
||||
}
|
||||
|
||||
/// Cursor starts after the final `/`; word-left lands on word starts,
|
||||
/// never inside a separator run.
|
||||
#[test]
|
||||
fn ctrl_b_walks_left_one_word_at_a_time() {
|
||||
let mut input = TextInput::with_value("/tmp/foo bar-baz/");
|
||||
assert_eq!(input.cursor(), 17);
|
||||
for expected in [13, 9, 5, 1, 0, 0] {
|
||||
input.handle_key(&ctrl('b'));
|
||||
assert_eq!(input.cursor(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_f_walks_right_one_word_at_a_time() {
|
||||
let mut input = TextInput::with_value("/tmp/foo bar");
|
||||
input.handle_key(&Home);
|
||||
for expected in [4, 8, 12, 12] {
|
||||
input.handle_key(&ctrl('f'));
|
||||
assert_eq!(input.cursor(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_deletes_before_the_cursor() {
|
||||
let mut input = fed(&typed("abcdef"));
|
||||
input.handle_key(&Left);
|
||||
input.handle_key(&Left);
|
||||
input.handle_key(&Left);
|
||||
input.handle_key(&Backspace);
|
||||
assert_eq!(input.value(), "abdef");
|
||||
assert_eq!(input.cursor(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_on_empty_input_is_a_noop() {
|
||||
let mut input = TextInput::default();
|
||||
input.handle_key(&Backspace);
|
||||
assert_eq!(input.value(), "");
|
||||
assert_eq!(input.cursor(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_removes_the_char_under_the_cursor() {
|
||||
let mut input = fed(&typed("abcdef"));
|
||||
input.handle_key(&Home);
|
||||
input.handle_key(&Delete);
|
||||
assert_eq!(input.value(), "bcdef");
|
||||
assert_eq!(input.cursor(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_past_the_end_is_a_noop() {
|
||||
let mut input = TextInput::with_value("abc");
|
||||
input.handle_key(&End);
|
||||
input.handle_key(&Delete);
|
||||
assert_eq!(input.value(), "abc");
|
||||
}
|
||||
|
||||
/// `cd /tmp/foo` with ctrl-w leaves `cd ` — the whole path segment is one
|
||||
/// word to a shell (readline kills back to whitespace, spaces included).
|
||||
#[test]
|
||||
fn ctrl_w_deletes_the_word_behind_the_cursor() {
|
||||
let mut input = fed(&[typed("cd ").as_slice(), typed("/tmp/foo").as_slice()].concat());
|
||||
input.handle_key(&ctrl('w'));
|
||||
assert_eq!(input.value(), "cd ");
|
||||
assert_eq!(input.cursor(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_w_stops_before_the_separator_run() {
|
||||
let mut input = TextInput::with_value("a b");
|
||||
input.cursor = 5;
|
||||
input.handle_key(&ctrl('w'));
|
||||
assert_eq!(input.value(), "a ");
|
||||
assert_eq!(input.cursor(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_k_kills_everything_after_the_cursor() {
|
||||
let mut input = fed(&typed("spawn --debug extra"));
|
||||
for _ in 0..14 {
|
||||
input.handle_key(&Left);
|
||||
}
|
||||
input.handle_key(&ctrl('k'));
|
||||
assert_eq!(input.value(), "spawn");
|
||||
assert_eq!(input.cursor(), 5);
|
||||
}
|
||||
|
||||
/// A paste arrives as one event carrying the whole payload and must land
|
||||
/// at the cursor as a single insertion, not per-character.
|
||||
#[test]
|
||||
fn paste_inserts_whole_payload_at_the_cursor() {
|
||||
let mut input = fed(&typed("cd "));
|
||||
input.handle_key(&InputKey::Paste("/srv/work".into()));
|
||||
assert_eq!(input.value(), "cd /srv/work");
|
||||
assert_eq!(input.cursor(), 12);
|
||||
// What follows still behaves like ordinary typed text.
|
||||
input.handle_key(&InputKey::char('/'));
|
||||
assert_eq!(input.value(), "cd /srv/work/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_between_existing_text_keeps_both_halves() {
|
||||
let mut input = TextInput::with_value("ac");
|
||||
input.handle_key(&Left);
|
||||
input.handle_key(&InputKey::Paste("b×".into()));
|
||||
assert_eq!(input.value(), "ab×c");
|
||||
assert_eq!(input.cursor(), 3, "cursor counts chars, not bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_an_empty_field_points_at_its_first_column() {
|
||||
let input = TextInput::default();
|
||||
let area = Rect::new(10, 5, 20, 1);
|
||||
let mut buf = Buffer::empty(area);
|
||||
let col = input.render(area, &mut buf, Style::default());
|
||||
assert_eq!(col, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_reports_the_visible_cursor_column() {
|
||||
let mut input = TextInput::with_value("hello");
|
||||
input.handle_key(&Left);
|
||||
input.handle_key(&Left);
|
||||
let area = Rect::new(10, 5, 20, 1);
|
||||
let mut buf = Buffer::empty(area);
|
||||
let col = input.render(area, &mut buf, Style::default());
|
||||
assert_eq!(col, 13);
|
||||
for (i, expected) in ["h", "e", "l", "l", "o"].iter().enumerate() {
|
||||
assert_eq!(buf[(10 + i as u16, 5)].symbol(), *expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_a_value_wider_than_the_field_shows_its_tail() {
|
||||
let value = "0123456789abcdefghij";
|
||||
let input = TextInput::with_value(value);
|
||||
let area = Rect::new(0, 0, 10, 1);
|
||||
let mut buf = Buffer::empty(area);
|
||||
let col = input.render(area, &mut buf, Style::default());
|
||||
assert_eq!(col, 9, "cursor sits on the last visible column");
|
||||
for (i, expected) in value.chars().skip(input.scroll_offset()).enumerate() {
|
||||
assert_eq!(
|
||||
buf[(i as u16, 0)].symbol(),
|
||||
expected.to_string(),
|
||||
"cell {i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Moving left into the hidden region must scroll the window back so the
|
||||
/// cursor never disappears off the left edge.
|
||||
#[test]
|
||||
fn moving_left_into_the_hidden_region_scrolls_back() {
|
||||
let value = "0123456789abcdefghij";
|
||||
let mut input = TextInput::with_value(value);
|
||||
let area = Rect::new(0, 0, 10, 1);
|
||||
let mut buf = Buffer::empty(area);
|
||||
input.render(area, &mut buf, Style::default());
|
||||
assert_eq!(input.cursor(), 20);
|
||||
|
||||
input.handle_key(&Home);
|
||||
for _ in 0..5 {
|
||||
input.handle_key(&Right);
|
||||
}
|
||||
let mut buf = Buffer::empty(area);
|
||||
let col = input.render(area, &mut buf, Style::default());
|
||||
assert_eq!(input.cursor(), 5);
|
||||
assert_eq!(
|
||||
input.value().chars().nth(input.scroll_offset()),
|
||||
Some('5'),
|
||||
"window scrolled back to the cursor"
|
||||
);
|
||||
assert_eq!(col, 0);
|
||||
assert_eq!(buf[(0, 0)].symbol(), "5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrinking_the_value_clamps_scroll_and_cursor() {
|
||||
let mut input = TextInput::with_value("0123456789abcdefghij");
|
||||
input.handle_key(&Home);
|
||||
input.handle_key(&ctrl('k'));
|
||||
let area = Rect::new(0, 0, 10, 1);
|
||||
let mut buf = Buffer::empty(area);
|
||||
let col = input.render(area, &mut buf, Style::default());
|
||||
assert_eq!(input.value(), "");
|
||||
assert_eq!(col, 0);
|
||||
}
|
||||
}
|
||||
@@ -1,84 +1,42 @@
|
||||
//! WS round-trip test for `CatalogStore::run_events_loop`. Spins a tiny axum
|
||||
//! server that emulates the daemon's `/api/events` contract: send a `Snapshot`
|
||||
//! on connect, then a delta.
|
||||
//! `CatalogStore::run_events_loop` against a daemon serving the real
|
||||
//! `/api/events` contract, rather than a scripted socket.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::ws::{Message, WebSocketUpgrade};
|
||||
use axum::response::Response;
|
||||
use axum::routing::any;
|
||||
use axum::Router;
|
||||
use chrono::Utc;
|
||||
use maestro_protocol::{CatalogEvent, Session, SessionStatus};
|
||||
use maestro_testing::{session, MockDaemon};
|
||||
use maestro_tui::catalog::CatalogStore;
|
||||
use uuid::Uuid;
|
||||
|
||||
fn session(id: u128) -> Session {
|
||||
Session {
|
||||
id: Uuid::from_u128(id),
|
||||
command: "bash".into(),
|
||||
cwd: std::path::PathBuf::from("/tmp"),
|
||||
env: Default::default(),
|
||||
metadata: Default::default(),
|
||||
status: SessionStatus::Running,
|
||||
created_at: Utc::now(),
|
||||
foreground: None,
|
||||
activity: Default::default(),
|
||||
last_activity_at: chrono::Utc::now(),
|
||||
|
||||
current_cwd: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn events_handler(ws: WebSocketUpgrade) -> Response {
|
||||
ws.on_upgrade(|mut socket| async move {
|
||||
let snapshot = CatalogEvent::Snapshot { sessions: vec![] };
|
||||
let text = serde_json::to_string(&snapshot).unwrap();
|
||||
if socket.send(Message::Text(text)).await.is_err() {
|
||||
return;
|
||||
}
|
||||
// Small delay so the client has the snapshot applied before the delta.
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
let added = CatalogEvent::SessionAdded {
|
||||
session: session(1),
|
||||
};
|
||||
let text = serde_json::to_string(&added).unwrap();
|
||||
let _ = socket.send(Message::Text(text)).await;
|
||||
// Keep the connection alive so the client doesn't enter reconnect.
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn run_events_loop_applies_snapshot_then_delta() {
|
||||
let app = Router::new().route("/api/events", any(events_handler));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
async fn applies_the_snapshot_then_live_deltas() {
|
||||
let mock = MockDaemon::start().await;
|
||||
mock.add_session(session(Uuid::from_u128(1), "/home/mock", "bash"));
|
||||
|
||||
let ws_url = mock.client().events_url().expect("events url");
|
||||
let store = CatalogStore::default();
|
||||
let bg = store.clone();
|
||||
let ws_url = format!("ws://{addr}/api/events");
|
||||
tokio::spawn(async move { bg.run_events_loop(ws_url).await });
|
||||
|
||||
// Bootstrap should land within ~250 ms.
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(500),
|
||||
store.wait_for_initial_snapshot(),
|
||||
)
|
||||
.await
|
||||
.expect("initial snapshot never arrived");
|
||||
tokio::time::timeout(Duration::from_secs(3), store.wait_for_initial_snapshot())
|
||||
.await
|
||||
.expect("initial snapshot");
|
||||
assert_eq!(store.snapshot().sessions.len(), 1);
|
||||
|
||||
assert!(store.snapshot().sessions.is_empty());
|
||||
mock.add_session(session(Uuid::from_u128(2), "/home/mock", "claude"));
|
||||
wait_until(|| store.snapshot().sessions.len() == 2).await;
|
||||
|
||||
// Delta arrives shortly after. Poll for up to 500 ms.
|
||||
for _ in 0..50 {
|
||||
if store.snapshot().sessions.len() == 1 {
|
||||
mock.remove_session(Uuid::from_u128(1));
|
||||
wait_until(|| store.snapshot().sessions.len() == 1).await;
|
||||
assert_eq!(store.snapshot().sessions[0].id, Uuid::from_u128(2));
|
||||
}
|
||||
|
||||
async fn wait_until(mut cond: impl FnMut() -> bool) {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
|
||||
while tokio::time::Instant::now() < deadline {
|
||||
if cond() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("delta never propagated; got {:?}", store.snapshot());
|
||||
panic!("timed out waiting for the catalog to converge");
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ dirs.workspace = true
|
||||
futures-util.workspace = true
|
||||
include_dir.workspace = true
|
||||
maestro-config.workspace = true
|
||||
maestro-protocol.workspace = true
|
||||
mime_guess.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde_json.workspace = true
|
||||
@@ -32,6 +33,8 @@ tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
maestro-testing.workspace = true
|
||||
uuid.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde_json.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -31,7 +31,6 @@ The binary reads `~/.config/maestro/config.toml`. The `[web]` section:
|
||||
[web]
|
||||
bind_addr = "127.0.0.1:8080" # default
|
||||
daemon_url = "http://127.0.0.1:7070" # default
|
||||
# dev_proxy_target = "http://127.0.0.1:5173" # only when developing the frontend
|
||||
```
|
||||
|
||||
Env-var overrides (all optional):
|
||||
|
||||
@@ -5,7 +5,9 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use maestro_config::MaestroConfigFile;
|
||||
|
||||
pub use maestro_config::{default_config_path, resolve_config_path, WebSection, CONFIG_PATH_ENV};
|
||||
pub use maestro_config::default_config_path;
|
||||
|
||||
use maestro_config::WebSection;
|
||||
|
||||
/// Default bind address when neither env nor file specify one.
|
||||
pub const DEFAULT_BIND_ADDR: &str = "127.0.0.1:8080";
|
||||
@@ -14,7 +16,6 @@ pub const DEFAULT_DAEMON_URL: &str = "http://127.0.0.1:7070";
|
||||
|
||||
pub const ENV_WEB_BIND_ADDR: &str = "MAESTRO_WEB_BIND_ADDR";
|
||||
pub const ENV_WEB_DAEMON_URL: &str = "MAESTRO_WEB_DAEMON_URL";
|
||||
pub const ENV_WEB_DEV_PROXY_TARGET: &str = "MAESTRO_WEB_DEV_PROXY_TARGET";
|
||||
|
||||
fn default_bind_addr() -> SocketAddr {
|
||||
DEFAULT_BIND_ADDR.parse().expect("valid default bind_addr")
|
||||
@@ -33,17 +34,12 @@ pub struct WebConfig {
|
||||
/// Daemon HTTP base URL — e.g. `http://127.0.0.1:7070`. Always a base
|
||||
/// without trailing slash and without a path.
|
||||
pub daemon_url: String,
|
||||
/// Optional dev override: when set, `/` (and only `/`) is proxied here
|
||||
/// instead of being served from the embedded bundle. Set to the Vite dev
|
||||
/// server URL during frontend development.
|
||||
pub dev_proxy_target: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct EnvOverrides {
|
||||
pub bind_addr: Option<String>,
|
||||
pub daemon_url: Option<String>,
|
||||
pub dev_proxy_target: Option<String>,
|
||||
}
|
||||
|
||||
impl EnvOverrides {
|
||||
@@ -51,7 +47,6 @@ impl EnvOverrides {
|
||||
Self {
|
||||
bind_addr: std::env::var(ENV_WEB_BIND_ADDR).ok(),
|
||||
daemon_url: std::env::var(ENV_WEB_DAEMON_URL).ok(),
|
||||
dev_proxy_target: std::env::var(ENV_WEB_DEV_PROXY_TARGET).ok(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,15 +71,9 @@ fn resolve_with(web: WebSection, env: EnvOverrides) -> Result<WebConfig, WebConf
|
||||
.trim_end_matches('/')
|
||||
.to_string();
|
||||
|
||||
let dev_proxy_target = env
|
||||
.dev_proxy_target
|
||||
.or(web.dev_proxy_target)
|
||||
.map(|s| s.trim_end_matches('/').to_string());
|
||||
|
||||
Ok(WebConfig {
|
||||
bind_addr,
|
||||
daemon_url,
|
||||
dev_proxy_target,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -105,7 +94,6 @@ mod tests {
|
||||
let cfg = load_config(&path, EnvOverrides::default()).unwrap();
|
||||
assert_eq!(cfg.bind_addr, default_bind_addr());
|
||||
assert_eq!(cfg.daemon_url, "http://127.0.0.1:7070");
|
||||
assert!(cfg.dev_proxy_target.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -118,17 +106,12 @@ mod tests {
|
||||
[web]
|
||||
bind_addr = "127.0.0.1:9090"
|
||||
daemon_url = "http://127.0.0.1:9070"
|
||||
dev_proxy_target = "http://127.0.0.1:5173"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let cfg = load_config(&path, EnvOverrides::default()).unwrap();
|
||||
assert_eq!(cfg.bind_addr, "127.0.0.1:9090".parse().unwrap());
|
||||
assert_eq!(cfg.daemon_url, "http://127.0.0.1:9070");
|
||||
assert_eq!(
|
||||
cfg.dev_proxy_target.as_deref(),
|
||||
Some("http://127.0.0.1:5173")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -147,7 +130,6 @@ daemon_url = "http://127.0.0.1:9070"
|
||||
let env = EnvOverrides {
|
||||
bind_addr: Some("0.0.0.0:8080".into()),
|
||||
daemon_url: Some("http://daemon:7070".into()),
|
||||
dev_proxy_target: None,
|
||||
};
|
||||
let cfg = load_config(&path, env).unwrap();
|
||||
assert_eq!(cfg.bind_addr, "0.0.0.0:8080".parse().unwrap());
|
||||
|
||||
@@ -47,17 +47,9 @@ async fn run(config_override: Option<PathBuf>) -> Result<(), Box<dyn Error>> {
|
||||
tracing::info!(
|
||||
bind = %cfg.bind_addr,
|
||||
daemon = %cfg.daemon_url,
|
||||
dev_proxy = ?cfg.dev_proxy_target,
|
||||
"loaded config",
|
||||
);
|
||||
if cfg.dev_proxy_target.is_some() {
|
||||
tracing::warn!(
|
||||
"dev_proxy_target is set in config but not yet honored by the server \
|
||||
(NAP-241 v1 ships only the embedded-bundle path)"
|
||||
);
|
||||
}
|
||||
|
||||
let router = router(&cfg);
|
||||
let router = router(&cfg)?;
|
||||
let listener = TcpListener::bind(cfg.bind_addr).await?;
|
||||
tracing::info!(addr = %listener.local_addr()?, "serving");
|
||||
axum::serve(listener, router)
|
||||
|
||||
@@ -10,9 +10,11 @@ use std::sync::Arc;
|
||||
use axum::body::Body;
|
||||
use axum::extract::ws::{Message as AxMessage, WebSocket};
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::{header, HeaderMap, HeaderValue, StatusCode, Uri};
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use maestro_protocol::routes::{self, UrlError};
|
||||
use maestro_protocol::ApiError;
|
||||
use tokio_tungstenite::tungstenite::Message as WsMessage;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -25,21 +27,13 @@ pub struct UpstreamConfig {
|
||||
}
|
||||
|
||||
impl UpstreamConfig {
|
||||
pub fn from_daemon_url(daemon_url: &str) -> Self {
|
||||
let http_base = daemon_url.trim_end_matches('/').to_string();
|
||||
let ws_base = if let Some(rest) = http_base.strip_prefix("https://") {
|
||||
format!("wss://{rest}")
|
||||
} else if let Some(rest) = http_base.strip_prefix("http://") {
|
||||
format!("ws://{rest}")
|
||||
} else {
|
||||
// Caller passed something already scheme-less or pre-wrapped; trust
|
||||
// it. Validation happens at config-load time.
|
||||
http_base.clone()
|
||||
};
|
||||
Self {
|
||||
pub fn from_daemon_url(daemon_url: &str) -> Result<Self, UrlError> {
|
||||
let http_base = routes::normalize_base(daemon_url).to_string();
|
||||
let ws_base = routes::ws_base(&http_base)?;
|
||||
Ok(Self {
|
||||
daemon_http_base: Arc::new(http_base),
|
||||
daemon_ws_base: Arc::new(ws_base),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,29 +164,22 @@ fn filter_response_headers(headers: &reqwest::header::HeaderMap) -> HeaderMap {
|
||||
|
||||
fn bad_gateway(msg: &str) -> Response {
|
||||
tracing::warn!(error = msg, "proxy: bad gateway");
|
||||
// Plain JSON without a serde_json dep — the message is short and we control
|
||||
// every byte we write, so manual escaping of `"` + `\` is enough here.
|
||||
let escaped = msg.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
let body = format!(r#"{{"error":{{"code":"proxy_failed","message":"{escaped}"}}}}"#);
|
||||
(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
[(header::CONTENT_TYPE, "application/json")],
|
||||
body,
|
||||
)
|
||||
.into_response()
|
||||
api_error(StatusCode::BAD_GATEWAY, "proxy_failed", msg)
|
||||
}
|
||||
|
||||
fn payload_too_large() -> Response {
|
||||
tracing::warn!(limit = MAX_REQUEST_BODY, "proxy: request body exceeds cap");
|
||||
let body = format!(
|
||||
r#"{{"error":{{"code":"payload_too_large","message":"request body exceeds {MAX_REQUEST_BODY} bytes"}}}}"#
|
||||
);
|
||||
(
|
||||
api_error(
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
[(header::CONTENT_TYPE, "application/json")],
|
||||
body,
|
||||
"payload_too_large",
|
||||
&format!("request body exceeds {MAX_REQUEST_BODY} bytes"),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// Answer in the same envelope the daemon uses, so a client cannot tell whether
|
||||
/// a failure came from the daemon or from this proxy.
|
||||
fn api_error(status: StatusCode, code: &str, message: &str) -> Response {
|
||||
(status, axum::Json(ApiError::new(code, message))).into_response()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -291,8 +278,7 @@ pub async fn pump_ws(mut client: WebSocket, upstream_url: String) {
|
||||
const CLOSE_UPSTREAM_REJECTED: u16 = 4502;
|
||||
|
||||
/// Turn a failed upstream WS handshake into a browser-facing close code +
|
||||
/// reason. When the daemon rejected the upgrade with its structured JSON error
|
||||
/// body (`{"error":{"code","message"}}` — see `local_api::error_response`),
|
||||
/// reason. When the daemon rejected the upgrade with an [`ApiError`] body,
|
||||
/// surface that message; otherwise fall back to a generic gateway reason. The
|
||||
/// reason rides a WS control frame, so it's truncated to the 123-byte limit.
|
||||
fn upstream_close_reason(e: &tokio_tungstenite::tungstenite::Error) -> (u16, String) {
|
||||
@@ -301,13 +287,8 @@ fn upstream_close_reason(e: &tokio_tungstenite::tungstenite::Error) -> (u16, Str
|
||||
WsError::Http(resp) => resp
|
||||
.body()
|
||||
.as_ref()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(b).ok())
|
||||
.and_then(|v| {
|
||||
v.get("error")
|
||||
.and_then(|err| err.get("message"))
|
||||
.and_then(|m| m.as_str())
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.and_then(|b| serde_json::from_slice::<ApiError>(b).ok())
|
||||
.map(|e| e.error.message)
|
||||
.unwrap_or_else(|| "the session's daemon rejected the attach".to_owned()),
|
||||
_ => "could not reach the session's daemon".to_owned(),
|
||||
};
|
||||
@@ -346,14 +327,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn ws_base_swaps_http_scheme() {
|
||||
let u = UpstreamConfig::from_daemon_url("http://127.0.0.1:7070/");
|
||||
let u = UpstreamConfig::from_daemon_url("http://127.0.0.1:7070/").unwrap();
|
||||
assert_eq!(&*u.daemon_http_base, "http://127.0.0.1:7070");
|
||||
assert_eq!(&*u.daemon_ws_base, "ws://127.0.0.1:7070");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ws_base_swaps_https_scheme() {
|
||||
let u = UpstreamConfig::from_daemon_url("https://daemon.example/");
|
||||
let u = UpstreamConfig::from_daemon_url("https://daemon.example/").unwrap();
|
||||
assert_eq!(&*u.daemon_ws_base, "wss://daemon.example");
|
||||
}
|
||||
|
||||
@@ -362,7 +343,7 @@ mod tests {
|
||||
/// a bogus unreachable address; a 413 (not a 502) proves we bailed early.
|
||||
#[tokio::test]
|
||||
async fn oversized_request_body_is_rejected_with_413() {
|
||||
let state = ProxyState::new(UpstreamConfig::from_daemon_url("http://127.0.0.1:9"));
|
||||
let state = ProxyState::new(UpstreamConfig::from_daemon_url("http://127.0.0.1:9").unwrap());
|
||||
let big = vec![0u8; MAX_REQUEST_BODY + 1];
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
@@ -379,7 +360,7 @@ mod tests {
|
||||
/// limit, not off-by-one against legitimate traffic.
|
||||
#[tokio::test]
|
||||
async fn body_at_cap_is_not_rejected_by_the_size_check() {
|
||||
let state = ProxyState::new(UpstreamConfig::from_daemon_url("http://127.0.0.1:9"));
|
||||
let state = ProxyState::new(UpstreamConfig::from_daemon_url("http://127.0.0.1:9").unwrap());
|
||||
let body = vec![0u8; MAX_REQUEST_BODY];
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
|
||||
@@ -5,6 +5,7 @@ use axum::extract::{Request, State, WebSocketUpgrade};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{any, get};
|
||||
use axum::Router;
|
||||
use maestro_protocol::routes::{self, UrlError};
|
||||
|
||||
use crate::config::WebConfig;
|
||||
use crate::proxy::{pump_ws, upstream_ws_url, ProxyState, UpstreamConfig};
|
||||
@@ -12,30 +13,37 @@ use crate::static_bundle;
|
||||
|
||||
/// Build the public router. The returned router is ready to hand to
|
||||
/// `axum::serve`.
|
||||
pub fn router(config: &WebConfig) -> Router {
|
||||
let upstream = UpstreamConfig::from_daemon_url(&config.daemon_url);
|
||||
pub fn router(config: &WebConfig) -> Result<Router, UrlError> {
|
||||
let upstream = UpstreamConfig::from_daemon_url(&config.daemon_url)?;
|
||||
let proxy_state = ProxyState::new(upstream);
|
||||
|
||||
// Mount each route at its real path (not under `nest`, which would strip
|
||||
// the `/api` prefix before the proxy could forward it). WS routes go
|
||||
// first so the HTTP fallback doesn't shadow them.
|
||||
Router::new()
|
||||
.route("/api/attach/:id", any(ws_proxy))
|
||||
.route("/api/events", any(ws_proxy))
|
||||
Ok(Router::new()
|
||||
.route(routes::patterns::ATTACH, any(ws_proxy))
|
||||
.route(routes::EVENTS, any(ws_proxy))
|
||||
.route("/", get(serve_index))
|
||||
.fallback(catch_all)
|
||||
.with_state(proxy_state)
|
||||
.with_state(proxy_state))
|
||||
}
|
||||
|
||||
/// Default handler: `/api/*` goes to the daemon, anything else falls through
|
||||
/// to the embedded SPA bundle (with SPA-style fallback to `index.html`).
|
||||
async fn catch_all(State(state): State<ProxyState>, req: Request) -> Response {
|
||||
if req.uri().path().starts_with("/api/") {
|
||||
if is_api_path(req.uri().path()) {
|
||||
return crate::proxy::proxy_http(State(state), req).await;
|
||||
}
|
||||
static_bundle::serve_path(req.uri().path())
|
||||
}
|
||||
|
||||
/// Split point between the proxied daemon surface and the SPA bundle. A daemon
|
||||
/// route added outside [`routes::API_PREFIX`] would silently be answered with
|
||||
/// `index.html` instead of being forwarded.
|
||||
fn is_api_path(path: &str) -> bool {
|
||||
path.starts_with(&format!("{}/", routes::API_PREFIX))
|
||||
}
|
||||
|
||||
async fn ws_proxy(State(state): State<ProxyState>, ws: WebSocketUpgrade, req: Request) -> Response {
|
||||
let upstream_url = upstream_ws_url(&state, req.uri());
|
||||
ws.on_upgrade(move |socket| async move {
|
||||
|
||||
@@ -1,72 +1,24 @@
|
||||
//! Integration tests for the maestro-web reverse-proxy.
|
||||
//!
|
||||
//! Spins up a tiny axum "daemon" on a random port, points maestro-web at it,
|
||||
//! and exercises both the HTTP and WS proxy paths end-to-end.
|
||||
//! Points maestro-web at a `MockDaemon` and exercises both the HTTP and WS
|
||||
//! proxy paths end-to-end.
|
||||
|
||||
use maestro_testing::MockDaemon;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::ws::{Message as AxMessage, WebSocket, WebSocketUpgrade};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::{any, get};
|
||||
use axum::{Json, Router};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use maestro_web::config::WebConfig;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_tungstenite::tungstenite::Message as WsMessage;
|
||||
|
||||
async fn spawn_mock_daemon() -> (SocketAddr, oneshot::Sender<()>) {
|
||||
async fn list_sessions() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!([{"id": "session-1"}]))
|
||||
}
|
||||
async fn daemon_info() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({"hostname": "mock-host"}))
|
||||
}
|
||||
async fn echo_ws(ws: WebSocketUpgrade) -> impl IntoResponse {
|
||||
ws.on_upgrade(echo_handler)
|
||||
}
|
||||
async fn echo_handler(mut socket: WebSocket) {
|
||||
while let Some(Ok(msg)) = socket.next().await {
|
||||
match msg {
|
||||
AxMessage::Text(t) => {
|
||||
let _ = socket.send(AxMessage::Text(format!("echo:{t}"))).await;
|
||||
}
|
||||
AxMessage::Binary(b) => {
|
||||
let _ = socket.send(AxMessage::Binary(b)).await;
|
||||
}
|
||||
AxMessage::Close(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let app = Router::new()
|
||||
.route("/api/sessions", get(list_sessions))
|
||||
.route("/api/info", get(daemon_info))
|
||||
.route("/api/attach/:id", any(echo_ws));
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = oneshot::channel::<()>();
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = rx.await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
(addr, tx)
|
||||
}
|
||||
|
||||
async fn spawn_web(daemon_url: String) -> (SocketAddr, oneshot::Sender<()>) {
|
||||
let cfg = WebConfig {
|
||||
bind_addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
|
||||
daemon_url,
|
||||
dev_proxy_target: None,
|
||||
};
|
||||
let router = maestro_web::router(&cfg);
|
||||
let router = maestro_web::router(&cfg).expect("router");
|
||||
let listener = TcpListener::bind(cfg.bind_addr).await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = oneshot::channel::<()>();
|
||||
@@ -82,7 +34,8 @@ async fn spawn_web(daemon_url: String) -> (SocketAddr, oneshot::Sender<()>) {
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_get_api_path_forwards_to_daemon() {
|
||||
let (daemon_addr, _d) = spawn_mock_daemon().await;
|
||||
let daemon = MockDaemon::start().await;
|
||||
let daemon_addr = daemon.addr();
|
||||
let (web_addr, _w) = spawn_web(format!("http://{daemon_addr}")).await;
|
||||
|
||||
let body: serde_json::Value = reqwest::get(format!("http://{web_addr}/api/sessions"))
|
||||
@@ -91,12 +44,13 @@ async fn http_get_api_path_forwards_to_daemon() {
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(body[0]["id"], "session-1");
|
||||
assert!(body.as_array().expect("array").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_get_unrelated_path_falls_back_to_spa_index() {
|
||||
let (daemon_addr, _d) = spawn_mock_daemon().await;
|
||||
let daemon = MockDaemon::start().await;
|
||||
let daemon_addr = daemon.addr();
|
||||
let (web_addr, _w) = spawn_web(format!("http://{daemon_addr}")).await;
|
||||
|
||||
// The bundle is empty in test builds — the placeholder index.html serves.
|
||||
@@ -114,22 +68,55 @@ async fn http_get_unrelated_path_falls_back_to_spa_index() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn ws_api_attach_forwards_to_daemon_and_echoes() {
|
||||
let (daemon_addr, _d) = spawn_mock_daemon().await;
|
||||
let daemon = MockDaemon::start().await;
|
||||
let id = uuid::Uuid::from_u128(7);
|
||||
daemon.add_session(maestro_testing::session(id, "/home/mock", "bash"));
|
||||
let daemon_addr = daemon.addr();
|
||||
let (web_addr, _w) = spawn_web(format!("http://{daemon_addr}")).await;
|
||||
|
||||
let url = format!("ws://{web_addr}/api/attach/abc");
|
||||
let url = format!("ws://{web_addr}/api/attach/{id}");
|
||||
let (mut ws, _) = tokio_tungstenite::connect_async(url).await.unwrap();
|
||||
ws.send(WsMessage::Text("hello".into())).await.unwrap();
|
||||
ws.send(WsMessage::Binary(b"hello".to_vec())).await.unwrap();
|
||||
|
||||
let echoed = tokio::time::timeout(Duration::from_secs(1), ws.next())
|
||||
.await
|
||||
.unwrap();
|
||||
match echoed {
|
||||
Some(Ok(WsMessage::Text(t))) => assert_eq!(t, "echo:hello"),
|
||||
Some(Ok(WsMessage::Binary(b))) => assert_eq!(b, b"hello"),
|
||||
other => panic!("unexpected frame: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The client is upgraded before the upstream connection is attempted, so an
|
||||
/// upstream rejection has to come back as a close code. This is the end-to-end
|
||||
/// counterpart to `upstream_close_reason`, which had only unit tests: the
|
||||
/// daemon's own message must reach the browser rather than a generic failure.
|
||||
#[tokio::test]
|
||||
async fn ws_attach_to_an_unknown_session_closes_with_the_daemon_reason() {
|
||||
let daemon = MockDaemon::start().await;
|
||||
let (web_addr, _w) = spawn_web(format!("http://{}", daemon.addr())).await;
|
||||
|
||||
let url = format!("ws://{web_addr}/api/attach/{}", uuid::Uuid::new_v4());
|
||||
let (mut ws, _) = tokio_tungstenite::connect_async(url)
|
||||
.await
|
||||
.expect("upgrade");
|
||||
|
||||
let frame = tokio::time::timeout(Duration::from_secs(2), ws.next())
|
||||
.await
|
||||
.expect("close frame");
|
||||
match frame {
|
||||
Some(Ok(WsMessage::Close(Some(cf)))) => {
|
||||
assert_eq!(u16::from(cf.code), 4502);
|
||||
assert!(
|
||||
cf.reason.contains("no such session"),
|
||||
"expected the daemon's message, got {:?}",
|
||||
cf.reason
|
||||
);
|
||||
}
|
||||
other => panic!("expected a Close frame with a reason, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_returns_502_when_daemon_unreachable() {
|
||||
// Bind a port, immediately drop the listener, hand the address to the
|
||||
|
||||
+98
-26
@@ -89,37 +89,37 @@ async fn dispatch(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
|
||||
match cli.command {
|
||||
#[cfg(feature = "cli")]
|
||||
Command::List(args) => {
|
||||
cli_dispatch(
|
||||
maestro_cli::dispatch(
|
||||
maestro_cli::cli::Command::List(args),
|
||||
cli.config,
|
||||
cli.daemon_url.clone(),
|
||||
cli.daemon_url,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
#[cfg(feature = "cli")]
|
||||
Command::Spawn(args) => {
|
||||
cli_dispatch(
|
||||
maestro_cli::dispatch(
|
||||
maestro_cli::cli::Command::Spawn(args),
|
||||
cli.config,
|
||||
cli.daemon_url.clone(),
|
||||
cli.daemon_url,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
#[cfg(feature = "cli")]
|
||||
Command::Attach(args) => {
|
||||
cli_dispatch(
|
||||
maestro_cli::dispatch(
|
||||
maestro_cli::cli::Command::Attach(args),
|
||||
cli.config,
|
||||
cli.daemon_url.clone(),
|
||||
cli.daemon_url,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
#[cfg(feature = "cli")]
|
||||
Command::Kill(args) => {
|
||||
cli_dispatch(
|
||||
maestro_cli::dispatch(
|
||||
maestro_cli::cli::Command::Kill(args),
|
||||
cli.config,
|
||||
cli.daemon_url.clone(),
|
||||
cli.daemon_url,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
@@ -141,16 +141,6 @@ async fn dispatch(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "cli")]
|
||||
#[allow(clippy::result_large_err)]
|
||||
async fn cli_dispatch(
|
||||
command: maestro_cli::cli::Command,
|
||||
config: Option<PathBuf>,
|
||||
daemon_url: Option<String>,
|
||||
) -> Result<(), maestro_cli::CliError> {
|
||||
maestro_cli::dispatch(command, config, daemon_url).await
|
||||
}
|
||||
|
||||
fn init_tracing(cli: &Cli) {
|
||||
let filter = if is_cli_subcommand(&cli.command) {
|
||||
cli_filter(cli.verbose)
|
||||
@@ -177,13 +167,95 @@ fn is_cli_subcommand(_command: &Command) -> bool {
|
||||
}
|
||||
|
||||
fn cli_filter(verbose: u8) -> EnvFilter {
|
||||
match (std::env::var_os("RUST_LOG"), verbose) {
|
||||
(Some(_), _) => {
|
||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn"))
|
||||
}
|
||||
(None, 0) => EnvFilter::new("warn"),
|
||||
(None, 1) => EnvFilter::new("info"),
|
||||
(None, 2) => EnvFilter::new("debug"),
|
||||
(None, _) => EnvFilter::new("trace"),
|
||||
match std::env::var_os("RUST_LOG") {
|
||||
// An explicit `RUST_LOG` always wins over `-v` flags.
|
||||
Some(_) => EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")),
|
||||
None => EnvFilter::new(verbosity_directive(verbose)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a `-v` repeat count to a tracing directive. Pure so it can be unit
|
||||
/// tested without touching the process-global `RUST_LOG`.
|
||||
fn verbosity_directive(verbose: u8) -> &'static str {
|
||||
match verbose {
|
||||
0 => "warn",
|
||||
1 => "info",
|
||||
2 => "debug",
|
||||
_ => "trace",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn verbosity_directive_maps_repeat_count() {
|
||||
assert_eq!(verbosity_directive(0), "warn");
|
||||
assert_eq!(verbosity_directive(1), "info");
|
||||
assert_eq!(verbosity_directive(2), "debug");
|
||||
// Anything past `-vv` saturates at trace.
|
||||
assert_eq!(verbosity_directive(3), "trace");
|
||||
assert_eq!(verbosity_directive(u8::MAX), "trace");
|
||||
}
|
||||
|
||||
/// Parse argv the way `main` does, returning just the dispatched subcommand.
|
||||
fn command_of(argv: &[&str]) -> Command {
|
||||
Cli::try_parse_from(argv)
|
||||
.unwrap_or_else(|e| panic!("parse {argv:?}: {e}"))
|
||||
.command
|
||||
}
|
||||
|
||||
#[cfg(feature = "cli")]
|
||||
#[test]
|
||||
fn cli_subcommands_are_classified_as_cli() {
|
||||
// Stable UUID for the subcommands that take a session id positional.
|
||||
const SID: &str = "00000000-0000-0000-0000-000000000000";
|
||||
// These four drive `cli_filter`; the tracing init must treat them as CLI.
|
||||
for argv in [
|
||||
vec!["maestro", "list"],
|
||||
vec![
|
||||
"maestro",
|
||||
"spawn",
|
||||
"--daemon-url",
|
||||
"d",
|
||||
"--cwd",
|
||||
"/tmp",
|
||||
"--command",
|
||||
"bash",
|
||||
],
|
||||
vec!["maestro", "attach", SID],
|
||||
vec!["maestro", "kill", SID],
|
||||
] {
|
||||
let cmd = command_of(&argv);
|
||||
assert!(
|
||||
is_cli_subcommand(&cmd),
|
||||
"expected {argv:?} to be classified as a CLI subcommand"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "cli", feature = "daemon", feature = "tui"))]
|
||||
#[test]
|
||||
fn server_subcommands_are_not_classified_as_cli() {
|
||||
// daemon / tui get the env-driven filter, not the `-v` one.
|
||||
for argv in [vec!["maestro", "daemon"], vec!["maestro", "tui"]] {
|
||||
let cmd = command_of(&argv);
|
||||
assert!(
|
||||
!is_cli_subcommand(&cmd),
|
||||
"expected {argv:?} to NOT be classified as a CLI subcommand"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Under a non-`cli` feature build, the classifier is the always-false stub
|
||||
/// and every subcommand takes the env-driven filter.
|
||||
#[cfg(not(feature = "cli"))]
|
||||
#[test]
|
||||
fn classifier_is_always_false_without_cli_feature() {
|
||||
#[cfg(feature = "daemon")]
|
||||
assert!(!is_cli_subcommand(&command_of(&["maestro", "daemon"])));
|
||||
#[cfg(feature = "tui")]
|
||||
assert!(!is_cli_subcommand(&command_of(&["maestro", "tui"])));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Smoke tests for the umbrella `maestro` binary's dispatch surface (NAP-271).
|
||||
//!
|
||||
//! These run against the real built binary via Cargo's `CARGO_BIN_EXE_maestro`
|
||||
//! env var. Integration tests are compiled with the package's active feature
|
||||
//! set, so the per-subcommand checks are `#[cfg]`-gated and the suite is
|
||||
//! meaningful under every feature subset (`cli` / `daemon` / `tui`)
|
||||
//! as well as the default all-features build. The asserts only inspect
|
||||
//! `--help`/`--version` output and exit codes, so nothing is actually started.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn maestro() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_maestro"))
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> (bool, String) {
|
||||
let out = maestro().args(args).output().expect("run maestro");
|
||||
let combined = format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
(out.status.success(), combined)
|
||||
}
|
||||
|
||||
/// Subcommands expected in `--help`, derived from the active feature set.
|
||||
fn expected_subcommands() -> Vec<&'static str> {
|
||||
let mut subs: Vec<&'static str> = Vec::new();
|
||||
#[cfg(feature = "cli")]
|
||||
subs.extend(["list", "spawn", "attach", "kill"]);
|
||||
#[cfg(feature = "daemon")]
|
||||
subs.extend(["daemon"]);
|
||||
#[cfg(feature = "tui")]
|
||||
subs.extend(["tui"]);
|
||||
subs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_level_help_lists_subcommands() {
|
||||
let (ok, text) = run(&["--help"]);
|
||||
assert!(ok, "--help should exit 0:\n{text}");
|
||||
for sub in expected_subcommands() {
|
||||
assert!(
|
||||
text.contains(sub),
|
||||
"--help missing subcommand `{sub}`:\n{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_flag_succeeds() {
|
||||
let (ok, text) = run(&["--version"]);
|
||||
assert!(ok, "--version should exit 0:\n{text}");
|
||||
assert!(text.contains("maestro"), "--version output: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_args_prints_help_and_fails() {
|
||||
// `arg_required_else_help = true` => exit non-zero but show usage.
|
||||
let (ok, text) = run(&[]);
|
||||
assert!(!ok, "bare invocation should fail:\n{text}");
|
||||
assert!(text.contains("Usage"), "expected usage text:\n{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_subcommand_fails() {
|
||||
let (ok, text) = run(&["definitely-not-a-subcommand"]);
|
||||
assert!(!ok, "unknown subcommand should fail:\n{text}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "cli")]
|
||||
#[test]
|
||||
fn cli_subcommand_help_works() {
|
||||
// A representative CLI subcommand resolves and renders help.
|
||||
let (ok, text) = run(&["spawn", "--help"]);
|
||||
assert!(ok, "spawn --help should exit 0:\n{text}");
|
||||
assert!(
|
||||
text.contains("--daemon-url"),
|
||||
"spawn help missing flags:\n{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "daemon")]
|
||||
#[test]
|
||||
fn daemon_subcommand_help_works() {
|
||||
let (ok, text) = run(&["daemon", "--help"]);
|
||||
assert!(ok, "daemon --help should exit 0:\n{text}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "tui")]
|
||||
#[test]
|
||||
fn tui_subcommand_help_works() {
|
||||
let (ok, text) = run(&["tui", "--help"]);
|
||||
assert!(ok, "tui --help should exit 0:\n{text}");
|
||||
}
|
||||
+3
-2
@@ -280,8 +280,9 @@ maestro daemon # foreground; or wire your own service manager
|
||||
```
|
||||
|
||||
Every setting has a default, so `~/.config/maestro/config.toml` is optional —
|
||||
create it only to change the bind address, worktree root, spawn presets, or TUI
|
||||
keymap.
|
||||
create it only to change the bind address, spawn presets, or TUI
|
||||
keymap. (Worktrees live inside their base repos at `<repo>/worktrees/<branch>`;
|
||||
set `[daemon].worktree_root` only to override that.)
|
||||
|
||||
## Non-Linux hosts
|
||||
|
||||
|
||||
Generated
+17
-1
@@ -64,11 +64,27 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"process-compose-flake": {
|
||||
"locked": {
|
||||
"lastModified": 1782060835,
|
||||
"narHash": "sha256-Q8HH2t1l3MITtWCWY4ytcH5F/Q7aAHo3Iq/QTMAKTe0=",
|
||||
"owner": "Platonic-Systems",
|
||||
"repo": "process-compose-flake",
|
||||
"rev": "464ff6880737f063c3f0d3d2c7781fda9190868f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "Platonic-Systems",
|
||||
"repo": "process-compose-flake",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"crane": "crane",
|
||||
"flake-parts": "flake-parts",
|
||||
"nixpkgs": "nixpkgs"
|
||||
"nixpkgs": "nixpkgs",
|
||||
"process-compose-flake": "process-compose-flake"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
flake-parts.url = "github:hercules-ci/flake-parts";
|
||||
crane.url = "github:ipetkov/crane";
|
||||
process-compose-flake.url = "github:Platonic-Systems/process-compose-flake";
|
||||
};
|
||||
|
||||
outputs =
|
||||
@@ -15,7 +16,10 @@
|
||||
"aarch64-linux"
|
||||
];
|
||||
|
||||
imports = [ ./nix/home-manager-module.nix ];
|
||||
imports = [
|
||||
./nix/home-manager-module.nix
|
||||
inputs.process-compose-flake.flakeModule
|
||||
];
|
||||
|
||||
perSystem =
|
||||
{
|
||||
@@ -51,6 +55,34 @@
|
||||
pkgs.git
|
||||
];
|
||||
|
||||
# The dev daemon's port, shared by its bind address, the readiness
|
||||
# probe, and the Vite proxy so they can never drift apart.
|
||||
devDaemonPort = 7071;
|
||||
|
||||
# Everything `nix run .#dev` needs on PATH. Listed explicitly so the
|
||||
# dev stack runs standalone, not only from inside `nix develop`.
|
||||
devTools = [
|
||||
# The base shell utilities. PATH is set explicitly below rather than
|
||||
# inherited, and node wrapper scripts reach for sed/dirname/uname,
|
||||
# which a NixOS host has nowhere near /usr/bin.
|
||||
pkgs.bash
|
||||
pkgs.coreutils
|
||||
pkgs.gnused
|
||||
pkgs.gnugrep
|
||||
pkgs.findutils
|
||||
pkgs.cargo
|
||||
pkgs.rustc
|
||||
pkgs.nodejs
|
||||
pkgs.pnpm_10
|
||||
# A personal ~/.cargo/config.toml commonly points the linker at
|
||||
# clang+mold. Cargo reads it regardless of where the toolchain came
|
||||
# from, so ship both rather than fail on a machine that has such a
|
||||
# config and a nix shell that doesn't.
|
||||
pkgs.clang
|
||||
pkgs.mold
|
||||
]
|
||||
++ runtimeDeps;
|
||||
|
||||
maestro = craneLib.buildPackage (
|
||||
commonArgs
|
||||
// {
|
||||
@@ -160,6 +192,75 @@
|
||||
);
|
||||
};
|
||||
|
||||
# `nix run .#dev` — the whole local stack under one supervisor:
|
||||
# a debug-build daemon on 127.0.0.1:7071 (`devDaemonPort`, not the
|
||||
# daemon's own default 7070) and Vite on :5173 with the SPA proxying
|
||||
# `/api/*` back to that daemon (see web/vite.config.ts).
|
||||
# Ctrl-C stops both.
|
||||
process-compose.dev = {
|
||||
# No HTTP control server: nothing here drives process-compose
|
||||
# remotely, and its default :8080 collides with whatever else the
|
||||
# developer happens to be running.
|
||||
cli = {
|
||||
environment.PC_NO_SERVER = true;
|
||||
# The tmux socket the dev daemon uses (see the daemon process
|
||||
# below) lives here.
|
||||
preHook = ''mkdir -p "$PWD/.dev/tmux"'';
|
||||
};
|
||||
|
||||
settings = {
|
||||
# `nix run .#dev` works from a bare shell, not only from inside
|
||||
# `nix develop`, so the toolchain is put on PATH here rather than
|
||||
# inherited. `/usr/bin:/bin` stays last for anything else a
|
||||
# spawned session reaches for.
|
||||
environment = [
|
||||
"PATH=${lib.makeBinPath devTools}:/usr/bin:/bin"
|
||||
# Not :7070: that is the daemon's own default, and the dev
|
||||
# stack must not fight a real daemon running on the same host.
|
||||
"MAESTRO_DAEMON_BIND_ADDR=127.0.0.1:${toString devDaemonPort}"
|
||||
"MAESTRO_DAEMON_URL=http://127.0.0.1:${toString devDaemonPort}"
|
||||
];
|
||||
|
||||
processes = {
|
||||
# Built once, up front, so the daemon and Vite don't race a
|
||||
# cold `cargo build` and trip their own readiness probes.
|
||||
build.command = "cargo build --bin maestro";
|
||||
|
||||
daemon = {
|
||||
# Both values need a shell: `$PWD` is only known at run time,
|
||||
# and process-compose does not expand anything in
|
||||
# `environment`. A tmux socket of its own keeps dev sessions
|
||||
# out of — and safe from — the tmux server belonging to
|
||||
# whatever daemon the developer actually runs.
|
||||
command = ''
|
||||
MAESTRO_DAEMON_TMUX_TMPDIR="$PWD/.dev/tmux" \
|
||||
RUST_LOG="''${RUST_LOG:-maestro=debug,info}" \
|
||||
target/debug/maestro daemon
|
||||
'';
|
||||
depends_on.build.condition = "process_completed_successfully";
|
||||
readiness_probe = {
|
||||
http_get = {
|
||||
host = "127.0.0.1";
|
||||
port = devDaemonPort;
|
||||
path = "/api/info";
|
||||
};
|
||||
initial_delay_seconds = 1;
|
||||
period_seconds = 1;
|
||||
failure_threshold = 30;
|
||||
};
|
||||
};
|
||||
|
||||
web = {
|
||||
# `--host` binds 0.0.0.0: the daemon stays on loopback and only
|
||||
# the UI is exposed, so the API is reachable solely through
|
||||
# the proxy.
|
||||
command = "pnpm -C web install && pnpm -C web dev --host";
|
||||
depends_on.daemon.condition = "process_healthy";
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
devShells.default = craneLib.devShell {
|
||||
inherit (self') checks;
|
||||
packages = [
|
||||
|
||||
+6
-2
@@ -8,14 +8,18 @@
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc -b --noEmit"
|
||||
"typecheck": "tsc -b --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xterm/addon-fit": "^0.10.0",
|
||||
"@xterm/xterm": "^5.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"happy-dom": "^20.11.6",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.4.10"
|
||||
"vite": "^5.4.10",
|
||||
"vitest": "^2.1.9"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+390
-15
@@ -15,12 +15,18 @@ importers:
|
||||
specifier: ^5.5.0
|
||||
version: 5.5.0
|
||||
devDependencies:
|
||||
happy-dom:
|
||||
specifier: ^20.11.6
|
||||
version: 20.11.6
|
||||
typescript:
|
||||
specifier: ^5.6.3
|
||||
version: 5.9.3
|
||||
vite:
|
||||
specifier: ^5.4.10
|
||||
version: 5.4.21
|
||||
version: 5.4.21(@types/node@26.2.0)
|
||||
vitest:
|
||||
specifier: ^2.1.9
|
||||
version: 2.1.9(@types/node@26.2.0)(happy-dom@20.11.6)
|
||||
|
||||
packages:
|
||||
|
||||
@@ -162,6 +168,9 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@jridgewell/sourcemap-codec@1.5.5':
|
||||
resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
|
||||
|
||||
'@rollup/rollup-android-arm-eabi@4.60.4':
|
||||
resolution: {integrity: sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ==}
|
||||
cpu: [arm]
|
||||
@@ -196,79 +205,66 @@ packages:
|
||||
resolution: {integrity: sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-arm-musleabihf@4.60.4':
|
||||
resolution: {integrity: sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-arm64-gnu@4.60.4':
|
||||
resolution: {integrity: sha512-BFDEZMYfUvLn37ONE1yMBojPxnMlTFsdyNoqncT0qFq1mAfllL+ATMMJd8TeuVMiX84s1KbcxcZbXInmcO2mRg==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-arm64-musl@4.60.4':
|
||||
resolution: {integrity: sha512-pc9EYOSlOgdQ2uPl1o9PF6/kLSgaUosia7gOuS8mB69IxJvlclko1MECXysjs5ryez1/5zjYqx3+xYU0TU6R1A==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-loong64-gnu@4.60.4':
|
||||
resolution: {integrity: sha512-NxnomyxYerDh5n4iLrNa+sH+Z+U4BMEE46V2PgQ/hoB909i8gV1M5wPojWg9fk1jWpO3IQnOs20K4wyZuFLEFQ==}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-loong64-musl@4.60.4':
|
||||
resolution: {integrity: sha512-nbJnQ8a3z1mtmrwImCYhc6BGpThAyYVRQxw9uKSKG4wR6aAYno9sVjJ0zaZcW9BPJX1GbrDPf+SvdWjgTuDmnw==}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-ppc64-gnu@4.60.4':
|
||||
resolution: {integrity: sha512-2EU6acNrQLd8tYvo/LXW535wupT3m6fo7HKo6lr7ktQoItxTyOL1ZCR/GfGCuXl2vR+zmfI6eRXkSemafv+iVg==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-ppc64-musl@4.60.4':
|
||||
resolution: {integrity: sha512-WeBtoMuaMxiiIrO2IYP3xs6GMWkJP2C0EoT8beTLkUPmzV1i/UcOSVw1d5r9KBODtHKilG5yFxsGRnBbK3wJ4A==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-riscv64-gnu@4.60.4':
|
||||
resolution: {integrity: sha512-FJHFfqpKUI3A10WrWKiFbBZ7yVbGT4q4B5o1qKFFojqpaYoh9LrQgqWCmmcxQzVSXYtyB5bzkXrYzlHTs21MYA==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-riscv64-musl@4.60.4':
|
||||
resolution: {integrity: sha512-mcEl6CUT5IAUmQf1m9FYSmVqCJlpQ8r8eyftFUHG8i9OhY7BkBXSUdnLH5DOf0wCOjcP9v/QO93zpmF1SptCCw==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-linux-s390x-gnu@4.60.4':
|
||||
resolution: {integrity: sha512-ynt3JxVd2w2buzoKDWIyiV1pJW93xlQic1THVLXilz429oijRpSHivZAgp65KBu+cMcgf1eVVjdnTLvPxgCuoQ==}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-x64-gnu@4.60.4':
|
||||
resolution: {integrity: sha512-Boiz5+MsaROEWDf+GGEwF8VMHGhlUoQMtIPjOgA5fv4osupqTVnJteQNKJwUcnUog2G55jYXH7KZFFiJe0TEzQ==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/rollup-linux-x64-musl@4.60.4':
|
||||
resolution: {integrity: sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/rollup-openbsd-x64@4.60.4':
|
||||
resolution: {integrity: sha512-VpTfOPHgVXEBeeR8hZ2O0F3aSso+JDWqTWmTmzcQKted54IAdUVbxE+j/MVxUsKa8L20HJhv3vUezVPoquqWjA==}
|
||||
@@ -303,6 +299,44 @@ packages:
|
||||
'@types/estree@1.0.8':
|
||||
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
|
||||
|
||||
'@types/node@26.2.0':
|
||||
resolution: {integrity: sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==}
|
||||
|
||||
'@types/whatwg-mimetype@3.0.2':
|
||||
resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}
|
||||
|
||||
'@types/ws@8.18.1':
|
||||
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
|
||||
|
||||
'@vitest/expect@2.1.9':
|
||||
resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
|
||||
|
||||
'@vitest/mocker@2.1.9':
|
||||
resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==}
|
||||
peerDependencies:
|
||||
msw: ^2.4.9
|
||||
vite: ^5.0.0
|
||||
peerDependenciesMeta:
|
||||
msw:
|
||||
optional: true
|
||||
vite:
|
||||
optional: true
|
||||
|
||||
'@vitest/pretty-format@2.1.9':
|
||||
resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==}
|
||||
|
||||
'@vitest/runner@2.1.9':
|
||||
resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==}
|
||||
|
||||
'@vitest/snapshot@2.1.9':
|
||||
resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==}
|
||||
|
||||
'@vitest/spy@2.1.9':
|
||||
resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==}
|
||||
|
||||
'@vitest/utils@2.1.9':
|
||||
resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
|
||||
|
||||
'@xterm/addon-fit@0.10.0':
|
||||
resolution: {integrity: sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==}
|
||||
peerDependencies:
|
||||
@@ -311,21 +345,88 @@ packages:
|
||||
'@xterm/xterm@5.5.0':
|
||||
resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
|
||||
|
||||
assertion-error@2.0.1:
|
||||
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
buffer-image-size@0.6.4:
|
||||
resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==}
|
||||
engines: {node: '>=4.0'}
|
||||
|
||||
cac@6.7.14:
|
||||
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
chai@5.3.3:
|
||||
resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
check-error@2.1.3:
|
||||
resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
|
||||
engines: {node: '>= 16'}
|
||||
|
||||
debug@4.4.3:
|
||||
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
|
||||
engines: {node: '>=6.0'}
|
||||
peerDependencies:
|
||||
supports-color: '*'
|
||||
peerDependenciesMeta:
|
||||
supports-color:
|
||||
optional: true
|
||||
|
||||
deep-eql@5.0.2:
|
||||
resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
entities@7.0.1:
|
||||
resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
|
||||
engines: {node: '>=0.12'}
|
||||
|
||||
es-module-lexer@1.7.0:
|
||||
resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
|
||||
|
||||
esbuild@0.21.5:
|
||||
resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}
|
||||
engines: {node: '>=12'}
|
||||
hasBin: true
|
||||
|
||||
estree-walker@3.0.3:
|
||||
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
|
||||
|
||||
expect-type@1.4.0:
|
||||
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
fsevents@2.3.3:
|
||||
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
os: [darwin]
|
||||
|
||||
happy-dom@20.11.6:
|
||||
resolution: {integrity: sha512-Hldbg8AdAa5a5oDcZpjqnGitp7JB0hqWmfv/8qr+kft4vzSD8BHsbdRfzYvL/0QcbKcURC/yyoygbeDQarPvYg==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
loupe@3.2.1:
|
||||
resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
|
||||
|
||||
magic-string@0.30.21:
|
||||
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
|
||||
|
||||
ms@2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
nanoid@3.3.12:
|
||||
resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==}
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
hasBin: true
|
||||
|
||||
pathe@1.1.2:
|
||||
resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==}
|
||||
|
||||
pathval@2.0.1:
|
||||
resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
|
||||
engines: {node: '>= 14.16'}
|
||||
|
||||
picocolors@1.1.1:
|
||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||
|
||||
@@ -338,15 +439,50 @@ packages:
|
||||
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
|
||||
hasBin: true
|
||||
|
||||
siginfo@2.0.0:
|
||||
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
|
||||
|
||||
source-map-js@1.2.1:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
stackback@0.0.2:
|
||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||
|
||||
std-env@3.10.0:
|
||||
resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
|
||||
|
||||
tinybench@2.9.0:
|
||||
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
||||
|
||||
tinyexec@0.3.2:
|
||||
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
|
||||
|
||||
tinypool@1.1.1:
|
||||
resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
|
||||
tinyrainbow@1.2.0:
|
||||
resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
|
||||
tinyspy@3.0.2:
|
||||
resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
|
||||
typescript@5.9.3:
|
||||
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
undici-types@8.3.0:
|
||||
resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==}
|
||||
|
||||
vite-node@2.1.9:
|
||||
resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
hasBin: true
|
||||
|
||||
vite@5.4.21:
|
||||
resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
@@ -378,6 +514,52 @@ packages:
|
||||
terser:
|
||||
optional: true
|
||||
|
||||
vitest@2.1.9:
|
||||
resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@edge-runtime/vm': '*'
|
||||
'@types/node': ^18.0.0 || >=20.0.0
|
||||
'@vitest/browser': 2.1.9
|
||||
'@vitest/ui': 2.1.9
|
||||
happy-dom: '*'
|
||||
jsdom: '*'
|
||||
peerDependenciesMeta:
|
||||
'@edge-runtime/vm':
|
||||
optional: true
|
||||
'@types/node':
|
||||
optional: true
|
||||
'@vitest/browser':
|
||||
optional: true
|
||||
'@vitest/ui':
|
||||
optional: true
|
||||
happy-dom:
|
||||
optional: true
|
||||
jsdom:
|
||||
optional: true
|
||||
|
||||
whatwg-mimetype@3.0.0:
|
||||
resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
why-is-node-running@2.3.0:
|
||||
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
|
||||
engines: {node: '>=8'}
|
||||
hasBin: true
|
||||
|
||||
ws@8.21.3:
|
||||
resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==}
|
||||
engines: {node: '>=10.0.0'}
|
||||
peerDependencies:
|
||||
bufferutil: ^4.0.1
|
||||
utf-8-validate: '>=5.0.2'
|
||||
peerDependenciesMeta:
|
||||
bufferutil:
|
||||
optional: true
|
||||
utf-8-validate:
|
||||
optional: true
|
||||
|
||||
snapshots:
|
||||
|
||||
'@esbuild/aix-ppc64@0.21.5':
|
||||
@@ -449,6 +631,8 @@ snapshots:
|
||||
'@esbuild/win32-x64@0.21.5':
|
||||
optional: true
|
||||
|
||||
'@jridgewell/sourcemap-codec@1.5.5': {}
|
||||
|
||||
'@rollup/rollup-android-arm-eabi@4.60.4':
|
||||
optional: true
|
||||
|
||||
@@ -526,12 +710,90 @@ snapshots:
|
||||
|
||||
'@types/estree@1.0.8': {}
|
||||
|
||||
'@types/node@26.2.0':
|
||||
dependencies:
|
||||
undici-types: 8.3.0
|
||||
|
||||
'@types/whatwg-mimetype@3.0.2': {}
|
||||
|
||||
'@types/ws@8.18.1':
|
||||
dependencies:
|
||||
'@types/node': 26.2.0
|
||||
|
||||
'@vitest/expect@2.1.9':
|
||||
dependencies:
|
||||
'@vitest/spy': 2.1.9
|
||||
'@vitest/utils': 2.1.9
|
||||
chai: 5.3.3
|
||||
tinyrainbow: 1.2.0
|
||||
|
||||
'@vitest/mocker@2.1.9(vite@5.4.21(@types/node@26.2.0))':
|
||||
dependencies:
|
||||
'@vitest/spy': 2.1.9
|
||||
estree-walker: 3.0.3
|
||||
magic-string: 0.30.21
|
||||
optionalDependencies:
|
||||
vite: 5.4.21(@types/node@26.2.0)
|
||||
|
||||
'@vitest/pretty-format@2.1.9':
|
||||
dependencies:
|
||||
tinyrainbow: 1.2.0
|
||||
|
||||
'@vitest/runner@2.1.9':
|
||||
dependencies:
|
||||
'@vitest/utils': 2.1.9
|
||||
pathe: 1.1.2
|
||||
|
||||
'@vitest/snapshot@2.1.9':
|
||||
dependencies:
|
||||
'@vitest/pretty-format': 2.1.9
|
||||
magic-string: 0.30.21
|
||||
pathe: 1.1.2
|
||||
|
||||
'@vitest/spy@2.1.9':
|
||||
dependencies:
|
||||
tinyspy: 3.0.2
|
||||
|
||||
'@vitest/utils@2.1.9':
|
||||
dependencies:
|
||||
'@vitest/pretty-format': 2.1.9
|
||||
loupe: 3.2.1
|
||||
tinyrainbow: 1.2.0
|
||||
|
||||
'@xterm/addon-fit@0.10.0(@xterm/xterm@5.5.0)':
|
||||
dependencies:
|
||||
'@xterm/xterm': 5.5.0
|
||||
|
||||
'@xterm/xterm@5.5.0': {}
|
||||
|
||||
assertion-error@2.0.1: {}
|
||||
|
||||
buffer-image-size@0.6.4:
|
||||
dependencies:
|
||||
'@types/node': 26.2.0
|
||||
|
||||
cac@6.7.14: {}
|
||||
|
||||
chai@5.3.3:
|
||||
dependencies:
|
||||
assertion-error: 2.0.1
|
||||
check-error: 2.1.3
|
||||
deep-eql: 5.0.2
|
||||
loupe: 3.2.1
|
||||
pathval: 2.0.1
|
||||
|
||||
check-error@2.1.3: {}
|
||||
|
||||
debug@4.4.3:
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
|
||||
deep-eql@5.0.2: {}
|
||||
|
||||
entities@7.0.1: {}
|
||||
|
||||
es-module-lexer@1.7.0: {}
|
||||
|
||||
esbuild@0.21.5:
|
||||
optionalDependencies:
|
||||
'@esbuild/aix-ppc64': 0.21.5
|
||||
@@ -558,11 +820,42 @@ snapshots:
|
||||
'@esbuild/win32-ia32': 0.21.5
|
||||
'@esbuild/win32-x64': 0.21.5
|
||||
|
||||
estree-walker@3.0.3:
|
||||
dependencies:
|
||||
'@types/estree': 1.0.8
|
||||
|
||||
expect-type@1.4.0: {}
|
||||
|
||||
fsevents@2.3.3:
|
||||
optional: true
|
||||
|
||||
happy-dom@20.11.6:
|
||||
dependencies:
|
||||
'@types/node': 26.2.0
|
||||
'@types/whatwg-mimetype': 3.0.2
|
||||
'@types/ws': 8.18.1
|
||||
buffer-image-size: 0.6.4
|
||||
entities: 7.0.1
|
||||
whatwg-mimetype: 3.0.0
|
||||
ws: 8.21.3
|
||||
transitivePeerDependencies:
|
||||
- bufferutil
|
||||
- utf-8-validate
|
||||
|
||||
loupe@3.2.1: {}
|
||||
|
||||
magic-string@0.30.21:
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.5.5
|
||||
|
||||
ms@2.1.3: {}
|
||||
|
||||
nanoid@3.3.12: {}
|
||||
|
||||
pathe@1.1.2: {}
|
||||
|
||||
pathval@2.0.1: {}
|
||||
|
||||
picocolors@1.1.1: {}
|
||||
|
||||
postcss@8.5.15:
|
||||
@@ -602,14 +895,96 @@ snapshots:
|
||||
'@rollup/rollup-win32-x64-msvc': 4.60.4
|
||||
fsevents: 2.3.3
|
||||
|
||||
siginfo@2.0.0: {}
|
||||
|
||||
source-map-js@1.2.1: {}
|
||||
|
||||
stackback@0.0.2: {}
|
||||
|
||||
std-env@3.10.0: {}
|
||||
|
||||
tinybench@2.9.0: {}
|
||||
|
||||
tinyexec@0.3.2: {}
|
||||
|
||||
tinypool@1.1.1: {}
|
||||
|
||||
tinyrainbow@1.2.0: {}
|
||||
|
||||
tinyspy@3.0.2: {}
|
||||
|
||||
typescript@5.9.3: {}
|
||||
|
||||
vite@5.4.21:
|
||||
undici-types@8.3.0: {}
|
||||
|
||||
vite-node@2.1.9(@types/node@26.2.0):
|
||||
dependencies:
|
||||
cac: 6.7.14
|
||||
debug: 4.4.3
|
||||
es-module-lexer: 1.7.0
|
||||
pathe: 1.1.2
|
||||
vite: 5.4.21(@types/node@26.2.0)
|
||||
transitivePeerDependencies:
|
||||
- '@types/node'
|
||||
- less
|
||||
- lightningcss
|
||||
- sass
|
||||
- sass-embedded
|
||||
- stylus
|
||||
- sugarss
|
||||
- supports-color
|
||||
- terser
|
||||
|
||||
vite@5.4.21(@types/node@26.2.0):
|
||||
dependencies:
|
||||
esbuild: 0.21.5
|
||||
postcss: 8.5.15
|
||||
rollup: 4.60.4
|
||||
optionalDependencies:
|
||||
'@types/node': 26.2.0
|
||||
fsevents: 2.3.3
|
||||
|
||||
vitest@2.1.9(@types/node@26.2.0)(happy-dom@20.11.6):
|
||||
dependencies:
|
||||
'@vitest/expect': 2.1.9
|
||||
'@vitest/mocker': 2.1.9(vite@5.4.21(@types/node@26.2.0))
|
||||
'@vitest/pretty-format': 2.1.9
|
||||
'@vitest/runner': 2.1.9
|
||||
'@vitest/snapshot': 2.1.9
|
||||
'@vitest/spy': 2.1.9
|
||||
'@vitest/utils': 2.1.9
|
||||
chai: 5.3.3
|
||||
debug: 4.4.3
|
||||
expect-type: 1.4.0
|
||||
magic-string: 0.30.21
|
||||
pathe: 1.1.2
|
||||
std-env: 3.10.0
|
||||
tinybench: 2.9.0
|
||||
tinyexec: 0.3.2
|
||||
tinypool: 1.1.1
|
||||
tinyrainbow: 1.2.0
|
||||
vite: 5.4.21(@types/node@26.2.0)
|
||||
vite-node: 2.1.9(@types/node@26.2.0)
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 26.2.0
|
||||
happy-dom: 20.11.6
|
||||
transitivePeerDependencies:
|
||||
- less
|
||||
- lightningcss
|
||||
- msw
|
||||
- sass
|
||||
- sass-embedded
|
||||
- stylus
|
||||
- sugarss
|
||||
- supports-color
|
||||
- terser
|
||||
|
||||
whatwg-mimetype@3.0.0: {}
|
||||
|
||||
why-is-node-running@2.3.0:
|
||||
dependencies:
|
||||
siginfo: 2.0.0
|
||||
stackback: 0.0.2
|
||||
|
||||
ws@8.21.3: {}
|
||||
|
||||
+17
-13
@@ -1,9 +1,11 @@
|
||||
import * as routes from "./routes.js";
|
||||
import type {
|
||||
ApiError,
|
||||
CreateSessionRequest,
|
||||
DaemonInfo,
|
||||
DirListing,
|
||||
GitRoot,
|
||||
Projects,
|
||||
RecentDirs,
|
||||
Session,
|
||||
Uuid,
|
||||
@@ -25,12 +27,12 @@ async function jsonOrError<T>(res: Response): Promise<T> {
|
||||
}
|
||||
|
||||
export async function listSessions(): Promise<Session[]> {
|
||||
return jsonOrError(await fetch("/api/sessions", { credentials: "same-origin" }));
|
||||
return jsonOrError(await fetch(routes.SESSIONS, { credentials: "same-origin" }));
|
||||
}
|
||||
|
||||
export async function createSession(req: CreateSessionRequest): Promise<Session> {
|
||||
return jsonOrError(
|
||||
await fetch("/api/sessions", {
|
||||
await fetch(routes.SESSIONS, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "content-type": "application/json" },
|
||||
@@ -41,7 +43,7 @@ export async function createSession(req: CreateSessionRequest): Promise<Session>
|
||||
|
||||
export async function killSession(id: Uuid): Promise<void> {
|
||||
await jsonOrError(
|
||||
await fetch(`/api/sessions/${encodeURIComponent(id)}`, {
|
||||
await fetch(routes.session(id), {
|
||||
method: "DELETE",
|
||||
credentials: "same-origin",
|
||||
}),
|
||||
@@ -51,30 +53,32 @@ export async function killSession(id: Uuid): Promise<void> {
|
||||
/** List one directory's immediate subdirectories (NAP-329). `path` may be empty,
|
||||
* `~`, relative, or absolute — the daemon resolves it against its home dir. */
|
||||
export async function listDir(path: string): Promise<DirListing> {
|
||||
const url = `/api/dirs?path=${encodeURIComponent(path)}`;
|
||||
const url = routes.withPathQuery(routes.DIRS, path);
|
||||
return jsonOrError(await fetch(url, { credentials: "same-origin" }));
|
||||
}
|
||||
|
||||
/** Identity + spawn presets of the daemon this web app is connected to (#26). */
|
||||
export async function getDaemonInfo(): Promise<DaemonInfo> {
|
||||
return jsonOrError(await fetch("/api/info", { credentials: "same-origin" }));
|
||||
return jsonOrError(await fetch(routes.INFO, { credentials: "same-origin" }));
|
||||
}
|
||||
|
||||
/** Recently-used working dirs, newest-first and deduped by dir (#26). Drives the
|
||||
* spawn form's recents picker. */
|
||||
/** Recently-used working dirs, newest-first and deduped by dir (#26). */
|
||||
export async function recentDirs(): Promise<RecentDirs> {
|
||||
return jsonOrError(await fetch("/api/recent-dirs", { credentials: "same-origin" }));
|
||||
return jsonOrError(await fetch(routes.RECENT_DIRS, { credentials: "same-origin" }));
|
||||
}
|
||||
|
||||
/** Every discovered git repository / worktree, newest-activity-first (#54).
|
||||
* Drives the spawn form's project picker. */
|
||||
export async function projects(): Promise<Projects> {
|
||||
return jsonOrError(await fetch(routes.PROJECTS, { credentials: "same-origin" }));
|
||||
}
|
||||
|
||||
/** Probe the enclosing git repo of `path` (#26). `root` is absent when the path
|
||||
* isn't inside a repo. `path` may be `~`/relative/absolute; the daemon resolves
|
||||
* it against its home dir. */
|
||||
export async function gitRoot(path: string): Promise<GitRoot> {
|
||||
const url = `/api/gitroot?path=${encodeURIComponent(path)}`;
|
||||
const url = routes.withPathQuery(routes.GITROOT, path);
|
||||
return jsonOrError(await fetch(url, { credentials: "same-origin" }));
|
||||
}
|
||||
|
||||
export function eventsWsUrl(): string {
|
||||
const proto = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
return `${proto}//${location.host}/api/events`;
|
||||
}
|
||||
export { eventsWsUrl } from "./routes.js";
|
||||
|
||||
+80
-89
@@ -2,6 +2,10 @@ import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
|
||||
import { attachWsUrl } from "./routes.js";
|
||||
import { escapeHtml } from "./html.js";
|
||||
import { INITIAL_RECONNECT_MS, MAX_RECONNECT_MS } from "./reconnect.js";
|
||||
import { applyModsToChar, cursorSeq } from "./keys.js";
|
||||
import type { ClientControl, Uuid } from "./types.js";
|
||||
|
||||
/**
|
||||
@@ -34,8 +38,13 @@ export interface AttachOptions {
|
||||
* dropped — but NOT on an intentional `dispose()` (eviction / user close). The
|
||||
* shell uses this to auto-close the pane rather than leave a dead one. */
|
||||
onClosed?: (sessionId: Uuid) => void;
|
||||
/** Asked on every close: should the socket be retried? The shell answers
|
||||
* from the catalog — see `shouldRetryClose`. */
|
||||
shouldReconnect?: (sessionId: Uuid, code: number) => boolean;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** What the header shows about the session (name / command). Optional — falls
|
||||
* back to a short session id when the session isn't known yet. */
|
||||
export interface AttachInfo {
|
||||
@@ -43,24 +52,6 @@ export interface AttachInfo {
|
||||
command: string;
|
||||
}
|
||||
|
||||
function esc(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
/**
|
||||
* Same-origin attach URL. The browser loads from `maestro-web`, which
|
||||
* reverse-proxies this WebSocket to the co-located daemon's `/api/attach/:id`
|
||||
* endpoint.
|
||||
*/
|
||||
function attachStreamUrl(sessionId: Uuid): string {
|
||||
const proto = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
return `${proto}//${location.host}/api/attach/${encodeURIComponent(sessionId)}`;
|
||||
}
|
||||
|
||||
export function createAttachConnection(
|
||||
sessionId: Uuid,
|
||||
opts: AttachOptions = {},
|
||||
@@ -71,16 +62,16 @@ export function createAttachConnection(
|
||||
// Useful identity over a bare UUID: name · command. The full id stays in the
|
||||
// tooltip for when you really need it.
|
||||
const titleHtml = info
|
||||
? `<span class="at-name">${esc(info.name)}</span>` +
|
||||
? `<span class="at-name">${escapeHtml(info.name)}</span>` +
|
||||
(info.command && info.command !== info.name
|
||||
? `<span class="at-cmd">${esc(info.command)}</span>`
|
||||
? `<span class="at-cmd">${escapeHtml(info.command)}</span>`
|
||||
: "")
|
||||
: `session <span class="sid">${esc(sessionId.slice(0, 8))}</span>`;
|
||||
: `session <span class="sid">${escapeHtml(sessionId.slice(0, 8))}</span>`;
|
||||
const titleAttr = info ? `${info.name} · ${info.command} (${sessionId})` : sessionId;
|
||||
el.innerHTML = `
|
||||
<header class="attach-header">
|
||||
<a class="btn btn-ghost back" href="#/" aria-label="Back to catalog" title="Back to catalog">←</a>
|
||||
<span class="attach-title" title="${esc(titleAttr)}">${titleHtml}</span>
|
||||
<span class="attach-title" title="${escapeHtml(titleAttr)}">${titleHtml}</span>
|
||||
<span class="attach-state" data-state="connecting">connecting…</span>
|
||||
<button class="btn btn-ghost btn-icon disconnect" type="button" aria-label="Disconnect" title="Disconnect this session">⏻</button>
|
||||
</header>
|
||||
@@ -264,8 +255,9 @@ export function createAttachConnection(
|
||||
}
|
||||
};
|
||||
|
||||
const ws = new WebSocket(attachStreamUrl(sessionId));
|
||||
ws.binaryType = "arraybuffer";
|
||||
let ws: WebSocket;
|
||||
let reconnectMs = INITIAL_RECONNECT_MS;
|
||||
let reconnectTimer: number | null = null;
|
||||
|
||||
const sendControl = (msg: ClientControl) => {
|
||||
if (ws.readyState !== WebSocket.OPEN) return;
|
||||
@@ -284,50 +276,70 @@ export function createAttachConnection(
|
||||
sendControl({ type: "Resize", cols: term.cols, rows: term.rows });
|
||||
};
|
||||
|
||||
ws.onopen = () => {
|
||||
setState("connected", "open");
|
||||
sendControl({ type: "Resize", cols: term.cols, rows: term.rows });
|
||||
if (mounted) term.focus();
|
||||
};
|
||||
function connect(): void {
|
||||
ws = new WebSocket(attachWsUrl(sessionId));
|
||||
ws.binaryType = "arraybuffer";
|
||||
|
||||
ws.onmessage = (ev) => {
|
||||
if (typeof ev.data === "string") {
|
||||
try {
|
||||
JSON.parse(ev.data) as ClientControl;
|
||||
} catch {
|
||||
// ignore unknown control frames
|
||||
ws.onopen = () => {
|
||||
reconnectMs = INITIAL_RECONNECT_MS;
|
||||
setState("connected", "open");
|
||||
sendControl({ type: "Resize", cols: term.cols, rows: term.rows });
|
||||
if (mounted) term.focus();
|
||||
};
|
||||
|
||||
ws.onmessage = (ev) => {
|
||||
if (typeof ev.data === "string") {
|
||||
try {
|
||||
JSON.parse(ev.data) as ClientControl;
|
||||
} catch {
|
||||
// ignore unknown control frames
|
||||
}
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (ev.data instanceof ArrayBuffer) {
|
||||
term.write(new Uint8Array(ev.data));
|
||||
} else if (ev.data instanceof Blob) {
|
||||
// Some browsers may default to Blob despite binaryType="arraybuffer".
|
||||
ev.data.arrayBuffer().then((b) => term.write(new Uint8Array(b)));
|
||||
}
|
||||
};
|
||||
if (ev.data instanceof ArrayBuffer) {
|
||||
term.write(new Uint8Array(ev.data));
|
||||
} else if (ev.data instanceof Blob) {
|
||||
// Some browsers may default to Blob despite binaryType="arraybuffer".
|
||||
ev.data.arrayBuffer().then((b) => term.write(new Uint8Array(b)));
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
setState("error", "error");
|
||||
};
|
||||
ws.onerror = () => {
|
||||
setState("error", "error");
|
||||
};
|
||||
|
||||
ws.onclose = (ev) => {
|
||||
// The web proxy relays a daemon rejection (unknown session) as an
|
||||
// application close code (4000+) carrying a human reason. Show it in the pane — both the header and the terminal body
|
||||
// — and KEEP the pane up so the user can read why, instead of letting it
|
||||
// flash and vanish (#39). Clean session-ends and ordinary drops keep the
|
||||
// auto-close behavior below.
|
||||
const reason = ev.reason?.trim();
|
||||
if (ev.code >= 4000 && reason && !disposed) {
|
||||
setState(reason, "error");
|
||||
term.write(`\r\n\x1b[31m⚠ cannot attach: ${reason}\x1b[0m\r\n`);
|
||||
return;
|
||||
}
|
||||
setState(`closed (${ev.code})`, "closed");
|
||||
// Only bubble up server/network closes — an intentional dispose has already
|
||||
// set `disposed`, and eviction/user-close handle their own pane teardown.
|
||||
if (!disposed) opts.onClosed?.(sessionId);
|
||||
};
|
||||
ws.onclose = (ev) => {
|
||||
// The web proxy relays a daemon rejection (unknown session) as an
|
||||
// application close code (4000+) carrying a human reason. Show it in the
|
||||
// pane — both the header and the terminal body — and KEEP the pane up so
|
||||
// the user can read why, instead of letting it flash and vanish (#39).
|
||||
const reason = ev.reason?.trim();
|
||||
if (ev.code >= 4000 && reason && !disposed) {
|
||||
setState(reason, "error");
|
||||
term.write(`\r\n\x1b[31m⚠ cannot attach: ${reason}\x1b[0m\r\n`);
|
||||
return;
|
||||
}
|
||||
// An intentional dispose has already set `disposed`; eviction and user
|
||||
// close handle their own pane teardown.
|
||||
if (disposed) return;
|
||||
|
||||
if (opts.shouldReconnect?.(sessionId, ev.code)) {
|
||||
const delay = Math.min(reconnectMs, MAX_RECONNECT_MS);
|
||||
setState("reconnecting…", "connecting");
|
||||
reconnectTimer = window.setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
reconnectMs = Math.min(reconnectMs * 2, MAX_RECONNECT_MS);
|
||||
connect();
|
||||
}, delay);
|
||||
return;
|
||||
}
|
||||
|
||||
setState(`closed (${ev.code})`, "closed");
|
||||
opts.onClosed?.(sessionId);
|
||||
};
|
||||
}
|
||||
|
||||
connect();
|
||||
|
||||
// PTY input: every keystroke goes out as a binary frame. A pending key-bar
|
||||
// Ctrl modifier (mobile) folds into the next typed character here.
|
||||
@@ -372,6 +384,10 @@ export function createAttachConnection(
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
if (reconnectTimer !== null) {
|
||||
window.clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
ro.disconnect();
|
||||
window.removeEventListener("resize", onResize);
|
||||
visual?.removeEventListener("resize", onResize);
|
||||
@@ -431,31 +447,6 @@ const KEY_DEFS: KeyDef[] = [
|
||||
* Fold a single character into its control code: letters and `@[\]^_` map to
|
||||
* 0x00–0x1f, space → NUL, `?` → DEL. Anything else is returned unchanged.
|
||||
*/
|
||||
function toCtrl(ch: string): string {
|
||||
if (ch.length !== 1) return ch;
|
||||
const upper = ch.toUpperCase().codePointAt(0) ?? 0;
|
||||
if (upper >= 0x40 && upper <= 0x5f) return String.fromCodePoint(upper & 0x1f);
|
||||
if (ch === " ") return "\x00";
|
||||
if (ch === "?") return "\x7f";
|
||||
return ch;
|
||||
}
|
||||
|
||||
/** Apply pending modifiers to a single typed character: Ctrl → control code,
|
||||
* Alt → ESC prefix (xterm meta). Both compose (Ctrl+Alt = ESC + control). */
|
||||
function applyModsToChar(ch: string, ctrl: boolean, alt: boolean): string {
|
||||
let out = ctrl ? toCtrl(ch) : ch;
|
||||
if (alt) out = "\x1b" + out;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Cursor/nav-key sequence, promoted to the modified CSI form when Ctrl/Alt are
|
||||
* pending — `\x1b[1;<n><final>`, n = 1 + alt(2) + ctrl(4) (xterm convention). */
|
||||
function cursorSeq(final: string, ctrl: boolean, alt: boolean): string {
|
||||
if (!ctrl && !alt) return `\x1b[${final}`;
|
||||
const n = 1 + (alt ? 2 : 0) + (ctrl ? 4 : 0);
|
||||
return `\x1b[1;${n}${final}`;
|
||||
}
|
||||
|
||||
interface KeyBar {
|
||||
readonly el: HTMLElement;
|
||||
/** Fold pending modifiers into typed input (soft keyboard), consuming them. */
|
||||
|
||||
+4
-88
@@ -1,92 +1,16 @@
|
||||
import { escapeHtml } from "./html.js";
|
||||
import { getDaemonInfo, killSession } from "./api.js";
|
||||
import { HUD_TOGGLE_EVENT, isHudEnabled, toggleHud } from "./debug.js";
|
||||
import { CatalogStore } from "./events.js";
|
||||
import type { Session } from "./types.js";
|
||||
import { abbreviateCwd, abbreviateFolderName, sessionCwd, sessionName } from "./types.js";
|
||||
import { abbreviateFolderName, sessionName } from "./types.js";
|
||||
import type { TreeNode } from "./tree.js";
|
||||
import { buildTree } from "./tree.js";
|
||||
import { openSpawnModal } from "./spawn.js";
|
||||
import { createThemeToggle } from "./theme.js";
|
||||
|
||||
interface TreeFolder {
|
||||
kind: "folder";
|
||||
name: string;
|
||||
path: string;
|
||||
children: TreeNode[];
|
||||
}
|
||||
|
||||
interface TreeLeaf {
|
||||
kind: "leaf";
|
||||
session: Session;
|
||||
}
|
||||
|
||||
type TreeNode = TreeFolder | TreeLeaf;
|
||||
|
||||
const collapsed = new Set<string>();
|
||||
|
||||
function compareNodes(a: TreeNode, b: TreeNode): number {
|
||||
if (a.kind !== b.kind) return a.kind === "folder" ? -1 : 1;
|
||||
const an = a.kind === "folder" ? a.name : sessionName(a.session);
|
||||
const bn = b.kind === "folder" ? b.name : sessionName(b.session);
|
||||
return an.localeCompare(bn);
|
||||
}
|
||||
|
||||
function buildTree(sessions: Session[], home: string | undefined, filter: string): TreeNode {
|
||||
const root: TreeFolder = { kind: "folder", name: "", path: "", children: [] };
|
||||
const lc = filter.trim().toLowerCase();
|
||||
|
||||
for (const s of sessions) {
|
||||
const cwd = sessionCwd(s);
|
||||
const dir = cwd ? abbreviateCwd(cwd, home) : "";
|
||||
if (lc) {
|
||||
const haystack = `${sessionName(s)} ${dir}`.toLowerCase();
|
||||
if (!haystack.includes(lc)) continue;
|
||||
}
|
||||
const parts = dir ? dir.split("/").filter(Boolean) : [];
|
||||
let cursor = root;
|
||||
for (const part of parts) {
|
||||
const path = cursor.path ? `${cursor.path}/${part}` : part;
|
||||
let next = cursor.children.find(
|
||||
(n): n is TreeFolder => n.kind === "folder" && n.name === part,
|
||||
);
|
||||
if (!next) {
|
||||
next = { kind: "folder", name: part, path, children: [] };
|
||||
cursor.children.push(next);
|
||||
}
|
||||
cursor = next;
|
||||
}
|
||||
cursor.children.push({ kind: "leaf", session: s });
|
||||
}
|
||||
|
||||
const sortRec = (n: TreeFolder) => {
|
||||
n.children.sort(compareNodes);
|
||||
for (const c of n.children) if (c.kind === "folder") sortRec(c);
|
||||
};
|
||||
sortRec(root);
|
||||
// Collapse linear directory chains so `~/git.naps.pt/naps62/maestro` reads as
|
||||
// one compact folder rather than four nested ones.
|
||||
root.children = root.children.map((c) => (c.kind === "folder" ? mergeLinear(c) : c));
|
||||
return root;
|
||||
}
|
||||
|
||||
/** Fold a folder with a single folder-child into one node (`a` + `b` → `a/b`),
|
||||
* repeating down the chain, then recurse into the surviving branches. The merged
|
||||
* node keeps the deepest path so collapse/expand state stays stable as it grows. */
|
||||
function mergeLinear(folder: TreeFolder): TreeFolder {
|
||||
let cur = folder;
|
||||
while (cur.children.length === 1 && cur.children[0].kind === "folder") {
|
||||
const child = cur.children[0];
|
||||
cur = {
|
||||
kind: "folder",
|
||||
name: `${cur.name}/${child.name}`,
|
||||
path: child.path,
|
||||
children: child.children,
|
||||
};
|
||||
}
|
||||
cur.children = cur.children.map((c) =>
|
||||
c.kind === "folder" ? mergeLinear(c) : c,
|
||||
);
|
||||
return cur;
|
||||
}
|
||||
|
||||
function renderNode(node: TreeNode, depth: number): HTMLElement {
|
||||
if (node.kind === "folder") {
|
||||
const wrap = document.createElement("div");
|
||||
@@ -163,14 +87,6 @@ function renderNode(node: TreeNode, depth: number): HTMLElement {
|
||||
return row;
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function renderStatusbar(sessions: Session[]): HTMLElement {
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "statusbar";
|
||||
|
||||
@@ -24,6 +24,8 @@ export interface PoolOptions {
|
||||
/** Fired when a connection's socket closes on its own (session ended/dropped),
|
||||
* not via an intentional close/eviction. The embedder closes the pane. */
|
||||
onClosed?: (id: Uuid) => void;
|
||||
/** Forwarded to each connection: should a dropped socket be retried? */
|
||||
shouldReconnect?: (id: Uuid, code: number) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,6 +84,7 @@ export class ConnectionPool {
|
||||
{
|
||||
onRequestClose: (sid) => this.opts.onRequestClose?.(sid),
|
||||
onClosed: (sid) => this.opts.onClosed?.(sid),
|
||||
shouldReconnect: (sid, code) => this.opts.shouldReconnect?.(sid, code) ?? false,
|
||||
},
|
||||
info,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("./api.js", () => ({ listDir: vi.fn() }));
|
||||
|
||||
import { attachDirAutocomplete, type DirAutocompleteHandle } from "./dirAutocomplete.js";
|
||||
import { listDir } from "./api.js";
|
||||
|
||||
const listDirMock = vi.mocked(listDir);
|
||||
|
||||
let input: HTMLInputElement;
|
||||
let nextField: HTMLInputElement;
|
||||
let docKeydown: ReturnType<typeof vi.fn>;
|
||||
let ac: DirAutocompleteHandle | undefined;
|
||||
|
||||
function popup(): HTMLUListElement {
|
||||
return document.querySelector(".dir-ac") as HTMLUListElement;
|
||||
}
|
||||
|
||||
function items(): HTMLElement[] {
|
||||
return [...popup().querySelectorAll<HTMLElement>(".dir-ac-item")];
|
||||
}
|
||||
|
||||
async function type(value: string): Promise<void> {
|
||||
input.focus();
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await vi.advanceTimersByTimeAsync(100); // past the fetch debounce
|
||||
}
|
||||
|
||||
/** Dispatch a cancelable, bubbling keydown on the input; report whether the
|
||||
* default browser behaviour (focus move, form submit) was suppressed. */
|
||||
function press(key: string): { defaultPrevented: boolean } {
|
||||
const evt = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });
|
||||
input.dispatchEvent(evt);
|
||||
return { defaultPrevented: evt.defaultPrevented };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
document.body.replaceChildren();
|
||||
input = document.createElement("input");
|
||||
nextField = document.createElement("input");
|
||||
document.body.append(input, nextField);
|
||||
docKeydown = vi.fn();
|
||||
document.addEventListener("keydown", docKeydown);
|
||||
listDirMock.mockReset().mockResolvedValue({ path: "/tmp", entries: ["proj-a", "proj-b", "other"], truncated: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
ac?.destroy();
|
||||
document.removeEventListener("keydown", docKeydown);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("dirAutocomplete dismissal", () => {
|
||||
it("Escape closes the popup, keeps the typed value and does not propagate", async () => {
|
||||
ac = attachDirAutocomplete(input);
|
||||
await type("/tmp/pro");
|
||||
expect(popup().hidden).toBe(false);
|
||||
|
||||
const { defaultPrevented } = press("Escape");
|
||||
|
||||
expect(defaultPrevented).toBe(true);
|
||||
expect(popup().hidden).toBe(true);
|
||||
expect(input.value).toBe("/tmp/pro");
|
||||
expect(document.activeElement).toBe(input);
|
||||
expect(docKeydown).not.toHaveBeenCalled(); // a draft pane's Escape handler must not fire
|
||||
});
|
||||
|
||||
it("blur dismisses the popup", async () => {
|
||||
ac = attachDirAutocomplete(input);
|
||||
await type("/tmp/pro");
|
||||
expect(popup().hidden).toBe(false);
|
||||
|
||||
input.blur();
|
||||
await vi.advanceTimersByTimeAsync(150);
|
||||
|
||||
expect(popup().hidden).toBe(true);
|
||||
});
|
||||
|
||||
it("does not reopen on refocus until the operator types again", async () => {
|
||||
ac = attachDirAutocomplete(input);
|
||||
await type("/tmp/pro");
|
||||
input.blur();
|
||||
await vi.advanceTimersByTimeAsync(150);
|
||||
|
||||
input.focus();
|
||||
await vi.advanceTimersByTimeAsync(150);
|
||||
expect(popup().hidden).toBe(true);
|
||||
|
||||
await type("/tmp/ot");
|
||||
expect(popup().hidden).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dirAutocomplete keyboard model", () => {
|
||||
it("Tab commits the highlighted entry and lets focus move to the next field", async () => {
|
||||
ac = attachDirAutocomplete(input);
|
||||
await type("/tmp/pro"); // highlight defaults to the first match: proj-a
|
||||
|
||||
nextField.focus();
|
||||
const { defaultPrevented } = press("Tab");
|
||||
|
||||
expect(input.value).toBe("/tmp/proj-a/");
|
||||
expect(defaultPrevented).toBe(false); // native tab navigation proceeds
|
||||
expect(document.activeElement).toBe(nextField); // focus was not yanked back
|
||||
});
|
||||
|
||||
it("Tab with nothing highlighted just moves on", async () => {
|
||||
ac = attachDirAutocomplete(input);
|
||||
await type("/tmp/nope-matches-nothing");
|
||||
expect(popup().hidden).toBe(true);
|
||||
|
||||
const { defaultPrevented } = press("Tab");
|
||||
|
||||
expect(defaultPrevented).toBe(false);
|
||||
expect(input.value).toBe("/tmp/nope-matches-nothing");
|
||||
});
|
||||
|
||||
it("arrows move the highlight and Enter commits it without submitting", async () => {
|
||||
ac = attachDirAutocomplete(input);
|
||||
await type("/tmp/");
|
||||
|
||||
press("ArrowDown");
|
||||
expect(items()[1].classList.contains("is-active")).toBe(true);
|
||||
|
||||
const enter = press("Enter");
|
||||
expect(enter.defaultPrevented).toBe(true); // no form submit
|
||||
expect(input.value).toBe("/tmp/proj-b/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("dirAutocomplete opening", () => {
|
||||
it("still opens on focus when not previously dismissed", async () => {
|
||||
ac = attachDirAutocomplete(input);
|
||||
input.focus();
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
||||
expect(popup().hidden).toBe(false);
|
||||
expect(listDirMock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+44
-46
@@ -4,14 +4,19 @@
|
||||
// per directory, and filters the trailing path segment locally — so typing within a segment is instant and only crossing a `/`
|
||||
// hits the network. Keyboard model mirrors `cd dir/sub<tab>`:
|
||||
//
|
||||
// Tab complete the longest common prefix; if one match, accept it (and
|
||||
// append `/` so the next level loads); if nothing to extend, cycle.
|
||||
// Tab commit the highlighted entry and let focus move on; with nothing
|
||||
// highlighted, plain tab navigation
|
||||
// ↑/↓ move the highlight
|
||||
// Enter accept the highlighted entry (and suppress form submit)
|
||||
// Esc close the dropdown
|
||||
// Esc close the dropdown, refocus the input, and swallow the key so it
|
||||
// can't also discard a surrounding draft pane
|
||||
//
|
||||
// Once dismissed (Esc or blur) the popup stays closed until the operator types
|
||||
// again — refocusing alone doesn't reopen it.
|
||||
//
|
||||
// Failures (offline daemon, permission denied) degrade to no suggestions.
|
||||
|
||||
import { splitPath } from "./paths.js";
|
||||
import { listDir } from "./api.js";
|
||||
|
||||
export interface DirAutocompleteHandle {
|
||||
@@ -26,26 +31,6 @@ const FETCH_DEBOUNCE_MS = 90;
|
||||
/** Split a path value into the directory to list and the trailing fragment
|
||||
* being typed within it. The directory keeps its trailing `/` (or is empty,
|
||||
* meaning "the daemon's home dir"). */
|
||||
function splitPath(value: string): { dir: string; prefix: string } {
|
||||
const slash = value.lastIndexOf("/");
|
||||
if (slash === -1) return { dir: "", prefix: value };
|
||||
return { dir: value.slice(0, slash + 1), prefix: value.slice(slash + 1) };
|
||||
}
|
||||
|
||||
/** Longest common prefix of a list of strings (case-sensitive, preserving the
|
||||
* actual on-disk casing). */
|
||||
function longestCommonPrefix(items: string[]): string {
|
||||
if (items.length === 0) return "";
|
||||
let lcp = items[0];
|
||||
for (const s of items.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < lcp.length && i < s.length && lcp[i] === s[i]) i++;
|
||||
lcp = lcp.slice(0, i);
|
||||
if (lcp === "") break;
|
||||
}
|
||||
return lcp;
|
||||
}
|
||||
|
||||
export function attachDirAutocomplete(input: HTMLInputElement): DirAutocompleteHandle {
|
||||
const dropdown = document.createElement("ul");
|
||||
dropdown.className = "dir-ac";
|
||||
@@ -61,6 +46,9 @@ export function attachDirAutocomplete(input: HTMLInputElement): DirAutocompleteH
|
||||
let fetchSeq = 0;
|
||||
let debounce: number | undefined;
|
||||
let open = false;
|
||||
// Set when the operator dismissed the popup (Esc, blur, outside click); a
|
||||
// refocus must not reopen it — only new typing does.
|
||||
let dismissed = false;
|
||||
|
||||
|
||||
function close(): void {
|
||||
@@ -73,6 +61,11 @@ export function attachDirAutocomplete(input: HTMLInputElement): DirAutocompleteH
|
||||
window.removeEventListener("resize", reposition);
|
||||
}
|
||||
|
||||
function dismiss(): void {
|
||||
dismissed = true;
|
||||
close();
|
||||
}
|
||||
|
||||
function reposition(): void {
|
||||
const r = input.getBoundingClientRect();
|
||||
dropdown.style.left = `${r.left}px`;
|
||||
@@ -116,6 +109,14 @@ export function attachDirAutocomplete(input: HTMLInputElement): DirAutocompleteH
|
||||
}
|
||||
|
||||
function applyFilter(entries: string[], prefix: string): void {
|
||||
// A fetch can outlive the dismissal that was meant to close this popup
|
||||
// (Tab-commit re-arms a refresh, then blur dismisses 120ms later). Showing
|
||||
// it now would anchor a dropdown under an unfocused input that nothing
|
||||
// closes until the next interaction.
|
||||
if (dismissed || document.activeElement !== input) {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
const lower = prefix.toLowerCase();
|
||||
filtered = entries.filter((e) => e.toLowerCase().startsWith(lower));
|
||||
highlight = filtered.length > 0 ? 0 : -1;
|
||||
@@ -151,21 +152,28 @@ export function attachDirAutocomplete(input: HTMLInputElement): DirAutocompleteH
|
||||
}
|
||||
|
||||
// Accept `name` as the next path segment: complete it and append `/` so the
|
||||
// child directory's listing loads immediately (the drill-in gesture).
|
||||
function accept(name: string): void {
|
||||
// child directory's listing loads on the next interaction (the drill-in
|
||||
// gesture). Unlike `accept`, doesn't steal focus — Tab uses this to commit
|
||||
// and move to the next field in one gesture.
|
||||
function commit(name: string): void {
|
||||
const { dir } = splitPath(input.value);
|
||||
input.value = `${dir}${name}/`;
|
||||
input.focus();
|
||||
// Notify other listeners (spawn.ts marks the field user-edited) and load
|
||||
// the child level.
|
||||
// Notify other listeners (spawnForm marks the field user-edited).
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
function accept(name: string): void {
|
||||
commit(name);
|
||||
input.focus();
|
||||
}
|
||||
|
||||
function onInput(): void {
|
||||
dismissed = false;
|
||||
scheduleRefresh();
|
||||
}
|
||||
|
||||
function onFocus(): void {
|
||||
if (dismissed) return;
|
||||
refresh();
|
||||
}
|
||||
|
||||
@@ -173,27 +181,17 @@ export function attachDirAutocomplete(input: HTMLInputElement): DirAutocompleteH
|
||||
if (e.key === "Escape") {
|
||||
if (open) {
|
||||
e.preventDefault();
|
||||
close();
|
||||
// Swallow the key: an Escape that bubbles would also discard the
|
||||
// draft pane hosting this form.
|
||||
e.stopPropagation();
|
||||
dismiss();
|
||||
input.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e.key === "Tab") {
|
||||
if (!open || filtered.length === 0) return; // let focus move normally
|
||||
e.preventDefault();
|
||||
if (filtered.length === 1) {
|
||||
accept(filtered[0]);
|
||||
return;
|
||||
}
|
||||
const { dir, prefix } = splitPath(input.value);
|
||||
const lcp = longestCommonPrefix(filtered);
|
||||
if (lcp.length > prefix.length) {
|
||||
input.value = `${dir}${lcp}`;
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
} else {
|
||||
// Nothing to extend — cycle the highlight like a second shell <tab>.
|
||||
highlight = (highlight + 1) % filtered.length;
|
||||
render();
|
||||
}
|
||||
if (!open || highlight < 0 || highlight >= filtered.length) return; // plain tab navigation
|
||||
commit(filtered[highlight]); // no preventDefault — focus moves to the next field
|
||||
return;
|
||||
}
|
||||
if (!open) return;
|
||||
@@ -215,7 +213,7 @@ export function attachDirAutocomplete(input: HTMLInputElement): DirAutocompleteH
|
||||
|
||||
function onBlur(): void {
|
||||
// Delay so a dropdown mousedown can complete first.
|
||||
window.setTimeout(close, 120);
|
||||
window.setTimeout(dismiss, 120);
|
||||
}
|
||||
|
||||
input.addEventListener("input", onInput);
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
CatalogStore,
|
||||
INITIAL_BACKOFF_MS,
|
||||
MAX_BACKOFF_MS,
|
||||
type CatalogState,
|
||||
type Scheduler,
|
||||
} from "./events.js";
|
||||
import type { CatalogEvent, Session } from "./types.js";
|
||||
|
||||
function session(id: string): Session {
|
||||
return {
|
||||
id,
|
||||
cwd: "/home/n",
|
||||
command: "bash",
|
||||
env: {},
|
||||
metadata: {},
|
||||
status: "Running",
|
||||
created_at: "2026-08-22T00:00:00Z",
|
||||
} as Session;
|
||||
}
|
||||
|
||||
/** Just enough of a WebSocket for the store to drive, plus a way to push frames. */
|
||||
class FakeSocket {
|
||||
onmessage: ((ev: { data: string }) => void) | null = null;
|
||||
onopen: (() => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
closed = false;
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.onopen?.();
|
||||
}
|
||||
|
||||
emit(event: CatalogEvent): void {
|
||||
this.onmessage?.({ data: JSON.stringify(event) });
|
||||
}
|
||||
|
||||
drop(): void {
|
||||
this.onclose?.();
|
||||
}
|
||||
}
|
||||
|
||||
/** Scheduler that records delays instead of waiting them out. */
|
||||
function fakeScheduler(): Scheduler & { delays: number[]; runNext(): void } {
|
||||
const queued: Array<() => void> = [];
|
||||
return {
|
||||
delays: [] as number[],
|
||||
setTimer(fn, ms) {
|
||||
this.delays.push(ms);
|
||||
queued.push(fn);
|
||||
return queued.length;
|
||||
},
|
||||
clearTimer() {},
|
||||
runNext() {
|
||||
queued.shift()?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function storeWith(sockets: FakeSocket[], refetch?: () => Promise<Session[]>) {
|
||||
let i = 0;
|
||||
const scheduler = fakeScheduler();
|
||||
const store = new CatalogStore({
|
||||
socket: () => sockets[i++] as unknown as WebSocket,
|
||||
scheduler,
|
||||
refetch,
|
||||
});
|
||||
return { store, scheduler };
|
||||
}
|
||||
|
||||
describe("CatalogStore reducer", () => {
|
||||
it("replaces state on Snapshot and applies deltas", () => {
|
||||
const ws = new FakeSocket();
|
||||
const { store } = storeWith([ws]);
|
||||
store.start();
|
||||
|
||||
ws.emit({ type: "Snapshot", sessions: [session("a")] } as CatalogEvent);
|
||||
expect([...store.snapshot().sessions.keys()]).toEqual(["a"]);
|
||||
|
||||
ws.emit({ type: "SessionAdded", session: session("b") } as CatalogEvent);
|
||||
expect([...store.snapshot().sessions.keys()].sort()).toEqual(["a", "b"]);
|
||||
|
||||
ws.emit({ type: "SessionRemoved", id: "a" } as CatalogEvent);
|
||||
expect([...store.snapshot().sessions.keys()]).toEqual(["b"]);
|
||||
});
|
||||
|
||||
it("ignores a frame that is not JSON", () => {
|
||||
const ws = new FakeSocket();
|
||||
const { store } = storeWith([ws]);
|
||||
store.start();
|
||||
ws.emit({ type: "Snapshot", sessions: [session("a")] } as CatalogEvent);
|
||||
|
||||
ws.onmessage?.({ data: "not json" });
|
||||
|
||||
expect([...store.snapshot().sessions.keys()]).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("refetches over REST when the server reports dropped frames", async () => {
|
||||
const ws = new FakeSocket();
|
||||
const refetch = vi.fn(async () => [session("fresh")]);
|
||||
const { store } = storeWith([ws], refetch);
|
||||
store.start();
|
||||
ws.emit({ type: "Snapshot", sessions: [session("stale")] } as CatalogEvent);
|
||||
|
||||
ws.emit({ type: "Lagged", skipped: 4 } as CatalogEvent);
|
||||
await vi.waitFor(() => expect(refetch).toHaveBeenCalledOnce());
|
||||
|
||||
expect([...store.snapshot().sessions.keys()]).toEqual(["fresh"]);
|
||||
});
|
||||
|
||||
it("hands each subscriber a copy it can diff against the next one", () => {
|
||||
const ws = new FakeSocket();
|
||||
const { store } = storeWith([ws]);
|
||||
const seen: CatalogState[] = [];
|
||||
store.subscribe((s) => seen.push(s));
|
||||
store.start();
|
||||
|
||||
ws.emit({ type: "Snapshot", sessions: [session("a")] } as CatalogEvent);
|
||||
ws.emit({ type: "SessionAdded", session: session("b") } as CatalogEvent);
|
||||
|
||||
const [, afterSnapshot, afterAdd] = seen;
|
||||
expect(afterSnapshot.sessions).not.toBe(afterAdd.sessions);
|
||||
expect(afterSnapshot.sessions.size).toBe(1);
|
||||
expect(afterAdd.sessions.size).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CatalogStore reconnect", () => {
|
||||
it("doubles the delay per attempt and caps it", () => {
|
||||
const sockets = Array.from({ length: 8 }, () => new FakeSocket());
|
||||
const { store, scheduler } = storeWith(sockets);
|
||||
store.start();
|
||||
|
||||
for (let i = 0; i < 7; i++) {
|
||||
sockets[i].drop();
|
||||
scheduler.runNext();
|
||||
}
|
||||
|
||||
expect(scheduler.delays[0]).toBe(INITIAL_BACKOFF_MS);
|
||||
expect(scheduler.delays[1]).toBe(INITIAL_BACKOFF_MS * 2);
|
||||
expect(scheduler.delays.at(-1)).toBe(MAX_BACKOFF_MS);
|
||||
});
|
||||
|
||||
it("resets the delay once a connection opens", () => {
|
||||
const sockets = [new FakeSocket(), new FakeSocket(), new FakeSocket()];
|
||||
const { store, scheduler } = storeWith(sockets);
|
||||
store.start();
|
||||
|
||||
sockets[0].drop();
|
||||
scheduler.runNext();
|
||||
expect(store.backoff()).toBe(INITIAL_BACKOFF_MS * 2);
|
||||
|
||||
sockets[1].open();
|
||||
expect(store.backoff()).toBe(INITIAL_BACKOFF_MS);
|
||||
});
|
||||
});
|
||||
+54
-10
@@ -7,20 +7,60 @@ export interface CatalogState {
|
||||
|
||||
export type CatalogListener = (state: CatalogState) => void;
|
||||
|
||||
/** Opens the events socket. Injectable so the reducer and the backoff schedule
|
||||
* can be driven without a server. */
|
||||
export type SocketFactory = () => WebSocket;
|
||||
|
||||
/** Schedules a reconnect attempt; returns a handle `clearTimer` understands. */
|
||||
export interface Scheduler {
|
||||
setTimer(fn: () => void, ms: number): number;
|
||||
clearTimer(handle: number): void;
|
||||
}
|
||||
|
||||
const browserScheduler: Scheduler = {
|
||||
setTimer: (fn, ms) => window.setTimeout(fn, ms),
|
||||
clearTimer: (h) => window.clearTimeout(h),
|
||||
};
|
||||
|
||||
/** Initial reconnect delay, doubling to `MAX_BACKOFF_MS`. */
|
||||
export const INITIAL_BACKOFF_MS = 500;
|
||||
export const MAX_BACKOFF_MS = 10_000;
|
||||
|
||||
export interface CatalogStoreOptions {
|
||||
socket?: SocketFactory;
|
||||
scheduler?: Scheduler;
|
||||
/** Full-state refetch used when the server reports it dropped frames. */
|
||||
refetch?: () => Promise<Session[]>;
|
||||
}
|
||||
|
||||
export class CatalogStore {
|
||||
private state: CatalogState = { sessions: new Map() };
|
||||
private listeners = new Set<CatalogListener>();
|
||||
private ws: WebSocket | null = null;
|
||||
private reconnectTimer: number | null = null;
|
||||
private backoffMs = 500;
|
||||
private backoffMs = INITIAL_BACKOFF_MS;
|
||||
private readonly socket: SocketFactory;
|
||||
private readonly scheduler: Scheduler;
|
||||
private readonly refetch: () => Promise<Session[]>;
|
||||
|
||||
constructor(opts: CatalogStoreOptions = {}) {
|
||||
this.socket = opts.socket ?? (() => new WebSocket(eventsWsUrl()));
|
||||
this.scheduler = opts.scheduler ?? browserScheduler;
|
||||
this.refetch = opts.refetch ?? listSessions;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.connect();
|
||||
}
|
||||
|
||||
/** Current reconnect delay, for tests asserting the backoff schedule. */
|
||||
backoff(): number {
|
||||
return this.backoffMs;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.reconnectTimer !== null) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.scheduler.clearTimer(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
if (this.ws) {
|
||||
@@ -36,12 +76,15 @@ export class CatalogStore {
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
/** A copy, so a listener can diff it against the previous one. Returning the
|
||||
* live object meant in-place mutation was invisible and every event forced a
|
||||
* full re-render. */
|
||||
snapshot(): CatalogState {
|
||||
return this.state;
|
||||
return { sessions: new Map(this.state.sessions) };
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
const ws = new WebSocket(eventsWsUrl());
|
||||
const ws = this.socket();
|
||||
this.ws = ws;
|
||||
|
||||
ws.onmessage = (ev) => {
|
||||
@@ -55,7 +98,7 @@ export class CatalogStore {
|
||||
};
|
||||
|
||||
ws.onopen = () => {
|
||||
this.backoffMs = 500;
|
||||
this.backoffMs = INITIAL_BACKOFF_MS;
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
@@ -74,10 +117,10 @@ export class CatalogStore {
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimer !== null) return;
|
||||
const delay = Math.min(this.backoffMs, 10_000);
|
||||
this.reconnectTimer = window.setTimeout(() => {
|
||||
const delay = Math.min(this.backoffMs, MAX_BACKOFF_MS);
|
||||
this.reconnectTimer = this.scheduler.setTimer(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.backoffMs = Math.min(this.backoffMs * 2, 10_000);
|
||||
this.backoffMs = Math.min(this.backoffMs * 2, MAX_BACKOFF_MS);
|
||||
this.connect();
|
||||
}, delay);
|
||||
}
|
||||
@@ -108,7 +151,7 @@ export class CatalogStore {
|
||||
|
||||
private async resync(): Promise<void> {
|
||||
try {
|
||||
const sessions = await listSessions();
|
||||
const sessions = await this.refetch();
|
||||
this.state = {
|
||||
sessions: new Map(sessions.map((s) => [s.id, s])),
|
||||
};
|
||||
@@ -119,6 +162,7 @@ export class CatalogStore {
|
||||
}
|
||||
|
||||
private emit(): void {
|
||||
for (const fn of this.listeners) fn(this.state);
|
||||
const snap = this.snapshot();
|
||||
for (const fn of this.listeners) fn(snap);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// One HTML escaper. Previously written four times, in catalog.ts, spawn.ts,
|
||||
// types.ts and attach.ts.
|
||||
|
||||
export function escapeHtml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { applyModsToChar, cursorSeq, toCtrl } from "./keys.js";
|
||||
|
||||
describe("toCtrl", () => {
|
||||
it("maps letters to their control code, case-insensitively", () => {
|
||||
expect(toCtrl("a")).toBe("\x01");
|
||||
expect(toCtrl("A")).toBe("\x01");
|
||||
expect(toCtrl("c")).toBe("\x03");
|
||||
expect(toCtrl("[")).toBe("\x1b");
|
||||
});
|
||||
|
||||
it("handles the two specials outside the @-_ range", () => {
|
||||
expect(toCtrl(" ")).toBe("\x00");
|
||||
expect(toCtrl("?")).toBe("\x7f");
|
||||
});
|
||||
|
||||
it("passes through anything it has no mapping for", () => {
|
||||
expect(toCtrl("1")).toBe("1");
|
||||
expect(toCtrl("é")).toBe("é");
|
||||
expect(toCtrl("abc")).toBe("abc");
|
||||
expect(toCtrl("")).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyModsToChar", () => {
|
||||
it("composes ctrl and alt, with ESC outermost", () => {
|
||||
expect(applyModsToChar("a", false, false)).toBe("a");
|
||||
expect(applyModsToChar("a", true, false)).toBe("\x01");
|
||||
expect(applyModsToChar("a", false, true)).toBe("\x1ba");
|
||||
expect(applyModsToChar("a", true, true)).toBe("\x1b\x01");
|
||||
});
|
||||
});
|
||||
|
||||
describe("cursorSeq", () => {
|
||||
it("uses the bare CSI form when unmodified", () => {
|
||||
expect(cursorSeq("A", false, false)).toBe("\x1b[A");
|
||||
});
|
||||
|
||||
it("uses the xterm modifier encoding n = 1 + alt(2) + ctrl(4)", () => {
|
||||
expect(cursorSeq("A", false, true)).toBe("\x1b[1;3A");
|
||||
expect(cursorSeq("A", true, false)).toBe("\x1b[1;5A");
|
||||
expect(cursorSeq("A", true, true)).toBe("\x1b[1;7A");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// Terminal key encoding: control characters, meta prefixes, and cursor escape
|
||||
// sequences. Table-driven and easy to get subtly wrong, so it lives apart from
|
||||
// the DOM and is tested directly.
|
||||
|
||||
export function toCtrl(ch: string): string {
|
||||
if (ch.length !== 1) return ch;
|
||||
const upper = ch.toUpperCase().codePointAt(0) ?? 0;
|
||||
if (upper >= 0x40 && upper <= 0x5f) return String.fromCodePoint(upper & 0x1f);
|
||||
if (ch === " ") return "\x00";
|
||||
if (ch === "?") return "\x7f";
|
||||
return ch;
|
||||
}
|
||||
|
||||
/** Apply pending modifiers to a single typed character: Ctrl → control code,
|
||||
* Alt → ESC prefix (xterm meta). Both compose (Ctrl+Alt = ESC + control). */
|
||||
export function applyModsToChar(ch: string, ctrl: boolean, alt: boolean): string {
|
||||
let out = ctrl ? toCtrl(ch) : ch;
|
||||
if (alt) out = "\x1b" + out;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Cursor/nav-key sequence, promoted to the modified CSI form when Ctrl/Alt are
|
||||
* pending — `\x1b[1;<n><final>`, n = 1 + alt(2) + ctrl(4) (xterm convention). */
|
||||
export function cursorSeq(final: string, ctrl: boolean, alt: boolean): string {
|
||||
if (!ctrl && !alt) return `\x1b[${final}`;
|
||||
const n = 1 + (alt ? 2 : 0) + (ctrl ? 4 : 0);
|
||||
return `\x1b[1;${n}${final}`;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
emptyLayout,
|
||||
leaves,
|
||||
locateSession,
|
||||
openSessions,
|
||||
removeLeaf,
|
||||
splitLeaf,
|
||||
type Tab,
|
||||
} from "./layout.js";
|
||||
|
||||
function tabWithOneLeaf(sessionId: string | null = null): Tab {
|
||||
const layout = emptyLayout();
|
||||
const tab = layout.tabs[0];
|
||||
splitLeaf(tab, "", sessionId, "row", true);
|
||||
return tab;
|
||||
}
|
||||
|
||||
describe("splitLeaf", () => {
|
||||
it("seeds an empty tab with a single leaf", () => {
|
||||
const tab = tabWithOneLeaf("s1");
|
||||
expect(leaves(tab.root)).toHaveLength(1);
|
||||
expect(leaves(tab.root)[0].sessionId).toBe("s1");
|
||||
});
|
||||
|
||||
it("splits a leaf in two and returns the new id", () => {
|
||||
const tab = tabWithOneLeaf("s1");
|
||||
const target = leaves(tab.root)[0].id;
|
||||
|
||||
const fresh = splitLeaf(tab, target, "s2", "row", true);
|
||||
|
||||
const ids = leaves(tab.root).map((l) => l.id);
|
||||
expect(ids).toHaveLength(2);
|
||||
expect(ids).toContain(fresh);
|
||||
});
|
||||
|
||||
it("honours the side the caller asked for", () => {
|
||||
const tab = tabWithOneLeaf("s1");
|
||||
const target = leaves(tab.root)[0].id;
|
||||
const fresh = splitLeaf(tab, target, "s2", "row", false);
|
||||
|
||||
expect(leaves(tab.root)[0].id).toBe(fresh);
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeLeaf", () => {
|
||||
it("collapses the parent split into the surviving sibling", () => {
|
||||
const tab = tabWithOneLeaf("s1");
|
||||
const first = leaves(tab.root)[0].id;
|
||||
splitLeaf(tab, first, "s2", "row", true);
|
||||
|
||||
removeLeaf(tab, first);
|
||||
|
||||
const remaining = leaves(tab.root);
|
||||
expect(remaining).toHaveLength(1);
|
||||
expect(remaining[0].sessionId).toBe("s2");
|
||||
expect(tab.root?.kind).toBe("leaf");
|
||||
});
|
||||
|
||||
it("empties the tab when the last leaf goes", () => {
|
||||
const tab = tabWithOneLeaf("s1");
|
||||
removeLeaf(tab, leaves(tab.root)[0].id);
|
||||
expect(tab.root).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("locateSession / openSessions", () => {
|
||||
it("finds the tab and leaf showing a session", () => {
|
||||
const layout = emptyLayout();
|
||||
const tab = layout.tabs[0];
|
||||
splitLeaf(tab, "", "s1", "row", true);
|
||||
|
||||
const hit = locateSession(layout, "s1");
|
||||
expect(hit?.tab.id).toBe(tab.id);
|
||||
expect(hit?.leaf.sessionId).toBe("s1");
|
||||
expect(locateSession(layout, "nope")).toBeNull();
|
||||
});
|
||||
|
||||
it("reports every open session once", () => {
|
||||
const layout = emptyLayout();
|
||||
const tab = layout.tabs[0];
|
||||
splitLeaf(tab, "", "s1", "row", true);
|
||||
const first = leaves(tab.root)[0].id;
|
||||
splitLeaf(tab, first, "s2", "row", true);
|
||||
|
||||
expect(openSessions(layout)).toEqual(new Set(["s1", "s2"]));
|
||||
});
|
||||
});
|
||||
+17
-2
@@ -11,8 +11,23 @@ import type { Uuid } from "./types.js";
|
||||
|
||||
export type Dir = "row" | "col";
|
||||
|
||||
/** Half-filled spawn-form state for a draft pane (issue #57): an empty leaf
|
||||
* renders the spawn form instead of a placeholder, and each pane's values
|
||||
* hang off its own leaf so two drafts stay independent. Never persisted —
|
||||
* a reload gives back an empty form (persistence strips it). */
|
||||
export interface Draft {
|
||||
command: string;
|
||||
cwd: string;
|
||||
name: string;
|
||||
worktreeEnabled?: boolean;
|
||||
worktreeBranch?: string;
|
||||
worktreeCleanup?: boolean;
|
||||
/** Whether the cwd lives in the raw text input (vs a picked recent row). */
|
||||
cwdRawVisible?: boolean;
|
||||
}
|
||||
|
||||
export type Node =
|
||||
| { kind: "leaf"; id: string; sessionId: Uuid | null }
|
||||
| { kind: "leaf"; id: string; sessionId: Uuid | null; draft?: Draft | null }
|
||||
| { kind: "split"; dir: Dir; a: Node; b: Node; ratio: number };
|
||||
|
||||
export type Leaf = Extract<Node, { kind: "leaf" }>;
|
||||
@@ -89,7 +104,7 @@ export function splitLeaf(
|
||||
dir: Dir,
|
||||
after: boolean,
|
||||
): string {
|
||||
const fresh: Leaf = { kind: "leaf", id: freshId("l"), sessionId };
|
||||
const fresh: Leaf = { kind: "leaf", id: freshId("l"), sessionId, draft: null };
|
||||
const rec = (n: Node): Node => {
|
||||
if (n.kind === "leaf") {
|
||||
if (n.id !== targetId) return n;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { renderSidebar, renderTopbar } from "./catalog.js";
|
||||
import { ConnectionPool } from "./connections.js";
|
||||
import { installHudKeybind } from "./debug.js";
|
||||
import { CatalogStore } from "./events.js";
|
||||
import { shouldRetryClose } from "./reconnect.js";
|
||||
import { mountHud, type Hud } from "./hud.js";
|
||||
import { emptyLayout, type Layout, openSessions } from "./layout.js";
|
||||
import { createMultiView, type MultiView } from "./multiview.js";
|
||||
@@ -149,6 +150,17 @@ const pool = new ConnectionPool({
|
||||
// pane is never left lying around.
|
||||
onRequestClose: (id) => closePane(id),
|
||||
onClosed: (id) => closePane(id),
|
||||
shouldReconnect: (id, code) => shouldRetryClose(id, code, store.snapshot().sessions),
|
||||
});
|
||||
|
||||
// Session death used to reach the UI on two uncoordinated channels — the row
|
||||
// from the events socket, the pane from `ws.onclose` — so either could happen
|
||||
// without the other. The catalog is the authority: a pane for a session that is
|
||||
// no longer listed gets closed here.
|
||||
store.subscribe((state) => {
|
||||
for (const id of mv?.openSessions() ?? []) {
|
||||
if (!state.sessions.has(id)) closePane(id);
|
||||
}
|
||||
});
|
||||
|
||||
function closePane(id: string): void {
|
||||
@@ -224,6 +236,9 @@ mv = createMultiView({
|
||||
infoFor,
|
||||
onDisconnect: closePane,
|
||||
renderWelcome,
|
||||
// A draft-pane submit (#57) fills its leaf in place; the shell route may flip
|
||||
// from catalog (no sessions) to attach.
|
||||
onOpenSessionsChange: updateShellRoute,
|
||||
onLayoutChange: scheduleSave,
|
||||
});
|
||||
let contentShowsMv = false;
|
||||
|
||||
+35
-12
@@ -33,8 +33,8 @@ function sess(
|
||||
};
|
||||
}
|
||||
|
||||
/** Stub the spawn-form backend endpoints (#26) so `?mock&spawn` renders the full
|
||||
* tile-first flow — presets, recents, gitroot — with no daemon running. Dev-only;
|
||||
/** Stub the spawn-form backend endpoints (#26/#59) so `?mock&spawn` renders the
|
||||
* full flow — presets, projects, gitroot — with no daemon running. Dev-only;
|
||||
* delegates every other request to the real `fetch`. */
|
||||
function stubSpawnApi(): void {
|
||||
const real = globalThis.fetch.bind(globalThis);
|
||||
@@ -61,16 +61,39 @@ function stubSpawnApi(): void {
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (path.includes("/recent-dirs")) {
|
||||
if (path.includes("/projects")) {
|
||||
const now = Date.now();
|
||||
const iso = (daysAgo: number) => new Date(now - daysAgo * 86_400_000).toISOString();
|
||||
return Promise.resolve(
|
||||
json({
|
||||
dirs: [
|
||||
{ cwd: "/home/dev/git/maestro", last_command: "claude", last_used: "2026-06-20T10:00:00Z" },
|
||||
{ cwd: "/home/dev/git/dotfiles", last_command: "zsh", last_used: "2026-06-19T18:00:00Z" },
|
||||
{ cwd: "/home/dev/work/acme/api", last_command: "opencode", last_used: "2026-06-18T09:00:00Z" },
|
||||
],
|
||||
truncated: false,
|
||||
}),
|
||||
json([
|
||||
{
|
||||
path: "/home/dev/git/maestro",
|
||||
name: "maestro",
|
||||
is_worktree: false,
|
||||
last_activity: iso(0),
|
||||
last_command: "claude",
|
||||
},
|
||||
{
|
||||
path: "/home/dev/worktrees/maestro-59",
|
||||
name: "maestro-59",
|
||||
is_worktree: true,
|
||||
base_repo: "/home/dev/git/maestro",
|
||||
last_activity: iso(1),
|
||||
last_command: "opencode",
|
||||
},
|
||||
{
|
||||
path: "/home/dev/git/dotfiles",
|
||||
name: "dotfiles",
|
||||
is_worktree: false,
|
||||
last_activity: iso(30),
|
||||
last_command: "zsh",
|
||||
},
|
||||
{
|
||||
path: "/home/dev/work/acme/api",
|
||||
name: "api",
|
||||
is_worktree: false,
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (path.includes("/gitroot")) {
|
||||
@@ -113,7 +136,7 @@ export function seedMock(store: CatalogStore): void {
|
||||
});
|
||||
|
||||
// `?mock&spawn` auto-opens the spawn modal for visual review, with the spawn
|
||||
// backend endpoints stubbed so presets/recents/gitroot all render.
|
||||
// backend endpoints stubbed so presets/projects/gitroot all render.
|
||||
if (location.search.includes("spawn")) {
|
||||
stubSpawnApi();
|
||||
void import("./spawn.js").then((m) => m.openSpawnModal());
|
||||
|
||||
+45
-3
@@ -1,8 +1,9 @@
|
||||
// The multi-view renderer/controller (issues #30 splits, #31 tabs, #33
|
||||
// highlights). Owns the tab bar + canvas inside the content pane, builds the
|
||||
// active tab's split tree into DOM, and mounts a live AttachConnection into each
|
||||
// session leaf via the pool. Empty leaves (freshly split, not yet filled) show a
|
||||
// placeholder. Drag-to-dock is a later issue (#32); mobile projection is #35.
|
||||
// session leaf via the pool. Empty leaves are draft panes (#57): they render
|
||||
// the spawn form inline, and submitting replaces the draft with that session's
|
||||
// terminal in place. Drag-to-dock is issue #32; mobile projection is #35.
|
||||
|
||||
import type { SidebarHandle } from "./catalog.js";
|
||||
import type { ConnectionPool } from "./connections.js";
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
} from "./layout.js";
|
||||
import { sessionColor } from "./sessioncolor.js";
|
||||
import type { AttachInfo } from "./attach.js";
|
||||
import { createSpawnForm, type SpawnFormHandle } from "./spawnForm.js";
|
||||
|
||||
export interface MultiViewOptions {
|
||||
pool: ConnectionPool;
|
||||
@@ -33,6 +35,9 @@ export interface MultiViewOptions {
|
||||
onDisconnect: (sessionId: string) => void;
|
||||
/** Welcome content for an empty tab. */
|
||||
renderWelcome: () => HTMLElement;
|
||||
/** Called when a draft-pane submit turns an empty pane into a session pane,
|
||||
* so the shell can re-evaluate its route (sidebar vs attach layout). */
|
||||
onOpenSessionsChange?: () => void;
|
||||
/** Called after any layout change (structure, focus, or divider resize) so the
|
||||
* shell can persist it (issue #34). */
|
||||
onLayoutChange?: () => void;
|
||||
@@ -45,6 +50,8 @@ export interface MultiView {
|
||||
openSession: (sessionId: string) => void;
|
||||
/** Drop the pane showing `sessionId` (the session was disconnected/killed). */
|
||||
closeSession: (sessionId: string) => void;
|
||||
/** Every session currently shown in some pane, across all tabs. */
|
||||
openSessions: () => Set<string>;
|
||||
/** Start dragging a sidebar session into the canvas (issue #32). The
|
||||
* controller owns drag-vs-tap: a tap lets the row's normal click open it, a
|
||||
* drag shows drop zones to place it. */
|
||||
@@ -58,6 +65,10 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
||||
const { pool, layout, sidebar, infoFor, onDisconnect, renderWelcome } = opts;
|
||||
const persist = () => opts.onLayoutChange?.();
|
||||
|
||||
// Draft-pane forms (#57) carry global listeners (dir autocomplete), so each
|
||||
// render tears down the previous generation before rebuilding the canvas.
|
||||
const draftForms = new Set<SpawnFormHandle>();
|
||||
|
||||
const el = document.createElement("div");
|
||||
el.className = "mv";
|
||||
const tabBar = document.createElement("div");
|
||||
@@ -131,7 +142,32 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
||||
const host = document.createElement("div");
|
||||
host.className = "mv-pane-host";
|
||||
if (!leaf.sessionId) {
|
||||
host.innerHTML = `<div class="mv-pane-empty">Empty pane — pick a session from the sidebar.</div>`;
|
||||
// Draft pane (#57): an empty pane is a spawn form. Values hang off the
|
||||
// leaf (never persisted) so each draft keeps its own half-filled state;
|
||||
// submitting fills this leaf with the new session in place.
|
||||
const form = createSpawnForm({
|
||||
seed: leaf.draft ?? undefined,
|
||||
class: "mv-draft",
|
||||
onChange: (values) => {
|
||||
leaf.draft = values;
|
||||
},
|
||||
onSuccess: (session) => {
|
||||
// The pane can be closed while the POST is in flight. Mounting the
|
||||
// session onto a leaf no longer in the tree would strand it in no
|
||||
// pane at all, so only claim the leaf while it is still there.
|
||||
const t = activeTab(layout);
|
||||
const attached = leaves(t.root).includes(leaf);
|
||||
if (attached) {
|
||||
leaf.sessionId = session.id;
|
||||
leaf.draft = null;
|
||||
t.focusedLeafId = leaf.id;
|
||||
}
|
||||
render();
|
||||
opts.onOpenSessionsChange?.();
|
||||
},
|
||||
});
|
||||
draftForms.add(form);
|
||||
host.appendChild(form.el);
|
||||
}
|
||||
|
||||
const tools = document.createElement("div");
|
||||
@@ -324,6 +360,7 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
||||
// Fill the focused pane (VS Code style: open replaces the active group).
|
||||
const target = (tab.focusedLeafId && findLeaf(tab.root, tab.focusedLeafId)) || leaves(tab.root)[0];
|
||||
target.sessionId = sessionId;
|
||||
target.draft = null;
|
||||
tab.focusedLeafId = target.id;
|
||||
render();
|
||||
}
|
||||
@@ -331,6 +368,8 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
||||
// ---- top-level render ----
|
||||
|
||||
function render(): void {
|
||||
for (const f of draftForms) f.destroy();
|
||||
draftForms.clear();
|
||||
renderTabs();
|
||||
canvas.replaceChildren();
|
||||
const tab = activeTab(layout);
|
||||
@@ -567,6 +606,7 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
||||
if (source.kind === "pane" && self) {
|
||||
const dragged = findLeaf(tab.root, self)!;
|
||||
[dragged.sessionId, target.sessionId] = [target.sessionId, dragged.sessionId];
|
||||
[dragged.draft, target.draft] = [target.draft, dragged.draft];
|
||||
tab.focusedLeafId = target.id;
|
||||
} else if (sessionId) {
|
||||
const loc = locateSession(layout, sessionId);
|
||||
@@ -574,6 +614,7 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
||||
const t2 = findLeaf(tab.root, targetLeafId);
|
||||
if (t2) {
|
||||
t2.sessionId = sessionId;
|
||||
t2.draft = null;
|
||||
tab.focusedLeafId = t2.id;
|
||||
}
|
||||
}
|
||||
@@ -599,6 +640,7 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
||||
el,
|
||||
openSession,
|
||||
closeSession,
|
||||
openSessions: () => openSessions(layout),
|
||||
beginSessionDrag,
|
||||
render,
|
||||
focusedSessionId: focusedLeafSession,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { longestCommonPrefix, splitPath } from "./paths.js";
|
||||
|
||||
describe("splitPath", () => {
|
||||
it("splits on the last slash, keeping it with the directory", () => {
|
||||
expect(splitPath("/home/n/wo")).toEqual({ dir: "/home/n/", prefix: "wo" });
|
||||
expect(splitPath("/home/n/")).toEqual({ dir: "/home/n/", prefix: "" });
|
||||
});
|
||||
|
||||
it("treats a slash-free value as all prefix", () => {
|
||||
expect(splitPath("work")).toEqual({ dir: "", prefix: "work" });
|
||||
expect(splitPath("")).toEqual({ dir: "", prefix: "" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("longestCommonPrefix", () => {
|
||||
it("returns the shared head", () => {
|
||||
expect(longestCommonPrefix(["maestro", "maestro-web"])).toBe("maestro");
|
||||
expect(longestCommonPrefix(["abc"])).toBe("abc");
|
||||
});
|
||||
|
||||
it("is empty when nothing is shared", () => {
|
||||
expect(longestCommonPrefix(["abc", "xyz"])).toBe("");
|
||||
expect(longestCommonPrefix([])).toBe("");
|
||||
});
|
||||
|
||||
it("preserves on-disk casing rather than folding it", () => {
|
||||
expect(longestCommonPrefix(["Alpha", "alpha"])).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// Path splitting and completion arithmetic for the working-directory input.
|
||||
|
||||
export function splitPath(value: string): { dir: string; prefix: string } {
|
||||
const slash = value.lastIndexOf("/");
|
||||
if (slash === -1) return { dir: "", prefix: value };
|
||||
return { dir: value.slice(0, slash + 1), prefix: value.slice(slash + 1) };
|
||||
}
|
||||
|
||||
/** Longest common prefix of a list of strings (case-sensitive, preserving the
|
||||
* actual on-disk casing). */
|
||||
export function longestCommonPrefix(items: string[]): string {
|
||||
if (items.length === 0) return "";
|
||||
let lcp = items[0];
|
||||
for (const s of items.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < lcp.length && i < s.length && lcp[i] === s[i]) i++;
|
||||
lcp = lcp.slice(0, i);
|
||||
if (lcp === "") break;
|
||||
}
|
||||
return lcp;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { hydrate, serializeLayout } from "./persistence.js";
|
||||
import { leaves, type Layout } from "./layout.js";
|
||||
|
||||
describe("hydrate", () => {
|
||||
it("rejects anything that is not a tab-bearing object", () => {
|
||||
expect(hydrate(null)).toBeNull();
|
||||
expect(hydrate("nope")).toBeNull();
|
||||
expect(hydrate({})).toBeNull();
|
||||
expect(hydrate({ tabs: [] })).toBeNull();
|
||||
expect(hydrate({ tabs: "no" })).toBeNull();
|
||||
});
|
||||
|
||||
it("rebuilds tabs and re-issues ids rather than trusting stored ones", () => {
|
||||
const layout = hydrate({
|
||||
tabs: [{ id: "old", title: "Work", root: { kind: "leaf", id: "l1", sessionId: "s1" } }],
|
||||
activeTabId: "old",
|
||||
});
|
||||
|
||||
expect(layout).not.toBeNull();
|
||||
expect(layout!.tabs).toHaveLength(1);
|
||||
expect(layout!.tabs[0].title).toBe("Work");
|
||||
expect(layout!.tabs[0].id).not.toBe("old");
|
||||
expect(layout!.activeTabId).toBe(layout!.tabs[0].id);
|
||||
expect(leaves(layout!.tabs[0].root)[0].sessionId).toBe("s1");
|
||||
});
|
||||
|
||||
it("carries the focused leaf across the id reissue", () => {
|
||||
const layout = hydrate({
|
||||
tabs: [
|
||||
{
|
||||
id: "t",
|
||||
root: {
|
||||
kind: "split",
|
||||
dir: "row",
|
||||
a: { kind: "leaf", id: "l1", sessionId: "s1" },
|
||||
b: { kind: "leaf", id: "l2", sessionId: "s2" },
|
||||
},
|
||||
focusedLeafId: "l2",
|
||||
},
|
||||
],
|
||||
activeTabId: "t",
|
||||
});
|
||||
|
||||
const tab = layout!.tabs[0];
|
||||
const focused = leaves(tab.root).find((l) => l.id === tab.focusedLeafId);
|
||||
expect(focused?.sessionId).toBe("s2");
|
||||
});
|
||||
|
||||
it("falls back to a default title and the first tab as active", () => {
|
||||
const layout = hydrate({ tabs: [{ id: "a" }, { id: "b" }], activeTabId: "missing" });
|
||||
expect(layout!.tabs[0].title).toBe("Tab 1");
|
||||
expect(layout!.activeTabId).toBe(layout!.tabs[0].id);
|
||||
});
|
||||
|
||||
it("drops a malformed split branch instead of failing the whole layout", () => {
|
||||
const layout = hydrate({
|
||||
tabs: [{ id: "t", root: { kind: "split", dir: "row", a: null, b: { kind: "leaf", id: "l", sessionId: "s" } } }],
|
||||
activeTabId: "t",
|
||||
});
|
||||
expect(leaves(layout!.tabs[0].root).map((l) => l.sessionId)).toEqual(["s"]);
|
||||
});
|
||||
|
||||
it("never restores draft state, even if a stale blob carries it", () => {
|
||||
const layout = hydrate({
|
||||
tabs: [
|
||||
{ id: "t", root: { kind: "leaf", id: "l1", sessionId: null, draft: { command: "zsh", cwd: "/x" } } },
|
||||
],
|
||||
activeTabId: "t",
|
||||
});
|
||||
expect(leaves(layout!.tabs[0].root)[0]).not.toHaveProperty("draft");
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeLayout", () => {
|
||||
it("strips draft state so a reload gives back an empty form", () => {
|
||||
const layout = hydrate({
|
||||
tabs: [
|
||||
{
|
||||
id: "t",
|
||||
root: {
|
||||
kind: "split",
|
||||
dir: "row",
|
||||
a: { kind: "leaf", id: "l1", sessionId: "s1" },
|
||||
b: { kind: "leaf", id: "l2", sessionId: null },
|
||||
},
|
||||
},
|
||||
],
|
||||
activeTabId: "t",
|
||||
}) as Layout;
|
||||
const draftLeaf = leaves(layout.tabs[0].root).find((l) => !l.sessionId)!;
|
||||
draftLeaf.draft = { command: "claude", cwd: "/home/user/project", name: "amber-fox" };
|
||||
|
||||
const restored = hydrate(JSON.parse(serializeLayout(layout)).layout);
|
||||
expect(restored).not.toBeNull();
|
||||
for (const leaf of leaves(restored!.tabs[0].root)) {
|
||||
expect(leaf.draft ?? null).toBeNull();
|
||||
}
|
||||
expect(leaves(restored!.tabs[0].root).map((l) => l.sessionId)).toEqual(["s1", null]);
|
||||
});
|
||||
|
||||
it("keeps the draft out of the stored blob itself, not just out of hydrate", () => {
|
||||
// A draft pane only exists once a tab has split, so the strip has to walk
|
||||
// into split branches; asserting on the restored layout alone passes even
|
||||
// when the draft was written to localStorage, because hydrate drops it.
|
||||
const layout = hydrate({
|
||||
tabs: [
|
||||
{
|
||||
id: "t",
|
||||
root: {
|
||||
kind: "split",
|
||||
dir: "row",
|
||||
a: { kind: "leaf", id: "l1", sessionId: "s1" },
|
||||
b: { kind: "leaf", id: "l2", sessionId: null },
|
||||
},
|
||||
},
|
||||
],
|
||||
activeTabId: "t",
|
||||
}) as Layout;
|
||||
const draftLeaf = leaves(layout.tabs[0].root).find((l) => !l.sessionId)!;
|
||||
draftLeaf.draft = { command: "claude", cwd: "/home/user/secret-project", name: "amber-fox" };
|
||||
|
||||
const raw = serializeLayout(layout);
|
||||
expect(raw).not.toContain("secret-project");
|
||||
expect(raw).not.toContain("amber-fox");
|
||||
});
|
||||
});
|
||||
+25
-2
@@ -14,12 +14,35 @@ const VERSION = 1;
|
||||
|
||||
export function saveLayout(layout: Layout): void {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify({ v: VERSION, layout }));
|
||||
localStorage.setItem(KEY, serializeLayout(layout));
|
||||
} catch {
|
||||
// Storage full or unavailable (private mode) — persistence is best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
/** Serialise the layout for storage with draft state stripped (issue #57): a
|
||||
* reload gives back an empty form, never a stale half-filled one. */
|
||||
export function serializeLayout(layout: Layout): string {
|
||||
const clean: Layout = {
|
||||
...layout,
|
||||
tabs: layout.tabs.map((t) => ({
|
||||
...t,
|
||||
root: stripDrafts(t.root),
|
||||
})),
|
||||
};
|
||||
return JSON.stringify({ v: VERSION, layout: clean });
|
||||
}
|
||||
|
||||
function stripDrafts(node: Node | null): Node | null {
|
||||
if (!node) return node;
|
||||
// Recurse: a draft pane only exists once a tab has split, so a shallow strip
|
||||
// would persist every half-filled form it was meant to drop.
|
||||
if (node.kind === "split") {
|
||||
return { ...node, a: stripDrafts(node.a)!, b: stripDrafts(node.b)! };
|
||||
}
|
||||
return { ...node, draft: null };
|
||||
}
|
||||
|
||||
export function loadLayout(): Layout | null {
|
||||
let raw: string | null;
|
||||
try {
|
||||
@@ -37,7 +60,7 @@ export function loadLayout(): Layout | null {
|
||||
}
|
||||
}
|
||||
|
||||
function hydrate(raw: unknown): Layout | null {
|
||||
export function hydrate(raw: unknown): Layout | null {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const r = raw as { tabs?: unknown; activeTabId?: unknown };
|
||||
if (!Array.isArray(r.tabs) || r.tabs.length === 0) return null;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { filterProjects, groupProjects, isStale, sortProjects } from "./projectList.js";
|
||||
import type { Project } from "./types.js";
|
||||
|
||||
const NOW = new Date("2026-08-23T12:00:00Z");
|
||||
|
||||
function project(overrides: Partial<Project>): Project {
|
||||
return {
|
||||
path: `/home/user/${overrides.name ?? "proj"}`,
|
||||
name: "proj",
|
||||
is_worktree: false,
|
||||
last_activity: undefined,
|
||||
last_command: undefined,
|
||||
...overrides,
|
||||
} as Project;
|
||||
}
|
||||
|
||||
describe("isStale", () => {
|
||||
it("marks projects with no known activity stale", () => {
|
||||
expect(isStale(project({ name: "never" }), NOW)).toBe(true);
|
||||
});
|
||||
|
||||
it("is fresh within 7 days and stale beyond", () => {
|
||||
const fresh = project({ name: "fresh", last_activity: "2026-08-17T00:00:00Z" });
|
||||
const stale = project({ name: "stale", last_activity: "2026-08-16T11:59:00Z" });
|
||||
expect(isStale(fresh, NOW)).toBe(false);
|
||||
expect(isStale(stale, NOW)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortProjects", () => {
|
||||
it("sorts newest-activity first", () => {
|
||||
const a = project({ name: "a", last_activity: "2026-08-20T00:00:00Z" });
|
||||
const b = project({ name: "b", last_activity: "2026-08-22T00:00:00Z" });
|
||||
expect(sortProjects([a, b], NOW).map((p) => p.name)).toEqual(["b", "a"]);
|
||||
});
|
||||
|
||||
it("sorts stale rows after fresh ones, each block newest first", () => {
|
||||
const freshOld = project({ name: "fresh-old", last_activity: "2026-08-18T00:00:00Z" });
|
||||
const freshNew = project({ name: "fresh-new", last_activity: "2026-08-23T00:00:00Z" });
|
||||
const staleNew = project({ name: "stale-new", last_activity: "2026-08-10T00:00:00Z" });
|
||||
const staleNone = project({ name: "stale-none" });
|
||||
const sorted = sortProjects([staleNew, freshOld, staleNone, freshNew], NOW);
|
||||
expect(sorted.map((p) => p.name)).toEqual(["fresh-new", "fresh-old", "stale-new", "stale-none"]);
|
||||
});
|
||||
|
||||
it("does not mutate the input", () => {
|
||||
const a = project({ name: "a", last_activity: "2026-08-01T00:00:00Z" });
|
||||
const b = project({ name: "b", last_activity: "2026-08-02T00:00:00Z" });
|
||||
sortProjects([a, b], NOW);
|
||||
expect(a.name).toBe("a");
|
||||
});
|
||||
});
|
||||
|
||||
describe("groupProjects", () => {
|
||||
it("keeps plain repositories as their own single-entry group", () => {
|
||||
const solo = project({ name: "solo" });
|
||||
expect(groupProjects(sortProjects([solo], NOW))).toEqual([{ main: solo, worktrees: [] }]);
|
||||
});
|
||||
|
||||
it("nests worktrees under their base repository even when fresher than it", () => {
|
||||
const main = project({ name: "maestro" });
|
||||
const wt = project({
|
||||
name: "wt",
|
||||
path: "/elsewhere/wt",
|
||||
is_worktree: true,
|
||||
base_repo: main.path,
|
||||
last_activity: "2026-08-23T00:00:00Z",
|
||||
});
|
||||
const groups = groupProjects(sortProjects([wt, main], NOW));
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0].main).toBe(main);
|
||||
expect(groups[0].worktrees).toEqual([wt]);
|
||||
});
|
||||
|
||||
it("orders groups by the freshest member and worktrees by activity", () => {
|
||||
const mainA = project({ name: "a", path: "/w/a", last_activity: "2026-08-01T00:00:00Z" });
|
||||
const wtA = project({
|
||||
name: "a-wt",
|
||||
path: "/w/a-wt",
|
||||
is_worktree: true,
|
||||
base_repo: "/w/a",
|
||||
last_activity: "2026-08-20T00:00:00Z",
|
||||
});
|
||||
const mainB = project({ name: "b", path: "/w/b", last_activity: "2026-08-15T00:00:00Z" });
|
||||
const wtB1 = project({
|
||||
name: "b-wt1",
|
||||
path: "/w/b-wt1",
|
||||
is_worktree: true,
|
||||
base_repo: "/w/b",
|
||||
last_activity: "2026-08-19T00:00:00Z",
|
||||
});
|
||||
const wtB2 = project({
|
||||
name: "b-wt2",
|
||||
path: "/w/b-wt2",
|
||||
is_worktree: true,
|
||||
base_repo: "/w/b",
|
||||
last_activity: "2026-08-21T00:00:00Z",
|
||||
});
|
||||
|
||||
const groups = groupProjects(sortProjects([mainA, mainB, wtB1, wtA, wtB2], NOW));
|
||||
expect(groups.map((g) => g.main.name)).toEqual(["b", "a"]);
|
||||
const gA = groups.find((g) => g.main.name === "a")!;
|
||||
const gB = groups.find((g) => g.main.name === "b")!;
|
||||
expect(gA.worktrees.map((p) => p.name)).toEqual(["a-wt"]);
|
||||
expect(gB.worktrees.map((p) => p.name)).toEqual(["b-wt2", "b-wt1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterProjects", () => {
|
||||
const maestro = project({ name: "maestro", path: "/home/u/git/maestro" });
|
||||
const tea = project({ name: "tea", path: "/home/u/work/tea" });
|
||||
|
||||
it("matches on name case-insensitively", () => {
|
||||
expect(filterProjects([maestro, tea], "MAES")).toEqual([maestro]);
|
||||
});
|
||||
|
||||
it("matches on the full path", () => {
|
||||
expect(filterProjects([maestro, tea], "work")).toEqual([tea]);
|
||||
});
|
||||
|
||||
it("returns everything unchanged for an empty query", () => {
|
||||
expect(filterProjects([maestro, tea], " ")).toEqual([maestro, tea]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
// Pure helpers behind the spawn form's project picker (#59): staleness,
|
||||
// recency ordering, worktree grouping, and free-text filtering. The daemon
|
||||
// reports the timestamps; what "stale" means is a client decision (#54).
|
||||
|
||||
import type { Project } from "./types.js";
|
||||
|
||||
/** Projects whose last activity is older than this are dimmed and sort after
|
||||
* fresh ones — still reachable, visibly stale (#59). */
|
||||
export const STALE_AFTER_DAYS = 7;
|
||||
|
||||
export function isStale(project: Project, now: Date): boolean {
|
||||
if (!project.last_activity) return true;
|
||||
const age = now.getTime() - Date.parse(project.last_activity);
|
||||
return !(age >= 0) || age > STALE_AFTER_DAYS * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
/** Fresh rows first, each block newest-activity-first; unknown or future
|
||||
* timestamps sort as stalest. Ties fall back to name so the order is stable. */
|
||||
export function sortProjects(projects: Project[], now: Date): Project[] {
|
||||
return [...projects].sort((a, b) => {
|
||||
const staleDiff = (isStale(a, now) ? 1 : 0) - (isStale(b, now) ? 1 : 0);
|
||||
if (staleDiff !== 0) return staleDiff;
|
||||
const ta = timeOf(a);
|
||||
const tb = timeOf(b);
|
||||
if (ta !== tb) return tb - ta;
|
||||
return a.name.localeCompare(b.name) || a.path.localeCompare(b.path);
|
||||
});
|
||||
}
|
||||
|
||||
function timeOf(project: Project): number {
|
||||
return project.last_activity ? Date.parse(project.last_activity) : Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
/** One repository group: the main checkout followed by its linked worktrees.
|
||||
* A group's position follows its freshest member, since a worktree worked on
|
||||
* today should pull its (dormant) base repo up with it. */
|
||||
export interface ProjectGroup {
|
||||
main: Project;
|
||||
worktrees: Project[];
|
||||
}
|
||||
|
||||
/** Group `sorted` projects by their base repository. A worktree nests under
|
||||
* its main checkout even when the main sorts later; a main checkout missing
|
||||
* from the list doesn't drop its worktrees. */
|
||||
export function groupProjects(sorted: Project[]): ProjectGroup[] {
|
||||
const members = new Map<string, Project[]>();
|
||||
const keys: string[] = [];
|
||||
for (const p of sorted) {
|
||||
const key = p.base_repo ?? p.path;
|
||||
let list = members.get(key);
|
||||
if (!list) {
|
||||
list = [];
|
||||
members.set(key, list);
|
||||
keys.push(key);
|
||||
}
|
||||
list.push(p);
|
||||
}
|
||||
return keys.map((key) => {
|
||||
const list = members.get(key)!;
|
||||
const main = list.find((p) => p.path === key && !p.is_worktree) ?? list[0];
|
||||
// Keep the daemon's newest-first order within the group.
|
||||
const worktrees = list
|
||||
.filter((p) => p !== main)
|
||||
.sort((a, b) => timeOf(b) - timeOf(a));
|
||||
return { main, worktrees };
|
||||
});
|
||||
}
|
||||
|
||||
/** Substring filter over project name and full path, case-insensitive. */
|
||||
export function filterProjects(projects: Project[], query: string): Project[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return [...projects];
|
||||
return projects.filter(
|
||||
(p) => p.name.toLowerCase().includes(q) || p.path.toLowerCase().includes(q),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createSpawnForm, type SpawnFormHandle } from "./spawnForm.js";
|
||||
import type { Project } from "./types.js";
|
||||
|
||||
const NOW = "2026-08-23T12:00:00Z";
|
||||
|
||||
function project(overrides: Partial<Project>): Project {
|
||||
return {
|
||||
path: `/home/user/${overrides.name ?? "proj"}`,
|
||||
name: "proj",
|
||||
is_worktree: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Two fetches gate the form's initial load: /api/info then /api/projects. */
|
||||
function stubFetch(info: unknown, projects: Project[]): void {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
const body = url.includes("/api/info")
|
||||
? info
|
||||
: url.includes("/api/projects")
|
||||
? projects
|
||||
: undefined;
|
||||
return new Response(JSON.stringify(body), { status: 200 });
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function rowPaths(form: HTMLFormElement): string[] {
|
||||
return [...form.querySelectorAll<HTMLButtonElement>(".project-row:not(.project-other)")].map(
|
||||
(r) => r.dataset.cwd ?? "",
|
||||
);
|
||||
}
|
||||
|
||||
describe("spawnForm project picker", () => {
|
||||
let handle: SpawnFormHandle | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ now: Date.parse(NOW) });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
handle?.destroy();
|
||||
handle = null;
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
async function mount(projects: Project[], seed?: Parameters<typeof createSpawnForm>[0]["seed"]) {
|
||||
stubFetch({ hostname: "h", version: "0", home_dir: "/home/user", presets: [] }, projects);
|
||||
handle = createSpawnForm({
|
||||
seed,
|
||||
onSuccess() {},
|
||||
});
|
||||
document.body.appendChild(handle.el);
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
return handle;
|
||||
}
|
||||
|
||||
it("renders one row per project, fresh before stale", async () => {
|
||||
const fresh = project({ name: "fresh", path: "/home/user/fresh", last_activity: NOW });
|
||||
const stale = project({
|
||||
name: "stale",
|
||||
path: "/home/user/stale",
|
||||
last_activity: "2026-01-01T00:00:00Z",
|
||||
});
|
||||
const form = (await mount([stale, fresh])).el;
|
||||
expect(rowPaths(form)).toEqual(["/home/user/fresh", "/home/user/stale"]);
|
||||
const rows = [...form.querySelectorAll<HTMLButtonElement>(".project-row")];
|
||||
expect(rows[1].classList.contains("is-stale")).toBe(true);
|
||||
expect(rows[0].classList.contains("is-stale")).toBe(false);
|
||||
});
|
||||
|
||||
it("nests worktrees under their base repository", async () => {
|
||||
const main = project({ name: "maestro", path: "/home/user/maestro" });
|
||||
const wt = project({
|
||||
name: "wt",
|
||||
path: "/elsewhere/wt",
|
||||
is_worktree: true,
|
||||
base_repo: main.path,
|
||||
});
|
||||
const form = (await mount([wt, main])).el;
|
||||
expect(rowPaths(form)).toEqual(["/home/user/maestro", "/elsewhere/wt"]);
|
||||
const [mainRow, wtRow] = [
|
||||
...form.querySelectorAll(".project-row:not(.project-other)"),
|
||||
];
|
||||
expect(wtRow.classList.contains("is-worktree")).toBe(true);
|
||||
expect(mainRow.classList.contains("is-worktree")).toBe(false);
|
||||
});
|
||||
|
||||
it("filters rows as the operator types", async () => {
|
||||
const a = project({ name: "maestro", path: "/home/user/maestro" });
|
||||
const b = project({ name: "tea", path: "/home/user/work/tea" });
|
||||
const form = (await mount([a, b])).el;
|
||||
const filter = form.querySelector<HTMLInputElement>(".project-filter")!;
|
||||
filter.value = "tea";
|
||||
filter.dispatchEvent(new Event("input"));
|
||||
expect(rowPaths(form)).toEqual(["/home/user/work/tea"]);
|
||||
filter.value = "zzz";
|
||||
filter.dispatchEvent(new Event("input"));
|
||||
expect(rowPaths(form)).toEqual([]);
|
||||
expect(form.querySelector(".picker-empty")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("picking a project selects its cwd and pre-selects its last command", async () => {
|
||||
const p = project({
|
||||
name: "maestro",
|
||||
path: "/home/user/maestro",
|
||||
last_command: "claude",
|
||||
});
|
||||
const onChange = vi.fn();
|
||||
stubFetch(
|
||||
{
|
||||
hostname: "h",
|
||||
version: "0",
|
||||
home_dir: "/home/user",
|
||||
presets: [
|
||||
{ id: "claude", label: "Claude", command: "claude" },
|
||||
{ id: "custom", label: "Custom…", command: "" },
|
||||
],
|
||||
},
|
||||
[p],
|
||||
);
|
||||
handle = createSpawnForm({ onSuccess() {}, onChange });
|
||||
const form = handle.el;
|
||||
document.body.appendChild(form);
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
onChange.mockClear();
|
||||
|
||||
const row = form.querySelector<HTMLButtonElement>(".project-row")!;
|
||||
row.click();
|
||||
|
||||
const values = form.querySelector<HTMLInputElement>("input[name=name]")!.value;
|
||||
const last = onChange.mock.lastCall![0];
|
||||
expect(last.cwd).toBe("/home/user/maestro");
|
||||
expect(last.command).toBe("claude");
|
||||
expect(values).toBeTruthy();
|
||||
// The raw input stays hidden — the picked row is the source of truth.
|
||||
expect((form.querySelector(".cwd-raw-wrap") as HTMLElement).hidden).toBe(true);
|
||||
expect(row.classList.contains("is-active")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps an 'Other directory…' escape hatch that reveals the raw input", async () => {
|
||||
const p = project({ name: "maestro", path: "/home/user/maestro" });
|
||||
const form = (await mount([p])).el;
|
||||
const other = form.querySelector<HTMLButtonElement>(".project-other")!;
|
||||
other.click();
|
||||
expect((form.querySelector(".cwd-raw-wrap") as HTMLElement).hidden).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the raw input when no projects exist", async () => {
|
||||
const form = (await mount([])).el;
|
||||
expect((form.querySelector(".cwd-raw-wrap") as HTMLElement).hidden).toBe(false);
|
||||
const raw = form.querySelector<HTMLInputElement>(".cwd-raw")!;
|
||||
expect(raw.value).toBe("/home/user");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// The reconnect *policy* — which closes are retried and which end the pane.
|
||||
// `createAttachConnection` itself needs a DOM and xterm, so the decision is
|
||||
// tested here as the predicate the shell supplies, plus the backoff schedule
|
||||
// it drives.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { INITIAL_RECONNECT_MS, MAX_RECONNECT_MS, shouldRetryClose } from "./reconnect.js";
|
||||
import type { Session } from "./types.js";
|
||||
|
||||
function session(id: string, status: Session["status"]): Session {
|
||||
return {
|
||||
id,
|
||||
cwd: "/home/n",
|
||||
command: "bash",
|
||||
env: {},
|
||||
metadata: {},
|
||||
status,
|
||||
created_at: "2026-08-22T00:00:00Z",
|
||||
} as Session;
|
||||
}
|
||||
|
||||
describe("shouldRetryClose", () => {
|
||||
const running = new Map([["a", session("a", "Running")]]);
|
||||
const dead = new Map([["a", session("a", "Dead")]]);
|
||||
const gone = new Map<string, Session>();
|
||||
|
||||
it("retries a dropped link to a session that is still running", () => {
|
||||
expect(shouldRetryClose("a", 1006, running)).toBe(true);
|
||||
expect(shouldRetryClose("a", 1001, running)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not retry a session the daemon has marked dead", () => {
|
||||
// Its stream is sealed; nothing further will ever arrive.
|
||||
expect(shouldRetryClose("a", 1006, dead)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not retry a session that is no longer in the catalog", () => {
|
||||
expect(shouldRetryClose("a", 1006, gone)).toBe(false);
|
||||
});
|
||||
|
||||
it("never retries an application close, which carries a daemon rejection", () => {
|
||||
// 4000+ means the proxy relayed a refusal — retrying would loop on it.
|
||||
expect(shouldRetryClose("a", 4502, running)).toBe(false);
|
||||
});
|
||||
|
||||
it("never retries a clean close", () => {
|
||||
expect(shouldRetryClose("a", 1000, running)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("backoff bounds", () => {
|
||||
it("starts well under a second and caps at ten", () => {
|
||||
expect(INITIAL_RECONNECT_MS).toBeLessThan(1000);
|
||||
expect(MAX_RECONNECT_MS).toBe(10_000);
|
||||
});
|
||||
|
||||
it("reaches the cap by doubling and never exceeds it", () => {
|
||||
let ms = INITIAL_RECONNECT_MS;
|
||||
for (let i = 0; i < 20; i++) ms = Math.min(ms * 2, MAX_RECONNECT_MS);
|
||||
expect(ms).toBe(MAX_RECONNECT_MS);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user