From ec441247c69835a178fc483ce3e8f2f2f9b13815 Mon Sep 17 00:00:00 2001 From: zjywill Date: Thu, 26 Nov 2026 18:13:19 +0800 Subject: [PATCH 01/13] fix(tui): replay the full conversation in native scrollback Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/README.md | 24 +- crates/dim-cli/src/model/session.rs | 2 + crates/dim-cli/src/session_host.rs | 11 +- crates/dim-cli/src/session_host/tasks.rs | 64 ++--- crates/dim-cli/src/ui/i18n/de/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/es/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/fr/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/id/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/ja/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/ko/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/pt_br/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs | 4 +- crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs | 4 +- crates/dim-cli/src/ui/render/fullscreen.rs | 14 +- crates/dim-cli/src/ui/transcript/blocks.rs | 6 + crates/dim-cli/src/ui/tui.rs | 250 ++++++++----------- crates/dimcode/tests/cli_flow/lines.rs | 4 +- crates/dimcode/tests/cli_flow/tasks.rs | 9 +- crates/dimcode/tests/cli_flow/windows.rs | 2 +- docs/architecture/tui-e2e.md | 1 + docs/design/cli-commands.md | 8 +- docs/design/timeline-ui.md | 4 +- docs/zh/design/timeline-ui.md | 4 +- scripts/tui-tmux/scenarios.mjs | 65 +++++ 25 files changed, 289 insertions(+), 219 deletions(-) diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index ef9fb0a449..2545982f51 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -1360,18 +1360,28 @@ their last validated cursor. Loading or failed history disables stop-all while known individual targets remain usable. A failure reading main history is a visible connection failure: submission is disabled and the unsent draft stays in the current UI. Recovery requires exiting and resuming the Session. -Resuming waits for main's complete initial history before drawing the latest -100 messages and its boundary. Fullscreen tops them with a load-more row: a -click, or `Tab` up to it and `Enter`, draws the previous 100 above and keeps the -oldest drawn message at the top of the view. Scrollback reaches earlier messages -through a `/timeline` jump; a draft typed meanwhile stays editable. +Resuming draws up to 100 messages from main's initial history window. Both modes +mark unread history above the oldest message, never below the transcript. In fullscreen a +click, or `Tab` up to it and `Enter`, shows the preceding page at the join. Scrolling +up or pressing PageUp at the top does the same. `/earlier` reveals one page in fullscreen. +In scrollback it reprints the entire shown branch in order below a separator, in the +same terminal. The draft stays editable and the next reply follows the reprinted history. +`/timeline` still jumps to a specific message; a draft typed meanwhile stays editable. ```text +↑ Earlier messages · /earlier > paged-message-051 ... > paged-message-150 ---- resumed paged · 100 messages · earlier history: /timeline --- -[ draft typed while history was loading ] +--- resumed paged · 100 messages --- +[ Ask anything... ] + +/earlier (scrollback) +--- Full conversation history --- +> paged-message-001 +... +> paged-message-150 +[ Ask anything... ] ``` Child-branch failures remain local to the task history and release buffered diff --git a/crates/dim-cli/src/model/session.rs b/crates/dim-cli/src/model/session.rs index 3e807a149b..ed2028e7f5 100644 --- a/crates/dim-cli/src/model/session.rs +++ b/crates/dim-cli/src/model/session.rs @@ -411,6 +411,7 @@ pub enum Command { Earlier { line: String, session: Origin, + all: bool, }, Export(crate::export::Format), /// `/compact`: ask the line the command was typed on to compact its @@ -1334,6 +1335,7 @@ impl DeleteOutcome { } pub enum Update { + ReplayHistory, Reportable { error: crate::report::Captured, show_error: bool, diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index 820c9acd75..e97eacb449 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -1586,7 +1586,7 @@ impl Worker { None, "The centre moved before /usage ran; no report was printed", ), - Command::Earlier { line, session } => ( + Command::Earlier { line, session, .. } => ( session, Some(line), None, @@ -2028,7 +2028,14 @@ impl Worker { } } Command::Rename(title) => self.rename(title).await, - Command::Earlier { line, .. } => self.earlier(&line), + Command::Earlier { line, all, .. } => { + if !self.earlier_member() { + if let Some(history) = self.task_history.get_mut(&line) { + history.replay_all |= all; + } + self.earlier(&line); + } + } Command::Goal { request, .. } => self.goal(request).await, Command::Loop { request, .. } => self.loop_command(request).await, Command::CheckUpdate if self.options.endpoint.is_some() => { diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index eff80e68be..333e1c9bb6 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -24,6 +24,7 @@ pub(super) struct BranchHistory { inventory_cursor: Option, goal_stale: bool, earlier: EarlierRead, + pub(super) replay_all: bool, pub running: Option, pub latest_reply: u64, pub seen_reply: u64, @@ -281,9 +282,6 @@ impl Worker { } pub(super) fn earlier(&mut self, line: &str) { - if self.earlier_member() { - return; - } let Some(history) = self.task_history.get_mut(line) else { return; }; @@ -291,7 +289,12 @@ impl Worker { return; } if history.window.before.is_none() { - self.send(Update::Notice("Beginning of conversation".into())); + if std::mem::take(&mut history.replay_all) { + self.publish(); + self.send(Update::ReplayHistory); + } else { + self.send(Update::Notice("Beginning of conversation".into())); + } return; } history.earlier = EarlierRead::Reading; @@ -644,7 +647,6 @@ impl Worker { .map_err(|error| error.to_string()) }); let window_ready = matches!(result, Ok(true)); - let mut missing_prefix = false; match result { Err(error) => { if fatal { @@ -666,7 +668,7 @@ impl Worker { .expect("current history"); history.window_error = None; let events = history.window.take(); - missing_prefix = + let missing_prefix = history.window.dropped_pages() || history.window.before.is_some() && !at_start; history.window_complete = true; if history.earlier == EarlierRead::Reading { @@ -732,23 +734,29 @@ impl Worker { self.send(Update::NoModel); } } - if window_ready { + if window_ready && !self.continue_replay(&request.branch_id) { self.publish(); } - if missing_prefix { - self.send(Update::Notice( - "Earlier content not loaded; /earlier to read it".into(), - )); - } Ok(()) } + fn continue_replay(&mut self, branch: &str) -> bool { + let history = self.task_history.get_mut(branch).expect("loaded history"); + history.replay_all &= self.focus == branch && self.members.selected.is_none(); + if history.done && history.replay_all { + self.earlier(branch); + return true; + } + false + } + /// 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()); + history.replay_all = false; if history.earlier == EarlierRead::Reading { history.earlier = EarlierRead::Failed; } else if !history.done && !history.window_complete { @@ -793,9 +801,7 @@ impl Worker { self.task_event(branch, event); } } - if let Some(projection) = transcript_mut(&mut self.projection, &mut self.lines, branch) { - projection.trim(300); - } + self.continue_replay(branch); self.changed(); } @@ -1994,13 +2000,8 @@ mod tests { ); } - /// A window whose page left out earlier content says so in a notice. The - /// notice is sent after the snapshot that carries the page, so the - /// interface's next frame draws the page's rows before the notice that - /// reports them missing. Both updates share one channel, and the interface - /// applies whatever it drains in that order. #[tokio::test] - async fn a_missing_prefix_notice_follows_the_page_it_reports() { + async fn a_page_with_missing_history_marks_its_snapshot_unread() { let (mut worker, receiver, _sent) = crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; worker.session_id = "s1".into(); @@ -2016,25 +2017,8 @@ mod tests { ) .await; - let updates: Vec = receiver.try_iter().collect(); - let page = updates - .iter() - .position(|update| { - matches!(update, Update::Snapshot(view) - if view.rows.iter().any(|row| row.text.contains("the loaded page"))) - }) - .expect("the page published its rows"); - let notice = updates - .iter() - .position(|update| { - matches!(update, Update::Notice(text) - if text == "Earlier content not loaded; /earlier to read it") - }) - .expect("the page reports the earlier content it left out"); - assert!( - page < notice, - "the page's snapshot is sent before the notice that reports the missing earlier content" - ); + assert!(receiver.try_iter().any(|update| matches!(update, Update::Snapshot(view) + if view.earlier == Earlier::Unread && view.rows.iter().any(|row| row.text.contains("the loaded page"))))); } /// A creation that fails while the line's first window is in flight diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index 53262edfd3..62aa459dbf 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y bestätigen · Esc abbrechen", "Enter save · Esc cancel" => "Enter speichern · Esc abbrechen", "Loading…" => "Wird geladen…", + "Beginning of conversation" => "Anfang der Unterhaltung erreicht", + "Full conversation history" => "Vollständiger Gesprächsverlauf", "Tab / Enter complete" => "Tab / Enter vervollständigen", "Queue" => "Warteschlange", "Export session" => "Sitzung exportieren", @@ -365,7 +367,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "Nur im Vollbild (/tui)", "new session" => "neue Session", "resumed {id} · {count} messages" => "{id} fortgesetzt · {count} Nachrichten", - " · earlier history: /timeline" => " · früherer Verlauf: /timeline", + "Earlier messages · {key}" => "Frühere Nachrichten · {key}", "Error: {message}" => "Fehler: {message}", "working… {elapsed}" => "arbeitet… {elapsed}", "thinking… {elapsed}" => "denkt… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index 37a436ec12..109a10bef4 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y confirmar · Esc cancelar", "Enter save · Esc cancel" => "Enter guardar · Esc cancelar", "Loading…" => "Cargando…", + "Beginning of conversation" => "Inicio de la conversación", + "Full conversation history" => "Historial completo de la conversación", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Cola", "Export session" => "Exportar sesión", @@ -365,7 +367,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "Solo en pantalla completa (/tui)", "new session" => "nueva sesión", "resumed {id} · {count} messages" => "reanudada {id} · {count} mensajes", - " · earlier history: /timeline" => " · historial anterior: /timeline", + "Earlier messages · {key}" => "Mensajes anteriores · {key}", "Error: {message}" => "Error: {message}", "working… {elapsed}" => "trabajando… {elapsed}", "thinking… {elapsed}" => "pensando… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index a9be46a569..2a17ab637f 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y confirmer · Échap annuler", "Enter save · Esc cancel" => "Entrée enregistrer · Échap annuler", "Loading…" => "Chargement…", + "Beginning of conversation" => "Début de la conversation atteint", + "Full conversation history" => "Historique complet de la conversation", "Tab / Enter complete" => "Tab / Enter compléter", "Queue" => "File d’attente", "Export session" => "Exporter la session", @@ -355,7 +357,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "Plein écran uniquement (/tui)", "new session" => "nouvelle session", "resumed {id} · {count} messages" => "{id} repris · {count} messages", - " · earlier history: /timeline" => " · historique antérieur: /timeline", + "Earlier messages · {key}" => "Messages précédents · {key}", "Error: {message}" => "Erreur: {message}", "working… {elapsed}" => "travail… {elapsed}", "thinking… {elapsed}" => "réflexion… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index cfaedcac3b..294de5bf2c 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y konfirmasi · Esc batal", "Enter save · Esc cancel" => "Enter simpan · Esc batal", "Loading…" => "Memuat…", + "Beginning of conversation" => "Awal percakapan", + "Full conversation history" => "Riwayat percakapan lengkap", "Tab / Enter complete" => "Tab / Enter lengkapi", "Queue" => "Antrean", "Export session" => "Ekspor sesi", @@ -355,7 +357,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "Hanya di layar penuh (/tui)", "new session" => "sesi baru", "resumed {id} · {count} messages" => "lanjut {id} · {count} pesan", - " · earlier history: /timeline" => " · riwayat lama: /timeline", + "Earlier messages · {key}" => "Pesan sebelumnya · {key}", "Error: {message}" => "Error: {message}", "working… {elapsed}" => "bekerja… {elapsed}", "thinking… {elapsed}" => "berpikir… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index d614634157..eccb85da57 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y 確定 · Esc キャンセル", "Enter save · Esc cancel" => "Enter 保存 · Esc キャンセル", "Loading…" => "読み込み中…", + "Beginning of conversation" => "会話の先頭です", + "Full conversation history" => "会話履歴の全体", "Tab / Enter complete" => "Tab / Enter 補完", "Queue" => "キュー", "Export session" => "セッションをエクスポート", @@ -343,7 +345,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "全画面のみ(/tui)", "new session" => "新規セッション", "resumed {id} · {count} messages" => "{id} を再開 · {count} 件", - " · earlier history: /timeline" => " · 過去の履歴:/timeline", + "Earlier messages · {key}" => "以前のメッセージ · {key}", "Error: {message}" => "エラー:{message}", "working… {elapsed}" => "処理中… {elapsed}", "thinking… {elapsed}" => "思考中… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index 4ce9270368..83ddcdd31b 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y 확인 · Esc 취소", "Enter save · Esc cancel" => "Enter 저장 · Esc 취소", "Loading…" => "불러오는 중…", + "Beginning of conversation" => "대화의 시작입니다", + "Full conversation history" => "전체 대화 기록", "Tab / Enter complete" => "Tab / Enter 완성", "Queue" => "대기열", "Export session" => "세션 내보내기", @@ -329,7 +331,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "전체 화면에서만 가능 (/tui)", "new session" => "새 세션", "resumed {id} · {count} messages" => "{id} 재개됨 · 메시지 {count}개", - " · earlier history: /timeline" => " · 이전 기록: /timeline", + "Earlier messages · {key}" => "이전 메시지 · {key}", "Error: {message}" => "오류: {message}", "working… {elapsed}" => "작업 중… {elapsed}", "thinking… {elapsed}" => "생각 중… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs index cfe8a9536e..21df5ca6a0 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y confirmar · Esc cancelar", "Enter save · Esc cancel" => "Enter salvar · Esc cancelar", "Loading…" => "Carregando…", + "Beginning of conversation" => "Início da conversa", + "Full conversation history" => "Histórico completo da conversa", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Fila", "Export session" => "Exportar sessão", @@ -361,7 +363,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "Só em tela cheia (/tui)", "new session" => "nova sessão", "resumed {id} · {count} messages" => "{id} retomada · {count} mensagens", - " · earlier history: /timeline" => " · histórico anterior: /timeline", + "Earlier messages · {key}" => "Mensagens anteriores · {key}", "Error: {message}" => "Erro: {message}", "working… {elapsed}" => "trabalhando… {elapsed}", "thinking… {elapsed}" => "pensando… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs index 20390ee1af..3590170956 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y confirmar · Esc cancelar", "Enter save · Esc cancel" => "Enter guardar · Esc cancelar", "Loading…" => "A carregar…", + "Beginning of conversation" => "Início da conversa", + "Full conversation history" => "Histórico completo da conversa", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Fila", "Export session" => "Exportar sessão", @@ -361,7 +363,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "Só em ecrã inteiro (/tui)", "new session" => "nova sessão", "resumed {id} · {count} messages" => "{id} retomada · {count} mensagens", - " · earlier history: /timeline" => " · histórico anterior: /timeline", + "Earlier messages · {key}" => "Mensagens anteriores · {key}", "Error: {message}" => "Erro: {message}", "working… {elapsed}" => "a trabalhar… {elapsed}", "thinking… {elapsed}" => "a pensar… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs index 794d8aeb14..d0d6896606 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "y confirm · Esc cancel" => "y 确认 · Esc 取消", "Enter save · Esc cancel" => "Enter 保存 · Esc 取消", + "Beginning of conversation" => "已到对话开头", + "Full conversation history" => "完整历史", "Tab / Enter complete" => "Tab / Enter 补全", "Queue" => "队列", "Export session" => "导出会话", @@ -337,7 +339,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "仅在全屏界面可用(/tui)", "new session" => "新会话", "resumed {id} · {count} messages" => "已恢复 {id} · {count} 条消息", - " · earlier history: /timeline" => " · 更早历史:/timeline", + "Earlier messages · {key}" => "还有更早的消息 · {key}", "Error: {message}" => "错误:{message}", "working… {elapsed}" => "处理中… {elapsed}", "thinking… {elapsed}" => "思考中… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs index 99bf73b7c6..4efab0a50f 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -36,6 +36,8 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y 確認 · Esc 取消", "Enter save · Esc cancel" => "Enter 儲存 · Esc 取消", "Loading…" => "載入中…", + "Beginning of conversation" => "已到對話開頭", + "Full conversation history" => "完整歷史", "Tab / Enter complete" => "Tab / Enter 補全", "Queue" => "佇列", "Export session" => "匯出工作階段", @@ -323,7 +325,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Only in fullscreen (/tui)" => "僅限全螢幕模式(/tui)", "new session" => "新工作階段", "resumed {id} · {count} messages" => "已繼續 {id} · {count} 則訊息", - " · earlier history: /timeline" => " · 較早歷程:/timeline", + "Earlier messages · {key}" => "還有更早的訊息 · {key}", "Error: {message}" => "錯誤:{message}", "working… {elapsed}" => "處理中… {elapsed}", "thinking… {elapsed}" => "思考中… {elapsed}", diff --git a/crates/dim-cli/src/ui/render/fullscreen.rs b/crates/dim-cli/src/ui/render/fullscreen.rs index f5f336d1fa..fb93bb27ff 100644 --- a/crates/dim-cli/src/ui/render/fullscreen.rs +++ b/crates/dim-cli/src/ui/render/fullscreen.rs @@ -131,6 +131,7 @@ pub trait Document { pub enum MouseOutcome { Ignored, Redraw, + Earlier, /// A selection ended: its text, ready for the clipboard. Copy(String), /// The wheel turned over an overlay: the list in it moves (+ down). @@ -759,14 +760,18 @@ impl FullScreen { self.reveal_focus(doc); } - /// Scrolls so block `id` starts at the top of the view. - pub fn show_block(&mut self, id: usize, doc: &dyn Document) { + /// Shows the previous screenful with two rows of context at the join. + pub fn show_before_block(&mut self, id: usize, doc: &dyn Document) { self.sync(doc); if let Some(start) = id .checked_sub(self.base) .and_then(|index| self.starts.get(index)) { - self.pin((*start).min(self.max_top())); + self.pin( + start + .saturating_sub(self.view_rows.saturating_sub(2)) + .min(self.max_top()), + ); } } @@ -1044,6 +1049,9 @@ impl FullScreen { } MouseKind::WheelUp => { self.press = None; + if row < self.view_rows && self.at_top() { + return MouseOutcome::Earlier; + } let rows = self.wheel.rows(Instant::now()); self.scroll(-rows); MouseOutcome::Redraw diff --git a/crates/dim-cli/src/ui/transcript/blocks.rs b/crates/dim-cli/src/ui/transcript/blocks.rs index a94c5b7ccb..5040a3a283 100644 --- a/crates/dim-cli/src/ui/transcript/blocks.rs +++ b/crates/dim-cli/src/ui/transcript/blocks.rs @@ -788,6 +788,12 @@ pub(crate) fn render_block( Block::Failure(message) => vec![tf("Error: {message}", &[("message", message)])], Block::Boundary(label) => vec![fg(&boundary_line(label, width), &p.muted)], Block::Note(text) => vec![fg(&truncate_cells(text, width), &p.muted)], + Block::LoadMore(hidden) if !interactive || *hidden == 0 => gutter_text( + LOAD_MORE_MARK, + &tf("Earlier messages · {key}", &[("key", "/earlier")]), + width, + &p.accent, + ), Block::LoadMore(hidden) => { let label = tf( "{count} earlier messages · Enter or click to load", diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 2f1b909db8..aaa9518172 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -143,8 +143,8 @@ enum Jump { Pick, /// Pick the user message drawn as this block id (`/timeline`). Block(usize), - /// Scroll so this block id is at the top (after a page loads above it). - Show(usize), + /// Show the preceding screenful with this block still visible at the join. + Before(usize), /// Scroll to the top of this block id when it is taller than the viewport, /// so a long report opens at its heading instead of scrolled past it /// (`/keys`). @@ -160,7 +160,7 @@ fn apply_jump(full: &mut FullScreen, app: &App, jump: Jump) { Jump::Top => full.scroll_to_top(), Jump::Pick => full.focus_older(app), Jump::Block(id) => full.pick_block(id, app), - Jump::Show(id) => full.show_block(id, app), + Jump::Before(id) => full.show_before_block(id, app), Jump::ShowTall(id) => full.show_tall_block(id, app), } } @@ -723,6 +723,12 @@ fn run_terminal( match full.mouse(event, &app) { MouseOutcome::Ignored => {} MouseOutcome::Redraw => dirty = true, + MouseOutcome::Earlier => { + if app.keyboard_free() && !app.shows_member() { + app.show_earlier(); + } + dirty = true; + } MouseOutcome::Overlay(rows) => { app.scroll_overlay(rows * 3); dirty = true; @@ -1415,6 +1421,7 @@ struct App { /// `show_earlier`, cleared once the page is shown or the read ends /// without one. reveal_pending: bool, + full_history_section: bool, /// The user message a `/timeline` jump or a loaded page lands on, once /// drawn: `(row id, pick it)`. landing: Option<(String, bool)>, @@ -1435,8 +1442,7 @@ struct App { pending_boundary: Option, /// The line the transcript switched to, until its boundary row is out. pending_line: Option, - /// `(messages in the window, messages before it)` of the last switch. - window_info: (usize, usize), + window_messages: usize, /// Rows `[start, end)` queued to be drawn as an earlier-history page. history_request: Option<(usize, usize)>, /// The fullscreen interface is on screen. @@ -1895,13 +1901,14 @@ impl App { history_floor: 0, load_more: false, reveal_pending: false, + full_history_section: false, landing: None, startup_session: None, awaiting_window: false, switches: PendingSwitches::default(), pending_boundary: None, pending_line: None, - window_info: (0, 0), + window_messages: 0, history_request: None, fullscreen: false, signed_in: false, @@ -2761,6 +2768,13 @@ impl App { self.set_notice(text); } } + Update::ReplayHistory => { + if !self.fullscreen { + self.rebuild_window(0); + self.load_more = false; + self.full_history_section = true; + } + } Update::Snapshot(snapshot) => { let was_running = self.running(); let switched = self @@ -2808,7 +2822,13 @@ impl App { self.runs.observe(&snapshot); let previous = self.snapshot.replace(*snapshot); self.follow_floors(previous.as_ref()); - self.apply_earlier(previous.as_ref()); + if self.reveal_pending { + self.reveal_pending = !self.reveal_earlier() + && self + .snapshot + .as_ref() + .is_some_and(|s| s.earlier == Earlier::Reading); + } self.refresh_compactions(); self.refresh_cards(); self.refresh_tool_origins(); @@ -6017,14 +6037,7 @@ impl App { Outcome::Continue } "earlier" => { - if self.fullscreen { - self.show_earlier(); - } else { - self.host.send(Command::Earlier { - line: self.target_line(), - session: self.target_session(), - }); - } + self.show_earlier(); Outcome::Continue } "export" => { @@ -6393,6 +6406,17 @@ impl App { self.banner_committed = true; } let ready = self.arm_window(); + if ready && std::mem::take(&mut self.full_history_section) { + let block = Block::Boundary(t("Full conversation history").into()); + frame.commits.push(chunk(&render_block( + &block, + width, + &self.palette, + &self.markdown, + false, + ))); + self.record(block); + } if ready && let Some(shown) = self.pending_line.take() { let lines = self.snapshot.as_ref().map_or(&[][..], |s| &s.lines[..]); let label = match line_name(lines, &shown) { @@ -6404,14 +6428,14 @@ impl App { self.record(Block::Boundary(label)); frame.commits.push(text); } - if ready && std::mem::take(&mut self.load_more) && self.fullscreen { - let hidden = self.snapshot.as_ref().map_or(0, |snapshot| { - snapshot.rows[..self.window_floor.min(snapshot.rows.len())] - .iter() - .filter(|row| row.kind.is_message()) - .count() - }); - if hidden > 0 { + if ready && std::mem::take(&mut self.load_more) { + let hidden = self.hidden_messages(); + if hidden > 0 + || self + .snapshot + .as_ref() + .is_some_and(|s| s.earlier != Earlier::AtStart) + { let block = Block::LoadMore(hidden); let text = chunk(&render_block( &block, @@ -6476,20 +6500,15 @@ impl App { let sid = self.session_id.get(..8).unwrap_or(&self.session_id); tf( "forked {id} · {count} messages", - &[("id", sid), ("count", &self.window_info.0.to_string())], + &[("id", sid), ("count", &self.window_messages.to_string())], ) } SwitchKind::Resumed => { - let (count, hidden) = self.window_info; let sid = self.session_id.get(..8).unwrap_or(&self.session_id); - let mut label = tf( + tf( "resumed {id} · {count} messages", - &[("id", sid), ("count", &count.to_string())], - ); - if hidden > 0 { - label.push_str(t(" · earlier history: /timeline")); - } - label + &[("id", sid), ("count", &self.window_messages.to_string())], + ) } }; let line = boundary_line(&label, width); @@ -6506,7 +6525,7 @@ impl App { self.jump = Some(if pick { Jump::Block(id) } else { - Jump::Show(id) + Jump::Before(id) }); } } @@ -7392,7 +7411,7 @@ impl App { self.window_floor = if hidden > 0 { messages[hidden] } else { 0 }; self.history_floor = self.window_floor; self.load_more = true; - self.window_info = (messages.len() - hidden, hidden); + self.window_messages = messages.len() - hidden; true } @@ -7882,7 +7901,7 @@ impl App { self.window_floor = 0; self.history_floor = 0; self.load_more = false; - self.window_info = (0, 0); + self.window_messages = 0; self.history_request = None; self.awaiting_window = true; } @@ -7898,8 +7917,9 @@ impl App { self.history_floor = 0; self.load_more = false; self.reveal_pending = false; + self.full_history_section = false; self.landing = None; - self.window_info = (0, 0); + self.window_messages = 0; self.history_request = None; self.awaiting_window = true; self.pending_line = Some(line); @@ -7997,8 +8017,9 @@ impl App { self.history_floor = 0; self.load_more = false; self.reveal_pending = false; + self.full_history_section = false; self.landing = None; - self.window_info = (0, 0); + self.window_messages = 0; self.history_request = None; // Home has no window to wait for. self.awaiting_window = !self.session_id.is_empty(); @@ -8078,41 +8099,48 @@ impl App { } else if index < self.history_floor { self.history_request = Some((index, self.history_floor)); self.history_floor = index; + self.load_more = true; } else { self.set_notice(t("Already on screen above; /tui jumps to it")); } } - /// Fullscreen's load-more row: draws the previous page above the drawn - /// messages and keeps the oldest drawn message at the top of the view. - fn load_earlier(&mut self) { + fn reveal_earlier(&mut self) -> bool { let Some(snapshot) = &self.snapshot else { - return; + return false; }; - let floor = self.window_floor.min(snapshot.rows.len()); - let messages: Vec = snapshot.rows[..floor] + let floor = self.history_floor.min(snapshot.rows.len()); + if floor == 0 { + return false; + } + let start = snapshot.rows[..floor] .iter() .enumerate() + .rev() .filter(|(_, row)| row.kind.is_message()) - .map(|(i, _)| i) - .collect(); - if messages.is_empty() { - return; - } - let start = messages[messages.len().saturating_sub(HISTORY_WINDOW)]; + .nth(HISTORY_WINDOW - 1) + .map_or(0, |(i, _)| i); self.landing = snapshot.rows[floor..] .iter() .find(|row| row.kind == RowKind::UserMessage && row.line.is_none()) .map(|row| (row.row_id.clone(), false)); + if self.landing.is_none() { + self.jump = Some(Jump::Top); + } self.rebuild_window(start); + true } - /// Shows what comes before the drawn top, for PageUp at that top, the - /// load-more row and fullscreen `/earlier`: loaded rows first, a read from - /// the daemon when none are loaded, and nothing at the branch start. fn show_earlier(&mut self) { - if self.hidden_messages() > 0 { - self.load_earlier(); + if !self.fullscreen { + self.host.send(Command::Earlier { + line: self.target_line(), + session: self.target_session(), + all: true, + }); + return; + } + if self.reveal_earlier() { return; } let Some(snapshot) = &self.snapshot else { @@ -8123,63 +8151,25 @@ impl App { self.host.send(Command::Earlier { line: self.target_line(), session: self.target_session(), + all: false, }); self.reveal_pending = true; } Earlier::Reading => self.reveal_pending = true, - Earlier::AtStart => {} + Earlier::AtStart => self.set_notice(t("Beginning of conversation")), } } - /// Message rows loaded above `window_floor`, which the drawn window hides. fn hidden_messages(&self) -> usize { let Some(snapshot) = &self.snapshot else { return 0; }; - snapshot.rows[..self.window_floor.min(snapshot.rows.len())] + snapshot.rows[..self.history_floor.min(snapshot.rows.len())] .iter() .filter(|row| row.kind.is_message()) .count() } - /// Reveals the page an earlier read just prepended, keeping the oldest - /// drawn message at the top of the view. - fn reveal_prepended(&mut self) { - if self.hidden_messages() > 0 { - self.load_earlier(); - } - self.reveal_pending = false; - } - - /// The pending reveal, once a snapshot arrived. A prepended page is shown; - /// a read that ended without one drops the request, so a later unrelated - /// prepend is not revealed by it. A live-turn snapshot during the read - /// changes nothing, which is why `Earlier::Reading` keeps it. - fn apply_earlier(&mut self, previous: Option<&ViewSnapshot>) { - if !self.reveal_pending { - return; - } - let Some(snapshot) = &self.snapshot else { - return; - }; - // Rows were prepended when the old first row now sits below the top: a - // front trim changes the first row too and must not count. - let prepended = previous.is_some_and(|previous| { - previous.rows.first().is_some_and(|first| { - snapshot - .rows - .iter() - .position(|row| row.row_id == first.row_id) - .is_some_and(|index| index > 0) - }) - }); - if prepended { - self.reveal_prepended(); - } else if snapshot.earlier != Earlier::Reading { - self.reveal_pending = false; - } - } - /// Entering fullscreen: the shown line is drawn again from its window, /// earlier history scrollback drew page by page in order under the /// load-more row, so nothing else scrollback committed (an earlier @@ -8592,6 +8582,8 @@ impl App { } fn set_fullscreen(&mut self, on: bool) { + self.reveal_pending = false; + self.full_history_section = false; self.fullscreen = on; if on { self.redraw_window(); @@ -16301,9 +16293,8 @@ mod tests { "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" + drawn.app.window_messages, HISTORY_WINDOW, + "the window counts its visible messages" ); assert!( drawn @@ -19062,7 +19053,10 @@ mod tests { !text.contains("ask 19\n") && text.contains("ask 20"), "{text}" ); - assert!(text.contains("earlier history: /timeline"), "{text}"); + assert!( + text.find("/earlier").unwrap() < text.find("ask 20").unwrap(), + "{text}" + ); drawn.app.run_command("timeline", ""); assert!(matches!(drawn.app.prompt, Some(Prompt::Timeline(_)))); drawn.key(KeyCode::Home); @@ -19130,7 +19124,7 @@ mod tests { .iter() .position(|block| matches!(block, Block::User { text, .. } if text == "ask 130")) .expect("the old top is drawn again"); - assert_eq!(drawn.app.jump, Some(Jump::Show(drawn.app.dropped + kept))); + assert_eq!(drawn.app.jump, Some(Jump::Before(drawn.app.dropped + kept))); drawn.app.jump = None; drawn.app.open_card(LOAD_MORE); drawn.draw(); @@ -23579,7 +23573,7 @@ mod tests { /// `/earlier` at the drawn top asks for the page and draws it when it lands. #[test] - fn show_earlier_requests_unread_history_and_does_nothing_at_the_start() { + fn show_earlier_requests_unread_history_and_reports_the_start() { 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())); @@ -23647,61 +23641,25 @@ mod tests { drawn.app.show_earlier(); assert!(sent.borrow().is_empty(), "a read in flight is not repeated"); - // At the start nothing earlier exists and no read is in flight: a - // window opened on a short Session whose page it has not drawn yet. - // The call's frame is the window's first, so a floor it moved still - // changes the page; the twin draws without the call. - let at_start = || { - 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.app.snapshot = Some(ViewSnapshot { - session_id: "s1".into(), - rows: window_rows(HISTORY_WINDOW), - focus: "main".into(), - history_complete: true, - earlier: Earlier::AtStart, - ..ViewSnapshot::default() - }); - (drawn, sent) - }; - let (mut untouched, _) = at_start(); - untouched.draw(); - let page = untouched.transcript(); - assert!(page.contains("ask 0"), "the window draws its page: {page}"); - let (mut no_op, sent) = at_start(); - no_op.app.show_earlier(); + let mut drawn = Drawn::new((80, 40), None, true); + let (app, sent) = fullscreen_app(); + drawn.app = app; + drawn.app.show_earlier(); assert!(sent.borrow().is_empty(), "AtStart sends nothing"); - no_op.draw(); - assert_eq!(no_op.transcript(), page, "AtStart draws nothing"); + drawn.draw(); + assert!(drawn.transcript().contains("Beginning of conversation")); // A page that lands afterwards draws what it draws without the call: // the no-op armed no reveal. let mut rows = older_rows(HISTORY_WINDOW); rows.extend(window_rows(HISTORY_WINDOW)); - let later = |drawn: &mut Drawn| { - drawn.app.apply(Update::Snapshot(Box::new(ViewSnapshot { - session_id: "s1".into(), - rows: rows.clone(), - focus: "main".into(), - history_complete: true, - earlier: Earlier::AtStart, - ..ViewSnapshot::default() - }))); - drawn.draw(); - drawn.transcript() - }; - let text = later(&mut no_op); + show_window(&mut drawn, rows); + drawn.draw(); + let text = drawn.transcript(); assert!( !text.contains("older ") && text.contains("ask 0"), "the no-op armed no reveal: {text}" ); - assert_eq!( - text, - later(&mut untouched), - "a page landing after the no-op draws what it draws without it" - ); } #[test] diff --git a/crates/dimcode/tests/cli_flow/lines.rs b/crates/dimcode/tests/cli_flow/lines.rs index 410607dc00..9750ce5fc9 100644 --- a/crates/dimcode/tests/cli_flow/lines.rs +++ b/crates/dimcode/tests/cli_flow/lines.rs @@ -928,7 +928,7 @@ fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { terminal.until("on the line"); terminal.write(b"\r"); switch_seen.recv_timeout(PATIENCE).unwrap(); - terminal.until("Earlier content not loaded"); + terminal.until("Earlier messages · /earlier"); // A composer echo proves the interface applied what the reply queued // before it, the limitation notice among it. terminal.write(b"probe"); @@ -968,6 +968,8 @@ fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { assert!(attempts < 25, "the earlier read never started"); terminal.write(b"/earlier\r"); } + terminal.until("Full conversation history"); + terminal.until("older page"); terminal.write(b"/timeline\r"); terminal.until("#1 older page"); assert_eq!( diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index 8c00e56167..cbee0c2e35 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -767,10 +767,10 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() terminal.write(b"draft during history"); terminal.until("draft during history"); proceed.send(()).unwrap(); + terminal.until("Earlier messages · /earlier"); terminal.until("paged-message-150"); terminal.until("resumed paged"); terminal.until("75 messages"); - terminal.until("Earlier content not loaded"); // The window title names the session's first message; only the // screen is windowed. let screen = terminal @@ -784,12 +784,13 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() "resume_on_launch={resume_on_launch}: {}", terminal.transcript ); - // A `/timeline` jump to the first message draws the earlier history. terminal.write(b"\r/earlier\r"); + terminal.until("Full conversation history"); + for index in 1..=150 { + terminal.until(&format!("paged-message-{index:03}")); + } terminal.write(b"/timeline\r"); terminal.until("#150"); - terminal.write(b"\x1b[H\r"); - terminal.until("paged-message-001"); home.kill(&terminal); terminal.wait(); daemon.join().unwrap(); diff --git a/crates/dimcode/tests/cli_flow/windows.rs b/crates/dimcode/tests/cli_flow/windows.rs index 2611c55b7c..97ec277e18 100644 --- a/crates/dimcode/tests/cli_flow/windows.rs +++ b/crates/dimcode/tests/cli_flow/windows.rs @@ -223,7 +223,7 @@ fn an_orphan_tool_result_reads_its_arguments_only_after_expanding_details() { wire.hold(); }); let mut terminal = Terminal::resume_tui(home.command()); - terminal.until("Earlier content not loaded"); + terminal.until("Earlier messages · /earlier"); terminal.write(b"/tools\r"); terminal.write(b"/tools\r"); terminal.until("point-read origin arguments"); diff --git a/docs/architecture/tui-e2e.md b/docs/architecture/tui-e2e.md index 297d9140a1..d797d565cf 100644 --- a/docs/architecture/tui-e2e.md +++ b/docs/architecture/tui-e2e.md @@ -100,6 +100,7 @@ daemon. `--keep` leaves the home and raw streams in place for inspection. | Area | Scenario | Verifies | | --- | --- | --- | +| terminal-modes | `earlier_reveals_resumed_history_in_both_modes` | Scrollback reprints all turns in order without clearing, switching screens or losing the draft; fullscreen reveals the preceding page at the join and reports the beginning | | terminal-modes | `scrollback_streams_and_exits_cleanly` | The default scrollback mode, streamed answer, committed history, `/exit`, `Bye!`, exit 0, no alternate screen, cursor restored, OSC 7501 working/clear | | terminal-modes | `fullscreen_switches_screens_and_restores_the_terminal` | Fullscreen takes the alternate screen; `/tui` leaves and re-enters it; the multiplexer's `ModifyOtherKeys` enable/reset pair appears and balances; the last screen switch is a leave, so the final exit cannot lean on the first `/tui` | | terminal-modes | `fullscreen_tool_body_click_collapses_only_its_node` | Fullscreen opens a tool batch and `exec` call via SGR mouse clicks, verifies drag, double-click, bracketed paste, and a near-deadline resize do not collapse it, and verifies clicking an output row in a scrolled 92×14 pane collapses only that call while re-anchoring its header and the reply below in view | diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index 8360bc4d7e..4cc63e1668 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -3809,9 +3809,11 @@ the turn settled, while a result read before its call asks nothing. ### Loading earlier conversation -`/earlier` reads the next bounded older window for the shown branch, retaining its original -cutoff and advancing its backward cursor. Fullscreen PageUp at the loaded top runs the same -action. TUI prepends projected rows; line mode prints a labelled older segment. Neither changes +`/earlier` reads bounded older windows for the shown branch, retaining its original +cutoff and advancing its backward cursor. Scrollback reads to the beginning and prints the +whole conversation oldest first under a new label, without switching screens. Fullscreen +reveals one page at the join; scrolling up or pressing PageUp at the drawn top does the same. +Line mode prints a labelled older segment. None changes live event/state cutoffs or resubmits an input. Opening uses the separate read-stop and whole-page retention budgets in the [client window contract](clients.md#opening-a-conversation-with-a-bounded-window); additional older rows are retained only when the user explicitly loads them. Raw pages are released diff --git a/docs/design/timeline-ui.md b/docs/design/timeline-ui.md index 917c3c234e..faff3ad28a 100644 --- a/docs/design/timeline-ui.md +++ b/docs/design/timeline-ui.md @@ -128,7 +128,9 @@ The Timeline's points are its user messages. Tab walks them one at a time from t - `Enter` opens a bordered action list naming the selected message: Jump to message, Edit as a new draft, Quote message, Create branch from here, Fork session. The fork choice states that its cut is before the selected message. Up/Down and Enter select an action; numbers 1–5 select directly. Existing `e`, `q`, `b` and `f` shortcuts work in both lists. Esc returns to the message list with its selection and list position intact, then closes it. Fullscreen shows the lists as overlays; scrollback shows them in the live interaction region without committing them to history. - Jump closes the panel. Fullscreen picks the message, as Tab would, and the pick keys apply. Scrollback cannot move up: a message it has not drawn yet is drawn from there on as an earlier-history page; one already drawn gets a notice that `/tui` can jump to it. -A resume draws the newest 100 messages. Fullscreen tops the transcript with a load-more row (`↑ 130 earlier messages · Enter or click to load`). Activating it (a click, or Tab up to it and `Enter`), PageUp at the drawn top, and `/earlier` all draw the previous 100 messages above the drawn ones, reading them from the daemon when none are loaded, and keep the oldest drawn message at the top of the view. Scrollback has no such row; its earlier history comes from `/timeline` jumps. This replaces `/history`, which paged earlier messages in after the newest ones. +A resume draws up to 100 messages from the latest window. The paging hint appears only above the oldest drawn message. In scrollback, `/earlier` starts a section labelled “Full conversation history” in the same terminal. It prints the shown branch from the beginning, oldest first, including the recent messages already printed above the label. Live output continues below. This does not reattach the Session, submit the draft or clear shell scrollback. + +In fullscreen, `/earlier` reveals the preceding page at the join, using loaded messages before requesting older ones. Scrolling up or pressing PageUp at the drawn top loads another page. At the start, requesting another page reports that there is no older conversation. ### 4.7 `/branch ` and the side panel diff --git a/docs/zh/design/timeline-ui.md b/docs/zh/design/timeline-ui.md index 5f5aea982b..d0e04f10cc 100644 --- a/docs/zh/design/timeline-ui.md +++ b/docs/zh/design/timeline-ui.md @@ -128,7 +128,9 @@ Timeline 的点就是它的用户消息。Tab 从最新一条起逐条走;`/ti - `Enter` 打开操作列表,写明所选消息,列出跳转、编辑为新草稿、引用、创建分支、派生会话;派生选项说明切点在该消息之前。↑↓ 和 Enter 选择,数字 1–5 直接执行;原有 `e`、`q`、`b`、`f` 在两个列表都可用。Esc 返回消息列表,保留所选消息和列表位置,再按 Esc 关闭。scrollback 在 live 交互区显示,fullscreen 显示为 overlay,均不提交到历史。 - 跳转会关闭面板。全屏选中这条消息,与 Tab 选中一样,之后可用选取的按键。scrollback 不能往上走:还没画出的消息从它开始作为一页更早历史画出;已经画出的给出提示,`/tui` 可直接跳到它。 -恢复会话时只画最新 100 条。全屏在 transcript 顶部放一行加载按钮(`↑ 130 earlier messages · Enter or click to load`)。点击它(或用 Tab 走到它再按 `Enter`)、在画出的顶部按 PageUp、或输入 `/earlier`,都会在已画出的消息上方画出前 100 条,没有加载过的就向 daemon 读取,并让原来最早的那条消息留在视图顶部。scrollback 没有这一行,更早的历史由 `/timeline` 跳转画出。它取代了 `/history`:后者把更早的消息接在最新消息之后翻页画出。 +恢复会话时从最近的窗口显示最多 100 条消息。翻页提示只在已显示的最早一条消息上方。Scrollback 的 `/earlier` 在原终端另起一段「完整历史」,从第一条开始按时间顺序打印当前分支的对话,包含分隔线上方已经显示过的近期消息。新消息接在末尾;不切屏、不清屏、不重新连接会话,也不提交草稿。 + +Fullscreen 的 `/earlier` 显示上一页,优先使用已经读入的消息,不够再向 daemon 请求,并停在新旧两页的交界处。在顶部继续向上滚动或按 PageUp 可加载上一页。已经到头时,再翻页会提示已到对话开头。 ### 4.7 `/branch ` 与侧面板 diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index e73a823a22..5e428bbd6f 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -247,6 +247,71 @@ async function checkDeviceDraftDestination(terminal, devicesOverDraft) { } const scenarios = [ + { + name: 'earlier_reveals_resumed_history_in_both_modes', + area: 'terminal-modes', + title: 'Replay the full conversation in native scrollback and page in place in fullscreen', + async run(tui) { + await tui.setup({respond: () => ({text: ANSWER})}); + let session; + for (let turn = 1; turn <= 16; turn++) { + const output = await tui.runCommandAsync([ + '--home', tui.home, '--model-config', tui.modelFile, 'exec', ...(session ? ['resume', session] : []), + '--json', '-p', `history-turn-${String(turn).padStart(2, '0')}`, + ]); + session ??= output.trim().split('\n').map((line) => JSON.parse(line).params?.sessionId).find(Boolean); + assert(session, 'all turns belong to one Session'); + } + for (const fullscreen of [true, false]) { + const terminal = await tui.launch(['--resume', session, ...(fullscreen ? ['--fullscreen'] : [])], {rows: 40}); + const initial = await terminal.waitFor(/resumed .* messages/, {history: true}); + assert(initial.includes('history-turn-16') && !initial.includes('history-turn-10'), initial); + const hint = 'Earlier messages · /earlier'; + assert(initial.includes(hint) && initial.indexOf(hint) < initial.search(/┃ history-turn-/), initial); + assert(!/earlier|\/timeline/i.test(initial.slice(initial.indexOf('resumed '))), initial); + if (fullscreen) { + terminal.send('/earlier'); + } else { + terminal.send('draft stays here'); + terminal.key('C-o'); + await terminal.waitFor('Suggestions'); + terminal.send('earlier'); + } + terminal.key('Enter'); + if (!fullscreen) { + const replay = await terminal.waitFor(/Full conversation history[\s\S]*┃ history-turn-16[\s\S]*draft stays here/, {history: true}); + const [before, after] = replay.split('Full conversation history'); + const turns = (text) => [...text.matchAll(/┃ history-turn-(\d+)/g)].map((m) => Number(m[1])); + assert.deepEqual(turns(before), turns(initial)); + assert.deepEqual(turns(after), Array.from({length: 16}, (_, i) => i + 1)); + assert.deepEqual(after.match(/┃ history-turn-\d+|The fixture answer is deterministic\./g), + Array.from({length: 16}, (_, i) => [`┃ history-turn-${String(i + 1).padStart(2, '0')}`, ANSWER]).flat()); + assert(!/\x1b\[\?(?:47|1047|1049)h|\x1b\[3J/.test(terminal.raw()), 'no alternate screen or cleared scrollback'); + terminal.key('Enter'); + const live = await terminal.waitFor(/┃ draft stays here[\s\S]*The fixture answer is deterministic\./, {history: true}); + assert.equal(live.split('Full conversation history').length, 2); + assert.equal(live.split('┃ draft stays here').length, 2); + await exitWith(terminal); + continue; + } + const join = await terminal.waitFor('history-turn-10'); + assert(!join.includes('history-turn-01'), `the viewport lands at the join: ${join}`); + terminal.key('Home'); + const oldest = await terminal.waitFor('history-turn-01'); + terminal.key('End'); + const newest = await terminal.waitFor('history-turn-16'); + for (const page of [oldest, join, newest]) { + const turns = [...page.matchAll(/┃ history-turn-(\d+)/g)].map((m) => Number(m[1])); + assert(turns.length >= 2 && turns.every((n, i) => !i || n === turns[i - 1] + 1), page); + } + terminal.key('Home'); + await terminal.waitFor('history-turn-01'); + terminal.key('PPage'); + await terminal.waitFor('Beginning of conversation'); + await exitWith(terminal); + } + }, + }, { name: 'scrollback_streams_and_exits_cleanly', area: 'terminal-modes', From 583da0593a7b98a7e1f3b137d02adbe7deb0ffac Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 14:00:48 +0800 Subject: [PATCH 02/13] fix(tui): replay scrollback history in one forward pass Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/src/model/session.rs | 7 +- crates/dim-cli/src/projection.rs | 44 +++-- crates/dim-cli/src/session_host.rs | 26 +-- crates/dim-cli/src/session_host/tasks.rs | 239 +++++++++++++++++++++-- crates/dim-cli/src/ui/tui.rs | 118 +++++++++-- crates/dimcode/tests/cli_flow/lines.rs | 64 +++--- crates/dimcode/tests/cli_flow/tasks.rs | 121 ++++++++---- docs/design/cli-commands.md | 10 +- docs/design/timeline-ui.md | 2 +- docs/zh/design/timeline-ui.md | 2 +- 10 files changed, 480 insertions(+), 153 deletions(-) diff --git a/crates/dim-cli/src/model/session.rs b/crates/dim-cli/src/model/session.rs index ed2028e7f5..1c1df2720c 100644 --- a/crates/dim-cli/src/model/session.rs +++ b/crates/dim-cli/src/model/session.rs @@ -1334,8 +1334,13 @@ impl DeleteOutcome { } } +pub struct HistoryReplay { + pub rows: Vec>, + pub window: Vec>, +} + pub enum Update { - ReplayHistory, + ReplayHistory(HistoryReplay), Reportable { error: crate::report::Captured, show_error: bool, diff --git a/crates/dim-cli/src/projection.rs b/crates/dim-cli/src/projection.rs index 5c9cfaee63..4e6344419a 100644 --- a/crates/dim-cli/src/projection.rs +++ b/crates/dim-cli/src/projection.rs @@ -29,6 +29,11 @@ use crate::wire::{Event, EventContent, Progress, WorkflowRun, WorkflowState}; mod thinking; +#[cfg(test)] +thread_local! { + pub(crate) static REPLAY_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Reasoning that is still arriving: the row shows what the Timeline holds /// plus the progress not written yet. struct OpenThought { @@ -55,7 +60,7 @@ pub struct Projection { /// 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. - messages: HashMap>, + messages: HashMap>, /// Each line's user messages withdrawn later, by input id and the sequence /// that withdrew them: a cut before that sequence still counts the /// message, whichever page carried the input or the withdrawal. @@ -141,10 +146,11 @@ impl Projection { pub fn line_event(&mut self, parent: &str, event: &Event) { match &event.content { EventContent::Input(data) if data.user.is_some() => { - let messages = self.messages.entry(parent.to_owned()).or_default(); - if !messages.iter().any(|(id, _)| *id == event.id) { - messages.push((event.id.clone(), event.sequence)); - } + self.messages + .entry(parent.to_owned()) + .or_default() + .entry(event.id.clone()) + .or_insert(event.sequence); } EventContent::InputDeleted(data) => { let withdrawals = self.withdrawals.entry(parent.to_owned()).or_default(); @@ -232,11 +238,11 @@ impl Projection { messages .iter() .filter(|(id, at)| { - *at <= sequence + **at <= sequence && self .withdrawals .get(branch) - .and_then(|withdrawals| withdrawals.get(id)) + .and_then(|withdrawals| withdrawals.get(*id)) .is_none_or(|withdrawn| *withdrawn > sequence) }) .count() @@ -311,6 +317,8 @@ impl Projection { } fn fold(&mut self, branch_id: &str, event: &Event, replayed: bool) { + #[cfg(test)] + REPLAY_WORK.set(REPLAY_WORK.get() + 1); match &event.content { EventContent::ToolCall(data) => { self.questions @@ -903,6 +911,12 @@ impl Projection { } pub fn snapshot(&self) -> ViewSnapshot { + self.snapshot_with_rows(&self.rows) + } + + pub fn snapshot_with_rows(&self, rows: &[Arc]) -> ViewSnapshot { + #[cfg(test)] + REPLAY_WORK.set(REPLAY_WORK.get() + rows.len()); let mut pending: Vec<_> = self.user_queue().collect(); pending.sort_by_key(|input| (!input.applied, input.sequence)); let queued = pending @@ -919,7 +933,7 @@ impl Projection { }) .collect(); ViewSnapshot { - rows: self.rows.clone(), + rows: rows.to_vec(), running: self.running, approvals: self.approvals.clone(), questions: self.questions.calls().cloned().collect(), @@ -1343,11 +1357,11 @@ impl Projection { older.name_agents(self.agent_names.clone(), Vec::new()); self.name_agents(older.agent_names.clone(), Vec::new()); older.rows.retain(|row| { - if let Some(existing) = self - .rows - .iter_mut() - .find(|existing| existing.row_id == row.row_id) - { + if let Some(existing) = self.rows.iter_mut().find(|existing| { + #[cfg(test)] + REPLAY_WORK.set(REPLAY_WORK.get() + 1); + existing.row_id == row.row_id + }) { if matches!( row.kind, RowKind::AssistantMessage | RowKind::StreamingAssistant @@ -1479,6 +1493,10 @@ impl Projection { &self.rows } + pub fn into_rows(self) -> Vec> { + self.rows + } + /// The lines `main` recorded, without `main` itself (design §14). pub fn directory(&mut self, entry: &dim_client::wire::BranchEntry) { if entry.branch_id == ROOT_BRANCH_ID { diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index e97eacb449..4e08b8da87 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -52,7 +52,7 @@ mod report; mod tasks; mod workflow; use member::Members; -use tasks::{BranchHistory, HistoryRequest, StopBatch}; +use tasks::{BranchHistory, HistoryRequest, Replay, StopBatch}; use workflow::WorkflowReads; const PUBLISH_INTERVAL: Duration = Duration::from_millis(16); @@ -328,6 +328,7 @@ struct Worker { task_history_queue: std::collections::VecDeque, /// A stale request still occupies this slot until its reply arrives. task_history_request: Option, + replay: Option, methods: std::collections::HashSet, report_generations: std::collections::HashMap, model_through: u64, @@ -832,6 +833,7 @@ impl Worker { task_history: Default::default(), task_history_queue: Default::default(), task_history_request: None, + replay: None, methods: Default::default(), report_generations: Default::default(), model_through: 0, @@ -2030,10 +2032,11 @@ impl Worker { Command::Rename(title) => self.rename(title).await, Command::Earlier { line, all, .. } => { if !self.earlier_member() { - if let Some(history) = self.task_history.get_mut(&line) { - history.replay_all |= all; + if all { + self.replay.get_or_insert_with(|| Replay::new(line)); + } else { + self.earlier(&line); } - self.earlier(&line); } } Command::Goal { request, .. } => self.goal(request).await, @@ -5619,14 +5622,13 @@ impl Worker { .values() .any(|line| line.projection.held_input(id).is_some()) }); - let mut snapshot = match self - .lines - .get(&self.focus) - .filter(|_| self.focus != ROOT_BRANCH_ID) - { - Some(line) => line.projection.snapshot(), - None => self.projection.snapshot(), - }; + let shown = self.shown(); + let rows = self + .replay + .as_ref() + .and_then(|r| r.window(&self.focus)) + .unwrap_or(shown.rows()); + let mut snapshot = shown.snapshot_with_rows(rows); snapshot.lines = self.line_views(); snapshot.unread_lines = snapshot .lines diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 333e1c9bb6..30f43cdd1b 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -24,7 +24,6 @@ pub(super) struct BranchHistory { inventory_cursor: Option, goal_stale: bool, earlier: EarlierRead, - pub(super) replay_all: bool, pub running: Option, pub latest_reply: u64, pub seen_reply: u64, @@ -52,12 +51,52 @@ pub(super) struct HistoryRequest { enum ReadStage { History, + Replay, Cut, Inventory(&'static str), Goal, ToolOrigin { request_id: String, call_id: String }, } +pub(super) struct Replay { + branch: String, + after: u64, + through: Option, + projection: Projection, + window: Vec>, +} + +impl Replay { + pub(super) fn window( + &self, + branch: &str, + ) -> Option<&[std::sync::Arc]> { + (self.branch == branch && self.through.is_some()).then_some(&self.window) + } + + pub(super) fn new(branch: String) -> Self { + Self { + projection: Projection::for_branch(&branch), + branch, + after: 0, + through: None, + window: Vec::new(), + } + } + + fn page(&mut self, page: crate::wire::History) -> crate::Result { + let next = page.next(self.after, self.through)?; + for value in page.events { + self.projection + .replay(&self.branch, &serde_json::from_value(value)?); + } + if let Some(after) = next { + self.after = after; + } + Ok(next.is_none()) + } +} + pub(super) struct StopBatch { session_id: String, projection_id: u64, @@ -108,6 +147,7 @@ impl Worker { self.side = None; self.lines.clear(); self.task_history.clear(); + self.replay = None; self.task_history_queue.clear(); self.workflow.clear(); if let Some(request) = &mut self.task_history_request { @@ -289,12 +329,7 @@ impl Worker { return; } if history.window.before.is_none() { - if std::mem::take(&mut history.replay_all) { - self.publish(); - self.send(Update::ReplayHistory); - } else { - self.send(Update::Notice("Beginning of conversation".into())); - } + self.send(Update::Notice("Beginning of conversation".into())); return; } history.earlier = EarlierRead::Reading; @@ -323,9 +358,79 @@ impl Worker { } pub(super) async fn poll_task_history(&mut self) -> crate::Result<()> { + if self + .replay + .as_ref() + .is_some_and(|r| r.branch != self.focus || self.members.selected.is_some()) + { + self.replay = None; + if let Some(request) = &mut self.task_history_request + && matches!(request.stage, ReadStage::Replay) + { + request.current = false; + } + self.changed(); + } if self.task_history_request.is_some() || self.session_id.is_empty() { return Ok(()); } + if let Some(replay) = &mut self.replay + && self + .task_history + .get(&replay.branch) + .is_some_and(|h| h.done) + { + let through = *replay.through.get_or_insert_with(|| { + if let Some(p) = + transcript_mut(&mut self.projection, &mut self.lines, &replay.branch) + { + replay.window = p.rows().to_vec(); + } + self.cursors.get(&replay.branch).copied().unwrap_or(0) + }); + let method = if self + .client + .supports(&["session.history.display", "session.history.detail"]) + { + "session.history.display" + } else { + "session.history" + }; + let branch_id = replay.branch.clone(); + #[derive(serde::Serialize)] + #[serde(rename_all = "camelCase")] + struct Page<'a> { + session_id: &'a str, + branch_id: &'a str, + after: u64, + through: u64, + limit: u32, + } + let params = serde_json::to_value(Page { + session_id: &self.session_id, + branch_id: &branch_id, + after: replay.after, + through, + limit: 256, + })?; + match self.client.send(method, params).await { + Ok(id) => { + self.task_history_request = Some(HistoryRequest { + id, + session_id: self.session_id.clone(), + branch_id, + current: true, + stage: ReadStage::Replay, + }) + } + Err(error) => { + self.replay = None; + self.report(error.to_string(), true); + self.changed(); + } + } + return Ok(()); + } if let Some(branch) = self .task_history .iter() @@ -519,6 +624,39 @@ impl Worker { if !request.current || request.session_id != self.session_id { return Ok(()); } + if matches!(request.stage, ReadStage::Replay) { + let Some(mut replay) = self.replay.take() else { + return Ok(()); + }; + let result = result.map_err(crate::Error::from).and_then(|value| { + let page = if self + .client + .supports(&["session.history.display", "session.history.detail"]) + { + serde_json::from_value::(value)?.into() + } else { + serde_json::from_value(value)? + }; + replay.page(page) + }); + match result { + Ok(false) => self.replay = Some(replay), + Ok(true) => { + self.send(Update::ReplayHistory( + crate::model::session::HistoryReplay { + rows: replay.projection.into_rows(), + window: replay.window, + }, + )); + self.publish(); + } + Err(error) => { + self.report(error.to_string(), true); + self.changed(); + } + } + return Ok(()); + } if let ReadStage::ToolOrigin { request_id, call_id, @@ -603,7 +741,10 @@ impl Worker { } history.inventory_cursor = next; } - ReadStage::History | ReadStage::Goal | ReadStage::ToolOrigin { .. } => { + ReadStage::History + | ReadStage::Replay + | ReadStage::Goal + | ReadStage::ToolOrigin { .. } => { unreachable!() } } @@ -734,29 +875,18 @@ impl Worker { self.send(Update::NoModel); } } - if window_ready && !self.continue_replay(&request.branch_id) { + if window_ready { self.publish(); } Ok(()) } - fn continue_replay(&mut self, branch: &str) -> bool { - let history = self.task_history.get_mut(branch).expect("loaded history"); - history.replay_all &= self.focus == branch && self.members.selected.is_none(); - if history.done && history.replay_all { - self.earlier(branch); - return true; - } - false - } - /// 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()); - history.replay_all = false; if history.earlier == EarlierRead::Reading { history.earlier = EarlierRead::Failed; } else if !history.done && !history.window_complete { @@ -801,7 +931,6 @@ impl Worker { self.task_event(branch, event); } } - self.continue_replay(branch); self.changed(); } @@ -973,6 +1102,74 @@ mod tests { serde_json::from_value(text(sequence, request, delta)).expect("a text event") } + #[tokio::test] + async fn full_replay_stitches_split_thoughts_with_a_linear_projection_budget() { + use crate::projection::REPLAY_WORK; + let (mut worker, updates, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + worker.session_id = "s1".into(); + worker.discover_branch("main"); + worker.task_history.get_mut("main").unwrap().done = true; + const HEAD: u64 = 4098; + worker.apply("main", event(HEAD, "tail", "last")); + REPLAY_WORK.set(0); + worker + .command(Command::Earlier { + line: "main".into(), + session: Origin::Session("s1".into()), + all: true, + }) + .await + .unwrap(); + for after in (0..HEAD).step_by(256) { + worker.poll_task_history().await.unwrap(); + let end = (after + 256).min(HEAD); + let events: Vec<_> = (after + 1..=end) + .map(|seq| { + let mut value = text( + seq, + &format!("r-{}", (seq - 1) / 3), + ["first ", "second", "answer"][((seq - 1) % 3) as usize], + ); + if seq % 3 != 0 { + value["name"] = json!("thinking"); + } + value + }) + .collect(); + answer( + &mut worker, + json!({"events":events,"through":HEAD,"nextAfter":end,"done":end==HEAD}), + ) + .await; + } + let rows = updates + .try_iter() + .find_map(|u| match u { + Update::ReplayHistory(r) => Some(r.rows), + _ => None, + }) + .unwrap(); + assert_eq!(rows.len(), (HEAD / 3 * 2) as usize); + for [thought, answer] in rows.as_chunks::<2>().0 { + assert_eq!(thought.text, "first second"); + assert!(!thought.streaming); + assert_eq!(answer.text, "answer"); + } + assert!( + REPLAY_WORK.get() <= 2 * HEAD as usize, + "{} event folds, row comparisons and snapshot row copies", + REPLAY_WORK.get() + ); + REPLAY_WORK.set(0); + worker.apply("main", event(HEAD + 1, "next", "live")); + worker.publish(); + assert!( + REPLAY_WORK.get() < 10, + "a live update must not copy the replay" + ); + } + /// One user message, as the daemon sends it on the wire and in a page. fn said(sequence: u64, message: &str) -> serde_json::Value { json!({ diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index aaa9518172..bf5f33387d 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -1421,7 +1421,7 @@ struct App { /// `show_earlier`, cleared once the page is shown or the read ends /// without one. reveal_pending: bool, - full_history_section: bool, + replay_rows: Option, /// The user message a `/timeline` jump or a loaded page lands on, once /// drawn: `(row id, pick it)`. landing: Option<(String, bool)>, @@ -1901,7 +1901,7 @@ impl App { history_floor: 0, load_more: false, reveal_pending: false, - full_history_section: false, + replay_rows: None, landing: None, startup_session: None, awaiting_window: false, @@ -2768,11 +2768,9 @@ impl App { self.set_notice(text); } } - Update::ReplayHistory => { + Update::ReplayHistory(rows) => { if !self.fullscreen { - self.rebuild_window(0); - self.load_more = false; - self.full_history_section = true; + self.replay_rows = Some(rows); } } Update::Snapshot(snapshot) => { @@ -6406,16 +6404,8 @@ impl App { self.banner_committed = true; } let ready = self.arm_window(); - if ready && std::mem::take(&mut self.full_history_section) { - let block = Block::Boundary(t("Full conversation history").into()); - frame.commits.push(chunk(&render_block( - &block, - width, - &self.palette, - &self.markdown, - false, - ))); - self.record(block); + if ready && let Some(rows) = self.replay_rows.take() { + self.draw_replay(rows, width, &mut frame); } if ready && let Some(shown) = self.pending_line.take() { let lines = self.snapshot.as_ref().map_or(&[][..], |s| &s.lines[..]); @@ -7415,6 +7405,62 @@ impl App { true } + fn draw_replay( + &mut self, + replay: crate::model::session::HistoryReplay, + width: usize, + frame: &mut Frame, + ) { + let rows = replay.rows; + let mut common = rows + .iter() + .rev() + .zip(replay.window.iter().rev()) + .take(HISTORY_WINDOW) + .take_while(|(a, b)| a == b || a.row_id == b.row_id && (a.streaming || a.pending)) + .count(); + while common > 0 + && rows[rows.len() - common].kind == RowKind::ToolCall + && !opens_group(&rows, rows.len() - common) + { + common -= 1; + } + let skipped = replay.window.len() - common; + let floor = skipped + .checked_sub(1) + .and_then(|index| { + self.snapshot + .as_ref()? + .rows + .iter() + .position(|r| r.row_id == replay.window[index].row_id) + }) + .map_or(0, |index| index + 1); + self.rebuild_window(floor); + self.load_more = false; + let tool_detail = self.tool_detail; + let thinking_detail = self.thinking_detail; + let mut write = |block| { + let lines = render_block(&block, width, &self.palette, &self.markdown, false); + if !lines.is_empty() { + frame.commits.push(chunk(&lines)); + self.record(block); + } + }; + write(Block::Boundary(t("Full conversation history").into())); + for (index, row) in rows[..rows.len() - common].iter().enumerate() { + if row.kind == RowKind::ToolCall && !opens_group(&rows, index) { + continue; + } + let detail = if row.kind == RowKind::Thinking { + thinking_detail + } else { + tool_detail + }; + write(project_row(&rows, index, detail)); + } + } + fn thought_frames(&mut self, width: usize) -> HashMap { let mut frames = HashMap::new(); let Some(snapshot) = &self.snapshot else { @@ -7917,7 +7963,7 @@ impl App { self.history_floor = 0; self.load_more = false; self.reveal_pending = false; - self.full_history_section = false; + self.replay_rows = None; self.landing = None; self.window_messages = 0; self.history_request = None; @@ -8017,7 +8063,7 @@ impl App { self.history_floor = 0; self.load_more = false; self.reveal_pending = false; - self.full_history_section = false; + self.replay_rows = None; self.landing = None; self.window_messages = 0; self.history_request = None; @@ -8583,7 +8629,7 @@ impl App { fn set_fullscreen(&mut self, on: bool) { self.reveal_pending = false; - self.full_history_section = false; + self.replay_rows = None; self.fullscreen = on; if on { self.redraw_window(); @@ -23571,6 +23617,40 @@ mod tests { ); } + #[test] + fn scrollback_replay_before_first_frame_keeps_the_whole_prefix_and_live_tail() { + let mut drawn = Drawn::new((80, 40), None, true); + drawn.app.switch_session("s1".into(), SwitchKind::Resumed); + let rows = window_rows(151); + let window = rows[45..150].to_vec(); + show_window(&mut drawn, rows[45..].to_vec()); + drawn.app.apply(Update::ReplayHistory( + crate::model::session::HistoryReplay { + rows: rows[..150].to_vec(), + window, + }, + )); + let frame = drawn.app.frame((80, 40)); + let text = crate::sanitize::safe(&frame.commits.join("\n")); + let (_, mut rest) = text.split_once("Full conversation history").unwrap(); + for n in 0..=150 { + let label = format!("ask {n}"); + rest = rest + .split_once(&label) + .unwrap_or_else(|| panic!("missing {label}")) + .1; + } + assert_eq!(text.matches("ask ").count(), 151); + assert!( + !drawn + .app + .frame((80, 40)) + .commits + .join("\n") + .contains("ask ") + ); + } + /// `/earlier` at the drawn top asks for the page and draws it when it lands. #[test] fn show_earlier_requests_unread_history_and_reports_the_start() { diff --git a/crates/dimcode/tests/cli_flow/lines.rs b/crates/dimcode/tests/cli_flow/lines.rs index 9750ce5fc9..9573fe8ba9 100644 --- a/crates/dimcode/tests/cli_flow/lines.rs +++ b/crates/dimcode/tests/cli_flow/lines.rs @@ -797,10 +797,10 @@ fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { "session.branch.get", "session.catalog", ]); - fn page(through: u64, before: u64, events: Vec) -> Value { - json!({"events":events,"through":through,"nextAfter":through, - "nextBefore":before,"done":true}) - } + let events = [ + said(1, "older page"), applied(2, "input-1"), consumed(3, "input-1"), + said(4, "resumed line"), applied(5, "input-4"), consumed(6, "input-4"), + ]; // Answers the inventory reads that follow a window, through the line's // turn read that finishes it. fn inventory(wire: &mut Wire) { @@ -865,42 +865,21 @@ fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { "session.history" if branch != "line-1" => { wire.reply(&request, history(8, vec![])); } + "session.history" if request["params"].get("after").is_some() => { + assert_eq!(request["params"], json!({"sessionId":"on-the-line","branchId":"line-1","after":0,"through":6,"limit":256})); + wire.reply(&request, history(6, events.to_vec())); + asked.send(()).unwrap(); + break; + } "session.history" => { - let before = request["params"] - .get("before") - .and_then(serde_json::Value::as_u64); - match before { - // The resumed window, and later the line opened for - // view: one page that leaves older content unread. - None => { - wire.reply( - &request, - page( - 6, - 3, - vec![ - said(4, "resumed line"), - applied(5, "input-4"), - consumed(6, "input-4"), - ], - ), - ); - inventory(wire); - windows += 1; - if windows == 1 { - window.send(()).unwrap(); - } - } - // `/earlier`: the page that reaches the branch start. - Some(3) => { - wire.reply( - &request, - page(6, 1, vec![said(1, "older page"), applied(2, "input-1")]), - ); - asked.send(()).unwrap(); - break; - } - other => panic!("unexpected earlier cursor {other:?}: {request}"), + assert!(request["params"].get("before").is_none(), "{request}"); + let mut window_page = history(6, events[3..].to_vec()); + window_page["nextBefore"] = json!(4); + wire.reply(&request, window_page); + inventory(wire); + windows += 1; + if windows == 1 { + window.send(()).unwrap(); } } "session.catalog" => wire.reply( @@ -970,8 +949,9 @@ fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { } terminal.until("Full conversation history"); terminal.until("older page"); + terminal.until("resumed line"); terminal.write(b"/timeline\r"); - terminal.until("#1 older page"); + terminal.until("#1 resumed line"); assert_eq!( reported(&terminal), 1, @@ -1946,7 +1926,9 @@ fn tui_earlier_typed_before_a_queued_move_loads_no_new_centre() { "session.branch.get" => wire.reply(&request, entry("line-1", "main")), "session.history" => { let through = if branch == "line-1" { 3 } else { 8 }; - if request["params"].get("before").is_some() { + if request["params"].get("before").is_some() + || request["params"].get("after").is_some() + { earlier.send(request["params"].clone()).unwrap(); } wire.reply(&request, history(through, vec![])); diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index cbee0c2e35..2bd8425bf4 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -256,7 +256,9 @@ fn tui_lines_count_a_cut_read_from_a_transcript_window() { } } }); - let mut terminal = Terminal::resume_tui(home.command()); + let mut command = home.command(); + command.arg("--fullscreen"); + let mut terminal = Terminal::resume_tui(command); terminal.until("test / model"); terminal.write(b"/lines\r"); terminal.until("parser race"); @@ -675,14 +677,22 @@ fn event(wire: &mut Wire, branch: &str, event: Value) { #[test] fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() { - for resume_on_launch in [true, false] { + const WINDOW_HEAD: usize = 384 * 7; + const THROUGH: usize = WINDOW_HEAD + 1; + for (resume_on_launch, display) in [(true, true), (false, false)] { let home = Home::new(); let workspace = std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap(); let workspace = workspace.to_string_lossy().into_owned(); let (ready, readiness) = std::sync::mpsc::channel(); let (proceed, control) = std::sync::mpsc::channel(); let daemon = home.daemon(move |wire| { - wire.hello(&[]); + let (method, field) = if display { + wire.hello(&["session.history.display", "session.history.detail", "session.history.display.tail"]); + ("session.history.display", "items") + } else { + wire.hello(&[]); + ("session.history", "events") + }; if !resume_on_launch { let attach = wire.read("session.attach"); wire.reply(&attach, attach_record(&attach)); @@ -713,7 +723,7 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() wire.reply(&attach, json!({"sessionId":"paged","cwd":"/workspace", "model":{"providerId":"test","modelId":"restored-model"},"createdAt":1, "running":false,"sequence":0,"attachedClients":1})); - let first = wire.read("session.history"); + let first = wire.read(method); wire.no_context(); if resume_on_launch { let providers = wire.read("account.providers"); @@ -721,33 +731,52 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() } ready.send(()).unwrap(); control.recv_timeout(Duration::from_secs(10)).unwrap(); - let mut request = first; - for page in 0..2 { - let start = (1 - page) * 75 + 1; - if page == 0 { assert_eq!(request["params"]["latestTurn"], true); } - else { assert_eq!(request["params"]["before"], 228); } - let mut events = Vec::new(); - for index in start..start + 75 { - events.push(fact(&format!("message-{index}"), index * 3, index * 3, "input", "message", - json!({"mode":"append","user":{"content":[{"type":"text","text":format!("paged-message-{index:03}")}]}}))); - events.push(fact(&format!("applied-{index}"), index * 3 + 1, index * 3, "input", "applied", - json!({"input_id": format!("message-{index}"), "mode": "append"}))); - events.push(fact(&format!("consumed-{index}"), index * 3 + 2, index * 3, "input", "consumed", - json!({"input_id": format!("message-{index}")}))); + let mut events = Vec::new(); + for index in 1..=384 { + let message = format!("message-{index}"); + let turn = format!("turn-{index}"); + let request = format!("request-{index}"); + for (kind, name, data) in [ + ("input", "message", json!({"mode":"append","user":{"content":[{"type":"text","text":format!("paged-message-{index:03}")}]}})), + ("input", "applied", json!({"input_id":message,"mode":"append"})), + ("input", "consumed", json!({"input_id":message})), + ("step", "text", json!({"turn_id":turn,"request_id":request,"delta":"paged-reply-"})), + ("step", "text", json!({"turn_id":turn,"request_id":request,"delta":format!("{index:03}")})), + ("step", "model-output-end", json!({"turn_id":turn,"request_id":request,"status":"completed","finish_reason":"end_turn"})), + ("turn", "end", json!({"turn_id":turn,"status":"completed","reason":"end_turn"})), + ] { + let sequence = events.len() as u64 + 1; + let id = if name == "message" { message.clone() } else { format!("event-{sequence}") }; + events.push(fact(&id, sequence, sequence, kind, name, data)); } - let last = if page == 0 { 452 } else { 227 }; - let before = if page == 0 { 228 } else { 1 }; - wire.reply(&request, json!({"events":events,"through":452,"nextAfter":last,"nextBefore":before,"done":page==1})); - if page == 0 { - let submit = wire.read("session.submit"); - assert_eq!(submit["params"]["sessionId"], "paged"); - assert_eq!(submit["params"]["text"], "draft during history"); - wire.reply(&submit, json!({"event":{}})); - request = wire.read("session.history"); - assert_eq!(request["params"]["through"], 452); + } + events.push(configured_event(THROUGH as u64, "before-replay", json!({}))); + let start = WINDOW_HEAD - 9 * 7; + assert_eq!(first["params"][if display { "tail" } else { "latestTurn" }], true); + wire.reply(&first, json!({(field):events[start..WINDOW_HEAD],"through":WINDOW_HEAD, + "nextAfter":WINDOW_HEAD,"nextBefore":start + 1,"done":false})); + let submit = wire.read("session.submit"); + assert_eq!(submit["params"]["sessionId"], "paged"); + assert_eq!(submit["params"]["text"], "draft during history"); + wire.reply(&submit, json!({"event":{}})); + let notice = |wire: &mut Wire, event: &Value| wire.notice("session.event", + json!({"sessionId":"paged","branchId":"main","event":event})); + notice(wire, &events[WINDOW_HEAD]); + for after in (0..THROUGH).step_by(256) { + let page = wire.read(method); + assert_eq!(page["params"], json!({"sessionId":"paged","branchId":"main", + "after":after,"through":THROUGH,"limit":256})); + if after == 0 { + notice(wire, &fact("live-end", THROUGH as u64 + 1, THROUGH as u64 + 1, "turn", "end", + json!({"turn_id":"live","status":"failed","error":"live failure while paging"}))); + notice(wire, &configured_event(THROUGH as u64 + 2, "during-replay", json!({}))); + control.recv_timeout(PATIENCE).unwrap(); } + let end = (after + 256).min(THROUGH); + wire.reply(&page, json!({(field):events[after..end],"through":THROUGH, + "nextAfter":end,"done":end == THROUGH})); } - assert_eq!(wire.trailing_request(), None, "earlier history is already loaded"); + assert_eq!(wire.trailing_request(), None, "replay reads each page once"); }); let mut command = home.command(); if resume_on_launch { @@ -768,29 +797,41 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() terminal.until("draft during history"); proceed.send(()).unwrap(); terminal.until("Earlier messages · /earlier"); - terminal.until("paged-message-150"); + terminal.until("paged-message-384"); terminal.until("resumed paged"); - terminal.until("75 messages"); - // The window title names the session's first message; only the - // screen is windowed. - let screen = terminal - .transcript - .replace("\x1b]0;DIM | paged-message-001\x07", ""); - assert!(screen.contains("paged-message-076")); - assert!(!screen.contains("paged-message-075")); + terminal.until("18 messages"); + let screen = strip_ansi(&terminal.transcript); + assert!(screen.contains("paged-message-376")); + assert!(!screen.contains("paged-message-375")); assert!(!screen.contains("paged-message-001")); assert!( !terminal.transcript.contains("resumed paged · 0 messages"), "resume_on_launch={resume_on_launch}: {}", terminal.transcript ); - terminal.write(b"\r/earlier\r"); + terminal.write(b"\r"); + terminal.until("test / before-replay"); + terminal.write(b"/earlier\r"); + terminal.until("test / during-replay"); + proceed.send(()).unwrap(); terminal.until("Full conversation history"); - for index in 1..=150 { + let replay_start = terminal.consumed; + for index in 1..=384 { terminal.until(&format!("paged-message-{index:03}")); + terminal.until(&format!("paged-reply-{index:03}")); } + terminal.until("live failure while paging"); + let replay = strip_ansi(&terminal.transcript[replay_start..]); + assert_eq!(replay.matches("paged-reply-").count(), 384); + assert_eq!(replay.matches("paged-message-").count(), 384); terminal.write(b"/timeline\r"); - terminal.until("#150"); + terminal.until("#9 paged-message-384"); + assert_eq!( + strip_ansi(&terminal.transcript) + .matches("live failure while paging") + .count(), + 1 + ); home.kill(&terminal); terminal.wait(); daemon.join().unwrap(); diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index 4cc63e1668..dc26e7ff66 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -3809,10 +3809,12 @@ the turn settled, while a result read before its call asks nothing. ### Loading earlier conversation -`/earlier` reads bounded older windows for the shown branch, retaining its original -cutoff and advancing its backward cursor. Scrollback reads to the beginning and prints the -whole conversation oldest first under a new label, without switching screens. Fullscreen -reveals one page at the join; scrolling up or pressing PageUp at the drawn top does the same. +Scrollback `/earlier` reads the shown branch forward from the beginning to its applied +cursor and prints the conversation under a new label without switching screens. Events +received during the read continue below the replay. This does not expand the working +window used by `/timeline` or later live updates. Fullscreen `/earlier` reads a bounded +older window at the original cutoff and reveals it at the join; scrolling up or pressing +PageUp at the drawn top does the same. Line mode prints a labelled older segment. None changes live event/state cutoffs or resubmits an input. Opening uses the separate read-stop and whole-page retention budgets in the [client window contract](clients.md#opening-a-conversation-with-a-bounded-window); diff --git a/docs/design/timeline-ui.md b/docs/design/timeline-ui.md index faff3ad28a..3f917ee874 100644 --- a/docs/design/timeline-ui.md +++ b/docs/design/timeline-ui.md @@ -108,7 +108,7 @@ While a line is shown, the composer's bottom border names its path from `main`, ╰── ~/repo (main) · ⑂ main ▸ parser race ▸ the guard · after message 4 ─╯ ``` -`after message N` counts the user messages in the parent's history, its inherited ones included, at the cut. The count is unknown while any retained history in the ancestor chain fails to reach the branch point: a parent line this attachment has never opened, and a loaded window that stops before the branch start, both leave it out. Counting never reads a whole parent history ([bounded window](clients.md#opening-a-conversation-with-a-bounded-window)), so a line shows no count rather than one that is too small; a read that reaches the start, such as `/earlier` on the shown line, fills it in. +`after message N` counts the user messages in the parent's history, its inherited ones included, at the cut. The count is unknown while any retained history in the ancestor chain fails to reach the branch point: a parent line this attachment has never opened, and a loaded window that stops before the branch start, both leave it out. Counting never reads a whole parent history ([bounded window](clients.md#opening-a-conversation-with-a-bounded-window)), so a line shows no count rather than one that is too small; extending that window to the start, such as with `/earlier` in fullscreen, fills it in. The workspace half of that label gives way before the line does. Beside a wide left status it shortens as a whole first — the path's front is cut, then the branch is dropped, then the path alone is cut — instead of disappearing, and only a border with no room for any of those forms drops it. A shown line keeps the three forms it has: the whole place, `⑂` alone, then nothing, so line information is never displaced by path information. The label names the workspace the Session works in rather than the directory the process was started in, and it follows a Session attached elsewhere — an explicit `--cwd`, a `/resume` into another worktree — together with that workspace's branch. Home, which has no Session yet, names the launch workspace again. File mentions, pasted paths and dropped files keep the local `--cwd` base instead ([CLI attachment input](cli-attachment-input.md)), so after a cross-workspace resume the label can name a different directory than they do; when it does, the `@` picker names that base in its title. diff --git a/docs/zh/design/timeline-ui.md b/docs/zh/design/timeline-ui.md index d0e04f10cc..4b02dd3502 100644 --- a/docs/zh/design/timeline-ui.md +++ b/docs/zh/design/timeline-ui.md @@ -108,7 +108,7 @@ scrollback 在 live 交互区以确认框替换输入框,不提交到历史; ╰── ~/repo (main) · ⑂ main ▸ parser race ▸ the guard · after message 4 ─╯ ``` -`after message N` 是切点时父线历史中的用户消息数,包括它继承的部分。祖先链上任一段已保留的历史没有覆盖到分支起点时,这个数未知:本条 attachment 从没打开过的父线,以及停在分支起点之前的已加载窗口,都让标签不写它。计数不会去读完整的父线历史([有界窗口](../../design/clients.md#opening-a-conversation-with-a-bounded-window)),所以线宁可不写计数,也不写一个偏小的数;读到起点的那次读取(比如在显示的线上用 `/earlier` 翻到起点)会把计数补上。 +`after message N` 是切点时父线历史中的用户消息数,包括它继承的部分。祖先链上任一段已保留的历史没有覆盖到分支起点时,这个数未知:本条 attachment 从没打开过的父线,以及停在分支起点之前的已加载窗口,都让标签不写它。计数不会去读完整的父线历史([有界窗口](../../design/clients.md#opening-a-conversation-with-a-bounded-window)),所以线宁可不写计数,也不写一个偏小的数;窗口扩展到起点时(比如在 Fullscreen 中用 `/earlier` 翻到起点),才会补上计数。 这个标签的工作区部分先于线让步。左侧状态很宽时,它先整体缩短(截掉路径前段,再放弃分支,再只保留截断的路径),而不是直接消失;只有连这些都放不下时边框才丢掉它。显示线时仍是原来那三档:完整标签、只剩 `⑂`、不画,所以路径信息永远不会挤掉线的信息。标签写的是 Session 实际工作的目录,不是进程的启动目录;attach 到别的目录的 Session(显式 `--cwd`、`/resume` 到另一个 worktree)时它连同那个目录的分支一起跟过去。还没有 Session 的 Home 写回启动工作区。文件提及、粘贴路径和拖入的文件仍以本地 `--cwd` 为基准([CLI 附件输入](../../design/cli-attachment-input.md)),所以跨工作区 resume 之后,标签写的目录可能与它们不同;不同时 `@` 面板会在标题里写出该基准。 From 1c5cd3529ecda4850bd74b8e425cc205cba92e45 Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 14:27:35 +0800 Subject: [PATCH 03/13] fix(tui): keep fullscreen page reveal through queued snapshots Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/src/session_host.rs | 3 +++ crates/dim-cli/src/ui/tui.rs | 14 ++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index 4e08b8da87..220c1d365f 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -2038,6 +2038,9 @@ impl Worker { self.earlier(&line); } } + if !all && self.earlier_view() == Earlier::Reading { + self.publish(); + } } Command::Goal { request, .. } => self.goal(request).await, Command::Loop { request, .. } => self.loop_command(request).await, diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index bf5f33387d..203174b137 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -2818,14 +2818,16 @@ impl App { } } self.runs.observe(&snapshot); + let earlier = snapshot.earlier; let previous = self.snapshot.replace(*snapshot); self.follow_floors(previous.as_ref()); if self.reveal_pending { self.reveal_pending = !self.reveal_earlier() - && self - .snapshot - .as_ref() - .is_some_and(|s| s.earlier == Earlier::Reading); + && (earlier == Earlier::Reading + || earlier == Earlier::Unread + && previous + .as_ref() + .is_some_and(|s| s.earlier == Earlier::Unread)); } self.refresh_compactions(); self.refresh_cards(); @@ -23674,6 +23676,8 @@ mod tests { assert!(matches!(sent.borrow()[0], Command::Earlier { .. })); drawn.draw(); assert_eq!(drawn.transcript(), before, "the request draws nothing"); + let queued = drawn.app.snapshot.as_ref().unwrap().clone(); + drawn.app.apply(Update::Snapshot(Box::new(queued))); let mut rows = window_rows(HISTORY_WINDOW); let mut live = (*window_rows(1)[0]).clone(); live.row_id = "live".into(); @@ -23716,6 +23720,8 @@ mod tests { "the page is drawn, nothing left hidden" ); assert_eq!(drawn_top(&drawn.app), "older 0"); + let join = drawn.app.block_of(&window_rows(1)[0]).unwrap(); + assert_eq!(drawn.app.jump, Some(Jump::Before(join))); sent.borrow_mut().clear(); drawn.app.snapshot.as_mut().unwrap().earlier = Earlier::Reading; drawn.app.show_earlier(); From eecd88b3c3f8dc623e4f11fea8d988319842f2f9 Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 14:55:19 +0800 Subject: [PATCH 04/13] fix(tui): keep provisional thoughts live across scrollback replay Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/src/ui/tui.rs | 84 +++++++++++++++++++++++++++++++++--- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 203174b137..ccb6e78980 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -7414,10 +7414,14 @@ impl App { frame: &mut Frame, ) { let rows = replay.rows; + let recorded_end = replay.window.iter().rposition(|row| { + !(row.kind == RowKind::Thinking && row.streaming && row.provisional_id.is_none()) + }); + let window = &replay.window[..recorded_end.map_or(0, |i| i + 1)]; let mut common = rows .iter() .rev() - .zip(replay.window.iter().rev()) + .zip(window.iter().rev()) .take(HISTORY_WINDOW) .take_while(|(a, b)| a == b || a.row_id == b.row_id && (a.streaming || a.pending)) .count(); @@ -7427,7 +7431,7 @@ impl App { { common -= 1; } - let skipped = replay.window.len() - common; + let skipped = window.len() - common; let floor = skipped .checked_sub(1) .and_then(|index| { @@ -7435,7 +7439,7 @@ impl App { .as_ref()? .rows .iter() - .position(|r| r.row_id == replay.window[index].row_id) + .position(|r| r.row_id == window[index].row_id) }) .map_or(0, |index| index + 1); self.rebuild_window(floor); @@ -8265,7 +8269,12 @@ impl App { let (Some(previous), Some(snapshot)) = (previous, &self.snapshot) else { return; }; - let index_of = |id: &str| snapshot.rows.iter().position(|row| row.row_id == id); + let index_of = |id: &str| { + snapshot + .rows + .iter() + .position(|row| row.row_id == id || row.provisional_id.as_deref() == Some(id)) + }; let moved = |floor: usize| -> usize { let Some(rows) = previous.rows.get(floor..).filter(|rows| !rows.is_empty()) else { return floor.min(snapshot.rows.len()); @@ -8276,7 +8285,9 @@ impl App { let present: std::collections::HashSet<&str> = snapshot .rows .iter() - .map(|row| row.row_id.as_str()) + .flat_map(|row| { + std::iter::once(row.row_id.as_str()).chain(row.provisional_id.as_deref()) + }) .collect(); rows.iter() .find(|row| present.contains(row.row_id.as_str())) @@ -23653,6 +23664,69 @@ mod tests { ); } + #[test] + fn scrollback_replay_keeps_a_live_thought_settled_on_either_side_of_its_frame() { + use crate::projection::Projection; + use serde_json::json; + + let results = [true, false].map(|settle_first| { + let mut drawn = attached(); + let mut projection = Projection::default(); + let event = |id, seq, name, delta| { + serde_json::from_value(json!({ + "id":id, "sequence":seq, "create_at":1000 * seq, + "type":"step", "name":name, + "data":{"turn_id":"t1", "request_id":"r1", "delta":delta} + })) + .unwrap() + }; + projection.progress( + &serde_json::from_value(json!({ + "sessionId":"s1", "branchId":"main", "requestId":"r1", + "text":"", "textOffset":0, "thinking":"Preview.", "thinkingOffset":0 + })) + .unwrap(), + ); + let mut recorded = window_rows(2); + let mut answer = (*message(false)).clone(); + answer.row_id = "previous-answer".into(); + answer.kind = RowKind::AssistantMessage; + answer.text = "Recorded answer.".into(); + recorded.push(std::sync::Arc::new(answer.clone())); + answer.text = "answer.".into(); + let recent = [std::sync::Arc::new(answer)]; + let live_rows = |p: &Projection| [recent.as_slice(), p.rows()].concat(); + let window = live_rows(&projection); + show(&mut drawn, window.clone()); + drawn.app.apply(Update::ReplayHistory( + crate::model::session::HistoryReplay { + rows: recorded, + window, + }, + )); + if !settle_first { + drawn.draw(); + } + projection.apply("main", &event("thought", 1, "thinking", "Settled thought.")); + projection.apply("main", &event("answer", 2, "text", "New response.")); + show(&mut drawn, live_rows(&projection)); + let text = drawn.transcript(); + let (_, replay) = text.split_once("Full conversation history").unwrap(); + let labels = ["ask 0", "ask 1", "answer.", "Settled thought."]; + ( + labels.map(|label| replay.matches(label).count()), + replay + .split_once("Recorded answer.") + .is_some_and(|(_, tail)| tail.contains("Settled thought.")), + ) + }); + assert_eq!( + results, + [([1; 4], true); 2], + "settled before / after replay frame" + ); + } + /// `/earlier` at the drawn top asks for the page and draws it when it lands. #[test] fn show_earlier_requests_unread_history_and_reports_the_start() { From 47badd0680bfc13307387476f5e3a785cee4e76a Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 15:25:01 +0800 Subject: [PATCH 05/13] fix(tui): retain live thoughts across interleaved replay results Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/src/ui/tui.rs | 61 +++++++++++++++++++++++++++--------- 1 file changed, 46 insertions(+), 15 deletions(-) diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index ccb6e78980..763a321cbe 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -7414,10 +7414,12 @@ impl App { frame: &mut Frame, ) { let rows = replay.rows; - let recorded_end = replay.window.iter().rposition(|row| { - !(row.kind == RowKind::Thinking && row.streaming && row.provisional_id.is_none()) + let first_preview = replay.window.iter().position(|row| { + row.kind == RowKind::Thinking && row.streaming && row.provisional_id.is_none() }); - let window = &replay.window[..recorded_end.map_or(0, |i| i + 1)]; + let (window, live) = replay + .window + .split_at(first_preview.unwrap_or(replay.window.len())); let mut common = rows .iter() .rev() @@ -7454,10 +7456,18 @@ impl App { } }; write(Block::Boundary(t("Full conversation history").into())); + let live_ids: HashSet<_> = live.iter().map(|row| row.row_id.as_str()).collect(); + let mut already_printed = Vec::new(); for (index, row) in rows[..rows.len() - common].iter().enumerate() { if row.kind == RowKind::ToolCall && !opens_group(&rows, index) { continue; } + if live_ids.contains(row.row_id.as_str()) { + if row.streaming || row.pending { + continue; + } + already_printed.push(row.row_id.clone()); + } let detail = if row.kind == RowKind::Thinking { thinking_detail } else { @@ -7465,6 +7475,7 @@ impl App { }; write(project_row(&rows, index, detail)); } + self.commits.plan(&already_printed); } fn thought_frames(&mut self, width: usize) -> HashMap { @@ -23669,7 +23680,7 @@ mod tests { use crate::projection::Projection; use serde_json::json; - let results = [true, false].map(|settle_first| { + let run = |member_result: bool, settle_first: bool| { let mut drawn = attached(); let mut projection = Projection::default(); let event = |id, seq, name, delta| { @@ -23695,6 +23706,18 @@ mod tests { recorded.push(std::sync::Arc::new(answer.clone())); answer.text = "answer.".into(); let recent = [std::sync::Arc::new(answer)]; + if member_result { + let result = serde_json::from_value(json!({ + "id":"member-done", "sequence":1, "create_at":900, + "type":"collaboration", "name":"result", "data":{ + "request_event_id":"background", "agent_id":"helper", "session_id":"member", + "status":"completed", "text":"Member finished." + } + })) + .unwrap(); + projection.apply("main", &result); + recorded.push(projection.rows().last().unwrap().clone()); + } let live_rows = |p: &Projection| [recent.as_slice(), p.rows()].concat(); let window = live_rows(&projection); show(&mut drawn, window.clone()); @@ -23707,24 +23730,32 @@ mod tests { if !settle_first { drawn.draw(); } - projection.apply("main", &event("thought", 1, "thinking", "Settled thought.")); - projection.apply("main", &event("answer", 2, "text", "New response.")); + projection.apply("main", &event("thought", 2, "thinking", "Settled thought.")); + projection.apply("main", &event("answer", 3, "text", "New response.")); show(&mut drawn, live_rows(&projection)); let text = drawn.transcript(); let (_, replay) = text.split_once("Full conversation history").unwrap(); let labels = ["ask 0", "ask 1", "answer.", "Settled thought."]; + let after_answer = replay.split_once("Recorded answer.").unwrap().1; ( labels.map(|label| replay.matches(label).count()), - replay - .split_once("Recorded answer.") - .is_some_and(|(_, tail)| tail.contains("Settled thought.")), + replay.matches("Member finished.").count(), + if member_result { + after_answer + .split_once("Member finished.") + .is_some_and(|(_, tail)| tail.contains("Settled thought.")) + } else { + after_answer.contains("Settled thought.") + }, ) - }); - assert_eq!( - results, - [([1; 4], true); 2], - "settled before / after replay frame" - ); + }; + for member_result in [false, true] { + assert_eq!( + [true, false].map(|settle_first| run(member_result, settle_first)), + [([1; 4], usize::from(member_result), true); 2], + "settled before / after replay frame" + ); + } } /// `/earlier` at the drawn top asks for the page and draws it when it lands. From b57f7adbadd92d01bf855865123ff1a18ca1769d Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 15:54:44 +0800 Subject: [PATCH 06/13] fix(tui): append one earlier page in native scrollback Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/README.md | 8 +- crates/dim-cli/src/model/session.rs | 7 - crates/dim-cli/src/projection.rs | 29 +-- crates/dim-cli/src/session_host.rs | 26 +-- crates/dim-cli/src/session_host/tasks.rs | 220 +------------------ crates/dim-cli/src/ui/i18n/de/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/es/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/fr/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/id/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/ja/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/ko/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/pt_br/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs | 1 - crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs | 1 - crates/dim-cli/src/ui/tui.rs | 216 +----------------- crates/dimcode/tests/cli_flow/lines.rs | 14 +- crates/dimcode/tests/cli_flow/tasks.rs | 79 ++++--- docs/architecture/tui-e2e.md | 2 +- docs/design/cli-commands.md | 8 +- docs/design/timeline-ui.md | 2 +- docs/zh/design/timeline-ui.md | 2 +- scripts/tui-tmux/scenarios.mjs | 32 ++- 23 files changed, 110 insertions(+), 545 deletions(-) diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index 2545982f51..d771447a8f 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -1364,8 +1364,8 @@ Resuming draws up to 100 messages from main's initial history window. Both modes mark unread history above the oldest message, never below the transcript. In fullscreen a click, or `Tab` up to it and `Enter`, shows the preceding page at the join. Scrolling up or pressing PageUp at the top does the same. `/earlier` reveals one page in fullscreen. -In scrollback it reprints the entire shown branch in order below a separator, in the -same terminal. The draft stays editable and the next reply follows the reprinted history. +In scrollback it appends only the preceding page, oldest first, below a separator in the +same terminal. Another `/earlier` continues backward without repeating messages. The next live reply follows the page. `/timeline` still jumps to a specific message; a draft typed meanwhile stays editable. ```text @@ -1377,10 +1377,10 @@ same terminal. The draft stays editable and the next reply follows the reprinted [ Ask anything... ] /earlier (scrollback) ---- Full conversation history --- +--- Earlier history · paged · 50 messages --- > paged-message-001 ... -> paged-message-150 +> paged-message-050 [ Ask anything... ] ``` diff --git a/crates/dim-cli/src/model/session.rs b/crates/dim-cli/src/model/session.rs index 1c1df2720c..3e807a149b 100644 --- a/crates/dim-cli/src/model/session.rs +++ b/crates/dim-cli/src/model/session.rs @@ -411,7 +411,6 @@ pub enum Command { Earlier { line: String, session: Origin, - all: bool, }, Export(crate::export::Format), /// `/compact`: ask the line the command was typed on to compact its @@ -1334,13 +1333,7 @@ impl DeleteOutcome { } } -pub struct HistoryReplay { - pub rows: Vec>, - pub window: Vec>, -} - pub enum Update { - ReplayHistory(HistoryReplay), Reportable { error: crate::report::Captured, show_error: bool, diff --git a/crates/dim-cli/src/projection.rs b/crates/dim-cli/src/projection.rs index 4e6344419a..b9f5689612 100644 --- a/crates/dim-cli/src/projection.rs +++ b/crates/dim-cli/src/projection.rs @@ -29,11 +29,6 @@ use crate::wire::{Event, EventContent, Progress, WorkflowRun, WorkflowState}; mod thinking; -#[cfg(test)] -thread_local! { - pub(crate) static REPLAY_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - /// Reasoning that is still arriving: the row shows what the Timeline holds /// plus the progress not written yet. struct OpenThought { @@ -317,8 +312,6 @@ impl Projection { } fn fold(&mut self, branch_id: &str, event: &Event, replayed: bool) { - #[cfg(test)] - REPLAY_WORK.set(REPLAY_WORK.get() + 1); match &event.content { EventContent::ToolCall(data) => { self.questions @@ -911,12 +904,6 @@ impl Projection { } pub fn snapshot(&self) -> ViewSnapshot { - self.snapshot_with_rows(&self.rows) - } - - pub fn snapshot_with_rows(&self, rows: &[Arc]) -> ViewSnapshot { - #[cfg(test)] - REPLAY_WORK.set(REPLAY_WORK.get() + rows.len()); let mut pending: Vec<_> = self.user_queue().collect(); pending.sort_by_key(|input| (!input.applied, input.sequence)); let queued = pending @@ -933,7 +920,7 @@ impl Projection { }) .collect(); ViewSnapshot { - rows: rows.to_vec(), + rows: self.rows.clone(), running: self.running, approvals: self.approvals.clone(), questions: self.questions.calls().cloned().collect(), @@ -1357,11 +1344,11 @@ impl Projection { older.name_agents(self.agent_names.clone(), Vec::new()); self.name_agents(older.agent_names.clone(), Vec::new()); older.rows.retain(|row| { - if let Some(existing) = self.rows.iter_mut().find(|existing| { - #[cfg(test)] - REPLAY_WORK.set(REPLAY_WORK.get() + 1); - existing.row_id == row.row_id - }) { + if let Some(existing) = self + .rows + .iter_mut() + .find(|existing| existing.row_id == row.row_id) + { if matches!( row.kind, RowKind::AssistantMessage | RowKind::StreamingAssistant @@ -1493,10 +1480,6 @@ impl Projection { &self.rows } - pub fn into_rows(self) -> Vec> { - self.rows - } - /// The lines `main` recorded, without `main` itself (design §14). pub fn directory(&mut self, entry: &dim_client::wire::BranchEntry) { if entry.branch_id == ROOT_BRANCH_ID { diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index 220c1d365f..44a22d4382 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -52,7 +52,7 @@ mod report; mod tasks; mod workflow; use member::Members; -use tasks::{BranchHistory, HistoryRequest, Replay, StopBatch}; +use tasks::{BranchHistory, HistoryRequest, StopBatch}; use workflow::WorkflowReads; const PUBLISH_INTERVAL: Duration = Duration::from_millis(16); @@ -328,7 +328,6 @@ struct Worker { task_history_queue: std::collections::VecDeque, /// A stale request still occupies this slot until its reply arrives. task_history_request: Option, - replay: Option, methods: std::collections::HashSet, report_generations: std::collections::HashMap, model_through: u64, @@ -833,7 +832,6 @@ impl Worker { task_history: Default::default(), task_history_queue: Default::default(), task_history_request: None, - replay: None, methods: Default::default(), report_generations: Default::default(), model_through: 0, @@ -1588,7 +1586,7 @@ impl Worker { None, "The centre moved before /usage ran; no report was printed", ), - Command::Earlier { line, session, .. } => ( + Command::Earlier { line, session } => ( session, Some(line), None, @@ -2030,15 +2028,9 @@ impl Worker { } } Command::Rename(title) => self.rename(title).await, - Command::Earlier { line, all, .. } => { - if !self.earlier_member() { - if all { - self.replay.get_or_insert_with(|| Replay::new(line)); - } else { - self.earlier(&line); - } - } - if !all && self.earlier_view() == Earlier::Reading { + Command::Earlier { line, .. } => { + self.earlier(&line); + if self.earlier_view() == Earlier::Reading { self.publish(); } } @@ -5625,13 +5617,7 @@ impl Worker { .values() .any(|line| line.projection.held_input(id).is_some()) }); - let shown = self.shown(); - let rows = self - .replay - .as_ref() - .and_then(|r| r.window(&self.focus)) - .unwrap_or(shown.rows()); - let mut snapshot = shown.snapshot_with_rows(rows); + let mut snapshot = self.shown().snapshot(); snapshot.lines = self.line_views(); snapshot.unread_lines = snapshot .lines diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 30f43cdd1b..f34bdfddeb 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -51,52 +51,12 @@ pub(super) struct HistoryRequest { enum ReadStage { History, - Replay, Cut, Inventory(&'static str), Goal, ToolOrigin { request_id: String, call_id: String }, } -pub(super) struct Replay { - branch: String, - after: u64, - through: Option, - projection: Projection, - window: Vec>, -} - -impl Replay { - pub(super) fn window( - &self, - branch: &str, - ) -> Option<&[std::sync::Arc]> { - (self.branch == branch && self.through.is_some()).then_some(&self.window) - } - - pub(super) fn new(branch: String) -> Self { - Self { - projection: Projection::for_branch(&branch), - branch, - after: 0, - through: None, - window: Vec::new(), - } - } - - fn page(&mut self, page: crate::wire::History) -> crate::Result { - let next = page.next(self.after, self.through)?; - for value in page.events { - self.projection - .replay(&self.branch, &serde_json::from_value(value)?); - } - if let Some(after) = next { - self.after = after; - } - Ok(next.is_none()) - } -} - pub(super) struct StopBatch { session_id: String, projection_id: u64, @@ -147,7 +107,6 @@ impl Worker { self.side = None; self.lines.clear(); self.task_history.clear(); - self.replay = None; self.task_history_queue.clear(); self.workflow.clear(); if let Some(request) = &mut self.task_history_request { @@ -322,6 +281,9 @@ impl Worker { } pub(super) fn earlier(&mut self, line: &str) { + if self.earlier_member() { + return; + } let Some(history) = self.task_history.get_mut(line) else { return; }; @@ -358,79 +320,9 @@ impl Worker { } pub(super) async fn poll_task_history(&mut self) -> crate::Result<()> { - if self - .replay - .as_ref() - .is_some_and(|r| r.branch != self.focus || self.members.selected.is_some()) - { - self.replay = None; - if let Some(request) = &mut self.task_history_request - && matches!(request.stage, ReadStage::Replay) - { - request.current = false; - } - self.changed(); - } if self.task_history_request.is_some() || self.session_id.is_empty() { return Ok(()); } - if let Some(replay) = &mut self.replay - && self - .task_history - .get(&replay.branch) - .is_some_and(|h| h.done) - { - let through = *replay.through.get_or_insert_with(|| { - if let Some(p) = - transcript_mut(&mut self.projection, &mut self.lines, &replay.branch) - { - replay.window = p.rows().to_vec(); - } - self.cursors.get(&replay.branch).copied().unwrap_or(0) - }); - let method = if self - .client - .supports(&["session.history.display", "session.history.detail"]) - { - "session.history.display" - } else { - "session.history" - }; - let branch_id = replay.branch.clone(); - #[derive(serde::Serialize)] - #[serde(rename_all = "camelCase")] - struct Page<'a> { - session_id: &'a str, - branch_id: &'a str, - after: u64, - through: u64, - limit: u32, - } - let params = serde_json::to_value(Page { - session_id: &self.session_id, - branch_id: &branch_id, - after: replay.after, - through, - limit: 256, - })?; - match self.client.send(method, params).await { - Ok(id) => { - self.task_history_request = Some(HistoryRequest { - id, - session_id: self.session_id.clone(), - branch_id, - current: true, - stage: ReadStage::Replay, - }) - } - Err(error) => { - self.replay = None; - self.report(error.to_string(), true); - self.changed(); - } - } - return Ok(()); - } if let Some(branch) = self .task_history .iter() @@ -624,39 +516,6 @@ impl Worker { if !request.current || request.session_id != self.session_id { return Ok(()); } - if matches!(request.stage, ReadStage::Replay) { - let Some(mut replay) = self.replay.take() else { - return Ok(()); - }; - let result = result.map_err(crate::Error::from).and_then(|value| { - let page = if self - .client - .supports(&["session.history.display", "session.history.detail"]) - { - serde_json::from_value::(value)?.into() - } else { - serde_json::from_value(value)? - }; - replay.page(page) - }); - match result { - Ok(false) => self.replay = Some(replay), - Ok(true) => { - self.send(Update::ReplayHistory( - crate::model::session::HistoryReplay { - rows: replay.projection.into_rows(), - window: replay.window, - }, - )); - self.publish(); - } - Err(error) => { - self.report(error.to_string(), true); - self.changed(); - } - } - return Ok(()); - } if let ReadStage::ToolOrigin { request_id, call_id, @@ -741,10 +600,7 @@ impl Worker { } history.inventory_cursor = next; } - ReadStage::History - | ReadStage::Replay - | ReadStage::Goal - | ReadStage::ToolOrigin { .. } => { + ReadStage::History | ReadStage::Goal | ReadStage::ToolOrigin { .. } => { unreachable!() } } @@ -1102,74 +958,6 @@ mod tests { serde_json::from_value(text(sequence, request, delta)).expect("a text event") } - #[tokio::test] - async fn full_replay_stitches_split_thoughts_with_a_linear_projection_budget() { - use crate::projection::REPLAY_WORK; - let (mut worker, updates, _sent) = - crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; - worker.session_id = "s1".into(); - worker.discover_branch("main"); - worker.task_history.get_mut("main").unwrap().done = true; - const HEAD: u64 = 4098; - worker.apply("main", event(HEAD, "tail", "last")); - REPLAY_WORK.set(0); - worker - .command(Command::Earlier { - line: "main".into(), - session: Origin::Session("s1".into()), - all: true, - }) - .await - .unwrap(); - for after in (0..HEAD).step_by(256) { - worker.poll_task_history().await.unwrap(); - let end = (after + 256).min(HEAD); - let events: Vec<_> = (after + 1..=end) - .map(|seq| { - let mut value = text( - seq, - &format!("r-{}", (seq - 1) / 3), - ["first ", "second", "answer"][((seq - 1) % 3) as usize], - ); - if seq % 3 != 0 { - value["name"] = json!("thinking"); - } - value - }) - .collect(); - answer( - &mut worker, - json!({"events":events,"through":HEAD,"nextAfter":end,"done":end==HEAD}), - ) - .await; - } - let rows = updates - .try_iter() - .find_map(|u| match u { - Update::ReplayHistory(r) => Some(r.rows), - _ => None, - }) - .unwrap(); - assert_eq!(rows.len(), (HEAD / 3 * 2) as usize); - for [thought, answer] in rows.as_chunks::<2>().0 { - assert_eq!(thought.text, "first second"); - assert!(!thought.streaming); - assert_eq!(answer.text, "answer"); - } - assert!( - REPLAY_WORK.get() <= 2 * HEAD as usize, - "{} event folds, row comparisons and snapshot row copies", - REPLAY_WORK.get() - ); - REPLAY_WORK.set(0); - worker.apply("main", event(HEAD + 1, "next", "live")); - worker.publish(); - assert!( - REPLAY_WORK.get() < 10, - "a live update must not copy the replay" - ); - } - /// One user message, as the daemon sends it on the wire and in a page. fn said(sequence: u64, message: &str) -> serde_json::Value { json!({ diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index 62aa459dbf..77c4e925fc 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Enter speichern · Esc abbrechen", "Loading…" => "Wird geladen…", "Beginning of conversation" => "Anfang der Unterhaltung erreicht", - "Full conversation history" => "Vollständiger Gesprächsverlauf", "Tab / Enter complete" => "Tab / Enter vervollständigen", "Queue" => "Warteschlange", "Export session" => "Sitzung exportieren", diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index 109a10bef4..a9e20ffea6 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Enter guardar · Esc cancelar", "Loading…" => "Cargando…", "Beginning of conversation" => "Inicio de la conversación", - "Full conversation history" => "Historial completo de la conversación", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Cola", "Export session" => "Exportar sesión", diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index 2a17ab637f..eece7c5b8f 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Entrée enregistrer · Échap annuler", "Loading…" => "Chargement…", "Beginning of conversation" => "Début de la conversation atteint", - "Full conversation history" => "Historique complet de la conversation", "Tab / Enter complete" => "Tab / Enter compléter", "Queue" => "File d’attente", "Export session" => "Exporter la session", diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index 294de5bf2c..523d960108 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Enter simpan · Esc batal", "Loading…" => "Memuat…", "Beginning of conversation" => "Awal percakapan", - "Full conversation history" => "Riwayat percakapan lengkap", "Tab / Enter complete" => "Tab / Enter lengkapi", "Queue" => "Antrean", "Export session" => "Ekspor sesi", diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index eccb85da57..3835a342f3 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Enter 保存 · Esc キャンセル", "Loading…" => "読み込み中…", "Beginning of conversation" => "会話の先頭です", - "Full conversation history" => "会話履歴の全体", "Tab / Enter complete" => "Tab / Enter 補完", "Queue" => "キュー", "Export session" => "セッションをエクスポート", diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index 83ddcdd31b..f3ef0b826e 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Enter 저장 · Esc 취소", "Loading…" => "불러오는 중…", "Beginning of conversation" => "대화의 시작입니다", - "Full conversation history" => "전체 대화 기록", "Tab / Enter complete" => "Tab / Enter 완성", "Queue" => "대기열", "Export session" => "세션 내보내기", diff --git a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs index 21df5ca6a0..fbcd2eeeb4 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Enter salvar · Esc cancelar", "Loading…" => "Carregando…", "Beginning of conversation" => "Início da conversa", - "Full conversation history" => "Histórico completo da conversa", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Fila", "Export session" => "Exportar sessão", diff --git a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs index 3590170956..709128a993 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Enter guardar · Esc cancelar", "Loading…" => "A carregar…", "Beginning of conversation" => "Início da conversa", - "Full conversation history" => "Histórico completo da conversa", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Fila", "Export session" => "Exportar sessão", diff --git a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs index d0d6896606..6cea0b798c 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y 确认 · Esc 取消", "Enter save · Esc cancel" => "Enter 保存 · Esc 取消", "Beginning of conversation" => "已到对话开头", - "Full conversation history" => "完整历史", "Tab / Enter complete" => "Tab / Enter 补全", "Queue" => "队列", "Export session" => "导出会话", diff --git a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs index 4efab0a50f..1035108bb2 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -37,7 +37,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Enter save · Esc cancel" => "Enter 儲存 · Esc 取消", "Loading…" => "載入中…", "Beginning of conversation" => "已到對話開頭", - "Full conversation history" => "完整歷史", "Tab / Enter complete" => "Tab / Enter 補全", "Queue" => "佇列", "Export session" => "匯出工作階段", diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 763a321cbe..2549e84af8 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -1421,7 +1421,6 @@ struct App { /// `show_earlier`, cleared once the page is shown or the read ends /// without one. reveal_pending: bool, - replay_rows: Option, /// The user message a `/timeline` jump or a loaded page lands on, once /// drawn: `(row id, pick it)`. landing: Option<(String, bool)>, @@ -1901,7 +1900,6 @@ impl App { history_floor: 0, load_more: false, reveal_pending: false, - replay_rows: None, landing: None, startup_session: None, awaiting_window: false, @@ -2768,11 +2766,6 @@ impl App { self.set_notice(text); } } - Update::ReplayHistory(rows) => { - if !self.fullscreen { - self.replay_rows = Some(rows); - } - } Update::Snapshot(snapshot) => { let was_running = self.running(); let switched = self @@ -6406,9 +6399,6 @@ impl App { self.banner_committed = true; } let ready = self.arm_window(); - if ready && let Some(rows) = self.replay_rows.take() { - self.draw_replay(rows, width, &mut frame); - } if ready && let Some(shown) = self.pending_line.take() { let lines = self.snapshot.as_ref().map_or(&[][..], |s| &s.lines[..]); let label = match line_name(lines, &shown) { @@ -7407,77 +7397,6 @@ impl App { true } - fn draw_replay( - &mut self, - replay: crate::model::session::HistoryReplay, - width: usize, - frame: &mut Frame, - ) { - let rows = replay.rows; - let first_preview = replay.window.iter().position(|row| { - row.kind == RowKind::Thinking && row.streaming && row.provisional_id.is_none() - }); - let (window, live) = replay - .window - .split_at(first_preview.unwrap_or(replay.window.len())); - let mut common = rows - .iter() - .rev() - .zip(window.iter().rev()) - .take(HISTORY_WINDOW) - .take_while(|(a, b)| a == b || a.row_id == b.row_id && (a.streaming || a.pending)) - .count(); - while common > 0 - && rows[rows.len() - common].kind == RowKind::ToolCall - && !opens_group(&rows, rows.len() - common) - { - common -= 1; - } - let skipped = window.len() - common; - let floor = skipped - .checked_sub(1) - .and_then(|index| { - self.snapshot - .as_ref()? - .rows - .iter() - .position(|r| r.row_id == window[index].row_id) - }) - .map_or(0, |index| index + 1); - self.rebuild_window(floor); - self.load_more = false; - let tool_detail = self.tool_detail; - let thinking_detail = self.thinking_detail; - let mut write = |block| { - let lines = render_block(&block, width, &self.palette, &self.markdown, false); - if !lines.is_empty() { - frame.commits.push(chunk(&lines)); - self.record(block); - } - }; - write(Block::Boundary(t("Full conversation history").into())); - let live_ids: HashSet<_> = live.iter().map(|row| row.row_id.as_str()).collect(); - let mut already_printed = Vec::new(); - for (index, row) in rows[..rows.len() - common].iter().enumerate() { - if row.kind == RowKind::ToolCall && !opens_group(&rows, index) { - continue; - } - if live_ids.contains(row.row_id.as_str()) { - if row.streaming || row.pending { - continue; - } - already_printed.push(row.row_id.clone()); - } - let detail = if row.kind == RowKind::Thinking { - thinking_detail - } else { - tool_detail - }; - write(project_row(&rows, index, detail)); - } - self.commits.plan(&already_printed); - } - fn thought_frames(&mut self, width: usize) -> HashMap { let mut frames = HashMap::new(); let Some(snapshot) = &self.snapshot else { @@ -7980,7 +7899,6 @@ impl App { self.history_floor = 0; self.load_more = false; self.reveal_pending = false; - self.replay_rows = None; self.landing = None; self.window_messages = 0; self.history_request = None; @@ -8080,7 +7998,6 @@ impl App { self.history_floor = 0; self.load_more = false; self.reveal_pending = false; - self.replay_rows = None; self.landing = None; self.window_messages = 0; self.history_request = None; @@ -8183,6 +8100,10 @@ impl App { .filter(|(_, row)| row.kind.is_message()) .nth(HISTORY_WINDOW - 1) .map_or(0, |(i, _)| i); + if !self.fullscreen { + self.jump_to(start); + return true; + } self.landing = snapshot.rows[floor..] .iter() .find(|row| row.kind == RowKind::UserMessage && row.line.is_none()) @@ -8195,15 +8116,7 @@ impl App { } fn show_earlier(&mut self) { - if !self.fullscreen { - self.host.send(Command::Earlier { - line: self.target_line(), - session: self.target_session(), - all: true, - }); - return; - } - if self.reveal_earlier() { + if self.history_request.is_some() || self.reveal_earlier() { return; } let Some(snapshot) = &self.snapshot else { @@ -8214,7 +8127,6 @@ impl App { self.host.send(Command::Earlier { line: self.target_line(), session: self.target_session(), - all: false, }); self.reveal_pending = true; } @@ -8653,7 +8565,6 @@ impl App { fn set_fullscreen(&mut self, on: bool) { self.reveal_pending = false; - self.replay_rows = None; self.fullscreen = on; if on { self.redraw_window(); @@ -23641,123 +23552,6 @@ mod tests { ); } - #[test] - fn scrollback_replay_before_first_frame_keeps_the_whole_prefix_and_live_tail() { - let mut drawn = Drawn::new((80, 40), None, true); - drawn.app.switch_session("s1".into(), SwitchKind::Resumed); - let rows = window_rows(151); - let window = rows[45..150].to_vec(); - show_window(&mut drawn, rows[45..].to_vec()); - drawn.app.apply(Update::ReplayHistory( - crate::model::session::HistoryReplay { - rows: rows[..150].to_vec(), - window, - }, - )); - let frame = drawn.app.frame((80, 40)); - let text = crate::sanitize::safe(&frame.commits.join("\n")); - let (_, mut rest) = text.split_once("Full conversation history").unwrap(); - for n in 0..=150 { - let label = format!("ask {n}"); - rest = rest - .split_once(&label) - .unwrap_or_else(|| panic!("missing {label}")) - .1; - } - assert_eq!(text.matches("ask ").count(), 151); - assert!( - !drawn - .app - .frame((80, 40)) - .commits - .join("\n") - .contains("ask ") - ); - } - - #[test] - fn scrollback_replay_keeps_a_live_thought_settled_on_either_side_of_its_frame() { - use crate::projection::Projection; - use serde_json::json; - - let run = |member_result: bool, settle_first: bool| { - let mut drawn = attached(); - let mut projection = Projection::default(); - let event = |id, seq, name, delta| { - serde_json::from_value(json!({ - "id":id, "sequence":seq, "create_at":1000 * seq, - "type":"step", "name":name, - "data":{"turn_id":"t1", "request_id":"r1", "delta":delta} - })) - .unwrap() - }; - projection.progress( - &serde_json::from_value(json!({ - "sessionId":"s1", "branchId":"main", "requestId":"r1", - "text":"", "textOffset":0, "thinking":"Preview.", "thinkingOffset":0 - })) - .unwrap(), - ); - let mut recorded = window_rows(2); - let mut answer = (*message(false)).clone(); - answer.row_id = "previous-answer".into(); - answer.kind = RowKind::AssistantMessage; - answer.text = "Recorded answer.".into(); - recorded.push(std::sync::Arc::new(answer.clone())); - answer.text = "answer.".into(); - let recent = [std::sync::Arc::new(answer)]; - if member_result { - let result = serde_json::from_value(json!({ - "id":"member-done", "sequence":1, "create_at":900, - "type":"collaboration", "name":"result", "data":{ - "request_event_id":"background", "agent_id":"helper", "session_id":"member", - "status":"completed", "text":"Member finished." - } - })) - .unwrap(); - projection.apply("main", &result); - recorded.push(projection.rows().last().unwrap().clone()); - } - let live_rows = |p: &Projection| [recent.as_slice(), p.rows()].concat(); - let window = live_rows(&projection); - show(&mut drawn, window.clone()); - drawn.app.apply(Update::ReplayHistory( - crate::model::session::HistoryReplay { - rows: recorded, - window, - }, - )); - if !settle_first { - drawn.draw(); - } - projection.apply("main", &event("thought", 2, "thinking", "Settled thought.")); - projection.apply("main", &event("answer", 3, "text", "New response.")); - show(&mut drawn, live_rows(&projection)); - let text = drawn.transcript(); - let (_, replay) = text.split_once("Full conversation history").unwrap(); - let labels = ["ask 0", "ask 1", "answer.", "Settled thought."]; - let after_answer = replay.split_once("Recorded answer.").unwrap().1; - ( - labels.map(|label| replay.matches(label).count()), - replay.matches("Member finished.").count(), - if member_result { - after_answer - .split_once("Member finished.") - .is_some_and(|(_, tail)| tail.contains("Settled thought.")) - } else { - after_answer.contains("Settled thought.") - }, - ) - }; - for member_result in [false, true] { - assert_eq!( - [true, false].map(|settle_first| run(member_result, settle_first)), - [([1; 4], usize::from(member_result), true); 2], - "settled before / after replay frame" - ); - } - } - /// `/earlier` at the drawn top asks for the page and draws it when it lands. #[test] fn show_earlier_requests_unread_history_and_reports_the_start() { diff --git a/crates/dimcode/tests/cli_flow/lines.rs b/crates/dimcode/tests/cli_flow/lines.rs index 9573fe8ba9..b759b63888 100644 --- a/crates/dimcode/tests/cli_flow/lines.rs +++ b/crates/dimcode/tests/cli_flow/lines.rs @@ -865,14 +865,14 @@ fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { "session.history" if branch != "line-1" => { wire.reply(&request, history(8, vec![])); } - "session.history" if request["params"].get("after").is_some() => { - assert_eq!(request["params"], json!({"sessionId":"on-the-line","branchId":"line-1","after":0,"through":6,"limit":256})); - wire.reply(&request, history(6, events.to_vec())); + "session.history" if request["params"].get("before").is_some() => { + assert_eq!(request["params"], json!({"sessionId":"on-the-line","branchId":"line-1","before":4,"through":6,"limit":256})); + wire.reply(&request, json!({"events":events[..3],"through":6,"nextAfter":3,"nextBefore":1,"done":true})); asked.send(()).unwrap(); break; } "session.history" => { - assert!(request["params"].get("before").is_none(), "{request}"); + assert!(request["params"].get("after").is_none(), "{request}"); let mut window_page = history(6, events[3..].to_vec()); window_page["nextBefore"] = json!(4); wire.reply(&request, window_page); @@ -947,11 +947,11 @@ fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { assert!(attempts < 25, "the earlier read never started"); terminal.write(b"/earlier\r"); } - terminal.until("Full conversation history"); + terminal.until("Earlier history · on-the-l · 1 messages"); terminal.until("older page"); - terminal.until("resumed line"); terminal.write(b"/timeline\r"); - terminal.until("#1 resumed line"); + terminal.until("#2 resumed line"); + terminal.until_anywhere("#1 older page"); assert_eq!( reported(&terminal), 1, diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index 2bd8425bf4..dbaa0376e2 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -677,8 +677,7 @@ fn event(wire: &mut Wire, branch: &str, event: Value) { #[test] fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() { - const WINDOW_HEAD: usize = 384 * 7; - const THROUGH: usize = WINDOW_HEAD + 1; + const WINDOW_HEAD: usize = 69 * 7; for (resume_on_launch, display) in [(true, true), (false, false)] { let home = Home::new(); let workspace = std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap(); @@ -732,7 +731,7 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() ready.send(()).unwrap(); control.recv_timeout(Duration::from_secs(10)).unwrap(); let mut events = Vec::new(); - for index in 1..=384 { + for index in 1..=69 { let message = format!("message-{index}"); let turn = format!("turn-{index}"); let request = format!("request-{index}"); @@ -750,7 +749,6 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() events.push(fact(&id, sequence, sequence, kind, name, data)); } } - events.push(configured_event(THROUGH as u64, "before-replay", json!({}))); let start = WINDOW_HEAD - 9 * 7; assert_eq!(first["params"][if display { "tail" } else { "latestTurn" }], true); wire.reply(&first, json!({(field):events[start..WINDOW_HEAD],"through":WINDOW_HEAD, @@ -761,22 +759,27 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() wire.reply(&submit, json!({"event":{}})); let notice = |wire: &mut Wire, event: &Value| wire.notice("session.event", json!({"sessionId":"paged","branchId":"main","event":event})); - notice(wire, &events[WINDOW_HEAD]); - for after in (0..THROUGH).step_by(256) { + notice(wire, &configured_event(WINDOW_HEAD as u64 + 1, "before-page", json!({}))); + for (lower, upper) in [(35 * 7, start), (10 * 7, 35 * 7), (0, 10 * 7)] { let page = wire.read(method); - assert_eq!(page["params"], json!({"sessionId":"paged","branchId":"main", - "after":after,"through":THROUGH,"limit":256})); - if after == 0 { - notice(wire, &fact("live-end", THROUGH as u64 + 1, THROUGH as u64 + 1, "turn", "end", + let mut params = json!({"sessionId":"paged","branchId":"main", + "before":upper + 1,"through":WINDOW_HEAD,"limit":256}); + if display { params["tail"] = json!(true); } + assert_eq!(page["params"], params); + if upper == start { + notice(wire, &fact("live-end", WINDOW_HEAD as u64 + 2, WINDOW_HEAD as u64 + 2, "turn", "end", json!({"turn_id":"live","status":"failed","error":"live failure while paging"}))); - notice(wire, &configured_event(THROUGH as u64 + 2, "during-replay", json!({}))); + notice(wire, &configured_event(WINDOW_HEAD as u64 + 3, "during-page", json!({}))); control.recv_timeout(PATIENCE).unwrap(); } - let end = (after + 256).min(THROUGH); - wire.reply(&page, json!({(field):events[after..end],"through":THROUGH, - "nextAfter":end,"done":end == THROUGH})); + wire.reply(&page, json!({(field):events[lower..upper],"through":WINDOW_HEAD, + "nextAfter":upper,"nextBefore":lower + 1,"done":lower == 0})); + if lower == 10 * 7 { + wire.quiet(Duration::from_millis(150)); + ready.send(()).unwrap(); + } } - assert_eq!(wire.trailing_request(), None, "replay reads each page once"); + assert_eq!(wire.trailing_request(), None, "no read at the beginning"); }); let mut command = home.command(); if resume_on_launch { @@ -797,12 +800,12 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() terminal.until("draft during history"); proceed.send(()).unwrap(); terminal.until("Earlier messages · /earlier"); - terminal.until("paged-message-384"); + terminal.until("paged-message-069"); terminal.until("resumed paged"); terminal.until("18 messages"); let screen = strip_ansi(&terminal.transcript); - assert!(screen.contains("paged-message-376")); - assert!(!screen.contains("paged-message-375")); + assert!(screen.contains("paged-message-061")); + assert!(!screen.contains("paged-message-060")); assert!(!screen.contains("paged-message-001")); assert!( !terminal.transcript.contains("resumed paged · 0 messages"), @@ -810,22 +813,34 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() terminal.transcript ); terminal.write(b"\r"); - terminal.until("test / before-replay"); - terminal.write(b"/earlier\r"); - terminal.until("test / during-replay"); - proceed.send(()).unwrap(); - terminal.until("Full conversation history"); - let replay_start = terminal.consumed; - for index in 1..=384 { - terminal.until(&format!("paged-message-{index:03}")); - terminal.until(&format!("paged-reply-{index:03}")); + terminal.until("test / before-page"); + let paging = terminal.consumed; + for (first, last) in [(11, 60), (1, 10)] { + terminal.write(b"/earlier\r"); + if first == 11 { + terminal.until("test / during-page"); + proceed.send(()).unwrap(); + } + let count = 2 * (last - first + 1); + terminal.until(&format!("Earlier history · paged · {count} messages")); + for index in first..=last { + terminal.until(&format!("paged-message-{index:03}")); + terminal.until(&format!("paged-reply-{index:03}")); + } + if first == 11 { + readiness.recv_timeout(PATIENCE).unwrap(); + } } - terminal.until("live failure while paging"); - let replay = strip_ansi(&terminal.transcript[replay_start..]); - assert_eq!(replay.matches("paged-reply-").count(), 384); - assert_eq!(replay.matches("paged-message-").count(), 384); + terminal.write(b"/earlier\r"); + terminal.until("Beginning of conversation"); + let pages = strip_ansi(&terminal.transcript[paging..terminal.consumed]); + assert_eq!(pages.matches("Earlier history · paged").count(), 2); + assert_eq!(pages.matches("paged-message-").count(), 60); + assert_eq!(pages.matches("paged-reply-").count(), 60); terminal.write(b"/timeline\r"); - terminal.until("#9 paged-message-384"); + terminal.until("#69 paged-message-069"); + terminal.write(b"\x1b[H"); + terminal.until("#1 paged-message-001"); assert_eq!( strip_ansi(&terminal.transcript) .matches("live failure while paging") diff --git a/docs/architecture/tui-e2e.md b/docs/architecture/tui-e2e.md index d797d565cf..ba2a44df90 100644 --- a/docs/architecture/tui-e2e.md +++ b/docs/architecture/tui-e2e.md @@ -100,7 +100,7 @@ daemon. `--keep` leaves the home and raw streams in place for inspection. | Area | Scenario | Verifies | | --- | --- | --- | -| terminal-modes | `earlier_reveals_resumed_history_in_both_modes` | Scrollback reprints all turns in order without clearing, switching screens or losing the draft; fullscreen reveals the preceding page at the join and reports the beginning | +| terminal-modes | `earlier_reveals_resumed_history_in_both_modes` | Scrollback appends preceding pages without overlap, clearing, switching screens or losing the draft; fullscreen reveals the preceding page at the join; both report the beginning | | terminal-modes | `scrollback_streams_and_exits_cleanly` | The default scrollback mode, streamed answer, committed history, `/exit`, `Bye!`, exit 0, no alternate screen, cursor restored, OSC 7501 working/clear | | terminal-modes | `fullscreen_switches_screens_and_restores_the_terminal` | Fullscreen takes the alternate screen; `/tui` leaves and re-enters it; the multiplexer's `ModifyOtherKeys` enable/reset pair appears and balances; the last screen switch is a leave, so the final exit cannot lean on the first `/tui` | | terminal-modes | `fullscreen_tool_body_click_collapses_only_its_node` | Fullscreen opens a tool batch and `exec` call via SGR mouse clicks, verifies drag, double-click, bracketed paste, and a near-deadline resize do not collapse it, and verifies clicking an output row in a scrolled 92×14 pane collapses only that call while re-anchoring its header and the reply below in view | diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index dc26e7ff66..f5dd070ff1 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -3809,10 +3809,10 @@ the turn settled, while a result read before its call asks nothing. ### Loading earlier conversation -Scrollback `/earlier` reads the shown branch forward from the beginning to its applied -cursor and prints the conversation under a new label without switching screens. Events -received during the read continue below the replay. This does not expand the working -window used by `/timeline` or later live updates. Fullscreen `/earlier` reads a bounded +Scrollback `/earlier` prints one preceding page of the shown branch, oldest first, +under an earlier-history label in the same terminal. The next invocation continues +backward from that page; neither invocation reprints already shown messages or reads +to the beginning to fill the page. Live output continues below. Fullscreen `/earlier` reads a bounded older window at the original cutoff and reveals it at the join; scrolling up or pressing PageUp at the drawn top does the same. Line mode prints a labelled older segment. None changes diff --git a/docs/design/timeline-ui.md b/docs/design/timeline-ui.md index 3f917ee874..3a657c54cf 100644 --- a/docs/design/timeline-ui.md +++ b/docs/design/timeline-ui.md @@ -128,7 +128,7 @@ The Timeline's points are its user messages. Tab walks them one at a time from t - `Enter` opens a bordered action list naming the selected message: Jump to message, Edit as a new draft, Quote message, Create branch from here, Fork session. The fork choice states that its cut is before the selected message. Up/Down and Enter select an action; numbers 1–5 select directly. Existing `e`, `q`, `b` and `f` shortcuts work in both lists. Esc returns to the message list with its selection and list position intact, then closes it. Fullscreen shows the lists as overlays; scrollback shows them in the live interaction region without committing them to history. - Jump closes the panel. Fullscreen picks the message, as Tab would, and the pick keys apply. Scrollback cannot move up: a message it has not drawn yet is drawn from there on as an earlier-history page; one already drawn gets a notice that `/tui` can jump to it. -A resume draws up to 100 messages from the latest window. The paging hint appears only above the oldest drawn message. In scrollback, `/earlier` starts a section labelled “Full conversation history” in the same terminal. It prints the shown branch from the beginning, oldest first, including the recent messages already printed above the label. Live output continues below. This does not reattach the Session, submit the draft or clear shell scrollback. +A resume draws up to 100 messages from the latest window. The paging hint appears only above the oldest drawn message. In scrollback, each `/earlier` appends one labelled page immediately preceding the oldest message shown so far. Pages arrive newest to oldest; messages within each page read oldest first. At the beginning the command reports that there is no older conversation instead of printing a page again. Live output continues below. This does not reattach the Session, submit the draft or clear shell scrollback. In fullscreen, `/earlier` reveals the preceding page at the join, using loaded messages before requesting older ones. Scrolling up or pressing PageUp at the drawn top loads another page. At the start, requesting another page reports that there is no older conversation. diff --git a/docs/zh/design/timeline-ui.md b/docs/zh/design/timeline-ui.md index 4b02dd3502..414a1bb6f0 100644 --- a/docs/zh/design/timeline-ui.md +++ b/docs/zh/design/timeline-ui.md @@ -128,7 +128,7 @@ Timeline 的点就是它的用户消息。Tab 从最新一条起逐条走;`/ti - `Enter` 打开操作列表,写明所选消息,列出跳转、编辑为新草稿、引用、创建分支、派生会话;派生选项说明切点在该消息之前。↑↓ 和 Enter 选择,数字 1–5 直接执行;原有 `e`、`q`、`b`、`f` 在两个列表都可用。Esc 返回消息列表,保留所选消息和列表位置,再按 Esc 关闭。scrollback 在 live 交互区显示,fullscreen 显示为 overlay,均不提交到历史。 - 跳转会关闭面板。全屏选中这条消息,与 Tab 选中一样,之后可用选取的按键。scrollback 不能往上走:还没画出的消息从它开始作为一页更早历史画出;已经画出的给出提示,`/tui` 可直接跳到它。 -恢复会话时从最近的窗口显示最多 100 条消息。翻页提示只在已显示的最早一条消息上方。Scrollback 的 `/earlier` 在原终端另起一段「完整历史」,从第一条开始按时间顺序打印当前分支的对话,包含分隔线上方已经显示过的近期消息。新消息接在末尾;不切屏、不清屏、不重新连接会话,也不提交草稿。 +恢复会话时从最近的窗口显示最多 100 条消息。翻页提示只在已显示的最早一条消息上方。Scrollback 每次 `/earlier` 只在原终端末尾追加「更早的消息」一页,紧接在此前最早的消息之前,不重复打印已显示的消息。连续翻页时,后追加的页更早,每页内部仍从旧到新。到头后只提示已到对话开头。实时消息继续接在末尾;不切屏、不清屏、不重新连接会话,也不提交草稿。 Fullscreen 的 `/earlier` 显示上一页,优先使用已经读入的消息,不够再向 daemon 请求,并停在新旧两页的交界处。在顶部继续向上滚动或按 PageUp 可加载上一页。已经到头时,再翻页会提示已到对话开头。 diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index 5e428bbd6f..5b4d0ea1e8 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -250,7 +250,7 @@ const scenarios = [ { name: 'earlier_reveals_resumed_history_in_both_modes', area: 'terminal-modes', - title: 'Replay the full conversation in native scrollback and page in place in fullscreen', + title: 'Append the preceding page in native scrollback and reveal it in place in fullscreen', async run(tui) { await tui.setup({respond: () => ({text: ANSWER})}); let session; @@ -279,17 +279,33 @@ const scenarios = [ } terminal.key('Enter'); if (!fullscreen) { - const replay = await terminal.waitFor(/Full conversation history[\s\S]*┃ history-turn-16[\s\S]*draft stays here/, {history: true}); - const [before, after] = replay.split('Full conversation history'); const turns = (text) => [...text.matchAll(/┃ history-turn-(\d+)/g)].map((m) => Number(m[1])); - assert.deepEqual(turns(before), turns(initial)); - assert.deepEqual(turns(after), Array.from({length: 16}, (_, i) => i + 1)); - assert.deepEqual(after.match(/┃ history-turn-\d+|The fixture answer is deterministic\./g), - Array.from({length: 16}, (_, i) => [`┃ history-turn-${String(i + 1).padStart(2, '0')}`, ANSWER]).flat()); + let oldest = turns(initial)[0]; + let pages = 0; + while (oldest > 1) { + pages++; + const last = String(oldest - 1).padStart(2, '0'); + const page = await terminal.waitFor(new RegExp(`(?:Earlier history ·[\\s\\S]*?){${pages}}┃ history-turn-${last}[\\s\\S]*draft stays here`), {history: true}); + const sections = page.split('Earlier history ·'); + assert.equal(sections.length, pages + 1); + assert.deepEqual(turns(sections[0]), turns(initial)); + const segment = sections.at(-1); + const first = turns(segment)[0]; + assert(first >= 1 && first < oldest, segment); + assert.deepEqual(segment.match(/┃ history-turn-\d+|The fixture answer is deterministic\./g), + Array.from({length: oldest - first}, (_, i) => [`┃ history-turn-${String(first + i).padStart(2, '0')}`, ANSWER]).flat()); + oldest = first; + terminal.key('C-o'); + await terminal.waitFor('Suggestions'); + terminal.send('earlier'); + terminal.key('Enter'); + } + const beginning = await terminal.waitFor('Beginning of conversation', {history: true}); + assert.equal(beginning.split('Earlier history ·').length, pages + 1); assert(!/\x1b\[\?(?:47|1047|1049)h|\x1b\[3J/.test(terminal.raw()), 'no alternate screen or cleared scrollback'); terminal.key('Enter'); const live = await terminal.waitFor(/┃ draft stays here[\s\S]*The fixture answer is deterministic\./, {history: true}); - assert.equal(live.split('Full conversation history').length, 2); + assert.equal(live.split('Earlier history ·').length, pages + 1); assert.equal(live.split('┃ draft stays here').length, 2); await exitWith(terminal); continue; From 4e22cdab9c7afa923b090a39157d9146387cec71 Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 16:24:42 +0800 Subject: [PATCH 07/13] fix(tui): preserve user messages split across history pages Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/src/session_host/member.rs | 5 ++-- crates/dim-cli/src/session_host/tasks.rs | 2 +- crates/dim-client/src/window.rs | 24 +++++++++++++++ crates/dimcode/tests/cli_flow/tasks.rs | 36 ++++++++++++----------- 4 files changed, 47 insertions(+), 20 deletions(-) diff --git a/crates/dim-cli/src/session_host/member.rs b/crates/dim-cli/src/session_host/member.rs index 417e11d939..a81272f42c 100644 --- a/crates/dim-cli/src/session_host/member.rs +++ b/crates/dim-cli/src/session_host/member.rs @@ -588,15 +588,16 @@ impl Worker { Err(error) => self.fail_member(&id, error), Ok(done) => { if done { + let events = observation.window.take_transcript(); if observation.earlier == EarlierRead::Reading { let mut older = Projection::default(); - for event in observation.window.take() { + for event in events { older.replay(DEFAULT_BRANCH_ID, &event); } observation.projection.prepend(older); observation.earlier = EarlierRead::None; } else { - for event in observation.window.take() { + for event in events { observation.event(event, true); } observation.cursor = diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index f34bdfddeb..9284d60071 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -664,7 +664,7 @@ impl Worker { .get_mut(&request.branch_id) .expect("current history"); history.window_error = None; - let events = history.window.take(); + let events = history.window.take_transcript(); let missing_prefix = history.window.dropped_pages() || history.window.before.is_some() && !at_start; history.window_complete = true; diff --git a/crates/dim-client/src/window.rs b/crates/dim-client/src/window.rs index 83578fc40b..6024c5296f 100644 --- a/crates/dim-client/src/window.rs +++ b/crates/dim-client/src/window.rs @@ -8,6 +8,7 @@ pub struct Window { pub before: Option, pub through: Option, pages: VecDeque<(Option, Vec)>, + input_continuations: Vec, initial: bool, dropped: bool, } @@ -18,6 +19,7 @@ impl Default for Window { before: None, through: None, pages: VecDeque::new(), + input_continuations: Vec::new(), initial: true, dropped: false, } @@ -133,6 +135,28 @@ impl Window { .collect() } + /// Events for a separately projected page. Apply and consume facts whose + /// input was written before the page travel back with the cursor until + /// the page containing that input can draw it. No extra page is read. + pub fn take_transcript(&mut self) -> Vec { + let mut events = self.take(); + events.append(&mut self.input_continuations); + if self.before.is_some() { + let written: HashSet<_> = events + .iter() + .filter(|event| matches!(event.content, EventContent::Input(_))) + .map(|event| event.id.clone()) + .collect(); + self.input_continuations + .extend(events.extract_if(.., |event| match &event.content { + EventContent::InputApplied(data) => !written.contains(&data.input_id), + EventContent::InputConsumed(data) => !written.contains(&data.input_id), + _ => false, + })); + } + events + } + /// Whether the last [`Window::take`] dropped the oldest page under the /// retention budget: the events it returned then start above the oldest /// page read, and `before` asks for the omitted history again. diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index dbaa0376e2..d43f171e63 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -760,7 +760,8 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() let notice = |wire: &mut Wire, event: &Value| wire.notice("session.event", json!({"sessionId":"paged","branchId":"main","event":event})); notice(wire, &configured_event(WINDOW_HEAD as u64 + 1, "before-page", json!({}))); - for (lower, upper) in [(35 * 7, start), (10 * 7, 35 * 7), (0, 10 * 7)] { + let split = 10 * 7 + 1; + for (lower, upper) in [(45 * 7, start), (35 * 7, 45 * 7), (25 * 7, 35 * 7), (split, 25 * 7), (0, split)] { let page = wire.read(method); let mut params = json!({"sessionId":"paged","branchId":"main", "before":upper + 1,"through":WINDOW_HEAD,"limit":256}); @@ -774,7 +775,7 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() } wire.reply(&page, json!({(field):events[lower..upper],"through":WINDOW_HEAD, "nextAfter":upper,"nextBefore":lower + 1,"done":lower == 0})); - if lower == 10 * 7 { + if lower == split { wire.quiet(Duration::from_millis(150)); ready.send(()).unwrap(); } @@ -815,22 +816,23 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() terminal.write(b"\r"); terminal.until("test / before-page"); let paging = terminal.consumed; - for (first, last) in [(11, 60), (1, 10)] { - terminal.write(b"/earlier\r"); - if first == 11 { - terminal.until("test / during-page"); - proceed.send(()).unwrap(); - } - let count = 2 * (last - first + 1); - terminal.until(&format!("Earlier history · paged · {count} messages")); - for index in first..=last { - terminal.until(&format!("paged-message-{index:03}")); - terminal.until(&format!("paged-reply-{index:03}")); - } - if first == 11 { - readiness.recv_timeout(PATIENCE).unwrap(); - } + terminal.write(b"/earlier\r"); + terminal.until("test / during-page"); + proceed.send(()).unwrap(); + terminal.until("Earlier history · paged · 99 messages"); + terminal.until("paged-reply-011"); + for index in 12..=60 { + terminal.until(&format!("paged-message-{index:03}")); + terminal.until(&format!("paged-reply-{index:03}")); + } + readiness.recv_timeout(PATIENCE).unwrap(); + terminal.write(b"/earlier\r"); + terminal.until("Earlier history · paged · 21 messages"); + for index in 1..=10 { + terminal.until(&format!("paged-message-{index:03}")); + terminal.until(&format!("paged-reply-{index:03}")); } + terminal.until("paged-message-011"); terminal.write(b"/earlier\r"); terminal.until("Beginning of conversation"); let pages = strip_ansi(&terminal.transcript[paging..terminal.consumed]); From f9cd5c574c955936a8f794b9155933b137c1b7b7 Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 16:45:37 +0800 Subject: [PATCH 08/13] fix(tui): settle recorded thinking across history pages Keep the first durable delta and the closing timestamp together across backward reads so native scrollback does not commit a partial thought. Exercise splits between deltas and before settlement, and show the actual single-page append order in the command example. Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/src/projection.rs | 5 +- crates/dim-cli/src/session_host/member.rs | 10 +- crates/dim-cli/src/session_host/tasks.rs | 2 +- crates/dim-client/src/window.rs | 118 +++++++++++++++++++++- crates/dim-client/src/wire.rs | 2 + crates/dimcode/tests/cli_flow/tasks.rs | 33 +++++- docs/design/cli-commands.md | 13 ++- scripts/tui-tmux/scenarios.mjs | 6 +- 8 files changed, 171 insertions(+), 18 deletions(-) diff --git a/crates/dim-cli/src/projection.rs b/crates/dim-cli/src/projection.rs index b9f5689612..2053b705ca 100644 --- a/crates/dim-cli/src/projection.rs +++ b/crates/dim-cli/src/projection.rs @@ -525,7 +525,7 @@ impl Projection { } } EventContent::ModelStart(_) => {} - EventContent::Thinking(data) => { + EventContent::Thinking(data) | EventContent::SettledThinking(data, _) => { *self .thinking_characters .entry(data.request_id.clone()) @@ -558,6 +558,9 @@ impl Projection { format!("thinking-{}", event.id), )); } + if let EventContent::SettledThinking(_, closed_at) = &event.content { + self.close_thinking(&data.request_id, *closed_at); + } } EventContent::Text(data) => { self.showed.insert(data.request_id.clone()); diff --git a/crates/dim-cli/src/session_host/member.rs b/crates/dim-cli/src/session_host/member.rs index a81272f42c..beaf9fcbb2 100644 --- a/crates/dim-cli/src/session_host/member.rs +++ b/crates/dim-cli/src/session_host/member.rs @@ -568,13 +568,17 @@ impl Worker { } } Pending::History(_) => { + let mut at_start = false; let page = result.map_err(|error| error.to_string()).and_then(|value| { let page = if self .client .supports(&["session.history.display", "session.history.detail"]) { - serde_json::from_value::(value) - .map(Into::into) + serde_json::from_value::(value).map(|page| { + at_start = page.done() + && self.client.offers("session.history.display.transcript"); + page.into() + }) } else { serde_json::from_value(value) } @@ -588,7 +592,7 @@ impl Worker { Err(error) => self.fail_member(&id, error), Ok(done) => { if done { - let events = observation.window.take_transcript(); + let events = observation.window.take_transcript(at_start); if observation.earlier == EarlierRead::Reading { let mut older = Projection::default(); for event in events { diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index 9284d60071..afd41c973e 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -664,7 +664,7 @@ impl Worker { .get_mut(&request.branch_id) .expect("current history"); history.window_error = None; - let events = history.window.take_transcript(); + let events = history.window.take_transcript(at_start); let missing_prefix = history.window.dropped_pages() || history.window.before.is_some() && !at_start; history.window_complete = true; diff --git a/crates/dim-client/src/window.rs b/crates/dim-client/src/window.rs index 6024c5296f..9d6319a4d3 100644 --- a/crates/dim-client/src/window.rs +++ b/crates/dim-client/src/window.rs @@ -1,6 +1,109 @@ use crate::wire::{Event, EventContent, HistoryWindow}; use serde_json::{Value, json}; -use std::collections::{HashSet, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; + +#[derive(Default)] +struct ThoughtBoundary { + turn_end: Option, + requests: HashMap, +} + +struct ClosedThought { + closed_at: u64, + first: Option, + suffix: Vec, +} + +impl ClosedThought { + fn ending(at: u64) -> Self { + Self { + closed_at: at, + first: None, + suffix: Vec::new(), + } + } + + fn prepend(&mut self, event: Event) { + if let Some(previous) = self.first.replace(event) { + let EventContent::Thinking(data) = previous.content else { + unreachable!() + }; + self.suffix.push(data.delta); + } + } + + fn emit(self, rows: &mut Vec) { + let Some(mut first) = self.first else { return }; + let EventContent::Thinking(mut data) = first.content else { + unreachable!() + }; + for delta in self.suffix.into_iter().rev() { + data.delta.push_str(&delta); + } + first.content = EventContent::SettledThinking(data, self.closed_at); + rows.push(first); + } +} + +impl ThoughtBoundary { + fn finish(&mut self, rows: &mut Vec) { + for (_, thought) in self.requests.drain() { + thought.emit(rows); + } + self.turn_end = None; + } + + fn page(&mut self, events: Vec, at_start: bool) -> Vec { + let mut rows = Vec::with_capacity(events.len()); + for event in events.into_iter().rev() { + let request = match &event.content { + EventContent::Text(data) => Some(&data.request_id), + EventContent::ToolUseStart(data) => Some(&data.request_id), + EventContent::ToolUse(data) => Some(&data.request_id), + EventContent::ModelEnd(data) => Some(&data.request_id), + EventContent::ModelStart(data) => Some(&data.request_id), + EventContent::TurnEnd(_) | EventContent::TurnStart(_) => { + self.finish(&mut rows); + if matches!(event.content, EventContent::TurnEnd(_)) { + self.turn_end = Some(event.create_at); + } + None + } + EventContent::Thinking(data) => { + let thought = match self.turn_end { + Some(at) => Some( + self.requests + .entry(data.request_id.clone()) + .or_insert_with(|| ClosedThought::ending(at)), + ), + None => self.requests.get_mut(&data.request_id), + }; + if let Some(thought) = thought { + thought.prepend(event); + continue; + } + None + } + _ => None, + }; + if let Some(request) = request { + if let Some(thought) = self.requests.remove(request) { + thought.emit(&mut rows); + } + if !matches!(event.content, EventContent::ModelStart(_)) { + self.requests + .insert(request.clone(), ClosedThought::ending(event.create_at)); + } + } + rows.push(event); + } + if at_start { + self.finish(&mut rows); + } + rows.sort_unstable_by_key(|event| event.sequence); + rows + } +} /// One bounded transcript load. The consumer takes and releases its raw pages /// after projecting them; this object is not a history cache. @@ -9,6 +112,7 @@ pub struct Window { pub through: Option, pages: VecDeque<(Option, Vec)>, input_continuations: Vec, + thoughts: ThoughtBoundary, initial: bool, dropped: bool, } @@ -20,6 +124,7 @@ impl Default for Window { through: None, pages: VecDeque::new(), input_continuations: Vec::new(), + thoughts: ThoughtBoundary::default(), initial: true, dropped: false, } @@ -137,9 +242,14 @@ impl Window { /// Events for a separately projected page. Apply and consume facts whose /// input was written before the page travel back with the cursor until - /// the page containing that input can draw it. No extra page is read. - pub fn take_transcript(&mut self) -> Vec { - let mut events = self.take(); + /// the page containing that input can draw it. A settled thought travels + /// with its close time until its first delta is known. `at_start` is the + /// indexed transcript's explicit end of history. No extra page is read. + pub fn take_transcript(&mut self, at_start: bool) -> Vec { + let events = self.take(); + let mut events = self + .thoughts + .page(events, self.before.is_none() || at_start && !self.dropped); events.append(&mut self.input_continuations); if self.before.is_some() { let written: HashSet<_> = events diff --git a/crates/dim-client/src/wire.rs b/crates/dim-client/src/wire.rs index 8331ffde83..876297a982 100644 --- a/crates/dim-client/src/wire.rs +++ b/crates/dim-client/src/wire.rs @@ -122,6 +122,8 @@ pub enum EventContent { PermissionChanged(PermissionChangedData), ModelStart(ModelStartData), Thinking(ThinkingData), + /// A paged transcript's complete reasoning block and its durable close time. + SettledThinking(ThinkingData, u64), Text(TextData), ToolUse(ToolUseData), ToolCall(Box), diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index d43f171e63..7d318ce84b 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -677,7 +677,7 @@ fn event(wire: &mut Wire, branch: &str, event: Value) { #[test] fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() { - const WINDOW_HEAD: usize = 69 * 7; + const WINDOW_HEAD: usize = 69 * 7 + 4; for (resume_on_launch, display) in [(true, true), (false, false)] { let home = Home::new(); let workspace = std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap(); @@ -732,6 +732,19 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() control.recv_timeout(Duration::from_secs(10)).unwrap(); let mut events = Vec::new(); for index in 1..=69 { + if index == 61 { + for delta in ["Check the ", "boundary."] { + let seq = events.len() as u64 + 1; + events.push(fact(&format!("thought-{seq}"), seq, seq * 1000, "step", "thinking", + json!({"turn_id":"reasoning","request_id":"reasoning","delta":delta}))); + } + let seq = events.len() as u64 + 1; + events.push(fact("output-end", seq, seq * 1000, "step", "model-output-end", + json!({"turn_id":"reasoning","request_id":"reasoning", + "status":"completed","finish_reason":"end_turn"}))); + events.push(fact("turn-end", seq + 1, (seq + 1) * 1000, "turn", "end", + json!({"turn_id":"reasoning","status":"completed","reason":"end_turn"}))); + } let message = format!("message-{index}"); let turn = format!("turn-{index}"); let request = format!("request-{index}"); @@ -746,10 +759,10 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() ] { let sequence = events.len() as u64 + 1; let id = if name == "message" { message.clone() } else { format!("event-{sequence}") }; - events.push(fact(&id, sequence, sequence, kind, name, data)); + events.push(fact(&id, sequence, sequence * 1000, kind, name, data)); } } - let start = WINDOW_HEAD - 9 * 7; + let start = 60 * 7 + if display { 1 } else { 2 }; assert_eq!(first["params"][if display { "tail" } else { "latestTurn" }], true); wire.reply(&first, json!({(field):events[start..WINDOW_HEAD],"through":WINDOW_HEAD, "nextAfter":WINDOW_HEAD,"nextBefore":start + 1,"done":false})); @@ -761,7 +774,9 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() json!({"sessionId":"paged","branchId":"main","event":event})); notice(wire, &configured_event(WINDOW_HEAD as u64 + 1, "before-page", json!({}))); let split = 10 * 7 + 1; - for (lower, upper) in [(45 * 7, start), (35 * 7, 45 * 7), (25 * 7, 35 * 7), (split, 25 * 7), (0, split)] { + for (lower, upper) in [ + (45 * 7, start), (35 * 7, 45 * 7), (25 * 7, 35 * 7), (split, 25 * 7), (0, split), + ] { let page = wire.read(method); let mut params = json!({"sessionId":"paged","branchId":"main", "before":upper + 1,"through":WINDOW_HEAD,"limit":256}); @@ -836,6 +851,16 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() terminal.write(b"/earlier\r"); terminal.until("Beginning of conversation"); let pages = strip_ansi(&terminal.transcript[paging..terminal.consumed]); + assert!( + pages.contains("Thought for 2.0s · Check the boundary."), + "{pages}" + ); + assert_eq!( + strip_ansi(&terminal.transcript) + .matches("Thought for ") + .count(), + 1 + ); assert_eq!(pages.matches("Earlier history · paged").count(), 2); assert_eq!(pages.matches("paged-message-").count(), 60); assert_eq!(pages.matches("paged-reply-").count(), 60); diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index f5dd070ff1..76b88187eb 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -3821,11 +3821,16 @@ and whole-page retention budgets in the [client window contract](clients.md#open additional older rows are retained only when the user explicitly loads them. Raw pages are released after projection. Export remains a complete fixed-prefix read. +For example, native scrollback grows downward as the operator pages backward: + ```text -[earlier content not loaded] <- /earlier, or PageUp at the loaded top -older requested rows -initial window -live output +↑ Earlier messages · /earlier +messages 61–69 (initial window) +Earlier history · paged · 50 messages (first /earlier) +messages 11–60 +Earlier history · paged · 10 messages (second /earlier) +messages 1–10 +Beginning of conversation (next /earlier; no repeated rows) ``` ### Pending terminal frames diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index 5b4d0ea1e8..82460f7d15 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -252,7 +252,9 @@ const scenarios = [ area: 'terminal-modes', title: 'Append the preceding page in native scrollback and reveal it in place in fullscreen', async run(tui) { - await tui.setup({respond: () => ({text: ANSWER})}); + const thought = 'Check the first turn.'; + await tui.setup({respond: (request) => userText(request).includes('history-turn-01') + ? {thinking: thought, text: ANSWER} : {text: ANSWER}}); let session; for (let turn = 1; turn <= 16; turn++) { const output = await tui.runCommandAsync([ @@ -302,6 +304,7 @@ const scenarios = [ } const beginning = await terminal.waitFor('Beginning of conversation', {history: true}); assert.equal(beginning.split('Earlier history ·').length, pages + 1); + assert.equal(beginning.split(thought).length, 2, beginning); assert(!/\x1b\[\?(?:47|1047|1049)h|\x1b\[3J/.test(terminal.raw()), 'no alternate screen or cleared scrollback'); terminal.key('Enter'); const live = await terminal.waitFor(/┃ draft stays here[\s\S]*The fixture answer is deterministic\./, {history: true}); @@ -314,6 +317,7 @@ const scenarios = [ assert(!join.includes('history-turn-01'), `the viewport lands at the join: ${join}`); terminal.key('Home'); const oldest = await terminal.waitFor('history-turn-01'); + assert(oldest.includes('Thought for ') && oldest.includes(thought), oldest); terminal.key('End'); const newest = await terminal.waitFor('history-turn-16'); for (const page of [oldest, join, newest]) { From 5815925b51ca58e297409d7dd0e751b1ca22042f Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 17:20:54 +0800 Subject: [PATCH 09/13] fix(tui): show complete thinking on initial resume MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Indexed transcript pages omit model-start. Loop consumes input before it starts the next request, so a consumed input also bounds the backward scan for that request’s first thinking delta. Merely submitting or applying input does not establish this boundary. Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-client/src/window.rs | 4 +- crates/dimcode/tests/cli_flow/tasks.rs | 59 ++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/dim-client/src/window.rs b/crates/dim-client/src/window.rs index 9d6319a4d3..82c7750ef0 100644 --- a/crates/dim-client/src/window.rs +++ b/crates/dim-client/src/window.rs @@ -62,7 +62,9 @@ impl ThoughtBoundary { EventContent::ToolUse(data) => Some(&data.request_id), EventContent::ModelEnd(data) => Some(&data.request_id), EventContent::ModelStart(data) => Some(&data.request_id), - EventContent::TurnEnd(_) | EventContent::TurnStart(_) => { + EventContent::InputConsumed(_) + | EventContent::TurnStart(_) + | EventContent::TurnEnd(_) => { self.finish(&mut rows); if matches!(event.content, EventContent::TurnEnd(_)) { self.turn_end = Some(event.create_at); diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index 7d318ce84b..875cff3e63 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -675,6 +675,65 @@ fn event(wire: &mut Wire, branch: &str, event: Value) { ); } +#[test] +fn tui_resume_draws_complete_thinking_in_the_first_indexed_window() { + for fullscreen in [false, true] { + let home = Home::new(); + let daemon = home.daemon(|wire| { + wire.hello(&["session.history.display", "session.history.detail", + "session.history.display.transcript"]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["sequence"] = json!(41); + wire.reply(&attach, record); + let page = wire.read("session.history.display"); + assert_eq!(page["params"]["transcript"], true); + assert_eq!(page["params"]["limit"], 32); + let mut items = vec![ + fact("input", 10, 0, "input", "message", json!({"user":{"content":[{"type":"text","text":"question"}]}})), + fact("applied", 11, 0, "input", "applied", json!({"input_id":"input"})), + fact("consumed", 12, 0, "input", "consumed", json!({"input_id":"input"})), + ]; + for seq in 13..40 { + let (kind, delta) = match seq { + 13 => ("thinking", "Check the "), + 14 => ("thinking", "first page."), + 15 => ("text", "visible answer"), + _ => ("text", "."), + }; + items.push(fact(&format!("step-{seq}"), seq, seq * 1000, "step", kind, + json!({"turn_id":"turn","request_id":"request","delta":delta}))); + } + items.push(fact("end", 40, 40000, "step", "model-output-end", json!({ + "turn_id":"turn","request_id":"request","status":"completed","finish_reason":"end_turn"}))); + items.push(fact("turn-end", 41, 41000, "turn", "end", json!({ + "turn_id":"turn","status":"completed","reason":"end_turn"}))); + wire.reply(&page, json!({"items":items,"through":41,"nextAfter":41,"nextBefore":10,"done":false})); + wire.no_context(); + let providers = wire.read("account.providers"); + wire.reply(&providers, json!([])); + assert_eq!(wire.trailing_request(), None, "resume must not fetch an older page"); + }); + let mut command = home.command(); + if fullscreen { + command.arg("--fullscreen"); + } + let mut terminal = Terminal::resume_tui(command); + terminal.until("visible answer"); + let screen = strip_ansi(&terminal.transcript[..terminal.consumed]); + assert_eq!( + screen + .matches("Thought for 2.0s · Check the first page.") + .count(), + 1, + "fullscreen={fullscreen}: {screen}" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + #[test] fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() { const WINDOW_HEAD: usize = 69 * 7 + 4; From 9d61a05265daf09e347abd170e20f6188238dcda Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 18:23:28 +0800 Subject: [PATCH 10/13] Show settled reasoning on resume after a tool batch Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-client/src/window.rs | 4 ++++ crates/dimcode/tests/cli_flow/tasks.rs | 17 ++++++++++++----- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/dim-client/src/window.rs b/crates/dim-client/src/window.rs index 82c7750ef0..934631fc9d 100644 --- a/crates/dim-client/src/window.rs +++ b/crates/dim-client/src/window.rs @@ -62,6 +62,10 @@ impl ThoughtBoundary { EventContent::ToolUse(data) => Some(&data.request_id), EventContent::ModelEnd(data) => Some(&data.request_id), EventContent::ModelStart(data) => Some(&data.request_id), + EventContent::ToolResult(data) if data.call_event_id.is_some() => { + self.finish(&mut rows); + None + } EventContent::InputConsumed(_) | EventContent::TurnStart(_) | EventContent::TurnEnd(_) => { diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index 875cff3e63..796bd6d409 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -677,9 +677,9 @@ fn event(wire: &mut Wire, branch: &str, event: Value) { #[test] fn tui_resume_draws_complete_thinking_in_the_first_indexed_window() { - for fullscreen in [false, true] { + for (fullscreen, after_tool) in [(false, true), (true, true), (false, false), (true, false)] { let home = Home::new(); - let daemon = home.daemon(|wire| { + let daemon = home.daemon(move |wire| { wire.hello(&["session.history.display", "session.history.detail", "session.history.display.transcript"]); let attach = wire.read("session.attach"); @@ -689,11 +689,18 @@ fn tui_resume_draws_complete_thinking_in_the_first_indexed_window() { let page = wire.read("session.history.display"); assert_eq!(page["params"]["transcript"], true); assert_eq!(page["params"]["limit"], 32); - let mut items = vec![ + let mut items = if after_tool { vec![ + fact("start", 10, 0, "step", "tool-start", json!({"turn_id":"turn","request_id":"previous", + "call_event_id":"batch","call_id":"call"})), + fact("completed", 11, 0, "step", "tool-completed", json!({"turn_id":"turn","request_id":"previous", + "call_event_id":"batch","call_id":"call","result":{"content":"ok"}})), + fact("result", 12, 0, "step", "tool-result", json!({"turn_id":"turn","request_id":"previous", + "call_event_id":"batch","results":[{"call_id":"call","result":{"content":"ok"}}]})), + ] } else { vec![ fact("input", 10, 0, "input", "message", json!({"user":{"content":[{"type":"text","text":"question"}]}})), fact("applied", 11, 0, "input", "applied", json!({"input_id":"input"})), fact("consumed", 12, 0, "input", "consumed", json!({"input_id":"input"})), - ]; + ] }; for seq in 13..40 { let (kind, delta) = match seq { 13 => ("thinking", "Check the "), @@ -726,7 +733,7 @@ fn tui_resume_draws_complete_thinking_in_the_first_indexed_window() { .matches("Thought for 2.0s · Check the first page.") .count(), 1, - "fullscreen={fullscreen}: {screen}" + "fullscreen={fullscreen}, after_tool={after_tool}: {screen}" ); home.kill(&terminal); terminal.wait(); From 1306cb41084b51231d2571f262a0cd141a9139ee Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 18:34:18 +0800 Subject: [PATCH 11/13] Redraw scrollback in chronological order when paging backward Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/src/ui/tui.rs | 7 +++-- crates/dimcode/tests/cli_flow/lines.rs | 2 +- crates/dimcode/tests/cli_flow/tasks.rs | 42 +++++++++++--------------- docs/architecture/tui-e2e.md | 2 +- docs/design/cli-commands.md | 22 ++++++-------- docs/design/timeline-ui.md | 2 +- scripts/tui-tmux/scenarios.mjs | 24 ++++++--------- 7 files changed, 43 insertions(+), 58 deletions(-) diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 2549e84af8..d749b4eb5b 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -8101,7 +8101,9 @@ impl App { .nth(HISTORY_WINDOW - 1) .map_or(0, |(i, _)| i); if !self.fullscreen { - self.jump_to(start); + self.rebuild_window(start); + self.banner_committed = false; + self.request_reflow(); return true; } self.landing = snapshot.rows[floor..] @@ -8155,8 +8157,7 @@ impl App { } } - /// Draws the fullscreen transcript again from row `floor`, the way a - /// line switch draws a line's. + /// Draws the shown line's transcript again from row `floor`. fn rebuild_window(&mut self, floor: usize) { self.planner.reset(); self.thoughts.clear(); diff --git a/crates/dimcode/tests/cli_flow/lines.rs b/crates/dimcode/tests/cli_flow/lines.rs index b759b63888..af60a728a5 100644 --- a/crates/dimcode/tests/cli_flow/lines.rs +++ b/crates/dimcode/tests/cli_flow/lines.rs @@ -947,8 +947,8 @@ fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { assert!(attempts < 25, "the earlier read never started"); terminal.write(b"/earlier\r"); } - terminal.until("Earlier history · on-the-l · 1 messages"); terminal.until("older page"); + terminal.until("resumed line"); terminal.write(b"/timeline\r"); terminal.until("#2 resumed line"); terminal.until_anywhere("#1 older page"); diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index 796bd6d409..2adb6ec1ee 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -900,46 +900,38 @@ fn tui_task_history_resume_windows_complete_main_pages_and_preserves_the_draft() terminal.write(b"/earlier\r"); terminal.until("test / during-page"); proceed.send(()).unwrap(); - terminal.until("Earlier history · paged · 99 messages"); terminal.until("paged-reply-011"); - for index in 12..=60 { + for index in 12..=69 { terminal.until(&format!("paged-message-{index:03}")); terminal.until(&format!("paged-reply-{index:03}")); } + let first = strip_ansi(&terminal.transcript[paging..terminal.consumed]); + assert!(!first.contains("paged-message-010")); readiness.recv_timeout(PATIENCE).unwrap(); + let paging = terminal.consumed; terminal.write(b"/earlier\r"); - terminal.until("Earlier history · paged · 21 messages"); - for index in 1..=10 { + for index in 1..=69 { terminal.until(&format!("paged-message-{index:03}")); terminal.until(&format!("paged-reply-{index:03}")); } - terminal.until("paged-message-011"); + terminal.until("live failure while paging"); terminal.write(b"/earlier\r"); terminal.until("Beginning of conversation"); - let pages = strip_ansi(&terminal.transcript[paging..terminal.consumed]); - assert!( - pages.contains("Thought for 2.0s · Check the boundary."), - "{pages}" - ); - assert_eq!( - strip_ansi(&terminal.transcript) - .matches("Thought for ") - .count(), - 1 - ); - assert_eq!(pages.matches("Earlier history · paged").count(), 2); - assert_eq!(pages.matches("paged-message-").count(), 60); - assert_eq!(pages.matches("paged-reply-").count(), 60); + let page = strip_ansi(&terminal.transcript[paging..terminal.consumed]); + for redraw in [&first, &page] { + assert_eq!( + redraw + .matches("Thought for 2.0s · Check the boundary.") + .count(), + 1 + ); + } + assert_eq!(page.matches("paged-message-").count(), 69); + assert_eq!(page.matches("paged-reply-").count(), 69); terminal.write(b"/timeline\r"); terminal.until("#69 paged-message-069"); terminal.write(b"\x1b[H"); terminal.until("#1 paged-message-001"); - assert_eq!( - strip_ansi(&terminal.transcript) - .matches("live failure while paging") - .count(), - 1 - ); home.kill(&terminal); terminal.wait(); daemon.join().unwrap(); diff --git a/docs/architecture/tui-e2e.md b/docs/architecture/tui-e2e.md index ba2a44df90..887e9277e1 100644 --- a/docs/architecture/tui-e2e.md +++ b/docs/architecture/tui-e2e.md @@ -100,7 +100,7 @@ daemon. `--keep` leaves the home and raw streams in place for inspection. | Area | Scenario | Verifies | | --- | --- | --- | -| terminal-modes | `earlier_reveals_resumed_history_in_both_modes` | Scrollback appends preceding pages without overlap, clearing, switching screens or losing the draft; fullscreen reveals the preceding page at the join; both report the beginning | +| terminal-modes | `earlier_reveals_resumed_history_in_both_modes` | Scrollback redraws the preceding page above newer messages without duplicates, switching screens or losing the draft; fullscreen reveals the preceding page at the join; both report the beginning | | terminal-modes | `scrollback_streams_and_exits_cleanly` | The default scrollback mode, streamed answer, committed history, `/exit`, `Bye!`, exit 0, no alternate screen, cursor restored, OSC 7501 working/clear | | terminal-modes | `fullscreen_switches_screens_and_restores_the_terminal` | Fullscreen takes the alternate screen; `/tui` leaves and re-enters it; the multiplexer's `ModifyOtherKeys` enable/reset pair appears and balances; the last screen switch is a leave, so the final exit cannot lean on the first `/tui` | | terminal-modes | `fullscreen_tool_body_click_collapses_only_its_node` | Fullscreen opens a tool batch and `exec` call via SGR mouse clicks, verifies drag, double-click, bracketed paste, and a near-deadline resize do not collapse it, and verifies clicking an output row in a scrolled 92×14 pane collapses only that call while re-anchoring its header and the reply below in view | diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index 76b88187eb..e46ac9ca32 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -3809,10 +3809,10 @@ the turn settled, while a result read before its call asks nothing. ### Loading earlier conversation -Scrollback `/earlier` prints one preceding page of the shown branch, oldest first, -under an earlier-history label in the same terminal. The next invocation continues -backward from that page; neither invocation reprints already shown messages or reads -to the beginning to fill the page. Live output continues below. Fullscreen `/earlier` reads a bounded +Scrollback `/earlier` reveals one preceding page and redraws the shown branch in the +same terminal, oldest to newest, with the draft below. Like a width-change redraw, +this replaces native scrollback, including output from before the UI started. It +does not open another window or switch screens. Fullscreen `/earlier` reads a bounded older window at the original cutoff and reveals it at the join; scrolling up or pressing PageUp at the drawn top does the same. Line mode prints a labelled older segment. None changes @@ -3821,16 +3821,14 @@ and whole-page retention budgets in the [client window contract](clients.md#open additional older rows are retained only when the user explicitly loads them. Raw pages are released after projection. Export remains a complete fixed-prefix read. -For example, native scrollback grows downward as the operator pages backward: +For example, each column shows native scrollback after one action: ```text -↑ Earlier messages · /earlier -messages 61–69 (initial window) -Earlier history · paged · 50 messages (first /earlier) -messages 11–60 -Earlier history · paged · 10 messages (second /earlier) -messages 1–10 -Beginning of conversation (next /earlier; no repeated rows) +Resume First /earlier Second /earlier +↑ Earlier messages ↑ Earlier messages messages 1–10 +messages 61–69 messages 11–60 messages 11–60 + messages 61–69 messages 61–69 +> draft > draft > draft ``` ### Pending terminal frames diff --git a/docs/design/timeline-ui.md b/docs/design/timeline-ui.md index 3a657c54cf..e2b786d6a2 100644 --- a/docs/design/timeline-ui.md +++ b/docs/design/timeline-ui.md @@ -128,7 +128,7 @@ The Timeline's points are its user messages. Tab walks them one at a time from t - `Enter` opens a bordered action list naming the selected message: Jump to message, Edit as a new draft, Quote message, Create branch from here, Fork session. The fork choice states that its cut is before the selected message. Up/Down and Enter select an action; numbers 1–5 select directly. Existing `e`, `q`, `b` and `f` shortcuts work in both lists. Esc returns to the message list with its selection and list position intact, then closes it. Fullscreen shows the lists as overlays; scrollback shows them in the live interaction region without committing them to history. - Jump closes the panel. Fullscreen picks the message, as Tab would, and the pick keys apply. Scrollback cannot move up: a message it has not drawn yet is drawn from there on as an earlier-history page; one already drawn gets a notice that `/tui` can jump to it. -A resume draws up to 100 messages from the latest window. The paging hint appears only above the oldest drawn message. In scrollback, each `/earlier` appends one labelled page immediately preceding the oldest message shown so far. Pages arrive newest to oldest; messages within each page read oldest first. At the beginning the command reports that there is no older conversation instead of printing a page again. Live output continues below. This does not reattach the Session, submit the draft or clear shell scrollback. +A resume draws up to 100 messages from the latest window. The paging hint appears only above the oldest drawn message. In scrollback, each `/earlier` reveals one preceding page above the messages already shown, using the [same-terminal redraw](cli-commands.md#loading-earlier-conversation). At the beginning the command reports that there is no older conversation instead of redrawing. Live output continues below. This does not reattach the Session or submit the draft. In fullscreen, `/earlier` reveals the preceding page at the join, using loaded messages before requesting older ones. Scrolling up or pressing PageUp at the drawn top loads another page. At the start, requesting another page reports that there is no older conversation. diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index 82460f7d15..a1b4fe8bc9 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -250,7 +250,7 @@ const scenarios = [ { name: 'earlier_reveals_resumed_history_in_both_modes', area: 'terminal-modes', - title: 'Append the preceding page in native scrollback and reveal it in place in fullscreen', + title: 'Redraw native scrollback oldest first and reveal the preceding page at the fullscreen join', async run(tui) { const thought = 'Check the first turn.'; await tui.setup({respond: (request) => userText(request).includes('history-turn-01') @@ -283,19 +283,14 @@ const scenarios = [ if (!fullscreen) { const turns = (text) => [...text.matchAll(/┃ history-turn-(\d+)/g)].map((m) => Number(m[1])); let oldest = turns(initial)[0]; - let pages = 0; while (oldest > 1) { - pages++; const last = String(oldest - 1).padStart(2, '0'); - const page = await terminal.waitFor(new RegExp(`(?:Earlier history ·[\\s\\S]*?){${pages}}┃ history-turn-${last}[\\s\\S]*draft stays here`), {history: true}); - const sections = page.split('Earlier history ·'); - assert.equal(sections.length, pages + 1); - assert.deepEqual(turns(sections[0]), turns(initial)); - const segment = sections.at(-1); - const first = turns(segment)[0]; - assert(first >= 1 && first < oldest, segment); - assert.deepEqual(segment.match(/┃ history-turn-\d+|The fixture answer is deterministic\./g), - Array.from({length: oldest - first}, (_, i) => [`┃ history-turn-${String(first + i).padStart(2, '0')}`, ANSWER]).flat()); + const page = await terminal.waitFor(new RegExp(`┃ history-turn-${last}[\\s\\S]*┃ history-turn-16[\\s\\S]*draft stays here`), {history: true}); + const first = turns(page)[0]; + assert(first >= 1 && first < oldest, page); + assert.deepEqual(page.match(/┃ history-turn-\d+|The fixture answer is deterministic\./g), + Array.from({length: 17 - first}, (_, i) => [`┃ history-turn-${String(first + i).padStart(2, '0')}`, ANSWER]).flat()); + assert.equal(page.includes(hint), first > 1); oldest = first; terminal.key('C-o'); await terminal.waitFor('Suggestions'); @@ -303,12 +298,11 @@ const scenarios = [ terminal.key('Enter'); } const beginning = await terminal.waitFor('Beginning of conversation', {history: true}); - assert.equal(beginning.split('Earlier history ·').length, pages + 1); assert.equal(beginning.split(thought).length, 2, beginning); - assert(!/\x1b\[\?(?:47|1047|1049)h|\x1b\[3J/.test(terminal.raw()), 'no alternate screen or cleared scrollback'); + assert(!/\x1b\[\?(?:47|1047|1049)h/.test(terminal.raw()), 'no alternate screen'); terminal.key('Enter'); const live = await terminal.waitFor(/┃ draft stays here[\s\S]*The fixture answer is deterministic\./, {history: true}); - assert.equal(live.split('Earlier history ·').length, pages + 1); + assert.deepEqual(turns(live), Array.from({length: 16}, (_, i) => i + 1)); assert.equal(live.split('┃ draft stays here').length, 2); await exitWith(terminal); continue; From 6757cfcb4357e25026557be1e679174ae9584c61 Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 18:59:23 +0800 Subject: [PATCH 12/13] Warn that paging replaces pre-Dim terminal output Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- crates/dim-cli/README.md | 14 ++++++++------ crates/dim-cli/src/ui/i18n/de/chrome.rs | 3 +++ crates/dim-cli/src/ui/i18n/es/chrome.rs | 3 +++ crates/dim-cli/src/ui/i18n/fr/chrome.rs | 3 +++ crates/dim-cli/src/ui/i18n/id/chrome.rs | 3 +++ crates/dim-cli/src/ui/i18n/ja/chrome.rs | 1 + crates/dim-cli/src/ui/i18n/ko/chrome.rs | 1 + crates/dim-cli/src/ui/i18n/pt_br/chrome.rs | 3 +++ crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs | 3 +++ crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs | 1 + crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs | 1 + crates/dim-cli/src/ui/transcript/blocks.rs | 14 ++++++++------ docs/design/cli-commands.md | 7 +++++-- scripts/tui-tmux/scenarios.mjs | 11 ++++++++++- 14 files changed, 53 insertions(+), 15 deletions(-) diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index d771447a8f..5b114fbe39 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -1364,23 +1364,25 @@ Resuming draws up to 100 messages from main's initial history window. Both modes mark unread history above the oldest message, never below the transcript. In fullscreen a click, or `Tab` up to it and `Enter`, shows the preceding page at the join. Scrolling up or pressing PageUp at the top does the same. `/earlier` reveals one page in fullscreen. -In scrollback it appends only the preceding page, oldest first, below a separator in the -same terminal. Another `/earlier` continues backward without repeating messages. The next live reply follows the page. +In scrollback, `/earlier` reveals one preceding page and redraws the loaded conversation +in the same terminal, with older messages above newer ones and the draft below. +**This replaces native scrollback, including terminal output from before Dim started.** +The hint above the oldest message warns before you page. At the beginning, `/earlier` +only shows a notice; it does not redraw. See [Loading earlier conversation](../../docs/design/cli-commands.md#loading-earlier-conversation). `/timeline` still jumps to a specific message; a draft typed meanwhile stays editable. ```text -↑ Earlier messages · /earlier +↑ Earlier messages · /earlier · Clears terminal output from before Dim started > paged-message-051 ... > paged-message-150 --- resumed paged · 100 messages --- [ Ask anything... ] -/earlier (scrollback) ---- Earlier history · paged · 50 messages --- +/earlier (same terminal, after redraw) > paged-message-001 ... -> paged-message-050 +> paged-message-150 [ Ask anything... ] ``` diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index 77c4e925fc..d8c6613c63 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -367,6 +367,9 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "neue Session", "resumed {id} · {count} messages" => "{id} fortgesetzt · {count} Nachrichten", "Earlier messages · {key}" => "Frühere Nachrichten · {key}", + "Clears terminal output from before Dim started" => { + "Löscht die Terminalausgabe vor dem Start von Dim" + } "Error: {message}" => "Fehler: {message}", "working… {elapsed}" => "arbeitet… {elapsed}", "thinking… {elapsed}" => "denkt… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index a9e20ffea6..7f6f11874f 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -367,6 +367,9 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "nueva sesión", "resumed {id} · {count} messages" => "reanudada {id} · {count} mensajes", "Earlier messages · {key}" => "Mensajes anteriores · {key}", + "Clears terminal output from before Dim started" => { + "Borra la salida del terminal anterior al inicio de Dim" + } "Error: {message}" => "Error: {message}", "working… {elapsed}" => "trabajando… {elapsed}", "thinking… {elapsed}" => "pensando… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index eece7c5b8f..d7bf7a8edf 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -357,6 +357,9 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "nouvelle session", "resumed {id} · {count} messages" => "{id} repris · {count} messages", "Earlier messages · {key}" => "Messages précédents · {key}", + "Clears terminal output from before Dim started" => { + "Efface la sortie du terminal antérieure au lancement de Dim" + } "Error: {message}" => "Erreur: {message}", "working… {elapsed}" => "travail… {elapsed}", "thinking… {elapsed}" => "réflexion… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index 523d960108..f0e938e931 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -357,6 +357,9 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "sesi baru", "resumed {id} · {count} messages" => "lanjut {id} · {count} pesan", "Earlier messages · {key}" => "Pesan sebelumnya · {key}", + "Clears terminal output from before Dim started" => { + "Menghapus keluaran terminal sebelum Dim dimulai" + } "Error: {message}" => "Error: {message}", "working… {elapsed}" => "bekerja… {elapsed}", "thinking… {elapsed}" => "berpikir… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index 3835a342f3..606f503e14 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -345,6 +345,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "新規セッション", "resumed {id} · {count} messages" => "{id} を再開 · {count} 件", "Earlier messages · {key}" => "以前のメッセージ · {key}", + "Clears terminal output from before Dim started" => "Dim 起動前の端末出力は消去されます", "Error: {message}" => "エラー:{message}", "working… {elapsed}" => "処理中… {elapsed}", "thinking… {elapsed}" => "思考中… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index f3ef0b826e..9042570d34 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -331,6 +331,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "새 세션", "resumed {id} · {count} messages" => "{id} 재개됨 · 메시지 {count}개", "Earlier messages · {key}" => "이전 메시지 · {key}", + "Clears terminal output from before Dim started" => "Dim 시작 전의 터미널 출력을 지웁니다", "Error: {message}" => "오류: {message}", "working… {elapsed}" => "작업 중… {elapsed}", "thinking… {elapsed}" => "생각 중… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs index fbcd2eeeb4..dcd154df52 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -363,6 +363,9 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "nova sessão", "resumed {id} · {count} messages" => "{id} retomada · {count} mensagens", "Earlier messages · {key}" => "Mensagens anteriores · {key}", + "Clears terminal output from before Dim started" => { + "Apaga a saída do terminal anterior ao início do Dim" + } "Error: {message}" => "Erro: {message}", "working… {elapsed}" => "trabalhando… {elapsed}", "thinking… {elapsed}" => "pensando… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs index 709128a993..cac60b9ef4 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -363,6 +363,9 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "nova sessão", "resumed {id} · {count} messages" => "{id} retomada · {count} mensagens", "Earlier messages · {key}" => "Mensagens anteriores · {key}", + "Clears terminal output from before Dim started" => { + "Apaga a saída do terminal anterior ao início do Dim" + } "Error: {message}" => "Erro: {message}", "working… {elapsed}" => "a trabalhar… {elapsed}", "thinking… {elapsed}" => "a pensar… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs index 6cea0b798c..19fb754d2d 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -339,6 +339,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "新会话", "resumed {id} · {count} messages" => "已恢复 {id} · {count} 条消息", "Earlier messages · {key}" => "还有更早的消息 · {key}", + "Clears terminal output from before Dim started" => "会清除启动 Dim 前的终端输出", "Error: {message}" => "错误:{message}", "working… {elapsed}" => "处理中… {elapsed}", "thinking… {elapsed}" => "思考中… {elapsed}", diff --git a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs index 1035108bb2..d0b35da2f0 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -325,6 +325,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "new session" => "新工作階段", "resumed {id} · {count} messages" => "已繼續 {id} · {count} 則訊息", "Earlier messages · {key}" => "還有更早的訊息 · {key}", + "Clears terminal output from before Dim started" => "會清除啟動 Dim 前的終端輸出", "Error: {message}" => "錯誤:{message}", "working… {elapsed}" => "處理中… {elapsed}", "thinking… {elapsed}" => "思考中… {elapsed}", diff --git a/crates/dim-cli/src/ui/transcript/blocks.rs b/crates/dim-cli/src/ui/transcript/blocks.rs index 5040a3a283..b866d1a28b 100644 --- a/crates/dim-cli/src/ui/transcript/blocks.rs +++ b/crates/dim-cli/src/ui/transcript/blocks.rs @@ -788,12 +788,14 @@ pub(crate) fn render_block( Block::Failure(message) => vec![tf("Error: {message}", &[("message", message)])], Block::Boundary(label) => vec![fg(&boundary_line(label, width), &p.muted)], Block::Note(text) => vec![fg(&truncate_cells(text, width), &p.muted)], - Block::LoadMore(hidden) if !interactive || *hidden == 0 => gutter_text( - LOAD_MORE_MARK, - &tf("Earlier messages · {key}", &[("key", "/earlier")]), - width, - &p.accent, - ), + Block::LoadMore(hidden) if !interactive || *hidden == 0 => { + let mut label = tf("Earlier messages · {key}", &[("key", "/earlier")]); + if !interactive { + label.push_str(" · "); + label.push_str(t("Clears terminal output from before Dim started")); + } + gutter_text(LOAD_MORE_MARK, &label, width, &p.accent) + } Block::LoadMore(hidden) => { let label = tf( "{count} earlier messages · Enter or click to load", diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index e46ac9ca32..b7304e552f 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -3811,8 +3811,11 @@ the turn settled, while a result read before its call asks nothing. Scrollback `/earlier` reveals one preceding page and redraws the shown branch in the same terminal, oldest to newest, with the draft below. Like a width-change redraw, -this replaces native scrollback, including output from before the UI started. It -does not open another window or switch screens. Fullscreen `/earlier` reads a bounded +this replaces native scrollback. Losing shell output from before Dim started is an +accepted consequence of keeping the loaded conversation in chronological order in the +same terminal. The `/earlier` hint above the oldest message warns of this loss before +the command is used. At the beginning there is no redraw. Paging does not open another +window or switch screens. Fullscreen `/earlier` reads a bounded older window at the original cutoff and reveals it at the join; scrolling up or pressing PageUp at the drawn top does the same. Line mode prints a labelled older segment. None changes diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index a1b4fe8bc9..f1229a2af1 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -264,12 +264,20 @@ const scenarios = [ session ??= output.trim().split('\n').map((line) => JSON.parse(line).params?.sessionId).find(Boolean); assert(session, 'all turns belong to one Session'); } + const sentinel = 'pre-Dim shell output'; + const warning = 'Clears terminal output from before Dim started'; for (const fullscreen of [true, false]) { - const terminal = await tui.launch(['--resume', session, ...(fullscreen ? ['--fullscreen'] : [])], {rows: 40}); + const terminal = await tui.launch(['--resume', session, ...(fullscreen ? ['--fullscreen'] : [])], { + rows: 40, + command: fullscreen ? undefined : ['/bin/sh', '-c', 'printf "%s" "$0"; exec "$@"', + sentinel + '\n'.repeat(41), tui.binary, '--home', tui.home, '--model-config', tui.modelFile], + }); const initial = await terminal.waitFor(/resumed .* messages/, {history: true}); assert(initial.includes('history-turn-16') && !initial.includes('history-turn-10'), initial); const hint = 'Earlier messages · /earlier'; assert(initial.includes(hint) && initial.indexOf(hint) < initial.search(/┃ history-turn-/), initial); + assert.equal(initial.includes(warning), !fullscreen, initial); + if (!fullscreen) assert(initial.includes(sentinel), initial); assert(!/earlier|\/timeline/i.test(initial.slice(initial.indexOf('resumed '))), initial); if (fullscreen) { terminal.send('/earlier'); @@ -287,6 +295,7 @@ const scenarios = [ const last = String(oldest - 1).padStart(2, '0'); const page = await terminal.waitFor(new RegExp(`┃ history-turn-${last}[\\s\\S]*┃ history-turn-16[\\s\\S]*draft stays here`), {history: true}); const first = turns(page)[0]; + assert(!page.includes(sentinel), page); assert(first >= 1 && first < oldest, page); assert.deepEqual(page.match(/┃ history-turn-\d+|The fixture answer is deterministic\./g), Array.from({length: 17 - first}, (_, i) => [`┃ history-turn-${String(first + i).padStart(2, '0')}`, ANSWER]).flat()); From 89f004964b16f1bcd1d41547465e7de88834b605 Mon Sep 17 00:00:00 2001 From: zjywill Date: Fri, 27 Nov 2026 21:32:27 +0800 Subject: [PATCH 13/13] Document top-only scrollback warning without confirmation Amp-Thread-ID: https://ampcode.com/threads/T-01a21717-81ee-72c0-b263-45c584e4b326 --- docs/architecture/tui-e2e.md | 2 +- docs/design/cli-commands.md | 11 +++++++---- docs/zh/design/timeline-ui.md | 4 +++- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/architecture/tui-e2e.md b/docs/architecture/tui-e2e.md index 887e9277e1..b928af1d14 100644 --- a/docs/architecture/tui-e2e.md +++ b/docs/architecture/tui-e2e.md @@ -100,7 +100,7 @@ daemon. `--keep` leaves the home and raw streams in place for inspection. | Area | Scenario | Verifies | | --- | --- | --- | -| terminal-modes | `earlier_reveals_resumed_history_in_both_modes` | Scrollback redraws the preceding page above newer messages without duplicates, switching screens or losing the draft; fullscreen reveals the preceding page at the join; both report the beginning | +| terminal-modes | `earlier_reveals_resumed_history_in_both_modes` | Scrollback shows the warning above the oldest message. A pre-Dim shell marker is present before paging and absent after redraw; messages stay in order and the draft survives without a screen switch. Fullscreen shows no clearing warning and reveals the page at the join. Both report the beginning | | terminal-modes | `scrollback_streams_and_exits_cleanly` | The default scrollback mode, streamed answer, committed history, `/exit`, `Bye!`, exit 0, no alternate screen, cursor restored, OSC 7501 working/clear | | terminal-modes | `fullscreen_switches_screens_and_restores_the_terminal` | Fullscreen takes the alternate screen; `/tui` leaves and re-enters it; the multiplexer's `ModifyOtherKeys` enable/reset pair appears and balances; the last screen switch is a leave, so the final exit cannot lean on the first `/tui` | | terminal-modes | `fullscreen_tool_body_click_collapses_only_its_node` | Fullscreen opens a tool batch and `exec` call via SGR mouse clicks, verifies drag, double-click, bracketed paste, and a near-deadline resize do not collapse it, and verifies clicking an output row in a scrolled 92×14 pane collapses only that call while re-anchoring its header and the reply below in view | diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index b7304e552f..1d5a22a4ef 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -3813,8 +3813,11 @@ Scrollback `/earlier` reveals one preceding page and redraws the shown branch in same terminal, oldest to newest, with the draft below. Like a width-change redraw, this replaces native scrollback. Losing shell output from before Dim started is an accepted consequence of keeping the loaded conversation in chronological order in the -same terminal. The `/earlier` hint above the oldest message warns of this loss before -the command is used. At the beginning there is no redraw. Paging does not open another +same terminal. The redraw restores the banner and conversation rows, including recorded +`!` shell runs. Private `!!` shell runs are not part of the conversation and are not +restored. The warning appears only in the hint above +the oldest message. Running `/earlier` from the composer does not ask for confirmation, +even when the hint is offscreen. At the beginning there is no redraw. Paging does not open another window or switch screens. Fullscreen `/earlier` reads a bounded older window at the original cutoff and reveals it at the join; scrolling up or pressing PageUp at the drawn top does the same. @@ -3824,11 +3827,11 @@ and whole-page retention budgets in the [client window contract](clients.md#open additional older rows are retained only when the user explicitly loads them. Raw pages are released after projection. Export remains a complete fixed-prefix read. -For example, each column shows native scrollback after one action: +In this example, `↑` stands for the full hint: `↑ Earlier messages · /earlier · Clears terminal output from before Dim started`. ```text Resume First /earlier Second /earlier -↑ Earlier messages ↑ Earlier messages messages 1–10 +↑ ↑ messages 1–10 messages 61–69 messages 11–60 messages 11–60 messages 61–69 messages 61–69 > draft > draft > draft diff --git a/docs/zh/design/timeline-ui.md b/docs/zh/design/timeline-ui.md index 414a1bb6f0..cdd1c1f2c8 100644 --- a/docs/zh/design/timeline-ui.md +++ b/docs/zh/design/timeline-ui.md @@ -128,7 +128,9 @@ Timeline 的点就是它的用户消息。Tab 从最新一条起逐条走;`/ti - `Enter` 打开操作列表,写明所选消息,列出跳转、编辑为新草稿、引用、创建分支、派生会话;派生选项说明切点在该消息之前。↑↓ 和 Enter 选择,数字 1–5 直接执行;原有 `e`、`q`、`b`、`f` 在两个列表都可用。Esc 返回消息列表,保留所选消息和列表位置,再按 Esc 关闭。scrollback 在 live 交互区显示,fullscreen 显示为 overlay,均不提交到历史。 - 跳转会关闭面板。全屏选中这条消息,与 Tab 选中一样,之后可用选取的按键。scrollback 不能往上走:还没画出的消息从它开始作为一页更早历史画出;已经画出的给出提示,`/tui` 可直接跳到它。 -恢复会话时从最近的窗口显示最多 100 条消息。翻页提示只在已显示的最早一条消息上方。Scrollback 每次 `/earlier` 只在原终端末尾追加「更早的消息」一页,紧接在此前最早的消息之前,不重复打印已显示的消息。连续翻页时,后追加的页更早,每页内部仍从旧到新。到头后只提示已到对话开头。实时消息继续接在末尾;不切屏、不清屏、不重新连接会话,也不提交草稿。 +恢复会话时从最近的窗口显示最多 100 条消息。Scrollback 每次 `/earlier` 只展开上一页,在当前终端把已加载的对话从旧到新重绘。旧消息在上,实时消息和草稿仍在底部;不切屏、不重新连接会话,也不提交草稿。 + +重绘会替换终端回滚区,启动 Dim 前的 shell 输出不会保留。清除提示只放在已显示的最早一条消息上方;即使它已滚出视口,从输入框执行 `/earlier` 也不会再要求确认。已到对话开头时只提示,不重绘。见[翻页约定](../../design/cli-commands.md#loading-earlier-conversation)。 Fullscreen 的 `/earlier` 显示上一页,优先使用已经读入的消息,不够再向 daemon 请求,并停在新旧两页的交界处。在顶部继续向上滚动或按 PageUp 可加载上一页。已经到头时,再翻页会提示已到对话开头。