diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index ef9fb0a449..5b114fbe39 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -1360,18 +1360,30 @@ 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, `/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 · Clears terminal output from before Dim started > 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 (same terminal, after redraw) +> 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/projection.rs b/crates/dim-cli/src/projection.rs index 5c9cfaee63..2053b705ca 100644 --- a/crates/dim-cli/src/projection.rs +++ b/crates/dim-cli/src/projection.rs @@ -55,7 +55,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 +141,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 +233,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() @@ -524,7 +525,7 @@ impl Projection { } } EventContent::ModelStart(_) => {} - EventContent::Thinking(data) => { + EventContent::Thinking(data) | EventContent::SettledThinking(data, _) => { *self .thinking_characters .entry(data.request_id.clone()) @@ -557,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.rs b/crates/dim-cli/src/session_host.rs index 820c9acd75..44a22d4382 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -2028,7 +2028,12 @@ impl Worker { } } Command::Rename(title) => self.rename(title).await, - Command::Earlier { line, .. } => self.earlier(&line), + Command::Earlier { line, .. } => { + self.earlier(&line); + if self.earlier_view() == Earlier::Reading { + self.publish(); + } + } Command::Goal { request, .. } => self.goal(request).await, Command::Loop { request, .. } => self.loop_command(request).await, Command::CheckUpdate if self.options.endpoint.is_some() => { @@ -5612,14 +5617,7 @@ 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 mut snapshot = self.shown().snapshot(); snapshot.lines = self.line_views(); snapshot.unread_lines = snapshot .lines diff --git a/crates/dim-cli/src/session_host/member.rs b/crates/dim-cli/src/session_host/member.rs index 417e11d939..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,15 +592,16 @@ impl Worker { Err(error) => self.fail_member(&id, error), Ok(done) => { if done { + let events = observation.window.take_transcript(at_start); 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 eff80e68be..afd41c973e 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -644,7 +644,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 { @@ -665,8 +664,8 @@ impl Worker { .get_mut(&request.branch_id) .expect("current history"); history.window_error = None; - let events = history.window.take(); - missing_prefix = + 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; if history.earlier == EarlierRead::Reading { @@ -735,11 +734,6 @@ impl Worker { if window_ready { self.publish(); } - if missing_prefix { - self.send(Update::Notice( - "Earlier content not loaded; /earlier to read it".into(), - )); - } Ok(()) } @@ -793,9 +787,6 @@ impl Worker { self.task_event(branch, event); } } - if let Some(projection) = transcript_mut(&mut self.projection, &mut self.lines, branch) { - projection.trim(300); - } self.changed(); } @@ -1994,13 +1985,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 +2002,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..d8c6613c63 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -36,6 +36,7 @@ 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", "Tab / Enter complete" => "Tab / Enter vervollständigen", "Queue" => "Warteschlange", "Export session" => "Sitzung exportieren", @@ -365,7 +366,10 @@ 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}", + "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 37a436ec12..7f6f11874f 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -36,6 +36,7 @@ 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", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Cola", "Export session" => "Exportar sesión", @@ -365,7 +366,10 @@ 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}", + "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 a9be46a569..d7bf7a8edf 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -36,6 +36,7 @@ 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", "Tab / Enter complete" => "Tab / Enter compléter", "Queue" => "File d’attente", "Export session" => "Exporter la session", @@ -355,7 +356,10 @@ 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}", + "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 cfaedcac3b..f0e938e931 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -36,6 +36,7 @@ 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", "Tab / Enter complete" => "Tab / Enter lengkapi", "Queue" => "Antrean", "Export session" => "Ekspor sesi", @@ -355,7 +356,10 @@ 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}", + "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 d614634157..606f503e14 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -36,6 +36,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y 確定 · Esc キャンセル", "Enter save · Esc cancel" => "Enter 保存 · Esc キャンセル", "Loading…" => "読み込み中…", + "Beginning of conversation" => "会話の先頭です", "Tab / Enter complete" => "Tab / Enter 補完", "Queue" => "キュー", "Export session" => "セッションをエクスポート", @@ -343,7 +344,8 @@ 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}", + "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 4ce9270368..9042570d34 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -36,6 +36,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y 확인 · Esc 취소", "Enter save · Esc cancel" => "Enter 저장 · Esc 취소", "Loading…" => "불러오는 중…", + "Beginning of conversation" => "대화의 시작입니다", "Tab / Enter complete" => "Tab / Enter 완성", "Queue" => "대기열", "Export session" => "세션 내보내기", @@ -329,7 +330,8 @@ 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}", + "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 cfe8a9536e..dcd154df52 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,7 @@ 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", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Fila", "Export session" => "Exportar sessão", @@ -361,7 +362,10 @@ 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}", + "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 20390ee1af..cac60b9ef4 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,7 @@ 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", "Tab / Enter complete" => "Tab / Enter completar", "Queue" => "Fila", "Export session" => "Exportar sessão", @@ -361,7 +362,10 @@ 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}", + "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 794d8aeb14..19fb754d2d 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,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "y confirm · Esc cancel" => "y 确认 · Esc 取消", "Enter save · Esc cancel" => "Enter 保存 · Esc 取消", + "Beginning of conversation" => "已到对话开头", "Tab / Enter complete" => "Tab / Enter 补全", "Queue" => "队列", "Export session" => "导出会话", @@ -337,7 +338,8 @@ 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}", + "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 99bf73b7c6..d0b35da2f0 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,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "y confirm · Esc cancel" => "y 確認 · Esc 取消", "Enter save · Esc cancel" => "Enter 儲存 · Esc 取消", "Loading…" => "載入中…", + "Beginning of conversation" => "已到對話開頭", "Tab / Enter complete" => "Tab / Enter 補全", "Queue" => "佇列", "Export session" => "匯出工作階段", @@ -323,7 +324,8 @@ 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}", + "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/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..b866d1a28b 100644 --- a/crates/dim-cli/src/ui/transcript/blocks.rs +++ b/crates/dim-cli/src/ui/transcript/blocks.rs @@ -788,6 +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 => { + 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/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 2f1b909db8..d749b4eb5b 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; @@ -1435,8 +1441,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. @@ -1901,7 +1906,7 @@ impl App { switches: PendingSwitches::default(), pending_boundary: None, pending_line: None, - window_info: (0, 0), + window_messages: 0, history_request: None, fullscreen: false, signed_in: false, @@ -2806,9 +2811,17 @@ impl App { } } self.runs.observe(&snapshot); + let earlier = snapshot.earlier; 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() + && (earlier == Earlier::Reading + || earlier == Earlier::Unread + && previous + .as_ref() + .is_some_and(|s| s.earlier == Earlier::Unread)); + } self.refresh_compactions(); self.refresh_cards(); self.refresh_tool_origins(); @@ -6017,14 +6030,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" => { @@ -6404,14 +6410,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 +6482,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 +6507,7 @@ impl App { self.jump = Some(if pick { Jump::Block(id) } else { - Jump::Show(id) + Jump::Before(id) }); } } @@ -7392,7 +7393,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 +7883,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; } @@ -7899,7 +7900,7 @@ impl App { self.load_more = false; self.reveal_pending = 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); @@ -7998,7 +7999,7 @@ impl App { self.load_more = false; self.reveal_pending = 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 +8079,46 @@ 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; + .nth(HISTORY_WINDOW - 1) + .map_or(0, |(i, _)| i); + if !self.fullscreen { + self.rebuild_window(start); + self.banner_committed = false; + self.request_reflow(); + return true; } - let start = messages[messages.len().saturating_sub(HISTORY_WINDOW)]; 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.history_request.is_some() || self.reveal_earlier() { return; } let Some(snapshot) = &self.snapshot else { @@ -8127,59 +8133,20 @@ impl App { 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 @@ -8190,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(); @@ -8227,7 +8193,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()); @@ -8238,7 +8209,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())) @@ -8592,6 +8565,7 @@ impl App { } fn set_fullscreen(&mut self, on: bool) { + self.reveal_pending = false; self.fullscreen = on; if on { self.redraw_window(); @@ -16301,9 +16275,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 +19035,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 +19106,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 +23555,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())); @@ -23600,6 +23576,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(); @@ -23642,66 +23620,32 @@ 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(); 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/dim-client/src/window.rs b/crates/dim-client/src/window.rs index 83578fc40b..934631fc9d 100644 --- a/crates/dim-client/src/window.rs +++ b/crates/dim-client/src/window.rs @@ -1,6 +1,115 @@ 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::ToolResult(data) if data.call_event_id.is_some() => { + self.finish(&mut rows); + None + } + EventContent::InputConsumed(_) + | EventContent::TurnStart(_) + | EventContent::TurnEnd(_) => { + 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. @@ -8,6 +117,8 @@ pub struct Window { pub before: Option, pub through: Option, pages: VecDeque<(Option, Vec)>, + input_continuations: Vec, + thoughts: ThoughtBoundary, initial: bool, dropped: bool, } @@ -18,6 +129,8 @@ impl Default for Window { before: None, through: None, pages: VecDeque::new(), + input_continuations: Vec::new(), + thoughts: ThoughtBoundary::default(), initial: true, dropped: false, } @@ -133,6 +246,33 @@ 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. 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 + .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/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/lines.rs b/crates/dimcode/tests/cli_flow/lines.rs index 410607dc00..af60a728a5 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("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" => { - 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("after").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( @@ -928,7 +907,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,8 +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("older page"); + terminal.until("resumed line"); terminal.write(b"/timeline\r"); - terminal.until("#1 older page"); + terminal.until("#2 resumed line"); + terminal.until_anywhere("#1 older page"); assert_eq!( reported(&terminal), 1, @@ -1944,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 8c00e56167..2adb6ec1ee 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"); @@ -673,16 +675,89 @@ fn event(wire: &mut Wire, branch: &str, event: Value) { ); } +#[test] +fn tui_resume_draws_complete_thinking_in_the_first_indexed_window() { + for (fullscreen, after_tool) in [(false, true), (true, true), (false, false), (true, false)] { + let home = Home::new(); + let daemon = home.daemon(move |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 = 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 "), + 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}, after_tool={after_tool}: {screen}" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + #[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 = 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(); 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 +788,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 +796,72 @@ 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..=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 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); + 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 * 1000, kind, name, data)); + } + } + 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})); + 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, &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), + ] { + let page = wire.read(method); + 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(WINDOW_HEAD as u64 + 3, "during-page", json!({}))); + control.recv_timeout(PATIENCE).unwrap(); + } + wire.reply(&page, json!({(field):events[lower..upper],"through":WINDOW_HEAD, + "nextAfter":upper,"nextBefore":lower + 1,"done":lower == 0})); + if lower == split { + wire.quiet(Duration::from_millis(150)); + ready.send(()).unwrap(); } } - assert_eq!(wire.trailing_request(), None, "earlier history is already loaded"); + assert_eq!(wire.trailing_request(), None, "no read at the beginning"); }); let mut command = home.command(); if resume_on_launch { @@ -767,29 +881,57 @@ 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("paged-message-150"); + terminal.until("Earlier messages · /earlier"); + terminal.until("paged-message-069"); 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 - .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-061")); + assert!(!screen.contains("paged-message-060")); assert!(!screen.contains("paged-message-001")); assert!( !terminal.transcript.contains("resumed paged · 0 messages"), "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.write(b"\r"); + terminal.until("test / before-page"); + let paging = terminal.consumed; + terminal.write(b"/earlier\r"); + terminal.until("test / during-page"); + proceed.send(()).unwrap(); + terminal.until("paged-reply-011"); + 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"); + for index in 1..=69 { + terminal.until(&format!("paged-message-{index:03}")); + terminal.until(&format!("paged-reply-{index:03}")); + } + terminal.until("live failure while paging"); + terminal.write(b"/earlier\r"); + terminal.until("Beginning of conversation"); + 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("#150"); - terminal.write(b"\x1b[H\r"); - terminal.until("paged-message-001"); + terminal.until("#69 paged-message-069"); + terminal.write(b"\x1b[H"); + terminal.until("#1 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..b928af1d14 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 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 8360bc4d7e..1d5a22a4ef 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -3809,19 +3809,32 @@ 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 +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. Losing shell output from before Dim started is an +accepted consequence of keeping the loaded conversation in chronological order in the +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. +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 after projection. Export remains a complete fixed-prefix read. +In this example, `↑` stands for the full hint: `↑ Earlier messages · /earlier · Clears terminal output from before Dim started`. + ```text -[earlier content not loaded] <- /earlier, or PageUp at the loaded top -older requested rows -initial window -live output +Resume First /earlier Second /earlier +↑ ↑ 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 917c3c234e..e2b786d6a2 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. @@ -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, 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. ### 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..cdd1c1f2c8 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 之后,标签写的目录可能与它们不同;不同时 `@` 面板会在标题里写出该基准。 @@ -128,7 +128,11 @@ 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` 只展开上一页,在当前终端把已加载的对话从旧到新重绘。旧消息在上,实时消息和草稿仍在底部;不切屏、不重新连接会话,也不提交草稿。 + +重绘会替换终端回滚区,启动 Dim 前的 shell 输出不会保留。清除提示只放在已显示的最早一条消息上方;即使它已滚出视口,从输入框执行 `/earlier` 也不会再要求确认。已到对话开头时只提示,不重绘。见[翻页约定](../../design/cli-commands.md#loading-earlier-conversation)。 + +Fullscreen 的 `/earlier` 显示上一页,优先使用已经读入的消息,不够再向 daemon 请求,并停在新旧两页的交界处。在顶部继续向上滚动或按 PageUp 可加载上一页。已经到头时,再翻页会提示已到对话开头。 ### 4.7 `/branch ` 与侧面板 diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index e73a823a22..f1229a2af1 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -247,6 +247,94 @@ async function checkDeviceDraftDestination(terminal, devicesOverDraft) { } const scenarios = [ + { + name: 'earlier_reveals_resumed_history_in_both_modes', + area: 'terminal-modes', + 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') + ? {thinking: thought, text: ANSWER} : {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'); + } + 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, + 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'); + } else { + terminal.send('draft stays here'); + terminal.key('C-o'); + await terminal.waitFor('Suggestions'); + terminal.send('earlier'); + } + terminal.key('Enter'); + if (!fullscreen) { + const turns = (text) => [...text.matchAll(/┃ history-turn-(\d+)/g)].map((m) => Number(m[1])); + let oldest = turns(initial)[0]; + while (oldest > 1) { + 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()); + assert.equal(page.includes(hint), first > 1); + 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(thought).length, 2, beginning); + 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.deepEqual(turns(live), Array.from({length: 16}, (_, i) => i + 1)); + 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'); + 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]) { + 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',