From 932ce2a903eb6b90bec27f29662fdc457ec9d96c Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 15 Oct 2026 15:56:27 +0800 Subject: [PATCH 01/20] feat(gpui): a bindable clear-screen action for the terminal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The GPUI shell had no clear-screen action at all: the macOS config table's ⌘K ClearHistory default executes only in the legacy shell, so after unbinding the Shell picker row ⌘K stayed inert and no settings row offered clear screen — the known limitation recorded in the 2026-09-21 macOS command-key aliases note. Map config::Action::ClearHistory to a new ClearTerminal workspace action and expose it as a Terminal-group row on the settings keymap page. No default shortcut changes on any platform: ⌘K stays on the Shell picker, and the feature is opt-in through a user keybind= row that applies without restart. After an instant app-side wipe of the viewport and scrollback, the action branches on the pane's foreground state: at a prompt it writes ^L to the pane's PTY so the shell repaints its prompt on the fresh screen; while a command runs it moves the terminal cursor home app-side so sequential output continues from the top; on the alternate screen it does nothing. The row label uses a typed i18n message (zh/en catalogs, English fallback elsewhere). Adds adapter, dispatch-probe and label regressions, and the decision note architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md (recording why pre-existing files need one re-record after upgrading, and why an app-side cursor-home and an unconditional ^L were rejected). --- .../2026-10-14-terminal-clear-action.md | 147 ++++++++++++++++++ nebula_app/i18n/en-US.json | 1 + nebula_app/i18n/zh-CN.json | 1 + nebula_app/src/display/keymap.rs | 28 +++- nebula_app/src/gpui_shell/terminal/view.rs | 28 +++- .../src/gpui_shell/workspace/key_actions.rs | 9 ++ .../gpui_shell/workspace/keyboard_bindings.rs | 14 ++ .../workspace/keyboard_bindings/tests.rs | 100 ++++++++++++ nebula_app/src/gpui_shell/workspace/render.rs | 3 + 9 files changed, 325 insertions(+), 6 deletions(-) create mode 100644 architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md diff --git a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md new file mode 100644 index 000000000..75f70809b --- /dev/null +++ b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md @@ -0,0 +1,147 @@ +# 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. + +## 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 +(`nebula_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` (`nebula_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 + +- `nebula_app/src/main.rs` selects `product_input.rs` for `input` when the legacy + shell is disabled; `input::Processor` / `process_key_bindings` are legacy-only. +- `nebula_app/src/config/bindings/defaults.rs` macOS platform table binds ⌘K twice + (`Esc("\x0c")`, `ClearHistory`); `nebula_terminal/src/term/clear.rs` shows + `ClearMode::Saved` clears only the scrollback while `ClearMode::All` clears the + viewport. +- `nebula_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`, zero-latency + feedback): + - Shell at a prompt (OSC 133 `nebula_prompt_active`): write `\x0c` to that + pane's PTY so the shell moves the cursor home and repaints the prompt on the + fresh screen, keeping its line state in sync. + - Command running: the shell cannot act on `^L` (it would stay queued and + clear the screen a second time when the command exits, wiping the output + produced in between). Instead 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. + - 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 `^L` byte 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). + +## 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. +- 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 + +- On a fresh macOS install the Clear screen row displays `Command+K`, because + `effective_combo` reads the config table and `mods_prefix` renders `super` + natively — while runtime ⌘K actually opens the Shell picker. This is the same + config-table display convention recorded in the 2026-09-21 note ("the keymap + page still shows Ctrl keys for actions whose macOS binding set includes ⌘"), + not a new runtime claim. Capturing any key on the row writes a user row that + wins immediately. +- Resetting the Clear screen row also removes `cmd+k:ReceiveChar` lines + (`reset_action`'s vocabulary includes config-table defaults), which hands ⌘K + back to the Shell picker. Clearing the row writes `keybind=cmd+k:ReceiveChar`, + which shadows the picker's ⌘K — ordinary combo-level shadowing, identical to + every other row. +- 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 `^L` byte reaches whatever shell owns the normal-screen PTY, + exactly as the legacy ⌘K pair behaved. 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 nebula --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 settings-pane suite, the +i18n contract suites, `cargo test -p nebula --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 keymap page renders platform-native or runtime-truth keycaps (removing the +Command+K display quirk), or the product decides clear screen deserves a default +key of its own. diff --git a/nebula_app/i18n/en-US.json b/nebula_app/i18n/en-US.json index 19d7bba1b..37c3ec194 100644 --- a/nebula_app/i18n/en-US.json +++ b/nebula_app/i18n/en-US.json @@ -349,6 +349,7 @@ "edit": "Edit", "rename": "Rename", "rename_tab": "Rename tab", + "clear_screen": "Clear screen", "copy": "Copy", "paste": "Paste", "cut": "Cut", diff --git a/nebula_app/i18n/zh-CN.json b/nebula_app/i18n/zh-CN.json index 368ce78d4..839448b03 100644 --- a/nebula_app/i18n/zh-CN.json +++ b/nebula_app/i18n/zh-CN.json @@ -349,6 +349,7 @@ "edit": "编辑", "rename": "重命名", "rename_tab": "重命名标签页", + "clear_screen": "清屏", "copy": "复制", "paste": "粘贴", "cut": "剪切", diff --git a/nebula_app/src/display/keymap.rs b/nebula_app/src/display/keymap.rs index 02542f040..7ebd34b86 100644 --- a/nebula_app/src/display/keymap.rs +++ b/nebula_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 行仍可覆盖其中的表驱动键)。 @@ -180,10 +183,10 @@ pub(crate) fn action_label( row: &(Action, &'static str, &'static str), language: super::UiLanguage, ) -> &'static str { - if row.0 == Action::RenameTab { - language.text(crate::i18n::Message::CommonRenameTab) - } else { - language.pick(row.1, row.2) + match row.0 { + Action::RenameTab => language.text(crate::i18n::Message::CommonRenameTab), + Action::ClearHistory => language.text(crate::i18n::Message::CommonClearScreen), + _ => language.pick(row.1, row.2), } } @@ -1010,6 +1013,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/nebula_app/src/gpui_shell/terminal/view.rs b/nebula_app/src/gpui_shell/terminal/view.rs index d608cd92b..ddc4b8fa6 100644 --- a/nebula_app/src/gpui_shell/terminal/view.rs +++ b/nebula_app/src/gpui_shell/terminal/view.rs @@ -49,7 +49,7 @@ use nebula_terminal::index::{Column, Line, Point as TermPoint, Side}; use nebula_terminal::render::{CellMetrics, TerminalViewport, ViewportTracker}; use nebula_terminal::selection::{Selection, SelectionType}; use nebula_terminal::term::TermMode; -use nebula_terminal::vte::ansi::CursorStyle; +use nebula_terminal::vte::ansi::{ClearMode, CursorStyle, Handler as _}; use std::sync::Arc; @@ -1067,6 +1067,32 @@ impl TerminalView { true } + /// 清屏(设置页「清屏」动作的落点)。应用侧立刻清掉可见屏与回滚(零 + /// 延迟反馈),随后按前台状态分流: + /// - 提示符状态(shell 在等输入,OSC 133 跟踪):发 ^L 让 shell 光标归 + /// 顶并重绘提示符,行状态与屏幕保持同步; + /// - 命令运行中:shell 读不到 ^L(只会排队到命令结束后再清一次屏,冲 + /// 掉运行期输出),应用侧直接把光标归顶,顺序输出从顶部继续; + /// - 备用屏(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); + self.write_bytes(b"\x0c".to_vec()); + } 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/nebula_app/src/gpui_shell/workspace/key_actions.rs b/nebula_app/src/gpui_shell/workspace/key_actions.rs index 25003931d..c1ad433de 100644 --- a/nebula_app/src/gpui_shell/workspace/key_actions.rs +++ b/nebula_app/src/gpui_shell/workspace/key_actions.rs @@ -123,4 +123,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/nebula_app/src/gpui_shell/workspace/keyboard_bindings.rs b/nebula_app/src/gpui_shell/workspace/keyboard_bindings.rs index 457827d69..966a0c08d 100644 --- a/nebula_app/src/gpui_shell/workspace/keyboard_bindings.rs +++ b/nebula_app/src/gpui_shell/workspace/keyboard_bindings.rs @@ -197,6 +197,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; + impl SelectTab { fn from_config(action: &crate::config::Action) -> Option { use crate::config::Action; @@ -272,6 +279,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)), Action::OpenQuickJump => Some(KeyBinding::new(&combo, OpenQuickJump, scope)), // macOS 的退出键走与托盘退出同一条路径:先落盘会话与草稿,再停 PTY。 diff --git a/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs b/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs index 1a68f476c..0c84d9fcf 100644 --- a/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs +++ b/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs @@ -108,6 +108,57 @@ 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(), + ]; + let mut statics = default_workspace_bindings(); + if cfg!(target_os = "macos") { + // 对照组:macOS 的 ⌘K 静态默认键(Shell 选择器)必须存在, + // 否则「用户清屏压过默认键」的断言空跑。 + statics.push(custom_workspace_binding("cmd+k", &Action::ToggleShellPicker).unwrap()); + } + 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 在所有平台都是它的 + // 工作区默认键,用户给 ⌘K 绑清屏不改变这一点。 + let (bindings, pending) = + keymap.bindings_for_input(&[Keystroke::parse("ctrl-k").unwrap()], &contexts); + assert!(!pending); + assert!( + bindings[0].action().as_any().is::(), + "清屏绑定不得挤占 Shell 选择器的默认键" + ); +} + #[test] fn cleared_shortcut_reaches_terminal_and_can_be_restored_without_restart() { use crate::config::Action; @@ -936,6 +987,7 @@ mod dispatch { focus: FocusHandle, selected: Option, renamed: usize, + cleared: usize, mode: TermMode, input: Vec, encoded: Vec, @@ -949,6 +1001,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() @@ -982,6 +1035,7 @@ mod dispatch { focus: cx.focus_handle(), selected: None, renamed: 0, + cleared: 0, mode: TermMode::empty(), input: Vec::new(), encoded: Vec::new(), @@ -1071,6 +1125,7 @@ mod dispatch { focus: cx.focus_handle(), selected: None, renamed: 0, + cleared: 0, mode: TermMode::empty(), input: Vec::new(), encoded: Vec::new(), @@ -1109,4 +1164,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/nebula_app/src/gpui_shell/workspace/render.rs b/nebula_app/src/gpui_shell/workspace/render.rs index a5cf76c79..3d61cd6ca 100644 --- a/nebula_app/src/gpui_shell/workspace/render.rs +++ b/nebula_app/src/gpui_shell/workspace/render.rs @@ -244,6 +244,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(); })) From 6d10f8c8573ca494c925bab9a9330b2f35c1b6d9 Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 15 Oct 2026 16:04:58 +0800 Subject: [PATCH 02/20] test(keymap): drop the platform conditional from the clear-screen control group The platform-cfg ratchet counts cfg! macros outside platform/ and the clear-screen adapter regression added one. Build the static default keymap identically on every platform instead: the precedence being tested is source-tier, not platform-specific, and the macOS-only registration behavior stays guarded by its own runtime-platform test. --- .../gpui_shell/workspace/keyboard_bindings/tests.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs b/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs index 0c84d9fcf..458855108 100644 --- a/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs +++ b/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs @@ -129,12 +129,12 @@ fn clear_history_maps_to_the_clear_terminal_action() { ) .unwrap(), ]; + // 对照组:⌘K 的静态默认键(Shell 选择器)必须存在,否则「用户绑定的 + // 清屏压过静态默认键」的断言空跑。键表级构造三平台同形;macOS 上 + // ⌘ 别名只在运行时注册的平台差异由 + // `command_shortcut_registration_follows_runtime_platform` 单独守住。 let mut statics = default_workspace_bindings(); - if cfg!(target_os = "macos") { - // 对照组:macOS 的 ⌘K 静态默认键(Shell 选择器)必须存在, - // 否则「用户清屏压过默认键」的断言空跑。 - statics.push(custom_workspace_binding("cmd+k", &Action::ToggleShellPicker).unwrap()); - } + statics.push(custom_workspace_binding("cmd+k", &Action::ToggleShellPicker).unwrap()); let keymap = Keymap::new(with_user_keybindings(&Keymap::new(statics), user)); let contexts = [ From 94cdb39edd43528970b9bff3d0b11e4aa03ab5ba Mon Sep 17 00:00:00 2001 From: zher52 Date: Mon, 19 Oct 2026 10:35:12 +0800 Subject: [PATCH 03/20] test(keymap): expect the released Ctrl+K default after the #656 policy Upstream cf77ccd4 releases plain Control-character workspace defaults on macOS, so the Shell picker's Ctrl+K default may legitimately be absent. Derive the Ctrl+K expectation from the control group's own shape instead of asserting it unconditionally; the user clear binding must neither steal a present default nor resurrect a released key. --- .../workspace/keyboard_bindings/tests.rs | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs b/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs index 458855108..e569ace68 100644 --- a/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs +++ b/nebula_app/src/gpui_shell/workspace/keyboard_bindings/tests.rs @@ -135,6 +135,15 @@ fn clear_history_maps_to_the_clear_terminal_action() { // `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 = [ @@ -148,15 +157,19 @@ fn clear_history_maps_to_the_clear_terminal_action() { bindings[0].action().as_any().is::(), "用户绑定的清屏必须压过静态默认键" ); - // Shell 选择器自身的默认键不受影响:Ctrl+K 在所有平台都是它的 - // 工作区默认键,用户给 ⌘K 绑清屏不改变这一点。 + // Shell 选择器的 Ctrl+K 默认键不受用户清屏绑定影响(期望形状已在 + // 构造 keymap 前从对照组读取)。 let (bindings, pending) = keymap.bindings_for_input(&[Keystroke::parse("ctrl-k").unwrap()], &contexts); - assert!(!pending); - assert!( - bindings[0].action().as_any().is::(), - "清屏绑定不得挤占 Shell 选择器的默认键" - ); + 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] From 92516fe2b5265d0b7547b234f42d2a62f251b7a7 Mon Sep 17 00:00:00 2001 From: kuddev Date: Mon, 19 Oct 2026 18:52:00 +0800 Subject: [PATCH 04/20] Verify clear-screen state transitions and preserve macOS shortcut ownership --- .../2026-10-14-terminal-clear-action.md | 25 ++---- nebula_app/src/display/keymap.rs | 19 +++++ .../gpui_shell/terminal/view/startup_tests.rs | 80 +++++++++++++++++++ 3 files changed, 107 insertions(+), 17 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md index 75f70809b..1e765ef33 100644 --- a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md +++ b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md @@ -46,8 +46,7 @@ established macOS ⌘K clear convention had no path to that behavior. 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`, zero-latency - feedback): + of the viewport and scrollback (`ClearMode::All` + `Saved`): - Shell at a prompt (OSC 133 `nebula_prompt_active`): write `\x0c` to that pane's PTY so the shell moves the cursor home and repaints the prompt on the fresh screen, keeping its line state in sync. @@ -96,18 +95,11 @@ established macOS ⌘K clear convention had no path to that behavior. ## Consequences -- On a fresh macOS install the Clear screen row displays `Command+K`, because - `effective_combo` reads the config table and `mods_prefix` renders `super` - natively — while runtime ⌘K actually opens the Shell picker. This is the same - config-table display convention recorded in the 2026-09-21 note ("the keymap - page still shows Ctrl keys for actions whose macOS binding set includes ⌘"), - not a new runtime claim. Capturing any key on the row writes a user row that - wins immediately. -- Resetting the Clear screen row also removes `cmd+k:ReceiveChar` lines - (`reset_action`'s vocabulary includes config-table defaults), which hands ⌘K - back to the Shell picker. Clearing the row writes `keybind=cmd+k:ReceiveChar`, - which shadows the picker's ⌘K — ordinary combo-level shadowing, identical to - every other row. +- 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 @@ -142,6 +134,5 @@ its alias-table authority and unbind vocabulary are reused unchanged. ## Revisit when -The keymap page renders platform-native or runtime-truth keycaps (removing the -Command+K display quirk), or the product decides clear screen deserves a default -key of its own. +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/nebula_app/src/display/keymap.rs b/nebula_app/src/display/keymap.rs index 7ebd34b86..a6867e757 100644 --- a/nebula_app/src/display/keymap.rs +++ b/nebula_app/src/display/keymap.rs @@ -922,6 +922,25 @@ 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)) + ); + assert!(LEGACY.effective_combo(&Action::ClearHistory, &[]).is_some()); + 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::*; diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index 49b05eede..6592891e6 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -109,6 +109,86 @@ pub(super) fn feed(view: &mut TerminalView, bytes: &[u8]) { parser.advance(&mut *term, bytes); } +#[gpui::test] +fn clear_screen_clears_history_and_writes_redraw_only_at_prompt(cx: &mut TestAppContext) { + let (view, cx, receiver) = open(cx); + for prompt in [false, true] { + view.update(cx, |view, 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 { + 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, if prompt { vec![b"\x0c".to_vec()] } else { vec![] }); + } +} + +#[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(); From db35ebd56491c462f112ed24f05cdf7c0f215f63 Mon Sep 17 00:00:00 2001 From: kuddev Date: Mon, 19 Oct 2026 19:24:39 +0800 Subject: [PATCH 05/20] Keep clear-screen policy test independent of legacy defaults --- nebula_app/src/display/keymap.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/nebula_app/src/display/keymap.rs b/nebula_app/src/display/keymap.rs index a6867e757..6fdb1828a 100644 --- a/nebula_app/src/display/keymap.rs +++ b/nebula_app/src/display/keymap.rs @@ -930,7 +930,6 @@ mod tests { GPUI.effective_combo(&Action::ToggleShellPicker, &[]), Some(("Command+K".into(), false)) ); - assert!(LEGACY.effective_combo(&Action::ClearHistory, &[]).is_some()); let mut raw = Vec::new(); GPUI.clear_action(&mut raw, &Action::ClearHistory); GPUI.reset_action(&mut raw, &Action::ClearHistory); From 06fbd22ca8b1bc4af3451bf2118e7db4449e73cd Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 22 Oct 2026 09:03:59 +0800 Subject: [PATCH 06/20] ci: retrigger the flaky Windows bash-input native test From ca073eedccd583c5a6580f3399355a26f495a9c0 Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 12 Nov 2026 13:25:58 +0800 Subject: [PATCH 07/20] fix(gpui): redraw the prompt through an owned shell integration key Review rejected writing ^L at the prompt: the byte is keyboard input to whatever owns the tty, so it invoked the user's remapped Ctrl+L binding instead of clear screen. The prompt branch now sends an integration-owned key installed next to the native editor query - \e[46~ bound to the readline/zle clear-screen function for bash/zsh, Ctrl+Shift+F11 bound to the PSReadLine ClearScreen function for pwsh - and participates in the same pebrel_editor_ready advertisement: a user-owned key withdraws the whole channel, and the action degrades to the app-side cursor home instead of ever writing a keyboard byte. The view matrix covers the remapped-key, running-command and alternate-screen cases; real-PTY script tests cover the installed key and the user-owned withdrawal. --- .../2026-10-14-terminal-clear-action.md | 57 ++++++++++------ nebula_app/src/gpui_shell/terminal/view.rs | 18 +++-- .../src/gpui_shell/terminal/view/editor.rs | 20 ++++++ .../gpui_shell/terminal/view/startup_tests.rs | 67 +++++++++++++++++-- nebula_terminal/src/tty/completion.ps1 | 16 +++++ nebula_terminal/src/tty/completion.sh | 19 ++++-- scripts/tests/test_completion_editor.py | 64 ++++++++++++++++-- 7 files changed, 225 insertions(+), 36 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md index 1e765ef33..2087ece14 100644 --- a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md +++ b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md @@ -47,22 +47,25 @@ established macOS ⌘K clear convention had no path to that behavior. 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`): write `\x0c` to that - pane's PTY so the shell moves the cursor home and repaints the prompt on the - fresh screen, keeping its line state in sync. - - Command running: the shell cannot act on `^L` (it would stay queued and - clear the screen a second time when the command exits, wiping the output - produced in between). Instead 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. + - Shell at a prompt (OSC 133 `nebula_prompt_active`) with the native editor + channel advertised (`pebrel_editor_ready`): write the integration-owned + clear key — `\e[46~` bound to the readline/zle `clear-screen` function, or + the PSReadLine `Ctrl+Shift+F11` → `ClearScreen` chord — 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 channel, or command running: 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 `^L` byte 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. + 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). @@ -84,6 +87,14 @@ established macOS ⌘K clear convention had no path to that behavior. - 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 @@ -111,9 +122,12 @@ established macOS ⌘K clear convention had no path to that behavior. `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 `^L` byte reaches whatever shell owns the normal-screen PTY, - exactly as the legacy ⌘K pair behaved. In the running-command branch no PTY - write happens; alternate-screen sessions are left untouched entirely. +- At the prompt the redraw key reaches the advertised shell's line editor as an + owned binding installed next to the native editor query; a user-owned `\e[46~` + (or PSReadLine `Ctrl+Shift+F11`) withdraws the whole native editor channel, + and the action then degrades to the app-side cursor home. 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 @@ -121,9 +135,14 @@ established macOS ⌘K clear convention had no path to that behavior. `cargo fmt --all -- --check`, `cargo check -p nebula --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 settings-pane suite, the -i18n contract suites, `cargo test -p nebula --test file_line_budget` and -`python3 scripts/check_architecture.py --base ` pass. The dispatch +adapter, dispatch-probe and label regressions), the clear-screen view matrix +(prompt with and without the advertised channel, running command, 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 key +withdraws the advertisement), `cargo test -p nebula --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. diff --git a/nebula_app/src/gpui_shell/terminal/view.rs b/nebula_app/src/gpui_shell/terminal/view.rs index b9c09f384..607d36644 100644 --- a/nebula_app/src/gpui_shell/terminal/view.rs +++ b/nebula_app/src/gpui_shell/terminal/view.rs @@ -1293,10 +1293,11 @@ impl TerminalView { /// 清屏(设置页「清屏」动作的落点)。应用侧立刻清掉可见屏与回滚(零 /// 延迟反馈),随后按前台状态分流: - /// - 提示符状态(shell 在等输入,OSC 133 跟踪):发 ^L 让 shell 光标归 - /// 顶并重绘提示符,行状态与屏幕保持同步; - /// - 命令运行中:shell 读不到 ^L(只会排队到命令结束后再清一次屏,冲 - /// 掉运行期输出),应用侧直接把光标归顶,顺序输出从顶部继续; + /// - 提示符状态(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 }; @@ -1309,7 +1310,14 @@ impl TerminalView { term.clear_screen(ClearMode::Saved); if term.nebula_prompt_active() { drop(term); - self.write_bytes(b"\x0c".to_vec()); + // 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); } diff --git a/nebula_app/src/gpui_shell/terminal/view/editor.rs b/nebula_app/src/gpui_shell/terminal/view/editor.rs index 5f9f54596..b3bc00931 100644 --- a/nebula_app/src/gpui_shell/terminal/view/editor.rs +++ b/nebula_app/src/gpui_shell/terminal/view/editor.rs @@ -232,6 +232,26 @@ impl TerminalView { .unwrap_or_else(|| b"\x1b[24;6~".to_vec()) } + /// 提示符重绘字节:`pebrel_editor_ready` 声明的 shell 集成自有键 + /// (completion.sh 的 `\e[46~` → readline/zle 原生 clear-screen, + /// completion.ps1 的 Ctrl+Shift+F11 → PSReadLine ClearScreen)。与查询 + /// 键同批安装、同批声明,用户占用任何一个都使通道整体退出。未就绪 + /// 返回 None,调用方退回应用侧光标归顶——绝不退回键盘字节(^L 会 + /// 执行 shell 里用户对 Ctrl+L 的任意重绑定)。 + pub(super) fn editor_clear_bytes(&self) -> Option> { + let owner = self.completion_editor.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-f11").unwrap(); + super::super::keymap::encode(&key, &self.term_mode()) + .or_else(|| Some(b"\x1b[23;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/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index c350c99ea..f90e39314 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -111,10 +111,32 @@ pub(super) fn feed(view: &mut TerminalView, bytes: &[u8]) { } #[gpui::test] -fn clear_screen_clears_history_and_writes_redraw_only_at_prompt(cx: &mut TestAppContext) { +fn clear_screen_clears_history_and_redraws_only_through_the_integration_key( + cx: &mut TestAppContext, +) { let (view, cx, receiver) = open(cx); - for prompt in [false, true] { + // (prompt, ready):命令运行中和未声明集成自有键的提示符都不发任何字 + // 节(应用侧光标归顶);只有 `pebrel_editor_ready` 声明的提示符才发 + // `\e[46~`。任何状态都绝不发 ^L——无论清屏快捷键绑定在哪个键上,^L + // 都会执行 shell 里用户对 Ctrl+L 的任意重绑定(审查裁定 2026-11-12)。 + for (prompt, ready) in [(false, false), (true, false), (true, true)] { view.update(cx, |view, cx| { + if ready { + view.process_event( + TermEvent::UserVar { + name: "pebrel_shell".into(), + value: "bash:clear-fixture".into(), + }, + cx, + ); + view.process_event( + TermEvent::UserVar { + name: "pebrel_editor_ready".into(), + value: "bash:clear-fixture".into(), + }, + cx, + ); + } for _ in 0..40 { feed(view, b"previous output\r\n"); } @@ -139,7 +161,7 @@ fn clear_screen_clears_history_and_writes_redraw_only_at_prompt(cx: &mut TestApp assert_eq!(term.grid().display_offset(), 0); assert!(term.selection.is_none()); assert!(term.grid().display_iter().all(|cell| cell.c == ' ')); - if !prompt { + if !prompt || !ready { assert_eq!(term.grid().cursor.point, TermPoint::new(Line(0), Column(0))); } }); @@ -150,10 +172,47 @@ fn clear_screen_clears_history_and_writes_redraw_only_at_prompt(cx: &mut TestApp _ => None, }) .collect(); - assert_eq!(writes, if prompt { vec![b"\x0c".to_vec()] } else { vec![] }); + let expected = if prompt && ready { vec![b"\x1b[46~".to_vec()] } else { vec![] }; + assert_eq!(writes, expected, "prompt={prompt} ready={ready}"); + 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, + ); + 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-f11").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_keeps_alternate_screen_and_primary_history(cx: &mut TestAppContext) { let (view, cx, receiver) = open(cx); diff --git a/nebula_terminal/src/tty/completion.ps1 b/nebula_terminal/src/tty/completion.ps1 index a6d3e5606..d85514d57 100644 --- a/nebula_terminal/src/tty/completion.ps1 +++ b/nebula_terminal/src/tty/completion.ps1 @@ -28,6 +28,22 @@ 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 bound to the native + # ClearScreen, so the terminal never sends ^L at the prompt. + $clearExisting = if ($query.Parameters.ContainsKey('Chord')) { + Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue + } else { + @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F11','Shift+Ctrl+F11' }) + } + if (-not $clearExisting -or $clearExisting.Function -eq 'Unbound' -or + $clearExisting.Function -eq 'ClearScreen') { + Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function ClearScreen + } else { + # A user-held F11 leaves the whole native editor unadvertised, + # matching the F12 ownership rule: the redraw pairing must not + # fall back to a keyboard byte that invokes user rebinding. + throw 'Ctrl+Shift+F11 is user-owned' + } # 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)) diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index 87e1e69db..97c69cc17 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -1,4 +1,5 @@ -# Private editor query; existing user bindings retain ownership of F24. +# Private editor query and prompt redraw; existing user bindings retain +# ownership of F24 and the clear-screen redraw key. __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" @@ -32,17 +33,27 @@ __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 while IFS= read -r __pebrel_binding; do [[ $__pebrel_binding == '"\e[45~":'* ]] && __pebrel_editor_bound=1 + [[ $__pebrel_binding == '"\e[46~":'* ]] && __pebrel_clear_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 + # The redraw key is a readline function binding, not a shell command: the + # editor clears the screen and repaints prompt, buffer and caret itself. + if [[ $__pebrel_editor_bound == 0 ]] && bind -x '"\e[45~":__pebrel_editor_report' 2>/dev/null && + [[ $__pebrel_clear_bound == 0 ]] && bind '"\e[46~": clear-screen' 2>/dev/null; then __pebrel_editor_ready=1 + else + # The channel is advertised as one unit; an unusable redraw key also + # withdraws the query binding instead of half-installing. + bind -r '"\e[45~"' 2>/dev/null fi - unset __pebrel_editor_bound __pebrel_binding + unset __pebrel_editor_bound __pebrel_clear_bound __pebrel_binding elif [ -n "${ZSH_VERSION-}" ]; then - if [[ $(bindkey '\e[45~') == *undefined-key ]]; then + if [[ $(bindkey '\e[45~') == *undefined-key ]] && [[ $(bindkey '\e[46~') == *undefined-key ]]; then zle -N __pebrel_editor_report bindkey '\e[45~' __pebrel_editor_report + bindkey '\e[46~' clear-screen __pebrel_editor_ready=1 fi fi diff --git a/scripts/tests/test_completion_editor.py b/scripts/tests/test_completion_editor.py index e5a3a4704..167e445bf 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -39,7 +39,8 @@ 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) -> shell_integration.ShellSession: root = Path(__file__).resolve().parents[2] program = shutil.which(shell) if not program: @@ -64,13 +65,23 @@ 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: 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' + 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" + (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 +145,51 @@ 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) + + 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_owned_redraw_binding(self, shell: str, route: str) -> None: + session = self.start_bootstrap(shell, route, owned_redraw=True) + # A user-owned redraw key withdraws the whole native editor channel. + self.assertNotIn(b"SetUserVar=pebrel_editor_ready=", 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) + + 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_middle_edit(self, shell: str) -> None: session = self.start(shell) line = 'echo "中-old" tail' From b6604cc26d6927ccd27c6779d1c8c34fa98c15c6 Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 12 Nov 2026 14:09:06 +0800 Subject: [PATCH 08/20] test(pwsh): keep the redraw chord ownership test off the sample user key The clipboard-preservation test injected a user binding on Ctrl+Shift+F11, which the redraw pairing now owns: the withdrawal correctly turned off editor readiness and the F12 query never answered. Move the unrelated sample chord to Ctrl+Shift+F2, assert the owned redraw chord clears the glass while the buffer and caret hold their place, and cover the user-owned F11 withdrawal as its own negative case (the pointer channels gate on completion readiness, so they exit together). --- scripts/tests/test_powershell_pointer.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index 20f68e009..e393e7a5b 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -215,13 +215,25 @@ 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[23;6~") - self.assertEqual(self.snapshot(session), (0, "echo abc")) + self.assertEqual(self.snapshot(session), (5, "echo abc")) + + def test_user_owned_redraw_chord_withdraws_the_editor_channel(self) -> None: + # Ctrl+Shift+F11 is the owned prompt-redraw chord: a user binding on it + # withdraws the whole native editor stack — the pointer channels gate + # on the completion readiness that the withdrawn chord turns off. + session = self.start(before="Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function BeginningOfLine") + self.assertNotIn(b"SetUserVar=pebrel_editor_ready=", session.output) + self.assertNotIn(b"SetUserVar=pebrel_pointer_ready=", session.output) def test_production_bootstrap_preserves_native_prompt_and_command_lifecycle(self) -> None: session = self.start(before="function prompt { if ($?) { 'native-ok> ' } else { 'native-failed> ' } }") From 48b0f2a84a2cf46efe30aa3df755d4d118550f35 Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 12 Nov 2026 14:33:03 +0800 Subject: [PATCH 09/20] fix(tty): probe both private keys before installing either binding Review found the redraw collision leaving half of the private channel installed: the rollback passed the surrounding quotes as part of the key to bind -r, so the query binding survived, and the PowerShell branch installed the query before even probing the redraw chord. Both branches now probe query and redraw ownership up front and install only when both are free; the bash rollback withdraws just the binding this invocation installed, with bind -r taking the bare key sequence. The collision tests now assert the query binding is really gone: bind -p/-X list no \e[45~ after a redraw collision, and the withdrawn F12 chord answers nothing in pwsh. --- nebula_terminal/src/tty/completion.ps1 | 32 +++++++++++------------- nebula_terminal/src/tty/completion.sh | 19 ++++++++------ scripts/tests/test_completion_editor.py | 7 ++++++ scripts/tests/test_powershell_pointer.py | 7 ++++-- 4 files changed, 38 insertions(+), 27 deletions(-) diff --git a/nebula_terminal/src/tty/completion.ps1 b/nebula_terminal/src/tty/completion.ps1 index d85514d57..db5f132ad 100644 --- a/nebula_terminal/src/tty/completion.ps1 +++ b/nebula_terminal/src/tty/completion.ps1 @@ -10,8 +10,19 @@ if (Get-Command Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) { # Windows PowerShell's bundled PSReadLine lacks -Chord. Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F12','Shift+Ctrl+F12' } } - if (-not $existing -or $existing.Function -eq 'Unbound' -or - ($global:PebrelEditorHandlerName -and $existing.Function -eq $global:PebrelEditorHandlerName)) { + # The prompt-redraw chord joins the same ownership boundary as the + # query: both are probed before either is installed, so a user-held + # F11 never leaves a half-installed channel behind, and the pairing + # never falls back to a keyboard byte that invokes user rebinding. + $clearExisting = if ($query.Parameters.ContainsKey('Chord')) { + Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue + } else { + @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F11','Shift+Ctrl+F11' }) + } + if ((-not $existing -or $existing.Function -eq 'Unbound' -or + ($global:PebrelEditorHandlerName -and $existing.Function -eq $global:PebrelEditorHandlerName)) -and + (-not $clearExisting -or $clearExisting.Function -eq 'Unbound' -or + $clearExisting.Function -eq 'ClearScreen')) { $global:PebrelEditorHandlerName = 'PebrelNativeEditor:' + $global:PebrelShellToken Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F12 -ScriptBlock { param($key, $arg) @@ -28,22 +39,7 @@ 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 bound to the native - # ClearScreen, so the terminal never sends ^L at the prompt. - $clearExisting = if ($query.Parameters.ContainsKey('Chord')) { - Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue - } else { - @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F11','Shift+Ctrl+F11' }) - } - if (-not $clearExisting -or $clearExisting.Function -eq 'Unbound' -or - $clearExisting.Function -eq 'ClearScreen') { - Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function ClearScreen - } else { - # A user-held F11 leaves the whole native editor unadvertised, - # matching the F12 ownership rule: the redraw pairing must not - # fall back to a keyboard byte that invokes user rebinding. - throw 'Ctrl+Shift+F11 is user-owned' - } + Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function ClearScreen # 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)) diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index 97c69cc17..63864824d 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -40,13 +40,18 @@ if [ -n "${BASH_VERSION-}" ] && (( BASH_VERSINFO[0] >= 4 )) && [[ $- == *i* ]]; done < <(bind -p 2>/dev/null; bind -X 2>/dev/null) # The redraw key is a readline function binding, not a shell command: the # editor clears the screen and repaints prompt, buffer and caret itself. - if [[ $__pebrel_editor_bound == 0 ]] && bind -x '"\e[45~":__pebrel_editor_report' 2>/dev/null && - [[ $__pebrel_clear_bound == 0 ]] && bind '"\e[46~": clear-screen' 2>/dev/null; then - __pebrel_editor_ready=1 - else - # The channel is advertised as one unit; an unusable redraw key also - # withdraws the query binding instead of half-installing. - bind -r '"\e[45~"' 2>/dev/null + # Both keys are probed before either binding is installed, so an occupied + # redraw key never leaves half of the private channel behind. The rollback + # runs only for the query binding this invocation just installed, and + # bind -r takes the bare key sequence. + if [[ $__pebrel_editor_bound == 0 && $__pebrel_clear_bound == 0 ]]; then + if bind -x '"\e[45~":__pebrel_editor_report' 2>/dev/null; then + if bind '"\e[46~": clear-screen' 2>/dev/null; then + __pebrel_editor_ready=1 + else + bind -r '\e[45~' 2>/dev/null + fi + fi fi unset __pebrel_editor_bound __pebrel_clear_bound __pebrel_binding elif [ -n "${ZSH_VERSION-}" ]; then diff --git a/scripts/tests/test_completion_editor.py b/scripts/tests/test_completion_editor.py index 167e445bf..57618e085 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -183,6 +183,13 @@ def check_owned_redraw_binding(self, shell: str, route: str) -> None: output = session.wait(b"OWNED-REDRAW\r\n") self.assertIn(b"OWNED-REDRAW\r\n", output) self.assertNotIn(b"SetUserVar=pebrel_editor=", output) + # The withdrawal must also remove the query binding this invocation + # installed: no half of the private channel may survive the collision. + bindings = session.command( + "bind -p 2>/dev/null; bind -X 2>/dev/null; printf 'BINDINGS-END\\n'", + b"BINDINGS-END\r\n", + ) + self.assertNotIn(b'"\\e[45~"', bindings) def test_ssh_bash_bootstrap_retains_user_owned_redraw_binding(self) -> None: self.check_owned_redraw_binding("bash", "ssh") diff --git a/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index e393e7a5b..41fcdabaa 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -229,11 +229,14 @@ def test_pointer_chords_preserve_the_clipboard_key(self) -> None: def test_user_owned_redraw_chord_withdraws_the_editor_channel(self) -> None: # Ctrl+Shift+F11 is the owned prompt-redraw chord: a user binding on it - # withdraws the whole native editor stack — the pointer channels gate - # on the completion readiness that the withdrawn chord turns off. + # withdraws the whole native editor stack, and nothing is half-installed + # — the query chord answers nothing either. session = self.start(before="Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function BeginningOfLine") self.assertNotIn(b"SetUserVar=pebrel_editor_ready=", session.output) self.assertNotIn(b"SetUserVar=pebrel_pointer_ready=", session.output) + os.write(session.master, b"echo probe\x1b[24;6~") + session.settle() + self.assertNotIn(b"SetUserVar=pebrel_editor=", session.output) def test_production_bootstrap_preserves_native_prompt_and_command_lifecycle(self) -> None: session = self.start(before="function prompt { if ($?) { 'native-ok> ' } else { 'native-failed> ' } }") From 8bc09aa60d1762a5c993a5c01728477f602b6a27 Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 12 Nov 2026 16:37:24 +0800 Subject: [PATCH 10/20] fix(tty): advertise prompt redraw as its own capability Query readiness says nothing about the redraw key: a live shell from a pre-redraw integration reports pebrel_editor_ready while \e[46~ is simply unbound, so an upgraded client that treated that event as redraw proof sent the key into the old shell. The integration now reports pebrel_editor_redraw only when it actually owns the key, and editor_clear_bytes requires that explicit capability. A user-owned redraw key again withdraws only redraw: query, completion and pointer support keep working as in 2.5.3. The Bash probe also reads bind -s, because bind -p and bind -X do not list string macros and a macro on the key must keep firing instead of being replaced by clear-screen; the zsh probe already saw bindkey -s bodies as user-owned and now keeps its own independent check. The pwsh chord pairs the same way in both bootstraps. Tests cover the macro and function-binding collisions through real PTYs, a query-only session that leaves the key unbound, and the view matrix regression asserting clear sends no redraw key when only query readiness is advertised. --- .../2026-10-14-terminal-clear-action.md | 48 +++++---- nebula_app/res/shell/powershell.ps1 | 3 + nebula_app/src/gpui_shell/terminal/view.rs | 4 + .../src/gpui_shell/terminal/view/editor.rs | 22 ++-- .../src/gpui_shell/terminal/view/startup.rs | 1 + .../gpui_shell/terminal/view/startup_tests.rs | 40 +++++-- nebula_terminal/src/tty/completion.ps1 | 31 +++--- nebula_terminal/src/tty/completion.sh | 46 +++++--- nebula_terminal/src/tty/windows/mod.rs | 1 + scripts/tests/test_completion_editor.py | 101 ++++++++++++++++-- scripts/tests/test_powershell_pointer.py | 14 ++- 11 files changed, 230 insertions(+), 81 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md index 2087ece14..f1f60219e 100644 --- a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md +++ b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md @@ -47,17 +47,20 @@ established macOS ⌘K clear convention had no path to that behavior. 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 native editor - channel advertised (`pebrel_editor_ready`): write the integration-owned - clear key — `\e[46~` bound to the readline/zle `clear-screen` function, or - the PSReadLine `Ctrl+Shift+F11` → `ClearScreen` chord — 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 channel, or command running: 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). + - 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+F11` → `ClearScreen` chord — 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, or a user-owned redraw key — 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 @@ -122,10 +125,14 @@ established macOS ⌘K clear convention had no path to that behavior. `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 advertised shell's line editor as an - owned binding installed next to the native editor query; a user-owned `\e[46~` - (or PSReadLine `Ctrl+Shift+F11`) withdraws the whole native editor channel, - and the action then degrades to the app-side cursor home. In the +- 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. 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. @@ -136,12 +143,15 @@ established macOS ⌘K clear convention had no path to that behavior. 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 and without the advertised channel, running command, alternate -screen; the remapped-key case asserts no `^L` byte ever leaves the app), the +(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 key -withdraws the advertisement), `cargo test -p nebula --test file_line_budget` +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), `cargo test -p nebula --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. diff --git a/nebula_app/res/shell/powershell.ps1 b/nebula_app/res/shell/powershell.ps1 index c185120b4..7ac760dac 100644 --- a/nebula_app/res/shell/powershell.ps1 +++ b/nebula_app/res/shell/powershell.ps1 @@ -19,6 +19,9 @@ if (-not $global:PebrelUnixReadLineInstalled) { if ($global:PebrelCompletionInputReady) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_ready=$global:PebrelEditorReady$([char]7)") } + if ($global:PebrelRedrawReady) { + [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_redraw=$global:PebrelShellToken$([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/nebula_app/src/gpui_shell/terminal/view.rs b/nebula_app/src/gpui_shell/terminal/view.rs index 607d36644..27f7e177c 100644 --- a/nebula_app/src/gpui_shell/terminal/view.rs +++ b/nebula_app/src/gpui_shell/terminal/view.rs @@ -530,6 +530,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, diff --git a/nebula_app/src/gpui_shell/terminal/view/editor.rs b/nebula_app/src/gpui_shell/terminal/view/editor.rs index b3bc00931..1ab0153c2 100644 --- a/nebula_app/src/gpui_shell/terminal/view/editor.rs +++ b/nebula_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,14 +240,16 @@ impl TerminalView { .unwrap_or_else(|| b"\x1b[24;6~".to_vec()) } - /// 提示符重绘字节:`pebrel_editor_ready` 声明的 shell 集成自有键 + /// 提示符重绘字节:`pebrel_editor_redraw` 声明的 shell 集成自有键 /// (completion.sh 的 `\e[46~` → readline/zle 原生 clear-screen, - /// completion.ps1 的 Ctrl+Shift+F11 → PSReadLine ClearScreen)。与查询 - /// 键同批安装、同批声明,用户占用任何一个都使通道整体退出。未就绪 - /// 返回 None,调用方退回应用侧光标归顶——绝不退回键盘字节(^L 会 - /// 执行 shell 里用户对 Ctrl+L 的任意重绑定)。 + /// completion.ps1 的 Ctrl+Shift+F11 → 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.completion_editor.owner.as_deref()?; + let owner = self.editor_redraw_owner.as_deref()?; if !self.suggest.completion_context.owns_current(owner) { return None; } diff --git a/nebula_app/src/gpui_shell/terminal/view/startup.rs b/nebula_app/src/gpui_shell/terminal/view/startup.rs index f979505ee..625b2d76f 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup.rs @@ -430,6 +430,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/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index f90e39314..00d362256 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -115,13 +115,17 @@ fn clear_screen_clears_history_and_redraws_only_through_the_integration_key( cx: &mut TestAppContext, ) { let (view, cx, receiver) = open(cx); - // (prompt, ready):命令运行中和未声明集成自有键的提示符都不发任何字 - // 节(应用侧光标归顶);只有 `pebrel_editor_ready` 声明的提示符才发 - // `\e[46~`。任何状态都绝不发 ^L——无论清屏快捷键绑定在哪个键上,^L - // 都会执行 shell 里用户对 Ctrl+L 的任意重绑定(审查裁定 2026-11-12)。 - for (prompt, ready) in [(false, false), (true, false), (true, true)] { + // (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 { + if ready || redraw { view.process_event( TermEvent::UserVar { name: "pebrel_shell".into(), @@ -129,6 +133,8 @@ fn clear_screen_clears_history_and_redraws_only_through_the_integration_key( }, cx, ); + } + if ready { view.process_event( TermEvent::UserVar { name: "pebrel_editor_ready".into(), @@ -137,6 +143,15 @@ fn clear_screen_clears_history_and_redraws_only_through_the_integration_key( 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"); } @@ -161,7 +176,7 @@ fn clear_screen_clears_history_and_redraws_only_through_the_integration_key( assert_eq!(term.grid().display_offset(), 0); assert!(term.selection.is_none()); assert!(term.grid().display_iter().all(|cell| cell.c == ' ')); - if !prompt || !ready { + if !prompt || !redraw { assert_eq!(term.grid().cursor.point, TermPoint::new(Line(0), Column(0))); } }); @@ -172,8 +187,8 @@ fn clear_screen_clears_history_and_redraws_only_through_the_integration_key( _ => None, }) .collect(); - let expected = if prompt && ready { vec![b"\x1b[46~".to_vec()] } else { vec![] }; - assert_eq!(writes, expected, "prompt={prompt} ready={ready}"); + 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:?}"); } } @@ -193,6 +208,13 @@ fn clear_screen_sends_the_owned_powershell_chord_for_pwsh(cx: &mut TestAppContex }, 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); diff --git a/nebula_terminal/src/tty/completion.ps1 b/nebula_terminal/src/tty/completion.ps1 index db5f132ad..446bd379a 100644 --- a/nebula_terminal/src/tty/completion.ps1 +++ b/nebula_terminal/src/tty/completion.ps1 @@ -10,19 +10,8 @@ if (Get-Command Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) { # Windows PowerShell's bundled PSReadLine lacks -Chord. Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F12','Shift+Ctrl+F12' } } - # The prompt-redraw chord joins the same ownership boundary as the - # query: both are probed before either is installed, so a user-held - # F11 never leaves a half-installed channel behind, and the pairing - # never falls back to a keyboard byte that invokes user rebinding. - $clearExisting = if ($query.Parameters.ContainsKey('Chord')) { - Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue - } else { - @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F11','Shift+Ctrl+F11' }) - } - if ((-not $existing -or $existing.Function -eq 'Unbound' -or - ($global:PebrelEditorHandlerName -and $existing.Function -eq $global:PebrelEditorHandlerName)) -and - (-not $clearExisting -or $clearExisting.Function -eq 'Unbound' -or - $clearExisting.Function -eq 'ClearScreen')) { + if (-not $existing -or $existing.Function -eq 'Unbound' -or + ($global:PebrelEditorHandlerName -and $existing.Function -eq $global:PebrelEditorHandlerName)) { $global:PebrelEditorHandlerName = 'PebrelNativeEditor:' + $global:PebrelShellToken Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F12 -ScriptBlock { param($key, $arg) @@ -39,7 +28,21 @@ if (Get-Command Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor=$payload$([char]7)") } } -BriefDescription $global:PebrelEditorHandlerName - Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function ClearScreen + # The prompt-redraw pairing: an owned chord bound to the native + # ClearScreen, probed separately so a user-held F11 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. + $clearExisting = if ($query.Parameters.ContainsKey('Chord')) { + Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue + } else { + @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F11','Shift+Ctrl+F11' }) + } + if (-not $clearExisting -or $clearExisting.Function -eq 'Unbound' -or + $clearExisting.Function -eq 'ClearScreen') { + Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function ClearScreen + $global:PebrelRedrawReady = $true + } # 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)) diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index 63864824d..d26fb8984 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -1,10 +1,17 @@ -# Private editor query and prompt redraw; existing user bindings retain -# ownership of F24 and the clear-screen redraw key. +# Private editor query and prompt redraw, advertised as separate capabilities; +# existing user bindings retain ownership of F24 and the clear-screen redraw key. __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. 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 + printf '\033]1337;SetUserVar=pebrel_editor_redraw=%s\007' "$__pebrel_shell_token" + fi } __pebrel_editor_report() { @@ -34,31 +41,36 @@ __pebrel_editor_report() { 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 [[ $__pebrel_binding == '"\e[46~":'* ]] && __pebrel_clear_bound=1 - done < <(bind -p 2>/dev/null; bind -X 2>/dev/null) - # The redraw key is a readline function binding, not a shell command: the - # editor clears the screen and repaints prompt, buffer and caret itself. - # Both keys are probed before either binding is installed, so an occupied - # redraw key never leaves half of the private channel behind. The rollback - # runs only for the query binding this invocation just installed, and - # bind -r takes the bare key sequence. - if [[ $__pebrel_editor_bound == 0 && $__pebrel_clear_bound == 0 ]]; then + 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 - if bind '"\e[46~": clear-screen' 2>/dev/null; then - __pebrel_editor_ready=1 - else - bind -r '\e[45~' 2>/dev/null - fi + __pebrel_editor_ready=1 + fi + fi + if [[ $__pebrel_clear_bound == 0 ]]; then + if bind '"\e[46~": clear-screen' 2>/dev/null; then + __pebrel_editor_redraw=1 fi fi unset __pebrel_editor_bound __pebrel_clear_bound __pebrel_binding elif [ -n "${ZSH_VERSION-}" ]; then - if [[ $(bindkey '\e[45~') == *undefined-key ]] && [[ $(bindkey '\e[46~') == *undefined-key ]]; then + if [[ $(bindkey '\e[45~') == *undefined-key ]]; then zle -N __pebrel_editor_report bindkey '\e[45~' __pebrel_editor_report - bindkey '\e[46~' clear-screen __pebrel_editor_ready=1 fi + # A bindkey -s string macro also reports a non-widget body, so the + # undefined-key probe treats it as user-owned and leaves it in place. + if [[ $(bindkey '\e[46~') == *undefined-key ]]; then + bindkey '\e[46~' clear-screen + __pebrel_editor_redraw=1 + fi fi diff --git a/nebula_terminal/src/tty/windows/mod.rs b/nebula_terminal/src/tty/windows/mod.rs index 89e79a605..83b876c0c 100644 --- a/nebula_terminal/src/tty/windows/mod.rs +++ b/nebula_terminal/src/tty/windows/mod.rs @@ -466,6 +466,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) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_redraw=$global:PebrelShellToken$([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 57618e085..eb15cfa1b 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -40,7 +40,7 @@ def snapshot(self, session: shell_integration.ShellSession) -> tuple[str, int, s return owner, int(cursor), line def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, - owned_redraw: bool = False) -> shell_integration.ShellSession: + owned_redraw: bool = False, owned_macro: bool = False) -> shell_integration.ShellSession: root = Path(__file__).resolve().parents[2] program = shutil.which(shell) if not program: @@ -65,7 +65,7 @@ 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 or owned_redraw: + if owned_binding or owned_redraw or owned_macro: if shell == "bash": inputrc = self.fixture.home / ".inputrc" lines = "" @@ -73,6 +73,9 @@ def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, 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' inputrc.write_text(lines) env["INPUTRC"] = str(inputrc) else: @@ -81,6 +84,8 @@ def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, 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" (self.fixture.home / ".zshrc").write_text(zshrc) session = shell_integration.ShellSession(program, self.fixture.home, args, env) self.addCleanup(session.close) @@ -175,21 +180,39 @@ def test_ssh_bash_bootstrap_redraws_through_the_owned_clear_key(self) -> None: 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) - # A user-owned redraw key withdraws the whole native editor channel. - self.assertNotIn(b"SetUserVar=pebrel_editor_ready=", session.output) + 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 withdrawal must also remove the query binding this invocation - # installed: no half of the private channel may survive the collision. - bindings = session.command( - "bind -p 2>/dev/null; bind -X 2>/dev/null; printf 'BINDINGS-END\\n'", - b"BINDINGS-END\r\n", - ) - self.assertNotIn(b'"\\e[45~"', bindings) + # The user's function binding survived; clear-screen never replaced it. + 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"clear-screen", bindings) def test_ssh_bash_bootstrap_retains_user_owned_redraw_binding(self) -> None: self.check_owned_redraw_binding("bash", "ssh") @@ -197,6 +220,62 @@ def test_ssh_bash_bootstrap_retains_user_owned_redraw_binding(self) -> None: 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~ printf 'AFTER-MACRO\\n'; \n") + output = session.wait(b"AFTER-MACRO\r\n") + self.assertIn(b"PEBREL-USER-MACRO", output) + self.assertNotIn(b"SetUserVar=pebrel_editor=", output) + 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"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 + self.assertIn(b"SetUserVar=pebrel_editor_ready=", session.output) + os.write(session.master, b"echo tail") + # Withdraw only the redraw binding this invocation installed, which is + # exactly the state a query-only integration advertises. + session.command( + "bind -r '\\e[46~' 2>/dev/null; bindkey -r '\\e[46~' 2>/dev/null; printf 'WITHDRAWN\\n'", + b"WITHDRAWN\r\n", + ) + 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) + + 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 41fcdabaa..b8e3af066 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -229,14 +229,18 @@ def test_pointer_chords_preserve_the_clipboard_key(self) -> None: def test_user_owned_redraw_chord_withdraws_the_editor_channel(self) -> None: # Ctrl+Shift+F11 is the owned prompt-redraw chord: a user binding on it - # withdraws the whole native editor stack, and nothing is half-installed - # — the query chord answers nothing either. + # withdraws only the redraw capability. Query, completion and pointer + # support keep working exactly as in the pre-redraw releases. session = self.start(before="Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function BeginningOfLine") - self.assertNotIn(b"SetUserVar=pebrel_editor_ready=", session.output) - self.assertNotIn(b"SetUserVar=pebrel_pointer_ready=", 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") + os.write(session.master, b"\x1b[23;6~") + # The user's BeginningOfLine still owns the chord, not ClearScreen. session.settle() - self.assertNotIn(b"SetUserVar=pebrel_editor=", session.output) + self.assertEqual(self.snapshot(session), (0, "echo probe")) def test_production_bootstrap_preserves_native_prompt_and_command_lifecycle(self) -> None: session = self.start(before="function prompt { if ($?) { 'native-ok> ' } else { 'native-failed> ' } }") From e082a9ea6ae1c123c98b231bd96931a57c99ae7a Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 12 Nov 2026 17:29:38 +0800 Subject: [PATCH 11/20] fix(tty): re-verify redraw ownership at every prompt The redraw advertisement only probed the binding at install time, so rebinding the chord in the same shell left the capability announced: the view kept sending \e[46~ into what had become the user's macro, and the macro text landed in the input line. Both shells and both pwsh bootstraps now re-verify the live binding before every announcement and revoke it with an empty value when the binding is no longer clear-screen, which makes the view forget the ownership; a binding the integration still owns keeps announcing its token. Also fixes the three Bash regressions from review: the collision test checks only the reserved chord's entry instead of rejecting the normal Ctrl+L clear-screen binding, the query-only test no longer queues an unterminated echo ahead of the unbind and now asserts the revocation on the next prompt plus the unbound zsh key, and the macro test verifies the inserted text through the editor query instead of an appended command that never ran. --- .../2026-10-14-terminal-clear-action.md | 30 +++++---- nebula_app/res/shell/powershell.ps1 | 9 ++- .../gpui_shell/terminal/view/startup_tests.rs | 47 +++++++++++++ nebula_terminal/src/tty/completion.sh | 28 ++++++-- nebula_terminal/src/tty/windows/mod.rs | 2 +- scripts/tests/test_completion_editor.py | 67 ++++++++++++++++--- scripts/tests/test_powershell_pointer.py | 17 +++++ 7 files changed, 171 insertions(+), 29 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md index f1f60219e..7ac81481b 100644 --- a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md +++ b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md @@ -56,11 +56,12 @@ established macOS ⌘K clear convention had no path to that behavior. 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, or a user-owned redraw key — 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). + 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 @@ -129,12 +130,15 @@ established macOS ⌘K clear convention had no path to that behavior. 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. 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. + 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 @@ -151,7 +155,9 @@ settings-pane suite, the i18n contract suites, the 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), `cargo test -p nebula --test file_line_budget` +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 nebula --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. diff --git a/nebula_app/res/shell/powershell.ps1 b/nebula_app/res/shell/powershell.ps1 index 7ac760dac..296b4de48 100644 --- a/nebula_app/res/shell/powershell.ps1 +++ b/nebula_app/res/shell/powershell.ps1 @@ -20,7 +20,14 @@ if (-not $global:PebrelUnixReadLineInstalled) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_ready=$global:PebrelEditorReady$([char]7)") } if ($global:PebrelRedrawReady) { - [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_redraw=$global:PebrelShellToken$([char]7)") + # Re-verify the live chord each prompt: a same-shell rebind revokes + # the capability with an empty value so the view forgets it. + $redrawChord = Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue + if ($redrawChord -and $redrawChord.Function -eq 'ClearScreen') { + [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') { diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index 00d362256..06604306a 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -235,6 +235,53 @@ fn clear_screen_sends_the_owned_powershell_chord_for_pwsh(cx: &mut TestAppContex 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); diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index d26fb8984..213b1b28c 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -1,16 +1,34 @@ # 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 + local tables + tables=$(bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null) + [[ $tables == *'"\\e[46~": clear-screen'* ]] + else + [[ $(bindkey '\e[46~') == *clear-screen* ]] + 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. 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. + # 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 - printf '\033]1337;SetUserVar=pebrel_editor_redraw=%s\007' "$__pebrel_shell_token" + 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 } diff --git a/nebula_terminal/src/tty/windows/mod.rs b/nebula_terminal/src/tty/windows/mod.rs index 83b876c0c..14f2906ae 100644 --- a/nebula_terminal/src/tty/windows/mod.rs +++ b/nebula_terminal/src/tty/windows/mod.rs @@ -466,7 +466,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) { [Console]::Write("$([char]27)]1337;SetUserVar=pebrel_editor_redraw=$global:PebrelShellToken$([char]7)") } + if ($global:PebrelRedrawReady) { $redrawChord = Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue; if ($redrawChord -and $redrawChord.Function -eq 'ClearScreen') { [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 eb15cfa1b..d1869df32 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -173,6 +173,11 @@ def check_integration_clear(self, shell: str, route: str) -> None: 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") @@ -205,14 +210,16 @@ def check_owned_redraw_binding(self, shell: str, route: str) -> None: 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; clear-screen never replaced it. + # 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"clear-screen", 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") @@ -229,17 +236,16 @@ def check_owned_redraw_macro(self, shell: str, route: str) -> None: # 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~ printf 'AFTER-MACRO\\n'; \n") - output = session.wait(b"AFTER-MACRO\r\n") - self.assertIn(b"PEBREL-USER-MACRO", output) - self.assertNotIn(b"SetUserVar=pebrel_editor=", 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"clear-screen", bindings) + 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") @@ -254,14 +260,19 @@ def check_query_only_session(self, shell: str, route: str) -> None: session = self.start_bootstrap(shell, route) if self.check_legacy_bash(shell, session): return - self.assertIn(b"SetUserVar=pebrel_editor_ready=", session.output) - os.write(session.master, b"echo tail") + ready_token = re.search(rb"SetUserVar=pebrel_editor_ready=([^\x07]+)\x07", session.output) + self.assertIsNotNone(ready_token, session.output) # Withdraw only the redraw binding this invocation installed, which is # exactly the state a query-only integration advertises. session.command( "bind -r '\\e[46~' 2>/dev/null; bindkey -r '\\e[46~' 2>/dev/null; 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'", @@ -269,6 +280,42 @@ def check_query_only_session(self, shell: str, route: str) -> None: ) 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. + 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": + rebind = "bind '\"\\e[46~\": \"PEBREL-REBIND\"'" + else: + rebind = "bindkey -s '\\e[46~' 'PEBREL-REBIND'" + 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, "echo tailPEBREL-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 test_ssh_bash_bootstrap_query_only_session_leaves_redraw_unbound(self) -> None: self.check_query_only_session("bash", "ssh") diff --git a/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index b8e3af066..462e5d406 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -242,6 +242,23 @@ def test_user_owned_redraw_chord_withdraws_the_editor_channel(self) -> None: session.settle() self.assertEqual(self.snapshot(session), (0, "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+F11 -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+F11).Function\r") + output = session.wait(b"PS> ") + self.assertIn(b"BeginningOfLine", output) + self.assertNotIn(b"ClearScreen", output) + def test_production_bootstrap_preserves_native_prompt_and_command_lifecycle(self) -> None: session = self.start(before="function prompt { if ($?) { 'native-ok> ' } else { 'native-failed> ' } }") self.assertIn(b"native-ok> ", session.output) From 681274ea1ff08d09bec331f3b95facbc68db2aa1 Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 12 Nov 2026 18:11:58 +0800 Subject: [PATCH 12/20] fix(tty): match the redraw entry's tail in the Bash ownership probe The re-verification pattern searched for the entry with its leading quotation mark and escaped key, but a [[ == ]] pattern treats \e as an escaped e after quote removal, so the literal backslash in the binding table never matched and every prompt revoked a binding the integration still owned - visible on the Linux runner as an immediate empty redraw advertisement and the sustained-announcement and rebind regressions failing together. Match the entry's tail instead: whatever renders the key's escape, our key's entry always ends with 46~": followed by the clear-screen function name. Verified against a real bash 5.2 build: owned, rebind-revoked and macro-preserved scenarios all report the expected probe results. --- nebula_terminal/src/tty/completion.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index 213b1b28c..e4e1deeae 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -7,7 +7,10 @@ __pebrel_redraw_owned() { if [ -n "${BASH_VERSION-}" ]; then local tables tables=$(bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null) - [[ $tables == *'"\\e[46~": clear-screen'* ]] + # Match the entry's tail: the key's ESC escape renders differently + # across readline versions, but our key's entry always ends with + # 46~": followed by the clear-screen function name. + [[ $tables == *"46~\": clear-screen"* ]] else [[ $(bindkey '\e[46~') == *clear-screen* ]] fi From 554235a84b191323453f32bd91fa995d297f3e03 Mon Sep 17 00:00:00 2001 From: zher52 Date: Thu, 12 Nov 2026 18:43:10 +0800 Subject: [PATCH 13/20] fix(tty): move the pwsh redraw off the paste chord and probe exact keys Three problems from review: Windows: completion.ps1 claimed Ctrl+Shift+F11 - the exact chord clipboard.ps1 needs for native paste - so production load order silently dropped paste support and its capability report. The redraw chord moves to Ctrl+Shift+F9, and the per-prompt re-verification moves into Test-PebrelRedrawBinding in completion.ps1, which reuses the installation's -Chord-less fallback for legacy PSReadLine. Bash: the ownership probe matched the entry's tail, so a clear-screen binding on \e[146~ stood in for our \e[46~ while the real key carried a user macro. [[ ]] patterns mangle the entry's backslash-and-bracket combination, so the probe now pipes the binding tables through grep -F against the key's complete entry; an unrecognized table counts as not owned. The rebind regression adds the \e[146~ decoy. zsh: the redraw binding now uses the built-in widget's canonical name (.clear-screen), and the probe requires the space-anchored built-in identity - a bindkey -s macro reading clear-screen or .clear-screen and a user widget shadowing the name all revoke. --- .../2026-10-14-terminal-clear-action.md | 7 ++-- nebula_app/res/shell/powershell.ps1 | 3 +- .../src/gpui_shell/terminal/view/editor.rs | 6 +-- .../gpui_shell/terminal/view/startup_tests.rs | 2 +- nebula_terminal/src/tty/completion.ps1 | 26 +++++++++--- nebula_terminal/src/tty/completion.sh | 25 +++++++---- nebula_terminal/src/tty/windows/mod.rs | 2 +- scripts/tests/test_completion_editor.py | 41 +++++++++++++------ scripts/tests/test_powershell_pointer.py | 32 +++++++++++---- 9 files changed, 101 insertions(+), 43 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md index 7ac81481b..6030b1dbc 100644 --- a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md +++ b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md @@ -51,9 +51,10 @@ established macOS ⌘K clear convention had no path to that behavior. 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+F11` → `ClearScreen` chord — so the shell's own - line editor clears the glass and repaints prompt, buffer and caret, - keeping its line state in sync. + 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 diff --git a/nebula_app/res/shell/powershell.ps1 b/nebula_app/res/shell/powershell.ps1 index 296b4de48..f08913659 100644 --- a/nebula_app/res/shell/powershell.ps1 +++ b/nebula_app/res/shell/powershell.ps1 @@ -22,8 +22,7 @@ if (-not $global:PebrelUnixReadLineInstalled) { 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. - $redrawChord = Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue - if ($redrawChord -and $redrawChord.Function -eq 'ClearScreen') { + 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)") diff --git a/nebula_app/src/gpui_shell/terminal/view/editor.rs b/nebula_app/src/gpui_shell/terminal/view/editor.rs index 1ab0153c2..d7a1472c7 100644 --- a/nebula_app/src/gpui_shell/terminal/view/editor.rs +++ b/nebula_app/src/gpui_shell/terminal/view/editor.rs @@ -242,7 +242,7 @@ impl TerminalView { /// 提示符重绘字节:`pebrel_editor_redraw` 声明的 shell 集成自有键 /// (completion.sh 的 `\e[46~` → readline/zle 原生 clear-screen, - /// completion.ps1 的 Ctrl+Shift+F11 → PSReadLine ClearScreen)。redraw + /// completion.ps1 的 Ctrl+Shift+F9 → PSReadLine ClearScreen)。redraw /// 是独立于查询能力(`pebrel_editor_ready`)的显式声明:2.5.3 旧集成 /// 只报 query、不装 redraw 键,只看 ready 会把键发进未绑定它的活动 /// shell;用户占用 redraw 键时声明整体缺席,query/补全/指针照常。 @@ -254,9 +254,9 @@ impl TerminalView { return None; } if owner.starts_with("pwsh:") { - let key = gpui::Keystroke::parse("ctrl-shift-f11").unwrap(); + let key = gpui::Keystroke::parse("ctrl-shift-f9").unwrap(); super::super::keymap::encode(&key, &self.term_mode()) - .or_else(|| Some(b"\x1b[23;6~".to_vec())) + .or_else(|| Some(b"\x1b[20;6~".to_vec())) } else { Some(b"\x1b[46~".to_vec()) } diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index 06604306a..61119d6cd 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -228,7 +228,7 @@ fn clear_screen_sends_the_owned_powershell_chord_for_pwsh(cx: &mut TestAppContex }) .collect(); let expected = view.read_with(cx, |view, _| { - let key = gpui::Keystroke::parse("ctrl-shift-f11").unwrap(); + let key = gpui::Keystroke::parse("ctrl-shift-f9").unwrap(); vec![keymap::encode(&key, &view.term_mode()).unwrap()] }); assert_eq!(writes, expected); diff --git a/nebula_terminal/src/tty/completion.ps1 b/nebula_terminal/src/tty/completion.ps1 index 446bd379a..22465a274 100644 --- a/nebula_terminal/src/tty/completion.ps1 +++ b/nebula_terminal/src/tty/completion.ps1 @@ -29,18 +29,19 @@ if (Get-Command Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) { } } -BriefDescription $global:PebrelEditorHandlerName # The prompt-redraw pairing: an owned chord bound to the native - # ClearScreen, probed separately so a user-held F11 leaves query, + # 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. + # keyboard byte that invokes user rebinding. Ctrl+Shift+F9 keeps + # Ctrl+Shift+F11 free for clipboard.ps1's native paste binding. $clearExisting = if ($query.Parameters.ContainsKey('Chord')) { - Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue + Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -ErrorAction SilentlyContinue } else { - @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F11','Shift+Ctrl+F11' }) + @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F9','Shift+Ctrl+F9' }) } if (-not $clearExisting -or $clearExisting.Function -eq 'Unbound' -or $clearExisting.Function -eq 'ClearScreen') { - Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function ClearScreen + Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -Function ClearScreen $global:PebrelRedrawReady = $true } # PSReadLine 2.0 loses surrogate pairs inserted after native editing. @@ -52,3 +53,18 @@ 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' }) + } + $bound -and $bound.Function -eq 'ClearScreen' + } catch { $false } +} diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index e4e1deeae..4f7f9c219 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -5,14 +5,20 @@ # the ownership, while a binding the integration still owns keeps announcing. __pebrel_redraw_owned() { if [ -n "${BASH_VERSION-}" ]; then - local tables - tables=$(bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null) - # Match the entry's tail: the key's ESC escape renders differently - # across readline versions, but our key's entry always ends with - # 46~": followed by the clear-screen function name. - [[ $tables == *"46~\": clear-screen"* ]] + # grep -F matches the key's complete binding entry without any pattern + # escaping: [[ ]] patterns mangle the entry's "\" and "[" combination, + # and a tail-only match would also accept a binding on \e[146~. The + # fixed string takes the table's literal single backslash. An + # unrecognized table counts as not owned. + { bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null; } | + grep -qF '"\e[46~": clear-screen' else - [[ $(bindkey '\e[46~') == *clear-screen* ]] + # 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' ]] fi } @@ -91,7 +97,10 @@ elif [ -n "${ZSH_VERSION-}" ]; then # A bindkey -s string macro also reports a non-widget body, so the # undefined-key probe treats it as user-owned and leaves it in place. if [[ $(bindkey '\e[46~') == *undefined-key ]]; then - bindkey '\e[46~' clear-screen + # Bind the built-in widget's canonical name: a user widget may shadow + # `clear-screen`, and binding the original keeps the redraw independent + # of such shadowing. + bindkey '\e[46~' .clear-screen __pebrel_editor_redraw=1 fi fi diff --git a/nebula_terminal/src/tty/windows/mod.rs b/nebula_terminal/src/tty/windows/mod.rs index 14f2906ae..0725d2fea 100644 --- a/nebula_terminal/src/tty/windows/mod.rs +++ b/nebula_terminal/src/tty/windows/mod.rs @@ -466,7 +466,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) { $redrawChord = Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -ErrorAction SilentlyContinue; if ($redrawChord -and $redrawChord.Function -eq 'ClearScreen') { [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)") } } + 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 d1869df32..632f8f025 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -292,24 +292,41 @@ def test_ssh_zsh_bootstrap_query_only_session_leaves_redraw_unbound(self) -> Non 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. + # 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": [("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": - rebind = "bind '\"\\e[46~\": \"PEBREL-REBIND\"'" - else: - rebind = "bindkey -s '\\e[46~' 'PEBREL-REBIND'" - 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, "echo tailPEBREL-REBIND") + # A decoy clear-screen on \e[146~ must not satisfy the probe for + # \e[46~: the following rebind revokes 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") diff --git a/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index 462e5d406..d6fda969c 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -62,6 +62,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" @@ -224,24 +225,39 @@ def test_pointer_chords_preserve_the_clipboard_key(self) -> None: 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[23;6~") + 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+F11 is the owned prompt-redraw chord: a user binding on it - # withdraws only the redraw capability. Query, completion and pointer - # support keep working exactly as in the pre-redraw releases. - session = self.start(before="Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function BeginningOfLine") + # 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[23;6~") + 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. + session = self.start() + os.write(session.master, b"(Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F9).Function\r") + output = session.wait(b"PS> ") + self.assertIn(b"ClearScreen", 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"ClearScreen", output.split(b"(Get-PSReadLineKeyHandler")[-1]) + 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 @@ -250,11 +266,11 @@ def test_rebinding_the_redraw_chord_revokes_the_advertisement(self) -> None: self.assertIn(b"SetUserVar=pebrel_editor_redraw=cHdzaDpmaXh0dXJl\x07", session.output) os.write( session.master, - b"Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F11 -Function BeginningOfLine\r", + 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+F11).Function\r") + 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) From 90860de911b9a9b9d15db68ed720e898bb4ff57f Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 00:29:54 +0800 Subject: [PATCH 14/20] fix(tty): redraw ownership survives lookalike bindings and keymap switches The Bash probe matched the clear-screen entry as a fixed substring, so a lookalike binding line that merely contains it kept a revoked chord announced while a quoted macro on the key fired user text. The probe now matches the complete binding line. The zsh probe validated only the prompt-time keymap; switching to vicmd inside the same prompt could route the byte into a user widget while the redraw capability stayed announced. Ownership now requires the built-in widget (or an inert unbound key) in every keymap one prompt can reach; the probe only reads, so user bindings stay untouched. PowerShell accepted Function == ClearScreen as ownership, but Function is PSReadLine's display description: a scriptblock with BriefDescription ClearScreen could take the chord before startup or rebind it afterwards and still count as native redraw. The installation now tags its binding with a Description token and both the startup probe and the per-prompt re-check match that token; anything else on the chord is user-owned and stays untouched. --- nebula_terminal/src/tty/completion.ps1 | 21 ++++++--- nebula_terminal/src/tty/completion.sh | 36 +++++++++++++--- scripts/tests/test_completion_editor.py | 55 ++++++++++++++++++++++-- scripts/tests/test_powershell_pointer.py | 32 ++++++++++++++ 4 files changed, 129 insertions(+), 15 deletions(-) diff --git a/nebula_terminal/src/tty/completion.ps1 b/nebula_terminal/src/tty/completion.ps1 index 22465a274..63e4c9866 100644 --- a/nebula_terminal/src/tty/completion.ps1 +++ b/nebula_terminal/src/tty/completion.ps1 @@ -28,20 +28,27 @@ 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 bound to the native + # 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' -or - $clearExisting.Function -eq 'ClearScreen') { - Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -Function ClearScreen + if (-not $clearExisting -or $clearExisting.Function -eq 'Unbound') { + $global:PebrelRedrawDescription = 'PebrelRedraw:' + $global:PebrelShellToken + Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -Function ClearScreen ` + -Description $global:PebrelRedrawDescription $global:PebrelRedrawReady = $true } # PSReadLine 2.0 loses surrogate pairs inserted after native editing. @@ -65,6 +72,10 @@ function global:Test-PebrelRedrawBinding { } else { @(Get-PSReadLineKeyHandler -ErrorAction Stop | Where-Object { $_.Key -in 'Ctrl+Shift+F9','Shift+Ctrl+F9' }) } - $bound -and $bound.Function -eq 'ClearScreen' + # Function is only a display description (see the installation probe): + # the token in Description is what proves the chord still carries the + # binding this session installed. + $bound -and $bound.Function -eq 'ClearScreen' -and + $bound.Description -eq $global:PebrelRedrawDescription } catch { $false } } diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index 4f7f9c219..d54c3e55c 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -5,20 +5,44 @@ # the ownership, while a binding the integration still owns keeps announcing. __pebrel_redraw_owned() { if [ -n "${BASH_VERSION-}" ]; then - # grep -F matches the key's complete binding entry without any pattern + # grep -x matches the key's complete binding line without any pattern # escaping: [[ ]] patterns mangle the entry's "\" and "[" combination, - # and a tail-only match would also accept a binding on \e[146~. The - # fixed string takes the table's literal single backslash. An - # unrecognized table counts as not owned. + # 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 -qF '"\e[46~": clear-screen' + grep -qxF '"\e[46~": clear-screen' 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' ]] + [[ $(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: a viins announcement + # would still send the byte into a user widget waiting in vicmd. The + # chord must therefore resolve to the built-in (or be unbound — an + # unbound key is inert, no user code runs) in every keymap; a string + # macro or a user widget anywhere revokes ownership. The probe only + # reads, so the user's vicmd binding stays untouched. + local -a keymaps reports + local keymap line owned=1 + keymaps=(${(f)"$(bindkey -l 2>/dev/null)"}) + (( ${#keymaps} )) || return 1 + reports=(${(f)"$(for keymap in "${keymaps[@]}"; do + bindkey -M "$keymap" '\e[46~' 2>/dev/null + done)"}) + (( ${#reports} )) || return 1 + for line in "${reports[@]}"; do + case $line in + *undefined-key*|*' .clear-screen') ;; + *) owned=0; break ;; + esac + done + (( owned )) fi } diff --git a/scripts/tests/test_completion_editor.py b/scripts/tests/test_completion_editor.py index 632f8f025..b6703a17b 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 @@ -40,7 +41,8 @@ def snapshot(self, session: shell_integration.ShellSession) -> tuple[str, int, s return owner, int(cursor), line def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, - owned_redraw: bool = False, owned_macro: bool = False) -> shell_integration.ShellSession: + owned_redraw: bool = False, owned_macro: bool = False, + vicmd_widget: bool = False) -> shell_integration.ShellSession: root = Path(__file__).resolve().parents[2] program = shutil.which(shell) if not program: @@ -65,7 +67,7 @@ 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 or owned_redraw or owned_macro: + if owned_binding or owned_redraw or owned_macro or vicmd_widget: if shell == "bash": inputrc = self.fixture.home / ".inputrc" lines = "" @@ -86,6 +88,14 @@ def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, 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" + ) (self.fixture.home / ".zshrc").write_text(zshrc) session = shell_integration.ShellSession(program, self.fixture.home, args, env) self.addCleanup(session.close) @@ -298,7 +308,18 @@ def check_redraw_rebind(self, shell: str, route: str) -> None: # macro whose text is exactly the widget's name, and a user widget # shadowing that name — neither may keep the capability announced. rebinds = { - "bash": [("bind '\"\\e[46~\": \"PEBREL-REBIND\"'", "PEBREL-REBIND")], + "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"), @@ -316,7 +337,7 @@ def check_redraw_rebind(self, shell: str, route: str) -> None: 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 rebind revokes despite the decoy staying. + # \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 @@ -334,6 +355,32 @@ def test_ssh_bash_rebinding_the_redraw_chord_revokes_the_advertisement(self) -> 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) + self.assertIsNotNone( + re.search(rb"SetUserVar=pebrel_editor_ready=([^\x07]+)\x07", session.output), + session.output, + ) + token = re.search(rb"SetUserVar=pebrel_editor_redraw=([^\x07]+)\x07", session.output) + self.assertIsNone(token, session.output) + self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", 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 test_ssh_bash_bootstrap_query_only_session_leaves_redraw_unbound(self) -> None: self.check_query_only_session("bash", "ssh") diff --git a/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index d6fda969c..64b8bf717 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -275,6 +275,38 @@ def test_rebinding_the_redraw_chord_revokes_the_advertisement(self) -> None: 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()) + output = session.wait(b"PS> ") + self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", 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> ' } }") self.assertIn(b"native-ok> ", session.output) From 30b5aed9cb4f1cea8c9a8d186c0517dae02f88d7 Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 06:55:19 +0800 Subject: [PATCH 15/20] fix(tty): install the pwsh redraw in a supported parameter set MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PSReadLine 2.4.5 keeps -Function and -Description in different parameter sets, so the redraw install threw ('Parameter Function cannot be specified in parameter set ScriptBlock.') and the outer catch killed the whole editor and pointer init with it. The redraw now installs through the ScriptBlock set — a handler performing the native ClearScreen work (erase display and scrollback, re-prompt) — carrying the session token in -Description inside its own try, so a refusing PSReadLine only leaves the redraw advertisement off. Identity moves with it: the per-prompt re-check matches the Description token alone, since Function is a display name scriptblocks imitate. The zsh ownership probe accepted any report containing undefined-key, so a quoted vicmd macro whose body merely contains the word stayed announced and fired user text; the probe now matches the bare space-anchored undefined-key tail an unbound keymap reports and revokes keymaps it cannot query. The bash probe validated only the prompt-time keymap; the probe now walks every keymap reachable within one prompt (emacs-standard/-ctlx/ -meta, vi-insert, vi-command, vi-move) inside a single subshell, anchoring entries to the key's complete binding line and restoring the original keymap before returning, so a user macro waiting in vi-command revokes while an unbound chord elsewhere stays inert. The PowerShell and bash-5 paths run on the Linux CI as before; the zsh editor suite is green locally. --- nebula_terminal/src/tty/completion.ps1 | 33 ++++++++++---- nebula_terminal/src/tty/completion.sh | 46 ++++++++++++++------ scripts/tests/test_completion_editor.py | 55 +++++++++++++++++++++++- scripts/tests/test_powershell_pointer.py | 46 ++++++++++++++++++-- 4 files changed, 154 insertions(+), 26 deletions(-) diff --git a/nebula_terminal/src/tty/completion.ps1 b/nebula_terminal/src/tty/completion.ps1 index 63e4c9866..0df4bcc50 100644 --- a/nebula_terminal/src/tty/completion.ps1 +++ b/nebula_terminal/src/tty/completion.ps1 @@ -46,10 +46,27 @@ if (Get-Command Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) { @(Get-PSReadLineKeyHandler | Where-Object { $_.Key -in 'Ctrl+Shift+F9','Shift+Ctrl+F9' }) } if (-not $clearExisting -or $clearExisting.Function -eq 'Unbound') { - $global:PebrelRedrawDescription = 'PebrelRedraw:' + $global:PebrelShellToken - Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -Function ClearScreen ` - -Description $global:PebrelRedrawDescription - $global:PebrelRedrawReady = $true + # 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. @@ -72,10 +89,10 @@ function global:Test-PebrelRedrawBinding { } 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): - # the token in Description is what proves the chord still carries the + # 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.Function -eq 'ClearScreen' -and - $bound.Description -eq $global:PebrelRedrawDescription + $bound -and $bound.Description -eq $global:PebrelRedrawDescription } catch { $false } } diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index d54c3e55c..d0ea6901d 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -13,7 +13,27 @@ __pebrel_redraw_owned() { # 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' + grep -qxF '"\e[46~": clear-screen' || return 1 + # Ownership must also hold in every keymap reachable within one prompt: + # vi mode switches vi-insert <-> vi-command mid-line via ESC, so a + # clear-screen in vi-insert next to a user macro waiting in vi-command + # would still send the byte into user code. The other keymaps may carry + # our binding or leave the chord unbound (an unbound key is inert, no + # user code runs), but any user function or macro revokes. Entries are + # anchored to the key's complete line, so a lookalike chord sequence + # ending in \e[46~ never trips the probe; the enumeration runs in one + # subshell and the original keymap is restored before returning. The + # probe only reads, so the user's bindings stay untouched. + local current rest keymap + current=$(bind -v 2>/dev/null | grep -E '^set keymap ' | cut -d ' ' -f3) + [ -n "$current" ] || return 1 + rest=$(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 + { bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null; } + done 2>/dev/null | grep -E '^"\\e\[46~":' | grep -vxF '"\e[46~": clear-screen') + bind "set keymap $current" 2>/dev/null + [ -z "$rest" ] else # The bound widget must be the built-in original: bindkey reports the # value space-separated, so a space-anchored ".clear-screen" tail only @@ -26,19 +46,21 @@ __pebrel_redraw_owned() { # would still send the byte into a user widget waiting in vicmd. The # chord must therefore resolve to the built-in (or be unbound — an # unbound key is inert, no user code runs) in every keymap; a string - # macro or a user widget anywhere revokes ownership. The probe only - # reads, so the user's vicmd binding stays untouched. - local -a keymaps reports - local keymap line owned=1 + # macro or a user widget anywhere revokes ownership. The queried key + # renders before the value, so an unbound keymap reports a bare + # space-anchored "undefined-key" tail while a macro always ends in a + # quote — one whose body merely contains the word (e.g. + # 'aundefined-key') revokes. A keymap the probe cannot query reports + # nothing, which revokes too. The probe only reads, so the user's + # vicmd binding stays untouched. + local -a keymaps + local keymap report owned=1 keymaps=(${(f)"$(bindkey -l 2>/dev/null)"}) (( ${#keymaps} )) || return 1 - reports=(${(f)"$(for keymap in "${keymaps[@]}"; do - bindkey -M "$keymap" '\e[46~' 2>/dev/null - done)"}) - (( ${#reports} )) || return 1 - for line in "${reports[@]}"; do - case $line in - *undefined-key*|*' .clear-screen') ;; + for keymap in "${keymaps[@]}"; do + report=$(bindkey -M "$keymap" '\e[46~' 2>/dev/null) + case $report in + *' undefined-key'|*' .clear-screen') ;; *) owned=0; break ;; esac done diff --git a/scripts/tests/test_completion_editor.py b/scripts/tests/test_completion_editor.py index b6703a17b..1810eeb38 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -42,7 +42,8 @@ def snapshot(self, session: shell_integration.ShellSession) -> tuple[str, int, s def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, owned_redraw: bool = False, owned_macro: bool = False, - vicmd_widget: bool = False) -> shell_integration.ShellSession: + vicmd_widget: bool = False, vicmd_macro: bool = False, + vi_command_macro: bool = False) -> shell_integration.ShellSession: root = Path(__file__).resolve().parents[2] program = shutil.which(shell) if not program: @@ -67,7 +68,7 @@ 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 or owned_redraw or owned_macro or vicmd_widget: + if owned_binding or owned_redraw or owned_macro or vicmd_widget or vicmd_macro or vi_command_macro: if shell == "bash": inputrc = self.fixture.home / ".inputrc" lines = "" @@ -78,6 +79,13 @@ def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, 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' inputrc.write_text(lines) env["INPUTRC"] = str(inputrc) else: @@ -96,6 +104,16 @@ def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, "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" + ) (self.fixture.home / ".zshrc").write_text(zshrc) session = shell_integration.ShellSession(program, self.fixture.home, args, env) self.addCleanup(session.close) @@ -381,6 +399,39 @@ def check_redraw_keymap_switch(self, route: str) -> None: 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 + self.assertIsNotNone( + re.search(rb"SetUserVar=pebrel_editor_ready=([^\x07]+)\x07", session.output), + session.output, + ) + token = re.search(rb"SetUserVar=pebrel_editor_redraw=([^\x07]+)\x07", session.output) + self.assertIsNone(token, session.output) + self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", 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 test_ssh_bash_bootstrap_query_only_session_leaves_redraw_unbound(self) -> None: self.check_query_only_session("bash", "ssh") diff --git a/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index 64b8bf717..f26da71b2 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -248,15 +248,53 @@ def test_user_owned_redraw_chord_withdraws_the_editor_channel(self) -> None: 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. + # 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).Function\r") + os.write(session.master, b"(Get-PSReadLineKeyHandler -Chord Ctrl+Shift+F9).Description\r") output = session.wait(b"PS> ") - self.assertIn(b"ClearScreen", output) + 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"ClearScreen", output.split(b"(Get-PSReadLineKeyHandler")[-1]) + 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")) + # 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\" -match 'Ctrl\\\\+Shift\\\\+F9') { throw 'fixture: redraw refused' }\n" + " & (Get-Command Set-PSReadLineKeyHandler -CommandType Cmdlet) @args\n" + "}\n" + )) + 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 From 8a743a011abd7c0e4c3bd20b7821088c3c0f86ec Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 09:05:56 +0800 Subject: [PATCH 16/20] test(pwsh): inject the redraw refusal observably and key chords after the handshake MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The isolation fixture's refusal never fired: the stub pattern went through two escaping layers and became a regex matching a literal backslash, so Ctrl+Shift+F9 slipped through to the real cmdlet and the redraw advertised anyway. Match the argument with -contains instead and emit a SetUserVar marker before throwing, which the test asserts before the isolation conditions — a silently-passing stub can no longer hide. Rebinding-to-a-scriptblock keyed the raw chord as soon as the prompt appeared, inside the read's cursor-position handshake, so the escape sequence reached the editor split and the buffer received "~;". Wait for the next editor read to announce itself and settle the handshake before keying the chord; the revocation and USER-F9 assertions then hold. --- scripts/tests/test_powershell_pointer.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index f26da71b2..ed4a68906 100644 --- a/scripts/tests/test_powershell_pointer.py +++ b/scripts/tests/test_powershell_pointer.py @@ -286,10 +286,16 @@ def test_redraw_install_failure_is_isolated_from_the_editor(self) -> None: # redraw advertisement appears. session = self.start(before=( "function global:Set-PSReadLineKeyHandler {\n" - " if (\"$args\" -match 'Ctrl\\\\+Shift\\\\+F9') { throw 'fixture: redraw refused' }\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) @@ -339,8 +345,13 @@ def test_rebinding_to_a_same_name_scriptblock_revokes_the_advertisement(self) -> "Set-PSReadLineKeyHandler -Chord Ctrl+Shift+F9 -ScriptBlock { " "[Microsoft.PowerShell.PSConsoleReadLine]::Insert('USER-F9') } -BriefDescription ClearScreen\r" ).encode()) - output = session.wait(b"PS> ") - self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", output) + # 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") From 0aa8f1053db6bdc6f6e8965abd3dd791d00cdb7d Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 13:11:57 +0800 Subject: [PATCH 17/20] fix(tty): announce redraw only when every reachable keymap consumes the chord MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A multi-byte chord is not consumed as a whole in an unbound keymap: zsh vicmd and readline vi-command keep the trailing "~" bound to the invert-case command, so a redraw sent into a merely-unbound keymap rewrote the user's line ("original" became "originaL" in the review reproduction). "Unbound is inert" is gone from the contract. Installation now scans every reachable keymap and either installs the built-in clear-screen into each of them — vi users keep the capability, with vicmd / vi-command consuming the full chord mid-line — or, when any keymap holds a user binding, installs nothing and the capability stays off. zsh protected keymaps (.safe) refuse binding and cannot be reached through a typed chord, so they are excluded from the contract instead of killing it, and the per-prompt probe re-verifies exactly the recorded keymap set: a rebind, an unbind, a macro or an unbound keymap all revoke the announcement to the app-side cursor home. The plain-vi-mode review reproduction is a regression now: the chord is announced, sent after ESC, and the line must survive as LINE:original. --- .../2026-10-14-terminal-clear-action.md | 18 ++- nebula_terminal/src/tty/completion.sh | 129 ++++++++++++------ scripts/tests/test_completion_editor.py | 66 +++++++-- 3 files changed, 159 insertions(+), 54 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md index 6030b1dbc..4e7711510 100644 --- a/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md +++ b/architecture/notes/nebula_app/gpui_shell/2026-10-14-terminal-clear-action.md @@ -4,7 +4,10 @@ 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. +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 @@ -73,6 +76,19 @@ established macOS ⌘K clear convention had no path to that behavior. 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 diff --git a/nebula_terminal/src/tty/completion.sh b/nebula_terminal/src/tty/completion.sh index d0ea6901d..b5c9e1118 100644 --- a/nebula_terminal/src/tty/completion.sh +++ b/nebula_terminal/src/tty/completion.sh @@ -14,26 +14,29 @@ __pebrel_redraw_owned() { # 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: - # vi mode switches vi-insert <-> vi-command mid-line via ESC, so a - # clear-screen in vi-insert next to a user macro waiting in vi-command - # would still send the byte into user code. The other keymaps may carry - # our binding or leave the chord unbound (an unbound key is inert, no - # user code runs), but any user function or macro revokes. Entries are - # anchored to the key's complete line, so a lookalike chord sequence - # ending in \e[46~ never trips the probe; the enumeration runs in one - # subshell and the original keymap is restored before returning. The - # probe only reads, so the user's bindings stay untouched. - local current rest keymap + # 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 - rest=$(for keymap in emacs-standard emacs-ctlx emacs-meta vi-insert vi-command vi-move; do + 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 - { bind -p 2>/dev/null; bind -X 2>/dev/null; bind -s 2>/dev/null; } - done 2>/dev/null | grep -E '^"\\e\[46~":' | grep -vxF '"\e[46~": clear-screen') - bind "set keymap $current" 2>/dev/null - [ -z "$rest" ] + 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 @@ -42,25 +45,22 @@ __pebrel_redraw_owned() { # 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: a viins announcement - # would still send the byte into a user widget waiting in vicmd. The - # chord must therefore resolve to the built-in (or be unbound — an - # unbound key is inert, no user code runs) in every keymap; a string - # macro or a user widget anywhere revokes ownership. The queried key - # renders before the value, so an unbound keymap reports a bare - # space-anchored "undefined-key" tail while a macro always ends in a - # quote — one whose body merely contains the word (e.g. - # 'aundefined-key') revokes. A keymap the probe cannot query reports - # nothing, which revokes too. The probe only reads, so the user's - # vicmd binding stays untouched. - local -a keymaps + # 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 - keymaps=(${(f)"$(bindkey -l 2>/dev/null)"}) - (( ${#keymaps} )) || return 1 - for keymap in "${keymaps[@]}"; do + for keymap in ${=__pebrel_redraw_keymaps}; do report=$(bindkey -M "$keymap" '\e[46~' 2>/dev/null) case $report in - *' undefined-key'|*' .clear-screen') ;; + *' .clear-screen') ;; *) owned=0; break ;; esac done @@ -129,9 +129,34 @@ if [ -n "${BASH_VERSION-}" ] && (( BASH_VERSINFO[0] >= 4 )) && [[ $- == *i* ]]; fi fi if [[ $__pebrel_clear_bound == 0 ]]; then - if bind '"\e[46~": clear-screen' 2>/dev/null; then - __pebrel_editor_redraw=1 + # 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 @@ -140,13 +165,33 @@ elif [ -n "${ZSH_VERSION-}" ]; then bindkey '\e[45~' __pebrel_editor_report __pebrel_editor_ready=1 fi - # A bindkey -s string macro also reports a non-widget body, so the - # undefined-key probe treats it as user-owned and leaves it in place. - if [[ $(bindkey '\e[46~') == *undefined-key ]]; then - # Bind the built-in widget's canonical name: a user widget may shadow - # `clear-screen`, and binding the original keeps the redraw independent - # of such shadowing. - bindkey '\e[46~' .clear-screen - __pebrel_editor_redraw=1 + # 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/scripts/tests/test_completion_editor.py b/scripts/tests/test_completion_editor.py index 1810eeb38..c0811ac94 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -43,7 +43,7 @@ def snapshot(self, session: shell_integration.ShellSession) -> tuple[str, int, s 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) -> shell_integration.ShellSession: + 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: @@ -68,7 +68,7 @@ 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 or owned_redraw or owned_macro or vicmd_widget or vicmd_macro or vi_command_macro: + 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" lines = "" @@ -86,6 +86,9 @@ def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, # 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: @@ -114,6 +117,9 @@ def start_bootstrap(self, shell: str, route: str, owned_binding: bool = False, "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) @@ -290,10 +296,15 @@ def check_query_only_session(self, shell: str, route: str) -> None: return ready_token = re.search(rb"SetUserVar=pebrel_editor_ready=([^\x07]+)\x07", session.output) self.assertIsNotNone(ready_token, session.output) - # Withdraw only the redraw binding this invocation installed, which is - # exactly the state a query-only integration advertises. + # 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( - "bind -r '\\e[46~' 2>/dev/null; bindkey -r '\\e[46~' 2>/dev/null; printf 'WITHDRAWN\\n'", + "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 @@ -379,13 +390,14 @@ def check_redraw_keymap_switch(self, route: str) -> None: # 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, ) - token = re.search(rb"SetUserVar=pebrel_editor_redraw=([^\x07]+)\x07", session.output) - self.assertIsNone(token, session.output) - self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", 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") @@ -409,13 +421,14 @@ def check_redraw_foreign_keymap_macro(self, shell: str, route: str) -> None: 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, ) - token = re.search(rb"SetUserVar=pebrel_editor_redraw=([^\x07]+)\x07", session.output) - self.assertIsNone(token, session.output) - self.assertIn(b"SetUserVar=pebrel_editor_redraw=\x07", 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") @@ -432,6 +445,37 @@ def test_ssh_bash_redraw_macro_in_the_vi_command_keymap_revokes(self) -> None: 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") + 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") From a3833cb95dbe6dc891e388389dce0fccc6cfbc40 Mon Sep 17 00:00:00 2001 From: zher52 Date: Mon, 16 Nov 2026 09:36:45 +0800 Subject: [PATCH 18/20] Settle the flaky PTY and resize windows behind the native CI failures - ShellSession.wait attributes each read window exactly up to its sentinel and carries the remainder into the next window; a read block that coalesced a command's sentinel with the following prompt's precmd markers could swallow the editor-ready marker into the previous command's output, which failed the zsh rebind revocation test on loaded macOS runners. - application_drag_stays_with_the_original_pane advances past the resize debounce gates before reading expectations or firing gestures; the pixel-driven grid resize could land between the read and the drag and encode one column past view.cols. - check_redraw_vi_mode_plain waits for the rendered newline it asserts. --- .../view/pointer/tests/application_mouse.rs | 9 +++++++ scripts/tests/test_completion_editor.py | 2 +- scripts/tests/test_shell_integration.py | 24 ++++++++++++------- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/nebula_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs b/nebula_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs index b87b80df4..254173f2e 100644 --- a/nebula_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs +++ b/nebula_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs @@ -236,6 +236,15 @@ 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/scripts/tests/test_completion_editor.py b/scripts/tests/test_completion_editor.py index c0811ac94..9744ad3f1 100644 --- a/scripts/tests/test_completion_editor.py +++ b/scripts/tests/test_completion_editor.py @@ -466,7 +466,7 @@ def check_redraw_vi_mode_plain(self, shell: str, route: str) -> None: os.write(session.master, b"\x1b[46~") time.sleep(0.4) os.write(session.master, b"\n") - output = session.wait(b"LINE:original") + output = session.wait(b"LINE:original\r\n") self.assertIn(b"LINE:original\r\n", output) self.assertNotIn(b"originaL", session.output) diff --git a/scripts/tests/test_shell_integration.py b/scripts/tests/test_shell_integration.py index b7445fad5..680670290 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") From f093a2344869ecd96bfc5b9973eb8fd9a2adee9d Mon Sep 17 00:00:00 2001 From: zher52 Date: Mon, 16 Nov 2026 10:03:58 +0800 Subject: [PATCH 19/20] Break the settle chain the way stable rustfmt formats it --- .../terminal/view/pointer/tests/application_mouse.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nebula_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs b/nebula_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs index 254173f2e..0b758081e 100644 --- a/nebula_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs +++ b/nebula_app/src/gpui_shell/terminal/view/pointer/tests/application_mouse.rs @@ -240,9 +240,8 @@ fn application_drag_stays_with_the_original_pane(cx: &mut TestAppContext) { // 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, - ); + 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)] { From 79001f6a9db79085527a0f893c7d79f5822c16a2 Mon Sep 17 00:00:00 2001 From: zher52 Date: Tue, 17 Nov 2026 09:46:13 +0800 Subject: [PATCH 20/20] Anchor pointer harness chords on editor turn boundaries The macos-26-intel CI failure (Missing SetUserVar=pebrel_editor=) was a harness turn overlap, not an editor flake: the snapshot chord landed inside the previous chord's render burst, PSReadLine tore the ESC prefix into a standalone Escape plus literal tail keys (line reverted, buffer littered with ; / [ / ~), and the handler never ran. A byte-level trace of a failing run pinned the overlap (304 ms of zero output between two chord writes), and a 4-way parallel stress loop reproduced the signature in 23/40 runs. The harness now waits for the editor's first reaction byte after each write and drains the burst before the next chord, and answers cursor probes on a 20 ms poll instead of 100 ms. Assertions are unchanged; the same stress shows 0/40 tear failures afterwards. Evidence and the rejected alternatives are recorded in architecture/notes/pebrel_terminal/tty/2026-11-17-pointer-chord-turn-serialization.md. --- ...-11-17-pointer-chord-turn-serialization.md | 87 +++++++++++++++++++ scripts/tests/test_powershell_pointer.py | 20 ++++- 2 files changed, 104 insertions(+), 3 deletions(-) create mode 100644 architecture/notes/pebrel_terminal/tty/2026-11-17-pointer-chord-turn-serialization.md 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/scripts/tests/test_powershell_pointer.py b/scripts/tests/test_powershell_pointer.py index f0304969b..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) @@ -117,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~") @@ -126,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"))