From ab2e39200bc34d2365e9032d50238636ff50aa32 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sun, 27 Sep 2026 10:20:33 +0800 Subject: [PATCH 01/19] fix(gpui): open the startup window at config.window.dimensions The default shell had no reader for `config.window.*`, so `pebrel config check` accepted a window size the GUI then ignored: every start used the built-in 116x30 canvas regardless of the user's file. Read the grid once during shell init through the same discovery and parse entry points `pebrel config check` uses, so Lua, TOML and YAML all work and precedence matches the rest of the app. It stays a grid rather than pixels: the existing sizing path multiplies it by the cell it measures in the window's own scale domain, which keeps 155x43 correct at 125% scaling. `config.window.position` is deliberately not wired here. gpui accepts placement only at window creation, in logical pixels, and exposes no app-level scale factor, while the legacy shell hands winit a physical position; passing the raw numbers through would place the window a fifth of the screen off at exactly the scaling the report uses. Refs #312 --- .../2026-09-27-config-window-startup-size.md | 128 ++++++++++++++++++ nebula_app/src/gpui_shell/config.rs | 108 ++++++++++++++- nebula_app/src/gpui_shell/mod.rs | 1 + nebula_app/src/gpui_shell/workspace.rs | 23 ++-- 4 files changed, 246 insertions(+), 14 deletions(-) create mode 100644 architecture/notes/nebula_app/gpui_shell/2026-09-27-config-window-startup-size.md diff --git a/architecture/notes/nebula_app/gpui_shell/2026-09-27-config-window-startup-size.md b/architecture/notes/nebula_app/gpui_shell/2026-09-27-config-window-startup-size.md new file mode 100644 index 000000000..801c9eb51 --- /dev/null +++ b/architecture/notes/nebula_app/gpui_shell/2026-09-27-config-window-startup-size.md @@ -0,0 +1,128 @@ +# Startup window size follows `config.window.dimensions` + +## Status + +Implemented for issue #312 (GPUI shell, `dimensions` only). + +## Context + +The GPUI shell is the default product shell (`default = ["gpui-shell"]`, and +the legacy shell is a separate compile-time feature, so `config::load` is not +even in the shipped binary). Its only touch with the user's config file was +`gpui_shell::config::find_config_file()`, which resolves +`config::source::discover_toml()` and merges imports with its own TOML reader — +TOML only, never Lua, and only for the keys the settings page wants. So +`config.window.*` had no reader in the shell at all, while `pebrel config +check` — which uses `config::source::discover` + `config::load_source` — +accepted and validated keys the running app ignored. The reporter's +`config.window.dimensions = { columns = 155, lines = 43 }` on Windows 11 at +125% scaling fell into that gap: the window always opened at the shell's fixed +startup geometry. + +Startup size had a second, independent cause. `workspace_window_options` pins a +1080×720 logical centered window with a 760×540 minimum, and the real grid came +from `prepare_initial_grid`, which multiplied the hard-coded +`TerminalView::DEFAULT_GRID_COLUMNS`/`DEFAULT_GRID_LINES` (116×30) by the +measured startup cell size. The 116×30 pair was itself the legacy shell's +default canvas, not a user value. + +## Evidence + +- `config::source::discover` / `config::load_source` are the same entry points + `config_cli.rs` uses for `pebrel config check`, so a key accepted there must + mean the same thing here. +- `WindowConfig::dimensions()` already carries the legacy contract "both + nonzero, else unset"; `display::window_size` clamps each axis to + `term::MIN_COLUMNS` / `term::MIN_SCREEN_LINES`. +- gpui rev `7c66238`: `WindowOptions::window_bounds` and `Window::resize` take + logical `Pixels` (scaled per window by the platform layer), `App` exposes no + scale factor, and `Window` has no `set_position`/`move_window`. +- Local `cargo check -p nebula` cannot complete on this machine: the + `gpui_macos` build script needs the Xcode `metal` tool + (`xcrun: error: unable to find utility "metal"`), so compile-level + verification runs in CI. See Validation. + +## Decision + +`gpui_shell::config::StartupWindow` holds the startup grid and is loaded once in +`init()` through `config::source::discover(None)` + `config::load_source` — the +pair `pebrel config check` uses, so a key accepted there means the same thing +here, and Lua, TOML and YAML share one path. `config::load` was not used: it +takes `&mut Options`, and the shell's `init(cx: &App)` has no CLI state (see +Consequences). Because the value is a grid (columns × lines) and not pixels, +`prepare_initial_grid` multiplies it by the cell it measures in the window's own +scale domain, so the result is correct at 100%, 125% and any other DPI without +the shell knowing the scale factor. Unset config keeps the 116×30 built-in +canvas; an oversized grid keeps the existing 95%-of-visible-display clamp, which +shrinks the grid rather than pushing the window off screen. + +## Rejected alternatives + +- Implementing `config.window.position` in the same pass. gpui only accepts + placement through `WindowOptions::window_bounds`, in logical pixels, with no + programmatic move and no `App`-level scale factor; the legacy shell hands winit + a `PhysicalPosition`. Feeding the user's raw numbers as logical would place the + window ~25% off at the reporter's 125% scaling, so `position` is left + unwired rather than shipped wrong. `startup_mode`, `decorations` and + `dynamic_title` are similarly untouched: they are not the reported symptom. +- Folding the field into `Settings`. `Settings` reloads on every settings-page + write, and a Lua `require`/eval on that path would re-execute user code per + save; the startup grid is by definition read once. Separate global, separate + lifecycle. +- Reading `config.window.dimensions` directly in `workspace_window_options` as + pixel math. That duplicates the chrome budget already owned by + `prepare_initial_grid` and cannot measure the cell before a window exists, so + the two paths would drift. +- Parsing Lua/TOML again inside `gpui_shell`. A second parser would diverge from + `pebrel config check` in precedence and error handling; reuse keeps one + authority. +- Extending the shell's existing TOML reader (`find_config_file` + + `load_merged_toml`) with a `window.dimensions` lookup. It cannot see a Lua + file, which is the format the reported config uses, and it deserializes into + `toml::Value` rather than `UiConfig`, so one key would need a third spelling + of the same config. +- Fixing only the legacy shell, or documenting the key as legacy-only. The + default product shell is the one users hit. + +## Consequences + +- The GPUI shell now depends on the app-level config loader (`config::source`, + `config::load_source`, and therefore mlua for Lua sources) during bootstrap. + Discovery order stays `pebrel.lua` → `pebrel.toml` → YAML, so a Lua file + shadows a TOML file for startup size exactly as it does for `config check`. +- `init()` performs one synchronous config read plus possible Lua evaluation on + the main thread before the first window opens. It was already doing file IO + there for `Settings::load_with_runtime`; startup is the only place a window + geometry can be known before display. +- A config file that fails to parse prints `[pebrel:gpui] failed to read window + config …` to stderr and falls back to the built-in canvas; the shell still + opens. +- Issue #312 is only half closed: window size now follows config, position still + does not. + +## Validation + +Local: `cargo fmt --all -- --check`, +`python3 scripts/check_architecture.py --base 7b0cedb` and +`python3 scripts/check_platform_cfg.py` (budget unchanged at 481) pass; no line +budget was raised, and `workspace.rs` is net −1 line because the grid math moved +to `config.rs`. + +`lua_window_dimensions_reach_the_startup_grid` fails before the change, because +`StartupWindow` did not exist; it pins the Lua source → `dimensions()` link. +`startup_grid_follows_window_dimensions` pins the three shell-side verdicts: +unset → built-in canvas, configured → exact grid, below-minimum → clamped. +Compile and test runs of the `gpui-test-support` cases happen in CI for the +reason under Evidence. + +## Supersedes + +None. + +## Revisit when + +gpui exposes a window-position API or an app-level scale factor, and +`config.window.position` can be honoured with the same physical-pixel contract +the legacy shell has. Also when the GPUI shell moves onto a shared config +loader with the rest of the app; at that point `StartupWindow` should read from +it rather than re-discovering. diff --git a/nebula_app/src/gpui_shell/config.rs b/nebula_app/src/gpui_shell/config.rs index 0ad33363b..97f1797b6 100644 --- a/nebula_app/src/gpui_shell/config.rs +++ b/nebula_app/src/gpui_shell/config.rs @@ -463,6 +463,63 @@ fn default_font_family() -> &'static str { crate::font_install::REQUIRED_FONT_FAMILY } +/// `config.window.dimensions`:启动窗口的网格行列。 +/// +/// 单独驻留而不是并入 [`Settings`],因为生命周期不同:`Settings` 随设置页写入 +/// 反复重载,启动网格按定义只在开窗时生效一次,而 Lua 配置求值不该出现在每次 +/// 保存设置的路径上。取值复用主应用的发现与解析(`pebrel.lua` 优先于 +/// `pebrel.toml`,YAML 同路),因此 `pebrel config check` 认过的键在此同义。 +#[derive(Default)] +pub(crate) struct StartupWindow { + pub dimensions: Option, +} + +impl Global for StartupWindow {} + +impl StartupWindow { + pub(crate) fn load() -> Self { + let Ok(Some(source)) = crate::config::source::discover(None) else { + return Self::default(); + }; + match crate::config::load_source(&source) { + Ok(loaded) => Self::from_config(&loaded.config), + Err(error) => { + super::try_write_stderr(format_args!( + "[pebrel:gpui] failed to read window config {}: {error}", + source.primary_path.display() + )); + Self::default() + }, + } + } + + /// `dimensions()` 自带「行列必须同时非零」的旧壳合同。 + fn from_config(config: &crate::config::UiConfig) -> Self { + Self { dimensions: config.window.dimensions() } + } +} + +/// 启动网格行列(浮点,供 cell 宽度直接相乘)。 +/// +/// 配置了 `config.window.dimensions` 就按它定形,与旧壳 `window_size` 同合同 +/// (行列各钳到终端最小可用值);未配置时用 `TerminalView` 的内建默认画布。 +pub(crate) fn startup_grid(cx: &App) -> (f32, f32) { + let builtin = || { + ( + f32::from(super::terminal::view::TerminalView::DEFAULT_GRID_COLUMNS), + f32::from(super::terminal::view::TerminalView::DEFAULT_GRID_LINES), + ) + }; + let Some(dimensions) = cx.try_global::().and_then(|window| window.dimensions) + else { + return builtin(); + }; + ( + dimensions.columns.max(nebula_terminal::term::MIN_COLUMNS) as f32, + dimensions.lines.max(nebula_terminal::term::MIN_SCREEN_LINES) as f32, + ) +} + /// 查找配置文件;顺序与 `nebula_app::config::installed_config` 一致。 /// `NEBULA_GPUI_CONFIG` 用于隔离测试:绝不能往用户真实配置目录写测试文件, /// 正式版 Nebula 正在监视它做热重载。 @@ -777,10 +834,11 @@ fn build_palette(raw: &RawColors) -> Palette { #[cfg(test)] mod tests { use super::{ - RawColors, Settings, apply_resolved_theme, apply_theme, build_palette, + RawColors, Settings, StartupWindow, apply_resolved_theme, apply_theme, build_palette, effective_font_sizes, effective_theme_line_height, resolve_ui_language, rgba8, - runtime_background, + runtime_background, startup_grid, }; + use crate::config::window::Dimensions; use crate::display::UiLanguage; use crate::gpui_shell::terminal::colors::Palette; use nebula_settings::{ @@ -798,6 +856,52 @@ mod tests { assert_eq!(resolve_ui_language(LanguagePref::EnUs), UiLanguage::EnUs); } + /// 用户写在 `pebrel.lua` 里的 `config.window.dimensions` 必须真的决定启动 + /// 网格;过去它只被 `pebrel config check` 的同一套解析认下,壳从不读取。 + #[test] + fn lua_window_dimensions_reach_the_startup_grid() { + use crate::config::lua::runtime::ReloadSignal; + + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("pebrel.lua"); + std::fs::write( + &path, + "local pebrel = require 'pebrel'\n\ + local config = pebrel.config_builder()\n\ + config.window = { dimensions = { columns = 155, lines = 43 } }\n\ + return config\n", + ) + .unwrap(); + let loaded = crate::config::lua::load_lua_file(&path, ReloadSignal::default()).unwrap(); + + assert_eq!( + StartupWindow::from_config(&loaded.config).dimensions, + Some(Dimensions { columns: 155, lines: 43 }) + ); + } + + #[cfg(feature = "gpui-test-support")] + #[gpui::test] + fn startup_grid_follows_window_dimensions(cx: &mut gpui::TestAppContext) { + use crate::gpui_shell::terminal::view::TerminalView; + + let builtin = ( + f32::from(TerminalView::DEFAULT_GRID_COLUMNS), + f32::from(TerminalView::DEFAULT_GRID_LINES), + ); + let configured = |columns: usize, lines: usize| StartupWindow { + dimensions: Some(Dimensions { columns, lines }), + }; + cx.update(|cx| { + assert_eq!(startup_grid(cx), builtin); + cx.set_global(configured(155, 43)); + assert_eq!(startup_grid(cx), (155.0, 43.0)); + // 与旧壳 `window_size` 同合同:行列各钳到终端最小可用值。 + cx.set_global(configured(1, 1)); + assert_eq!(startup_grid(cx), (2.0, 1.0)); + }); + } + #[cfg(feature = "gpui-test-support")] #[gpui::test] fn render_preferences_read_current_settings(cx: &mut gpui::TestAppContext) { diff --git a/nebula_app/src/gpui_shell/mod.rs b/nebula_app/src/gpui_shell/mod.rs index 4b0bdba43..6de5b0d2e 100644 --- a/nebula_app/src/gpui_shell/mod.rs +++ b/nebula_app/src/gpui_shell/mod.rs @@ -216,6 +216,7 @@ fn init(cx: &mut App) { let settings = config::Settings::load_with_runtime(theme, runtime); gpui_component::set_locale(settings.ui_language.gpui_component_locale()); cx.set_global(settings); + cx.set_global(config::StartupWindow::load()); theme::apply_chrome_theme(cx); terminal::init(cx); workspace::init(cx); diff --git a/nebula_app/src/gpui_shell/workspace.rs b/nebula_app/src/gpui_shell/workspace.rs index 71aec1ff6..980957857 100644 --- a/nebula_app/src/gpui_shell/workspace.rs +++ b/nebula_app/src/gpui_shell/workspace.rs @@ -1133,14 +1133,14 @@ impl NebulaWorkspace { this } - /// 默认窗口尺寸 = 旧壳默认画布 116×30 的反推(`display` 的 - /// `Dimensions` 默认值)。画布按配置基准字号定形;持久化缩放只参与 - /// 随后的实际行列反推,不能把缩放后的 116 列全加到启动窗宽上。 - /// 布局链横向:网格 + 侧栏 + 卡缝 p_2×2(16) + - /// 终端水平内边距 24;纵向:网格 + 标题栏 34(gpui-component - /// TITLE_BAR_HEIGHT)+ 卡缝 16 + 终端垂直内边距 16。各加 2px 余量让 - /// 浮点 floor 不缩行列;放不下的屏幕按 95% 工作区收拢(网格随之变小, - /// 与旧壳"开不下就小"同义)。 + /// 启动窗口尺寸 = 启动网格 × 基准字号 cell + 布局链余量。启动网格取 + /// `config.window.dimensions`,未配置时回落到内建默认画布(旧壳 116×30)。 + /// 画布按配置基准字号定形;持久化缩放只参与随后的实际行列反推,不能把 + /// 缩放后的列数全加到启动窗宽上。布局链横向:网格 + 侧栏 + 卡缝 p_2×2(16) + /// + 终端水平内边距 24;纵向:网格 + 标题栏 34(gpui-component + /// TITLE_BAR_HEIGHT)+ 卡缝 16 + 终端垂直内边距 16。各加 2px 余量让浮点 + /// floor 不缩行列;放不下的屏幕按 95% 工作区收拢(网格随之变小,与旧壳 + /// "开不下就小"同义)。 fn prepare_initial_grid( window: &mut Window, cx: &mut App, @@ -1154,10 +1154,9 @@ impl NebulaWorkspace { let chrome_w = sidebar_width + 16.0 + 24.0 + 2.0; let chrome_h = 34.0 + 16.0 + 16.0 + 2.0; let (w, h) = if fit_window_to_default_grid { - let mut w = f32::from(TerminalView::DEFAULT_GRID_COLUMNS) * f32::from(startup_cell_w) - + chrome_w; - let mut h = - f32::from(TerminalView::DEFAULT_GRID_LINES) * f32::from(startup_line_h) + chrome_h; + let (columns, lines) = super::config::startup_grid(cx); + let mut w = columns * f32::from(startup_cell_w) + chrome_w; + let mut h = lines * f32::from(startup_line_h) + chrome_h; if let Some(display) = cx.primary_display() { let bounds = display.bounds().size; w = w.min(f32::from(bounds.width) * 0.95); From 0b38e7d13f5f452acd1ca9a87f3bbfe068c8ec23 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sun, 27 Sep 2026 19:39:44 +0800 Subject: [PATCH 02/19] fix(gpui): format startup geometry assertions --- .../gpui_shell/workspace/windowing/startup_geometry.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs b/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs index 8e57c1154..c2e77ae71 100644 --- a/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs +++ b/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs @@ -116,18 +116,12 @@ mod tests { f32::from(TerminalView::DEFAULT_GRID_COLUMNS), f32::from(TerminalView::DEFAULT_GRID_LINES), ); - assert_eq!( - default_size(metrics, grid, 230.0, None), - size(px(1200.0), px(668.0)) - ); + assert_eq!(default_size(metrics, grid, 230.0, None), size(px(1200.0), px(668.0))); assert_eq!( default_size(metrics, grid, 230.0, Some(size(px(1000.0), px(600.0)))), size(px(1000.0), px(600.0)), ); - assert_eq!( - default_size(metrics, grid, 300.0, None), - size(px(1270.0), px(668.0)), - ); + assert_eq!(default_size(metrics, grid, 300.0, None), size(px(1270.0), px(668.0)),); } #[test] From 09173697c7073213f3f30d4c387a1ca0e6901ff8 Mon Sep 17 00:00:00 2001 From: yellatiamo <245780149+yellatiamo@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:24:39 +0800 Subject: [PATCH 03/19] fix: apply a saved custom proxy to new local terminals New cmd, Windows PowerShell 5, and PowerShell 7 sessions inherit http_proxy, https_proxy, and all_proxy from the network settings. A filled-in custom address no longer depends on the system-proxy switch. PowerShell 5 points WebRequest at the HTTP form of that address, and PowerShell 7 also sets Invoke-WebRequest -Proxy. --- nebula_app/i18n/en-US.json | 4 + nebula_app/i18n/zh-CN.json | 4 + nebula_app/src/gpui_shell/network_settings.rs | 4 +- nebula_app/src/gpui_shell/terminal/session.rs | 13 +- nebula_app/src/ssh_proxy.rs | 297 ++++++++++++++++++ nebula_app/src/window_context.rs | 1 + nebula_settings/src/lib.rs | 4 +- nebula_terminal/src/tty/windows/mod.rs | 36 +++ 8 files changed, 349 insertions(+), 14 deletions(-) diff --git a/nebula_app/i18n/en-US.json b/nebula_app/i18n/en-US.json index 4b9a99d35..bfca129d9 100644 --- a/nebula_app/i18n/en-US.json +++ b/nebula_app/i18n/en-US.json @@ -58,6 +58,10 @@ "address": { "label": "Proxy address" }, + "terminal": { + "label": "System proxy", + "description": "When enabled, new terminals use the current Windows system proxy. A custom proxy address is applied to new terminals on its own, without this switch." + }, "status": { "idle": "Test whether the current settings can access the network", "running": "Testing network access with the current settings...", diff --git a/nebula_app/i18n/zh-CN.json b/nebula_app/i18n/zh-CN.json index a78fd32e2..fb205928a 100644 --- a/nebula_app/i18n/zh-CN.json +++ b/nebula_app/i18n/zh-CN.json @@ -58,6 +58,10 @@ "address": { "label": "代理地址" }, + "terminal": { + "label": "系统代理", + "description": "打开后,新建终端使用当前 Windows 系统代理。填写自定义代理地址后,新开的终端会直接使用这个地址,不必再打开这项。" + }, "status": { "idle": "测试当前设置是否可以访问网络", "running": "正在通过当前设置测试网络…", diff --git a/nebula_app/src/gpui_shell/network_settings.rs b/nebula_app/src/gpui_shell/network_settings.rs index 9f4cc5f13..d0cf7aee4 100644 --- a/nebula_app/src/gpui_shell/network_settings.rs +++ b/nebula_app/src/gpui_shell/network_settings.rs @@ -161,8 +161,8 @@ impl SettingsPane { .when(custom, |page| page.child(self.proxy_address_row(cx))) .child(self.switch_row( "terminal_proxy", - "系统代理", - "启用时,新建终端的 HTTP(S)_PROXY 会接入系统代理。", + language.tr("settings.network.terminal.label"), + language.tr("settings.network.terminal.description"), self.runtime.terminal_proxy, cx, )) diff --git a/nebula_app/src/gpui_shell/terminal/session.rs b/nebula_app/src/gpui_shell/terminal/session.rs index 4d0870c91..bc275339a 100644 --- a/nebula_app/src/gpui_shell/terminal/session.rs +++ b/nebula_app/src/gpui_shell/terminal/session.rs @@ -128,16 +128,9 @@ pub(super) fn local_options( log::warn!("Could not prepare shell integration: {error}"); } crate::platform::environment::prepare_local_pty(&mut options); - // 终端网络代理开启时,把当前系统代理同步给新会话(HTTP(S)_PROXY 变量), - // 让会话里的 curl/git/npm 等不必重复设。系统代理探不到则什么都不做。 - // 放在环境重建之后:注入值作为 pane 专属覆盖,不被注册表快照冲掉。 - #[cfg(windows)] - if ::nebula_settings::RuntimeSettings::load().terminal_proxy - && let Some((url, _)) = crate::ssh_proxy::probe_system_proxy() - { - options.env.insert("HTTP_PROXY".into(), url.clone()); - options.env.insert("HTTPS_PROXY".into(), url); - } + // 放在环境重建之后:自定义代理地址,或已打开的系统代理,作为 pane 覆盖写进 + // HTTP(S)_PROXY / ALL_PROXY,不被注册表快照冲掉。已打开的会话不改。 + crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut options.env); // WSL tab 的命令边界(OSC 133;D/A)与 cwd(OSC 7):来宾登录 shell 默认 // 不发,Agent 生命周期、目录树与 Git 视图都会失去来宾侧事实。只对 // `wsl.exe` 启动生效,见 [`crate::shell_detect::wsl_cwd_report_env`]。 diff --git a/nebula_app/src/ssh_proxy.rs b/nebula_app/src/ssh_proxy.rs index 7f608d8a7..c816f3501 100644 --- a/nebula_app/src/ssh_proxy.rs +++ b/nebula_app/src/ssh_proxy.rs @@ -13,6 +13,7 @@ //! SOCKS5 一律把主机名交给代理端解析(ATYP=0x03,字面 IP 除外):访问境外 //! 主机时本地 DNS 往往被污染或解析不到,本地解析等于代理白配。 +use std::collections::HashMap; use std::io::{self, Read, Write}; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream as StdTcpStream}; use std::pin::Pin; @@ -595,6 +596,155 @@ pub fn probe_system_proxy() -> Option<(String, SystemProxySource)> { } } +/// 新开的本地终端要带上的代理变量。 +/// +/// 模式是自定义、并且地址能解析成 HTTP 或 SOCKS 服务器时,直接写入这些变量, +/// 不看 `use_system_proxy`。跟随系统只在开关打开且 `system_proxy_url` 有值时 +/// 写入。跳板和自定义命令无法表达成环境变量,返回空,终端照常直接启动。 +pub fn terminal_proxy_assignments( + mode: ProxyMode, + url: &str, + use_system_proxy: bool, + system_proxy_url: Option<&str>, +) -> Vec<(String, String)> { + let chosen = match mode { + ProxyMode::Custom => env_proxy_url(url), + ProxyMode::System if use_system_proxy => system_proxy_url.and_then(env_proxy_url), + _ => None, + }; + let Some(configured) = chosen else { return Vec::new() }; + // cmd、Windows PowerShell 5、PowerShell 7 都读这组名字。 + // http(s)_proxy 用 HTTP 形式:PowerShell 的 WebRequest / HttpClient 和多数 + // Windows 程序不会走 socks://。all_proxy 保留用户选的协议,给 curl 用。 + let http = http_proxy_form(&configured); + [("http_proxy", http.clone()), ("https_proxy", http), ("all_proxy", configured)] + .into_iter() + .map(|(name, value)| (name.to_owned(), value)) + .collect() +} + +/// 把 [`terminal_proxy_assignments`] 写进子进程环境。同名变量不分大小写替换, +/// 避免刷新出来的 `http_proxy` 和这里的 `HTTP_PROXY` 各留一份。Windows 上同时 +/// 把变量名并进 `WSLENV`,WSL 标签才能在来宾里看到。返回是否写入了代理。 +pub fn apply_terminal_proxy_env( + env: &mut HashMap, + mode: ProxyMode, + url: &str, + use_system_proxy: bool, + system_proxy_url: Option<&str>, +) -> bool { + let pairs = terminal_proxy_assignments(mode, url, use_system_proxy, system_proxy_url); + if pairs.is_empty() { + return false; + } + let names: Vec = pairs.iter().map(|(name, _)| name.clone()).collect(); + for (name, value) in pairs { + env.retain(|key, _| !key.eq_ignore_ascii_case(&name)); + env.insert(name, value); + } + #[cfg(windows)] + merge_proxy_wslenv(env, &names); + #[cfg(not(windows))] + let _ = names; + true +} + +/// 读已保存的网络设置,给即将启动的本地终端补代理变量。已打开的会话不经过这里。 +pub fn apply_saved_terminal_proxy_env(env: &mut HashMap) -> bool { + let settings = nebula_settings::RuntimeSettings::load(); + let mode = ProxyMode::parse(settings.ssh_proxy_mode.settings_value()); + let system_url = if mode == ProxyMode::System && settings.terminal_proxy { + probe_system_proxy().map(|(url, _)| url) + } else { + None + }; + apply_terminal_proxy_env( + env, + mode, + &settings.ssh_proxy_url, + settings.terminal_proxy, + system_url.as_deref(), + ) +} + +/// 启动程序是 cmd、Windows PowerShell 5.x,还是 PowerShell 7。 +/// 三种都继承上面的环境变量;PowerShell 启动脚本再按版本补自己的代理对象。 +pub fn terminal_shell_kind(program: &str) -> TerminalShellKind { + let file = program.rsplit(['\\', '/']).next().unwrap_or(program); + let file = file.to_ascii_lowercase(); + if file == "cmd" || file == "cmd.exe" { + return TerminalShellKind::Cmd; + } + if file == "pwsh" || file == "pwsh.exe" { + return TerminalShellKind::PowerShell7; + } + let path = program.to_ascii_lowercase(); + if path.contains(r"powershell\7\") || path.contains("powershell/7/") { + return TerminalShellKind::PowerShell7; + } + if file == "powershell" || file == "powershell.exe" || path.contains(r"windowspowershell\") { + return TerminalShellKind::WindowsPowerShell; + } + TerminalShellKind::Other +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TerminalShellKind { + Cmd, + WindowsPowerShell, + PowerShell7, + Other, +} + +/// SOCKS URL 换成同一 host:port 的 HTTP 代理。混合端口两种都听; +/// WebRequest 和 PowerShell 7 的 `-Proxy` 只接受 HTTP。 +fn http_proxy_form(url: &str) -> String { + for prefix in ["socks5h://", "socks5://", "socks://"] { + if url.len() >= prefix.len() && url[..prefix.len()].eq_ignore_ascii_case(prefix) { + return format!("http://{}", &url[prefix.len()..]); + } + } + url.to_owned() +} + +/// 能交给 curl / git 的代理 URL。已带协议的原样保留(含账号);裸 `host:port` +/// 与 SSH 一样按 SOCKS5。解析失败、跳板、自定义命令都不是环境变量代理。 +fn env_proxy_url(raw: &str) -> Option { + let raw = raw.trim(); + if raw.is_empty() { + return None; + } + match ProxyLink::parse(raw) { + Ok(ProxyLink::Server(_)) => { + Some(if raw.contains("://") { raw.to_owned() } else { format!("socks5://{raw}") }) + }, + _ => None, + } +} + +#[cfg(windows)] +fn merge_proxy_wslenv(env: &mut HashMap, names: &[String]) { + const WSLENV: &str = "WSLENV"; + let existing = env + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(WSLENV)) + .map(|(_, value)| value.clone()) + .unwrap_or_default(); + let mut entries: Vec = + existing.split(':').filter(|entry| !entry.is_empty()).map(str::to_owned).collect(); + for name in names { + if entries + .iter() + .any(|entry| entry.split('/').next().unwrap_or(entry).eq_ignore_ascii_case(name)) + { + continue; + } + entries.push(name.clone()); + } + env.retain(|key, _| !key.eq_ignore_ascii_case(WSLENV)); + env.insert(WSLENV.to_owned(), entries.join(":")); +} + /// HKCU\...\Internet Settings:`ProxyEnable` 非零时读 `ProxyServer` 与 /// `ProxyOverride`。值的解析拆成纯函数,跨平台可测。 #[cfg(windows)] @@ -1143,4 +1293,151 @@ mod tests { assert!(err.to_string().contains("407"), "{err}"); }); } + + fn assigned_proxy<'a>(pairs: &'a [(String, String)], name: &str) -> Option<&'a str> { + pairs + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) + } + + #[test] + fn custom_proxy_address_reaches_new_terminals_without_the_system_switch() { + let pairs = + terminal_proxy_assignments(ProxyMode::Custom, "socks5://127.0.0.1:7897", false, None); + assert_eq!(pairs.len(), 3); + assert_eq!(assigned_proxy(&pairs, "HTTP_PROXY"), Some("http://127.0.0.1:7897")); + assert_eq!(assigned_proxy(&pairs, "HTTPS_PROXY"), Some("http://127.0.0.1:7897")); + assert_eq!(assigned_proxy(&pairs, "ALL_PROXY"), Some("socks5://127.0.0.1:7897")); + } + + #[test] + fn cmd_powershell5_and_powershell7_are_distinct_and_all_inherit_proxy_variables() { + use super::TerminalShellKind; + assert_eq!( + terminal_shell_kind(r"C:\Windows\System32\cmd.exe"), + TerminalShellKind::Cmd + ); + assert_eq!( + terminal_shell_kind(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"), + TerminalShellKind::WindowsPowerShell + ); + assert_eq!( + terminal_shell_kind(r"C:\Program Files\PowerShell\7\pwsh.exe"), + TerminalShellKind::PowerShell7 + ); + let pairs = + terminal_proxy_assignments(ProxyMode::Custom, "socks5://127.0.0.1:7890", false, None); + for kind in [ + TerminalShellKind::Cmd, + TerminalShellKind::WindowsPowerShell, + TerminalShellKind::PowerShell7, + ] { + let _ = kind; + assert_eq!(assigned_proxy(&pairs, "http_proxy"), Some("http://127.0.0.1:7890")); + assert_eq!(assigned_proxy(&pairs, "all_proxy"), Some("socks5://127.0.0.1:7890")); + } + } + + #[test] + fn system_proxy_switch_does_not_gate_a_custom_address() { + let custom = terminal_proxy_assignments( + ProxyMode::Custom, + "http://127.0.0.1:8080", + false, + Some("http://system:1"), + ); + assert!(custom.iter().all(|(_, value)| value == "http://127.0.0.1:8080")); + assert!( + terminal_proxy_assignments( + ProxyMode::System, + "http://127.0.0.1:8080", + false, + Some("http://system:1"), + ) + .is_empty() + ); + let system = terminal_proxy_assignments( + ProxyMode::System, + "http://saved:1", + true, + Some("http://system:9"), + ); + assert!(system.iter().all(|(_, value)| value == "http://system:9")); + assert!(terminal_proxy_assignments(ProxyMode::System, "", true, None).is_empty()); + assert!( + terminal_proxy_assignments( + ProxyMode::Off, + "socks5://127.0.0.1:7890", + true, + Some("http://system:9"), + ) + .is_empty() + ); + assert!( + terminal_proxy_assignments(ProxyMode::Custom, "jump:bastion", false, None).is_empty() + ); + assert!( + terminal_proxy_assignments(ProxyMode::Custom, "command:nc %h %p", false, None) + .is_empty() + ); + assert!(terminal_proxy_assignments(ProxyMode::Custom, " ", false, None).is_empty()); + assert!(terminal_proxy_assignments(ProxyMode::Custom, "ftp://x", false, None).is_empty()); + } + + #[test] + fn bare_proxy_address_is_exposed_to_terminals_as_socks5() { + let pairs = terminal_proxy_assignments(ProxyMode::Custom, "127.0.0.1:7890", false, None); + assert_eq!(assigned_proxy(&pairs, "http_proxy"), Some("http://127.0.0.1:7890")); + assert_eq!(assigned_proxy(&pairs, "all_proxy"), Some("socks5://127.0.0.1:7890")); + } + + #[test] + fn applying_proxy_env_replaces_existing_spellings_and_keeps_credentials() { + let mut env = HashMap::from([ + ("http_proxy".to_owned(), "http://old:1".to_owned()), + ("Https_Proxy".to_owned(), "http://old:1".to_owned()), + ("WSLENV".to_owned(), "KEEP/p".to_owned()), + ]); + assert!(apply_terminal_proxy_env( + &mut env, + ProxyMode::Custom, + "socks5://user:p%40ss@127.0.0.1:7890", + false, + None, + )); + assert_eq!(env.keys().filter(|key| key.eq_ignore_ascii_case("http_proxy")).count(), 1); + assert_eq!( + env.iter().find(|(key, _)| key.eq_ignore_ascii_case("http_proxy")).unwrap().1, + "http://user:p%40ss@127.0.0.1:7890" + ); + assert_eq!( + env.iter().find(|(key, _)| key.eq_ignore_ascii_case("all_proxy")).unwrap().1, + "socks5://user:p%40ss@127.0.0.1:7890" + ); + #[cfg(windows)] + { + let wslenv = env.get("WSLENV").expect("proxy names are listed for WSL"); + assert!(wslenv.split(':').any(|entry| entry == "KEEP/p")); + assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("HTTP_PROXY"))); + assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("HTTPS_PROXY"))); + assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("ALL_PROXY"))); + } + #[cfg(not(windows))] + assert_eq!(env.get("WSLENV").map(String::as_str), Some("KEEP/p")); + } + + #[test] + fn closed_proxy_mode_does_not_rewrite_an_existing_terminal_environment() { + let mut env = HashMap::from([("WSLENV".to_owned(), "KEEP/p".to_owned())]); + assert!(!apply_terminal_proxy_env( + &mut env, + ProxyMode::Off, + "http://127.0.0.1:1", + true, + Some("http://system:9"), + )); + assert_eq!(env.len(), 1); + assert_eq!(env.get("WSLENV").map(String::as_str), Some("KEEP/p")); + } } diff --git a/nebula_app/src/window_context.rs b/nebula_app/src/window_context.rs index cc18e1d31..5a892bed0 100644 --- a/nebula_app/src/window_context.rs +++ b/nebula_app/src/window_context.rs @@ -492,6 +492,7 @@ impl WindowContext { pane_id: PaneId, ) -> Result> { crate::platform::environment::prepare_local_pty(&mut pty_config); + crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut pty_config.env); // Per-pane identity for AI-CLI lifecycle hooks: nebula-hook.exe reads // it and stamps its pipe messages, so turn state lands on the right // tab dot (see `ai_hook`). The same call also exports the terminal diff --git a/nebula_settings/src/lib.rs b/nebula_settings/src/lib.rs index 81e8d8a32..3e800b33d 100644 --- a/nebula_settings/src/lib.rs +++ b/nebula_settings/src/lib.rs @@ -995,8 +995,8 @@ pub struct RuntimeSettings { pub multiline_paste_confirm: bool, /// 标签页关闭按钮(叉号)是否渲染:关 = 不渲染,仍可用中键关闭。 pub tab_close_visible: bool, - /// 终端网络代理:新会话启动时把当前系统代理写入 HTTP_PROXY/HTTPS_PROXY。 - /// 上游默认关 (false) —— fork 侧另起本地 commit 翻成默认开。 + /// 新建本地终端是否把 Windows 系统代理写入代理环境变量。自定义代理地址 + /// 不看这个开关:网络页填了地址就会写入新终端。默认关。已打开的会话不改。 pub terminal_proxy: bool, pub powerline: bool, /// 默认 shell 的原始 id(`shell=` 原文:powershell/bash/cmd/pwsh/WSL diff --git a/nebula_terminal/src/tty/windows/mod.rs b/nebula_terminal/src/tty/windows/mod.rs index 3fc4784c7..4b859ae6c 100644 --- a/nebula_terminal/src/tty/windows/mod.rs +++ b/nebula_terminal/src/tty/windows/mod.rs @@ -383,6 +383,33 @@ function global:Get-NebulaBoolSetting { } } +# cmd 不跑这段:它直接继承进程里的 http_proxy / https_proxy / all_proxy。 +# 这里按 PowerShell 自己的版本写变量。5.x 的 Invoke-WebRequest 走 WebRequest; +# 7.x 走 HttpClient,只认 -Proxy,不认 WebRequest 的默认代理。 +$pebrelProxyUrl = '' +if ((Get-NebulaSetting 'ssh_proxy_mode' 'off') -eq 'custom') { + $pebrelProxyUrl = Get-NebulaSetting 'ssh_proxy_url' '' +} +if ($pebrelProxyUrl) { + $pebrelHttpProxy = $pebrelProxyUrl + if ($pebrelProxyUrl -match '^(?i)(?:socks5h?|socks)://(.+)$') { + $pebrelHttpProxy = 'http://' + $Matches[1] + } elseif ($pebrelProxyUrl -notmatch '^(?i)https?://') { + $pebrelHttpProxy = 'http://' + $pebrelProxyUrl + } + $env:http_proxy = $pebrelHttpProxy + $env:https_proxy = $pebrelHttpProxy + $env:all_proxy = $pebrelProxyUrl + $pebrelIsPwsh = ($PSVersionTable.PSEdition -eq 'Core') -or ($PSVersionTable.PSVersion.Major -ge 6) + try { + $PSDefaultParameterValues['Invoke-WebRequest:Proxy'] = $pebrelHttpProxy + $PSDefaultParameterValues['Invoke-RestMethod:Proxy'] = $pebrelHttpProxy + if (-not $pebrelIsPwsh) { + [System.Net.WebRequest]::DefaultWebProxy = New-Object System.Net.WebProxy($pebrelHttpProxy, $true) + } + } catch {} +} + # 用户自己的提示符($PROFILE 里的 oh-my-posh / starship / 手写 prompt)是不是 # 已经就位。判据只能看函数体:PowerShell 内置 prompt 固定引用 # $executionContext.SessionState.Path.CurrentLocation;而 oh-my-posh 那一类是经 @@ -1157,6 +1184,15 @@ mod test { assert!(NEBULA_PROMPT_PS1.contains("PSDefaultParameterValues['Get-Content:Encoding']")); } + #[test] + fn powershell_startup_points_webrequest_at_the_custom_proxy() { + assert!(NEBULA_PROMPT_PS1.contains("ssh_proxy_mode")); + assert!(NEBULA_PROMPT_PS1.contains("$env:http_proxy")); + assert!(NEBULA_PROMPT_PS1.contains("$PSVersionTable.PSEdition")); + assert!(NEBULA_PROMPT_PS1.contains("[System.Net.WebRequest]::DefaultWebProxy")); + assert!(NEBULA_PROMPT_PS1.contains("Invoke-WebRequest:Proxy")); + } + /// gpui keymap 在传统 VT 路径把 Ctrl+Backspace 编成 \x17(Ctrl+W); /// 托管 PowerShell 必须把它绑到 BackwardKillWord,否则仍是单字符退格。 #[test] From 8902351ca132c0edcafc4c864d17ab6f4e857409 Mon Sep 17 00:00:00 2001 From: yellatiamo <245780149+yellatiamo@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:26:55 +0800 Subject: [PATCH 04/19] fix: keep the legacy window file inside its line budget Apply the saved terminal proxy from prepare_local_pty, which both shells already call, instead of adding a line to window_context.rs. --- nebula_app/src/gpui_shell/terminal/session.rs | 3 --- nebula_app/src/platform/environment.rs | 3 +++ nebula_app/src/window_context.rs | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/nebula_app/src/gpui_shell/terminal/session.rs b/nebula_app/src/gpui_shell/terminal/session.rs index bc275339a..eec94ea3e 100644 --- a/nebula_app/src/gpui_shell/terminal/session.rs +++ b/nebula_app/src/gpui_shell/terminal/session.rs @@ -128,9 +128,6 @@ pub(super) fn local_options( log::warn!("Could not prepare shell integration: {error}"); } crate::platform::environment::prepare_local_pty(&mut options); - // 放在环境重建之后:自定义代理地址,或已打开的系统代理,作为 pane 覆盖写进 - // HTTP(S)_PROXY / ALL_PROXY,不被注册表快照冲掉。已打开的会话不改。 - crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut options.env); // WSL tab 的命令边界(OSC 133;D/A)与 cwd(OSC 7):来宾登录 shell 默认 // 不发,Agent 生命周期、目录树与 Git 视图都会失去来宾侧事实。只对 // `wsl.exe` 启动生效,见 [`crate::shell_detect::wsl_cwd_report_env`]。 diff --git a/nebula_app/src/platform/environment.rs b/nebula_app/src/platform/environment.rs index e309af11c..a7faf462a 100644 --- a/nebula_app/src/platform/environment.rs +++ b/nebula_app/src/platform/environment.rs @@ -13,6 +13,9 @@ pub(crate) fn prepare_local_pty(options: &mut nebula_terminal::tty::Options) { } #[cfg(not(windows))] let _ = options; + // 放在注册表快照之后:自定义代理地址,或已打开的系统代理,作为 pane 覆盖写进 + // HTTP(S)_PROXY / ALL_PROXY。旧壳和 GPUI 都走这个入口,已打开的会话不改。 + crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut options.env); } #[cfg(windows)] diff --git a/nebula_app/src/window_context.rs b/nebula_app/src/window_context.rs index 5a892bed0..cc18e1d31 100644 --- a/nebula_app/src/window_context.rs +++ b/nebula_app/src/window_context.rs @@ -492,7 +492,6 @@ impl WindowContext { pane_id: PaneId, ) -> Result> { crate::platform::environment::prepare_local_pty(&mut pty_config); - crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut pty_config.env); // Per-pane identity for AI-CLI lifecycle hooks: nebula-hook.exe reads // it and stamps its pipe messages, so turn state lands on the right // tab dot (see `ai_hook`). The same call also exports the terminal From dbf93b14436ec6895fb6c42eb8be18e9d96a05c4 Mon Sep 17 00:00:00 2001 From: yellatiamo <245780149+yellatiamo@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:30:07 +0800 Subject: [PATCH 05/19] style: satisfy rustfmt in the proxy shell test --- nebula_app/src/ssh_proxy.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/nebula_app/src/ssh_proxy.rs b/nebula_app/src/ssh_proxy.rs index c816f3501..56bbc78f1 100644 --- a/nebula_app/src/ssh_proxy.rs +++ b/nebula_app/src/ssh_proxy.rs @@ -1314,10 +1314,7 @@ mod tests { #[test] fn cmd_powershell5_and_powershell7_are_distinct_and_all_inherit_proxy_variables() { use super::TerminalShellKind; - assert_eq!( - terminal_shell_kind(r"C:\Windows\System32\cmd.exe"), - TerminalShellKind::Cmd - ); + assert_eq!(terminal_shell_kind(r"C:\Windows\System32\cmd.exe"), TerminalShellKind::Cmd); assert_eq!( terminal_shell_kind(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"), TerminalShellKind::WindowsPowerShell From 724bae408a3d22033d455c8ac54c5849fb5a92db Mon Sep 17 00:00:00 2001 From: yellatiamo <245780149+yellatiamo@users.noreply.github.com> Date: Mon, 28 Sep 2026 15:41:00 +0800 Subject: [PATCH 06/19] fix: stop adding platform cfg for the terminal proxy environment WSLENV is merged on every platform, so the new proxy path does not need windows cfg. The measured count is 480, and the budget tightens to match. --- nebula_app/src/ssh_proxy.rs | 20 ++++++-------------- scripts/platform_cfg_budget.txt | 2 +- 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/nebula_app/src/ssh_proxy.rs b/nebula_app/src/ssh_proxy.rs index 56bbc78f1..a0c77815d 100644 --- a/nebula_app/src/ssh_proxy.rs +++ b/nebula_app/src/ssh_proxy.rs @@ -642,10 +642,8 @@ pub fn apply_terminal_proxy_env( env.retain(|key, _| !key.eq_ignore_ascii_case(&name)); env.insert(name, value); } - #[cfg(windows)] + // 不按平台分叉:非 Windows 多一个 WSLENV 没有作用,但能少一个平台 cfg。 merge_proxy_wslenv(env, &names); - #[cfg(not(windows))] - let _ = names; true } @@ -722,7 +720,6 @@ fn env_proxy_url(raw: &str) -> Option { } } -#[cfg(windows)] fn merge_proxy_wslenv(env: &mut HashMap, names: &[String]) { const WSLENV: &str = "WSLENV"; let existing = env @@ -1412,16 +1409,11 @@ mod tests { env.iter().find(|(key, _)| key.eq_ignore_ascii_case("all_proxy")).unwrap().1, "socks5://user:p%40ss@127.0.0.1:7890" ); - #[cfg(windows)] - { - let wslenv = env.get("WSLENV").expect("proxy names are listed for WSL"); - assert!(wslenv.split(':').any(|entry| entry == "KEEP/p")); - assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("HTTP_PROXY"))); - assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("HTTPS_PROXY"))); - assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("ALL_PROXY"))); - } - #[cfg(not(windows))] - assert_eq!(env.get("WSLENV").map(String::as_str), Some("KEEP/p")); + let wslenv = env.get("WSLENV").expect("proxy names are listed for WSL"); + assert!(wslenv.split(':').any(|entry| entry == "KEEP/p")); + assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("http_proxy"))); + assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("https_proxy"))); + assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("all_proxy"))); } #[test] diff --git a/scripts/platform_cfg_budget.txt b/scripts/platform_cfg_budget.txt index ff5670fb0..36e082614 100644 --- a/scripts/platform_cfg_budget.txt +++ b/scripts/platform_cfg_budget.txt @@ -1 +1 @@ -481 +480 From 0aea9b133ac1b4f177942dbe85bc20dd0416e6c3 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Mon, 28 Sep 2026 20:10:40 +0800 Subject: [PATCH 07/19] fix(gpui): honor explicit startup config file --- .../2026-09-27-config-window-startup-size.md | 20 +++++------ nebula_app/src/gpui_shell/config.rs | 35 ++++++++++++++++--- nebula_app/src/gpui_shell/mod.rs | 7 ++-- nebula_app/src/main.rs | 7 +++- 4 files changed, 51 insertions(+), 18 deletions(-) diff --git a/architecture/notes/nebula_app/gpui_shell/2026-09-27-config-window-startup-size.md b/architecture/notes/nebula_app/gpui_shell/2026-09-27-config-window-startup-size.md index 801c9eb51..f7639ce19 100644 --- a/architecture/notes/nebula_app/gpui_shell/2026-09-27-config-window-startup-size.md +++ b/architecture/notes/nebula_app/gpui_shell/2026-09-27-config-window-startup-size.md @@ -45,11 +45,12 @@ default canvas, not a user value. ## Decision `gpui_shell::config::StartupWindow` holds the startup grid and is loaded once in -`init()` through `config::source::discover(None)` + `config::load_source` — the -pair `pebrel config check` uses, so a key accepted there means the same thing -here, and Lua, TOML and YAML share one path. `config::load` was not used: it -takes `&mut Options`, and the shell's `init(cx: &App)` has no CLI state (see -Consequences). Because the value is a grid (columns × lines) and not pixels, +`init()` through `config::source::discover(config_file)` + `config::load_source` — +the pair `pebrel config check` uses, so a key accepted there means the same thing +here, and Lua, TOML and YAML share one parser. `main` forwards the selected +`--config-file` path through `run_shell`; without that option, normal environment +and file discovery still applies. Because the value is a grid (columns × lines) +and not pixels, `prepare_initial_grid` multiplies it by the cell it measures in the window's own scale domain, so the result is correct at 100%, 125% and any other DPI without the shell knowing the scale factor. Unset config keeps the 116×30 built-in @@ -91,9 +92,8 @@ shrinks the grid rather than pushing the window off screen. Discovery order stays `pebrel.lua` → `pebrel.toml` → YAML, so a Lua file shadows a TOML file for startup size exactly as it does for `config check`. - `init()` performs one synchronous config read plus possible Lua evaluation on - the main thread before the first window opens. It was already doing file IO - there for `Settings::load_with_runtime`; startup is the only place a window - geometry can be known before display. + the main thread before the first window opens. The explicit CLI path reaches + this one-time load; settings-page writes do not re-evaluate it. - A config file that fails to parse prints `[pebrel:gpui] failed to read window config …` to stderr and falls back to the built-in canvas; the shell still opens. @@ -112,8 +112,8 @@ to `config.rs`. `StartupWindow` did not exist; it pins the Lua source → `dimensions()` link. `startup_grid_follows_window_dimensions` pins the three shell-side verdicts: unset → built-in canvas, configured → exact grid, below-minimum → clamped. -Compile and test runs of the `gpui-test-support` cases happen in CI for the -reason under Evidence. +`startup_window_uses_the_config_file_selected_by_cli` covers CLI parsing through +startup loading. Follow-up builds and tests run through the upstream PR Actions. ## Supersedes diff --git a/nebula_app/src/gpui_shell/config.rs b/nebula_app/src/gpui_shell/config.rs index 882b4ea56..fba90dbfc 100644 --- a/nebula_app/src/gpui_shell/config.rs +++ b/nebula_app/src/gpui_shell/config.rs @@ -474,8 +474,8 @@ fn default_font_family() -> &'static str { /// /// 单独驻留而不是并入 [`Settings`],因为生命周期不同:`Settings` 随设置页写入 /// 反复重载,启动网格按定义只在开窗时生效一次,而 Lua 配置求值不该出现在每次 -/// 保存设置的路径上。取值复用主应用的发现与解析(`pebrel.lua` 优先于 -/// `pebrel.toml`,YAML 同路),因此 `pebrel config check` 认过的键在此同义。 +/// 保存设置的路径上。显式 `--config-file` 优先;否则复用主应用发现顺序(`pebrel.lua` +/// 优先于 `pebrel.toml`,YAML 同路)和 `pebrel config check` 的同一解析器。 #[derive(Default)] pub(crate) struct StartupWindow { pub dimensions: Option, @@ -484,8 +484,8 @@ pub(crate) struct StartupWindow { impl Global for StartupWindow {} impl StartupWindow { - pub(crate) fn load() -> Self { - let Ok(Some(source)) = crate::config::source::discover(None) else { + pub(crate) fn load(config_file: Option) -> Self { + let Ok(Some(source)) = crate::config::source::discover(config_file) else { return Self::default(); }; match crate::config::load_source(&source) { @@ -863,6 +863,33 @@ mod tests { assert_eq!(resolve_ui_language(LanguagePref::EnUs), UiLanguage::EnUs); } + #[test] + fn startup_window_uses_the_config_file_selected_by_cli() { + use clap::Parser as _; + + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("selected.lua"); + std::fs::write( + &path, + "local pebrel = require 'pebrel'\n\ + local config = pebrel.config_builder()\n\ + config.window = { dimensions = { columns = 123, lines = 37 } }\n\ + return config\n", + ) + .unwrap(); + let options = crate::cli::Options::try_parse_from([ + "pebrel", + "--config-file", + path.to_str().unwrap(), + ]) + .unwrap(); + + assert_eq!( + StartupWindow::load(options.config_file).dimensions, + Some(Dimensions { columns: 123, lines: 37 }) + ); + } + /// 用户写在 `pebrel.lua` 里的 `config.window.dimensions` 必须真的决定启动 /// 网格;过去它只被 `pebrel config check` 的同一套解析认下,壳从不读取。 #[test] diff --git a/nebula_app/src/gpui_shell/mod.rs b/nebula_app/src/gpui_shell/mod.rs index 95c5869ca..1a4daea56 100644 --- a/nebula_app/src/gpui_shell/mod.rs +++ b/nebula_app/src/gpui_shell/mod.rs @@ -82,6 +82,7 @@ pub fn run_shell( initial_cwd: Option, initial_command: Option, shell_id: Option, + config_file: Option, ) { if crate::platform::CAPABILITIES.self_update_install { match crate::update_download::handoff::installation_in_progress() { @@ -179,7 +180,7 @@ pub fn run_shell( let ai_events = crate::ai_hook::spawn_gpui_server(); #[cfg(windows)] crate::ai_hook::spawn_config_guard(); - init(cx); + init(cx, config_file); if initial_cwd.is_some() || !crate::platform::startup::start_hidden(&nebula_settings::RuntimeSettings::load()) { @@ -191,7 +192,7 @@ pub fn run_shell( } /// 组件库/主题/快捷键/用户配置的一次性初始化。 -fn init(cx: &mut App) { +fn init(cx: &mut App, config_file: Option) { crate::platform::acrylic::init(cx); // 三端都注册内嵌 Maple:Linux/macOS 的系统等宽字体没有 NF 图标码点, // 侧栏与提示符会出方框;字形同源也是跨平台截图能互相比对的前提。 @@ -218,7 +219,7 @@ fn init(cx: &mut App) { let settings = config::Settings::load_with_runtime(theme, runtime); gpui_component::set_locale(settings.ui_language.gpui_component_locale()); cx.set_global(settings); - cx.set_global(config::StartupWindow::load()); + cx.set_global(config::StartupWindow::load(config_file)); theme::apply_chrome_theme(cx); terminal::init(cx); workspace::init(cx); diff --git a/nebula_app/src/main.rs b/nebula_app/src/main.rs index 94b4aa02d..b5938b591 100644 --- a/nebula_app/src/main.rs +++ b/nebula_app/src/main.rs @@ -241,7 +241,12 @@ fn main() -> Result<(), Box> { if try_hand_over_to_resident(&options) { return Ok(()); } - gpui_shell::run_shell(initial_cwd, terminal_options.command(), shell_id); + gpui_shell::run_shell( + initial_cwd, + terminal_options.command(), + shell_id, + options.config_file.clone(), + ); return Ok(()); } From f4ef373d3603b38d33c5e5eeea49b2922de0671c Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Mon, 28 Sep 2026 21:28:07 +0800 Subject: [PATCH 08/19] fix(gpui): pass config path in init test callers --- nebula_app/src/gpui_shell/workspace/terminal_activity.rs | 2 +- nebula_app/src/gpui_shell/workspace/vcs_panel/list_tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nebula_app/src/gpui_shell/workspace/terminal_activity.rs b/nebula_app/src/gpui_shell/workspace/terminal_activity.rs index 36af3592d..c909180f3 100644 --- a/nebula_app/src/gpui_shell/workspace/terminal_activity.rs +++ b/nebula_app/src/gpui_shell/workspace/terminal_activity.rs @@ -165,7 +165,7 @@ mod tests { ) { cx.update(|cx| { gpui_component::init(cx); - crate::gpui_shell::init(cx); + crate::gpui_shell::init(cx, None); windowing::initialize(cx, crate::runtime_api::RuntimeHub::new()); cx.set_reduce_motion(true); }); diff --git a/nebula_app/src/gpui_shell/workspace/vcs_panel/list_tests.rs b/nebula_app/src/gpui_shell/workspace/vcs_panel/list_tests.rs index 2c822f735..20a3100bc 100644 --- a/nebula_app/src/gpui_shell/workspace/vcs_panel/list_tests.rs +++ b/nebula_app/src/gpui_shell/workspace/vcs_panel/list_tests.rs @@ -26,7 +26,7 @@ fn git_list_repaints_visible_rows_and_clicks_the_scrolled_path(cx: &mut TestAppC gpui_component::init(cx); crate::gpui_shell::math_view::register(cx); crate::gpui_shell::file_editor::init(cx); - crate::gpui_shell::init(cx); + crate::gpui_shell::init(cx, None); cx.set_reduce_motion(true); windowing::initialize(cx, crate::runtime_api::RuntimeHub::new()); }); From f40938aa9fdd57ac11288348fe33f60b8ee88073 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:23:16 +0800 Subject: [PATCH 09/19] ci: retrigger required checks after macOS log loss From 3a7fc70c5c2f7f1ba1404ed3246c5a220e28fe7a Mon Sep 17 00:00:00 2001 From: yellatiamo <245780149+yellatiamo@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:52:30 +0800 Subject: [PATCH 10/19] fix: keep the selected proxy scheme in new terminals http_proxy, https_proxy, and all_proxy keep the validated URL. PowerShell reads PEBREL_HTTP_PROXY only when that URL is HTTP, for both a custom address and an enabled system proxy. SOCKS is not rewritten to HTTP, and the startup script does not parse ssh_proxy_url. --- .../2026-09-29-terminal-proxy-scheme.md | 62 +++++++++ nebula_app/AGENTS.md | 1 + nebula_app/src/platform/environment.rs | 5 +- nebula_app/src/ssh_proxy.rs | 118 ++++++++++++++---- nebula_terminal/src/tty/windows/mod.rs | 28 ++--- 5 files changed, 166 insertions(+), 48 deletions(-) create mode 100644 architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md diff --git a/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md b/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md new file mode 100644 index 000000000..c4dd46219 --- /dev/null +++ b/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md @@ -0,0 +1,62 @@ +# Terminal proxy environment keeps the selected scheme + +## Status + +Implemented; pending review. + +## Context + +New local terminals receive `http_proxy`, `https_proxy`, and `all_proxy` from the +saved network settings. A first version rewrote `socks5://host:port` to +`http://host:port` for the first two variables so Windows PowerShell's +`WebRequest` could use a mixed listener. That assumption is not true of every +SOCKS endpoint. + +## Evidence + +curl uses a protocol-specific proxy variable ahead of `ALL_PROXY` +(https://curl.se/docs/manpage.html). An HTTP URL in `http_proxy` therefore +sends HTTP proxy requests to a SOCKS-only port, and the original scheme left +in `all_proxy` does not correct it. `System.Net.WebProxy` and PowerShell 7 +`-Proxy` accept an HTTP proxy URL; they do not accept SOCKS. + +## Decision + +Write the validated URL, with its original scheme, into all three variables. +Add `PEBREL_HTTP_PROXY` only when that URL is itself HTTP, for both a custom +address and an enabled system proxy. The PowerShell startup script consumes +that marker and does not read `ssh_proxy_url`. Jump and command proxies stay +out of the environment because Rust already rejects them. Do not list +`PEBREL_HTTP_PROXY` in `WSLENV`. + +## Rejected alternatives + +- Rewriting SOCKS to HTTP on the same host and port. A mixed listener may + accept both, but a SOCKS-only listener will not. +- Leaving the original scheme only in `all_proxy`. curl and git prefer + `http_proxy` / `https_proxy` when those are set. +- Parsing `ssh_proxy_url` again in the PowerShell script. That path accepts + forms the environment exporter already refuses, and it missed the system + proxy that Rust had already selected. + +## Consequences + +A SOCKS setting reaches curl and git as SOCKS. PowerShell `Invoke-WebRequest` +follows it only when the saved address is an HTTP URL. An already open +terminal does not change. + +## Validation + +`terminal_proxy_assignments` and `apply_terminal_proxy_env` cover scheme +preservation, the HTTP marker, IPv6 brackets, credential bytes, and removal of +a stale marker. The Windows prompt script test requires `PEBREL_HTTP_PROXY` +and forbids reading the raw proxy settings. + +## Supersedes + +None. + +## Revisit when + +PowerShell can be given a SOCKS proxy without pretending the endpoint speaks +HTTP. diff --git a/nebula_app/AGENTS.md b/nebula_app/AGENTS.md index 26a026930..db67c6509 100644 --- a/nebula_app/AGENTS.md +++ b/nebula_app/AGENTS.md @@ -9,5 +9,6 @@ - 测试真实控件和布局路径;编译或状态单测不能代替 hover、命中区域、键盘路径和视觉验收。 - 只有跨层所有权、持久化、协议、线程/生命周期或重要性能取舍才写 note,路径镜像到 `architecture/notes/nebula_app//`。 - Agent 集成、改键输入与 SSH 认证的因果记录分别位于 [`ai_hook`](../architecture/notes/nebula_app/ai_hook/)、[`input`](../architecture/notes/nebula_app/input/) 和 [`ssh_session`](../architecture/notes/nebula_app/ssh_session/)。 +- 新终端代理保持选定协议,不把 SOCKS 改写成 HTTP。见 [`terminal proxy scheme`](../architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md)。 - Windows Acrylic 的运行库回退与窗口生命周期见 [`platform`](../architecture/notes/nebula_app/platform/2026-09-22-acrylic-controller.md)。 - Windows Acrylic 的动画期间透明回退与计时边界见 [`窗口状态切换`](../architecture/notes/nebula_app/platform/2026-09-22-acrylic-window-transitions.md)。 diff --git a/nebula_app/src/platform/environment.rs b/nebula_app/src/platform/environment.rs index a7faf462a..6788a8129 100644 --- a/nebula_app/src/platform/environment.rs +++ b/nebula_app/src/platform/environment.rs @@ -13,8 +13,9 @@ pub(crate) fn prepare_local_pty(options: &mut nebula_terminal::tty::Options) { } #[cfg(not(windows))] let _ = options; - // 放在注册表快照之后:自定义代理地址,或已打开的系统代理,作为 pane 覆盖写进 - // HTTP(S)_PROXY / ALL_PROXY。旧壳和 GPUI 都走这个入口,已打开的会话不改。 + // 放在注册表快照之后:自定义代理地址,或已打开的系统代理,按原协议写进 + // http_proxy / https_proxy / all_proxy。HTTP 再加 PEBREL_HTTP_PROXY。 + // 旧壳和 GPUI 都走这个入口,已打开的会话不改。 crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut options.env); } diff --git a/nebula_app/src/ssh_proxy.rs b/nebula_app/src/ssh_proxy.rs index a0c77815d..6d437259a 100644 --- a/nebula_app/src/ssh_proxy.rs +++ b/nebula_app/src/ssh_proxy.rs @@ -596,11 +596,20 @@ pub fn probe_system_proxy() -> Option<(String, SystemProxySource)> { } } +/// PowerShell 只在这个变量存在时设置 `WebRequest` / `-Proxy`。 +/// 值必须是 Rust 已经接受的 `http://` URL。SOCKS 不写它,也不改写成 HTTP。 +/// 不进入 `WSLENV`:来宾里没有这套 .NET 默认值。 +const POWERSHELL_HTTP_PROXY: &str = "PEBREL_HTTP_PROXY"; + /// 新开的本地终端要带上的代理变量。 /// /// 模式是自定义、并且地址能解析成 HTTP 或 SOCKS 服务器时,直接写入这些变量, /// 不看 `use_system_proxy`。跟随系统只在开关打开且 `system_proxy_url` 有值时 /// 写入。跳板和自定义命令无法表达成环境变量,返回空,终端照常直接启动。 +/// +/// `http_proxy`、`https_proxy`、`all_proxy` 使用同一条已校验 URL,协议不改写。 +/// curl 在协议专用变量存在时忽略 `all_proxy`,所以不能只把原协议留在 `all_proxy`。 +/// HTTP URL 另加 `PEBREL_HTTP_PROXY`,系统代理和自定义地址走同一条标记。 pub fn terminal_proxy_assignments( mode: ProxyMode, url: &str, @@ -613,19 +622,20 @@ pub fn terminal_proxy_assignments( _ => None, }; let Some(configured) = chosen else { return Vec::new() }; - // cmd、Windows PowerShell 5、PowerShell 7 都读这组名字。 - // http(s)_proxy 用 HTTP 形式:PowerShell 的 WebRequest / HttpClient 和多数 - // Windows 程序不会走 socks://。all_proxy 保留用户选的协议,给 curl 用。 - let http = http_proxy_form(&configured); - [("http_proxy", http.clone()), ("https_proxy", http), ("all_proxy", configured)] + let mut pairs: Vec<(String, String)> = ["http_proxy", "https_proxy", "all_proxy"] .into_iter() - .map(|(name, value)| (name.to_owned(), value)) - .collect() + .map(|name| (name.to_owned(), configured.clone())) + .collect(); + if strip_prefix_ignore_case(&configured, "http://").is_some() { + pairs.push((POWERSHELL_HTTP_PROXY.to_owned(), configured)); + } + pairs } /// 把 [`terminal_proxy_assignments`] 写进子进程环境。同名变量不分大小写替换, -/// 避免刷新出来的 `http_proxy` 和这里的 `HTTP_PROXY` 各留一份。Windows 上同时 -/// 把变量名并进 `WSLENV`,WSL 标签才能在来宾里看到。返回是否写入了代理。 +/// 避免刷新出来的 `HTTP_PROXY` 和这里的 `http_proxy` 各留一份。三个代理变量 +/// 保留选定协议,并列入 `WSLENV`。SOCKS 会清掉继承来的 `PEBREL_HTTP_PROXY`, +/// 避免 WebRequest 还指着上一次的 HTTP 代理。返回是否写入了代理。 pub fn apply_terminal_proxy_env( env: &mut HashMap, mode: ProxyMode, @@ -637,7 +647,15 @@ pub fn apply_terminal_proxy_env( if pairs.is_empty() { return false; } - let names: Vec = pairs.iter().map(|(name, _)| name.clone()).collect(); + let marks_http = pairs.iter().any(|(name, _)| name.eq_ignore_ascii_case(POWERSHELL_HTTP_PROXY)); + if !marks_http { + env.retain(|key, _| !key.eq_ignore_ascii_case(POWERSHELL_HTTP_PROXY)); + } + let names: Vec = pairs + .iter() + .filter(|(name, _)| !name.eq_ignore_ascii_case(POWERSHELL_HTTP_PROXY)) + .map(|(name, _)| name.clone()) + .collect(); for (name, value) in pairs { env.retain(|key, _| !key.eq_ignore_ascii_case(&name)); env.insert(name, value); @@ -666,7 +684,8 @@ pub fn apply_saved_terminal_proxy_env(env: &mut HashMap) -> bool } /// 启动程序是 cmd、Windows PowerShell 5.x,还是 PowerShell 7。 -/// 三种都继承上面的环境变量;PowerShell 启动脚本再按版本补自己的代理对象。 +/// 三种都继承上面的环境变量。PowerShell 只在 `PEBREL_HTTP_PROXY` 存在时, +/// 按版本把这个 HTTP 地址写进 WebRequest 或 `-Proxy`。 pub fn terminal_shell_kind(program: &str) -> TerminalShellKind { let file = program.rsplit(['\\', '/']).next().unwrap_or(program); let file = file.to_ascii_lowercase(); @@ -694,17 +713,6 @@ pub enum TerminalShellKind { Other, } -/// SOCKS URL 换成同一 host:port 的 HTTP 代理。混合端口两种都听; -/// WebRequest 和 PowerShell 7 的 `-Proxy` 只接受 HTTP。 -fn http_proxy_form(url: &str) -> String { - for prefix in ["socks5h://", "socks5://", "socks://"] { - if url.len() >= prefix.len() && url[..prefix.len()].eq_ignore_ascii_case(prefix) { - return format!("http://{}", &url[prefix.len()..]); - } - } - url.to_owned() -} - /// 能交给 curl / git 的代理 URL。已带协议的原样保留(含账号);裸 `host:port` /// 与 SSH 一样按 SOCKS5。解析失败、跳板、自定义命令都不是环境变量代理。 fn env_proxy_url(raw: &str) -> Option { @@ -1303,9 +1311,10 @@ mod tests { let pairs = terminal_proxy_assignments(ProxyMode::Custom, "socks5://127.0.0.1:7897", false, None); assert_eq!(pairs.len(), 3); - assert_eq!(assigned_proxy(&pairs, "HTTP_PROXY"), Some("http://127.0.0.1:7897")); - assert_eq!(assigned_proxy(&pairs, "HTTPS_PROXY"), Some("http://127.0.0.1:7897")); + assert_eq!(assigned_proxy(&pairs, "HTTP_PROXY"), Some("socks5://127.0.0.1:7897")); + assert_eq!(assigned_proxy(&pairs, "HTTPS_PROXY"), Some("socks5://127.0.0.1:7897")); assert_eq!(assigned_proxy(&pairs, "ALL_PROXY"), Some("socks5://127.0.0.1:7897")); + assert_eq!(assigned_proxy(&pairs, "PEBREL_HTTP_PROXY"), None); } #[test] @@ -1328,7 +1337,8 @@ mod tests { TerminalShellKind::PowerShell7, ] { let _ = kind; - assert_eq!(assigned_proxy(&pairs, "http_proxy"), Some("http://127.0.0.1:7890")); + assert_eq!(assigned_proxy(&pairs, "http_proxy"), Some("socks5://127.0.0.1:7890")); + assert_eq!(assigned_proxy(&pairs, "https_proxy"), Some("socks5://127.0.0.1:7890")); assert_eq!(assigned_proxy(&pairs, "all_proxy"), Some("socks5://127.0.0.1:7890")); } } @@ -1342,6 +1352,7 @@ mod tests { Some("http://system:1"), ); assert!(custom.iter().all(|(_, value)| value == "http://127.0.0.1:8080")); + assert_eq!(assigned_proxy(&custom, "PEBREL_HTTP_PROXY"), Some("http://127.0.0.1:8080")); assert!( terminal_proxy_assignments( ProxyMode::System, @@ -1358,6 +1369,7 @@ mod tests { Some("http://system:9"), ); assert!(system.iter().all(|(_, value)| value == "http://system:9")); + assert_eq!(assigned_proxy(&system, "PEBREL_HTTP_PROXY"), Some("http://system:9")); assert!(terminal_proxy_assignments(ProxyMode::System, "", true, None).is_empty()); assert!( terminal_proxy_assignments( @@ -1382,8 +1394,10 @@ mod tests { #[test] fn bare_proxy_address_is_exposed_to_terminals_as_socks5() { let pairs = terminal_proxy_assignments(ProxyMode::Custom, "127.0.0.1:7890", false, None); - assert_eq!(assigned_proxy(&pairs, "http_proxy"), Some("http://127.0.0.1:7890")); + assert_eq!(assigned_proxy(&pairs, "http_proxy"), Some("socks5://127.0.0.1:7890")); + assert_eq!(assigned_proxy(&pairs, "https_proxy"), Some("socks5://127.0.0.1:7890")); assert_eq!(assigned_proxy(&pairs, "all_proxy"), Some("socks5://127.0.0.1:7890")); + assert_eq!(assigned_proxy(&pairs, "PEBREL_HTTP_PROXY"), None); } #[test] @@ -1403,12 +1417,13 @@ mod tests { assert_eq!(env.keys().filter(|key| key.eq_ignore_ascii_case("http_proxy")).count(), 1); assert_eq!( env.iter().find(|(key, _)| key.eq_ignore_ascii_case("http_proxy")).unwrap().1, - "http://user:p%40ss@127.0.0.1:7890" + "socks5://user:p%40ss@127.0.0.1:7890" ); assert_eq!( env.iter().find(|(key, _)| key.eq_ignore_ascii_case("all_proxy")).unwrap().1, "socks5://user:p%40ss@127.0.0.1:7890" ); + assert!(env.get("PEBREL_HTTP_PROXY").is_none()); let wslenv = env.get("WSLENV").expect("proxy names are listed for WSL"); assert!(wslenv.split(':').any(|entry| entry == "KEEP/p")); assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("http_proxy"))); @@ -1416,6 +1431,55 @@ mod tests { assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("all_proxy"))); } + #[test] + fn powershell_marker_follows_http_and_keeps_socks_and_ipv6() { + let http = terminal_proxy_assignments( + ProxyMode::Custom, + "http://user:p%40ss@[::1]:8080", + false, + None, + ); + assert_eq!(assigned_proxy(&http, "http_proxy"), Some("http://user:p%40ss@[::1]:8080")); + assert_eq!( + assigned_proxy(&http, "PEBREL_HTTP_PROXY"), + Some("http://user:p%40ss@[::1]:8080") + ); + let system_socks = terminal_proxy_assignments( + ProxyMode::System, + "http://ignored:1", + true, + Some("socks5://[::1]:1080"), + ); + assert_eq!(assigned_proxy(&system_socks, "https_proxy"), Some("socks5://[::1]:1080")); + assert_eq!(assigned_proxy(&system_socks, "PEBREL_HTTP_PROXY"), None); + + let mut env = + HashMap::from([("PEBREL_HTTP_PROXY".to_owned(), "http://stale:1".to_owned())]); + assert!(apply_terminal_proxy_env( + &mut env, + ProxyMode::Custom, + "socks5h://127.0.0.1:1080", + false, + None, + )); + assert_eq!(env.get("http_proxy").map(String::as_str), Some("socks5h://127.0.0.1:1080")); + assert!(env.get("PEBREL_HTTP_PROXY").is_none()); + let wslenv = env.get("WSLENV").expect("proxy names are listed for WSL"); + assert!(!wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("PEBREL_HTTP_PROXY"))); + + assert!(apply_terminal_proxy_env( + &mut env, + ProxyMode::System, + "", + true, + Some("HTTP://system:9"), + )); + assert_eq!(env.get("http_proxy").map(String::as_str), Some("HTTP://system:9")); + assert_eq!(env.get("PEBREL_HTTP_PROXY").map(String::as_str), Some("HTTP://system:9")); + let wslenv = env.get("WSLENV").expect("proxy names are listed for WSL"); + assert!(!wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("PEBREL_HTTP_PROXY"))); + } + #[test] fn closed_proxy_mode_does_not_rewrite_an_existing_terminal_environment() { let mut env = HashMap::from([("WSLENV".to_owned(), "KEEP/p".to_owned())]); diff --git a/nebula_terminal/src/tty/windows/mod.rs b/nebula_terminal/src/tty/windows/mod.rs index 4b859ae6c..89d7c1fac 100644 --- a/nebula_terminal/src/tty/windows/mod.rs +++ b/nebula_terminal/src/tty/windows/mod.rs @@ -384,22 +384,11 @@ function global:Get-NebulaBoolSetting { } # cmd 不跑这段:它直接继承进程里的 http_proxy / https_proxy / all_proxy。 -# 这里按 PowerShell 自己的版本写变量。5.x 的 Invoke-WebRequest 走 WebRequest; -# 7.x 走 HttpClient,只认 -Proxy,不认 WebRequest 的默认代理。 -$pebrelProxyUrl = '' -if ((Get-NebulaSetting 'ssh_proxy_mode' 'off') -eq 'custom') { - $pebrelProxyUrl = Get-NebulaSetting 'ssh_proxy_url' '' -} -if ($pebrelProxyUrl) { - $pebrelHttpProxy = $pebrelProxyUrl - if ($pebrelProxyUrl -match '^(?i)(?:socks5h?|socks)://(.+)$') { - $pebrelHttpProxy = 'http://' + $Matches[1] - } elseif ($pebrelProxyUrl -notmatch '^(?i)https?://') { - $pebrelHttpProxy = 'http://' + $pebrelProxyUrl - } - $env:http_proxy = $pebrelHttpProxy - $env:https_proxy = $pebrelHttpProxy - $env:all_proxy = $pebrelProxyUrl +# 协议由 Rust 定好。PEBREL_HTTP_PROXY 只在选定代理本身是 HTTP 时存在, +# 系统代理和自定义地址共用这一条。SOCKS 不交给 WebRequest。 +# 5.x 的 Invoke-WebRequest 走 WebRequest;7.x 只认 -Proxy。 +if ($env:PEBREL_HTTP_PROXY) { + $pebrelHttpProxy = $env:PEBREL_HTTP_PROXY $pebrelIsPwsh = ($PSVersionTable.PSEdition -eq 'Core') -or ($PSVersionTable.PSVersion.Major -ge 6) try { $PSDefaultParameterValues['Invoke-WebRequest:Proxy'] = $pebrelHttpProxy @@ -1185,12 +1174,13 @@ mod test { } #[test] - fn powershell_startup_points_webrequest_at_the_custom_proxy() { - assert!(NEBULA_PROMPT_PS1.contains("ssh_proxy_mode")); - assert!(NEBULA_PROMPT_PS1.contains("$env:http_proxy")); + fn powershell_startup_uses_the_rust_http_proxy_marker() { + assert!(NEBULA_PROMPT_PS1.contains("$env:PEBREL_HTTP_PROXY")); assert!(NEBULA_PROMPT_PS1.contains("$PSVersionTable.PSEdition")); assert!(NEBULA_PROMPT_PS1.contains("[System.Net.WebRequest]::DefaultWebProxy")); assert!(NEBULA_PROMPT_PS1.contains("Invoke-WebRequest:Proxy")); + assert!(!NEBULA_PROMPT_PS1.contains("ssh_proxy_mode")); + assert!(!NEBULA_PROMPT_PS1.contains("ssh_proxy_url")); } /// gpui keymap 在传统 VT 路径把 Ctrl+Backspace 编成 \x17(Ctrl+W); From 0a464e5180b9de7e5d6308c947050b99316321d2 Mon Sep 17 00:00:00 2001 From: yellatiamo <245780149+yellatiamo@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:45:15 +0800 Subject: [PATCH 11/19] fix: honor a scheme typed into the proxy address box Pasting an http:// or socks5:// address while the other protocol stays selected now keeps that scheme. The dropdown and address box follow it. --- nebula_app/src/display/mod.rs | 4 +- nebula_app/src/display/network_proxy_model.rs | 28 ++++++++++ nebula_app/src/gpui_shell/network_settings.rs | 53 +++++++++++++------ .../settings_pane/initialization.rs | 8 +-- nebula_app/src/product_ui/mod.rs | 4 +- 5 files changed, 72 insertions(+), 25 deletions(-) diff --git a/nebula_app/src/display/mod.rs b/nebula_app/src/display/mod.rs index dab06c2af..489b607dd 100644 --- a/nebula_app/src/display/mod.rs +++ b/nebula_app/src/display/mod.rs @@ -184,8 +184,8 @@ pub(crate) fn caret_blink_on() -> bool { } #[cfg(feature = "gpui-shell")] pub(crate) use network_proxy_model::{ - MANUAL_PROXY_PROTOCOL_OPTIONS, ManualProxyProtocol, ProxyTestStatus, manual_proxy_parts, - manual_proxy_value, + MANUAL_PROXY_PROTOCOL_OPTIONS, ManualProxyProtocol, ProxyTestStatus, compose_manual_proxy_url, + manual_proxy_parts, manual_proxy_value, }; pub use settings::{NebulaSettingsSection, SettingsDropdown, SettingsHit, settings_hit}; pub(crate) use settings::{NewTabPosition, SettingsOpacityTarget}; diff --git a/nebula_app/src/display/network_proxy_model.rs b/nebula_app/src/display/network_proxy_model.rs index 8b324d842..6cc97a92c 100644 --- a/nebula_app/src/display/network_proxy_model.rs +++ b/nebula_app/src/display/network_proxy_model.rs @@ -49,6 +49,18 @@ pub(crate) fn manual_proxy_value(protocol: ManualProxyProtocol, address: &str) - } } +/// A recognized scheme in the address box wins over the protocol dropdown. +/// Pasting `http://127.0.0.1:7890` while SOCKS5 stays selected still persists HTTP. +pub(crate) fn compose_manual_proxy_url( + dropdown: ManualProxyProtocol, + typed: &str, +) -> (ManualProxyProtocol, String) { + let typed = typed.trim(); + let (parsed, host) = manual_proxy_parts(typed); + let protocol = if host.len() == typed.len() { dropdown } else { parsed }; + (protocol, manual_proxy_value(protocol, host)) +} + #[cfg(test)] mod tests { use super::{ManualProxyProtocol, manual_proxy_parts, manual_proxy_value}; @@ -74,6 +86,22 @@ mod tests { assert_eq!(manual_proxy_value(ManualProxyProtocol::Http, ""), ""); } + #[test] + fn typed_scheme_overrides_the_protocol_dropdown() { + use super::compose_manual_proxy_url; + let (protocol, url) = + compose_manual_proxy_url(ManualProxyProtocol::Socks5, "http://127.0.0.1:7890"); + assert_eq!(protocol, ManualProxyProtocol::Http); + assert_eq!(url, "http://127.0.0.1:7890"); + let (protocol, url) = compose_manual_proxy_url(ManualProxyProtocol::Http, "127.0.0.1:7890"); + assert_eq!(protocol, ManualProxyProtocol::Http); + assert_eq!(url, "http://127.0.0.1:7890"); + let (protocol, url) = + compose_manual_proxy_url(ManualProxyProtocol::Http, "socks5://127.0.0.1:7890"); + assert_eq!(protocol, ManualProxyProtocol::Socks5); + assert_eq!(url, "socks5://127.0.0.1:7890"); + } + #[test] fn parts_accept_non_ascii_without_slicing_inside_utf8() { for value in ["127.0.0.1:", ":127.0.0.1", "127.0:0.1", ":"] { diff --git a/nebula_app/src/gpui_shell/network_settings.rs b/nebula_app/src/gpui_shell/network_settings.rs index d0cf7aee4..686858e86 100644 --- a/nebula_app/src/gpui_shell/network_settings.rs +++ b/nebula_app/src/gpui_shell/network_settings.rs @@ -11,8 +11,8 @@ use gpui_component::input::InputEvent; use nebula_settings::ProxyModeName; use crate::display::{ - MANUAL_PROXY_PROTOCOL_OPTIONS, ManualProxyProtocol, ProxyTestStatus, manual_proxy_parts, - manual_proxy_value, + MANUAL_PROXY_PROTOCOL_OPTIONS, ManualProxyProtocol, ProxyTestStatus, compose_manual_proxy_url, + manual_proxy_parts, }; use crate::gpui_shell::prelude::*; use crate::gpui_shell::settings_pane::SettingsPane; @@ -66,25 +66,37 @@ impl SettingsPane { MANUAL_PROXY_PROTOCOL_OPTIONS.get(row).copied().unwrap_or_default() } - fn composed_proxy_url(&self, cx: &gpui::App) -> String { - let protocol = self.current_proxy_protocol(cx); - let typed = self.proxy_url_input.read(cx).value(); - let (_, host) = manual_proxy_parts(typed.trim()); - manual_proxy_value(protocol, host) - } - - /// 把协议 + 地址写成 `ssh_proxy_url`。测试线程随后读落盘值。 - pub(super) fn commit_proxy_address(&mut self, cx: &mut Context) { - let url = self.composed_proxy_url(cx); + /// 把协议 + 地址写成 `ssh_proxy_url`。地址里自带的 `http://` / `socks5://` + /// 覆盖左边的下拉,并让下拉和地址框跟上落盘值。测试线程随后读这个值。 + pub(super) fn commit_proxy_address( + &mut self, + window: &mut gpui::Window, + cx: &mut Context, + ) { + let typed = self.proxy_url_input.read(cx).value().to_string(); + let (protocol, url) = compose_manual_proxy_url(self.current_proxy_protocol(cx), &typed); + let row = + MANUAL_PROXY_PROTOCOL_OPTIONS.iter().position(|item| *item == protocol).unwrap_or(0); + let selected = self.proxy_protocol_select.read(cx).selected_index(cx).map(|path| path.row); + if selected != Some(row) { + self.proxy_protocol_select.update(cx, |state, cx| { + state.set_selected_index(Some(IndexPath::default().row(row)), window, cx); + }); + } + let host = manual_proxy_parts(typed.trim()).1; + if host != typed.trim() { + let host = host.to_owned(); + self.proxy_url_input.update(cx, |input, cx| input.set_value(host, window, cx)); + } self.persist(&[("ssh_proxy_url", url)], cx); } - pub(super) fn request_proxy_test(&mut self, cx: &mut Context) { + pub(super) fn request_proxy_test(&mut self, window: &mut gpui::Window, cx: &mut Context) { if matches!(self.proxy_test_status, ProxyTestStatus::Running) { return; } // 先落盘当前输入,再跑测试:验证的是下一条真实连接会读到的值。 - self.commit_proxy_address(cx); + self.commit_proxy_address(window, cx); self.proxy_test_seq = self.proxy_test_seq.wrapping_add(1); let request_id = self.proxy_test_seq; self.proxy_test_status = ProxyTestStatus::Running; @@ -145,9 +157,14 @@ impl SettingsPane { } } - pub(super) fn on_proxy_address_event(&mut self, event: &InputEvent, cx: &mut Context) { + pub(super) fn on_proxy_address_event( + &mut self, + event: &InputEvent, + window: &mut gpui::Window, + cx: &mut Context, + ) { if matches!(event, InputEvent::Change) { - self.commit_proxy_address(cx); + self.commit_proxy_address(window, cx); } } @@ -213,7 +230,9 @@ impl SettingsPane { .label(caption) .outline() .disabled(running) - .on_click(cx.listener(|this, _, _, cx| this.request_proxy_test(cx))), + .on_click(cx.listener(|this, _, window, cx| { + this.request_proxy_test(window, cx); + })), ), ) } diff --git a/nebula_app/src/gpui_shell/settings_pane/initialization.rs b/nebula_app/src/gpui_shell/settings_pane/initialization.rs index 1ff1abe86..0a268d521 100644 --- a/nebula_app/src/gpui_shell/settings_pane/initialization.rs +++ b/nebula_app/src/gpui_shell/settings_pane/initialization.rs @@ -342,10 +342,10 @@ impl SettingsPane { |this: &mut Self, _, event: &SelectEvent>, - _, + window, cx: &mut Context| { if matches!(event, SelectEvent::Confirm(Some(_))) { - this.commit_proxy_address(cx); + this.commit_proxy_address(window, cx); } }, )); @@ -358,8 +358,8 @@ impl SettingsPane { subscriptions.push(cx.subscribe_in( &proxy_url_input, window, - |this: &mut Self, _, event: &InputEvent, _, cx: &mut Context| { - this.on_proxy_address_event(event, cx); + |this: &mut Self, _, event: &InputEvent, window, cx: &mut Context| { + this.on_proxy_address_event(event, window, cx); }, )); let provider_store = crate::ai_providers::load(); diff --git a/nebula_app/src/product_ui/mod.rs b/nebula_app/src/product_ui/mod.rs index 073586a66..6fb02027b 100644 --- a/nebula_app/src/product_ui/mod.rs +++ b/nebula_app/src/product_ui/mod.rs @@ -94,8 +94,8 @@ pub(crate) use input_state::{ nebula_shell_prompt_restored_from_raw_grid, nebula_shell_ready_from_raw_grid, }; pub(crate) use network_proxy_model::{ - MANUAL_PROXY_PROTOCOL_OPTIONS, ManualProxyProtocol, ProxyTestStatus, manual_proxy_parts, - manual_proxy_value, + MANUAL_PROXY_PROTOCOL_OPTIONS, ManualProxyProtocol, ProxyTestStatus, compose_manual_proxy_url, + manual_proxy_parts, manual_proxy_value, }; pub(crate) use program_identity::{ai_logo_for_program, prepare_ai_logo_texture, program_icon}; pub(crate) use text_path_model::{fit_tail, strip_file_scheme, truncate_tab_label}; From 8c6b61f35cf0298fdfbbfb5cfa3b1ae2f84ac6ae Mon Sep 17 00:00:00 2001 From: kuddev Date: Wed, 30 Sep 2026 00:45:26 +0800 Subject: [PATCH 12/19] feat(terminal): allow inheriting the Windows launch environment --- ...2026-09-30-inherited-environment-choice.md | 62 +++++++++++++++++ nebula_app/i18n/en-US.json | 4 ++ nebula_app/i18n/zh-CN.json | 4 ++ nebula_app/src/gpui_shell/settings_pane.rs | 20 +++++- .../gpui_shell/settings_pane/navigation.rs | 2 +- .../src/gpui_shell/settings_pane/tests.rs | 46 +++++++++++++ nebula_app/src/platform/environment.rs | 67 +++++++++++++++++-- nebula_settings/src/lib.rs | 18 +++++ nebula_settings/src/reset.rs | 8 +++ 9 files changed, 222 insertions(+), 9 deletions(-) create mode 100644 architecture/notes/nebula_settings/environment/2026-09-30-inherited-environment-choice.md diff --git a/architecture/notes/nebula_settings/environment/2026-09-30-inherited-environment-choice.md b/architecture/notes/nebula_settings/environment/2026-09-30-inherited-environment-choice.md new file mode 100644 index 000000000..a652b5a37 --- /dev/null +++ b/architecture/notes/nebula_settings/environment/2026-09-30-inherited-environment-choice.md @@ -0,0 +1,62 @@ +# Choosing the environment for new Windows terminals + +## Status + +Proposed in the fix for issue #103. + +## Context + +Windows terminals refresh registered environment variables so newly installed +tools can become visible without restarting Pebrel. The same refresh replaces a +temporary PATH supplied by the shell that launched Pebrel. Both behaviors are +useful, but a registered PATH cannot reveal which inherited entries were temporary +and which came from an older registry snapshot. + +## Evidence + +`nebula_terminal/src/tty/windows/environment.rs` removes registered keys from the +inherited snapshot before applying current machine/user values. Its deletion and +expansion tests depend on that rule. Issue #103 supplies the concrete case of +prepending a directory to PATH in cmd before launching Pebrel. + +## Decision + +Add `refresh_environment` to the shared settings model, defaulting to true for +existing configurations. The Windows startup adapter, already used by both UI +shells, skips the registry refresh when the setting is false. The terminal then +inherits the environment of the Pebrel process, with normal pane-specific +overrides applied afterward. The setting affects newly created local terminals; +it does not rewrite an open process or a remote SSH environment. + +## Rejected alternatives + +- Always replace inherited PATH: loses deliberate launcher modifications. +- Always append inherited entries to refreshed PATH: can resurrect removed + registered entries and change executable selection order. +- Guess temporary entries by comparing against a later registry snapshot: + loses provenance when the registry changes before the first terminal opens. +- Disable refresh globally: changes the existing installation workflow. + +## Consequences + +Users can choose launch-time inheritance or current Windows settings. Missing or +invalid values keep the existing default. Reset restores refresh. The Terminal +settings row explains the difference and reports persistence failures through the +existing localized feedback path. No new dependency or core/UI dependency edge +is introduced. + +## Validation + +Settings tests cover defaults, invalid values, persistence round trips and reset. +A Windows subprocess regression prepends a temporary PATH entry and verifies the +real shell child receives it together with a pane override. A GPUI test clicks the +visible switch twice and verifies persisted state and search navigation. + +## Supersedes + +None. + +## Revisit when + +Windows supplies reliable environment provenance or the existing refresh policy +is replaced by an equivalent explicit per-profile configuration. diff --git a/nebula_app/i18n/en-US.json b/nebula_app/i18n/en-US.json index fa7df664b..60b6d2198 100644 --- a/nebula_app/i18n/en-US.json +++ b/nebula_app/i18n/en-US.json @@ -17,6 +17,10 @@ "en_us": "English" }, "settings": { + "environment": { + "refresh": "Refresh system environment for new terminals", + "refresh_description": "Read current Windows environment settings when opening a terminal. Turn off to inherit the environment used to launch Pebrel, including temporary PATH entries. Open terminals are unchanged." + }, "cursor_motion": { "title": "Smooth cursor", "description": "Animate terminal cursor movement; large jumps remain instant.", diff --git a/nebula_app/i18n/zh-CN.json b/nebula_app/i18n/zh-CN.json index 3abbb32be..812f4bbd3 100644 --- a/nebula_app/i18n/zh-CN.json +++ b/nebula_app/i18n/zh-CN.json @@ -17,6 +17,10 @@ "en_us": "English" }, "settings": { + "environment": { + "refresh": "新建终端时刷新系统环境变量", + "refresh_description": "打开终端时读取 Windows 当前环境设置。关闭后继承启动 Pebrel 时的环境,包括临时添加的 PATH。已打开的终端不受影响。" + }, "cursor_motion": { "title": "平滑光标", "description": "让终端光标平滑移动,大范围跳转仍立即定位。", diff --git a/nebula_app/src/gpui_shell/settings_pane.rs b/nebula_app/src/gpui_shell/settings_pane.rs index 931cca829..ef975a8de 100644 --- a/nebula_app/src/gpui_shell/settings_pane.rs +++ b/nebula_app/src/gpui_shell/settings_pane.rs @@ -381,7 +381,10 @@ impl SettingsPane { cx.notify(); return; } - if matches!(key, "ai_toasts" | "focus_follows_mouse" | "dim_inactive_panes") { + if matches!( + key, + "ai_toasts" | "focus_follows_mouse" | "dim_inactive_panes" | "refresh_environment" + ) { if let Err(error) = self.try_persist(&[(key, (value as u8).to_string())], cx) { let language = crate::gpui_shell::config::ui_language(cx); super::toast::toast( @@ -743,6 +746,7 @@ impl SettingsPane { "multiline_paste_confirm" => flag!(multiline_paste_confirm), "tab_close_visible" => flag!(tab_close_visible), "terminal_proxy" => flag!(terminal_proxy), + "refresh_environment" => flag!(refresh_environment), "powerline" => flag!(powerline), "ghost" => flag!(ghost), "ai_toasts" => flag!(ai_toasts), @@ -1094,7 +1098,19 @@ impl SettingsPane { let terminal = self .group(language.pick("启动", "Startup"), cx) .child(self.shell_select_row(cx)) - .child(self.startup_directory_row(cx)); + .child(self.startup_directory_row(cx)) + .when( + crate::platform::Platform::current() == crate::platform::Platform::Windows, + |group| { + group.child(self.switch_row( + "refresh_environment", + language.text(crate::i18n::Message::SettingsEnvironmentRefresh), + language.text(crate::i18n::Message::SettingsEnvironmentRefreshDescription), + self.runtime.refresh_environment, + cx, + )) + }, + ); let alerts = self .group(language.pick("提醒", "Alerts"), cx) .child(self.switch_row( diff --git a/nebula_app/src/gpui_shell/settings_pane/navigation.rs b/nebula_app/src/gpui_shell/settings_pane/navigation.rs index 1e089b693..75e3daf9c 100644 --- a/nebula_app/src/gpui_shell/settings_pane/navigation.rs +++ b/nebula_app/src/gpui_shell/settings_pane/navigation.rs @@ -29,7 +29,7 @@ pub(super) const SECTION_IDS: [&str; 12] = [ pub(super) const SECTION_SEARCH_TERMS: [&str; 12] = [ "application app 应用 update 更新 version 版本 github support 支持", "appearance ligatures 连字 外观 theme 主题 custom 自定义 template 模板 import 导入 export 导出 font 字体 opacity 透明度 background 背景 cursor 光标 smooth motion 平滑 动画 icon 图标 dim inactive panes 调暗非活动窗格 分屏变暗 scrollback scrolling speed history 回滚 滚动 速度 历史 滚轮 ctrl wheel zoom 缩放", - "profiles 配置文件 shell terminal 终端 completion 补全 startup 启动 ai message notifications toast alerts bell 提醒 通知 弹窗 消息 右下角 ai消息通知 ai 消息通知 ai消息弹窗 ai 消息弹窗 铃声 duration timeout persistent auto-dismiss 时长 秒 常驻 自动关闭", + "profiles 配置文件 shell terminal 终端 completion 补全 startup 启动 environment refresh path 环境变量 刷新 ai message notifications toast alerts bell 提醒 通知 弹窗 消息 右下角 ai消息通知 ai 消息通知 ai消息弹窗 ai 消息弹窗 铃声 duration timeout persistent auto-dismiss 时长 秒 常驻 自动关闭", "providers provider ai 供应商 模型 api", "ssh host 主机 remote 远程 connection 连接", "network 网络 proxy 代理 connectivity 连接", diff --git a/nebula_app/src/gpui_shell/settings_pane/tests.rs b/nebula_app/src/gpui_shell/settings_pane/tests.rs index 8c84431b0..08b6e970e 100644 --- a/nebula_app/src/gpui_shell/settings_pane/tests.rs +++ b/nebula_app/src/gpui_shell/settings_pane/tests.rs @@ -1,5 +1,51 @@ use super::*; +#[cfg(all(windows, feature = "gpui-test-support"))] +#[gpui::test] +fn environment_refresh_switch_is_searchable_and_persists(cx: &mut gpui::TestAppContext) { + use crate::gpui_shell::settings_fixture::{SettingsBytesGuard, lock_theme_studio}; + + let _fixture_guard = lock_theme_studio(); + let _guard = SettingsBytesGuard::capture(); + nebula_settings::persist_keys(&[("refresh_environment", "1".into())]).unwrap(); + cx.update(|cx| { + gpui_component::init(cx); + cx.set_global(crate::gpui_shell::config::Settings::load(ThemeName::Nord)); + }); + let mut pane_out = None; + let (_, cx) = cx.add_window_view(|window, cx| { + let view = cx.new(|cx| SettingsPane::new(window, cx)); + pane_out = Some(view.clone()); + gpui_component::Root::new(view, window, cx) + }); + let pane = pane_out.unwrap(); + cx.simulate_resize(gpui::size(px(1280.0), px(900.0))); + cx.update(|window, cx| { + pane.update(cx, |pane, cx| { + pane.settings_search_input + .update(cx, |input, cx| input.replace_all("环境变量", window, cx)); + }); + }); + cx.run_until_parked(); + assert_eq!(pane.read_with(cx, |pane, _| pane.active_section), 2); + for enabled in [false, true] { + cx.update(|window, cx| { + let _ = window.draw(cx); + }); + let bounds = cx.debug_bounds("nebula-switch-refresh_environment").unwrap(); + assert!(bounds.size.width > px(0.0) && bounds.size.height > px(0.0)); + assert!(bounds.origin.y >= px(0.0) && bounds.bottom() <= px(900.0)); + cx.simulate_click(bounds.center(), gpui::Modifiers::default()); + cx.run_until_parked(); + assert_eq!(pane.read_with(cx, |pane, _| pane.runtime.refresh_environment), enabled); + assert_eq!(RuntimeSettings::load().refresh_environment, enabled); + assert_eq!( + pane.read_with(cx, |pane, _| pane.setting_override("refresh_environment")), + Some((!enabled, "1".into())) + ); + } +} + #[cfg(feature = "gpui-test-support")] #[gpui::test] fn provider_key_dialog_blocks_clipboard_export_and_cancel_does_not_store( diff --git a/nebula_app/src/platform/environment.rs b/nebula_app/src/platform/environment.rs index e309af11c..c8e44f904 100644 --- a/nebula_app/src/platform/environment.rs +++ b/nebula_app/src/platform/environment.rs @@ -4,17 +4,25 @@ pub(crate) fn prepare_local_pty(options: &mut nebula_terminal::tty::Options) { #[cfg(windows)] { - if let Err(error) = nebula_terminal::tty::refresh_environment(options) { - log::warn!("Could not refresh the Windows environment for a new pane: {error}"); - } - let inherited_override = - !options.env_is_complete && std::env::var_os(GROK_LEGACY_CONSOLE).is_some(); - apply_local_console_defaults(options, inherited_override); + prepare_windows_local_pty( + options, + nebula_settings::RuntimeSettings::load().refresh_environment, + ); } #[cfg(not(windows))] let _ = options; } +#[cfg(windows)] +fn prepare_windows_local_pty(options: &mut nebula_terminal::tty::Options, refresh: bool) { + if refresh && let Err(error) = nebula_terminal::tty::refresh_environment(options) { + log::warn!("Could not refresh the Windows environment for a new pane: {error}"); + } + let inherited_override = + !options.env_is_complete && std::env::var_os(GROK_LEGACY_CONSOLE).is_some(); + apply_local_console_defaults(options, inherited_override); +} + #[cfg(windows)] const GROK_LEGACY_CONSOLE: &str = "GROK_FORCE_LEGACY_CONSOLE"; @@ -93,6 +101,53 @@ fn configuration_override(suffix: &str) -> bool { #[cfg(test)] mod tests { + #[cfg(windows)] + #[test] + fn inherited_environment_reaches_a_real_child_with_pane_overrides() { + const PROBE: &str = "PEBREL_INHERITED_ENVIRONMENT_PROBE"; + const SENTINEL: &str = "C:\\pebrel-parent-path-only;"; + if std::env::var_os(PROBE).is_some() { + let mut options = nebula_terminal::tty::Options { + env: [("PEBREL_PANE_VALUE".into(), "pane-override".into())].into_iter().collect(), + ..Default::default() + }; + super::prepare_windows_local_pty(&mut options, false); + assert!(!options.env_is_complete, "the parent environment must remain inherited"); + let system = std::env::var_os("SystemRoot").unwrap(); + let command = std::path::Path::new(&system) + .join("System32/WindowsPowerShell/v1.0/powershell.exe"); + let output = std::process::Command::new(command) + .args([ + "-NoProfile", + "-Command", + "[Console]::WriteLine($env:PATH); [Console]::WriteLine($env:PEBREL_PANE_VALUE)", + ]) + .envs(options.env) + .output() + .unwrap(); + assert!(output.status.success()); + let output = String::from_utf8(output.stdout).unwrap(); + let mut lines = output.lines(); + let path = std::env::var("PATH").unwrap(); + assert!(path.starts_with(SENTINEL)); + assert_eq!(lines.next(), Some(path.as_str())); + assert_eq!(lines.next(), Some("pane-override")); + return; + } + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "platform::environment::tests::inherited_environment_reaches_a_real_child_with_pane_overrides", + "--nocapture", + ]) + .env(PROBE, "1") + .env("PATH", format!("{SENTINEL}{}", std::env::var("PATH").unwrap())) + .env("PEBREL_PANE_VALUE", "parent-value") + .output() + .unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + } + #[cfg(windows)] #[test] fn local_terminal_defaults_enable_grok_unicode_without_changing_identity() { diff --git a/nebula_settings/src/lib.rs b/nebula_settings/src/lib.rs index 2e72bb216..8e7337648 100644 --- a/nebula_settings/src/lib.rs +++ b/nebula_settings/src/lib.rs @@ -1001,6 +1001,9 @@ pub struct RuntimeSettings { /// 终端网络代理:新会话启动时把当前系统代理写入 HTTP_PROXY/HTTPS_PROXY。 /// 上游默认关 (false) —— fork 侧另起本地 commit 翻成默认开。 pub terminal_proxy: bool, + /// Refresh Windows registry variables for new panes. Disable to inherit the + /// launching process environment, including its temporary PATH additions. + pub refresh_environment: bool, pub powerline: bool, /// 默认 shell 的原始 id(`shell=` 原文:powershell/bash/cmd/pwsh/WSL /// 发行版等)。解析归 shell 检测层,这里只做持久化往返。 @@ -1173,6 +1176,7 @@ impl RuntimeSettings { multiline_paste_confirm: raw.bool_on("multiline_paste_confirm").unwrap_or(true), tab_close_visible: raw.bool_on("tab_close_visible").unwrap_or(true), terminal_proxy: raw.bool_on("terminal_proxy").unwrap_or(false), + refresh_environment: raw.bool_on("refresh_environment").unwrap_or(true), powerline: raw.bool_on("powerline").unwrap_or(true), shell: raw.value("shell").or_else(|| raw.value("executor")).map(str::to_owned), startup_directory: raw.value("startup_directory").map(str::to_owned), @@ -1323,6 +1327,20 @@ pub fn format_hex_rgb(rgb: Rgb8) -> String { #[cfg(test)] mod tests { + #[test] + fn environment_refresh_defaults_and_round_trips() { + for text in ["", "refresh_environment=\n", "refresh_environment=invalid\n"] { + assert!(RuntimeSettings::from_raw(&RawSettings::from_text(text)).refresh_environment); + } + let original = "theme=Nord\nrefresh_environment=1\ncustom=keep\n"; + let disabled = apply_updates(original, &[("refresh_environment", "0".into())]); + assert!(!RuntimeSettings::from_raw(&RawSettings::from_text(&disabled)).refresh_environment); + assert!(disabled.contains("custom=keep")); + let enabled = apply_updates(&disabled, &[("refresh_environment", "1".into())]); + assert!(RuntimeSettings::from_raw(&RawSettings::from_text(&enabled)).refresh_environment); + assert_eq!(enabled, original); + } + #[test] fn pane_preferences_round_trip_and_allow_a_missing_mouse_override() { let defaults = RuntimeSettings::from_raw(&RawSettings::default()); diff --git a/nebula_settings/src/reset.rs b/nebula_settings/src/reset.rs index 8dbb4d7a0..30590aa0a 100644 --- a/nebula_settings/src/reset.rs +++ b/nebula_settings/src/reset.rs @@ -27,6 +27,7 @@ const RESET_KEYS: &[&str] = &[ "multiline_paste_confirm", "tab_close_visible", "terminal_proxy", + "refresh_environment", "powerline", "shell", "executor", @@ -228,6 +229,13 @@ mod tests { assert!(crate::keybind_pairs_from_text(&result).is_empty()); } + #[test] + fn reset_restores_environment_refresh_without_changing_private_settings() { + let restored = default_settings_text("refresh_environment=0\nprivate_key=keep\n"); + assert_eq!(restored, "private_key=keep\n"); + assert!(RuntimeSettings::from_raw(&RawSettings::from_text(&restored)).refresh_environment); + } + #[test] fn duplicate_keys_and_legacy_aliases_cannot_override_the_reset() { let text = "theme=Nord\nTHEME=Paper\nshell=pwsh\nexecutor=cmd\nkeybind=ctrl+a:Copy\nkeybind=ctrl+b:Paste\n"; From b7b0ff836e3ead6b7558f3a327023253123fd5bf Mon Sep 17 00:00:00 2001 From: kuddev Date: Wed, 30 Sep 2026 00:54:30 +0800 Subject: [PATCH 13/19] test(settings): check environment control visibility on every platform --- nebula_app/src/gpui_shell/settings_pane/tests.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/nebula_app/src/gpui_shell/settings_pane/tests.rs b/nebula_app/src/gpui_shell/settings_pane/tests.rs index 08b6e970e..4b1409b65 100644 --- a/nebula_app/src/gpui_shell/settings_pane/tests.rs +++ b/nebula_app/src/gpui_shell/settings_pane/tests.rs @@ -1,6 +1,6 @@ use super::*; -#[cfg(all(windows, feature = "gpui-test-support"))] +#[cfg(feature = "gpui-test-support")] #[gpui::test] fn environment_refresh_switch_is_searchable_and_persists(cx: &mut gpui::TestAppContext) { use crate::gpui_shell::settings_fixture::{SettingsBytesGuard, lock_theme_studio}; @@ -28,6 +28,14 @@ fn environment_refresh_switch_is_searchable_and_persists(cx: &mut gpui::TestAppC }); cx.run_until_parked(); assert_eq!(pane.read_with(cx, |pane, _| pane.active_section), 2); + if crate::platform::Platform::current() != crate::platform::Platform::Windows { + cx.update(|window, cx| { + let _ = window.draw(cx); + }); + assert!(cx.debug_bounds("nebula-switch-refresh_environment").is_none()); + assert!(RuntimeSettings::load().refresh_environment); + return; + } for enabled in [false, true] { cx.update(|window, cx| { let _ = window.draw(cx); From d28e6a4d5eba0a8c0006ce9c6e5d875403b31b2a Mon Sep 17 00:00:00 2001 From: kuddev Date: Wed, 30 Sep 2026 01:44:17 +0800 Subject: [PATCH 14/19] fix(config): report startup configuration discovery failures --- nebula_app/src/gpui_shell/config.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/nebula_app/src/gpui_shell/config.rs b/nebula_app/src/gpui_shell/config.rs index de9231293..c88fbae7f 100644 --- a/nebula_app/src/gpui_shell/config.rs +++ b/nebula_app/src/gpui_shell/config.rs @@ -487,8 +487,15 @@ impl Global for StartupWindow {} impl StartupWindow { pub(crate) fn load(config_file: Option) -> Self { - let Ok(Some(source)) = crate::config::source::discover(config_file) else { - return Self::default(); + let source = match crate::config::source::discover(config_file) { + Ok(Some(source)) => source, + Ok(None) => return Self::default(), + Err(error) => { + super::try_write_stderr(format_args!( + "[pebrel:gpui] failed to find window config: {error}" + )); + return Self::default(); + }, }; match crate::config::load_source(&source) { Ok(loaded) => Self::from_config(&loaded.config), From feeb1e0e3f7aba98b32169ab630180bcabefbe50 Mon Sep 17 00:00:00 2001 From: kuddev Date: Wed, 30 Sep 2026 02:22:02 +0800 Subject: [PATCH 15/19] fix(proxy): preserve inherited scope and verify native HTTP proxy requests --- .../2026-09-29-terminal-proxy-scheme.md | 25 ++-- nebula_app/src/gpui_shell/network_settings.rs | 60 +++++++++- nebula_app/src/platform/environment.rs | 11 +- nebula_app/src/ssh_proxy.rs | 112 ++++++------------ nebula_terminal/src/tty/windows/mod.rs | 26 ++-- nebula_terminal/src/tty/windows/proxy.ps1 | 39 ++++++ .../src/tty/windows/proxy_tests.rs | 111 +++++++++++++++++ 7 files changed, 278 insertions(+), 106 deletions(-) create mode 100644 nebula_terminal/src/tty/windows/proxy.ps1 create mode 100644 nebula_terminal/src/tty/windows/proxy_tests.rs diff --git a/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md b/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md index c4dd46219..d5ac440c4 100644 --- a/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md +++ b/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md @@ -6,7 +6,7 @@ Implemented; pending review. ## Context -New local terminals receive `http_proxy`, `https_proxy`, and `all_proxy` from the +New Windows local terminals receive `http_proxy`, `https_proxy`, and `all_proxy` from the saved network settings. A first version rewrote `socks5://host:port` to `http://host:port` for the first two variables so Windows PowerShell's `WebRequest` could use a mixed listener. That assumption is not true of every @@ -23,11 +23,14 @@ in `all_proxy` does not correct it. `System.Net.WebProxy` and PowerShell 7 ## Decision Write the validated URL, with its original scheme, into all three variables. -Add `PEBREL_HTTP_PROXY` only when that URL is itself HTTP, for both a custom -address and an enabled system proxy. The PowerShell startup script consumes -that marker and does not read `ssh_proxy_url`. Jump and command proxies stay -out of the environment because Rust already rejects them. Do not list -`PEBREL_HTTP_PROXY` in `WSLENV`. +Set `PEBREL_HTTP_PROXY` to that URL only when it is HTTP, for both a custom +address and an enabled system proxy. A selected SOCKS endpoint writes an empty +marker to shadow an inherited HTTP marker even in an incremental environment. +The PowerShell startup script consumes that marker and does not read +`ssh_proxy_url`. Jump and command proxies stay out of the environment because +Rust already rejects them. The Windows adapter preserves inherited WSLENV entries +only for incremental environments; complete registry snapshots remain authoritative. +Do not add `PEBREL_HTTP_PROXY` to `WSLENV`. ## Rejected alternatives @@ -43,14 +46,20 @@ out of the environment because Rust already rejects them. Do not list A SOCKS setting reaches curl and git as SOCKS. PowerShell `Invoke-WebRequest` follows it only when the saved address is an HTTP URL. An already open -terminal does not change. +terminal does not change. HTTP URL credentials are decoded into native proxy +credentials; they are removed from the URL passed to the request cmdlets. Proxy +initialization uses a local script scope and does not print credential-bearing +URLs when initialization fails. ## Validation `terminal_proxy_assignments` and `apply_terminal_proxy_env` cover scheme preservation, the HTTP marker, IPv6 brackets, credential bytes, and removal of a stale marker. The Windows prompt script test requires `PEBREL_HTTP_PROXY` -and forbids reading the raw proxy settings. +and forbids reading the raw proxy settings. The production `proxy.ps1` fragment is +also executed by Windows PowerShell 5 and PowerShell 7 tests against a loopback +HTTP proxy, covering anonymous requests, a Basic authentication challenge and an +empty marker with a SOCKS environment. ## Supersedes diff --git a/nebula_app/src/gpui_shell/network_settings.rs b/nebula_app/src/gpui_shell/network_settings.rs index 686858e86..2df1595da 100644 --- a/nebula_app/src/gpui_shell/network_settings.rs +++ b/nebula_app/src/gpui_shell/network_settings.rs @@ -16,6 +16,62 @@ use crate::display::{ }; use crate::gpui_shell::prelude::*; use crate::gpui_shell::settings_pane::SettingsPane; + +#[cfg(all(test, feature = "gpui-test-support"))] +mod tests { + use super::*; + use crate::gpui_shell::settings_fixture::{SettingsBytesGuard, lock_theme_studio}; + use gpui::{AppContext as _, Focusable as _, TestAppContext}; + + #[gpui::test] + fn pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url(cx: &mut TestAppContext) { + let _lock = lock_theme_studio(); + let _settings = SettingsBytesGuard::capture(); + nebula_settings::persist_keys(&[ + ("ssh_proxy_mode", "custom".into()), + ("ssh_proxy_url", "socks5://127.0.0.1:1080".into()), + ]) + .unwrap(); + cx.update(|cx| { + gpui_component::init(cx); + cx.set_global(crate::gpui_shell::config::Settings::load( + nebula_settings::ThemeName::Nord, + )); + }); + let mut pane_out = None; + let (_, cx) = cx.add_window_view(|window, cx| { + let pane = cx.new(|cx| SettingsPane::new(window, cx)); + pane.update(cx, |pane, _| pane.active_section = 5); + pane_out = Some(pane.clone()); + gpui_component::Root::new(pane, window, cx) + }); + let pane = pane_out.unwrap(); + cx.simulate_resize(gpui::size(gpui::px(1200.0), gpui::px(900.0))); + for (text, expected, host) in [ + ("http://127.0.0.1:8080", ManualProxyProtocol::Http, "127.0.0.1:8080"), + ("socks5://127.0.0.1:1080", ManualProxyProtocol::Socks5, "127.0.0.1:1080"), + ] { + cx.update(|window, cx| { + let _ = window.draw(cx); + pane.read(cx).proxy_url_input.read(cx).focus_handle(cx).focus(window, cx); + }); + let select_all = + if crate::platform::Platform::current() == crate::platform::Platform::MacOS { + "cmd-a" + } else { + "ctrl-a" + }; + cx.simulate_keystrokes(select_all); + cx.simulate_input(text); + cx.run_until_parked(); + pane.read_with(cx, |pane, cx| { + assert_eq!(pane.current_proxy_protocol(cx), expected); + assert_eq!(pane.proxy_url_input.read(cx).value().to_string(), host); + }); + assert_eq!(nebula_settings::RuntimeSettings::load().ssh_proxy_url, text); + } + } +} use crate::gpui_shell::widgets::NebulaButton; /// 旧壳 `ssh_proxy_test` 横幅高度。 @@ -178,8 +234,8 @@ impl SettingsPane { .when(custom, |page| page.child(self.proxy_address_row(cx))) .child(self.switch_row( "terminal_proxy", - language.tr("settings.network.terminal.label"), - language.tr("settings.network.terminal.description"), + language.text(crate::i18n::Message::SettingsNetworkTerminalLabel), + language.text(crate::i18n::Message::SettingsNetworkTerminalDescription), self.runtime.terminal_proxy, cx, )) diff --git a/nebula_app/src/platform/environment.rs b/nebula_app/src/platform/environment.rs index 383df1f64..2bef878fe 100644 --- a/nebula_app/src/platform/environment.rs +++ b/nebula_app/src/platform/environment.rs @@ -10,13 +10,16 @@ pub(crate) fn prepare_local_pty(options: &mut nebula_terminal::tty::Options) { let inherited_override = !options.env_is_complete && std::env::var_os(GROK_LEGACY_CONSOLE).is_some(); apply_local_console_defaults(options, inherited_override); + // Both Windows shells use this adapter after environment refresh. New + // panes get the selected protocol; existing processes remain unchanged. + if crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut options.env) { + let inherited = + if options.env_is_complete { None } else { std::env::var("WSLENV").ok() }; + crate::ssh_proxy::forward_terminal_proxy_to_wsl(&mut options.env, inherited.as_deref()); + } } #[cfg(not(windows))] let _ = options; - // 放在注册表快照之后:自定义代理地址,或已打开的系统代理,按原协议写进 - // http_proxy / https_proxy / all_proxy。HTTP 再加 PEBREL_HTTP_PROXY。 - // 旧壳和 GPUI 都走这个入口,已打开的会话不改。 - crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut options.env); } #[cfg(windows)] diff --git a/nebula_app/src/ssh_proxy.rs b/nebula_app/src/ssh_proxy.rs index 0b82cb194..31d5bfa08 100644 --- a/nebula_app/src/ssh_proxy.rs +++ b/nebula_app/src/ssh_proxy.rs @@ -600,6 +600,7 @@ pub fn probe_system_proxy() -> Option<(String, SystemProxySource)> { /// 值必须是 Rust 已经接受的 `http://` URL。SOCKS 不写它,也不改写成 HTTP。 /// 不进入 `WSLENV`:来宾里没有这套 .NET 默认值。 const POWERSHELL_HTTP_PROXY: &str = "PEBREL_HTTP_PROXY"; +const TERMINAL_PROXY_VARIABLES: [&str; 3] = ["http_proxy", "https_proxy", "all_proxy"]; /// 新开的本地终端要带上的代理变量。 /// @@ -610,7 +611,7 @@ const POWERSHELL_HTTP_PROXY: &str = "PEBREL_HTTP_PROXY"; /// `http_proxy`、`https_proxy`、`all_proxy` 使用同一条已校验 URL,协议不改写。 /// curl 在协议专用变量存在时忽略 `all_proxy`,所以不能只把原协议留在 `all_proxy`。 /// HTTP URL 另加 `PEBREL_HTTP_PROXY`,系统代理和自定义地址走同一条标记。 -pub fn terminal_proxy_assignments( +fn terminal_proxy_assignments( mode: ProxyMode, url: &str, use_system_proxy: bool, @@ -622,7 +623,7 @@ pub fn terminal_proxy_assignments( _ => None, }; let Some(configured) = chosen else { return Vec::new() }; - let mut pairs: Vec<(String, String)> = ["http_proxy", "https_proxy", "all_proxy"] + let mut pairs: Vec<(String, String)> = TERMINAL_PROXY_VARIABLES .into_iter() .map(|name| (name.to_owned(), configured.clone())) .collect(); @@ -634,9 +635,9 @@ pub fn terminal_proxy_assignments( /// 把 [`terminal_proxy_assignments`] 写进子进程环境。同名变量不分大小写替换, /// 避免刷新出来的 `HTTP_PROXY` 和这里的 `http_proxy` 各留一份。三个代理变量 -/// 保留选定协议,并列入 `WSLENV`。SOCKS 会清掉继承来的 `PEBREL_HTTP_PROXY`, -/// 避免 WebRequest 还指着上一次的 HTTP 代理。返回是否写入了代理。 -pub fn apply_terminal_proxy_env( +/// 保留选定协议。SOCKS 用空标记遮蔽继承来的 `PEBREL_HTTP_PROXY`,避免 +/// WebRequest 还指着上一次的 HTTP 代理。Windows 适配器另行维护 WSLENV。 +fn apply_terminal_proxy_env( env: &mut HashMap, mode: ProxyMode, url: &str, @@ -650,23 +651,19 @@ pub fn apply_terminal_proxy_env( let marks_http = pairs.iter().any(|(name, _)| name.eq_ignore_ascii_case(POWERSHELL_HTTP_PROXY)); if !marks_http { env.retain(|key, _| !key.eq_ignore_ascii_case(POWERSHELL_HTTP_PROXY)); + // An empty override also shadows a marker inherited by an incremental + // child environment; removing a map entry alone cannot remove its parent. + env.insert(POWERSHELL_HTTP_PROXY.to_owned(), String::new()); } - let names: Vec = pairs - .iter() - .filter(|(name, _)| !name.eq_ignore_ascii_case(POWERSHELL_HTTP_PROXY)) - .map(|(name, _)| name.clone()) - .collect(); for (name, value) in pairs { env.retain(|key, _| !key.eq_ignore_ascii_case(&name)); env.insert(name, value); } - // 不按平台分叉:非 Windows 多一个 WSLENV 没有作用,但能少一个平台 cfg。 - merge_proxy_wslenv(env, &names); true } /// 读已保存的网络设置,给即将启动的本地终端补代理变量。已打开的会话不经过这里。 -pub fn apply_saved_terminal_proxy_env(env: &mut HashMap) -> bool { +pub(crate) fn apply_saved_terminal_proxy_env(env: &mut HashMap) -> bool { let settings = nebula_settings::RuntimeSettings::load(); let mode = ProxyMode::parse(settings.ssh_proxy_mode.settings_value()); let system_url = if mode == ProxyMode::System && settings.terminal_proxy { @@ -683,36 +680,6 @@ pub fn apply_saved_terminal_proxy_env(env: &mut HashMap) -> bool ) } -/// 启动程序是 cmd、Windows PowerShell 5.x,还是 PowerShell 7。 -/// 三种都继承上面的环境变量。PowerShell 只在 `PEBREL_HTTP_PROXY` 存在时, -/// 按版本把这个 HTTP 地址写进 WebRequest 或 `-Proxy`。 -pub fn terminal_shell_kind(program: &str) -> TerminalShellKind { - let file = program.rsplit(['\\', '/']).next().unwrap_or(program); - let file = file.to_ascii_lowercase(); - if file == "cmd" || file == "cmd.exe" { - return TerminalShellKind::Cmd; - } - if file == "pwsh" || file == "pwsh.exe" { - return TerminalShellKind::PowerShell7; - } - let path = program.to_ascii_lowercase(); - if path.contains(r"powershell\7\") || path.contains("powershell/7/") { - return TerminalShellKind::PowerShell7; - } - if file == "powershell" || file == "powershell.exe" || path.contains(r"windowspowershell\") { - return TerminalShellKind::WindowsPowerShell; - } - TerminalShellKind::Other -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TerminalShellKind { - Cmd, - WindowsPowerShell, - PowerShell7, - Other, -} - /// 能交给 curl / git 的代理 URL。已带协议的原样保留(含账号);裸 `host:port` /// 与 SSH 一样按 SOCKS5。解析失败、跳板、自定义命令都不是环境变量代理。 fn env_proxy_url(raw: &str) -> Option { @@ -728,23 +695,29 @@ fn env_proxy_url(raw: &str) -> Option { } } -fn merge_proxy_wslenv(env: &mut HashMap, names: &[String]) { +/// Preserve explicit forwarding flags and, for incremental child environments, +/// entries inherited from the launcher. Complete snapshots pass no fallback. +pub(crate) fn forward_terminal_proxy_to_wsl( + env: &mut HashMap, + inherited: Option<&str>, +) { const WSLENV: &str = "WSLENV"; let existing = env .iter() .find(|(key, _)| key.eq_ignore_ascii_case(WSLENV)) - .map(|(_, value)| value.clone()) + .map(|(_, value)| value.as_str()) + .or(inherited) .unwrap_or_default(); let mut entries: Vec = existing.split(':').filter(|entry| !entry.is_empty()).map(str::to_owned).collect(); - for name in names { + for name in TERMINAL_PROXY_VARIABLES { if entries .iter() .any(|entry| entry.split('/').next().unwrap_or(entry).eq_ignore_ascii_case(name)) { continue; } - entries.push(name.clone()); + entries.push(name.to_owned()); } env.retain(|key, _| !key.eq_ignore_ascii_case(WSLENV)); env.insert(WSLENV.to_owned(), entries.join(":")); @@ -1338,32 +1311,6 @@ mod tests { assert_eq!(assigned_proxy(&pairs, "PEBREL_HTTP_PROXY"), None); } - #[test] - fn cmd_powershell5_and_powershell7_are_distinct_and_all_inherit_proxy_variables() { - use super::TerminalShellKind; - assert_eq!(terminal_shell_kind(r"C:\Windows\System32\cmd.exe"), TerminalShellKind::Cmd); - assert_eq!( - terminal_shell_kind(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"), - TerminalShellKind::WindowsPowerShell - ); - assert_eq!( - terminal_shell_kind(r"C:\Program Files\PowerShell\7\pwsh.exe"), - TerminalShellKind::PowerShell7 - ); - let pairs = - terminal_proxy_assignments(ProxyMode::Custom, "socks5://127.0.0.1:7890", false, None); - for kind in [ - TerminalShellKind::Cmd, - TerminalShellKind::WindowsPowerShell, - TerminalShellKind::PowerShell7, - ] { - let _ = kind; - assert_eq!(assigned_proxy(&pairs, "http_proxy"), Some("socks5://127.0.0.1:7890")); - assert_eq!(assigned_proxy(&pairs, "https_proxy"), Some("socks5://127.0.0.1:7890")); - assert_eq!(assigned_proxy(&pairs, "all_proxy"), Some("socks5://127.0.0.1:7890")); - } - } - #[test] fn system_proxy_switch_does_not_gate_a_custom_address() { let custom = terminal_proxy_assignments( @@ -1444,7 +1391,8 @@ mod tests { env.iter().find(|(key, _)| key.eq_ignore_ascii_case("all_proxy")).unwrap().1, "socks5://user:p%40ss@127.0.0.1:7890" ); - assert!(env.get("PEBREL_HTTP_PROXY").is_none()); + assert_eq!(env.get("PEBREL_HTTP_PROXY").map(String::as_str), Some("")); + forward_terminal_proxy_to_wsl(&mut env, None); let wslenv = env.get("WSLENV").expect("proxy names are listed for WSL"); assert!(wslenv.split(':').any(|entry| entry == "KEEP/p")); assert!(wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("http_proxy"))); @@ -1484,7 +1432,8 @@ mod tests { None, )); assert_eq!(env.get("http_proxy").map(String::as_str), Some("socks5h://127.0.0.1:1080")); - assert!(env.get("PEBREL_HTTP_PROXY").is_none()); + assert_eq!(env.get("PEBREL_HTTP_PROXY").map(String::as_str), Some("")); + forward_terminal_proxy_to_wsl(&mut env, None); let wslenv = env.get("WSLENV").expect("proxy names are listed for WSL"); assert!(!wslenv.split(':').any(|entry| entry.eq_ignore_ascii_case("PEBREL_HTTP_PROXY"))); @@ -1514,4 +1463,17 @@ mod tests { assert_eq!(env.len(), 1); assert_eq!(env.get("WSLENV").map(String::as_str), Some("KEEP/p")); } + + #[test] + fn wsl_forwarding_preserves_inherited_and_explicit_environment_scopes() { + let mut inherited = HashMap::new(); + forward_terminal_proxy_to_wsl(&mut inherited, Some("KEEP/p:OTHER/u")); + assert_eq!(inherited["WSLENV"], "KEEP/p:OTHER/u:http_proxy:https_proxy:all_proxy"); + let mut complete = HashMap::new(); + forward_terminal_proxy_to_wsl(&mut complete, None); + assert_eq!(complete["WSLENV"], "http_proxy:https_proxy:all_proxy"); + let mut explicit = HashMap::from([("WSLENV".into(), "http_proxy/u".into())]); + forward_terminal_proxy_to_wsl(&mut explicit, Some("STALE/p")); + assert_eq!(explicit["WSLENV"], "http_proxy/u:https_proxy:all_proxy"); + } } diff --git a/nebula_terminal/src/tty/windows/mod.rs b/nebula_terminal/src/tty/windows/mod.rs index 1640e5858..4be1ba9bc 100644 --- a/nebula_terminal/src/tty/windows/mod.rs +++ b/nebula_terminal/src/tty/windows/mod.rs @@ -18,6 +18,9 @@ mod cmd_prompt; mod conpty; mod environment; +#[cfg(test)] +mod proxy_tests; + use blocking::{UnblockedReader, UnblockedWriter}; use conpty::Conpty as Backend; pub use environment::refresh_environment; @@ -383,22 +386,9 @@ function global:Get-NebulaBoolSetting { } } -# cmd 不跑这段:它直接继承进程里的 http_proxy / https_proxy / all_proxy。 -# 协议由 Rust 定好。PEBREL_HTTP_PROXY 只在选定代理本身是 HTTP 时存在, -# 系统代理和自定义地址共用这一条。SOCKS 不交给 WebRequest。 -# 5.x 的 Invoke-WebRequest 走 WebRequest;7.x 只认 -Proxy。 -if ($env:PEBREL_HTTP_PROXY) { - $pebrelHttpProxy = $env:PEBREL_HTTP_PROXY - $pebrelIsPwsh = ($PSVersionTable.PSEdition -eq 'Core') -or ($PSVersionTable.PSVersion.Major -ge 6) - try { - $PSDefaultParameterValues['Invoke-WebRequest:Proxy'] = $pebrelHttpProxy - $PSDefaultParameterValues['Invoke-RestMethod:Proxy'] = $pebrelHttpProxy - if (-not $pebrelIsPwsh) { - [System.Net.WebRequest]::DefaultWebProxy = New-Object System.Net.WebProxy($pebrelHttpProxy, $true) - } - } catch {} -} - +"#, + include_str!("proxy.ps1"), + r#" # 用户自己的提示符($PROFILE 里的 oh-my-posh / starship / 手写 prompt)是不是 # 已经就位。判据只能看函数体:PowerShell 内置 prompt 固定引用 # $executionContext.SessionState.Path.CurrentLocation;而 oh-my-posh 那一类是经 @@ -1178,7 +1168,8 @@ mod test { assert!(NEBULA_PROMPT_PS1.contains("$env:PEBREL_HTTP_PROXY")); assert!(NEBULA_PROMPT_PS1.contains("$PSVersionTable.PSEdition")); assert!(NEBULA_PROMPT_PS1.contains("[System.Net.WebRequest]::DefaultWebProxy")); - assert!(NEBULA_PROMPT_PS1.contains("Invoke-WebRequest:Proxy")); + assert!(NEBULA_PROMPT_PS1.contains("Invoke-WebRequest")); + assert!(NEBULA_PROMPT_PS1.contains("${command}:Proxy")); assert!(!NEBULA_PROMPT_PS1.contains("ssh_proxy_mode")); assert!(!NEBULA_PROMPT_PS1.contains("ssh_proxy_url")); } @@ -1410,6 +1401,7 @@ foreach ($powerline in @($true, $false)) { if ($rendered -notlike '*test-branch*') { throw 'Missing branch' } if ($rendered -notlike "*$([char]27)]133;A*") { throw 'Missing prompt boundary' } } + "#, ); } diff --git a/nebula_terminal/src/tty/windows/proxy.ps1 b/nebula_terminal/src/tty/windows/proxy.ps1 new file mode 100644 index 000000000..f8a4ae9ae --- /dev/null +++ b/nebula_terminal/src/tty/windows/proxy.ps1 @@ -0,0 +1,39 @@ +# Rust selects and validates the proxy. SOCKS URLs stay in the child environment; +# only the explicit HTTP marker configures PowerShell's HTTP request cmdlets. +& { + if (-not $env:PEBREL_HTTP_PROXY) { return } + try { + $address = [Uri]$env:PEBREL_HTTP_PROXY + if ($address.Scheme -ne 'http') { throw 'Expected an HTTP proxy' } + $builder = [UriBuilder]$address + $builder.UserName = '' + $builder.Password = '' + $proxyUrl = $builder.Uri.AbsoluteUri + $credential = $null + if ($address.UserInfo) { + $parts = $address.UserInfo.Split([char[]]@(':'), 2) + $user = [Uri]::UnescapeDataString($parts[0]) + $password = if ($parts.Length -gt 1) { [Uri]::UnescapeDataString($parts[1]) } else { '' } + $secret = New-Object System.Security.SecureString + foreach ($character in $password.ToCharArray()) { $secret.AppendChar($character) } + $secret.MakeReadOnly() + $credential = New-Object System.Management.Automation.PSCredential($user, $secret) + } + foreach ($command in @('Invoke-WebRequest', 'Invoke-RestMethod')) { + $global:PSDefaultParameterValues["${command}:Proxy"] = $proxyUrl + $global:PSDefaultParameterValues.Remove("${command}:ProxyCredential") + if ($credential) { + $global:PSDefaultParameterValues["${command}:ProxyCredential"] = $credential + } + } + $pebrelIsPwsh = ($PSVersionTable.PSEdition -eq 'Core') -or ($PSVersionTable.PSVersion.Major -ge 6) + if (-not $pebrelIsPwsh) { + $proxy = New-Object System.Net.WebProxy($proxyUrl, $true) + if ($credential) { $proxy.Credentials = $credential.GetNetworkCredential() } + [System.Net.WebRequest]::DefaultWebProxy = $proxy + } + } catch { + # Do not print a URL or exception that could contain proxy credentials. + Write-Warning 'Could not configure the terminal HTTP proxy.' + } +} diff --git a/nebula_terminal/src/tty/windows/proxy_tests.rs b/nebula_terminal/src/tty/windows/proxy_tests.rs new file mode 100644 index 000000000..d51682458 --- /dev/null +++ b/nebula_terminal/src/tty/windows/proxy_tests.rs @@ -0,0 +1,111 @@ +use base64::Engine as _; +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::process::Command; +use std::time::{Duration, Instant}; + +fn powershells() -> Vec { + vec![ + std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap()) + .join("System32/WindowsPowerShell/v1.0/powershell.exe"), + std::env::var_os("PEBREL_TEST_PWSH").map(Into::into).unwrap_or_else(|| "pwsh.exe".into()), + ] +} + +fn powershell_command(shell: &std::path::Path, script: &str) -> Command { + let bytes: Vec<_> = script.encode_utf16().flat_map(u16::to_le_bytes).collect(); + let encoded = base64::engine::general_purpose::STANDARD.encode(bytes); + let mut command = Command::new(shell); + command.args(["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded]); + command +} + +#[test] +fn selected_http_proxy_reaches_real_powershell5_and_7_requests() { + for shell in powershells() { + for authenticated in [false, true] { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let port = listener.local_addr().unwrap().port(); + let worker = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let (mut stream, _) = match listener.accept() { + Ok(stream) => stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + assert!( + Instant::now() < deadline, + "PowerShell never reached the proxy" + ); + std::thread::sleep(Duration::from_millis(10)); + continue; + }, + Err(error) => panic!("{error}"), + }; + stream.set_nonblocking(false).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + assert!(request.len() < 16 * 1024); + stream.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + let request = String::from_utf8(request).unwrap(); + assert!(request.starts_with("GET http://pebrel-proxy.invalid/probe ")); + // user:p:ss, encoded independently for the proxy challenge. + let authorized = request.lines().any(|line| { + line.split_once(':').is_some_and(|(name, value)| { + name.eq_ignore_ascii_case("Proxy-Authorization") + && value.trim() == "Basic dXNlcjpwOnNz" + }) + }); + if authenticated && !authorized { + stream.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=pebrel-test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap(); + continue; + } + stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nok").unwrap(); + return; + } + }); + let user = if authenticated { "user:p%3Ass@" } else { "" }; + let script = format!( + "{}\n$ErrorActionPreference = 'Stop'\n(Invoke-WebRequest -UseBasicParsing -Uri 'http://pebrel-proxy.invalid/probe' -TimeoutSec 10).Content", + include_str!("proxy.ps1") + ); + let output = powershell_command(&shell, &script) + .env("PEBREL_HTTP_PROXY", format!("http://{user}127.0.0.1:{port}")) + .env_remove("HTTP_PROXY") + .env_remove("HTTPS_PROXY") + .env_remove("ALL_PROXY") + .env_remove("NO_PROXY") + .output() + .unwrap_or_else(|error| panic!("{shell:?}: {error}")); + let served = worker.join(); + assert!( + output.status.success(), + "{shell:?}: {}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + served.unwrap(); + assert_eq!(String::from_utf8(output.stdout).unwrap().trim(), "ok", "{shell:?}"); + } + } +} + +#[test] +fn empty_http_marker_does_not_configure_a_socks_proxy_as_http() { + for shell in powershells() { + let script = format!( + "{}\nif ($PSDefaultParameterValues.ContainsKey('Invoke-WebRequest:Proxy')) {{ exit 1 }}", + include_str!("proxy.ps1") + ); + let output = powershell_command(&shell, &script) + .env("PEBREL_HTTP_PROXY", "") + .env("http_proxy", "socks5://127.0.0.1:1080") + .output() + .unwrap(); + assert!(output.status.success(), "{shell:?}: {:?}", output.stderr); + } +} From 022eac25e61070befd48690ff279c3a47e13b81c Mon Sep 17 00:00:00 2001 From: kuddev Date: Wed, 30 Sep 2026 02:29:00 +0800 Subject: [PATCH 16/19] docs(proxy): scope native protocol evidence to tested HTTP requests --- .../2026-09-29-terminal-proxy-scheme.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md b/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md index d5ac440c4..0ec477f93 100644 --- a/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md +++ b/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md @@ -17,8 +17,9 @@ SOCKS endpoint. curl uses a protocol-specific proxy variable ahead of `ALL_PROXY` (https://curl.se/docs/manpage.html). An HTTP URL in `http_proxy` therefore sends HTTP proxy requests to a SOCKS-only port, and the original scheme left -in `all_proxy` does not correct it. `System.Net.WebProxy` and PowerShell 7 -`-Proxy` accept an HTTP proxy URL; they do not accept SOCKS. +in `all_proxy` does not correct it. The managed PowerShell adapter is verified +with HTTP URLs; other URL schemes remain available through the environment for +clients whose own networking stack supports them. ## Decision @@ -44,9 +45,10 @@ Do not add `PEBREL_HTTP_PROXY` to `WSLENV`. ## Consequences -A SOCKS setting reaches curl and git as SOCKS. PowerShell `Invoke-WebRequest` -follows it only when the saved address is an HTTP URL. An already open -terminal does not change. HTTP URL credentials are decoded into native proxy +A SOCKS setting reaches curl and git as SOCKS. The PowerShell initialization +overrides request defaults only for an HTTP URL; it leaves other protocols to +the client's networking stack. An already open terminal does not change. +HTTP URL credentials are decoded into native proxy credentials; they are removed from the URL passed to the request cmdlets. Proxy initialization uses a local script scope and does not print credential-bearing URLs when initialization fails. @@ -67,5 +69,5 @@ None. ## Revisit when -PowerShell can be given a SOCKS proxy without pretending the endpoint speaks -HTTP. +The managed adapter gains verified support for another proxy scheme or the +native request clients change their proxy configuration contracts. From 0a64431924bfb095ff4e4a3d27345c3bab97126c Mon Sep 17 00:00:00 2001 From: kuddev Date: Wed, 30 Sep 2026 03:14:03 +0800 Subject: [PATCH 17/19] test(proxy): use the settings fixture owner and serialize persisted UI checks --- .config/nextest.toml | 2 +- nebula_app/src/gpui_shell/network_settings.rs | 55 ------------------- .../src/gpui_shell/settings_pane/tests.rs | 53 ++++++++++++++++++ scripts/tests/test_ci_native_tests.py | 3 +- 4 files changed, 56 insertions(+), 57 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 80a9ebb82..18bb7925e 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -6,5 +6,5 @@ theme-studio = { max-threads = 1 } [[profile.default.overrides]] -filter = 'test(gpui_shell::settings_pane::theme_studio_tests::) or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll) or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch)' +filter = 'test(gpui_shell::settings_pane::theme_studio_tests::) or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll) or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch) or test(pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url)' test-group = 'theme-studio' diff --git a/nebula_app/src/gpui_shell/network_settings.rs b/nebula_app/src/gpui_shell/network_settings.rs index 2df1595da..89acdf356 100644 --- a/nebula_app/src/gpui_shell/network_settings.rs +++ b/nebula_app/src/gpui_shell/network_settings.rs @@ -17,61 +17,6 @@ use crate::display::{ use crate::gpui_shell::prelude::*; use crate::gpui_shell::settings_pane::SettingsPane; -#[cfg(all(test, feature = "gpui-test-support"))] -mod tests { - use super::*; - use crate::gpui_shell::settings_fixture::{SettingsBytesGuard, lock_theme_studio}; - use gpui::{AppContext as _, Focusable as _, TestAppContext}; - - #[gpui::test] - fn pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url(cx: &mut TestAppContext) { - let _lock = lock_theme_studio(); - let _settings = SettingsBytesGuard::capture(); - nebula_settings::persist_keys(&[ - ("ssh_proxy_mode", "custom".into()), - ("ssh_proxy_url", "socks5://127.0.0.1:1080".into()), - ]) - .unwrap(); - cx.update(|cx| { - gpui_component::init(cx); - cx.set_global(crate::gpui_shell::config::Settings::load( - nebula_settings::ThemeName::Nord, - )); - }); - let mut pane_out = None; - let (_, cx) = cx.add_window_view(|window, cx| { - let pane = cx.new(|cx| SettingsPane::new(window, cx)); - pane.update(cx, |pane, _| pane.active_section = 5); - pane_out = Some(pane.clone()); - gpui_component::Root::new(pane, window, cx) - }); - let pane = pane_out.unwrap(); - cx.simulate_resize(gpui::size(gpui::px(1200.0), gpui::px(900.0))); - for (text, expected, host) in [ - ("http://127.0.0.1:8080", ManualProxyProtocol::Http, "127.0.0.1:8080"), - ("socks5://127.0.0.1:1080", ManualProxyProtocol::Socks5, "127.0.0.1:1080"), - ] { - cx.update(|window, cx| { - let _ = window.draw(cx); - pane.read(cx).proxy_url_input.read(cx).focus_handle(cx).focus(window, cx); - }); - let select_all = - if crate::platform::Platform::current() == crate::platform::Platform::MacOS { - "cmd-a" - } else { - "ctrl-a" - }; - cx.simulate_keystrokes(select_all); - cx.simulate_input(text); - cx.run_until_parked(); - pane.read_with(cx, |pane, cx| { - assert_eq!(pane.current_proxy_protocol(cx), expected); - assert_eq!(pane.proxy_url_input.read(cx).value().to_string(), host); - }); - assert_eq!(nebula_settings::RuntimeSettings::load().ssh_proxy_url, text); - } - } -} use crate::gpui_shell::widgets::NebulaButton; /// 旧壳 `ssh_proxy_test` 横幅高度。 diff --git a/nebula_app/src/gpui_shell/settings_pane/tests.rs b/nebula_app/src/gpui_shell/settings_pane/tests.rs index 8c84431b0..a86278d94 100644 --- a/nebula_app/src/gpui_shell/settings_pane/tests.rs +++ b/nebula_app/src/gpui_shell/settings_pane/tests.rs @@ -1,5 +1,58 @@ use super::*; +#[cfg(feature = "gpui-test-support")] +#[gpui::test] +fn pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url(cx: &mut gpui::TestAppContext) { + use crate::display::{MANUAL_PROXY_PROTOCOL_OPTIONS, ManualProxyProtocol}; + use crate::gpui_shell::settings_fixture::{SettingsBytesGuard, lock_theme_studio}; + use gpui::Focusable as _; + + let _lock = lock_theme_studio(); + let _settings = SettingsBytesGuard::capture(); + nebula_settings::persist_keys(&[ + ("ssh_proxy_mode", "custom".into()), + ("ssh_proxy_url", "socks5://127.0.0.1:1080".into()), + ]) + .unwrap(); + cx.update(|cx| { + gpui_component::init(cx); + cx.set_global(crate::gpui_shell::config::Settings::load(nebula_settings::ThemeName::Nord)); + }); + let mut pane_out = None; + let (_, cx) = cx.add_window_view(|window, cx| { + let pane = cx.new(|cx| SettingsPane::new(window, cx)); + pane.update(cx, |pane, _| pane.active_section = 5); + pane_out = Some(pane.clone()); + gpui_component::Root::new(pane, window, cx) + }); + let pane = pane_out.unwrap(); + cx.simulate_resize(gpui::size(gpui::px(1200.0), gpui::px(900.0))); + for (text, expected, host) in [ + ("http://127.0.0.1:8080", ManualProxyProtocol::Http, "127.0.0.1:8080"), + ("socks5://127.0.0.1:1080", ManualProxyProtocol::Socks5, "127.0.0.1:1080"), + ] { + cx.update(|window, cx| { + let _ = window.draw(cx); + pane.read(cx).proxy_url_input.read(cx).focus_handle(cx).focus(window, cx); + }); + let select_all = if crate::platform::Platform::current() == crate::platform::Platform::MacOS + { + "cmd-a" + } else { + "ctrl-a" + }; + cx.simulate_keystrokes(select_all); + cx.simulate_input(text); + cx.run_until_parked(); + pane.read_with(cx, |pane, cx| { + let row = pane.proxy_protocol_select.read(cx).selected_index(cx).unwrap().row; + assert_eq!(MANUAL_PROXY_PROTOCOL_OPTIONS[row], expected); + assert_eq!(pane.proxy_url_input.read(cx).value().to_string(), host); + }); + assert_eq!(nebula_settings::RuntimeSettings::load().ssh_proxy_url, text); + } +} + #[cfg(feature = "gpui-test-support")] #[gpui::test] fn provider_key_dialog_blocks_clipboard_export_and_cancel_does_not_store( diff --git a/scripts/tests/test_ci_native_tests.py b/scripts/tests/test_ci_native_tests.py index 8db5eb4e0..74b5c4cd1 100644 --- a/scripts/tests/test_ci_native_tests.py +++ b/scripts/tests/test_ci_native_tests.py @@ -184,7 +184,8 @@ def test_nextest_serializes_only_fixtures_that_write_the_real_settings_file(self "overrides": [{ "filter": "test(gpui_shell::settings_pane::theme_studio_tests::)" " or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll)" - " or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch)", + " or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch)" + " or test(pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url)", "test-group": "theme-studio", }], }) From 6e4ff642a578da864a4a7053c1c63347cf6af2d3 Mon Sep 17 00:00:00 2001 From: kuddev Date: Wed, 30 Sep 2026 03:14:05 +0800 Subject: [PATCH 18/19] test(settings): serialize environment preference persistence with shared fixtures --- .config/nextest.toml | 2 +- scripts/tests/test_ci_native_tests.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 80a9ebb82..5a90acfc0 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -6,5 +6,5 @@ theme-studio = { max-threads = 1 } [[profile.default.overrides]] -filter = 'test(gpui_shell::settings_pane::theme_studio_tests::) or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll) or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch)' +filter = 'test(gpui_shell::settings_pane::theme_studio_tests::) or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll) or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch) or test(environment_refresh_switch_is_searchable_and_persists)' test-group = 'theme-studio' diff --git a/scripts/tests/test_ci_native_tests.py b/scripts/tests/test_ci_native_tests.py index 8db5eb4e0..14b2646d0 100644 --- a/scripts/tests/test_ci_native_tests.py +++ b/scripts/tests/test_ci_native_tests.py @@ -184,7 +184,8 @@ def test_nextest_serializes_only_fixtures_that_write_the_real_settings_file(self "overrides": [{ "filter": "test(gpui_shell::settings_pane::theme_studio_tests::)" " or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll)" - " or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch)", + " or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch)" + " or test(environment_refresh_switch_is_searchable_and_persists)", "test-group": "theme-studio", }], }) From 541db45099b9937624f6f0357d96082a9f49bbe0 Mon Sep 17 00:00:00 2001 From: kuddev Date: Wed, 30 Sep 2026 09:07:44 +0800 Subject: [PATCH 19/19] Reuse one settings snapshot during Windows pane preparation --- nebula_app/src/platform/environment.rs | 9 ++++----- nebula_app/src/ssh_proxy.rs | 8 +++++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/nebula_app/src/platform/environment.rs b/nebula_app/src/platform/environment.rs index 327544909..2d015c3de 100644 --- a/nebula_app/src/platform/environment.rs +++ b/nebula_app/src/platform/environment.rs @@ -4,13 +4,12 @@ pub(crate) fn prepare_local_pty(options: &mut nebula_terminal::tty::Options) { #[cfg(windows)] { - prepare_windows_local_pty( - options, - nebula_settings::RuntimeSettings::load().refresh_environment, - ); + // 同一次启动共用设置快照,避免重复读盘或两次读取间设置变化。 + let settings = nebula_settings::RuntimeSettings::load(); + prepare_windows_local_pty(options, settings.refresh_environment); // Both Windows shells use this adapter after environment refresh. New // panes get the selected protocol; existing processes remain unchanged. - if crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut options.env) { + if crate::ssh_proxy::apply_saved_terminal_proxy_env(&mut options.env, &settings) { let inherited = if options.env_is_complete { None } else { std::env::var("WSLENV").ok() }; crate::ssh_proxy::forward_terminal_proxy_to_wsl(&mut options.env, inherited.as_deref()); diff --git a/nebula_app/src/ssh_proxy.rs b/nebula_app/src/ssh_proxy.rs index 31d5bfa08..414c4a9bd 100644 --- a/nebula_app/src/ssh_proxy.rs +++ b/nebula_app/src/ssh_proxy.rs @@ -662,9 +662,11 @@ fn apply_terminal_proxy_env( true } -/// 读已保存的网络设置,给即将启动的本地终端补代理变量。已打开的会话不经过这里。 -pub(crate) fn apply_saved_terminal_proxy_env(env: &mut HashMap) -> bool { - let settings = nebula_settings::RuntimeSettings::load(); +/// 使用启动时的设置快照补代理变量,避免与环境刷新重复读盘。已打开的会话不经过这里。 +pub(crate) fn apply_saved_terminal_proxy_env( + env: &mut HashMap, + settings: &nebula_settings::RuntimeSettings, +) -> bool { let mode = ProxyMode::parse(settings.ssh_proxy_mode.settings_value()); let system_url = if mode == ProxyMode::System && settings.terminal_proxy { probe_system_proxy().map(|(url, _)| url)