From ae694e9f38348204a488452062d17ed7b83c7f8a Mon Sep 17 00:00:00 2001 From: zjywill Date: Thu, 26 Nov 2026 11:09:23 +0800 Subject: [PATCH 1/3] Place the scrollback draft cursor on mouse clicks Refs #2179 Amp-Thread-ID: https://ampcode.com/threads/T-01a2125b-f93a-7216-9485-dafd82fea69f --- crates/dim-cli/README.md | 4 ++- crates/dim-cli/src/ui/i18n/de/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/es/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/fr/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/id/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/ja/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/ko/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/pt_br/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs | 2 +- crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs | 2 +- crates/dim-cli/src/ui/render/screen.rs | 18 +++++++++++-- crates/dim-cli/src/ui/settings_panel.rs | 6 +---- crates/dim-cli/src/ui/terminal/mod.rs | 4 +-- crates/dim-cli/src/ui/tui.rs | 25 +++++++++++++---- docs/architecture/tui-e2e.md | 1 + scripts/tui-tmux/scenarios.mjs | 28 ++++++++++++++++++++ 17 files changed, 81 insertions(+), 25 deletions(-) diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index 1272fe83e8..12c8f7b639 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -1157,6 +1157,8 @@ answer text (including its retained streaming tail) Both TUI modes share the same composer border layout: the adopted model and, when its configuration carries one, the reasoning effort it sends (`provider / model · effort`) sit at the right of the top border, while shell mode keeps the top-border left title. The bottom border keeps the run status, status slot (a notice, `esc interrupt`, `permission required` / `answer required`, disconnect), background task count, goal and main branch context reading (`1.8K / 256K`) at the left, and the attached Session's workspace, git branch and unread badge at the right, with Home naming the launch directory. The permission preset is not in that border: both modes show only the live permission footer described above, without an `AGENT` prefix, with its hint in the selected interface language. While a prompt replaces the composer, a notice or the disconnect state is drawn once, on the rows above the footer. Scrollback keeps its `›` prompt, while fullscreen omits the prompt mark and keeps mouse targets such as clicking the model label. The live footer is not committed to transcript history. When the workspace differs from the CLI's `--cwd`, the `@` picker names the `--cwd` in its title, so local file completion still says which directory it lists. A box too narrow for the whole model label drops the effort first, then the label. +In scrollback, left-click a text cell to move the insertion point while editing a nonempty draft with mouse mode on. Clearing or submitting the draft, opening a picker or prompt, or turning mouse mode off returns mouse handling to the terminal. While Dim receives mouse reports, native selection and wheel scrolling depend on the terminal's mouse override gesture. + The Git branch label follows branch switches in both modes, including switches made by tools or another terminal. At startup the client resolves the workspace's own Git `HEAD` path (including linked worktrees); the existing UI timer reads that file at most once every 10 seconds, without spawning more Git processes, and requests a repaint only when the name changes. Detached HEAD displays `HEAD`; a transient read failure keeps the last known name until the next check. If no Git branch is available at startup, the composer shows only the working directory, without parentheses or a placeholder. The welcome banner still reports `Not available` for its Git branch field. Initializing a repository later requires restarting the TUI to discover it. The client does not repeatedly spawn Git to look for a new repository. @@ -1236,7 +1238,7 @@ Opening `/` selects `/new`; pressing Enter starts a new session. `/permissions` Typing ranks the matches: the exact name, a name prefix, an alias prefix, a prefix of a name part (`reload-skills` for `sk`), a name containing the query, a description word starting with it, then three or more letters in order through the name (`stg` for `settings`); a match inside a description word does not count. Equally ranked matches keep the fixed order. -`/settings` gathers the interface settings: theme and language (each opens its picker and comes back), the startup form (`tuiMode`), the default send mode (`tuiDefaultSendMode`), tool details (`tuiToolDetails`: `collapsed`, `summary`, `expanded`), thinking details (`tuiThinkingDetailsExpanded`), the fullscreen mouse (`tuiMouseMode`: off hands selection and the wheel to the terminal), notifications (`tuiNotifyOnComplete`, on by default), ACP Sessions in `/resume` (`showAcpSessions`, off by default), the permission preset and execution settings. Tool and thinking details are independent and both default to collapsed in both modes. The old `tuiToolDetailsExpanded` boolean is read when no valid three-state preference exists; new changes save to `tuiToolDetails` without replacing the legacy key's format. In scrollback, collapsed tool groups retain their header and member cards; summary shows one row per call; expanded shows full details. In fullscreen these are defaults for independent nodes: collapsed closes batches, summary opens containers with call details closed, and expanded opens both; explicit per-node choices take precedence. Edit and Write details show recorded old/new unified comparisons, including new-file additions; records without a diff explicitly say comparison is unavailable. Compaction bodies show only in expanded, and so does a hook's context (below). `/tools` cycles the defaults without changing thinking or clearing fullscreen manual choices. Model selection stays in `/model` (`/models`). Settings change with `Enter`, `←`/`→` or `Space` and save to `config.json` at once. See the [transcript detail settings contract](../../docs/design/cli-commands.md#transcript-detail-settings). +`/settings` gathers the interface settings: theme and language (each opens its picker and comes back), the startup form (`tuiMode`), the default send mode (`tuiDefaultSendMode`), tool details (`tuiToolDetails`: `collapsed`, `summary`, `expanded`), thinking details (`tuiThinkingDetailsExpanded`), mouse input (`tuiMouseMode`: off hands selection and the wheel to the terminal), notifications (`tuiNotifyOnComplete`, on by default), ACP Sessions in `/resume` (`showAcpSessions`, off by default), the permission preset and execution settings. Tool and thinking details are independent and both default to collapsed in both modes. The old `tuiToolDetailsExpanded` boolean is read when no valid three-state preference exists; new changes save to `tuiToolDetails` without replacing the legacy key's format. In scrollback, collapsed tool groups retain their header and member cards; summary shows one row per call; expanded shows full details. In fullscreen these are defaults for independent nodes: collapsed closes batches, summary opens containers with call details closed, and expanded opens both; explicit per-node choices take precedence. Edit and Write details show recorded old/new unified comparisons, including new-file additions; records without a diff explicitly say comparison is unavailable. Compaction bodies show only in expanded, and so does a hook's context (below). `/tools` cycles the defaults without changing thinking or clearing fullscreen manual choices. Model selection stays in `/model` (`/models`). Settings change with `Enter`, `←`/`→` or `Space` and save to `config.json` at once. See the [transcript detail settings contract](../../docs/design/cli-commands.md#transcript-detail-settings). Notifications reach a user who switched windows when the run finishes or waits on a permission or a question (each request once): iTerm2 gets `OSC 9`, kitty `OSC 99`, Ghostty, WezTerm and foot `OSC 777`; any other terminal gets a bell, which it turns into a Dock bounce, a taskbar flash or a tab badge. Inside a multiplexer the bytes differ, because neither carries the form upward by itself and a notification asserts nothing after it is delivered, so the record's reasons for staying inside a multiplexer (`ui::status`, `ui::progress`) do not apply to it. tmux gets the form in its passthrough wrapper (`ESC P tmux;`, the sequence's `ESC`s doubled, `ESC \`) followed by a bare `BEL`: tmux 3.3 and later default `allow-passthrough` to off, so a tmux that forwards the wrapper draws the notification and one that drops it still rings. GNU screen follows the same rule for the same reason: it doubles no `ESC` (`ESC P` opens a passthrough it ends differently from tmux, which a notification does not need), and some builds forward an `OSC` closed by `BEL` while others drop every `OSC` a pane writes — so a `BEL`-terminated form (`OSC 9`, `OSC 777`) goes through unwrapped as it is and a bare `BEL` follows it, which draws the notification where the form is forwarded and rings where it is dropped. kitty's `ST`-terminated `OSC 99` has no shape screen carries whole, so it becomes the bell alone. herdr gets a bell whatever its `TERM_PROGRAM` says: it reads a pane's `OSC`s for itself and notifies from its own list of terminals, so a form the pane's variables name is not known to reach the user, while a `BEL` is not an `OSC` it takes. diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index ee288623a8..f6c7101910 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -441,7 +441,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "Denkdetails", "expanded" => "ausgeklappt", "collapsed" => "eingeklappt", - "Mouse (fullscreen)" => "Maus (Vollbild)", + "Mouse" => "Maus", "Permissions" => "Berechtigungen", "Tool approvals" => "Tool-Freigaben", "Execution" => "Ausführung", diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index fc8087043c..3292d8b1d8 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -447,7 +447,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "Detalles de razonamiento", "expanded" => "expandido", "collapsed" => "contraído", - "Mouse (fullscreen)" => "Ratón (pantalla completa)", + "Mouse" => "Ratón", "Permissions" => "Permisos", "Tool approvals" => "Aprobaciones", "Execution" => "Ejecución", diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index d8a2f7626c..b066d6ef27 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -433,7 +433,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "Détails de réflexion", "expanded" => "dépliés", "collapsed" => "repliés", - "Mouse (fullscreen)" => "Souris (plein écran)", + "Mouse" => "Souris", "Permissions" => "Autorisations", "Tool approvals" => "Approbations d'outils", "Execution" => "Exécution", diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index 52bafe2e64..6293732781 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -427,7 +427,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "Detail pemikiran", "expanded" => "terbuka", "collapsed" => "terlipat", - "Mouse (fullscreen)" => "Mouse (layar penuh)", + "Mouse" => "Mouse", "Permissions" => "Izin", "Tool approvals" => "Persetujuan tool", "Execution" => "Eksekusi", diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index d1ccae21a0..120662199f 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -411,7 +411,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "思考詳細", "expanded" => "展開", "collapsed" => "折りたたみ", - "Mouse (fullscreen)" => "マウス(全画面)", + "Mouse" => "マウス", "Permissions" => "権限", "Tool approvals" => "ツール承認", "Execution" => "実行", diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index 204d0342bd..f8340d7771 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -395,7 +395,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "생각 상세", "expanded" => "펼침", "collapsed" => "접힘", - "Mouse (fullscreen)" => "마우스 (전체 화면)", + "Mouse" => "마우스", "Permissions" => "권한", "Tool approvals" => "도구 승인", "Execution" => "실행", 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 a2567ae65f..1c8b9e55ef 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -437,7 +437,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "Detalhes de raciocínio", "expanded" => "expandido", "collapsed" => "recolhido", - "Mouse (fullscreen)" => "Mouse (tela cheia)", + "Mouse" => "Mouse", "Permissions" => "Permissões", "Tool approvals" => "Aprovações de ferramentas", "Execution" => "Execuçã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 dfca95d535..31406eb63e 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -445,7 +445,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "Detalhes de raciocínio", "expanded" => "expandido", "collapsed" => "recolhido", - "Mouse (fullscreen)" => "Rato (ecrã inteiro)", + "Mouse" => "Rato", "Permissions" => "Permissões", "Tool approvals" => "Aprovações de ferramentas", "Execution" => "Execuçã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 88e413bfdd..4478b25ce7 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -452,7 +452,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "思考详情", "expanded" => "展开", "collapsed" => "折叠", - "Mouse (fullscreen)" => "鼠标(全屏)", + "Mouse" => "鼠标", "Permissions" => "权限", "Tool approvals" => "工具审批", "Execution" => "执行", 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 dcfaae2239..9db33eaa3b 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -389,7 +389,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Thinking details" => "思考詳情", "expanded" => "展開", "collapsed" => "收合", - "Mouse (fullscreen)" => "滑鼠(全螢幕)", + "Mouse" => "滑鼠", "Permissions" => "權限", "Tool approvals" => "工具核准", "Execution" => "執行", diff --git a/crates/dim-cli/src/ui/render/screen.rs b/crates/dim-cli/src/ui/render/screen.rs index 7a41263195..6aea06b005 100644 --- a/crates/dim-cli/src/ui/render/screen.rs +++ b/crates/dim-cli/src/ui/render/screen.rs @@ -11,7 +11,7 @@ use std::borrow::Cow; use std::io::{self, Write}; -use ratatui::layout::{Rect, Size}; +use ratatui::layout::{Position, Rect, Size}; use xai_ratatui_inline::{TerminalLike, emit_to_scrollback}; /// History rows kept visible when space permits. @@ -43,7 +43,7 @@ pub struct Frame { pub thought_rows: Vec<(usize, std::ops::Range, String, bool)>, /// Model label row and columns in `live`, for the fullscreen model picker. pub model_label: Option<(usize, std::ops::Range)>, - /// Editable text cells relative to the start of the fullscreen dock. + /// Editable text cells relative to the start of the dock. pub composer: Option, /// Cursor position inside the live region (row, column), `None` hides it. pub cursor: Option<(u16, u16)>, @@ -100,6 +100,7 @@ pub struct Screen { cursor_visible: bool, /// Where the terminal's cursor is after our last write, when known. cursor_at: Option<(u16, u16)>, + composer: Option<(Rect, usize)>, synchronized: bool, } @@ -118,6 +119,7 @@ impl Screen { painted: Vec::new(), cursor_visible: true, cursor_at: None, + composer: None, synchronized, } } @@ -126,6 +128,15 @@ impl Screen { self.size } + pub fn composer_hit(&self, x: u16, y: u16) -> Option<(Rect, Position)> { + let (area, dock_rows) = self.composer?; + let row = y.checked_sub(self.top)?; + let from_bottom = self.viewport_height.checked_sub(row)?; + let dock_row = dock_rows.checked_sub(usize::from(from_bottom))?; + let cell = Position::new(x, u16::try_from(dock_row).ok()?); + area.contains(cell).then_some((area, cell)) + } + /// Where the shell left the cursor: the region starts there instead of /// at the bottom of the screen. pub fn set_origin(&mut self, row: u16) { @@ -176,6 +187,9 @@ impl Screen { /// (empty when nothing changed). pub fn render(&mut self, frame: &Frame, size: (u16, u16)) -> Vec { let mut out = Vec::new(); + self.composer = frame + .composer + .map(|area| (area, frame.live.len() - frame.dock)); let resized = size != self.size; let (mut layout, mut wanted) = self.layout(frame, size); let tail = visible_tail(&layout, wanted); diff --git a/crates/dim-cli/src/ui/settings_panel.rs b/crates/dim-cli/src/ui/settings_panel.rs index 6df31bab3b..b507b3d41e 100644 --- a/crates/dim-cli/src/ui/settings_panel.rs +++ b/crates/dim-cli/src/ui/settings_panel.rs @@ -215,11 +215,7 @@ impl SettingsPanel { } .to_owned(), ), - row( - Setting::Mouse, - "Mouse (fullscreen)", - on_off(values.mouse).to_owned(), - ), + row(Setting::Mouse, "Mouse", on_off(values.mouse).to_owned()), row( Setting::Notify, "Notify when agent needs you", diff --git a/crates/dim-cli/src/ui/terminal/mod.rs b/crates/dim-cli/src/ui/terminal/mod.rs index 5299638e88..52c24b4a77 100644 --- a/crates/dim-cli/src/ui/terminal/mod.rs +++ b/crates/dim-cli/src/ui/terminal/mod.rs @@ -319,10 +319,10 @@ impl Terminal { modes::is_live(Mode::Mouse) } - /// Turns mouse reporting on or off on the alternate screen; off hands + /// Turns mouse reporting on or off; off hands /// selection and the wheel back to the terminal. pub fn set_mouse(&mut self, on: bool) -> io::Result<()> { - if on == self.mouse() || !modes::is_live(Mode::AltScreen) { + if on == self.mouse() { return Ok(()); } if on { diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index eb8380f550..a5f11f1b89 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -128,7 +128,7 @@ enum Placement { }, } -/// `config.json` key of the fullscreen mouse switch (`"on"` / `"off"`). +/// `config.json` key of the mouse switch (`"on"` / `"off"`). const MOUSE_KEY: &str = "tuiMouseMode"; /// Where a palette action or a sent message moves the fullscreen view. @@ -400,11 +400,16 @@ fn run_terminal( app.host.shutdown(); return code; } - let mouse = app.mouse && !app.native_selection(); + let mouse = app.mouse + && if full.is_some() { + !app.native_selection() + } else { + app.keyboard_free() && !app.composer.is_empty() + }; if !mouse && let Some(full) = &mut full { full.cancel_click(); } - if full.is_some() && terminal.mouse() != mouse && terminal.set_mouse(mouse).is_err() { + if terminal.set_mouse(mouse).is_err() { let code = terminal.lost(); app.host.shutdown(); return code; @@ -571,7 +576,17 @@ fn run_terminal( } } Wait::Event(InputEvent::Mouse(event)) => { - let Some(full) = &mut full else { continue }; + let Some(full) = &mut full else { + if mouse + && event.kind == crate::ui::terminal::MouseKind::Press + && screen.size() == terminal.size() + && let Some((area, cell)) = screen.composer_hit(event.column, event.row) + { + app.composer.click(cell, area); + dirty = true; + } + continue; + }; dirty |= full.resize(terminal.size()); match full.mouse(event, &app) { MouseOutcome::Ignored => {} @@ -6592,7 +6607,7 @@ impl App { } } let box_top = live.len(); - if self.fullscreen && self.prompt.is_none() && !palette_overlay { + if self.prompt.is_none() && !palette_overlay { frame.composer = Some(Rect::new( (MARGIN + 2 + prompt_width) as u16, (box_top + 1 - frame.dock) as u16, diff --git a/docs/architecture/tui-e2e.md b/docs/architecture/tui-e2e.md index d011677e68..b1eb78cbdd 100644 --- a/docs/architecture/tui-e2e.md +++ b/docs/architecture/tui-e2e.md @@ -106,6 +106,7 @@ daemon. `--keep` leaves the home and raw streams in place for inspection. | terminal-modes | `resize_during_a_stream_rewraps_and_finishes` | A resize while the fixture streams repaints the live output at the new width, keeps the streamed text, and the run still finishes | | terminal-modes | `resize_during_thinking_rewraps_multiline_history` | Expanded reasoning streams in a turn sent as three lines; five resizes (100x24, 60x24, 120x40, 45x18, 100x36) keep every user line and every reasoning line, the transcript settles as a thought, and the answer still arrives | | composer | `fullscreen_composer_click_places_the_cursor` | Click-to-insert in an ASCII draft and between wide characters in a wrapped, vertically scrolled draft | +| composer | `scrollback_click_places_draft_cursor` | Check native mouse ownership before and after editing and the submitted text after clicking on a wrapped row following a wide character | | composer | `composer_edits_multiline_and_stores_a_large_paste` | `Ctrl+J` newline editing, backspace, a five-line bracketed paste stored as an attachment, and the exact prompt text the model receives | | composer | `file_mention_inserts_a_workspace_link` | The `@` picker lists the `--cwd` workspace, inserts the chosen file, and completes a directory prefix to the file under it; the prompt carries both as absolute links | | no-session | `home_commands_without_a_session_answer_and_send_nothing` | `/export`, `/queue` and `/mcp list` run from the palette over a draft answer at home in both layouts, the draft returns to the composer after each, no command sends it, and the fixture model receives no request; `/agent` and a valued `/effort` stay with `tui_home_commands_without_a_session_answer_and_send_nothing` in CI | diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index 131d28bd77..e46e01b414 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -533,6 +533,34 @@ const scenarios = [ await terminal.waitFor('中Y界tail'); }, }, + { + name: 'scrollback_click_places_draft_cursor', + area: 'composer', + title: 'Scrollback captures clicks only while editing and inserts at the clicked cell', + async run(tui) { + await tui.setup({respond: () => ({text: ANSWER})}); + const terminal = await tui.launch(['--scrollback'], {waitForComposer: true, cols: 60}); + const mouseEnabled = () => tui.tmuxRun(['display-message', '-p', '-t', terminal.session, '#{mouse_any_flag}']).trim() === '1'; + assert(!mouseEnabled(), 'empty scrollback draft preserves native selection'); + const prefix = 'a'.repeat(60); + terminal.send(`${prefix}界bc`); + terminal.key('C-j'); + terminal.send('last line'); + await terminal.waitFor('last line'); + assert(mouseEnabled(), 'editing enables terminal mouse reporting'); + const lines = terminal.capture({join: false}).split('\n'); + const row = lines.findIndex((line) => line.includes('界bc')); + assert(row > 0 && lines[row - 1].includes('aaaa'), 'target is on a wrapped row'); + const report = `\x1b[<0;${lines[row].indexOf('界') + 3};${row + 1}`; + terminal.bytes(Buffer.from(`${report}M${report}m`)); + terminal.send('X'); + terminal.key('Enter'); + await terminal.waitFor(ANSWER); + assert.equal(lastTurnText(tui.model), `${prefix}界Xbc\nlast line`); + assert(!mouseEnabled(), 'submitting releases the mouse'); + await exitWith(terminal); + }, + }, { name: 'composer_edits_multiline_and_stores_a_large_paste', area: 'composer', From 57f9390aee06c119e009e3c781a9297994663df6 Mon Sep 17 00:00:00 2001 From: zjywill Date: Thu, 26 Nov 2026 13:49:31 +0800 Subject: [PATCH 2/3] fix: reject stale scrollback clicks and preserve mouse cleanup Amp-Thread-ID: https://ampcode.com/threads/T-01a2125b-f93a-7216-9485-dafd82fea69f --- crates/dim-cli/README.md | 2 +- crates/dim-cli/src/ui/render/screen.rs | 21 +++++++++++++++++++++ crates/dim-cli/src/ui/terminal/mod.rs | 20 ++++++++++++-------- crates/dim-cli/src/ui/terminal/modes.rs | 2 +- crates/dim-cli/src/ui/tui.rs | 11 ++++++++--- scripts/tui-tmux/scenarios.mjs | 13 +++++++++++++ 6 files changed, 56 insertions(+), 13 deletions(-) diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index 12c8f7b639..efcd15c2d0 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -1157,7 +1157,7 @@ answer text (including its retained streaming tail) Both TUI modes share the same composer border layout: the adopted model and, when its configuration carries one, the reasoning effort it sends (`provider / model · effort`) sit at the right of the top border, while shell mode keeps the top-border left title. The bottom border keeps the run status, status slot (a notice, `esc interrupt`, `permission required` / `answer required`, disconnect), background task count, goal and main branch context reading (`1.8K / 256K`) at the left, and the attached Session's workspace, git branch and unread badge at the right, with Home naming the launch directory. The permission preset is not in that border: both modes show only the live permission footer described above, without an `AGENT` prefix, with its hint in the selected interface language. While a prompt replaces the composer, a notice or the disconnect state is drawn once, on the rows above the footer. Scrollback keeps its `›` prompt, while fullscreen omits the prompt mark and keeps mouse targets such as clicking the model label. The live footer is not committed to transcript history. When the workspace differs from the CLI's `--cwd`, the `@` picker names the `--cwd` in its title, so local file completion still says which directory it lists. A box too narrow for the whole model label drops the effort first, then the label. -In scrollback, left-click a text cell to move the insertion point while editing a nonempty draft with mouse mode on. Clearing or submitting the draft, opening a picker or prompt, or turning mouse mode off returns mouse handling to the terminal. While Dim receives mouse reports, native selection and wheel scrolling depend on the terminal's mouse override gesture. +In scrollback, left-click a text cell to move the insertion point while editing a nonempty draft with mouse mode on. Clearing or submitting the draft, opening a picker or prompt, or turning mouse mode off returns mouse handling to the terminal. While Dim receives mouse reports, native selection and wheel scrolling depend on the terminal's mouse override gesture. If you use the terminal's scrollbar or a scrollback key binding, return to the live view before clicking the draft: Dim cannot see the terminal's history offset. The Git branch label follows branch switches in both modes, including switches made by tools or another terminal. At startup the client resolves the workspace's own Git `HEAD` path (including linked worktrees); the existing UI timer reads that file at most once every 10 seconds, without spawning more Git processes, and requests a repaint only when the name changes. Detached HEAD displays `HEAD`; a transient read failure keeps the last known name until the next check. diff --git a/crates/dim-cli/src/ui/render/screen.rs b/crates/dim-cli/src/ui/render/screen.rs index 6aea06b005..43e9af2eef 100644 --- a/crates/dim-cli/src/ui/render/screen.rs +++ b/crates/dim-cli/src/ui/render/screen.rs @@ -128,6 +128,8 @@ impl Screen { self.size } + /// Maps a screen cell to the rendered composer box and cell, keeping screen columns + /// and using dock-relative rows. Cells outside the visible editor return `None`. pub fn composer_hit(&self, x: u16, y: u16) -> Option<(Rect, Position)> { let (area, dock_rows) = self.composer?; let row = y.checked_sub(self.top)?; @@ -901,6 +903,25 @@ mod tests { ) } + #[test] + fn composer_click_tracks_the_visible_box_in_clipped_and_padded_frames() { + let (mut screen, mut emu) = setup(true); + screen.set_origin(0); + for tail in [10, 1] { + let mut rows = vec!["tail"; tail]; + rows.extend(["border", "first", "second", "status"]); + let mut f = docked(&rows, tail, None); + let area = Rect::new(3, 1, 8, 2); + f.composer = Some(area); + drive(&mut screen, &mut emu, &f); + let drawn = emu.rows_text(); + let y = drawn.iter().position(|row| row == "second").unwrap() as u16; + assert_eq!(screen.composer_hit(5, y), Some((area, Position::new(5, 2)))); + assert_eq!(screen.composer_hit(5, y - 2), None); + assert_eq!(screen.composer_hit(2, y), None); + } + } + #[test] fn live_region_is_pinned_to_the_bottom_rows() { let (mut screen, mut emu) = setup(true); diff --git a/crates/dim-cli/src/ui/terminal/mod.rs b/crates/dim-cli/src/ui/terminal/mod.rs index 52c24b4a77..2a33f7fdbf 100644 --- a/crates/dim-cli/src/ui/terminal/mod.rs +++ b/crates/dim-cli/src/ui/terminal/mod.rs @@ -210,6 +210,7 @@ pub struct Terminal { coalesce_min_run: Option, queue: std::collections::VecDeque, keyboard: KeyboardProtocol, + mouse_requested: bool, background_report: Option, clipboard: bool, /// The terminal answered the program status query (`OSC 7501`): it keeps @@ -246,6 +247,7 @@ impl Terminal { ), queue: Default::default(), keyboard: KeyboardProtocol::Legacy, + mouse_requested: false, background_report: None, clipboard: false, program_status: false, @@ -287,9 +289,9 @@ impl Terminal { } else { bytes.extend_from_slice(Mode::Mouse.restore_sequence()); bytes.extend_from_slice(Mode::AltScreen.restore_sequence()); - modes::clear(Mode::Mouse); modes::clear(Mode::AltScreen); } + self.mouse_requested = on; if self.keyboard == KeyboardProtocol::Kitty { bytes.extend_from_slice(Mode::KittyKeyboard.enable_sequence()); } @@ -314,22 +316,17 @@ impl Terminal { self.writer.send(bar.to_vec()) } - /// Mouse reporting is on. - pub fn mouse(&self) -> bool { - modes::is_live(Mode::Mouse) - } - /// Turns mouse reporting on or off; off hands /// selection and the wheel back to the terminal. pub fn set_mouse(&mut self, on: bool) -> io::Result<()> { - if on == self.mouse() { + if on == self.mouse_requested { return Ok(()); } + self.mouse_requested = on; if on { modes::mark(Mode::Mouse); self.writer.send(Mode::Mouse.enable_sequence().to_vec()) } else { - modes::clear(Mode::Mouse); self.writer.send(Mode::Mouse.restore_sequence().to_vec()) } } @@ -419,6 +416,12 @@ impl Terminal { self.writer.pending.load(Ordering::SeqCst) > 0 } + /// Drops mouse reports already read against a superseded scrollback frame. + pub fn discard_queued_mouse(&mut self) { + self.queue + .retain(|event| !matches!(event, InputEvent::Mouse(_))); + } + /// True once a background write failed (terminal gone). pub fn write_failed(&self) -> bool { self.writer.lost.load(Ordering::SeqCst) @@ -597,6 +600,7 @@ impl Terminal { sys::restore_terminal_once_until(deadline); sys::remove_signal_guard(); modes::clear_all(); + self.mouse_requested = false; } fn drain_until_da1(&mut self, deadline: Instant) { diff --git a/crates/dim-cli/src/ui/terminal/modes.rs b/crates/dim-cli/src/ui/terminal/modes.rs index 9cb6d259dc..4ba38dc20d 100644 --- a/crates/dim-cli/src/ui/terminal/modes.rs +++ b/crates/dim-cli/src/ui/terminal/modes.rs @@ -79,7 +79,7 @@ impl Mode { } } -/// The modes currently on, shared with signal handlers. +/// Modes that may still need restoring, including those with a queued reset. static LIVE: AtomicU16 = AtomicU16::new(0); pub fn mark(mode: Mode) { diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 16eb5dc271..c56ce1ffd9 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -470,6 +470,7 @@ fn run_terminal( std::env::var_os("TERMUX_VERSION").is_some(), ); if reflow || !keyboard { + terminal.discard_queued_mouse(); let rows = app.reflow_history(size.0 as usize); let frame = app.frame(size); let wanted = screen.wanted_for(size, frame.live.len()); @@ -493,7 +494,10 @@ fn run_terminal( let frame = app.frame(size); let bytes = match &mut full { Some(full) => full.render(&frame, size, &app.palette, &app), - None => screen.render(&frame, size), + None => { + terminal.discard_queued_mouse(); + screen.render(&frame, size) + } }; if terminal.write(&bytes).is_err() || terminal.write_failed() { let code = terminal.lost(); @@ -578,6 +582,8 @@ fn run_terminal( Wait::Event(InputEvent::Mouse(event)) => { let Some(full) = &mut full else { if mouse + && !dirty + && !terminal.writing() && event.kind == crate::ui::terminal::MouseKind::Press && screen.size() == terminal.size() && let Some((area, cell)) = screen.composer_hit(event.column, event.row) @@ -1318,8 +1324,7 @@ struct App { /// The `/models` picker a Provider's management area was opened from: /// closing the area goes back to the picker, as it was left. models_return: Option, - /// Fullscreen reads the mouse (`tuiMouseMode`); off leaves selection - /// and the wheel to the terminal. + /// Mouse input in both TUI modes (`tuiMouseMode`); off leaves selection and scrolling native. pub mouse: bool, /// Ask the terminal to notify when the run needs the user /// (`tuiNotifyOnComplete`). diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index 159f575523..e4dd2090ea 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -580,7 +580,20 @@ const scenarios = [ await terminal.waitFor(ANSWER); assert.equal(lastTurnText(tui.model), `${prefix}界Xbc\nlast line`); assert(!mouseEnabled(), 'submitting releases the mouse'); + const draft = Array.from({length: 18}, (_, i) => `draft-row-${i}`); + terminal.bytes(Buffer.from(draft.map((line) => `\x1b[200~${line}\x1b[201~`).join('\n'))); + await terminal.waitFor('draft-row-17'); + const visible = terminal.capture({join: false}).split('\n'); + const first = visible.findIndex((line) => line.includes('draft-row-')); + assert(first >= 0 && !visible[first].includes('draft-row-0'), 'the editor is scrolled'); + const oldCell = `\x1b[<0;${visible[first].indexOf('draft-row-') + 1};${first + 1}`; + terminal.bytes(Buffer.from(`\x1b[200~\nnew-row\x1b[201~${oldCell}M${oldCell}mX`)); + await terminal.waitFor('new-rowX'); + terminal.key('Enter'); + await waitForRequest(tui.model, (request) => userText(request) === `${draft.join('\n')}\nnew-rowX`); await exitWith(terminal); + const raw = terminal.raw(); + assert(raw.slice(raw.lastIndexOf('\x1b[?2026l\x1b[0m')).includes('\x1b[?1006l\x1b[?1003l\x1b[?1002l'), 'exit resets mouse reporting even after mouse-off was queued'); }, }, { From ee8dcae40933f77491e908fd9dc87322366857ca Mon Sep 17 00:00:00 2001 From: zjywill Date: Thu, 26 Nov 2026 14:38:30 +0800 Subject: [PATCH 3/3] fix: reject the first ambiguous press after the draft scrolls Amp-Thread-ID: https://ampcode.com/threads/T-01a2125b-f93a-7216-9485-dafd82fea69f --- crates/dim-cli/README.md | 4 +++- crates/dim-cli/src/ui/composer/mod.rs | 5 +++++ crates/dim-cli/src/ui/tui.rs | 8 ++++++++ docs/architecture/tui-e2e.md | 2 +- scripts/tui-tmux/scenarios.mjs | 15 ++++++++++++++- 5 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index efcd15c2d0..ef9fb0a449 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -1157,7 +1157,9 @@ answer text (including its retained streaming tail) Both TUI modes share the same composer border layout: the adopted model and, when its configuration carries one, the reasoning effort it sends (`provider / model · effort`) sit at the right of the top border, while shell mode keeps the top-border left title. The bottom border keeps the run status, status slot (a notice, `esc interrupt`, `permission required` / `answer required`, disconnect), background task count, goal and main branch context reading (`1.8K / 256K`) at the left, and the attached Session's workspace, git branch and unread badge at the right, with Home naming the launch directory. The permission preset is not in that border: both modes show only the live permission footer described above, without an `AGENT` prefix, with its hint in the selected interface language. While a prompt replaces the composer, a notice or the disconnect state is drawn once, on the rows above the footer. Scrollback keeps its `›` prompt, while fullscreen omits the prompt mark and keeps mouse targets such as clicking the model label. The live footer is not committed to transcript history. When the workspace differs from the CLI's `--cwd`, the `@` picker names the `--cwd` in its title, so local file completion still says which directory it lists. A box too narrow for the whole model label drops the effort first, then the label. -In scrollback, left-click a text cell to move the insertion point while editing a nonempty draft with mouse mode on. Clearing or submitting the draft, opening a picker or prompt, or turning mouse mode off returns mouse handling to the terminal. While Dim receives mouse reports, native selection and wheel scrolling depend on the terminal's mouse override gesture. If you use the terminal's scrollbar or a scrollback key binding, return to the live view before clicking the draft: Dim cannot see the terminal's history offset. +In scrollback, left-click a text cell to move the insertion point while editing a nonempty draft with mouse mode on. If the draft has scrolled to a different first row, the first click acknowledges the new view without moving the cursor. Click again to place it. This prevents a delayed click on the previous view from editing the wrong row. + +Clearing or submitting the draft, opening a picker or prompt, or turning mouse mode off returns mouse handling to the terminal. While Dim receives mouse reports, native selection and wheel scrolling depend on the terminal's mouse override gesture. If you use the terminal's scrollbar or a scrollback key binding, return to the live view before clicking the draft: Dim cannot see the terminal's history offset. The Git branch label follows branch switches in both modes, including switches made by tools or another terminal. At startup the client resolves the workspace's own Git `HEAD` path (including linked worktrees); the existing UI timer reads that file at most once every 10 seconds, without spawning more Git processes, and requests a repaint only when the name changes. Detached HEAD displays `HEAD`; a transient read failure keeps the last known name until the next check. diff --git a/crates/dim-cli/src/ui/composer/mod.rs b/crates/dim-cli/src/ui/composer/mod.rs index 51147b92dc..2a418f4d62 100644 --- a/crates/dim-cli/src/ui/composer/mod.rs +++ b/crates/dim-cli/src/ui/composer/mod.rs @@ -1236,6 +1236,11 @@ impl Composer { } } + /// Wrapped row at the top of the rendered textarea. + pub fn rendered_scroll(&self) -> u16 { + self.state.scroll + } + /// Place the cursor at `cell` and clear the selection. Both `cell` and the /// rendered textarea `area` use screen columns and rows counted from the /// top of the unclipped dock. Clicks outside `area` are ignored. diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index c56ce1ffd9..276079dffd 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -317,6 +317,7 @@ fn run_terminal( active: saved.unwrap_or_else(|| default_id.to_owned()), }); let mut dirty = true; + let mut click_scroll = None; let mut last_frame: Option = None; let mut resize: Option = None; let code = loop { @@ -516,6 +517,11 @@ fn run_terminal( dirty = true; } } + if !mouse || full.is_some() { + click_scroll = None; + } else if !dirty { + click_scroll.get_or_insert(app.composer.rendered_scroll()); + } let wait = match (dirty && resize.is_none(), last_frame) { (true, Some(at)) if !terminal.writing() => { FRAME_INTERVAL.saturating_sub(now.duration_since(at)) @@ -587,6 +593,8 @@ fn run_terminal( && event.kind == crate::ui::terminal::MouseKind::Press && screen.size() == terminal.size() && let Some((area, cell)) = screen.composer_hit(event.column, event.row) + && click_scroll.replace(app.composer.rendered_scroll()) + == Some(app.composer.rendered_scroll()) { app.composer.click(cell, area); dirty = true; diff --git a/docs/architecture/tui-e2e.md b/docs/architecture/tui-e2e.md index 6d0f222534..f07b17c402 100644 --- a/docs/architecture/tui-e2e.md +++ b/docs/architecture/tui-e2e.md @@ -105,7 +105,7 @@ daemon. `--keep` leaves the home and raw streams in place for inspection. | terminal-modes | `resize_rewraps_history_without_losing_rows` | Resizing to 60x18 and 140x40 keeps the message and answer, rewraps rows, and draws to the new width: the capture is taken only after the product's own `CSI 3J` reflow and completed frame, tmux reports the target pane size, and the new frame is stable at that width | | terminal-modes | `resize_during_a_stream_rewraps_and_finishes` | A resize while the fixture streams repaints the live output at the new width, keeps the streamed text, and the run still finishes | | terminal-modes | `resize_during_thinking_rewraps_multiline_history` | Expanded reasoning streams in a turn sent as three lines; five resizes (100x24, 60x24, 120x40, 45x18, 100x36) keep every user line and every reasoning line, the transcript settles as a thought, and the answer still arrives | -| composer | `scrollback_click_places_draft_cursor` | Check native mouse ownership before and after editing and the submitted text after clicking on a wrapped row following a wide character | +| composer | `scrollback_click_places_draft_cursor` | Check mouse ownership, wrapped wide-character placement, and that a delayed click across input reads does not edit a different row after the draft scrolls | | composer | `fullscreen_composer_click_places_the_cursor` | Click-to-insert in ASCII and scrolled, wrapped wide text. Releasing in another cell, dragging back to the pressed cell, or typing before release preserves the insertion point | | composer | `fullscreen_composer_click_with_a_clipped_task_strip` | In a short pane with three background tasks, clicking the top visible row of a wrapped draft inserts there. The textarea scrolls inside a padded composer box | | composer | `composer_edits_multiline_and_stores_a_large_paste` | `Ctrl+J` newline editing, backspace, a five-line bracketed paste stored as an attachment, and the exact prompt text the model receives | diff --git a/scripts/tui-tmux/scenarios.mjs b/scripts/tui-tmux/scenarios.mjs index e4dd2090ea..b5adfc12f7 100644 --- a/scripts/tui-tmux/scenarios.mjs +++ b/scripts/tui-tmux/scenarios.mjs @@ -589,8 +589,21 @@ const scenarios = [ const oldCell = `\x1b[<0;${visible[first].indexOf('draft-row-') + 1};${first + 1}`; terminal.bytes(Buffer.from(`\x1b[200~\nnew-row\x1b[201~${oldCell}M${oldCell}mX`)); await terminal.waitFor('new-rowX'); + const before = terminal.capture({join: false}).split('\n')[first]; + terminal.paste('\nlast-row'); + await terminal.waitFor('last-row'); + const after = terminal.capture({join: false}).split('\n')[first]; + assert.notEqual(before, after, 'the old screen cell now shows another draft row'); + terminal.bytes(Buffer.from(`${oldCell}M${oldCell}mY`)); + const edited = await terminal.waitFor(/last-rowY|Ydraft-row-/); + assert(edited.includes('last-rowY'), edited); + terminal.bytes(Buffer.from(`${oldCell}M${oldCell}mZ`)); + const target = after.match(/draft-row-(\d+)/); + assert(target, after); + await terminal.waitFor(`Z${target[0]}`); + draft[Number(target[1])] = `Z${target[0]}`; terminal.key('Enter'); - await waitForRequest(tui.model, (request) => userText(request) === `${draft.join('\n')}\nnew-rowX`); + await waitForRequest(tui.model, (request) => userText(request) === `${draft.join('\n')}\nnew-rowX\nlast-rowY`); await exitWith(terminal); const raw = terminal.raw(); assert(raw.slice(raw.lastIndexOf('\x1b[?2026l\x1b[0m')).includes('\x1b[?1006l\x1b[?1003l\x1b[?1002l'), 'exit resets mouse reporting even after mouse-off was queued');