The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(tui): harness list newest first, machine over folders, old sessions folded (#2564)
lingrd1d69ae651b64
diff --git a/scripts/validate-tui-native.py b/scripts/validate-tui-native.pyindex 9d07adcae..6d6a353bc 100644--- a/scripts/validate-tui-native.py+++ b/scripts/validate-tui-native.py@@ -43,6 +43,7 @@ def main():fixture("welcome", "HN_WELCOME_TEST_BINARY", "HN_WELCOME_TEST_PORT", 19787),fixture("welcome-composer", "HN_WELCOME_TEST_BINARY", "HN_WELCOME_TEST_PORT", 19788),fixture("session-picker", "HN_SESSION_TEST_BINARY", "HN_SESSION_TEST_PORT", 19929),+ fixture("harness-list", "HN_HARNESS_LIST_BINARY", "HN_HARNESS_LIST_PORT", 19785),{"name": "shell-integration", "cwd": "tui", "timeout_seconds": 120,"argv": [sys.executable, "-u", "tests/shell-integration.py"]},{"name": "composer-machine", "cwd": "tui", "timeout_seconds": 120,diff --git a/tui/Cargo.lock b/tui/Cargo.lockindex 2e201aadf..cad103016 100644--- a/tui/Cargo.lock+++ b/tui/Cargo.lock@@ -661,7 +661,7 @@ dependencies = [[[package]]name = "harness-tui"-version = "0.1.44"+version = "0.1.45"dependencies = ["alacritty_terminal","base64",diff --git a/tui/Cargo.toml b/tui/Cargo.tomlindex bce68c562..a55f51abf 100644--- a/tui/Cargo.toml+++ b/tui/Cargo.toml@@ -1,6 +1,6 @@[package]name = "harness-tui"-version = "0.1.44"+version = "0.1.45"edition = "2024"[dependencies]diff --git a/tui/README.md b/tui/README.mdindex 8ac66d047..de32b1ea6 100644--- a/tui/README.md+++ b/tui/README.md@@ -454,7 +454,10 @@ pane counts as done and unread (`✓`) until you go to that pane.(`'waiting`, `'failed`, `'done`, `'working`, `'idle`). From the list, without opening it: `M-m`marks it read (`M-M` every row shown), `M-s` sends it a message, `M-r` restarts it, `M-1…9` /`M-a` answer it; Enter adds marked rows as panes, while `C-t` opens a window each. The list stays- ranked while it is open. The preview adds its final message whole, what it was last asked, its plan (its to-do list,+ ranked while it is open. The list reads newest first, each machine with its folders under it.+ A harness untouched for over 7 days, with nothing going on and not on screen, folds under its+ folder's `▸ N older` (Enter shows them; a search always finds them). The keys line shows the main+ keys; `?` lists them all. The preview adds its final message whole, what it was last asked, its plan (its to-do list,`✓` done, `▸` doing), the sub-agents it has running, and what it has used (`1.2M tokens · +340−52 · 1 PR`).- **A session per project**: in `C-b s` then `#` (the projects, each with its counts), `C-t` makesdiff --git a/tui/src/format.rs b/tui/src/format.rsindex a1a22e3b9..9dbb90aea 100644--- a/tui/src/format.rs+++ b/tui/src/format.rs@@ -1080,13 +1080,17 @@ fn quota_remaining<'a>(readings: impl Iterator<Item = (&'a str, &'a crate::fleet}).collect::<Vec<_>>().join(" ")}-/// A subscription's provider as its engine's icon, in the engine's colour (`✳` Claude, `◎`-/// Codex/OpenAI…); a provider with no engine of its own, its name.+/// A subscription's provider as its engine's icon, in the engine's colour and on its tile (`✳`+/// Claude, `☁` Codex/OpenAI…); a provider with no engine of its own, its name.fn quota_icon(provider: &str) -> String {let engine = match provider.to_ascii_lowercase().as_str() { "anthropic" | "claude" => "claude", "openai" | "chatgpt" | "codex" => "codex", _ => return quota_provider(provider) };let (mark, colour) = crate::theme::engine_mark(engine);if crate::theme::no_color() { return mark.to_string() }- format!("#[fg={}]{mark}#[fg=default]", crate::tmuxconf::colour_name(crate::theme::paint(colour)))+ let fg = crate::tmuxconf::colour_name(crate::theme::paint(colour));+ match crate::theme::engine_tile(engine) {+ Some(tile) => format!("#[fg={fg},bg={}]{mark}#[fg=default,bg=default]", crate::tmuxconf::colour_name(tile)),+ None => format!("#[fg={fg}]{mark}#[fg=default]"),+ }}fn quota_provider(provider: &str) -> String {@@ -1454,7 +1458,7 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<V"usage_remaining" | "usage_remaining_mark" => quota_remaining(app.usage.iter().flat_map(|(machine, readings)| readings.iter().map(move |u| (machine.as_str(), u))),&app.fleet.local_id, |id| app.fleet.machine_name(id), name == "usage_remaining_mark", false),- // The same, each subscription by its engine's icon (`✳ 43% ◎ 80%`): the side bar's.+ // The same, each subscription by its engine's icon (`✳ 43% ☁ 80%`): the side bar's."usage_remaining_icons" => quota_remaining(app.usage.iter().flat_map(|(machine, readings)| readings.iter().map(move |u| (machine.as_str(), u))),&app.fleet.local_id, |id| app.fleet.machine_name(id), true, true),diff --git a/tui/src/input.rs b/tui/src/input.rsindex 687853979..f5678f5d3 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -816,7 +816,8 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {let mut recency: std::collections::HashMap<String,u64> = app.fleet.agents.values().map(|a| (format!("{}:{}",a.machine_id,a.id),a.recency())).collect();// (One list by last activity: its harnesses not headed by where they work.)- for r in rows.iter_mut().filter(|r| recency.contains_key(&r.id)) { r.group = None }+ rows.retain(|r| !r.id.starts_with(modal::OLDER_ROW));+ for r in rows.iter_mut().filter(|r| recency.contains_key(&r.id)) { r.group = None; r.section = None; r.older = None }for x in app.said.iter().chain(app.shell_context.catalog.iter()).filter_map(|s| s.external.as_ref()) {let at = recency.entry(format!("external:{}:{}",x.machine,x.session_id)).or_default();*at = (*at).max(x.last_at);@@ -850,7 +851,8 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {picker.catalog_ids = app.shell_context.catalog.iter().filter(|_| app.shell_context.sessions_machine.is_some()).map(|h| format!("external:{}:{}", h.machine, h.session_id)).collect();picker.set_rows(rows);picker.status = modal::open_status(app, *filter);- picker.hints = vec![("enter", "add pane"), ("C-t", "new window"), ("M-1..9", "answer"), ("M-m", "read"), ("C-v", "beside"), ("C-x", "below"), ("M-enter", "here"), ("M-a", "type an answer"), ("M-s", "message"), ("M-r", "restart"), ("tab", "mark"), ("C-/", "preview"), ("M-p", "pause")];+ // (The main keys; `?` lists the rest, which all still work: modal::mode_rows.)+ picker.hints = vec![("enter", "add pane"), ("C-t", "new window"), ("tab", "mark"), ("?", "all keys")];picker.empty = if app.fleet.agents.is_empty() { "no harnesses yet — C-b C makes one".into() } else { String::new() };if app.shell_context.sessions_machine.is_some() {picker.hints = vec![("enter", "open"), ("C-t", "new window"), ("C-/", "preview"), ("esc", "cancel")];@@ -3080,6 +3082,14 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {if let Some(msg) = crate::settings::set_key(app, knob, value) { picker.say(msg) }return keep(app, kind, picker);}+ // `▸ N older`: Enter unfolds them where it stands; no other key means anything on it.+ PickerKind::Open { .. } if id.as_deref().is_some_and(|i| i.starts_with(modal::OLDER_ROW)) => {+ if choice == Choice::Enter {+ if let Some(key) = id.as_deref().and_then(|i| i.strip_prefix(modal::OLDER_ROW)) { picker.unfolded.insert(key.to_string()); }+ picker.refilter();+ }+ keep(app, kind, picker)+ }PickerKind::Open { .. } if id.as_deref().map(|i| i.starts_with("session:")).unwrap_or(false) => {let sid = id.as_deref().and_then(|i| i.strip_prefix("session:")).and_then(|n| n.parse().ok()).unwrap_or(app.session_id);SPLIT.with(|s| s.set(None));@@ -3799,7 +3809,9 @@ mod tests {fill(&app, &kind, &mut picker);// (Its harnesses: other tests' sessions can be listed after them.)let shown: Vec<(&str, &str)> = picker.rows.iter().filter(|r| !r.id.starts_with("session:")).map(|r| (r.group.as_deref().unwrap_or(""), r.label.as_str())).collect();- assert_eq!(shown, [("studio · webapp", "fix login"), ("studio · webapp", "release notes"), ("studio · api", "rate limit")]);+ // (Their fixed dates are over a week old: each folder closes with its `▸ N older`.)+ let shown: Vec<_> = shown.into_iter().filter(|(_, label)| !label.contains("older")).collect();+ assert_eq!(shown, [("webapp", "fix login"), ("webapp", "release notes"), ("api", "rate limit")]);}/// What the person typed into hn's own box is marked as theirs, as the desktop's composer marksdiff --git a/tui/src/modal.rs b/tui/src/modal.rsindex 7bc7d95bc..d8d4d8833 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -277,7 +277,16 @@ fn folder_of(a: &crate::fleet::Agent) -> String {std::path::Path::new(&a.cwd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "No folder".into())}+/// How long since a harness was last touched before it folds under `▸ N older`.+const OLDER_THAN_MS: u64 = 7 * 24 * 60 * 60 * 1000;+/// What a `▸ N older` row's id starts with, the rest the key its folded rows share ([Row::older]).+pub const OLDER_ROW: &str = "older:";+pub fn agent_rows(app: &App, filter: Filter, machine: Option<&str>, project: Option<&str>) -> Vec<Row> {+ // (A project's own list, or a filtered one, was asked for by name: nothing folds there.)+ let folds = filter == Filter::All && project.is_none();+ let now = crate::fleet::now_ms();+ let shown: Vec<(String, String)> = app.panes.values().map(|p| (p.machine_id.clone(), p.agent_id.clone())).collect();// By the time each row shows, the shortest first (the one that came to be as it is last) — a// query ranks by how well it matches, this order breaking ties. (C-b A lists those waiting// on you.)@@ -290,17 +299,21 @@ pub fn agent_rows(app: &App, filter: Filter, machine: Option<&str>, project: Opt.filter(|a| filter.keeps(app.fleet.state_of(a))).map(|a| {let state = app.fleet.state_of(a);- let (mark, mark_color) = engine_mark(&a.engine);- // Headed by where it works — its machine and folder (the folder alone in one machine's- // list) — so a row is its agent's icon, its name, and how it is in a word by how long- // it has been so (`idle 15s`: waiting on you since its question, working since its turn- // began, done since it ended); what it is doing is in the preview. Only one waiting on- // you keeps its question in its row, as M-1…9 answer it from here with the preview- // hidden too.+ let (mark, _) = engine_mark(&a.engine);+ // Headed by where it works — its machine, then its folder under it (the folder alone in+ // one machine's list) — so a row is its agent's icon, its name, and how it is in a word+ // by how long it has been so (`idle 15s`: waiting on you since its question, working+ // since its turn began, done since it ended); what it is doing is in the preview. Only+ // one waiting on you keeps its question in its row, as M-1…9 answer it from here with+ // the preview hidden too.let question = a.question.as_ref().filter(|_| state == State::NeedsInput).map(|q| q.prompt.clone()).unwrap_or_default();let folder = folder_of(a);- let group = if machine.is_some() { folder } else { format!("{} · {folder}", app.fleet.machine_name(&a.machine_id)) };let since = a.state_since(state);+ // Folded under its folder's `▸ N older`: last touched over a week ago, nothing going on+ // in it and not on screen. A search still finds it.+ let active = matches!(state, State::NeedsInput | State::Working | State::Starting);+ let older = (folds && !active && !shown.contains(&a.key()) && now.saturating_sub(since) > OLDER_THAN_MS)+ .then(|| format!("{}\t{folder}", a.machine_id));let pr = a.pr.as_ref().map(|p| p.label()).unwrap_or_default();let narrow = ago(since);let status = match state {@@ -316,27 +329,58 @@ pub fn agent_rows(app: &App, filter: Filter, machine: Option<&str>, project: Opt};// Its pull request's state in words too: 'pr, 'open, 'merged.let pr_words = a.pr.as_ref().map(|p| format!("pr {}", p.state.to_lowercase())).unwrap_or_default();- Row::new(format!("{}:{}", a.machine_id, a.id), a.name.clone())- .group(group)+ let mut row = Row::new(format!("{}:{}", a.machine_id, a.id), a.name.clone()).group(folder);+ if machine.is_none() { row.section = Some(app.fleet.machine_name(&a.machine_id)) }+ row.older = older;+ row.boost(if state == State::NeedsInput { 60 } else if live { 30 } else { 0 }).extra(format!("{} {} {} {} {} {} {} {} {} {}", a.project, a.branch, a.cwd, app.fleet.machine_name(&a.machine_id), a.engine, engine_label(&a.engine), a.dsh, pr, pr_words, words))// How long it has been as it is changes as you look..volatile(false, narrow.chars().count())- .lead(vec![span(mark, fg(mark_color)), span(" ", Style::default())])+ .lead(vec![span(mark, theme::engine_style(&a.engine)), span(" ", Style::default())]).detail(vec![span(question, fg(theme::ATTENTION))]).right(format!("{status} {narrow}")).line_first(true)}).collect();- grouped_in_order(rows)+ with_older_rows(grouped_in_order(rows))+}++/// [rows] with a `▸ N older` row closing each folder that has rows folded away (Enter unfolds them).+fn with_older_rows(rows: Vec<Row>) -> Vec<Row> {+ let mut out: Vec<Row> = Vec::with_capacity(rows.len());+ let mut run: Option<(String, Option<String>, Option<String>, usize)> = None;+ let close = |out: &mut Vec<Row>, run: &mut Option<(String, Option<String>, Option<String>, usize)>| {+ if let Some((key, section, group, n)) = run.take() {+ let label = format!("▸ {n} older");+ let mut row = Row::new(format!("{OLDER_ROW}{key}"), label.clone());+ row.label_dim = label.chars().count();+ row.section = section;+ row.group = group;+ out.push(row);+ }+ };+ for row in rows {+ if run.as_ref().is_some_and(|(_, s, g, _)| *s != row.section || *g != row.group) { close(&mut out, &mut run) }+ if let Some(key) = &row.older {+ match &mut run { Some((_, _, _, n)) => *n += 1, None => run = Some((key.clone(), row.section.clone(), row.group.clone(), 1)) }+ }+ out.push(row);+ }+ close(&mut out, &mut run);+ out}-/// [rows] with each group's rows together, in the order of each group's first row (the one-/// active last's group first), each group's rows in their own order.+/// [rows] with each section's rows together and each group's within it, in the order of each one's+/// first row (the one active last's first), each group's rows in their own order.pub fn grouped_in_order(mut rows: Vec<Row>) -> Vec<Row> {- let mut first: Vec<Option<String>> = Vec::new();- for r in &rows { if !first.contains(&r.group) { first.push(r.group.clone()) } }- rows.sort_by_key(|r| first.iter().position(|g| *g == r.group));+ let mut sections: Vec<Option<String>> = Vec::new();+ let mut groups: Vec<(Option<String>, Option<String>)> = Vec::new();+ for r in &rows {+ if !sections.contains(&r.section) { sections.push(r.section.clone()) }+ if !groups.iter().any(|(s, g)| *s == r.section && *g == r.group) { groups.push((r.section.clone(), r.group.clone())) }+ }+ rows.sort_by_key(|r| (sections.iter().position(|s| *s == r.section), groups.iter().position(|(s, g)| *s == r.section && *g == r.group)));rows}@@ -347,7 +391,7 @@ pub fn external_rows(app: &App) -> Vec<Row> {let many = app.fleet.visible_machines().filter(|m| m.usable()).count() > 1;app.said.iter().chain(app.shell_context.catalog.iter().filter(|_| app.shell_context.sessions_machine.is_some())).filter_map(|s| s.external.as_ref()).filter(|x| !app.fleet.agents.values().any(|a| a.machine_id == x.machine && a.session_id == x.session_id)).map(|x| {- let (mark, mark_color) = engine_mark(&x.engine);+ let (mark, _) = engine_mark(&x.engine);let folder = x.cwd.trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();let title = if x.title.is_empty() { folder.clone() } else { x.title.clone() };let note = if x.open { "open elsewhere" } else if x.cwd.is_empty() { "folder unavailable" } else { "saved" };@@ -355,7 +399,7 @@ pub fn external_rows(app: &App) -> Vec<Row> {let mut row = Row::new(format!("external:{}:{}", x.machine, x.session_id), title).extra(format!("{} {} {} {}", x.cwd, x.engine, engine_label(&x.engine), app.fleet.machine_name(&x.machine))).group("Saved conversations")- .lead(vec![span("‖", fg(theme::MUTED)), span(" ", Style::default()), span(mark, fg(mark_color)), span(" ", Style::default())])+ .lead(vec![span("‖", fg(theme::MUTED)), span(" ", Style::default()), span(mark, theme::engine_style(&x.engine)), span(" ", Style::default())]).detail(vec![span(folder, fg(theme::MUTED))]).right(right).right_narrow(ago(x.last_at));@@ -492,6 +536,9 @@ pub fn mode_rows(app: &App) -> Vec<Row> {("#", "projects", "a project folder, then its harnesses", String::new()), (":", "models", "local, shared, subscriptions, APIs", hint("choose-tree -i")),("*", "store", "the Harness Store", hint("choose-tree -S"))];let mut rows: Vec<Row> = modes.iter().map(|(p, t, d, k)| Row::new(format!("mode:{p}"), format!("{p} {t}")).detail(vec![span(*d, Style::default().add_modifier(ratatui::style::Modifier::DIM))]).right(k.clone())).collect();+ // The harness list's keys: its own line shows only the main ones, and points here.+ const LIST_KEYS: [(&str, &str); 13] = [("enter", "add pane"), ("C-t", "new window"), ("C-v", "beside"), ("C-x", "below"), ("M-enter", "here"), ("tab", "mark"), ("M-1..9", "answer"), ("M-a", "type an answer"), ("M-m", "read"), ("M-s", "message"), ("M-r", "restart"), ("M-p", "pause"), ("C-/", "preview")];+ rows.extend(LIST_KEYS.iter().map(|(k, what)| Row::new(format!("listkey:{k}"), format!("{k:<7} {what}")).extra("harness list").right("harness list")));let prefix = crate::keys::name(&app.keymap.prefix);// Each key as part of its line (as fzf would be given it): searched for as any word is// (`C-b z`, `PPage`), lit only where the query matches.@@ -509,12 +556,12 @@ pub fn inbox_rows(app: &App) -> Vec<Row> {// a question, answered where it stands (M-1…9, M-a).let who = [a.name.clone(), a.project.clone(), app.fleet.machine_name(&a.machine_id)].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");let options = q.options.iter().enumerate().map(|(i, o)| format!("{} {o}", i + 1)).collect::<Vec<_>>().join(" · ");- let (mark, mark_color) = engine_mark(&a.engine);+ let (mark, _) = engine_mark(&a.engine);let since = crate::fleet::now_ms().saturating_sub(q.since.elapsed().as_millis() as u64);let mut detail = vec![span(who.clone(), fg(theme::MUTED))];if !options.is_empty() { detail.push(span(format!(" {options}"), fg(theme::accent()))) }rows.push(Row::new(format!("{}:{}#", a.machine_id, a.id), q.prompt.clone()).extra(format!("{who} {} {options}", a.branch))- .lead(vec![span("? ", fg(theme::ATTENTION).add_modifier(ratatui::style::Modifier::BOLD)), span(mark, fg(mark_color)), span(" ", Style::default())])+ .lead(vec![span("? ", fg(theme::ATTENTION).add_modifier(ratatui::style::Modifier::BOLD)), span(mark, theme::engine_style(&a.engine)), span(" ", Style::default())]).detail(detail).right(ago(since)));}@@ -834,9 +881,9 @@ pub fn new_machine_rows(app: &App, prefer: &str) -> Vec<Row> {pub fn new_what_rows(catalog: &[Value]) -> Vec<Row> {let mut rows: Vec<Row> = ENGINES.iter().filter(|e| **e != "terminal").map(|e| {- let (mark, color) = engine_mark(e);+ let (mark, _) = engine_mark(e);Row::new(format!("engine:{e}"), engine_label(e)).extra(*e).group("Agents")- .lead(vec![span(mark, fg(color)), span(" ", Style::default())])+ .lead(vec![span(mark, theme::engine_style(e)), span(" ", Style::default())])}).collect();for row in catalog {if row.get("installed").and_then(Value::as_bool) == Some(false) || row.get("kind").and_then(Value::as_str) == Some("viewer") { continue }@@ -869,10 +916,11 @@ pub fn route_rows(reply: &Value) -> Vec<Row> {let mut rows: Vec<Row> = reply.get("candidates").and_then(Value::as_array).cloned().unwrap_or_default().iter().filter_map(|c| {let agent = c.get("agentId")?.as_str()?;let machine = c.get("machineId")?.as_str()?;- let (mark, color) = engine_mark(c.get("engine").and_then(Value::as_str).unwrap_or(""));+ let engine = c.get("engine").and_then(Value::as_str).unwrap_or("");+ let mark = engine_mark(engine).0;let confidence = c.get("confidence").and_then(Value::as_f64).unwrap_or(0.0);Some(Row::new(format!("{machine}:{agent}"), c.get("name").and_then(Value::as_str).unwrap_or(agent).to_string())- .lead(vec![span(mark, fg(color)), span(" ", Style::default())])+ .lead(vec![span(mark, theme::engine_style(engine)), span(" ", Style::default())]).detail(vec![span(c.get("recent").and_then(Value::as_str).unwrap_or("").to_string(), fg(theme::MUTED))]).right(format!("{} {}", c.get("machine").and_then(Value::as_str).unwrap_or(""), if confidence > 0.0 { format!("{}%", (confidence * 100.0) as u32) } else { String::new() })))}).collect();@@ -918,21 +966,87 @@ mod agent_row_tests {out}- /// C-b s: one heading per machine and folder, the one active last first, each harness under its- /// own once (never a heading twice), its folder from where it works when it has no project.+ /// C-b s: the machine with the newest harness first, each machine's folders under it, the+ /// newest folder first, a folder of the same name on two machines kept apart.#[test]- fn harnesses_are_grouped_by_machine_and_folder() {+ fn harnesses_are_grouped_by_machine_then_folder_newest_first() {let app = app();- let groups = by_group(&agent_rows(&app, Filter::All, None, None));- assert_eq!(groups, vec![- ("studio · webapp".to_string(), vec!["fix login".to_string(), "release notes".to_string()]),- ("lab · webapp".to_string(), vec!["train".to_string()]),- ("studio · api".to_string(), vec!["rate limit".to_string()]),- ("lab · ops".to_string(), vec!["ops shell".to_string()]),- ("studio · No folder".to_string(), vec!["scratch".to_string()]),+ let rows = agent_rows(&app, Filter::All, None, None);+ let got: Vec<(String, String, Vec<String>)> = {+ let mut out: Vec<(String, String, Vec<String>)> = Vec::new();+ // (Their fixed dates are long past: each folder also closes with its `▸ N older`.)+ for r in rows.iter().filter(|r| !r.id.starts_with(OLDER_ROW)) {+ let (s, g) = (r.section.clone().unwrap_or_default(), r.group.clone().unwrap_or_default());+ match out.last_mut() { Some((ls, lg, names)) if *ls == s && *lg == g => names.push(r.label.clone()), _ => out.push((s, g, vec![r.label.clone()])) }+ }+ out+ };+ let s = |t: &str| t.to_string();+ assert_eq!(got, vec![+ (s("studio"), s("webapp"), vec![s("fix login"), s("release notes")]),+ (s("studio"), s("api"), vec![s("rate limit")]),+ (s("studio"), s("No folder"), vec![s("scratch")]),+ (s("lab"), s("webapp"), vec![s("train")]),+ (s("lab"), s("ops"), vec![s("ops shell")]),]);}+ fn make_old(app: &mut App, machine: &str, id: &str) {+ let a = app.fleet.agents.get_mut(&(machine.to_string(), id.to_string())).unwrap();+ a.updated_at = crate::fleet::now_ms() - 30 * 24 * 60 * 60 * 1000;+ a.active_at = 0;+ }++ fn opened(rows: Vec<Row>) -> Picker {+ let mut p = Picker::new("t", "t");+ p.live = true;+ p.set_rows(rows);+ p+ }++ fn visible_labels(p: &Picker) -> Vec<String> { p.visible.iter().map(|(i, _)| p.rows[*i].label.clone()).collect() }++ /// A harness untouched for over a week folds under its folder's `▸ N older`; Enter's unfolding+ /// brings it back, a search finds it with no such row, and one active or on screen never folds.+ #[test]+ fn old_harnesses_fold_until_opened_or_searched() {+ let mut app = app();+ for a in app.fleet.agents.values_mut() { a.updated_at = crate::fleet::now_ms(); }+ make_old(&mut app, "local", "a1");+ make_old(&mut app, "local", "a2");+ assert_eq!(agent_rows(&app, Filter::All, None, None).iter().filter(|r| r.id.starts_with(OLDER_ROW)).count(), 2, "one for webapp, one for api");+ let mut p = opened(agent_rows(&app, Filter::All, None, None));+ let names = visible_labels(&p);+ assert!(names.contains(&"▸ 1 older".to_string()), "{names:?}");+ assert!(!names.contains(&"fix login".to_string()) && !names.contains(&"rate limit".to_string()), "{names:?}");++ let key = p.rows.iter().find(|r| r.label == "fix login").and_then(|r| r.older.clone()).unwrap();+ p.unfolded.insert(key);+ p.refilter();+ let names = visible_labels(&p);+ assert!(names.contains(&"fix login".to_string()) && !names.contains(&"rate limit".to_string()), "{names:?}");++ let mut p = opened(agent_rows(&app, Filter::All, None, None));+ p.query = "rate".into();+ p.refilter();+ let names = visible_labels(&p);+ assert!(names.contains(&"rate limit".to_string()) && !names.iter().any(|n| n.contains("older")), "{names:?}");++ app.fleet.agents.get_mut(&("local".to_string(), "a2".to_string())).unwrap().working = true;+ let p = opened(agent_rows(&app, Filter::All, None, None));+ assert!(visible_labels(&p).contains(&"rate limit".to_string()));+ }++ /// A project's own list shows all its harnesses: it was asked for by name.+ #[test]+ fn a_projects_list_does_not_fold() {+ let mut app = app();+ make_old(&mut app, "lab", "b1");+ let root = app.fleet.agents[&("lab".to_string(), "b1".to_string())].cwd.clone();+ let rows = agent_rows(&app, Filter::All, Some("lab"), Some(&root));+ assert!(rows.iter().all(|r| r.older.is_none() && !r.id.starts_with(OLDER_ROW)));+ }+/// A row is its status, name and time: where it works is its heading, not said again in it.#[test]fn a_row_says_no_machine_or_folder() {@@ -985,8 +1099,8 @@ mod agent_row_tests {a2.working = true;a2.since = crate::fleet::now_ms();let groups = by_group(&agent_rows(&app, Filter::All, None, None));- assert_eq!(groups[0], ("studio · api".to_string(), vec!["rate limit".to_string()]));- assert_eq!(groups[1].0, "studio · webapp");+ assert_eq!(groups[0], ("api".to_string(), vec!["rate limit".to_string()]));+ assert_eq!(groups[1].0, "webapp");}/// One machine's harnesses (from the machines list) are headed by their folder alone.diff --git a/tui/src/picker.rs b/tui/src/picker.rsindex 36f3d10b1..4c6332946 100644--- a/tui/src/picker.rs+++ b/tui/src/picker.rs@@ -16,6 +16,10 @@ pub struct Row {/// Everything else typing should match (label is included automatically).pub extra: String,pub group: Option<String>,+ /// A heading over its groups (a machine, over its folders).+ pub section: Option<String>,+ /// Folded under the `▸ N older` row with this key until that row is opened; a search finds it.+ pub older: Option<String>,/// Drawn before the label (state dot, engine mark).pub lead: Vec<Span<'static>>,/// Drawn after the label, dim.@@ -60,7 +64,7 @@ impl Row {impl Row {pub fn new(id: impl Into<String>, label: impl Into<String>) -> Row {- Row { id: id.into(), label: label.into(), extra: String::new(), group: None, lead: vec![], detail: vec![], right: String::new(), disabled: false, boost: 0, volatile_detail: false, volatile_right: 0, label_dim: 0, right_narrow: None, line_first: false, tier: 0 }+ Row { id: id.into(), label: label.into(), extra: String::new(), group: None, section: None, older: None, lead: vec![], detail: vec![], right: String::new(), disabled: false, boost: 0, volatile_detail: false, volatile_right: 0, label_dim: 0, right_narrow: None, line_first: false, tier: 0 }}pub fn tier(mut self, tier: u8) -> Row { self.tier = tier; self }pub fn extra(mut self, text: impl Into<String>) -> Row { self.extra = text.into(); self }@@ -217,6 +221,8 @@ pub struct Picker {pub landed: Option<Instant>,/// C-b s: the order its rows had when it opened, which they keep while it is open.pub hold: Option<Vec<String>>,+ /// C-b s: the `▸ N older` rows opened (their keys), for as long as it is open.+ pub unfolded: std::collections::HashSet<String>,/// C-b s: the rows its query found by what was said in them (best first), and that query.pub said: Vec<String>,pub said_query: String,@@ -317,6 +323,7 @@ impl Picker {defer_filter: false,header_text: None,hold: None,+ unfolded: Default::default(),q_seen: HashMap::new(),landed: None,said: Vec::new(),@@ -385,7 +392,12 @@ impl Picker {// the machines answer the new one (no row blinking out on every key).let found_now = !self.said_query.is_empty() && !query.trim().is_empty()&& (self.said_query == query || query.starts_with(&self.said_query) || self.said_query.starts_with(query));- let offered = |r: &Row| !r.id.starts_with("external:") || self.catalog_ids.contains(&r.id) || (found_now && self.said.contains(&r.id));+ // Old harnesses fold under their folder's `▸ N older` while browsing; a search goes through+ // all of them, with no such row in its results.+ let browsing = query.trim().is_empty();+ let folded = |r: &Row| browsing && r.older.as_ref().is_some_and(|k| !self.unfolded.contains(k));+ let spent = |r: &Row| r.id.strip_prefix(crate::modal::OLDER_ROW).is_some_and(|k| !browsing || self.unfolded.contains(k));+ let offered = |r: &Row| !folded(r) && !spent(r) && (!r.id.starts_with("external:") || self.catalog_ids.contains(&r.id) || (found_now && self.said.contains(&r.id)));if query.trim().is_empty() {self.visible = self.rows.iter().enumerate().filter(|(_, r)| !self.excluded.contains(&r.id) && offered(r)).map(|(i, _)| (i, Vec::new())).collect();} else {@@ -717,6 +729,8 @@ impl Picker {/// The current row marked or not, the other way: false when nothing changed (--multi=N full).pub fn toggle_mark(&mut self) -> bool {let Some(id) = self.current_id() else { return false };+ // (`▸ N older` is not a harness: nothing to mark.)+ if id.starts_with(crate::modal::OLDER_ROW) { return false }if let Some(at) = self.marked.iter().position(|m| *m == id) { self.marked.remove(at); return true }if !self.room_to_mark() { return false }self.marked.push(id);diff --git a/tui/src/preview.rs b/tui/src/preview.rsindex ecaa25d48..1c16ea9f4 100644--- a/tui/src/preview.rs+++ b/tui/src/preview.rs@@ -38,6 +38,7 @@ pub fn shell_lines(app: &App, kind: &PickerKind, id: &str) -> Vec<Line<'static>>fn lines_with_actions(app: &App, kind: &PickerKind, id: &str, actions: bool) -> Vec<Line<'static>> {match kind {+ PickerKind::Open { .. } if id.starts_with(crate::modal::OLDER_ROW) => vec![Line::raw("Harnesses not touched in the last 7 days."), Line::raw("Press enter to show them. Search always finds them.")],PickerKind::Open { .. } if id.starts_with("session:") => session(app, id),PickerKind::Open { .. } if id.starts_with("external:") => external(app, id, actions),PickerKind::Open { .. } | PickerKind::Inbox | PickerKind::Route { .. } => {diff --git a/tui/src/settings.rs b/tui/src/settings.rsindex 145c07f07..eb98215c3 100644--- a/tui/src/settings.rs+++ b/tui/src/settings.rs@@ -31,9 +31,10 @@ pub fn is_panel(kind: &PickerKind) -> bool {/// Whether [kind]'s list reads top-down (↑ toward its first row): fzf's under --layout=reverse,/// and the panel's menus; the launcher's lists read bottom-up in the panel too, their query/// under them, as fzf's do — except Models, which reads from the top as the desktop's picker does-/// (its sections in the desktop's order, and no blank space over a short list).+/// (its sections in the desktop's order, and no blank space over a short list), and the harnesses,+/// the newest at the very top, its machine and folder over it.pub fn top_down(kind: &PickerKind) -> bool {- if is_panel(kind) { !crate::modal::is_launcher(kind) || matches!(kind, PickerKind::Models) } else { theme::fzf().reverse }+ if is_panel(kind) { !crate::modal::is_launcher(kind) || matches!(kind, PickerKind::Models | PickerKind::Open { .. }) } else { theme::fzf().reverse }}/// Step into [section]: its options in the same list, the cursor on the one in use.@@ -616,7 +617,11 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:sx += put(buf, sx, qy, right.saturating_sub(sx), &text, style) + 3;}// Over it: how many rows match of how many (and how many marked), a rule after.- CountRule { shown: picker.visible.len(), total: picker.rows.len(), marked: Some(picker.marked.len()), chrome: &c }.render(Rect::new(x, qy - 1, inner_w, 1), buf);+ // (A `▸ N older` row is not one of them.)+ let folds = |id: &str| id.starts_with(crate::modal::OLDER_ROW);+ let shown = picker.visible.iter().filter(|(i, _)| !folds(&picker.rows[*i].id)).count();+ let total = picker.rows.iter().filter(|r| !folds(&r.id)).count();+ CountRule { shown, total, marked: Some(picker.marked.len()), chrome: &c }.render(Rect::new(x, qy - 1, inner_w, 1), buf);// Over that: this list's keys, `key what` · `key what`, the keys bold (the tab row's own,// while it has the keys).let tab_keys = [("← →", "switch"), ("↑", "list"), ("type", "to search")];@@ -722,16 +727,7 @@ fn grouped(picker: &Picker) -> bool {/// The lines [list] draws for [picker]'s rows, top-down: each row, a heading where the group/// changes and a blank line before every heading but the first (at least one: the empty notice).-pub fn list_lines(picker: &Picker) -> usize {- let (grouped, mut lines, mut last) = (grouped(picker), 0, None);- for (i, _) in &picker.visible {- let group = picker.rows[*i].group.as_deref().filter(|_| grouped);- if group.is_some() && group != last { lines += 1 + usize::from(lines > 0) }- last = group;- lines += 1;- }- lines.max(1)-}+pub fn list_lines(picker: &Picker) -> usize { list_layout(picker, false).0.len().max(1) }/// The rows, top-down, the cursor's row marked as the New Harness chooser marks its own.pub fn list(buf: &mut Buffer, picker: &mut Picker, r: Rect, c: &Chrome, details: bool) { list_from(buf, picker, r, c, details, false) }@@ -775,7 +771,10 @@ impl StatefulWidget for PanelList<'_> {let line = Rect::new(r.x, y, r.width, 1);match lines[i] {Some(vi) => { self.row(buf, picker, vi, line); row_at.push((y, vi)) }- None => if let Some((_, title)) = titles.iter().find(|(at, _)| *at == i) { put(buf, r.x + 2, y, r.width.saturating_sub(2), title, c.muted.add_modifier(Modifier::BOLD)); },+ None => if let Some((_, title, kind)) = titles.iter().find(|(at, _, _)| *at == i) {+ let style = match kind { TitleKind::Plain => c.muted.add_modifier(Modifier::BOLD), TitleKind::Section => c.base.add_modifier(Modifier::BOLD), TitleKind::Under => c.muted };+ put(buf, r.x + 2, y, r.width.saturating_sub(2), title, style);+ },}}// (No scrollbar: the list follows the cursor, the wheel scrolls it.)@@ -796,48 +795,78 @@ fn empty_notice(picker: &Picker) -> String {empty}+/// What a heading in the list heads, for how it is drawn.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum TitleKind {+ /// A group with nothing over it.+ Plain,+ /// A section (a machine): the strong one, a blank line over it.+ Section,+ /// A group under a section (a folder under its machine): quiet, level with it, no blank line.+ Under,+}+/// The lines as drawn, first to last (bottom to top when [bottom_up]): each visible row by its/// index, and None for a heading (titled, at its line) or the blank line before one.-fn list_layout(picker: &Picker, bottom_up: bool) -> (Vec<Option<usize>>, Vec<(usize, String)>) {+fn list_layout(picker: &Picker, bottom_up: bool) -> (Vec<Option<usize>>, Vec<(usize, String, TitleKind)>) {// The lines as drawn: each row, and a titled heading (a blank line before it) wherever the// group changes — as opencode's palette groups its commands. The scroll counts lines.let mut lines: Vec<Option<usize>> = Vec::new();- let mut titles: Vec<(usize, String)> = Vec::new();- let mut last: Option<&str> = None;+ let mut titles: Vec<(usize, String, TitleKind)> = Vec::new();+ let (mut last, mut last_section): (Option<&str>, Option<&str>) = (None, None);let grouped = grouped(picker);if !bottom_up {for vi in 0..picker.visible.len() {- let group = picker.rows[picker.visible[vi].0].group.as_deref().filter(|_| grouped);- if group.is_some() && group != last {- if !lines.is_empty() { lines.push(None) }- titles.push((lines.len(), group.unwrap_or_default().to_string()));+ let row = &picker.rows[picker.visible[vi].0];+ let (group, section) = (row.group.as_deref().filter(|_| grouped), row.section.as_deref().filter(|_| grouped));+ if let Some(title) = group.filter(|_| group != last || section != last_section) {+ if section.is_none() || section != last_section {+ if !lines.is_empty() { lines.push(None) }+ if let Some(s) = section { titles.push((lines.len(), s.to_string(), TitleKind::Section)); lines.push(None) }+ }+ titles.push((lines.len(), title.to_string(), if section.is_some() { TitleKind::Under } else { TitleKind::Plain }));lines.push(None);}- last = group;+ (last, last_section) = (group, section);lines.push(Some(vi));}} else {- // Bottom up: a group's rows, then its heading (drawn over them), then a blank.- let mut pending: Option<String> = None;+ // Bottom up: a group's rows, then its heading (drawn over them), then its section's if the+ // next rows are not in it, then a blank.+ let mut pending: Option<(String, Option<String>)> = None;for vi in 0..picker.visible.len() {- let group = picker.rows[picker.visible[vi].0].group.as_deref().filter(|_| grouped);- if group != last {- if let Some(title) = pending.take() { titles.push((lines.len(), title)); lines.push(None); lines.push(None) }- pending = group.map(str::to_string);+ let row = &picker.rows[picker.visible[vi].0];+ let (group, section) = (row.group.as_deref().filter(|_| grouped), row.section.as_deref().filter(|_| grouped));+ if group != last || section != last_section {+ if let Some((title, over)) = pending.take() {+ titles.push((lines.len(), title, if over.is_some() { TitleKind::Under } else { TitleKind::Plain }));+ lines.push(None);+ match over {+ Some(s) if Some(s.as_str()) != section => { titles.push((lines.len(), s, TitleKind::Section)); lines.push(None); lines.push(None) }+ Some(_) => {}+ None => lines.push(None),+ }+ }+ pending = group.map(|g| (g.to_string(), section.map(str::to_string)));}- last = group;+ (last, last_section) = (group, section);lines.push(Some(vi));}- if let Some(title) = pending { titles.push((lines.len(), title)); lines.push(None) }+ if let Some((title, over)) = pending {+ titles.push((lines.len(), title, if over.is_some() { TitleKind::Under } else { TitleKind::Plain }));+ lines.push(None);+ if let Some(s) = over { titles.push((lines.len(), s, TitleKind::Section)); lines.push(None) }+ }}(lines, titles)}/// [picker]'s scroll (the first line shown of [n]) keeping the cursor's row in view — and, top-/// down, its heading with it — unless the wheel put the list where it is.-fn scroll_to_cursor(picker: &mut Picker, lines: &[Option<usize>], titles: &[(usize, String)], n: usize, bottom_up: bool) {+/// down, its headings with it — unless the wheel put the list where it is.+fn scroll_to_cursor(picker: &mut Picker, lines: &[Option<usize>], titles: &[(usize, String, TitleKind)], n: usize, bottom_up: bool) {let at_line = lines.iter().position(|l| *l == Some(picker.cursor)).unwrap_or(0);- let top = if !bottom_up && at_line >= 1 && titles.iter().any(|(i, _)| *i + 1 == at_line) { at_line - 1 } else { at_line };+ let mut top = at_line;+ while !bottom_up && top >= 1 && titles.iter().any(|(i, _, _)| *i + 1 == top) { top -= 1 }if !picker.free_scroll {if top < picker.scroll { picker.scroll = top }if at_line >= picker.scroll + n { picker.scroll = at_line + 1 - n }@@ -858,7 +887,8 @@ impl PanelList<'_> {if picker.marked.contains(&row.id) { put(buf, r.x + 1, y, 1, "•", if here { c.selected } else { c.accent }); }let mut at = r.x + 2;for span in &row.lead {- let s = if here { style.patch(Style::default().fg(span.style.fg.unwrap_or(Color::Reset))) } else { c.base.patch(span.style) };+ // (A mark keeps its colour on the cursor's row, and its tile if it has one.)+ let s = if here { let s = style.patch(Style::default().fg(span.style.fg.unwrap_or(Color::Reset))); match span.style.bg { Some(tile) => s.bg(tile), None => s } } else { c.base.patch(span.style) };at += put(buf, at, y, r.right().saturating_sub(at), &span.content, s);}// The right column as the row has it for this width (its short form in a narrow list:@@ -1788,7 +1818,40 @@ mod tests {(buf, p.screen_area.get(), cursor)}- /// The launcher's rows from the list's tail to the query, and the styles of its query, count,+ /// The harness list reads from the top, the first row first, its query still under it.+ #[test]+ fn the_harness_list_reads_from_the_top() {+ let _l = crate::term_out::colours_lock();+ let (buf, r, _) = launcher_buffer("", false);+ let row = |y: u16| (r.x..r.right()).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>().replace('│', "").trim_end().to_string();+ let rows: Vec<String> = (r.y + 3..r.y + 6).map(row).collect();+ assert_eq!(rows, [" ›•alpha", " beta", " alpine"]);+ }++ /// A machine's heading, its folders level with it under it, a blank line only between machines:+ /// no indent, and the cursor's row keeps both headings in view.+ #[test]+ fn machines_head_their_folders_with_no_indent() {+ use crate::picker::Row;+ let mut p = Picker::new("harnesses", "");+ let row = |id: &str, s: &str, g: &str| { let mut r = Row::new(id, id).group(g); r.section = Some(s.to_string()); r };+ p.set_rows(vec![row("a", "studio", "webapp"), row("b", "studio", "api"), row("c", "lab", "webapp")]);+ let (lines, titles) = list_layout(&p, false);+ let at = |t: &str, k: TitleKind| titles.iter().filter(|(_, s, kind)| s == t && *kind == k).map(|(i, _, _)| *i).collect::<Vec<_>>();+ assert_eq!(at("studio", TitleKind::Section), [0]);+ assert_eq!(at("webapp", TitleKind::Under), [1, 7]);+ assert_eq!(at("api", TitleKind::Under), [3]);+ assert_eq!(at("lab", TitleKind::Section), [6]);+ assert_eq!(lines, [None, None, Some(0), None, Some(1), None, None, None, Some(2)]);+ assert_eq!(list_lines(&p), 9);+ // Scrolled past them, coming back to the first row brings its two headings too.+ p.cursor = 0;+ p.scroll = 2;+ scroll_to_cursor(&mut p, &lines, &titles, 4, false);+ assert_eq!(p.scroll, 0);+ }++ /// The launcher's keys, count and query at its foot, and the styles of its query, count,/// rule and keys: what `draw` drew inline before those lines became shared pieces.#[test]fn the_launcher_keeps_its_rows_and_styles() {@@ -1798,11 +1861,11 @@ mod tests {let rule = |count: &str| format!(" {count} {}", "─".repeat(86 - count.width() - 1));let query = |typed: &str, more: &str| format!(" › {typed} [harnesses] > commands @ machines # projects : models{more}");let keys = |s: &str| format!(" {s}");- let (alpine, beta, alpha) = (" alpine".to_string(), " beta".to_string(), " ›•alpha".to_string());+ let blank = String::new;let cases = [- ("", false, [alpine.clone(), beta.clone(), alpha.clone(), String::new(), keys("↑↓ move · enter open"), rule("3/3 (1)"), query("Search harnesses", "")]),- ("al", false, [String::new(), alpine.clone(), alpha.clone(), String::new(), keys("↑↓ move · enter open"), rule("2/3 (1)"), query("al", " * store")]),- ("", true, [alpine, beta, alpha, String::new(), keys("← → switch · ↑ list · type to search"), rule("3/3 (1)"), query("Search harnesses", "")]),+ ("", false, [blank(), blank(), blank(), blank(), keys("↑↓ move · enter open"), rule("3/3 (1)"), query("Search harnesses", "")]),+ ("al", false, [blank(), blank(), blank(), blank(), keys("↑↓ move · enter open"), rule("2/3 (1)"), query("al", " * store")]),+ ("", true, [blank(), blank(), blank(), blank(), keys("← → switch · ↑ list · type to search"), rule("3/3 (1)"), query("Search harnesses", "")]),];for (typed, on_tabs, want) in cases {let (buf, r, _) = launcher_buffer(typed, on_tabs);diff --git a/tui/src/theme.rs b/tui/src/theme.rsindex 767cc5b0e..f01b68a9c 100644--- a/tui/src/theme.rs+++ b/tui/src/theme.rs@@ -1255,15 +1255,31 @@ pub fn engine_mark(engine: &str) -> (&'static str, Color) {(mark, paint(color))}+/// The tile an engine's mark sits on, for the marks that have one: Codex's purple cloud on white,+/// OpenCode's white square on black.+pub fn engine_tile(engine: &str) -> Option<Color> {+ match engine {+ "codex" => Some(paint(Color::Rgb(0xFF, 0xFF, 0xFF))),+ "opencode" => Some(paint(Color::Rgb(0x00, 0x00, 0x00))),+ _ => None,+ }+}++/// An engine's mark as drawn: its colour, on its tile if it has one.+pub fn engine_style(engine: &str) -> Style {+ let style = fg(engine_mark(engine).1);+ match engine_tile(engine) { Some(tile) => style.bg(tile), None => style }+}+/// A colour as this terminal can show it: none under NO_COLOR, the nearest it has otherwise.pub fn paint(c: Color) -> Color { if no_color() { Color::Reset } else { depth_fit(c) } }fn engine_mark_raw(engine: &str) -> (&'static str, Color) {match engine {"claude" => ("✳", Color::Rgb(0xD9, 0x77, 0x57)),- "codex" => ("◎", Color::Rgb(0x10, 0xA3, 0x7F)),+ "codex" => ("☁", Color::Rgb(0x7C, 0x3A, 0xED)),"cursor" => ("▲", TEXT),- "opencode" => ("▣", Color::Rgb(0xF5, 0xA7, 0x42)),+ "opencode" => ("■", Color::Rgb(0xFF, 0xFF, 0xFF)),"pi" => ("π", ACCENT_SOFT),"hermes" => ("☿", Color::Rgb(0xC7, 0x92, 0xEA)),"amp" => ("ϟ", DANGER),diff --git a/tui/tests/harness-list.py b/tui/tests/harness-list.pynew file mode 100644index 000000000..2613b88bf--- /dev/null+++ b/tui/tests/harness-list.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+"""The harness list with real keys: newest first, machine over folders, old sessions folded.++Only a private fixture backend, temporary HOME and explicitly named hn/tmux sockets.+"""+import os+from pathlib import Path+import shlex+import shutil+import socket+import subprocess+import sys+import tempfile+import time+import urllib.request++ROOT = Path(__file__).resolve().parents[1]+PORT = int(os.environ.get('HN_HARNESS_LIST_PORT', '19786'))+assert 19783 <= PORT <= 19789, 'refusing non-test port'+PREFIX = f'hn-harness-list-{os.getpid()}'+BASE = Path(tempfile.mkdtemp(prefix='hnhl-', dir='/tmp')).resolve()+HN = BASE / 'hn'+shutil.copy2(os.environ.get('HN_HARNESS_LIST_BINARY', ROOT / 'target/release/harness-tui'), HN)+TMUX = shutil.which('tmux')+assert TMUX+ENV = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ') if k in os.environ}+ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(PORT),+ TERM='xterm-256color', COLORTERM='truecolor', SHELL='/bin/sh', HARNESS_TUI_DESK='sync',+ HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', MOCK_DEMO='1', MOCK_RECONNECT='1',+ MOCK_OLD_HARNESSES='1')+# (hn asks the `harness` CLI who is signed in: one on this PATH answers "nobody" for this HOME.)+ENV['PATH'] = os.pathsep.join(d for d in ENV['PATH'].split(os.pathsep) if not (Path(d) / 'harness').exists())+++def tmux(*args, ok=True):+ p = subprocess.run([TMUX, '-L', PREFIX + '-outer', *args], env=ENV, cwd=BASE,+ text=True, capture_output=True, timeout=10)+ if ok: assert p.returncode == 0, (args, p.stderr)+ return p.stdout+++def screen(): return tmux('capture-pane', '-p', '-t', 'test')+def coloured(): return tmux('capture-pane', '-p', '-e', '-t', 'test')+def wait(fn, label, seconds=8):+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ if fn(): return+ time.sleep(.05)+ raise AssertionError(label + '\n' + screen())+def shows(text): taken(text)+def gone(text): wait(lambda: text not in screen(), 'still shows ' + text)+def keys(*args): tmux('send-keys', '-t', 'test', *args); time.sleep(.15)+def type_text(text): tmux('send-keys', '-l', '-t', 'test', text); time.sleep(.15)+def taken(text, seconds=8):+ # One capture that has [text]: every check on it reads the same frame.+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ s = screen()+ if text in s: return s+ time.sleep(.05)+ raise AssertionError(text + '\n' + screen())+++mock = None+started = False+try:+ with socket.socket() as probe: probe.bind(('127.0.0.1', PORT))+ mock = subprocess.Popen(['node', str(ROOT / 'tests/mock-daemon.mjs'), str(PORT)], env=ENV,+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ for _ in range(100):+ assert mock.poll() is None+ try:+ urllib.request.urlopen(f'http://127.0.0.1:{PORT}/test/dial', timeout=2).read()+ break+ except OSError: time.sleep(.05)+ else: raise AssertionError('mock startup timeout')+ command = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',+ *[f'{k}={v}' for k, v in ENV.items()], str(HN), '-L', PREFIX,+ '--port', str(PORT), '-f', '/dev/null'])+ tmux('-f', '/dev/null', 'new-session', '-d', '-s', 'test', '-x', '170', '-y', '50', command)+ tmux('set-window-option', '-t', 'test', 'remain-on-exit', 'on')+ shows('Fix flaky login test')+ started = True++ time.sleep(1) # (The account check settles first: it owns the keys until it has.)+ keys('C-b', 's')+ s = taken('▸ 25 older')+ if len(sys.argv) > 1: print(s)++ # The month-old ones are folded, and their folder is the last one on their machine.+ assert 'Old session' not in s, s+ assert s.index('old-repo') < s.index('▸ 25 older'), s+ assert s.index('old-repo') > s.index('billing'), 'newest folders first\n' + s++ # One column: a machine, its folders, their rows, no indent; never `machine · folder`.+ column = lambda text: next(l.index(text) for l in s.splitlines() if text in l)+ assert column('studio') == column('old-repo') == column('▸ 25 older'), s+ assert ' · old-repo' not in s, s++ # The keys line has the main keys and says where the rest are.+ assert 'enter add pane' in s and 'C-t new window' in s and '? all keys' in s, s+ assert 'M-s message' not in s and 'M-r restart' not in s, s++ # Enter on `▸ 25 older` shows them, newest first.+ for _ in range(60):+ if any('›' in l and '▸ 25 older' in l for l in taken('Search harnesses').splitlines()): break+ keys('Down')+ else: raise AssertionError('never reached ▸ 25 older\n' + screen())+ keys('Enter')+ s = taken('Old session 0')+ assert '▸ 25 older' not in s, s+ assert s.index('Old session 0') < s.index('Old session 2'), s++ # Opened again they are folded again; a search finds one, with no `older` row in its results.+ keys('Escape'); gone('Search harnesses')+ keys('C-b', 's'); taken('▸ 25 older')+ type_text('Old session 7')+ s = taken('Old session 7')+ assert 'older' not in s, s++ # OpenCode's white square on black and Codex's purple cloud on white, cursor's row included.+ painted = coloured()+ assert any(p in painted for p in ('48;2;0;0;0', '48;5;16', '48;5;0')) and '■' in painted, repr(painted)+ keys('C-u'); type_text('Old session 8'); taken('Old session 8')+ painted = coloured()+ assert any(p in painted for p in ('48;2;255;255;255', '48;5;231', '48;5;15')) and '☁' in painted, repr(painted)+ print('harness-list ok')+except BaseException:+ if started: print(screen(), file=sys.stderr)+ raise+finally:+ if started:+ subprocess.run([str(HN), '-L', PREFIX, '--port', str(PORT), '-f', '/dev/null', 'kill-server'], env=ENV, cwd=BASE, capture_output=True, timeout=12)+ subprocess.run([TMUX, '-L', PREFIX + '-outer', 'kill-server'], env=ENV, cwd=BASE, capture_output=True)+ if mock:+ mock.terminate()+ try: mock.wait(timeout=5)+ except subprocess.TimeoutExpired: mock.kill()+ shutil.rmtree(BASE, ignore_errors=True)diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjsindex 80727eb48..966321a91 100644--- a/tui/tests/mock-daemon.mjs+++ b/tui/tests/mock-daemon.mjs@@ -54,6 +54,14 @@ if (process.env.MOCK_PROJECT_SEARCH === '1') {`autonomous-harness-2026-${String(i).padStart(3, '0')}`, 'main'))}}+if (process.env.MOCK_OLD_HARNESSES === '1') {+ // A month-old history in a folder of its own, for the harness list's `▸ N older`.+ for (let i = 0; i < 25; i++) {+ const older = new Date(Date.parse(now) - (30 + i) * 86_400_000).toISOString()+ agents[LOCAL].push(project({ ...agent(`old-${i}`, `Old session ${i}`, i % 2 ? 'opencode' : 'codex', 'stopped'), createdAt: older, updatedAt: older },+ 'old-repo', 'main'))+ }+}if (process.env.MOCK_SHARED_LAYOUT === '1') {for (let i = 1; i <= 9; i++) agents[LOCAL].push(agent(`shared-layout-${i}`, `Shared pane ${i}`, 'terminal'))}