From 1fcb93cf1435c727757a35a66148c8e8b1d2e136 Mon Sep 17 00:00:00 2001 From: Nori Date: Sun, 15 Nov 2026 19:28:15 +0000 Subject: [PATCH 01/16] feat(tui): show delegated child sessions clearly in the parent Delegations read as a one-line card naming the child by its task, agent and status, with the brief in the transcript view. Results arrive as a short block that names the child and points to its history; the delivered prompt collapses to one line. The cross-agent prompt names who asks, which agent runs, and the task. A waiting child's request line names parent and child, children get a breadcrumb and an Alt+Up parent_session key, and host ls plus the attach list show children under their parent with tree glyphs inside TITLE and colored status words. Delegations now record whether the user or the agent asked (origin), and the harness names sessions readably in notices and result prompts. --- nori-rs/Cargo.lock | 1 + nori-rs/cli/Cargo.toml | 1 + nori-rs/cli/src/host/table.rs | 137 +++++++--- .../harness/src/session_manager/delegation.rs | 8 +- .../src/session_manager/delegation_state.rs | 21 +- nori-rs/harness/tests/delegation.rs | 52 +++- nori-rs/nori-config/src/types/mod.rs | 22 +- nori-rs/nori-config/src/types/tests.rs | 8 +- nori-rs/nori-protocol/src/delegation.rs | 66 +++++ nori-rs/nori-protocol/src/lib.rs | 2 + nori-rs/nori-protocol/src/session_event.rs | 13 + nori-rs/tui-components/src/picker/mod.rs | 13 + nori-rs/tui-components/src/picker/render.rs | 10 +- nori-rs/tui-components/src/picker/tree.rs | 44 ++- nori-rs/tui-pty-e2e/src/keys.rs | 3 + nori-rs/tui-pty-e2e/tests/delegation.rs | 109 +++++++- nori-rs/tui-pty-e2e/tests/host_attach.rs | 12 +- ...elegation__delegation_approval_prompt.snap | 20 ++ .../delegation__delegation_session_tree.snap | 38 +++ ..._list__session_list_fork_under_parent.snap | 2 +- nori-rs/tui/src/app/session_keys.rs | 11 + nori-rs/tui/src/app/session_overview.rs | 99 +++++-- nori-rs/tui/src/attach/input.rs | 22 ++ nori-rs/tui/src/attach/mod.rs | 1 + nori-rs/tui/src/attach/render.rs | 76 ++++-- ...h__tests__attached_current_session_id.snap | 5 +- ...ttach__tests__attached_host_restarted.snap | 3 +- ...tests__attached_permission_controller.snap | 2 +- ...h__tests__attached_permission_watcher.snap | 2 +- ...h__tests__delegation_approval_watcher.snap | 14 +- ...h__tests__delegation_child_breadcrumb.snap | 21 ++ ..._attach__tests__delegation_child_list.snap | 6 +- ...tui__attach__tests__delegation_result.snap | 10 +- ...ttach__tests__delegation_session_tree.snap | 21 ++ nori-rs/tui/src/attach/state.rs | 107 +++++--- nori-rs/tui/src/attach/tests.rs | 106 ++++++- .../tui/src/bottom_pane/session_list_view.rs | 66 ++++- nori-rs/tui/src/chatwidget/delegation.rs | 49 ++-- .../tui/src/chatwidget/tests/delegation.rs | 252 +++++++++++++++-- ...legation__completed_delegation_result.snap | 8 + ...legation__delivered_delegation_result.snap | 5 + ...s__delegation__ended_delegation_lines.snap | 10 + ...delegation__local_delegation_approval.snap | 15 +- ...__delegation__running_delegation_line.snap | 6 + ...gation__running_delegation_transcript.snap | 8 + ..._delegation__user_delegation_approval.snap | 14 + nori-rs/tui/src/delegation.rs | 258 ++++++++++++++++-- nori-rs/tui/src/history_cell/mod.rs | 23 ++ nori-rs/tui/src/nori/hotkey_picker.rs | 1 + nori-rs/tui/src/session_status.rs | 14 + 50 files changed, 1549 insertions(+), 268 deletions(-) create mode 100644 nori-rs/nori-protocol/src/delegation.rs create mode 100644 nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_approval_prompt.snap create mode 100644 nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_session_tree.snap create mode 100644 nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_breadcrumb.snap create mode 100644 nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_session_tree.snap create mode 100644 nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__completed_delegation_result.snap create mode 100644 nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__delivered_delegation_result.snap create mode 100644 nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__ended_delegation_lines.snap create mode 100644 nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__running_delegation_line.snap create mode 100644 nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__running_delegation_transcript.snap create mode 100644 nori-rs/tui/src/chatwidget/tests/snapshots/nori_tui__chatwidget__tests__delegation__user_delegation_approval.snap diff --git a/nori-rs/Cargo.lock b/nori-rs/Cargo.lock index 2e56a6300..a8cf58afe 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", 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/src/host/table.rs b/nori-rs/cli/src/host/table.rs index d3da6427f..b7c97bd0a 100644 --- a/nori-rs/cli/src/host/table.rs +++ b/nori-rs/cli/src/host/table.rs @@ -1,4 +1,8 @@ -//! 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; @@ -14,7 +18,25 @@ pub(super) fn format_table(listing: &Value, width: Option, color: bool) - "{}\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() @@ -26,18 +48,11 @@ 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, + let title = format!("{guide}{}", clean("title")); + let title = if depth > 0 && width.is_none() { + format!("{title} (parent {})", clean("parent")) + } else { + title }; let seconds = row["age_seconds"].as_i64().unwrap_or(0).max(0); let age = if seconds < 60 { @@ -64,7 +79,8 @@ pub(super) fn format_table(listing: &Value, width: Option, color: bool) - let status = if color { match row["status"].as_str().unwrap_or_default() { "failed" => status.red().to_string(), - "waiting_on_you" | "working" | "starting" => status.yellow().to_string(), + "waiting_on_you" => status.yellow().to_string(), + "working" | "starting" => status.cyan().to_string(), "ready" => status.green().to_string(), _ => status.dimmed().to_string(), } @@ -137,30 +153,85 @@ 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 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 tty = format_table(&listing, Some(120), false); + 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| &row[82..]).collect::>(), + [ + "Ship tree picker", + "├─ Port picker", + "│ └─ Write snapshot tests", + "└─ Update docs", + "Spike transport", + ], + "{tty}" + ); + assert_eq!(&rows[2][38..54], "mock-model "); + assert_eq!(&rows[1][56..72], "waiting on you "); + let narrow = format_table(&listing, Some(92), false); + assert!(narrow.lines().all(|line| line.width() <= 92), "{narrow}"); assert!( - title.contains(parent), - "child row must identify its parent: {title}" + narrow.lines().nth(3).unwrap()[82..].starts_with("│ └─ "), + "glyphs survive truncation: {narrow}" ); - let tty = format_table(&listing, Some(110), false); - assert!(tty.lines().all(|line| line.width() <= 110)); + let piped = format_table(&listing, None, false); + let child_row = piped.lines().nth(2).unwrap(); + assert_eq!(&child_row[..36], child); assert!( - tty.lines().nth(2).unwrap()[82..].contains("parent 11111111"), - "normal terminal width must retain parent identity" + child_row[82..].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:?}" + ); + } } } diff --git a/nori-rs/harness/src/session_manager/delegation.rs b/nori-rs/harness/src/session_manager/delegation.rs index 9f67e6466..f2807c1ca 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(), diff --git a/nori-rs/harness/src/session_manager/delegation_state.rs b/nori-rs/harness/src/session_manager/delegation_state.rs index c5cef2aa3..50ae39960 100644 --- a/nori-rs/harness/src/session_manager/delegation_state.rs +++ b/nori-rs/harness/src/session_manager/delegation_state.rs @@ -183,10 +183,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 +227,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/tests/delegation.rs b/nori-rs/harness/tests/delegation.rs index 248e242a4..be145105a 100644 --- a/nori-rs/harness/tests/delegation.rs +++ b/nori-rs/harness/tests/delegation.rs @@ -275,6 +275,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) @@ -327,14 +349,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 +450,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 +526,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 +711,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("· completed"), "{reply}"); m.shutdown(Duration::ZERO).await; } 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/src/delegation.rs b/nori-rs/nori-protocol/src/delegation.rs new file mode 100644 index 000000000..2985c1402 --- /dev/null +++ b/nori-rs/nori-protocol/src/delegation.rs @@ -0,0 +1,66 @@ +//! 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: usize = 40; + +/// A short readable name for a session, taken from the first non-empty line of +/// its task or title. +pub fn session_display_name(text: &str) -> Option { + let line = text.lines().map(str::trim).find(|line| !line.is_empty())?; + if line.chars().count() <= NAME_CHARS { + return Some(line.to_owned()); + } + let cut: String = line.chars().take(NAME_CHARS - 1).collect(); + Some(format!("{}…", cut.trim_end())) +} + +/// The readable name of a delegated child. +pub fn delegation_child_name(delegation: &Delegation) -> String { + session_display_name(&delegation.task).unwrap_or_else(|| { + let id: String = delegation.child_id.chars().take(8).collect(); + format!("session {id}") + }) +} + +/// 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 => "ready", + 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. +pub fn delegation_result_prompt(delegation: &Delegation) -> String { + let outcome = match delegation.status { + DelegationStatus::Completed => "completed", + other => delegation_status_word(other), + }; + format!( + "{DELEGATION_RESULT_HEADER} from {} · {} · {outcome}\nChild session: {}\n{}", + delegation.agent, + delegation_child_name(delegation), + delegation.child_id, + delegation.result.as_deref().unwrap_or_default(), + ) +} + +/// The readable summary line of a result prompt, or `None` for other text. +pub fn delegation_result_summary(prompt: &str) -> Option<&str> { + let first = prompt.lines().next()?; + first + .strip_prefix(DELEGATION_RESULT_HEADER) + .map(str::trim) + .filter(|summary| !summary.is_empty()) +} 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_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/src/picker/mod.rs b/nori-rs/tui-components/src/picker/mod.rs index 2c987074e..cd3ad6f84 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; @@ -329,6 +331,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 +359,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 +395,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..4eb61f024 100644 --- a/nori-rs/tui-components/src/picker/render.rs +++ b/nori-rs/tui-components/src/picker/render.rs @@ -437,14 +437,20 @@ 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() { std::mem::take(primary) 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-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..c14beb86b 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -4,6 +4,7 @@ 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() @@ -36,19 +37,20 @@ fn same_kind_child_starts_and_returns_without_approval_or_exiting_terminal() { 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 +88,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 @@ -140,7 +142,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 +153,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 +176,93 @@ 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… › mock:request") + }, + 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 list = session.screen_contents(); + assert!(!list.contains("(parent"), "{list}"); + // The agent still receives the child's ID; mask it for a stable snapshot. + let list = regex::Regex::new("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + .unwrap() + .replace_all(&list, "CHILD-ID") + .into_owned(); + insta::assert_snapshot!( + "delegation_session_tree", + normalize_for_input_snapshot(list) ); } diff --git a/nori-rs/tui-pty-e2e/tests/host_attach.rs b/nori-rs/tui-pty-e2e/tests/host_attach.rs index 4fa40fa4f..9561ecf1e 100644 --- a/nori-rs/tui-pty-e2e/tests/host_attach.rs +++ b/nori-rs/tui-pty-e2e/tests/host_attach.rs @@ -835,14 +835,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/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..bd82312ab --- /dev/null +++ b/nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_session_tree.snap @@ -0,0 +1,38 @@ +--- +source: tui-pty-e2e/tests/delegation.rs +expression: normalize_for_input_snapshot(list) +--- +› parent task identity + +• parent final answer + +↳ you delegated to mock-model-alt · mock:request-permission:write-child-file · working + ctrl + t shows the brief + +⚠ mock-model-alt · mock:request-permission:write-child-file is waiting on you (delegated by mock-model · parent task identity). + Press Alt+Down to answer it. + +○ result from mock-model-alt · mock:request-permission:write-child-file · ready + ▏ child final answerPermission granted with option: allow + returns to mock-model on its own · its history: alt + s + +› delegation result from mock-model-alt · mock:request-permission:write-child-file · completed · delivered to this session + +• Delegation continuation received: [Nori delegation result] from mock-model-alt · mock:request-permission:write-child-file + · completed + Child session: CHILD-ID + child final answerPermission granted with option: allow + + 1 ready + + Sessions 2 · 1 ready tab: waiting only · type to search + + All waiting on you + + Session Agent Status + › ○ parent task identity (current) Mock ACP ready + child final answerPermission granted with option: allow + └─ · mock:request-permission:write-child-file Mock ACP Alt closed + closed + + ↑↓ 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_fork_under_parent.snap b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_fork_under_parent.snap index cd1ded8b7..7630eb994 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 ques… › mock:request-pe… is waiting on you · approve: rm -rf target/… · alt + down to jump 1 waiting on you · 1 ready Sessions 2 · 1 waiting on you · 1 ready tab: waiting only · type to search diff --git a/nori-rs/tui/src/app/session_keys.rs b/nori-rs/tui/src/app/session_keys.rs index 27a17de82..9dc169021 100644 --- a/nori-rs/tui/src/app/session_keys.rs +++ b/nori-rs/tui/src/app/session_keys.rs @@ -39,6 +39,17 @@ impl App { tui.frame_requester().schedule_frame(); return true; } + if pressed(HotkeyAction::ParentSession) + && 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 direction = if pressed(HotkeyAction::PreviousSession) { Direction::Previous } else if pressed(HotkeyAction::NextSession) { diff --git a/nori-rs/tui/src/app/session_overview.rs b/nori-rs/tui/src/app/session_overview.rs index 278db22f4..36c68d1a4 100644 --- a/nori-rs/tui/src/app/session_overview.rs +++ b/nori-rs/tui/src/app/session_overview.rs @@ -23,6 +23,10 @@ const TITLE_CHARS: i32 = 60; /// line fits one row of a 100-column terminal. const REQUEST_LINE_TITLE_CHARS: i32 = 24; const REQUEST_LINE_REQUEST_CHARS: i32 = 28; +/// A child's request names its parent too, so each part is shorter. +const REQUEST_LINE_PARENT_CHARS: i32 = 12; +const REQUEST_LINE_CHILD_CHARS: i32 = 16; +const REQUEST_LINE_CHILD_REQUEST_CHARS: i32 = 24; fn cut(text: &str, limit: i32) -> String { let limit = usize::try_from(limit).unwrap_or(0); @@ -189,20 +193,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::() - ) - }, - ); // A parent speaks for its family: if a child needs the user, so does // the parent row. let shown_status = if depth == 0 { @@ -268,6 +258,7 @@ impl App { let name = self.agent_display_name(agent_name); lines.push(Line::from(format!("Preparing {name}…").dim())); } + lines.extend(self.parent_breadcrumb(&facts)); lines.extend(self.background_request_line(&facts)); if facts.len() > 1 && let Some(summary) = status_summary(facts.iter().map(|fact| fact.status)) @@ -355,23 +346,24 @@ impl App { 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| { + let (title, request_chars) = match first.parent { + Some(parent) => ( format!( - "(parent {}) {title}", - parent.to_string().chars().take(8).collect::() - ) - }, - ); - let title = cut(&title, REQUEST_LINE_TITLE_CHARS); + "{} › {}", + self.session_name(&parent, REQUEST_LINE_PARENT_CHARS), + cut(&title, REQUEST_LINE_CHILD_CHARS) + ), + REQUEST_LINE_CHILD_REQUEST_CHARS, + ), + None => (title, REQUEST_LINE_REQUEST_CHARS), + }; let mut spans = vec![ - "● ".cyan(), + ratatui::text::Span::styled("● ", crate::style::component_theme().warning), 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); + let request = cut(&request, request_chars); spans.push(format!(" · {request}").dim()); } if waiting.len() > 1 { @@ -385,4 +377,61 @@ impl App { } Some(Line::from(spans)) } + + /// A readable name for any session the manager knows: its title in this + /// TUI, else its recorded title, else a short ID. + 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_display_name(&title)) + .map(|title| cut(&title, limit)) + }) + .unwrap_or_else(|| { + let short: String = id.to_string().chars().take(8).collect(); + format!("session {short}") + }) + } + + /// The parent of the delegated child on screen, if any. + pub(super) fn on_screen_parent(&self) -> Option { + 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, with the key that returns to its parent. + fn parent_breadcrumb(&self, facts: &[SessionFacts]) -> Option> { + let parent = self.on_screen_parent()?; + let child = facts.iter().find(|fact| fact.on_screen)?; + let parent_agent = self + .session_manager + .get(&parent) + .map(|record| record.agent) + .unwrap_or_default(); + let child_name = self + .session_title(child.generation, REQUEST_LINE_TITLE_CHARS) + .unwrap_or_else(|| "this session".to_string()); + let mut spans = vec![ + format!("{parent_agent} · ").dim(), + self.session_name(&parent, REQUEST_LINE_TITLE_CHARS).into(), + " › ".dim(), + format!("{} · ", child.agent).dim(), + child_name.bold(), + ]; + let binding = self + .hotkey_config + .binding_for(nori_config::HotkeyAction::ParentSession); + if !binding.is_none() { + spans.push(format!(" · {} to parent", binding.display_name()).dim()); + } + Some(Line::from(spans)) + } } diff --git a/nori-rs/tui/src/attach/input.rs b/nori-rs/tui/src/attach/input.rs index e2d8aa023..6792317ed 100644 --- a/nori-rs/tui/src/attach/input.rs +++ b/nori-rs/tui/src/attach/input.rs @@ -29,6 +29,28 @@ impl Runtime { 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.parent.clone()) + }) + && self + .state + .sessions + .iter() + .any(|row| row.session_id == parent) + { + self.state.selected = Some(parent); + self.state.list_open = false; + self.state.scroll = 0; + self.state.notice = None; + self.state.replay_error = None; + self.subscribe_selected(); + return true; + } if crate::nori::hotkey_match::matches_binding(&self.session_list_binding, &key) { self.state.list_open = !self.state.list_open; self.refresh_list(); 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..e27f4ae93 100644 --- a/nori-rs/tui/src/attach/render.rs +++ b/nori-rs/tui/src/attach/render.rs @@ -57,20 +57,7 @@ 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).render(Rect::new(area.x, area.y + 1, 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 +111,41 @@ pub(super) fn render( composer.render_ref(input, buf); } +/// The selected session's agent, name, and status. Inside a delegated child +/// it is a breadcrumb from the parent with the key that returns there. +fn identity_line(state: &AttachState) -> 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 name = |row: &super::state::SessionRow| { + row.title + .as_deref() + .and_then(nori_protocol::session_display_name) + .unwrap_or_else(|| row.session_id.chars().take(8).collect()) + }; + let Some(current) = row(id) else { + return Line::from(format!(" session · {id}").dim()); + }; + let mut spans = vec![" ".into()]; + if let Some(parent) = current.parent.as_deref().and_then(row) { + spans.extend([ + format!("{} · ", parent.agent).dim(), + name(parent).into(), + " › ".dim(), + ]); + } + spans.extend([ + format!("{} · ", current.agent).dim(), + name(current).bold(), + format!(" · {}", crate::session_status::status_label(current.status)).dim(), + ]); + if current.parent.as_deref().and_then(row).is_some() && !state.parent_binding.is_none() { + spans.push(format!(" · {} parent", state.parent_binding.as_str()).dim()); + } + Line::from(spans) +} + fn notice_lines(state: &AttachState, width: u16) -> Vec> { state .stopped @@ -150,19 +172,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)), ) }) @@ -218,6 +237,11 @@ 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())], 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_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..0e01c7303 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 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..5242e77b7 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 · ready + ▏ 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..60868d288 --- /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 + + + 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..caeeeeab8 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; @@ -35,8 +36,6 @@ pub(super) struct SessionRow { #[serde(default)] pub parent: Option, #[serde(default)] - pub depth: i32, - #[serde(default)] pub delegations: Vec, } @@ -49,6 +48,7 @@ pub(super) enum Part { Tool(Box), Plan(PlanSnapshot), Notice(String), + Delegation(nori_protocol::Delegation), } pub(super) struct Permission { @@ -81,6 +81,8 @@ pub(super) struct AttachState { pub notice: Option, pub replay_error: Option, pub scroll: usize, + /// Key that moves from a delegated child to its parent. + pub parent_binding: nori_config::HotkeyBinding, } impl Default for AttachState { @@ -100,7 +102,8 @@ impl Default for AttachState { ], Vec::new(), ) - .search_placeholder("Title or agent"), + .search_placeholder("Title or agent") + .tree_column("title"), watching: true, connected: false, stopped: None, @@ -109,6 +112,7 @@ impl Default for AttachState { notice: None, replay_error: None, scroll: 0, + parent_binding: nori_config::HotkeyConfig::default().parent_session, } } } @@ -128,45 +132,39 @@ 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::() - ) - }, - ); - 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::()) - .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(|| "New session".into()); + PickerItem::new(row.session_id.clone(), "title", title) + .cell("id", row.session_id.chars().take(8).collect::()) + .cell("agent", row.agent.clone()) + .cell("status", crate::session_status::status_label(row.status)) + .cell_detail_tone("status", crate::session_status::status_tone(row.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(()) } @@ -182,6 +180,12 @@ impl AttachState { .map(|part| match part { Part::Message { text, .. } | Part::Notice(text) => text.clone(), Part::Tool(tool) => tool.title.clone(), + Part::Delegation(delegation) => delegation_cell(delegation) + .display_lines(u16::MAX) + .iter() + .map(ToString::to_string) + .collect::>() + .join("\n"), Part::Plan(plan) => plan .entries .iter() @@ -305,9 +309,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; } @@ -401,3 +407,14 @@ 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(), + ) +} diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs index 7f0dddc9c..456b5fac9 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -367,7 +367,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 +477,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 +522,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 +558,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 +569,92 @@ 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() + .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::>(), + ["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 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 next_waiting_uses_the_configured_binding() { use crossterm::event::KeyCode; 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..33ce0b51b 100644 --- a/nori-rs/tui/src/bottom_pane/session_list_view.rs +++ b/nori-rs/tui/src/bottom_pane/session_list_view.rs @@ -203,15 +203,6 @@ fn glyph(status: SessionStatus) -> &'static str { } } -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> { rows.iter() .map(|row| { @@ -222,7 +213,10 @@ fn items(rows: &[SessionRow]) -> Vec> { ) .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); @@ -438,6 +432,58 @@ mod tests { assert!(parent_line.contains("● parent session"), "{screen}"); } + #[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, - 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, + 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/tests/delegation.rs b/nori-rs/tui/src/chatwidget/tests/delegation.rs index 2adfcab6f..134136a96 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) -> (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::>() + .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,202 @@ fn local_delegation_approval_identifies_parent_child_and_start_decline() { .to_owned() }) .collect::>() - .join("\n"); + .join("\n") +} + +fn delegating_parent() -> (ChatWidget, tokio::sync::mpsc::UnboundedReceiver) { + 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(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("Start") && rendered.contains("Decline"), - "{rendered}" + !screen.contains(CHILD) && !screen.contains(PARENT), + "{screen}" ); assert!( - rendered.contains("mock-model-alt") && rendered.contains("parent"), - "{rendered}" + !screen.contains("Do not touch picker.rs"), + "the brief stays off screen: {screen}" ); assert!( - rendered.contains("00000000-0000-0000-0000-000000000001") - && rendered.contains("00000000-0000-0000-0000-000000000002"), - "approval identifies both sessions: {rendered}" + transcript.contains("Cover depths 0 to 3. Do not touch picker.rs."), + "the transcript view shows the whole brief: {transcript}" ); - insta::assert_snapshot!("local_delegation_approval", rendered); + 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::>() + .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 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::(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] 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..607fdd4dc --- /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 · ready + ▏ 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..783bb64f6 --- /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 · completed · 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..4da146f02 --- /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 · working + 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..cab12cc74 --- /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 · working + 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/delegation.rs b/nori-rs/tui/src/delegation.rs index 084b526ea..a8b004734 100644 --- a/nori-rs/tui/src/delegation.rs +++ b/nori-rs/tui/src/delegation.rs @@ -1,6 +1,20 @@ -//! 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 crate::history_cell::HistoryCell; + +/// Result lines shown on screen before the rest moves to the transcript view. +const RESULT_PREVIEW_LINES: usize = 6; pub(crate) fn parse_command(text: &str) -> Option> { let rest = text.strip_prefix("/delegate")?; @@ -18,22 +32,230 @@ pub(crate) fn parse_command(text: &str) -> Option 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, + /// Opens the session list, where the child's history can be opened. + pub(crate) sessions: Option, +} + +/// 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(), + } +} + +fn status_span(status: DelegationStatus) -> Span<'static> { + let word = 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) -> Vec> { + vec![ + delegation.agent.clone().bold(), + " · ".dim(), + nori_protocol::delegation_child_name(delegation).into(), + ] +} + +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>) { + 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 } + } + + fn header(&self) -> 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)); + spans + } + DelegationStatus::Completed => { + let mut spans = vec!["○ ".green(), "result from ".into()]; + spans.extend(child_spans(delegation)); + spans + } + DelegationStatus::Failed => { + let mut spans = vec!["✕ ".red()]; + spans.extend(child_spans(delegation)); + spans + } + DelegationStatus::Declined | DelegationStatus::Cancelled => { + let mut spans = vec!["✕ ".dim(), "delegation to ".dim()]; + spans.extend(child_spans(delegation)); + 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 matches!( + delegation.status, + DelegationStatus::Failed | DelegationStatus::Cancelled + ) && !reason.is_empty() + { + spans.push(format!(" · {reason}").dim()); + } + Line::from(spans) + } + + fn footer(&self) -> Option> { + 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())) + } + + fn result_lines(&self, limit: Option) -> Vec> { + 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.map_or(lines.len(), |limit| limit.min(lines.len())); + let mut out: Vec> = lines[..shown] + .iter() + .map(|line| Line::from(vec![" ▏ ".dim(), (*line).to_owned().into()])) + .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> { + let mut lines = vec![self.header()]; + lines.extend(self.result_lines(Some(RESULT_PREVIEW_LINES))); + lines.extend(self.footer()); + wrap_each(&lines, width) + } + + fn transcript_lines(&self, width: u16) -> Vec> { + let mut lines = vec![self.header()]; + 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(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> { + 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..7f0c2159e 100644 --- a/nori-rs/tui/src/history_cell/mod.rs +++ b/nori-rs/tui/src/history_cell/mod.rs @@ -84,7 +84,30 @@ 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> { + let Some(summary) = nori_protocol::delegation_result_summary(&self.message) else { + return self.transcript_lines(width); + }; + let style = user_message_style(); + let line = Line::from(vec![ + "› ".bold().dim(), + "delegation result ".dim(), + summary.to_owned().into(), + " · delivered to this session".dim(), + ]); + 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> { let mut lines: Vec> = Vec::new(); let wrap_width = width 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/session_status.rs b/nori-rs/tui/src/session_status.rs index add114c57..c59cfb1a7 100644 --- a/nori-rs/tui/src/session_status.rs +++ b/nori-rs/tui/src/session_status.rs @@ -44,6 +44,20 @@ pub(crate) fn status_label(status: SessionStatus) -> &'static str { } } +/// 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. +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::Closed | SessionStatus::Starting => DetailTone::Muted, + } +} + /// The status word for one session row. A ready session that finished while /// another session was on screen reads `ready · new` until it is viewed. pub(crate) fn status_word(status: SessionStatus, unseen_finish: bool) -> String { From b6806ef12012cf27e761031092b29698398681ed Mon Sep 17 00:00:00 2001 From: Nori Date: Sun, 15 Nov 2026 19:31:52 +0000 Subject: [PATCH 02/16] docs(tui): describe readable delegation, session trees and parent_session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Nori](https://noriagentic.com) Co-Authored-By: Nori --- docs/glossary.md | 3 + docs/remote-control.md | 35 ++++++++---- nori-rs/cli/docs.md | 2 +- nori-rs/cli/src/host/docs.md | 22 +++++-- nori-rs/config.md | 19 ++++++- nori-rs/harness/docs.md | 23 ++++++-- nori-rs/nori-config/docs.md | 2 +- nori-rs/nori-protocol/docs.md | 60 +++++++++++--------- nori-rs/tui-components/docs.md | 16 +++++- nori-rs/tui/docs.md | 101 ++++++++++++++++++++++----------- nori-rs/tui/src/attach/docs.md | 40 +++++++++---- 11 files changed, 227 insertions(+), 96 deletions(-) diff --git a/docs/glossary.md b/docs/glossary.md index edf651e55..afd1b31bd 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -140,6 +140,8 @@ ACP v1 defines prompt turns but no agent-initiated turn primitive. | **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..7753fb443 100644 --- a/docs/remote-control.md +++ b/docs/remote-control.md @@ -384,7 +384,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 +399,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 +414,16 @@ 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 and the parent name is its recorded title, each cut to 40 +characters. 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 · · `, its +second is `Child session: `, and the rest is the child's result +text; the parent's own ID is not included. 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 @@ -490,7 +501,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. TTY output colors status (waiting on you yellow, working/starting cyan, ready green, failed red) and truncates titles to the terminal width; piped output keeps full titles without color and appends ` (parent )` to each child row. | | `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 +586,12 @@ 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, 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. Inside a child, the identity line reads as a +breadcrumb from the parent's agent and name to the child's. Socket loss or a receive-liveness deadline starts recovery. Periodic session list requests keep idle connections observable; receiving JSON renews the 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..ccc762710 100644 --- a/nori-rs/cli/src/host/docs.md +++ b/nori-rs/cli/src/host/docs.md @@ -50,10 +50,24 @@ host ls / host stop ---------------+ SessionManager 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. + Piped output retains full titles without color or a width limit. +- 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, and truncation + cuts the title rather than its guide. Piped output appends + ` (parent )` to each child's title so scripts keep the exact + link; terminal output omits it. + + | Status | Terminal color | + | --- | --- | + | waiting on you | yellow | + | working, starting | cyan | + | ready | green | + | failed | red | + | others | 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 diff --git a/nori-rs/config.md b/nori-rs/config.md index fd218d8d2..44264aac6 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`, @@ -118,6 +119,7 @@ another session and say how to close one. | `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 | | 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 | 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 @@ -141,9 +143,20 @@ 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 names +the parent and child and the `parent_session` key. In the session list, +status words are colored: waiting on you amber, working cyan, ready green, +failed red. 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..6f3f26418 100644 --- a/nori-rs/harness/docs.md +++ b/nori-rs/harness/docs.md @@ -769,7 +769,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 +780,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 +792,28 @@ 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`, 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, child name, and outcome, then the child ID, then the result. + It does not repeat the parent's own ID. The TUI recognizes these prompts by + their `[Nori delegation result]` header. 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 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-protocol/docs.md b/nori-rs/nori-protocol/docs.md index f8f2eee4b..adfd4b3ae 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 @@ -108,6 +89,30 @@ 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. +`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. + +[`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_display_name` | First non-empty trimmed line of a task or title, cut to 40 characters with `…` | +| `delegation_child_name` | The child's display name from its task, else `session ` | +| `delegation_status_word` | `waiting on you`, `working`, `ready`, `failed`, `declined`, or `cancelled`, matching session status words | +| `delegation_result_prompt` | The prompt delivered to the parent: `[Nori delegation result] from · · `, then `Child session: `, then the result text | +| `delegation_result_summary` | The text after `DELEGATION_RESULT_HEADER` on a prompt's first line, or `None` for any other prompt | + +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. Because the +parent TUI recognizes a delivered result only by that header prefix, the +header string is a cross-crate contract. + Session termination reasons are `Shutdown`, `Closed`, `ConnectionLost`, `SpawnFailed`, and `TimedOut`. Raw ACP request and response envelopes retain the original `RequestId`; consumers do not correlate requests from content or from @@ -120,15 +125,16 @@ 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. diff --git a/nori-rs/tui-components/docs.md b/nori-rs/tui-components/docs.md index 9a2805eea..f96fd7ff6 100644 --- a/nori-rs/tui-components/docs.md +++ b/nori-rs/tui-components/docs.md @@ -158,10 +158,22 @@ 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. - `Picker::compact_descriptions(true)` keeps each row's description on a diff --git a/nori-rs/tui/docs.md b/nori-rs/tui/docs.md index 862ce4399..b564d335a 100644 --- a/nori-rs/tui/docs.md +++ b/nori-rs/tui/docs.md @@ -924,6 +924,7 @@ a binding). | `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 | | `open_session_list` | `alt+s` | Needs the composer in front | +| `parent_session` | `alt+up` | Only on a delegated child (record source `Session` with a parent); shows the parent's widget | The Hotkeys view lists these actions only with the flag (`HotkeyAction::is_multi_session`). @@ -957,9 +958,12 @@ in the prompt still moves the cursor. 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, + starting and closed muted. 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,19 +977,24 @@ 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: - +`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: + +- a parent breadcrumb, only while a delegated child is on screen: + ` · › · · to parent`, where the + key is the `parent_session` binding (omitted when unbound). The parent name + comes from `App::session_name`: its title in this TUI, else its replay + journal title, else `session `; - 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`), its request, `+N more` + when others wait, and the `next_waiting_session` key. For a delegated child + the label is `<parent> › <child>` with smaller per-part budgets for parent, + child, and request, so either form fits one row of a 100-column terminal; - 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. @@ -1059,38 +1068,66 @@ 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. +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> · working`, plus `<transcript key> shows the brief` | +| completed | `○ result from <agent> · <child name> · ready`, up to six result lines (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 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 its first line carries the `[Nori delegation result]` +header, [`history_cell`](src/history_cell/mod.rs) shows it on screen as one +line (`› delegation result <summary> · 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. 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. +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 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 diff --git a/nori-rs/tui/src/attach/docs.md b/nori-rs/tui/src/attach/docs.md index a4a1294e9..3998d1c2c 100644 --- a/nori-rs/tui/src/attach/docs.md +++ b/nori-rs/tui/src/attach/docs.md @@ -51,15 +51,34 @@ 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 session title through + `nori_protocol::session_display_name` (else the short ID). Inside a delegated + child whose parent is listed, it becomes a breadcrumb + `<parent agent> · <parent name> › <agent> · <child name> · <status>` followed + by the `parent_session` key (Alt+Up by default). +- 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). 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. - 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 @@ -67,9 +86,10 @@ Path: @/nori-rs/tui/src/attach 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. + 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 child to its parent + when that parent is in the cached list, closing the list and resubscribing. Results return through the parent's ordinary event stream without a terminal review step. From 541911a5c4af630301e6fc062e261511620472c0 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 19:45:52 +0000 Subject: [PATCH 03/16] fix(tui): keep delegation results readable across frontends Separate result paragraphs at tool calls and permission requests, collapse the delivered result prompt in nori attach too, match it only by its full header, keep the result rail on wrapped lines, limit the breadcrumb and parent key to delegated children, and keep the parent ID for orphaned children in piped host ls output. --- docs/remote-control.md | 12 ++-- nori-rs/cli/src/host/docs.md | 9 +-- nori-rs/cli/src/host/table.rs | 13 +++- nori-rs/harness/docs.md | 5 +- .../harness/src/session_manager/delegation.rs | 1 + .../src/session_manager/delegation_state.rs | 14 +++- nori-rs/harness/tests/delegation.rs | 9 ++- nori-rs/nori-protocol/docs.md | 13 ++-- nori-rs/nori-protocol/src/delegation.rs | 17 +++-- nori-rs/tui-pty-e2e/tests/delegation.rs | 15 +++-- .../delegation__delegation_session_tree.snap | 25 +------ nori-rs/tui/docs.md | 8 ++- nori-rs/tui/src/attach/docs.md | 13 ++-- nori-rs/tui/src/attach/input.rs | 2 +- nori-rs/tui/src/attach/render.rs | 18 ++++- nori-rs/tui/src/attach/state.rs | 12 ++++ nori-rs/tui/src/attach/tests.rs | 65 +++++++++++++++++++ .../tui/src/chatwidget/tests/delegation.rs | 36 ++++++++++ nori-rs/tui/src/delegation.rs | 24 +++++-- 19 files changed, 240 insertions(+), 71 deletions(-) diff --git a/docs/remote-control.md b/docs/remote-control.md index 7753fb443..809494b31 100644 --- a/docs/remote-control.md +++ b/docs/remote-control.md @@ -423,7 +423,9 @@ characters. 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 <agent> · <child name> · <outcome>`, its second is `Child session: <child id>`, and the rest is the child's result -text; the parent's own ID is not included. The manager retains delivery until that parent's correlated +text (its last turn's message text, with a paragraph break wherever a tool +call, permission request, or other update interrupted it); the parent's own ID +is not included. 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 @@ -501,7 +503,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 `ID AGENT STATUS AGE TITLE` table with delegated children listed under their parent and `├─`/`└─`/`│` tree guides inside TITLE. TTY output colors status (waiting on you yellow, working/starting cyan, ready green, failed red) and truncates titles to the terminal width; piped output keeps full titles without color and appends ` (parent <full id>)` to each child row. | +| `nori host ls` | Print the `ID AGENT STATUS AGE TITLE` table with delegated children listed under their parent and `├─`/`└─`/`│` tree guides inside TITLE. TTY output colors status (waiting on you yellow, working cyan, ready green, failed red, everything else including starting dimmed) and truncates titles to the terminal width; piped output keeps full titles without color and appends ` (parent <full id>)` 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 <id>` | Open the named Nori conversation. | | `nori attach --host <URL> --token-file <path>` | Connect to an explicit managed endpoint using a private token file. | @@ -590,8 +592,10 @@ start delegations. The configured `hotkeys.next_waiting_session` binding `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. Inside a child, the identity line reads as a -breadcrumb from the parent's agent and name to the child's. +and AGE columns stay aligned. Inside a delegated child (not a fork), the +identity line reads as a breadcrumb from the parent's agent and name to the +child's. An attached parent shows a delivered result prompt as one +`› delegation result … · delivered to this session` line. Socket loss or a receive-liveness deadline starts recovery. Periodic session list requests keep idle connections observable; receiving JSON renews the diff --git a/nori-rs/cli/src/host/docs.md b/nori-rs/cli/src/host/docs.md index ccc762710..b999814aa 100644 --- a/nori-rs/cli/src/host/docs.md +++ b/nori-rs/cli/src/host/docs.md @@ -58,16 +58,17 @@ host ls / host stop ---------------+ SessionManager `│` prefixes. The guides are written inside TITLE, after the fixed ID, AGENT, STATUS, and AGE columns, so nesting never shifts metadata, and truncation cuts the title rather than its guide. Piped output appends - ` (parent <full parent ID>)` to each child's title so scripts keep the exact - link; terminal output omits it. + ` (parent <full parent ID>)` 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, starting | cyan | + | working | cyan | | ready | green | | failed | red | - | others | dimmed | + | others, including starting | 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 diff --git a/nori-rs/cli/src/host/table.rs b/nori-rs/cli/src/host/table.rs index b7c97bd0a..ea3c3d7b4 100644 --- a/nori-rs/cli/src/host/table.rs +++ b/nori-rs/cli/src/host/table.rs @@ -35,7 +35,7 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - let order = nori_tui_components::picker::tree_order(&links); let depths: Vec<i32> = 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) { + for ((index, _), (guide, _)) in order.into_iter().zip(guides) { let row = rows[index]; let clean = |key: &str| { row[key] @@ -49,7 +49,7 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - let agent = clean("agent"); let status = clean("status").replace('_', " "); let title = format!("{guide}{}", clean("title")); - let title = if depth > 0 && width.is_none() { + let title = if row["parent"].is_string() && width.is_none() { format!("{title} (parent {})", clean("parent")) } else { title @@ -80,7 +80,7 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - match row["status"].as_str().unwrap_or_default() { "failed" => status.red().to_string(), "waiting_on_you" => status.yellow().to_string(), - "working" | "starting" => status.cyan().to_string(), + "working" => status.cyan().to_string(), "ready" => status.green().to_string(), _ => status.dimmed().to_string(), } @@ -195,6 +195,13 @@ mod tests { let piped = format_table(&listing, None, false); 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!( + format_table(&orphan, None, false).contains(root), + "a child whose parent is gone still names it when piped" + ); assert!( child_row[82..].starts_with("├─ Port picker") && child_row.contains(root), "piped output keeps the complete parent ID: {child_row}" diff --git a/nori-rs/harness/docs.md b/nori-rs/harness/docs.md index 6f3f26418..3391a734b 100644 --- a/nori-rs/harness/docs.md +++ b/nori-rs/harness/docs.md @@ -812,7 +812,10 @@ remote /session/delegate ----------+ | its parent automatically, without a review step. Its text is `nori_protocol::delegation_result_prompt`: a readable first line naming the child agent, child name, and outcome, then the child ID, then the result. - It does not repeat the parent's own ID. The TUI recognizes these prompts by + 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. The TUI recognizes these prompts by their `[Nori delegation result]` header. 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`, diff --git a/nori-rs/harness/src/session_manager/delegation.rs b/nori-rs/harness/src/session_manager/delegation.rs index f2807c1ca..b5dd9310b 100644 --- a/nori-rs/harness/src/session_manager/delegation.rs +++ b/nori-rs/harness/src/session_manager/delegation.rs @@ -157,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_state.rs b/nori-rs/harness/src/session_manager/delegation_state.rs index 50ae39960..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<acp::v1::RequestId>, pub(super) completed_turns: HashSet<acp::v1::RequestId>, 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<String>, 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, diff --git a/nori-rs/harness/tests/delegation.rs b/nori-rs/harness/tests/delegation.rs index be145105a..c66726483 100644 --- a/nori-rs/harness/tests/delegation.rs +++ b/nori-rs/harness/tests/delegation.rs @@ -320,7 +320,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] diff --git a/nori-rs/nori-protocol/docs.md b/nori-rs/nori-protocol/docs.md index adfd4b3ae..b9e401aca 100644 --- a/nori-rs/nori-protocol/docs.md +++ b/nori-rs/nori-protocol/docs.md @@ -94,7 +94,8 @@ 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. +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, @@ -106,12 +107,14 @@ and `nori attach` must agree on. | `delegation_child_name` | The child's display name from its task, else `session <first 8 of child ID>` | | `delegation_status_word` | `waiting on you`, `working`, `ready`, `failed`, `declined`, or `cancelled`, matching session status words | | `delegation_result_prompt` | The prompt delivered to the parent: `[Nori delegation result] from <agent> · <child name> · <outcome>`, then `Child session: <child id>`, then the result text | -| `delegation_result_summary` | The text after `DELEGATION_RESULT_HEADER` on a prompt's first line, or `None` for any other prompt | +| `delegation_result_summary` | The text after `DELEGATION_RESULT_HEADER` on a prompt's first line, only when that line starts with the header and the second line starts with `Child session: `; `None` for any other text | 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. Because the -parent TUI recognizes a delivered result only by that header prefix, the -header string is a cross-crate contract. +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 both the header and the +`Child session: ` second line, so ordinary user text that merely begins with +the header is left whole. 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 diff --git a/nori-rs/nori-protocol/src/delegation.rs b/nori-rs/nori-protocol/src/delegation.rs index 2985c1402..8dcfb44d0 100644 --- a/nori-rs/nori-protocol/src/delegation.rs +++ b/nori-rs/nori-protocol/src/delegation.rs @@ -5,16 +5,19 @@ 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: usize = 40; +const NAME_CHARS: i32 = 40; + +const CHILD_LINE_PREFIX: &str = "Child session: "; /// A short readable name for a session, taken from the first non-empty line of /// its task or title. pub fn session_display_name(text: &str) -> Option<String> { let line = text.lines().map(str::trim).find(|line| !line.is_empty())?; - if line.chars().count() <= NAME_CHARS { + let limit = usize::try_from(NAME_CHARS).unwrap_or_default(); + if line.chars().count() <= limit { return Some(line.to_owned()); } - let cut: String = line.chars().take(NAME_CHARS - 1).collect(); + let cut: String = line.chars().take(limit - 1).collect(); Some(format!("{}…", cut.trim_end())) } @@ -48,7 +51,7 @@ pub fn delegation_result_prompt(delegation: &Delegation) -> String { other => delegation_status_word(other), }; format!( - "{DELEGATION_RESULT_HEADER} from {} · {} · {outcome}\nChild session: {}\n{}", + "{DELEGATION_RESULT_HEADER} from {} · {} · {outcome}\n{CHILD_LINE_PREFIX}{}\n{}", delegation.agent, delegation_child_name(delegation), delegation.child_id, @@ -58,7 +61,11 @@ pub fn delegation_result_prompt(delegation: &Delegation) -> String { /// The readable summary line of a result prompt, or `None` for other text. pub fn delegation_result_summary(prompt: &str) -> Option<&str> { - let first = prompt.lines().next()?; + let mut lines = prompt.lines(); + let first = lines.next()?; + if !lines.next()?.starts_with(CHILD_LINE_PREFIX) { + return None; + } first .strip_prefix(DELEGATION_RESULT_HEADER) .map(str::trim) diff --git a/nori-rs/tui-pty-e2e/tests/delegation.rs b/nori-rs/tui-pty-e2e/tests/delegation.rs index c14beb86b..4d848d91e 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -254,13 +254,14 @@ fn delegation_reads_clearly_from_request_to_result() { .wait_for(|screen| screen.contains("└─ "), TIMEOUT) .expect("the child is listed under its parent"); session.settle(Duration::from_millis(200)); - let list = session.screen_contents(); - assert!(!list.contains("(parent"), "{list}"); - // The agent still receives the child's ID; mask it for a stable snapshot. - let list = regex::Regex::new("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") - .unwrap() - .replace_all(&list, "CHILD-ID") - .into_owned(); + 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::<Vec<_>>() + .join("\n"); insta::assert_snapshot!( "delegation_session_tree", normalize_for_input_snapshot(list) 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 index bd82312ab..8cc55d3e5 100644 --- 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 @@ -2,36 +2,13 @@ source: tui-pty-e2e/tests/delegation.rs expression: normalize_for_input_snapshot(list) --- -› parent task identity - -• parent final answer - -↳ you delegated to mock-model-alt · mock:request-permission:write-child-file · working - ctrl + t shows the brief - -⚠ mock-model-alt · mock:request-permission:write-child-file is waiting on you (delegated by mock-model · parent task identity). - Press Alt+Down to answer it. - -○ result from mock-model-alt · mock:request-permission:write-child-file · ready - ▏ child final answerPermission granted with option: allow - returns to mock-model on its own · its history: alt + s - -› delegation result from mock-model-alt · mock:request-permission:write-child-file · completed · delivered to this session - -• Delegation continuation received: [Nori delegation result] from mock-model-alt · mock:request-permission:write-child-file - · completed - Child session: CHILD-ID - child final answerPermission granted with option: allow - - 1 ready - Sessions 2 · 1 ready tab: waiting only · type to search All waiting on you Session Agent Status › ○ parent task identity (current) Mock ACP ready - child final answerPermission granted with option: allow + Permission granted with option: allow └─ · mock:request-permission:write-child-file Mock ACP Alt closed closed diff --git a/nori-rs/tui/docs.md b/nori-rs/tui/docs.md index b564d335a..2be3826ae 100644 --- a/nori-rs/tui/docs.md +++ b/nori-rs/tui/docs.md @@ -1083,7 +1083,7 @@ child ID. | Status | On screen | | --- | --- | | running | `↳ <requester> delegated to <agent> · <child name> · working`, plus `<transcript key> shows the brief` | -| completed | `○ result from <agent> · <child name> · ready`, up to six result lines (then `… N more lines`), and `returns to <parent agent> on its own · its history: <session list key>` | +| completed | `○ result from <agent> · <child name> · ready`, 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>` | @@ -1101,8 +1101,10 @@ 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 its first line carries the `[Nori delegation result]` -header, [`history_cell`](src/history_cell/mod.rs) shows it on screen as one +`UserHistoryCell`. When `nori_protocol::delegation_result_summary` recognizes +it (a `[Nori delegation result]` first line followed by a `Child session: ` +line; 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 <summary> · 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. diff --git a/nori-rs/tui/src/attach/docs.md b/nori-rs/tui/src/attach/docs.md index 3998d1c2c..30f34e875 100644 --- a/nori-rs/tui/src/attach/docs.md +++ b/nori-rs/tui/src/attach/docs.md @@ -55,7 +55,8 @@ Path: @/nori-rs/tui/src/attach - The identity line under the header shows the selected session as `<agent> · <name> · <status>`, where the name is the session title through `nori_protocol::session_display_name` (else the short ID). Inside a delegated - child whose parent is listed, it becomes a breadcrumb + child (a row whose `source` is `session`; forks get no breadcrumb) whose + parent is listed, it becomes a breadcrumb `<parent agent> · <parent name> › <agent> · <child name> · <status>` followed by the `parent_session` key (Alt+Up by default). - The session list is tree-ordered: [AttachState](state.rs) runs the listed @@ -88,10 +89,14 @@ Path: @/nori-rs/tui/src/attach composer, including after paste, so a draft begun in the parent stays there. 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 child to its parent - when that parent is in the cached list, closing the list and resubscribing. + 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_summary` recognizes) renders as one + `› delegation result <summary> · delivered to this session` line, since the + result block already shows the text. ### Things to Know diff --git a/nori-rs/tui/src/attach/input.rs b/nori-rs/tui/src/attach/input.rs index 6792317ed..70ad0e032 100644 --- a/nori-rs/tui/src/attach/input.rs +++ b/nori-rs/tui/src/attach/input.rs @@ -35,7 +35,7 @@ impl Runtime { .sessions .iter() .find(|row| &row.session_id == id) - .and_then(|row| row.parent.clone()) + .and_then(|row| row.delegating_parent().map(str::to_owned)) }) && self .state diff --git a/nori-rs/tui/src/attach/render.rs b/nori-rs/tui/src/attach/render.rs index e27f4ae93..cf5682a27 100644 --- a/nori-rs/tui/src/attach/render.rs +++ b/nori-rs/tui/src/attach/render.rs @@ -128,7 +128,8 @@ fn identity_line(state: &AttachState) -> Line<'static> { return Line::from(format!(" session · {id}").dim()); }; let mut spans = vec![" ".into()]; - if let Some(parent) = current.parent.as_deref().and_then(row) { + let parent = current.delegating_parent().and_then(row); + if let Some(parent) = parent { spans.extend([ format!("{} · ", parent.agent).dim(), name(parent).into(), @@ -140,7 +141,7 @@ fn identity_line(state: &AttachState) -> Line<'static> { name(current).bold(), format!(" · {}", crate::session_status::status_label(current.status)).dim(), ]); - if current.parent.as_deref().and_then(row).is_some() && !state.parent_binding.is_none() { + if parent.is_some() && !state.parent_binding.is_none() { spans.push(format!(" · {} parent", state.parent_binding.as_str()).dim()); } Line::from(spans) @@ -205,6 +206,19 @@ 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_summary(text).is_some() => { + let summary = nori_protocol::delegation_result_summary(text).unwrap_or_default(); + lines.push(Line::from(vec![ + "› ".bold(), + "delegation result ".dim(), + summary.to_owned().into(), + " · delivered to this session".dim(), + ])); + } Part::Message { stream, text, .. } => { match stream { MessageStream::User => lines.push(Line::from("› You".bold())), diff --git a/nori-rs/tui/src/attach/state.rs b/nori-rs/tui/src/attach/state.rs index caeeeeab8..0935533dc 100644 --- a/nori-rs/tui/src/attach/state.rs +++ b/nori-rs/tui/src/attach/state.rs @@ -35,6 +35,9 @@ 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 source: Option<String>, #[serde(default)] pub delegations: Vec<nori_protocol::Delegation>, } @@ -418,3 +421,12 @@ pub(super) fn delegation_cell( 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 456b5fac9..39fcc5b1c 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -655,6 +655,71 @@ fn alt_up_in_a_top_level_session_stays_put() { 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; diff --git a/nori-rs/tui/src/chatwidget/tests/delegation.rs b/nori-rs/tui/src/chatwidget/tests/delegation.rs index 134136a96..b10120afa 100644 --- a/nori-rs/tui/src/chatwidget/tests/delegation.rs +++ b/nori-rs/tui/src/chatwidget/tests/delegation.rs @@ -204,6 +204,42 @@ fn long_results_are_shortened_on_screen_and_kept_whole_in_the_transcript() { 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(); diff --git a/nori-rs/tui/src/delegation.rs b/nori-rs/tui/src/delegation.rs index a8b004734..9861e1dee 100644 --- a/nori-rs/tui/src/delegation.rs +++ b/nori-rs/tui/src/delegation.rs @@ -14,7 +14,7 @@ use ratatui::text::Span; use crate::history_cell::HistoryCell; /// Result lines shown on screen before the rest moves to the transcript view. -const RESULT_PREVIEW_LINES: usize = 6; +const RESULT_PREVIEW_LINES: i32 = 6; pub(crate) fn parse_command(text: &str) -> Option<Result<(String, String), String>> { let rest = text.strip_prefix("/delegate")?; @@ -194,7 +194,9 @@ impl DelegationCell { Some(Line::from(format!(" {}", parts.join(" · ")).dim())) } - fn result_lines(&self, limit: Option<usize>) -> Vec<Line<'static>> { + /// 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(); } @@ -203,10 +205,20 @@ impl DelegationCell { if lines.is_empty() { return vec![Line::from(vec![" ▏ ".dim(), "(no text)".dim().italic()])]; } - let shown = limit.map_or(lines.len(), |limit| limit.min(lines.len())); + 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() - .map(|line| Line::from(vec![" ▏ ".dim(), (*line).to_owned().into()])) + .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; @@ -225,7 +237,7 @@ impl DelegationCell { impl HistoryCell for DelegationCell { fn display_lines(&self, width: u16) -> Vec<Line<'static>> { let mut lines = vec![self.header()]; - lines.extend(self.result_lines(Some(RESULT_PREVIEW_LINES))); + lines.extend(self.result_lines(width, Some(RESULT_PREVIEW_LINES))); lines.extend(self.footer()); wrap_each(&lines, width) } @@ -238,7 +250,7 @@ impl HistoryCell for DelegationCell { brief.next().unwrap_or_default().to_owned().into(), ])); lines.extend(brief.map(|line| Line::from(format!(" {line}")))); - lines.extend(self.result_lines(None)); + lines.extend(self.result_lines(width, None)); lines.push(Line::from( format!(" child session {}", self.delegation.child_id).dim(), )); From 456b4d6dd360a6c511b00161db5c243c6495fdb2 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 19:56:15 +0000 Subject: [PATCH 04/16] fix(tui): fit the attached child breadcrumb to the terminal width MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Nori](https://noriagentic.com) Co-Authored-By: Nori <contact@tilework.tech> --- nori-rs/tui/src/attach/render.rs | 70 ++++++++++++++++++++++---------- nori-rs/tui/src/attach/tests.rs | 24 +++++++++++ 2 files changed, 72 insertions(+), 22 deletions(-) diff --git a/nori-rs/tui/src/attach/render.rs b/nori-rs/tui/src/attach/render.rs index cf5682a27..4798eecb5 100644 --- a/nori-rs/tui/src/attach/render.rs +++ b/nori-rs/tui/src/attach/render.rs @@ -9,6 +9,7 @@ use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; +use unicode_width::UnicodeWidthStr; use super::state::AttachState; use super::state::Part; @@ -57,7 +58,7 @@ 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); - identity_line(state).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); let input = composer_area(state, composer, area); let notice_lines = notice_lines(state, area.width); let notice_height = u16::try_from(notice_lines.len()) @@ -113,38 +114,63 @@ pub(super) fn render( /// The selected session's agent, name, and status. Inside a delegated child /// it is a breadcrumb from the parent with the key that returns there. -fn identity_line(state: &AttachState) -> Line<'static> { +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 name = |row: &super::state::SessionRow| { row.title .as_deref() .and_then(nori_protocol::session_display_name) .unwrap_or_else(|| row.session_id.chars().take(8).collect()) }; - let Some(current) = row(id) else { - return Line::from(format!(" session · {id}").dim()); - }; - let mut spans = vec![" ".into()]; - let parent = current.delegating_parent().and_then(row); - if let Some(parent) = parent { - spans.extend([ - format!("{} · ", parent.agent).dim(), - name(parent).into(), - " › ".dim(), + let status = format!(" · {}", crate::session_status::status_label(current.status)); + let Some(parent) = current.delegating_parent().and_then(row) else { + return Line::from(vec![ + " ".into(), + format!("{} · ", current.agent).dim(), + name(current).bold(), + status.dim(), ]); - } - spans.extend([ - format!("{} · ", current.agent).dim(), - name(current).bold(), - format!(" · {}", crate::session_status::status_label(current.status)).dim(), - ]); - if parent.is_some() && !state.parent_binding.is_none() { - spans.push(format!(" · {} parent", state.parent_binding.as_str()).dim()); - } - Line::from(spans) + }; + let key = (!state.parent_binding.is_none()) + .then(|| format!(" · {} parent", state.parent_binding.as_str())) + .unwrap_or_default(); + let parent_agent = format!("{} · ", parent.agent); + let child_agent = format!("{} · ", current.agent); + // The two names share whatever the agents, status, and parent key leave. + let fixed = [" ", &parent_agent, " › ", &child_agent, &status, &key] + .iter() + .map(|part| part.width()) + .sum::<usize>(); + let room = usize::from(width).saturating_sub(fixed) / 2; + let fit = |name: String| { + if name.width() <= room { + return name; + } + let mut kept = String::new(); + for ch in name.chars() { + if kept.width() + ch.to_string().width() + 1 > room { + break; + } + kept.push(ch); + } + format!("{}…", kept.trim_end()) + }; + Line::from(vec![ + " ".into(), + parent_agent.dim(), + fit(name(parent)).into(), + " › ".dim(), + child_agent.dim(), + fit(name(current)).bold(), + status.dim(), + key.dim(), + ]) } fn notice_lines(state: &AttachState, width: u16) -> Vec<Line<'static>> { diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs index 39fcc5b1c..1c48daee0 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -638,6 +638,30 @@ fn child_view_shows_breadcrumb_and_alt_up_returns_to_parent() { assert_eq!(request["params"]["session_id"], "parent-session"); } +#[test] +fn long_names_leave_room_for_the_parent_key_in_the_breadcrumb() { + 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.ends_with("alt+up parent"), "{rendered}"); +} + #[test] fn alt_up_in_a_top_level_session_stays_put() { use crossterm::event::KeyCode; From 768df0283d3f77b2342e3a250339bd6e0fda472f Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 19:56:46 +0000 Subject: [PATCH 05/16] style(tui): spell the breadcrumb key hint as an if expression --- nori-rs/tui/src/attach/render.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/nori-rs/tui/src/attach/render.rs b/nori-rs/tui/src/attach/render.rs index 4798eecb5..7819121ff 100644 --- a/nori-rs/tui/src/attach/render.rs +++ b/nori-rs/tui/src/attach/render.rs @@ -137,9 +137,11 @@ fn identity_line(state: &AttachState, width: u16) -> Line<'static> { status.dim(), ]); }; - let key = (!state.parent_binding.is_none()) - .then(|| format!(" · {} parent", state.parent_binding.as_str())) - .unwrap_or_default(); + let key = if state.parent_binding.is_none() { + String::new() + } else { + format!(" · {} parent", state.parent_binding.as_str()) + }; let parent_agent = format!("{} · ", parent.agent); let child_agent = format!("{} · ", current.agent); // The two names share whatever the agents, status, and parent key leave. From a61a00019247d50fe0049429aee063b8edaa3f17 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 21:32:12 +0000 Subject: [PATCH 06/16] fix(host): keep host ls aligned and titled at any terminal width On a terminal, ID, AGENT, STATUS and AGE shrink to a compact layout before TITLE loses its space, so the tree glyphs, whole ages and status colors stay at 80 columns. A long agent name is cut with an ellipsis instead of pushing the later columns right. A top-level row shows its family's status, so a waiting grandchild marks it as waiting on you. Piped output is unchanged. --- nori-rs/cli/src/host/table.rs | 271 ++++++++++++++++++++++++++++++---- 1 file changed, 241 insertions(+), 30 deletions(-) diff --git a/nori-rs/cli/src/host/table.rs b/nori-rs/cli/src/host/table.rs index ea3c3d7b4..a1c0931d0 100644 --- a/nori-rs/cli/src/host/table.rs +++ b/nori-rs/cli/src/host/table.rs @@ -9,9 +9,65 @@ 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<usize>) -> 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<usize>, 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", + "{:<id_cells$} {:<agent_cells$} {:<status_cells$} {:>age_cells$} TITLE", "ID", "AGENT", "STATUS", "AGE" ); let mut output = format!( @@ -35,7 +91,7 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - let order = nori_tui_components::picker::tree_order(&links); let depths: Vec<i32> = order.iter().map(|(_, depth)| *depth).collect(); let guides = nori_tui_components::picker::tree_guides(&depths); - for ((index, _), (guide, _)) in order.into_iter().zip(guides) { + for ((index, depth), (guide, _)) in order.into_iter().zip(guides) { let row = rows[index]; let clean = |key: &str| { row[key] @@ -47,7 +103,13 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - }; let id = clean("session_id"); let agent = clean("agent"); - let status = clean("status").replace('_', " "); + // A top-level session speaks for its family: if anything under it + // waits on the user, so does its row. + 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 title = format!("{guide}{}", clean("title")); let title = if row["parent"].is_string() && width.is_none() { format!("{title} (parent {})", clean("parent")) @@ -62,22 +124,26 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, 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:<id_cells$} {agent:<agent_cells$} {status:<status_cells$} {age:>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; - } let title = width.map_or_else( || title.clone(), |width| truncate(&title, width.saturating_sub(prefix_width)), ); - let status = format!("{status:<16}"); + let status = format!("{status:<status_cells$}"); let status = if color { - match row["status"].as_str().unwrap_or_default() { + match status_key { "failed" => status.red().to_string(), "waiting_on_you" => status.yellow().to_string(), "working" => status.cyan().to_string(), @@ -87,9 +153,10 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - } else { status }; - output.push_str(&format!( - "{id:<36} {agent:<16} {status} {age:>6} {title}\n" - )); + let line = + format!("{id:<id_cells$} {agent:<agent_cells$} {status} {age:>age_cells$} {title}"); + output.push_str(line.trim_end()); + output.push('\n'); } output } @@ -118,8 +185,47 @@ mod tests { 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"), @@ -129,18 +235,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 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::<Vec<_>>(); + 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 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 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::<Vec<_>>(); + assert_eq!( + rows.iter() + .map(|row| from_column(row, title)) + .collect::<Vec<_>>(), + [ + "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::<Vec<_>>(), + ["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::<Vec<_>>(); + 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] @@ -167,6 +369,11 @@ mod tests { {"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::<Vec<_>>(); assert_eq!( rows.iter().map(|row| &row[..8]).collect::<Vec<_>>(), @@ -174,7 +381,9 @@ mod tests { "children follow their parent: {tty}" ); assert_eq!( - rows.iter().map(|row| &row[82..]).collect::<Vec<_>>(), + rows.iter() + .map(|row| from_column(row, title_at)) + .collect::<Vec<_>>(), [ "Ship tree picker", "├─ Port picker", @@ -184,12 +393,13 @@ mod tests { ], "{tty}" ); - assert_eq!(&rows[2][38..54], "mock-model "); - assert_eq!(&rows[1][56..72], "waiting on you "); + 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!( - narrow.lines().nth(3).unwrap()[82..].starts_with("│ └─ "), + from_column(narrow.lines().nth(3).unwrap(), narrow_title).starts_with("│ └─ "), "glyphs survive truncation: {narrow}" ); let piped = format_table(&listing, None, false); @@ -203,7 +413,8 @@ mod tests { "a child whose parent is gone still names it when piped" ); assert!( - child_row[82..].starts_with("├─ Port picker") && child_row.contains(root), + from_column(child_row, column(&piped, "TITLE")).starts_with("├─ Port picker") + && child_row.contains(root), "piped output keeps the complete parent ID: {child_row}" ); } From 444cbcd245b948728d0a88db866ab96e4d754d60 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 21:32:19 +0000 Subject: [PATCH 07/16] fix(delegation): name finished, declined and delegating sessions plainly - A child that finished its task ends as done; closed is left for sessions the user closed. - A declined delegation tells the parent agent so without naming a session that never started. - A session whose first input is /delegate is titled by that task, never by the result prompt it receives, and a result prompt never starts the first-prompt summary. - The host session list carries each family's status for top-level rows. - Untitled sessions are called "new session" instead of an ID fragment. - just test protocol runs the nori-protocol crate, which now tests the result prompt it builds. --- justfile | 2 +- nori-rs/harness/src/backend/user_input.rs | 3 +- nori-rs/harness/src/managed_remote.rs | 1 + .../src/session_manager/delegation_driver.rs | 4 + .../harness/src/session_manager/registry.rs | 18 ++- nori-rs/harness/src/session_manager/replay.rs | 12 +- nori-rs/harness/tests/delegation.rs | 108 +++++++++++++++- nori-rs/nori-protocol/src/delegation.rs | 122 +++++++++++++++--- nori-rs/nori-protocol/src/session_envelope.rs | 10 ++ 9 files changed, 253 insertions(+), 27 deletions(-) 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/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_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<Shared>) { } 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/registry.rs b/nori-rs/harness/src/session_manager/registry.rs index 229cdb626..ca75ad416 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<RequestResolved>, ended: Option<SessionStatus>, + /// 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<ConversationId>, transcript_path: Option<PathBuf>, @@ -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; @@ -466,6 +472,14 @@ impl Registry { } /// The live agent process of a session, if it still has one. + /// 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; + } + } + pub(crate) fn live_process(&self, conversation_id: &ConversationId) -> Option<AgentProcessId> { 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..5991c3789 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 = nori_protocol::session_display_name(&delegation.task); + } SessionEvent::Acp(AcpEvent::Notification( acp::AgentNotification::SessionNotification(notification), )) => match ¬ification.update { @@ -105,7 +113,9 @@ impl Journal { } } acp::SessionUpdate::UserMessageChunk(chunk) if history.title.is_none() => { - if let acp::ContentBlock::Text(text) = &chunk.content { + if let acp::ContentBlock::Text(text) = &chunk.content + && nori_protocol::delegation_result_summary(&text.text).is_none() + { history.title = Some( text.text .lines() diff --git a/nori-rs/harness/tests/delegation.rs b/nori-rs/harness/tests/delegation.rs index c66726483..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); @@ -718,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("· completed"), "{reply}"); + assert!(reply.contains("· done"), "{reply}"); m.shutdown(Duration::ZERO).await; } diff --git a/nori-rs/nori-protocol/src/delegation.rs b/nori-rs/nori-protocol/src/delegation.rs index 8dcfb44d0..bf9023be1 100644 --- a/nori-rs/nori-protocol/src/delegation.rs +++ b/nori-rs/nori-protocol/src/delegation.rs @@ -9,6 +9,9 @@ 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"; + /// A short readable name for a session, taken from the first non-empty line of /// its task or title. pub fn session_display_name(text: &str) -> Option<String> { @@ -23,10 +26,7 @@ pub fn session_display_name(text: &str) -> Option<String> { /// The readable name of a delegated child. pub fn delegation_child_name(delegation: &Delegation) -> String { - session_display_name(&delegation.task).unwrap_or_else(|| { - let id: String = delegation.child_id.chars().take(8).collect(); - format!("session {id}") - }) + 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. @@ -34,7 +34,7 @@ pub fn delegation_status_word(status: DelegationStatus) -> &'static str { match status { DelegationStatus::AwaitingApproval => "waiting on you", DelegationStatus::Running => "working", - DelegationStatus::Completed => "ready", + DelegationStatus::Completed => "done", DelegationStatus::Failed => "failed", DelegationStatus::Declined => "declined", DelegationStatus::Cancelled => "cancelled", @@ -44,30 +44,112 @@ pub fn delegation_status_word(status: DelegationStatus) -> &'static str { /// 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. +/// 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 outcome = match delegation.status { - DelegationStatus::Completed => "completed", - other => delegation_status_word(other), - }; - format!( - "{DELEGATION_RESULT_HEADER} from {} · {} · {outcome}\n{CHILD_LINE_PREFIX}{}\n{}", + let header = format!( + "{DELEGATION_RESULT_HEADER} from {} · {} · {}", delegation.agent, delegation_child_name(delegation), - delegation.child_id, - delegation.result.as_deref().unwrap_or_default(), + 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 first = lines.next()?; - if !lines.next()?.starts_with(CHILD_LINE_PREFIX) { - return None; - } - first + let summary = lines + .next()? .strip_prefix(DELEGATION_RESULT_HEADER) .map(str::trim) - .filter(|summary| !summary.is_empty()) + .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) +} + +#[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 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/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) + } } From 87d748b9bbc807136d5d38a550b8442ada249974 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 21:32:19 +0000 Subject: [PATCH 08/16] fix(tui): fit session paths to the terminal and name sessions alike MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The breadcrumb inside a delegated child shows the whole path from its top-level session, on one row at any width; sessions between the root and the current one collapse to … when names would get too short. - The waiting-on-you line cuts names to the room the terminal has rather than to a fixed length, and nori attach shows it too, so a top-level session says when a grandchild waits. - Alt+Down reaches a waiting session even with a draft, which stays in its session's prompt; Alt+Up outside a delegated child does nothing. - Every surface names agents by the slug /delegate takes, a finished child reads done everywhere, and its list row keeps its last answer instead of repeating closed. --- nori-rs/tui-pty-e2e/tests/delegation.rs | 182 +++++++- nori-rs/tui-pty-e2e/tests/session_list.rs | 2 +- .../delegation__delegation_session_tree.snap | 7 +- ...session_list__background_request_line.snap | 3 +- ...session_list__session_list_failed_row.snap | 5 +- ..._list__session_list_fork_under_parent.snap | 7 +- ...ion_list__session_list_three_sessions.snap | 9 +- ...ion_list__session_list_waiting_on_you.snap | 5 +- nori-rs/tui/src/app/event_handling.rs | 2 +- nori-rs/tui/src/app/session_keys.rs | 42 +- nori-rs/tui/src/app/session_lifecycle.rs | 13 +- nori-rs/tui/src/app/session_overview.rs | 142 +++---- nori-rs/tui/src/app/session_view.rs | 2 +- nori-rs/tui/src/attach/render.rs | 108 +++-- nori-rs/tui/src/attach/runtime.rs | 1 + ...attach__tests__attached_host_sessions.snap | 3 +- ..._attach__tests__delegation_child_list.snap | 3 +- ...tui__attach__tests__delegation_result.snap | 3 +- ...ttach__tests__delegation_session_tree.snap | 3 +- nori-rs/tui/src/attach/state.rs | 21 +- nori-rs/tui/src/attach/tests.rs | 143 ++++++- .../tui/src/bottom_pane/session_list_view.rs | 8 +- nori-rs/tui/src/chatwidget/constructors.rs | 2 + nori-rs/tui/src/chatwidget/delegation.rs | 3 + nori-rs/tui/src/chatwidget/event_handlers.rs | 2 +- nori-rs/tui/src/chatwidget/helpers.rs | 8 + nori-rs/tui/src/chatwidget/mod.rs | 3 + ...legation__completed_delegation_result.snap | 3 +- ...legation__delivered_delegation_result.snap | 3 +- nori-rs/tui/src/chatwidget/user_input.rs | 6 +- nori-rs/tui/src/lib.rs | 1 + nori-rs/tui/src/session_path.rs | 402 ++++++++++++++++++ nori-rs/tui/src/session_preview.rs | 42 +- nori-rs/tui/src/session_status.rs | 3 +- ...show_the_whole_path_and_fit_the_width.snap | 25 ++ ...nd_child_as_fully_as_the_width_allows.snap | 22 + 36 files changed, 1060 insertions(+), 179 deletions(-) create mode 100644 nori-rs/tui/src/session_path.rs create mode 100644 nori-rs/tui/src/snapshots/nori_tui__session_path__tests__breadcrumbs_show_the_whole_path_and_fit_the_width.snap create mode 100644 nori-rs/tui/src/snapshots/nori_tui__session_path__tests__waiting_lines_name_parent_and_child_as_fully_as_the_width_allows.snap diff --git a/nori-rs/tui-pty-e2e/tests/delegation.rs b/nori-rs/tui-pty-e2e/tests/delegation.rs index 4d848d91e..f21f6be14 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -6,12 +6,23 @@ 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(); @@ -30,7 +41,7 @@ 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(); @@ -120,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(); @@ -200,7 +211,9 @@ fn delegation_reads_clearly_from_request_to_result() { .wait_for( |screen| { screen.contains("delegated to mock-model-alt") - && screen.contains("parent task… › mock:request") + && screen.contains( + "parent task identity › mock:request-permission:write-child-file is waiting on you", + ) }, TIMEOUT, ) @@ -267,3 +280,158 @@ fn delegation_reads_clearly_from_request_to_result() { 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.settle(Duration::from_millis(300)); + 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::<Vec<_>>(); + 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")) + .unwrap_or_default(); + 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(); + session.settle(Duration::from_millis(500)); + 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::<Vec<_>>(); + 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("to parent", TIMEOUT) + .expect("the child shows the way back to its parent"); + session.settle(Duration::from_millis(200)); + let screen = session.screen_contents(); + let breadcrumb = screen + .lines() + .find(|line| line.contains("to parent")) + .unwrap_or_else(|| panic!("breadcrumb missing:\n{screen}")); + assert!( + breadcrumb.contains("mock-model · parent task") + && breadcrumb.contains("› mock-model-alt · mock:req"), + "the breadcrumb is one row:\n{screen}" + ); + assert!( + breadcrumb.trim_end().ends_with("alt + up to parent"), + "{screen}" + ); +} 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_session_tree.snap b/nori-rs/tui-pty-e2e/tests/snapshots/delegation__delegation_session_tree.snap index 8cc55d3e5..5f29b2b14 100644 --- 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 @@ -1,5 +1,6 @@ --- source: tui-pty-e2e/tests/delegation.rs +assertion_line: 278 expression: normalize_for_input_snapshot(list) --- Sessions 2 · 1 ready tab: waiting only · type to search @@ -7,9 +8,9 @@ expression: normalize_for_input_snapshot(list) All waiting on you Session Agent Status - › ○ parent task identity (current) Mock ACP ready + › ○ parent task identity (current) mock-model ready Permission granted with option: allow - └─ · mock:request-permission:write-child-file Mock ACP Alt closed - closed + └─ · 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..750fbd8cb 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 @@ -1,5 +1,6 @@ --- source: tui-pty-e2e/tests/session_list.rs +assertion_line: 237 expression: normalize_for_input_snapshot(session.screen_contents()) --- • Mock ACP options: Model=Mock Default Model, Thought Level=Medium (/config to change) @@ -8,7 +9,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-permission:rm -rf targe… 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..fa3ac6250 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 @@ -1,5 +1,6 @@ --- source: tui-pty-e2e/tests/session_list.rs +assertion_line: 298 expression: normalize_for_input_snapshot(session.screen_contents()) --- • Mock ACP options: Model=Mock Default Model, Thought Level=Medium (/config to change) @@ -19,9 +20,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 7630eb994..7044bf97b 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 @@ -1,5 +1,6 @@ --- source: tui-pty-e2e/tests/session_list.rs +assertion_line: 367 expression: normalize_for_input_snapshot(screen) --- • Mock ACP options: Model=Mock Default Model, Thought Level=Medium (/config to change) @@ -8,7 +9,7 @@ expression: normalize_for_input_snapshot(screen) • alpha agent answer - ● parent ques… › mock:request-pe… is waiting on you · approve: rm -rf target/… · alt + down to jump + ● parent question › mock:request-permission:rm -… 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 +17,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..5750d81d5 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 @@ -1,12 +1,13 @@ --- source: tui-pty-e2e/tests/session_list.rs +assertion_line: 121 expression: normalize_for_input_snapshot(screen) --- › gamma question • 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 +15,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..c3244bb35 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 @@ -1,12 +1,13 @@ --- source: tui-pty-e2e/tests/session_list.rs +assertion_line: 144 expression: normalize_for_input_snapshot(session.screen_contents()) --- › gamma question • 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 +15,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/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 9dc169021..2b34b134a 100644 --- a/nori-rs/tui/src/app/session_keys.rs +++ b/nori-rs/tui/src/app/session_keys.rs @@ -34,27 +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(); + // 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) { + Some(Direction::Previous) + } else if pressed(HotkeyAction::NextSession) { + 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; } - if pressed(HotkeyAction::ParentSession) - && 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(); + // 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 direction = if pressed(HotkeyAction::PreviousSession) { - Direction::Previous - } else if pressed(HotkeyAction::NextSession) { - Direction::Next - } else { + 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 36c68d1a4..3ac6208b1 100644 --- a/nori-rs/tui/src/app/session_overview.rs +++ b/nori-rs/tui/src/app/session_overview.rs @@ -19,15 +19,6 @@ 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; -/// A child's request names its parent too, so each part is shorter. -const REQUEST_LINE_PARENT_CHARS: i32 = 12; -const REQUEST_LINE_CHILD_CHARS: i32 = 16; -const REQUEST_LINE_CHILD_REQUEST_CHARS: i32 = 24; - fn cut(text: &str, limit: i32) -> String { let limit = usize::try_from(limit).unwrap_or(0); if text.chars().count() > limit { @@ -142,7 +133,7 @@ impl App { let widget = self.widget_for(generation); self.session_previews .title(generation) - .or_else(|| widget.and_then(ChatWidget::first_prompt_text)) + .or_else(|| widget.and_then(ChatWidget::first_input_title)) .map(|title| cut(title.lines().next().unwrap_or_default().trim(), limit)) .filter(|title| !title.is_empty()) } @@ -203,7 +194,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( @@ -217,6 +208,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(); @@ -244,7 +243,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; } @@ -258,8 +258,10 @@ impl App { let name = self.agent_display_name(agent_name); lines.push(Line::from(format!("Preparing {name}…").dim())); } - lines.extend(self.parent_breadcrumb(&facts)); - 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)) { @@ -318,7 +320,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() @@ -332,54 +335,43 @@ 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, request_chars) = match first.parent { - Some(parent) => ( - format!( - "{} › {}", - self.session_name(&parent, REQUEST_LINE_PARENT_CHARS), - cut(&title, REQUEST_LINE_CHILD_CHARS) - ), - REQUEST_LINE_CHILD_REQUEST_CHARS, - ), - None => (title, REQUEST_LINE_REQUEST_CHARS), - }; - let mut spans = vec![ - ratatui::text::Span::styled("● ", crate::style::component_theme().warning), - 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_chars); - spans.push(format!(" · {request}").dim()); - } - if waiting.len() > 1 { - spans.push(format!(" (+{} more)", waiting.len() - 1).dim()); + .session_title(first.generation, TITLE_CHARS) + .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, TITLE_CHARS)); } + 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()); - } - Some(Line::from(spans)) + 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 short ID. + /// TUI, else its recorded title, else a placeholder. pub(super) fn session_name(&self, id: &ConversationId, limit: i32) -> String { self.session_facts() .iter() @@ -392,10 +384,7 @@ impl App { .and_then(|title| nori_protocol::session_display_name(&title)) .map(|title| cut(&title, limit)) }) - .unwrap_or_else(|| { - let short: String = id.to_string().chars().take(8).collect(); - format!("session {short}") - }) + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_string()) } /// The parent of the delegated child on screen, if any. @@ -407,31 +396,40 @@ impl App { .and_then(|record| record.parent) } - /// Where a delegated child sits, with the key that returns to its parent. - fn parent_breadcrumb(&self, facts: &[SessionFacts]) -> Option<Line<'static>> { - let parent = self.on_screen_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 parent_agent = self - .session_manager - .get(&parent) - .map(|record| record.agent) - .unwrap_or_default(); - let child_name = self - .session_title(child.generation, REQUEST_LINE_TITLE_CHARS) - .unwrap_or_else(|| "this session".to_string()); - let mut spans = vec![ - format!("{parent_agent} · ").dim(), - self.session_name(&parent, REQUEST_LINE_TITLE_CHARS).into(), - " › ".dim(), - format!("{} · ", child.agent).dim(), - child_name.bold(), - ]; + let mut path = vec![crate::session_path::PathStep { + agent: child.agent.clone(), + name: self + .session_title(child.generation, TITLE_CHARS) + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_string()), + }]; + let mut record = child + .conversation_id + .and_then(|id| self.session_manager.get(&id)); + while let Some(current) = record + && current.source == nori_harness::session_manager::SessionSource::Session + && let Some(parent) = current.parent + && let Some(parent_record) = self.session_manager.get(&parent) + { + path.push(crate::session_path::PathStep { + agent: parent_record.agent.clone(), + name: self.session_name(&parent, TITLE_CHARS), + }); + record = Some(parent_record); + } + path.reverse(); let binding = self .hotkey_config .binding_for(nori_config::HotkeyAction::ParentSession); - if !binding.is_none() { - spans.push(format!(" · {} to parent", binding.display_name()).dim()); - } - Some(Line::from(spans)) + 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_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/render.rs b/nori-rs/tui/src/attach/render.rs index 7819121ff..6e3e5d523 100644 --- a/nori-rs/tui/src/attach/render.rs +++ b/nori-rs/tui/src/attach/render.rs @@ -9,7 +9,6 @@ use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; -use unicode_width::UnicodeWidthStr; use super::state::AttachState; use super::state::Part; @@ -59,6 +58,9 @@ pub(super) fn render( } Line::from(header).render(Rect::new(area.x, area.y, 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()) @@ -112,8 +114,17 @@ pub(super) fn render( composer.render_ref(input, buf); } +/// A readable name for a listed session. +fn row_name(row: &super::state::SessionRow) -> String { + row.title + .as_deref() + .and_then(nori_protocol::session_display_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 parent with the key that returns there. +/// 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()); @@ -122,57 +133,72 @@ fn identity_line(state: &AttachState, width: u16) -> Line<'static> { let Some(current) = row(id) else { return Line::from(format!(" session · {id}").dim()); }; - let name = |row: &super::state::SessionRow| { - row.title - .as_deref() - .and_then(nori_protocol::session_display_name) - .unwrap_or_else(|| row.session_id.chars().take(8).collect()) - }; let status = format!(" · {}", crate::session_status::status_label(current.status)); - let Some(parent) = current.delegating_parent().and_then(row) else { + if current.delegating_parent().and_then(row).is_none() { return Line::from(vec![ " ".into(), format!("{} · ", current.agent).dim(), - name(current).bold(), + row_name(current).bold(), status.dim(), ]); - }; + } + 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 state.parent_binding.is_none() { String::new() } else { format!(" · {} parent", state.parent_binding.as_str()) }; - let parent_agent = format!("{} · ", parent.agent); - let child_agent = format!("{} · ", current.agent); - // The two names share whatever the agents, status, and parent key leave. - let fixed = [" ", &parent_agent, " › ", &child_agent, &status, &key] + let mut line = crate::session_path::breadcrumb_line( + &path, + &format!("{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() - .map(|part| part.width()) - .sum::<usize>(); - let room = usize::from(width).saturating_sub(fixed) / 2; - let fit = |name: String| { - if name.width() <= room { - return name; - } - let mut kept = String::new(); - for ch in name.chars() { - if kept.width() + ch.to_string().width() + 1 > room { - break; - } - kept.push(ch); - } - format!("{}…", kept.trim_end()) - }; - Line::from(vec![ - " ".into(), - parent_agent.dim(), - fit(name(parent)).into(), - " › ".dim(), - child_agent.dim(), - fit(name(current)).bold(), - status.dim(), - key.dim(), - ]) + .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>> { diff --git a/nori-rs/tui/src/attach/runtime.rs b/nori-rs/tui/src/attach/runtime.rs index 84065dfd7..2178f6f5f 100644 --- a/nori-rs/tui/src/attach/runtime.rs +++ b/nori-rs/tui/src/attach/runtime.rs @@ -32,6 +32,7 @@ pub(super) struct Runtime { 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"), 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..0c79f069a 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 @@ -1,10 +1,11 @@ --- source: tui/src/attach/tests.rs +assertion_line: 183 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__delegation_child_list.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__delegation_child_list.snap index 0e01c7303..8ffbe2745 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 @@ -1,10 +1,11 @@ --- source: tui/src/attach/tests.rs +assertion_line: 571 expression: rendered --- Nori host WATCHING · read-only · alt+t take control mock-model · Parent task · ready - + ● Parent task › Child task is waiting on you · alt+down to jump Sessions 2 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 5242e77b7..ba90986fe 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 @@ -1,11 +1,12 @@ --- source: tui/src/attach/tests.rs +assertion_line: 548 expression: rendered --- Nori host WATCHING · read-only · alt+t take control session · parent-session - ○ result from mock-model-alt · Review the parser · ready + ○ result from mock-model-alt · Review the parser · done ▏ Parser reviewed returns to mock-model on its own 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 index 60868d288..e64d6817e 100644 --- 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 @@ -1,10 +1,11 @@ --- source: tui/src/attach/tests.rs +assertion_line: 616 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 diff --git a/nori-rs/tui/src/attach/state.rs b/nori-rs/tui/src/attach/state.rs index 0935533dc..27e31b88b 100644 --- a/nori-rs/tui/src/attach/state.rs +++ b/nori-rs/tui/src/attach/state.rs @@ -40,6 +40,10 @@ pub(super) struct SessionRow { 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 { @@ -86,6 +90,8 @@ pub(super) struct AttachState { 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 { @@ -116,6 +122,7 @@ impl Default for AttachState { replay_error: None, scroll: 0, parent_binding: nori_config::HotkeyConfig::default().parent_session, + jump_binding: nori_config::HotkeyConfig::default().next_waiting_session, } } } @@ -152,12 +159,20 @@ impl AttachState { } else { format!("{}h", seconds / 3600) }; - let title = row.title.clone().unwrap_or_else(|| "New session".into()); + let title = row + .title + .clone() + .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.into()); + // A top-level session speaks for its family. + 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(row.status)) - .cell_detail_tone("status", crate::session_status::status_tone(row.status)) + .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)) diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs index 1c48daee0..b14aed921 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) @@ -585,6 +593,7 @@ fn session_tree_keeps_children_under_their_parent_with_aligned_columns() { 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() @@ -887,3 +896,135 @@ 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(); + sessions["sessions"][3]["status"] = json!("waiting_on_you"); + sessions["sessions"][3]["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("›")) + .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("›")) + .unwrap_or_else(|| panic!("breadcrumb missing:\n{rendered}")); + assert!( + breadcrumb.starts_with(" mock-model · Ship"), + "@{width}: {rendered}" + ); + assert!( + breadcrumb.contains("› mock-model · Write"), + "@{width}: {rendered}" + ); + assert!( + breadcrumb.ends_with("alt+up parent"), + "@{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}"); +} 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 33ce0b51b..68bb9c19d 100644 --- a/nori-rs/tui/src/bottom_pane/session_list_view.rs +++ b/nori-rs/tui/src/bottom_pane/session_list_view.rs @@ -138,7 +138,7 @@ impl SessionListView { return; } match row.status { - SessionStatus::Closed => { + SessionStatus::Closed | SessionStatus::Done => { self.app_event_tx .send(AppEvent::RemoveSession { generation }); } @@ -162,7 +162,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,7 +198,7 @@ fn glyph(status: SessionStatus) -> &'static str { SessionStatus::Working => "⠋", SessionStatus::Ready => "○", SessionStatus::Failed => "✕", - SessionStatus::Closed => "·", + SessionStatus::Closed | SessionStatus::Done => "·", SessionStatus::Starting => "…", } } @@ -223,7 +223,7 @@ fn items(rows: &[SessionRow]) -> Vec<PickerItem<SessionGeneration>> { 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 { diff --git a/nori-rs/tui/src/chatwidget/constructors.rs b/nori-rs/tui/src/chatwidget/constructors.rs index 016456e9b..f42cfdb1d 100644 --- a/nori-rs/tui/src/chatwidget/constructors.rs +++ b/nori-rs/tui/src/chatwidget/constructors.rs @@ -193,6 +193,7 @@ impl ChatWidget { login_agent_override: None, active_resume_picker_generation: None, first_prompt_text, + first_delegated_task: None, current_goal: None, session_agent_capabilities: crate::presentation::AgentCapabilitiesView::default(), cloud_mode, @@ -385,6 +386,7 @@ impl ChatWidget { login_agent_override: None, active_resume_picker_generation: None, first_prompt_text, + first_delegated_task: None, current_goal: None, session_agent_capabilities: crate::presentation::AgentCapabilitiesView::default(), cloud_mode, diff --git a/nori-rs/tui/src/chatwidget/delegation.rs b/nori-rs/tui/src/chatwidget/delegation.rs index aa59962b8..da05ac73b 100644 --- a/nori-rs/tui/src/chatwidget/delegation.rs +++ b/nori-rs/tui/src/chatwidget/delegation.rs @@ -25,6 +25,9 @@ impl ChatWidget { self.add_error_message("Start a session before delegating a task.".into()); return true; }; + if self.first_prompt_text.is_none() && self.first_delegated_task.is_none() { + self.first_delegated_task = Some(task.clone()); + } let manager = self.session_manager.clone(); let tx = self.app_event_tx.clone(); tokio::spawn(async move { 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/helpers.rs b/nori-rs/tui/src/chatwidget/helpers.rs index 293d06d91..a505e0947 100644 --- a/nori-rs/tui/src/chatwidget/helpers.rs +++ b/nori-rs/tui/src/chatwidget/helpers.rs @@ -223,6 +223,14 @@ impl ChatWidget { self.first_prompt_text.clone() } + /// What the session list calls this session before the agent sums it + /// up: the first prompt, else the task of a `/delegate` sent first. + pub(crate) fn first_input_title(&self) -> Option<String> { + self.first_prompt_text + .clone() + .or_else(|| self.first_delegated_task.clone()) + } + pub(crate) fn take_initial_input(&mut self) -> (Option<String>, Vec<PathBuf>) { let Some(UserMessage { text, image_paths }) = self.initial_user_message.take() else { return (None, Vec::new()); diff --git a/nori-rs/tui/src/chatwidget/mod.rs b/nori-rs/tui/src/chatwidget/mod.rs index 62acb66e6..9ed735b4c 100644 --- a/nori-rs/tui/src/chatwidget/mod.rs +++ b/nori-rs/tui/src/chatwidget/mod.rs @@ -270,6 +270,9 @@ pub(crate) struct ChatWidget { active_resume_picker_generation: Option<u64>, // The first user prompt text, preserved for /first-prompt command first_prompt_text: Option<String>, + /// The task of a `/delegate` sent before any prompt; it names the + /// session until the user's own first prompt does. + first_delegated_task: Option<String>, // Latest ACP-owned goal snapshot for this session. current_goal: Option<nori_protocol::ThreadGoal>, // Latest ACP capability snapshot projected into Nori client concepts. 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 index 607fdd4dc..c82f7a728 100644 --- 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 @@ -1,8 +1,9 @@ --- source: tui/src/chatwidget/tests/delegation.rs +assertion_line: 186 expression: screen --- -○ result from mock-model-alt · Review the parser · ready +○ 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 index 783bb64f6..8e43cf2e7 100644 --- 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 @@ -1,5 +1,6 @@ --- source: tui/src/chatwidget/tests/delegation.rs +assertion_line: 290 expression: screen --- -› delegation result from mock-model-alt · Review the parser · completed · delivered to this session +› delegation result from mock-model-alt · Review the parser · done · delivered to this session 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/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/session_path.rs b/nori-rs/tui/src/session_path.rs new file mode 100644 index 000000000..46f4453ec --- /dev/null +++ b/nori-rs/tui/src/session_path.rs @@ -0,0 +1,402 @@ +//! 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()) +} + +/// 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 +} + +/// `root › … › current` with each session's agent, followed by `tail` +/// (status words and the key back to the parent), in at most `width` cells. +/// The top-level session and the current one always stay; sessions between +/// them give way to `…` when the names would otherwise be cut short. +pub(crate) fn breadcrumb_line(path: &[PathStep], tail: &str, width: u16) -> Line<'static> { + let width = usize::from(width); + let mut steps: Vec<Option<&PathStep>> = path.iter().map(Some).collect(); + let mut with_agents = true; + let agent_label = |step: &PathStep, with_agents: bool| { + if with_agents { + format!("{} · ", step.agent) + } else { + String::new() + } + }; + loop { + 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); + let full = names.iter().map(|name| name.width()).sum::<usize>(); + // Keep every session while each name keeps a readable start. + let elidable = steps.len() > 2 && steps[1].is_some(); + if full > room && elidable && room / names.len().max(1) < 16 { + steps.splice(1..steps.len() - 1, [None]); + continue; + } + // On a very narrow terminal the names matter more than the agents. + if full > room && with_agents && room / names.len().max(1) < 4 { + with_agents = false; + continue; + } + let budgets = share(&names, room); + let mut spans: Vec<Span<'static>> = Vec::new(); + let mut named = 0; + let last = 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(&step.name, budgets[named]); + named += 1; + spans.push(if position == last { + name.bold() + } else { + name.into() + }); + } + None => spans.push(ELIDED.dim()), + } + } + spans.push(tail.to_string().dim()); + return clip(Line::from(spans), width); + } +} + +/// `● 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, 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; + } + let mut left = width.saturating_sub(1); + let mut spans = Vec::new(); + for span in line.spans { + if left == 0 { + break; + } + let kept = fit(&span.content, left.min(span.content.width())); + let kept = if kept.width() < span.content.width() { + fit(&span.content, left + 1) + .trim_end_matches('…') + .to_string() + } else { + kept + }; + left -= kept.width(); + 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)), + ])); + } + + #[test] + fn a_breadcrumb_never_drops_its_root_its_current_session_or_the_key() { + 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.starts_with("mock-model · A "), "@{width}: {line}"); + assert!(line.contains("› mock-model · A gran"), "@{width}: {line}"); + assert!(line.ends_with(KEY), "@{width}: {line}"); + } + } + + #[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}"); + } +} diff --git a/nori-rs/tui/src/session_preview.rs b/nori-rs/tui/src/session_preview.rs index c62e9c815..4ed5441d9 100644 --- a/nori-rs/tui/src/session_preview.rs +++ b/nori-rs/tui/src/session_preview.rs @@ -110,13 +110,15 @@ impl SessionPreviews { 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 +171,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 +469,40 @@ 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()) + ); + } } diff --git a/nori-rs/tui/src/session_status.rs b/nori-rs/tui/src/session_status.rs index c59cfb1a7..ffe749d25 100644 --- a/nori-rs/tui/src/session_status.rs +++ b/nori-rs/tui/src/session_status.rs @@ -41,6 +41,7 @@ pub(crate) fn status_label(status: SessionStatus) -> &'static str { SessionStatus::Ready => "ready", SessionStatus::Failed => "failed", SessionStatus::Closed => "closed", + SessionStatus::Done => "done", } } @@ -54,7 +55,7 @@ pub(crate) fn status_tone(status: SessionStatus) -> nori_tui_components::DetailT SessionStatus::Working => DetailTone::Info, SessionStatus::Ready => DetailTone::Success, SessionStatus::Failed => DetailTone::Error, - SessionStatus::Closed | SessionStatus::Starting => DetailTone::Muted, + SessionStatus::Closed | SessionStatus::Done | 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..7aa8be020 --- /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,25 @@ +--- +source: tui/src/session_path.rs +assertion_line: 286 +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 tree-row p… › … › pi · Write snapshot… · alt + up to parent + +shared prefix @120 +mock-model · mock:delegate mock-model inspect… › mock-model-alt · mock:delegate mock-model inspect… · alt + up to parent + +shared prefix @78 +mock-model · mock:delega… › mock-model-alt · mock:delega… · alt + up to parent + +long names @118 +mock-model · A parent sessio… › mock-model-alt · A child with a… › mock-model · A grandchild wh… · alt + up to parent + +long names @78 +mock-model · A parent se… › … › mock-model · A grandchil… · alt + up to parent + +long names @40 +A par… › … › A gra… · alt + up to parent 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..4b5e370f5 --- /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,22 @@ +--- +source: tui/src/session_path.rs +assertion_line: 326 +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-permission:cargo tes… is waiting on you · cargo test --wor… · alt + down to jump + +child @78 +● Ship tree-row pi… › mock:request-per… is waiting on you · alt + down to jump + +shared prefix @118 +● mock:delegate mock-mo… › mock:delegate mock-mo… is waiting on you · cargo test --wor… (+1 more) · alt + down to jump + +shared prefix @78 +● mock:delega… › mock:delega… 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-permission:cargo test… is waiting on you From 3137aaa917d0c9739f0ac613244bfda90c8d04f6 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 21:36:20 +0000 Subject: [PATCH 09/16] docs(tui): describe width-aware session paths, done status and host ls layouts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Nori](https://noriagentic.com) Co-Authored-By: Nori <contact@tilework.tech> --- docs/glossary.md | 2 +- docs/remote-control.md | 34 +++++++----- nori-rs/cli/src/host/docs.md | 29 +++++++--- nori-rs/config.md | 24 +++++---- nori-rs/harness/docs.md | 27 ++++++++-- nori-rs/nori-protocol/docs.md | 33 ++++++++---- nori-rs/tui/docs.md | 98 +++++++++++++++++++++------------- nori-rs/tui/src/attach/docs.md | 24 ++++++--- 8 files changed, 183 insertions(+), 88 deletions(-) diff --git a/docs/glossary.md b/docs/glossary.md index afd1b31bd..94f7e06ad 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -134,7 +134,7 @@ 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 | diff --git a/docs/remote-control.md b/docs/remote-control.md index 809494b31..e1748480e 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 @@ -418,14 +419,17 @@ 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: `<agent> · <child name> is waiting on you (delegated by <parent agent> · <parent name>). Press Alt+Down to answer it.` The child name is the first non-empty -line of the task and the parent name is its recorded title, each cut to 40 -characters. A completed child's result is automatically queued as attributed +line of the task (else `new session`) and the parent name is its recorded +title, each cut to 40 characters. 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 <agent> · <child name> · <outcome>`, its -second is `Child session: <child id>`, 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); the parent's own ID -is not included. The manager retains delivery until that parent's correlated +line is `[Nori delegation result] from <agent> · <child name> · <outcome>` +(`done`, `failed`, `declined`, or `cancelled`), its second is +`Child session: <child id>`, 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 @@ -503,7 +507,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 `ID AGENT STATUS AGE TITLE` table with delegated children listed under their parent and `├─`/`└─`/`│` tree guides inside TITLE. TTY output colors status (waiting on you yellow, working cyan, ready green, failed red, everything else including starting dimmed) and truncates titles to the terminal width; piped output keeps full titles without color and appends ` (parent <full id>)` to every row with a parent, including a child whose parent is no longer listed and so prints at top level. | +| `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, everything else including starting, done, 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; piped output keeps full values without color and appends ` (parent <full id>)` 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 <id>` | Open the named Nori conversation. | | `nori attach --host <URL> --token-file <path>` | Connect to an explicit managed endpoint using a private token file. | @@ -592,9 +596,13 @@ start delegations. The configured `hotkeys.next_waiting_session` binding `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. Inside a delegated child (not a fork), the -identity line reads as a breadcrumb from the parent's agent and name to the -child's. An attached parent shows a delivered result prompt as one +and AGE columns stay aligned, and both show a top-level row's `family_status`. +Inside a delegated child (not a fork), the identity line reads as a breadcrumb +of agents and names from the top-level session down to the child, fitted to +the terminal width. 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`; `closed` means a session the user closed or shut down. An +attached parent shows a delivered result prompt as one `› delegation result … · delivered to this session` line. Socket loss or a receive-liveness deadline starts recovery. Periodic session diff --git a/nori-rs/cli/src/host/docs.md b/nori-rs/cli/src/host/docs.md index b999814aa..92f0ba724 100644 --- a/nori-rs/cli/src/host/docs.md +++ b/nori-rs/cli/src/host/docs.md @@ -47,17 +47,32 @@ 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. + 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) and is cut with `…` at + grapheme boundaries. 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, and truncation - cuts the title rather than its guide. Piped output appends + cuts from the end of the title, so the guide is the last thing to go. Piped output appends ` (parent <full parent ID>)` 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. @@ -68,7 +83,7 @@ host ls / host stop ---------------+ SessionManager | working | cyan | | ready | green | | failed | red | - | others, including starting | dimmed | + | others (starting, done, 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 @@ -87,7 +102,7 @@ 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 diff --git a/nori-rs/config.md b/nori-rs/config.md index 44264aac6..32be70b4b 100644 --- a/nori-rs/config.md +++ b/nori-rs/config.md @@ -117,27 +117,30 @@ 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 | +| `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`. @@ -145,10 +148,11 @@ 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 (for a delegated child, as `<parent> › <child>`), and a temporary "Preparing <agent>…" line shows while -`/agent` starts a new agent. Inside a delegated child, a breadcrumb line names -the parent and child and the `parent_session` key. In the session list, -status words are colored: waiting on you amber, working cyan, ready green, -failed red. A blank session that never started is not counted or listed. +`/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 <agent> <task>` (or the agent's own `delegate` tool) starts a delegated child session, named after the first line of its task. In the diff --git a/nori-rs/harness/docs.md b/nori-rs/harness/docs.md index 3391a734b..8fd4c63bc 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,12 @@ 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. 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 +708,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 @@ -815,8 +823,12 @@ remote /session/delegate ----------+ | 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. The TUI recognizes these prompts by - their `[Nori delegation result]` header. A busy parent consumes it + 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 @@ -825,6 +837,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/nori-protocol/docs.md b/nori-rs/nori-protocol/docs.md index b9e401aca..23e333a6b 100644 --- a/nori-rs/nori-protocol/docs.md +++ b/nori-rs/nori-protocol/docs.md @@ -84,10 +84,13 @@ 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 @@ -104,17 +107,23 @@ and `nori attach` must agree on. | Function | Produces | | --- | --- | | `session_display_name` | First non-empty trimmed line of a task or title, cut to 40 characters with `…` | -| `delegation_child_name` | The child's display name from its task, else `session <first 8 of child ID>` | -| `delegation_status_word` | `waiting on you`, `working`, `ready`, `failed`, `declined`, or `cancelled`, matching session status words | -| `delegation_result_prompt` | The prompt delivered to the parent: `[Nori delegation result] from <agent> · <child name> · <outcome>`, then `Child session: <child id>`, then the result text | -| `delegation_result_summary` | The text after `DELEGATION_RESULT_HEADER` on a prompt's first line, only when that line starts with the header and the second line starts with `Child session: `; `None` for any other text | +| `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 <agent> · <child name> · <status word>`, then `Child session: <child id>`, 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 | + +`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. 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 both the header and the -`Child session: ` second line, so ordinary user text that merely begins with -the header is left whole. Both strings are a cross-crate contract. +`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. 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 @@ -141,6 +150,8 @@ exact ACP wire `RequestId` for harness-issued operations. - `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/tui/docs.md b/nori-rs/tui/docs.md index 2be3826ae..38ab77aed 100644 --- a/nori-rs/tui/docs.md +++ b/nori-rs/tui/docs.md @@ -921,10 +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` | Only on a delegated child (record source `Session` with a parent); shows the parent's widget | +| `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`). @@ -935,16 +935,22 @@ 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 + `ChatWidget::first_input_title` (the widget's first prompt, else the task of + a `/delegate` sent before any prompt), cut to its first line. A delegation + result prompt never counts as the first message. `first_prompt_text` itself + is unchanged and still serves loop mode and `/first-prompt`. 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 @@ -954,7 +960,7 @@ 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 @@ -963,7 +969,8 @@ in the prompt still moves the cursor. **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, - starting and closed muted. Manager sessions that descend from a listed session + starting, closed, and done muted (closed and done titles are muted too). + 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 @@ -980,24 +987,38 @@ in the prompt still moves the cursor. 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`. Lines drawn -above the bottom pane (`ChatWidget::set_session_lines`) stay visible while a -view is open: - -- a parent breadcrumb, only while a delegated child is on screen: - `<parent agent> · <parent> › <agent> · <child> · <key> to parent`, where the - key is the `parent_session` binding (omitted when unbound). The parent name - comes from `App::session_name`: its title in this TUI, else its replay - journal title, else `session <short id>`; +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, `<agent> · <name> › … › <agent> · <child> · <key> 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`: the title + in this TUI, else the replay journal title, else + `nori_protocol::UNTITLED_SESSION_NAME`; - a background-request line, naming the first off-screen session waiting on - you with an amber `●` (`<title> is waiting on you`), its request, `+N more` - when others wait, and the `next_waiting_session` key. For a delegated child - the label is `<parent> › <child>` with smaller per-part budgets for parent, - child, and request, so either form 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, tail, width)` | Never drops the top-level session, the current one, or the tail. Sessions between them collapse to one `…` when the names would get fewer than 16 cells each; on very narrow terminals agent labels drop; spare cells go to longer names; a final clip guarantees the width | +| `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 `…` | 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 @@ -1012,7 +1033,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 @@ -1083,7 +1104,7 @@ child ID. | Status | On screen | | --- | --- | | running | `↳ <requester> delegated to <agent> · <child name> · working`, plus `<transcript key> shows the brief` | -| completed | `○ result from <agent> · <child name> · ready`, 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>` | +| 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>` | @@ -1103,7 +1124,8 @@ 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; a user message that only begins with the header stays whole), +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 <summary> · delivered to this session`), because the result block was already shown when the child ended; the transcript view @@ -1115,7 +1137,7 @@ 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, and Alt+Up (`parent_session`) returns. Parent notices name both sessions readably and do not open the child's permission popup in the parent. -Closed completed children keep inspectable history; ending their process must +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 @@ -1448,9 +1470,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/attach/docs.md b/nori-rs/tui/src/attach/docs.md index 30f34e875..c01d5bb5a 100644 --- a/nori-rs/tui/src/attach/docs.md +++ b/nori-rs/tui/src/attach/docs.md @@ -54,18 +54,30 @@ Path: @/nori-rs/tui/src/attach 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 session title through - `nori_protocol::session_display_name` (else the short ID). Inside a delegated - child (a row whose `source` is `session`; forks get no breadcrumb) whose - parent is listed, it becomes a breadcrumb - `<parent agent> · <parent name> › <agent> · <child name> · <status>` followed - by the `parent_session` key (Alt+Up by default). + `nori_protocol::session_display_name`, else + `nori_protocol::UNTITLED_SESSION_NAME`. 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, + built by the shared [`session_path::breadcrumb_line`](../session_path.rs) + with the tail ` · <status> · <parent_session key> parent` (Alt+Up by + default). 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, 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). The list ignores the host's `depth` field and + cyan, ready green, failed red; starting, closed, and done 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`. The list ignores the host's `depth` field and derives depth from parent links. - Delegation uses the shared [command parser and presentation](../delegation.rs): From 40837dcd2942dd1881032919b119f776c44cf175 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 21:47:08 +0000 Subject: [PATCH 10/16] fix(tui): keep narrow session lines within the width and titles alike across frontends - Session path and waiting lines never exceed the terminal width, down to zero columns. - A /delegate sent before any prompt titles the session from the session events, so the local list, nori attach and nori host ls agree. - nori host ls clips plainly below its tightest layout. - The local breadcrumb stops if a parent chain ever loops. --- nori-rs/cli/src/host/table.rs | 27 ++++++-- nori-rs/harness/docs.md | 3 + .../harness/src/session_manager/registry.rs | 2 +- nori-rs/harness/src/session_manager/replay.rs | 22 +++--- nori-rs/tui-pty-e2e/tests/delegation.rs | 10 ++- .../delegation__delegation_session_tree.snap | 1 - ...session_list__background_request_line.snap | 1 - ...session_list__session_list_failed_row.snap | 1 - ..._list__session_list_fork_under_parent.snap | 1 - ...ion_list__session_list_three_sessions.snap | 1 - ...ion_list__session_list_waiting_on_you.snap | 1 - nori-rs/tui/docs.md | 11 +-- nori-rs/tui/src/app/session_overview.rs | 5 +- ...attach__tests__attached_host_sessions.snap | 1 - ..._attach__tests__delegation_child_list.snap | 1 - ...tui__attach__tests__delegation_result.snap | 1 - ...ttach__tests__delegation_session_tree.snap | 1 - nori-rs/tui/src/attach/state.rs | 3 +- nori-rs/tui/src/attach/tests.rs | 12 ++-- nori-rs/tui/src/chatwidget/constructors.rs | 2 - nori-rs/tui/src/chatwidget/delegation.rs | 3 - nori-rs/tui/src/chatwidget/helpers.rs | 8 --- nori-rs/tui/src/chatwidget/mod.rs | 3 - ...legation__completed_delegation_result.snap | 1 - ...legation__delivered_delegation_result.snap | 1 - nori-rs/tui/src/session_path.rs | 69 +++++++++++++++---- nori-rs/tui/src/session_preview.rs | 32 +++++++++ ...show_the_whole_path_and_fit_the_width.snap | 1 - ...nd_child_as_fully_as_the_width_allows.snap | 1 - 29 files changed, 154 insertions(+), 72 deletions(-) diff --git a/nori-rs/cli/src/host/table.rs b/nori-rs/cli/src/host/table.rs index a1c0931d0..d6453d2d5 100644 --- a/nori-rs/cli/src/host/table.rs +++ b/nori-rs/cli/src/host/table.rs @@ -103,8 +103,8 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - }; let id = clean("session_id"); let agent = clean("agent"); - // A top-level session speaks for its family: if anything under it - // waits on the user, so does its row. + // 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) @@ -153,8 +153,13 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - } else { status }; - let line = - format!("{id:<id_cells$} {agent:<agent_cells$} {status} {age:>age_cells$} {title}"); + let line = match width { + // Below the tight layout, metadata alone overflows: clip plainly. + Some(width) if width < prefix_width => truncate(&prefix, width), + _ => format!( + "{id:<id_cells$} {agent:<agent_cells$} {status} {age:>age_cells$} {title}" + ), + }; output.push_str(line.trim_end()); output.push('\n'); } @@ -452,4 +457,18 @@ mod tests { ); } } + + #[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/harness/docs.md b/nori-rs/harness/docs.md index 8fd4c63bc..4683881d8 100644 --- a/nori-rs/harness/docs.md +++ b/nori-rs/harness/docs.md @@ -685,6 +685,9 @@ processes. 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` lives only in the in-memory registry: nothing in the transcript + records it, so a child reloaded from its transcript after the host restarts + reads `Closed`. A pending request clears when any `HarnessHandle` clone answers it, when the phase returns to `Idle` or enters `Cancelling`, or when the session ends. diff --git a/nori-rs/harness/src/session_manager/registry.rs b/nori-rs/harness/src/session_manager/registry.rs index ca75ad416..a849d8453 100644 --- a/nori-rs/harness/src/session_manager/registry.rs +++ b/nori-rs/harness/src/session_manager/registry.rs @@ -471,7 +471,6 @@ impl Registry { } } - /// The live agent process of a session, if it still has one. /// 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) { @@ -480,6 +479,7 @@ impl Registry { } } + /// The live agent process of a session, if it still has one. pub(crate) fn live_process(&self, conversation_id: &ConversationId) -> Option<AgentProcessId> { self.sessions.get(conversation_id)?.process } diff --git a/nori-rs/harness/src/session_manager/replay.rs b/nori-rs/harness/src/session_manager/replay.rs index 5991c3789..cac81bf20 100644 --- a/nori-rs/harness/src/session_manager/replay.rs +++ b/nori-rs/harness/src/session_manager/replay.rs @@ -102,7 +102,7 @@ impl Journal { && delegation.origin == nori_protocol::DelegationOrigin::User && delegation.parent_id == envelope.conversation_id => { - history.title = nori_protocol::session_display_name(&delegation.task); + history.title = Some(title_line(&delegation.task)); } SessionEvent::Acp(AcpEvent::Notification( acp::AgentNotification::SessionNotification(notification), @@ -116,15 +116,7 @@ impl Journal { if let acp::ContentBlock::Text(text) = &chunk.content && nori_protocol::delegation_result_summary(&text.text).is_none() { - history.title = Some( - text.text - .lines() - .next() - .unwrap_or_default() - .chars() - .take(120) - .collect(), - ); + history.title = Some(title_line(&text.text)); } } _ => {} @@ -231,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/tui-pty-e2e/tests/delegation.rs b/nori-rs/tui-pty-e2e/tests/delegation.rs index f21f6be14..36d31019a 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -301,7 +301,9 @@ 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.settle(Duration::from_millis(300)); + 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) @@ -332,7 +334,7 @@ fn alt_down_reaches_a_waiting_child_even_with_a_draft_in_the_parent() { let last_answer = lines .iter() .rposition(|line| line.contains("Delegation continuation received")) - .unwrap_or_default(); + .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}" @@ -345,7 +347,9 @@ fn alt_up_in_a_top_level_session_leaves_the_prompt_alone() { session.settle(Duration::from_millis(300)); let before = session.screen_contents(); session.send_key(Key::AltUp).unwrap(); - session.settle(Duration::from_millis(500)); + // 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(), 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 index 5f29b2b14..ce2440715 100644 --- 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 @@ -1,6 +1,5 @@ --- source: tui-pty-e2e/tests/delegation.rs -assertion_line: 278 expression: normalize_for_input_snapshot(list) --- Sessions 2 · 1 ready tab: waiting only · type to search 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 750fbd8cb..5b7cceca7 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 @@ -1,6 +1,5 @@ --- source: tui-pty-e2e/tests/session_list.rs -assertion_line: 237 expression: normalize_for_input_snapshot(session.screen_contents()) --- • Mock ACP options: Model=Mock Default Model, Thought Level=Medium (/config to change) 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 fa3ac6250..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 @@ -1,6 +1,5 @@ --- source: tui-pty-e2e/tests/session_list.rs -assertion_line: 298 expression: normalize_for_input_snapshot(session.screen_contents()) --- • Mock ACP options: Model=Mock Default Model, Thought Level=Medium (/config to change) 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 7044bf97b..8e4c04b5a 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 @@ -1,6 +1,5 @@ --- source: tui-pty-e2e/tests/session_list.rs -assertion_line: 367 expression: normalize_for_input_snapshot(screen) --- • Mock ACP options: Model=Mock Default Model, Thought Level=Medium (/config to change) 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 5750d81d5..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 @@ -1,6 +1,5 @@ --- source: tui-pty-e2e/tests/session_list.rs -assertion_line: 121 expression: normalize_for_input_snapshot(screen) --- › gamma question 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 c3244bb35..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 @@ -1,6 +1,5 @@ --- source: tui-pty-e2e/tests/session_list.rs -assertion_line: 144 expression: normalize_for_input_snapshot(session.screen_contents()) --- › gamma question diff --git a/nori-rs/tui/docs.md b/nori-rs/tui/docs.md index 38ab77aed..d074b0537 100644 --- a/nori-rs/tui/docs.md +++ b/nori-rs/tui/docs.md @@ -939,11 +939,12 @@ in the prompt still moves the cursor. 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 - `ChatWidget::first_input_title` (the widget's first prompt, else the task of - a `/delegate` sent before any prompt), cut to its first line. A delegation - result prompt never counts as the first message. `first_prompt_text` itself - is unchanged and still serves loop mode and `/first-prompt`. Previews + (so a prompt sent by a remote-control client also titles it), else the + widget's first prompt, cut to its first line. 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 (connection lost, diff --git a/nori-rs/tui/src/app/session_overview.rs b/nori-rs/tui/src/app/session_overview.rs index 3ac6208b1..effcedee5 100644 --- a/nori-rs/tui/src/app/session_overview.rs +++ b/nori-rs/tui/src/app/session_overview.rs @@ -133,7 +133,7 @@ impl App { let widget = self.widget_for(generation); self.session_previews .title(generation) - .or_else(|| widget.and_then(ChatWidget::first_input_title)) + .or_else(|| widget.and_then(ChatWidget::first_prompt_text)) .map(|title| cut(title.lines().next().unwrap_or_default().trim(), limit)) .filter(|title| !title.is_empty()) } @@ -410,11 +410,14 @@ impl App { 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, TITLE_CHARS), 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 0c79f069a..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 @@ -1,6 +1,5 @@ --- source: tui/src/attach/tests.rs -assertion_line: 183 expression: rendered --- Nori host CONTROLLING 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 8ffbe2745..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 @@ -1,6 +1,5 @@ --- source: tui/src/attach/tests.rs -assertion_line: 571 expression: rendered --- Nori host WATCHING · read-only · alt+t take control 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 ba90986fe..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 @@ -1,6 +1,5 @@ --- source: tui/src/attach/tests.rs -assertion_line: 548 expression: rendered --- Nori host WATCHING · read-only · alt+t take control 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 index e64d6817e..7af01c1f4 100644 --- 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 @@ -1,6 +1,5 @@ --- source: tui/src/attach/tests.rs -assertion_line: 616 expression: rendered --- Nori host WATCHING · read-only · alt+t take control diff --git a/nori-rs/tui/src/attach/state.rs b/nori-rs/tui/src/attach/state.rs index 27e31b88b..7d0e37a2c 100644 --- a/nori-rs/tui/src/attach/state.rs +++ b/nori-rs/tui/src/attach/state.rs @@ -163,7 +163,8 @@ impl AttachState { .title .clone() .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.into()); - // A top-level session speaks for its family. + // 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) diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs index b14aed921..705f02325 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -958,8 +958,12 @@ fn the_waiting_line_names_another_waiting_session_never_the_one_on_screen() { ..Default::default() }; let mut sessions = family(); - sessions["sessions"][3]["status"] = json!("waiting_on_you"); - sessions["sessions"][3]["family_status"] = json!("waiting_on_you"); + 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); @@ -979,7 +983,7 @@ 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("›")) + .find(|line| line.contains("alt+up parent")) .unwrap_or_else(|| panic!("breadcrumb missing:\n{rendered}")); assert!( breadcrumb.contains( @@ -991,7 +995,7 @@ fn a_grandchild_breadcrumb_shows_the_path_from_its_top_level_session() { let rendered = screen_at(&viewing("grandchild-session"), width); let breadcrumb = rendered .lines() - .find(|line| line.contains("›")) + .find(|line| line.contains("alt+up parent")) .unwrap_or_else(|| panic!("breadcrumb missing:\n{rendered}")); assert!( breadcrumb.starts_with(" mock-model · Ship"), diff --git a/nori-rs/tui/src/chatwidget/constructors.rs b/nori-rs/tui/src/chatwidget/constructors.rs index f42cfdb1d..016456e9b 100644 --- a/nori-rs/tui/src/chatwidget/constructors.rs +++ b/nori-rs/tui/src/chatwidget/constructors.rs @@ -193,7 +193,6 @@ impl ChatWidget { login_agent_override: None, active_resume_picker_generation: None, first_prompt_text, - first_delegated_task: None, current_goal: None, session_agent_capabilities: crate::presentation::AgentCapabilitiesView::default(), cloud_mode, @@ -386,7 +385,6 @@ impl ChatWidget { login_agent_override: None, active_resume_picker_generation: None, first_prompt_text, - first_delegated_task: None, current_goal: None, session_agent_capabilities: crate::presentation::AgentCapabilitiesView::default(), cloud_mode, diff --git a/nori-rs/tui/src/chatwidget/delegation.rs b/nori-rs/tui/src/chatwidget/delegation.rs index da05ac73b..aa59962b8 100644 --- a/nori-rs/tui/src/chatwidget/delegation.rs +++ b/nori-rs/tui/src/chatwidget/delegation.rs @@ -25,9 +25,6 @@ impl ChatWidget { self.add_error_message("Start a session before delegating a task.".into()); return true; }; - if self.first_prompt_text.is_none() && self.first_delegated_task.is_none() { - self.first_delegated_task = Some(task.clone()); - } let manager = self.session_manager.clone(); let tx = self.app_event_tx.clone(); tokio::spawn(async move { diff --git a/nori-rs/tui/src/chatwidget/helpers.rs b/nori-rs/tui/src/chatwidget/helpers.rs index a505e0947..293d06d91 100644 --- a/nori-rs/tui/src/chatwidget/helpers.rs +++ b/nori-rs/tui/src/chatwidget/helpers.rs @@ -223,14 +223,6 @@ impl ChatWidget { self.first_prompt_text.clone() } - /// What the session list calls this session before the agent sums it - /// up: the first prompt, else the task of a `/delegate` sent first. - pub(crate) fn first_input_title(&self) -> Option<String> { - self.first_prompt_text - .clone() - .or_else(|| self.first_delegated_task.clone()) - } - pub(crate) fn take_initial_input(&mut self) -> (Option<String>, Vec<PathBuf>) { let Some(UserMessage { text, image_paths }) = self.initial_user_message.take() else { return (None, Vec::new()); diff --git a/nori-rs/tui/src/chatwidget/mod.rs b/nori-rs/tui/src/chatwidget/mod.rs index 9ed735b4c..62acb66e6 100644 --- a/nori-rs/tui/src/chatwidget/mod.rs +++ b/nori-rs/tui/src/chatwidget/mod.rs @@ -270,9 +270,6 @@ pub(crate) struct ChatWidget { active_resume_picker_generation: Option<u64>, // The first user prompt text, preserved for /first-prompt command first_prompt_text: Option<String>, - /// The task of a `/delegate` sent before any prompt; it names the - /// session until the user's own first prompt does. - first_delegated_task: Option<String>, // Latest ACP-owned goal snapshot for this session. current_goal: Option<nori_protocol::ThreadGoal>, // Latest ACP capability snapshot projected into Nori client concepts. 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 index c82f7a728..42cb91a24 100644 --- 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 @@ -1,6 +1,5 @@ --- source: tui/src/chatwidget/tests/delegation.rs -assertion_line: 186 expression: screen --- ○ result from mock-model-alt · Review the parser · done 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 index 8e43cf2e7..ff860c74e 100644 --- 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 @@ -1,6 +1,5 @@ --- source: tui/src/chatwidget/tests/delegation.rs -assertion_line: 290 expression: screen --- › delegation result from mock-model-alt · Review the parser · done · delivered to this session diff --git a/nori-rs/tui/src/session_path.rs b/nori-rs/tui/src/session_path.rs index 46f4453ec..8668c07b2 100644 --- a/nori-rs/tui/src/session_path.rs +++ b/nori-rs/tui/src/session_path.rs @@ -220,21 +220,23 @@ fn clip(line: Line<'static>, width: usize) -> Line<'static> { if line.width() <= width { return line; } - let mut left = width.saturating_sub(1); + 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(); - for span in line.spans { - if left == 0 { - break; + '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); } - let kept = fit(&span.content, left.min(span.content.width())); - let kept = if kept.width() < span.content.width() { - fit(&span.content, left + 1) - .trim_end_matches('…') - .to_string() - } else { - kept - }; - left -= kept.width(); spans.push(Span::styled(kept, span.style)); } spans.push(Span::raw("…")); @@ -399,4 +401,45 @@ mod tests { ); 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 4ed5441d9..31a77f04f 100644 --- a/nori-rs/tui/src/session_preview.rs +++ b/nori-rs/tui/src/session_preview.rs @@ -107,6 +107,15 @@ 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(); @@ -505,4 +514,27 @@ mod tests { 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/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 index 7aa8be020..5c6202761 100644 --- 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 @@ -1,6 +1,5 @@ --- source: tui/src/session_path.rs -assertion_line: 286 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 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 index 4b5e370f5..171e1703a 100644 --- 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 @@ -1,6 +1,5 @@ --- source: tui/src/session_path.rs -assertion_line: 326 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 From 1224863e02aaaf144566c2018928c67aa105898d Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 23:50:40 +0000 Subject: [PATCH 11/16] fix(tui): keep drafts across attach jumps and cut session names in the middle - nori attach: Alt+Down jumps even with a draft; each session keeps its own draft. - Session names keep their start and end, so shared prefixes read apart. - Breadcrumbs drop the parent key before cutting the current session's name. - The collapsed delegation result fits one row at 80 columns; the result header carries the child's whole task line. - Delegation cards say started instead of a status that goes stale. - Attached top-level headers show the family status; done reads apart from closed; a finished child's view points back to its parent. --- nori-rs/cli/src/host/table.rs | 87 ++++++- nori-rs/nori-protocol/src/delegation.rs | 102 +++++++- nori-rs/tui-pty-e2e/tests/delegation.rs | 20 +- nori-rs/tui-pty-e2e/tests/host_attach.rs | 6 +- ...session_list__background_request_line.snap | 2 +- ..._list__session_list_fork_under_parent.snap | 2 +- nori-rs/tui/src/app/session_overview.rs | 24 +- nori-rs/tui/src/attach/docs.md | 60 +++-- nori-rs/tui/src/attach/input.rs | 36 +-- nori-rs/tui/src/attach/render.rs | 55 +++-- nori-rs/tui/src/attach/runtime.rs | 32 ++- nori-rs/tui/src/attach/state.rs | 33 ++- nori-rs/tui/src/attach/tests.rs | 222 ++++++++++++++++- .../tui/src/chatwidget/tests/delegation.rs | 44 ++++ ...__delegation__running_delegation_line.snap | 2 +- ...gation__running_delegation_transcript.snap | 2 +- nori-rs/tui/src/delegation.rs | 42 +++- nori-rs/tui/src/history_cell/mod.rs | 13 +- .../tui/src/public_widgets/composer_input.rs | 5 + nori-rs/tui/src/session_path.rs | 231 ++++++++++++++---- nori-rs/tui/src/session_status.rs | 6 +- ...show_the_whole_path_and_fit_the_width.snap | 14 +- ...nd_child_as_fully_as_the_width_allows.snap | 10 +- 23 files changed, 858 insertions(+), 192 deletions(-) diff --git a/nori-rs/cli/src/host/table.rs b/nori-rs/cli/src/host/table.rs index d6453d2d5..8f6693b6f 100644 --- a/nori-rs/cli/src/host/table.rs +++ b/nori-rs/cli/src/host/table.rs @@ -110,11 +110,11 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - .filter(|_| depth == 0) .unwrap_or_else(|| row["status"].as_str().unwrap_or("-")); let status = status_key.replace('_', " "); - let title = format!("{guide}{}", clean("title")); + let name = clean("title"); let title = if row["parent"].is_string() && width.is_none() { - format!("{title} (parent {})", clean("parent")) + format!("{guide}{name} (parent {})", clean("parent")) } else { - title + format!("{guide}{name}") }; let seconds = row["age_seconds"].as_i64().unwrap_or(0).max(0); let age = if seconds < 60 { @@ -137,9 +137,18 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - "{id:<id_cells$} {agent:<agent_cells$} {status:<status_cells$} {age:>age_cells$} " ); let prefix_width = prefix.width(); + // 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:<status_cells$}"); let status = if color { @@ -148,6 +157,9 @@ pub(super) fn format_table(listing: &Value, width: Option<usize>, color: bool) - "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 { @@ -184,6 +196,35 @@ 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::*; @@ -458,6 +499,44 @@ mod tests { } } + #[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::<Vec<_>>(); + assert!(rows[0].contains("done"), "{colored:?}"); + assert!( + !rows[0].contains("\u{1b}[2m"), + "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::<Vec<_>>(); + 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":[ diff --git a/nori-rs/nori-protocol/src/delegation.rs b/nori-rs/nori-protocol/src/delegation.rs index bf9023be1..42f4b9df0 100644 --- a/nori-rs/nori-protocol/src/delegation.rs +++ b/nori-rs/nori-protocol/src/delegation.rs @@ -12,16 +12,32 @@ 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<String> { + 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. +/// 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<String> { - let line = text.lines().map(str::trim).find(|line| !line.is_empty())?; - let limit = usize::try_from(NAME_CHARS).unwrap_or_default(); - if line.chars().count() <= limit { - return Some(line.to_owned()); + 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(); } - let cut: String = line.chars().take(limit - 1).collect(); - Some(format!("{}…", cut.trim_end())) + 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. @@ -50,7 +66,7 @@ pub fn delegation_result_prompt(delegation: &Delegation) -> String { let header = format!( "{DELEGATION_RESULT_HEADER} from {} · {} · {}", delegation.agent, - delegation_child_name(delegation), + 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(); @@ -78,6 +94,29 @@ pub fn delegation_result_summary(prompt: &str) -> Option<&str> { (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<DelegationResultParts<'_>> { + 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::*; @@ -145,6 +184,53 @@ mod tests { 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!( diff --git a/nori-rs/tui-pty-e2e/tests/delegation.rs b/nori-rs/tui-pty-e2e/tests/delegation.rs index 36d31019a..e430168ba 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -421,21 +421,19 @@ fn the_child_breadcrumb_fits_one_row_of_an_80_column_terminal() { .wait_for_text("Would you like to allow", TIMEOUT) .unwrap(); session - .wait_for_text("to parent", TIMEOUT) - .expect("the child shows the way back to its parent"); + .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("to parent")) - .unwrap_or_else(|| panic!("breadcrumb missing:\n{screen}")); - assert!( - breadcrumb.contains("mock-model · parent task") - && breadcrumb.contains("› mock-model-alt · mock:req"), - "the breadcrumb is one row:\n{screen}" - ); + .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("alt + up to parent"), - "{screen}" + breadcrumb + .trim_end() + .ends_with("› mock:request-permission:write-child-file") + || breadcrumb.contains("write-child-file · alt + up to parent"), + "the current name stays whole; the key gives way first:\n{screen}" ); } diff --git a/nori-rs/tui-pty-e2e/tests/host_attach.rs b/nori-rs/tui-pty-e2e/tests/host_attach.rs index 9561ecf1e..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}"); } 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 5b7cceca7..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:rm -rf targe… is waiting on you · approve: rm -rf… (+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_fork_under_parent.snap b/nori-rs/tui-pty-e2e/tests/snapshots/session_list__session_list_fork_under_parent.snap index 8e4c04b5a..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 question › mock:request-permission:rm -… is waiting on you · approve: rm -rf… · 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 diff --git a/nori-rs/tui/src/app/session_overview.rs b/nori-rs/tui/src/app/session_overview.rs index effcedee5..95443b288 100644 --- a/nori-rs/tui/src/app/session_overview.rs +++ b/nori-rs/tui/src/app/session_overview.rs @@ -18,15 +18,11 @@ use crate::session_status::status_word; /// Longest title shown for a session that has no summary yet. const TITLE_CHARS: i32 = 60; +/// For lines that fit names to the terminal width themselves. +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. @@ -349,11 +345,11 @@ impl App { .collect(); let first = waiting.first()?; let title = self - .session_title(first.generation, TITLE_CHARS) + .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, TITLE_CHARS)); + path.push(self.session_name(&parent, WHOLE_NAME)); } path.push(title); let request = self.session_previews.pending_request(first.generation); @@ -381,7 +377,7 @@ impl App { self.session_manager .replay_info(id) .and_then(|info| info.title) - .and_then(|title| nori_protocol::session_display_name(&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()) @@ -404,7 +400,7 @@ impl App { let mut path = vec![crate::session_path::PathStep { agent: child.agent.clone(), name: self - .session_title(child.generation, TITLE_CHARS) + .session_title(child.generation, WHOLE_NAME) .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_string()), }]; let mut record = child @@ -420,7 +416,7 @@ impl App { seen.push(parent); path.push(crate::session_path::PathStep { agent: parent_record.agent.clone(), - name: self.session_name(&parent, TITLE_CHARS), + name: self.session_name(&parent, WHOLE_NAME), }); record = Some(parent_record); } @@ -433,6 +429,8 @@ impl App { } else { format!(" · {} to parent", binding.display_name()) }; - Some(crate::session_path::breadcrumb_line(&path, &tail, width)) + Some(crate::session_path::breadcrumb_line( + &path, "", &tail, width, + )) } } diff --git a/nori-rs/tui/src/attach/docs.md b/nori-rs/tui/src/attach/docs.md index c01d5bb5a..0530ba8d6 100644 --- a/nori-rs/tui/src/attach/docs.md +++ b/nori-rs/tui/src/attach/docs.md @@ -53,27 +53,33 @@ Path: @/nori-rs/tui/src/attach selected conversation or session list. Watchers receive the same content and 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 session title through - `nori_protocol::session_display_name`, else - `nori_protocol::UNTITLED_SESSION_NAME`. 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, - built by the shared [`session_path::breadcrumb_line`](../session_path.rs) - with the tail ` · <status> · <parent_session key> parent` (Alt+Up by - default). The walk follows listed delegating parents and stops at a repeat. + `<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, and the row stays empty when nothing waits. + 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; starting, closed, and done muted). A row at + 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 @@ -93,12 +99,19 @@ Path: @/nori-rs/tui/src/attach empty `DelegationHints` and shows no key hints. An `awaiting_approval` change adds no part; the approval prompt covers it. - 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. + `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 composer text with the session it + was typed in and restores the target's own draft, so text never follows the + user into another session. 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 @@ -106,9 +119,18 @@ Path: @/nori-rs/tui/src/attach 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. The echoed result prompt (a user message that - `nori_protocol::delegation_result_summary` recognizes) renders as one - `› delegation result <summary> · delivered to this session` line, since the - result block already shows the text. + `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 70ad0e032..01ec9d098 100644 --- a/nori-rs/tui/src/attach/input.rs +++ b/nori-rs/tui/src/attach/input.rs @@ -23,10 +23,11 @@ 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) @@ -43,12 +44,7 @@ impl Runtime { .iter() .any(|row| row.session_id == parent) { - self.state.selected = Some(parent); - self.state.list_open = false; - self.state.scroll = 0; - self.state.notice = None; - self.state.replay_error = None; - self.subscribe_selected(); + self.open_session(parent); return true; } if crate::nori::hotkey_match::matches_binding(&self.session_list_binding, &key) { @@ -137,7 +133,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() @@ -151,16 +148,14 @@ 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 } fn delegation_key(&mut self, key: KeyEvent) -> bool { @@ -212,12 +207,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 } diff --git a/nori-rs/tui/src/attach/render.rs b/nori-rs/tui/src/attach/render.rs index 6e3e5d523..641bb6ba9 100644 --- a/nori-rs/tui/src/attach/render.rs +++ b/nori-rs/tui/src/attach/render.rs @@ -114,11 +114,12 @@ pub(super) fn render( composer.render_ref(input, buf); } -/// A readable name for a listed session. +/// 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_display_name) + .and_then(nori_protocol::session_full_name) .unwrap_or_else(|| nori_protocol::UNTITLED_SESSION_NAME.to_string()) } @@ -133,15 +134,14 @@ fn identity_line(state: &AttachState, width: u16) -> Line<'static> { let Some(current) = row(id) else { return Line::from(format!(" session · {id}").dim()); }; - let status = format!(" · {}", crate::session_status::status_label(current.status)); - if current.delegating_parent().and_then(row).is_none() { - return Line::from(vec![ - " ".into(), - format!("{} · ", current.agent).dim(), - row_name(current).bold(), - status.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() @@ -159,16 +159,13 @@ fn identity_line(state: &AttachState, width: u16) -> Line<'static> { name: row_name(row), }) .collect(); - let key = if state.parent_binding.is_none() { + 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, - &format!("{status}{key}"), - width.saturating_sub(1), - ); + let mut line = + crate::session_path::breadcrumb_line(&path, &status, &key, width.saturating_sub(1)); line.spans.insert(0, " ".into()); line } @@ -264,14 +261,16 @@ fn render_conversation(state: &AttachState, id: &str, area: Rect, buf: &mut Buff stream: MessageStream::User, text, .. - } if nori_protocol::delegation_result_summary(text).is_some() => { - let summary = nori_protocol::delegation_result_summary(text).unwrap_or_default(); - lines.push(Line::from(vec![ - "› ".bold(), - "delegation result ".dim(), - summary.to_owned().into(), - " · delivered to this session".dim(), - ])); + } 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 { @@ -316,6 +315,12 @@ fn render_conversation(state: &AttachState, id: &str, area: Rect, buf: &mut Buff 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 2178f6f5f..436666b96 100644 --- a/nori-rs/tui/src/attach/runtime.rs +++ b/nori-rs/tui/src/attach/runtime.rs @@ -28,6 +28,8 @@ 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, + /// Unsent text of each session not on screen, restored when it returns. + drafts: HashMap<String, String>, } impl Runtime { @@ -75,9 +77,32 @@ 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 draft in the composer stays with the session + /// it was typed in, and `id`'s own draft comes back. + pub(super) fn open_session(&mut self, id: String) { + if self.state.selected.as_ref() != Some(&id) { + if let Some(previous) = self.state.selected.take() + && !self.composer.is_empty() + { + self.drafts.insert(previous, self.composer.text()); + } + self.composer.clear(); + if let Some(draft) = self.drafts.remove(&id) { + self.composer.handle_paste(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; @@ -239,12 +264,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/state.rs b/nori-rs/tui/src/attach/state.rs index 7d0e37a2c..06ff7b180 100644 --- a/nori-rs/tui/src/attach/state.rs +++ b/nori-rs/tui/src/attach/state.rs @@ -56,6 +56,8 @@ pub(super) enum Part { 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 { @@ -198,6 +200,7 @@ 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) @@ -246,6 +249,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; @@ -346,11 +373,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; } diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs index 705f02325..d8cfc1b05 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -648,7 +648,7 @@ fn child_view_shows_breadcrumb_and_alt_up_returns_to_parent() { } #[test] -fn long_names_leave_room_for_the_parent_key_in_the_breadcrumb() { +fn long_names_keep_the_current_name_whole_before_the_parent_key() { let state = { let mut state = AttachState { connected: true, @@ -668,7 +668,12 @@ fn long_names_leave_room_for_the_parent_key_in_the_breadcrumb() { .lines() .find(|line| line.contains("›")) .unwrap_or_else(|| panic!("breadcrumb missing:\n{rendered}")); - assert!(breadcrumb.ends_with("alt+up parent"), "{rendered}"); + assert!( + breadcrumb.contains("› Verify every link in the generated changelog · waiting on you") + || breadcrumb + .contains("› mock-model-alt · Verify every link in the generated changelog"), + "{rendered}" + ); } #[test] @@ -995,18 +1000,14 @@ fn a_grandchild_breadcrumb_shows_the_path_from_its_top_level_session() { let rendered = screen_at(&viewing("grandchild-session"), width); let breadcrumb = rendered .lines() - .find(|line| line.contains("alt+up parent")) + .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"), - "@{width}: {rendered}" - ); - assert!( - breadcrumb.ends_with("alt+up parent"), + breadcrumb.contains("› mock-model · Write snapshot tests · waiting on you"), "@{width}: {rendered}" ); } @@ -1032,3 +1033,208 @@ fn an_untitled_session_is_called_new_session_not_an_id() { ); 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" + ); + 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"); +} + +#[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); + let end = rendered + .lines() + .find(|line| line.contains("finished")) + .unwrap_or_else(|| panic!("end line missing:\n{rendered}")); + assert!(end.contains("alt+up"), "{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("finished"), "{closed}"); + assert!(!closed.contains("/new to start"), "{closed}"); +} + +#[test] +fn the_grandchild_name_stays_whole_at_80_columns() { + let mut state = AttachState { + connected: true, + selected: Some("grandchild-session".into()), + ..Default::default() + }; + state + .replace_sessions(json!({"sessions":[ + {"session_id":"root-session","agent":"mock-model","status":"ready","title":"mock:delegate mock-model mock:delegate mock-model mock:request-permission:x"}, + {"session_id":"child-session","agent":"mock-model","status":"working","title":"mock:delegate mock-model mock:request-permission:x","parent":"root-session","source":"session"}, + {"session_id":"grandchild-session","agent":"mock-model","status":"waiting_on_you","title":"mock:request-permission:x","parent":"child-session","source":"session"} + ]})) + .unwrap(); + state.list_open = false; + let rendered = screen_at(&state, 80); + assert!( + rendered.contains("mock:request-permission:x · waiting on you"), + "{rendered}" + ); + assert!(!rendered.contains("alt+up"), "{rendered}"); + let wide = screen_at(&state, 120); + assert!( + wide.contains("mock:request-permission:x · waiting on you · alt+up parent"), + "{wide}" + ); +} + +#[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}"); + let next = lines.get(at + 1).copied().unwrap_or_default(); + assert!( + !next.starts_with(" ") || next.trim().is_empty(), + "the line wraps onto a second row: {rendered}" + ); +} diff --git a/nori-rs/tui/src/chatwidget/tests/delegation.rs b/nori-rs/tui/src/chatwidget/tests/delegation.rs index b10120afa..1c4287d10 100644 --- a/nori-rs/tui/src/chatwidget/tests/delegation.rs +++ b/nori-rs/tui/src/chatwidget/tests/delegation.rs @@ -144,6 +144,14 @@ fn running_delegation_is_one_line_naming_child_agent_and_status() { 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); } @@ -290,6 +298,42 @@ fn delivered_result_reads_as_a_short_line_in_the_parent() { 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(78)); + 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] fn child_shutdown_preserves_terminal_and_history() { let (mut chat, mut rx, _) = make_chatwidget_manual(); 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 index 4da146f02..41f1eff52 100644 --- 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 @@ -2,5 +2,5 @@ source: tui/src/chatwidget/tests/delegation.rs expression: screen --- -↳ mock-model delegated to mock-model-alt · Write snapshot tests for TreeRow · working +↳ 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 index cab12cc74..2e0185cae 100644 --- 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 @@ -2,7 +2,7 @@ source: tui/src/chatwidget/tests/delegation.rs expression: transcript --- -↳ mock-model delegated to mock-model-alt · Write snapshot tests for TreeRow · working +↳ 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/delegation.rs b/nori-rs/tui/src/delegation.rs index 9861e1dee..72a6a0a7d 100644 --- a/nori-rs/tui/src/delegation.rs +++ b/nori-rs/tui/src/delegation.rs @@ -10,6 +10,7 @@ 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; @@ -49,8 +50,17 @@ fn requester(delegation: &Delegation) -> String { } } +/// 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 = nori_protocol::delegation_status_word(status); + 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) @@ -71,6 +81,36 @@ fn child_spans(delegation: &Delegation) -> Vec<Span<'static>> { ] } +/// 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) diff --git a/nori-rs/tui/src/history_cell/mod.rs b/nori-rs/tui/src/history_cell/mod.rs index 7f0c2159e..c99187f9a 100644 --- a/nori-rs/tui/src/history_cell/mod.rs +++ b/nori-rs/tui/src/history_cell/mod.rs @@ -88,16 +88,15 @@ impl HistoryCell for UserHistoryCell { /// 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(summary) = nori_protocol::delegation_result_summary(&self.message) else { + 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 line = Line::from(vec![ - "› ".bold().dim(), - "delegation result ".dim(), - summary.to_owned().into(), - " · delivered to this session".dim(), - ]); + 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)], diff --git a/nori-rs/tui/src/public_widgets/composer_input.rs b/nori-rs/tui/src/public_widgets/composer_input.rs index ad4233e22..094ddac24 100644 --- a/nori-rs/tui/src/public_widgets/composer_input.rs +++ b/nori-rs/tui/src/public_widgets/composer_input.rs @@ -55,6 +55,11 @@ impl ComposerInput { self.inner.is_empty() } + /// The current input text. + pub fn text(&self) -> String { + self.inner.current_text() + } + /// 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 index 8668c07b2..16f80ff16 100644 --- a/nori-rs/tui/src/session_path.rs +++ b/nori-rs/tui/src/session_path.rs @@ -35,6 +35,35 @@ pub(crate) fn fit(text: &str, cells: usize) -> String { 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 { + if text.width() <= cells { + return text.to_string(); + } + if cells == 0 { + return String::new(); + } + let room = cells - 1; + let mut head = String::new(); + for ch in text.chars() { + if head.width() + ch.to_string().width() > room.div_ceil(2) { + break; + } + head.push(ch); + } + let mut tail: Vec<char> = Vec::new(); + for ch in text.chars().rev() { + let cells = ch.to_string().width(); + if head.width() + tail.iter().collect::<String>().width() + cells > room { + break; + } + tail.push(ch); + } + let tail: String = tail.into_iter().rev().collect(); + format!("{}…{}", head.trim_end(), tail.trim_start()) +} + /// 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> { @@ -61,22 +90,40 @@ fn share(names: &[&str], room: usize) -> Vec<usize> { budgets } -/// `root › … › current` with each session's agent, followed by `tail` -/// (status words and the key back to the parent), in at most `width` cells. -/// The top-level session and the current one always stay; sessions between -/// them give way to `…` when the names would otherwise be cut short. -pub(crate) fn breadcrumb_line(path: &[PathStep], tail: &str, width: u16) -> Line<'static> { +/// 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 mut steps: Vec<Option<&PathStep>> = path.iter().map(Some).collect(); - let mut with_agents = true; - let agent_label = |step: &PathStep, with_agents: bool| { - if with_agents { - format!("{} · ", step.agent) - } else { - String::new() - } + 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(), }; - loop { + 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 @@ -93,22 +140,30 @@ pub(crate) fn breadcrumb_line(path: &[PathStep], tail: &str, width: u16) -> Line .map(|step| step.name.as_str()) .collect(); let room = width.saturating_sub(fixed); - let full = names.iter().map(|name| name.width()).sum::<usize>(); - // Keep every session while each name keeps a readable start. - let elidable = steps.len() > 2 && steps[1].is_some(); - if full > room && elidable && room / names.len().max(1) < 16 { - steps.splice(1..steps.len() - 1, [None]); - continue; - } - // On a very narrow terminal the names matter more than the agents. - if full > room && with_agents && room / names.len().max(1) < 4 { - with_agents = false; + let floor = if index == last { + MIN_NAME_CELLS + } else { + MIN_OTHER + }; + 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 budgets = share(&names, room); let mut spans: Vec<Span<'static>> = Vec::new(); let mut named = 0; - let last = steps.len().saturating_sub(1); + let current = steps.len().saturating_sub(1); for (position, step) in steps.iter().enumerate() { if position > 0 { spans.push(PATH_SEPARATOR.dim()); @@ -118,9 +173,9 @@ pub(crate) fn breadcrumb_line(path: &[PathStep], tail: &str, width: u16) -> Line if with_agents { spans.push(agent_label(step, true).dim()); } - let name = fit(&step.name, budgets[named]); + let name = fit_name(&step.name, budgets[named]); named += 1; - spans.push(if position == last { + spans.push(if position == current { name.bold() } else { name.into() @@ -132,6 +187,32 @@ pub(crate) fn breadcrumb_line(path: &[PathStep], tail: &str, width: u16) -> Line 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 @@ -185,7 +266,7 @@ pub(crate) fn waiting_line( let path_text = names .iter() .zip(budgets) - .map(|(name, budget)| fit(name, budget)) + .map(|(name, budget)| fit_name(name, budget)) .collect::<Vec<_>>() .join(PATH_SEPARATOR); spans.push(path_text.bold()); @@ -309,18 +390,78 @@ mod tests { ), ]; 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)), + ("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}"); + } + + #[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_its_current_session_or_the_key() { + fn a_breadcrumb_never_drops_its_root_or_its_current_session() { let long = [ step( "mock-model", @@ -336,11 +477,15 @@ mod tests { ), ]; for width in [118, 100, 78] { - let line = text(&breadcrumb_line(&long, KEY, width)); - assert!(line.starts_with("mock-model · A "), "@{width}: {line}"); - assert!(line.contains("› mock-model · A gran"), "@{width}: {line}"); - assert!(line.ends_with(KEY), "@{width}: {line}"); + let line = text(&breadcrumb_line(&long, "", KEY, width)); + assert!(line.contains("A parent"), "@{width}: {line}"); + assert!( + line.contains("› A gran") || line.contains("› mock-model · A gran"), + "@{width}: {line}" + ); } + let wide = text(&breadcrumb_line(&long, "", KEY, 118)); + assert!(wide.ends_with(KEY), "{wide}"); } #[test] @@ -422,8 +567,8 @@ mod tests { let alone = ["Spike transport".to_string()]; for width in 0..=120 { let lines = [ - breadcrumb_line(&long, KEY, width), - breadcrumb_line(&long[..1], KEY, width), + breadcrumb_line(&long, "", KEY, width), + breadcrumb_line(&long[..1], "", KEY, width), waiting_line( &names, Some("cargo test --workspace"), diff --git a/nori-rs/tui/src/session_status.rs b/nori-rs/tui/src/session_status.rs index ffe749d25..334c61b5c 100644 --- a/nori-rs/tui/src/session_status.rs +++ b/nori-rs/tui/src/session_status.rs @@ -47,7 +47,8 @@ pub(crate) fn status_label(status: SessionStatus) -> &'static str { /// 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. +/// 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 { @@ -55,7 +56,8 @@ pub(crate) fn status_tone(status: SessionStatus) -> nori_tui_components::DetailT SessionStatus::Working => DetailTone::Info, SessionStatus::Ready => DetailTone::Success, SessionStatus::Failed => DetailTone::Error, - SessionStatus::Closed | SessionStatus::Done | SessionStatus::Starting => DetailTone::Muted, + 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 index 5c6202761..ca7e158d8 100644 --- 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 @@ -1,24 +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)),])" +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 tree-row p… › … › pi · Write snapshot… · alt + up to parent +claude-code · Ship…icker › … › pi · Write snapshot tests · alt + up to parent shared prefix @120 -mock-model · mock:delegate mock-model inspect… › mock-model-alt · mock:delegate mock-model inspect… · alt + up to parent +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-model · mock:delega… › mock-model-alt · mock:delega… · alt + up to parent +mock:delegate…t the parser › mock:delegate mock-model inspect the parser again long names @118 -mock-model · A parent sessio… › mock-model-alt · A child with a… › mock-model · A grandchild wh… · alt + up to parent +mock-model · A parent…e indeed › … › mock-model · A grandchild whose title is also very long here · alt + up to parent long names @78 -mock-model · A parent se… › … › mock-model · A grandchil… · alt + up to parent +A parent ses…itle indeed › … › A grandchild whose title is also very long here long names @40 -A par… › … › A gra… · alt + up to parent +A…d › … › A grandchild w…very 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 index 171e1703a..0e797ee7d 100644 --- 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 @@ -3,19 +3,19 @@ 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-permission:cargo tes… is waiting on you · cargo test --wor… · alt + down to jump +● Ship tree-row picker › mock:request-perm…test --workspace is waiting on you · cargo test --wor… · alt + down to jump child @78 -● Ship tree-row pi… › mock:request-per… is waiting on you · alt + down to jump +● Ship tre…w picker › mock:req…orkspace is waiting on you · alt + down to jump shared prefix @118 -● mock:delegate mock-mo… › mock:delegate mock-mo… is waiting on you · cargo test --wor… (+1 more) · alt + down to jump +● 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:delega… › mock:delega… is waiting on you (+1 more) · alt + down to jump +● 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-permission:cargo test… is waiting on you +● Ship tree-row picker › mock:request-perm…test --workspace is waiting on you From 4aae7d76b79a9c0457cd9c902dffe7efa8a97562 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 23:50:41 +0000 Subject: [PATCH 12/16] docs(tui): describe attach drafts, middle-cut names and the restarted host's view of finished children MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Nori](https://noriagentic.com) Co-Authored-By: Nori <contact@tilework.tech> --- docs/remote-control.md | 38 +++++++++++++++++++++++++---------- nori-rs/cli/src/host/docs.md | 16 +++++++++------ nori-rs/harness/docs.md | 13 +++++++----- nori-rs/nori-protocol/docs.md | 20 ++++++++++++++---- nori-rs/tui/docs.md | 28 +++++++++++++++++--------- 5 files changed, 80 insertions(+), 35 deletions(-) diff --git a/docs/remote-control.md b/docs/remote-control.md index e1748480e..5d2cf1f9a 100644 --- a/docs/remote-control.md +++ b/docs/remote-control.md @@ -420,10 +420,12 @@ the parent, the parent receives a notice that names both sessions readably: `<agent> · <child name> is waiting on you (delegated by <parent agent> · <parent name>). 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. A completed child's result is automatically queued as attributed +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 <agent> · <child name> · <outcome>` -(`done`, `failed`, `declined`, or `cancelled`), its second is +(`done`, `failed`, `declined`, or `cancelled`; the child name here is the +task's whole first line), its second is `Child session: <child id>`, 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 @@ -441,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 @@ -507,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 `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, everything else including starting, done, 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; piped output keeps full values without color and appends ` (parent <full id>)` to every row with a parent, including a child whose parent is no longer listed and so prints at top level. | +| `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 <full id>)` 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 <id>` | Open the named Nori conversation. | | `nori attach --host <URL> --token-file <path>` | Connect to an explicit managed endpoint using a private token file. | @@ -592,18 +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 <agent> <task>` 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, and +(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`. -Inside a delegated child (not a fork), the identity line reads as a breadcrumb -of agents and names from the top-level session down to the child, fitted to -the terminal width. 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`; `closed` means a session the user closed or shut down. An -attached parent shows a delivered result prompt as one -`› delegation result … · delivered to this session` line. +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 <agent> · <name> · <status> · 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/nori-rs/cli/src/host/docs.md b/nori-rs/cli/src/host/docs.md index 92f0ba724..1e3987f34 100644 --- a/nori-rs/cli/src/host/docs.md +++ b/nori-rs/cli/src/host/docs.md @@ -59,8 +59,10 @@ host ls / host stop ---------------+ SessionManager 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) and is cut with `…` at - grapheme boundaries. Status color applies on every row. Piped output + (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; @@ -71,8 +73,7 @@ host ls / host stop ---------------+ SessionManager 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, and truncation - cuts from the end of the title, so the guide is the last thing to go. Piped output appends + STATUS, and AGE columns, so nesting never shifts metadata. Piped output appends ` (parent <full parent ID>)` 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. @@ -83,7 +84,8 @@ host ls / host stop ---------------+ SessionManager | working | cyan | | ready | green | | failed | red | - | others (starting, done, closed) | dimmed | + | 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 @@ -106,7 +108,9 @@ host ls / host stop ---------------+ SessionManager 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/harness/docs.md b/nori-rs/harness/docs.md index 4683881d8..406cb932e 100644 --- a/nori-rs/harness/docs.md +++ b/nori-rs/harness/docs.md @@ -685,9 +685,11 @@ processes. 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` lives only in the in-memory registry: nothing in the transcript - records it, so a child reloaded from its transcript after the host restarts - reads `Closed`. + `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. @@ -818,11 +820,12 @@ remote /session/delegate ----------+ | `<agent> · <child name> is waiting on you (delegated by <parent agent> · <parent name>). 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`, else `this session`. + `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. Its text is `nori_protocol::delegation_result_prompt`: a readable first line naming the - child agent, child name, and outcome, then the child ID, then the result. + 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 diff --git a/nori-rs/nori-protocol/docs.md b/nori-rs/nori-protocol/docs.md index 23e333a6b..05b246a16 100644 --- a/nori-rs/nori-protocol/docs.md +++ b/nori-rs/nori-protocol/docs.md @@ -106,24 +106,36 @@ and `nori attach` must agree on. | Function | Produces | | --- | --- | -| `session_display_name` | First non-empty trimmed line of a task or title, cut to 40 characters with `…` | +| `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 <agent> · <child name> · <status word>`, then `Child session: <child id>`, then the result text. A declined delegation omits the `Child session:` line because its child never started | +| `delegation_result_prompt` | The prompt delivered to the parent: `[Nori delegation result] from <agent> · <child name> · <status word>` (the child name is the task's whole first line, else `UNTITLED_SESSION_NAME`), then `Child session: <child id>`, 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. Both -strings are a cross-crate contract. +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 diff --git a/nori-rs/tui/docs.md b/nori-rs/tui/docs.md index d074b0537..3bcc5bf9d 100644 --- a/nori-rs/tui/docs.md +++ b/nori-rs/tui/docs.md @@ -970,7 +970,8 @@ in the prompt still moves the cursor. **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, - starting, closed, and done muted (closed and done titles are muted too). + 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 @@ -1001,9 +1002,9 @@ handler and fits each line to one row, two cells narrower than the terminal: the top-level session, `<agent> · <name> › … › <agent> · <child> · <key> 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`: the title - in this TUI, else the replay journal title, else - `nori_protocol::UNTITLED_SESSION_NAME`; + `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 with an amber `●` (`<title> is waiting on you`, or `<parent> › <child>` for a delegated child), its request, `(+N more)` when others wait, and the @@ -1017,9 +1018,10 @@ Both path lines are built by [`session_path.rs`](src/session_path.rs), which | Builder | Fitting rules | | --- | --- | -| `breadcrumb_line(path, tail, width)` | Never drops the top-level session, the current one, or the tail. Sessions between them collapse to one `…` when the names would get fewer than 16 cells each; on very narrow terminals agent labels drop; spare cells go to longer names; a final clip guarantees the width | +| `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 | 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 @@ -1098,13 +1100,15 @@ notices, result prompts, and terminal text agree. The 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> · working`, plus `<transcript key> shows the brief` | +| 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>` | @@ -1128,9 +1132,15 @@ 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 <summary> · 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. +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 From 3c1e431eb9f1edb5d84791c96bf7c3b7b93fd8fb Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Sun, 15 Nov 2026 23:59:49 +0000 Subject: [PATCH 13/16] fix(tui): keep whole drafts and readable parent names when sessions switch - Attach parks the composer's full edit per session, so large pastes and images survive a jump, and text typed before choosing a session stays. - The last breadcrumb layout keeps other names readable while the current name gets the most room. - Middle cuts keep graphemes whole; a resumed session keeps its whole title. --- nori-rs/cli/src/host/table.rs | 2 +- nori-rs/nori-protocol/src/delegation.rs | 3 + nori-rs/tui-pty-e2e/tests/delegation.rs | 3 +- nori-rs/tui/src/app/session_overview.rs | 8 +- nori-rs/tui/src/app/session_resume.rs | 2 +- nori-rs/tui/src/attach/docs.md | 8 +- nori-rs/tui/src/attach/runtime.rs | 23 ++-- nori-rs/tui/src/attach/tests.rs | 108 +++++++++++------- .../tui/src/chatwidget/tests/delegation.rs | 2 +- .../tui/src/public_widgets/composer_input.rs | 13 ++- nori-rs/tui/src/session_path.rs | 72 +++++++++--- ...show_the_whole_path_and_fit_the_width.snap | 2 +- 12 files changed, 167 insertions(+), 79 deletions(-) diff --git a/nori-rs/cli/src/host/table.rs b/nori-rs/cli/src/host/table.rs index 8f6693b6f..6e6f951b7 100644 --- a/nori-rs/cli/src/host/table.rs +++ b/nori-rs/cli/src/host/table.rs @@ -509,7 +509,7 @@ mod tests { let rows = colored.lines().skip(1).collect::<Vec<_>>(); assert!(rows[0].contains("done"), "{colored:?}"); assert!( - !rows[0].contains("\u{1b}[2m"), + !rows[0].contains("\u{1b}[2mdone"), "done is not dimmed: {colored:?}" ); assert!( diff --git a/nori-rs/nori-protocol/src/delegation.rs b/nori-rs/nori-protocol/src/delegation.rs index 42f4b9df0..e9f9fff80 100644 --- a/nori-rs/nori-protocol/src/delegation.rs +++ b/nori-rs/nori-protocol/src/delegation.rs @@ -34,6 +34,9 @@ pub fn shorten_name(name: &str, limit: i32) -> String { 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(); diff --git a/nori-rs/tui-pty-e2e/tests/delegation.rs b/nori-rs/tui-pty-e2e/tests/delegation.rs index e430168ba..866d3e1f6 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -432,8 +432,7 @@ fn the_child_breadcrumb_fits_one_row_of_an_80_column_terminal() { assert!( breadcrumb .trim_end() - .ends_with("› mock:request-permission:write-child-file") - || breadcrumb.contains("write-child-file · alt + up to parent"), + .ends_with("› mock:request-permission:write-child-file"), "the current name stays whole; the key gives way first:\n{screen}" ); } diff --git a/nori-rs/tui/src/app/session_overview.rs b/nori-rs/tui/src/app/session_overview.rs index 95443b288..8d19e36f1 100644 --- a/nori-rs/tui/src/app/session_overview.rs +++ b/nori-rs/tui/src/app/session_overview.rs @@ -19,7 +19,7 @@ use crate::session_status::status_word; /// Longest title shown for a session that has no summary yet. const TITLE_CHARS: i32 = 60; /// For lines that fit names to the terminal width themselves. -const WHOLE_NAME: i32 = i32::MAX; +pub(super) const WHOLE_NAME: i32 = i32::MAX; fn cut(text: &str, limit: i32) -> String { nori_protocol::shorten_name(text, limit) @@ -125,7 +125,11 @@ impl App { /// 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> { + pub(super) fn session_title( + &self, + generation: SessionGeneration, + limit: i32, + ) -> Option<String> { let widget = self.widget_for(generation); self.session_previews .title(generation) 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/attach/docs.md b/nori-rs/tui/src/attach/docs.md index 0530ba8d6..3507a996c 100644 --- a/nori-rs/tui/src/attach/docs.md +++ b/nori-rs/tui/src/attach/docs.md @@ -109,9 +109,11 @@ Path: @/nori-rs/tui/src/attach 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 composer text with the session it - was typed in and restores the target's own draft, so text never follows the - user into another session. Drafts live only in this terminal's memory. + `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 diff --git a/nori-rs/tui/src/attach/runtime.rs b/nori-rs/tui/src/attach/runtime.rs index 436666b96..d76758059 100644 --- a/nori-rs/tui/src/attach/runtime.rs +++ b/nori-rs/tui/src/attach/runtime.rs @@ -28,8 +28,9 @@ 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, - /// Unsent text of each session not on screen, restored when it returns. - drafts: HashMap<String, String>, + /// The unsent edit of each session not on screen, restored when it + /// returns. + drafts: HashMap<String, crate::bottom_pane::ComposerDraft>, } impl Runtime { @@ -81,18 +82,16 @@ impl Runtime { } } - /// Put `id` on screen. The draft in the composer stays with the session - /// it was typed in, and `id`'s own draft comes back. + /// 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 self.state.selected.as_ref() != Some(&id) { - if let Some(previous) = self.state.selected.take() - && !self.composer.is_empty() - { - self.drafts.insert(previous, self.composer.text()); - } - self.composer.clear(); + 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.handle_paste(draft); + self.composer.restore_draft(draft); } } self.state.selected = Some(id); diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs index d8cfc1b05..ac6559974 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -669,11 +669,13 @@ fn long_names_keep_the_current_name_whole_before_the_parent_key() { .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") - || breadcrumb - .contains("› mock-model-alt · Verify every link in the generated changelog"), + breadcrumb.contains("Verify every link in the generated changelog · waiting on you"), "{rendered}" ); + assert!( + !breadcrumb.contains("alt+up"), + "the key gave way: {rendered}" + ); } #[test] @@ -1062,6 +1064,7 @@ fn alt_down_with_a_draft_jumps_and_the_draft_waits_in_the_parent() { 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")); @@ -1071,6 +1074,59 @@ fn alt_down_with_a_draft_jumps_and_the_draft_waits_in_the_parent() { 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] @@ -1148,47 +1204,22 @@ fn a_finished_child_ends_by_pointing_back_to_its_parent() { }) .unwrap(); let rendered = screen(&state); - let end = rendered - .lines() - .find(|line| line.contains("finished")) - .unwrap_or_else(|| panic!("end line missing:\n{rendered}")); - assert!(end.contains("alt+up"), "{rendered}"); + 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("finished"), "{closed}"); - assert!(!closed.contains("/new to start"), "{closed}"); -} - -#[test] -fn the_grandchild_name_stays_whole_at_80_columns() { - let mut state = AttachState { - connected: true, - selected: Some("grandchild-session".into()), - ..Default::default() - }; - state - .replace_sessions(json!({"sessions":[ - {"session_id":"root-session","agent":"mock-model","status":"ready","title":"mock:delegate mock-model mock:delegate mock-model mock:request-permission:x"}, - {"session_id":"child-session","agent":"mock-model","status":"working","title":"mock:delegate mock-model mock:request-permission:x","parent":"root-session","source":"session"}, - {"session_id":"grandchild-session","agent":"mock-model","status":"waiting_on_you","title":"mock:request-permission:x","parent":"child-session","source":"session"} - ]})) - .unwrap(); - state.list_open = false; - let rendered = screen_at(&state, 80); - assert!( - rendered.contains("mock:request-permission:x · waiting on you"), - "{rendered}" - ); - assert!(!rendered.contains("alt+up"), "{rendered}"); - let wide = screen_at(&state, 120); assert!( - wide.contains("mock:request-permission:x · waiting on you · alt+up parent"), - "{wide}" + 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] @@ -1232,9 +1263,8 @@ fn a_delivered_result_fits_one_row_at_80_columns() { .unwrap_or_else(|| panic!("{rendered}")); assert!(lines[at].contains("mock:request"), "{rendered}"); assert!(lines[at].contains("lexer-tokens · done"), "{rendered}"); - let next = lines.get(at + 1).copied().unwrap_or_default(); assert!( - !next.starts_with(" ") || next.trim().is_empty(), - "the line wraps onto a second row: {rendered}" + lines[at].trim_end().ends_with("lexer-tokens · done"), + "the whole line sits on one row: {rendered}" ); } diff --git a/nori-rs/tui/src/chatwidget/tests/delegation.rs b/nori-rs/tui/src/chatwidget/tests/delegation.rs index 1c4287d10..fc8e8ce90 100644 --- a/nori-rs/tui/src/chatwidget/tests/delegation.rs +++ b/nori-rs/tui/src/chatwidget/tests/delegation.rs @@ -321,7 +321,7 @@ fn a_delivered_result_fits_one_row_at_80_columns() { 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(78)); + 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(); } diff --git a/nori-rs/tui/src/public_widgets/composer_input.rs b/nori-rs/tui/src/public_widgets/composer_input.rs index 094ddac24..b7f38c1b3 100644 --- a/nori-rs/tui/src/public_widgets/composer_input.rs +++ b/nori-rs/tui/src/public_widgets/composer_input.rs @@ -55,9 +55,16 @@ impl ComposerInput { self.inner.is_empty() } - /// The current input text. - pub fn text(&self) -> String { - self.inner.current_text() + /// 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. diff --git a/nori-rs/tui/src/session_path.rs b/nori-rs/tui/src/session_path.rs index 16f80ff16..05678e66c 100644 --- a/nori-rs/tui/src/session_path.rs +++ b/nori-rs/tui/src/session_path.rs @@ -5,6 +5,7 @@ use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; +use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; /// One session on the way from a top-level session to the one on screen. @@ -45,23 +46,25 @@ pub(crate) fn fit_name(text: &str, cells: usize) -> String { return String::new(); } let room = cells - 1; + let graphemes: Vec<&str> = text.graphemes(true).collect(); let mut head = String::new(); - for ch in text.chars() { - if head.width() + ch.to_string().width() > room.div_ceil(2) { + for grapheme in &graphemes { + if head.width() + grapheme.width() > room.div_ceil(2) { break; } - head.push(ch); + head.push_str(grapheme); } - let mut tail: Vec<char> = Vec::new(); - for ch in text.chars().rev() { - let cells = ch.to_string().width(); - if head.width() + tail.iter().collect::<String>().width() + cells > room { + 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.push(ch); + tail_width += grapheme.width(); + tail.push(grapheme); } - let tail: String = tail.into_iter().rev().collect(); - format!("{}…{}", head.trim_end(), tail.trim_start()) + tail.reverse(); + format!("{}…{}", head.trim_end(), tail.concat().trim_start()) } /// Share `room` cells between names, so a short name leaves its unused cells @@ -140,10 +143,16 @@ pub(crate) fn breadcrumb_line( .map(|step| step.name.as_str()) .collect(); let room = width.saturating_sub(fixed); - let floor = if index == last { - MIN_NAME_CELLS - } else { + // 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 @@ -436,6 +445,41 @@ mod tests { 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] @@ -480,7 +524,7 @@ mod tests { let line = text(&breadcrumb_line(&long, "", KEY, width)); assert!(line.contains("A parent"), "@{width}: {line}"); assert!( - line.contains("› A gran") || line.contains("› mock-model · A gran"), + line.contains("A grandchild whose title is also very long here"), "@{width}: {line}" ); } 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 index ca7e158d8..3db2817fa 100644 --- 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 @@ -21,4 +21,4 @@ long names @78 A parent ses…itle indeed › … › A grandchild whose title is also very long here long names @40 -A…d › … › A grandchild w…very long here +A pa…eed › … › A grandchild…ry long here From 985a39b71c90344a7ef521f61ed399787ee9ff08 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Mon, 16 Nov 2026 01:42:32 +0000 Subject: [PATCH 14/16] fix(tui): keep long session names apart in lists and let requests answer over a draft Both session lists cut titles once, in the middle, at the column width, so names sharing a long prefix keep the ends that tell them apart. In nori attach, a request shown for the session on screen takes Enter and number keys even while the composer holds a draft, which stays put, as in the local TUI. The delegation card cuts the child's name to fit one row. --- nori-rs/Cargo.lock | 1 + nori-rs/tui-components/Cargo.toml | 1 + nori-rs/tui-components/src/lib.rs | 1 + nori-rs/tui-components/src/picker/mod.rs | 10 + nori-rs/tui-components/src/picker/render.rs | 13 +- .../tui-components/src/picker/tree_tests.rs | 50 +++++ nori-rs/tui-components/src/text.rs | 36 ++++ nori-rs/tui-pty-e2e/tests/delegation.rs | 52 +++++ nori-rs/tui/src/app/session_overview.rs | 27 ++- nori-rs/tui/src/attach/input.rs | 6 +- nori-rs/tui/src/attach/state.rs | 8 +- nori-rs/tui/src/attach/tests.rs | 194 ++++++++++++++++++ .../tui/src/bottom_pane/session_list_view.rs | 50 ++++- .../tui/src/chatwidget/tests/delegation.rs | 54 +++++ nori-rs/tui/src/delegation.rs | 36 ++-- nori-rs/tui/src/session_path.rs | 28 +-- 16 files changed, 507 insertions(+), 60 deletions(-) create mode 100644 nori-rs/tui-components/src/text.rs diff --git a/nori-rs/Cargo.lock b/nori-rs/Cargo.lock index a8cf58afe..84b3a454d 100644 --- a/nori-rs/Cargo.lock +++ b/nori-rs/Cargo.lock @@ -4031,6 +4031,7 @@ dependencies = [ "ratatui", "supports-color", "textwrap 0.16.2", + "unicode-segmentation", "unicode-width 0.2.1", ] 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/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 cd3ad6f84..a2b632515 100644 --- a/nori-rs/tui-components/src/picker/mod.rs +++ b/nori-rs/tui-components/src/picker/mod.rs @@ -34,6 +34,9 @@ pub struct PickerColumn { pub header: String, pub width: PickerColumnWidth, pub hide_below: Option<u16>, + /// 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 { @@ -47,6 +50,7 @@ impl PickerColumn { weight: 1, }, hide_below: None, + cut_middle: false, } } @@ -56,6 +60,7 @@ impl PickerColumn { header: header.into(), width: PickerColumnWidth::Fixed(width), hide_below: None, + cut_middle: false, } } @@ -64,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 diff --git a/nori-rs/tui-components/src/picker/render.rs b/nori-rs/tui-components/src/picker/render.rs index 4eb61f024..7edaf89e6 100644 --- a/nori-rs/tui-components/src/picker/render.rs +++ b/nori-rs/tui-components/src/picker/render.rs @@ -452,7 +452,12 @@ impl<K: Clone + Eq> Picker<'_, K> { }; 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) @@ -541,7 +546,11 @@ impl<K: Clone + Eq> 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_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<String> { let columns = [ @@ -193,3 +194,52 @@ fn a_badge_survives_when_a_long_title_is_cut() { "{screen}" ); } + +fn shared_prefix_picker() -> PickerState<String> { + 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..bbfe4d53b --- /dev/null +++ b/nori-rs/tui-components/src/text.rs @@ -0,0 +1,36 @@ +//! 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()) +} diff --git a/nori-rs/tui-pty-e2e/tests/delegation.rs b/nori-rs/tui-pty-e2e/tests/delegation.rs index 866d3e1f6..28f74effe 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -436,3 +436,55 @@ fn the_child_breadcrumb_fits_one_row_of_an_80_column_terminal() { "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)"), + 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/src/app/session_overview.rs b/nori-rs/tui/src/app/session_overview.rs index 8d19e36f1..6422df42c 100644 --- a/nori-rs/tui/src/app/session_overview.rs +++ b/nori-rs/tui/src/app/session_overview.rs @@ -123,23 +123,30 @@ impl App { rows } - /// The title a session is listed under: the agent's summary, else the - /// first prompt, cut to `limit` characters. - pub(super) 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 @@ -312,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}")); } diff --git a/nori-rs/tui/src/attach/input.rs b/nori-rs/tui/src/attach/input.rs index 01ec9d098..5dd5eb3b9 100644 --- a/nori-rs/tui/src/attach/input.rs +++ b/nori-rs/tui/src/attach/input.rs @@ -102,10 +102,12 @@ 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) { + // A request shown for the session on screen takes its keys even + // while the composer holds a draft; the draft stays put. + if !self.state.list_open && self.delegation_key(key) { return true; } - if self.composer.is_empty() && !self.state.list_open && self.permission_key(key) { + if !self.state.list_open && self.permission_key(key) { return true; } if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) { diff --git a/nori-rs/tui/src/attach/state.rs b/nori-rs/tui/src/attach/state.rs index 06ff7b180..1aebeed57 100644 --- a/nori-rs/tui/src/attach/state.rs +++ b/nori-rs/tui/src/attach/state.rs @@ -109,7 +109,13 @@ 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(), ) diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs index ac6559974..41a6bbdb7 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -1268,3 +1268,197 @@ fn a_delivered_result_fits_one_row_at_80_columns() { "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"); +} + +#[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}"); +} 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 68bb9c19d..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), ]; @@ -432,6 +434,44 @@ 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; diff --git a/nori-rs/tui/src/chatwidget/tests/delegation.rs b/nori-rs/tui/src/chatwidget/tests/delegation.rs index fc8e8ce90..af495a862 100644 --- a/nori-rs/tui/src/chatwidget/tests/delegation.rs +++ b/nori-rs/tui/src/chatwidget/tests/delegation.rs @@ -431,3 +431,57 @@ 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_card_fits_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}" + ); + let wide = lines_to_single_string(&card.display_lines(140)); + assert!( + wide.contains(task), + "the whole name shows when it fits:\n{wide}" + ); +} diff --git a/nori-rs/tui/src/delegation.rs b/nori-rs/tui/src/delegation.rs index 72a6a0a7d..3c9e8558d 100644 --- a/nori-rs/tui/src/delegation.rs +++ b/nori-rs/tui/src/delegation.rs @@ -73,14 +73,14 @@ fn status_span(status: DelegationStatus) -> Span<'static> { } /// The child as `agent · name`, the form every delegation surface uses. -fn child_spans(delegation: &Delegation) -> Vec<Span<'static>> { - vec![ - delegation.agent.clone().bold(), - " · ".dim(), - nori_protocol::delegation_child_name(delegation).into(), - ] +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. @@ -167,7 +167,17 @@ impl DelegationCell { Self { delegation, hints } } - fn header(&self) -> Line<'static> { + /// 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()).width(); + let room = usize::from(width).saturating_sub(fixed).max(MIN_CARD_NAME); + self.header_spans(crate::session_path::fit_name(&full_name, room)) + } + + fn header_spans(&self, name: String) -> Line<'static> { let delegation = &self.delegation; let mut spans = match delegation.status { DelegationStatus::AwaitingApproval | DelegationStatus::Running => { @@ -175,22 +185,22 @@ impl DelegationCell { "↳ ".dim(), format!("{} delegated to ", requester(delegation)).into(), ]; - spans.extend(child_spans(delegation)); + spans.extend(child_spans(delegation, name)); spans } DelegationStatus::Completed => { let mut spans = vec!["○ ".green(), "result from ".into()]; - spans.extend(child_spans(delegation)); + spans.extend(child_spans(delegation, name)); spans } DelegationStatus::Failed => { let mut spans = vec!["✕ ".red()]; - spans.extend(child_spans(delegation)); + spans.extend(child_spans(delegation, name)); spans } DelegationStatus::Declined | DelegationStatus::Cancelled => { let mut spans = vec!["✕ ".dim(), "delegation to ".dim()]; - spans.extend(child_spans(delegation)); + spans.extend(child_spans(delegation, name)); spans } }; @@ -276,14 +286,14 @@ impl DelegationCell { impl HistoryCell for DelegationCell { fn display_lines(&self, width: u16) -> Vec<Line<'static>> { - let mut lines = vec![self.header()]; + 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()]; + let mut lines = vec![self.header(width)]; let mut brief = self.delegation.task.lines(); lines.push(Line::from(vec![ " brief ".dim(), diff --git a/nori-rs/tui/src/session_path.rs b/nori-rs/tui/src/session_path.rs index 05678e66c..7e73895d8 100644 --- a/nori-rs/tui/src/session_path.rs +++ b/nori-rs/tui/src/session_path.rs @@ -5,7 +5,6 @@ use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; -use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; /// One session on the way from a top-level session to the one on screen. @@ -39,32 +38,7 @@ pub(crate) fn fit(text: &str, cells: usize) -> String { /// `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 { - 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()) + nori_tui_components::text::truncate_middle(text, cells) } /// Share `room` cells between names, so a short name leaves its unused cells From f58a3ef67b461c72c25b8ffae2447b9d456b1578 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Mon, 16 Nov 2026 01:43:57 +0000 Subject: [PATCH 15/16] docs(tui): describe middle-cut list titles and request keys that answer over a draft --- nori-rs/tui-components/docs.md | 8 ++++++++ nori-rs/tui/docs.md | 14 +++++++++++--- nori-rs/tui/src/attach/docs.md | 11 ++++++++++- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/nori-rs/tui-components/docs.md b/nori-rs/tui-components/docs.md index f96fd7ff6..a314bf043 100644 --- a/nori-rs/tui-components/docs.md +++ b/nori-rs/tui-components/docs.md @@ -176,6 +176,14 @@ consumer application 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/docs.md b/nori-rs/tui/docs.md index 3bcc5bf9d..78aa0e469 100644 --- a/nori-rs/tui/docs.md +++ b/nori-rs/tui/docs.md @@ -940,7 +940,11 @@ in the prompt still moves the cursor. 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. A user-origin + 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 @@ -1021,7 +1025,7 @@ Both path lines are built by [`session_path.rs`](src/session_path.rs), which | `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 | +| `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 @@ -1113,7 +1117,11 @@ child ID. | 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 requester is `you` for origin `user` and the parent agent for origin +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. diff --git a/nori-rs/tui/src/attach/docs.md b/nori-rs/tui/src/attach/docs.md index 3507a996c..ed91424de 100644 --- a/nori-rs/tui/src/attach/docs.md +++ b/nori-rs/tui/src/attach/docs.md @@ -83,7 +83,9 @@ Path: @/nori-rs/tui/src/attach 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`. The list ignores the host's `depth` field and + `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 and presentation](../delegation.rs): @@ -98,6 +100,13 @@ Path: @/nori-rs/tui/src/attach 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 request shown for the session on screen (a permission prompt or a + delegation approval) takes its keys while the session list is closed, even + when the composer holds a draft: Enter, digits, and Up/Down for permission + choices; 1, 2, and Enter for a delegation approval. The draft stays + untouched, matching the local TUI where the approval overlay takes keys and + the composer keeps its text. Other keys still edit the composer. A request + in a session that is not on screen does not capture keys. - Child permissions stay in the child's conversation. The configured `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 From 54fcdeb3b5f0bca9f0f7abb1bd7cf29bf93cd4d6 Mon Sep 17 00:00:00 2001 From: Nori <contact@tilework.tech> Date: Mon, 16 Nov 2026 01:50:23 +0000 Subject: [PATCH 16/16] fix(tui): hold the keyboard for a request shown in nori attach A permission or delegation approval on the session on screen now takes every key but scrolling and Ctrl+C, as the local approval overlay does, so text typed into a draft can no longer answer it. Only a plain Enter answers. A card's failure reason wraps instead of shrinking the child's name. --- nori-rs/tui-components/src/text.rs | 38 +++++++++++++++++++ nori-rs/tui-pty-e2e/tests/delegation.rs | 7 +++- nori-rs/tui/src/attach/docs.md | 13 +++---- nori-rs/tui/src/attach/input.rs | 37 ++++++++++++++---- nori-rs/tui/src/attach/tests.rs | 34 +++++++++++++++++ .../tui/src/chatwidget/tests/delegation.rs | 31 ++++++++++++++- nori-rs/tui/src/delegation.rs | 19 ++++++---- 7 files changed, 155 insertions(+), 24 deletions(-) diff --git a/nori-rs/tui-components/src/text.rs b/nori-rs/tui-components/src/text.rs index bbfe4d53b..93a0db8b2 100644 --- a/nori-rs/tui-components/src/text.rs +++ b/nori-rs/tui-components/src/text.rs @@ -34,3 +34,41 @@ pub fn truncate_middle(text: &str, cells: usize) -> String { 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/tests/delegation.rs b/nori-rs/tui-pty-e2e/tests/delegation.rs index 28f74effe..3d2f50977 100644 --- a/nori-rs/tui-pty-e2e/tests/delegation.rs +++ b/nori-rs/tui-pty-e2e/tests/delegation.rs @@ -460,7 +460,12 @@ fn the_session_list_keeps_names_with_a_shared_prefix_apart_at_80_columns() { session.send_key(Key::Alt('s')).unwrap(); session .wait_for( - |screen| screen.contains("Sessions 2") && screen.contains("(current)"), + |screen| { + screen.contains("Sessions 2") + && screen.contains("(current)") + && screen.contains("parent side") + && screen.contains("permission:z") + }, TIMEOUT, ) .unwrap(); diff --git a/nori-rs/tui/src/attach/docs.md b/nori-rs/tui/src/attach/docs.md index ed91424de..973fad465 100644 --- a/nori-rs/tui/src/attach/docs.md +++ b/nori-rs/tui/src/attach/docs.md @@ -100,13 +100,12 @@ Path: @/nori-rs/tui/src/attach 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 request shown for the session on screen (a permission prompt or a - delegation approval) takes its keys while the session list is closed, even - when the composer holds a draft: Enter, digits, and Up/Down for permission - choices; 1, 2, and Enter for a delegation approval. The draft stays - untouched, matching the local TUI where the approval overlay takes keys and - the composer keeps its text. Other keys still edit the composer. A request - in a session that is not on screen does not capture keys. +- 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, even with a draft in the composer, as in the local TUI. With nothing waiting in diff --git a/nori-rs/tui/src/attach/input.rs b/nori-rs/tui/src/attach/input.rs index 5dd5eb3b9..90e6cb81b 100644 --- a/nori-rs/tui/src/attach/input.rs +++ b/nori-rs/tui/src/attach/input.rs @@ -102,13 +102,19 @@ impl Runtime { if self.state.list_open && self.picker_key(key) { return true; } - // A request shown for the session on screen takes its keys even - // while the composer holds a draft; the draft stays put. - if !self.state.list_open && self.delegation_key(key) { - return true; - } - if !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() { @@ -160,6 +166,21 @@ impl Runtime { 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 { let Some(id) = self.state.selected.clone() else { return false; @@ -236,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/tests.rs b/nori-rs/tui/src/attach/tests.rs index 41a6bbdb7..e8ab3971f 100644 --- a/nori-rs/tui/src/attach/tests.rs +++ b/nori-rs/tui/src/attach/tests.rs @@ -1442,6 +1442,11 @@ fn enter_approves_a_pending_delegation_and_keeps_the_draft() { 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] @@ -1461,4 +1466,33 @@ fn a_request_in_another_session_leaves_enter_to_the_draft() { 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/chatwidget/tests/delegation.rs b/nori-rs/tui/src/chatwidget/tests/delegation.rs index af495a862..73ece48a5 100644 --- a/nori-rs/tui/src/chatwidget/tests/delegation.rs +++ b/nori-rs/tui/src/chatwidget/tests/delegation.rs @@ -457,7 +457,7 @@ fn a_shown_delegation_request_takes_enter_from_the_draft_and_keeps_it() { } #[test] -fn a_running_card_fits_one_row_at_80_columns() { +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"; @@ -479,9 +479,38 @@ fn a_running_card_fits_one_row_at_80_columns() { 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/delegation.rs b/nori-rs/tui/src/delegation.rs index 3c9e8558d..1bcdd0923 100644 --- a/nori-rs/tui/src/delegation.rs +++ b/nori-rs/tui/src/delegation.rs @@ -172,12 +172,15 @@ impl DelegationCell { 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()).width(); + 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)) + self.header_spans(crate::session_path::fit_name(&full_name, room), true) } - fn header_spans(&self, name: String) -> Line<'static> { + /// 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 => { @@ -210,10 +213,12 @@ impl DelegationCell { spans.push(" by you".dim()); } let reason = first_line(delegation.result.as_deref().unwrap_or_default()); - if matches!( - delegation.status, - DelegationStatus::Failed | DelegationStatus::Cancelled - ) && !reason.is_empty() + if with_reason + && matches!( + delegation.status, + DelegationStatus::Failed | DelegationStatus::Cancelled + ) + && !reason.is_empty() { spans.push(format!(" · {reason}").dim()); }