diff --git a/CHANGELOG.md b/CHANGELOG.md index 9faee4c6..a3bffd63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,30 @@ and listed with their assets on the ## [Unreleased] +### Added + +- **Worktrees show at once, and a stopped stack's lanes too** + ([ADR-0078](docs/adr/0078-the-hub-follows-every-stacks-worktrees.md)): + the hub follows every stack's worktrees and tells the dashboard when one + is added, removed or switches branch, so the sidebar shows it without + opening its stack first. A stack that does not run lists its worktrees + as lanes not started; one opens a start card, and *Start here* or *Start + in the pool* brings its daemon up and starts the lane, the main working + tree's services left stopped. A lane the branch picker makes for a + stopped stack opens there. +- **A stack's dot in the sidebar sums up its trees**: folded, it shows the + worst of its trees' dots (a failed start first); unfolded it has none, as + its trees show theirs. The main working tree's and a lane's dot are red + when one of their services fails (as last seen), yellow for trouble on a + lane's node. A stack whose daemon runs + but nothing of it says `idle`, as one without a daemon says `offline`. +- **The sidebar keeps its order**: stacks by name, and a stack's trees + with the main working tree first, then by name; a start or a stop no + longer moves anything. +- **The tab follows you**: opening another stack or lane keeps the tab + shown (Infrastructure, Commands, Usage, Activity), also coming back from + the pool area, instead of going back to Overview. + ### Fixed - **`devstack up --on` moves a started lane**: a lane started on a node @@ -77,6 +101,9 @@ since not showing, and dashboard details. - **A lane not started shows no tabs**: its start options stand in for its views, so Overview, Infrastructure and the others no longer all led to the same start page. +- **A tree not started says so first**: a dashed box across the page + above its start options, which no running tree shows; the stack's + offline banner no longer repeats it. - **The pool's devstack column** no longer shows a stray "–" after a node's version when no update runs. - **A GitHub skill set names its commit**: the set showed diff --git a/crates/devstack-daemon/src/lanes.rs b/crates/devstack-daemon/src/lanes.rs index f38cabd6..135de8e6 100644 --- a/crates/devstack-daemon/src/lanes.rs +++ b/crates/devstack-daemon/src/lanes.rs @@ -749,7 +749,7 @@ pub fn worktree_of(repo: &Path, path: &Path) -> Option { /// What changes in `/worktrees` when a worktree is added or /// removed or checks out another branch: its entries and their `HEAD`s. -fn fingerprint(dir: &Path) -> Vec<(std::ffi::OsString, Option)> { +pub fn fingerprint(dir: &Path) -> Vec<(std::ffi::OsString, Option)> { let mut out: Vec<_> = std::fs::read_dir(dir) .into_iter() .flatten() diff --git a/crates/devstack-hub/src/branches.rs b/crates/devstack-hub/src/branches.rs index 6bfd8f83..ddbb2e6b 100644 --- a/crates/devstack-hub/src/branches.rs +++ b/crates/devstack-hub/src/branches.rs @@ -146,7 +146,7 @@ fn git_with( } /// The repository's git directory shared by its worktrees. -fn common_dir(repo: &Path) -> Result { +pub(crate) fn common_dir(repo: &Path) -> Result { let d = git(repo, &["rev-parse", "--git-common-dir"], LOCAL)?; Ok(repo.join(d.trim())) } diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index 4bc00808..cc6d493a 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -53,6 +53,7 @@ mod stdio; mod summary; pub mod tray; pub mod upstreams; +mod worktrees; mod ws; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -451,6 +452,8 @@ pub fn serve() -> Result<(), String> { // The pools, followed over their coordinators' streams (ADR-0073): // their guest lanes and MCP upstreams (ADR-0069 option B). poolfeed::start(state.upstreams.clone(), state.skills.clone()); + // Every stack's worktrees, its daemon running or not (ADR-0078). + worktrees::start(); tray::start_quietly(); let app = router(state); if let Some(v6) = v6 { @@ -532,10 +535,14 @@ fn router(state: AppState) -> axum::Router { .route("/hub/stacks/add", post(stack_add)) .route("/hub/stacks/scan", post(stack_scan)) .route("/hub/stacks/{id}/up", post(stack_up)) + .route("/hub/stacks/{id}/lanes/start", post(worktrees::start_lane)) .route("/hub/stacks/{id}/down", post(stack_down)) .route("/hub/stacks/{id}", delete(forget)) .route("/hub/stacks/{id}/branches", get(stack_branches)) - .route("/hub/stacks/{id}/worktrees", post(worktree_add)) + .route( + "/hub/stacks/{id}/worktrees", + get(worktrees::list).post(worktree_add), + ) .route("/hub/stacks/{id}/worktrees/remove", post(worktree_remove)) .route("/hub/stacks/{id}/fetch", post(stack_fetch)) // No route writes a file of a repository (ADR-0071). @@ -1506,6 +1513,8 @@ fn hub_events(s: &AppState) -> impl tokio_stream::Stream impl tokio_stream::Stream/worktrees` of each stack once a +//! second (what the daemon of a running stack does too: its entries and +//! their `HEAD`s, a local folder) and tells dashboards on `/hub/events` +//! (`worktrees`: a version per stack) when one was added, removed or +//! checked out another branch; the dashboard reads that stack's lanes +//! again then. +//! - `GET /hub/stacks/{id}/worktrees`: a stack's worktrees as lanes not +//! started, for a stack whose daemon does not run. +//! - `POST /hub/stacks/{id}/lanes/start {path, on?}`: start a worktree's +//! lane as `devstack up` in it does: the daemon comes up, the main working +//! tree's services stay stopped. `on`: a node of the pool or `pool`; +//! without it, this machine. + +use axum::Json; +use axum::extract::{Path as UrlPath, State}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; +use std::time::Duration; +use tokio::sync::watch; + +/// How often the folders are looked at. +const EVERY: Duration = Duration::from_secs(1); + +fn sender() -> &'static watch::Sender> { + static TX: OnceLock>> = OnceLock::new(); + TX.get_or_init(|| watch::channel(BTreeMap::new()).0) +} + +/// Each stack's worktrees' version now, and each change. +pub fn subscribe() -> watch::Receiver> { + sender().subscribe() +} + +/// Start looking, once per hub. +pub fn start() { + static ONCE: OnceLock<()> = OnceLock::new(); + if ONCE.set(()).is_err() { + return; + } + let _ = std::thread::Builder::new() + .name("worktrees".into()) + .spawn(|| { + // A stack's git directory, asked of git once. + let mut dirs: HashMap> = HashMap::new(); + loop { + let stacks = devstack_daemon::registry::list(); + let mut now = BTreeMap::new(); + for e in &stacks { + let dir = dirs + .entry(e.id.clone()) + .or_insert_with(|| crate::branches::common_dir(&e.repo).ok()) + .clone(); + let Some(dir) = dir else { continue }; + let print = devstack_daemon::lanes::fingerprint(&dir.join("worktrees")); + now.insert(e.id.clone(), version(&print)); + } + dirs.retain(|id, _| stacks.iter().any(|e| &e.id == id)); + sender().send_if_modified(|v| { + if *v == now { + false + } else { + *v = now; + true + } + }); + std::thread::sleep(EVERY); + } + }); +} + +fn version(print: &[(std::ffi::OsString, Option)]) -> String { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + print.hash(&mut h); + format!("{:016x}", h.finish()) +} + +/// A worktree as the dashboard's lane list has it, not started. +#[derive(Debug, Serialize)] +pub struct Worktree { + pub name: String, + pub path: PathBuf, + pub branch: Option, + pub number: u32, + pub active: bool, + pub port_offset: u32, + pub owns_main: bool, + pub running: u32, + pub services: u32, + /// It has no stack file of its own: it runs with the main tree's. + pub main_stack_file: bool, + /// Why it cannot start on a node of the pool (ADR-0028). + #[serde(skip_serializing_if = "Option::is_none")] + pub not_in_pool: Option<&'static str>, +} + +/// The worktrees of the stack in `repo` with its stack file `file`, the +/// main working tree left out. +pub fn of(repo: &Path, file: &Path) -> Vec { + let rel = file + .strip_prefix(repo) + .map(Path::to_path_buf) + .unwrap_or_else(|_| PathBuf::from(file.file_name().unwrap_or("devstack.toml".as_ref()))); + devstack_daemon::lanes::worktree_branches(repo) + .unwrap_or_default() + .into_iter() + .filter(|(p, _)| !devstack_daemon::lanes::same_tree(p, repo)) + .map(|(path, branch)| { + let own = path.join(&rel); + let has_own = own.is_file(); + // As the daemon names it (a second of one name gets `-2` there). + let base = devstack_daemon::lanes::lane_name( + &path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + ); + let name = if base.is_empty() || base == "main" { + format!("lane-{base}").trim_end_matches('-').to_string() + } else { + base + }; + Worktree { + name, + not_in_pool: devstack_daemon::lanes::not_in_pool(if has_own { &own } else { file }), + main_stack_file: !has_own, + path, + branch, + number: 0, + active: false, + port_offset: 0, + owns_main: false, + running: 0, + services: 0, + } + }) + .collect() +} + +/// `GET /hub/stacks/{id}/worktrees`. +pub async fn list(State(s): State, UrlPath(id): UrlPath) -> Response { + let Some(e) = crate::entry(&s, &id) else { + return crate::err(StatusCode::NOT_FOUND, "no such stack"); + }; + match tokio::task::spawn_blocking(move || of(&e.repo, &e.file)).await { + Ok(v) => Json(v).into_response(), + Err(e) => crate::err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +#[derive(Deserialize)] +pub struct StartBody { + pub path: String, + #[serde(default)] + pub on: Option, + /// A profile of the stack file (ADR-0041). + #[serde(default)] + pub profile: Option, +} + +/// `POST /hub/stacks/{id}/lanes/start {path, on?, profile?}`: `devstack up` in the +/// worktree `path` (one git lists for the stack), `--on local` without +/// `on`. `202` once started; a start that fails before the daemon runs is +/// the stack's `start_error`, as a stack's start. +pub async fn start_lane( + State(s): State, + UrlPath(id): UrlPath, + Json(b): Json, +) -> Response { + let Some(e) = crate::entry(&s, &id) else { + return crate::err(StatusCode::NOT_FOUND, "no such stack"); + }; + let on = b.on.map(|o| o.trim().to_string()).filter(|o| !o.is_empty()); + if on.as_deref().is_some_and(|o| { + o.len() > 100 + || !o + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-_.:".contains(c)) + }) { + return crate::err( + StatusCode::BAD_REQUEST, + "`on`: a node, `:` or `pool`", + ); + } + let profile = b + .profile + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty()); + if profile.as_deref().is_some_and(|p| { + p.len() > 64 + || !p + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-_".contains(c)) + }) { + return crate::err(StatusCode::BAD_REQUEST, "`profile`: a profile's name"); + } + let raw = PathBuf::from(&b.path); + let repo = e.repo.clone(); + let tree = tokio::task::spawn_blocking(move || { + devstack_daemon::lanes::worktree_of(&repo, &raw) + .filter(|t| !devstack_daemon::lanes::same_tree(t, &repo)) + }) + .await + .ok() + .flatten(); + let Some(tree) = tree else { + return crate::err( + StatusCode::BAD_REQUEST, + "not a worktree of this stack's repository", + ); + }; + let Ok(exe) = crate::devstack_exe() else { + return crate::err(StatusCode::INTERNAL_SERVER_ERROR, "cannot find devstack"); + }; + s.start_errors.lock().unwrap().remove(&id); + let log = crate::state_dir().join(format!("up-{id}-lane.log")); + let Ok((out, out2)) = std::fs::File::create(&log).and_then(|f| Ok((f.try_clone()?, f))) else { + return crate::err( + StatusCode::INTERNAL_SERVER_ERROR, + "cannot write the start's log", + ); + }; + let mut cmd = std::process::Command::new(exe); + cmd.arg("up") + .arg("--on") + .arg(on.as_deref().unwrap_or("local")) + .args(profile.iter().flat_map(|p| ["--profile", p.as_str()])) + .current_dir(&tree) + .env("NO_COLOR", "1") + .stdin(std::process::Stdio::null()) + .stdout(out) + .stderr(out2); + crate::no_window(&mut cmd); + let mut child = match cmd.spawn() { + Ok(c) => c, + Err(e) => return crate::err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + }; + let errors = s.start_errors.clone(); + let repo = e.repo.clone(); + std::thread::spawn(move || { + if child.wait().is_ok_and(|st| st.success()) { + return; + } + // A daemon that runs reports what went wrong with the lane itself. + if devstack_daemon::read_info(&repo.join(".devstack")).is_some() { + return; + } + let text = std::fs::read_to_string(&log).unwrap_or_default(); + let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect(); + let tail = lines[lines.len().saturating_sub(12)..].join("\n"); + crate::diag::warn( + "lane_start_failed", + serde_json::json!({ "id": id, "output": tail }), + ); + errors.lock().unwrap().insert( + id, + if tail.is_empty() { + "devstack up ended without a word".into() + } else { + tail + }, + ); + }); + StatusCode::ACCEPTED.into_response() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn git(dir: &Path, args: &[&str]) { + let ok = std::process::Command::new("git") + .args(args) + .current_dir(dir) + .output() + .unwrap() + .status + .success(); + assert!(ok, "git {args:?}"); + } + + #[test] + fn a_stacks_worktrees_are_lanes_not_started_with_their_stack_file() { + let d = tempfile::tempdir().unwrap(); + let repo = d.path().join("shop"); + std::fs::create_dir_all(&repo).unwrap(); + git(&repo, &["init", "-q", "-b", "main"]); + git(&repo, &["config", "user.email", "t@example.com"]); + git(&repo, &["config", "user.name", "t"]); + std::fs::write( + repo.join("devstack.toml"), + "version = 1\n[stack]\nname = \"shop\"\n", + ) + .unwrap(); + git(&repo, &["add", "."]); + git(&repo, &["commit", "-q", "-m", "x"]); + let common = crate::branches::common_dir(&repo).unwrap(); + let before = devstack_daemon::lanes::fingerprint(&common.join("worktrees")); + let wt = d.path().join("shop.worktrees").join("Fix Login"); + git( + &repo, + &[ + "worktree", + "add", + "-q", + "-b", + "fix/login", + wt.to_str().unwrap(), + ], + ); + let after = devstack_daemon::lanes::fingerprint(&common.join("worktrees")); + assert_ne!( + version(&before), + version(&after), + "a new worktree changes the version" + ); + + let list = of(&repo, &repo.join("devstack.toml")); + assert_eq!(list.len(), 1, "the main working tree is left out"); + assert_eq!(list[0].name, "fix-login"); + assert_eq!(list[0].branch.as_deref(), Some("fix/login")); + assert!(!list[0].active && !list[0].main_stack_file); + assert!( + list[0].not_in_pool.is_some(), + "no `[lanes] image`: not in the pool" + ); + } +} diff --git a/docs/adr/0078-the-hub-follows-every-stacks-worktrees.md b/docs/adr/0078-the-hub-follows-every-stacks-worktrees.md new file mode 100644 index 00000000..c4842793 --- /dev/null +++ b/docs/adr/0078-the-hub-follows-every-stacks-worktrees.md @@ -0,0 +1,93 @@ +# ADR-0078: The hub follows every stack's worktrees; a stopped stack's lane can be started from the dashboard + +- **Status:** Accepted (2026-10-29) +- **Date:** 2026-10-29 +- **Deciders:** project owner +- **Related:** [ADR-0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md) (a worktree is a lane), [ADR-0047](0047-the-dashboard-makes-a-lane-from-a-branch.md) (lanes made from a branch), [ADR-0021](0021-a-hub-serves-the-dashboard.md) (no polling), [ADR-0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md) + +## Context + +Two gaps, found in use: + +- A worktree made with `git worktree add` in a stack that was not shown + appeared in the dashboard's sidebar only when that stack was opened. The + stack's daemon noticed it within a second and told its stream, but the + dashboard follows the stream of the stack it shows only; the other + stacks' lanes were read when the hub's list of stacks changed. +- A stack whose daemon did not run showed no worktrees at all. A worktree + the dashboard made for it from a branch was listed in the branch picker + and could neither be opened nor started: a lane's views and its start + need the daemon. + +## Decision + +The owner approved the review card in the conversation on **2026-10-29**, +all three points: + +| Category | Point | Beats | Reversing costs | +|---|---|---|---| +| contract | The hub follows `.git/worktrees` of every registered stack, running or not, as the daemon does, and tells `/hub/events` when one changes; the dashboard reads that stack's lanes again then. | Reading lanes only when the list of stacks changes (before); following every running daemon's stream (a connection per stack, and nothing of a stopped one). | An additive event; without it the behaviour before. | +| concept | A stopped stack shows its worktrees in the sidebar as not started, read from git through the hub; a click opens the lane's start page. | A stopped stack's worktrees invisible and unreachable. | UI only. | +| contract | `POST /hub/stacks/{id}/lanes/start {path, on?}`: the hub starts the lane of a stopped stack as `devstack up` in its worktree does: the daemon comes up, the main working tree's services stay stopped, the lane starts here or on the pool. | "Start stack" first (the main tree's services), then the lane. | A hub route less; the stack is started first again. | + +What was built: + +1. **Following.** A thread of the hub looks once a second at + `/worktrees` of each registered stack: its entries and + their `HEAD`s (`devstack_daemon::lanes::fingerprint`, what the daemon + looks at). Its git directory is asked of git once per stack. The event + is a snapshot, `{"type":"worktrees","worktrees":{"":""}}`, + as every hub event starts with one, rather than one event per change: a + dashboard that connects again misses nothing. Looking at a local folder + is not asking anyone for state (ADR-0073's line between timers that ask + and ones that look here). +2. **`GET /hub/stacks/{id}/worktrees`**: the worktrees but the main one, in + the shape of a lane not started (`active: false`), named as the daemon + names them (`lane_name` of the folder; a second one of the same name + gets `-2` there and not here), with `main_stack_file` and `not_in_pool` + for the stack file it runs with. +3. **`POST /hub/stacks/{id}/lanes/start`** (`profile` too): `path` must be a worktree git + lists for the stack's repository, not the main tree; `on` a node, + `:` or `pool`, else `--on local`. The hub runs `devstack up` + in the worktree, its output in `up--lane.log`; a start that fails + before the daemon runs is the stack's `start_error`, as a stack's start. + `202` once started. +4. **The dashboard.** The sidebar lists every stack's worktrees, of a + stopped one from the hub, and reads a stack's lanes again when its + version in `worktrees` changes. A stopped stack's lane opens the same + start page as a lane of a running stack (machines, the coordinator's + order, profiles; `LaneStart`), and its starts go through the hub route + above; once the daemon runs, the lane's own start and views take over. + The main working tree of a stopped stack shows that page too, instead of + its views and their tabs: *Start here* starts the stack, *Start in the + pool* is off with why (the main tree runs on this machine; a worktree's + lane runs in the pool). Above that page, across its width, a dashed box + says the tree does not run, unlike any running tree's view; the stack's + offline banner gives way to it, and shows only a failed start then. The branch picker finds a + stopped stack's worktrees too, and a lane it makes for a stopped stack + opens on its start page. A stopped stack's trees show no running dot, + whatever was seen last. + +## Alternatives considered + +- **Following each running daemon's stream from the hub**: lanes would + arrive as they are (started, stopped), but a connection per stack, and a + stopped stack has no daemon to follow. +- **A file watcher** (`notify`): fewer wakeups, another dependency and its + platform differences, for a folder of a handful of entries; the daemon + looks the same way already. + +## Consequences + +- The hub reads the worktree folders of every registered stack once a + second; a stack whose repository is gone is skipped. +- A lane of a stopped stack starts without the main tree's services; its + stack shows as running then (its daemon runs). + +## Enforced by + +`crates/devstack-hub/src/worktrees.rs`, `crates/devstack-hub/src/lib.rs` +(the routes and `/hub/events`), `crates/devstack-daemon/src/lanes.rs` +(`fingerprint`), `ui/src/components/Sidebar.vue`, `ui/src/stores/stack.ts` +(`offlineLanes`, `offlineLane`, `startOfflineLane`), +`ui/src/components/LaneStart.vue`, `ui/src/components/BranchPicker.vue`. diff --git a/docs/adr/README.md b/docs/adr/README.md index 2770234c..ec43d80c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -160,3 +160,4 @@ stay. | [0075](0075-a-lanes-steady-use-is-measured-and-shown-never-admitted-by.md) | A lane's steady use is measured and shown, never admitted by | Accepted (card in the pull request) | | [0076](0076-a-pool-machine-has-one-page-the-pool-area-has-tabs.md) | A machine of the pool has one page; the pool area has tabs, and the pool and the tab are in the URL | Accepted (card in the pull request) | | [0077](0077-a-sets-skills-are-grouped-and-switched-one-by-one.md) | A set's skills are grouped by their frontmatter and switched one by one | Accepted (card in the pull request; point 5 taken back) | +| [0078](0078-the-hub-follows-every-stacks-worktrees.md) | The hub follows every stack's worktrees; a stopped stack's lane can be started from the dashboard | Accepted (card in the pull request) | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 33a0fb9e..9223ed88 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -53,7 +53,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `GET /hub/stacks` | cookie | `[StackEntry]` | | `GET /hub/summary` | cookie or token | every registered stack at a glance, for the tray ([ADR-0060](adr/0060-the-tray-is-a-client-of-the-hub.md)): `{"state", "version", "stacks": [{id, name, repo, running, state, ready, total, lanes, attention: [{lane, service, text, detail}]}]}`. A stack's `state`: `stopped`, `starting`, `stopping` (a start or stop the hub runs), `ok` or `attention`; the whole `state` is the worst: `attention`, `starting`, `ok` (a stack runs) or `idle`. `ready` of `total`: the main tree's services running, healthy or done. `lanes`: started lanes. `attention`: what notifies (ADR-0045) and is still so, in the main tree and every started lane (`lane` names it): a failed service (not one the user stopped, not one held back by another's failure), a candidate `held` or whose build `failed`; and a failed start from the dashboard (`service` `null`). Containers are not in it. `version`: the hub's devstack | | `GET /hub/ws?path=` | cookie + Origin | WebSocket that carries the server-sent event stream at `` (`/hub/events`, `/hub/stacks/{id}/api/v1/...`, or `/hub/pool/shared/{lease}/api/v1/...[?pool=]` for a lane shared with this machine), one text message per event's `data`; how the dashboard reads every stream (a browser allows six HTTP/1.1 connections per host across all its tabs, WebSockets do not count; ADR-0021). The upstream is opened before the upgrade: `503` for a stack not running, `400` for another path. When the stream ends the socket closes | -| `GET /hub/events` | cookie | SSE: `{"type":"stacks","stacks":[StackEntry]}` and `{"type":"docker","docker":DockerEngine}` and `{"type":"release","current","newer":string|null,"error":string|null}` (a newer devstack; checked at start, every 12 h by the clock and when a dashboard connects and the last answer is over an hour old, unless `DEVSTACK_NO_UPDATE_CHECK`; `error` why the last check failed, no network or GitHub's rate limit, tried again after an hour and `null` once one succeeds, while a `newer` found before stays; older hubs leave it out) and `{"type":"update","update":{"running":bool,"error":string|null,"installed":string|null,"finished":ms|null}}` (the dashboard's update; `finished` is when the last one ended, `installed` the version it installed, told by the hub it started) and `{"type":"guests","guests":[Guest]}` (lanes of other members on this machine, every pool: `{pool, lease, member, owner, repo, lane, state: "offered"\|"running", since: unix s, cpus, memory}`, the leases whose node is this machine; read when the pool's stream says its leases or nodes changed) and `{"type":"pools","pools":{"":{"live":"connecting"\|"live"\|"lost"\|"old","error"?,"versions":{"members","nodes","leases","upstreams","telemetry"}}}}` (the pools this machine follows over their coordinators' streams, ADR-0073: `old` for a coordinator without one, whose parts are read when the pool area opens; `versions` of each part, read again when one is not the one read last; older hubs never send it), each first and on every change | +| `GET /hub/events` | cookie | SSE: `{"type":"stacks","stacks":[StackEntry]}` and `{"type":"docker","docker":DockerEngine}` and `{"type":"release","current","newer":string|null,"error":string|null}` (a newer devstack; checked at start, every 12 h by the clock and when a dashboard connects and the last answer is over an hour old, unless `DEVSTACK_NO_UPDATE_CHECK`; `error` why the last check failed, no network or GitHub's rate limit, tried again after an hour and `null` once one succeeds, while a `newer` found before stays; older hubs leave it out) and `{"type":"update","update":{"running":bool,"error":string|null,"installed":string|null,"finished":ms|null}}` (the dashboard's update; `finished` is when the last one ended, `installed` the version it installed, told by the hub it started) and `{"type":"guests","guests":[Guest]}` (lanes of other members on this machine, every pool: `{pool, lease, member, owner, repo, lane, state: "offered"\|"running", since: unix s, cpus, memory}`, the leases whose node is this machine; read when the pool's stream says its leases or nodes changed) and `{"type":"worktrees","worktrees":{"":""}}` (a version of each registered stack's worktrees, running or not, ADR-0078: the hub looks at their folder once a second; a stack's lanes are read again when its version changes; older hubs never send it) and `{"type":"pools","pools":{"":{"live":"connecting"\|"live"\|"lost"\|"old","error"?,"versions":{"members","nodes","leases","upstreams","telemetry"}}}}` (the pools this machine follows over their coordinators' streams, ADR-0073: `old` for a coordinator without one, whose parts are read when the pool area opens; `versions` of each part, read again when one is not the one read last; older hubs never send it), each first and on every change | | `POST /hub/update` | cookie + Origin | `202`: `devstack update` in the background (output in `hub/update.log`); on success it restarts the hub on the new version, so the dashboard reconnects to it, and the new hub's `update` event names the installed version (the old hub leaves `hub/update.json` for it; a hub that starts on the old version while the updater runs waits for it and reports a failure); on failure the `update` event carries the end of its output. `409` while one runs (checked and claimed in one step). Running stacks switch at their next restart | | `POST /hub/update/check` | cookie + Origin | look for a newer release now: `{"current", "newer": string\|null}`, the same as the next `release` event; asked again within 30 s, the last answer (GitHub allows 60 unauthenticated requests an hour). `409` with `DEVSTACK_NO_UPDATE_CHECK`, `502` when GitHub cannot be asked, `504` after 30 s | | `POST /hub/stacks/scan` | cookie + Origin | `{"path", "add"?, "depth"?}`: every repository with a `devstack.toml` below a folder (default three levels, `depth` is clamped to 1 to 6; a repository only at its root, linked worktrees skipped), `[{repo, id, name, error, registered, added}]`; with `add` the valid new ones are registered | @@ -61,6 +61,8 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `GET /hub/openers` | cookie | what this machine opens a stack's folder with ([ADR-0046](adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md)), in menu order: `[{id, label, kind, prompt?}]`, `kind` one of `files`, `terminal`, `editor`, `git`, `agent`; `prompt` for an agent `POST /hub/agent` starts: `prefill` (`claude`, `claude-cli`: the prompt is filled in, the user sends it) or `send` (`orca`: it starts on it at once). Ids: `files` (Explorer, the file manager, Finder), `wt`, `powershell` (Windows), `terminal` (Linux; Terminal on macOS), `vscode`, `vscode-insiders`, `cursor`, `windsurf`, `zed`, `github-desktop` (Windows, macOS), `claude`, `claude-cli`, `orca`; only those found (a scheme registered, on macOS as LaunchServices knows it, a program on `PATH` or in its install folder). Empty without a desktop | | `GET /hub/stacks/{id}/branches` | cookie | the repository's branches ([ADR-0047](adr/0047-the-dashboard-makes-a-lane-from-a-branch.md)), local ones first, each group newest first: `{branches: [{name, remote?, upstream?, worktree?, main, date, stack_file}], fetched?}`. `remote`: a remote-tracking branch (`origin/feat/x`), listed only when no local branch is named after it or tracks it; `worktree`: the folder that has it checked out, `main` when that is the main working tree; `date`, `fetched` (when the repository last fetched): Unix seconds; `stack_file`: the branch has a stack file at the main one's path ([ADR-0055](adr/0055-a-lane-without-a-stack-file-says-so-and-can-be-given-one.md)), in its worktree when it has one (committed or not), else in its last commit (one `git cat-file --batch-check` for all). Read while the stack is stopped too | | `POST /hub/stacks/{id}/worktrees {"branch", "new"?}` | cookie + Origin | a worktree (a lane, not started) on `branch`, which must be one `branches` lists and no worktree has; with `new`, on a new branch of that name made from `branch` (git's rules for a name, `400` for one taken). A remote-tracking `branch` gets a local branch of its name that tracks it. The folder is the hub's: beside the repository's most recently added worktree, else `.worktrees/` beside the repository, named as the lane will be: `{path}`. `409 {"error"}` with what git said | +| `GET /hub/stacks/{id}/worktrees` | cookie | the stack's worktrees but the main one, as lanes not started (`LaneView` with `active: false`, `main_stack_file`, `not_in_pool`), from git, whether its daemon runs or not ([ADR-0078](adr/0078-the-hub-follows-every-stacks-worktrees.md)); for a stopped stack's sidebar and start card | +| `POST /hub/stacks/{id}/lanes/start {"path", "on"?, "profile"?}` | cookie + Origin | start the lane of the worktree `path` (one git lists for the stack, not the main tree) as `devstack up` in it does: the stack's daemon comes up, the main working tree's services stay stopped; `on` a node, `:` or `pool`, else this machine; `profile` a profile of the stack file (ADR-0041). `202`; `400` for another path or `on`; a start that fails before the daemon runs is the stack's `start_error` (ADR-0078) | | `POST /hub/stacks/{id}/worktrees/remove {"path"}` | cookie + Origin | `git worktree remove` (never `--force`) of a linked worktree of the stack (`400` for the main working tree or anything else): `{}`; `409 {"error"}` with git's refusal, a worktree with changes. The branch stays | | `POST /hub/stacks/{id}/fetch` | cookie + Origin | `git fetch --all --prune`, without a prompt (`GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`) and within 120 s: `{}`; `409 {"error"}` with what git said | | `GET /hub/stacks/{id}/skills` | cookie | the agent skills `devstack skills install` wrote into the repository (the folders `[agents] skills` names, and generated copies in the other agents' folders), held against what this devstack would write for the stack file: `{found, outdated, from, current, ahead}`. `found`, `outdated`: skills by their folder, `.claude/skills/devstack` (one the project wrote itself is not listed); `from`: the oldest devstack their marker lines name (`null` when none); `current`: this devstack; `ahead`: `from` is newer than `current` (a teammate's newer devstack wrote them; installing would go back). All empty when the stack file does not load. Read while the stack is stopped too | diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index dc02a3e4..e21ee2d9 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -197,6 +197,8 @@ class MockHub { if (q.includes('configchanged')) shop.view.config_changed = true; if (q.includes('startfailed')) docs.entry.start_error = 'Error: port 4000 (site) is taken by another process (node.exe, pid 4242)\n devstack doctor names it; stop it or change the port in devstack.toml'; // `?mock=skills`: shop was set up with an older devstack, crm's stack file changed since. + // `?mock=worktrees`: a worktree appears in docs (not running) after 4 s, as one made by `git worktree add` elsewhere. + if (q.includes('worktrees')) setTimeout(() => this.addWorktree(docs.entry.id, docs.entry.repo, 'hotfix', 'hotfix/footer'), 4000); if (q.includes('skills')) this.reviewed[shop.entry.id] = null; this.skills[shop.entry.id] = q.includes('skills') ? { from: '0.1.4', outdated: true } : { from: MOCK_VERSION, outdated: false }; this.skills[crm.entry.id] = { from: MOCK_VERSION, outdated: q.includes('skills') }; @@ -235,6 +237,22 @@ class MockHub { for (const l of this.hubSubs) l.send(ev); } + /** Worktrees made in a stack (by the dashboard, or `?mock=worktrees`), by stack id; each stack has `fix-login` besides (ADR-0078). */ + worktreesMade: Record = {}; + worktreeVersions: Record = {}; + worktreesOf(id: string, repo: string): LaneView[] { + const base: LaneView = { name: 'fix-login', path: `${repo}.worktrees/fix-login`, branch: 'fix/login', number: 0, active: false, port_offset: 0, owns_main: false, running: 0, services: 0, main_stack_file: false }; + return [base, ...(this.worktreesMade[id] ?? [])]; + } + /** A worktree appears in `id`'s repository: the hub tells, as it does when `.git/worktrees` changes. */ + addWorktree(id: string, repo: string, name: string, branch: string): string { + const path = `${repo}.worktrees/${name}`; + (this.worktreesMade[id] ??= []).push({ name, path, branch, number: 0, active: false, port_offset: 0, owns_main: false, running: 0, services: 0, main_stack_file: false }); + this.worktreeVersions = { ...this.worktreeVersions, [id]: String(Date.now()) }; + for (const l of this.hubSubs) l.send({ type: 'worktrees', worktrees: this.worktreeVersions }); + return path; + } + stack(id: string): MockStack | undefined { return this.stacks.find((s) => s.entry.id === id); } @@ -785,6 +803,18 @@ export class MockTransport implements Transport { if (!stack.running) void stack.goUp(); return empty(202); } + // A stopped stack's worktrees, from the hub (ADR-0078): one for each. + if (rest === '/worktrees' && method === 'GET') { + return json(200, hub.worktreesOf(stack.entry.id, stack.entry.repo)); + } + if (rest === '/lanes/start' && method === 'POST') { + // `devstack up` in the worktree: the daemon and this lane, the main tree's services left stopped. + const l = hub.worktreesOf(stack.entry.id, stack.entry.repo).find((w) => w.path === body?.path); + if (!l) return json(400, { error: "not a worktree of this stack's repository" }); + stack.startedLanes.add(l.name); + if (!stack.running) void stack.goUp({ main: false }); + return empty(202); + } if (rest === '/down' && method === 'POST') { setTimeout(() => stack.goDown(), 600); return empty(202); @@ -820,7 +850,10 @@ export class MockTransport implements Transport { } if (rest === '/worktrees' && method === 'POST') { await sleep(600); - const name = String(body?.new ?? body?.branch ?? '').replace(/^origin\//, '').replace(/[^a-z0-9]+/gi, '-').toLowerCase(); + const branch = String(body?.new ?? body?.branch ?? '').replace(/^origin\//, ''); + const name = branch.replace(/[^a-z0-9]+/gi, '-').toLowerCase(); + // A stopped stack's new worktree is listed by the hub at once (ADR-0078). + if (!stack.running) return json(200, { path: hub.addWorktree(stack.entry.id, stack.entry.repo, name, branch) }); return json(200, { path: `C:\\work\\shop.worktrees\\${name}` }); } if (rest === '/worktrees/remove' && method === 'POST') return json(409, { error: 'error: worktree contains modified or untracked files, use --force to delete it' }); @@ -848,9 +881,16 @@ export class MockTransport implements Transport { private async daemonApi(s: MockStack, method: string, p: string, q: URLSearchParams, body?: Record): Promise { // Lanes (plan §3.5): the shop repository has two other worktrees, one // started; a lane's API is the stack's, here. + // Another stack's lanes are its worktrees as the hub lists them (ADR-0078). + const others = () => + this.hub.worktreesOf(s.entry.id, s.entry.repo).map((w, i) => { + const active = s.startedLanes.has(w.name); + return { ...w, number: i + 1, port_offset: 100 * (i + 1), active, running: active ? 5 : 0, services: 5 }; + }); const lanes = () => - s.view.name === 'shop' - ? [ + s.view.name !== 'shop' + ? others() + : [ { name: 'agent-login-fix', path: 'C:\\work\\shop-agent-login-fix', branch: 'agent/login-fix', number: 1, port_offset: 100 }, { name: 'review-cart', path: 'C:\\work\\shop-review-cart', branch: 'review-cart', number: 2, port_offset: 200 }, // Worktrees agents opened and left: lanes, not started. @@ -888,8 +928,7 @@ export class MockTransport implements Transport { const image = l.name === '1242' ? { not_in_pool: NO_LANE_IMAGE } : {}; return { ...l, active, owns_main: owns, running: active ? (l.name === 'agent-login-fix' ? 3 : 5) : 0, services: 5, ...node, ...notices, ...file, ...image }; }) - .filter((l) => l !== null) - : []; + .filter((l) => l !== null); if (p === '/v1/lanes' && method === 'GET') return json(200, lanes()); if (p === '/v1/lanes' && method === 'POST') { await sleep(600); @@ -1174,6 +1213,7 @@ export class MockTransport implements Transport { l.send({ type: 'guests', guests: hub.guests }); l.send({ type: 'pools', pools: hub.pools }); l.send({ type: 'skills', skills: hub.poolSkillState }); + l.send({ type: 'worktrees', worktrees: hub.worktreeVersions }); hub.hubSubs.add(l); return { stop: () => hub.hubSubs.delete(l) }; } diff --git a/ui/src/api/mock/stack.ts b/ui/src/api/mock/stack.ts index b65cf733..b188cc21 100644 --- a/ui/src/api/mock/stack.ts +++ b/ui/src/api/mock/stack.ts @@ -120,7 +120,8 @@ export class MockStack { this.onEntryChange(); } - async goUp(): Promise { + /** `main: false`: the daemon only, as a lane's start brings it up (ADR-0078). */ + async goUp(opts: { main?: boolean } = {}): Promise { const gen = this.generation; // A new daemon reads the stack file afresh. this.view.config_changed = false; @@ -132,8 +133,10 @@ export class MockStack { daemon: { pid: 20000 + Math.floor(Math.random() * 9000), port: 50000 + Math.floor(Math.random() * 9000), started: Date.now(), version: '0.2.0' }, last_seen: Date.now(), }; - for (const s of this.view.services) { - if (s.autostart && s.kind !== 'job') s.status = { state: 'starting' }; + if (opts.main !== false) { + for (const s of this.view.services) { + if (s.autostart && s.kind !== 'job') s.status = { state: 'starting' }; + } } this.onEntryChange(); this.start(); diff --git a/ui/src/api/transport.ts b/ui/src/api/transport.ts index 14d6331b..1b7848f7 100644 --- a/ui/src/api/transport.ts +++ b/ui/src/api/transport.ts @@ -69,6 +69,7 @@ export const paths = { branches: (stack: string) => `/hub/stacks/${enc(stack)}/branches`, worktrees: (stack: string) => `/hub/stacks/${enc(stack)}/worktrees`, worktreeRemove: (stack: string) => `/hub/stacks/${enc(stack)}/worktrees/remove`, + laneStart: (stack: string) => `/hub/stacks/${enc(stack)}/lanes/start`, fetch: (stack: string) => `/hub/stacks/${enc(stack)}/fetch`, skills: (stack: string) => `/hub/stacks/${enc(stack)}/skills`, upgrade: (stack: string) => `/hub/stacks/${enc(stack)}/upgrade`, diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 01083b19..8af75d1a 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -49,6 +49,8 @@ export type HubEvent = | { type: 'pools'; pools: Record } /** The pools' skill sets on this machine (ADR-0074); older hubs never send it. */ | { type: 'skills'; skills: PoolSkillsState } + /** A version of each stack's worktrees (ADR-0078): read a stack's lanes again when its version changes. Older hubs never send it. */ + | { type: 'worktrees'; worktrees: Record } /** Something happened once in the hub that no request reports (ADR-0050): a toast. */ | { type: 'notice'; level: NoticeLevel; text: string }; diff --git a/ui/src/components/BranchPicker.vue b/ui/src/components/BranchPicker.vue index 02d199c7..0c7b77c0 100644 --- a/ui/src/components/BranchPicker.vue +++ b/ui/src/components/BranchPicker.vue @@ -52,7 +52,8 @@ const rows = computed(() => { const q = filter.value.trim().toLowerCase(); return (stack.branches?.branches ?? []) .filter((b) => !q || b.name.toLowerCase().includes(q)) - .map((b) => ({ b, lane: b.worktree && !b.main ? (stack.lanes.find((l) => samePath(l.path, b.worktree!)) ?? null) : null })) + // A stack that does not run has its worktrees from the hub (ADR-0078). + .map((b) => ({ b, lane: b.worktree && !b.main ? ([...stack.lanes, ...stack.offlineLanes].find((l) => samePath(l.path, b.worktree!)) ?? null) : null })) .sort((x, y) => Number(y.b.main) - Number(x.b.main) || x.b.name.localeCompare(y.b.name)); }); /** The branches with a worktree (the main tree's first), then the other local ones, then the remote ones; each by name. */ diff --git a/ui/src/components/LaneStart.vue b/ui/src/components/LaneStart.vue index b4ff8d23..566ce230 100644 --- a/ui/src/components/LaneStart.vue +++ b/ui/src/components/LaneStart.vue @@ -1,9 +1,12 @@