diff --git a/docs/glossary.md b/docs/glossary.md index edf651e55..94f7e06ad 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -134,12 +134,14 @@ ACP v1 defines prompt turns but no agent-initiated turn primitive. | Term | Definition | Aliases to avoid | | -------------------- | ------------------------------------------------------------------------------------------------- | ------------------ | | **Session envelope** | A session event tagged with its **conversation ID**, agent, and per-conversation sequence number. | Frame, message | -| **Session status** | A managed session's coarse state: starting, working, waiting on you, ready, failed, or closed. | Phase, turn status | +| **Session status** | A managed session's coarse state: starting, working, waiting on you, ready, failed, closed, or done (a delegated child whose task finished). | Phase, turn status | | **Session family** | A top-level **session** plus all of its descendants, whose **session statuses** roll up into one. | Thread, tree | | **Request resolved** | A **session envelope** announcing that a client answered a pending agent request, and which one. | Approval event | | **Active session** | The one **session** the TUI shows; the prompt, terminal title, and scrollback belong to it. | Current tab | | **Parked session** | A live **session** the TUI holds off screen with its own transcript, input, and pending requests. | Hidden, paused | | **Session cap** | The most managed **sessions** that may run at once, set by `[tui] max_sessions`. | Limit, quota | +| **Delegated child** | A **session** the **session manager** starts for a parent through `/delegate` or the MCP `delegate` tool; named by the first line of its task. | Subagent, worker | +| **Delegation origin** | Who asked for a **delegated child**: the parent's agent (`agent`) or the user (`user`). | Requester, source | ### Session lifecycle @@ -180,6 +182,7 @@ ACP v1 defines prompt turns but no agent-initiated turn primitive. - A **request resolved** envelope removes that request from the ones keeping a **session status** at "waiting on you"; requests cleared by idle, cancel, or session end get none. - When the **session manager** restarts a failed session, its **conversation ID**, family position, and envelope sequence continue across the new agent process. Remote targets, subscriptions, and replay cursors keep using that ID. - With `[features] multi_session`, replacing the **active session** parks it instead of closing it; a **parked session** keeps running and receiving its events. +- A **delegated child** belongs to its parent's **session family** and, in the local TUI, is a **parked session** until the user moves to it; its result returns to the parent as a queued prompt. ### Example dialogue diff --git a/docs/remote-control.md b/docs/remote-control.md index 8e5388d93..5d2cf1f9a 100644 --- a/docs/remote-control.md +++ b/docs/remote-control.md @@ -336,8 +336,9 @@ prompts; the WebSocket extension controls sessions already owned by the TUI. | `_nori/session/delegate` | Optional parent `session_id`, `agent`, `task` | Delegation record | | `_nori/session/delegation/resolve` | Optional parent `session_id`, delegation `request_id`, `approved` boolean | Updated delegation record | -A list row reports identity, agent, status, cwd, lineage, pending request IDs, -`source`, delegation `depth`, the parent's `delegations`, sequence bounds (`latest_seq`, `first_available_seq`), age in seconds, and a +A list row reports identity, agent, status, `family_status` (the most urgent +status across the row's whole session family, rooted at its top-level session), +cwd, lineage, pending request IDs, `source`, delegation `depth`, the parent's `delegations`, sequence bounds (`latest_seq`, `first_available_seq`), age in seconds, and a title derived from observed session activity. `replay_cursors` includes every conversation known to the journal. Restarting a failed session with Ctrl+R keeps its Nori conversation ID, list row, and sequence counter. Existing subscriptions @@ -384,7 +385,11 @@ Agents without HTTP MCP support retain user-driven `/delegate`, but have no stdio agent-tool fallback. A delegation record contains `request_id`, `parent_id`, `child_id`, -`parent_agent`, `agent`, `task`, `depth`, `status`, and optional `result`. +`parent_agent`, `agent`, `task`, `depth`, `status`, optional `result`, and +`origin`. `origin` is `agent` when the parent agent called the MCP `delegate` +tool and `user` when the request came through the manager directly (`/delegate` +or `_nori/session/delegate`); records from hosts that predate the field +deserialize as `agent`. Clients use it only to word who asked for the child. The child conversation ID is reserved before approval. The statuses are `awaiting_approval`, `running`, `declined`, `completed`, `failed`, and `cancelled`; these describe delegation state, separately from session status. @@ -395,7 +400,8 @@ parent-only subscription does not become a subscription to every descendant. Same-kind children start immediately. A different-kind request returns `awaiting_approval`; resolve it for the requesting parent and request ID with -`approved: true` (Start) or `approved: false` (Decline). Only the controller may +`approved: true` or `approved: false` (the terminals label these +"Yes, start it" and "No, decline"). Only the controller may request or resolve delegation. Unknown, resolved, or wrongly attributed requests fail rather than starting another child. Approval does not reserve a process indefinitely: actual startup must pass the shared session cap. Depth @@ -409,10 +415,23 @@ the new parent identity. A child's ACP permission request belongs to that child's conversation and request ID. Answer it after selecting the child, with Alt+Down in the terminal -for next waiting session. Parent notices name the child and parent rather than -opening the child's permission popup in the parent. A completed child's result -is automatically queued as attributed input to the parent, including when the -parent is busy. The manager retains delivery until that parent's correlated +for next waiting session. Instead of opening the child's permission popup in +the parent, the parent receives a notice that names both sessions readably: +` · is waiting on you (delegated by · ). Press Alt+Down to answer it.` The child name is the first non-empty +line of the task (else `new session`) and the parent name is its recorded +title, each cut to 40 characters in the middle (start, `…`, end) so names +sharing a long prefix stay distinct. A completed child's result is automatically queued as attributed +input to the parent, including when the parent is busy. That prompt's first +line is `[Nori delegation result] from · · ` +(`done`, `failed`, `declined`, or `cancelled`; the child name here is the +task's whole first line), its second is +`Child session: `, and the rest is the child's result text (its last +turn's message text, with a paragraph break wherever a tool call, permission +request, or other update interrupted it; for a crashed child, the first line of +its failure). A declined delegation never started a child, so its prompt has no +`Child session:` line. The parent's own ID is not included, and the prompt +never becomes the parent's title. The manager retains delivery until that parent's correlated ACP prompt response, rather than treating queue admission as acknowledgment. If the parent process crashes before acknowledgment, stable-ID resume submits the result again. A delegated child with descendants waits for them and its @@ -424,6 +443,9 @@ the parent's process has already failed. Parent crash preserves running children and holds results until stable-ID resume (Ctrl+R). Child failure returns a failure result without failing the parent. This state belongs to the current manager lifetime; host restart does not restore it from transcripts. +After a restart a finished child is not listed by `nori host ls` or +`nori attach`, and `/resume` on its transcript reopens it as a live top-level +`ready` session without its parent link. ### Reconnect and retention @@ -490,7 +512,7 @@ released after cleanup. Startup and stop do not require a terminal. | Command | Behavior | | --- | --- | | `nori host` | Start the background host, or report the already-running host. | -| `nori host ls` | Print the flat `ID AGENT STATUS AGE TITLE` table; TTY output colors status and truncates titles to the terminal width, while piped output keeps full titles without color. | +| `nori host ls` | Print the `ID AGENT STATUS AGE TITLE` table with delegated children listed under their parent and `├─`/`└─`/`│` tree guides inside TITLE. Top-level rows show their `family_status` when the host sends it. TTY output colors status (waiting on you yellow, working cyan, ready green, failed red, done in the default color, starting and closed dimmed) and fits the terminal: IDs shorten and AGENT and STATUS cut with `…` as the width shrinks, AGE is never cut, and TITLE always gets the remaining cells, keeping its tree guide whole and cutting the name in the middle; piped output keeps full values without color and appends ` (parent )` to every row with a parent, including a child whose parent is no longer listed and so prints at top level. | | `nori attach` | Open the host session list; requires `[features] multi_session = true`. | | `nori attach ` | Open the named Nori conversation. | | `nori attach --host --token-file ` | Connect to an explicit managed endpoint using a private token file. | @@ -575,10 +597,29 @@ current session marker appears inside TITLE, leaving its short ID visible. Session commands address the host; they do not launch local agents. `/delegate ` is the delegation entry point; the list does not start delegations. The configured `hotkeys.next_waiting_session` binding -(Alt+Down by default) selects the next waiting child or other session. -Delegated child rows prefix TITLE with the parent identity and hierarchy marker, -so long task titles cannot displace that identity; metadata columns remain fixed -in the attached list and `nori host ls`. +(Alt+Down by default) selects the next waiting child or other session, even +with an unsent draft (with nothing waiting, a draft keeps the key for the +composer), and +`hotkeys.parent_session` (Alt+Up by default) returns from a delegated child to +its parent. Both the attached list and `nori host ls` order children directly +under their parent and draw tree guides inside TITLE, so the ID, AGENT, STATUS, +and AGE columns stay aligned, and both show a top-level row's `family_status`. +Each session keeps its own unsent draft: switching sessions parks the +composer text with the session it was typed in and restores the target's. +The identity line names the selected session; a top-level session shows its +family status, as the lists do. Inside a delegated child (not a fork), it reads +as a breadcrumb of agents and names from the top-level session down to the +child. Both are fitted to the terminal width: the parent key gives way before +the current name is cut, and names are cut in the middle. A second line names +the next other session waiting on you, under its parent, with the jump key. A +delegated child whose task finished lists as `done` (default color); `closed` +(muted) means a session the user closed or shut down. A child's history ends +with `This child finished its task` or `This child session ended`, plus the +parent key. An attached parent shows a delivered result prompt as one +`› delegation result from · · · delivered to this +session` line, which drops the delivered suffix and then cuts the name to fit +one row. A running child's delegation card reads `started`, because cards are +printed once and do not update. Socket loss or a receive-liveness deadline starts recovery. Periodic session list requests keep idle connections observable; receiving JSON renews the diff --git a/justfile b/justfile index efe12ce2d..66dae6c15 100644 --- a/justfile +++ b/justfile @@ -53,7 +53,7 @@ test *args: cd nori-rs && cargo test -p codex-core "$@" ;; protocol) - cd nori-rs && cargo test -p codex-protocol "$@" + cd nori-rs && cargo test -p nori-protocol "$@" ;; e2e) cd nori-rs && cargo build --bin nori && cargo test -p tui-pty-e2e "$@" diff --git a/nori-rs/Cargo.lock b/nori-rs/Cargo.lock index 2e56a6300..84b3a454d 100644 --- a/nori-rs/Cargo.lock +++ b/nori-rs/Cargo.lock @@ -3821,6 +3821,7 @@ dependencies = [ "nori-harness", "nori-installed", "nori-tui", + "nori-tui-components", "owo-colors", "predicates", "pretty_assertions", @@ -4030,6 +4031,7 @@ dependencies = [ "ratatui", "supports-color", "textwrap 0.16.2", + "unicode-segmentation", "unicode-width 0.2.1", ] diff --git a/nori-rs/cli/Cargo.toml b/nori-rs/cli/Cargo.toml index d7d98546c..469706b10 100644 --- a/nori-rs/cli/Cargo.toml +++ b/nori-rs/cli/Cargo.toml @@ -30,6 +30,7 @@ codex-execpolicy = { workspace = true } codex-process-hardening = { workspace = true } codex-stdio-to-uds = { workspace = true } nori-tui = { workspace = true } +nori-tui-components = { workspace = true } ctor = { workspace = true } crossterm = { workspace = true } unicode-segmentation = { workspace = true } diff --git a/nori-rs/cli/docs.md b/nori-rs/cli/docs.md index ad00e7fd9..cf68da741 100644 --- a/nori-rs/cli/docs.md +++ b/nori-rs/cli/docs.md @@ -49,7 +49,7 @@ PostHog identity or organization membership itself. - TUI flags such as `--agent`, approval-bypass options, prompts, images, `-c`, and working-directory overrides can be passed after `resume`; they are merged into the normal interactive CLI configuration before `nori_tui::run_main()` **Host and attach:** `nori host` starts a detached Unix process owning an empty -session manager; `host ls` reads its flat table and `host stop` shuts it down. +session manager; `host ls` prints its sessions as a tree-ordered table and `host stop` shuts it down. The host outlives both attached terminals and its final session. `nori attach` requires `multi_session`, discovers the local host and token, then opens the session list or a supplied conversation ID. Explicit `--host` and diff --git a/nori-rs/cli/src/host/docs.md b/nori-rs/cli/src/host/docs.md index 6ed38d7f5..1e3987f34 100644 --- a/nori-rs/cli/src/host/docs.md +++ b/nori-rs/cli/src/host/docs.md @@ -47,13 +47,45 @@ host ls / host stop ---------------+ SessionManager - Each start generates a token and binds loopback before publishing discovery state. Administrative clients initialize with `observe: true`, so list and stop do not claim the controller slot. [List formatting](table.rs) sanitizes - control characters and colors status only on a terminal. Terminal rows fit - the available display cells by truncating titles with an ellipsis at grapheme - boundaries; if metadata alone exceeds the width, that prefix is clipped. - Piped output retains full titles without color or a width limit. Delegated - child rows retain their own ID, agent, status, and age columns; the hierarchy - marker and parent identity prefix TITLE, so long task titles do not displace - parent attribution and indentation never shifts the metadata columns. + control characters and colors status only on a terminal. On a terminal the + ID, AGENT, STATUS, and AGE columns take one of three fixed layouts, chosen + as the widest that still leaves TITLE at least 24 cells: + + | Layout | ID | AGENT | STATUS | AGE | Used when | + | --- | --- | --- | --- | --- | --- | + | Wide | 36 | 16 | 16 | 6 | TITLE keeps 24 cells; also every piped listing | + | Compact | 8 | 14 | 16 | 5 | Wide does not fit; matches the `nori attach` list | + | Tight | 8 | 10 | 14 | 4 | Neither fits | + + The ID is shortened to the column, AGENT and STATUS are cut with `…`, and + AGE is never cut. TITLE, with its tree guides, gets whatever cells remain + (none only below the tight layout's metadata width). The guide stays whole + and the name is cut in the middle (start, `…`, end) at grapheme boundaries, + so titles sharing a long prefix still read apart; only when the room is no + wider than the guide is the whole title cut from the end. Status color applies on every row. Piped output + keeps full values in the wide layout, without color or a width limit. +- A top-level row (tree depth 0) shows the row's `family_status` when the host + sends one, so a parent reads `waiting on you` while anything under it does; + child rows always show their own `status`. Older hosts omit + `family_status`, and the row falls back to `status`. +- Rows are tree-ordered with the shared + [picker helpers](../../../tui-components/docs.md): `tree_order` builds a + depth-first order from each row's `session_id` and `parent` (a missing + parent makes the row top level), and `tree_guides` supplies `├─`, `└─`, and + `│` prefixes. The guides are written inside TITLE, after the fixed ID, AGENT, + STATUS, and AGE columns, so nesting never shifts metadata. Piped output appends + ` (parent )` to every row that has a parent, including a + child whose parent is no longer listed and so prints at top level, so scripts + keep the exact link; terminal output omits it. + + | Status | Terminal color | + | --- | --- | + | waiting on you | yellow | + | working | cyan | + | ready | green | + | failed | red | + | done | default color, so a finished child reads apart from a closed one | + | others (starting, closed) | dimmed | - Lifecycle requests prepare agents using the host's configuration. Resume uses the stored agent and working directory while retaining the conversation identity. Stop closes the server, shuts down the manager, removes discovery @@ -72,11 +104,13 @@ host ls / host stop ---------------+ SessionManager - Delegation requests pass through `ManagedRemoteHost` to the same manager used by local sessions. Child sessions consume the ordinary session cap; completing a child releases its process slot but preserves its listed record - and transcript. Closing a parent cancels descendants, while a parent crash + and transcript, and the row then reads `done` rather than `closed`. Closing a parent cancels descendants, while a parent crash preserves children and holds their results for stable-ID resume. - The host has no persistent manager snapshot. Transcripts survive normally, but in-memory registry state and reconnect replay belong to the current host - process. The token rotates when that process starts again. + process. After a restart, earlier sessions, including finished delegated + children, are not listed; `/resume` on a child's transcript reopens it as a + live top-level `ready` session without its parent link. The token rotates when that process starts again. - [Lifecycle tests](../../tests/host_lifecycle.rs) use isolated homes and bounded process waits to cover detached startup, privacy, lock ownership, occupied ports, and explicit stop. diff --git a/nori-rs/cli/src/host/table.rs b/nori-rs/cli/src/host/table.rs index d3da6427f..6e6f951b7 100644 --- a/nori-rs/cli/src/host/table.rs +++ b/nori-rs/cli/src/host/table.rs @@ -1,20 +1,98 @@ -//! Flat host listing with terminal-cell budgets; piped output retains complete values. +//! Host session listing with terminal-cell budgets; piped output retains +//! complete values. +//! +//! Children follow their parent. Tree glyphs sit inside TITLE so the ID, +//! AGENT, STATUS, and AGE columns never move. use owo_colors::OwoColorize; use serde_json::Value; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; +/// Cells for ID, AGENT, STATUS, and AGE. TITLE takes what is left. +#[derive(Clone, Copy)] +struct Columns { + id: usize, + agent: usize, + status: usize, + age: usize, +} + +impl Columns { + /// The two spaces after every column, TITLE's start included. + fn prefix(self) -> usize { + self.id + self.agent + self.status + self.age + 8 + } +} + +/// Full IDs when piped or when TITLE still gets [`MIN_TITLE`] cells. +const WIDE: Columns = Columns { + id: 36, + agent: 16, + status: 16, + age: 6, +}; +/// Short IDs, as in the `nori attach` list. +const COMPACT: Columns = Columns { + id: 8, + agent: 14, + status: 16, + age: 5, +}; +/// The narrowest layout; `waiting on you` and ages such as `59m` still fit. +const TIGHT: Columns = Columns { + id: 8, + agent: 10, + status: 14, + age: 4, +}; +const MIN_TITLE: usize = 24; + +fn columns_for(width: Option) -> Columns { + let Some(width) = width else { + return WIDE; + }; + [WIDE, COMPACT] + .into_iter() + .find(|columns| width >= columns.prefix() + MIN_TITLE) + .unwrap_or(TIGHT) +} + pub(super) fn format_table(listing: &Value, width: Option, color: bool) -> String { + let columns = columns_for(width); + let Columns { + id: id_cells, + agent: agent_cells, + status: status_cells, + age: age_cells, + } = columns; let header = format!( - "{:<36} {:<16} {:<16} {:>6} TITLE", + "{:age_cells$} TITLE", "ID", "AGENT", "STATUS", "AGE" ); let mut output = format!( "{}\n", width.map_or_else(|| header.clone(), |width| truncate(&header, width)) ); - for row in listing["sessions"].as_array().into_iter().flatten() { + let rows: Vec<&Value> = listing["sessions"] + .as_array() + .into_iter() + .flatten() + .collect(); + let links: Vec<(&str, Option<&str>)> = rows + .iter() + .map(|row| { + ( + row["session_id"].as_str().unwrap_or("-"), + row["parent"].as_str(), + ) + }) + .collect(); + let order = nori_tui_components::picker::tree_order(&links); + let depths: Vec = order.iter().map(|(_, depth)| *depth).collect(); + let guides = nori_tui_components::picker::tree_guides(&depths); + for ((index, depth), (guide, _)) in order.into_iter().zip(guides) { + let row = rows[index]; let clean = |key: &str| { row[key] .as_str() @@ -25,19 +103,18 @@ pub(super) fn format_table(listing: &Value, width: Option, color: bool) - }; let id = clean("session_id"); let agent = clean("agent"); - let status = clean("status").replace('_', " "); - let title = clean("title"); - let title = match row["parent"].as_str() { - Some(_) if row["source"] == "session" => { - let parent = clean("parent"); - let parent = if width.is_some() { - parent.chars().take(8).collect::() - } else { - parent - }; - format!("↳ (parent {parent}) {title}") - } - _ => title, + // A top-level session speaks for its family: its row shows the + // status of the member that most needs the user. + let status_key = row["family_status"] + .as_str() + .filter(|_| depth == 0) + .unwrap_or_else(|| row["status"].as_str().unwrap_or("-")); + let status = status_key.replace('_', " "); + let name = clean("title"); + let title = if row["parent"].is_string() && width.is_none() { + format!("{guide}{name} (parent {})", clean("parent")) + } else { + format!("{guide}{name}") }; let seconds = row["age_seconds"].as_i64().unwrap_or(0).max(0); let age = if seconds < 60 { @@ -47,33 +124,56 @@ pub(super) fn format_table(listing: &Value, width: Option, color: bool) - } else { format!("{}h", seconds / 3600) }; - let prefix = format!("{id:<36} {agent:<16} {status:<16} {age:>6} "); + let (id, agent, status) = if width.is_some() { + ( + id.chars().take(id_cells).collect(), + truncate(&agent, agent_cells), + truncate(&status, status_cells), + ) + } else { + (id, agent, status) + }; + let prefix = format!( + "{id:age_cells$} " + ); let prefix_width = prefix.width(); - if let Some(width) = width - && width < prefix_width - { - output.push_str(&truncate(&prefix, width)); - output.push('\n'); - continue; - } + // The tree guide stays whole; the name is cut in the middle so titles + // that share a long prefix still read apart. let title = width.map_or_else( || title.clone(), - |width| truncate(&title, width.saturating_sub(prefix_width)), + |width| { + let room = width.saturating_sub(prefix_width); + if room > guide.width() { + format!("{guide}{}", truncate_middle(&name, room - guide.width())) + } else { + truncate(&title, room) + } + }, ); - let status = format!("{status:<16}"); + let status = format!("{status: status.red().to_string(), - "waiting_on_you" | "working" | "starting" => status.yellow().to_string(), + "waiting_on_you" => status.yellow().to_string(), + "working" => status.cyan().to_string(), "ready" => status.green().to_string(), + // A child that finished its task reads apart from one the + // user closed. + "done" => status, _ => status.dimmed().to_string(), } } else { status }; - output.push_str(&format!( - "{id:<36} {agent:<16} {status} {age:>6} {title}\n" - )); + let line = match width { + // Below the tight layout, metadata alone overflows: clip plainly. + Some(width) if width < prefix_width => truncate(&prefix, width), + _ => format!( + "{id:age_cells$} {title}" + ), + }; + output.push_str(line.trim_end()); + output.push('\n'); } output } @@ -96,14 +196,82 @@ fn truncate(value: &str, width: usize) -> String { format!("{}…", &value[..end]) } +/// `value` in at most `width` cells, cut in the middle with `…` on grapheme +/// boundaries. +fn truncate_middle(value: &str, width: usize) -> String { + if value.width() <= width { + return value.into(); + } + if width == 0 { + return String::new(); + } + let room = width - 1; + let graphemes: Vec<&str> = value.graphemes(true).collect(); + let mut head = String::new(); + for grapheme in &graphemes { + if head.width() + grapheme.width() > room.div_ceil(2) { + break; + } + head.push_str(grapheme); + } + let mut tail: Vec<&str> = Vec::new(); + for grapheme in graphemes.iter().rev() { + if head.width() + tail.concat().width() + grapheme.width() > room { + break; + } + tail.push(grapheme); + } + tail.reverse(); + format!("{}…{}", head.trim_end(), tail.concat().trim_start()) +} + #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; use serde_json::json; + /// The display column where `name` starts in the header row. + fn column(rendered: &str, name: &str) -> usize { + let header = rendered.lines().next().unwrap_or_default(); + let padded = format!(" {header} "); + let at = padded + .find(&format!(" {name} ")) + .unwrap_or_else(|| panic!("{name} column in {rendered}")); + padded[..at].width() + } + + /// The text of `row` from display column `from` on. + fn from_column(row: &str, from: usize) -> &str { + let mut cells = 0; + for (index, ch) in row.char_indices() { + if cells >= from { + return &row[index..]; + } + cells += unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0); + } + "" + } + + fn strip_ansi(text: &str) -> String { + let mut plain = String::new(); + let mut chars = text.chars(); + while let Some(ch) = chars.next() { + if ch == '\u{1b}' { + for code in chars.by_ref() { + if code == 'm' { + break; + } + } + } else { + plain.push(ch); + } + } + plain + } + #[test] - fn tty_titles_respect_display_columns_and_keep_graphemes_intact() { + fn titles_are_cut_by_display_columns_and_keep_graphemes_intact() { for (title, budget, expected) in [ ("abcdef", 4, "abc…"), ("abcd", 4, "abcd"), @@ -113,18 +281,114 @@ mod tests { ("abcdef", 1, "…"), ("abcdef", 0, ""), ] { - let listing = json!({"sessions":[{"session_id":"id", "agent":"agent", "status":"ready", "title":title}]}); - let rendered = format_table(&listing, Some(82 + budget), false); - let row = rendered.lines().nth(1).unwrap(); - assert_eq!(row.get(82..).unwrap_or(""), expected, "title {title}"); + assert_eq!(truncate(title, budget), expected, "title {title}"); } } #[test] - fn tty_title_budget_accounts_for_expanded_metadata_columns() { - let listing = json!({"sessions":[{"session_id":"id", "agent":"abcdefghijklmnopqrst", "status":"ready", "title":"long title"}]}); - let rendered = format_table(&listing, Some(90), false); - assert!(rendered.lines().nth(1).unwrap().ends_with("lon…")); + fn a_long_agent_name_is_cut_so_later_columns_stay_put() { + let listing = json!({"sessions":[ + {"session_id":"11111111-1111-1111-1111-111111111111","agent":"reviewer-long-agent-name-x","status":"ready","title":"Review the parser"}, + {"session_id":"22222222-2222-2222-2222-222222222222","agent":"mock-model","status":"ready","title":"Spike transport"} + ]}); + for width in [120, 80] { + let rendered = format_table(&listing, Some(width), false); + let status = column(&rendered, "STATUS"); + let title = column(&rendered, "TITLE"); + let rows = rendered.lines().skip(1).collect::>(); + assert!(rows[0].contains("reviewer-long"), "{rendered}"); + assert!(rows[0].contains('…'), "the agent is cut: {rendered}"); + assert!( + !rows[0].contains("reviewer-long-agent-name-x"), + "{rendered}" + ); + for row in &rows { + assert!(from_column(row, status).starts_with("ready "), "{rendered}"); + } + assert_eq!( + from_column(rows[0], title), + "Review the parser", + "{rendered}" + ); + assert_eq!(from_column(rows[1], title), "Spike transport", "{rendered}"); + } + let piped = format_table(&listing, None, false); + assert!(piped.contains("reviewer-long-agent-name-x"), "{piped}"); + } + + #[test] + fn an_80_column_terminal_keeps_titles_tree_glyphs_ages_and_colors() { + let root = "11111111-1111-1111-1111-111111111111"; + let child = "22222222-2222-2222-2222-222222222222"; + let grandchild = "44444444-4444-4444-4444-444444444444"; + let listing = json!({"sessions":[ + {"session_id":root,"agent":"mock-model","status":"ready","family_status":"waiting_on_you","title":"Ship tree picker","age_seconds":754}, + {"session_id":child,"agent":"mock-model-alt","status":"ready","title":"Port picker","parent":root,"source":"session","depth":1,"age_seconds":75}, + {"session_id":grandchild,"agent":"mock-model","status":"waiting_on_you","title":"Write snapshot tests","parent":child,"source":"session","depth":2,"age_seconds":7} + ]}); + let colored = format_table(&listing, Some(80), true); + let plain = strip_ansi(&colored); + assert!(plain.lines().all(|line| line.width() <= 80), "{plain}"); + let title = column(&plain, "TITLE"); + let age = column(&plain, "AGE"); + let rows = plain.lines().skip(1).collect::>(); + assert_eq!( + rows.iter() + .map(|row| from_column(row, title)) + .collect::>(), + [ + "Ship tree picker", + "└─ Port picker", + " └─ Write snapshot tests" + ], + "{plain}" + ); + assert_eq!( + rows.iter() + .map(|row| from_column(row, age) + .split_whitespace() + .next() + .unwrap_or_default()) + .collect::>(), + ["12m", "1m", "7s"], + "AGE is never cut: {plain}" + ); + assert!( + rows[0].starts_with("11111111 "), + "IDs shorten to fit: {plain}" + ); + let root_row = colored.lines().nth(1).unwrap_or_default(); + assert!( + root_row.contains("\u{1b}[33mwaiting on you"), + "the top-level row takes its family's color: {colored:?}" + ); + } + + #[test] + fn a_top_level_session_shows_when_anything_below_it_waits_on_you() { + let root = "11111111-1111-1111-1111-111111111111"; + let listing = json!({"sessions":[ + {"session_id":root,"agent":"mock-model","status":"ready","family_status":"waiting_on_you","title":"Ship tree picker"}, + {"session_id":"22222222-2222-2222-2222-222222222222","agent":"mock-model","status":"working","family_status":"waiting_on_you","title":"Port picker","parent":root,"source":"session","depth":1}, + {"session_id":"33333333-3333-3333-3333-333333333333","agent":"mock-model","status":"ready","family_status":"ready","title":"Spike transport"} + ]}); + for width in [Some(120), None] { + let rendered = format_table(&listing, width, false); + let status = column(&rendered, "STATUS"); + let rows = rendered.lines().skip(1).collect::>(); + assert!( + from_column(rows[0], status).starts_with("waiting on you"), + "{rendered}" + ); + assert!( + from_column(rows[1], status).starts_with("working "), + "{rendered}" + ); + assert!( + from_column(rows[2], status).starts_with("ready "), + "{rendered}" + ); + } } #[test] @@ -137,30 +401,153 @@ mod tests { } #[test] - fn delegated_child_identity_stays_inside_title_column() { - let parent = "11111111-1111-1111-1111-111111111111"; + fn children_print_under_their_parent_with_tree_glyphs_inside_title() { + let root = "11111111-1111-1111-1111-111111111111"; + let other = "33333333-3333-3333-3333-333333333333"; let child = "22222222-2222-2222-2222-222222222222"; + let grandchild = "44444444-4444-4444-4444-444444444444"; + let sibling = "55555555-5555-5555-5555-555555555555"; let listing = json!({"sessions":[ - {"session_id":parent,"agent":"mock-model","status":"ready","title":"Parent"}, - {"session_id":child,"agent":"mock-model-alt","status":"waiting_on_you","title":"Child task","parent":parent,"source":"session","depth":1} + {"session_id":root,"agent":"mock-model","status":"working","title":"Ship tree picker"}, + {"session_id":other,"agent":"mock-model","status":"ready","title":"Spike transport"}, + {"session_id":child,"agent":"mock-model-alt","status":"waiting_on_you","title":"Port picker","parent":root,"source":"session","depth":1}, + {"session_id":grandchild,"agent":"mock-model","status":"failed","title":"Write snapshot tests","parent":child,"source":"session","depth":2}, + {"session_id":sibling,"agent":"mock-model","status":"ready","title":"Update docs","parent":root,"source":"session","depth":1} ]}); + let tty = format_table(&listing, Some(120), false); + let (agent_at, status_at, title_at) = ( + column(&tty, "AGENT"), + column(&tty, "STATUS"), + column(&tty, "TITLE"), + ); + let rows = tty.lines().skip(1).collect::>(); + assert_eq!( + rows.iter().map(|row| &row[..8]).collect::>(), + ["11111111", "22222222", "44444444", "55555555", "33333333"], + "children follow their parent: {tty}" + ); + assert_eq!( + rows.iter() + .map(|row| from_column(row, title_at)) + .collect::>(), + [ + "Ship tree picker", + "├─ Port picker", + "│ └─ Write snapshot tests", + "└─ Update docs", + "Spike transport", + ], + "{tty}" + ); + assert!(from_column(rows[2], agent_at).starts_with("mock-model ")); + assert!(from_column(rows[1], status_at).starts_with("waiting on you ")); + let narrow = format_table(&listing, Some(92), false); + assert!(narrow.lines().all(|line| line.width() <= 92), "{narrow}"); + let narrow_title = column(&narrow, "TITLE"); + assert!( + from_column(narrow.lines().nth(3).unwrap(), narrow_title).starts_with("│ └─ "), + "glyphs survive truncation: {narrow}" + ); let piped = format_table(&listing, None, false); - let rows = piped.lines().collect::>(); - assert_eq!(&rows[2][..36], child); - assert_eq!(&rows[2][38..54], "mock-model-alt "); - assert_eq!(&rows[2][56..72], "waiting on you "); - let title = &rows[2][82..]; - assert!(title.contains("Child task")); + let child_row = piped.lines().nth(2).unwrap(); + assert_eq!(&child_row[..36], child); + let orphan = json!({"sessions":[ + {"session_id":child,"agent":"m","status":"ready","title":"Port picker","parent":root,"source":"session"} + ]}); assert!( - title.contains(parent), - "child row must identify its parent: {title}" + format_table(&orphan, None, false).contains(root), + "a child whose parent is gone still names it when piped" ); - let tty = format_table(&listing, Some(110), false); - assert!(tty.lines().all(|line| line.width() <= 110)); assert!( - tty.lines().nth(2).unwrap()[82..].contains("parent 11111111"), - "normal terminal width must retain parent identity" + from_column(child_row, column(&piped, "TITLE")).starts_with("├─ Port picker") + && child_row.contains(root), + "piped output keeps the complete parent ID: {child_row}" ); - assert_eq!(&tty.lines().nth(2).unwrap()[..82], &rows[2][..82]); + } + + #[test] + fn status_words_are_colored_by_what_the_session_needs() { + let listing = json!({"sessions":[ + {"session_id":"a","agent":"m","status":"waiting_on_you","title":"a"}, + {"session_id":"b","agent":"m","status":"working","title":"b"}, + {"session_id":"c","agent":"m","status":"ready","title":"c"}, + {"session_id":"d","agent":"m","status":"failed","title":"d"} + ]}); + let colored = format_table(&listing, Some(120), true); + let rows = colored.lines().skip(1).collect::>(); + let codes_before = |row: &str, word: &str| { + let at = row + .find(word) + .unwrap_or_else(|| panic!("{word} in {row:?}")); + let start = row[..at].rfind("\u{1b}[").expect("styled word"); + row[start + 2..at] + .trim_end_matches('m') + .split(';') + .map(str::to_owned) + .collect::>() + }; + for (row, word, code) in [ + (rows[0], "waiting on you", "33"), + (rows[1], "working", "36"), + (rows[2], "ready", "32"), + (rows[3], "failed", "31"), + ] { + assert!( + codes_before(row, word).iter().any(|c| c == code), + "{word} uses color {code}: {colored:?}" + ); + } + } + + #[test] + fn done_reads_apart_from_closed_which_stays_dim() { + let listing = json!({"sessions":[ + {"session_id":"a","agent":"m","status":"done","title":"a"}, + {"session_id":"b","agent":"m","status":"closed","title":"b"} + ]}); + let colored = format_table(&listing, Some(120), true); + let rows = colored.lines().skip(1).collect::>(); + assert!(rows[0].contains("done"), "{colored:?}"); + assert!( + !rows[0].contains("\u{1b}[2mdone"), + "done is not dimmed: {colored:?}" + ); + assert!( + rows[1].contains("\u{1b}[2mclosed"), + "closed stays dim: {colored:?}" + ); + } + + #[test] + fn titles_sharing_a_long_prefix_keep_their_ends() { + let listing = json!({"sessions":[ + {"session_id":"11111111-1111-1111-1111-111111111111","agent":"mock-model","status":"ready", + "title":"shared prefix for the parser review: parent side and a long tail of words"}, + {"session_id":"22222222-2222-2222-2222-222222222222","agent":"mock-model","status":"ready", + "title":"shared prefix for the parser review: child side and a long tail of words z"} + ]}); + let rendered = format_table(&listing, Some(80), false); + let rows = rendered.lines().skip(1).collect::>(); + assert!(rows[0].starts_with("11111111"), "{rendered}"); + assert!(rows[0].trim_end().ends_with("of words"), "{rendered}"); + assert!(rows[1].trim_end().ends_with("of words z"), "{rendered}"); + for row in &rows { + assert!(row.width() <= 80, "{rendered}"); + assert!(row.contains("shared pre"), "{rendered}"); + } + } + + #[test] + fn rows_stay_within_a_very_narrow_terminal() { + let listing = json!({"sessions":[ + {"session_id":"11111111-1111-1111-1111-111111111111","agent":"mock-model","status":"waiting_on_you","title":"Ship tree picker","age_seconds":754} + ]}); + for width in [20, 40, 50] { + let rendered = strip_ansi(&format_table(&listing, Some(width), true)); + assert!( + rendered.lines().all(|line| line.width() <= width), + "@{width}: {rendered}" + ); + } } } diff --git a/nori-rs/config.md b/nori-rs/config.md index fd218d8d2..32be70b4b 100644 --- a/nori-rs/config.md +++ b/nori-rs/config.md @@ -99,6 +99,7 @@ previous_session = "alt+," next_session = "alt+." next_waiting_session = "alt+down" open_session_list = "alt+s" +parent_session = "alt+up" ``` Off by default; restart Nori after changing it. With it on, `/new`, `/resume`, @@ -116,34 +117,50 @@ another session and say how to close one. | Way in | What it does | | --- | --- | | `previous_session` / `next_session` | Move through sessions in the order they were opened, wrapping at the ends | -| `next_waiting_session` | With an empty prompt, jump to the next session waiting on you | +| `next_waiting_session` | Jump to the next session waiting on you; a draft stays in its own session's prompt. With nothing waiting, the key goes to a non-empty prompt | | Left on an empty prompt, `open_session_list`, or `/sessions` | Open the session list | +| `parent_session` | From a delegated child, return to the session that delegated it; elsewhere it does nothing | The `[tui.hotkeys]` values above are the defaults, and the actions appear in the Hotkeys view only with the feature on. Moving between sessions skips -closed ones. In the session list, Tab shows only sessions waiting on you (Tab +closed and done ones. In the session list, Tab shows only sessions waiting on you (Tab again shows all), typing filters by title or agent, Enter jumps, Esc clears the filter and then closes, and Ctrl+R restarts a failed session from its transcript in the same place, keeping its title. A session is titled by the -agent's summary, else its first message. +agent's summary, else its first message, else the task of a `/delegate` sent +first; a delegation result never titles a session. Rows show the agent slug +that `/delegate` takes. Closing a session: | Way | What it does | | --- | --- | | Ctrl+D in the session list | Closes the selected session and stops its agent. A working, starting, or waiting session needs a second Ctrl+D; any other key cancels | -| Ctrl+D on a `closed` row | Removes it from the list | +| Ctrl+D on a `closed` or `done` row | Removes it from the list | | `/close` | Closes the session on screen (local sessions); in Nori Cloud it releases the session | -A closed session stays in the list as `closed` until you remove it. Closing +A closed session stays in the list as `closed` until you remove it; a +delegated child whose task finished stays as `done`. Closing the session on screen shows the next open one. The last open session cannot be closed this way; use `/quit`. A status line above the prompt counts open sessions by status (starting, working, waiting on you, ready, failed) once two or more are open, a separate -line names a background session that is waiting on you, and a temporary -"Preparing …" line shows while `/agent` starts a new agent. A blank -session that never started is not counted or listed. +line names a background session that is waiting on you (for a delegated child, +as ` › `), and a temporary "Preparing …" line shows while +`/agent` starts a new agent. Inside a delegated child, a breadcrumb line shows +the path from the top-level session down to it and the `parent_session` key. +These lines fit the terminal width, shortening names before dropping them. In +the session list, status words are colored: waiting on you amber, working +cyan, ready green, failed red; starting, closed, and done are muted. A blank session that never started is not counted or listed. + +`/delegate ` (or the agent's own `delegate` tool) starts a +delegated child session, named after the first line of its task. In the +parent it reads as one line (`↳ you delegated to · · working`); +the full brief and result are in the transcript view (Ctrl+T). When the child +ends, a short result block names it and shows up to six result lines, and the +result goes back to the parent agent on its own. A child on a different agent +asks first ("Yes, start it" / "No, decline"; Esc declines). Remote control (`--remote`, `/remote-control`) serves the most recently started session, which is not necessarily the one on screen. diff --git a/nori-rs/harness/docs.md b/nori-rs/harness/docs.md index c5453a25d..406cb932e 100644 --- a/nori-rs/harness/docs.md +++ b/nori-rs/harness/docs.md @@ -373,7 +373,8 @@ not keep a process-global host or own listener policy. [`ManagedRemoteHost`](src/managed_remote.rs) shares one command boundary between the WebSocket `/sessions` adapter and managed ACP stdio. It lists -manager records and journal cursors, resolves explicit conversation IDs before +manager records and journal cursors (each row also carries `family_status`, +the record's `SessionManager::family_status`, else its own status), resolves explicit conversation IDs before using the frontend's selected default, and opens one-session or all-session subscriptions. Its `_nori/session/event` notifications retain the complete manager envelope, including Nori events; legacy ACP projection stays separate. @@ -678,6 +679,17 @@ processes. | `Ready` | Idle | | `Failed` | `SessionEnded` with `ConnectionLost`, `SpawnFailed`, or `TimedOut`, or the stream closed with no end event | | `Closed` | `SessionEnded` with `Shutdown` or `Closed`, or superseded by a fork | + | `Done` | A delegated child's `SessionEnded(Closed)` after its task completed | + + The [delegation driver](src/session_manager/delegation_driver.rs) marks a + child's registry entry task-done (`Registry::mark_task_done`) when its + delegation reaches `Completed`, before closing the child; the entry then + records that close as `Done`. Every other end keeps its ordinary status. + `Done`, like the parent link and the rest of the registry, lives only in + the in-memory manager; the host keeps no snapshot of it. After a host + restart a finished child is not listed at all (`nori host ls` and the + `nori attach` list omit it), and reopening its transcript with `/resume` + starts it as a live top-level `ready` session with no parent link. A pending request clears when any `HarnessHandle` clone answers it, when the phase returns to `Idle` or enters `Cancelling`, or when the session ends. @@ -701,7 +713,8 @@ processes. client following a session learns the request no longer waits on the user. - **Families.** A session family is a top-level session plus all of its descendants. `family_status` rolls member statuses up with priority - `WaitingOnYou` > `Failed` > `Working` > `Starting` > `Ready` > `Closed`. + `WaitingOnYou` > `Failed` > `Working` > `Starting` > `Ready` > `Closed` / + `Done` (equal rank). - **Fork.** On `NoriEvent::SessionForked` (branch at head) the parent becomes `Closed` and a child record (source `Fork`, parent = previous conversation) takes over the same agent process and capacity slot. `SessionForked` is @@ -769,7 +782,7 @@ is unchanged. parent agent -- HTTP MCP delegate --+ local /delegate -------------------+--> SessionManager remote /session/delegate ----------+ | - different agent? -> Start / Decline + different agent? -> approve / decline | child ACP process | @@ -780,7 +793,7 @@ remote /session/delegate ----------+ | - Delegation records reserve a child conversation identity before approval. Same-kind children start immediately; different-kind children stay - `awaiting_approval` until Start or Decline. Approval is scoped to the + `awaiting_approval` until the user approves or declines. Approval is scoped to the requesting parent and request ID. Spawn admission uses the manager's shared session cap, including children, and is checked when a child actually starts. - Depth counts delegation edges, separately from fork ancestry. A top-level @@ -792,15 +805,36 @@ remote /session/delegate ----------+ | stable. [State reduction](src/session_manager/delegation_state.rs) republishes the changed attribution for observers. - `DelegationChanged` carries request, parent, and child identities, agent - names, task, depth, status, and optional result. Manager envelopes make those + names, task, depth, status, optional result, and origin. The MCP tool path + passes the calling process as its expected process and records origin + `agent`; the public `SessionManager::delegate` (local and remote `/delegate`) + records `user`. Frontends use origin only to word who asked. Manager envelopes make those changes observable through ordinary subscriptions and reconnect replay, including events published while a failed parent has no process. Child-start approval contributes to the parent's `WaitingOnYou` status separately from its ACP permission request IDs. ACP permission requests remain owned by the child conversation; permission - responses must target that child, not its parent. + responses must target that child, not its parent. When a child sends an ACP + permission request, [state reduction](src/session_manager/delegation_state.rs) + emits a `Notice` into the parent: + ` · is waiting on you (delegated by · ). Press Alt+Down to answer it.` + The child name comes from `nori_protocol::delegation_child_name`; the parent + name is the parent's replay-journal title through + `nori_protocol::session_display_name` (40 characters, cut in the middle), + else `this session`. - A child's final output or failure becomes an attributed prompt queued into - its parent automatically, without a review step. A busy parent consumes it + its parent automatically, without a review step. Its text is + `nori_protocol::delegation_result_prompt`: a readable first line naming the + child agent, the child's whole first task line, and outcome, then the child ID, then the result. + It does not repeat the parent's own ID. The result is the text of the + child's agent message chunks from its last prompting turn; when a tool call, + permission request, or other session update arrived between chunks, the next + chunk starts a new paragraph (`\n\n`) rather than being joined directly. A + child that crashed reports only the first non-empty line of its + `RequestFailed` message (for example `Agent process exited unexpectedly + (exit code 17).`); the agent's stderr tail stays in the child's own history. + Frontends recognize these prompts through + `nori_protocol::delegation_result_summary`. A busy parent consumes it through its normal prompt queue. The [result driver](src/session_manager/delegation_driver.rs) retains that delivery until the parent's correlated ACP `PromptResponse`, not merely queue admission. If the process crashes first, stable-ID resume @@ -809,6 +843,13 @@ remote /session/delegate ----------+ | turns before returning its own final result. Terminal completion stops the child process and releases its capacity slot while retaining the registry record and transcript. +- A result prompt never titles the parent that receives it. The + [replay journal](src/session_manager/replay.rs) skips user-message chunks + that are result prompts when it derives a title, and titles a still-untitled + parent from the task of a user-origin `DelegationChanged` it requested, so a + session whose first input is `/delegate` is named by that task. The + first-prompt summary hook in [user input](src/backend/user_input.rs) likewise + ignores result prompts, leaving the summary for the user's own first prompt. - Explicit parent close cancels descendants and invalidates pending delegation approvals, including when the parent has already failed. A parent process crash leaves children running; results wait for the parent's stable-ID diff --git a/nori-rs/harness/src/backend/user_input.rs b/nori-rs/harness/src/backend/user_input.rs index 4053c77b4..806f1f878 100644 --- a/nori-rs/harness/src/backend/user_input.rs +++ b/nori-rs/harness/src/backend/user_input.rs @@ -73,7 +73,8 @@ impl AcpBackend { // produce meaningful summaries. { let mut is_first = self.is_first_prompt.lock().await; - if *is_first { + // A child's result is not the user's own first prompt. + if *is_first && nori_protocol::delegation_result_summary(&display_text).is_none() { *is_first = false; let skip_summary = cfg!(debug_assertions) && self.agent_name.starts_with("mock-"); if !skip_summary && (self.prompt_summary_enabled || self.auto_worktree.is_enabled()) diff --git a/nori-rs/harness/src/managed_remote.rs b/nori-rs/harness/src/managed_remote.rs index 63c575fba..9711aaf3a 100644 --- a/nori-rs/harness/src/managed_remote.rs +++ b/nori-rs/harness/src/managed_remote.rs @@ -138,6 +138,7 @@ impl ManagedRemoteHost { "session_id":record.conversation_id.to_string(), "agent":record.agent, "status":record.status, + "family_status":self.manager.family_status(&record.conversation_id).unwrap_or(record.status), "cwd":record.cwd, "parent":record.parent.map(|id| id.to_string()), "pending_requests":record.pending_requests, diff --git a/nori-rs/harness/src/session_manager/delegation.rs b/nori-rs/harness/src/session_manager/delegation.rs index 9f67e6466..b5dd9310b 100644 --- a/nori-rs/harness/src/session_manager/delegation.rs +++ b/nori-rs/harness/src/session_manager/delegation.rs @@ -60,7 +60,8 @@ impl DelegationContext { } impl SessionManager { - /// Request a child session. A different agent kind waits for user approval. + /// Request a child session for the user. A different agent kind waits for + /// user approval. pub async fn delegate( &self, parent: &ConversationId, @@ -143,6 +144,11 @@ impl SessionManager { status, depth, result: None, + origin: if expected_process.is_some() { + nori_protocol::DelegationOrigin::Agent + } else { + nori_protocol::DelegationOrigin::User + }, }; state.delegation.entries.push(Entry { value: value.clone(), @@ -151,6 +157,7 @@ impl SessionManager { pending_turns: HashSet::new(), completed_turns: HashSet::new(), output: String::new(), + output_break: false, last_result: String::new(), failure: None, cancelled: false, diff --git a/nori-rs/harness/src/session_manager/delegation_driver.rs b/nori-rs/harness/src/session_manager/delegation_driver.rs index 711a72796..36d43476b 100644 --- a/nori-rs/harness/src/session_manager/delegation_driver.rs +++ b/nori-rs/harness/src/session_manager/delegation_driver.rs @@ -69,8 +69,12 @@ pub(super) fn wake(shared: &Arc) { } else { entry.last_result.clone() }); + let completed = entry.value.status == DelegationStatus::Completed; changed.push(entry.value.clone()); finished.push(child); + if completed { + state.registry.mark_task_done(&child); + } } for value in changed { state.publish_delegation(&value); diff --git a/nori-rs/harness/src/session_manager/delegation_state.rs b/nori-rs/harness/src/session_manager/delegation_state.rs index c5cef2aa3..56fca5445 100644 --- a/nori-rs/harness/src/session_manager/delegation_state.rs +++ b/nori-rs/harness/src/session_manager/delegation_state.rs @@ -15,6 +15,9 @@ pub(super) struct Entry { pub(super) pending_turns: HashSet, pub(super) completed_turns: HashSet, pub(super) output: String, + /// Something other than message text happened since the last chunk, so + /// the next chunk starts a new paragraph of the result. + pub(super) output_break: bool, pub(super) last_result: String, pub(super) failure: Option, pub(super) cancelled: bool, @@ -91,16 +94,25 @@ impl DelegationState { match &envelope.event { SessionEvent::Nori(NoriEvent::SessionPhaseChanged(SessionPhase::Prompting { .. - })) => entry.output.clear(), + })) => { + entry.output.clear(); + entry.output_break = false; + } SessionEvent::Acp(AcpEvent::Notification( acp::v1::AgentNotification::SessionNotification(n), )) => { if let acp::v1::SessionUpdate::AgentMessageChunk(chunk) = &n.update && let acp::v1::ContentBlock::Text(text) = &chunk.content { + if std::mem::take(&mut entry.output_break) && !entry.output.is_empty() { + entry.output.push_str("\n\n"); + } entry.output.push_str(&text.text); + } else { + entry.output_break = true; } } + SessionEvent::Acp(AcpEvent::Request { .. }) => entry.output_break = true, SessionEvent::Acp(AcpEvent::Response { request_id, response, @@ -183,10 +195,18 @@ impl State { let Ok(parent) = ConversationId::from_string(&value.parent_id) else { return; }; + let parent_name = self + .journal + .info(&value.parent_id) + .and_then(|info| info.title) + .and_then(|title| nori_protocol::session_display_name(&title)) + .unwrap_or_else(|| "this session".to_owned()); let event = SessionEvent::Nori(NoriEvent::Notice(nori_protocol::Notice { message: format!( - "Child session {} ({}) of parent session {} ({}) needs your answer. Switch to the child with Alt+Down.", - value.child_id, value.agent, value.parent_id, value.parent_agent + "{} · {} is waiting on you (delegated by {} · {parent_name}). Press Alt+Down to answer it.", + value.agent, + nori_protocol::delegation_child_name(&value), + value.parent_agent, ), })); if let Some(envelope) = self.registry.emit(&parent, event) { @@ -219,10 +239,13 @@ impl State { if self.delegation.closed.contains(&parent) { return; } - let result = value.result.as_deref().unwrap_or(""); self.delegation.deliveries.push_back(Delivery { - request: value.request_id.clone(), parent, in_flight: false, submitted: None, process: None, - text: format!("[Nori delegation result]\nChild session {} ({}) for parent session {} ({}): {:?}\n{}", value.child_id, value.agent, value.parent_id, value.parent_agent, value.status, result), + request: value.request_id.clone(), + parent, + in_flight: false, + submitted: None, + process: None, + text: nori_protocol::delegation_result_prompt(value), }); } diff --git a/nori-rs/harness/src/session_manager/registry.rs b/nori-rs/harness/src/session_manager/registry.rs index 229cdb626..a849d8453 100644 --- a/nori-rs/harness/src/session_manager/registry.rs +++ b/nori-rs/harness/src/session_manager/registry.rs @@ -70,6 +70,8 @@ struct Entry { /// read a request from the harness directly, ahead of this registry. early_answers: Vec, ended: Option, + /// A delegated child whose task finished; closing it reads as done. + task_done: bool, /// The child that took over this session's agent process in a fork. forked_into: Option, transcript_path: Option, @@ -90,6 +92,7 @@ impl Entry { delegation_approvals: std::collections::HashSet::new(), early_answers: Vec::new(), ended: None, + task_done: false, forked_into: None, transcript_path: None, acp_session_id: None, @@ -112,7 +115,10 @@ impl Entry { fn end(&mut self, status: SessionStatus) { if self.ended.is_none() { - self.ended = Some(status); + self.ended = Some(match status { + SessionStatus::Closed if self.task_done => SessionStatus::Done, + other => other, + }); } self.process = None; self.reservation = None; @@ -465,6 +471,14 @@ impl Registry { } } + /// Mark a delegated child whose task finished, so closing it reads as + /// done rather than closed. + pub(crate) fn mark_task_done(&mut self, conversation_id: &ConversationId) { + if let Some(entry) = self.sessions.get_mut(conversation_id) { + entry.task_done = true; + } + } + /// The live agent process of a session, if it still has one. pub(crate) fn live_process(&self, conversation_id: &ConversationId) -> Option { self.sessions.get(conversation_id)?.process @@ -535,7 +549,7 @@ impl Registry { SessionStatus::Working => 2, SessionStatus::Starting => 3, SessionStatus::Ready => 4, - SessionStatus::Closed => 5, + SessionStatus::Closed | SessionStatus::Done => 5, }) } } diff --git a/nori-rs/harness/src/session_manager/replay.rs b/nori-rs/harness/src/session_manager/replay.rs index 467fdaadc..cac81bf20 100644 --- a/nori-rs/harness/src/session_manager/replay.rs +++ b/nori-rs/harness/src/session_manager/replay.rs @@ -96,6 +96,14 @@ impl Journal { SessionEvent::Nori(NoriEvent::PromptSummaryUpdated(summary)) => { history.title = Some(summary.summary.clone()) } + // A session whose first input is `/delegate` is named by that task. + SessionEvent::Nori(NoriEvent::DelegationChanged(delegation)) + if history.title.is_none() + && delegation.origin == nori_protocol::DelegationOrigin::User + && delegation.parent_id == envelope.conversation_id => + { + history.title = Some(title_line(&delegation.task)); + } SessionEvent::Acp(AcpEvent::Notification( acp::AgentNotification::SessionNotification(notification), )) => match ¬ification.update { @@ -105,16 +113,10 @@ impl Journal { } } acp::SessionUpdate::UserMessageChunk(chunk) if history.title.is_none() => { - if let acp::ContentBlock::Text(text) = &chunk.content { - history.title = Some( - text.text - .lines() - .next() - .unwrap_or_default() - .chars() - .take(120) - .collect(), - ); + if let acp::ContentBlock::Text(text) = &chunk.content + && nori_protocol::delegation_result_summary(&text.text).is_none() + { + history.title = Some(title_line(&text.text)); } } _ => {} @@ -221,3 +223,13 @@ impl Journal { Ok(ManagedSubscription { replay, events }) } } + +/// The title a session gets from text the user gave it: its first line. +fn title_line(text: &str) -> String { + text.lines() + .next() + .unwrap_or_default() + .chars() + .take(120) + .collect() +} diff --git a/nori-rs/harness/tests/delegation.rs b/nori-rs/harness/tests/delegation.rs index 248e242a4..a85615884 100644 --- a/nori-rs/harness/tests/delegation.rs +++ b/nori-rs/harness/tests/delegation.rs @@ -156,7 +156,7 @@ async fn same_kind_starts_immediately_and_retains_child_history_after_releasing_ let done = terminal(&m, &p.conversation_id, &d.request_id).await; assert_eq!(done.status, DelegationStatus::Completed); assert!(done.result.is_some()); - status(&m, &id(&d), SessionStatus::Closed).await; + status(&m, &id(&d), SessionStatus::Done).await; assert_eq!(m.free_slots(), 1); let child = m.get(&id(&d)).unwrap(); assert_eq!(child.parent, Some(p.conversation_id)); @@ -166,6 +166,110 @@ async fn same_kind_starts_immediately_and_retains_child_history_after_releasing_ } #[tokio::test] #[serial] +async fn a_declined_delegation_reaches_the_parent_agent_without_a_session_id() { + let _echo = Env::set("MOCK_AGENT_ECHO_PROMPT", "1"); + let home = tempfile::tempdir().unwrap(); + let m = manager(3); + let mut p = start(&m, home.path(), true); + status(&m, &p.conversation_id, SessionStatus::Ready).await; + let d = m + .delegate( + &p.conversation_id, + "mock-model-alt".into(), + "Review the parser".into(), + ) + .await + .unwrap(); + m.resolve_delegation(&p.conversation_id, &d.request_id, false) + .await + .unwrap(); + let reply = wait_parent_reply(&mut p, "· declined").await; + assert!( + reply.contains("from mock-model-alt · Review the parser · declined"), + "{reply}" + ); + assert!( + reply.contains("The user declined this delegation."), + "{reply}" + ); + assert!(!reply.contains(&d.child_id), "{reply}"); + assert!(!reply.contains("Child session"), "{reply}"); + m.shutdown(Duration::ZERO).await; +} +#[tokio::test] +#[serial] +async fn a_delegation_as_first_input_titles_the_parent_with_its_task_not_the_result() { + let _echo = Env::set("MOCK_AGENT_ECHO_PROMPT", "1"); + let home = tempfile::tempdir().unwrap(); + let m = manager(3); + let mut p = start(&m, home.path(), true); + status(&m, &p.conversation_id, SessionStatus::Ready).await; + let d = m + .delegate( + &p.conversation_id, + "mock-model".into(), + "Inspect the parser\nand report back".into(), + ) + .await + .unwrap(); + wait_parent_reply(&mut p, &d.child_id).await; + status(&m, &p.conversation_id, SessionStatus::Ready).await; + let listed = ManagedRemoteHost::new(m.clone()) + .request(serde_json::json!({"jsonrpc":"2.0","id":1,"method":"_nori/session/list"})) + .await; + let rows = listed.response["result"]["sessions"].as_array().unwrap(); + let title_of = |session: &str| { + rows.iter() + .find(|row| row["session_id"] == session) + .and_then(|row| row["title"].as_str()) + .map(str::to_owned) + }; + assert_eq!( + title_of(&p.conversation_id.to_string()).as_deref(), + Some("Inspect the parser"), + "{rows:?}" + ); + assert_eq!( + m.replay_info(&p.conversation_id) + .and_then(|info| info.title) + .as_deref(), + Some("Inspect the parser") + ); + m.shutdown(Duration::ZERO).await; +} +#[tokio::test] +#[serial] +async fn the_session_list_marks_a_top_level_session_whose_child_waits_on_you() { + let home = tempfile::tempdir().unwrap(); + let m = manager(3); + let p = start(&m, home.path(), true); + status(&m, &p.conversation_id, SessionStatus::Ready).await; + let d = m + .delegate( + &p.conversation_id, + "mock-model".into(), + "mock:request-permission:cargo test".into(), + ) + .await + .unwrap(); + status(&m, &id(&d), SessionStatus::WaitingOnYou).await; + let listed = ManagedRemoteHost::new(m.clone()) + .request(serde_json::json!({"jsonrpc":"2.0","id":1,"method":"_nori/session/list"})) + .await; + let rows = listed.response["result"]["sessions"].as_array().unwrap(); + let row = |session: &str| { + rows.iter() + .find(|row| row["session_id"] == session) + .unwrap_or_else(|| panic!("{session} in {rows:?}")) + }; + let parent = row(&p.conversation_id.to_string()); + assert_eq!(parent["status"], "ready", "{rows:?}"); + assert_eq!(parent["family_status"], "waiting_on_you", "{rows:?}"); + assert_eq!(row(&d.child_id)["status"], "waiting_on_you", "{rows:?}"); + m.shutdown(Duration::ZERO).await; +} +#[tokio::test] +#[serial] async fn different_kind_waits_for_approval_and_decline_never_launches() { let home = tempfile::tempdir().unwrap(); let m = manager(3); @@ -275,6 +379,28 @@ async fn child_permission_belongs_to_child_and_family_reports_waiting() { }) .await .unwrap(); + let notice = tokio::time::timeout(WAIT, async { + loop { + let e = events.recv().await.unwrap(); + if e.conversation_id == p.conversation_id.to_string() + && let SessionEvent::Nori(NoriEvent::Notice(notice)) = e.event + && notice.message.contains("waiting on you") + { + return notice.message; + } + } + }) + .await + .expect("parent hears that its child is waiting"); + assert!( + notice.contains("mock:request-permission:echo child") && notice.contains("mock-model"), + "the notice names the asking child by its task: {notice}" + ); + assert!( + !notice.contains(&d.child_id) && !notice.contains(&d.parent_id), + "the notice uses readable names: {notice}" + ); + assert!(notice.contains("Alt+Down"), "{notice}"); assert_eq!(m.get(&id(&d)).unwrap().parent, Some(p.conversation_id)); assert!( m.get(&p.conversation_id) @@ -298,7 +424,14 @@ async fn child_permission_belongs_to_child_and_family_reports_waiting() { ) .await .unwrap(); - terminal(&m, &p.conversation_id, &d.request_id).await; + let done = terminal(&m, &p.conversation_id, &d.request_id).await; + let result = done.result.unwrap_or_default(); + assert!( + result + .lines() + .any(|line| line.starts_with("Permission request was cancelled")), + "text after the permission request starts its own paragraph: {result:?}" + ); m.shutdown(Duration::ZERO).await; } #[tokio::test] @@ -327,14 +460,27 @@ async fn result_is_automatically_submitted_as_attributed_parent_input() { && let acp::v1::ContentBlock::Text(t) = c.content && t.text.contains("unique child payload") { - assert!(t.text.contains(&d.child_id)); - assert!(t.text.contains(&d.parent_id)); + assert!( + t.text.contains(&d.child_id), + "the agent can still address the child: {}", + t.text + ); + assert!( + t.text.contains("from mock-model · unique child payload"), + "the result names the child readably: {}", + t.text + ); break; } } }) .await .expect("automatic result reaches parent agent"); + assert_eq!( + d.origin, + nori_protocol::DelegationOrigin::User, + "a manager call made for the user is attributed to the user" + ); m.shutdown(Duration::ZERO).await; } #[tokio::test] @@ -415,8 +561,10 @@ async fn child_crash_returns_failure_without_failing_parent() { ); assert!(m.handle(&p.conversation_id).is_some()); let reply = wait_parent_reply(&mut p, &d.child_id).await; - assert!(reply.contains(&d.parent_id)); - assert!(reply.contains("Failed")); + assert!( + reply.contains("from mock-model · mock:exit-during-prompt · failed"), + "{reply}" + ); assert!(reply.contains("Agent process exited unexpectedly (exit code 17).")); assert!(!reply.contains("RequestFailure"), "{reply}"); m.shutdown(Duration::ZERO).await; @@ -489,6 +637,11 @@ async fn actual_agent_mcp_request_starts_child_and_nested_results_finish_once() .await .expect("nested delegation completes"); let top = m.delegations(&p.conversation_id).pop().unwrap(); + assert_eq!( + top.origin, + nori_protocol::DelegationOrigin::Agent, + "an MCP request is attributed to the agent" + ); let nested = m.delegations(&id(&top)); assert_eq!(nested.len(), 1); assert_eq!(nested[0].status, DelegationStatus::Completed); @@ -669,7 +822,7 @@ async fn child_result_waits_in_busy_parent_queue() { DelegationStatus::Completed ); let reply = wait_parent_reply(&mut p, &d.child_id).await; - assert!(reply.contains(&d.parent_id)); + assert!(reply.contains("· done"), "{reply}"); m.shutdown(Duration::ZERO).await; } diff --git a/nori-rs/nori-config/docs.md b/nori-rs/nori-config/docs.md index aaf48e00e..bdd9dc5b9 100644 --- a/nori-rs/nori-config/docs.md +++ b/nori-rs/nori-config/docs.md @@ -45,7 +45,7 @@ to the harness `SessionManager` as its capacity. `[tui.hotkeys]` resolves every `HotkeyAction` to a `HotkeyBinding`, with per-action defaults from `HotkeyAction::default_binding`. The session-move actions (`previous_session`, `next_session`, `next_waiting_session`, -`open_session_list`) always resolve, but `HotkeyAction::is_multi_session` +`open_session_list`, `parent_session`) always resolve, but `HotkeyAction::is_multi_session` marks them so frontends ignore and hide them unless `multi_session` is on. `[default_models]` maps an agent slug to a model id. This crate only stores the diff --git a/nori-rs/nori-config/src/types/mod.rs b/nori-rs/nori-config/src/types/mod.rs index 70bc04b1b..f150a6080 100644 --- a/nori-rs/nori-config/src/types/mod.rs +++ b/nori-rs/nori-config/src/types/mod.rs @@ -825,6 +825,8 @@ pub enum HotkeyAction { NextWaitingSession, /// Open the session list (multi-session only). OpenSessionList, + /// Move from a delegated child to its parent session (multi-session only). + ParentSession, } impl HotkeyAction { @@ -851,6 +853,7 @@ impl HotkeyAction { Self::NextSession => "Next Session", Self::NextWaitingSession => "Next Waiting Session", Self::OpenSessionList => "Open Session List", + Self::ParentSession => "Parent Session", } } @@ -881,6 +884,7 @@ impl HotkeyAction { "Move to the next session waiting on you (empty prompt only)" } Self::OpenSessionList => "Open the list of sessions", + Self::ParentSession => "Move from a delegated child to its parent session", } } @@ -907,6 +911,7 @@ impl HotkeyAction { Self::NextSession => "next_session", Self::NextWaitingSession => "next_waiting_session", Self::OpenSessionList => "open_session_list", + Self::ParentSession => "parent_session", } } @@ -933,6 +938,7 @@ impl HotkeyAction { Self::NextSession => "alt+.", Self::NextWaitingSession => "alt+down", Self::OpenSessionList => "alt+s", + Self::ParentSession => "alt+up", } } @@ -959,6 +965,7 @@ impl HotkeyAction { Self::NextSession, Self::NextWaitingSession, Self::OpenSessionList, + Self::ParentSession, ] } @@ -969,7 +976,8 @@ impl HotkeyAction { Self::PreviousSession | Self::NextSession | Self::NextWaitingSession - | Self::OpenSessionList => true, + | Self::OpenSessionList + | Self::ParentSession => true, Self::OpenTranscript | Self::OpenEditor | Self::MoveBackwardChar @@ -1113,6 +1121,8 @@ pub struct HotkeyConfigToml { pub next_waiting_session: Option, /// Hotkey: open the list of sessions. pub open_session_list: Option, + /// Hotkey: move from a delegated child to its parent session. + pub parent_session: Option, } /// Resolved hotkey configuration with defaults applied. @@ -1158,6 +1168,8 @@ pub struct HotkeyConfig { pub next_waiting_session: HotkeyBinding, /// Hotkey: open the list of sessions. pub open_session_list: HotkeyBinding, + /// Hotkey: move from a delegated child to its parent session. + pub parent_session: HotkeyBinding, } impl Default for HotkeyConfig { @@ -1215,6 +1227,7 @@ impl Default for HotkeyConfig { open_session_list: HotkeyBinding::from_str( HotkeyAction::OpenSessionList.default_binding(), ), + parent_session: HotkeyBinding::from_str(HotkeyAction::ParentSession.default_binding()), } } } @@ -1295,6 +1308,10 @@ impl HotkeyConfig { .open_session_list .clone() .unwrap_or(defaults.open_session_list), + parent_session: toml + .parent_session + .clone() + .unwrap_or(defaults.parent_session), } } @@ -1321,6 +1338,7 @@ impl HotkeyConfig { HotkeyAction::NextSession => &self.next_session, HotkeyAction::NextWaitingSession => &self.next_waiting_session, HotkeyAction::OpenSessionList => &self.open_session_list, + HotkeyAction::ParentSession => &self.parent_session, } } @@ -1347,6 +1365,7 @@ impl HotkeyConfig { HotkeyAction::NextSession => self.next_session = binding, HotkeyAction::NextWaitingSession => self.next_waiting_session = binding, HotkeyAction::OpenSessionList => self.open_session_list = binding, + HotkeyAction::ParentSession => self.parent_session = binding, } } @@ -1379,6 +1398,7 @@ impl HotkeyConfig { (HotkeyAction::NextSession, &self.next_session), (HotkeyAction::NextWaitingSession, &self.next_waiting_session), (HotkeyAction::OpenSessionList, &self.open_session_list), + (HotkeyAction::ParentSession, &self.parent_session), ] } } diff --git a/nori-rs/nori-config/src/types/tests.rs b/nori-rs/nori-config/src/types/tests.rs index 06416c08a..ec2757181 100644 --- a/nori-rs/nori-config/src/types/tests.rs +++ b/nori-rs/nori-config/src/types/tests.rs @@ -294,7 +294,7 @@ fn test_hotkey_action_default_bindings() { #[test] fn test_hotkey_action_all_actions() { let actions = HotkeyAction::all_actions(); - assert_eq!(actions.len(), 20); + assert_eq!(actions.len(), 21); assert_eq!(actions[0], HotkeyAction::OpenTranscript); assert_eq!(actions[1], HotkeyAction::OpenEditor); assert_eq!(actions[2], HotkeyAction::MoveBackwardChar); @@ -388,7 +388,7 @@ fn test_hotkey_config_set_binding() { fn test_hotkey_config_all_bindings() { let config = HotkeyConfig::default(); let bindings = config.all_bindings(); - assert_eq!(bindings.len(), 20); + assert_eq!(bindings.len(), 21); assert_eq!(bindings[0].0, HotkeyAction::OpenTranscript); assert_eq!(bindings[1].0, HotkeyAction::OpenEditor); } @@ -626,6 +626,7 @@ fn test_hotkey_config_from_toml_editing_overrides() { next_session: None, next_waiting_session: None, open_session_list: None, + parent_session: None, }; let config = HotkeyConfig::from_toml(&toml); assert_eq!( @@ -671,6 +672,7 @@ fn test_hotkey_config_from_toml_editing_unbind() { next_session: None, next_waiting_session: None, open_session_list: None, + parent_session: None, }; let config = HotkeyConfig::from_toml(&toml); assert!(config.move_backward_char.is_none()); @@ -682,7 +684,7 @@ fn test_hotkey_config_from_toml_editing_unbind() { fn test_hotkey_config_all_bindings_includes_editing() { let config = HotkeyConfig::default(); let bindings = config.all_bindings(); - assert_eq!(bindings.len(), 20); + assert_eq!(bindings.len(), 21); // First two are app-level actions assert_eq!(bindings[0].0, HotkeyAction::OpenTranscript); assert_eq!(bindings[1].0, HotkeyAction::OpenEditor); diff --git a/nori-rs/nori-protocol/docs.md b/nori-rs/nori-protocol/docs.md index f8f2eee4b..05b246a16 100644 --- a/nori-rs/nori-protocol/docs.md +++ b/nori-rs/nori-protocol/docs.md @@ -49,29 +49,10 @@ pub enum AcpEvent { } ``` -`NoriEvent` outer variants: - -```rust -pub enum NoriEvent { - SessionStarted(SessionStarted), - SessionPhaseChanged(SessionPhase), - SessionEnded(SessionEnded), - QueueChanged(QueueSnapshot), - ReplayStarted(ReplayStarted), - ReplayFinished, - ContextCompacted(ContextCompactedEvent), - SessionForked(SessionForked), - GoalChanged(Option), - CapabilitiesChanged(NoriCapabilities), - Undo(UndoEvent), - UserShell(UserShellEvent), - HookOutput(HookOutput), - PromptSummaryUpdated(PromptSummary), - Notice(Notice), - RequestFailed(RequestFailure), - RequestResolved(RequestResolved), -} -``` +`NoriEvent` variants cover session lifecycle (started, phase changed, ended, +forked), queue and replay bracketing, compaction, goals, capabilities, undo, +user-shell and hook output, prompt summaries, notices, request failure and +resolution, and delegation changes (`DelegationChanged`). `NoriEvent` carries harness-owned lifecycle and product behavior that has no ACP event of its own. A `session/update` received without a locally owned @@ -103,10 +84,58 @@ fork starts a new conversation and therefore a new sequence. The envelope adds routing only; the wrapped event is unchanged. `SessionStatus` is the coarse per-session status shown in a session list: -`Starting`, `Working`, `WaitingOnYou`, `Ready`, `Failed`, or `Closed` (serialized -in snake case). The rules that derive it from the event stream live in the -harness session manager (see [`nori-harness`](../harness/docs.md)); this crate -defines only the values. +`Starting`, `Working`, `WaitingOnYou`, `Ready`, `Failed`, `Closed`, or `Done` +(serialized in snake case). `Closed` is a session the user closed or shut down, +or one superseded by a fork; `Done` is a delegated child whose task finished. +`SessionStatus::is_closed()` is true for both, and frontends treat the two +alike wherever they ask whether a session has ended normally. The rules that +derive status from the event stream live in the harness session manager (see +[`nori-harness`](../harness/docs.md)); this crate defines only the values. + +`Delegation` is the record a `DelegationChanged` event carries for one +delegated child: request, parent, and child identities, both agent names, the +task, depth, `DelegationStatus`, optional result, and `DelegationOrigin` +(`Agent` when the parent agent called the `delegate` tool, `User` for +`/delegate` or a direct manager call). `origin` has a serde default of `Agent` +so events from hosts that predate the field still deserialize; a user's +`/delegate` relayed by such a host therefore reads as the agent's request. + +[`delegation.rs`](src/delegation.rs) holds the only text logic in the crate: +the shared naming and result-prompt wording that the harness, the local TUI, +and `nori attach` must agree on. + +| Function | Produces | +| --- | --- | +| `session_full_name` | First non-empty trimmed line of a task or title, uncut | +| `shorten_name` | A name in at most a given number of characters, cut in the middle (start, `…`, end) | +| `session_display_name` | `session_full_name` shortened to 40 characters with `shorten_name` | +| `delegation_child_name` | The child's display name from its task, else `UNTITLED_SESSION_NAME` | +| `delegation_status_word` | `waiting on you`, `working`, `done`, `failed`, `declined`, or `cancelled`, matching session status words | +| `delegation_result_prompt` | The prompt delivered to the parent: `[Nori delegation result] from · · ` (the child name is the task's whole first line, else `UNTITLED_SESSION_NAME`), then `Child session: `, then the result text. A declined delegation omits the `Child session:` line because its child never started | +| `delegation_result_summary` | The text after `DELEGATION_RESULT_HEADER` on a prompt's first line, when the second line starts with `Child session: ` or the first line ends in ` · declined`; `None` for any other text | +| `delegation_result_parts` | `DelegationResultParts` (agent, child name, status word) parsed from a result prompt's summary; the name is everything between the first and last ` · `, so a name containing ` · ` survives. `None` for any other text | + +`UNTITLED_SESSION_NAME` (`new session`) is the shared name for a session with +no title or task; the harness, the local TUI, and `nori attach` use it instead +of an ID fragment. + +Names are cut in the middle rather than at the end because sibling and parent +sessions often share a long task prefix; keeping the end keeps them apart. +`shorten_name` counts characters, for fixed-length names such as notices. +Lines that fit names to the terminal width take the whole name +(`session_full_name`) and cut it once by display cells in the TUI. + +The result prompt keeps the child ID on its own line so the receiving agent can +still address that session, while the first line stays readable. The local +TUI and `nori attach` recognize a delivered result through +`delegation_result_summary`, which requires the header plus either the +`Child session: ` second line or the declined ending, so ordinary user text +that merely begins with the header is left whole. The harness and TUI also use +it to keep result prompts from titling the session that receives them. To +draw the collapsed result line they read the agent, name, and status back out +with `delegation_result_parts` instead of rebuilding the header, so the header +wording exists only in `delegation_result_prompt`. Both strings are a +cross-crate contract. Session termination reasons are `Shutdown`, `Closed`, `ConnectionLost`, `SpawnFailed`, and `TimedOut`. Raw ACP request and response envelopes retain the @@ -120,18 +149,21 @@ exact ACP wire `RequestId` for harness-issued operations. terminal requests, modes, config options, capabilities, usage, and method responses. Do not mirror them into Nori types. - Nori owns only behavior around the ACP session: lifecycle, queueing, replay, - compaction, goals, undo, user-shell output, hooks, summaries, notices, and - failures that have no ACP response. + compaction, goals, undo, user-shell output, hooks, summaries, notices, + delegation, and failures that have no ACP response. - Output without an active local request remains raw `SessionEvent::Acp` traffic. Presentation grouping and optional lifecycle hints stay private to consumers such as [`nori-tui`](../tui/docs.md). - `SessionEnvelope` and `SessionStatus` are Nori routing and summary types, not ACP extensions. -- The crate contains no reducer, normalizer, parser, formatter, transcript - compatibility decoder, or presentation state. +- The crate contains no reducer, normalizer, transcript compatibility + decoder, or presentation state. The delegation text helpers are plain + strings with no styling; each frontend applies its own colors. - `ReplayStarted` and `ReplayFinished` bracket historical ACP notifications only. Current setup responses and Nori lifecycle events remain outside the replay body. +- Unit tests in [`delegation.rs`](src/delegation.rs) pin the result-prompt + and summary shapes; `just test protocol` runs `cargo test -p nori-protocol`. - The deleted Codex `Event`/`EventMsg`/`Op` API and the former public `ClientEvent` normalization API have no compatibility aliases. diff --git a/nori-rs/nori-protocol/src/delegation.rs b/nori-rs/nori-protocol/src/delegation.rs new file mode 100644 index 000000000..e9f9fff80 --- /dev/null +++ b/nori-rs/nori-protocol/src/delegation.rs @@ -0,0 +1,244 @@ +//! Text shared by every surface that names a delegated child or reads its result. +use crate::Delegation; +use crate::DelegationStatus; + +/// First line of every result prompt a parent agent receives from a child. +pub const DELEGATION_RESULT_HEADER: &str = "[Nori delegation result]"; + +const NAME_CHARS: i32 = 40; + +const CHILD_LINE_PREFIX: &str = "Child session: "; + +/// What a session without a title or task is called. +pub const UNTITLED_SESSION_NAME: &str = "new session"; + +/// The first non-empty line of a session's task or title, whole. +pub fn session_full_name(text: &str) -> Option { + text.lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .map(str::to_owned) +} + +/// A short readable name for a session, taken from the first non-empty line of +/// its task or title. A long line keeps its start and end, so sessions whose +/// names share a long prefix still read apart. +pub fn session_display_name(text: &str) -> Option { + session_full_name(text).map(|line| shorten_name(&line, NAME_CHARS)) +} + +/// `name` in at most `limit` characters, cut in the middle with `…`. +pub fn shorten_name(name: &str, limit: i32) -> String { + let limit = usize::try_from(limit).unwrap_or_default(); + let count = name.chars().count(); + if count <= limit { + return name.to_owned(); + } + if limit == 0 { + return String::new(); + } + let room = limit.saturating_sub(1); + let head: String = name.chars().take(room.div_ceil(2)).collect(); + let tail: String = name.chars().skip(count - room / 2).collect(); + format!("{}…{}", head.trim_end(), tail.trim_start()) +} + +/// The readable name of a delegated child. +pub fn delegation_child_name(delegation: &Delegation) -> String { + session_display_name(&delegation.task).unwrap_or_else(|| UNTITLED_SESSION_NAME.to_owned()) +} + +/// The word used for a delegation's state, matching the session status words. +pub fn delegation_status_word(status: DelegationStatus) -> &'static str { + match status { + DelegationStatus::AwaitingApproval => "waiting on you", + DelegationStatus::Running => "working", + DelegationStatus::Completed => "done", + DelegationStatus::Failed => "failed", + DelegationStatus::Declined => "declined", + DelegationStatus::Cancelled => "cancelled", + } +} + +/// The prompt that carries a child's outcome back to its parent agent. +/// +/// The first line names the child readably; the second keeps its ID so the +/// agent can still refer to that session. A declined child never started, so +/// its prompt names no session. +pub fn delegation_result_prompt(delegation: &Delegation) -> String { + let header = format!( + "{DELEGATION_RESULT_HEADER} from {} · {} · {}", + delegation.agent, + session_full_name(&delegation.task).unwrap_or_else(|| UNTITLED_SESSION_NAME.to_owned()), + delegation_status_word(delegation.status), + ); + let result = delegation.result.as_deref().unwrap_or_default(); + if delegation.status == DelegationStatus::Declined { + return format!("{header}\n{result}"); + } + format!( + "{header}\n{CHILD_LINE_PREFIX}{}\n{result}", + delegation.child_id + ) +} + +/// The readable summary line of a result prompt, or `None` for other text. +pub fn delegation_result_summary(prompt: &str) -> Option<&str> { + let mut lines = prompt.lines(); + let summary = lines + .next()? + .strip_prefix(DELEGATION_RESULT_HEADER) + .map(str::trim) + .filter(|summary| !summary.is_empty())?; + let declined = summary.ends_with(&format!( + " · {}", + delegation_status_word(DelegationStatus::Declined) + )); + (declined || lines.next()?.starts_with(CHILD_LINE_PREFIX)).then_some(summary) +} + +/// The parts of a result prompt's readable summary line. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DelegationResultParts<'a> { + pub agent: &'a str, + pub name: &'a str, + pub status: &'a str, +} + +/// The agent, child name and status a result prompt names, or `None` for +/// other text. +pub fn delegation_result_parts(prompt: &str) -> Option> { + let rest = delegation_result_summary(prompt)?.strip_prefix("from ")?; + let (agent, rest) = rest.split_once(PARTS_SEPARATOR)?; + let (name, status) = rest.rsplit_once(PARTS_SEPARATOR)?; + Some(DelegationResultParts { + agent, + name, + status, + }) +} + +const PARTS_SEPARATOR: &str = " · "; + +#[cfg(test)] +mod tests { + use super::*; + use crate::DelegationOrigin; + use pretty_assertions::assert_eq; + + fn delegation(status: DelegationStatus, task: &str, result: Option<&str>) -> Delegation { + Delegation { + request_id: "request-1".into(), + parent_id: "11111111-2222-3333-4444-555555555555".into(), + child_id: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee".into(), + parent_agent: "claude-code".into(), + agent: "codex".into(), + task: task.into(), + status, + depth: 1, + result: result.map(str::to_owned), + origin: DelegationOrigin::User, + } + } + + #[test] + fn a_finished_child_reports_done_with_its_answer_and_session() { + let prompt = delegation_result_prompt(&delegation( + DelegationStatus::Completed, + "Review the parser\nwith care", + Some("Looks good."), + )); + assert_eq!( + prompt, + "[Nori delegation result] from codex · Review the parser · done\n\ + Child session: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\n\ + Looks good." + ); + assert_eq!( + delegation_result_summary(&prompt), + Some("from codex · Review the parser · done") + ); + } + + #[test] + fn a_declined_delegation_names_no_session_and_still_reads_as_a_result() { + let prompt = delegation_result_prompt(&delegation( + DelegationStatus::Declined, + "Review the parser", + Some("The user declined this delegation."), + )); + assert_eq!( + prompt, + "[Nori delegation result] from codex · Review the parser · declined\n\ + The user declined this delegation." + ); + assert_eq!( + delegation_result_summary(&prompt), + Some("from codex · Review the parser · declined") + ); + } + + #[test] + fn text_that_only_starts_with_the_header_is_not_a_result() { + assert_eq!( + delegation_result_summary("[Nori delegation result] from me\nhello"), + None + ); + assert_eq!(delegation_result_summary("Review the parser"), None); + } + + #[test] + fn long_names_keep_their_start_and_end_so_shared_prefixes_stay_apart() { + let parent = + session_display_name("shared prefix for the parser review: parent side").unwrap(); + let child = session_display_name( + "shared prefix for the parser review: child side mock:request-permission:z", + ) + .unwrap(); + assert!(parent.chars().count() <= 40, "{parent}"); + assert!(child.chars().count() <= 40, "{child}"); + assert!(parent.starts_with("shared prefix"), "{parent}"); + assert!(parent.ends_with("parent side"), "{parent}"); + assert!(child.ends_with("permission:z"), "{child}"); + assert_eq!( + session_display_name("Review the parser").as_deref(), + Some("Review the parser") + ); + } + + #[test] + fn a_result_header_names_the_child_by_its_whole_task_line() { + let task = "mock:request-permission:review-the-lexer-tokens and the parser too"; + let prompt = delegation_result_prompt(&delegation( + DelegationStatus::Completed, + task, + Some("Looks good."), + )); + let parts = delegation_result_parts(&prompt).expect("a result prompt"); + assert_eq!(parts.agent, "codex"); + assert_eq!(parts.name, task); + assert_eq!(parts.status, "done"); + let dotted = delegation_result_prompt(&delegation( + DelegationStatus::Failed, + "lint · then test", + Some("Agent process exited unexpectedly."), + )); + assert_eq!( + delegation_result_parts(&dotted), + Some(DelegationResultParts { + agent: "codex", + name: "lint · then test", + status: "failed", + }) + ); + assert_eq!(delegation_result_parts("Review the parser"), None); + } + + #[test] + fn a_child_without_a_task_line_has_a_readable_placeholder_name() { + assert_eq!( + delegation_child_name(&delegation(DelegationStatus::Running, " \n ", None)), + "new session" + ); + } +} diff --git a/nori-rs/nori-protocol/src/lib.rs b/nori-rs/nori-protocol/src/lib.rs index fcd62c398..2b6b8786f 100644 --- a/nori-rs/nori-protocol/src/lib.rs +++ b/nori-rs/nori-protocol/src/lib.rs @@ -3,10 +3,12 @@ //! ACP owns agent/client semantics. Nori adds only the lifecycle and product //! notifications that ACP does not define. +mod delegation; mod session_envelope; mod session_event; pub use agent_client_protocol_schema as acp; +pub use delegation::*; pub use session_envelope::*; pub use session_event::*; diff --git a/nori-rs/nori-protocol/src/session_envelope.rs b/nori-rs/nori-protocol/src/session_envelope.rs index 41690f246..9d51950af 100644 --- a/nori-rs/nori-protocol/src/session_envelope.rs +++ b/nori-rs/nori-protocol/src/session_envelope.rs @@ -38,4 +38,14 @@ pub enum SessionStatus { Failed, /// The session was shut down, closed, or superseded by a fork. Closed, + /// A delegated child that finished its task; its history stays readable. + Done, +} + +impl SessionStatus { + /// Whether the session ended normally: closed by the user or done with + /// its task. Its history stays readable; it takes no prompts. + pub fn is_closed(self) -> bool { + matches!(self, Self::Closed | Self::Done) + } } diff --git a/nori-rs/nori-protocol/src/session_event.rs b/nori-rs/nori-protocol/src/session_event.rs index a07e771e7..e036849c0 100644 --- a/nori-rs/nori-protocol/src/session_event.rs +++ b/nori-rs/nori-protocol/src/session_event.rs @@ -274,6 +274,19 @@ pub struct Delegation { pub status: DelegationStatus, pub depth: i32, pub result: Option, + /// Who asked for the child. Events from older hosts omit it. + #[serde(default)] + pub origin: DelegationOrigin, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DelegationOrigin { + /// The parent agent called the `delegate` tool. + #[default] + Agent, + /// The user ran `/delegate` or a client called the manager directly. + User, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] diff --git a/nori-rs/tui-components/Cargo.toml b/nori-rs/tui-components/Cargo.toml index 96045d072..97e5208bd 100644 --- a/nori-rs/tui-components/Cargo.toml +++ b/nori-rs/tui-components/Cargo.toml @@ -18,6 +18,7 @@ nucleo-matcher = { workspace = true } pulldown-cmark = { workspace = true } ratatui = { workspace = true, features = ["unstable-rendered-line-info"] } textwrap = { workspace = true } +unicode-segmentation = { workspace = true } unicode-width = { workspace = true } [dev-dependencies] diff --git a/nori-rs/tui-components/docs.md b/nori-rs/tui-components/docs.md index 9a2805eea..a314bf043 100644 --- a/nori-rs/tui-components/docs.md +++ b/nori-rs/tui-components/docs.md @@ -158,12 +158,32 @@ consumer application negative values clamp to 0; a row nests under the closest earlier row with a smaller depth. The [`tree`](src/picker/tree.rs) helper computes indent guides (`├─`, `└─`, `│`) from the depths of the visible rows only, so filtering - redraws the guides for what remains. The guide prefixes the primary cell and + redraws the guides for what remains. The guide prefixes the tree column and a matching continuation prefixes the row's description line, at every depth. +- `PickerState::tree_column(key)` names the column that carries tree guides and + badges. It defaults to the first visible column, and falls back to it when + the named column is hidden. Pointing it at a later column (the attached + session list uses TITLE) keeps the earlier fixed-width columns aligned at + every depth. +- `tree_guides` and `tree_order` are public so non-picker output can draw the + same tree. `tree_order` takes `(id, parent)` pairs and returns each row's + index and depth in depth-first order: children follow their parent and + siblings keep their given order. A row whose parent is absent (or is itself) + becomes top level, and rows caught in a parent cycle are listed at top level + rather than dropped. `nori host ls` uses both helpers for its plain-text + table. - An item's `current`, `default`, and `read_only` flags render as a badge such - as `(current)` after the primary cell. When the first column is too narrow, + as `(current)` after the tree column's text. When that column is too narrow, the renderer cuts the title (with `…`) to make room, so the tree guide and the badge always stay visible. +- `PickerColumn::cut_middle()` makes a column cut overlong values in the + middle (start, `…`, end) instead of at the tail, so values sharing a long + prefix stay distinguishable. In the tree column the title is cut once, to the + room left after the guide and badges. Both TUI session lists use it for + TITLE. The cut comes from the public + [`text::truncate_middle`](src/text.rs), which works in display cells, never + splits a grapheme, and gives the start the larger half; the TUI's + `session_path::fit_name` delegates to it. - `Picker::compact_descriptions(true)` keeps each row's description on a second line in compact density as well, for lists whose descriptions carry a live preview. Compact rows become two lines tall only when at least one diff --git a/nori-rs/tui-components/src/lib.rs b/nori-rs/tui-components/src/lib.rs index 6dcfe021d..75bf53a68 100644 --- a/nori-rs/tui-components/src/lib.rs +++ b/nori-rs/tui-components/src/lib.rs @@ -10,6 +10,7 @@ pub mod markdown; pub mod menu; pub mod picker; pub mod primitives; +pub mod text; pub mod theme; pub use block_meter::BlockMeter; diff --git a/nori-rs/tui-components/src/picker/mod.rs b/nori-rs/tui-components/src/picker/mod.rs index 2c987074e..a2b632515 100644 --- a/nori-rs/tui-components/src/picker/mod.rs +++ b/nori-rs/tui-components/src/picker/mod.rs @@ -14,6 +14,8 @@ use crate::ProviderKind; mod render; mod tree; +pub use tree::tree_guides; +pub use tree::tree_order; pub use render::Picker; @@ -32,6 +34,9 @@ pub struct PickerColumn { pub header: String, pub width: PickerColumnWidth, pub hide_below: Option, + /// Cut a value that does not fit in the middle, keeping its start and + /// end, instead of at its tail. + pub cut_middle: bool, } impl PickerColumn { @@ -45,6 +50,7 @@ impl PickerColumn { weight: 1, }, hide_below: None, + cut_middle: false, } } @@ -54,6 +60,7 @@ impl PickerColumn { header: header.into(), width: PickerColumnWidth::Fixed(width), hide_below: None, + cut_middle: false, } } @@ -62,6 +69,11 @@ impl PickerColumn { self } + pub fn cut_middle(mut self) -> Self { + self.cut_middle = true; + self + } + pub fn hide_below(mut self, viewport_width: u16) -> Self { self.hide_below = Some(viewport_width); self @@ -329,6 +341,9 @@ pub struct PickerState { pub page_size: usize, pub load_state: PickerLoadState, pub search_placeholder: String, + /// Column that carries tree guides and row badges; the first visible + /// column when unset or hidden. + pub tree_column: Option, } impl PickerState { @@ -354,6 +369,7 @@ impl PickerState { page_size: 8, load_state: PickerLoadState::Ready, search_placeholder: "Type to search".to_string(), + tree_column: None, }; state.select_first_available(); state @@ -389,6 +405,13 @@ impl PickerState { self } + /// Draw tree guides and badges in this column, so earlier fixed columns + /// keep their alignment. + pub fn tree_column(mut self, key: impl Into) -> Self { + self.tree_column = Some(key.into()); + self + } + pub fn search_placeholder(mut self, placeholder: impl Into) -> Self { self.search_placeholder = placeholder.into(); self diff --git a/nori-rs/tui-components/src/picker/render.rs b/nori-rs/tui-components/src/picker/render.rs index fef148cd8..7edaf89e6 100644 --- a/nori-rs/tui-components/src/picker/render.rs +++ b/nori-rs/tui-components/src/picker/render.rs @@ -437,16 +437,27 @@ impl Picker<'_, K> { .map(|column| item.cells.get(&column.key).cloned().unwrap_or_default()) .collect::>(); let (guide, description_guide) = &guides[start + row_offset]; - if let Some(primary) = values.first_mut() { + let tree_index = self + .state + .tree_column + .as_ref() + .and_then(|key| columns.iter().position(|column| &column.key == key)) + .unwrap_or(0); + if let Some(primary) = values.get_mut(tree_index) { // Cut the title, not the badge, when the column is narrow. let badge = if badges.is_empty() { String::new() } else { format!(" ({badges})") }; - let room = usize::from(widths.first().copied().unwrap_or(0)) + let room = usize::from(widths.get(tree_index).copied().unwrap_or(0)) .saturating_sub(guide.width() + badge.width()); - let title = if badge.is_empty() { + let cut_middle = columns + .get(tree_index) + .is_some_and(|column| column.cut_middle); + let title = if cut_middle { + crate::text::truncate_middle(primary, room) + } else if badge.is_empty() { std::mem::take(primary) } else { truncate(primary, room) @@ -535,7 +546,11 @@ impl Picker<'_, K> { buf.set_string(x, area.y, marker, marker_style); x = x.saturating_add(marker_width); for ((column, width), (value, value_style)) in columns.iter().zip(widths).zip(values) { - let value = truncate(value, *width as usize); + let value = if column.cut_middle { + crate::text::truncate_middle(value, *width as usize) + } else { + truncate(value, *width as usize) + }; buf.set_string(x, area.y, value, value_style); x = x.saturating_add(*width); if column.key diff --git a/nori-rs/tui-components/src/picker/tree.rs b/nori-rs/tui-components/src/picker/tree.rs index 43453d16f..a8433bb97 100644 --- a/nori-rs/tui-components/src/picker/tree.rs +++ b/nori-rs/tui-components/src/picker/tree.rs @@ -3,7 +3,7 @@ /// Guides for each row, given the depth of every visible row in order. /// Each entry is the prefix for the row's first line and the prefix for its /// description line. Top-level rows get no guides. -pub(crate) fn tree_guides(depths: &[i32]) -> Vec<(String, String)> { +pub fn tree_guides(depths: &[i32]) -> Vec<(String, String)> { // A filter can hide a row's parent. Each row nests at most one level below // the row above it, so guides never hang from a row that is not shown. let mut previous = -1; @@ -52,3 +52,45 @@ fn sibling_follows(depths: &[i32], row: usize, level: i32) -> bool { .find(|depth| **depth <= level) .is_some_and(|depth| *depth == level) } + +/// Depth-first order for rows given as `(id, parent)`: each child follows its +/// parent and siblings keep their given order. A row whose parent is not in +/// the list is top level. Returns each row's index and depth. +pub fn tree_order(rows: &[(&str, Option<&str>)]) -> Vec<(usize, i32)> { + let known: std::collections::HashSet<&str> = rows.iter().map(|(id, _)| *id).collect(); + let mut order = Vec::with_capacity(rows.len()); + let mut placed = vec![false; rows.len()]; + let mut stack: Vec<(usize, i32)> = rows + .iter() + .enumerate() + .rev() + .filter(|(_, (id, parent))| { + parent.is_none_or(|parent| parent == *id || !known.contains(parent)) + }) + .map(|(index, _)| (index, 0)) + .collect(); + loop { + while let Some((index, depth)) = stack.pop() { + if std::mem::replace(&mut placed[index], true) { + continue; + } + order.push((index, depth)); + let id = rows[index].0; + stack.extend( + rows.iter() + .enumerate() + .rev() + .filter(|(child, (child_id, parent))| { + !placed[*child] && *child_id != id && *parent == Some(id) + }) + .map(|(child, _)| (child, depth + 1)), + ); + } + // Rows caught in a parent cycle have no root; list them at top level. + match placed.iter().position(|placed| !placed) { + Some(index) => stack.push((index, 0)), + None => break, + } + } + order +} diff --git a/nori-rs/tui-components/src/picker/tree_tests.rs b/nori-rs/tui-components/src/picker/tree_tests.rs index c83951f78..89d22d76f 100644 --- a/nori-rs/tui-components/src/picker/tree_tests.rs +++ b/nori-rs/tui-components/src/picker/tree_tests.rs @@ -5,6 +5,7 @@ use insta::assert_snapshot; use pretty_assertions::assert_eq; use ratatui::Terminal; use ratatui::backend::TestBackend; +use unicode_width::UnicodeWidthStr; fn family_picker() -> PickerState { let columns = [ @@ -193,3 +194,52 @@ fn a_badge_survives_when_a_long_title_is_cut() { "{screen}" ); } + +fn shared_prefix_picker() -> PickerState { + let columns = [ + PickerColumn::fixed("status", "Status", 16), + PickerColumn::flexible("title", "Title").cut_middle(), + ]; + let row = |key: &str, depth| { + PickerItem::new( + key.to_string(), + "title", + format!("shared prefix for the parser review and its long tail {key}"), + ) + .depth(depth) + .cell("status", "ready") + }; + PickerState::new( + "Sessions", + columns, + [row("parent side", 0), row("child side", 1).current(true)], + ) + .tree_column("title") +} + +#[test] +fn middle_cut_titles_keep_their_distinct_ends_once_cut() { + for width in [80, 60] { + let screen = render(&shared_prefix_picker(), width, 8, PickerDensity::Compact); + let parent = screen + .lines() + .find(|line| line.contains("parent side")) + .unwrap_or_else(|| panic!("parent end is shown at {width}: {screen}")); + let child = screen + .lines() + .find(|line| line.contains("child side")) + .unwrap_or_else(|| panic!("child end is shown at {width}: {screen}")); + for row in [parent, child] { + assert!(row.contains("shared"), "start is kept at {width}: {row}"); + assert_eq!(row.matches('…').count(), 1, "cut once at {width}: {row}"); + assert!( + row.trim_matches('"').trim_end().width() <= usize::from(width), + "{row}" + ); + } + assert!( + child.contains("└─") && child.contains("(current)"), + "{child}" + ); + } +} diff --git a/nori-rs/tui-components/src/text.rs b/nori-rs/tui-components/src/text.rs new file mode 100644 index 000000000..93a0db8b2 --- /dev/null +++ b/nori-rs/tui-components/src/text.rs @@ -0,0 +1,74 @@ +//! Width-aware text helpers shared by components and their callers. + +use unicode_segmentation::UnicodeSegmentation; +use unicode_width::UnicodeWidthStr; + +/// Fit `text` in `cells` display cells by cutting its middle, keeping the +/// start and the end so names that share a long prefix stay apart. The start +/// gets the larger half; graphemes are never split. +pub fn truncate_middle(text: &str, cells: usize) -> String { + if text.width() <= cells { + return text.to_string(); + } + if cells == 0 { + return String::new(); + } + let room = cells - 1; + let graphemes: Vec<&str> = text.graphemes(true).collect(); + let mut head = String::new(); + for grapheme in &graphemes { + if head.width() + grapheme.width() > room.div_ceil(2) { + break; + } + head.push_str(grapheme); + } + let mut tail_width = 0; + let mut tail: Vec<&str> = Vec::new(); + for grapheme in graphemes.iter().rev() { + if head.width() + tail_width + grapheme.width() > room { + break; + } + tail_width += grapheme.width(); + tail.push(grapheme); + } + tail.reverse(); + format!("{}…{}", head.trim_end(), tail.concat().trim_start()) +} + +#[cfg(test)] +mod tests { + use super::truncate_middle; + use pretty_assertions::assert_eq; + use unicode_width::UnicodeWidthStr; + + #[test] + fn text_that_fits_is_unchanged() { + assert_eq!(truncate_middle("parser", 6), "parser"); + } + + #[test] + fn tiny_widths_still_fit() { + assert_eq!(truncate_middle("parser", 0), ""); + assert_eq!(truncate_middle("parser", 1), "…"); + assert_eq!(truncate_middle("parser", 2), "p…"); + } + + #[test] + fn the_start_and_end_survive_with_the_start_getting_more() { + assert_eq!(truncate_middle("review the parser:x", 9), "revi…er:x"); + } + + #[test] + fn wide_and_joined_characters_are_never_split() { + for (text, cells) in [ + ("日本語のパーサー", 7), + ("ab👩‍💻cd👩‍💻ef", 6), + ("cafe\u{301} au lait", 6), + ] { + let cut = truncate_middle(text, cells); + assert!(cut.width() <= cells, "{cut:?} fits {cells}"); + assert!(!cut.contains('\u{200d}') || cut.contains("👩‍💻"), "{cut:?}"); + assert!(cut.contains('…'), "{cut:?}"); + } + } +} diff --git a/nori-rs/tui-pty-e2e/src/keys.rs b/nori-rs/tui-pty-e2e/src/keys.rs index a56eee3b1..123559d28 100644 --- a/nori-rs/tui-pty-e2e/src/keys.rs +++ b/nori-rs/tui-pty-e2e/src/keys.rs @@ -14,6 +14,8 @@ pub enum Key { Alt(char), /// Down arrow pressed with Alt. AltDown, + /// Up arrow pressed with Alt. + AltUp, /// Shift+Tab. BackTab, /// The terminal window gained focus. @@ -41,6 +43,7 @@ impl Key { bytes } Key::AltDown => b"\x1b[1;3B".to_vec(), + Key::AltUp => b"\x1b[1;3A".to_vec(), Key::BackTab => b"\x1b[Z".to_vec(), Key::FocusIn => b"\x1b[I".to_vec(), Key::FocusOut => b"\x1b[O".to_vec(), diff --git a/nori-rs/tui-pty-e2e/tests/delegation.rs b/nori-rs/tui-pty-e2e/tests/delegation.rs index 55a68b336..3d2f50977 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -4,13 +4,25 @@ use tui_pty_e2e::Key; use tui_pty_e2e::SessionConfig; use tui_pty_e2e::TIMEOUT; use tui_pty_e2e::TuiSession; +use tui_pty_e2e::normalize_for_input_snapshot; -fn spawn(enabled: bool) -> TuiSession { - let config = SessionConfig::new() +fn config(enabled: bool) -> SessionConfig { + SessionConfig::new() .with_extra_config_toml(format!("[features]\nmulti_session = {enabled}\n")) .with_agent_env("MOCK_AGENT_RESPONSE_MOCK_MODEL", "parent final answer") - .with_agent_env("MOCK_AGENT_RESPONSE_MOCK_MODEL_ALT", "child final answer"); - let mut session = TuiSession::spawn_with_config(40, 130, config).unwrap(); + .with_agent_env("MOCK_AGENT_RESPONSE_MOCK_MODEL_ALT", "child final answer") +} + +fn spawn_fresh(rows: u16, cols: u16) -> TuiSession { + let mut session = TuiSession::spawn_with_config(rows, cols, config(true)).unwrap(); + session + .wait_for_text("Mock Default Model", TIMEOUT) + .unwrap(); + session +} + +fn spawn(enabled: bool) -> TuiSession { + let mut session = TuiSession::spawn_with_config(40, 130, config(enabled)).unwrap(); session .wait_for_text("Mock Default Model", TIMEOUT) .unwrap(); @@ -29,26 +41,27 @@ fn same_kind_child_starts_and_returns_without_approval_or_exiting_terminal() { .unwrap(); session .wait_for( - |screen| screen.contains("completed") || screen.contains("Completed"), + |screen| screen.contains("result from mock-model") && screen.contains(" · done"), TIMEOUT, ) .unwrap(); assert!( !session .screen_contents() - .contains("Start delegated session") + .contains("start a mock-model-alt session") ); session.submit_input("/sessions").unwrap(); session - .wait_for_text("inspect the parser", TIMEOUT) + .wait_for( + |screen| screen.contains("Sessions 2") && screen.contains("└─ · inspect the parser"), + TIMEOUT, + ) .unwrap(); session.send_key(Key::Down).unwrap(); session.send_key(Key::Enter).unwrap(); session .wait_for( - |screen| { - screen.contains("inspect the parser") && !screen.contains("parent task identity") - }, + |screen| screen.contains("inspect the parser") && screen.contains("alt + up to parent"), TIMEOUT, ) .unwrap(); @@ -86,7 +99,7 @@ fn different_kind_child_needs_start_and_its_permission_stays_in_child() { .submit_input("/delegate mock-model-alt mock:request-permission:write-child-file") .unwrap(); session - .wait_for_text("Start delegated session", TIMEOUT) + .wait_for_text("start a mock-model-alt session", TIMEOUT) .unwrap(); assert!( !session @@ -118,7 +131,7 @@ fn different_kind_child_needs_start_and_its_permission_stays_in_child() { session.send_key(Key::Alt(',')).unwrap(); session .wait_for( - |screen| screen.contains("completed") || screen.contains("Completed"), + |screen| screen.contains("result from mock-model") && screen.contains(" · done"), TIMEOUT, ) .unwrap(); @@ -140,7 +153,7 @@ fn declining_different_kind_does_not_start_child() { .submit_input("/delegate mock-model-alt inspect parser without starting a child") .unwrap(); session - .wait_for_text("Start delegated session", TIMEOUT) + .wait_for_text("start a mock-model-alt session", TIMEOUT) .unwrap(); session.send_key(Key::Char('2')).unwrap(); session @@ -151,7 +164,9 @@ fn declining_different_kind_does_not_start_child() { .unwrap(); session .wait_for( - |screen| !screen.contains("Working") && !screen.contains("Start delegated session"), + |screen| { + !screen.contains("Working") && !screen.contains("start a mock-model-alt session") + }, TIMEOUT, ) .unwrap(); @@ -172,6 +187,309 @@ fn delegation_is_unavailable_without_multi_session() { assert!( !session .screen_contents() - .contains("Start delegated session") + .contains("start a mock-model-alt session") + ); +} + +#[test] +fn delegation_reads_clearly_from_request_to_result() { + let mut session = spawn(true); + session + .submit_input("/delegate mock-model-alt mock:request-permission:write-child-file") + .unwrap(); + session + .wait_for_text("start a mock-model-alt session", TIMEOUT) + .unwrap(); + session.settle(Duration::from_millis(200)); + insta::assert_snapshot!( + "delegation_approval_prompt", + normalize_for_input_snapshot(session.screen_contents()) + ); + + session.send_key(Key::Char('1')).unwrap(); + session + .wait_for( + |screen| { + screen.contains("delegated to mock-model-alt") + && screen.contains( + "parent task identity › mock:request-permission:write-child-file is waiting on you", + ) + }, + TIMEOUT, + ) + .expect("the parent names both sessions while the child waits"); + session.settle(Duration::from_millis(200)); + let parent = session.screen_contents(); + let request_line = parent + .lines() + .find(|line| line.contains("● ") && line.contains("is waiting on you")) + .unwrap_or_else(|| panic!("request line missing:\n{parent}")); + assert!(request_line.contains("alt + down"), "{parent}"); + assert!( + !regex::Regex::new("[0-9a-f]{8}-[0-9a-f]{4}") + .unwrap() + .is_match(&parent), + "sessions are named, not identified by raw IDs:\n{parent}" + ); + + session.send_key(Key::AltDown).unwrap(); + session + .wait_for_text("Would you like to allow", TIMEOUT) + .unwrap(); + session + .wait_for_text("alt + up to parent", TIMEOUT) + .expect("the child shows the way back to its parent"); + + session.send_key(Key::Char('1')).unwrap(); + session + .wait_for_text("Permission granted with option: allow", TIMEOUT) + .unwrap(); + session.send_key(Key::AltUp).unwrap(); + session + .wait_for( + |screen| { + screen.contains("result from mock-model-alt") + && screen.contains("parent task identity") + }, + TIMEOUT, + ) + .expect("the result block names the child in the parent"); + session + .wait_for_text("Delegation continuation received", TIMEOUT) + .unwrap(); + assert!( + session.history_contents().contains("returns to mock-model"), + "the result block says where it goes" + ); + + session.submit_input("/sessions").unwrap(); + session + .wait_for(|screen| screen.contains("└─ "), TIMEOUT) + .expect("the child is listed under its parent"); + session.settle(Duration::from_millis(200)); + let screen = session.screen_contents(); + assert!(!screen.contains("(parent"), "{screen}"); + // Only the list itself; the transcript above it is covered elsewhere. + let list = screen + .lines() + .skip_while(|line| !line.contains("Sessions 2")) + .collect::>() + .join("\n"); + insta::assert_snapshot!( + "delegation_session_tree", + normalize_for_input_snapshot(list) + ); +} + +/// Start a different-kind child that waits on a permission, and approve it. +fn start_waiting_child(session: &mut TuiSession) { + session + .submit_input("/delegate mock-model-alt mock:request-permission:write-child-file") + .unwrap(); + session + .wait_for_text("start a mock-model-alt session", TIMEOUT) + .unwrap(); + session.send_key(Key::Char('1')).unwrap(); + session + .wait_for_text("is waiting on you", TIMEOUT) + .expect("the parent says the child waits"); + session.settle(Duration::from_millis(200)); +} + +#[test] +fn alt_down_reaches_a_waiting_child_even_with_a_draft_in_the_parent() { + let mut session = spawn(true); + start_waiting_child(&mut session); + session.type_input("my unsent draft").unwrap(); + session + .wait_for_text("my unsent draft", TIMEOUT) + .expect("the draft is in the parent's prompt"); + session.send_key(Key::AltDown).unwrap(); + session + .wait_for_text("Would you like to allow", TIMEOUT) + .expect("alt + down opens the waiting child"); + assert!( + !session.screen_contents().contains("my unsent draft"), + "the draft stays with the parent:\n{}", + session.screen_contents() + ); + session.send_key(Key::Char('1')).unwrap(); + session + .wait_for_text("Permission granted with option: allow", TIMEOUT) + .unwrap(); + session.send_key(Key::AltUp).unwrap(); + session + .wait_for_text("Delegation continuation received", TIMEOUT) + .expect("the parent gets the child's result"); + session + .wait_for_text("my unsent draft", TIMEOUT) + .expect("the parent's draft comes back with it"); + session.settle(Duration::from_millis(300)); + let screen = session.screen_contents(); + let lines = screen.lines().collect::>(); + let draft = lines + .iter() + .rposition(|line| line.contains("my unsent draft")) + .unwrap_or_else(|| panic!("draft missing:\n{screen}")); + let last_answer = lines + .iter() + .rposition(|line| line.contains("Delegation continuation received")) + .expect("the parent's answer to the result"); + assert!( + draft > last_answer && screen.matches("my unsent draft").count() == 1, + "the draft is still unsent, in the parent's prompt:\n{screen}" + ); +} + +#[test] +fn alt_up_in_a_top_level_session_leaves_the_prompt_alone() { + let mut session = spawn(true); + session.settle(Duration::from_millis(300)); + let before = session.screen_contents(); + session.send_key(Key::AltUp).unwrap(); + // A typed sentinel shows that the key has been handled before comparing. + session.type_input("zq").unwrap(); + session.wait_for_text("zq", TIMEOUT).unwrap(); + let after = session.screen_contents(); + assert_eq!( + after.matches("parent task identity").count(), + before.matches("parent task identity").count(), + "alt + up does not recall the last prompt:\n{after}" + ); +} + +#[test] +fn a_session_that_starts_with_a_delegation_is_titled_by_its_task() { + let mut session = spawn_fresh(40, 130); + session + .submit_input("/delegate mock-model inspect the parser") + .unwrap(); + session + .wait_for_text("result from mock-model", TIMEOUT) + .unwrap(); + session + .wait_for_text("Delegation continuation received", TIMEOUT) + .expect("the parent answers the delivered result"); + session.settle(Duration::from_millis(300)); + session.submit_input("/sessions").unwrap(); + session + .wait_for(|screen| screen.contains("└─ "), TIMEOUT) + .expect("the child is listed under its parent"); + session.settle(Duration::from_millis(200)); + let screen = session.screen_contents(); + let rows = screen + .lines() + .skip_while(|line| !line.contains("Sessions 2")) + .collect::>(); + let parent = rows + .iter() + .find(|line| line.contains("(current)")) + .unwrap_or_else(|| panic!("parent row missing:\n{screen}")); + assert!(parent.contains("inspect the parser"), "{screen}"); + assert!( + rows.iter() + .all(|row| !row.contains("[Nori delegation result]")), + "{screen}" + ); + let child = rows + .iter() + .find(|line| line.contains("└─ ")) + .unwrap_or_else(|| panic!("child row missing:\n{screen}")); + assert!( + child.contains("mock-model "), + "agents are named by slug:\n{screen}" + ); + assert!( + child.contains(" done"), + "a child that finished its task is done:\n{screen}" + ); + assert!(rows.iter().all(|row| !row.contains("closed")), "{screen}"); +} + +#[test] +fn the_child_breadcrumb_fits_one_row_of_an_80_column_terminal() { + let mut session = spawn_fresh(30, 80); + session + .submit_input("parent task identity with a long title for the breadcrumb") + .unwrap(); + session + .wait_for_text("parent final answer", TIMEOUT) + .unwrap(); + start_waiting_child(&mut session); + session.send_key(Key::AltDown).unwrap(); + session + .wait_for_text("Would you like to allow", TIMEOUT) + .unwrap(); + session + .wait_for_text("breadcrumb › ", TIMEOUT) + .expect("the child shows where it sits under its parent"); + session.settle(Duration::from_millis(200)); + let screen = session.screen_contents(); + let breadcrumb = screen + .lines() + .find(|line| line.contains("parent task") && line.contains(" › ")) + .unwrap_or_else(|| panic!("the breadcrumb is one row from the parent:\n{screen}")); + assert!( + breadcrumb + .trim_end() + .ends_with("› mock:request-permission:write-child-file"), + "the current name stays whole; the key gives way first:\n{screen}" + ); +} + +#[test] +fn the_session_list_keeps_names_with_a_shared_prefix_apart_at_80_columns() { + let mut session = spawn_fresh(30, 80); + session + .submit_input("shared prefix for the parser review: parent side") + .unwrap(); + session + .wait_for_text("parent final answer", TIMEOUT) + .unwrap(); + session + .submit_input( + "/delegate mock-model-alt shared prefix for the parser review: child side mock:request-permission:z", + ) + .unwrap(); + session + .wait_for_text("start a mock-model-alt session", TIMEOUT) + .unwrap(); + session.send_key(Key::Char('1')).unwrap(); + session.wait_for_text("is waiting on you", TIMEOUT).unwrap(); + session.settle(Duration::from_millis(200)); + session.send_key(Key::Alt('s')).unwrap(); + session + .wait_for( + |screen| { + screen.contains("Sessions 2") + && screen.contains("(current)") + && screen.contains("parent side") + && screen.contains("permission:z") + }, + TIMEOUT, + ) + .unwrap(); + let screen = session.screen_contents(); + let list = &screen[screen.find("Sessions 2").expect("list header")..]; + let parent = list + .lines() + .find(|line| line.contains("parent side")) + .unwrap_or_else(|| panic!("the parent row keeps its end:\n{screen}")); + let child = list + .lines() + .find(|line| line.contains("└─") && line.contains("permission:z")) + .unwrap_or_else(|| panic!("the child row keeps its end:\n{screen}")); + for row in [parent, child] { + assert!(row.contains("shared"), "{screen}"); + assert!( + row.matches('…').count() <= 1, + "names are cut once:\n{screen}" + ); + } + assert_eq!( + child.matches('…').count(), + 1, + "the long child name is cut:\n{screen}" ); + assert!(parent.contains("(current)"), "{screen}"); } diff --git a/nori-rs/tui-pty-e2e/tests/host_attach.rs b/nori-rs/tui-pty-e2e/tests/host_attach.rs index 4fa40fa4f..602190d00 100644 --- a/nori-rs/tui-pty-e2e/tests/host_attach.rs +++ b/nori-rs/tui-pty-e2e/tests/host_attach.rs @@ -789,7 +789,11 @@ fn host_list_truncates_tty_title_without_losing_piped_title() { .lines() .find(|line| line.contains(&id)) .expect("session row"); - assert!(row.trim_end().ends_with('…'), "{screen}"); + assert!(row.contains("Long title") && row.contains('…'), "{screen}"); + assert!( + row.trim_end().ends_with("ID column"), + "a cut title keeps its end: {screen}" + ); assert!(!screen.contains("continuation text"), "{screen}"); } @@ -835,14 +839,12 @@ fn delegated_child_in_host_list_preserves_metadata_columns_and_can_be_opened() { .any(|row| row.get(82..).unwrap().contains("child-column-check")), "{listing}" ); - client.wait_for_text("needs your answer", TIMEOUT).unwrap(); + client.wait_for_text("is waiting on you", TIMEOUT).unwrap(); let parent_screen = client.screen_contents(); - for row in &rows { - assert!( - parent_screen.contains(row.get(..36).unwrap()), - "notice names parent and child: {parent_screen}" - ); - } + assert!( + parent_screen.contains("child-column-ch") && parent_screen.contains("parent host task"), + "notice names child and parent by their tasks: {parent_screen}" + ); client.send_key(Key::AltDown).unwrap(); client.wait_for_text("child-column-check", TIMEOUT).unwrap(); client.wait_for_text("Allow", TIMEOUT).unwrap(); diff --git a/nori-rs/tui-pty-e2e/tests/session_list.rs b/nori-rs/tui-pty-e2e/tests/session_list.rs index 733e43321..f39fcba6c 100644 --- a/nori-rs/tui-pty-e2e/tests/session_list.rs +++ b/nori-rs/tui-pty-e2e/tests/session_list.rs @@ -227,7 +227,7 @@ fn a_background_request_is_named_and_one_key_jumps_to_it_for_an_answer() { session .wait_for( |screen| { - screen.contains("waiting on you · approve: rm -rf target/debug") + screen.contains("waiting on you · approve: rm -rf") && screen.contains("(+1 more)") && screen.contains("to jump") }, diff --git a/nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_approval_prompt.snap b/nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_approval_prompt.snap new file mode 100644 index 000000000..ba2b02f0a --- /dev/null +++ b/nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_approval_prompt.snap @@ -0,0 +1,20 @@ +--- +source: tui-pty-e2e/tests/delegation.rs +expression: normalize_for_input_snapshot(session.screen_contents()) +--- +• Mock ACP options: Model=Mock Default Model, Thought Level=Medium (/config to change) + +› parent task identity + +• parent final answer + + Would you like to start a mock-model-alt session for your task? + + asked by you, with /delegate + runs on mock-model-alt · a different agent from this session + task mock:request-permission:write-child-file + +› 1. Yes, start it + 2. No, decline + + Press enter to confirm or esc to decline diff --git a/nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_session_tree.snap b/nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_session_tree.snap new file mode 100644 index 000000000..ce2440715 --- /dev/null +++ b/nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_session_tree.snap @@ -0,0 +1,15 @@ +--- +source: tui-pty-e2e/tests/delegation.rs +expression: normalize_for_input_snapshot(list) +--- + Sessions 2 · 1 ready tab: waiting only · type to search + + All waiting on you + + Session Agent Status + › ○ parent task identity (current) mock-model ready + Permission granted with option: allow + └─ · mock:request-permission:write-child-file mock-model-alt done + Permission granted with option: allow + + ↑↓ move enter open ctrl+d close tab waiting on you esc close diff --git a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__background_request_line.snap b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__background_request_line.snap index 67cd7ac6b..a713bbcc7 100644 --- a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__background_request_line.snap +++ b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__background_request_line.snap @@ -8,7 +8,7 @@ expression: normalize_for_input_snapshot(session.screen_contents()) • alpha agent answer - ● mock:request-permission… is waiting on you · approve: rm -rf target/debug (+1 more) · alt + down to jump + ● mock:request-permi…m -rf target/debug is waiting on you · approve: rm -rf… (+1 more) · alt + down to jump 2 waiting on you · 1 ready › [DEFAULT_PROMPT] diff --git a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_failed_row.snap b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_failed_row.snap index d59be0509..9211bf08c 100644 --- a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_failed_row.snap +++ b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_failed_row.snap @@ -19,9 +19,9 @@ expression: normalize_for_input_snapshot(session.screen_contents()) All waiting on you Session Agent Status - ○ alpha question (current) Mock ACP ready + ○ alpha question (current) mock-model ready alpha agent answer - › ✕ doomed question Mock ACP failed + › ✕ doomed question mock-model failed agent exited · resume available ↑↓ move enter open ctrl+r resume ctrl+d close tab waiting on you esc close diff --git a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_fork_under_parent.snap b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_fork_under_parent.snap index cd1ded8b7..1347e00da 100644 --- a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_fork_under_parent.snap +++ b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_fork_under_parent.snap @@ -8,7 +8,7 @@ expression: normalize_for_input_snapshot(screen) • alpha agent answer - ● (parent PARENTID) mock:… is waiting on you · approve: rm -rf target/debug · alt + down to jump + ● parent question › mock:request-p…f target/debug is waiting on you · approve: rm -rf… · alt + down to jump 1 waiting on you · 1 ready Sessions 2 · 1 waiting on you · 1 ready tab: waiting only · type to search @@ -16,9 +16,9 @@ expression: normalize_for_input_snapshot(screen) All waiting on you Session Agent Status - › ● parent question (current) Mock ACP waiting on you + › ● parent question (current) mock-model waiting on you alpha agent answer - └─ ● mock:request-permission:rm -rf target/debug Mock ACP waiting on you + └─ ● mock:request-permission:rm -rf target/debug mock-model waiting on you approve: rm -rf target/debug ↑↓ move enter open ctrl+d close tab waiting on you esc close diff --git a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_three_sessions.snap b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_three_sessions.snap index 772f33973..4065a6e6e 100644 --- a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_three_sessions.snap +++ b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_three_sessions.snap @@ -6,7 +6,7 @@ expression: normalize_for_input_snapshot(screen) • alpha agent answer - ● mock:request-permission… is waiting on you · approve: rm -rf target/debug · alt + down to jump + ● mock:request-permission:rm -rf target/debug is waiting on you · approve: rm -rf targ… · alt + down to jump 1 waiting on you · 2 ready Sessions 3 · 1 waiting on you · 2 ready tab: waiting only · type to search @@ -14,11 +14,11 @@ expression: normalize_for_input_snapshot(screen) All waiting on you Session Agent Status - ○ alpha question Mock ACP ready + ○ alpha question mock-model ready alpha agent answer - ● mock:request-permission:rm -rf target/debug Mock ACP Alt waiting on you + ● mock:request-permission:rm -rf target/debug mock-model-alt waiting on you approve: rm -rf target/debug - › ○ gamma question (current) Mock ACP ready + › ○ gamma question (current) mock-model ready alpha agent answer ↑↓ move enter open ctrl+d close tab waiting on you esc close diff --git a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_waiting_on_you.snap b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_waiting_on_you.snap index 3b39d1d4b..33673b7c7 100644 --- a/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_waiting_on_you.snap +++ b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_waiting_on_you.snap @@ -6,7 +6,7 @@ expression: normalize_for_input_snapshot(session.screen_contents()) • alpha agent answer - ● mock:request-permission… is waiting on you · approve: rm -rf target/debug · alt + down to jump + ● mock:request-permission:rm -rf target/debug is waiting on you · approve: rm -rf targ… · alt + down to jump 1 waiting on you · 2 ready Sessions 3 · 1 waiting on you · 2 ready tab: all sessions · type to search @@ -14,7 +14,7 @@ expression: normalize_for_input_snapshot(session.screen_contents()) All waiting on you Session Agent Status - › ● mock:request-permission:rm -rf target/debug Mock ACP Alt waiting on you + › ● mock:request-permission:rm -rf target/debug mock-model-alt waiting on you approve: rm -rf target/debug ↑↓ move enter open ctrl+d close tab all sessions esc close diff --git a/nori-rs/tui/docs.md b/nori-rs/tui/docs.md index 862ce4399..78aa0e469 100644 --- a/nori-rs/tui/docs.md +++ b/nori-rs/tui/docs.md @@ -921,9 +921,10 @@ a binding). | Action (`[tui.hotkeys]`) | Default | Notes | | --- | --- | --- | -| `previous_session` / `next_session` | `alt+,` / `alt+.` | Wraps at both ends of the navigation order and skips closed sessions | -| `next_waiting_session` | `alt+down` | Only with an empty prompt; next session after the active one that is waiting on you | +| `previous_session` / `next_session` | `alt+,` / `alt+.` | Wraps at both ends of the navigation order and skips closed and done sessions | +| `next_waiting_session` | `alt+down` | Shows the next session after the active one that is waiting on you, even with a draft (the draft stays in the parked widget's composer). With nothing waiting, an empty prompt consumes the key and a draft passes it on to the composer | | `open_session_list` | `alt+s` | Needs the composer in front | +| `parent_session` | `alt+up` | On a delegated child (record source `Session` with a parent) shows the parent's widget; elsewhere it is consumed and does nothing, so it never reaches history recall | The Hotkeys view lists these actions only with the flag (`HotkeyAction::is_multi_session`). @@ -934,16 +935,27 @@ default, behind `LEFT_ON_EMPTY_PROMPT_OPENS_SESSION_LIST`), `open_session_list`, or `/sessions` (hidden from the slash popup without the flag). Left with text in the prompt still moves the cursor. -- Each row is a status glyph and title, the agent with its provider tone, and - a status word, with a preview line below. The title is the agent's prompt - summary, else the session's first user message as seen in - `UserMessageChunk` updates (so a prompt sent by a remote-control client also - titles it), else the widget's first prompt, cut to its first line. Previews +- Each row is a status glyph and title, the agent slug (the name `/delegate` + takes; "Nori Cloud" in cloud mode) with its provider tone, and a status + word, with a preview line below. The title is the agent's prompt summary, + else the session's first user message as seen in `UserMessageChunk` updates + (so a prompt sent by a remote-control client also titles it), else the + widget's first prompt, cut to its first line. Rows carry that whole line; + the TITLE column (`cut_middle`) cuts it once, in the middle, to the column + width, so sibling names sharing a long prefix keep their distinct ends. + Notifications that name a session still use a 60-character cut + (`session_title` with `TITLE_CHARS`). A user-origin + `DelegationChanged` that arrives before any prompt (a `/delegate` sent first) + titles the session with the first line of its task, the same rule the host + journal uses, so `nori attach` and `nori host ls` name it alike. A + delegation result prompt never counts as the first message. Previews come from [`session_preview.rs`](src/session_preview.rs) using only session events, never a call to the agent, in priority order: pending request - (`approve: ...`), running tool, how the session ended, then the latest line - of agent text. Agent text after a request or tool starts a new line, so the - preview never glues the two together. + (`approve: ...`), running tool, how the session ended (connection lost, + spawn failure, or timeout; an ordinary close or shutdown adds nothing, since + the status column already says so), then the latest line of agent text. + Agent text after a request or tool starts a new line, so the preview never + glues the two together. - The header counts sessions by status. Tab toggles a "waiting on you" filter and back (the footer then offers "tab all sessions"); typing filters by title or agent; Esc clears the query first, then closes; Enter shows the selected @@ -953,13 +965,18 @@ in the prompt still moves the cursor. - Ctrl+D closes the selected session through `AppEvent::CloseSession`. A `working`, `waiting on you`, or `starting` row is armed by the first press (footer "ctrl+d again to close") and closed by the second; any other key - disarms it. On a `closed` row Ctrl+D sends `AppEvent::RemoveSession` + disarms it. On a `closed` or `done` row Ctrl+D sends `AppEvent::RemoveSession` instead. The footer hint reads "ctrl+d close" or "ctrl+d remove". Rows for manager-only descendants (negative keys) cannot be closed here. - Children are indented under their parent using the session manager's record - parent, with the shared picker's tree rows. A top-level row's status word and - tone, and its glyph, follow its **session family** status, so a parent reads - "waiting on you" when a child does. Manager sessions that descend from a listed session + parent, with the shared picker's tree rows; titles carry no parent-ID + prefix. A top-level row's status word and tone, and its glyph, follow its + **session family** status, so a parent reads "waiting on you" when a child + does. Status tones come from `session_status::status_tone`, shared with + `nori attach`: waiting on you amber, working cyan, ready green, failed red, + done in the default color, starting and closed muted (closed and done titles + are muted). `nori host ls` follows the same split: done plain, closed dimmed. + Manager sessions that descend from a listed session but have no TUI view are listed under their parent with negative keys that cannot collide with a generation; they are not navigation targets. Delegated children are adopted as real parked widgets by @@ -973,22 +990,42 @@ in the prompt still moves the cursor. open it replaces the rows in place, keeping the selection on the same session. In cloud mode every session's agent reads "Nori Cloud". -Status words live in [`session_status.rs`](src/session_status.rs): `starting`, +Status words and their tones live in [`session_status.rs`](src/session_status.rs): `starting`, `working`, `waiting on you` (`WAITING_ON_YOU_LABEL`, the **session status** `WaitingOnYou`), `ready`, `ready · new` (finished a turn while off screen, until -it is viewed), `failed`, and `closed`. Statuses come from the harness -`SessionManager`; a widget without a managed record reads `starting`. Two lines -drawn above the bottom pane (`ChatWidget::set_session_lines`) stay visible -while a view is open: - +it is viewed), `failed`, `closed` (closed or shut down by the user), and +`done` (a delegated child whose task finished). Code that asks whether a +session has ended uses `SessionStatus::is_closed()`, which covers both closed +and done. Statuses come from the harness `SessionManager`; a widget without a +managed record reads `starting`. Lines drawn above the bottom pane +(`ChatWidget::set_session_lines`) stay visible while a view is open. +`App::refresh_session_overview` receives the terminal width from the draw +handler and fits each line to one row, two cells narrower than the terminal: + +- a breadcrumb, only while a delegated child is on screen: the full path from + the top-level session, ` · › … › · · to + parent`, where the key is the `parent_session` binding (omitted when + unbound). The path walks `SessionRecord.parent` while the record's source is + `Session`, so a fork ends it. Names come from `App::session_name` whole (the + title in this TUI, else the replay journal title's first line, else + `nori_protocol::UNTITLED_SESSION_NAME`) and are cut only by the builder; - a background-request line, naming the first off-screen session waiting on - you by title (` is waiting on you`), its request, `+N more` when - others wait, and the `next_waiting_session` key. The title, including any - parent attribution prefix, shares one bounded label budget; the request text - is separately shortened so the line fits one row of a 100-column terminal; + you with an amber `●` (`<title> is waiting on you`, or `<parent> › <child>` + for a delegated child), its request, `(+N more)` when others wait, and the + `next_waiting_session` key; - a status line counting sessions by their own status, most urgent first - (waiting on you, failed, working, starting, ready; closed is omitted), shown - only with two or more sessions. + (waiting on you, failed, working, starting, ready; closed and done are + omitted), shown only with two or more sessions. + +Both path lines are built by [`session_path.rs`](src/session_path.rs), which +`nori attach` shares. It holds pure, width-aware builders: + +| Builder | Fitting rules | +| --- | --- | +| `breadcrumb_line(path, status, key, width)` | Never drops the top-level session or the current one. Tries layouts in order (whole path with key, middle steps elided to one `…` with key, whole path without key, elided without key, elided without key or agent labels) and takes the first where the current name is whole and every other name keeps at least min(its width, 8) cells. The last layout always renders, giving the current name priority while others keep at least 4 cells. So the key gives way before the current name is cut, and the current name is cut last; a final clip guarantees the width. The local TUI passes an empty status and ` · <key> to parent` | +| `waiting_line(path_names, request, more, jump_key, width)` | Names come first. The request text gets the cells left after the full names when it fits there or at least 20 cells remain; otherwise it is cut to 20 cells only if each name can still keep 16, and dropped if not | +| `fit(text, cells)` | Cuts by display cells, ending in `…` | +| `fit_name(text, cells)` | Cuts by display cells in the middle (start, `…`, end), so names sharing a long prefix stay distinct; used for every session name on these lines. Delegates to `nori_tui_components::text::truncate_middle`, the same cut the session lists' TITLE columns use | While an `/agent` candidate is preparing, a dim `Preparing <agent>…` line sits above these. With the flag this replaces the history cell that single-session @@ -1003,7 +1040,7 @@ Ctrl+D (list) / local /close ──> AppEvent::CloseSession{generation} | mark_closed_by_user + SessionManager::close | on screen? show next open session v -row reads `closed` ── Ctrl+D ──> AppEvent::RemoveSession ──> deck.remove +row reads `closed`/`done` ── Ctrl+D ──> AppEvent::RemoveSession ──> deck.remove cloud /close ──> session/close ──> SessionEnded(Closed) ──> AppEvent::SessionClosed{generation} ──> App::on_session_closed @@ -1059,38 +1096,81 @@ reflow. `/delegate <agent> <task>` is the user entry point in the local and attached frontends. It is enabled only with `multi_session`; the session list does not -start delegations. The shared [parser and labels](src/delegation.rs) keep -syntax and parent/child attribution consistent. The +start delegations. [`delegation.rs`](src/delegation.rs) holds the command +parser and all delegation presentation shared by both frontends; naming and +status words come from `nori_protocol`'s delegation helpers so the harness +notices, result prompts, and terminal text agree. The [chat-widget adapter](src/chatwidget/delegation.rs) calls the harness manager -and renders its `DelegationChanged` events. Different-kind requests expose -Start and Decline; same-kind requests start immediately. These approval choices -control child creation, separately from a child's later ACP permission request. +and renders its `DelegationChanged` events. + +Each non-approval `DelegationChanged` adds a `DelegationCell` history cell. +A cell is printed once and never updates, so a running child's card says +`started` rather than `working` (the protocol's status words are unchanged). +On screen it stays compact so many delegations remain readable; the +transcript view (`open_transcript`) shows the full brief, full result, and +child ID. + +| Status | On screen | +| --- | --- | +| running | `↳ <requester> delegated to <agent> · <child name> · started`, plus `<transcript key> shows the brief` | +| completed | `○ result from <agent> · <child name> · done`, up to six result lines, each wrapped under the `▏` rail (then `… N more lines`), and `returns to <parent agent> on its own · its history: <session list key>` | +| failed | `✕ <agent> · <child name> · failed · <reason>` and `sent to <parent agent> as a failure` | +| declined, cancelled | `✕ delegation to <agent> · <child name> · declined by you` / `cancelled · <reason>` | + +The card header is width-aware: it measures the other spans and cuts the +child's whole first task line (`nori_protocol::session_full_name`) in the +middle with `session_path::fit_name` to the remaining room, never below a small +minimum, so the header stays one row at 80 columns and long sibling names stay +apart. The requester is `you` for origin `user` and the parent agent for origin +`agent`. Key hints come from `DelegationHints`, filled from the configured +`open_transcript` and `open_session_list` bindings; an unbound key, or the +attached frontend, hides its hint. + +Same-kind requests start immediately. Different-kind requests open a selection +view built from `approval_lines`: a question worded by origin ("Would you like +<parent agent> to start a <agent> session?" or "Would you like to start a +<agent> session for your task?"), then `asked by`, `runs on`, and `task` rows. +The choices are "Yes, start it" and "No, decline"; Esc (dismiss) declines. +These choices control child creation, separately from a child's later ACP +permission request. + +The result prompt the manager delivers to the parent appears as a +`UserHistoryCell`. When `nori_protocol::delegation_result_summary` recognizes +it (a `[Nori delegation result]` first line followed by a `Child session: ` +line, or ending in ` · declined`; a user message that only begins with the +header stays whole), +[`history_cell`](src/history_cell/mod.rs) shows it on screen as one +line, `› delegation result from <agent> · <name> · <status> · delivered to this +session`, because the result block was already shown when the child ended; the +transcript view keeps the exact text the agent received. The line comes from +`delegation::delivered_result_spans`, shared with `nori attach`: it reads the +parts back with `nori_protocol::delegation_result_parts`, drops +` · delivered to this session` first when the row is too narrow, then cuts the +name in the middle with `session_path::fit_name`, so it fits one row at 80 +columns. The header carries the child's whole first task line, so the name is +cut only once, by width. Children receive navigable parked widgets without replacing the parent on screen. Their stream, history, pending permissions, and session-scoped events follow the normal session-deck path. Alt+Down (`next_waiting_session`) opens the next session needing the user, where the ordinary permission UI answers the -child. Parent notices identify both child and parent and do not open the -child's permission popup in the parent. Child list labels put the parent -identity before the task title so title truncation preserves attribution. Closed completed children keep -inspectable history; ending their process must not be interpreted as exiting -Nori. When [startup replay](src/chatwidget/event_handlers.rs) reaches a closed -child widget with no live handle, it applies the history metadata without +child, and Alt+Up (`parent_session`) returns. Parent notices name both +sessions readably and do not open the child's permission popup in the parent. +Completed children read `done` and keep inspectable history; ending their process must +not be interpreted as exiting Nori. When +[startup replay](src/chatwidget/event_handlers.rs) reaches a closed child +widget with no live handle, it applies the history metadata without requesting custom prompts. If a retained handle instead races normal teardown, [command submission](src/chatwidget/helpers.rs) suppresses only the harness's classified expected transport closure. Real backend errors and unexpected transport loss still follow the originating session's failure route. Result delivery is manager-owned and automatically prompts the parent. The -terminal renders attributed status/result text; it neither approves the result -nor drives completion. Explicit parent close cancels descendants; a crashed -parent can be resumed with Ctrl+R under the same conversation ID to receive -held results, including redelivery when the previous parent process admitted -but never acknowledged a result turn. See the [manager lifecycle](../harness/docs.md#delegation-between-managed-sessions). - -The initial rendering is intentionally text and existing selection components. -Dedicated delegation/result cards and further hierarchy styling belong to the -later presentation workstream. +terminal renders the result; it neither approves the result nor drives +completion. Explicit parent close cancels descendants; a crashed parent can be +resumed with Ctrl+R under the same conversation ID to receive held results, +including redelivery when the previous parent process admitted but never +acknowledged a result turn. See the [manager lifecycle](../harness/docs.md#delegation-between-managed-sessions). #### Host attachment @@ -1409,9 +1489,13 @@ part of the public harness protocol. (`SessionClosed`, `LoopIteration`, `CloseSession`, `RemoveSession`) carry a session generation. Acting on "the active widget" instead would close or replace the wrong session. -- A `closed` session is still in the deck. Navigation, the status-line counts, - and "next open session" filter it out by status; code that walks the deck - directly sees it. +- A `closed` or `done` session is still in the deck. Navigation, the + status-line counts, and "next open session" filter it out with + `SessionStatus::is_closed()`; code that walks the deck directly sees it, and + a check against `Closed` alone misses finished delegated children. +- The queued-message preview in the bottom pane advertises `⌥↑ edit`, but no + key handler edits a queued message; with `multi_session`, Alt+Up is the + `parent_session` key. - `nori-config` is the source of approval and sandbox policy; ACP session config options remain ACP schema values. - `-p` belongs to the top-level CLI as `--print`. The TUI's own flag set must not diff --git a/nori-rs/tui/src/app/event_handling.rs b/nori-rs/tui/src/app/event_handling.rs index a8dee735c..9b618bdae 100644 --- a/nori-rs/tui/src/app/event_handling.rs +++ b/nori-rs/tui/src/app/event_handling.rs @@ -110,7 +110,7 @@ impl App { } TuiEvent::Draw => { self.adopt_delegated_sessions(tui); - self.refresh_session_overview(); + self.refresh_session_overview(tui.terminal.size()?.width); self.chat_widget.pre_draw_tick(); self.chat_widget.maybe_post_pending_notification(tui); self.post_parked_session_notifications(tui); diff --git a/nori-rs/tui/src/app/session_keys.rs b/nori-rs/tui/src/app/session_keys.rs index 27a17de82..2b34b134a 100644 --- a/nori-rs/tui/src/app/session_keys.rs +++ b/nori-rs/tui/src/app/session_keys.rs @@ -34,16 +34,37 @@ impl App { tui.frame_requester().schedule_frame(); return true; } - if pressed(HotkeyAction::NextWaitingSession) && self.chat_widget.composer_is_empty() { - self.show_next_waiting_session(); - tui.frame_requester().schedule_frame(); - return true; - } + // A draft stays in its session's prompt, so the jump never loses it. + // With nothing waiting, a typed draft keeps the key for the composer. + let next_waiting = pressed(HotkeyAction::NextWaitingSession); + let parent_session = pressed(HotkeyAction::ParentSession); let direction = if pressed(HotkeyAction::PreviousSession) { - Direction::Previous + Some(Direction::Previous) } else if pressed(HotkeyAction::NextSession) { - Direction::Next + Some(Direction::Next) } else { + None + }; + if next_waiting + && (self.show_next_waiting_session() || self.chat_widget.composer_is_empty()) + { + tui.frame_requester().schedule_frame(); + return true; + } + // Outside a delegated child there is no parent; the key does nothing. + if parent_session { + if let Some(parent) = self.on_screen_parent() + && let Some(target) = self + .session_facts() + .into_iter() + .find(|fact| fact.conversation_id == Some(parent)) + { + self.show_session(target.generation); + tui.frame_requester().schedule_frame(); + } + return true; + } + let Some(direction) = direction else { return false; }; self.step_session(direction); diff --git a/nori-rs/tui/src/app/session_lifecycle.rs b/nori-rs/tui/src/app/session_lifecycle.rs index 22070ad74..46f175081 100644 --- a/nori-rs/tui/src/app/session_lifecycle.rs +++ b/nori-rs/tui/src/app/session_lifecycle.rs @@ -44,7 +44,7 @@ impl App { let closed: Vec<SessionGeneration> = self .session_facts() .into_iter() - .filter(|fact| fact.status == SessionStatus::Closed) + .filter(|fact| fact.status.is_closed()) .map(|fact| fact.generation) .collect(); self.session_deck @@ -68,7 +68,10 @@ impl App { ); return; } - if self.session_status(generation) == Some(SessionStatus::Closed) { + if self + .session_status(generation) + .is_some_and(SessionStatus::is_closed) + { return; } let grace = if self.cloud_mode { @@ -109,7 +112,9 @@ impl App { /// Drop a closed session from the deck and the session list. pub(super) fn remove_session(&mut self, generation: SessionGeneration) { if generation == self.chat_widget.session_generation() - || self.session_status(generation) != Some(SessionStatus::Closed) + || !self + .session_status(generation) + .is_some_and(SessionStatus::is_closed) { return; } @@ -180,7 +185,7 @@ impl App { if !parked.widget.is_closed_by_user() && let Some(id) = parked.widget.managed_conversation_id() && self.session_manager.get(&id).is_some_and(|record| { - !matches!(record.status, SessionStatus::Closed | SessionStatus::Failed) + !(record.status.is_closed() || record.status == SessionStatus::Failed) }) { parked.widget.mark_closed_by_user(); diff --git a/nori-rs/tui/src/app/session_overview.rs b/nori-rs/tui/src/app/session_overview.rs index 278db22f4..6422df42c 100644 --- a/nori-rs/tui/src/app/session_overview.rs +++ b/nori-rs/tui/src/app/session_overview.rs @@ -18,20 +18,11 @@ use crate::session_status::status_word; /// Longest title shown for a session that has no summary yet. const TITLE_CHARS: i32 = 60; - -/// Longest title and request text on the background-request line, so the -/// line fits one row of a 100-column terminal. -const REQUEST_LINE_TITLE_CHARS: i32 = 24; -const REQUEST_LINE_REQUEST_CHARS: i32 = 28; +/// For lines that fit names to the terminal width themselves. +pub(super) const WHOLE_NAME: i32 = i32::MAX; fn cut(text: &str, limit: i32) -> String { - let limit = usize::try_from(limit).unwrap_or(0); - if text.chars().count() > limit { - let kept: String = text.chars().take(limit.saturating_sub(1)).collect(); - format!("{kept}…") - } else { - text.to_string() - } + nori_protocol::shorten_name(text, limit) } /// One session as the overview sees it. @@ -132,19 +123,30 @@ impl App { rows } - /// The title a session is listed under: the agent's summary, else the - /// first prompt, cut to `limit` characters. - fn session_title(&self, generation: SessionGeneration, limit: i32) -> Option<String> { + /// The title a session is listed under: the first line of the agent's + /// summary, else of the first prompt. + fn session_full_title(&self, generation: SessionGeneration) -> Option<String> { let widget = self.widget_for(generation); self.session_previews .title(generation) .or_else(|| widget.and_then(ChatWidget::first_prompt_text)) - .map(|title| cut(title.lines().next().unwrap_or_default().trim(), limit)) + .map(|title| title.lines().next().unwrap_or_default().trim().to_owned()) .filter(|title| !title.is_empty()) } + /// The session's title cut to `limit` characters. + pub(super) fn session_title( + &self, + generation: SessionGeneration, + limit: i32, + ) -> Option<String> { + self.session_full_title(generation) + .map(|title| cut(&title, limit)) + } + + /// The list cuts titles to its column width itself. pub(super) fn session_rows_title(&self, generation: SessionGeneration) -> Option<String> { - self.session_title(generation, TITLE_CHARS) + self.session_full_title(generation) } /// Sessions in the manager that descend from a session this TUI shows but @@ -189,20 +191,6 @@ impl App { let title = self .session_rows_title(fact.generation) .unwrap_or_else(|| "New session".to_string()); - let title = fact - .conversation_id - .and_then(|id| self.session_manager.get(&id)) - .filter(|record| record.source == nori_harness::session_manager::SessionSource::Session) - .and_then(|record| record.parent) - .map_or_else( - || title.clone(), - |parent| { - format!( - "(parent {}) {title}", - parent.to_string().chars().take(8).collect::<String>() - ) - }, - ); // A parent speaks for its family: if a child needs the user, so does // the parent row. let shown_status = if depth == 0 { @@ -213,7 +201,7 @@ impl App { SessionRow { generation: fact.generation, title, - agent: self.agent_display_name(&agent_name), + agent: self.agent_label(&agent_name), provider: Some(provider_kind(&agent_name)), status: fact.status, status_word: status_word( @@ -227,6 +215,14 @@ impl App { } } + /// Sessions name their agent by the slug `/delegate` takes. + fn agent_label(&self, agent_name: &str) -> String { + if self.cloud_mode { + return "Nori Cloud".to_string(); + } + agent_name.to_string() + } + fn agent_display_name(&self, agent_name: &str) -> String { if self.cloud_mode { return "Nori Cloud".to_string(); @@ -254,7 +250,8 @@ impl App { /// Refresh the lines about other sessions on the active widget. Runs /// before every draw; with one session, or without /// `[features] multi_session`, nothing is shown. - pub(super) fn refresh_session_overview(&mut self) { + /// `width` is the terminal width; the lines are fitted to one row each. + pub(super) fn refresh_session_overview(&mut self, width: u16) { if !self.config.multi_session { return; } @@ -268,7 +265,10 @@ impl App { let name = self.agent_display_name(agent_name); lines.push(Line::from(format!("Preparing {name}…").dim())); } - lines.extend(self.background_request_line(&facts)); + // Session lines sit two cells in from the terminal edge. + let width = width.saturating_sub(2); + lines.extend(self.parent_breadcrumb(&facts, width)); + lines.extend(self.background_request_line(&facts, width)); if facts.len() > 1 && let Some(summary) = status_summary(facts.iter().map(|fact| fact.status)) { @@ -319,7 +319,7 @@ impl App { } for (generation, message) in pending { let title = self - .session_rows_title(generation) + .session_title(generation, TITLE_CHARS) .unwrap_or_else(|| "A session".to_string()); tui.notify(format!("{title}: {message}")); } @@ -327,7 +327,8 @@ impl App { /// Bring on screen the next session, after the active one in navigation /// order, that is waiting on the user. - pub(super) fn show_next_waiting_session(&mut self) { + /// Returns whether a session was brought on screen. + pub(super) fn show_next_waiting_session(&mut self) -> bool { let waiting: Vec<SessionGeneration> = self .session_facts() .into_iter() @@ -341,48 +342,106 @@ impl App { |generation| waiting.contains(&generation), ) { self.show_session(target); + return true; } + false } /// The line naming a session in the background that waits on the user, - /// with the key that jumps to it. - fn background_request_line(&self, facts: &[SessionFacts]) -> Option<Line<'static>> { + /// with the key that jumps to it. A child is named under its parent. + fn background_request_line(&self, facts: &[SessionFacts], width: u16) -> Option<Line<'static>> { let waiting: Vec<&SessionFacts> = facts .iter() .filter(|fact| !fact.on_screen && fact.status == SessionStatus::WaitingOnYou) .collect(); let first = waiting.first()?; let title = self - .session_title(first.generation, REQUEST_LINE_TITLE_CHARS) - .unwrap_or_else(|| "A session".to_string()); - let title = first.parent.map_or_else( - || title.clone(), - |parent| { - format!( - "(parent {}) {title}", - parent.to_string().chars().take(8).collect::<String>() - ) - }, - ); - let title = cut(&title, REQUEST_LINE_TITLE_CHARS); - let mut spans = vec![ - "● ".cyan(), - title.bold(), - format!(" is {}", crate::session_status::WAITING_ON_YOU_LABEL).into(), - ]; - if let Some(request) = self.session_previews.pending_request(first.generation) { - let request = cut(&request, REQUEST_LINE_REQUEST_CHARS); - spans.push(format!(" · {request}").dim()); - } - if waiting.len() > 1 { - spans.push(format!(" (+{} more)", waiting.len() - 1).dim()); + .session_title(first.generation, WHOLE_NAME) + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_string()); + let mut path = Vec::new(); + if let Some(parent) = first.parent { + path.push(self.session_name(&parent, WHOLE_NAME)); } + path.push(title); + let request = self.session_previews.pending_request(first.generation); let binding = self .hotkey_config .binding_for(nori_config::HotkeyAction::NextWaitingSession); - if !binding.is_none() { - spans.push(format!(" · {} to jump", binding.display_name()).dim()); + let key = (!binding.is_none()).then(|| binding.display_name()); + Some(crate::session_path::waiting_line( + &path, + request.as_deref(), + waiting.len() - 1, + key.as_deref(), + width, + )) + } + + /// A readable name for any session the manager knows: its title in this + /// TUI, else its recorded title, else a placeholder. + pub(super) fn session_name(&self, id: &ConversationId, limit: i32) -> String { + self.session_facts() + .iter() + .find(|fact| fact.conversation_id.as_ref() == Some(id)) + .and_then(|fact| self.session_title(fact.generation, limit)) + .or_else(|| { + self.session_manager + .replay_info(id) + .and_then(|info| info.title) + .and_then(|title| nori_protocol::session_full_name(&title)) + .map(|title| cut(&title, limit)) + }) + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_string()) + } + + /// The parent of the delegated child on screen, if any. + pub(super) fn on_screen_parent(&self) -> Option<ConversationId> { + self.chat_widget + .managed_conversation_id() + .and_then(|id| self.session_manager.get(&id)) + .filter(|record| record.source == nori_harness::session_manager::SessionSource::Session) + .and_then(|record| record.parent) + } + + /// Where a delegated child sits, from its top-level session down, with + /// the key that returns to its parent. + fn parent_breadcrumb(&self, facts: &[SessionFacts], width: u16) -> Option<Line<'static>> { + self.on_screen_parent()?; + let child = facts.iter().find(|fact| fact.on_screen)?; + let mut path = vec![crate::session_path::PathStep { + agent: child.agent.clone(), + name: self + .session_title(child.generation, WHOLE_NAME) + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_string()), + }]; + let mut record = child + .conversation_id + .and_then(|id| self.session_manager.get(&id)); + let mut seen = Vec::new(); + while let Some(current) = record + && current.source == nori_harness::session_manager::SessionSource::Session + && let Some(parent) = current.parent + && !seen.contains(&parent) + && let Some(parent_record) = self.session_manager.get(&parent) + { + seen.push(parent); + path.push(crate::session_path::PathStep { + agent: parent_record.agent.clone(), + name: self.session_name(&parent, WHOLE_NAME), + }); + record = Some(parent_record); } - Some(Line::from(spans)) + path.reverse(); + let binding = self + .hotkey_config + .binding_for(nori_config::HotkeyAction::ParentSession); + let tail = if binding.is_none() { + String::new() + } else { + format!(" · {} to parent", binding.display_name()) + }; + Some(crate::session_path::breadcrumb_line( + &path, "", &tail, width, + )) } } diff --git a/nori-rs/tui/src/app/session_resume.rs b/nori-rs/tui/src/app/session_resume.rs index 468b47725..a4d70c3d5 100644 --- a/nori-rs/tui/src/app/session_resume.rs +++ b/nori-rs/tui/src/app/session_resume.rs @@ -29,7 +29,7 @@ impl App { else { return Ok(()); }; - let title = self.session_rows_title(generation); + let title = self.session_title(generation, super::session_overview::WHOLE_NAME); let config = self.config_for_agent(&record.agent); let session = match self .session_manager diff --git a/nori-rs/tui/src/app/session_view.rs b/nori-rs/tui/src/app/session_view.rs index 419492b72..4686affe4 100644 --- a/nori-rs/tui/src/app/session_view.rs +++ b/nori-rs/tui/src/app/session_view.rs @@ -126,7 +126,7 @@ impl App { let closed: Vec<SessionGeneration> = self .session_facts() .into_iter() - .filter(|fact| fact.status == nori_protocol::SessionStatus::Closed) + .filter(|fact| fact.status.is_closed()) .map(|fact| fact.generation) .collect(); if let Some(target) = self diff --git a/nori-rs/tui/src/attach/docs.md b/nori-rs/tui/src/attach/docs.md index a4a1294e9..973fad465 100644 --- a/nori-rs/tui/src/attach/docs.md +++ b/nori-rs/tui/src/attach/docs.md @@ -51,27 +51,96 @@ Path: @/nori-rs/tui/src/attach phases, and session end. - [Rendering](render.rs) keeps role and connectivity visible beside the selected conversation or session list. Watchers receive the same content and - permissions but must take control before sending mutations. The current - session marker appears in TITLE, preserving the short ID in its own column. + permissions but must take control before sending mutations. +- The identity line under the header shows the selected session as + `<agent> · <name> · <status>`, where the name is the title's whole first + line through `nori_protocol::session_full_name`, else + `nori_protocol::UNTITLED_SESSION_NAME`. A top-level session shows its + `family_status` when present, as in the session lists. Inside a delegated + child (a row whose `source` is `session`; forks get no breadcrumb) whose + parent is listed, it becomes the full-path breadcrumb from the top-level + session with its own status and the key ` · <parent_session key> parent` + (Alt+Up by default). Both forms go through the shared + [`session_path::breadcrumb_line`](../session_path.rs) (a top-level session + is a one-step path without a key), so long names are fitted to the width: + the key gives way before the current name is cut, and names are cut in the + middle. The walk follows listed delegating parents and stops at a repeat. +- A waiting line (the row under the identity line) names the next session, + other than the selected one, whose own status is `waiting on you`: under its + parent when the parent is listed, with `(+N more)` and the jump key + (`AttachState.jump_binding`, set from the configured `next_waiting_session` + binding). It uses the shared `session_path::waiting_line` without request + text, passing whole names that it cuts in the middle by width, and the row + stays empty when nothing waits. +- The session list is tree-ordered: [AttachState](state.rs) runs the listed + `(session_id, parent)` pairs through the shared picker `tree_order` and gives + each item its depth, and the picker is built with `tree_column("title")`. + Tree guides and the `(current)` badge therefore sit inside TITLE while ID, + AGENT, STATUS, and AGE stay aligned at every depth. Status words take the + shared `session_status::status_tone` colors (waiting on you amber, working + cyan, ready green, failed red, done in the default color; starting and + closed muted). A row at + depth 0 shows the host's `family_status` when present, so a parent reads + `waiting on you` while anything under it does; older hosts omit the field + and the row shows its own status. A row without a title reads + `UNTITLED_SESSION_NAME`. TITLE is a wide `cut_middle` column, so it takes + the room the terminal leaves and cuts long titles once in the middle, + keeping the ends that tell sibling sessions apart. The list ignores the host's `depth` field and + derives depth from parent links. -- Delegation uses the shared [command parser](../delegation.rs): +- Delegation uses the shared [command parser and presentation](../delegation.rs): `/delegate <agent> <task>` sends the selected parent to the manager's remote - delegate method. Different-kind Start/Decline decisions resolve the manager - request; watchers must take control before either operation. Session lists - carry pending delegation state so reconnecting terminals can recover the - approval view without resending a mutation. + delegate method. A different-kind request shows the shared `approval_lines` + prompt (question, `asked by` / `runs on` / `task` rows) with + `1 Yes, start it · 2 No, decline`; watchers must take control before either + operation. Session lists carry pending delegation state so reconnecting + terminals can recover the approval view without resending a mutation. +- Every other `DelegationChanged` becomes a `Part::Delegation` in the parent's + conversation, rendered by the shared `DelegationCell`. Attached clients have + no transcript view or local session-list key here, so the cell is built with + empty `DelegationHints` and shows no key hints. An `awaiting_approval` change + adds no part; the approval prompt covers it. +- A permission prompt or delegation approval on the on-screen session is modal + while the session list is closed, like the local approval overlay. Its keys + answer it (permission: Up/Down, plain Enter, 1-9; delegation: 1 or plain + Enter approves, 2 declines); PageUp/PageDown and Ctrl+C work as usual; every + other key is swallowed, so the draft is never edited or sent. Earlier + hotkeys and pastes are unaffected; off-screen requests capture nothing. - Child permissions stay in the child's conversation. The configured - `next_waiting_session` binding (Alt+Down by default) navigates there. If the - cached list has no waiting target, a connected terminal retains the navigation - action while refreshing the list, then selects a newly discovered waiting - session from the response. Later input or navigation, list errors, and - disconnection cancel that pending action. The response also requires an empty - composer, including after paste, so a draft begun in the parent stays there. - Parent notices and child list rows identify the child and its parent. - Hierarchy labels prefix TITLE so parent attribution survives long task titles - while metadata columns keep their positions. + `next_waiting_session` binding (Alt+Down by default) navigates there, even + with a draft in the composer, as in the local TUI. With nothing waiting in + the cached list, a draft lets the key pass to the composer; an empty + composer on a connected terminal retains the navigation action while + refreshing the list, then selects a newly discovered waiting session from + the response. Later input or navigation, list errors, and disconnection + cancel that pending action, and the response jumps only if the composer is + still empty, including after paste. +- Unsent drafts are kept per session. Every switch (next waiting, parent, + picker Enter, and the session `/new` creates) goes through + `Runtime::open_session`, which parks the whole composer edit (text, large + pastes, images, cursor; the composer's own draft hand-off) with the session + it was typed in and restores the target's own draft, so text never follows + the user into another session. Text typed while no session is open goes + with the session opened next. Drafts live only in this terminal's memory. + Parent notices name the child and parent readably (see the + [harness](../../../harness/docs.md#delegation-between-managed-sessions)). + The `parent_session` binding moves the selection from a delegated child + (`source` `session`, not a fork) to its parent when that parent is in the + cached list, closing the list and resubscribing; elsewhere it does nothing. Results return through the parent's ordinary event stream without a terminal - review step. + review step. The echoed result prompt (a user message that + `nori_protocol::delegation_result_parts` recognizes) renders as one + `› delegation result from <agent> · <name> · <status> · delivered to this + session` line through the shared `delegation::delivered_result_spans` + (the delivered suffix gives way first, then the name is cut in the middle), + since the result block already shows the text. +- A session end is stored as `Part::Ended` with the host's message, and its + line is worded at draw time from the row's current status, because the host + may report `done` after the end event. A host message is shown as sent. + Otherwise a delegated child reads `This child finished its task · <parent + key> to its parent` when done and `This child session ended · …` otherwise + (just a period when the key is unbound); a top-level session reads + `Session ended. Use /new to start another session.` ### Things to Know diff --git a/nori-rs/tui/src/attach/input.rs b/nori-rs/tui/src/attach/input.rs index e2d8aa023..90e6cb81b 100644 --- a/nori-rs/tui/src/attach/input.rs +++ b/nori-rs/tui/src/attach/input.rs @@ -23,10 +23,28 @@ impl Runtime { if key.code == KeyCode::Char('d') && key.modifiers.contains(KeyModifiers::CONTROL) { return false; } - if self.composer.is_empty() - && crate::nori::hotkey_match::matches_binding(&self.next_waiting_binding, &key) + // A draft stays with its session, so the jump never loses it. With + // nothing waiting, a typed draft keeps the key for the composer. + if crate::nori::hotkey_match::matches_binding(&self.next_waiting_binding, &key) + && (self.next_waiting_session(self.composer.is_empty()) || self.composer.is_empty()) { - self.next_waiting_session(true); + return true; + } + if crate::nori::hotkey_match::matches_binding(&self.state.parent_binding, &key) + && let Some(parent) = self.state.selected.as_ref().and_then(|id| { + self.state + .sessions + .iter() + .find(|row| &row.session_id == id) + .and_then(|row| row.delegating_parent().map(str::to_owned)) + }) + && self + .state + .sessions + .iter() + .any(|row| row.session_id == parent) + { + self.open_session(parent); return true; } if crate::nori::hotkey_match::matches_binding(&self.session_list_binding, &key) { @@ -84,11 +102,19 @@ impl Runtime { if self.state.list_open && self.picker_key(key) { return true; } - if self.composer.is_empty() && !self.state.list_open && self.delegation_key(key) { - return true; - } - if self.composer.is_empty() && !self.state.list_open && self.permission_key(key) { - return true; + // A request shown for the session on screen holds the keyboard, as + // the local approval overlay does: its keys answer it, scrolling and + // Ctrl+C still work, and anything else leaves the draft untouched. + if !self.state.list_open && self.request_shown() { + let passes = matches!(key.code, KeyCode::PageUp | KeyCode::PageDown) + || (key.code == KeyCode::Char('c') + && key.modifiers.contains(KeyModifiers::CONTROL)); + if !passes { + if !self.delegation_key(key) { + self.permission_key(key); + } + return true; + } } if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) { if self.composer.is_empty() { @@ -115,7 +141,8 @@ impl Runtime { true } - pub(super) fn next_waiting_session(&mut self, refresh_if_missing: bool) { + /// Returns whether a waiting session was brought on screen. + pub(super) fn next_waiting_session(&mut self, refresh_if_missing: bool) -> bool { let rows = &self.state.sessions; let start = rows .iter() @@ -129,16 +156,29 @@ impl Runtime { }) .map(|row| row.session_id.clone()); if let Some(id) = target { - self.state.selected = Some(id); - self.state.list_open = false; - self.state.scroll = 0; - self.state.notice = None; - self.state.replay_error = None; - self.subscribe_selected(); - } else if refresh_if_missing && self.state.connected { + self.open_session(id); + return true; + } + if refresh_if_missing && self.state.connected { self.next_waiting_after_refresh = true; self.refresh_list(); } + false + } + + /// Whether the session on screen shows a permission request or a + /// delegation waiting for approval. + fn request_shown(&self) -> bool { + self.state + .selected + .as_ref() + .and_then(|id| self.state.conversations.get(id)) + .is_some_and(|conversation| { + !conversation.permissions.is_empty() + || conversation.delegations.iter().any(|delegation| { + delegation.status == nori_protocol::DelegationStatus::AwaitingApproval + }) + }) } fn delegation_key(&mut self, key: KeyEvent) -> bool { @@ -190,12 +230,7 @@ impl Runtime { _ => return false, }; if let PickerOutcome::Selected(id) = self.state.picker.handle(action) { - self.state.selected = Some(id); - self.state.list_open = false; - self.state.scroll = 0; - self.state.notice = None; - self.state.replay_error = None; - self.subscribe_selected(); + self.open_session(id); } true } @@ -222,7 +257,7 @@ impl Runtime { (permission.selected + 1).min(permission.options.len().saturating_sub(1)); return true; } - KeyCode::Enter => permission.selected, + KeyCode::Enter if key.modifiers.is_empty() => permission.selected, KeyCode::Char(character @ '1'..='9') if key.modifiers.is_empty() => { usize::try_from(character.to_digit(10).unwrap_or(1)).unwrap_or(1) - 1 } diff --git a/nori-rs/tui/src/attach/mod.rs b/nori-rs/tui/src/attach/mod.rs index ce0f41287..ba2c8aa06 100644 --- a/nori-rs/tui/src/attach/mod.rs +++ b/nori-rs/tui/src/attach/mod.rs @@ -58,6 +58,7 @@ async fn run( let mut runtime = runtime::Runtime::new(options.session_id.clone(), request_tx); runtime.set_session_list_binding(hotkeys.open_session_list); runtime.set_next_waiting_binding(hotkeys.next_waiting_session); + runtime.state.parent_binding = hotkeys.parent_session; let connection = tokio::spawn(connection::drive(options, initial, request_rx, event_tx)); let mut events = tui.event_stream(); let mut refresh = tokio::time::interval(std::time::Duration::from_secs(1)); diff --git a/nori-rs/tui/src/attach/render.rs b/nori-rs/tui/src/attach/render.rs index 1b78ae36c..641bb6ba9 100644 --- a/nori-rs/tui/src/attach/render.rs +++ b/nori-rs/tui/src/attach/render.rs @@ -57,20 +57,10 @@ pub(super) fn render( header.push("RECONNECTING · sessions continue on the host".cyan()); } Line::from(header).render(Rect::new(area.x, area.y, area.width, 1), buf); - let identity = state - .selected - .as_ref() - .map(|id| { - let row = state.sessions.iter().find(|row| &row.session_id == id); - format!( - " {} · {} · {}", - row.map_or("session", |row| row.agent.as_str()), - id, - row.map_or("", |row| crate::session_status::status_label(row.status)) - ) - }) - .unwrap_or_else(|| " Sessions · /new starts a session · ctrl+d detaches".into()); - Line::from(identity.dim()).render(Rect::new(area.x, area.y + 1, area.width, 1), buf); + identity_line(state, area.width).render(Rect::new(area.x, area.y + 1, area.width, 1), buf); + if let Some(line) = waiting_line(state, area.width) { + line.render(Rect::new(area.x, area.y + 2, area.width, 1), buf); + } let input = composer_area(state, composer, area); let notice_lines = notice_lines(state, area.width); let notice_height = u16::try_from(notice_lines.len()) @@ -124,6 +114,90 @@ pub(super) fn render( composer.render_ref(input, buf); } +/// A listed session's name, whole: the lines that show it fit it to the +/// terminal width. +fn row_name(row: &super::state::SessionRow) -> String { + row.title + .as_deref() + .and_then(nori_protocol::session_full_name) + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_string()) +} + +/// The selected session's agent, name, and status. Inside a delegated child +/// it is a breadcrumb from the top-level session, with the key that returns +/// to the parent. +fn identity_line(state: &AttachState, width: u16) -> Line<'static> { + let Some(id) = state.selected.as_ref() else { + return Line::from(" Sessions · /new starts a session · ctrl+d detaches".dim()); + }; + let row = |id: &str| state.sessions.iter().find(|row| row.session_id == id); + let Some(current) = row(id) else { + return Line::from(format!(" session · {id}").dim()); + }; + let top_level = current.delegating_parent().and_then(row).is_none(); + // A top-level session speaks for its family, as in the session lists. + let shown = if top_level { + current.family_status.unwrap_or(current.status) + } else { + current.status + }; + let status = format!(" · {}", crate::session_status::status_label(shown)); + let mut path = vec![current]; + while let Some(parent) = path + .last() + .and_then(|row| row.delegating_parent()) + .and_then(row) + .filter(|parent| !path.iter().any(|seen| seen.session_id == parent.session_id)) + { + path.push(parent); + } + let path: Vec<crate::session_path::PathStep> = path + .into_iter() + .rev() + .map(|row| crate::session_path::PathStep { + agent: row.agent.clone(), + name: row_name(row), + }) + .collect(); + let key = if top_level || state.parent_binding.is_none() { + String::new() + } else { + format!(" · {} parent", state.parent_binding.as_str()) + }; + let mut line = + crate::session_path::breadcrumb_line(&path, &status, &key, width.saturating_sub(1)); + line.spans.insert(0, " ".into()); + line +} + +/// The next session, other than the one on screen, that waits on the user, +/// named under its parent, with the key that jumps to it. +fn waiting_line(state: &AttachState, width: u16) -> Option<Line<'static>> { + let row = |id: &str| state.sessions.iter().find(|row| row.session_id == id); + let waiting: Vec<&super::state::SessionRow> = state + .sessions + .iter() + .filter(|row| row.status == nori_protocol::SessionStatus::WaitingOnYou) + .filter(|row| state.selected.as_deref() != Some(row.session_id.as_str())) + .collect(); + let first = waiting.first()?; + let mut path = Vec::new(); + if let Some(parent) = first.parent.as_deref().and_then(row) { + path.push(row_name(parent)); + } + path.push(row_name(first)); + let key = (!state.jump_binding.is_none()).then(|| state.jump_binding.as_str().to_string()); + let mut line = crate::session_path::waiting_line( + &path, + None, + waiting.len() - 1, + key.as_deref(), + width.saturating_sub(1), + ); + line.spans.insert(0, " ".into()); + Some(line) +} + fn notice_lines(state: &AttachState, width: u16) -> Vec<Line<'static>> { state .stopped @@ -150,19 +224,16 @@ fn render_conversation(state: &AttachState, id: &str, area: Rect, buf: &mut Buff .find(|delegation| delegation.status == nori_protocol::DelegationStatus::AwaitingApproval); let delegation_lines = delegation .map(|delegation| { + let (title, rows) = crate::delegation::approval_lines(delegation); + let mut lines = vec![Line::from(title.bold())]; + lines.extend(rows); + lines.push(Line::from(vec![ + "1 Yes, start it".green(), + " · ".dim(), + "2 No, decline".into(), + ])); crate::wrapping::word_wrap_lines( - [ - Line::from("Start delegated session?".bold()), - Line::from(format!( - "Child {} ({}) · parent {} ({})", - delegation.child_id, - delegation.agent, - delegation.parent_id, - delegation.parent_agent - )), - Line::from(delegation.task.clone()), - Line::from("1 Start · 2 Decline".green()), - ], + lines.iter(), usize::from(area.width.saturating_sub(2)), ) }) @@ -186,6 +257,21 @@ fn render_conversation(state: &AttachState, id: &str, area: Rect, buf: &mut Buff let mut lines = Vec::new(); for part in &conversation.parts { match part { + Part::Message { + stream: MessageStream::User, + text, + .. + } if nori_protocol::delegation_result_parts(text).is_some() => { + let mut line = Line::from(vec!["› ".bold()]); + line.spans.extend( + crate::delegation::delivered_result_spans( + text, + usize::from(history_area.width).saturating_sub(2), + ) + .unwrap_or_default(), + ); + lines.push(line); + } Part::Message { stream, text, .. } => { match stream { MessageStream::User => lines.push(Line::from("› You".bold())), @@ -218,12 +304,23 @@ fn render_conversation(state: &AttachState, id: &str, area: Rect, buf: &mut Buff lines.push(Line::from(format!("{marker} {}", entry.step))); } } + Part::Delegation(delegation) => { + lines.extend( + super::state::delegation_cell(delegation).display_lines(history_area.width), + ); + } Part::Notice(notice) => { lines.extend(crate::wrapping::word_wrap_lines( [Line::from(notice.clone().cyan())], usize::from(history_area.width), )); } + Part::Ended(message) => { + lines.extend(crate::wrapping::word_wrap_lines( + [Line::from(state.end_notice(id, message.as_deref()).cyan())], + usize::from(history_area.width), + )); + } } lines.push(Line::default()); } diff --git a/nori-rs/tui/src/attach/runtime.rs b/nori-rs/tui/src/attach/runtime.rs index 84065dfd7..d76758059 100644 --- a/nori-rs/tui/src/attach/runtime.rs +++ b/nori-rs/tui/src/attach/runtime.rs @@ -28,10 +28,14 @@ pub(super) struct Runtime { pub session_list_binding: nori_config::HotkeyBinding, pub next_waiting_binding: nori_config::HotkeyBinding, pub(super) next_waiting_after_refresh: bool, + /// The unsent edit of each session not on screen, restored when it + /// returns. + drafts: HashMap<String, crate::bottom_pane::ComposerDraft>, } impl Runtime { pub fn set_next_waiting_binding(&mut self, binding: nori_config::HotkeyBinding) { + self.state.jump_binding = binding.clone(); self.next_waiting_binding = binding; self.composer.set_hint_items(vec![ (self.session_list_binding.as_str(), "sessions"), @@ -74,9 +78,30 @@ impl Runtime { session_list_binding: nori_config::HotkeyConfig::default().open_session_list, next_waiting_binding: nori_config::HotkeyConfig::default().next_waiting_session, next_waiting_after_refresh: false, + drafts: HashMap::new(), } } + /// Put `id` on screen. The edit in the composer stays with the session + /// it was typed in, and `id`'s own edit comes back. Text typed while no + /// session was open goes with the session opened next. + pub(super) fn open_session(&mut self, id: String) { + if let Some(previous) = self.state.selected.take() + && previous != id + { + self.drafts.insert(previous, self.composer.take_draft()); + if let Some(draft) = self.drafts.remove(&id) { + self.composer.restore_draft(draft); + } + } + self.state.selected = Some(id); + self.state.list_open = false; + self.state.scroll = 0; + self.state.notice = None; + self.state.replay_error = None; + self.subscribe_selected(); + } + pub fn send(&mut self, method: &str, params: Value, pending: Pending) { if self.state.stopped.is_some() { return; @@ -238,12 +263,7 @@ impl Runtime { let id = result["session_id"] .as_str() .ok_or_else(|| anyhow::anyhow!("Host did not return the new session ID"))?; - self.state.selected = Some(id.into()); - self.state.list_open = false; - self.state.scroll = 0; - self.state.notice = None; - self.state.replay_error = None; - self.subscribe_selected(); + self.open_session(id.into()); self.refresh_list(); } Pending::TakeControl => { diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_current_session_id.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_current_session_id.snap index ed641d376..75177d660 100644 --- a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_current_session_id.snap +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_current_session_id.snap @@ -1,16 +1,15 @@ --- source: tui/src/attach/tests.rs -assertion_line: 372 expression: rendered --- Nori host WATCHING · read-only · alt+t take control - mock-model · abcd1234-session · ready + mock-model · Review parser · ready Sessions 1 ID AGENT STATUS AGE TITLE - ▏ abcd1234 mock-model ready 2m (current) Review parser ▕ + ▏ abcd1234 mock-model ready 2m Review parser (current) ▕ diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted.snap index 82950bad4..2024c63cb 100644 --- a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted.snap +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted.snap @@ -1,10 +1,9 @@ --- source: tui/src/attach/tests.rs -assertion_line: 398 expression: rendered --- Nori host DISCONNECTED · ctrl+d to detach - session · one · + session · one Preserved history diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_sessions.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_sessions.snap index ef9a9a3d3..5c46e044c 100644 --- a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_sessions.snap +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_sessions.snap @@ -4,7 +4,7 @@ expression: rendered --- Nori host CONTROLLING Sessions · /new starts a session · ctrl+d detaches - + ● Update tests is waiting on you · alt+down to jump Sessions 2 diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_controller.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_controller.snap index 8c5f1ee5b..f88d6e756 100644 --- a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_controller.snap +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_controller.snap @@ -3,7 +3,7 @@ source: tui/src/attach/tests.rs expression: screen(&state) --- Nori host CONTROLLING - session · one · + session · one Ready. Send a prompt to begin. diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_watcher.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_watcher.snap index ddc5ceb78..5f94664d7 100644 --- a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_watcher.snap +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_watcher.snap @@ -3,7 +3,7 @@ source: tui/src/attach/tests.rs expression: screen(&state) --- Nori host WATCHING · read-only · alt+t take control - session · one · + session · one Ready. Send a prompt to begin. diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_approval_watcher.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_approval_watcher.snap index 4514a9fdb..088497767 100644 --- a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_approval_watcher.snap +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_approval_watcher.snap @@ -3,19 +3,19 @@ source: tui/src/attach/tests.rs expression: rendered --- Nori host WATCHING · read-only · alt+t take control - session · parent-session · + session · parent-session - Child child-session (mock-model-alt) · parent parent-session (mock-model) · awaiting - approval + Ready. Send a prompt to begin. - Start delegated session? - Child child-session (mock-model-alt) · parent parent-session (mock-model) - Review the parser - 1 Start · 2 Decline + Would you like mock-model to start a mock-model-alt session? + asked by mock-model (this session) + runs on mock-model-alt · a different agent from this session + task Review the parser + 1 Yes, start it · 2 No, decline › Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_breadcrumb.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_breadcrumb.snap new file mode 100644 index 000000000..f71610814 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_breadcrumb.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +expression: rendered +--- + Nori host WATCHING · read-only · alt+t take control + mock-model · Parent task › mock-model-alt · Child task · waiting on you · alt+up parent + + Waiting for session history… + + + + + + + + + + + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_list.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_list.snap index c5b54ab19..868393b56 100644 --- a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_list.snap +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_list.snap @@ -3,14 +3,14 @@ source: tui/src/attach/tests.rs expression: rendered --- Nori host WATCHING · read-only · alt+t take control - mock-model · parent-session · ready - + mock-model · Parent task · ready + ● Parent task › Child task is waiting on you · alt+down to jump Sessions 2 ID AGENT STATUS AGE TITLE - ▏ parent-s mock-model ready 0s (current) Parent task ▕ - child-se mock-model-alt waiting on you 0s ↳ (parent parent-s) Child task + ▏ parent-s mock-model ready 0s Parent task (current) ▕ + child-se mock-model-alt waiting on you 0s └─ Child task diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_result.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_result.snap index c32e1e4ab..cc7dc4d41 100644 --- a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_result.snap +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_result.snap @@ -3,13 +3,13 @@ source: tui/src/attach/tests.rs expression: rendered --- Nori host WATCHING · read-only · alt+t take control - session · parent-session · + session · parent-session + + ○ result from mock-model-alt · Review the parser · done + ▏ Parser reviewed + returns to mock-model on its own - Child child-session (mock-model-alt) · parent parent-session (mock-model) · awaiting - approval - Child child-session (mock-model-alt) · parent parent-session (mock-model) · completed - Parser reviewed diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_session_tree.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_session_tree.snap new file mode 100644 index 000000000..7af01c1f4 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_session_tree.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +expression: rendered +--- + Nori host WATCHING · read-only · alt+t take control + Sessions · /new starts a session · ctrl+d detaches + ● Ship tree picker › Port picker is waiting on you · alt+down to jump + + Sessions 5 + + ID AGENT STATUS AGE TITLE + ▏ root-one mock-model working 5m Ship tree picker ▕ + child-on mock-model-alt waiting on you 1m ├─ Port picker + grandchi mock-model failed 50s │ └─ Write snapshot tests + child-tw mock-model ready 20s └─ Update docs + root-two mock-model ready 3m Spike transport + + ↑↓ move enter open ctrl+r resume ctrl+f search esc back + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/state.rs b/nori-rs/tui/src/attach/state.rs index a5f8cc9cc..1aebeed57 100644 --- a/nori-rs/tui/src/attach/state.rs +++ b/nori-rs/tui/src/attach/state.rs @@ -15,6 +15,7 @@ use serde::Deserialize; use serde_json::Value; use serde_json::json; +use crate::history_cell::HistoryCell; use crate::presentation::ClientEvent; use crate::presentation::ClientEventNormalizer; use crate::presentation::MessageStream; @@ -34,10 +35,15 @@ pub(super) struct SessionRow { pub age_seconds: i64, #[serde(default)] pub parent: Option<String>, + /// `session` for a delegated child, `fork` or `user` otherwise. #[serde(default)] - pub depth: i32, + pub source: Option<String>, #[serde(default)] pub delegations: Vec<nori_protocol::Delegation>, + /// The status of the whole family under the top-level session: waiting + /// on you if any member is. Older hosts omit it. + #[serde(default)] + pub family_status: Option<SessionStatus>, } pub(super) enum Part { @@ -49,6 +55,9 @@ pub(super) enum Part { Tool(Box<ToolSnapshot>), Plan(PlanSnapshot), Notice(String), + Delegation(nori_protocol::Delegation), + /// Where the session ended, with the host's message when it sent one. + Ended(Option<String>), } pub(super) struct Permission { @@ -81,6 +90,10 @@ pub(super) struct AttachState { pub notice: Option<String>, pub replay_error: Option<String>, pub scroll: usize, + /// Key that moves from a delegated child to its parent. + pub parent_binding: nori_config::HotkeyBinding, + /// Key that opens the next session waiting on the user. + pub jump_binding: nori_config::HotkeyBinding, } impl Default for AttachState { @@ -96,11 +109,18 @@ impl Default for AttachState { PickerColumn::fixed("agent", "AGENT", 14).hide_below(55), PickerColumn::fixed("status", "STATUS", 16), PickerColumn::fixed("age", "AGE", 5).hide_below(45), - PickerColumn::flexible("title", "TITLE"), + PickerColumn::flexible("title", "TITLE") + .width(nori_tui_components::PickerColumnWidth::Flexible { + min: 8, + max: 240, + weight: 1, + }) + .cut_middle(), ], Vec::new(), ) - .search_placeholder("Title or agent"), + .search_placeholder("Title or agent") + .tree_column("title"), watching: true, connected: false, stopped: None, @@ -109,6 +129,8 @@ impl Default for AttachState { notice: None, replay_error: None, scroll: 0, + parent_binding: nori_config::HotkeyConfig::default().parent_session, + jump_binding: nori_config::HotkeyConfig::default().next_waiting_session, } } } @@ -128,45 +150,48 @@ impl AttachState { } } self.picker.title = format!("Sessions {}", self.sessions.len()); - self.picker.replace_items(self.sessions.iter().map(|row| { - let seconds = row.age_seconds.max(0); - let age = if seconds < 60 { - format!("{seconds}s") - } else if seconds < 3600 { - format!("{}m", seconds / 60) - } else { - format!("{}h", seconds / 3600) - }; - let title = row.title.clone().unwrap_or_else(|| "New session".into()); - let title = row.parent.as_ref().map_or_else( - || title.clone(), - |parent| { - format!( - "{}↳ (parent {}) {title}", - " ".repeat( - usize::try_from(row.depth.saturating_sub(1).clamp(0, 2)).unwrap_or(0) - ), - parent.chars().take(8).collect::<String>() - ) - }, - ); - let title = if self.selected.as_ref() == Some(&row.session_id) { - format!("(current) {title}") - } else { - title - }; - PickerItem::new(row.session_id.clone(), "title", title) - .cell("id", row.session_id.chars().take(8).collect::<String>()) - .cell("agent", row.agent.clone()) - .cell("status", crate::session_status::status_label(row.status)) - .cell("age", age) - .search_text(format!( - "{} {} {}", - row.title.as_deref().unwrap_or_default(), - row.agent, - row.session_id - )) - })); + let links: Vec<(&str, Option<&str>)> = self + .sessions + .iter() + .map(|row| (row.session_id.as_str(), row.parent.as_deref())) + .collect(); + let order = nori_tui_components::picker::tree_order(&links); + self.picker + .replace_items(order.into_iter().map(|(index, depth)| { + let row = &self.sessions[index]; + let seconds = row.age_seconds.max(0); + let age = if seconds < 60 { + format!("{seconds}s") + } else if seconds < 3600 { + format!("{}m", seconds / 60) + } else { + format!("{}h", seconds / 3600) + }; + let title = row + .title + .clone() + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.into()); + // A top-level session shows the status of the family member + // that most needs the user, as in the local list. + let status = row + .family_status + .filter(|_| depth == 0) + .unwrap_or(row.status); + PickerItem::new(row.session_id.clone(), "title", title) + .cell("id", row.session_id.chars().take(8).collect::<String>()) + .cell("agent", row.agent.clone()) + .cell("status", crate::session_status::status_label(status)) + .cell_detail_tone("status", crate::session_status::status_tone(status)) + .cell("age", age) + .depth(depth) + .current(self.selected.as_ref() == Some(&row.session_id)) + .search_text(format!( + "{} {} {}", + row.title.as_deref().unwrap_or_default(), + row.agent, + row.session_id + )) + })); Ok(()) } @@ -181,7 +206,14 @@ impl AttachState { .iter() .map(|part| match part { Part::Message { text, .. } | Part::Notice(text) => text.clone(), + Part::Ended(message) => self.end_notice(id, message.as_deref()), Part::Tool(tool) => tool.title.clone(), + Part::Delegation(delegation) => delegation_cell(delegation) + .display_lines(u16::MAX) + .iter() + .map(ToString::to_string) + .collect::<Vec<_>>() + .join("\n"), Part::Plan(plan) => plan .entries .iter() @@ -223,6 +255,30 @@ impl AttachState { Ok(json!({"session_id":id,"prompt":[{"type":"text","text":text}]})) } + /// The line that ends session `id`'s history. A delegated child points + /// back to its parent and says whether it finished its task; the words + /// follow the session's current status, which the host may report after + /// the end itself. + pub fn end_notice(&self, id: &str, message: Option<&str>) -> String { + if let Some(message) = message { + return message.to_owned(); + } + let row = self.sessions.iter().find(|row| row.session_id == id); + let Some(row) = row.filter(|row| row.delegating_parent().is_some()) else { + return "Session ended. Use /new to start another session.".into(); + }; + let ending = if row.status == nori_protocol::SessionStatus::Done { + "This child finished its task" + } else { + "This child session ended" + }; + if self.parent_binding.is_none() { + format!("{ending}.") + } else { + format!("{ending} · {} to its parent", self.parent_binding.as_str()) + } + } + pub fn show_notice(&mut self, message: impl Into<String>) { if self.stopped.is_some() { return; @@ -305,9 +361,11 @@ impl AttachState { conversation .delegations .retain(|current| current.request_id != delegation.request_id); - conversation - .parts - .push(Part::Notice(crate::delegation::summary(&delegation))); + if delegation.status != nori_protocol::DelegationStatus::AwaitingApproval { + conversation + .parts + .push(Part::Delegation(delegation.clone())); + } conversation.delegations.push(delegation); conversation.message_boundary = true; } @@ -321,11 +379,7 @@ impl AttachState { .retain(|permission| permission.request_id != resolved.request_id); } SessionEvent::Nori(NoriEvent::SessionEnded(ended)) => { - conversation - .parts - .push(Part::Notice(ended.message.unwrap_or_else(|| { - "Session ended. Use /new to start another session.".into() - }))); + conversation.parts.push(Part::Ended(ended.message)); conversation.permissions.clear(); conversation.message_boundary = true; } @@ -401,3 +455,23 @@ impl Conversation { } } } + +/// Attached clients have no transcript view or local session list key, so +/// delegation cells show no key hints. +pub(super) fn delegation_cell( + delegation: &nori_protocol::Delegation, +) -> crate::delegation::DelegationCell { + crate::delegation::DelegationCell::new( + delegation.clone(), + crate::delegation::DelegationHints::default(), + ) +} + +impl SessionRow { + /// The parent of a delegated child; forks and top-level sessions have none. + pub(super) fn delegating_parent(&self) -> Option<&str> { + self.parent + .as_deref() + .filter(|_| self.source.as_deref() == Some("session")) + } +} diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs index 7f0dddc9c..e8ab3971f 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -113,8 +113,16 @@ fn screen(state: &AttachState) -> String { screen_with_composer(state, &crate::ComposerInput::for_attachment()) } +fn screen_at(state: &AttachState, width: u16) -> String { + screen_sized(state, &crate::ComposerInput::for_attachment(), width) +} + fn screen_with_composer(state: &AttachState, composer: &crate::ComposerInput) -> String { - let area = ratatui::layout::Rect::new(0, 0, 90, 18); + screen_sized(state, composer, 90) +} + +fn screen_sized(state: &AttachState, composer: &crate::ComposerInput, width: u16) -> String { + let area = ratatui::layout::Rect::new(0, 0, width, 18); let mut buffer = ratatui::buffer::Buffer::empty(area); super::render::render(state, composer, area, &mut buffer); (0..area.height) @@ -367,7 +375,7 @@ fn current_session_row_keeps_short_id_visible() { let rendered = screen(&state); let row = rendered .lines() - .find(|line| line.contains("Review parser")) + .find(|line| line.contains("Review parser") && line.contains("2m")) .unwrap(); assert!(row.contains("abcd1234"), "{rendered}"); assert!(row.contains("current"), "{rendered}"); @@ -477,11 +485,15 @@ fn delegation_approval_names_both_sessions_and_cannot_be_answered_by_watcher() { .unwrap(); let rendered = screen(&runtime.state); assert!( - rendered.contains("child-session") && rendered.contains("parent-session"), + rendered.contains("mock-model-alt") && rendered.contains("Review the parser"), "{rendered}" ); assert!( - rendered.contains("Start") && rendered.contains("Decline"), + !rendered.contains("child-session"), + "the prompt names the child, not its ID: {rendered}" + ); + assert!( + rendered.contains("start it") && rendered.contains("decline"), "{rendered}" ); if approved { @@ -518,6 +530,10 @@ fn delegation_result_replaces_approval_and_replay_is_not_duplicated() { state.apply(delegation_event(2, "completed")).unwrap(); let rendered = screen(&state); assert!(rendered.contains("Parser reviewed"), "{rendered}"); + assert!( + rendered.contains("result from mock-model-alt") && !rendered.contains("child-session"), + "{rendered}" + ); assert!( !rendered.contains("1 Start"), "completed delegation must not retain approval" @@ -550,10 +566,8 @@ fn next_waiting_opens_actual_child_and_keeps_parent_identity_in_list() { rendered.contains("Parent task") && rendered.contains("Child task"), "{rendered}" ); - assert!( - rendered.contains("(parent parent-s) Child task"), - "{rendered}" - ); + assert!(rendered.contains("└─ "), "{rendered}"); + assert!(!rendered.contains("(parent"), "{rendered}"); insta::assert_snapshot!("delegation_child_list", rendered); runtime.key(KeyEvent::new(KeyCode::Down, KeyModifiers::ALT)); assert_eq!(runtime.state.selected.as_deref(), Some("child-session")); @@ -563,6 +577,189 @@ fn next_waiting_opens_actual_child_and_keeps_parent_identity_in_list() { assert_eq!(request["params"]["session_id"], "child-session"); } +#[test] +fn session_tree_keeps_children_under_their_parent_with_aligned_columns() { + let mut state = AttachState { + connected: true, + ..Default::default() + }; + state.replace_sessions(json!({"sessions":[ + {"session_id":"root-one","agent":"mock-model","status":"working","title":"Ship tree picker","age_seconds":300}, + {"session_id":"root-two","agent":"mock-model","status":"ready","title":"Spike transport","age_seconds":200}, + {"session_id":"child-one","agent":"mock-model-alt","status":"waiting_on_you","title":"Port picker","parent":"root-one","depth":1,"source":"session","age_seconds":100}, + {"session_id":"grandchild","agent":"mock-model","status":"failed","title":"Write snapshot tests","parent":"child-one","depth":2,"source":"session","age_seconds":50}, + {"session_id":"child-two","agent":"mock-model","status":"ready","title":"Update docs","parent":"root-one","depth":1,"source":"session","age_seconds":20} + ]})).unwrap(); + let rendered = screen(&state); + let titles: Vec<_> = rendered + .lines() + .skip_while(|line| !line.contains("Sessions 5")) + .filter_map(|line| { + ["Ship", "Port", "Write", "Update", "Spike"] + .iter() + .find(|word| line.contains(*word)) + .map(|word| { + let at = line.find("mock-model").expect("agent column"); + (*word, unicode_width::UnicodeWidthStr::width(&line[..at])) + }) + }) + .collect(); + assert_eq!( + titles.iter().map(|(word, _)| *word).collect::<Vec<_>>(), + ["Ship", "Port", "Write", "Update", "Spike"], + "children follow their parent: {rendered}" + ); + assert!( + titles.iter().all(|(_, column)| *column == titles[0].1), + "the AGENT column does not move: {rendered}" + ); + insta::assert_snapshot!("delegation_session_tree", rendered); +} + +#[test] +fn child_view_shows_breadcrumb_and_alt_up_returns_to_parent() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("child-session".into()), tx); + runtime.state.connected = true; + runtime.state.replace_sessions(json!({"sessions":[ + {"session_id":"parent-session","agent":"mock-model","status":"working","title":"Parent task","depth":0}, + {"session_id":"child-session","agent":"mock-model-alt","status":"waiting_on_you","title":"Child task","parent":"parent-session","depth":1,"source":"session"} + ]})).unwrap(); + runtime.state.list_open = false; + let rendered = screen(&runtime.state); + let breadcrumb = rendered + .lines() + .find(|line| line.contains("›")) + .unwrap_or_else(|| panic!("breadcrumb missing:\n{rendered}")); + assert!( + breadcrumb.contains("Parent task") && breadcrumb.contains("Child task"), + "{rendered}" + ); + assert!(breadcrumb.contains("alt+up"), "{rendered}"); + insta::assert_snapshot!("delegation_child_breadcrumb", rendered); + runtime.key(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT)); + assert_eq!(runtime.state.selected.as_deref(), Some("parent-session")); + let request = rx.try_recv().unwrap(); + assert_eq!(request["method"], "_nori/session/subscribe"); + assert_eq!(request["params"]["session_id"], "parent-session"); +} + +#[test] +fn long_names_keep_the_current_name_whole_before_the_parent_key() { + let state = { + let mut state = AttachState { + connected: true, + selected: Some("child-session".into()), + list_open: false, + ..Default::default() + }; + state.replace_sessions(json!({"sessions":[ + {"session_id":"parent-session","agent":"mock-model","status":"working","title":"Coordinate the quarterly release notes for every product"}, + {"session_id":"child-session","agent":"mock-model-alt","status":"waiting_on_you","title":"Verify every link in the generated changelog","parent":"parent-session","source":"session"} + ]})).unwrap(); + state.list_open = false; + state + }; + let rendered = screen(&state); + let breadcrumb = rendered + .lines() + .find(|line| line.contains("›")) + .unwrap_or_else(|| panic!("breadcrumb missing:\n{rendered}")); + assert!( + breadcrumb.contains("Verify every link in the generated changelog · waiting on you"), + "{rendered}" + ); + assert!( + !breadcrumb.contains("alt+up"), + "the key gave way: {rendered}" + ); +} + +#[test] +fn alt_up_in_a_top_level_session_stays_put() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("parent-session".into()), tx); + runtime.state.connected = true; + runtime.state.replace_sessions(json!({"sessions":[ + {"session_id":"parent-session","agent":"mock-model","status":"ready","title":"Parent task"} + ]})).unwrap(); + runtime.state.list_open = false; + runtime.key(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT)); + assert_eq!(runtime.state.selected.as_deref(), Some("parent-session")); + assert!(rx.try_recv().is_err(), "nothing to subscribe to"); +} + +#[test] +fn delivered_result_prompt_reads_as_one_line_in_attached_parent() { + use nori_protocol::acp::v1 as acp; + let mut state = AttachState { + connected: true, + selected: Some("parent-session".into()), + list_open: false, + ..Default::default() + }; + state.apply(delegation_event(1, "completed")).unwrap(); + let nori_protocol::SessionEvent::Nori(nori_protocol::NoriEvent::DelegationChanged(done)) = + delegation_event(1, "completed").event + else { + panic!("delegation fixture"); + }; + let prompt = nori_protocol::delegation_result_prompt(&done); + let chunk = acp::ContentChunk::new(acp::ContentBlock::Text(acp::TextContent::new(prompt))) + .message_id("delivery"); + state + .apply(SessionEnvelope { + conversation_id: "parent-session".into(), + agent: "mock-model".into(), + seq: 2, + event: nori_protocol::SessionEvent::Acp(nori_protocol::AcpEvent::Notification( + acp::AgentNotification::SessionNotification(acp::SessionNotification::new( + "agent-session", + acp::SessionUpdate::UserMessageChunk(chunk), + )), + )), + }) + .unwrap(); + let rendered = screen(&state); + assert_eq!( + rendered.matches("Parser reviewed").count(), + 1, + "the result shows once, in its block: {rendered}" + ); + assert!( + rendered.contains("delegation result from mock-model-alt"), + "{rendered}" + ); + assert!(!rendered.contains("child-session"), "{rendered}"); +} + +#[test] +fn a_fork_gets_no_parent_breadcrumb_or_parent_key() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("fork-session".into()), tx); + runtime.state.connected = true; + runtime.state.replace_sessions(json!({"sessions":[ + {"session_id":"parent-session","agent":"mock-model","status":"closed","title":"Parent task"}, + {"session_id":"fork-session","agent":"mock-model","status":"ready","title":"Forked task","parent":"parent-session","source":"fork"} + ]})).unwrap(); + runtime.state.list_open = false; + let rendered = screen(&runtime.state); + assert!(!rendered.contains("alt+up"), "{rendered}"); + assert!(!rendered.contains("Parent task"), "{rendered}"); + runtime.key(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT)); + assert_eq!(runtime.state.selected.as_deref(), Some("fork-session")); + assert!(rx.try_recv().is_err()); +} + #[test] fn next_waiting_uses_the_configured_binding() { use crossterm::event::KeyCode; @@ -706,3 +903,596 @@ fn explicit_session_list_navigation_cancels_deferred_next_waiting() { "refresh cannot override explicit navigation" ); } + +fn family() -> serde_json::Value { + json!({"sessions":[ + {"session_id":"root-session","agent":"mock-model","status":"ready","family_status":"waiting_on_you","title":"Ship tree-row picker","depth":0}, + {"session_id":"child-session","agent":"mock-model-alt","status":"working","family_status":"waiting_on_you","title":"Port picker","parent":"root-session","depth":1,"source":"session"}, + {"session_id":"grandchild-session","agent":"mock-model","status":"waiting_on_you","family_status":"waiting_on_you","title":"Write snapshot tests","parent":"child-session","depth":2,"source":"session"}, + {"session_id":"other-session","agent":"mock-model","status":"ready","family_status":"ready","title":"Spike transport","depth":0} + ]}) +} + +fn viewing(selected: &str) -> AttachState { + let mut state = AttachState { + connected: true, + selected: Some(selected.into()), + ..Default::default() + }; + state.replace_sessions(family()).unwrap(); + state.list_open = false; + state +} + +#[test] +fn a_top_level_session_says_when_a_grandchild_waits_on_you() { + let rendered = screen(&viewing("root-session")); + let waiting = rendered + .lines() + .find(|line| line.contains("is waiting on you")) + .unwrap_or_else(|| panic!("waiting line missing:\n{rendered}")); + assert!( + waiting.contains("● Port picker › Write snapshot tests is waiting on you"), + "{rendered}" + ); + assert!( + waiting.trim_end().ends_with("alt+down to jump"), + "{rendered}" + ); + let mut state = viewing("root-session"); + state.list_open = true; + let list = screen(&state); + let row = |title: &str| { + list.lines() + .skip_while(|line| !line.contains("Sessions 4")) + .find(|line| line.contains(title)) + .unwrap_or_else(|| panic!("{title} row in:\n{list}")) + .to_string() + }; + assert!( + row("Ship tree-row picker").contains("waiting on you"), + "{list}" + ); + assert!(row("Port picker").contains("working"), "{list}"); + assert!(row("Spike transport").contains("ready"), "{list}"); +} + +#[test] +fn the_waiting_line_names_another_waiting_session_never_the_one_on_screen() { + let mut state = AttachState { + connected: true, + selected: Some("grandchild-session".into()), + ..Default::default() + }; + let mut sessions = family(); + for row in sessions["sessions"].as_array_mut().unwrap() { + if row["session_id"] == "other-session" { + row["status"] = json!("waiting_on_you"); + row["family_status"] = json!("waiting_on_you"); + } + } + state.replace_sessions(sessions).unwrap(); + state.list_open = false; + let rendered = screen(&state); + let waiting = rendered + .lines() + .find(|line| line.contains("is waiting on you")) + .unwrap_or_else(|| panic!("waiting line missing:\n{rendered}")); + assert!( + waiting.contains("● Spike transport is waiting on you"), + "{rendered}" + ); + assert!(!waiting.contains("Write snapshot tests"), "{rendered}"); +} + +#[test] +fn a_grandchild_breadcrumb_shows_the_path_from_its_top_level_session() { + let rendered = screen_at(&viewing("grandchild-session"), 140); + let breadcrumb = rendered + .lines() + .find(|line| line.contains("alt+up parent")) + .unwrap_or_else(|| panic!("breadcrumb missing:\n{rendered}")); + assert!( + breadcrumb.contains( + "mock-model · Ship tree-row picker › mock-model-alt · Port picker › mock-model · Write snapshot tests" + ), + "{rendered}" + ); + for width in [100, 80] { + let rendered = screen_at(&viewing("grandchild-session"), width); + let breadcrumb = rendered + .lines() + .find(|line| line.contains("› mock-model · Write")) + .unwrap_or_else(|| panic!("breadcrumb missing:\n{rendered}")); + assert!( + breadcrumb.starts_with(" mock-model · Ship"), + "@{width}: {rendered}" + ); + assert!( + breadcrumb.contains("› mock-model · Write snapshot tests · waiting on you"), + "@{width}: {rendered}" + ); + } +} + +#[test] +fn an_untitled_session_is_called_new_session_not_an_id() { + let mut state = AttachState { + connected: true, + selected: Some("24444c0e-1111-2222-3333-444444444444".into()), + ..Default::default() + }; + state + .replace_sessions(json!({"sessions":[ + {"session_id":"24444c0e-1111-2222-3333-444444444444","agent":"mock-model","status":"ready","title":null} + ]})) + .unwrap(); + state.list_open = false; + let rendered = screen(&state); + assert!( + rendered.contains("mock-model · new session · ready"), + "{rendered}" + ); + assert!(!rendered.contains("24444c0e"), "{rendered}"); +} + +fn key( + runtime: &mut super::runtime::Runtime, + code: crossterm::event::KeyCode, + modifiers: crossterm::event::KeyModifiers, +) { + runtime.key(crossterm::event::KeyEvent::new(code, modifiers)); +} + +#[test] +fn alt_down_with_a_draft_jumps_and_the_draft_waits_in_the_parent() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("root-session".into()), tx); + runtime.state.connected = true; + runtime.state.role_changed("controller"); + runtime.state.replace_sessions(family()).unwrap(); + runtime.state.list_open = false; + runtime.composer.handle_paste("my draft".into()); + key(&mut runtime, KeyCode::Down, KeyModifiers::ALT); + assert_eq!( + runtime.state.selected.as_deref(), + Some("grandchild-session") + ); + assert!( + runtime.composer.is_empty(), + "the draft stays with the parent" + ); + runtime.composer.handle_paste("child draft".into()); + key(&mut runtime, KeyCode::Up, KeyModifiers::ALT); + key(&mut runtime, KeyCode::Up, KeyModifiers::ALT); + assert_eq!(runtime.state.selected.as_deref(), Some("root-session")); + while rx.try_recv().is_ok() {} + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let prompt = rx.try_recv().unwrap(); + assert_eq!(prompt["method"], "_nori/session/prompt"); + assert_eq!(prompt["params"]["session_id"], "root-session"); + assert_eq!(prompt["params"]["prompt"][0]["text"], "my draft"); + key(&mut runtime, KeyCode::Down, KeyModifiers::ALT); + assert_eq!( + runtime.state.selected.as_deref(), + Some("grandchild-session") + ); + while rx.try_recv().is_ok() {} + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let prompt = rx.try_recv().unwrap(); + assert_eq!(prompt["params"]["session_id"], "grandchild-session"); + assert_eq!(prompt["params"]["prompt"][0]["text"], "child draft"); +} + +#[test] +fn a_large_pasted_draft_survives_a_jump_and_back_whole() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("root-session".into()), tx); + runtime.state.connected = true; + runtime.state.role_changed("controller"); + runtime.state.replace_sessions(family()).unwrap(); + runtime.state.list_open = false; + let pasted = "x".repeat(1500); + runtime.composer.handle_paste(pasted.clone()); + key(&mut runtime, KeyCode::Down, KeyModifiers::ALT); + key(&mut runtime, KeyCode::Up, KeyModifiers::ALT); + key(&mut runtime, KeyCode::Up, KeyModifiers::ALT); + assert_eq!(runtime.state.selected.as_deref(), Some("root-session")); + while rx.try_recv().is_ok() {} + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let prompt = rx.try_recv().unwrap(); + assert_eq!(prompt["params"]["prompt"][0]["text"], pasted.as_str()); +} + +#[test] +fn text_typed_before_choosing_a_session_goes_with_the_chosen_session() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(None, tx); + runtime.state.connected = true; + runtime.state.role_changed("controller"); + runtime.state.replace_sessions(family()).unwrap(); + runtime.composer.handle_paste("first words".into()); + runtime.state.list_open = true; + runtime.composer.clear(); + runtime.composer.handle_paste("first words".into()); + runtime.open_session("other-session".into()); + while rx.try_recv().is_ok() {} + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let prompt = rx.try_recv().unwrap(); + assert_eq!(prompt["params"]["session_id"], "other-session"); + assert_eq!(prompt["params"]["prompt"][0]["text"], "first words"); +} + +#[test] +fn a_top_level_header_shows_its_family_status() { + let rendered = screen(&viewing("root-session")); + assert!( + rendered.contains("mock-model · Ship tree-row picker · waiting on you"), + "{rendered}" + ); +} + +#[test] +fn done_reads_apart_from_closed_in_the_session_list() { + let mut state = AttachState { + connected: true, + ..Default::default() + }; + state + .replace_sessions(json!({"sessions":[ + {"session_id":"done-session","agent":"mock-model","status":"done","title":"Finished child"}, + {"session_id":"closed-session","agent":"mock-model","status":"closed","title":"Closed by you"} + ]})) + .unwrap(); + state.list_open = true; + let area = ratatui::layout::Rect::new(0, 0, 90, 18); + let mut buffer = ratatui::buffer::Buffer::empty(area); + super::render::render( + &state, + &crate::ComposerInput::for_attachment(), + area, + &mut buffer, + ); + let style_of = |title: &str, word: &str| { + (0..area.height) + .find_map(|y| { + let cells: Vec<&str> = (0..area.width).map(|x| buffer[(x, y)].symbol()).collect(); + let row = cells.concat(); + if !row.contains(title) { + return None; + } + let x = (0..cells.len()) + .find(|x| cells[*x..].concat().starts_with(&format!("{word} ")))?; + Some(buffer[(u16::try_from(x).unwrap(), y)].style()) + }) + .unwrap_or_else(|| panic!("{word} on the {title} row")) + }; + let done = style_of("Finished child", "done"); + let closed = style_of("Closed by you", "closed"); + assert_eq!( + closed.fg, + Some(ratatui::style::Color::DarkGray), + "closed stays muted: {closed:?}" + ); + assert_ne!(done.fg, closed.fg, "done reads apart from closed: {done:?}"); +} + +#[test] +fn a_finished_child_ends_by_pointing_back_to_its_parent() { + let mut state = viewing("child-session"); + let mut sessions = family(); + sessions["sessions"][1]["status"] = json!("done"); + state.replace_sessions(sessions).unwrap(); + state.list_open = false; + state + .apply(SessionEnvelope { + conversation_id: "child-session".into(), + agent: "mock-model-alt".into(), + seq: 1, + event: nori_protocol::SessionEvent::Nori(nori_protocol::NoriEvent::SessionEnded( + nori_protocol::SessionEnded { + reason: nori_protocol::SessionEndReason::Closed, + message: None, + }, + )), + }) + .unwrap(); + let rendered = screen(&state); + assert!( + rendered.contains("This child finished its task · alt+up to its parent"), + "{rendered}" + ); + assert!(!rendered.contains("/new to start"), "{rendered}"); + let mut sessions = family(); + sessions["sessions"][1]["status"] = json!("closed"); + state.replace_sessions(sessions).unwrap(); + state.list_open = false; + let closed = screen(&state); + assert!( + closed.contains("This child session ended · alt+up to its parent"), + "{closed}" + ); + assert!(!closed.contains("finished"), "{closed}"); + assert!(!closed.contains("/new to start"), "{closed}"); +} + +#[test] +fn a_delivered_result_fits_one_row_at_80_columns() { + use nori_protocol::acp::v1 as acp; + let mut state = AttachState { + connected: true, + selected: Some("parent-session".into()), + list_open: false, + ..Default::default() + }; + let done: nori_protocol::Delegation = serde_json::from_value(json!({ + "request_id":"delegation-one", "parent_id":"parent-session", "child_id":"child-session", + "parent_agent":"mock-model", "agent":"mock-model-alt", + "task":"mock:request-permission:review-the-lexer-tokens", + "status":"completed", "depth":1, "result":"Parser reviewed" + })) + .unwrap(); + let chunk = acp::ContentChunk::new(acp::ContentBlock::Text(acp::TextContent::new( + nori_protocol::delegation_result_prompt(&done), + ))) + .message_id("delivery"); + state + .apply(SessionEnvelope { + conversation_id: "parent-session".into(), + agent: "mock-model".into(), + seq: 1, + event: nori_protocol::SessionEvent::Acp(nori_protocol::AcpEvent::Notification( + acp::AgentNotification::SessionNotification(acp::SessionNotification::new( + "agent-session", + acp::SessionUpdate::UserMessageChunk(chunk), + )), + )), + }) + .unwrap(); + let rendered = screen_at(&state, 80); + let lines: Vec<&str> = rendered.lines().collect(); + let at = lines + .iter() + .position(|line| line.contains("delegation result")) + .unwrap_or_else(|| panic!("{rendered}")); + assert!(lines[at].contains("mock:request"), "{rendered}"); + assert!(lines[at].contains("lexer-tokens · done"), "{rendered}"); + assert!( + lines[at].trim_end().ends_with("lexer-tokens · done"), + "the whole line sits on one row: {rendered}" + ); +} + +fn shared_prefix_families() -> serde_json::Value { + let task = |end: &str| { + format!("mock:delegate mock-model mock:delegate mock-model mock:request-permission:{end}") + }; + json!({"sessions":[ + {"session_id":"root-x","agent":"mock-model","status":"ready","family_status":"waiting_on_you","title":task("x"),"depth":0}, + {"session_id":"child-x","agent":"mock-model","status":"waiting_on_you","title":task("x"),"parent":"root-x","depth":1,"source":"session"}, + {"session_id":"root-y","agent":"mock-model","status":"ready","family_status":"waiting_on_you","title":task("y"),"depth":0}, + {"session_id":"child-y","agent":"mock-model","status":"waiting_on_you","title":task("y"),"parent":"root-y","depth":1,"source":"session"} + ]}) +} + +#[test] +fn list_titles_sharing_a_long_prefix_keep_their_distinct_ends() { + for width in [120, 80] { + let mut state = AttachState { + connected: true, + selected: Some("child-x".into()), + ..Default::default() + }; + state.replace_sessions(shared_prefix_families()).unwrap(); + let rendered = screen_at(&state, width); + let list = &rendered[rendered.find("TITLE").expect("list header")..]; + for (id, end, other) in [ + ("root-x ", ":x", ":y"), + ("child-x ", ":x", ":y"), + ("root-y ", ":y", ":x"), + ("child-y ", ":y", ":x"), + ] { + let row = list + .lines() + .find(|line| line.contains(id)) + .unwrap_or_else(|| panic!("{id} is drawn at {width}:\n{rendered}")); + let title = row + .trim_end() + .trim_end_matches('▕') + .trim_end_matches(" (current)"); + assert!(title.contains("mock"), "the start is kept: {row}"); + assert!( + title.ends_with(end) && !title.contains(other), + "the end that tells {id} apart is kept at {width}: {row}" + ); + assert_eq!(row.matches('…').count(), 1, "cut once at {width}: {row}"); + } + let child = list.lines().find(|line| line.contains("child-x ")).unwrap(); + assert!( + child.contains("└─") && child.contains("(current)"), + "{rendered}" + ); + } +} + +fn permission_event(seq: i64) -> SessionEnvelope { + use nori_protocol::acp::v1 as acp; + let request: acp::RequestPermissionRequest = serde_json::from_value(json!({ + "sessionId":"agent-session", "toolCall":{"toolCallId":"tool", "title":"Write a file"}, + "options":[ + {"optionId":"allow", "name":"Allow once", "kind":"allow_once"}, + {"optionId":"reject", "name":"Reject", "kind":"reject_once"} + ] + })) + .unwrap(); + SessionEnvelope { + conversation_id: "parent-session".into(), + agent: "mock-model".into(), + seq, + event: nori_protocol::SessionEvent::Acp(nori_protocol::AcpEvent::Request { + request_id: acp::RequestId::Str("permission".into()), + request: acp::AgentRequest::RequestPermissionRequest(request), + }), + } +} + +fn runtime_with_draft( + event: SessionEnvelope, +) -> ( + super::runtime::Runtime, + tokio::sync::mpsc::UnboundedReceiver<serde_json::Value>, +) { + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("parent-session".into()), tx); + runtime.state.connected = true; + runtime.state.role_changed("controller"); + runtime.state.list_open = false; + runtime.state.apply(event).unwrap(); + runtime.composer.handle_paste("my draft".into()); + while rx.try_recv().is_ok() {} + (runtime, rx) +} + +#[test] +fn enter_answers_a_pending_permission_and_keeps_the_draft() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (mut runtime, mut rx) = runtime_with_draft(permission_event(1)); + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let sent = rx.try_recv().expect("an answer is sent"); + assert_eq!(sent["method"], "_nori/session/respond", "{sent}"); + assert_eq!( + sent["params"]["response"]["outcome"]["optionId"], "allow", + "{sent}" + ); + assert!(rx.try_recv().is_err(), "the draft is not sent as a prompt"); + let rendered = screen_with_composer(&runtime.state, &runtime.composer); + assert!( + rendered.contains("my draft"), + "the draft stays:\n{rendered}" + ); +} + +#[test] +fn a_number_answers_a_pending_permission_and_keeps_the_draft() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (mut runtime, mut rx) = runtime_with_draft(permission_event(1)); + key(&mut runtime, KeyCode::Char('2'), KeyModifiers::NONE); + let sent = rx.try_recv().expect("an answer is sent"); + assert_eq!(sent["method"], "_nori/session/respond", "{sent}"); + assert_eq!( + sent["params"]["response"]["outcome"]["optionId"], "reject", + "{sent}" + ); + assert!(rx.try_recv().is_err(), "the draft is not sent as a prompt"); + let rendered = screen_with_composer(&runtime.state, &runtime.composer); + assert!( + rendered.contains("my draft"), + "the draft stays:\n{rendered}" + ); +} + +#[test] +fn a_number_approves_a_pending_delegation_and_keeps_the_draft() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (mut runtime, mut rx) = runtime_with_draft(delegation_event(1, "awaiting_approval")); + key(&mut runtime, KeyCode::Char('1'), KeyModifiers::NONE); + let sent = rx.try_recv().expect("an answer is sent"); + assert_eq!(sent["method"], "_nori/session/delegation/resolve", "{sent}"); + assert_eq!(sent["params"]["approved"], true, "{sent}"); + assert!(rx.try_recv().is_err(), "the draft is not sent as a prompt"); + let rendered = screen_with_composer(&runtime.state, &runtime.composer); + assert!( + rendered.contains("my draft"), + "the draft stays:\n{rendered}" + ); +} + +#[test] +fn with_no_request_shown_enter_still_sends_the_draft() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (mut runtime, mut rx) = runtime_with_draft(delegation_event(1, "running")); + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let sent = rx.try_recv().expect("the draft is sent"); + assert_eq!(sent["method"], "_nori/session/prompt", "{sent}"); + assert_eq!(sent["params"]["prompt"][0]["text"], "my draft"); + let rendered = screen_with_composer(&runtime.state, &runtime.composer); + assert!( + !rendered.contains("my draft"), + "the sent draft leaves the composer" + ); +} + +#[test] +fn enter_approves_a_pending_delegation_and_keeps_the_draft() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (mut runtime, mut rx) = runtime_with_draft(delegation_event(1, "awaiting_approval")); + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let sent = rx.try_recv().expect("an answer is sent"); + assert_eq!(sent["method"], "_nori/session/delegation/resolve", "{sent}"); + assert_eq!(sent["params"]["approved"], true, "{sent}"); + assert!(rx.try_recv().is_err(), "the draft is not sent as a prompt"); + let rendered = screen_with_composer(&runtime.state, &runtime.composer); + assert!( + rendered.contains("my draft"), + "the draft stays:\n{rendered}" + ); +} + +#[test] +fn a_request_in_another_session_leaves_enter_to_the_draft() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (mut runtime, mut rx) = runtime_with_draft(permission_event(1)); + runtime + .state + .replace_sessions(json!({"sessions":[ + {"session_id":"parent-session","agent":"mock-model","status":"waiting_on_you","title":"Parent task"}, + {"session_id":"other-session","agent":"mock-model","status":"ready","title":"Other task"} + ]})) + .unwrap(); + runtime.state.selected = Some("other-session".into()); + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let sent = rx.try_recv().expect("the draft is sent"); + assert_eq!(sent["method"], "_nori/session/prompt", "{sent}"); + assert_eq!(sent["params"]["session_id"], "other-session", "{sent}"); + assert_eq!(sent["params"]["prompt"][0]["text"], "my draft"); + assert!( + rx.try_recv().is_err(), + "the other session's request is not answered" + ); +} + +#[test] +fn while_a_request_shows_typing_leaves_both_the_request_and_the_draft_alone() { + use crossterm::event::KeyCode; + use crossterm::event::KeyModifiers; + let (mut runtime, mut rx) = runtime_with_draft(permission_event(1)); + for character in " fix bugs".chars() { + key(&mut runtime, KeyCode::Char(character), KeyModifiers::NONE); + } + key(&mut runtime, KeyCode::Enter, KeyModifiers::SHIFT); + assert!(rx.try_recv().is_err(), "nothing is answered or sent"); + let rendered = screen_with_composer(&runtime.state, &runtime.composer); + assert!(rendered.contains("my draft"), "{rendered}"); + assert!( + !rendered.contains("fix"), + "the request keeps the keys:\n{rendered}" + ); + key(&mut runtime, KeyCode::Enter, KeyModifiers::NONE); + let sent = rx.try_recv().expect("plain enter still answers"); + assert_eq!( + sent["params"]["response"]["outcome"]["optionId"], "allow", + "{sent}" + ); +} diff --git a/nori-rs/tui/src/bottom_pane/session_list_view.rs b/nori-rs/tui/src/bottom_pane/session_list_view.rs index b6ab550d7..3a1c94fad 100644 --- a/nori-rs/tui/src/bottom_pane/session_list_view.rs +++ b/nori-rs/tui/src/bottom_pane/session_list_view.rs @@ -76,11 +76,13 @@ const STATUS: &str = "status"; impl SessionListView { pub(crate) fn new(rows: Vec<SessionRow>, app_event_tx: AppEventSender) -> Self { let columns = [ - PickerColumn::flexible(TITLE, "Session").width(PickerColumnWidth::Flexible { - min: 16, - max: 72, - weight: 4, - }), + PickerColumn::flexible(TITLE, "Session") + .width(PickerColumnWidth::Flexible { + min: 16, + max: 72, + weight: 4, + }) + .cut_middle(), PickerColumn::fixed(AGENT, "Agent", 14).hide_below(48), PickerColumn::fixed(STATUS, "Status", 16), ]; @@ -138,7 +140,7 @@ impl SessionListView { return; } match row.status { - SessionStatus::Closed => { + SessionStatus::Closed | SessionStatus::Done => { self.app_event_tx .send(AppEvent::RemoveSession { generation }); } @@ -162,7 +164,7 @@ impl SessionListView { fn close_hint(&self) -> Option<KeyHint<'static>> { let row = self.selected_row().filter(|row| row.generation >= 0)?; Some(match row.status { - SessionStatus::Closed => KeyHint::new("ctrl+d", "remove"), + SessionStatus::Closed | SessionStatus::Done => KeyHint::new("ctrl+d", "remove"), _ if self.close_armed == Some(row.generation) => { KeyHint::new("ctrl+d", "again to close") } @@ -198,20 +200,11 @@ fn glyph(status: SessionStatus) -> &'static str { SessionStatus::Working => "⠋", SessionStatus::Ready => "○", SessionStatus::Failed => "✕", - SessionStatus::Closed => "·", + SessionStatus::Closed | SessionStatus::Done => "·", SessionStatus::Starting => "…", } } -fn tone(status: SessionStatus) -> DetailTone { - match status { - SessionStatus::WaitingOnYou => DetailTone::Warning, - SessionStatus::Failed => DetailTone::Error, - SessionStatus::Closed | SessionStatus::Starting => DetailTone::Muted, - SessionStatus::Working | SessionStatus::Ready => DetailTone::Default, - } -} - fn items(rows: &[SessionRow]) -> Vec<PickerItem<SessionGeneration>> { rows.iter() .map(|row| { @@ -222,14 +215,17 @@ fn items(rows: &[SessionRow]) -> Vec<PickerItem<SessionGeneration>> { ) .cell(AGENT, row.agent.clone()) .cell(STATUS, row.status_word.clone()) - .cell_detail_tone(STATUS, tone(row.family_status)) + .cell_detail_tone( + STATUS, + crate::session_status::status_tone(row.family_status), + ) .search_text(format!("{} {}", row.title, row.agent)) .depth(row.depth) .current(row.on_screen); if let Some(provider) = row.provider { item = item.cell_tone(AGENT, provider); } - if row.status == SessionStatus::Closed { + if row.status.is_closed() { item = item.cell_detail_tone(TITLE, DetailTone::Muted); } if row.family_status == SessionStatus::WaitingOnYou { @@ -438,6 +434,96 @@ mod tests { assert!(parent_line.contains("● parent session"), "{screen}"); } + #[test] + fn titles_sharing_a_long_prefix_stay_distinct_with_one_cut() { + let mut parent = row( + 1, + "shared prefix for the parser review: parent side", + SessionStatus::Ready, + ); + parent.on_screen = true; + let mut child = row( + 2, + "shared prefix for the parser review: child side mock:request-permission:z", + SessionStatus::WaitingOnYou, + ); + child.depth = 1; + for width in [120, 80] { + let screen = render(&view(vec![parent.clone(), child.clone()]), width); + let parent_line = screen + .lines() + .find(|line| line.contains("parent side")) + .unwrap_or_else(|| panic!("parent end is shown at {width}: {screen}")); + let child_line = screen + .lines() + .find(|line| line.contains("permission:z")) + .unwrap_or_else(|| panic!("child end is shown at {width}: {screen}")); + for line in [parent_line, child_line] { + assert!(line.contains("shared"), "start kept at {width}: {line}"); + } + assert_eq!( + child_line.matches('…').count(), + 1, + "the long child name is cut once at {width}: {child_line}" + ); + assert!(parent_line.matches('…').count() <= 1, "{parent_line}"); + assert!(child_line.contains("└─"), "{child_line}"); + assert!(parent_line.contains("(current)"), "{parent_line}"); + } + } + + #[test] + fn status_words_are_colored_by_what_the_session_needs() { + use ratatui::style::Color; + let rows = vec![ + row(1, "asks", SessionStatus::WaitingOnYou), + row(2, "busy", SessionStatus::Working), + row(3, "done", SessionStatus::Ready), + row(4, "broke", SessionStatus::Failed), + SessionRow { + on_screen: true, + ..row(5, "selected", SessionStatus::Closed) + }, + ]; + let titles = [ + ("waiting on you", "asks"), + ("working", "busy"), + ("ready", "done"), + ("failed", "broke"), + ]; + let list = view(rows); + let height = list.desired_height(80); + let mut terminal = Terminal::new(TestBackend::new(80, height)).expect("terminal"); + terminal + .draw(|frame| list.render(frame.area(), frame.buffer_mut())) + .expect("draw"); + let buffer = terminal.backend().buffer(); + let color_of = |word: &str| { + let title = titles + .iter() + .find(|(status, _)| *status == word) + .map(|(_, title)| *title) + .expect("row title"); + (0..buffer.area.height) + .find_map(|y| { + let line: String = (0..buffer.area.width) + .map(|x| buffer[(x, y)].symbol()) + .collect(); + if !line.contains(title) { + return None; + } + let column = line.rfind(word)?; + let x = line[..column].chars().count() as u16; + Some(buffer[(x, y)].fg) + }) + .unwrap_or_else(|| panic!("{word} is shown")) + }; + assert_eq!(color_of("waiting on you"), Color::Yellow); + assert_eq!(color_of("working"), Color::Cyan); + assert_eq!(color_of("ready"), Color::Green); + assert_eq!(color_of("failed"), Color::Red); + } + #[test] fn after_tab_the_footer_offers_every_session_again() { let mut waiting = row(1, "waiting session", SessionStatus::WaitingOnYou); diff --git a/nori-rs/tui/src/chatwidget/delegation.rs b/nori-rs/tui/src/chatwidget/delegation.rs index 0ed2dae33..aa59962b8 100644 --- a/nori-rs/tui/src/chatwidget/delegation.rs +++ b/nori-rs/tui/src/chatwidget/delegation.rs @@ -57,7 +57,13 @@ impl ChatWidget { self.bottom_pane.dismiss_selection(&delegation.request_id); self.delegation_approval = None; } - self.add_info_message(crate::delegation::summary(&delegation), None); + if delegation.status != DelegationStatus::AwaitingApproval { + let hints = self.delegation_hints(); + self.add_boxed_history(Box::new(crate::delegation::DelegationCell::new( + delegation.clone(), + hints, + ))); + } self.delegations .insert(delegation.request_id.clone(), delegation); self.show_delegation_approval(); @@ -78,7 +84,7 @@ impl ChatWidget { let Ok(parent) = ConversationId::from_string(&delegation.parent_id) else { return false; }; - let items = [("Start", true), ("Decline", false)] + let items = [("Yes, start it", true), ("No, decline", false)] .into_iter() .map(|(name, approved)| { let request_id = delegation.request_id.clone(); @@ -100,6 +106,7 @@ impl ChatWidget { .collect(); self.delegation_approval = Some(delegation.request_id.clone()); let request_id = delegation.request_id.clone(); + let (title, rows) = crate::delegation::approval_lines(&delegation); self.bottom_pane.show_selection_view(SelectionViewParams { on_dismiss: Some(Box::new(move |tx| { tx.send(AppEvent::ResolveDelegation { @@ -109,27 +116,31 @@ impl ChatWidget { }) })), header: Box::new(ColumnRenderable::with(vec![ - Box::new(Line::from("Start delegated session?").bold()) as Box<dyn Renderable>, - Box::new( - Paragraph::new(format!( - "Child {} ({})", - delegation.child_id, delegation.agent - )) - .wrap(Wrap { trim: false }), - ), - Box::new( - Paragraph::new(format!( - "parent {} ({})", - delegation.parent_id, delegation.parent_agent - )) - .wrap(Wrap { trim: false }), - ), - Box::new(Paragraph::new(delegation.task).wrap(Wrap { trim: false })), + Box::new(Line::from(title.bold())) as Box<dyn Renderable>, + Box::new(Line::from("")), + Box::new(Paragraph::new(rows).wrap(Wrap { trim: false })), ])), items, - footer_hint: Some(standard_popup_hint_line()), + footer_hint: Some(Line::from(vec![ + "Press ".into(), + crate::key_hint::plain(crossterm::event::KeyCode::Enter).into(), + " to confirm or ".into(), + crate::key_hint::plain(crossterm::event::KeyCode::Esc).into(), + " to decline".into(), + ])), ..Default::default() }); true } + + fn delegation_hints(&self) -> crate::delegation::DelegationHints { + let key = |action| { + let binding = self.config.hotkeys.binding_for(action); + (!binding.is_none()).then(|| binding.display_name()) + }; + crate::delegation::DelegationHints { + transcript: key(nori_config::HotkeyAction::OpenTranscript), + sessions: key(nori_config::HotkeyAction::OpenSessionList), + } + } } diff --git a/nori-rs/tui/src/chatwidget/event_handlers.rs b/nori-rs/tui/src/chatwidget/event_handlers.rs index 184b77c48..2ad93af57 100644 --- a/nori-rs/tui/src/chatwidget/event_handlers.rs +++ b/nori-rs/tui/src/chatwidget/event_handlers.rs @@ -379,7 +379,7 @@ impl ChatWidget { && self .managed_conversation_id .and_then(|id| self.session_manager.get(&id)) - .is_some_and(|record| record.status == nori_protocol::SessionStatus::Closed); + .is_some_and(|record| record.status.is_closed()); if !historical_child { self.submit_harness_action(crate::app_event::HarnessAction::LoadCustomPrompts); } diff --git a/nori-rs/tui/src/chatwidget/tests/delegation.rs b/nori-rs/tui/src/chatwidget/tests/delegation.rs index 2adfcab6f..73ece48a5 100644 --- a/nori-rs/tui/src/chatwidget/tests/delegation.rs +++ b/nori-rs/tui/src/chatwidget/tests/delegation.rs @@ -1,24 +1,53 @@ use super::*; +const PARENT: &str = "00000000-0000-0000-0000-000000000001"; +const CHILD: &str = "00000000-0000-0000-0000-000000000002"; + fn delegation(status: &str) -> nori_protocol::SessionEvent { - serde_json::from_value(serde_json::json!({"source":"nori","event":{"event_type":"delegation_changed","event":{ - "request_id":"delegation-one","parent_id":"00000000-0000-0000-0000-000000000001", - "child_id":"00000000-0000-0000-0000-000000000002","parent_agent":"mock-model","agent":"mock-model-alt", - "task":"Review the parser","depth":1,"status":status,"result":null - }}})).unwrap() + delegation_with(status, "agent", "Review the parser", None) } -#[test] -fn local_delegation_approval_identifies_parent_child_and_start_decline() { +fn delegation_with( + status: &str, + origin: &str, + task: &str, + result: Option<&str>, +) -> nori_protocol::SessionEvent { + serde_json::from_value( + serde_json::json!({"source":"nori","event":{"event_type":"delegation_changed","event":{ + "request_id":"delegation-one","parent_id":PARENT, + "child_id":CHILD,"parent_agent":"mock-model","agent":"mock-model-alt", + "task":task,"depth":1,"status":status,"result":result,"origin":origin + }}}), + ) + .unwrap() +} + +/// Screen and transcript text of every history cell the widget emitted. +fn history_text(rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>) -> (String, String) { + let mut screen = String::new(); + let mut transcript = String::new(); + while let Ok(event) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = event { + screen.push_str(&lines_to_single_string(&cell.display_lines(100))); + transcript.push_str(&lines_to_single_string(&cell.transcript_lines(100))); + } + } + let trim = |text: String| { + text.lines() + .map(str::trim_end) + .collect::<Vec<_>>() + .join("\n") + }; + (trim(screen), trim(transcript)) +} + +fn render_bottom_pane(chat: &ChatWidget) -> String { use crate::render::renderable::Renderable; - let (mut chat, _rx, _) = make_chatwidget_manual(); - chat.config.multi_session = true; - let generation = chat.session_generation(); - chat.handle_session_event(generation, delegation("awaiting_approval")); let area = ratatui::layout::Rect::new(0, 0, 100, chat.bottom_pane.desired_height(100)); let mut buffer = ratatui::buffer::Buffer::empty(area); chat.bottom_pane.render(area, &mut buffer); - let rendered = (0..area.height) + (0..area.height) .map(|y| { (0..area.width) .map(|x| buffer[(x, y)].symbol()) @@ -27,21 +56,282 @@ fn local_delegation_approval_identifies_parent_child_and_start_decline() { .to_owned() }) .collect::<Vec<_>>() - .join("\n"); + .join("\n") +} + +fn delegating_parent() -> (ChatWidget, tokio::sync::mpsc::UnboundedReceiver<AppEvent>) { + let (mut chat, mut rx, _) = make_chatwidget_manual(); + chat.config.multi_session = true; + while rx.try_recv().is_ok() {} + (chat, rx) +} + +#[test] +fn different_agent_approval_names_who_asks_which_agent_runs_and_the_task() { + let (mut chat, _rx) = delegating_parent(); + let generation = chat.session_generation(); + chat.handle_session_event(generation, delegation("awaiting_approval")); + let rendered = render_bottom_pane(&chat); assert!( - rendered.contains("Start") && rendered.contains("Decline"), - "{rendered}" + !rendered.contains(PARENT) && !rendered.contains(CHILD), + "the prompt names sessions, not raw IDs: {rendered}" + ); + for expected in [ + "asked by", + "mock-model (this session)", + "mock-model-alt", + "Review the parser", + ] { + assert!(rendered.contains(expected), "{expected}: {rendered}"); + } + insta::assert_snapshot!("local_delegation_approval", rendered); +} + +#[test] +fn user_requested_approval_says_the_user_asked() { + let (mut chat, _rx) = delegating_parent(); + let generation = chat.session_generation(); + chat.handle_session_event( + generation, + delegation_with("awaiting_approval", "user", "Review the parser", None), ); + let rendered = render_bottom_pane(&chat); + assert!(rendered.contains("you, with /delegate"), "{rendered}"); + insta::assert_snapshot!("user_delegation_approval", rendered); +} + +#[test] +fn escape_declines_a_pending_delegation() { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + chat.handle_session_event(generation, delegation("awaiting_approval")); + chat.handle_key_event(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Esc, + crossterm::event::KeyModifiers::NONE, + )); + let mut resolved = None; + while let Ok(event) = rx.try_recv() { + if let AppEvent::ResolveDelegation { approved, .. } = event { + resolved = Some(approved); + } + } + assert_eq!(resolved, Some(false)); +} + +#[test] +fn running_delegation_is_one_line_naming_child_agent_and_status() { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + chat.handle_session_event( + generation, + delegation_with( + "running", + "agent", + "Write snapshot tests for TreeRow\nCover depths 0 to 3. Do not touch picker.rs.", + None, + ), + ); + let (screen, transcript) = history_text(&mut rx); assert!( - rendered.contains("mock-model-alt") && rendered.contains("parent"), - "{rendered}" + !screen.contains(CHILD) && !screen.contains(PARENT), + "{screen}" ); assert!( - rendered.contains("00000000-0000-0000-0000-000000000001") - && rendered.contains("00000000-0000-0000-0000-000000000002"), - "approval identifies both sessions: {rendered}" + !screen.contains("Do not touch picker.rs"), + "the brief stays off screen: {screen}" ); - insta::assert_snapshot!("local_delegation_approval", rendered); + assert!( + transcript.contains("Cover depths 0 to 3. Do not touch picker.rs."), + "the transcript view shows the whole brief: {transcript}" + ); + let card = screen + .lines() + .find(|line| line.contains("mock-model-alt")) + .unwrap_or_else(|| panic!("card missing: {screen}")); + assert!( + card.contains(" · started") && !card.contains("working"), + "a card keeps a word that stays true once the child moves on: {screen}" + ); + insta::assert_snapshot!("running_delegation_line", screen); + insta::assert_snapshot!("running_delegation_transcript", transcript); +} + +#[test] +fn user_started_delegation_is_attributed_to_the_user() { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + chat.handle_session_event( + generation, + delegation_with("running", "user", "Review the parser", None), + ); + let (screen, _) = history_text(&mut rx); + assert!(screen.contains("you delegated"), "{screen}"); +} + +#[test] +fn completed_delegation_shows_a_result_block_naming_the_child() { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + chat.handle_session_event(generation, delegation("running")); + while rx.try_recv().is_ok() {} + chat.handle_session_event( + generation, + delegation_with( + "completed", + "agent", + "Review the parser", + Some("Found two bugs in parse_command.\nBoth have regression tests now."), + ), + ); + let (screen, _) = history_text(&mut rx); + assert!(screen.contains("result from mock-model-alt"), "{screen}"); + assert!(screen.contains("Review the parser"), "{screen}"); + assert!( + screen.contains("Both have regression tests now."), + "{screen}" + ); + assert!(!screen.contains(CHILD), "{screen}"); + insta::assert_snapshot!("completed_delegation_result", screen); +} + +#[test] +fn long_results_are_shortened_on_screen_and_kept_whole_in_the_transcript() { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + let result = (1..=12) + .map(|n| format!("finding {n}")) + .collect::<Vec<_>>() + .join("\n"); + chat.handle_session_event( + generation, + delegation_with("completed", "agent", "Review the parser", Some(&result)), + ); + let (screen, transcript) = history_text(&mut rx); + assert!(!screen.contains("finding 12"), "{screen}"); + assert!(screen.contains("more lines"), "{screen}"); + assert!(transcript.contains("finding 12"), "{transcript}"); +} + +#[test] +fn long_result_lines_keep_the_result_rail_when_wrapped() { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + let long = "word ".repeat(40); + chat.handle_session_event( + generation, + delegation_with("completed", "agent", "Review the parser", Some(long.trim())), + ); + let (screen, _) = history_text(&mut rx); + let rail_lines = screen + .lines() + .filter(|line| line.starts_with(" ▏ ")) + .count(); + assert!( + rail_lines >= 2, + "wrapped result lines keep the rail: {screen}" + ); +} + +#[test] +fn a_user_message_that_only_starts_like_a_result_stays_whole() { + let (mut chat, mut rx) = delegating_parent(); + chat.on_task_started(); + chat.handle_client_event(crate::presentation::ClientEvent::MessageDelta( + crate::presentation::MessageDelta { + stream: crate::presentation::MessageStream::User, + delta: "[Nori delegation result] what does this header mean?\nPlease explain.".into(), + message_id: Some("question".into()), + }, + )); + chat.on_task_complete(None); + let (screen, _) = history_text(&mut rx); + assert!(screen.contains("Please explain."), "{screen}"); +} + +#[test] +fn failed_declined_and_cancelled_delegations_read_clearly() { + let mut rendered = Vec::new(); + for (status, result) in [ + ("failed", "agent exited (code 1)"), + ("declined", "The user declined this delegation."), + ("cancelled", "Session closed by the user"), + ] { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + chat.handle_session_event( + generation, + delegation_with(status, "agent", "Review the parser", Some(result)), + ); + let (screen, _) = history_text(&mut rx); + assert!( + screen.contains("mock-model-alt") && screen.contains(status) && !screen.contains(CHILD), + "{screen}" + ); + rendered.push(screen); + } + insta::assert_snapshot!("ended_delegation_lines", rendered.join("\n---\n")); +} + +#[test] +fn delivered_result_reads_as_a_short_line_in_the_parent() { + let (mut chat, mut rx) = delegating_parent(); + chat.on_task_started(); + chat.handle_client_event(crate::presentation::ClientEvent::MessageDelta( + crate::presentation::MessageDelta { + stream: crate::presentation::MessageStream::User, + delta: nori_protocol::delegation_result_prompt( + &serde_json::from_value::<nori_protocol::Delegation>(serde_json::json!({ + "request_id":"delegation-one","parent_id":PARENT,"child_id":CHILD, + "parent_agent":"mock-model","agent":"mock-model-alt","task":"Review the parser", + "depth":1,"status":"completed","result":"Found two bugs." + })) + .unwrap(), + ), + message_id: Some("delegation-result".into()), + }, + )); + chat.on_task_complete(Some("Thanks".into())); + let (screen, transcript) = history_text(&mut rx); + assert!(!screen.contains(CHILD), "{screen}"); + assert!(screen.contains("mock-model-alt"), "{screen}"); + assert!(transcript.contains("Found two bugs."), "{transcript}"); + insta::assert_snapshot!("delivered_delegation_result", screen); +} + +#[test] +fn a_delivered_result_fits_one_row_at_80_columns() { + let (mut chat, mut rx) = delegating_parent(); + let task = "mock:request-permission:review-the-lexer-tokens"; + chat.on_task_started(); + chat.handle_client_event(crate::presentation::ClientEvent::MessageDelta( + crate::presentation::MessageDelta { + stream: crate::presentation::MessageStream::User, + delta: nori_protocol::delegation_result_prompt( + &serde_json::from_value::<nori_protocol::Delegation>(serde_json::json!({ + "request_id":"delegation-one","parent_id":PARENT,"child_id":CHILD, + "parent_agent":"mock-model","agent":"mock-model-alt","task":task, + "depth":1,"status":"completed","result":"Found two bugs." + })) + .unwrap(), + ), + message_id: Some("delegation-result".into()), + }, + )); + chat.on_task_complete(Some("Thanks".into())); + let mut rows = Vec::new(); + while let Ok(event) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = event { + let text = lines_to_single_string(&cell.display_lines(80)); + if text.contains("delegation result") { + rows = text.lines().map(str::trim_end).map(str::to_owned).collect(); + } + } + } + let rows: Vec<String> = rows.into_iter().filter(|row| !row.is_empty()).collect(); + assert_eq!(rows.len(), 1, "{rows:#?}"); + assert!(rows[0].contains("mock:request"), "{}", rows[0]); + assert!(rows[0].contains("lexer-tokens"), "{}", rows[0]); + assert!(rows[0].contains("· done"), "{}", rows[0]); } #[test] @@ -141,3 +431,86 @@ fn delegation_result_and_parent_continuation_preserve_composer_draft() { chat.on_task_complete(Some("Result received".into())); assert_eq!(chat.composer_text(), "/sessions"); } + +#[test] +fn a_shown_delegation_request_takes_enter_from_the_draft_and_keeps_it() { + let (mut chat, mut rx) = delegating_parent(); + chat.set_composer_text("my draft".into()); + let generation = chat.session_generation(); + chat.handle_session_event(generation, delegation("awaiting_approval")); + chat.handle_key_event(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Enter, + crossterm::event::KeyModifiers::NONE, + )); + let mut resolved = None; + while let Ok(event) = rx.try_recv() { + if let AppEvent::ResolveDelegation { approved, .. } = event { + resolved = Some(approved); + } + } + assert_eq!(resolved, Some(true), "enter answers the request"); + assert_eq!( + chat.composer_text(), + "my draft", + "the draft is neither sent nor changed" + ); +} + +#[test] +fn a_running_cards_header_keeps_both_name_ends_on_one_row_at_80_columns() { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + let task = "shared prefix for the parser review: child side mock:request-permission:z"; + chat.handle_session_event(generation, delegation_with("running", "agent", task, None)); + let mut cards = Vec::new(); + while let Ok(event) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = event { + cards.push(cell); + } + } + let card = cards.first().expect("a card is inserted"); + let at_80 = lines_to_single_string(&card.display_lines(80)); + let header = at_80.lines().next().unwrap_or_default(); + assert!( + header.contains("shared") && header.contains("permission:z") && header.ends_with("started"), + "the header keeps both ends of the name and its status on one row:\n{at_80}" + ); + assert!( + unicode_width::UnicodeWidthStr::width(header.trim_end()) <= 80, + "{at_80}" + ); + assert_eq!(header.matches('…').count(), 1, "{at_80}"); + let wide = lines_to_single_string(&card.display_lines(140)); + assert!( + wide.contains(task), + "the whole name shows when it fits:\n{wide}" + ); +} + +#[test] +fn a_long_failure_reason_wraps_instead_of_squeezing_the_child_name() { + let (mut chat, mut rx) = delegating_parent(); + let generation = chat.session_generation(); + let task = "shared prefix for the parser review: child side mock:request-permission:z"; + let reason = "agent exited during prompt after the connection to its tool server dropped twice"; + chat.handle_session_event( + generation, + delegation_with("failed", "agent", task, Some(reason)), + ); + let mut cards = Vec::new(); + while let Ok(event) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = event { + cards.push(cell); + } + } + let card = lines_to_single_string(&cards.first().expect("a card").display_lines(80)); + let header = card.lines().next().unwrap_or_default(); + assert!( + header.contains("shared prefix") && header.contains("permission:z"), + "the name keeps the room it would have without the reason:\n{card}" + ); + assert!( + card.contains("tool server"), + "the reason is still shown:\n{card}" + ); +} diff --git a/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__completed_delegation_result.snap b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__completed_delegation_result.snap new file mode 100644 index 000000000..42cb91a24 --- /dev/null +++ b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__completed_delegation_result.snap @@ -0,0 +1,8 @@ +--- +source: tui/src/chatwidget/tests/delegation.rs +expression: screen +--- +○ result from mock-model-alt · Review the parser · done + ▏ Found two bugs in parse_command. + ▏ Both have regression tests now. + returns to mock-model on its own · its history: alt + s diff --git a/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__delivered_delegation_result.snap b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__delivered_delegation_result.snap new file mode 100644 index 000000000..ff860c74e --- /dev/null +++ b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__delivered_delegation_result.snap @@ -0,0 +1,5 @@ +--- +source: tui/src/chatwidget/tests/delegation.rs +expression: screen +--- +› delegation result from mock-model-alt · Review the parser · done · delivered to this session diff --git a/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__ended_delegation_lines.snap b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__ended_delegation_lines.snap new file mode 100644 index 000000000..be02cbee0 --- /dev/null +++ b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__ended_delegation_lines.snap @@ -0,0 +1,10 @@ +--- +source: tui/src/chatwidget/tests/delegation.rs +expression: "rendered.join(\"\\n---\\n\")" +--- +✕ mock-model-alt · Review the parser · failed · agent exited (code 1) + sent to mock-model as a failure · its history: alt + s +--- +✕ delegation to mock-model-alt · Review the parser · declined by you +--- +✕ delegation to mock-model-alt · Review the parser · cancelled · Session closed by the user diff --git a/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__local_delegation_approval.snap b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__local_delegation_approval.snap index e9671c2e7..62ba303b7 100644 --- a/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__local_delegation_approval.snap +++ b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__local_delegation_approval.snap @@ -2,12 +2,13 @@ source: tui/src/chatwidget/tests/delegation.rs expression: rendered --- - Start delegated session? - Child 00000000-0000-0000-0000-000000000002 (mock-model-alt) - parent 00000000-0000-0000-0000-000000000001 (mock-model) - Review the parser + Would you like mock-model to start a mock-model-alt session? -› 1. Start - 2. Decline + asked by mock-model (this session) + runs on mock-model-alt · a different agent from this session + task Review the parser - ↑/k ↓/j to navigate, enter to confirm, esc to go back +› 1. Yes, start it + 2. No, decline + + Press enter to confirm or esc to decline diff --git a/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__running_delegation_line.snap b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__running_delegation_line.snap new file mode 100644 index 000000000..41f1eff52 --- /dev/null +++ b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__running_delegation_line.snap @@ -0,0 +1,6 @@ +--- +source: tui/src/chatwidget/tests/delegation.rs +expression: screen +--- +↳ mock-model delegated to mock-model-alt · Write snapshot tests for TreeRow · started + ctrl + t shows the brief diff --git a/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__running_delegation_transcript.snap b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__running_delegation_transcript.snap new file mode 100644 index 000000000..2e0185cae --- /dev/null +++ b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__running_delegation_transcript.snap @@ -0,0 +1,8 @@ +--- +source: tui/src/chatwidget/tests/delegation.rs +expression: transcript +--- +↳ mock-model delegated to mock-model-alt · Write snapshot tests for TreeRow · started + brief Write snapshot tests for TreeRow + Cover depths 0 to 3. Do not touch picker.rs. + child session 00000000-0000-0000-0000-000000000002 diff --git a/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__user_delegation_approval.snap b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__user_delegation_approval.snap new file mode 100644 index 000000000..b7c2b81ff --- /dev/null +++ b/nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__user_delegation_approval.snap @@ -0,0 +1,14 @@ +--- +source: tui/src/chatwidget/tests/delegation.rs +expression: rendered +--- + Would you like to start a mock-model-alt session for your task? + + asked by you, with /delegate + runs on mock-model-alt · a different agent from this session + task Review the parser + +› 1. Yes, start it + 2. No, decline + + Press enter to confirm or esc to decline diff --git a/nori-rs/tui/src/chatwidget/user_input.rs b/nori-rs/tui/src/chatwidget/user_input.rs index e00cd071a..7ee0c7b10 100644 --- a/nori-rs/tui/src/chatwidget/user_input.rs +++ b/nori-rs/tui/src/chatwidget/user_input.rs @@ -141,10 +141,8 @@ impl ChatWidget { .managed_conversation_id .and_then(|id| self.session_manager.get(&id)) .is_some_and(|record| { - matches!( - record.status, - nori_protocol::SessionStatus::Closed | nori_protocol::SessionStatus::Failed - ) + record.status.is_closed() + || record.status == nori_protocol::SessionStatus::Failed }) { self.add_error_message("This child session has ended. Its history remains available; return to its parent or start /new.".into()); diff --git a/nori-rs/tui/src/delegation.rs b/nori-rs/tui/src/delegation.rs index 084b526ea..1bcdd0923 100644 --- a/nori-rs/tui/src/delegation.rs +++ b/nori-rs/tui/src/delegation.rs @@ -1,6 +1,21 @@ -//! Shared command syntax and minimal delegation labels for both terminal frontends. +//! Command syntax and presentation of delegated child sessions, shared by the +//! local and attached terminal frontends. +//! +//! A delegation reads as one compact line while its child works and as a +//! short result block once it ends. The full brief and result stay in the +//! transcript view so many delegations remain readable on screen. use nori_protocol::Delegation; +use nori_protocol::DelegationOrigin; use nori_protocol::DelegationStatus; +use ratatui::style::Stylize; +use ratatui::text::Line; +use ratatui::text::Span; +use unicode_width::UnicodeWidthStr; + +use crate::history_cell::HistoryCell; + +/// Result lines shown on screen before the rest moves to the transcript view. +const RESULT_PREVIEW_LINES: i32 = 6; pub(crate) fn parse_command(text: &str) -> Option<Result<(String, String), String>> { let rest = text.strip_prefix("/delegate")?; @@ -18,22 +33,296 @@ pub(crate) fn parse_command(text: &str) -> Option<Result<(String, String), Strin }) } -pub(crate) fn summary(delegation: &Delegation) -> String { - let status = match delegation.status { - DelegationStatus::AwaitingApproval => "awaiting approval", - DelegationStatus::Running => "running", - DelegationStatus::Declined => "declined", - DelegationStatus::Completed => "completed", - DelegationStatus::Failed => "failed", - DelegationStatus::Cancelled => "cancelled", +/// Key names a frontend offers next to a delegation; `None` hides the hint. +#[derive(Clone, Debug, Default)] +pub(crate) struct DelegationHints { + /// Opens the transcript view, where the full brief and result are shown. + pub(crate) transcript: Option<String>, + /// Opens the session list, where the child's history can be opened. + pub(crate) sessions: Option<String>, +} + +/// Who asked for the child, as the parent's transcript names them. +fn requester(delegation: &Delegation) -> String { + match delegation.origin { + DelegationOrigin::User => "you".to_owned(), + DelegationOrigin::Agent => delegation.parent_agent.clone(), + } +} + +/// A card keeps the word it was printed with, so a running child's card says +/// it started rather than claiming it is still working. +fn status_span(status: DelegationStatus) -> Span<'static> { + let word = match status { + DelegationStatus::Running => "started", + DelegationStatus::AwaitingApproval + | DelegationStatus::Completed + | DelegationStatus::Failed + | DelegationStatus::Declined + | DelegationStatus::Cancelled => nori_protocol::delegation_status_word(status), + }; + match status { + DelegationStatus::AwaitingApproval => { + Span::styled(word, crate::style::component_theme().warning) + } + DelegationStatus::Running => word.cyan(), + DelegationStatus::Completed => word.green(), + DelegationStatus::Failed => word.red(), + DelegationStatus::Declined | DelegationStatus::Cancelled => word.dim(), + } +} + +/// The child as `agent · name`, the form every delegation surface uses. +fn child_spans(delegation: &Delegation, name: String) -> Vec<Span<'static>> { + vec![delegation.agent.clone().bold(), " · ".dim(), name.into()] +} + +/// The fewest cells a card gives the child's name before it lets the +/// header wrap instead. +const MIN_CARD_NAME: usize = 8; + +/// The collapsed line a delivered result prompt reads as, after its `› ` +/// marker, in at most `width` cells when it can: ` · delivered to this +/// session` gives way first, then the child's name is cut in the middle. +/// `None` for text that is not a result prompt. +pub(crate) fn delivered_result_spans(message: &str, width: usize) -> Option<Vec<Span<'static>>> { + const DELIVERED: &str = " · delivered to this session"; + const MIN_NAME: usize = 4; + let parts = nori_protocol::delegation_result_parts(message)?; + let lead = format!("from {} · ", parts.agent); + let status = format!(" · {}", parts.status); + let fixed = "delegation result ".width() + lead.width() + status.width(); + let name_width = parts.name.width(); + let (name, delivered) = if fixed + name_width + DELIVERED.width() <= width { + (parts.name.to_owned(), true) + } else { + let room = width.saturating_sub(fixed).max(MIN_NAME); + (crate::session_path::fit_name(parts.name, room), false) + }; + let mut spans = vec![ + "delegation result ".dim(), + lead.into(), + name.into(), + status.into(), + ]; + if delivered { + spans.push(DELIVERED.dim()); + } + Some(spans) +} + +fn first_line(text: &str) -> &str { + text.lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .unwrap_or_default() +} + +/// The question, attribution rows, and task shown before a child of a +/// different agent kind starts. +pub(crate) fn approval_lines(delegation: &Delegation) -> (String, Vec<Line<'static>>) { + let (title, asked_by) = match delegation.origin { + DelegationOrigin::User => ( + format!( + "Would you like to start a {} session for your task?", + delegation.agent + ), + "you, with /delegate".to_owned(), + ), + DelegationOrigin::Agent => ( + format!( + "Would you like {} to start a {} session?", + delegation.parent_agent, delegation.agent + ), + format!("{} (this session)", delegation.parent_agent), + ), }; - let mut message = format!( - "Child {} ({}) · parent {} ({}) · {status}", - delegation.child_id, delegation.agent, delegation.parent_id, delegation.parent_agent, - ); - if let Some(result) = &delegation.result { - message.push('\n'); - message.push_str(result); - } - message + let label = |name: &'static str| format!("{name:<10}").dim(); + let mut lines = vec![ + Line::from(vec![label("asked by"), asked_by.into()]), + Line::from(vec![ + label("runs on"), + delegation.agent.clone().bold(), + " · a different agent from this session".dim(), + ]), + ]; + let mut task = delegation.task.lines(); + lines.push(Line::from(vec![ + label("task"), + task.next().unwrap_or_default().to_owned().into(), + ])); + lines.extend(task.map(|line| Line::from(format!("{:<10}{line}", "")))); + (title, lines) +} + +/// One delegation state change in the parent's transcript. +#[derive(Debug)] +pub(crate) struct DelegationCell { + delegation: Delegation, + hints: DelegationHints, +} + +impl DelegationCell { + pub(crate) fn new(delegation: Delegation, hints: DelegationHints) -> Self { + Self { delegation, hints } + } + + /// The header in one row of `width` cells when it can: the child's name + /// is cut in the middle to the room the rest leaves. + fn header(&self, width: u16) -> Line<'static> { + let full_name = nori_protocol::session_full_name(&self.delegation.task) + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_owned()); + let fixed = self.header_spans(String::new(), false).width(); + let room = usize::from(width).saturating_sub(fixed).max(MIN_CARD_NAME); + self.header_spans(crate::session_path::fit_name(&full_name, room), true) + } + + /// The header with `name` for the child; a failure or cancellation reason + /// follows only `with_reason`, and wraps rather than taking the name's + /// room. + fn header_spans(&self, name: String, with_reason: bool) -> Line<'static> { + let delegation = &self.delegation; + let mut spans = match delegation.status { + DelegationStatus::AwaitingApproval | DelegationStatus::Running => { + let mut spans = vec![ + "↳ ".dim(), + format!("{} delegated to ", requester(delegation)).into(), + ]; + spans.extend(child_spans(delegation, name)); + spans + } + DelegationStatus::Completed => { + let mut spans = vec!["○ ".green(), "result from ".into()]; + spans.extend(child_spans(delegation, name)); + spans + } + DelegationStatus::Failed => { + let mut spans = vec!["✕ ".red()]; + spans.extend(child_spans(delegation, name)); + spans + } + DelegationStatus::Declined | DelegationStatus::Cancelled => { + let mut spans = vec!["✕ ".dim(), "delegation to ".dim()]; + spans.extend(child_spans(delegation, name)); + spans + } + }; + spans.push(" · ".dim()); + spans.push(status_span(delegation.status)); + if delegation.status == DelegationStatus::Declined { + spans.push(" by you".dim()); + } + let reason = first_line(delegation.result.as_deref().unwrap_or_default()); + if with_reason + && matches!( + delegation.status, + DelegationStatus::Failed | DelegationStatus::Cancelled + ) + && !reason.is_empty() + { + spans.push(format!(" · {reason}").dim()); + } + Line::from(spans) + } + + fn footer(&self) -> Option<Line<'static>> { + let delegation = &self.delegation; + let mut parts = match delegation.status { + DelegationStatus::AwaitingApproval | DelegationStatus::Running => { + return self + .hints + .transcript + .as_ref() + .map(|key| Line::from(format!(" {key} shows the brief").dim())); + } + DelegationStatus::Completed => { + vec![format!("returns to {} on its own", delegation.parent_agent)] + } + DelegationStatus::Failed => { + vec![format!("sent to {} as a failure", delegation.parent_agent)] + } + DelegationStatus::Declined | DelegationStatus::Cancelled => return None, + }; + if let Some(key) = &self.hints.sessions { + parts.push(format!("its history: {key}")); + } + Some(Line::from(format!(" {}", parts.join(" · ")).dim())) + } + + /// The result text under a rail, each source line wrapped on its own so + /// continuation rows keep the rail. + fn result_lines(&self, width: u16, limit: Option<i32>) -> Vec<Line<'static>> { + if self.delegation.status != DelegationStatus::Completed { + return Vec::new(); + } + let result = self.delegation.result.as_deref().unwrap_or_default(); + let lines: Vec<&str> = result.trim_end().lines().collect(); + if lines.is_empty() { + return vec![Line::from(vec![" ▏ ".dim(), "(no text)".dim().italic()])]; + } + let shown = limit + .and_then(|limit| usize::try_from(limit).ok()) + .map_or(lines.len(), |limit| limit.min(lines.len())); + let rail = || Line::from(" ▏ ".dim()); + let mut out: Vec<Line<'static>> = lines[..shown] + .iter() + .flat_map(|line| { + crate::wrapping::word_wrap_lines( + [Line::from((*line).to_owned())], + crate::wrapping::RtOptions::new(usize::from(width.max(1))) + .initial_indent(rail()) + .subsequent_indent(rail()), + ) + }) + .collect(); + if shown < lines.len() { + let more = lines.len() - shown; + let hint = self + .hints + .transcript + .as_ref() + .map(|key| format!(" · {key} shows all")) + .unwrap_or_default(); + out.push(Line::from(format!(" ▏ … {more} more lines{hint}").dim())); + } + out + } +} + +impl HistoryCell for DelegationCell { + fn display_lines(&self, width: u16) -> Vec<Line<'static>> { + let mut lines = vec![self.header(width)]; + lines.extend(self.result_lines(width, Some(RESULT_PREVIEW_LINES))); + lines.extend(self.footer()); + wrap_each(&lines, width) + } + + fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> { + let mut lines = vec![self.header(width)]; + let mut brief = self.delegation.task.lines(); + lines.push(Line::from(vec![ + " brief ".dim(), + brief.next().unwrap_or_default().to_owned().into(), + ])); + lines.extend(brief.map(|line| Line::from(format!(" {line}")))); + lines.extend(self.result_lines(width, None)); + lines.push(Line::from( + format!(" child session {}", self.delegation.child_id).dim(), + )); + wrap_each(&lines, width) + } +} + +/// Wrap every line on its own so a wrapped line continues under its text. +fn wrap_each(lines: &[Line<'static>], width: u16) -> Vec<Line<'static>> { + lines + .iter() + .flat_map(|line| { + crate::wrapping::word_wrap_lines( + [line], + crate::wrapping::RtOptions::new(usize::from(width.max(1))) + .subsequent_indent(" ".into()), + ) + }) + .collect() } diff --git a/nori-rs/tui/src/history_cell/mod.rs b/nori-rs/tui/src/history_cell/mod.rs index 42aa4d735..c99187f9a 100644 --- a/nori-rs/tui/src/history_cell/mod.rs +++ b/nori-rs/tui/src/history_cell/mod.rs @@ -84,7 +84,29 @@ pub(crate) struct UserHistoryCell { } impl HistoryCell for UserHistoryCell { + /// A child's result reaches its parent as user input; on screen it reads + /// as one line because its result block was already shown when the child + /// ended. The transcript view keeps the exact text the agent received. fn display_lines(&self, width: u16) -> Vec<Line<'static>> { + let Some(spans) = crate::delegation::delivered_result_spans( + &self.message, + usize::from(width).saturating_sub(2), + ) else { + return self.transcript_lines(width); + }; + let style = user_message_style(); + let mut line = Line::from(vec!["› ".bold().dim()]); + line.spans.extend(spans); + let mut lines = vec![Line::from("").style(style)]; + lines.extend(word_wrap_lines( + [line.style(style)], + RtOptions::new(usize::from(width.max(1))).subsequent_indent(" ".into()), + )); + lines.push(Line::from("").style(style)); + lines + } + + fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> { let mut lines: Vec<Line<'static>> = Vec::new(); let wrap_width = width diff --git a/nori-rs/tui/src/lib.rs b/nori-rs/tui/src/lib.rs index 592c2060d..330d6a65b 100644 --- a/nori-rs/tui/src/lib.rs +++ b/nori-rs/tui/src/lib.rs @@ -72,6 +72,7 @@ mod remote_control; mod render; mod resume_picker; mod session_log; +mod session_path; mod session_preview; pub mod session_stats; mod session_status; diff --git a/nori-rs/tui/src/nori/hotkey_picker.rs b/nori-rs/tui/src/nori/hotkey_picker.rs index 6981629cb..40b6ae7cc 100644 --- a/nori-rs/tui/src/nori/hotkey_picker.rs +++ b/nori-rs/tui/src/nori/hotkey_picker.rs @@ -356,6 +356,7 @@ mod tests { (HotkeyAction::NextSession, "alt+.".to_string()), (HotkeyAction::NextWaitingSession, "alt+down".to_string()), (HotkeyAction::OpenSessionList, "alt+s".to_string()), + (HotkeyAction::ParentSession, "alt+up".to_string()), ] ); } diff --git a/nori-rs/tui/src/public_widgets/composer_input.rs b/nori-rs/tui/src/public_widgets/composer_input.rs index ad4233e22..b7f38c1b3 100644 --- a/nori-rs/tui/src/public_widgets/composer_input.rs +++ b/nori-rs/tui/src/public_widgets/composer_input.rs @@ -55,6 +55,18 @@ impl ComposerInput { self.inner.is_empty() } + /// Take the whole edit (text, pastes, attachments, cursor), leaving the + /// input empty. + pub(crate) fn take_draft(&mut self) -> crate::bottom_pane::ComposerDraft { + self.inner.take_draft() + } + + /// Put back an edit taken with [`Self::take_draft`]. + pub(crate) fn restore_draft(&mut self, draft: crate::bottom_pane::ComposerDraft) { + self.inner.restore_draft(draft); + self.drain_app_events(); + } + /// Clear the input text. pub fn clear(&mut self) { self.inner.set_text_content(String::new()); diff --git a/nori-rs/tui/src/session_path.rs b/nori-rs/tui/src/session_path.rs new file mode 100644 index 000000000..7e73895d8 --- /dev/null +++ b/nori-rs/tui/src/session_path.rs @@ -0,0 +1,608 @@ +//! Lines that name a session by where it sits in its family, fitted to the +//! terminal width: the breadcrumb inside a delegated child and the line about +//! a session waiting on the user. + +use ratatui::style::Stylize; +use ratatui::text::Line; +use ratatui::text::Span; +use unicode_width::UnicodeWidthStr; + +/// One session on the way from a top-level session to the one on screen. +#[derive(Clone, Debug)] +pub(crate) struct PathStep { + pub(crate) agent: String, + pub(crate) name: String, +} + +const PATH_SEPARATOR: &str = " › "; +const ELIDED: &str = "…"; + +/// `text` cut to at most `cells` display cells, ending in `…` when cut. +pub(crate) fn fit(text: &str, cells: usize) -> String { + if text.width() <= cells { + return text.to_string(); + } + if cells == 0 { + return String::new(); + } + let mut kept = String::new(); + for ch in text.chars() { + if kept.width() + ch.to_string().width() + 1 > cells { + break; + } + kept.push(ch); + } + format!("{}…", kept.trim_end()) +} + +/// `text` cut to at most `cells` display cells, keeping its start and end +/// around `…`, so names that share a long prefix still read apart. +pub(crate) fn fit_name(text: &str, cells: usize) -> String { + nori_tui_components::text::truncate_middle(text, cells) +} + +/// Share `room` cells between names, so a short name leaves its unused cells +/// to the longer ones. +fn share(names: &[&str], room: usize) -> Vec<usize> { + let mut budgets = vec![0; names.len()]; + let mut open: Vec<usize> = (0..names.len()).collect(); + let mut left = room; + while !open.is_empty() { + let each = left / open.len(); + let (fits, cut): (Vec<usize>, Vec<usize>) = open + .iter() + .partition(|index| names[**index].width() <= each); + if fits.is_empty() { + for (position, index) in cut.iter().enumerate() { + budgets[*index] = each + usize::from(position < left % open.len()); + } + break; + } + for index in fits { + budgets[index] = names[index].width(); + left -= budgets[index]; + } + open = cut; + } + budgets +} + +/// The fewest cells a session other than the current one keeps before the +/// key back to the parent gives way. +const MIN_OTHER: usize = 8; +/// The fewest cells any name keeps on a terminal too narrow for the rest. +const MIN_NAME_CELLS: usize = 4; + +/// `root › … › current` with each session's agent, followed by `status` and +/// `key` (the key back to the parent), in at most `width` cells. +/// +/// The top-level session and the current one always stay. When space runs +/// short, sessions between them give way to `…` first, then the key, then the +/// agent labels, and the current session's name is cut last. +pub(crate) fn breadcrumb_line( + path: &[PathStep], + status: &str, + key: &str, + width: u16, +) -> Line<'static> { + let width = usize::from(width); + let whole: Vec<Option<&PathStep>> = path.iter().map(Some).collect(); + let elided: Vec<Option<&PathStep>> = match path { + [root, .., current] if path.len() > 2 => vec![Some(root), None, Some(current)], + _ => whole.clone(), + }; + let with_status = format!("{status}{key}"); + let layouts = [ + (&whole, with_status.as_str(), true), + (&elided, with_status.as_str(), true), + (&whole, status, true), + (&elided, status, true), + (&elided, status, false), + ]; + let last = layouts.len() - 1; + for (index, (steps, tail, with_agents)) in layouts.into_iter().enumerate() { + let fixed = tail.width() + + PATH_SEPARATOR.width() * steps.len().saturating_sub(1) + + steps + .iter() + .map(|step| { + step.map_or(ELIDED.width(), |step| { + agent_label(step, with_agents).width() + }) + }) + .sum::<usize>(); + let names: Vec<&str> = steps + .iter() + .flatten() + .map(|step| step.name.as_str()) + .collect(); + let room = width.saturating_sub(fixed); + // The last layout keeps other names readable too, unless the terminal + // is too narrow to give the current name a fair share. + let readable = names[..names.len().saturating_sub(1)] + .iter() + .map(|name| name.width().min(MIN_OTHER)) + .sum::<usize>(); + let floor = if index != last || room >= readable + MIN_OTHER * 2 { + MIN_OTHER + } else { + MIN_NAME_CELLS + }; + let budgets = share_current_last(&names, room, floor); + let fits = names + .iter() + .zip(&budgets) + .enumerate() + .all(|(at, (name, budget))| { + *budget + >= if at + 1 == names.len() { + name.width() + } else { + name.width().min(floor) + } + }); + if !fits && index != last { + continue; + } + let mut spans: Vec<Span<'static>> = Vec::new(); + let mut named = 0; + let current = steps.len().saturating_sub(1); + for (position, step) in steps.iter().enumerate() { + if position > 0 { + spans.push(PATH_SEPARATOR.dim()); + } + match step { + Some(step) => { + if with_agents { + spans.push(agent_label(step, true).dim()); + } + let name = fit_name(&step.name, budgets[named]); + named += 1; + spans.push(if position == current { + name.bold() + } else { + name.into() + }); + } + None => spans.push(ELIDED.dim()), + } + } + spans.push(tail.to_string().dim()); + return clip(Line::from(spans), width); + } + Line::default() +} + +fn agent_label(step: &PathStep, with_agents: bool) -> String { + if with_agents { + format!("{} · ", step.agent) + } else { + String::new() + } +} + +/// Share `room` cells so the last name (the current session) is cut last: +/// every other name keeps up to `floor` cells, the current name takes what it +/// needs from the rest, and the others share what it leaves. +fn share_current_last(names: &[&str], room: usize, floor: usize) -> Vec<usize> { + let Some((current, others)) = names.split_last() else { + return Vec::new(); + }; + let reserved = others + .iter() + .map(|name| name.width().min(floor)) + .sum::<usize>(); + let current_budget = current.width().min(room.saturating_sub(reserved)); + let mut budgets = share(others, room - current_budget); + budgets.push(current_budget); + budgets +} + +/// `● parent › child is waiting on you · request (+N more) · key to jump`, in +/// at most `width` cells. Names come first; the request text gets what they +/// leave, and every name keeps a share when space is short. +pub(crate) fn waiting_line( + path: &[String], + request: Option<&str>, + more: usize, + jump_key: Option<&str>, + width: u16, +) -> Line<'static> { + let width = usize::from(width); + let marker = "● "; + let label = format!(" is {}", crate::session_status::WAITING_ON_YOU_LABEL); + let more = if more > 0 { + format!(" (+{more} more)") + } else { + String::new() + }; + let key = jump_key + .map(|key| format!(" · {key} to jump")) + .unwrap_or_default(); + let request_sep = " · "; + let fixed = marker.width() + + label.width() + + more.width() + + key.width() + + PATH_SEPARATOR.width() * path.len().saturating_sub(1); + let names: Vec<&str> = path.iter().map(String::as_str).collect(); + let room = width.saturating_sub(fixed); + let names_full = names.iter().map(|name| name.width()).sum::<usize>(); + let request_room = request.map_or(0, |request| { + let wanted = request.width() + request_sep.width(); + // Names come first. A cut request is shown only while it stays + // readable and every name keeps a readable start. + let left = room.saturating_sub(names_full); + if left >= wanted || left >= MIN_REQUEST { + left.min(wanted) + } else if room.saturating_sub(MIN_REQUEST) >= MIN_NAME * names.len() { + MIN_REQUEST.min(wanted) + } else { + 0 + } + }); + let budgets = share(&names, room.saturating_sub(request_room)); + let mut spans = vec![Span::styled( + marker, + crate::style::component_theme().warning, + )]; + let path_text = names + .iter() + .zip(budgets) + .map(|(name, budget)| fit_name(name, budget)) + .collect::<Vec<_>>() + .join(PATH_SEPARATOR); + spans.push(path_text.bold()); + spans.push(label.into()); + if let Some(request) = request + && request_room > request_sep.width() + { + spans.push( + format!( + "{request_sep}{}", + fit(request, request_room - request_sep.width()) + ) + .dim(), + ); + } + if !more.is_empty() { + spans.push(more.dim()); + } + if !key.is_empty() { + spans.push(key.dim()); + } + clip(Line::from(spans), width) +} + +/// The fewest cells a cut request text gets, separator included. +const MIN_REQUEST: usize = 20; +/// The fewest cells a name keeps before a request gives way to it. +const MIN_NAME: usize = 16; + +/// `line` cut to `width` cells, for terminals too narrow for its fixed parts. +fn clip(line: Line<'static>, width: usize) -> Line<'static> { + if line.width() <= width { + return line; + } + if width == 0 { + return Line::default(); + } + // Leave one cell for the ellipsis that marks the cut. + let mut left = width - 1; + let mut spans = Vec::new(); + 'spans: for span in line.spans { + let mut kept = String::new(); + for ch in span.content.chars() { + let cells = ch.to_string().width(); + if cells > left { + spans.push(Span::styled(kept, span.style)); + break 'spans; + } + left -= cells; + kept.push(ch); + } + spans.push(Span::styled(kept, span.style)); + } + spans.push(Span::raw("…")); + Line::from(spans) +} + +#[cfg(test)] +mod tests { + use super::*; + use unicode_width::UnicodeWidthStr; + + fn text(line: &Line<'_>) -> String { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect() + } + + fn step(agent: &str, name: &str) -> PathStep { + PathStep { + agent: agent.into(), + name: name.into(), + } + } + + /// Each case rendered at its width, with a ruler, so a snapshot shows + /// what fits. + fn render(cases: &[(&str, u16, Line<'static>)]) -> String { + cases + .iter() + .map(|(label, width, line)| { + let text = text(line); + assert!( + text.width() <= usize::from(*width), + "{label}: {} cells > {width}: {text}", + text.width() + ); + format!("{label} @{width}\n{text}\n") + }) + .collect::<Vec<_>>() + .join("\n") + } + + const SHARED: &str = "mock:delegate mock-model inspect the parser"; + const KEY: &str = " · alt + up to parent"; + + #[test] + fn breadcrumbs_show_the_whole_path_and_fit_the_width() { + let three = [ + step("claude-code", "Ship tree-row picker"), + step("codex", "Port picker"), + step("pi", "Write snapshot tests"), + ]; + let shared = [ + step("mock-model", SHARED), + step("mock-model-alt", &format!("{SHARED} again")), + ]; + let long = [ + step( + "mock-model", + "A parent session with a very long title indeed", + ), + step( + "mock-model-alt", + "A child with a very long title that goes on", + ), + step( + "mock-model", + "A grandchild whose title is also very long here", + ), + ]; + insta::assert_snapshot!(render(&[ + ("three levels", 120, breadcrumb_line(&three, "", KEY, 120)), + ("three levels", 78, breadcrumb_line(&three, "", KEY, 78)), + ("shared prefix", 120, breadcrumb_line(&shared, "", KEY, 120)), + ("shared prefix", 78, breadcrumb_line(&shared, "", KEY, 78)), + ("long names", 118, breadcrumb_line(&long, "", KEY, 118)), + ("long names", 78, breadcrumb_line(&long, "", KEY, 78)), + ("long names", 40, breadcrumb_line(&long, "", KEY, 40)), + ])); + } + + const SHARED_PARENT: &str = "shared prefix for the parser review: parent side"; + const SHARED_CHILD: &str = + "shared prefix for the parser review: child side mock:request-permission:z"; + + #[test] + fn names_sharing_a_long_prefix_stay_apart() { + let crumb = text(&breadcrumb_line( + &[ + step("mock-model", SHARED_PARENT), + step("mock-model-alt", SHARED_CHILD), + ], + " · waiting on you", + " · alt+up parent", + 120, + )); + assert!(crumb.contains("parent side"), "{crumb}"); + assert!(crumb.contains("permission:z"), "{crumb}"); + let waiting = text(&waiting_line( + &[SHARED_PARENT.to_string(), SHARED_CHILD.to_string()], + None, + 0, + Some("alt + down"), + 120, + )); + assert!(waiting.contains("parent side ›"), "{waiting}"); + assert!(waiting.contains("permission:z is waiting"), "{waiting}"); + } + + #[test] + fn a_cut_name_keeps_its_start_and_end() { + assert_eq!(fit_name("Review the parser", 40), "Review the parser"); + let cut = fit_name("shared prefix for the parser review: parent side", 20); + assert!(cut.width() <= 20, "{cut}"); + assert!(cut.starts_with("shared"), "{cut}"); + assert!(cut.ends_with("side"), "{cut}"); + assert!(cut.contains('…'), "{cut}"); + for (wide, cells) in [("界界界界界界界界", 7), ("👩‍💻👩‍💻👩‍💻👩‍💻", 5), ("abcdef", 1)] + { + let cut = fit_name(wide, cells); + assert!(cut.width() <= cells, "{wide} @{cells}: {cut}"); + assert!(cut.contains('…'), "{wide} @{cells}: {cut}"); + } + let joined = fit_name("👩‍💻👩‍💻👩‍💻👩‍💻", 5); + assert_eq!( + joined.replace("👩‍💻", "").replace('…', ""), + "", + "graphemes stay whole: {joined:?}" + ); + } + + #[test] + fn a_long_current_name_still_leaves_the_root_readable() { + let path = [ + step("mock-model", "Ship tree-row picker"), + step( + "mock-model-alt", + "mock:request-permission:a delegated task line that runs on for well over eighty cells in total", + ), + ]; + let line = text(&breadcrumb_line( + &path, + " · waiting on you", + " · alt+up parent", + 119, + )); + let root = line.split(" › ").next().unwrap_or_default(); + assert!(root.width() >= 8 && root.contains("Ship"), "{line}"); + assert!( + line.contains("eighty cells in total · waiting on you"), + "{line}" + ); + } + + #[test] + fn the_key_gives_way_before_the_current_name_is_cut() { + let grandchild = [ + step("mock-model", "mock:delegate mock-model mock:delegate mo"), + step("mock-model", "mock:delegate mock-model mock:request-pe"), + step("mock-model", "mock:request-permission:x"), + ]; + let status = " · waiting on you"; + let key = " · alt+up parent"; + let narrow = text(&breadcrumb_line(&grandchild, status, key, 79)); + assert!( + narrow.contains("mock:request-permission:x · waiting on you"), + "{narrow}" + ); + assert!(!narrow.contains("alt+up"), "{narrow}"); + let wide = text(&breadcrumb_line(&grandchild, status, key, 119)); + assert!( + wide.ends_with("mock:request-permission:x · waiting on you · alt+up parent"), + "{wide}" + ); + } + + #[test] + fn a_breadcrumb_never_drops_its_root_or_its_current_session() { + let long = [ + step( + "mock-model", + "A parent session with a very long title indeed", + ), + step( + "mock-model-alt", + "A child with a very long title that goes on", + ), + step( + "mock-model", + "A grandchild whose title is also very long here", + ), + ]; + for width in [118, 100, 78] { + let line = text(&breadcrumb_line(&long, "", KEY, width)); + assert!(line.contains("A parent"), "@{width}: {line}"); + assert!( + line.contains("A grandchild whose title is also very long here"), + "@{width}: {line}" + ); + } + let wide = text(&breadcrumb_line(&long, "", KEY, 118)); + assert!(wide.ends_with(KEY), "{wide}"); + } + + #[test] + fn waiting_lines_name_parent_and_child_as_fully_as_the_width_allows() { + let child = [ + "Ship tree-row picker".to_string(), + "mock:request-permission:cargo test --workspace".to_string(), + ]; + let shared = [SHARED.to_string(), format!("{SHARED} again")]; + let root = ["Spike transport".to_string()]; + let request = Some("cargo test --workspace --all-features"); + insta::assert_snapshot!(render(&[ + ( + "child", + 118, + waiting_line(&child, request, 0, Some("alt + down"), 118) + ), + ( + "child", + 78, + waiting_line(&child, request, 0, Some("alt + down"), 78) + ), + ( + "shared prefix", + 118, + waiting_line(&shared, request, 1, Some("alt + down"), 118) + ), + ( + "shared prefix", + 78, + waiting_line(&shared, request, 1, Some("alt + down"), 78) + ), + ( + "top level", + 78, + waiting_line(&root, request, 0, Some("alt + down"), 78) + ), + ("no key", 78, waiting_line(&child, None, 0, None, 78)), + ])); + } + + #[test] + fn a_wide_terminal_shows_names_whole() { + let child = [ + "Ship tree-row picker".to_string(), + "mock:request-permission:cargo test --workspace".to_string(), + ]; + let line = text(&waiting_line( + &child, + Some("cargo test"), + 0, + Some("alt + down"), + 128, + )); + assert!( + line.contains("Ship tree-row picker › mock:request-permission:cargo test --workspace"), + "{line}" + ); + assert!(line.ends_with(" · alt + down to jump"), "{line}"); + } + + #[test] + fn lines_never_exceed_the_terminal_width() { + let long = [ + step( + "mock-model", + "A parent session with a very long title indeed", + ), + step( + "mock-model-alt", + "A child with a very long title that goes on", + ), + step( + "mock-model", + "A grandchild whose title is also very long here", + ), + ]; + let names = ["Ship tree-row picker".to_string(), SHARED.to_string()]; + let alone = ["Spike transport".to_string()]; + for width in 0..=120 { + let lines = [ + breadcrumb_line(&long, "", KEY, width), + breadcrumb_line(&long[..1], "", KEY, width), + waiting_line( + &names, + Some("cargo test --workspace"), + 2, + Some("alt + down"), + width, + ), + waiting_line(&alone, None, 0, Some("alt + down"), width), + ]; + for line in lines { + assert!( + line.width() <= usize::from(width), + "@{width}: {:?}", + text(&line) + ); + } + } + } +} diff --git a/nori-rs/tui/src/session_preview.rs b/nori-rs/tui/src/session_preview.rs index c62e9c815..31a77f04f 100644 --- a/nori-rs/tui/src/session_preview.rs +++ b/nori-rs/tui/src/session_preview.rs @@ -107,16 +107,27 @@ impl SessionPreviews { } SessionPhase::Cancelling { .. } => {} }, + // A `/delegate` sent before any prompt names the session by its + // task. A child's own first prompt is that same task. + SessionEvent::Nori(NoriEvent::DelegationChanged(delegation)) + if preview.first_prompt.is_none() + && delegation.origin == nori_protocol::DelegationOrigin::User => + { + preview.first_prompt = delegation.task.lines().next().map(str::to_owned); + preview.first_prompt_open = false; + } SessionEvent::Nori(NoriEvent::SessionEnded(ended)) => { preview.pending.clear(); preview.running.clear(); + // The status column already says a session closed; its + // description keeps the last thing the agent said. preview.ended = Some(match ended.reason { + SessionEndReason::Shutdown | SessionEndReason::Closed => return, SessionEndReason::ConnectionLost => { "agent exited · resume available".to_string() } SessionEndReason::SpawnFailed => "agent failed to start".to_string(), SessionEndReason::TimedOut => "agent timed out · resume available".to_string(), - SessionEndReason::Shutdown | SessionEndReason::Closed => "closed".to_string(), }); } SessionEvent::Nori(_) => {} @@ -169,6 +180,8 @@ fn observe_update(preview: &mut Preview, update: &acp::SessionUpdate) { acp::SessionUpdate::UserMessageChunk(chunk) => { if let acp::ContentBlock::Text(text) = &chunk.content { match &mut preview.first_prompt { + // A child's result is not the user's own first prompt. + None if nori_protocol::delegation_result_summary(&text.text).is_some() => {} None => { preview.first_prompt = Some(text.text.clone()); preview.first_prompt_open = true; @@ -465,4 +478,63 @@ mod tests { ) ); } + + #[test] + fn a_delegation_result_never_titles_the_session_that_receives_it() { + let mut previews = SessionPreviews::default(); + previews.observe( + 1, + &user_text( + "[Nori delegation result] from mock-model · inspect the parser · done\n\ + Child session: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\nAll good.", + ), + ); + previews.observe(1, &text("Thanks")); + assert_eq!(previews.title(1), None); + previews.observe( + 1, + &SessionEvent::Nori(NoriEvent::SessionPhaseChanged(SessionPhase::Prompting { + request_id: acp::RequestId::Number(2), + })), + ); + previews.observe(1, &user_text("now fix it")); + assert_eq!(previews.title(1), Some("now fix it".to_string())); + } + + #[test] + fn a_session_closed_after_its_work_keeps_its_last_answer_as_preview() { + assert_eq!( + feed(&[ + text("All tests pass."), + SessionEvent::Nori(NoriEvent::SessionEnded(nori_protocol::SessionEnded { + reason: SessionEndReason::Closed, + message: None, + })), + ]), + Some("All tests pass.".to_string()) + ); + } + + #[test] + fn a_delegation_sent_before_any_prompt_names_the_session_by_its_task() { + let delegation = nori_protocol::Delegation { + request_id: "request-1".into(), + parent_id: "parent".into(), + child_id: "child".into(), + parent_agent: "mock-model".into(), + agent: "mock-model".into(), + task: "inspect the parser\nand report".into(), + status: nori_protocol::DelegationStatus::Running, + depth: 1, + result: None, + origin: nori_protocol::DelegationOrigin::User, + }; + let mut previews = SessionPreviews::default(); + previews.observe( + 1, + &SessionEvent::Nori(NoriEvent::DelegationChanged(delegation)), + ); + previews.observe(1, &user_text("now fix it")); + assert_eq!(previews.title(1), Some("inspect the parser".to_string())); + } } diff --git a/nori-rs/tui/src/session_status.rs b/nori-rs/tui/src/session_status.rs index add114c57..334c61b5c 100644 --- a/nori-rs/tui/src/session_status.rs +++ b/nori-rs/tui/src/session_status.rs @@ -41,6 +41,23 @@ pub(crate) fn status_label(status: SessionStatus) -> &'static str { SessionStatus::Ready => "ready", SessionStatus::Failed => "failed", SessionStatus::Closed => "closed", + SessionStatus::Done => "done", + } +} + +/// The color of a status word and glyph in session lists: amber for what +/// needs the user, cyan for work in progress, green for ready, red for +/// failed, the default color for a child that finished its task, and muted +/// for closed and starting sessions. +pub(crate) fn status_tone(status: SessionStatus) -> nori_tui_components::DetailTone { + use nori_tui_components::DetailTone; + match status { + SessionStatus::WaitingOnYou => DetailTone::Warning, + SessionStatus::Working => DetailTone::Info, + SessionStatus::Ready => DetailTone::Success, + SessionStatus::Failed => DetailTone::Error, + SessionStatus::Done => DetailTone::Default, + SessionStatus::Closed | SessionStatus::Starting => DetailTone::Muted, } } diff --git a/nori-rs/tui/src/snapshots/nori_tui__session_path__tests__breadcrumbs_show_the_whole_path_and_fit_the_width.snap b/nori-rs/tui/src/snapshots/nori_tui__session_path__tests__breadcrumbs_show_the_whole_path_and_fit_the_width.snap new file mode 100644 index 000000000..3db2817fa --- /dev/null +++ b/nori-rs/tui/src/snapshots/nori_tui__session_path__tests__breadcrumbs_show_the_whole_path_and_fit_the_width.snap @@ -0,0 +1,24 @@ +--- +source: tui/src/session_path.rs +expression: "render(&[(\"three levels\", 120, breadcrumb_line(&three, \"\", KEY, 120)),\n(\"three levels\", 78, breadcrumb_line(&three, \"\", KEY, 78)),\n(\"shared prefix\", 120, breadcrumb_line(&shared, \"\", KEY, 120)),\n(\"shared prefix\", 78, breadcrumb_line(&shared, \"\", KEY, 78)),\n(\"long names\", 118, breadcrumb_line(&long, \"\", KEY, 118)),\n(\"long names\", 78, breadcrumb_line(&long, \"\", KEY, 78)),\n(\"long names\", 40, breadcrumb_line(&long, \"\", KEY, 40)),])" +--- +three levels @120 +claude-code · Ship tree-row picker › codex · Port picker › pi · Write snapshot tests · alt + up to parent + +three levels @78 +claude-code · Ship…icker › … › pi · Write snapshot tests · alt + up to parent + +shared prefix @120 +mock-model · mock:del…e parser › mock-model-alt · mock:delegate mock-model inspect the parser again · alt + up to parent + +shared prefix @78 +mock:delegate…t the parser › mock:delegate mock-model inspect the parser again + +long names @118 +mock-model · A parent…e indeed › … › mock-model · A grandchild whose title is also very long here · alt + up to parent + +long names @78 +A parent ses…itle indeed › … › A grandchild whose title is also very long here + +long names @40 +A pa…eed › … › A grandchild…ry long here diff --git a/nori-rs/tui/src/snapshots/nori_tui__session_path__tests__waiting_lines_name_parent_and_child_as_fully_as_the_width_allows.snap b/nori-rs/tui/src/snapshots/nori_tui__session_path__tests__waiting_lines_name_parent_and_child_as_fully_as_the_width_allows.snap new file mode 100644 index 000000000..0e797ee7d --- /dev/null +++ b/nori-rs/tui/src/snapshots/nori_tui__session_path__tests__waiting_lines_name_parent_and_child_as_fully_as_the_width_allows.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/session_path.rs +expression: "render(&[(\"child\", 118,\nwaiting_line(&child, request, 0, Some(\"alt + down\"), 118)),\n(\"child\", 78, waiting_line(&child, request, 0, Some(\"alt + down\"), 78)),\n(\"shared prefix\", 118,\nwaiting_line(&shared, request, 1, Some(\"alt + down\"), 118)),\n(\"shared prefix\", 78,\nwaiting_line(&shared, request, 1, Some(\"alt + down\"), 78)),\n(\"top level\", 78, waiting_line(&root, request, 0, Some(\"alt + down\"), 78)),\n(\"no key\", 78, waiting_line(&child, None, 0, None, 78)),])" +--- +child @118 +● Ship tree-row picker › mock:request-perm…test --workspace is waiting on you · cargo test --wor… · alt + down to jump + +child @78 +● Ship tre…w picker › mock:req…orkspace is waiting on you · alt + down to jump + +shared prefix @118 +● mock:delega…the parser › mock:delega…rser again is waiting on you · cargo test --wor… (+1 more) · alt + down to jump + +shared prefix @78 +● mock:d…arser › mock:d…again is waiting on you (+1 more) · alt + down to jump + +top level @78 +● Spike transport is waiting on you · cargo test --works… · alt + down to jump + +no key @78 +● Ship tree-row picker › mock:request-perm…test --workspace is waiting on you