diff --git a/architecture/notes/pebrel_app/gpui_shell/2026-10-14-terminal-clear-action.md b/architecture/notes/pebrel_app/gpui_shell/2026-10-14-terminal-clear-action.md new file mode 100644 index 000000000..6561ddcc4 --- /dev/null +++ b/architecture/notes/pebrel_app/gpui_shell/2026-10-14-terminal-clear-action.md @@ -0,0 +1,190 @@ +# Bindable terminal clear action (GPUI shell) + +## Status + +Implemented; resolves the clear-screen limitation recorded in +[2026-09-21-macos-command-key-aliases.md](2026-09-21-macos-command-key-aliases.md) +under Consequences and Revisit when. Amended 2026-11-13: the redraw +capability contract tightened to full-sequence consumption across every +reachable keymap (review round 13, PR #653) — see the last Decision +bullet. + +## Context + +The GPUI product shell had no clear-screen action at all. `config::Action::ClearHistory` +and the `Esc("\x0c")` sibling existed only in the legacy shell's action table +(`pebrel_app/src/input/action.rs`), and the product build replaces that module with +`product_input.rs`, so the macOS config-table defaults `⌘K → Esc("\x0c")` plus +`⌘K → ClearHistory` (`pebrel_app/src/config/bindings/defaults.rs`, macOS platform +section) were inert data. Runtime ⌘K belongs to the Shell picker via +`display::keymap::MACOS_COMMAND_ALIASES`. After a user cleared the Shell picker row, +`clear_action` wrote `keybind=cmd+k:ReceiveChar`, which the shell registers as +`NoAction`; ⌘K became inert. Even a hand-written `keybind=cmd+k:ClearHistory` was +dropped because `workspace_binding_in_context` had no `ClearHistory` arm, and the +settings keymap page offered no clear-screen row. Users coming from the +established macOS ⌘K clear convention had no path to that behavior. + +## Evidence + +- `pebrel_app/src/main.rs` selects `product_input.rs` for `input` when the legacy + shell is disabled; `input::Processor` / `process_key_bindings` are legacy-only. +- `pebrel_app/src/config/bindings/defaults.rs` macOS platform table binds ⌘K twice + (`Esc("\x0c")`, `ClearHistory`); `pebrel_terminal/src/term/clear.rs` shows + `ClearMode::Saved` clears only the scrollback while `ClearMode::All` clears the + viewport. +- `pebrel_app/src/gpui_shell/workspace/keyboard_bindings.rs`: the adapter's match + fell through to `_ => None` for `ClearHistory` before this change; user rows are + registered at workspace and terminal depth by `update_keybinds`. +- The 2026-09-21 alias note documents "⌘K after unbinding does not clear the + screen … the key is released but inert" and defers the decision. + +## Decision + +- `nebula_workspace::ClearTerminal` is a new GPUI action. `Action::ClearHistory` + maps to it in `workspace_binding_in_context` with the terminal key context, + the same shape as Copy/Paste, so text inputs never lose the key. +- **No default binding is registered anywhere.** ⌘K stays on the Shell picker on + macOS and nothing changes on Windows/Linux. The action is reachable only through + a user `keybind=` row, now writable from the settings page: `EDITABLE_ACTIONS` + gains a terminal-group row backed by `Action::ClearHistory` (a unit variant that + already round-trips through `parse_action` / `action_storage_name`). +- Semantics branch on the pane's foreground state after an instant app-side wipe + of the viewport and scrollback (`ClearMode::All` + `Saved`): + - Shell at a prompt (OSC 133 `nebula_prompt_active`) with the explicit + redraw capability advertised (`pebrel_editor_redraw`, independent of the + query readiness `pebrel_editor_ready`): write the integration-owned clear + key — `\e[46~` bound to the readline/zle `clear-screen` function, or the + PSReadLine `Ctrl+Shift+F9` → `ClearScreen` chord (`Ctrl+Shift+F11` stays + with clipboard.ps1's native paste) — so the shell's own line editor + clears the glass and repaints prompt, buffer and caret, keeping its line + state in sync. + - Prompt without the advertised redraw capability — no integration at all, + a pre-redraw (2.5.3) integration whose query-only readiness says nothing + about the unbound key, a user-owned redraw key, or a same-shell rebind + that took the key back after the integration had owned it — or a running + command: the view moves the terminal cursor home app-side + (`Handler::goto(0, 0)`); sequential output continues from the top and the + next prompt lands after the last output line. No keyboard byte is ever + written at the prompt (see Rejected alternatives). + - Alternate screen (vim, less, other full-screen programs): the action does + nothing — `^L` is a redraw there, not a clear. + Clearing the grid alone leaves the cursor on its original row and the prompt + stranded; manual acceptance rejected that. The redraw key is a direct PTY + write on the focused pane, not a user-input event, so broadcast fan-out stays + out of scope. Without shell integration the prompt probe reads false, so + clears take the cursor-home branch; the wipe still works and the next Enter + restores a prompt. +- The row label uses the typed message `common.clear_screen` (Simplified Chinese + and English catalogs; other languages fall back per the catalog contract). +- **Amendment (2026-11-13, review round 13):** ownership of the Bash/zsh redraw + key is all-or-nothing across keymaps. A multi-byte chord is not consumed as a + whole in an unbound keymap — vi(zsh) `vicmd` and readline `vi-command` leave + the trailing `~` bound to the invert-case command, so a redraw sent into a + merely-unbound keymap rewrote the user's line ("original" → "originaL"). + Installation therefore scans every reachable keymap and either installs the + built-in clear-screen into each of them (vi users included) or, if any keymap + holds a user binding, installs nothing at all; keymaps that refuse binding + (zsh protected keymaps like `.safe`) are unreachable through a typed chord and + are excluded from the contract rather than killing it. The per-prompt probe + re-verifies exactly the recorded keymap set: anything that is not our + binding — rebind, unbind, macro — revokes the announcement and the view falls + back to the app-side cursor home. + +## Rejected alternatives + +- A pure app-side grid clear with no PTY write (the first implementation): + deterministic under any foreground program, but the cursor stays on its + original row and the shell never repaints the prompt — after the wipe the + screen is blank with a stray cursor, and only the next Enter restores a + visible prompt. Manual acceptance rejected this as broken. +- An app-side cursor-home instead of `^L` at the prompt: desynchronizes the + shell's line state from the screen and breaks cursor-addressed redraws + (wrapped input lines, history search) without any cooperation from the shell. +- An unconditional `^L` (the exact legacy ⌘K pair): correct at the prompt, but + while a command runs the byte stays queued in the tty input queue and the + shell consumes it only after the command exits — clearing the screen a second + time and wiping the output the command produced in between. The prompt-state + probe avoids the deferred wipe. +- Scrollback-only (`ClearMode::Saved` alone, matching the legacy `ClearHistory` + executor): leaves the screen populated; users asking for clear screen expect a + blank viewport plus a dropped scrollback. +- Writing `^L` at the prompt (the first implementation, rejected in review + 2026-11-12): at an OSC 133 prompt the byte is keyboard input to whatever owns + the tty, so it invokes the user's *remapped* Ctrl+L binding, not clear screen. + With a fixture Readline binding that inserts a marker, the marker was appended + to live input; the dispatch test only verified the byte was sent and could not + catch it. The owned redraw key above keeps redraw semantics independent of any + user binding; where the channel is not advertised the action degrades to the + app-side cursor home instead of falling back to a keyboard byte. +- Reassigning ⌘K in `MACOS_COMMAND_ALIASES` to `ClearHistory` (the common macOS + terminal clear convention): changes shipped default behavior for every macOS + user. This change + deliberately preserves existing defaults; users who want it bind ⌘K themselves + through the new row. +- Registering the config table's ⌘K `ClearHistory` default as a GPUI workspace + default: collides with the Shell picker alias in the same keymap source tier and + makes dispatch ambiguous. + +## Consequences + +- The current GPUI shortcut policy assigns Command+K to the Shell picker and + removes competing legacy defaults. Clear screen therefore starts unbound on + macOS as well. Clearing or resetting an unbound Clear screen row does not + consume or release the picker's chord. An explicit user binding still wins + through the existing keymap ownership rules. +- Windows/Linux gain an unbound row and no behavior change; existing default + keybindings are untouched on every platform. +- Files written by earlier builds hold no `ClearHistory` line — the old shell + could not express one — only the `ReceiveChar` leftovers of unbinding the + Shell picker row. Those lines keep their "release the key" semantics after + upgrading, so a pre-update clear-screen attempt stays inert until the user + records the row once (verified against a real upgraded file: the re-record + replaced `cmd+k:ReceiveChar` with `win+k:ReceiveChar` plus the new + `win+k:ClearHistory`, where the later line wins). Auto-rewriting + `ReceiveChar` lines into `ClearHistory` would overwrite an explicitly chosen + "release the key" decision and is rejected. +- At the prompt the redraw key reaches the shell only when the integration + explicitly owns it — query readiness (`pebrel_editor_ready`) and redraw + ownership (`pebrel_editor_redraw`) are separate capabilities, so an upgraded + client facing a live pre-redraw integration (query-only, key unbound) degrades + to the app-side cursor home instead of writing the key. The redraw + advertisement is re-verified against the live binding at every prompt and a + same-shell rebind revokes it with an empty value, which makes the view forget + the ownership; a binding the integration still owns keeps announcing its + token. A user-owned redraw key — including an inert Bash string macro, which + `bind -p`/`bind -X` do not list — withdraws only the redraw capability: query, + completion and pointer support keep working exactly as in the pre-redraw + releases. In the running-command branch no PTY write happens; alternate-screen + sessions are left untouched entirely. +- The legacy shell already executes `Action::ClearHistory` and is unchanged. + +## Validation + +`cargo fmt --all -- --check`, `cargo check -p pebrel --bin pebrel --features +gpui-shell --tests --locked`, the `display::keymap` and +`gpui_shell::workspace::keyboard_bindings` test groups (including the new +adapter, dispatch-probe and label regressions), the clear-screen view matrix +(prompt with query-only readiness — the 2.5.3 regression — with the explicit +redraw capability, with no advertisement, running command, and alternate screen; +the remapped-key case asserts no `^L` byte ever leaves the app), the +settings-pane suite, the i18n contract suites, the +`scripts/tests/test_completion_editor.py` redraw regressions (installed key +clears and keeps the buffer through a real bash/zsh PTY; a user-owned function +binding and a Bash string macro each keep the query capability alive while the +redraw advertisement stays off and the user binding keeps firing; a query-only +session leaves the key unbound; a same-shell rebind revokes the advertisement +with an empty value while a still-owned binding keeps announcing), +`cargo test -p pebrel --test file_line_budget` +and `python3 scripts/check_architecture.py --base ` pass. The dispatch +regression fails without the adapter arm; the label regression fails without the +catalog entries. + +## Supersedes + +None. Extends [2026-09-21-macos-command-key-aliases.md](2026-09-21-macos-command-key-aliases.md); +its alias-table authority and unbind vocabulary are reused unchanged. + +## Revisit when + +The product decides clear screen deserves a default key of its own, or native +shell feedback shows that prompt redraw needs a different integration contract. diff --git a/architecture/notes/pebrel_terminal/tty/2026-11-17-pointer-chord-turn-serialization.md b/architecture/notes/pebrel_terminal/tty/2026-11-17-pointer-chord-turn-serialization.md new file mode 100644 index 000000000..d8fc0fcd7 --- /dev/null +++ b/architecture/notes/pebrel_terminal/tty/2026-11-17-pointer-chord-turn-serialization.md @@ -0,0 +1,87 @@ +# Pointer chord turns must not overlap a render burst + +## Status + +Implemented in the PTY harness (`scripts/tests/test_powershell_pointer.py`). +The chord transport itself is unchanged from +[the native PSReadLine pointer decision](2026-10-31-powershell-native-pointer.md); +this note records a harness contract and the load-fragility evidence behind it. + +## Context + +CI (macos-26-intel) failed `test_native_unicode_moves_range_delete_and_one_undo` +sporadically while the same test passed on the same runner image at other times +of the same day. The pointer protocol drives PSReadLine with ESC-prefixed CSI +chords (`Ctrl+Shift+F10,digit`, `Ctrl+Shift+F12`) written over a real PTY, and +the harness schedules its next chord after a wall-clock quiet window. + +## Evidence + +A byte-level trace (both PTY directions, timestamps) of a failing run showed: + +- The numeric query completed normally (`pebrel_pointer` var arrived). +- The move chord and the snapshot chord were written 304 ms apart with **zero + output between them**: pwsh had not yet reacted to the move chord when the + snapshot chord landed inside its in-flight render burst. +- The subsequent renders show the snapshot chord torn: a standalone Escape + (Windows mode reverts the line — the buffer render collapses to spaces), + then literal `[` and `;` keys inserted (digits swallowed by DigitArgument), + and the `pebrel_editor` var never emitted; the harness timed out after 12 s. + +Reproduced under a 4-way parallel stress loop on macOS x64: 36/40 runs failed, +23 of them with exactly this tear signature (matching the CI assertion and the +captured buffer residues). The same test passes deterministically without +parallel load. In every passing turn the chord was parsed only after the +previous burst had drained (probe, render, quiet). + +## Decision + +The harness serializes protocol turns: before writing any chord it waits +(bounded) for the editor's first reaction byte to the previous write, then +drains the burst to quiet (`PowerShellSession.turn`). The wait-loop poll +interval drops from 100 ms to 20 ms so cursor-position replies land closer to +real-terminal timing. Test assertions are unchanged; no coverage is removed. + +## Rejected alternatives + +- Retry or restart the session on corruption: masks the tear instead of + removing its cause, and could hide a genuinely corrupted buffer behind a + fresh one. +- Longer wall-clock quiet windows: the quiet window expired mid-burst in the + failing trace (304 ms of total silence), so tuning the window alone cannot + anchor on the editor's actual progress. +- Changing the protocol chords: unbound CSI chords necessarily carry an ESC + prefix, and the same encoding is what the GUI negotiates through its + keyboard encoder; there is no non-ESC alternative in the xterm space. +- A background reader thread for cursor-position replies: the failing trace + shows replies arriving 1 ms after each probe, so reply latency was not the + cause; threading would rewrite the harness without addressing the overlap. + +## Consequences + +Each chord is parsed from a quiescent input queue, and the harness now states +its turn discipline in code rather than relying on runner idle time. Turns +cost one reaction wait plus the drain window, so the suite runs somewhat +slower under load. The production exposure is unchanged and documented: the +GUI sends the same chords over a real PTY, so the same tear remains possible +under extreme load; the protocol's query/snapshot replies let the GUI detect a +desynchronized editor, and no field occurrence is known. + +## Validation + +`scripts.tests.test_powershell_pointer` passes. Under the identical 4-way +parallel stress: before the change 23/40 runs showed the tear signature, +after the change 0/40 (the remaining 8 are pwsh cold starts starved past the +12 s startup timeout by four concurrent instances — an artifact of the +artificial parallel load, never observed in CI's serial native jobs). + +## Supersedes + +None. Evidence amendment for +[the native PSReadLine pointer decision](2026-10-31-powershell-native-pointer.md). + +## Revisit when + +A tear is observed outside the test harness, PSReadLine or .NET documents a +reliable ESC-sequence read contract, or the GUI starts batching pointer chords +with its own turn scheduling. diff --git a/pebrel_app/i18n/en-US.json b/pebrel_app/i18n/en-US.json index 7029eef56..89f6c1969 100644 --- a/pebrel_app/i18n/en-US.json +++ b/pebrel_app/i18n/en-US.json @@ -755,6 +755,7 @@ "edit": "Edit", "rename": "Rename", "rename_tab": "Rename tab", + "clear_screen": "Clear screen", "copy": "Copy", "paste": "Paste", "cut": "Cut", diff --git a/pebrel_app/i18n/zh-CN.json b/pebrel_app/i18n/zh-CN.json index d984b1849..1b4f9cbfc 100644 --- a/pebrel_app/i18n/zh-CN.json +++ b/pebrel_app/i18n/zh-CN.json @@ -755,6 +755,7 @@ "edit": "编辑", "rename": "重命名", "rename_tab": "重命名标签页", + "clear_screen": "清屏", "copy": "复制", "paste": "粘贴", "cut": "剪切", diff --git a/pebrel_app/res/shell/powershell.ps1 b/pebrel_app/res/shell/powershell.ps1 index c185120b4..f08913659 100644 --- a/pebrel_app/res/shell/powershell.ps1 +++ b/pebrel_app/res/shell/powershell.ps1 @@ -19,6 +19,15 @@ if (-not $global:PebrelUnixReadLineInstalled) { if ($global:PebrelCompletionInputReady) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_ready=$global:PebrelEditorReady$([char]7)") } + if ($global:PebrelRedrawReady) { + # Re-verify the live chord each prompt: a same-shell rebind revokes + # the capability with an empty value so the view forgets it. + if (Test-PebrelRedrawBinding) { + [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_redraw=$global:PebrelShellToken$([char]7)") + } else { + [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_redraw=$([char]7)") + } + } # OSC 7 is the native location, including paths with spaces or Unicode. if ($PWD.Provider.Name -eq 'FileSystem') { $uri = [Uri]::new($PWD.Path).AbsoluteUri diff --git a/pebrel_app/src/display/keymap.rs b/pebrel_app/src/display/keymap.rs index 50f1b8d60..443c4c538 100644 --- a/pebrel_app/src/display/keymap.rs +++ b/pebrel_app/src/display/keymap.rs @@ -69,6 +69,9 @@ pub(crate) const EDITABLE_ACTIONS: &[(Action, &str, &str)] = &[ (Action::IncreaseFontSize, "增大字号", "Font size up"), (Action::DecreaseFontSize, "减小字号", "Font size down"), (Action::ResetFontSize, "重置字号", "Reset font size"), + // GPUI 壳的清屏没有静态默认键(⌘K 归 Shell 选择器);这一行让用户 + // 能把任意键(含 ⌘K)绑到清屏,落到 ClearTerminal 动作。 + (Action::ClearHistory, "清屏", "Clear screen"), ]; /// 设置页分组(无框裁定 2026-08-09:只用段标题+间距分组,不画容器)。 @@ -78,7 +81,7 @@ pub(crate) const GROUPS: &[(&str, &str, usize)] = &[ ("标签页", "Tabs", 5), ("窗格", "Panes", 7), ("侧栏面板", "Side panels", 2), - ("终端", "Terminal", 9), + ("终端", "Terminal", 10), ]; /// 只读展示行(无法在图形页编辑,TOML/settings 行仍可覆盖其中的表驱动键)。 @@ -216,6 +219,7 @@ fn action_message(action: &Action) -> Option { Action::IncreaseFontSize => Message::SettingsKeymapActionFontSizeUp, Action::DecreaseFontSize => Message::SettingsKeymapActionFontSizeDown, Action::ResetFontSize => Message::SettingsKeymapActionResetFontSize, + Action::ClearHistory => Message::CommonClearScreen, _ => return None, }) } @@ -986,6 +990,24 @@ mod tests { ); } + #[test] + #[cfg(target_os = "macos")] + fn clear_screen_does_not_claim_the_shell_picker_default() { + assert_eq!(GPUI.effective_combo(&Action::ClearHistory, &[]), None); + assert_eq!( + GPUI.effective_combo(&Action::ToggleShellPicker, &[]), + Some(("Command+K".into(), false)) + ); + let mut raw = Vec::new(); + GPUI.clear_action(&mut raw, &Action::ClearHistory); + GPUI.reset_action(&mut raw, &Action::ClearHistory); + assert!(raw.is_empty()); + assert_eq!( + GPUI.effective_combo(&Action::ToggleShellPicker, &build_bindings(&raw)), + Some(("Command+K".into(), false)) + ); + } + #[test] fn frontend_policies_do_not_share_defaults_or_digit_identity() { use super::*; @@ -1084,6 +1106,21 @@ mod tests { assert_eq!(action_label(row, super::super::UiLanguage::ZhCn), "重命名标签页"); } + #[test] + fn clear_screen_is_editable_and_localized_through_the_typed_message() { + use super::*; + let row = + EDITABLE_ACTIONS.iter().find(|(action, ..)| *action == Action::ClearHistory).unwrap(); + for language in super::super::UiLanguage::ALL { + assert_eq!( + action_label(row, *language), + language.text(crate::i18n::Message::CommonClearScreen) + ); + assert!(!action_label(row, *language).is_empty()); + } + assert_eq!(action_label(row, super::super::UiLanguage::ZhCn), "清屏"); + } + #[test] fn clearing_ctrl_k_survives_persistence_and_restore_is_explicit() { use super::*; diff --git a/pebrel_app/src/gpui_shell/terminal/view.rs b/pebrel_app/src/gpui_shell/terminal/view.rs index d2f5c60c5..66182fa01 100644 --- a/pebrel_app/src/gpui_shell/terminal/view.rs +++ b/pebrel_app/src/gpui_shell/terminal/view.rs @@ -58,7 +58,7 @@ use pebrel_terminal::index::{Column, Line, Point as TermPoint, Side}; use pebrel_terminal::render::{CellMetrics, TerminalViewport, ViewportTracker}; use pebrel_terminal::selection::{Selection, SelectionType}; use pebrel_terminal::term::TermMode; -use pebrel_terminal::vte::ansi::CursorStyle; +use pebrel_terminal::vte::ansi::{ClearMode, CursorStyle, Handler as _}; use std::sync::Arc; @@ -514,6 +514,10 @@ pub struct TerminalView { suggestion_task: Option, completion_session: crate::completion::Session, completion_editor: editor::Editor, + /// 拥有 redraw 键的 shell token(`pebrel_editor_redraw` 上报)。与查询 + /// 能力(`completion_editor`)分开声明:旧集成只报 query、不装 redraw + /// 键,二者混用会让升级后的客户端把键发进未绑定它的活动 shell。 + editor_redraw_owner: Option, editor_query_task: Option>, ghost_enabled: bool, completion_style: crate::display::CompletionStyle, @@ -1288,6 +1292,40 @@ impl TerminalView { true } + /// 清屏(设置页「清屏」动作的落点)。应用侧立刻清掉可见屏与回滚(零 + /// 延迟反馈),随后按前台状态分流: + /// - 提示符状态(shell 在等输入,OSC 133 跟踪):发集成自有键让 shell + /// 行编辑器自己清屏重绘提示符,行状态与屏幕保持同步; + /// - 命令运行中或集成通道未就绪:应用侧直接把光标归顶,顺序输出从顶 + /// 部继续;绝不发送 ^L 之类的键盘字节——那会执行 shell 里用户对 + /// Ctrl+L 的任意重绑定(审查裁定 2026-11-12); + /// - 备用屏(vim/less 等全屏程序):^L 不是清屏,整键不动。 + pub fn clear_screen(&mut self, cx: &mut Context) { + let Some(session) = &self.session else { return }; + { + let mut term = session.term.lock(); + if term.mode().contains(TermMode::ALT_SCREEN) { + return; + } + term.clear_screen(ClearMode::All); + term.clear_screen(ClearMode::Saved); + if term.nebula_prompt_active() { + drop(term); + // editor_clear_bytes reads term_mode(), which re-locks the same + // term mutex; the redraw decision must run after the guard is + // released, and the fallback re-locks for the cursor home. + if let Some(bytes) = self.editor_clear_bytes() { + self.write_bytes(bytes); + } else { + session.term.lock().goto(0, 0); + } + } else { + term.goto(0, 0); + } + } + cx.notify(); + } + fn paste_now(&mut self, text: &str, cx: &mut Context) { self.paste_now_impl(text, true, cx); } diff --git a/pebrel_app/src/gpui_shell/terminal/view/editor.rs b/pebrel_app/src/gpui_shell/terminal/view/editor.rs index 828560000..0c9c4851e 100644 --- a/pebrel_app/src/gpui_shell/terminal/view/editor.rs +++ b/pebrel_app/src/gpui_shell/terminal/view/editor.rs @@ -204,6 +204,14 @@ impl TerminalView { if queued == Some(self.prompt_input_epoch) { self.query_completion_editor(cx); } + } else if name == "pebrel_editor_redraw" { + // 与 ready 分开的能力声明:只有当前 shell 的 token 才被认领; + // ready 到达而 redraw 缺席(旧集成、键被占用)时保持 None。 + if self.suggest.completion_context.owns_current(value) { + self.editor_redraw_owner = Some(value.to_owned()); + } else { + self.editor_redraw_owner = None; + } } else if name == "pebrel_editor" { let owner = value.split('\n').next().unwrap_or_default(); if !self.suggest.completion_context.owns_current(owner) { @@ -232,6 +240,28 @@ impl TerminalView { .unwrap_or_else(|| b"\x1b[24;6~".to_vec()) } + /// 提示符重绘字节:`pebrel_editor_redraw` 声明的 shell 集成自有键 + /// (completion.sh 的 `\e[46~` → readline/zle 原生 clear-screen, + /// completion.ps1 的 Ctrl+Shift+F9 → PSReadLine ClearScreen)。redraw + /// 是独立于查询能力(`pebrel_editor_ready`)的显式声明:2.5.3 旧集成 + /// 只报 query、不装 redraw 键,只看 ready 会把键发进未绑定它的活动 + /// shell;用户占用 redraw 键时声明整体缺席,query/补全/指针照常。 + /// 未声明返回 None,调用方退回应用侧光标归顶——绝不退回键盘字节 + /// (^L 会执行 shell 里用户对 Ctrl+L 的任意重绑定)。 + pub(super) fn editor_clear_bytes(&self) -> Option> { + let owner = self.editor_redraw_owner.as_deref()?; + if !self.suggest.completion_context.owns_current(owner) { + return None; + } + if owner.starts_with("pwsh:") { + let key = gpui::Keystroke::parse("ctrl-shift-f9").unwrap(); + super::super::keymap::encode(&key, &self.term_mode()) + .or_else(|| Some(b"\x1b[20;6~".to_vec())) + } else { + Some(b"\x1b[46~".to_vec()) + } + } + pub(super) fn query_completion_editor(&mut self, cx: &mut Context) -> bool { if self.completion_editor.is_querying() { return true; diff --git a/pebrel_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs b/pebrel_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs index 1ff8a6a5d..27f64934a 100644 --- a/pebrel_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs +++ b/pebrel_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs @@ -236,6 +236,14 @@ fn application_drag_stays_with_the_original_pane(cx: &mut TestAppContext) { window.simulate_resize(gpui::size(px(800.0), px(400.0))); window.update(|window, _| window.activate_window()); draw(&mut window); + // The pixel-driven grid resize commits only after the trailing-edge + // RESIZE_SETTLE_DELAY, possibly one paint later than this test's gesture. + // Settle both resize gates and redraw first, or the drag encodes against + // the constructor grid while `view.cols` already reports the widened one. + cx.executor() + .advance_clock(TerminalView::STARTUP_GRID_GRACE + TerminalView::RESIZE_SETTLE_DELAY); + window.run_until_parked(); + draw(&mut window); for (source, target) in [(0, 1), (1, 0)] { let start = cell(&panes[source], &window, 2); let end = cell(&panes[target], &window, 5); diff --git a/pebrel_app/src/gpui_shell/terminal/view/startup.rs b/pebrel_app/src/gpui_shell/terminal/view/startup.rs index 7726b9f56..9bf72d46c 100644 --- a/pebrel_app/src/gpui_shell/terminal/view/startup.rs +++ b/pebrel_app/src/gpui_shell/terminal/view/startup.rs @@ -510,6 +510,7 @@ impl TerminalView { suggestion_task: None, completion_session: crate::completion::Session::default(), completion_editor: super::editor::Editor::default(), + editor_redraw_owner: None, editor_query_task: None, completion_viewport: super::super::completion_viewport::CompletionViewport::default(), ghost_enabled, diff --git a/pebrel_app/src/gpui_shell/terminal/view/startup_tests.rs b/pebrel_app/src/gpui_shell/terminal/view/startup_tests.rs index f4f372428..2ab06e2c8 100644 --- a/pebrel_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/pebrel_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -110,6 +110,214 @@ pub(super) fn feed(view: &mut TerminalView, bytes: &[u8]) { parser.advance(&mut *term, bytes); } +#[gpui::test] +fn clear_screen_clears_history_and_redraws_only_through_the_integration_key( + cx: &mut TestAppContext, +) { + let (view, cx, receiver) = open(cx); + // (prompt, ready, redraw):redraw 是独立于 query 的显式能力。命令运行 + // 中、无任何声明、以及 2.5.3 旧集成的 query-only 会话(ready 有、 + // redraw 缺席——键在旧 shell 里未绑定)都不发任何字节(应用侧光标归 + // 顶);只有 `pebrel_editor_redraw` 声明的提示符才发 `\e[46~`。任何状 + // 态都绝不发 ^L——无论清屏快捷键绑定在哪个键上,^L 都会执行 shell 里 + // 用户对 Ctrl+L 的任意重绑定(审查裁定 2026-11-12)。 + for (prompt, ready, redraw) in + [(false, false, false), (true, false, false), (true, true, false), (true, true, true)] + { + view.update(cx, |view, cx| { + if ready || redraw { + view.process_event( + TermEvent::UserVar { + name: "pebrel_shell".into(), + value: "bash:clear-fixture".into(), + }, + cx, + ); + } + if ready { + view.process_event( + TermEvent::UserVar { + name: "pebrel_editor_ready".into(), + value: "bash:clear-fixture".into(), + }, + cx, + ); + } + if redraw { + view.process_event( + TermEvent::UserVar { + name: "pebrel_editor_redraw".into(), + value: "bash:clear-fixture".into(), + }, + cx, + ); + } + for _ in 0..40 { + feed(view, b"previous output\r\n"); + } + { + let mut term = view.session.as_ref().unwrap().term.lock(); + assert!(term.history_size() > 0); + term.selection = Some(Selection::new( + SelectionType::Simple, + TermPoint::new(Line(0), Column(0)), + Side::Left, + )); + if prompt { + term.nebula_add_prompt_mark(); + } else { + term.nebula_end_prompt(); + } + } + receiver.try_iter().for_each(drop); + view.clear_screen(cx); + let term = view.session.as_ref().unwrap().term.lock(); + assert_eq!(term.history_size(), 0); + assert_eq!(term.grid().display_offset(), 0); + assert!(term.selection.is_none()); + assert!(term.grid().display_iter().all(|cell| cell.c == ' ')); + if !prompt || !redraw { + assert_eq!(term.grid().cursor.point, TermPoint::new(Line(0), Column(0))); + } + }); + let writes: Vec<_> = receiver + .try_iter() + .filter_map(|message| match message { + Msg::Input(bytes) => Some(bytes.into_owned()), + _ => None, + }) + .collect(); + let expected = if prompt && redraw { vec![b"\x1b[46~".to_vec()] } else { vec![] }; + assert_eq!(writes, expected, "prompt={prompt} ready={ready} redraw={redraw}"); + assert!(writes.iter().all(|bytes| !bytes.contains(&0x0c)), "{writes:?}"); + } +} + +#[gpui::test] +fn clear_screen_sends_the_owned_powershell_chord_for_pwsh(cx: &mut TestAppContext) { + let (view, cx, receiver) = open(cx); + view.update(cx, |view, cx| { + view.process_event( + TermEvent::UserVar { name: "pebrel_shell".into(), value: "pwsh:clear-fixture".into() }, + cx, + ); + view.process_event( + TermEvent::UserVar { + name: "pebrel_editor_ready".into(), + value: "pwsh:clear-fixture".into(), + }, + cx, + ); + view.process_event( + TermEvent::UserVar { + name: "pebrel_editor_redraw".into(), + value: "pwsh:clear-fixture".into(), + }, + cx, + ); + feed(view, b"previous output\r\n"); + view.session.as_ref().unwrap().term.lock().nebula_add_prompt_mark(); + receiver.try_iter().for_each(drop); + view.clear_screen(cx); + }); + let writes: Vec<_> = receiver + .try_iter() + .filter_map(|message| match message { + Msg::Input(bytes) => Some(bytes.into_owned()), + _ => None, + }) + .collect(); + let expected = view.read_with(cx, |view, _| { + let key = gpui::Keystroke::parse("ctrl-shift-f9").unwrap(); + vec![keymap::encode(&key, &view.term_mode()).unwrap()] + }); + assert_eq!(writes, expected); + assert!(writes.iter().all(|bytes| !bytes.contains(&0x0c)), "{writes:?}"); +} + +#[gpui::test] +fn clear_screen_forgets_redraw_ownership_when_revoked(cx: &mut TestAppContext) { + let (view, cx, receiver) = open(cx); + view.update(cx, |view, cx| { + for (name, value) in [ + ("pebrel_shell", "bash:rebind-fixture"), + ("pebrel_editor_ready", "bash:rebind-fixture"), + ("pebrel_editor_redraw", "bash:rebind-fixture"), + ] { + view.process_event(TermEvent::UserVar { name: name.into(), value: value.into() }, cx); + } + feed(view, b"previous output\r\n"); + view.session.as_ref().unwrap().term.lock().nebula_add_prompt_mark(); + receiver.try_iter().for_each(drop); + view.clear_screen(cx); + assert_eq!( + receiver + .try_iter() + .filter_map(|message| match message { + Msg::Input(bytes) => Some(bytes.into_owned()), + _ => None, + }) + .collect::>(), + vec![b"\x1b[46~".to_vec()] + ); + // 同一会话内用户重绑了 chord:下一个提示符的撤销上报(空值)让视图 + // 忘掉所有权,再清屏退回应用侧光标归顶,不向已不属于集成的键发字节。 + view.process_event( + TermEvent::UserVar { name: "pebrel_editor_redraw".into(), value: String::new() }, + cx, + ); + receiver.try_iter().for_each(drop); + view.clear_screen(cx); + let term = view.session.as_ref().unwrap().term.lock(); + assert_eq!(term.grid().cursor.point, TermPoint::new(Line(0), Column(0))); + }); + let writes: Vec<_> = receiver + .try_iter() + .filter_map(|message| match message { + Msg::Input(bytes) => Some(bytes.into_owned()), + _ => None, + }) + .collect(); + assert_eq!(writes, Vec::>::new()); + assert!(writes.iter().all(|bytes| !bytes.contains(&0x0c)), "{writes:?}"); +} + +#[gpui::test] +fn clear_screen_keeps_alternate_screen_and_primary_history(cx: &mut TestAppContext) { + let (view, cx, receiver) = open(cx); + view.update(cx, |view, cx| { + for _ in 0..40 { + feed(view, b"primary output\r\n"); + } + let history = view.session.as_ref().unwrap().term.lock().history_size(); + assert!(history > 0); + feed(view, b"\x1b[?1049hfull-screen application"); + let before = { + let term = view.session.as_ref().unwrap().term.lock(); + ( + term.grid().cursor.point, + term.grid().display_iter().map(|cell| cell.c).collect::(), + ) + }; + receiver.try_iter().for_each(drop); + view.clear_screen(cx); + { + let term = view.session.as_ref().unwrap().term.lock(); + assert!(term.mode().contains(TermMode::ALT_SCREEN)); + assert_eq!( + before, + ( + term.grid().cursor.point, + term.grid().display_iter().map(|cell| cell.c).collect::() + ) + ); + } + assert!(receiver.try_iter().all(|message| !matches!(message, Msg::Input(_)))); + feed(view, b"\x1b[?1049l"); + assert_eq!(view.session.as_ref().unwrap().term.lock().history_size(), history); + }); +} + fn refresh_completion_from_grid(view: &mut TerminalView, cx: &mut Context) { let (line, anchor) = { let term = view.session.as_ref().unwrap().term.lock(); diff --git a/pebrel_app/src/gpui_shell/workspace/key_actions.rs b/pebrel_app/src/gpui_shell/workspace/key_actions.rs index 3419d1122..d87c408ea 100644 --- a/pebrel_app/src/gpui_shell/workspace/key_actions.rs +++ b/pebrel_app/src/gpui_shell/workspace/key_actions.rs @@ -164,4 +164,13 @@ impl NebulaWorkspace { view.update(cx, |view, cx| view.paste(window, cx)); } } + + /// 清空焦点终端。清屏由焦点 pane 的视图执行(提示符状态随附的 ^L + /// 也只写该 pane 的 PTY);它不是用户输入事件,与复制/粘贴一样不走 + /// 广播扇出。 + pub(super) fn clear_focused_terminal(&mut self, cx: &mut Context) { + if let Some(view) = self.tabs.get(self.active).and_then(WorkspaceTab::focused_view) { + view.update(cx, |view, cx| view.clear_screen(cx)); + } + } } diff --git a/pebrel_app/src/gpui_shell/workspace/keyboard_bindings.rs b/pebrel_app/src/gpui_shell/workspace/keyboard_bindings.rs index 67cc5cab2..6a692ebde 100644 --- a/pebrel_app/src/gpui_shell/workspace/keyboard_bindings.rs +++ b/pebrel_app/src/gpui_shell/workspace/keyboard_bindings.rs @@ -229,6 +229,13 @@ pub(super) struct SelectTab { #[action(namespace = nebula_workspace, no_json)] pub(super) struct QuitApp; +/// 清屏(`Action::ClearHistory` 的 GPUI 落点),与 SelectTab/QuitApp 同属 +/// 适配层动作。没有静态默认绑定:⌘K 已归 Shell 选择器,清屏只能经设置页 +/// keybind= 行注册。 +#[derive(Clone, Debug, PartialEq, gpui::Action)] +#[action(namespace = nebula_workspace, no_json)] +pub(super) struct ClearTerminal; + /// 最小化当前窗口,macOS 上绑 ⌘M(`Action::Minimize` 的 GPUI 侧落点)。 /// 与 QuitApp 同式:动作与其绑定适配臂同处维护;新动作不再进根文件的 /// actions! 列表,workspace.rs 的行数棘轮得以保持基线。 @@ -316,6 +323,13 @@ fn workspace_binding_in_context( PasteClipboard, scope.or(Some(crate::gpui_shell::terminal::KEY_CONTEXT)), )), + // 清屏只有用户 keybind= 行会走到这里(无静态默认,⌘K 归 Shell + // 选择器);作用域与 Copy/Paste 同型,输入框聚焦时不抢键。 + Action::ClearHistory => Some(KeyBinding::new( + &combo, + ClearTerminal, + scope.or(Some(crate::gpui_shell::terminal::KEY_CONTEXT)), + )), Action::ToggleFullscreen => Some(KeyBinding::new(&combo, ToggleFullscreen, scope)), // ⌘M 最小化当前窗口:视图处理器调 gpui 的 minimize_window。 Action::Minimize => Some(KeyBinding::new(&combo, MinimizeWindow, scope)), diff --git a/pebrel_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs b/pebrel_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs index 9888d5e44..a4d2f36db 100644 --- a/pebrel_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs +++ b/pebrel_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs @@ -122,6 +122,70 @@ mod macos_command_keys { } } +/// 清屏动作必须能被 keybind= 行表达:此前 `Action::ClearHistory` 落入 +/// `_ => None` 被静默丢弃,用户解绑 ⌘K 后该键成为惰性键(#238 note 的 +/// 已知遗留)。这条守住适配分支不再消失。 +#[test] +fn clear_history_maps_to_the_clear_terminal_action() { + use crate::config::Action; + use gpui::{KeyContext, Keymap, Keystroke}; + let bound = workspace_binding_in_context("cmd+k", &Action::ClearHistory, None) + .expect("ClearHistory 必须有对应的 gpui 绑定"); + assert!(bound.action().as_any().is::()); + + // 运行时形状:update_keybinds 在两个作用域各注册一次,这里照抄。 + let user = vec![ + bound, + workspace_binding_in_context( + "cmd+k", + &Action::ClearHistory, + Some(crate::gpui_shell::terminal::KEY_CONTEXT), + ) + .unwrap(), + ]; + // 对照组:⌘K 的静态默认键(Shell 选择器)必须存在,否则「用户绑定的 + // 清屏压过静态默认键」的断言空跑。键表级构造三平台同形;macOS 上 + // ⌘ 别名只在运行时注册的平台差异由 + // `command_shortcut_registration_follows_runtime_platform` 单独守住。 + let mut statics = default_workspace_bindings(); + statics.push(custom_workspace_binding("cmd+k", &Action::ToggleShellPicker).unwrap()); + // macOS 上纯 Ctrl 字符默认键已被 #656 的平台策略释放(对照组表里可能 + // 没有它),所以 Ctrl+K 的期望形状以对照组自身为准,不写平台分支。 + let picker_owns_ctrl_k = statics.iter().any(|binding| { + binding.action().as_any().is::() + && binding.keystrokes().iter().any(|stroke| { + let stroke = stroke.inner(); + stroke.key == "k" && stroke.modifiers.control + }) + }); + let keymap = Keymap::new(with_user_keybindings(&Keymap::new(statics), user)); + + let contexts = [ + KeyContext::parse("Root").unwrap(), + KeyContext::parse(crate::gpui_shell::terminal::KEY_CONTEXT).unwrap(), + ]; + let (bindings, pending) = + keymap.bindings_for_input(&[Keystroke::parse("cmd-k").unwrap()], &contexts); + assert!(!pending); + assert!( + bindings[0].action().as_any().is::(), + "用户绑定的清屏必须压过静态默认键" + ); + // Shell 选择器的 Ctrl+K 默认键不受用户清屏绑定影响(期望形状已在 + // 构造 keymap 前从对照组读取)。 + let (bindings, pending) = + keymap.bindings_for_input(&[Keystroke::parse("ctrl-k").unwrap()], &contexts); + assert_eq!(picker_owns_ctrl_k, !pending && !bindings.is_empty()); + if picker_owns_ctrl_k { + assert!( + bindings[0].action().as_any().is::(), + "清屏绑定不得挤占 Shell 选择器的 Ctrl+K 默认键" + ); + } else { + assert!(bindings.is_empty() && !pending, "被平台策略释放的 Ctrl+K 不得被清屏绑定重新占用"); + } +} + #[test] fn cleared_shortcut_reaches_terminal_and_can_be_restored_without_restart() { use crate::config::Action; @@ -1248,6 +1312,7 @@ mod dispatch { focus: FocusHandle, selected: Option, renamed: usize, + cleared: usize, mode: TermMode, input: Vec, encoded: Vec, @@ -1261,6 +1326,7 @@ mod dispatch { this.selected = action.index_for(10); })) .on_action(cx.listener(|this, _: &RenameActiveTab, _, _| this.renamed += 1)) + .on_action(cx.listener(|this, _: &ClearTerminal, _, _| this.cleared += 1)) .child( div() .size_full() @@ -1294,6 +1360,7 @@ mod dispatch { focus: cx.focus_handle(), selected: None, renamed: 0, + cleared: 0, mode: TermMode::empty(), input: Vec::new(), encoded: Vec::new(), @@ -1383,6 +1450,7 @@ mod dispatch { focus: cx.focus_handle(), selected: None, renamed: 0, + cleared: 0, mode: TermMode::empty(), input: Vec::new(), encoded: Vec::new(), @@ -1421,4 +1489,49 @@ mod dispatch { }); } } + + /// `keybind=cmd+k:ClearHistory`(设置页「清屏」行录制 ⌘K 的落盘形状) + /// 必须端到端派发 ClearTerminal,且按键不进入终端输入流。 + #[gpui::test] + fn clear_screen_shortcut_dispatches_and_stays_out_of_the_terminal_stream( + cx: &mut TestAppContext, + ) { + cx.update(|cx| { + gpui_component::init(cx); + init(cx); + // 运行时形状:update_keybinds 对每条 keybind= 行在两个作用域 + // 各注册一次。 + for scope in [None, Some(crate::gpui_shell::terminal::KEY_CONTEXT)] { + cx.bind_keys([workspace_binding_in_context( + "cmd+k", + &crate::config::Action::ClearHistory, + scope, + ) + .unwrap()]); + } + }); + let mut probe_out = None; + let (_, cx) = cx.add_window_view(|window, cx| { + let probe = cx.new(|cx| TerminalKeyProbe { + focus: cx.focus_handle(), + selected: None, + renamed: 0, + cleared: 0, + mode: TermMode::empty(), + input: Vec::new(), + encoded: Vec::new(), + }); + let focus = probe.read(cx).focus.clone(); + focus.focus(window, cx); + probe_out = Some(probe.clone()); + Root::new(probe, window, cx) + }); + let probe = probe_out.unwrap(); + press("cmd-k", cx); + probe.read_with(cx, |p, _| { + assert_eq!(p.cleared, 1, "清屏绑定必须派发 ClearTerminal"); + assert!(p.input.is_empty(), "清屏快捷键不得进入 PTY 输入流"); + assert!(p.encoded.is_empty()); + }); + } } diff --git a/pebrel_app/src/gpui_shell/workspace/render.rs b/pebrel_app/src/gpui_shell/workspace/render.rs index b528a9e9d..f78ad2ce7 100644 --- a/pebrel_app/src/gpui_shell/workspace/render.rs +++ b/pebrel_app/src/gpui_shell/workspace/render.rs @@ -247,6 +247,9 @@ impl Render for NebulaWorkspace { .on_action(cx.listener(|this, _: &PasteClipboard, window, cx| { this.paste_focused_terminal(window, cx); })) + .on_action(cx.listener(|this, _: &super::keyboard_bindings::ClearTerminal, _, cx| { + this.clear_focused_terminal(cx); + })) .on_action(cx.listener(|this, _: &ToggleFullscreen, window, _cx| { window.toggle_fullscreen(); })) diff --git a/pebrel_terminal/src/tty/completion.ps1 b/pebrel_terminal/src/tty/completion.ps1 index a6d3e5606..0df4bcc50 100644 --- a/pebrel_terminal/src/tty/completion.ps1 +++ b/pebrel_terminal/src/tty/completion.ps1 @@ -28,6 +28,46 @@ if (Get-Command Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor=$payload$([char]7)") } } -BriefDescription $global:PebrelEditorHandlerName + # The prompt-redraw pairing: an owned chord re-bound to the native + # ClearScreen, probed separately so a user-held chord leaves query, + # completion and pointer support untouched — the redraw capability + # is simply not advertised, and the terminal never falls back to a + # keyboard byte that invokes user rebinding. Ctrl+Shift+F9 keeps + # Ctrl+Shift+F11 free for clipboard.ps1's native paste binding. + # Identity is the binding we installed, not the Function display: + # PSReadLine reports a scriptblock's BriefDescription as Function, + # so -BriefDescription ClearScreen can imitate the native name and + # Function alone proves nothing. The Description token below is + # what installation and the per-prompt re-check match; anything + # else already on the chord is user-owned and stays untouched. + $clearExisting = if ($query.Parameters.ContainsKey('Chord')) { + Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -ErrorAction SilentlyContinue + } else { + @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F9','Shift+Ctrl+F9' }) + } + if (-not $clearExisting -or $clearExisting.Function -eq 'Unbound') { + # The redraw install is an optional capability: a PSReadLine that + # refuses the binding must not take the editor and pointer init + # down with it, so its failure stays inside this try and only + # leaves the redraw advertisement off. + try { + $global:PebrelRedrawDescription = 'PebrelRedraw:' + $global:PebrelShellToken + # -Function and -Description live in different parameter sets + # (PSReadLine 2.4.5: "Parameter 'Function' cannot be specified + # in parameter set 'ScriptBlock.'"), so the ScriptBlock set is + # the only one that carries the identity token. The handler + # performs the native ClearScreen work itself — erase display + # and scrollback, then re-prompt — exactly what the built-in + # does, and Description stays what the per-prompt re-check + # matches; Function is a display name scriptblocks imitate. + Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -ScriptBlock { + param($key, $arg) + [Console]::Write("$([char]27)[2J$([char]27)[3J$([char]27)[H") + [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt() + } -Description $global:PebrelRedrawDescription + $global:PebrelRedrawReady = $true + } catch { $global:PebrelRedrawReady = $false } + } # PSReadLine 2.0 loses surrogate pairs inserted after native editing. # Advertise that boundary so completion cannot silently alter a name. $owner = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($global:PebrelShellToken)) @@ -37,3 +77,22 @@ if (Get-Command Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) { } } catch { $global:PebrelCompletionInputReady = $false } } + +# Prompt-redraw re-verification shared by both bootstraps. Reuses the same +# lookup fallback as the installation for PSReadLine builds without -Chord. +function global:Test-PebrelRedrawBinding { + try { + if (-not $global:PebrelRedrawReady) { return $false } + $query = Get-Command Get-PSReadLineKeyHandler -ErrorAction Stop + $bound = if ($query.Parameters.ContainsKey('Chord')) { + Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -ErrorAction SilentlyContinue + } else { + @(Get-PSReadLineKeyHandler -ErrorAction Stop | Where-Object { $_.Key -in 'Ctrl+Shift+F9','Shift+Ctrl+F9' }) + } + # Function is only a display description (see the installation probe), + # and the installed binding is a scriptblock carrying its identity in + # Description: the token is what proves the chord still carries the + # binding this session installed. + $bound -and $bound.Description -eq $global:PebrelRedrawDescription + } catch { $false } +} diff --git a/pebrel_terminal/src/tty/completion.sh b/pebrel_terminal/src/tty/completion.sh index 87e1e69db..b5c9e1118 100644 --- a/pebrel_terminal/src/tty/completion.sh +++ b/pebrel_terminal/src/tty/completion.sh @@ -1,9 +1,90 @@ -# Private editor query; existing user bindings retain ownership of F24. +# Private editor query and prompt redraw, advertised as separate capabilities; +# existing user bindings retain ownership of F24 and the clear-screen redraw key. +# The redraw advertisement is re-verified against the live binding every prompt: +# a same-shell rebind revokes it with an empty value, which lets the view forget +# the ownership, while a binding the integration still owns keeps announcing. +__pebrel_redraw_owned() { + if [ -n "${BASH_VERSION-}" ]; then + # grep -x matches the key's complete binding line without any pattern + # escaping: [[ ]] patterns mangle the entry's "\" and "[" combination, + # a tail-only match would also accept a binding on \e[146~, and a + # plain fixed-string search would match a lookalike line that merely + # contains the entry (a chord sequence ending in \e[46~ bound to + # clear-screen). Only our own binding's full line proves ownership. + # An unrecognized table counts as not owned. + { bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null; } | + grep -qxF '"\e[46~": clear-screen' || return 1 + # Ownership must also hold in every keymap reachable within one prompt, + # and it must be complete: vi mode switches vi-insert <-> vi-command + # mid-line via ESC, and an unbound multi-byte chord is NOT consumed as + # a whole there — vi-command leaves the tail "~" bound to the + # invert-case command, so sending our redraw into a keymap where the + # chord is merely unbound still rewrites the user's line (review + # reproduction: "original" became "originaL"). Every reachable keymap + # must therefore carry exactly our clear-screen binding — nothing else + # on the chord counts, unbound included. Entries are anchored to the + # key's complete line, so a lookalike chord sequence ending in \e[46~ + # never trips the probe; each keymap is restored right after its dump + # and the probe only reads, so the user's bindings stay untouched. + local current dump keymap + current=$(bind -v 2>/dev/null | grep -E '^set keymap ' | cut -d ' ' -f3) + [ -n "$current" ] || return 1 + for keymap in emacs-standard emacs-ctlx emacs-meta vi-insert vi-command vi-move; do + [ "$keymap" = "$current" ] && continue + bind "set keymap $keymap" 2>/dev/null || continue + dump=$({ bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null; } | + grep -E '^"\\e\[46~":') + bind "set keymap $current" 2>/dev/null + [ "$dump" = '"\e[46~": clear-screen' ] || return 1 + done + else + # The bound widget must be the built-in original: bindkey reports the + # value space-separated, so a space-anchored ".clear-screen" tail only + # matches the built-in widget. A bindkey -s macro reporting a quoted + # body (even one reading ".clear-screen") ends in a quote, and a user + # widget shadowing the name reports the bare name — both revoke. + [[ $(bindkey '\e[46~' 2>/dev/null) == *' .clear-screen' ]] || return 1 + # One prompt can switch keymaps mid-line (viins -> vicmd via ESC), and + # the check above only sees the current one. Ownership is re-verified + # against the exact keymap set the installation recorded: every keymap + # in it must still resolve the chord to the built-in widget. An + # unbound keymap is NOT safe — a multi-byte sequence is not consumed + # as a whole there, and vicmd leaves the trailing "~" bound to the + # invert-case command, so sending the redraw would rewrite the user's + # line (review reproduction: "original" became "originaL"). A string + # macro, a user widget, an unbound keymap and one the probe cannot + # query all revoke ownership. The probe only reads, so the user's + # bindings stay untouched. + [[ -n ${__pebrel_redraw_keymaps:-} ]] || return 1 + local keymap report owned=1 + for keymap in ${=__pebrel_redraw_keymaps}; do + report=$(bindkey -M "$keymap" '\e[46~' 2>/dev/null) + case $report in + *' .clear-screen') ;; + *) owned=0; break ;; + esac + done + (( owned )) + fi +} + __pebrel_editor_ready_report() { if [ "${__pebrel_editor_ready:-0}" = 1 ] && [ -n "${__pebrel_shell_token:-}" ]; then printf '\033]1337;SetUserVar=pebrel_editor_ready=%s\007' "$__pebrel_shell_token" if typeset -f __pebrel_pointer_ready_report >/dev/null; then __pebrel_pointer_ready_report; fi fi + # Only an integration that actually owns the redraw key reports it, and it + # keeps reporting only while the binding is still ours. The query capability + # alone says nothing about the redraw key: an upgraded client facing an older + # integration (query-only) must never send the key into a live shell where it + # is simply unbound. + if [ "${__pebrel_editor_redraw:-0}" = 1 ] && [ -n "${__pebrel_shell_token:-}" ]; then + if __pebrel_redraw_owned; then + printf '\033]1337;SetUserVar=pebrel_editor_redraw=%s\007' "$__pebrel_shell_token" + else + printf '\033]1337;SetUserVar=pebrel_editor_redraw=\007' + fi + fi } __pebrel_editor_report() { @@ -32,17 +113,85 @@ __pebrel_editor_report() { # Bash 3 does not expose the native buffer/caret variables used by bind -x. if [ -n "${BASH_VERSION-}" ] && (( BASH_VERSINFO[0] >= 4 )) && [[ $- == *i* ]]; then __pebrel_editor_bound=0 + __pebrel_clear_bound=0 + # bind -p and bind -X do not list string macros; bind -s does. A user macro + # on a private key must keep the key user-owned instead of being replaced. while IFS= read -r __pebrel_binding; do [[ $__pebrel_binding == '"\e[45~":'* ]] && __pebrel_editor_bound=1 - done < <(bind -p 2>/dev/null; bind -X 2>/dev/null) - if [[ $__pebrel_editor_bound == 0 ]] && bind -x '"\e[45~":__pebrel_editor_report' 2>/dev/null; then - __pebrel_editor_ready=1 + [[ $__pebrel_binding == '"\e[46~":'* ]] && __pebrel_clear_bound=1 + done < <(bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null) + # Query and redraw are independent capabilities, each probed before its own + # binding is installed: a user-owned redraw key leaves query, completion and + # pointer support working exactly as in integrations that shipped no redraw. + if [[ $__pebrel_editor_bound == 0 ]]; then + if bind -x '"\e[45~":__pebrel_editor_report' 2>/dev/null; then + __pebrel_editor_ready=1 + fi fi - unset __pebrel_editor_bound __pebrel_binding + if [[ $__pebrel_clear_bound == 0 ]]; then + # The redraw chord is all-or-nothing across keymaps: the capability is + # only announced when the sequence is fully consumed everywhere it can + # be reached, and an unbound tail byte still runs Vi commands (see + # __pebrel_redraw_owned). Scan every reachable keymap first — a user + # binding in any one of them leaves the whole capability off and the + # key untouched — then install the built-in clear-screen into each of + # them, vi users included. The startup keymap is restored afterwards. + __pebrel_clear_free=1 + __pebrel_start_keymap=$(bind -v 2>/dev/null | grep -E '^set keymap ' | cut -d ' ' -f3) + for __pebrel_keymap in emacs-standard emacs-ctlx emacs-meta vi-insert vi-command vi-move; do + bind "set keymap $__pebrel_keymap" 2>/dev/null || continue + while IFS= read -r __pebrel_binding; do + [[ $__pebrel_binding == '"\e[46~":'* ]] && __pebrel_clear_free=0 + done < <(bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null) + done + if [[ -n "$__pebrel_start_keymap" ]]; then + bind "set keymap $__pebrel_start_keymap" 2>/dev/null + fi + if [[ $__pebrel_clear_free == 1 ]]; then + for __pebrel_keymap in emacs-standard emacs-ctlx emacs-meta vi-insert vi-command vi-move; do + bind -m "$__pebrel_keymap" '"\e[46~": clear-screen' 2>/dev/null || { + __pebrel_clear_free=0 + break + } + done + [[ $__pebrel_clear_free == 1 ]] && __pebrel_editor_redraw=1 + fi + unset __pebrel_clear_free __pebrel_start_keymap __pebrel_keymap __pebrel_binding + fi + unset __pebrel_editor_bound __pebrel_clear_bound __pebrel_binding elif [ -n "${ZSH_VERSION-}" ]; then if [[ $(bindkey '\e[45~') == *undefined-key ]]; then zle -N __pebrel_editor_report bindkey '\e[45~' __pebrel_editor_report __pebrel_editor_ready=1 fi + # The redraw chord is all-or-nothing across keymaps (see + # __pebrel_redraw_owned): the capability is announced only when the chord + # is ours in every keymap that can be reached while editing. Scan every + # keymap first — a user binding anywhere (a widget, or a bindkey -s macro + # whose quoted body ends in a quote, even one reading "undefined-key") + # keeps the key untouched and the whole capability off. All free → install + # the built-in into each keymap and record the set for the per-prompt + # re-verification. zsh refuses binding into protected keymaps (like + # .safe); such a keymap can never carry our binding and is not reachable + # through a typed chord, so it is excluded from the contract instead of + # killing it. + __pebrel_clear_free=1 + __pebrel_redraw_keymaps='' + __pebrel_keymaps=(${(f)"$(bindkey -l 2>/dev/null)"}) + if (( ${#__pebrel_keymaps} )); then + for __pebrel_keymap in "${__pebrel_keymaps[@]}"; do + [[ $(bindkey -M "$__pebrel_keymap" '\e[46~' 2>/dev/null) == *' undefined-key' ]] || + __pebrel_clear_free=0 + done + if [[ $__pebrel_clear_free == 1 ]]; then + for __pebrel_keymap in "${__pebrel_keymaps[@]}"; do + if bindkey -M "$__pebrel_keymap" '\e[46~' .clear-screen 2>/dev/null; then + __pebrel_redraw_keymaps="$__pebrel_redraw_keymaps $__pebrel_keymap" + fi + done + [[ -n $__pebrel_redraw_keymaps ]] && __pebrel_editor_redraw=1 + fi + fi + unset __pebrel_clear_free __pebrel_keymaps __pebrel_keymap fi diff --git a/pebrel_terminal/src/tty/windows/mod.rs b/pebrel_terminal/src/tty/windows/mod.rs index 65a410d42..579481a06 100644 --- a/pebrel_terminal/src/tty/windows/mod.rs +++ b/pebrel_terminal/src/tty/windows/mod.rs @@ -438,6 +438,7 @@ $global:NebulaPromptTemplate = { $clipboardReady = Get-PebrelClipboardCapability [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_clipboard_ready=$clipboardReady$([char]7)") if ($global:PebrelCompletionInputReady) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_ready=$global:PebrelEditorReady$([char]7)") } + if ($global:PebrelRedrawReady) { if (Test-PebrelRedrawBinding) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_redraw=$global:PebrelShellToken$([char]7)") } else { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_redraw=$([char]7)") } } $global:NebulaPromptCount = [int]$global:NebulaPromptCount + 1 $global:NebulaLastCommandSucceeded = $originalDollarQuestion $global:NebulaLastCommandExitCode = $originalLastExitCode diff --git a/scripts/tests/test_completion_editor.py b/scripts/tests/test_completion_editor.py index 7d0eae6d3..afd91ff63 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -7,6 +7,7 @@ import re import shutil import subprocess +import time import unittest from scripts.tests import test_shell_integration as shell_integration @@ -39,7 +40,10 @@ def snapshot(self, session: shell_integration.ShellSession) -> tuple[str, int, s self.assertTrue(owner.startswith(("bash:", "zsh:", "wsl|")), owner) return owner, int(cursor), line - def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False) -> shell_integration.ShellSession: + def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, + owned_redraw: bool = False, owned_macro: bool = False, + vicmd_widget: bool = False, vicmd_macro: bool = False, + vi_command_macro: bool = False, vi_mode: bool = False) -> shell_integration.ShellSession: root = Path(__file__).resolve().parents[2] program = shutil.which(shell) if not program: @@ -64,13 +68,59 @@ def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False) - rc.write_text(body.group(1) + "\n" + adapter) args = ["--noprofile", "--rcfile", str(rc), "-i"] if shell == "bash" else ["-d", "-i"] env = {} if shell == "bash" else {"ZDOTDIR": str(directory)} - if owned_binding: + if owned_binding or owned_redraw or owned_macro or vicmd_widget or vicmd_macro or vi_command_macro or vi_mode: if shell == "bash": inputrc = self.fixture.home / ".inputrc" - inputrc.write_text('"\\e[45~": beginning-of-line\n') + lines = "" + if owned_binding: + lines += '"\\e[45~": beginning-of-line\n' + if owned_redraw: + lines += '"\\e[46~": beginning-of-line\n' + if owned_macro: + # A string macro, which bind -p and bind -X do not list. + lines += '"\\e[46~": "PEBREL-USER-MACRO"\n' + if vi_command_macro: + # vi mode: the integration installs its clear-screen into + # the startup keymap (vi-insert) while the chord carries a + # user macro in vi-command, reachable mid-prompt via ESC. + # The leading "a" makes the vi-command macro append text, + # so the insertion is deterministic. + lines += 'set editing-mode vi\nset keymap vi-command\n"\\e[46~": "aPEBREL-USER-MACRO"\n' + elif vi_mode: + # Plain vi mode, no custom keys anywhere on the chord. + lines += 'set editing-mode vi\n' + inputrc.write_text(lines) env["INPUTRC"] = str(inputrc) else: - (self.fixture.home / ".zshrc").write_text("bindkey '\\e[45~' beginning-of-line\n") + zshrc = "" + if owned_binding: + zshrc += "bindkey '\\e[45~' beginning-of-line\n" + if owned_redraw: + zshrc += "bindkey '\\e[46~' beginning-of-line\n" + if owned_macro: + zshrc += "bindkey -s '\\e[46~' 'PEBREL-USER-MACRO'\n" + if vicmd_widget: + # vi mode: the chord is free in viins but carries a user + # widget in vicmd, reachable mid-prompt via ESC. + zshrc += ( + "bindkey -v\n" + "userwid() { BUFFER+='VICMD-USER' }; zle -N userwid\n" + "bindkey -M vicmd '\\e[46~' userwid\n" + ) + if vicmd_macro: + # vi mode: the chord resolves to our built-in in viins, but + # vicmd carries a quoted string macro whose body merely + # contains the word undefined-key. A bare undefined-key + # report means unbound; a quoted macro ends in a quote and + # must revoke. + zshrc += ( + "bindkey -v\n" + "bindkey -M vicmd -s '\\e[46~' 'aundefined-key'\n" + ) + if vi_mode: + # Plain vi mode, no custom keys anywhere on the chord. + zshrc += "bindkey -v\n" + (self.fixture.home / ".zshrc").write_text(zshrc) session = shell_integration.ShellSession(program, self.fixture.home, args, env) self.addCleanup(session.close) session.wait(b"\x1b]133;A\x07") @@ -134,6 +184,304 @@ def test_ssh_bash_bootstrap_retains_user_owned_query_binding(self) -> None: def test_ssh_zsh_bootstrap_retains_user_owned_query_binding(self) -> None: self.check_bootstrap_binding("zsh", "ssh") + def check_integration_clear(self, shell: str, route: str) -> None: + session = self.start_bootstrap(shell, route) + ready = re.search(rb"SetUserVar=pebrel_editor_ready=([^\x07]+)\x07", session.output) + if shell == "bash": + version = subprocess.check_output( + [shutil.which(shell), "--noprofile", "--norc", "-c", 'printf "%s" "${BASH_VERSINFO[0]}"'], + text=True, + ) + if int(version) < 4: + # Legacy Bash never installs the channel, so nothing owns the + # redraw key either: the byte stays inert for the host to decide. + self.assertIsNone(ready, session.output) + return + self.assertIsNotNone(ready, session.output) + # The redraw key drives the line editor's own clear-screen: the editor + # wipes the glass and repaints prompt, buffer and caret. + os.write(session.master, b"echo kept-line") + os.write(session.master, b"\x1b[46~") + output = session.wait(b"\x1b[2J") + self.assertIn(b"\x1b[2J", output) + os.write(session.master, b"\n") + output = session.wait(b"kept-line\r\n") + self.assertIn(b"kept-line\r\n", output) + # While the integration still owns the key, every prompt keeps + # announcing the redraw capability with the same token. + sustained = session.command("printf 'SUSTAINED\\n'", b"SUSTAINED\r\n") + self.assertIn(b"SetUserVar=pebrel_editor_redraw=", sustained) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=\x07", sustained) + + def test_ssh_bash_bootstrap_redraws_through_the_owned_clear_key(self) -> None: + self.check_integration_clear("bash", "ssh") + + def test_ssh_zsh_bootstrap_redraws_through_the_owned_clear_key(self) -> None: + self.check_integration_clear("zsh", "ssh") + + def check_legacy_bash(self, shell: str, session: shell_integration.ShellSession) -> bool: + if shell == "bash": + version = subprocess.check_output( + [shutil.which(shell), "--noprofile", "--norc", "-c", 'printf "%s" "${BASH_VERSINFO[0]}"'], + text=True, + ) + if int(version) < 4: + # Legacy Bash installs neither capability and binds no key. + self.assertNotIn(b"SetUserVar=pebrel_editor_ready=", session.output) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=", session.output) + return True + return False + + def check_owned_redraw_binding(self, shell: str, route: str) -> None: + session = self.start_bootstrap(shell, route, owned_redraw=True) + if self.check_legacy_bash(shell, session): + return + # A user-owned redraw key only withdraws the redraw capability: the + # query capability keeps reporting, matching the pre-redraw releases. + self.assertIn(b"SetUserVar=pebrel_editor_ready=", session.output) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=", session.output) + os.write(session.master, b"echo tail\x1b[46~printf 'OWNED-REDRAW\\n'; \n") + output = session.wait(b"OWNED-REDRAW\r\n") + self.assertIn(b"OWNED-REDRAW\r\n", output) + self.assertNotIn(b"SetUserVar=pebrel_editor=", output) + # The user's function binding survived; the reserved chord itself was + # never replaced by clear-screen (the table still lists the user's + # normal Ctrl+L entry, so only the reserved chord may be inspected). + if shell == "bash": + bindings = session.command( + "bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null; printf 'BINDINGS-END\\n'", + b"BINDINGS-END\r\n", + ) + self.assertIn(b'"\\e[46~": beginning-of-line', bindings) + self.assertNotIn(b'"\\e[46~": clear-screen', bindings) + + def test_ssh_bash_bootstrap_retains_user_owned_redraw_binding(self) -> None: + self.check_owned_redraw_binding("bash", "ssh") + + def test_ssh_zsh_bootstrap_retains_user_owned_redraw_binding(self) -> None: + self.check_owned_redraw_binding("zsh", "ssh") + + def check_owned_redraw_macro(self, shell: str, route: str) -> None: + session = self.start_bootstrap(shell, route, owned_macro=True) + if self.check_legacy_bash(shell, session): + return + # A string macro on the redraw key is invisible to bind -p and bind -X + # in Bash; the probe must still treat the key as user-owned and leave + # the macro working, with the query capability unaffected. + self.assertIn(b"SetUserVar=pebrel_editor_ready=", session.output) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=", session.output) + os.write(session.master, b"echo tail\x1b[46~") + _, _, line = self.snapshot(session) + self.assertEqual(line, "echo tailPEBREL-USER-MACRO") + if shell == "bash": + bindings = session.command( + "bind -s 2>/dev/null; printf 'BINDINGS-END\\n'", + b"BINDINGS-END\r\n", + ) + self.assertIn(b'PEBREL-USER-MACRO', bindings) + self.assertNotIn(b'"\\e[46~": clear-screen', bindings) + + def test_ssh_bash_bootstrap_retains_user_owned_redraw_macro(self) -> None: + self.check_owned_redraw_macro("bash", "ssh") + + def test_ssh_zsh_bootstrap_retains_user_owned_redraw_macro(self) -> None: + self.check_owned_redraw_macro("zsh", "ssh") + + def check_query_only_session(self, shell: str, route: str) -> None: + # The pre-redraw integrations advertised query readiness only and left + # the redraw key unbound: the current installation must not touch the + # key at all in such a session. + session = self.start_bootstrap(shell, route) + if self.check_legacy_bash(shell, session): + return + ready_token = re.search(rb"SetUserVar=pebrel_editor_ready=([^\x07]+)\x07", session.output) + self.assertIsNotNone(ready_token, session.output) + # Withdraw the redraw binding this invocation installed — it now spans + # every keymap, so the withdrawal must too — which lands the session + # exactly where a query-only integration advertises: the chord free in + # every keymap. + session.command( + "for km in emacs-standard emacs-ctlx emacs-meta vi-insert vi-command vi-move; do" + " bind -m \"$km\" -r '\\e[46~' 2>/dev/null; done;" + " for km in $(bindkey -l 2>/dev/null); do bindkey -M \"$km\" -r '\\e[46~' 2>/dev/null; done;" + " printf 'WITHDRAWN\\n'", + b"WITHDRAWN\r\n", + ) + # The next prompt re-verifies ownership and revokes the capability with + # an empty value while query readiness keeps its token. + output = session.command("printf 'REPROBE\\n'", b"REPROBE\r\n") + self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", output) + self.assertIn(ready_token.group(0), output) + if shell == "bash": + bindings = session.command( + "bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null; printf 'BINDINGS-END\\n'", + b"BINDINGS-END\r\n", + ) + self.assertNotIn(b'"\\e[46~"', bindings) + self.assertIn(b'"\\e[45~"', bindings) + else: + output = session.command("bindkey '\\e[46~'; printf 'UNBOUND-CHECK\\n'", b"UNBOUND-CHECK\r\n") + self.assertIn(b"undefined-key", output) + + def test_ssh_bash_bootstrap_query_only_session_leaves_redraw_unbound(self) -> None: + self.check_query_only_session("bash", "ssh") + + def test_ssh_zsh_bootstrap_query_only_session_leaves_redraw_unbound(self) -> None: + self.check_query_only_session("zsh", "ssh") + + def check_redraw_rebind(self, shell: str, route: str) -> None: + # The advertisement follows the live binding: rebinding the chord in + # the same shell — without reconnecting — revokes the capability on + # the next prompt, and the user's new binding keeps firing. + # zsh additionally covers the two lookalike rebinds from review: a + # macro whose text is exactly the widget's name, and a user widget + # shadowing that name — neither may keep the capability announced. + rebinds = { + "bash": [ + # Review repro: a lookalike line that merely CONTAINS the + # entry (a chord sequence ending in \e[46~ bound to + # clear-screen) must not satisfy the probe once the real + # entry is gone — the quoted macro keeps the chord and fires. + ( + "bind '\"\\C-x\\\"\\e[46~\": clear-screen';" + " bind '\"\\e[46~\": \"QUOTED-KEY-MACRO\"'", + "QUOTED-KEY-MACRO", + ), + ("bind '\"\\e[46~\": \"PEBREL-REBIND\"'", "PEBREL-REBIND"), + ], + "zsh": [ + ("bindkey -s '\\e[46~' 'PEBREL-REBIND'", "PEBREL-REBIND"), + ("bindkey -s '\\e[46~' 'clear-screen'", "clear-screen"), + ( + "userfn() { BUFFER+='USERWID'; }; zle -N clear-screen userfn;" + " bindkey '\\e[46~' clear-screen", + "USERWID", + ), + ], + }[shell] + session = self.start_bootstrap(shell, route) + if self.check_legacy_bash(shell, session): + return + token = re.search(rb"SetUserVar=pebrel_editor_redraw=([^\x07]+)\x07", session.output) + self.assertIsNotNone(token, session.output) + if shell == "bash": + # A decoy clear-screen on \e[146~ must not satisfy the probe for + # \e[46~: the following rebinds revoke despite the decoy staying. + session.command("bind '\"\\e[146~\": clear-screen'; printf 'DECOY\\n'", b"DECOY\r\n") + for rebind, inserted in rebinds: + os.write(session.master, b"\x15") # discard any line from the prior case + session.command(rebind + "; printf 'REBIND-DONE\\n'", b"REBIND-DONE\r\n") + output = session.command("printf 'REBOUND\\n'", b"REBOUND\r\n") + self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", output) + self.assertIn(b"SetUserVar=pebrel_editor_ready=", output) + os.write(session.master, b"echo tail\x1b[46~") + _, _, line = self.snapshot(session) + self.assertEqual(line, f"echo tail{inserted}", f"{shell}: {rebind}") + + def test_ssh_bash_rebinding_the_redraw_chord_revokes_the_advertisement(self) -> None: + self.check_redraw_rebind("bash", "ssh") + + def test_ssh_zsh_rebinding_the_redraw_chord_revokes_the_advertisement(self) -> None: + self.check_redraw_rebind("zsh", "ssh") + + def check_redraw_keymap_switch(self, route: str) -> None: + # vi mode: the prompt validates the main keymap, but one prompt can + # switch keymaps mid-line (ESC -> vicmd). A user widget on the chord + # in vicmd keeps the capability revoked — announcing from viins alone + # would send the byte into user code — while the widget itself stays. + session = self.start_bootstrap("zsh", route, vicmd_widget=True) + # A user widget on the chord in any keymap aborts the whole install: + # the capability is never announced at all — no token and no empty + # revocation either — while the widget itself stays. + self.assertIsNotNone( + re.search(rb"SetUserVar=pebrel_editor_ready=([^\x07]+)\x07", session.output), + session.output, + ) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=", session.output) + # Within the same prompt: ESC switches to vicmd and the chord fires + # the user's widget into the line, then Enter runs the buffer. + os.write(session.master, b"echo tail") + time.sleep(0.4) + os.write(session.master, b"\x1b") + time.sleep(0.4) + os.write(session.master, b"\x1b[46~\n") + output = session.wait(b"tailVICMD-USER\r\n") + self.assertIn(b"tailVICMD-USER\r\n", output) + + def test_ssh_zsh_redraw_keymap_switch_in_the_same_prompt_revokes(self) -> None: + self.check_redraw_keymap_switch("ssh") + + def check_redraw_foreign_keymap_macro(self, shell: str, route: str) -> None: + # The chord is ours in the startup keymap, but a quoted macro waits in + # the keymap ESC reaches mid-prompt (vicmd / vi-command). A macro body + # that merely contains the word undefined-key is user code, not an + # unbound key: the prompt must revoke instead of announcing, and the + # macro keeps firing. + flag = {"bash": "vi_command_macro", "zsh": "vicmd_macro"}[shell] + session = self.start_bootstrap(shell, route, **{flag: True}) + if self.check_legacy_bash(shell, session): + return + # A user binding in any keymap aborts the whole install: no redraw + # announcement and no empty revocation either, while query readiness + # and the user's macro keep working. + self.assertIsNotNone( + re.search(rb"SetUserVar=pebrel_editor_ready=([^\x07]+)\x07", session.output), + session.output, + ) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=", session.output) + # Within the same prompt: ESC switches to the foreign keymap and the + # chord fires the user's macro into the line, then Enter runs it. + os.write(session.master, b"echo tail") + time.sleep(0.4) + os.write(session.master, b"\x1b") + time.sleep(0.4) + os.write(session.master, b"\x1b[46~\n") + output = session.wait(b"tailPEBREL-USER-MACRO\r\n" if shell == "bash" else b"tailundefined-key\r\n") + self.assertIn(b"tailPEBREL-USER-MACRO\r\n" if shell == "bash" else b"tailundefined-key\r\n", output) + + def test_ssh_bash_redraw_macro_in_the_vi_command_keymap_revokes(self) -> None: + self.check_redraw_foreign_keymap_macro("bash", "ssh") + + def test_ssh_zsh_quoted_macro_in_another_keymap_revokes(self) -> None: + self.check_redraw_foreign_keymap_macro("zsh", "ssh") + + def check_redraw_vi_mode_plain(self, shell: str, route: str) -> None: + # Review reproduction, vi mode with no custom keys anywhere on the + # chord: the capability is announced only because the installation now + # covers every reachable keymap, so vicmd / vi-command consume the + # whole chord with our clear-screen. Sending it mid-line clears the + # glass and leaves the line intact — the tail "~" must never run the + # invert-case command ("original" -> "originaL"). + session = self.start_bootstrap(shell, route, vi_mode=True) + if self.check_legacy_bash(shell, session): + return + self.assertIsNotNone( + re.search(rb"SetUserVar=pebrel_editor_redraw=([^\x07]+)\x07", session.output), + session.output, + ) + os.write(session.master, b"printf 'LINE:%s\\n' original") + time.sleep(0.4) + os.write(session.master, b"\x1b") + time.sleep(0.4) + os.write(session.master, b"\x1b[46~") + time.sleep(0.4) + os.write(session.master, b"\n") + output = session.wait(b"LINE:original\r\n") + self.assertIn(b"LINE:original\r\n", output) + self.assertNotIn(b"originaL", session.output) + + def test_ssh_zsh_plain_vi_mode_fully_consumes_the_redraw_chord(self) -> None: + self.check_redraw_vi_mode_plain("zsh", "ssh") + + def test_ssh_bash_plain_vi_mode_fully_consumes_the_redraw_chord(self) -> None: + self.check_redraw_vi_mode_plain("bash", "ssh") + + def test_ssh_bash_bootstrap_query_only_session_leaves_redraw_unbound(self) -> None: + self.check_query_only_session("bash", "ssh") + + def test_ssh_zsh_bootstrap_query_only_session_leaves_redraw_unbound(self) -> None: + self.check_query_only_session("zsh", "ssh") + def check_middle_edit(self, shell: str) -> None: session = self.start(shell) line = 'echo "中-old" tail' diff --git a/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index ee7c24dfb..410cbec8d 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -30,11 +30,25 @@ def settle(self, quiet: float = 0.3) -> None: block = os.read(self.master, 65536) self.consume(block) + def turn(self) -> None: + # PSReadLine accepts an ESC-prefixed chord only while the rest of the + # sequence is already readable; a chord written into the previous turn's + # render burst is torn into a standalone Escape plus literal tail keys + # under load (the line is reverted or littered, and the handler never + # runs). Anchor every chord on the editor's first reaction, then drain + # the burst, so each chord is parsed from a quiescent input queue. + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if select.select([self.master], [], [], 0.02)[0]: + self.consume(os.read(self.master, 65536)) + break + self.settle() + def wait(self, marker: bytes) -> bytes: collected = b"" deadline = time.monotonic() + 12 while time.monotonic() < deadline: - if select.select([self.master], [], [], 0.1)[0]: + if select.select([self.master], [], [], 0.02)[0]: block = os.read(self.master, 65536) collected += block self.consume(block) @@ -62,6 +76,7 @@ def start(self, mode: str = "Emacs", before: str = "", *, legacy: bool = False) script = home / "init.ps1" (home / "native-editor.ps1").write_text( (root / "completion.ps1").read_text(encoding="utf-8") + "\n" + + (root / "clipboard.ps1").read_text(encoding="utf-8") + "\n" + (root / "pointer.ps1").read_text(encoding="utf-8"), encoding="utf-8", ) bootstrap = home / "bootstrap.ps1" @@ -116,7 +131,7 @@ def value(self, session: PowerShellSession, name: str) -> list[str]: return base64.b64decode(match[1]).decode().split("\n", 3) def action(self, session: PowerShellSession, argument: int) -> None: - session.settle() + session.turn() digits = b"".join(b"\x1b[21;6~" + digit.encode() for digit in str(argument)) os.write(session.master, digits + b"\x1b[24;6~") @@ -125,7 +140,7 @@ def query(self, session: PowerShellSession, nonce: int = 20000) -> list[str]: return self.value(session, "pebrel_pointer") def snapshot(self, session: PowerShellSession) -> tuple[int, str]: - session.settle() + session.turn() os.write(session.master, b"\x1b[24;6~") owner, unit, cursor, line = self.value(session, "pebrel_editor") self.assertEqual((owner, unit), ("pwsh:fixture", "utf16")) @@ -215,13 +230,145 @@ def test_vi_and_user_binding_ownership_are_not_advertised(self) -> None: self.assertNotIn(b"SetUserVar=pebrel_pointer_ready=", session.output) def test_pointer_chords_preserve_the_clipboard_key(self) -> None: - session = self.start(before="Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function BeginningOfLine") + # An unrelated user-held chord (never a Pebrel-owned F-key) must not + # disturb the native pointer or editor channels. + session = self.start(before="Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F2 -Function BeginningOfLine") + os.write(session.master, b"echo abc") + self.assertEqual(self.query(session)[3], "echo abc") + self.action(session, 1 + 5) + self.assertEqual(self.snapshot(session), (5, "echo abc")) + # The owned redraw chord clears the glass through the line editor: the + # buffer and caret survive it in place. + os.write(session.master, b"\x1b[20;6~") + self.assertEqual(self.snapshot(session), (5, "echo abc")) + + def test_user_owned_redraw_chord_withdraws_the_editor_channel(self) -> None: + # Ctrl+Shift+F9 is the owned prompt-redraw chord: a user binding on it + # withdraws only the redraw capability. Query, completion, pointer and + # the native paste chord keep working exactly as in the pre-redraw + # releases. + session = self.start( + before="Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -Function BeginningOfLine" + ) + self.assertIn(b"SetUserVar=pebrel_editor_ready=", session.output) + self.assertIn(b"SetUserVar=pebrel_pointer_ready=", session.output) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=", session.output) + os.write(session.master, b"echo probe\x1b[24;6~") + self.assertEqual(self.value(session, "pebrel_editor")[3], "echo probe") + os.write(session.master, b"\x1b[20;6~") + # The user's BeginningOfLine still owns the chord, not ClearScreen. + session.settle() + self.assertEqual(self.snapshot(session), (0, "echo probe")) + + def test_production_load_order_keeps_paste_and_redraw_independent(self) -> None: + # Production loads completion.ps1 before clipboard.ps1: the redraw + # chord must never squat on the native paste's Ctrl+Shift+F11. The + # installed redraw identity lives in Description; Function is only a + # display name (the installed handler is a scriptblock). + session = self.start() + os.write(session.master, b"(Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F9).Description\r") + output = session.wait(b"PS> ") + self.assertIn(b"PebrelRedraw:cHdzaDpmaXh0dXJl", output) + os.write(session.master, b"(Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11).Function\r") + output = session.wait(b"PS> ") + self.assertIn(b"PebrelClipboardPaste", output) + self.assertNotIn(b"PebrelRedraw:", output.split(b"(Get-PSReadLineKeyHandler")[-1]) + + def test_redraw_identity_is_the_description_token(self) -> None: + # The installed redraw handler is a scriptblock performing the native + # ClearScreen work, carrying its identity in Description: Function is + # a display name and proves nothing, so the re-check matches the token + # alone — and the chord still clears the glass through the line editor. + session = self.start() + self.assertIn(b"SetUserVar=pebrel_editor_redraw=cHdzaDpmaXh0dXJl\x07", session.output) + os.write(session.master, b"(Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F9).Description\r") + output = session.wait(b"PS> ") + self.assertIn(b"PebrelRedraw:cHdzaDpmaXh0dXJl", output) os.write(session.master, b"echo abc") self.assertEqual(self.query(session)[3], "echo abc") self.action(session, 1 + 5) self.assertEqual(self.snapshot(session), (5, "echo abc")) - os.write(session.master, b"\x1b[23;6~") - self.assertEqual(self.snapshot(session), (0, "echo abc")) + # The chord clears the glass through the line editor: buffer and caret + # hold their place. + os.write(session.master, b"\x1b[20;6~") + self.assertEqual(self.snapshot(session), (5, "echo abc")) + + def test_redraw_install_failure_is_isolated_from_the_editor(self) -> None: + # A PSReadLine that refuses the redraw binding (2.4.5 rejects the + # Function+Description combination outright) must only cost the redraw + # capability: query, completion and pointer init keep working, and no + # redraw advertisement appears. + session = self.start(before=( + "function global:Set-PSReadLineKeyHandler {\n" + " if ($args -contains 'Ctrl+Shift+F9') {\n" + " [Console]::Write(\"$([char]27)]1337;SetUserVar=qa_redraw_refused=eQ==$([char]7)\")\n" + " throw 'fixture: redraw refused'\n" + " }\n" + " & (Get-Command Set-PSReadLineKeyHandler -CommandType Cmdlet) @args\n" + "}\n" + )) + # The fixture must prove the refusal was actually injected before the + # isolation assertions mean anything. + self.assertIn(b"SetUserVar=qa_redraw_refused=eQ==\x07", session.output) + self.assertIn(b"SetUserVar=pebrel_editor_ready=", session.output) + self.assertIn(b"SetUserVar=pebrel_pointer_ready=", session.output) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=", session.output) + os.write(session.master, b"echo probe\x1b[24;6~") + self.assertEqual(self.value(session, "pebrel_editor")[3], "echo probe") + + def test_rebinding_the_redraw_chord_revokes_the_advertisement(self) -> None: + # The advertisement follows the live chord: rebinding it in the same + # session revokes the capability with an empty value on the next + # prompt, and the user's new binding keeps the chord. + session = self.start() + self.assertIn(b"SetUserVar=pebrel_editor_redraw=cHdzaDpmaXh0dXJl\x07", session.output) + os.write( + session.master, + b"Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -Function BeginningOfLine\r", + ) + output = session.wait(b"PS> ") + self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", output) + os.write(session.master, b"(Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F9).Function\r") + output = session.wait(b"PS> ") + self.assertIn(b"BeginningOfLine", output) + self.assertNotIn(b"ClearScreen", output) + + def test_same_name_scriptblock_before_startup_stays_user_owned(self) -> None: + # Function is PSReadLine's display description, not handler identity: + # a scriptblock wearing BriefDescription ClearScreen keeps the chord + # user-owned — the integration may neither overwrite it nor advertise + # the redraw capability. + session = self.start(before=( + "Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -ScriptBlock { " + "[Microsoft.PowerShell.PSConsoleReadLine]::Insert('USER-F9') } -BriefDescription ClearScreen" + )) + self.assertIn(b"SetUserVar=pebrel_editor_ready=", session.output) + self.assertNotIn(b"SetUserVar=pebrel_editor_redraw=", session.output) + os.write(session.master, b"\x1b[20;6~") + session.settle() + # The user's scriptblock still owns the chord and keeps firing. + self.assertEqual(self.snapshot(session)[1], "USER-F9") + + def test_rebinding_to_a_same_name_scriptblock_revokes_the_advertisement(self) -> None: + # Rebinding the chord to a scriptblock described as ClearScreen must + # revoke the capability on the next prompt: the description alone does + # not make it the native handler this session installed. + session = self.start() + self.assertIn(b"SetUserVar=pebrel_editor_redraw=cHdzaDpmaXh0dXJl\x07", session.output) + os.write(session.master, ( + "Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -ScriptBlock { " + "[Microsoft.PowerShell.PSConsoleReadLine]::Insert('USER-F9') } -BriefDescription ClearScreen\r" + ).encode()) + # Keying the raw chord as soon as the prompt shows up lands it inside + # the read's cursor-position handshake and the buffer receives "~;". + # Wait for the next editor read to announce itself, then finish the + # handshake before sending the chord. + session.wait(b"SetUserVar=qa_ready=") + session.settle() + self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", session.output) + os.write(session.master, b"\x1b[20;6~") + session.settle() + self.assertEqual(self.snapshot(session)[1], "USER-F9") def test_production_bootstrap_preserves_native_prompt_and_command_lifecycle(self) -> None: session = self.start(before="function prompt { if ($?) { 'native-ok> ' } else { 'native-failed> ' } }") diff --git a/scripts/tests/test_shell_integration.py b/scripts/tests/test_shell_integration.py index f8cde348f..b8b1044ae 100644 --- a/scripts/tests/test_shell_integration.py +++ b/scripts/tests/test_shell_integration.py @@ -34,6 +34,7 @@ def __init__(self, program: str, home: Path, args: list[str], env: dict[str, str self.master, slave = pty.openpty() self.output = b"" + self.pending = b"" self.process = subprocess.Popen( [program, *args], stdin=slave, stdout=slave, stderr=slave, cwd=home, env={"PATH": os.environ["PATH"], "HOME": str(home), "TERM": "xterm-256color", @@ -45,19 +46,26 @@ def __init__(self, program: str, home: Path, args: list[str], env: dict[str, str os.close(slave) def wait(self, marker: bytes) -> bytes: - collected = b"" + collected = self.pending + self.pending = b"" deadline = time.monotonic() + 8 - while time.monotonic() < deadline: + while marker not in collected and time.monotonic() < deadline: if select.select([self.master], [], [], 0.1)[0]: try: - block = os.read(self.master, 65536) + collected += os.read(self.master, 65536) except OSError: break - collected += block - self.output += block - if marker in collected: - return collected - raise AssertionError(f"shell never emitted {marker!r}: {self.output!r}") + self.output += collected + if marker not in collected: + raise AssertionError(f"shell never emitted {marker!r}: {self.output!r}") + # A PTY read often coalesces this command's sentinel with the precmd + # markers of the *following* prompt. Attribute exactly up to the first + # sentinel to this window and keep the remainder for the next one, so a + # per-window assertion (e.g. "the rebind revoked the advertisement") + # cannot lose its markers to the previous command's read. + index = collected.index(marker) + len(marker) + self.pending = collected[index:] + return collected[:index] def command(self, command: str, marker: bytes) -> bytes: os.write(self.master, command.encode("utf-8") + b"\n")