From 9a09bc1f9c4b2d7243834b36959b21ab7872f5c6 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 04:36:19 +0800 Subject: [PATCH 01/13] fix(cli): show a failed line window and stop frame polling A line whose first history window cannot be read is no longer treated as still loading: the line draws the failure with the reopen-to-retry wording and the view returns to the idle poll instead of waking at frame rate. The initial window failure is kept apart from later inventory and earlier-page errors, so those leave the loaded transcript in place, and selecting the line again in /lines or reopening /tasks reads it again. main keeps the existing visible open failure on daemons that offer report.prepare: it now fails the Session regardless of report availability, refuses submission and keeps the draft. Refs #2046 --- crates/dim-cli/src/model/view.rs | 5 + crates/dim-cli/src/session_host.rs | 7 +- crates/dim-cli/src/session_host/tasks.rs | 224 +++++++++++++++++++++-- crates/dim-cli/src/ui/tui.rs | 91 ++++++++- crates/dimcode/tests/cli_flow/tasks.rs | 37 ++++ docs/design/timeline-ui.md | 2 + docs/zh/design/timeline-ui.md | 2 + 7 files changed, 336 insertions(+), 32 deletions(-) diff --git a/crates/dim-cli/src/model/view.rs b/crates/dim-cli/src/model/view.rs index 7d9e4b1077..52e74f5fc6 100644 --- a/crates/dim-cli/src/model/view.rs +++ b/crates/dim-cli/src/model/view.rs @@ -472,6 +472,11 @@ 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. + 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/session_host.rs b/crates/dim-cli/src/session_host.rs index b64631d0a7..e788cb7406 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -4927,10 +4927,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 fce7881f8c..5bb0ca6076 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, @@ -124,13 +129,15 @@ impl Worker { .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 (!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; @@ -232,6 +239,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; } @@ -256,7 +264,6 @@ impl Worker { return; } history.earlier = EarlierRead::Reading; - history.window_complete = false; history.error = None; self.task_history_queue.push_back(self.focus.clone()); } @@ -365,16 +372,18 @@ impl Worker { "This daemon cannot read a bounded transcript window; update the daemon".into(), ); } - let (stage, method, params) = if branch_id != DEFAULT_BRANCH_ID + 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 window_read + && branch_id != DEFAULT_BRANCH_ID && !self.lines.contains_key(&branch_id) - && !self.task_history[&branch_id].window_complete { ( ReadStage::Cut, "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( @@ -452,8 +461,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(); } } @@ -573,10 +587,8 @@ impl Worker { .and_then(|error| error.data.as_ref()) .and_then(|data| data["appError"].as_str()) .map(str::to_owned); - let history = self - .task_history - .get_mut(&request.branch_id) - .expect("current history"); + let fatal = + request.branch_id == DEFAULT_BRANCH_ID && !self.task_history[&request.branch_id].done; let result = result.map_err(|error| error.to_string()).and_then(|value| { let page = if self .client @@ -587,27 +599,34 @@ 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)); 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 == DEFAULT_BRANCH_ID && !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(); let missing_prefix = history.window.before.is_some(); history.window_complete = true; @@ -642,6 +661,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); @@ -837,6 +869,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 { @@ -1135,4 +1168,155 @@ mod tests { "a press during the retried read queues nothing" ); } + + /// 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(); + 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"); + } + + 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") + } } diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 8ab0e5beb0..310e1c4d7e 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -518,13 +518,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() @@ -1877,6 +1872,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 @@ -6881,10 +6886,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() @@ -7364,6 +7372,19 @@ 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) } @@ -15744,6 +15765,60 @@ 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}" + ); + } + } + #[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 b27d649216..ee699906f2 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -1820,6 +1820,43 @@ 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 + ); + 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..377f52f85d 100644 --- a/docs/design/timeline-ui.md +++ b/docs/design/timeline-ui.md @@ -209,6 +209,8 @@ 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). + ## 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..018340f8d0 100644 --- a/docs/zh/design/timeline-ui.md +++ b/docs/zh/design/timeline-ui.md @@ -206,6 +206,8 @@ 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)里原有的打开失败:失败可见、拒绝提交、保留草稿。 + ## 6. Lines 面板 `/lines` 是 Timeline 的地图。子线先按它在父线上被切出的位置排序,再按打开顺序。每行以线的用途开头,后面写 `after message N` 和它的 id: From 13558fa624d4366958a1cda7219e02d1aa630b10 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 05:23:06 +0800 Subject: [PATCH 02/13] fix(cli): clear a line's read failure when its creation fails A branch whose creation fails no longer keeps the first window's read failure on its line: the creation failure settles the line and clears the stale failure with the rest of the read state, so the line cannot show a failure the tasks panel no longer lists. The unit tests cover the transport-failure exit that feeds the same failed-window state, and the reporting-daemon flow asserts that a fatal main history failure is not offered as a report. Refs #2046 --- crates/dim-cli/src/session_host/tasks.rs | 156 +++++++++++++++++++++++ crates/dimcode/tests/cli_flow/tasks.rs | 7 + 2 files changed, 163 insertions(+) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 5bb0ca6076..fb6f1b19d6 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -190,6 +190,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 @@ -921,6 +922,80 @@ 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(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" + } + })) + .expect("a create-failed event") + } + + /// 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 @@ -1310,6 +1385,87 @@ mod tests { 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" + ); + } + fn published(receiver: &mut std::sync::mpsc::Receiver) -> ViewSnapshot { let mut snapshot = None; while let Ok(update) = receiver.try_recv() { diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index ee699906f2..9d623af588 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -1852,6 +1852,13 @@ fn tui_main_history_failure_is_visible_on_a_reporting_daemon() { "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(); From 5db4273fe05bf1d79119ca52a342745e59875801 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 06:06:33 +0800 Subject: [PATCH 03/13] test(cli): cover retried line windows and failed creations A failed line window retried from the tasks panel publishes the same focus as loading, so the TUI test reopens the panel and checks that the retry arms the window, that the page lays out its window floor and that the older history stays behind the load-more row. A branch whose creation fails before its first window settles has no read that could end it; the task-history test covers the surviving focus, the cancelled read and the refusal to show the terminal line again. Refs #2046 --- crates/dim-cli/src/session_host/tasks.rs | 95 ++++++++++++++++++++++++ crates/dim-cli/src/ui/tui.rs | 90 ++++++++++++++++++++++ 2 files changed, 185 insertions(+) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index fb6f1b19d6..67613429c2 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -1466,6 +1466,101 @@ mod tests { ); } + /// 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"); + } + fn published(receiver: &mut std::sync::mpsc::Receiver) -> ViewSnapshot { let mut snapshot = None; while let Ok(update) = receiver.try_recv() { diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 310e1c4d7e..22abbcd89c 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -15819,6 +15819,96 @@ mod tests { } } + /// 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); + 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.load_more, "the older history is left to load"); + } + #[test] fn the_scrollback_composer_names_the_shown_line() { let mut drawn = Drawn::new((80, 40), None, true); From 47758bea66d80bb49be30a5e928673723454ffb7 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 06:10:12 +0800 Subject: [PATCH 04/13] fix(cli): re-arm a retried line and leave a failed creation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reopening the tasks panel on a line whose first window failed publishes the same focus as loading, which no switch announces; the view now arms that window again when the failure clears, so the retry enters loading and the page that lands is laid out over its newest window with the older history behind the load-more row. A creation that fails while the shown line's first window loads leaves no read that could end its wait. The line's creation is terminal, so the Session attachment shows the line it was cut from, main when the directory does not know it, and refuses a lines-panel selection of the failed line instead of leaving the view loading forever. Design: docs/design/timeline-ui.md §5 and docs/zh/design/timeline-ui.md §5 record the creation-failure transition. Refs #2046 --- crates/dim-cli/src/session_host.rs | 10 +++++++++ crates/dim-cli/src/session_host/tasks.rs | 18 +++++++++++++++ crates/dim-cli/src/ui/tui.rs | 28 +++++++++++++++++++++++- docs/design/timeline-ui.md | 2 ++ docs/zh/design/timeline-ui.md | 2 ++ 5 files changed, 59 insertions(+), 1 deletion(-) diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index e788cb7406..4b55ecca27 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -4834,6 +4834,16 @@ impl Worker { self.send(Update::Notice(format!("No line {line} in this session"))); return; } + if line != ROOT_BRANCH_ID + && self + .projection + .line_views() + .iter() + .any(|view| view.id == line && view.state == LineState::CreationFailed) + { + self.send(Update::Notice(format!("Line creation failed: {line}"))); + return; + } if line != ROOT_BRANCH_ID { self.line_projection(&line); } diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 67613429c2..e29d662fc1 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -200,6 +200,24 @@ impl Worker { if newly_failed { self.send(Update::Notice(format!("Branch {branch}: {error}"))); } + 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(); + } } _ => {} } diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 22abbcd89c..c58109d2be 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -2478,6 +2478,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 { @@ -7388,6 +7395,17 @@ impl App { (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(); @@ -15825,6 +15843,7 @@ mod tests { #[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); @@ -15906,7 +15925,14 @@ mod tests { (HISTORY_WINDOW, 30), "the window names the older messages it hides" ); - assert!(drawn.app.load_more, "the older history is left to load"); + assert!( + drawn + .app + .history + .iter() + .any(|block| matches!(block, Block::LoadMore(30))), + "the older history is left to the load-more row" + ); } #[test] diff --git a/docs/design/timeline-ui.md b/docs/design/timeline-ui.md index 377f52f85d..7df2d3c850 100644 --- a/docs/design/timeline-ui.md +++ b/docs/design/timeline-ui.md @@ -211,6 +211,8 @@ Unchanged from #427 §14: a switch writes a `⑂ name · id` boundary and the sh 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 018340f8d0..39ddfe0667 100644 --- a/docs/zh/design/timeline-ui.md +++ b/docs/zh/design/timeline-ui.md @@ -208,6 +208,8 @@ applied 的输入可以跨过一次 stop 继续待消费,正是下一个 turn 窗口有三种状态:加载中、完成、失败。首次读取失败不再算作“仍在加载”:线上用 `读取分支历史失败;重新打开重试:<原因>` 代替 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: From fd6c5bb8d190aa72c169ff6a5a41a3d4c9d082fc Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 06:24:22 +0800 Subject: [PATCH 05/13] test(cli): cover the line a failed creation returns to The focus fallback after a failed line creation was only exercised with `main` as the parent, so the parent lookup and its window reset had no test when the directory knows the line the failed one was cut from. The new test cuts a line from another line, fails its creation while the first window is in flight, and checks that the focus returns to that line, that its window starts over and is read again, and that `/lines` refuses the failed line. --- crates/dim-cli/src/session_host/tasks.rs | 139 +++++++++++++++++++++++ 1 file changed, 139 insertions(+) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index e29d662fc1..d710f99242 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -1579,6 +1579,145 @@ mod tests { 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()); + } + fn published(receiver: &mut std::sync::mpsc::Receiver) -> ViewSnapshot { let mut snapshot = None; while let Ok(update) = receiver.try_recv() { From f354436c757342babd4ff1cb2d1d744b8eced52a Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 06:38:45 +0800 Subject: [PATCH 06/13] test(cli): refuse a failed creation before its parent window settles The directory learns that a branch creation failed when the fact arrives, but a line whose parent window is still loading keeps the fact in the parent's live queue: the existing refusal only sees the failure once that window replays the queue, and a window that fails to read never replays it. Cover both moments: the failed line is refused while the parent's first window is reading and after that read fails. --- crates/dim-cli/src/session_host/tasks.rs | 151 +++++++++++++++++++++++ 1 file changed, 151 insertions(+) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index d710f99242..0d76b4016c 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -1718,6 +1718,157 @@ mod tests { 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:?}" + ); + } + fn published(receiver: &mut std::sync::mpsc::Receiver) -> ViewSnapshot { let mut snapshot = None; while let Ok(update) = receiver.try_recv() { From fed6ce780c7a67e213676780e6ac6398b18edf80 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 06:40:16 +0800 Subject: [PATCH 07/13] fix(cli): record a failed creation in the directory when the fact arrives A line whose creation failed stayed selectable until the window that recorded the fact replayed it: the fact sits in the parent's live queue while that window loads, and a window whose read fails never replays it. Record the line's terminal state in the session directory when the failure arrives, so the existing refusal sees it immediately and the transcript still replays the queue once the window loads. --- crates/dim-cli/src/session_host/tasks.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 0d76b4016c..116af129b7 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -200,6 +200,9 @@ 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. + self.projection.apply(branch, event); if self.focus == *branch { let parent = self .projection From e6d06de0caf049ccd21ed397332844b0f4e48743 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 07:21:30 +0800 Subject: [PATCH 08/13] test(cli): cover a creation failure before its create is projected The live failure can reach the worker before the parent's page projects the child's branch/create, and the parent's inventory can stay in flight after that. The test delivers the failure first, replays a page that only holds branch/create, and gates the follow-up inventory read: the child row must be terminal, /lines must refuse it, and nothing may reset or queue it, before and after the parent's window finishes. It also pins the failure notice at one per failure and checks that a re-attached Session projection holds neither the row nor the failure. --- crates/dim-cli/src/session_host/tasks.rs | 177 +++++++++++++++++++++++ 1 file changed, 177 insertions(+) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 116af129b7..c2564ad57c 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -1872,6 +1872,183 @@ mod tests { ); } + /// 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" + ); + } + fn published(receiver: &mut std::sync::mpsc::Receiver) -> ViewSnapshot { let mut snapshot = None; while let Ok(update) = receiver.try_recv() { From 384381bad6834be4ae6aec764d7bf472328ba8f8 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 07:22:08 +0800 Subject: [PATCH 09/13] fix(cli): keep a failed creation terminal before its line is projected A live branch/create-failed can reach the worker before the parent's page projects the child's branch/create, and the row created from that page was published as waiting until the parent's window finished and replayed the failure. Focus admission read only the projected row, so the child could be opened, its done state reset and a read queued for it. The Session projection now records the failed branch when the fact arrives, whether or not its row exists. A row projected later carries the failure, focus admission asks the fact instead of the row, and opening a line leaves a failed creation's state alone. The record lives with the line directory, so switching or re-attaching a Session starts without it, and the notice that announces the failure still comes from the live fact alone. --- crates/dim-cli/src/projection.rs | 17 ++++++++++++++++- crates/dim-cli/src/session_host.rs | 8 +------- crates/dim-cli/src/session_host/tasks.rs | 8 +++++--- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/crates/dim-cli/src/projection.rs b/crates/dim-cli/src/projection.rs index d98d73a798..6b097d9858 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 one is /// dropped. @@ -158,7 +162,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, cut: Some(LineCut { sequence, @@ -172,6 +180,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; } @@ -1379,6 +1388,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 4b55ecca27..e9449a8260 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -4834,13 +4834,7 @@ impl Worker { self.send(Update::Notice(format!("No line {line} in this session"))); return; } - if line != ROOT_BRANCH_ID - && self - .projection - .line_views() - .iter() - .any(|view| view.id == line && view.state == LineState::CreationFailed) - { + if line != ROOT_BRANCH_ID && self.projection.creation_failed(&line) { self.send(Update::Notice(format!("Line creation failed: {line}"))); return; } diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index c2564ad57c..fe3e38170b 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -124,14 +124,16 @@ 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())) - || history.window_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; From e2e7e774e17013e5cead978ab72ca62ab1e989db Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 07:25:17 +0800 Subject: [PATCH 10/13] test(cli): pin the page that records a create and its failure A parent page can hold both the child's branch/create and the branch/create-failed that ends it. The replay folds the pair before the reply publishes, so no frame or command sees the child waiting; this test asserts the projected state, the refusal, the intact done flag and the empty queue, then fails the parent's inventory and reopens /tasks to show that only the parent is retried. --- crates/dim-cli/src/session_host/tasks.rs | 115 ++++++++++++++++++++++- 1 file changed, 112 insertions(+), 3 deletions(-) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index fe3e38170b..9c8779afb1 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -947,7 +947,12 @@ mod tests { /// A `branch/create-failed` event for `branch`, as the daemon sends it. fn create_failed(sequence: u64, branch: &str) -> Event { - serde_json::from_value(json!({ + 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, @@ -957,8 +962,7 @@ mod tests { "status": "failed", "branch": branch, "createEvent": sequence - 1, "error": "creation refused" } - })) - .expect("a create-failed event") + }) } /// A client whose daemon answered hello and then hung up: the next request @@ -2051,6 +2055,111 @@ mod tests { ); } + /// 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"); + } + fn published(receiver: &mut std::sync::mpsc::Receiver) -> ViewSnapshot { let mut snapshot = None; while let Ok(update) = receiver.try_recv() { From d1916a1c3d75f4bbde9e291ef47cc7977bf140b3 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 08:49:26 +0800 Subject: [PATCH 11/13] test(cli): pin a live creation failure published without focus A child published as waiting by its parent's first page, whose creation fails after the parent's inventory failed with the parent focused, must publish the terminal directory state on its own; a repeated failure event must not schedule another snapshot. --- crates/dim-cli/src/session_host/tasks.rs | 96 ++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 9c8779afb1..0cef1eb005 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -2160,6 +2160,102 @@ mod tests { 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() { From 2f4237ac0d825d15941e153ca0ce545ff747a23c Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 08:54:30 +0800 Subject: [PATCH 12/13] fix(cli): publish a line's first failed creation without focus A live branch/create-failed that first makes the directory row terminal now schedules a snapshot even when another line is focused, so `/lines` cannot keep showing the line as waiting until unrelated activity. The terminal fact decides the first change, so a repeated failure event schedules nothing. --- crates/dim-cli/src/session_host/tasks.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 0cef1eb005..6b5358639f 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -204,6 +204,7 @@ impl Worker { } // 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 @@ -222,6 +223,9 @@ impl Worker { } self.focus = parent; self.changed(); + } else if first_terminal { + // `/lines` draws the directory from published snapshots. + self.changed(); } } _ => {} From c45fa4e42230b186e71eb70d2498625eae36a854 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 08:54:30 +0800 Subject: [PATCH 13/13] docs(cli): name the field that tells a loading window from a loaded one The `window_error` doc comment now says `history_complete` separates a window that is still loading from one that loaded, whether or not a later read failed. --- crates/dim-cli/src/model/view.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/dim-cli/src/model/view.rs b/crates/dim-cli/src/model/view.rs index 52e74f5fc6..00cb1a8462 100644 --- a/crates/dim-cli/src/model/view.rs +++ b/crates/dim-cli/src/model/view.rs @@ -475,7 +475,8 @@ pub struct ViewSnapshot { /// 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. + /// 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