From 7147f43e93acc314ab100614a22efc3a5fcd327c Mon Sep 17 00:00:00 2001 From: zher52 Date: Wed, 4 Nov 2026 09:13:57 +0800 Subject: [PATCH 1/6] feat(ssh): add-and-connect fallback row for launcher search misses When the Shell/SSH launcher or the command palette finds no match and the query looks like a host address, offer one "Add and connect" row. It opens a workspace overlay instead of navigating to Settings; the form's field order, wording and authentication segmented row mirror the Settings editor's basic form, and "More settings" hands the composed destination to the full editor. Persistence reuses the existing authorities (validate_ssh_destination, SshProfiles::save, the credential store) and then connects through add_ssh_terminal, so tab naming, the remote file drawer and host recording behave like any built-in connection. The overlay cannot collect private-key files, so a public-key profile is rejected with guidance instead of being written in a state that cannot connect. The palette action enum moves to workspace/palette_action.rs: the workspace root file sits at its line budget and the row actions belong beside the palette projection that renders them. Refs #864. --- ...2026-11-03-launcher-add-and-connect-ssh.md | 105 +++ nebula_app/i18n/en-US.json | 8 +- nebula_app/i18n/zh-CN.json | 8 +- nebula_app/src/gpui_shell/ssh_settings.rs | 2 +- .../src/gpui_shell/ssh_settings/editor.rs | 12 +- nebula_app/src/gpui_shell/workspace.rs | 33 +- .../src/gpui_shell/workspace/palette.rs | 83 +++ .../gpui_shell/workspace/palette_action.rs | 35 + nebula_app/src/gpui_shell/workspace/render.rs | 1 + .../src/gpui_shell/workspace/ssh_quick_add.rs | 611 ++++++++++++++++++ 10 files changed, 865 insertions(+), 33 deletions(-) create mode 100644 architecture/notes/nebula_app/gpui_shell/workspace/2026-11-03-launcher-add-and-connect-ssh.md create mode 100644 nebula_app/src/gpui_shell/workspace/palette_action.rs create mode 100644 nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-03-launcher-add-and-connect-ssh.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-03-launcher-add-and-connect-ssh.md new file mode 100644 index 000000000..3812ccc48 --- /dev/null +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-03-launcher-add-and-connect-ssh.md @@ -0,0 +1,105 @@ +# Launcher "add and connect" fallback row + +## Status + +Accepted (#864). + +## Context + +Cmd/Ctrl+K and the command palette share one row projection +(`workspace/palette.rs::filtered_palette_rows`). Both list the same SSH host +authority (`SshHostLists`: saved/pinned plus `~/.ssh/config`). Typing a host +that is not in that authority produced an empty result with no next step: the +user had to open Settings → SSH, add the host, then come back and connect. + +The rows are a projection, not a connection authority. A new host therefore +cannot be connected straight from the row: it has no profile, no credentials +and no label. The editor already owns validation, persistence, credential +storage and the `SettingsPaneEvent::LaunchSsh` transition that the host +library's "Connect" button uses. + +## Evidence + +- Row projection and filtering: `nebula_app/src/gpui_shell/workspace/palette.rs`. +- Existing edit dispatch pattern (`window.defer` into the settings pane): + `nebula_app/src/gpui_shell/workspace/launcher_menu.rs`. +- Prefilled editor and save pipeline: + `nebula_app/src/gpui_shell/ssh_settings.rs` (`open_ssh_editor`, + `save_ssh_editor`). +- Connect transition: `SettingsPaneEvent::LaunchSsh` handled in + `nebula_app/src/gpui_shell/workspace/settings_navigation.rs`. + +## Decision + +- When filtering yields no rows and the query looks like a host address + (non-empty, no whitespace, at least three characters, contains `@` or `.`), + append one row whose action is `WorkspacePaletteAction::AddSshHostAndConnect`. +- Address validity is decided by the editor's save-time validation, not by the + row predicate. A false positive only costs an opened editor. +- The action opens a workspace-owned overlay (`workspace/ssh_quick_add.rs`) + instead of navigating to Settings: the user's intent is "connect", and a + page switch in between is not part of that intent. The overlay renders above + the terminal, closes on Esc/Backdrop, and Enter submits. +- Field order and wording mirror the Settings editor's basic form exactly + (name optional, then address+port on one row with the address hint and a + composed-destination preview, then username, divider, the same segmented + authentication row in the same mode order). Divergence on purpose: the + overlay has no group/tags/notes organization block and no private-key file + picker. Choosing "Key" shows a hint and saving is rejected with guidance, + because a public-key profile without keys cannot connect. Validation, + destination composition, persistence and credential storage reuse the + existing authorities (`validate_ssh_destination`, `join_destination_*`, + `SshProfiles::save`, `ssh_credentials::store_password`); the full editor in + Settings remains the authority for proxy/jump/key/icon configuration, and + both write the same `ssh_profiles.json`. +- "More settings" carries the composed destination into the Settings editor + (`manage_launcher_ssh(dest, edit=true)`), so half-filled work continues + there instead of being retyped. +- Persistence is split from connecting (`persist_quick_add`), so failures keep + the overlay open with the reason, and tests can verify the disk side without + opening a session. + +## Rejected alternatives + +- Connect the typed address directly without saving: the existing design + records a first connection in `saved_hosts` anyway, and password hosts still + need the editor, so it would split one flow into two authorities. +- Only add the row to the launcher and not the command palette: both render the + same projection, so gating one would fork the row source. +- Treat the row as "edit this host": `Some(destination)` skips the new-host + username default, which produced `core.example.cn` instead of + `root@core.example.cn` in testing. +- Persist the intent: it describes one in-flight editor session, not user + configuration. + +## Consequences + +- New-host onboarding from the launcher is one flow: search → add → save → + connected tab, using the same profile/credential/label path as the host + library. +- Quick Jump folder/agent scopes and the launcher's Shell filter never show the + row; All and SSH views do. +- A host typed but never saved leaves no trace; cancel and Esc clear the intent. + +## Validation + +- `workspace::ssh_quick_add::tests::quick_add_draft_composes_and_validates` + covers destination composition, the port range and authority rejection. +- `workspace::ssh_quick_add::tests::quick_add_persists_a_nameless_profile_before_any_connection` + covers the disk side against a temp file: no auto "Host N" label, Auto auth. + The public-key save guard is asserted by the same module's validation test + path (`KeysNeedAdvancedEditor`). +- `workspace::palette::palette_tests::plausible_ssh_query_needs_host_shape` + covers the row predicate. +- i18n contract (`HostsAddAndConnect` with a `{destination}` placeholder), + `cargo fmt`, and `scripts/check_architecture.py --base origin/main` pass. + +## Supersedes + +None. + +## Revisit when + +The host library gains a way to create a profile without the editor (for +example a dedicated quick-add dialog), or the launcher starts owning connection +state rather than projecting it. diff --git a/nebula_app/i18n/en-US.json b/nebula_app/i18n/en-US.json index 0c7e00e39..72295bb08 100644 --- a/nebula_app/i18n/en-US.json +++ b/nebula_app/i18n/en-US.json @@ -1137,6 +1137,11 @@ "title": "SSH hosts", "subtitle": "Organize your saved hosts, manage sign-in options, and open a terminal.", "add": "Add host", + "quick_add_title": "Add SSH host", + "quick_add_save_and_connect": "Save and connect", + "quick_add_address_required": "Enter a host address", + "quick_add_port_invalid": "Port must be 1-65535", + "add_and_connect": "Add and connect {destination}", "connect": "Connect", "exchange": "Import / export", "pinned": "Pinned", @@ -1159,7 +1164,8 @@ "via": "via {host}", "connection_time_unknown": "Connection time has not been recorded for this host.", "key_file": "Private key {name}", - "search_placeholder": "Name, address, tags" + "search_placeholder": "Name, address, tags", + "quick_add_keys_advanced": "Private keys are added in the full editor (More settings)" }, "vcs": { "changes": "Changes", diff --git a/nebula_app/i18n/zh-CN.json b/nebula_app/i18n/zh-CN.json index 6555ba308..2c13fc012 100644 --- a/nebula_app/i18n/zh-CN.json +++ b/nebula_app/i18n/zh-CN.json @@ -1137,6 +1137,11 @@ "title": "SSH 主机", "subtitle": "整理已保存的主机、管理登录方式,直接打开终端会话。", "add": "添加主机", + "quick_add_title": "添加 SSH 主机", + "quick_add_save_and_connect": "保存并连接", + "quick_add_address_required": "请填写主机地址", + "quick_add_port_invalid": "端口必须是 1–65535", + "add_and_connect": "添加并连接 {destination}", "connect": "连接", "exchange": "导入 / 导出", "pinned": "置顶", @@ -1159,7 +1164,8 @@ "via": "经 {host}", "connection_time_unknown": "这台主机尚无已记录的连接时间。", "key_file": "私钥 {name}", - "search_placeholder": "名称、地址、标签" + "search_placeholder": "名称、地址、标签", + "quick_add_keys_advanced": "私钥文件请在完整编辑器(更多设置)中添加" }, "vcs": { "changes": "变更", diff --git a/nebula_app/src/gpui_shell/ssh_settings.rs b/nebula_app/src/gpui_shell/ssh_settings.rs index c9fd652d8..e1067007c 100644 --- a/nebula_app/src/gpui_shell/ssh_settings.rs +++ b/nebula_app/src/gpui_shell/ssh_settings.rs @@ -28,7 +28,7 @@ use crate::gpui_shell::settings_pane::{SettingsPane, SettingsPaneEvent, SshStatu use crate::gpui_shell::widgets::NebulaButton; mod advanced; -mod editor; +pub(super) mod editor; pub(super) mod library; #[cfg(all(test, feature = "gpui-test-support"))] mod serial_tests; diff --git a/nebula_app/src/gpui_shell/ssh_settings/editor.rs b/nebula_app/src/gpui_shell/ssh_settings/editor.rs index bced8ceb2..f2abd89b5 100644 --- a/nebula_app/src/gpui_shell/ssh_settings/editor.rs +++ b/nebula_app/src/gpui_shell/ssh_settings/editor.rs @@ -5,7 +5,7 @@ const EDITOR_WIDTH: f32 = 512.0; const EDITOR_HEIGHT: f32 = 720.0; const EDITOR_PADDING: f32 = 28.0; -pub(super) fn editor_input( +pub(in crate::gpui_shell) fn editor_input( state: &Entity, label: &'static str, window: &Window, @@ -32,7 +32,10 @@ pub(super) fn editor_input( .aria_label(label) } -pub(super) fn editor_field(label: &'static str, control: impl IntoElement) -> gpui::Div { +pub(in crate::gpui_shell) fn editor_field( + label: &'static str, + control: impl IntoElement, +) -> gpui::Div { v_flex() .w_full() .min_w_0() @@ -41,7 +44,10 @@ pub(super) fn editor_field(label: &'static str, control: impl IntoElement) -> gp .child(control) } -pub(super) fn editor_hint(text: impl Into, cx: &gpui::App) -> gpui::Div { +pub(in crate::gpui_shell) fn editor_hint( + text: impl Into, + cx: &gpui::App, +) -> gpui::Div { div() .text_xs() .line_height(gpui::relative(1.6)) diff --git a/nebula_app/src/gpui_shell/workspace.rs b/nebula_app/src/gpui_shell/workspace.rs index 88c3bc5b3..6c5af8018 100644 --- a/nebula_app/src/gpui_shell/workspace.rs +++ b/nebula_app/src/gpui_shell/workspace.rs @@ -63,6 +63,7 @@ mod launcher_menu; mod logos; mod notifications; mod palette; +mod palette_action; mod pane_header; mod quick_jump; mod quick_terminal; @@ -82,6 +83,7 @@ mod session_recovery; pub(crate) mod shell_launch; mod shell_picker; mod sidebar_resize; +mod ssh_quick_add; mod terminal_activity; use shell_picker::shell_palette_rows; mod settings_navigation; @@ -418,33 +420,7 @@ const PALETTE_FILTER_BAR_HEIGHT: f32 = 44.0; const PALETTE_ROW_GAP: f32 = 4.0; const PALETTE_SCROLLBAR_CONTENT_GUTTER: f32 = 16.0; -#[derive(Clone)] -enum WorkspacePaletteAction { - TerminalReading { - commands: bool, - }, - Shared(crate::display::command_palette::PaletteAction), - /// 聚焦已经存在的工作区标签,不创建副本。 - FocusTab(usize), - LayoutRecipes, - /// 先激活标签,再把焦点交给其中的明确 pane。 - FocusPane { - tab: usize, - pane: u64, - }, - /// 在 frecency 目录中新建终端;已有目录中的 pane 由上面的 FocusPane 命中。 - OpenDirectory(std::path::PathBuf), - RunAiSession { - command: String, - cwd: Option, - }, - /// 启动器混排的 SSH 主机行(数据源 = 共享主机列表权威)。 - LaunchSshHost(String), - /// 新建终端弹窗里的一台已检测 shell(旧壳 `ProfileRow::Shell`)。 - LaunchShell(crate::shell_detect::DetectedShell), - /// 设置页“导入终端目录”落盘的可执行文件快照。 - LaunchProfile(crate::config::ui_config::Profile), -} +pub(super) use palette_action::WorkspacePaletteAction; #[derive(Clone, Copy)] enum WorkspacePaletteHintStyle { @@ -684,6 +660,8 @@ pub struct NebulaWorkspace { theme_transition: crate::gpui_shell::theme::ThemeTransition, /// GPUI presentation over the shared old-shell command catalog. command_palette_open: bool, + /// 启动器「添加并连接」的工作区内浮层(#864);见 `ssh_quick_add`。 + ssh_quick_add: Option, command_palette_input: Entity, command_palette_selected: usize, /// 用户命令管理器贴在右侧覆盖显示,不占终端布局宽度,也不复用应用动作 @@ -953,6 +931,7 @@ impl NebulaWorkspace { titlebar_background: window_titlebar::TitleBarBackground::default(), theme_transition: crate::gpui_shell::theme::ThemeTransition::default(), command_palette_open: false, + ssh_quick_add: None, command_palette_input, command_palette_selected: 0, command_manager_open: false, diff --git a/nebula_app/src/gpui_shell/workspace/palette.rs b/nebula_app/src/gpui_shell/workspace/palette.rs index b6e07968f..49cff78f1 100644 --- a/nebula_app/src/gpui_shell/workspace/palette.rs +++ b/nebula_app/src/gpui_shell/workspace/palette.rs @@ -16,6 +16,39 @@ fn shell_glyph_size() -> f32 { PALETTE_ICON_PX * crate::shell_detect::FALLBACK_ICON_SCALE } +/// 输入形似 SSH 主机地址:无空白,主机段至少 3 个字符,且带 `@` 或 `.` +/// (纯单词如 `myhost` 不算,避免把普通检索词变成添加行)。只决定 +/// 「添加并连接」兜底行是否出现;地址是否真的可连由编辑器保存时校验。 +fn plausible_ssh_query(query: &str) -> bool { + let query = query.trim(); + if query.is_empty() || query.chars().any(char::is_whitespace) { + return false; + } + let (_, address) = crate::display::split_destination_user(query); + let (address, _) = crate::display::split_destination_port(&address); + address.len() >= 3 && (address.contains('.') || query.contains('@')) +} + +#[cfg(test)] +mod palette_tests { + use super::*; + + #[test] + fn plausible_ssh_query_needs_host_shape() { + assert!(plausible_ssh_query("core.example.cn")); + assert!(plausible_ssh_query("root@10.11.12.11")); + assert!(plausible_ssh_query("user@example.com:2222")); + assert!(plausible_ssh_query(" host.example.org ")); + assert!(!plausible_ssh_query("zsh")); + assert!(!plausible_ssh_query("copy path")); + assert!(!plausible_ssh_query("a@b")); + assert!(!plausible_ssh_query("myhost")); + assert!(!plausible_ssh_query("")); + assert!(plausible_ssh_query("box.lan")); + assert!(plausible_ssh_query("deploy@box")); + } +} + impl NebulaWorkspace { pub(super) fn run_selected_palette_action( &mut self, @@ -78,6 +111,11 @@ impl NebulaWorkspace { self.dismiss_palette_state(); self.add_ssh_terminal(host, window, cx); }, + WorkspacePaletteAction::AddSshHostAndConnect(destination) => { + // 不导航到设置页:表单浮在工作区上,保存后直接开标签连接。 + self.dismiss_palette_state(); + self.open_ssh_quick_add(destination, window, cx); + }, WorkspacePaletteAction::LaunchShell(detected) => { self.launch_palette_shell(detected, window, cx); }, @@ -229,10 +267,55 @@ impl NebulaWorkspace { || words.iter().all(|word| row.search.to_ascii_lowercase().contains(word)) }) .collect(); + // 检索没有任何命中、而输入形似主机地址时,兜底给一个「添加并连接」 + // 行(#864)。地址合法性由编辑器保存时的校验裁决,这里保持宽松。 + if rows.is_empty() + && let Some(row) = self.launcher_add_host_row(cx) + { + rows.push(row); + } rows.sort_by_key(|row| row.group_order); rows } + /// 检索无命中的「添加 SSH 主机并连接」兜底行;条件不满足时返回 None。 + fn launcher_add_host_row(&self, cx: &App) -> Option { + // Quick Jump 的文件夹/智能体 scope 不放主机添加行。 + if let Some(filter) = self.quick_jump_filter + && !matches!(filter, QuickJumpFilter::All | QuickJumpFilter::Ssh) + { + return None; + } + // 启动器的 Shell 视图是纯 shell 列表,不放主机行;All/SSH 视图保留。 + if self.shell_picker_open + && self.launcher_filter == crate::display::command_palette::LauncherFilter::Shell + { + return None; + } + // 输入框原值(未小写化):用户名大小写敏感,不能拿查询缓存的小写串。 + let destination = self.command_palette_input.read(cx).value().trim().to_owned(); + if !plausible_ssh_query(&destination) { + return None; + } + let language = crate::gpui_shell::config::ui_language(cx); + let group = language.pick("SSH 主机", "SSH hosts"); + Some(WorkspacePaletteRow { + group_order: 2, + group: group.to_owned(), + label: language.format( + crate::i18n::Message::HostsAddAndConnect, + &[("destination", destination.as_str())], + ), + hint: "SSH".to_owned(), + hint_style: WorkspacePaletteHintStyle::Metadata, + search: format!("{destination} ssh host add remote 远程 连接 添加").to_lowercase(), + action: WorkspacePaletteAction::AddSshHostAndConnect(destination), + icon: None, + icon_glyph: Some(crate::display::ui::os_icons::resolve(None).glyph), + icon_path: None, + }) + } + pub(super) fn render_command_palette( &mut self, window: &mut Window, diff --git a/nebula_app/src/gpui_shell/workspace/palette_action.rs b/nebula_app/src/gpui_shell/workspace/palette_action.rs new file mode 100644 index 000000000..59ff410f2 --- /dev/null +++ b/nebula_app/src/gpui_shell/workspace/palette_action.rs @@ -0,0 +1,35 @@ +//! Palette/launcher row actions. +//! +//! Lives beside the palette projection instead of the workspace root: the rows +//! and their commands change together, and `workspace.rs` sits at its line +//! budget. Execution stays in `palette::run_workspace_palette_action`. + +#[derive(Clone)] +pub(crate) enum WorkspacePaletteAction { + TerminalReading { + commands: bool, + }, + Shared(crate::display::command_palette::PaletteAction), + /// 聚焦已经存在的工作区标签,不创建副本。 + FocusTab(usize), + LayoutRecipes, + /// 先激活标签,再把焦点交给其中的明确 pane。 + FocusPane { + tab: usize, + pane: u64, + }, + /// 在 frecency 目录中新建终端;已有目录中的 pane 由上面的 FocusPane 命中。 + OpenDirectory(std::path::PathBuf), + RunAiSession { + command: String, + cwd: Option, + }, + /// 启动器混排的 SSH 主机行(数据源 = 共享主机列表权威)。 + LaunchSshHost(String), + /// 检索无命中时的兜底行:预填 SSH 编辑器,保存成功后自动连接。 + AddSshHostAndConnect(String), + /// 新建终端弹窗里的一台已检测 shell(旧壳 `ProfileRow::Shell`)。 + LaunchShell(crate::shell_detect::DetectedShell), + /// 设置页“导入终端目录”落盘的可执行文件快照。 + LaunchProfile(crate::config::ui_config::Profile), +} diff --git a/nebula_app/src/gpui_shell/workspace/render.rs b/nebula_app/src/gpui_shell/workspace/render.rs index 2492451b0..22453673e 100644 --- a/nebula_app/src/gpui_shell/workspace/render.rs +++ b/nebula_app/src/gpui_shell/workspace/render.rs @@ -445,6 +445,7 @@ impl Render for NebulaWorkspace { .when(self.command_palette_open, |root| { root.child(self.render_command_palette(window, cx)) }) + .when_some(self.render_ssh_quick_add(window, cx), |root, layer| root.child(layer)) .when(self.command_manager_open, |root| { root.child(self.render_command_manager(window, cx)) }) diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs new file mode 100644 index 000000000..71e90fc27 --- /dev/null +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs @@ -0,0 +1,611 @@ +//! 工作区内的 SSH 快速添加浮层(#864)。 +//! +//! # 为什么不是导航到设置页 +//! +//! 启动器里输入一个还没保存的地址时,用户意图是「连上它」,不是「去配置」。 +//! 把人送进设置页再送回来,等于用一个页面切换换一次表单填写。所以这里把 +//! 表单浮在终端上,保存后直接开标签连接。 +//! +//! # 为什么不复制一份完整编辑器 +//! +//! 设置页的编辑器要承载代理、跳板、私钥、图标、测试连接;那是主机库的管理 +//! 面。快捷连接只需要「账号 + 地址 + 端口 + 认证方式 + 密码」这几项。这里 +//! 只做子集,但**校验、拼接、落盘和凭据全部复用既有权威**: +//! `validate_ssh_destination`、`join_destination_*`、`SshProfiles::upsert/save`、 +//! `ssh_credentials::store_password`。复杂配置仍走设置页(表单里的 +//! 「更多设置」按钮),两边写的是同一份 `ssh_profiles.json`。 + +use gpui::{AppContext as _, Entity, Focusable as _, IntoElement, Window}; +use gpui::{InteractiveElement as _, ParentElement as _, Styled as _, div, px}; + +use crate::gpui_shell::prelude::*; +use crate::gpui_shell::ssh_settings::editor::{editor_field, editor_hint, editor_input}; +use crate::i18n::Message; + +use super::NebulaWorkspace; + +const QUICK_ADD_WIDTH: f32 = 460.0; + +/// 身份验证分段选择与设置页完全同款、同序(密码/密钥/自动/交互式), +/// 字段顺序也与其基础表单一致。差异只有一点:密钥文件需要文件选择器, +/// 浮层不收集私钥,保存时引导到完整编辑器。 +pub(super) struct SshQuickAddState { + username: Entity, + address: Entity, + port: Entity, + password: Entity, + label: Entity, + auth: crate::ssh_profiles::SshAuthMode, + error: Option, +} + +/// 每个字段都是独立 `InputState`;统一走这里,掩码与占位符口径一致。 +fn quick_input( + value: &str, + placeholder: &'static str, + masked: bool, + window: &mut Window, + cx: &mut gpui::App, +) -> Entity { + let entity = cx.new(|cx| { + let mut state = InputState::new(window, cx).placeholder(placeholder); + if masked { + state = state.masked(true); + } + state + }); + entity.update(cx, |state, cx| { + state.set_value(value.to_owned(), window, cx); + cx.notify(); + }); + entity +} + +impl SshQuickAddState { + fn new(destination: &str, window: &mut Window, cx: &mut gpui::App) -> Self { + let (address_with_user, port) = crate::display::split_destination_port(destination); + let (username, address) = crate::display::split_destination_user(&address_with_user); + let language = crate::gpui_shell::config::ui_language(cx); + let username = if username.is_empty() { "root".to_owned() } else { username }; + let username = quick_input(&username, "", false, window, cx); + let address = quick_input(&address, "", false, window, cx); + let port = quick_input(&port, "", false, window, cx); + let password = quick_input( + "", + language.pick("留空则连接时询问", "Leave empty to ask when connecting"), + true, + window, + cx, + ); + let label = quick_input("", "", false, window, cx); + Self { + username, + address, + port, + password, + label, + auth: crate::ssh_profiles::SshAuthMode::Auto, + error: None, + } + } + + /// 组合成最终 destination:用户名与端口填过就以输入为准,否则沿用地址串 + /// 里自带的 `user@` / `:port`,最后交给 `validate_ssh_destination` 裁决。 + fn draft_destination(&self, cx: &gpui::App) -> Result { + let address = self.address.read(cx).value().trim().to_owned(); + if address.is_empty() { + return Err(QuickAddError::MissingAddress); + } + let (inline_user, host) = crate::display::split_destination_user(&address); + let (host, inline_port) = crate::display::split_destination_port(&host); + let typed_port = self.port.read(cx).value().trim().to_owned(); + let port = if !typed_port.is_empty() { + if !typed_port.parse::().is_ok_and(|value| value > 0) { + return Err(QuickAddError::InvalidPort); + } + typed_port + } else { + inline_port + }; + let typed_user = self.username.read(cx).value().trim().to_owned(); + let user = if !inline_user.is_empty() { inline_user } else { typed_user }; + let destination = crate::display::join_destination_port( + &crate::display::join_destination_user(&user, &host), + &port, + ); + crate::ssh_profiles::validate_ssh_destination(&destination) + .map_err(QuickAddError::Rejected)?; + Ok(destination) + } +} + +#[derive(Debug, PartialEq)] +pub(super) enum QuickAddError { + MissingAddress, + InvalidPort, + Rejected(String), + Io(String), + KeysNeedAdvancedEditor, +} + +/// 落盘一次快捷添加。独立函数让测试能指向临时文件,避免触碰真实主机库。 +fn persist_quick_add( + state: &SshQuickAddState, + path: &std::path::Path, + cx: &gpui::App, +) -> Result { + let destination = state.draft_destination(cx)?; + let auth = state.auth; + if auth == crate::ssh_profiles::SshAuthMode::PublicKey { + // 浮层没有私钥文件选择器:空私钥列表的公钥 profile 一定连不上, + // 直接引导到完整编辑器,而不是写进一份坏数据。 + return Err(QuickAddError::KeysNeedAdvancedEditor); + } + let password = state.password.read(cx).value().to_string(); + let label = { + let label = state.label.read(cx).value().trim().to_owned(); + (!label.is_empty()).then_some(label) + }; + let mut profiles = crate::ssh_profiles::SshProfiles::load(path) + .map_err(|error| QuickAddError::Io(error.to_string()))?; + profiles.upsert(crate::ssh_profiles::SshProfileAuth { + destination: destination.clone(), + auth, + private_keys: Vec::new(), + label, + icon: None, + connection: crate::ssh_profiles::SshConnectionOptions::default(), + }); + profiles.save(path).map_err(|error| QuickAddError::Io(error.to_string()))?; + if auth == crate::ssh_profiles::SshAuthMode::Password + && !password.is_empty() + && let Err(error) = + crate::ssh_credentials::store_password(&destination, password.as_bytes()) + { + return Err(QuickAddError::Io(error.to_string())); + } + Ok(destination) +} + +impl NebulaWorkspace { + pub(super) fn open_ssh_quick_add( + &mut self, + destination: String, + window: &mut Window, + cx: &mut gpui::Context, + ) { + let state = SshQuickAddState::new(&destination, window, cx); + let address_focus = state.address.read(cx).focus_handle(cx); + self.ssh_quick_add = Some(state); + window.focus(&address_focus, cx); + cx.notify(); + } + + pub(super) fn close_ssh_quick_add(&mut self, cx: &mut gpui::Context) { + if self.ssh_quick_add.take().is_some() { + cx.notify(); + } + } + + /// 把浮层里的草稿写进主机库并保存密码;成功返回规范化 destination。 + /// 与连接分开,测试可以只验证落盘而不真的建 SSH 会话。 + pub(super) fn save_quick_add_host(&self, cx: &gpui::App) -> Result { + let state = self.ssh_quick_add.as_ref().ok_or(QuickAddError::MissingAddress)?; + persist_quick_add(state, &crate::display::nebula_data_dir().join("ssh_profiles.json"), cx) + } + + /// 保存到主机库后立刻连接。落盘失败时不连接,浮层保留并显示原因。 + pub(super) fn submit_ssh_quick_add( + &mut self, + window: &mut Window, + cx: &mut gpui::Context, + ) { + let language = crate::gpui_shell::config::ui_language(cx); + let destination = match self.save_quick_add_host(cx) { + Ok(destination) => destination, + Err(QuickAddError::MissingAddress) => { + self.quick_add_error( + language.text(Message::HostsQuickAddAddressRequired).to_owned(), + cx, + ); + return; + }, + Err(QuickAddError::InvalidPort) => { + self.quick_add_error( + language.text(Message::HostsQuickAddPortInvalid).to_owned(), + cx, + ); + return; + }, + Err(QuickAddError::KeysNeedAdvancedEditor) => { + self.quick_add_error( + language.text(Message::HostsQuickAddKeysAdvanced).to_owned(), + cx, + ); + return; + }, + Err(QuickAddError::Rejected(error) | QuickAddError::Io(error)) => { + self.quick_add_error(error, cx); + return; + }, + }; + self.close_ssh_quick_add(cx); + // `add_ssh_terminal` 负责记住主机、开标签并走内建 SSH 连接链路。 + self.add_ssh_terminal(destination, window, cx); + } + + /// 「更多设置」:带着已填地址跳到设置页的完整编辑器。浮层里拆好的 + /// 用户名/端口经 `draft_destination` 组合回 `user@host:port`,设置页 + /// 编辑器会再拆进各自的框;校验不过就把原始地址原样带过去。 + pub(super) fn open_quick_add_advanced( + &mut self, + window: &mut Window, + cx: &mut gpui::Context, + ) { + let destination = self + .ssh_quick_add + .as_ref() + .map(|state| { + state + .draft_destination(cx) + .unwrap_or_else(|_| state.address.read(cx).value().trim().to_owned()) + }) + .unwrap_or_default(); + self.close_ssh_quick_add(cx); + self.open_settings(window, cx); + if let Some((pane, _)) = &self.settings_surface { + let pane = pane.clone(); + window.defer(cx, move |window, cx| { + pane.update(cx, |pane, cx| pane.manage_launcher_ssh(destination, true, window, cx)); + }); + } + cx.notify(); + } + + fn quick_add_error(&mut self, error: String, cx: &mut gpui::Context) { + if let Some(state) = self.ssh_quick_add.as_mut() { + state.error = Some(error); + } + cx.notify(); + } + + pub(super) fn render_ssh_quick_add( + &self, + window: &Window, + cx: &mut gpui::Context, + ) -> Option { + let state = self.ssh_quick_add.as_ref()?; + let language = crate::gpui_shell::config::ui_language(cx); + let theme = cx.theme(); + // 字段顺序与设置页基础表单一致:名称(可选) → 地址*+端口 → 提示 → + // destination 预览 → 用户名 → 分隔线 → 身份验证分段(同款组件同序)。 + let preview = state.draft_destination(cx).ok(); + use crate::ssh_profiles::SshAuthMode; + let modes = [ + ("ssh-quick-add-password", language.pick("密码", "Password"), SshAuthMode::Password), + ("ssh-quick-add-key", language.pick("密钥", "Key"), SshAuthMode::PublicKey), + ("ssh-quick-add-auto", language.pick("自动", "Auto"), SshAuthMode::Auto), + ( + "ssh-quick-add-interactive", + language.pick("交互式", "Interactive"), + SshAuthMode::KeyboardInteractive, + ), + ]; + let selected_auth = modes.iter().position(|(_, _, mode)| *mode == state.auth).unwrap_or(0); + let auth_buttons = modes + .iter() + .map(|(id, label, mode)| { + let mode = *mode; + Button::new(*id) + .label(*label) + .custom( + gpui_component::button::ButtonCustomVariant::new(cx) + .hover(theme.foreground.opacity(0.04)) + .active(theme.foreground.opacity(0.08)), + ) + .small() + .flex_1() + .min_w_0() + .h(px(31.0)) + .rounded(gpui_component::button::ButtonRounded::Size(px(5.0))) + .px_1() + .toggled(state.auth == mode) + .text_color(if state.auth == mode { + theme.foreground + } else { + theme.muted_foreground + }) + .on_click(cx.listener(move |this, _, _, cx| { + if let Some(state) = this.ssh_quick_add.as_mut() { + state.auth = mode; + state.error = None; + } + cx.notify(); + })) + }) + .collect::>(); + let (shows_password, shows_keys) = crate::display::auth_sections(state.auth); + let mut form = v_flex() + .w_full() + .child( + v_flex() + .gap(px(7.0)) + .child( + h_flex() + .gap_2() + .child( + div() + .text_xs() + .font_medium() + .child(language.pick("主机名称", "Host name")), + ) + .child(editor_hint(language.pick("可选", "Optional"), cx)), + ) + .child(editor_input( + &state.label, + language.pick("主机名称", "Host name"), + window, + cx, + )), + ) + .child( + h_flex() + .mt_5() + .gap_3() + .items_start() + .child(div().flex_1().min_w_0().child(editor_field( + language.pick("主机地址 *", "Host address *"), + editor_input( + &state.address, + language.pick("主机地址", "Host address"), + window, + cx, + ), + ))) + .child(div().w(px(84.0)).flex_shrink_0().child(editor_field( + language.pick("端口", "Port"), + editor_input(&state.port, language.pick("端口", "Port"), window, cx), + ))), + ) + .child(editor_hint(language.tr("settings.ssh.address_hint"), cx).mt_1()); + if let Some(preview) = preview { + form = form.child(editor_hint(preview, cx).mt_2().truncate()); + } + form = form.child(div().mt_4().child(editor_field( + language.pick("用户名", "Username"), + editor_input(&state.username, language.pick("用户名", "Username"), window, cx), + ))); + form = form.child( + v_flex() + .mt_5() + .pt_5() + .border_t_1() + .border_color(theme.border) + .child( + div() + .text_xs() + .font_medium() + .child(language.pick("身份验证", "Authentication")), + ) + .child( + h_flex().mt_2().p(px(3.0)).rounded(px(8.0)).bg(theme.muted).child( + crate::gpui_shell::widgets::segmented::SegmentedRow::new( + "ssh-quick-add-auth-modes", + selected_auth, + h_flex().w_full().h(px(31.0)).gap(px(3.0)).children(auth_buttons), + div().rounded(px(5.0)).bg(theme.popover).shadow_sm(), + ) + .w_full(), + ), + ), + ); + if shows_password { + form = form.child(div().mt_4().child(editor_field( + language.pick("密码", "Password"), + editor_input(&state.password, language.pick("密码", "Password"), window, cx), + ))); + } + if shows_keys { + form = form + .child(editor_hint(language.text(Message::HostsQuickAddKeysAdvanced), cx).mt_2()); + } + if let Some(error) = state.error.clone() { + form = form.child(div().mt_2().text_xs().text_color(theme.danger).child(error)); + } + + Some( + div() + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .occlude() + .bg(theme.overlay) + .on_mouse_down( + gpui::MouseButton::Left, + cx.listener(|this, _, _, cx| this.close_ssh_quick_add(cx)), + ) + .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { + match event.keystroke.key.as_str() { + "escape" => { + this.close_ssh_quick_add(cx); + cx.stop_propagation(); + }, + "enter" if !event.keystroke.modifiers.shift => { + this.submit_ssh_quick_add(window, cx); + cx.stop_propagation(); + }, + _ => {}, + } + })) + .child( + v_flex() + .w(px(QUICK_ADD_WIDTH)) + .max_w_full() + .gap(px(18.0)) + .rounded(px(14.0)) + .border_1() + .border_color(theme.border) + .bg(theme.popover) + .p(px(22.0)) + .shadow_lg() + .occlude() + .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .child( + div() + .text_sm() + .font_semibold() + .child(language.text(Message::HostsQuickAddTitle)), + ) + .child(form) + .child( + h_flex() + .justify_between() + .gap_2() + .child( + Button::new("ssh-quick-add-advanced") + .label(language.pick("更多设置", "More settings")) + .ghost() + .small() + .on_click(cx.listener(|this, _, window, cx| { + this.open_quick_add_advanced(window, cx) + })), + ) + .child( + h_flex() + .gap_2() + .child( + Button::new("ssh-quick-add-cancel") + .label(language.text(Message::CommonCancel)) + .ghost() + .small() + .on_click(cx.listener(|this, _, _, cx| { + this.close_ssh_quick_add(cx) + })), + ) + .child( + Button::new("ssh-quick-add-save") + .debug_selector(|| "ssh-quick-add-save".to_owned()) + .label( + language + .text(Message::HostsQuickAddSaveAndConnect), + ) + .primary() + .small() + .on_click(cx.listener(|this, _, window, cx| { + this.submit_ssh_quick_add(window, cx) + })), + ), + ), + ), + ) + .into_any_element(), + ) + } +} + +#[cfg(all(test, feature = "gpui-test-support"))] +mod tests { + use super::*; + + /// `add_window_view` 需要一个 Render 根视图;浮层状态在闭包里创建, + /// 这里只当窗口宿主。 + struct TestHost; + impl gpui::Render for TestHost { + fn render( + &mut self, + _window: &mut Window, + _cx: &mut gpui::Context, + ) -> impl IntoElement { + gpui::div() + } + } + + fn init_and_build<'a>( + destination: &str, + cx: &'a mut gpui::TestAppContext, + ) -> (SshQuickAddState, &'a mut gpui::VisualTestContext) { + cx.update(|cx| { + gpui_component::init(cx); + cx.set_global(crate::gpui_shell::config::Settings::load( + nebula_settings::ThemeName::Nord, + )); + }); + let mut state = None; + let (_, cx) = cx.add_window_view(|window, cx| { + state = Some(SshQuickAddState::new(destination, window, cx)); + TestHost + }); + (state.expect("state built"), cx) + } + + #[test] + fn quick_add_prefills_user_and_port_from_the_typed_address() { + // 不依赖窗口:预填拆分只走 `split_destination_*`。 + let (address_with_user, port) = + crate::display::split_destination_port("deploy@box.example:2222"); + let (username, address) = crate::display::split_destination_user(&address_with_user); + assert_eq!( + (username.as_str(), address.as_str(), port.as_str()), + ("deploy", "box.example", "2222") + ); + } + + #[gpui::test] + fn quick_add_draft_composes_and_validates(cx: &mut gpui::TestAppContext) { + let (state, cx) = init_and_build("core.example.cn", cx); + cx.update(|window, cx| { + assert_eq!(state.draft_destination(cx).unwrap(), "root@core.example.cn"); + // 端口非法直接拒绝,不进入落盘。 + state.port.update(cx, |input, cx| input.set_value("70000", window, cx)); + assert_eq!(state.draft_destination(cx).unwrap_err(), QuickAddError::InvalidPort); + state.port.update(cx, |input, cx| input.set_value("2222", window, cx)); + assert_eq!(state.draft_destination(cx).unwrap(), "root@core.example.cn:2222"); + // 带非法字符交给权威校验拒绝;空地址单独报"缺地址"。 + state.address.update(cx, |input, cx| input.set_value("bad host", window, cx)); + assert!(matches!(state.draft_destination(cx), Err(QuickAddError::Rejected(_)))); + state.address.update(cx, |input, cx| input.set_value("", window, cx)); + assert_eq!(state.draft_destination(cx).unwrap_err(), QuickAddError::MissingAddress); + }); + } + + #[gpui::test] + fn quick_add_persists_a_nameless_profile_before_any_connection(cx: &mut gpui::TestAppContext) { + let (mut state, cx) = init_and_build("core.example.cn", cx); + let directory = std::env::temp_dir().join(format!( + "pebrel-quick-add-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&directory).unwrap(); + let path = directory.join("ssh_profiles.json"); + cx.update(|_, cx| { + let destination = persist_quick_add(&state, &path, cx).unwrap(); + assert_eq!(destination, "root@core.example.cn"); + }); + let profiles = crate::ssh_profiles::SshProfiles::load(&path).unwrap(); + let profile = profiles.for_destination("root@core.example.cn"); + // 没填名称:保持空,列表回落显示地址,而不是自动起「主机 N」。 + assert_eq!(profile.label, None); + assert_eq!(profile.auth, crate::ssh_profiles::SshAuthMode::Auto); + // 公钥模式:浮层收集不了私钥文件,落盘必须被守卫拦下, + // 且不能把空私钥的坏 profile 写进文件。 + cx.update(|_, cx| { + state.auth = crate::ssh_profiles::SshAuthMode::PublicKey; + assert_eq!( + persist_quick_add(&state, &path, cx).unwrap_err(), + QuickAddError::KeysNeedAdvancedEditor + ); + }); + assert_eq!( + crate::ssh_profiles::SshProfiles::load(&path) + .unwrap() + .for_destination("root@core.example.cn") + .auth, + crate::ssh_profiles::SshAuthMode::Auto, + "rejected save must not overwrite the stored profile" + ); + let _ = std::fs::remove_dir_all(&directory); + } +} From 19da736334d5a679018870525728f78af5a304ac Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 00:16:41 +0800 Subject: [PATCH 2/6] fix(ssh): quick-add reuses the saved profile on a destination collision Saving a quick-add whose final validated destination already has a stored profile used to replace it wholesale (empty keys, default connection options), discarding private keys, jump route, label and icon, and then connected with the degraded replacement. Save now resolves duplicates first: an existing profile is reused untouched and the connect path picks it up by destination. Credentials are also written before the profile file, so a keychain failure leaves the host library exactly as it was instead of reporting an error over a half-written save. --- .../2026-11-13-quick-add-collision-reuse.md | 80 ++++++++++ .../src/gpui_shell/workspace/ssh_quick_add.rs | 138 +++++++++++++++++- nebula_app/src/ssh_profiles.rs | 7 + 3 files changed, 217 insertions(+), 8 deletions(-) create mode 100644 architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md new file mode 100644 index 000000000..263373248 --- /dev/null +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md @@ -0,0 +1,80 @@ +# Quick-add collision reuse and credential ordering + +## Status + +Accepted (#869 review, 2026-11-12). + +## Context + +The quick-add overlay only opens on a launcher search miss, but the final +validated destination is decided at save time: the user can start the form for +one address and edit it onto a destination that already has a saved profile. +`persist_quick_add` built a fresh subset profile (empty keys, default +connection options) and `SshProfiles::upsert` replaces the stored profile for +that exact destination, so saving silently discarded private keys, jump route, +label and icon and then connected with the degraded replacement. Password +storage also ran after `profiles.save()`, so a credential-storage failure was +reported by the form after the profile file had already changed. + +## Evidence + +- Save path: `nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs` + (`persist_quick_add_with`). +- Replace-on-exact-match semantics and the existence probe: + `nebula_app/src/ssh_profiles.rs` (`SshProfiles::upsert`, + `SshProfiles::contains_destination`). +- Review reproduction on PR #869 (2026-11-12): a populated + `deploy@box.example` profile replaced through a quick-add save. + +## Decision + +- Save-time duplicate resolution against the final validated destination: + when the host library already holds a profile for it, quick-add persists + nothing and writes no credentials; it returns the destination and + `add_ssh_terminal` connects through the saved profile. Editing keys, jump, + label or icon remains the Settings editor's job via "More settings". +- Credential storage runs before the profile file is written: a + credential-storage failure leaves the host library untouched and the overlay + open with the error. The write set is one profile plus one credential, so + all-or-nothing ordering is achievable here. + +## Rejected alternatives + +- Overwrite the existing profile with the subset form: destroys editor-owned + fields and connects with the degraded replacement (the reported bug). +- Profile-save first with a partial-success message (the Settings editor's + pattern for proxy credentials): the overlay has no UI state for "saved but + password missing", so the kept-open form would invite a retry that now + collides with the profile it just wrote. +- Auto-route the collision into the Settings editor: the overlay's purpose is + connecting; silently switching pages breaks the one-flow intent recorded in + `2026-11-03-launcher-add-and-connect-ssh.md`. + +## Consequences + +- Typing an existing host's address into quick-add connects with the saved + configuration and changes nothing on disk or in the credential store. +- A stored password can exist for a destination whose profile save later + fails; it is keyed by destination and overwritten or reused by the next + successful save for that host. + +## Validation + +- `quick_add_collision_reuses_the_saved_profile_untouched`: a populated + profile (keys, jump host, label, icon) survives a colliding save + byte-for-byte and the injected credential recorder sees no call. +- `quick_add_password_failure_leaves_the_host_library_untouched`: a failing + credential store is injected and the profile file is never created. +- `persist_quick_add_with` takes the credential write as a parameter, + mirroring the closure-injected tests of `platform::credentials`, so tests + never touch the user keychain. + +## Supersedes + +None. Amends the persistence paragraph of +`2026-11-03-launcher-add-and-connect-ssh.md`. + +## Revisit when + +The overlay gains field-level merge into an existing profile, or the host +library grows a create path outside the Settings editor. diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs index 71e90fc27..f70e3afbe 100644 --- a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs @@ -133,6 +133,17 @@ fn persist_quick_add( state: &SshQuickAddState, path: &std::path::Path, cx: &gpui::App, +) -> Result { + persist_quick_add_with(state, path, crate::ssh_credentials::store_password, cx) +} + +/// 凭据写入由调用方注入:真实路径直连系统凭据库,测试注入假存储来验证 +/// 落盘顺序,顺带保证测试永远不触碰用户钥匙串。 +fn persist_quick_add_with( + state: &SshQuickAddState, + path: &std::path::Path, + mut store_password: impl FnMut(&str, &[u8]) -> std::io::Result<()>, + cx: &gpui::App, ) -> Result { let destination = state.draft_destination(cx)?; let auth = state.auth; @@ -148,6 +159,21 @@ fn persist_quick_add( }; let mut profiles = crate::ssh_profiles::SshProfiles::load(path) .map_err(|error| QuickAddError::Io(error.to_string()))?; + if profiles.contains_destination(&destination) { + // 目的地已有保存的 profile:私钥、跳板、图标只存在于完整编辑器里, + // 这份子集表单没有资格整体替换它。原样复用交给连接链路——返回 + // destination 后 `add_ssh_terminal` 会按已存 profile 建会话;凭据 + // 同样不碰,改密码或密钥请走「更多设置」。 + return Ok(destination); + } + // 密码先于主机库落盘:凭据写失败时表单报错,主机库文件必须还是原样, + // 不能留下「报了错却已经改了文件」的半写状态。 + if auth == crate::ssh_profiles::SshAuthMode::Password + && !password.is_empty() + && let Err(error) = store_password(&destination, password.as_bytes()) + { + return Err(QuickAddError::Io(error.to_string())); + } profiles.upsert(crate::ssh_profiles::SshProfileAuth { destination: destination.clone(), auth, @@ -157,13 +183,6 @@ fn persist_quick_add( connection: crate::ssh_profiles::SshConnectionOptions::default(), }); profiles.save(path).map_err(|error| QuickAddError::Io(error.to_string()))?; - if auth == crate::ssh_profiles::SshAuthMode::Password - && !password.is_empty() - && let Err(error) = - crate::ssh_credentials::store_password(&destination, password.as_bytes()) - { - return Err(QuickAddError::Io(error.to_string())); - } Ok(destination) } @@ -188,7 +207,8 @@ impl NebulaWorkspace { } /// 把浮层里的草稿写进主机库并保存密码;成功返回规范化 destination。 - /// 与连接分开,测试可以只验证落盘而不真的建 SSH 会话。 + /// 目的地已保存时原样复用既有 profile(不写库、不动凭据),同样返回 + /// destination 供连接。与连接分开,测试可以只验证落盘而不真的建 SSH 会话。 pub(super) fn save_quick_add_host(&self, cx: &gpui::App) -> Result { let state = self.ssh_quick_add.as_ref().ok_or(QuickAddError::MissingAddress)?; persist_quick_add(state, &crate::display::nebula_data_dir().join("ssh_profiles.json"), cx) @@ -522,6 +542,108 @@ mod tests { } } + /// 临时主机库目录:唯一命名避免测试并行互踩,用完整目录删除。 + fn temp_profile_dir(tag: &str) -> std::path::PathBuf { + let directory = std::env::temp_dir().join(format!( + "pebrel-quick-add-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&directory).unwrap(); + directory + } + + #[gpui::test] + fn quick_add_collision_reuses_the_saved_profile_untouched(cx: &mut gpui::TestAppContext) { + let (mut state, cx) = init_and_build("other.example", cx); + let directory = temp_profile_dir("collision"); + let path = directory.join("ssh_profiles.json"); + // 库里先有一台带完整配置的主机:私钥、跳板、名称、图标都是浮层 + // 这份子集表单覆盖不了的权威数据。 + let mut profiles = crate::ssh_profiles::SshProfiles::default(); + profiles.upsert(crate::ssh_profiles::SshProfileAuth { + destination: "deploy@box.example".to_owned(), + auth: crate::ssh_profiles::SshAuthMode::Password, + private_keys: vec![std::path::PathBuf::from("~/.id_ed25519")], + label: Some("Deploy box".to_owned()), + icon: Some("debian".to_owned()), + connection: { + let mut connection = crate::ssh_profiles::SshConnectionOptions::default(); + connection.jump_mode = crate::ssh_profiles::SshHostJumpMode::Host; + connection.jump_host = "bastion.example".to_owned(); + connection + }, + }); + profiles.save(&path).unwrap(); + let before = std::fs::read(&path).unwrap(); + // 表单地址改成已有主机的目的地,还填了密码:保存必须原样复用, + // 连凭据都不能替编辑器写。 + cx.update(|window, cx| { + state.address.update(cx, |input, cx| { + input.set_value("deploy@box.example", window, cx) + }); + state.auth = crate::ssh_profiles::SshAuthMode::Password; + state.password.update(cx, |input, cx| { + input.set_value("typed-for-other-host", window, cx) + }); + }); + let mut credential_writes = Vec::new(); + cx.update(|_, cx| { + let destination = persist_quick_add_with( + &state, + &path, + |destination, secret| { + credential_writes.push((destination.to_owned(), secret.to_vec())); + Ok(()) + }, + cx, + ) + .unwrap(); + assert_eq!(destination, "deploy@box.example"); + }); + assert!( + credential_writes.is_empty(), + "collision must not touch credentials behind the editor" + ); + assert_eq!( + std::fs::read(&path).unwrap(), + before, + "collision must not rewrite the saved profile" + ); + let profile = crate::ssh_profiles::SshProfiles::load(&path) + .unwrap() + .for_destination("deploy@box.example"); + assert_eq!(profile.private_keys, vec![std::path::PathBuf::from("~/.id_ed25519")]); + assert_eq!(profile.label.as_deref(), Some("Deploy box")); + assert_eq!(profile.icon.as_deref(), Some("debian")); + assert_eq!(profile.connection.jump_host, "bastion.example"); + let _ = std::fs::remove_dir_all(&directory); + } + + #[gpui::test] + fn quick_add_password_failure_leaves_the_host_library_untouched(cx: &mut gpui::TestAppContext) { + let (mut state, cx) = init_and_build("core.example.cn", cx); + let directory = temp_profile_dir("password-failure"); + let path = directory.join("ssh_profiles.json"); + cx.update(|window, cx| { + state.auth = crate::ssh_profiles::SshAuthMode::Password; + state.password.update(cx, |input, cx| input.set_value("secret", window, cx)); + }); + cx.update(|_, cx| { + let error = persist_quick_add_with( + &state, + &path, + |_, _| Err(std::io::Error::other("keychain unavailable")), + cx, + ) + .unwrap_err(); + assert!(matches!(error, QuickAddError::Io(_))); + }); + // 密码先于主机库落盘:凭据失败时表单报错,文件必须还没被写出来。 + assert!(!path.exists(), "credential failure must not write the profile file"); + let _ = std::fs::remove_dir_all(&directory); + } + fn init_and_build<'a>( destination: &str, cx: &'a mut gpui::TestAppContext, diff --git a/nebula_app/src/ssh_profiles.rs b/nebula_app/src/ssh_profiles.rs index 8071a199d..1ac7cf949 100644 --- a/nebula_app/src/ssh_profiles.rs +++ b/nebula_app/src/ssh_profiles.rs @@ -164,6 +164,13 @@ impl SshProfiles { }) } + /// 目的地是否已有保存的 profile。[`Self::for_destination`] 缺失时返回 + /// 回落默认值,调用方区分不了「库里已有」和「未保存」;写入路径用它 + /// 在落盘前识别冲突,精确比较与 `upsert` 的替换键一致。 + pub fn contains_destination(&self, destination: &str) -> bool { + self.profiles.iter().any(|profile| profile.destination == destination) + } + /// 地址 → 显示名。侧栏每帧都要画主机行,不能每帧读一次 JSON,所以调用方 /// 把结果缓存起来,只在编辑器保存后刷新。 pub fn labels(&self) -> std::collections::HashMap { From 140d95c68d43d1876c450b81c6315db3f802e0c1 Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 06:44:41 +0800 Subject: [PATCH 3/6] fix(ssh): make quick-add save one leased transaction Two windows quick-adding the same destination could interleave as A loads the library, B saves profile and password, A writes its password, then A's commit fails on the changed file: the library kept B's profile while A had already overwritten B's credential. The duplicate check, the credential write and the library commit now run under the same OS-handle lifetime lease (SshProfiles::save_leased), so another window's save is rejected as lease-busy and retried on a fresh snapshot instead. When the commit itself fails, the credential is rolled back to its pre-transaction state: the prior password is restored, or the just-typed one is deleted. The credential seam is extended to the full transaction (CredentialOp), and the interleaving plus both rollback outcomes are pinned by tests. Test coverage also moved to the sibling ssh_quick_add/tests.rs module, and the note records the superseded credential-ordering decision. The stray rustfmt drift that kept the lint job red came from the local default toolchain (1.99.1) formatting two set_value calls differently than the pinned 1.97.1; cargo +1.97.1 fmt is clean now. --- .../2026-11-13-quick-add-collision-reuse.md | 49 ++- .../src/gpui_shell/workspace/ssh_quick_add.rs | 286 ++++---------- .../workspace/ssh_quick_add/tests.rs | 355 ++++++++++++++++++ nebula_app/src/ssh_profiles.rs | 25 +- 4 files changed, 479 insertions(+), 236 deletions(-) create mode 100644 nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md index 263373248..a4061b314 100644 --- a/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md @@ -2,7 +2,9 @@ ## Status -Accepted (#869 review, 2026-11-12). +Accepted (#869 review, 2026-11-12). Amended 2026-11-13: the credential +ordering bullet was superseded by the leased save transaction below (#869 +review round 2). ## Context @@ -25,6 +27,11 @@ reported by the form after the profile file had already changed. `SshProfiles::contains_destination`). - Review reproduction on PR #869 (2026-11-12): a populated `deploy@box.example` profile replaced through a quick-add save. +- Review reproduction on PR #869 (2026-11-13): with the plain + "credential first" ordering, two windows quick-adding the same destination + interleave as A loads the library, B saves profile and password, A writes + its password, then A's `profiles.save()` fails on the changed file — the + library keeps B's profile while A has already overwritten B's credential. ## Decision @@ -33,10 +40,15 @@ reported by the form after the profile file had already changed. nothing and writes no credentials; it returns the destination and `add_ssh_terminal` connects through the saved profile. Editing keys, jump, label or icon remains the Settings editor's job via "More settings". -- Credential storage runs before the profile file is written: a - credential-storage failure leaves the host library untouched and the overlay - open with the error. The write set is one profile plus one credential, so - all-or-nothing ordering is achievable here. +- Duplicate check, credential write and library commit run as one save + transaction under a single `atomic_file` lifetime lease + (`SshProfiles::save_leased`): another window's save cannot slip between + the check and the commit, and the lease-busy error tells it to retry. + Within the transaction the credential write still precedes the commit, so + a credential-storage failure leaves the host library untouched. When the + commit itself fails (a lease-bypassing writer changed the file, or the + disk errored), the credential is rolled back to its pre-transaction state + — the prior password is restored, or the just-written one is deleted. ## Rejected alternatives @@ -49,14 +61,23 @@ reported by the form after the profile file had already changed. - Auto-route the collision into the Settings editor: the overlay's purpose is connecting; silently switching pages breaks the one-flow intent recorded in `2026-11-03-launcher-add-and-connect-ssh.md`. +- Commit first with a file rollback on credential failure: restoring the + pre-save bytes also works while the lease is held, but the interleaving + and commit-failure regressions the review asked for then have no seam to + pin them (everything injectable sits after the commit), and the write set + hits the profile file twice per save. ## Consequences - Typing an existing host's address into quick-add connects with the saved configuration and changes nothing on disk or in the credential store. -- A stored password can exist for a destination whose profile save later - fails; it is keyed by destination and overwritten or reused by the next - successful save for that host. +- The window-vs-window interleaving cannot produce a mismatched pair + anymore: a concurrent quick-add either reuses the freshly saved profile + (collision path) or is rejected as lease-busy and retried on a fresh + snapshot. +- A failed library commit can still leave a lease-bypassing writer's + profile in place, but never paired with this transaction's password: the + credential is restored or removed before the error is reported. ## Validation @@ -65,9 +86,15 @@ reported by the form after the profile file had already changed. byte-for-byte and the injected credential recorder sees no call. - `quick_add_password_failure_leaves_the_host_library_untouched`: a failing credential store is injected and the profile file is never created. -- `persist_quick_add_with` takes the credential write as a parameter, - mirroring the closure-injected tests of `platform::credentials`, so tests - never touch the user keychain. +- `quick_add_transaction_rejects_a_window_save_in_the_middle`: window B's + API save fired from inside the transaction is rejected with the lease-busy + error and A's profile and password are the only survivors. +- `quick_add_commit_failure_rolls_the_password_back`: an out-of-band writer + makes the commit fail; with no prior password the typed one is deleted, + with a prior one it is restored. +- `persist_quick_add_with` takes the credential operations as a parameter + (`CredentialOp`), mirroring the closure-injected tests of + `platform::credentials`, so tests never touch the user keychain. ## Supersedes diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs index f70e3afbe..914bd414a 100644 --- a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs @@ -128,21 +128,51 @@ pub(super) enum QuickAddError { KeysNeedAdvancedEditor, } +/// 保存事务里的凭据操作。事务要读事务前的密码(回滚起点)、写新密码、 +/// 提交失败时恢复旧值或删掉本次写入;真实实现直连系统凭据库,测试注入 +/// 内存库,顺带保证测试永远不触碰用户钥匙串。 +enum CredentialOp<'a> { + /// 读该目的地当前已存的密码,作为提交失败时的回滚起点。 + Prior(&'a str), + /// 写入表单里的密码。 + Store(&'a str, &'a [u8]), + /// 提交失败后的回滚:`Prior` 读到过旧值时恢复它。 + Restore(&'a str, &'a [u8]), + /// 提交失败后的回滚:`Prior` 是 `None` 时删掉本次写入。 + Forget(&'a str), +} + /// 落盘一次快捷添加。独立函数让测试能指向临时文件,避免触碰真实主机库。 fn persist_quick_add( state: &SshQuickAddState, path: &std::path::Path, cx: &gpui::App, ) -> Result { - persist_quick_add_with(state, path, crate::ssh_credentials::store_password, cx) + persist_quick_add_with(state, path, system_credentials, cx) +} + +fn system_credentials(op: CredentialOp<'_>) -> std::io::Result>> { + match op { + CredentialOp::Prior(destination) => { + crate::ssh_credentials::load_stored_password(destination) + }, + CredentialOp::Store(destination, secret) | CredentialOp::Restore(destination, secret) => { + crate::ssh_credentials::store_password(destination, secret).map(|()| None) + }, + CredentialOp::Forget(destination) => { + crate::ssh_credentials::forget_password(destination).map(|()| None) + }, + } } -/// 凭据写入由调用方注入:真实路径直连系统凭据库,测试注入假存储来验证 -/// 落盘顺序,顺带保证测试永远不触碰用户钥匙串。 +/// 一笔保存事务:重复检查、凭据写入和主机库提交全程持有同一份 OS 句柄 +/// 租约,其它窗口的保存插不进来;提交失败时把凭据回滚到事务前——有旧值 +/// 恢复旧值,没有就删掉本次写入——两个存储都不留「库是别人的、密码是 +/// 我的」这类半笔状态。 fn persist_quick_add_with( state: &SshQuickAddState, path: &std::path::Path, - mut store_password: impl FnMut(&str, &[u8]) -> std::io::Result<()>, + mut credential: impl FnMut(CredentialOp<'_>) -> std::io::Result>>, cx: &gpui::App, ) -> Result { let destination = state.draft_destination(cx)?; @@ -157,23 +187,32 @@ fn persist_quick_add_with( let label = state.label.read(cx).value().trim().to_owned(); (!label.is_empty()).then_some(label) }; + let lease = crate::atomic_file::try_lifetime_lock(path) + .map_err(|error| QuickAddError::Io(error.to_string()))? + .ok_or_else(|| { + QuickAddError::Io("Host profiles are being saved by another window".to_owned()) + })?; let mut profiles = crate::ssh_profiles::SshProfiles::load(path) .map_err(|error| QuickAddError::Io(error.to_string()))?; if profiles.contains_destination(&destination) { // 目的地已有保存的 profile:私钥、跳板、图标只存在于完整编辑器里, // 这份子集表单没有资格整体替换它。原样复用交给连接链路——返回 // destination 后 `add_ssh_terminal` 会按已存 profile 建会话;凭据 - // 同样不碰,改密码或密钥请走「更多设置」。 + // 同样不碰,改密码或密钥请走「更多设置」。检查发生在租约内的最新 + // 快照上,别的窗口刚保存完的同目标不会漏判。 return Ok(destination); } - // 密码先于主机库落盘:凭据写失败时表单报错,主机库文件必须还是原样, - // 不能留下「报了错却已经改了文件」的半写状态。 - if auth == crate::ssh_profiles::SshAuthMode::Password - && !password.is_empty() - && let Err(error) = store_password(&destination, password.as_bytes()) - { - return Err(QuickAddError::Io(error.to_string())); - } + let wants_password = auth == crate::ssh_profiles::SshAuthMode::Password && !password.is_empty(); + let prior = if wants_password { + let prior = credential(CredentialOp::Prior(&destination)) + .map_err(|error| QuickAddError::Io(error.to_string()))?; + // 密码仍先于主机库提交:凭据写失败时表单报错,主机库文件还没动。 + credential(CredentialOp::Store(&destination, password.as_bytes())) + .map_err(|error| QuickAddError::Io(error.to_string()))?; + prior + } else { + None + }; profiles.upsert(crate::ssh_profiles::SshProfileAuth { destination: destination.clone(), auth, @@ -182,7 +221,20 @@ fn persist_quick_add_with( icon: None, connection: crate::ssh_profiles::SshConnectionOptions::default(), }); - profiles.save(path).map_err(|error| QuickAddError::Io(error.to_string()))?; + if let Err(error) = profiles.save_leased(path, &lease) { + // 提交失败:文件只会被绕过保存 API 的写入方改掉(或磁盘出错)。 + // `save_leased` 在租约内比对过快照,按事务语义回滚凭据。 + let restore = match prior { + Some(prior) => credential(CredentialOp::Restore(&destination, &prior)), + None => credential(CredentialOp::Forget(&destination)), + }; + return Err(match restore { + Ok(_) => QuickAddError::Io(error.to_string()), + Err(restore_error) => QuickAddError::Io(format!( + "{error}; rolling the password back failed too: {restore_error}" + )), + }); + } Ok(destination) } @@ -526,208 +578,4 @@ impl NebulaWorkspace { } #[cfg(all(test, feature = "gpui-test-support"))] -mod tests { - use super::*; - - /// `add_window_view` 需要一个 Render 根视图;浮层状态在闭包里创建, - /// 这里只当窗口宿主。 - struct TestHost; - impl gpui::Render for TestHost { - fn render( - &mut self, - _window: &mut Window, - _cx: &mut gpui::Context, - ) -> impl IntoElement { - gpui::div() - } - } - - /// 临时主机库目录:唯一命名避免测试并行互踩,用完整目录删除。 - fn temp_profile_dir(tag: &str) -> std::path::PathBuf { - let directory = std::env::temp_dir().join(format!( - "pebrel-quick-add-{tag}-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::create_dir_all(&directory).unwrap(); - directory - } - - #[gpui::test] - fn quick_add_collision_reuses_the_saved_profile_untouched(cx: &mut gpui::TestAppContext) { - let (mut state, cx) = init_and_build("other.example", cx); - let directory = temp_profile_dir("collision"); - let path = directory.join("ssh_profiles.json"); - // 库里先有一台带完整配置的主机:私钥、跳板、名称、图标都是浮层 - // 这份子集表单覆盖不了的权威数据。 - let mut profiles = crate::ssh_profiles::SshProfiles::default(); - profiles.upsert(crate::ssh_profiles::SshProfileAuth { - destination: "deploy@box.example".to_owned(), - auth: crate::ssh_profiles::SshAuthMode::Password, - private_keys: vec![std::path::PathBuf::from("~/.id_ed25519")], - label: Some("Deploy box".to_owned()), - icon: Some("debian".to_owned()), - connection: { - let mut connection = crate::ssh_profiles::SshConnectionOptions::default(); - connection.jump_mode = crate::ssh_profiles::SshHostJumpMode::Host; - connection.jump_host = "bastion.example".to_owned(); - connection - }, - }); - profiles.save(&path).unwrap(); - let before = std::fs::read(&path).unwrap(); - // 表单地址改成已有主机的目的地,还填了密码:保存必须原样复用, - // 连凭据都不能替编辑器写。 - cx.update(|window, cx| { - state.address.update(cx, |input, cx| { - input.set_value("deploy@box.example", window, cx) - }); - state.auth = crate::ssh_profiles::SshAuthMode::Password; - state.password.update(cx, |input, cx| { - input.set_value("typed-for-other-host", window, cx) - }); - }); - let mut credential_writes = Vec::new(); - cx.update(|_, cx| { - let destination = persist_quick_add_with( - &state, - &path, - |destination, secret| { - credential_writes.push((destination.to_owned(), secret.to_vec())); - Ok(()) - }, - cx, - ) - .unwrap(); - assert_eq!(destination, "deploy@box.example"); - }); - assert!( - credential_writes.is_empty(), - "collision must not touch credentials behind the editor" - ); - assert_eq!( - std::fs::read(&path).unwrap(), - before, - "collision must not rewrite the saved profile" - ); - let profile = crate::ssh_profiles::SshProfiles::load(&path) - .unwrap() - .for_destination("deploy@box.example"); - assert_eq!(profile.private_keys, vec![std::path::PathBuf::from("~/.id_ed25519")]); - assert_eq!(profile.label.as_deref(), Some("Deploy box")); - assert_eq!(profile.icon.as_deref(), Some("debian")); - assert_eq!(profile.connection.jump_host, "bastion.example"); - let _ = std::fs::remove_dir_all(&directory); - } - - #[gpui::test] - fn quick_add_password_failure_leaves_the_host_library_untouched(cx: &mut gpui::TestAppContext) { - let (mut state, cx) = init_and_build("core.example.cn", cx); - let directory = temp_profile_dir("password-failure"); - let path = directory.join("ssh_profiles.json"); - cx.update(|window, cx| { - state.auth = crate::ssh_profiles::SshAuthMode::Password; - state.password.update(cx, |input, cx| input.set_value("secret", window, cx)); - }); - cx.update(|_, cx| { - let error = persist_quick_add_with( - &state, - &path, - |_, _| Err(std::io::Error::other("keychain unavailable")), - cx, - ) - .unwrap_err(); - assert!(matches!(error, QuickAddError::Io(_))); - }); - // 密码先于主机库落盘:凭据失败时表单报错,文件必须还没被写出来。 - assert!(!path.exists(), "credential failure must not write the profile file"); - let _ = std::fs::remove_dir_all(&directory); - } - - fn init_and_build<'a>( - destination: &str, - cx: &'a mut gpui::TestAppContext, - ) -> (SshQuickAddState, &'a mut gpui::VisualTestContext) { - cx.update(|cx| { - gpui_component::init(cx); - cx.set_global(crate::gpui_shell::config::Settings::load( - nebula_settings::ThemeName::Nord, - )); - }); - let mut state = None; - let (_, cx) = cx.add_window_view(|window, cx| { - state = Some(SshQuickAddState::new(destination, window, cx)); - TestHost - }); - (state.expect("state built"), cx) - } - - #[test] - fn quick_add_prefills_user_and_port_from_the_typed_address() { - // 不依赖窗口:预填拆分只走 `split_destination_*`。 - let (address_with_user, port) = - crate::display::split_destination_port("deploy@box.example:2222"); - let (username, address) = crate::display::split_destination_user(&address_with_user); - assert_eq!( - (username.as_str(), address.as_str(), port.as_str()), - ("deploy", "box.example", "2222") - ); - } - - #[gpui::test] - fn quick_add_draft_composes_and_validates(cx: &mut gpui::TestAppContext) { - let (state, cx) = init_and_build("core.example.cn", cx); - cx.update(|window, cx| { - assert_eq!(state.draft_destination(cx).unwrap(), "root@core.example.cn"); - // 端口非法直接拒绝,不进入落盘。 - state.port.update(cx, |input, cx| input.set_value("70000", window, cx)); - assert_eq!(state.draft_destination(cx).unwrap_err(), QuickAddError::InvalidPort); - state.port.update(cx, |input, cx| input.set_value("2222", window, cx)); - assert_eq!(state.draft_destination(cx).unwrap(), "root@core.example.cn:2222"); - // 带非法字符交给权威校验拒绝;空地址单独报"缺地址"。 - state.address.update(cx, |input, cx| input.set_value("bad host", window, cx)); - assert!(matches!(state.draft_destination(cx), Err(QuickAddError::Rejected(_)))); - state.address.update(cx, |input, cx| input.set_value("", window, cx)); - assert_eq!(state.draft_destination(cx).unwrap_err(), QuickAddError::MissingAddress); - }); - } - - #[gpui::test] - fn quick_add_persists_a_nameless_profile_before_any_connection(cx: &mut gpui::TestAppContext) { - let (mut state, cx) = init_and_build("core.example.cn", cx); - let directory = std::env::temp_dir().join(format!( - "pebrel-quick-add-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::create_dir_all(&directory).unwrap(); - let path = directory.join("ssh_profiles.json"); - cx.update(|_, cx| { - let destination = persist_quick_add(&state, &path, cx).unwrap(); - assert_eq!(destination, "root@core.example.cn"); - }); - let profiles = crate::ssh_profiles::SshProfiles::load(&path).unwrap(); - let profile = profiles.for_destination("root@core.example.cn"); - // 没填名称:保持空,列表回落显示地址,而不是自动起「主机 N」。 - assert_eq!(profile.label, None); - assert_eq!(profile.auth, crate::ssh_profiles::SshAuthMode::Auto); - // 公钥模式:浮层收集不了私钥文件,落盘必须被守卫拦下, - // 且不能把空私钥的坏 profile 写进文件。 - cx.update(|_, cx| { - state.auth = crate::ssh_profiles::SshAuthMode::PublicKey; - assert_eq!( - persist_quick_add(&state, &path, cx).unwrap_err(), - QuickAddError::KeysNeedAdvancedEditor - ); - }); - assert_eq!( - crate::ssh_profiles::SshProfiles::load(&path) - .unwrap() - .for_destination("root@core.example.cn") - .auth, - crate::ssh_profiles::SshAuthMode::Auto, - "rejected save must not overwrite the stored profile" - ); - let _ = std::fs::remove_dir_all(&directory); - } -} +mod tests; diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs new file mode 100644 index 000000000..3db65d40b --- /dev/null +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs @@ -0,0 +1,355 @@ +use super::*; + +/// `add_window_view` 需要一个 Render 根视图;浮层状态在闭包里创建, +/// 这里只当窗口宿主。 +struct TestHost; +impl gpui::Render for TestHost { + fn render(&mut self, _window: &mut Window, _cx: &mut gpui::Context) -> impl IntoElement { + gpui::div() + } +} + +/// 临时主机库目录:唯一命名避免测试并行互踩,用完整目录删除。 +fn temp_profile_dir(tag: &str) -> std::path::PathBuf { + let directory = std::env::temp_dir().join(format!( + "pebrel-quick-add-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&directory).unwrap(); + directory +} + +/// 内存凭据库:按目的地存密码。「写入」这一步可挂一个外来动作,交错 +/// 测试用它把别的窗口的保存插进事务中间。测试永不触碰用户钥匙串。 +struct FakeCredentials { + secrets: std::collections::BTreeMap>, + on_store: Option>, +} + +impl FakeCredentials { + fn new() -> Self { + Self { secrets: Default::default(), on_store: None } + } + + fn call(&mut self, op: CredentialOp<'_>) -> std::io::Result>> { + match op { + CredentialOp::Prior(destination) => Ok(self.secrets.get(destination).cloned()), + CredentialOp::Store(destination, secret) => { + if let Some(on_store) = self.on_store.as_mut() { + on_store(destination); + } + self.secrets.insert(destination.to_owned(), secret.to_vec()); + Ok(None) + }, + CredentialOp::Restore(destination, secret) => { + self.secrets.insert(destination.to_owned(), secret.to_vec()); + Ok(None) + }, + CredentialOp::Forget(destination) => { + self.secrets.remove(destination); + Ok(None) + }, + } + } +} + +/// 窗口 B 的保存数据:同一目的地、默认认证、名称可区分。两个测试都要 +/// 一份能和 A 的表单区分开的 profile。 +fn window_b_profile() -> crate::ssh_profiles::SshProfileAuth { + crate::ssh_profiles::SshProfileAuth { + destination: "root@core.example.cn".to_owned(), + auth: crate::ssh_profiles::SshAuthMode::Auto, + private_keys: Vec::new(), + label: Some("Window B".to_owned()), + icon: None, + connection: crate::ssh_profiles::SshConnectionOptions::default(), + } +} + +/// 模拟一个不走保存 API(不取租约)的写入方:把窗口 B 对同一目的地的 +/// 保存直接写进主机库文件。A 事务的提交会在快照比对处失败。 +fn out_of_band_window_b_save(path: &std::path::Path) { + let mut window_b = crate::ssh_profiles::SshProfiles::load(path).unwrap(); + window_b.upsert(window_b_profile()); + let data = serde_json::to_vec_pretty(&window_b).unwrap(); + crate::atomic_file::write(path, &data).unwrap(); +} + +#[gpui::test] +fn quick_add_collision_reuses_the_saved_profile_untouched(cx: &mut gpui::TestAppContext) { + let (mut state, cx) = init_and_build("other.example", cx); + let directory = temp_profile_dir("collision"); + let path = directory.join("ssh_profiles.json"); + // 库里先有一台带完整配置的主机:私钥、跳板、名称、图标都是浮层 + // 这份子集表单覆盖不了的权威数据。 + let mut profiles = crate::ssh_profiles::SshProfiles::default(); + profiles.upsert(crate::ssh_profiles::SshProfileAuth { + destination: "deploy@box.example".to_owned(), + auth: crate::ssh_profiles::SshAuthMode::Password, + private_keys: vec![std::path::PathBuf::from("~/.id_ed25519")], + label: Some("Deploy box".to_owned()), + icon: Some("debian".to_owned()), + connection: { + let mut connection = crate::ssh_profiles::SshConnectionOptions::default(); + connection.jump_mode = crate::ssh_profiles::SshHostJumpMode::Host; + connection.jump_host = "bastion.example".to_owned(); + connection + }, + }); + profiles.save(&path).unwrap(); + let before = std::fs::read(&path).unwrap(); + // 表单地址改成已有主机的目的地,还填了密码:保存必须原样复用, + // 连凭据都不能替编辑器写。 + cx.update(|window, cx| { + state.address.update(cx, |input, cx| input.set_value("deploy@box.example", window, cx)); + state.auth = crate::ssh_profiles::SshAuthMode::Password; + state.password.update(cx, |input, cx| input.set_value("typed-for-other-host", window, cx)); + }); + let mut credential_writes = Vec::new(); + cx.update(|_, cx| { + let destination = persist_quick_add_with( + &state, + &path, + |op| { + if let CredentialOp::Store(destination, secret) = op { + credential_writes.push((destination.to_owned(), secret.to_vec())); + } + Ok(None) + }, + cx, + ) + .unwrap(); + assert_eq!(destination, "deploy@box.example"); + }); + assert!(credential_writes.is_empty(), "collision must not touch credentials behind the editor"); + assert_eq!( + std::fs::read(&path).unwrap(), + before, + "collision must not rewrite the saved profile" + ); + let profile = crate::ssh_profiles::SshProfiles::load(&path) + .unwrap() + .for_destination("deploy@box.example"); + assert_eq!(profile.private_keys, vec![std::path::PathBuf::from("~/.id_ed25519")]); + assert_eq!(profile.label.as_deref(), Some("Deploy box")); + assert_eq!(profile.icon.as_deref(), Some("debian")); + assert_eq!(profile.connection.jump_host, "bastion.example"); + let _ = std::fs::remove_dir_all(&directory); +} + +#[gpui::test] +fn quick_add_password_failure_leaves_the_host_library_untouched(cx: &mut gpui::TestAppContext) { + let (mut state, cx) = init_and_build("core.example.cn", cx); + let directory = temp_profile_dir("password-failure"); + let path = directory.join("ssh_profiles.json"); + cx.update(|window, cx| { + state.auth = crate::ssh_profiles::SshAuthMode::Password; + state.password.update(cx, |input, cx| input.set_value("secret", window, cx)); + }); + cx.update(|_, cx| { + let error = persist_quick_add_with( + &state, + &path, + |op| match op { + CredentialOp::Store(_, _) => Err(std::io::Error::other("keychain unavailable")), + _ => Ok(None), + }, + cx, + ) + .unwrap_err(); + assert!(matches!(error, QuickAddError::Io(_))); + }); + // 密码先于主机库提交:凭据失败时表单报错,文件必须还没被写出来。 + assert!(!path.exists(), "credential failure must not write the profile file"); + let _ = std::fs::remove_dir_all(&directory); +} + +#[gpui::test] +fn quick_add_transaction_rejects_a_window_save_in_the_middle(cx: &mut gpui::TestAppContext) { + let (mut state, cx) = init_and_build("core.example.cn", cx); + let directory = temp_profile_dir("transaction"); + let path = directory.join("ssh_profiles.json"); + cx.update(|window, cx| { + state.auth = crate::ssh_profiles::SshAuthMode::Password; + state.password.update(cx, |input, cx| input.set_value("from-window-a", window, cx)); + }); + // 复现审查固定的交错顺序:A 读取主机库、B 保存同一目标及其密码、 + // A 写密码、A 提交。A 的事务全程持有租约,B 的保存API 落在 A 的 + // 凭据写入这一步,必须被租约拒绝,而不是带着 A 的旧快照写入。 + let mut credentials = FakeCredentials::new(); + let closure_path = path.clone(); + credentials.on_store = Some(Box::new(move |destination| { + assert_eq!(destination, "root@core.example.cn"); + let mut window_b = crate::ssh_profiles::SshProfiles::load(&closure_path).unwrap(); + window_b.upsert(window_b_profile()); + let error = window_b.save(&closure_path).unwrap_err(); + assert_eq!( + error.kind(), + std::io::ErrorKind::WouldBlock, + "the window save must be rejected by A's lease" + ); + })); + cx.update(|_, cx| { + let destination = + persist_quick_add_with(&state, &path, |op| credentials.call(op), cx).unwrap(); + assert_eq!(destination, "root@core.example.cn"); + }); + // 终态只有 A 的 profile 和 A 的密码;B 的保存一个字节都没落下。 + let profiles = crate::ssh_profiles::SshProfiles::load(&path).unwrap(); + let profile = profiles.for_destination("root@core.example.cn"); + assert_eq!(profile.auth, crate::ssh_profiles::SshAuthMode::Password); + assert_eq!(profile.label, None); + assert_eq!( + credentials.secrets.get("root@core.example.cn").map(Vec::as_slice), + Some(b"from-window-a".as_slice()) + ); + let _ = std::fs::remove_dir_all(&directory); +} + +#[gpui::test] +fn quick_add_commit_failure_rolls_the_password_back(cx: &mut gpui::TestAppContext) { + let (mut state, cx) = init_and_build("core.example.cn", cx); + cx.update(|window, cx| { + state.auth = crate::ssh_profiles::SshAuthMode::Password; + state.password.update(cx, |input, cx| input.set_value("typed-secret", window, cx)); + }); + + // 场景一:事务前该目的地没有密码。提交前一刻,一个绕过保存 API 的 + // 写入方把 B 的同目标保存落了盘;提交必须失败,且本次写入的密码被 + // 删掉——库和凭据都停在 B 的状态上,谁也不覆盖谁。 + { + let directory = temp_profile_dir("rollback-forget"); + let path = directory.join("ssh_profiles.json"); + let mut credentials = FakeCredentials::new(); + let closure_path = path.clone(); + credentials.on_store = Some(Box::new(move |_| out_of_band_window_b_save(&closure_path))); + cx.update(|_, cx| { + let error = + persist_quick_add_with(&state, &path, |op| credentials.call(op), cx).unwrap_err(); + assert!( + matches!(&error, QuickAddError::Io(message) if message.contains("Host profiles changed")), + "the commit itself must fail on the changed file: {error:?}" + ); + }); + assert!( + credentials.secrets.is_empty(), + "the transaction's own password write must be rolled back" + ); + let profiles = crate::ssh_profiles::SshProfiles::load(&path).unwrap(); + let profile = profiles.for_destination("root@core.example.cn"); + assert_eq!( + profile.label.as_deref(), + Some("Window B"), + "the out-of-band save must survive the failed commit" + ); + let _ = std::fs::remove_dir_all(&directory); + } + + // 场景二:事务前已有旧密码(比如早先删过的主机留下的孤儿凭据)。 + // 同样的提交失败这次要恢复旧值,而不是删掉。 + { + let directory = temp_profile_dir("rollback-restore"); + let path = directory.join("ssh_profiles.json"); + let mut credentials = FakeCredentials::new(); + credentials.secrets.insert("root@core.example.cn".to_owned(), b"old-secret".to_vec()); + let closure_path = path.clone(); + credentials.on_store = Some(Box::new(move |_| out_of_band_window_b_save(&closure_path))); + cx.update(|_, cx| { + let error = + persist_quick_add_with(&state, &path, |op| credentials.call(op), cx).unwrap_err(); + assert!(matches!(error, QuickAddError::Io(_))); + }); + assert_eq!( + credentials.secrets.get("root@core.example.cn").map(Vec::as_slice), + Some(b"old-secret".as_slice()), + "commit failure must restore the prior password, not the typed one" + ); + let _ = std::fs::remove_dir_all(&directory); + } +} + +fn init_and_build<'a>( + destination: &str, + cx: &'a mut gpui::TestAppContext, +) -> (SshQuickAddState, &'a mut gpui::VisualTestContext) { + cx.update(|cx| { + gpui_component::init(cx); + cx.set_global(crate::gpui_shell::config::Settings::load(nebula_settings::ThemeName::Nord)); + }); + let mut state = None; + let (_, cx) = cx.add_window_view(|window, cx| { + state = Some(SshQuickAddState::new(destination, window, cx)); + TestHost + }); + (state.expect("state built"), cx) +} + +#[test] +fn quick_add_prefills_user_and_port_from_the_typed_address() { + // 不依赖窗口:预填拆分只走 `split_destination_*`。 + let (address_with_user, port) = + crate::display::split_destination_port("deploy@box.example:2222"); + let (username, address) = crate::display::split_destination_user(&address_with_user); + assert_eq!( + (username.as_str(), address.as_str(), port.as_str()), + ("deploy", "box.example", "2222") + ); +} + +#[gpui::test] +fn quick_add_draft_composes_and_validates(cx: &mut gpui::TestAppContext) { + let (state, cx) = init_and_build("core.example.cn", cx); + cx.update(|window, cx| { + assert_eq!(state.draft_destination(cx).unwrap(), "root@core.example.cn"); + // 端口非法直接拒绝,不进入落盘。 + state.port.update(cx, |input, cx| input.set_value("70000", window, cx)); + assert_eq!(state.draft_destination(cx).unwrap_err(), QuickAddError::InvalidPort); + state.port.update(cx, |input, cx| input.set_value("2222", window, cx)); + assert_eq!(state.draft_destination(cx).unwrap(), "root@core.example.cn:2222"); + // 带非法字符交给权威校验拒绝;空地址单独报"缺地址"。 + state.address.update(cx, |input, cx| input.set_value("bad host", window, cx)); + assert!(matches!(state.draft_destination(cx), Err(QuickAddError::Rejected(_)))); + state.address.update(cx, |input, cx| input.set_value("", window, cx)); + assert_eq!(state.draft_destination(cx).unwrap_err(), QuickAddError::MissingAddress); + }); +} + +#[gpui::test] +fn quick_add_persists_a_nameless_profile_before_any_connection(cx: &mut gpui::TestAppContext) { + let (mut state, cx) = init_and_build("core.example.cn", cx); + let directory = std::env::temp_dir().join(format!( + "pebrel-quick-add-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&directory).unwrap(); + let path = directory.join("ssh_profiles.json"); + cx.update(|_, cx| { + let destination = persist_quick_add(&state, &path, cx).unwrap(); + assert_eq!(destination, "root@core.example.cn"); + }); + let profiles = crate::ssh_profiles::SshProfiles::load(&path).unwrap(); + let profile = profiles.for_destination("root@core.example.cn"); + // 没填名称:保持空,列表回落显示地址,而不是自动起「主机 N」。 + assert_eq!(profile.label, None); + assert_eq!(profile.auth, crate::ssh_profiles::SshAuthMode::Auto); + // 公钥模式:浮层收集不了私钥文件,落盘必须被守卫拦下, + // 且不能把空私钥的坏 profile 写进文件。 + cx.update(|_, cx| { + state.auth = crate::ssh_profiles::SshAuthMode::PublicKey; + assert_eq!( + persist_quick_add(&state, &path, cx).unwrap_err(), + QuickAddError::KeysNeedAdvancedEditor + ); + }); + assert_eq!( + crate::ssh_profiles::SshProfiles::load(&path) + .unwrap() + .for_destination("root@core.example.cn") + .auth, + crate::ssh_profiles::SshAuthMode::Auto, + "rejected save must not overwrite the stored profile" + ); + let _ = std::fs::remove_dir_all(&directory); +} diff --git a/nebula_app/src/ssh_profiles.rs b/nebula_app/src/ssh_profiles.rs index 1ac7cf949..c11b5be1b 100644 --- a/nebula_app/src/ssh_profiles.rs +++ b/nebula_app/src/ssh_profiles.rs @@ -122,19 +122,32 @@ impl SshProfiles { } pub fn save(&mut self, path: &Path) -> io::Result<()> { - self.validate_targets() - .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } // Reuse the OS-handle lease, scoped to this write. A stale snapshot must // never replace a profile another window has just edited. - let _lease = crate::atomic_file::try_lifetime_lock(path)?.ok_or_else(|| { + let lease = crate::atomic_file::try_lifetime_lock(path)?.ok_or_else(|| { io::Error::new( io::ErrorKind::WouldBlock, "Host profiles are being saved by another window", ) })?; + self.save_leased(path, &lease) + } + + /// 在调用方已持有的租约内提交。重复检查、凭据写入和提交要作为一笔事务 + /// 的写入方(快捷添加)必须从取租约到落盘全程持锁,才能让其它窗口的 + /// 保存插不进来,所以把「读当前文件 → 写出」拆到这里;公开的 + /// [`Self::save`] 自己取租约后同样落到这里。租约参数只是调用方持有它 + /// 的证明——没有租约的调用方不允许绕过这段互斥。 + pub(crate) fn save_leased( + &mut self, + path: &Path, + _lease: &crate::atomic_file::LifetimeFileLock, + ) -> io::Result<()> { + self.validate_targets() + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } let current = match std::fs::read(path) { Ok(bytes) => Some(bytes), Err(error) if error.kind() == io::ErrorKind::NotFound => None, From 5e6a13091e4aa82fd7f14a9c53b88f81f3442392 Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 09:04:26 +0800 Subject: [PATCH 4/6] fix(ssh): only roll back a password this save actually wrote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The commit-failure rollback keyed on prior alone: a save that never writes a password (auto auth, or password auth with the field left empty) shares the prior=None shape with wrote-and-nothing-existed, so a failed commit called the delete path on a credential this transaction never touched — an existing password for the destination was wiped. Reproduced on Linux with a pre-seeded credential, an existing lock file and a read-only directory: both no-write saves errored on the commit and deleted the pre-existing password. The transaction now records whether it wrote a password at all; the restore/delete path only runs for a written one, and a no-write save reports the commit error with the credential untouched. Regression covers auto auth and empty-password saves through the same injection; the note records the narrowed rollback scope. --- .../2026-11-13-quick-add-collision-reuse.md | 18 ++++- .../src/gpui_shell/workspace/ssh_quick_add.rs | 40 ++++++---- .../workspace/ssh_quick_add/tests.rs | 74 +++++++++++++++++++ 3 files changed, 115 insertions(+), 17 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md b/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md index a4061b314..25d416aec 100644 --- a/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md +++ b/architecture/notes/nebula_app/gpui_shell/workspace/2026-11-13-quick-add-collision-reuse.md @@ -32,6 +32,14 @@ reported by the form after the profile file had already changed. interleave as A loads the library, B saves profile and password, A writes its password, then A's `profiles.save()` fails on the changed file — the library keeps B's profile while A has already overwritten B's credential. +- Review reproduction on PR #869 (2026-11-13, second round): with the + rollback keyed on `prior` alone, a save that never writes a password + (auto auth, or password auth with the field left empty) shared the + `prior = None` shape with "wrote, nothing existed" — a failing commit + then called the delete path on a credential this transaction never + touched. Reproduced on Linux with a pre-seeded credential, an existing + lock file and a read-only directory: both no-write saves errored on the + commit and deleted the pre-existing password. ## Decision @@ -47,8 +55,9 @@ reported by the form after the profile file had already changed. Within the transaction the credential write still precedes the commit, so a credential-storage failure leaves the host library untouched. When the commit itself fails (a lease-bypassing writer changed the file, or the - disk errored), the credential is rolled back to its pre-transaction state - — the prior password is restored, or the just-written one is deleted. + disk errored), only a password this transaction actually wrote is rolled + back — the prior password is restored, or the just-written one is deleted; + a save that wrote no password leaves an existing credential untouched. ## Rejected alternatives @@ -92,6 +101,11 @@ reported by the form after the profile file had already changed. - `quick_add_commit_failure_rolls_the_password_back`: an out-of-band writer makes the commit fail; with no prior password the typed one is deleted, with a prior one it is restored. +- `quick_add_commit_failure_without_a_password_write_keeps_the_existing_credential`: + auto auth and empty-password saves with a pre-existing credential fail the + commit through a read-only directory (existing lock file keeps the lease + working) and record zero credential operations — the pre-existing password + survives. - `persist_quick_add_with` takes the credential operations as a parameter (`CredentialOp`), mirroring the closure-injected tests of `platform::credentials`, so tests never touch the user keychain. diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs index 914bd414a..b3bd7ef35 100644 --- a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs @@ -203,16 +203,19 @@ fn persist_quick_add_with( return Ok(destination); } let wants_password = auth == crate::ssh_profiles::SshAuthMode::Password && !password.is_empty(); - let prior = if wants_password { + // 本次事务对凭据的写入记录:None = 没写过密码(自动认证或密码留空), + // Some(prior) = 写过,prior 是事务前的旧值(None = 原本没有)。回滚只 + // 针对本次真正写入的凭据——目的地原有的密码不是这次写的,提交失败时 + // 把它删掉是替用户清库。 + let mut written_password: Option>> = None; + if wants_password { let prior = credential(CredentialOp::Prior(&destination)) .map_err(|error| QuickAddError::Io(error.to_string()))?; // 密码仍先于主机库提交:凭据写失败时表单报错,主机库文件还没动。 credential(CredentialOp::Store(&destination, password.as_bytes())) .map_err(|error| QuickAddError::Io(error.to_string()))?; - prior - } else { - None - }; + written_password = Some(prior); + } profiles.upsert(crate::ssh_profiles::SshProfileAuth { destination: destination.clone(), auth, @@ -223,16 +226,23 @@ fn persist_quick_add_with( }); if let Err(error) = profiles.save_leased(path, &lease) { // 提交失败:文件只会被绕过保存 API 的写入方改掉(或磁盘出错)。 - // `save_leased` 在租约内比对过快照,按事务语义回滚凭据。 - let restore = match prior { - Some(prior) => credential(CredentialOp::Restore(&destination, &prior)), - None => credential(CredentialOp::Forget(&destination)), - }; - return Err(match restore { - Ok(_) => QuickAddError::Io(error.to_string()), - Err(restore_error) => QuickAddError::Io(format!( - "{error}; rolling the password back failed too: {restore_error}" - )), + // `save_leased` 在租约内比对过快照,按事务语义处理凭据——本次写过 + // 密码的,有旧值恢复旧值、没有旧值删掉本次写入;本次没写过的不碰 + // 凭据,只报提交错误。 + return Err(match written_password { + Some(prior) => { + let restore = match prior { + Some(prior) => credential(CredentialOp::Restore(&destination, &prior)), + None => credential(CredentialOp::Forget(&destination)), + }; + match restore { + Ok(_) => QuickAddError::Io(error.to_string()), + Err(restore_error) => QuickAddError::Io(format!( + "{error}; rolling the password back failed too: {restore_error}" + )), + } + }, + None => QuickAddError::Io(error.to_string()), }); } Ok(destination) diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs index 3db65d40b..b6e7294d9 100644 --- a/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs @@ -269,6 +269,80 @@ fn quick_add_commit_failure_rolls_the_password_back(cx: &mut gpui::TestAppContex } } +/// 提交失败但本次没写过密码:自动认证与密码留空的保存不得碰凭据—— +/// 目的地原有的密码不是这次写的,回滚删除就是替用户清库。提交失败用 +/// 维护者的注入方式复现:预置锁文件后目录只读,租约照常取得,落盘的 +/// 临时文件建不出来。目录权限在 Windows 上不拦截建文件,这条只在 +/// Unix 上跑。 +#[cfg(unix)] +#[gpui::test] +fn quick_add_commit_failure_without_a_password_write_keeps_the_existing_credential( + cx: &mut gpui::TestAppContext, +) { + use std::os::unix::fs::PermissionsExt as _; + let (mut state, cx) = init_and_build("core.example.cn", cx); + let directory = temp_profile_dir("rollback-no-write"); + let path = directory.join("ssh_profiles.json"); + // 库里先有另一台主机,目的地原有的密码只存在凭据库里。 + let mut seeded = crate::ssh_profiles::SshProfiles::default(); + seeded.upsert(crate::ssh_profiles::SshProfileAuth { + destination: "other@box.example".to_owned(), + auth: crate::ssh_profiles::SshAuthMode::Password, + private_keys: Vec::new(), + label: Some("Other box".to_owned()), + icon: None, + connection: crate::ssh_profiles::SshConnectionOptions::default(), + }); + seeded.save(&path).unwrap(); + // 预置锁文件:目录只读后,已有锁文件仍能打开加锁,落盘才会败在 + // 建临时文件这一步——正好是提交失败,而不是取租约失败。 + std::fs::write(path.with_extension("json.nebula-lock"), b"0").unwrap(); + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o555)).unwrap(); + + // 「本次没写密码」的两种保存:自动认证、密码认证但密码留空。 + for (name, auth) in [ + ("auto", crate::ssh_profiles::SshAuthMode::Auto), + ("empty-password", crate::ssh_profiles::SshAuthMode::Password), + ] { + cx.update(|window, cx| { + state.auth = auth; + state.password.update(cx, |input, cx| input.set_value("", window, cx)); + }); + let mut credentials = FakeCredentials::new(); + credentials.secrets.insert("root@core.example.cn".to_owned(), b"pre-existing".to_vec()); + let mut ops = Vec::new(); + cx.update(|_, cx| { + let error = persist_quick_add_with( + &state, + &path, + |op| { + ops.push(match op { + CredentialOp::Prior(_) => "prior", + CredentialOp::Store(..) => "store", + CredentialOp::Restore(..) => "restore", + CredentialOp::Forget(_) => "forget", + }); + credentials.call(op) + }, + cx, + ) + .unwrap_err(); + assert!(matches!(error, QuickAddError::Io(_)), "{name}: expected the commit error"); + }); + assert!( + ops.is_empty(), + "{name}: a save that writes no password must not touch credentials: {ops:?}" + ); + assert_eq!( + credentials.secrets.get("root@core.example.cn").map(Vec::as_slice), + Some(b"pre-existing".as_slice()), + "{name}: the existing credential must survive a failed commit it did not write" + ); + } + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o755)).unwrap(); + let _ = std::fs::remove_dir_all(&directory); +} + fn init_and_build<'a>( destination: &str, cx: &'a mut gpui::TestAppContext, From 9e69edb0093a34f2bf8f129de1a186f8ac7615d3 Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 09:58:05 +0800 Subject: [PATCH 5/6] test(ssh): keep the no-write rollback regression out of the platform cfg budget The unix-only injection carried a platform cfg attribute, and the platform-cfg budget outside platform/ only ever shrinks (459 -> 460 failed CI lint). Gate on the runtime OS constant instead, following the existing workspace test pattern, and go through the chmod binary for the read-only directory so the file compiles on every platform while the injection still only runs on Unix. --- .../workspace/ssh_quick_add/tests.rs | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs index b6e7294d9..b0aaafdc7 100644 --- a/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs @@ -272,16 +272,26 @@ fn quick_add_commit_failure_rolls_the_password_back(cx: &mut gpui::TestAppContex /// 提交失败但本次没写过密码:自动认证与密码留空的保存不得碰凭据—— /// 目的地原有的密码不是这次写的,回滚删除就是替用户清库。提交失败用 /// 维护者的注入方式复现:预置锁文件后目录只读,租约照常取得,落盘的 -/// 临时文件建不出来。目录权限在 Windows 上不拦截建文件,这条只在 -/// Unix 上跑。 -#[cfg(unix)] +/// 临时文件建不出来。目录权限在 Windows 上拦不住建文件,提交不会失败, +/// 所以注入只跑 Unix;用运行时判断而不是编译期平台属性,平台 cfg 预算 +/// 只能减不能增,chmod 走子进程,Windows 上不执行但全平台可编译。 #[gpui::test] fn quick_add_commit_failure_without_a_password_write_keeps_the_existing_credential( cx: &mut gpui::TestAppContext, ) { - use std::os::unix::fs::PermissionsExt as _; + if std::env::consts::OS == "windows" { + return; + } let (mut state, cx) = init_and_build("core.example.cn", cx); let directory = temp_profile_dir("rollback-no-write"); + let chmod = |mode: u32| { + let status = std::process::Command::new("chmod") + .arg(format!("{mode:o}")) + .arg(&directory) + .status() + .expect("run chmod"); + assert!(status.success(), "chmod {mode:o} on the profile directory failed: {status}"); + }; let path = directory.join("ssh_profiles.json"); // 库里先有另一台主机,目的地原有的密码只存在凭据库里。 let mut seeded = crate::ssh_profiles::SshProfiles::default(); @@ -297,7 +307,7 @@ fn quick_add_commit_failure_without_a_password_write_keeps_the_existing_credenti // 预置锁文件:目录只读后,已有锁文件仍能打开加锁,落盘才会败在 // 建临时文件这一步——正好是提交失败,而不是取租约失败。 std::fs::write(path.with_extension("json.nebula-lock"), b"0").unwrap(); - std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o555)).unwrap(); + chmod(0o555); // 「本次没写密码」的两种保存:自动认证、密码认证但密码留空。 for (name, auth) in [ @@ -339,7 +349,7 @@ fn quick_add_commit_failure_without_a_password_write_keeps_the_existing_credenti "{name}: the existing credential must survive a failed commit it did not write" ); } - std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o755)).unwrap(); + chmod(0o755); let _ = std::fs::remove_dir_all(&directory); } From f1a7e3bf9799278ea164ef4cbf3b29c00d69019c Mon Sep 17 00:00:00 2001 From: zher52 Date: Fri, 13 Nov 2026 12:57:03 +0800 Subject: [PATCH 6/6] fix(ssh): hand focus back to the terminal when quick-add is cancelled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Esc closed the overlay and left the host library untouched, but focus stayed with the dismissed overlay: the next typed command went nowhere until the user clicked the terminal first. The three cancel paths (Esc, the Cancel button, clicking the overlay mask) now funnel through cancel_ssh_quick_add, which hands focus back to the active pane via the workspace's focus_active. Save-and-connect and More-settings keep the old close_ssh_quick_add — the tab or settings page they open takes focus over itself, and the deferred refocus must not compete with it. The keyboard regression builds a real workspace over the terminal test fixture (a missing-shell pane with the test session) and pins the full chain: open the overlay from a focused terminal, Esc, focus is back on the terminal, then typing reaches the session as Msg::Input bytes. --- .../src/gpui_shell/workspace/ssh_quick_add.rs | 22 +++- .../workspace/ssh_quick_add/tests.rs | 118 ++++++++++++++++++ 2 files changed, 136 insertions(+), 4 deletions(-) diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs index b3bd7ef35..b5ecdb19e 100644 --- a/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add.rs @@ -268,6 +268,20 @@ impl NebulaWorkspace { } } + /// Esc / 取消按钮 / 点遮罩三条取消路径:收起浮层并把焦点交回活动 + /// 窗格。浮层开着时按键全被它吞掉,不还焦点的话,用户取消后接着敲 + /// 的命令会落进虚空,得先点一下终端才能输入。 + pub(super) fn cancel_ssh_quick_add( + &mut self, + window: &mut Window, + cx: &mut gpui::Context, + ) { + if self.ssh_quick_add.take().is_some() { + self.focus_active(window, cx); + cx.notify(); + } + } + /// 把浮层里的草稿写进主机库并保存密码;成功返回规范化 destination。 /// 目的地已保存时原样复用既有 profile(不写库、不动凭据),同样返回 /// destination 供连接。与连接分开,测试可以只验证落盘而不真的建 SSH 会话。 @@ -506,12 +520,12 @@ impl NebulaWorkspace { .bg(theme.overlay) .on_mouse_down( gpui::MouseButton::Left, - cx.listener(|this, _, _, cx| this.close_ssh_quick_add(cx)), + cx.listener(|this, _, window, cx| this.cancel_ssh_quick_add(window, cx)), ) .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { match event.keystroke.key.as_str() { "escape" => { - this.close_ssh_quick_add(cx); + this.cancel_ssh_quick_add(window, cx); cx.stop_propagation(); }, "enter" if !event.keystroke.modifiers.shift => { @@ -562,8 +576,8 @@ impl NebulaWorkspace { .label(language.text(Message::CommonCancel)) .ghost() .small() - .on_click(cx.listener(|this, _, _, cx| { - this.close_ssh_quick_add(cx) + .on_click(cx.listener(|this, _, window, cx| { + this.cancel_ssh_quick_add(window, cx) })), ) .child( diff --git a/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs b/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs index b0aaafdc7..c63bd05e9 100644 --- a/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs +++ b/nebula_app/src/gpui_shell/workspace/ssh_quick_add/tests.rs @@ -353,6 +353,124 @@ fn quick_add_commit_failure_without_a_password_write_keeps_the_existing_credenti let _ = std::fs::remove_dir_all(&directory); } +/// 工作区级键盘回归(审查实测的路径):终端聚焦时打开「添加并连接」, +/// Esc 取消后焦点必须回到终端,接着敲的命令要进终端。构建复用终端夹具 +/// (open_painted_workspace 同款的最小形态):一个终端 pane,shell 指向 +/// 不存在的可执行文件(没有真实 PTY 输出),会话换成 test_session——键 +/// 入以 `Msg::Input` 落到通道接收端,「终端收到输入」可以字面断言。 +#[gpui::test] +fn quick_add_cancel_returns_focus_and_the_next_command_reaches_the_terminal( + cx: &mut gpui::TestAppContext, +) { + cx.update(|cx| { + crate::gpui_shell::init(cx, Default::default()); + crate::gpui_shell::workspace::windowing::initialize( + cx, + crate::runtime_api::RuntimeHub::new(), + ); + cx.set_reduce_motion(true); + }); + let mut workspace_entity = None; + let mut receiver = None; + let mut terminal_focus = None; + let (_, mut window) = cx.add_window_view(|window, cx| { + let entity = cx.new(|cx| { + let mut workspace = NebulaWorkspace::new( + window, + None, + None, + 1, + crate::runtime_api::RuntimeHub::new(), + crate::gpui_shell::workspace::windowing::WorkspaceStartup::Empty, + crate::gpui_shell::workspace::windowing::WindowRole::Regular, + cx, + ); + let pane = workspace.new_pane( + (80, 24), + crate::gpui_shell::terminal::view::TerminalLaunch::Local { + cwd: None, + shell: Some(nebula_terminal::tty::Shell::new( + "pebrel-test-missing-shell-executable".into(), + vec![], + )), + shell_name: None, + }, + None, + window, + cx, + ); + receiver = Some(pane.view.update(cx, |view, _| view.install_completion_test_session())); + let pane_id = pane.id; + workspace.tabs.push(crate::gpui_shell::workspace::WorkspaceTab::Terminal { + panes: vec![pane], + tree: nebula_split::SplitTree::Leaf(pane_id), + focused: pane_id, + zoomed: false, + broadcast: false, + }); + workspace.tab_meta.push(crate::gpui_shell::workspace::TabMeta::default()); + let focus = workspace.tabs[0] + .focused_view() + .expect("terminal pane") + .read(cx) + .focus_handle + .clone(); + window.focus(&focus, cx); + terminal_focus = Some(focus); + workspace + }); + workspace_entity = Some(entity.clone()); + gpui_component::Root::new(entity, window, cx) + }); + let workspace_entity = workspace_entity.expect("workspace built"); + window.update(|window, _| window.activate_window()); + window.run_until_parked(); + + // 用户正在终端里,启动器搜索未命中回车 → 浮层打开,焦点进地址框。 + window.update(|window, cx| { + workspace_entity.update(cx, |workspace, cx| { + workspace.open_ssh_quick_add("core.example.cn".to_owned(), window, cx); + }); + }); + window.update(|window, _| { + assert!( + !terminal_focus.as_ref().expect("terminal focus").is_focused(window), + "浮层打开后焦点应在表单地址框" + ); + }); + + // Esc 取消:浮层收起,焦点交回活动窗格的终端。 + window.simulate_keystrokes("escape"); + draw(&mut window); + window.update(|window, _| { + assert!( + terminal_focus.as_ref().expect("terminal focus").is_focused(window), + "Esc 取消后焦点必须回到终端" + ); + }); + + // 不点鼠标直接敲命令:终端必须收到这次输入(空格是 keystroke 分隔符, + // 字面空格要用 space 键名)。 + window.simulate_keystrokes("echo space hi"); + let mut input = Vec::new(); + while let Ok(message) = receiver.as_ref().expect("test session").try_recv() { + if let nebula_terminal::event_loop::Msg::Input(bytes) = message { + input.extend_from_slice(&bytes); + } + } + assert!( + input.windows("echo hi".len()).any(|chunk| chunk == b"echo hi"), + "取消后键入的命令必须到达终端: {input:?}" + ); +} + +fn draw(cx: &mut gpui::VisualTestContext) { + cx.update(|window, cx| { + let _ = window.draw(cx); + }); + cx.run_until_parked(); +} + fn init_and_build<'a>( destination: &str, cx: &'a mut gpui::TestAppContext,