diff --git a/crates/dim-cli/src/model/view.rs b/crates/dim-cli/src/model/view.rs index 2f587af0af..1afa066d15 100644 --- a/crates/dim-cli/src/model/view.rs +++ b/crates/dim-cli/src/model/view.rs @@ -477,6 +477,12 @@ pub struct ViewSnapshot { pub projection_id: u64, /// The shown line's history has loaded: its transcript can be laid out. pub history_complete: bool, + /// The shown line's first window could not be read, with the reason; the + /// line draws it instead of a transcript until the line is opened again. + /// `None` while the window loads, after it loads, and when only a later + /// read (an inventory refresh or an `/earlier` page) failed; + /// `history_complete` separates the first case from the other two. + pub window_error: Option, /// Whether history older than the loaded window exists, and whether an /// earlier read is in flight; `/earlier`, PageUp at the drawn top and the /// load-more row act on it. diff --git a/crates/dim-cli/src/projection.rs b/crates/dim-cli/src/projection.rs index ce99ab9872..0d6cb46df9 100644 --- a/crates/dim-cli/src/projection.rs +++ b/crates/dim-cli/src/projection.rs @@ -44,6 +44,10 @@ pub struct Projection { owner: String, /// The lines of the Session, as `main` recorded them (design §14). lines: Vec, + /// Lines whose creation failed. The fact outruns the line's row: a + /// `branch/create-failed` the parent's page has not projected a + /// `branch/create` for is still terminal. + creation_failed: HashSet, /// Each line's own user messages, by input id and submission sequence, /// to count where a line was cut (timeline UI §6); a withdrawn message /// stays, and `withdrawals` decides which cuts still count it. @@ -167,7 +171,11 @@ impl Projection { id: data.branch.clone(), parent: Some(parent.to_owned()), purpose, - state: LineState::Waiting, + state: if self.creation_failed.contains(&data.branch) { + LineState::CreationFailed + } else { + LineState::Waiting + }, running: None, branch_point: Some(sequence), cut, @@ -179,6 +187,7 @@ impl Projection { BranchCreateFailedData::Failed { branch, .. } | BranchCreateFailedData::Cancelled { branch, .. } => branch, }; + self.creation_failed.insert(branch.clone()); if let Some(line) = self.lines.iter_mut().find(|line| line.id == *branch) { line.state = LineState::CreationFailed; } @@ -1474,6 +1483,12 @@ impl Projection { &self.lines } + /// Whether `branch`'s creation failed, whether or not its row is + /// projected yet: the line is terminal from the fact. + pub fn creation_failed(&self, branch: &str) -> bool { + self.creation_failed.contains(branch) + } + pub fn approvals(&self) -> Vec { self.approvals.clone() } diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index 1dce5ad70c..3521fdcc5e 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -5413,6 +5413,10 @@ impl Worker { self.send(Update::Notice(format!("No line {line} in this session"))); return; } + if line != ROOT_BRANCH_ID && self.projection.creation_failed(&line) { + self.send(Update::Notice(format!("Line creation failed: {line}"))); + return; + } if line != ROOT_BRANCH_ID { self.line_projection(&line); } @@ -5507,10 +5511,9 @@ impl Worker { } snapshot.session_id = self.session_id.clone(); snapshot.projection_id = self.projection_id; - snapshot.history_complete = self - .task_history - .get(&self.focus) - .is_some_and(|branch| branch.window_complete); + let shown = self.task_history.get(&self.focus); + snapshot.history_complete = shown.is_some_and(|branch| branch.window_complete); + snapshot.window_error = shown.and_then(|branch| branch.window_error.clone()); snapshot.earlier = self.earlier_view(); snapshot.task_history_loading = self .task_history diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index f2dffb6ea4..d96faa73c1 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -15,6 +15,11 @@ pub(super) struct BranchHistory { pub error: Option, live: Vec, pub(super) window_complete: bool, + /// The first window's failed read; the line shows it instead of a + /// transcript until the line is opened again. A later read (an inventory + /// refresh or an `/earlier` page) records `error` and leaves the loaded + /// window in place. + pub(super) window_error: Option, inventory_index: usize, inventory_cursor: Option, goal_stale: bool, @@ -122,18 +127,22 @@ impl Worker { } pub(super) fn line_projection(&mut self, branch_id: &str) -> &mut LineProjection { + let creation_failed = self.projection.creation_failed(branch_id); let history = self .task_history .get_mut(branch_id) .expect("discovered line"); history.seen_reply = history.latest_reply; - if !self.lines.contains_key(branch_id) - && (history.window.through.is_some() || history.done || history.error.is_some()) + if !creation_failed + && ((!self.lines.contains_key(branch_id) + && (history.window.through.is_some() || history.done || history.error.is_some())) + || history.window_error.is_some()) { history.window = Default::default(); history.done = false; history.error = None; history.window_complete = false; + history.window_error = None; history.inventory_index = 0; history.inventory_cursor = None; history.earlier = EarlierRead::None; @@ -186,6 +195,7 @@ impl Worker { history.error = None; history.live.clear(); history.window_complete = false; + history.window_error = None; self.task_history_queue.retain(|id| id != branch); if let Some(request) = &mut self.task_history_request && request.branch_id == *branch @@ -195,6 +205,31 @@ impl Worker { if newly_failed { self.send(Update::Notice(format!("Branch {branch}: {error}"))); } + // Terminal for the directory as soon as the fact arrives; the + // transcript still waits for the window that recorded it. + let first_terminal = !self.projection.creation_failed(branch); + self.projection.apply(branch, event); + if self.focus == *branch { + let parent = self + .projection + .line_views() + .iter() + .find(|line| line.id == *branch) + .and_then(|line| line.parent.clone()) + .filter(|parent| { + parent.as_str() == DEFAULT_BRANCH_ID + || self.task_history.contains_key(parent) + }) + .unwrap_or_else(|| DEFAULT_BRANCH_ID.into()); + if parent != DEFAULT_BRANCH_ID { + self.line_projection(&parent); + } + self.focus = parent; + self.changed(); + } else if first_terminal { + // `/lines` draws the directory from published snapshots. + self.changed(); + } } _ => {} } @@ -235,6 +270,7 @@ impl Worker { pub(super) fn retry_task_history(&mut self) { for (id, history) in &mut self.task_history { if history.error.take().is_some() { + history.window_error = None; if history.earlier == EarlierRead::Failed { history.earlier = EarlierRead::Reading; } @@ -259,7 +295,6 @@ impl Worker { return; } history.earlier = EarlierRead::Reading; - history.window_complete = false; history.error = None; self.task_history_queue.push_back(line.to_owned()); } @@ -368,6 +403,8 @@ impl Worker { "This daemon cannot read a bounded transcript window; update the daemon".into(), ); } + let earlier_reading = self.task_history[&branch_id].earlier == EarlierRead::Reading; + let window_read = earlier_reading || !self.task_history[&branch_id].window_complete; let (stage, method, params) = if branch_id != self.default_branch && !self.lines.contains_key(&branch_id) && !self.task_history[&branch_id].window_complete @@ -377,7 +414,7 @@ impl Worker { "session.turn.get", json!({"sessionId":self.session_id,"branchId":branch_id}), ) - } else if self.task_history[&branch_id].window_complete { + } else if !window_read { for required in ["session.input.pending", "session.turn.get"] { if !self.task_history[&branch_id].ended && !self.methods.contains(required) { self.fail_inventory( @@ -455,8 +492,13 @@ impl Worker { }) } Err(error) => { - let history = self.task_history.get_mut(&branch_id).unwrap(); - history.error = Some(error.to_string()); + match stage { + ReadStage::History => self.fail_history(&branch_id, error.to_string()), + _ => { + self.task_history.get_mut(&branch_id).unwrap().error = + Some(error.to_string()); + } + } self.changed(); } } @@ -577,14 +619,12 @@ impl Worker { .and_then(|error| error.data.as_ref()) .and_then(|data| data["appError"].as_str()) .map(str::to_owned); + let fatal = + request.branch_id == self.default_branch && !self.task_history[&request.branch_id].done; let display = self .client .supports(&["session.history.display", "session.history.detail"]); let transcript = self.client.offers("session.history.display.transcript"); - let history = self - .task_history - .get_mut(&request.branch_id) - .expect("current history"); let mut at_start = false; let result = result.map_err(|error| error.to_string()).and_then(|value| { let page = if display { @@ -596,28 +636,35 @@ impl Worker { serde_json::from_value(value) .map_err(|error| format!("Invalid history reply: {error}"))? }; - history.window.push(page).map_err(|error| error.to_string()) + self.task_history + .get_mut(&request.branch_id) + .expect("current history") + .window + .push(page) + .map_err(|error| error.to_string()) }); let window_ready = matches!(result, Ok(true)); let mut missing_prefix = false; match result { Err(error) => { - history.error = Some(error.clone()); - if history.earlier == EarlierRead::Reading { - history.earlier = EarlierRead::Failed; + if fatal { + return Err(format!("Main branch history: {error}").into()); } - let fatal = request.branch_id == self.default_branch && !history.done; + self.fail_history(&request.branch_id, error.clone()); let report = crate::report::Captured::observed( crate::report::Operation::SessionRead, code.as_deref(), format!("Could not read conversation state: {error}"), ); - if !self.reportable(report, true) && fatal { - return Err(format!("Main branch history: {error}").into()); - } + self.reportable(report, true); } Ok(false) => self.task_history_queue.push_back(request.branch_id.clone()), Ok(true) => { + let history = self + .task_history + .get_mut(&request.branch_id) + .expect("current history"); + history.window_error = None; let events = history.window.take(); missing_prefix = history.window.dropped_pages() || history.window.before.is_some() && !at_start; @@ -696,6 +743,19 @@ impl Worker { Ok(()) } + /// Records a failed history read. A first window that never loaded is a + /// window failure; a failed older page leaves the loaded window in place + /// and returns `/earlier` to its unread state. + fn fail_history(&mut self, branch: &str, error: String) { + let history = self.task_history.get_mut(branch).expect("a line's history"); + history.error = Some(error.clone()); + if history.earlier == EarlierRead::Reading { + history.earlier = EarlierRead::Failed; + } else if !history.done && !history.window_complete { + history.window_error = Some(error); + } + } + fn fail_inventory(&mut self, branch: &str, error: String) { let history = self.task_history.get_mut(branch).unwrap(); history.error = Some(error); @@ -891,6 +951,7 @@ impl Worker { mod tests { use super::*; use crate::client::Message; + use crate::model::view::ViewSnapshot; /// One `step/text` event, as the daemon sends it on the wire and in a page. fn text(sequence: u64, request: &str, delta: &str) -> serde_json::Value { @@ -988,6 +1049,84 @@ mod tests { .unwrap(); } + /// A `branch/create-failed` event for `branch`, as the daemon sends it. + fn create_failed(sequence: u64, branch: &str) -> Event { + serde_json::from_value(create_failed_page(sequence, branch)).expect("a create-failed event") + } + + /// The wire form of [`create_failed`], for a page that records it. + fn create_failed_page(sequence: u64, branch: &str) -> serde_json::Value { + json!({ + "id": format!("create-failed-{sequence}"), + "sequence": sequence, + "create_at": 2000, + "type": "branch", + "name": "create-failed", + "data": { + "status": "failed", "branch": branch, + "createEvent": sequence - 1, "error": "creation refused" + } + }) + } + + /// A client whose daemon answered hello and then hung up: the next request + /// fails where it is written, before any reply exists. + async fn hung_up_client() -> Client { + use std::os::unix::fs::PermissionsExt; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + + let home = tempfile::tempdir().unwrap(); + let endpoint = home.path().join("daemon.sock"); + let listener = tokio::net::UnixListener::bind(&endpoint).unwrap(); + std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o600)).unwrap(); + let (hung_up, wait) = tokio::sync::oneshot::channel(); + tokio::spawn(async move { + let _home = home; + let Ok((stream, _)) = listener.accept().await else { + return; + }; + let mut reader = BufReader::new(stream); + let mut line = String::new(); + if reader.read_line(&mut line).await.unwrap_or(0) == 0 { + return; + } + let Ok(request) = serde_json::from_str::(&line) else { + return; + }; + let mut socket = reader.into_inner(); + let reply = json!({"jsonrpc":"2.0","id":request["id"],"result":{ + "instanceId":"hung-up-test","serverVersion":"test","protocolVersion":4, + "features":["session.create","session.history","session.history.latestTurn"], + "daemonProfile":{"kind":"product"} + }}); + if socket + .write_all(format!("{reply}\n").as_bytes()) + .await + .is_err() + { + return; + } + let _ = socket.shutdown().await; + drop(socket); + let _ = hung_up.send(()); + }); + let client = Client::connect(&dim_client::ConnectionConfig { + endpoint, + server: dim_client::Server { + program: std::env::current_exe().unwrap(), + embedded: false, + }, + profile: None, + client_kind: "cli", + client_name: "dim-cli-test", + protocol_version: 4, + }) + .await + .unwrap(); + wait.await.unwrap(); + client + } + /// A branch whose earlier read failed reports `Unread` and reads again on /// the next press. A failure that kept the read recorded as in flight makes /// `earlier_view` report `Reading` with nothing sent, and `earlier` returns @@ -1236,6 +1375,1001 @@ mod tests { ); } + /// A line whose first window read failed is not left waiting: opening the + /// line again in `/lines` starts its window over, and the page that lands + /// draws the conversation. + #[tokio::test] + async fn a_failed_line_window_reads_again_when_the_line_is_opened() { + let (mut worker, mut receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.discover_branch("b-7c"); + worker + .command(crate::model::session::Command::FocusLine("b-7c".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + fail(&mut worker, "the line's window").await; + assert!( + worker.lines["b-7c"].projection.rows().is_empty(), + "a failed window has drawn nothing" + ); + worker.publish(); + let snapshot = published(&mut receiver); + assert!( + snapshot + .window_error + .as_deref() + .is_some_and(|error| error.starts_with("the daemon dropped the read")), + "the failed window is published apart from a loading one: {:?}", + snapshot.window_error + ); + assert!(!snapshot.history_complete, "the window did not load"); + + worker + .command(crate::model::session::Command::TaskHistory { + projection_id: worker.projection_id, + }) + .await + .unwrap(); + worker.publish(); + let snapshot = published(&mut receiver); + assert!( + snapshot.window_error.is_none(), + "a retry is loading again, not still failed" + ); + worker.poll_task_history().await.unwrap(); + fail(&mut worker, "the retried window").await; + worker.publish(); + let snapshot = published(&mut receiver); + assert!( + snapshot.window_error.is_some(), + "the retried window failed again" + ); + worker.task_history_queue.clear(); + + worker + .command(crate::model::session::Command::FocusLine("b-7c".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + assert!( + worker.task_history_request.is_some(), + "opening the line again reads its window" + ); + worker.task_history.get_mut("b-7c").unwrap().ended = true; + answer( + &mut worker, + json!({"events":[text(300, "r-answer", "the answer")], "through": 300, "nextBefore": 300, "nextAfter": 300}), + ) + .await; + worker.poll_task_history().await.unwrap(); + + let rows = worker.lines["b-7c"].projection.rows(); + assert_eq!(rows.len(), 1, "the page drew the line's conversation"); + assert_eq!(rows[0].text, "the answer"); + assert!(worker.task_history["b-7c"].done, "the read window finished"); + worker.publish(); + let snapshot = published(&mut receiver); + assert!( + snapshot.window_error.is_none(), + "the read page cleared the failure" + ); + assert!(snapshot.history_complete, "the window loaded"); + assert_eq!(snapshot.rows.len(), 1); + } + + /// A failure after the window loaded belongs to that read: an inventory + /// refresh or an `/earlier` page that fails leaves the loaded transcript + /// drawn and the window complete. + #[tokio::test] + async fn late_inventory_and_earlier_failures_keep_the_loaded_line() { + let (mut worker, mut receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.discover_branch("b-7c"); + worker + .command(crate::model::session::Command::FocusLine("b-7c".into())) + .await + .unwrap(); + { + let history = worker.task_history.get_mut("b-7c").unwrap(); + history.done = true; + history.window_complete = true; + history.window.through = Some(300); + history.window.before = Some(200); + } + worker.apply("b-7c", event(300, "r-answer", "the loaded answer")); + + worker.task_history_queue.push_back("b-7c".into()); + worker.poll_task_history().await.unwrap(); + assert!( + worker.task_history["b-7c"].error.is_some(), + "the inventory read failed" + ); + let rows = worker.lines["b-7c"].projection.rows(); + assert_eq!(rows.len(), 1, "the inventory failure drew over nothing"); + assert_eq!(rows[0].text, "the loaded answer"); + worker.publish(); + let snapshot = published(&mut receiver); + assert!( + snapshot.history_complete, + "the loaded window stays complete" + ); + assert_eq!(snapshot.rows.len(), 1, "the loaded row stays drawn"); + + worker.earlier("b-7c"); + worker.poll_task_history().await.unwrap(); + fail(&mut worker, "the earlier page").await; + assert_eq!( + worker.lines["b-7c"].projection.rows().len(), + 1, + "the failed older page drew over the loaded transcript" + ); + assert_eq!(worker.earlier_view(), Earlier::Unread); + worker.publish(); + let snapshot = published(&mut receiver); + assert!( + snapshot.history_complete, + "a failed older page leaves the window complete" + ); + assert_eq!(snapshot.rows.len(), 1, "the loaded row stays drawn"); + } + + /// A request that fails on the transport, before any reply exists, lands a + /// first window in its failed state: the line shows the failure instead of + /// staying blank and nothing reads it again on its own. + #[tokio::test] + async fn a_failed_window_send_lands_the_line_in_the_error_state() { + let (mut worker, mut receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.focus = "main".into(); + worker.discover_branch("main"); + worker.client = hung_up_client().await; + + worker.poll_task_history().await.unwrap(); + + let history = &worker.task_history["main"]; + assert!( + history.window_error.is_some(), + "a window that could not be sent is a failed window: {:?}", + history.error + ); + assert!(!history.window_complete, "the window did not read"); + assert!( + worker.task_history_request.is_none(), + "no read is in flight" + ); + assert!( + !worker.task_history_queue.iter().any(|id| id == "main"), + "the failed window is not read again on its own" + ); + + worker.publish(); + let snapshot = published(&mut receiver); + assert!( + snapshot.window_error.is_some(), + "the failed window is published, not left loading" + ); + assert!(!snapshot.history_complete, "the window did not load"); + } + + /// A first window that failed is not kept as the line's failure once its + /// creation fails: the creation settles the line and `/tasks` no longer + /// lists the read error, so a stale read failure would be all the line + /// still showed. + #[tokio::test] + async fn a_create_failure_clears_a_failed_window() { + let (mut worker, mut receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.discover_branch("b-7c"); + worker + .command(crate::model::session::Command::FocusLine("b-7c".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + fail(&mut worker, "the line's window").await; + assert!(worker.task_history["b-7c"].window_error.is_some()); + + worker.task_event("b-7c", create_failed(400, "b-7c")); + + let history = &worker.task_history["b-7c"]; + assert!(history.done, "the failed creation settled the line"); + assert!( + history.error.is_none(), + "the tasks panel no longer lists it" + ); + assert!( + history.window_error.is_none(), + "the line does not keep the read failure of a window it will never read" + ); + assert!( + !history.window_complete, + "the failed creation read no window" + ); + worker.publish(); + let snapshot = published(&mut receiver); + assert!( + snapshot.window_error.is_none(), + "the settled line publishes no read failure" + ); + } + + /// A creation that fails while the line's first window is still loading + /// leaves no request that could settle it. The line is terminal, so the + /// interface shows the line it was cut from, and `/lines` cannot show it + /// again. + #[tokio::test] + async fn a_create_failure_before_the_first_window_moves_to_the_parent() { + let (mut worker, mut receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.focus = "main".into(); + worker.discover_branch("b-7c"); + worker.discover_branch("main"); + { + let history = worker.task_history.get_mut("main").unwrap(); + history.done = true; + history.window_complete = true; + history.window.through = Some(1); + } + let create: Event = serde_json::from_value(json!({ + "id": "create", "sequence": 1, "create_at": 1000, "type": "branch", "name": "create", + "data": { + "at": {"kind": "sequence", "sequence": 0}, "branch": "b-7c", "prompt": "Check the parser", + "source": {"kind": "host", "operation_id": "op"} + } + })) + .expect("a branch create event"); + worker.discover_task_branches(&create); + worker.apply("main", create); + worker + .command(crate::model::session::Command::FocusLine("b-7c".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + assert_eq!( + worker + .task_history_request + .as_ref() + .map(|read| read.branch_id.as_str()), + Some("b-7c"), + "the line's first window is in flight" + ); + + worker.task_event("main", create_failed(400, "b-7c")); + + assert_eq!( + worker.focus, "main", + "a line whose creation failed is not left loading" + ); + let history = &worker.task_history["b-7c"]; + assert!(history.done, "the failed creation settled the line"); + assert!( + !history.window_complete, + "the failed creation read no window" + ); + assert!( + history.window_error.is_none(), + "there is no first-window failure to show" + ); + if let Some(read) = &worker.task_history_request { + assert!(!read.current, "the failed line's read is no longer current"); + } + assert!( + !worker.task_history_queue.contains(&"b-7c".to_owned()), + "the failed line is not read again on its own" + ); + + worker + .command(crate::model::session::Command::FocusLine("b-7c".into())) + .await + .unwrap(); + assert_eq!( + worker.focus, "main", + "the terminal line cannot be shown again" + ); + let notices: Vec = receiver + .try_iter() + .filter_map(|update| match update { + Update::Notice(text) => Some(text), + _ => None, + }) + .collect(); + assert!( + notices + .iter() + .any(|notice| notice == "Line creation failed: b-7c"), + "the refusal names the failed creation: {notices:?}" + ); + + worker.publish(); + let snapshot = published(&mut receiver); + assert_eq!(snapshot.focus, "main", "the shown line survives"); + assert!(snapshot.window_error.is_none()); + assert!(snapshot.history_complete, "the surviving line is settled"); + } + + /// A creation that fails while the line's first window is still loading + /// returns to the line it was cut from when the directory knows that + /// line, not to `main`: the parent's window starts over and is read again. + #[tokio::test] + async fn a_create_failure_returns_to_a_parent_the_directory_knows() { + let (mut worker, mut receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.focus = "main".into(); + worker.discover_branch("b-7c"); + { + let history = worker.task_history.get_mut("b-7c").unwrap(); + history.done = true; + history.window_complete = true; + history.window.through = Some(2); + } + worker.task_history_queue.clear(); + let create: Event = serde_json::from_value(json!({ + "id": "create-child", "sequence": 2, "create_at": 1000, "type": "branch", "name": "create", + "data": { + "at": {"kind": "sequence", "sequence": 1}, "branch": "b-7d", "prompt": "Narrow the parser", + "source": {"kind": "host", "operation_id": "op"} + } + })) + .expect("a branch create event"); + worker.apply("b-7c", create); + assert!( + worker + .projection + .line_views() + .iter() + .any(|line| line.id == "b-7d" && line.parent.as_deref() == Some("b-7c")), + "the directory knows the line it was cut from" + ); + assert!( + !worker.lines.contains_key("b-7c"), + "the parent's window is not open in the view" + ); + worker + .command(crate::model::session::Command::FocusLine("b-7d".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + assert_eq!( + worker + .task_history_request + .as_ref() + .map(|read| read.branch_id.as_str()), + Some("b-7d"), + "the line's first window is in flight" + ); + + worker.task_event("b-7c", create_failed(400, "b-7d")); + + assert_eq!( + worker.focus, "b-7c", + "a line whose creation failed returns to the line it was cut from" + ); + let parent = &worker.task_history["b-7c"]; + assert_eq!( + parent.window.through, None, + "the returned-to window starts over" + ); + assert!( + !parent.window_complete, + "the returned-to window is armed for a new read" + ); + assert!( + worker.task_history_queue.contains(&"b-7c".to_owned()), + "the returned-to line is queued" + ); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "the failed line is not read again on its own" + ); + + fail(&mut worker, "the failed line's first window").await; + worker.poll_task_history().await.unwrap(); + assert_eq!( + worker + .task_history_request + .as_ref() + .map(|read| read.branch_id.as_str()), + Some("b-7c"), + "the returned-to line reads its window" + ); + worker.task_history.get_mut("b-7c").unwrap().ended = true; + answer( + &mut worker, + json!({"events":[text(300, "r-parent", "the parent's answer")], "through": 300, "nextBefore": 300, "nextAfter": 300}), + ) + .await; + worker.poll_task_history().await.unwrap(); + + assert_eq!( + worker.task_history["b-7c"].window.through, + Some(300), + "the returned-to window loaded its page" + ); + assert!( + worker.task_history["b-7c"].done, + "the returned-to window finished" + ); + let rows = worker.lines["b-7c"].projection.rows(); + assert_eq!(rows.len(), 1, "the page drew the parent's conversation"); + assert_eq!(rows[0].text, "the parent's answer"); + + worker + .command(crate::model::session::Command::FocusLine("b-7d".into())) + .await + .unwrap(); + assert_eq!( + worker.focus, "b-7c", + "the terminal line cannot be shown again" + ); + let notices: Vec = receiver + .try_iter() + .filter_map(|update| match update { + Update::Notice(text) => Some(text), + _ => None, + }) + .collect(); + assert!( + notices + .iter() + .any(|notice| notice == "Line creation failed: b-7d"), + "the refusal names the failed creation: {notices:?}" + ); + + worker.publish(); + let snapshot = published(&mut receiver); + assert_eq!(snapshot.focus, "b-7c", "the shown line survives"); + assert!( + snapshot.history_complete, + "the returned-to line's window loaded" + ); + assert!(snapshot.window_error.is_none()); + } + + /// A line cut from a line the directory knows, focused with its first + /// read in flight, whose creation then fails: the parent's window starts + /// over and the parent's read follows the failed line's last reply. + async fn a_failed_creation_with_the_parent_window_reading() + -> (Worker, std::sync::mpsc::Receiver) { + let (mut worker, receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.focus = "main".into(); + worker.discover_branch("b-7c"); + { + let history = worker.task_history.get_mut("b-7c").unwrap(); + history.done = true; + history.window_complete = true; + history.window.through = Some(2); + } + worker.task_history_queue.clear(); + let create: Event = serde_json::from_value(json!({ + "id": "create-child", "sequence": 2, "create_at": 1000, "type": "branch", "name": "create", + "data": { + "at": {"kind": "sequence", "sequence": 1}, "branch": "b-7d", "prompt": "Narrow the parser", + "source": {"kind": "host", "operation_id": "op"} + } + })) + .expect("a branch create event"); + worker.apply("b-7c", create); + worker + .command(crate::model::session::Command::FocusLine("b-7d".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + assert_eq!( + worker + .task_history_request + .as_ref() + .map(|read| read.branch_id.as_str()), + Some("b-7d"), + "the line's first window is in flight" + ); + + worker.task_event("b-7c", create_failed(400, "b-7d")); + assert_eq!( + worker.focus, "b-7c", + "a failed creation returns to the line it was cut from" + ); + fail(&mut worker, "the failed line's first window").await; + worker.poll_task_history().await.unwrap(); + assert_eq!( + worker + .task_history_request + .as_ref() + .map(|read| read.branch_id.as_str()), + Some("b-7c"), + "the parent's window is reading" + ); + assert!( + !worker.task_history["b-7c"].done, + "the parent's window has not finished" + ); + (worker, receiver) + } + + /// A creation that fails while the line it was cut from is still reading + /// its window is terminal for `/lines` at once: the directory records the + /// failure when the fact arrives, not when the parent's window replays + /// `live`. + #[tokio::test] + async fn a_create_failure_is_refused_before_the_parent_window_loads() { + let (mut worker, receiver) = a_failed_creation_with_the_parent_window_reading().await; + + worker + .command(crate::model::session::Command::FocusLine("b-7d".into())) + .await + .unwrap(); + + assert_eq!( + worker.focus, "b-7c", + "the failed line is refused while its parent's window is still reading" + ); + assert!( + worker.task_history["b-7d"].done, + "the refused line was not reset for a read" + ); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "the refused line is not read again on its own" + ); + let notices: Vec = receiver + .try_iter() + .filter_map(|update| match update { + Update::Notice(text) => Some(text), + _ => None, + }) + .collect(); + assert!( + notices + .iter() + .any(|notice| notice == "Line creation failed: b-7d"), + "the refusal names the failed creation: {notices:?}" + ); + } + + /// A parent's window that fails to read does not leave its failed creation + /// selectable: the failure is a directory fact from the moment it arrives. + #[tokio::test] + async fn a_create_failure_is_still_refused_after_the_parent_window_fails() { + let (mut worker, receiver) = a_failed_creation_with_the_parent_window_reading().await; + + fail(&mut worker, "the parent's window").await; + worker.poll_task_history().await.unwrap(); + assert!( + worker.task_history["b-7c"].window_error.is_some(), + "the parent's window failed" + ); + assert!( + !worker.task_history["b-7c"].done, + "the parent's window did not load" + ); + + worker + .command(crate::model::session::Command::FocusLine("b-7d".into())) + .await + .unwrap(); + + assert_eq!( + worker.focus, "b-7c", + "the failed line is refused after its parent's window failed" + ); + assert!( + worker.task_history["b-7d"].done, + "the refused line was not reset for a read" + ); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "the refused line is not read again on its own" + ); + let notices: Vec = receiver + .try_iter() + .filter_map(|update| match update { + Update::Notice(text) => Some(text), + _ => None, + }) + .collect(); + assert!( + notices + .iter() + .any(|notice| notice == "Line creation failed: b-7d"), + "the refusal names the failed creation: {notices:?}" + ); + } + + /// A live failure the parent's page has not projected a `branch/create` + /// for, with the parent's inventory still in flight: the child row is + /// projected terminal, `/lines` refuses it for the whole gap, and neither + /// the refusal nor the parent's finished window resets or queues it. + #[tokio::test] + async fn a_create_failure_before_its_create_is_projected_is_terminal() { + let (mut worker, mut receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.focus = "main".into(); + worker.discover_branch("b-7c"); + worker + .command(Command::FocusLine("b-7c".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + assert_eq!( + worker + .task_history_request + .as_ref() + .map(|read| read.branch_id.as_str()), + Some("b-7c"), + "the parent's first window is in flight" + ); + + worker.task_event("b-7c", create_failed(400, "b-7d")); + answer( + &mut worker, + json!({"events":[{ + "id": "create-child", "sequence": 2, "create_at": 1000, "type": "branch", "name": "create", + "data": { + "at": {"kind": "sequence", "sequence": 1}, "branch": "b-7d", "prompt": "Narrow the parser", + "source": {"kind": "host", "operation_id": "op"} + } + }], "through": 300, "nextBefore": 1, "nextAfter": 300}), + ) + .await; + + worker.methods.insert("session.input.pending".into()); + worker.methods.insert("session.turn.get".into()); + worker.poll_task_history().await.unwrap(); + assert!( + matches!( + worker.task_history_request.as_ref().map(|read| &read.stage), + Some(ReadStage::Inventory("session.input.pending")) + ), + "the parent's inventory is gated" + ); + + let child = worker + .projection + .line_views() + .iter() + .find(|line| line.id == "b-7d") + .expect("the parent's page projected the child"); + assert_eq!( + child.state, + LineState::CreationFailed, + "the projected child is terminal, not waiting" + ); + worker + .command(Command::FocusLine("b-7d".into())) + .await + .unwrap(); + assert_eq!( + worker.focus, "b-7c", + "the child is refused while its parent's inventory is in flight" + ); + assert!( + worker.task_history["b-7d"].done, + "the refused child was not reset for a read" + ); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "the refused child is not queued for a read" + ); + assert!( + !worker.lines.contains_key("b-7d"), + "the refused child has no transcript" + ); + let failed_notice = |receiver: &mut std::sync::mpsc::Receiver| -> usize { + receiver + .try_iter() + .filter_map(|update| match update { + Update::Notice(text) => Some(text), + _ => None, + }) + .filter(|notice| notice == "Branch b-7d: creation refused") + .count() + }; + assert_eq!( + failed_notice(&mut receiver), + 1, + "the failure is announced once" + ); + + answer( + &mut worker, + json!({"branchId":"b-7c","through":300,"inputs":[],"next":null}), + ) + .await; + worker.poll_task_history().await.unwrap(); + answer( + &mut worker, + json!({"branchId":"b-7c","through":300,"turn":null,"output":null}), + ) + .await; + worker.poll_task_history().await.unwrap(); + assert!( + worker.task_history["b-7c"].done, + "the parent's window finished" + ); + assert!( + worker.task_history["b-7d"].done, + "the parent's window did not reset the child" + ); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "the parent's window did not queue the child" + ); + assert_eq!( + failed_notice(&mut receiver), + 0, + "the drained failure is not announced again" + ); + + worker + .command(Command::TaskHistory { + projection_id: worker.projection_id, + }) + .await + .unwrap(); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "reopening /tasks does not queue the child" + ); + worker + .command(Command::FocusLine("b-7d".into())) + .await + .unwrap(); + assert_eq!(worker.focus, "b-7c", "the child stays refused"); + + receiver.try_iter().for_each(drop); + worker.invalidate_projection(); + assert!( + worker.projection.line_views().is_empty(), + "a new Session's projection holds no line from the old one" + ); + worker + .command(Command::FocusLine("b-7d".into())) + .await + .unwrap(); + let notices: Vec = receiver + .try_iter() + .filter_map(|update| match update { + Update::Notice(text) => Some(text), + _ => None, + }) + .collect(); + assert!( + notices + .iter() + .any(|notice| notice == "No line b-7d in this session"), + "a re-attached Session does not know the failed line: {notices:?}" + ); + assert!( + !notices + .iter() + .any(|notice| notice == "Line creation failed: b-7d"), + "the old Session's failure did not cross over: {notices:?}" + ); + assert_eq!( + worker.focus, "main", + "a re-attached Session does not know the failed line" + ); + } + + /// A page that records the child's creation and its failure in one read: + /// the replay folds the pair before any snapshot goes out, so the child is + /// terminal from that page alone, and a failed inventory on the parent + /// changes neither the child's state nor the queue. + #[tokio::test] + async fn a_page_that_records_a_create_and_its_failure_leaves_the_line_terminal() { + let (mut worker, _receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.focus = "main".into(); + worker.discover_branch("b-7c"); + worker + .command(Command::FocusLine("b-7c".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + assert_eq!( + worker + .task_history_request + .as_ref() + .map(|read| read.branch_id.as_str()), + Some("b-7c"), + "the parent's first window is in flight" + ); + + answer( + &mut worker, + json!({"events":[{ + "id": "create-child", "sequence": 2, "create_at": 1000, "type": "branch", "name": "create", + "data": { + "at": {"kind": "sequence", "sequence": 1}, "branch": "b-7d", "prompt": "Narrow the parser", + "source": {"kind": "host", "operation_id": "op"} + } + }, create_failed_page(3, "b-7d")], "through": 300, "nextBefore": 1, "nextAfter": 300}), + ) + .await; + + let child = worker + .projection + .line_views() + .iter() + .find(|line| line.id == "b-7d") + .expect("the page projected the child"); + assert_eq!( + child.state, + LineState::CreationFailed, + "the page's failure is the child's only projected state" + ); + worker + .command(Command::FocusLine("b-7d".into())) + .await + .unwrap(); + assert_eq!(worker.focus, "b-7c", "the child is refused"); + assert!( + worker.task_history["b-7d"].done, + "the refused child was not reset for a read" + ); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "the refused child is not queued for a read" + ); + assert!( + !worker.lines.contains_key("b-7d"), + "the refused child has no transcript" + ); + + worker.methods.insert("session.input.pending".into()); + worker.methods.insert("session.turn.get".into()); + worker.poll_task_history().await.unwrap(); + fail(&mut worker, "the parent's inventory").await; + worker.poll_task_history().await.unwrap(); + assert!( + worker.task_history["b-7c"].error.is_some(), + "the parent's inventory failed" + ); + assert!( + worker.task_history["b-7d"].done, + "the failed inventory left the child settled" + ); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "the failed inventory did not queue the child" + ); + + worker + .command(Command::TaskHistory { + projection_id: worker.projection_id, + }) + .await + .unwrap(); + assert!( + worker.task_history_queue.contains(&"b-7c".to_owned()), + "reopening /tasks retries the parent" + ); + assert!( + !worker.task_history_queue.contains(&"b-7d".to_owned()), + "reopening /tasks does not queue the child" + ); + worker + .command(Command::FocusLine("b-7d".into())) + .await + .unwrap(); + assert_eq!(worker.focus, "b-7c", "the child stays refused"); + } + + /// A child its parent's first page published as waiting, whose creation + /// fails after the parent's inventory failed while the parent stays + /// focused: the terminal directory state publishes a snapshot on its own, + /// and a repeated failure schedules nothing. + #[tokio::test] + async fn a_live_create_failure_publishes_the_terminal_directory_without_focus() { + let (mut worker, mut receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.focus = "main".into(); + worker.discover_branch("b-7c"); + worker + .command(Command::FocusLine("b-7c".into())) + .await + .unwrap(); + worker.poll_task_history().await.unwrap(); + answer( + &mut worker, + json!({"events":[{ + "id": "create-child", "sequence": 2, "create_at": 1000, "type": "branch", "name": "create", + "data": { + "at": {"kind": "sequence", "sequence": 1}, "branch": "b-7d", "prompt": "Narrow the parser", + "source": {"kind": "host", "operation_id": "op"} + } + }], "through": 300, "nextBefore": 1, "nextAfter": 300}), + ) + .await; + let snapshot = published(&mut receiver); + let child = snapshot + .lines + .iter() + .find(|line| line.id == "b-7d") + .expect("the parent's first page published the child"); + assert_eq!( + child.state, + LineState::Waiting, + "the child waits for its creation" + ); + + worker.methods.insert("session.input.pending".into()); + worker.methods.insert("session.turn.get".into()); + worker.task_history_queue.clear(); + worker.task_history_queue.push_back("b-7c".into()); + worker.poll_task_history().await.unwrap(); + assert!( + matches!( + worker.task_history_request.as_ref().map(|read| &read.stage), + Some(ReadStage::Inventory("session.input.pending")) + ), + "the parent's inventory is in flight" + ); + fail(&mut worker, "the parent's inventory").await; + assert!( + worker.task_history["b-7c"].error.is_some(), + "the parent's inventory failed" + ); + worker.publish(); + let snapshot = published(&mut receiver); + let child = snapshot + .lines + .iter() + .find(|line| line.id == "b-7d") + .expect("the failed inventory leaves the child listed"); + assert_eq!( + child.state, + LineState::Waiting, + "the failed inventory left the child waiting" + ); + assert_eq!(snapshot.focus, "b-7c", "the parent stays shown"); + + worker.task_event("b-7c", create_failed(400, "b-7d")); + assert!( + worker.publish_at.is_some(), + "the terminal directory state schedules a snapshot without focus" + ); + worker.publish(); + let snapshot = published(&mut receiver); + let child = snapshot + .lines + .iter() + .find(|line| line.id == "b-7d") + .expect("the published directory keeps the child"); + assert_eq!( + child.state, + LineState::CreationFailed, + "the published snapshot shows the terminal state, not waiting" + ); + assert_eq!(snapshot.focus, "b-7c", "the parent stays shown"); + + worker.task_event("b-7c", create_failed(401, "b-7d")); + assert!( + worker.publish_at.is_none(), + "a repeated failure schedules no second snapshot" + ); + } + + fn published(receiver: &mut std::sync::mpsc::Receiver) -> ViewSnapshot { + let mut snapshot = None; + while let Ok(update) = receiver.try_recv() { + if let Update::Snapshot(state) = update { + snapshot = Some(*state); + } + } + snapshot.expect("a published snapshot") + } + /// A line's own window can start after its start. The lines it opened show /// no count then, and the earlier page that reaches the start fills it in. #[tokio::test] diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 8ac17f7cf5..b56943edf1 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -510,13 +510,8 @@ fn run_terminal( (true, Some(at)) if !terminal.writing() => { FRAME_INTERVAL.saturating_sub(now.duration_since(at)) } - _ if app.running() - || terminal.writing() - || app.failure.is_none() && app.awaiting_window => - { - FRAME_INTERVAL - } - _ => SESSION_POLL, + _ if terminal.writing() => FRAME_INTERVAL, + _ => app.poll_interval(), }; let wait = full .as_ref() @@ -1888,6 +1883,16 @@ impl App { self.failure.is_none() && self.snapshot.as_ref().is_some_and(|s| s.running) } + /// The wait before input is polled again when no frame is due: frame rate + /// while a turn runs or a shown window still loads, else the idle poll. + fn poll_interval(&self) -> Duration { + if self.running() || (self.failure.is_none() && self.awaiting_window) { + FRAME_INTERVAL + } else { + SESSION_POLL + } + } + /// Refuses to start a clipboard or image read while a send-now is settling, /// with the notice that says why. A read started after the stop was asked /// for cannot be ordered against the stop's reply, so the message a settled @@ -2570,6 +2575,13 @@ impl App { .is_some_and(|shown| shown.focus != snapshot.focus); if switched { self.switch_line(snapshot.focus.clone()); + } else if self + .snapshot + .as_ref() + .is_some_and(|shown| shown.window_error.is_some()) + && snapshot.window_error.is_none() + { + self.rearm_window(); } if let Some(Prompt::Tasks(panel)) = &mut self.prompt { if panel.projection_id == snapshot.projection_id { @@ -7080,10 +7092,13 @@ impl App { let Some(snapshot) = &self.snapshot else { return false; }; - if !snapshot.history_complete { + if !snapshot.history_complete && snapshot.window_error.is_none() { return false; } self.awaiting_window = false; + if !snapshot.history_complete { + return true; + } let messages: Vec = snapshot .rows .iter() @@ -7563,9 +7578,33 @@ impl App { } self.tail_groups = tail_groups; self.tail_thoughts = tail_thoughts; + if let Some(error) = snapshot.window_error.as_deref() { + let block = Block::Status { + text: format!( + "{}: {}", + t("Branch history failed; reopen to retry"), + crate::sanitize::safe_line(error) + ), + tone: Tone::Warning, + }; + let rows = render_block(&block, width, p, markdown, self.fullscreen); + tail.push(String::new()); + tail.extend(rows.into_iter().map(|r| format!("{pad}{r}"))); + } (commits, sources, tail) } + /// Arms the shown line's window again after its first read failed. A + /// retry publishes the same focus as loading, so no switch announces it. + fn rearm_window(&mut self) { + self.window_floor = 0; + self.history_floor = 0; + self.load_more = false; + self.window_info = (0, 0); + self.history_request = None; + self.awaiting_window = true; + } + fn switch_line(&mut self, line: String) { self.release_compaction_details(); self.planner.reset(); @@ -15998,6 +16037,158 @@ mod tests { assert_eq!(text.matches("line one").count(), 1, "{text}"); } + #[test] + fn a_failed_line_window_shows_its_error_and_returns_the_idle_poll() { + for fullscreen in [false, true] { + let mut drawn = Drawn::new((100, 40), None, true); + drawn.app.fullscreen = fullscreen; + drawn.show(&[], "main", true); + drawn.show(&[], "b-7c", false); + assert!( + drawn.app.awaiting_window, + "fullscreen={fullscreen}: the line is still loading" + ); + assert_eq!( + drawn.app.poll_interval(), + FRAME_INTERVAL, + "fullscreen={fullscreen}: a loading window asks for frames" + ); + assert!( + !drawn.transcript().contains("Branch history failed"), + "fullscreen={fullscreen}: nothing is drawn while the window loads" + ); + + drawn.app.apply(Update::Snapshot(Box::new(ViewSnapshot { + session_id: "s1".into(), + focus: "b-7c".into(), + window_error: Some("the daemon dropped the read".into()), + ..ViewSnapshot::default() + }))); + drawn.draw(); + + let text = drawn.transcript(); + assert!( + !drawn.app.awaiting_window, + "fullscreen={fullscreen}: the failed window armed the view" + ); + assert_eq!( + drawn.app.poll_interval(), + SESSION_POLL, + "fullscreen={fullscreen}: a failed window waits at the idle poll" + ); + assert!( + text.contains("Branch history failed; reopen to retry"), + "fullscreen={fullscreen}: the line names the failure and its retry: {text}" + ); + assert!( + text.contains("the daemon dropped the read"), + "fullscreen={fullscreen}: the line carries the reason: {text}" + ); + assert!( + text.contains("⑂ b-7c"), + "fullscreen={fullscreen}: the failure draws under the line's boundary: {text}" + ); + } + } + + /// A failed first window can be read again: reopening `/tasks` on the + /// same line publishes it as loading, and the page that lands is laid out + /// as a first window with the older history behind the load-more row. + #[test] + fn reopening_a_failed_line_rearms_its_window() { + let mut drawn = Drawn::new((80, 40), None, true); + drawn.app.fullscreen = true; + let sent = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + drawn.app.host = Box::new(Recorder(sent.clone())); + drawn.show(&[], "main", true); + drawn.show(&[], "b-7c", false); + drawn.app.apply(Update::Snapshot(Box::new(ViewSnapshot { + session_id: "s1".into(), + focus: "b-7c".into(), + window_error: Some("the daemon dropped the read".into()), + ..ViewSnapshot::default() + }))); + drawn.draw(); + assert!( + !drawn.app.awaiting_window, + "the failed window settled the view" + ); + + drawn.app.run_command("tasks", ""); + assert!( + matches!(drawn.app.prompt, Some(Prompt::Tasks(_))), + "/tasks opens on the failed line" + ); + assert!( + sent.borrow() + .iter() + .any(|command| matches!(command, Command::TaskHistory { .. })), + "reopening the panel retries the line's window" + ); + + drawn.app.apply(Update::Snapshot(Box::new(ViewSnapshot { + session_id: "s1".into(), + focus: "b-7c".into(), + ..ViewSnapshot::default() + }))); + drawn.draw(); + assert!( + drawn.app.awaiting_window, + "the retry loads the same line again instead of staying failed" + ); + assert_eq!( + drawn.app.poll_interval(), + FRAME_INTERVAL, + "a loading window asks for frames" + ); + assert!( + !drawn.transcript().contains("Branch history failed"), + "the retry clears the failure from the line" + ); + + let mut rows = older_rows(30); + rows.extend(window_rows(HISTORY_WINDOW)); + drawn.app.apply(Update::Snapshot(Box::new(ViewSnapshot { + session_id: "s1".into(), + focus: "b-7c".into(), + rows, + history_complete: true, + earlier: Earlier::Unread, + ..ViewSnapshot::default() + }))); + drawn.draw(); + assert!( + !drawn.app.awaiting_window, + "the retried page armed the view" + ); + assert_eq!( + drawn.app.poll_interval(), + SESSION_POLL, + "the loaded window waits at the idle poll" + ); + assert_eq!( + drawn.app.window_floor, 30, + "the page is laid out over the newest window" + ); + assert_eq!( + drawn.app.history_floor, 30, + "the retried page starts at the same floor" + ); + assert_eq!( + drawn.app.window_info, + (HISTORY_WINDOW, 30), + "the window names the older messages it hides" + ); + assert!( + drawn + .app + .history + .iter() + .any(|block| matches!(block, Block::LoadMore(30))), + "the older history is left to the load-more row" + ); + } + #[test] fn the_scrollback_composer_names_the_shown_line() { let mut drawn = Drawn::new((80, 40), None, true); diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index e32a741ba2..f27d0f3e15 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -1952,6 +1952,50 @@ fn tui_main_history_failure_is_visible_and_disables_submission() { } } +#[test] +fn tui_main_history_failure_is_visible_on_a_reporting_daemon() { + let home = Home::new(); + let daemon = home.daemon(move |wire| { + wire.hello(&["report.prepare"]); + let attach = wire.read("session.attach"); + wire.reply(&attach, attach_record(&attach)); + let history = wire.read("session.history"); + assert_eq!(history["params"]["branchId"], "main"); + wire.send(json!({"jsonrpc":"2.0","id":history["id"],"error":{"code":-32000,"message":"main store unreadable","data":{"appError":"storage_failed"}}})); + while let Some(line) = wire.trailing_request() { + let request: Value = serde_json::from_str(&line).unwrap(); + match request["method"].as_str().unwrap() { + "session.context.usage" => assert_eq!(request["params"], json!({"sessionId":"session","branchId":"main"})), + "account.providers" => wire.reply(&request, json!([])), + other => panic!("failed main history must not accept a hidden turn: {other}"), + } + } + }); + let mut launch = home.command(); + launch.args(["--resume", "session"]); + let mut terminal = Terminal::launch_tui(launch); + terminal.until("Main branch history:"); + terminal.write(b"keep this draft"); + terminal.until("keep this draft"); + terminal.write(b"\r"); + terminal.until("Disconnected; draft kept. Exit and resume this Session."); + assert!( + terminal.transcript.contains("keep this draft"), + "the refused submission stays in the composer: {}", + terminal.transcript + ); + assert!( + !terminal + .transcript + .contains("Run /report to create a report."), + "a fatal main history failure is not offered as a report: {}", + terminal.transcript + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + fn workflow_run(id: &str, name: &str, state: &str, started_by: Value, report_to: Value) -> Value { let ended = !matches!(state, "running" | "stopping"); let mut run = json!({ diff --git a/docs/design/timeline-ui.md b/docs/design/timeline-ui.md index 1f1a2eb26b..7df2d3c850 100644 --- a/docs/design/timeline-ui.md +++ b/docs/design/timeline-ui.md @@ -209,6 +209,10 @@ The row is keyed by input id from the `input/message` that wrote it to the `inpu Unchanged from #427 §14: a switch writes a `⑂ name · id` boundary and the shown line's transcript, laid out once that line's history has loaded, which holds its own events only (each branch numbers its own sequences, [sessions service D11](appserver/sessions-service.md)). Its inherited history is its parent's, one marker away. +A window has three states: loading, complete and failed. A failed first read is not still-loading: the line draws `Branch history failed; reopen to retry: ` in place of its transcript, the interface waits at the idle poll instead of frame rate, and nothing reads it again in the background. Selecting the line again in `/lines`, or reopening the tasks panel, starts that read over. The failure belongs to the first read: when a later inventory refresh or an `/earlier` page fails, the loaded transcript stays drawn and the read reports its own error. `main` keeps the existing open failure (failure visible, submission refused, draft kept) from the [native CLI contract](../../crates/dim-cli/README.md). + +A line whose creation fails before its first window loads has no transcript and no read that could settle it. The interface shows the line it was cut from, `main` when the directory does not know it, under the usual switch boundary, and the failure's notice names the creation that failed. `/lines` keeps the line as `creation failed` and refuses to show it. + ## 6. Lines panel `/lines` is the map of the Timelines. Children are ordered by where they were cut from their parent, then by opening order. Each row leads with the line's purpose and says `after message N` and its id: diff --git a/docs/zh/design/timeline-ui.md b/docs/zh/design/timeline-ui.md index 78baedc119..39ddfe0667 100644 --- a/docs/zh/design/timeline-ui.md +++ b/docs/zh/design/timeline-ui.md @@ -206,6 +206,10 @@ applied 的输入可以跨过一次 stop 继续待消费,正是下一个 turn 与 #427 §14 相同:切换时写一行 `⑂ 名字 · id` 边界,等该线的历史加载完后接着是它的 transcript,只含它自己的事件(每个分支各自编号,[sessions service D11](appserver/sessions-service.md))。它继承的历史属于父线,离它只有一个标记的距离。 +窗口有三种状态:加载中、完成、失败。首次读取失败不再算作“仍在加载”:线上用 `读取分支历史失败;重新打开重试:<原因>` 代替 transcript,界面回到空闲轮询而不是逐帧唤醒,后台也不自动重读。重新在 `/lines` 里选中这条线,或重新打开 `/tasks` 面板,会重新开始这次读取。失败只属于首次读取:之后任务清单刷新或 `/earlier` 的一页读取失败时,已加载的 transcript 保持原样,只报告那次读取自己的错误。`main` 保持[原生 CLI 契约](../../../crates/dim-cli/README.md)里原有的打开失败:失败可见、拒绝提交、保留草稿。 + +线在首窗加载完成之前创建失败时,既没有 transcript,也没有能结束这次等待的读取。界面按普通的切换边界显示它被切出的那条线(目录不知道父线时显示 `main`),失败通知写明是哪次创建失败。`/lines` 仍把这条线标为 `creation failed`,并拒绝显示它。 + ## 6. Lines 面板 `/lines` 是 Timeline 的地图。子线先按它在父线上被切出的位置排序,再按打开顺序。每行以线的用途开头,后面写 `after message N` 和它的 id: