diff --git a/.config/nextest.toml b/.config/nextest.toml index 80a9ebb82..28e33a45c 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) or test(pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url)' test-group = 'theme-studio' 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..f7639ce19 --- /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(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 +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. 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. +- 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. +`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 + +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/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..0ec477f93 --- /dev/null +++ b/architecture/notes/nebula_app/ssh_proxy/2026-09-29-terminal-proxy-scheme.md @@ -0,0 +1,73 @@ +# Terminal proxy environment keeps the selected scheme + +## Status + +Implemented; pending review. + +## Context + +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 +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. 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 + +Write the validated URL, with its original scheme, into all three variables. +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 + +- 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. 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. + +## 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. 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 + +None. + +## Revisit when + +The managed adapter gains verified support for another proxy scheme or the +native request clients change their proxy configuration contracts. 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/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/i18n/en-US.json b/nebula_app/i18n/en-US.json index fa7df664b..247399fff 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.", @@ -69,6 +73,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 3abbb32be..2a419a8f3 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": "让终端光标平滑移动,大范围跳转仍立即定位。", @@ -69,6 +73,10 @@ "address": { "label": "代理地址" }, + "terminal": { + "label": "系统代理", + "description": "打开后,新建终端使用当前 Windows 系统代理。填写自定义代理地址后,新开的终端会直接使用这个地址,不必再打开这项。" + }, "status": { "idle": "测试当前设置是否可以访问网络", "running": "正在通过当前设置测试网络…", 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/config.rs b/nebula_app/src/gpui_shell/config.rs index 8a58d0c7e..c88fbae7f 100644 --- a/nebula_app/src/gpui_shell/config.rs +++ b/nebula_app/src/gpui_shell/config.rs @@ -472,6 +472,70 @@ fn default_font_family() -> &'static str { crate::font_install::REQUIRED_FONT_FAMILY } +/// `config.window.dimensions`:启动窗口的网格行列。 +/// +/// 单独驻留而不是并入 [`Settings`],因为生命周期不同:`Settings` 随设置页写入 +/// 反复重载,启动网格按定义只在开窗时生效一次,而 Lua 配置求值不该出现在每次 +/// 保存设置的路径上。显式 `--config-file` 优先;否则复用主应用发现顺序(`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(config_file: Option) -> Self { + 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), + 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 正在监视它做热重载。 @@ -786,10 +850,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::{ @@ -807,6 +872,79 @@ 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] + 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 fbdbef76c..d31e71721 100644 --- a/nebula_app/src/gpui_shell/mod.rs +++ b/nebula_app/src/gpui_shell/mod.rs @@ -83,6 +83,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() { @@ -185,7 +186,7 @@ pub fn run_shell( // GPUI is the only event loop in `--gpui` mode, so it owns the same // per-process hook pipe before the first TerminalView spawns. let ai_events = crate::ai_hook::spawn_gpui_server(); - init(cx); + init(cx, config_file); if initial_cwd.is_some() || !crate::platform::startup::start_hidden(&nebula_settings::RuntimeSettings::load()) { @@ -206,7 +207,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 图标码点, // 侧栏与提示符会出方框;字形同源也是跨平台截图能互相比对的前提。 @@ -233,6 +234,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(config_file)); theme::apply_chrome_theme(cx); terminal::init(cx); workspace::init(cx); diff --git a/nebula_app/src/gpui_shell/network_settings.rs b/nebula_app/src/gpui_shell/network_settings.rs index 9f4cc5f13..89acdf356 100644 --- a/nebula_app/src/gpui_shell/network_settings.rs +++ b/nebula_app/src/gpui_shell/network_settings.rs @@ -11,11 +11,12 @@ 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; + use crate::gpui_shell::widgets::NebulaButton; /// 旧壳 `ssh_proxy_test` 横幅高度。 @@ -66,25 +67,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 +158,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); } } @@ -161,8 +179,8 @@ impl SettingsPane { .when(custom, |page| page.child(self.proxy_address_row(cx))) .child(self.switch_row( "terminal_proxy", - "系统代理", - "启用时,新建终端的 HTTP(S)_PROXY 会接入系统代理。", + language.text(crate::i18n::Message::SettingsNetworkTerminalLabel), + language.text(crate::i18n::Message::SettingsNetworkTerminalDescription), self.runtime.terminal_proxy, cx, )) @@ -213,7 +231,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.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/initialization.rs b/nebula_app/src/gpui_shell/settings_pane/initialization.rs index f79a6e8aa..a5e248d06 100644 --- a/nebula_app/src/gpui_shell/settings_pane/initialization.rs +++ b/nebula_app/src/gpui_shell/settings_pane/initialization.rs @@ -353,10 +353,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); } }, )); @@ -369,8 +369,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/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..d19c0be19 100644 --- a/nebula_app/src/gpui_shell/settings_pane/tests.rs +++ b/nebula_app/src/gpui_shell/settings_pane/tests.rs @@ -1,5 +1,112 @@ use super::*; +#[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}; + + 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); + 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); + }); + 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 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/nebula_app/src/gpui_shell/terminal/session.rs b/nebula_app/src/gpui_shell/terminal/session.rs index 583b9a12e..909b19d9d 100644 --- a/nebula_app/src/gpui_shell/terminal/session.rs +++ b/nebula_app/src/gpui_shell/terminal/session.rs @@ -136,16 +136,6 @@ 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); - } // 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/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()); }); 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 ec225ae28..c2e77ae71 100644 --- a/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs +++ b/nebula_app/src/gpui_shell/workspace/windowing/startup_geometry.rs @@ -15,14 +15,12 @@ fn chrome_size(sidebar_width: f32) -> Size { fn default_size( metrics: (Pixels, Pixels), + grid: (f32, f32), sidebar_width: f32, display_limit: Option>, ) -> Size { let chrome = chrome_size(sidebar_width); - let preferred = size( - metrics.0 * f32::from(TerminalView::DEFAULT_GRID_COLUMNS) + chrome.width, - metrics.1 * f32::from(TerminalView::DEFAULT_GRID_LINES) + chrome.height, - ); + let preferred = size(metrics.0 * grid.0 + chrome.width, metrics.1 * grid.1 + chrome.height); display_limit.map_or(preferred, |limit| preferred.min(&limit)) } @@ -49,6 +47,7 @@ pub(super) fn preferred_size(cx: &App, sidebar_width: f32) -> Option 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(()); } diff --git a/nebula_app/src/platform/environment.rs b/nebula_app/src/platform/environment.rs index 0b3266c1d..2d015c3de 100644 --- a/nebula_app/src/platform/environment.rs +++ b/nebula_app/src/platform/environment.rs @@ -4,17 +4,31 @@ 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 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, &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()); } - let inherited_override = - !options.env_is_complete && std::env::var_os(GROK_LEGACY_CONSOLE).is_some(); - apply_local_console_defaults(options, inherited_override); } #[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 +107,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_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}; diff --git a/nebula_app/src/ssh_proxy.rs b/nebula_app/src/ssh_proxy.rs index 71be3909b..414c4a9bd 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,135 @@ 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"; +const TERMINAL_PROXY_VARIABLES: [&str; 3] = ["http_proxy", "https_proxy", "all_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`,系统代理和自定义地址走同一条标记。 +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() }; + let mut pairs: Vec<(String, String)> = TERMINAL_PROXY_VARIABLES + .into_iter() + .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` 各留一份。三个代理变量 +/// 保留选定协议。SOCKS 用空标记遮蔽继承来的 `PEBREL_HTTP_PROXY`,避免 +/// WebRequest 还指着上一次的 HTTP 代理。Windows 适配器另行维护 WSLENV。 +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 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()); + } + for (name, value) in pairs { + env.retain(|key, _| !key.eq_ignore_ascii_case(&name)); + env.insert(name, value); + } + true +} + +/// 使用启动时的设置快照补代理变量,避免与环境刷新重复读盘。已打开的会话不经过这里。 +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) + } else { + None + }; + apply_terminal_proxy_env( + env, + mode, + &settings.ssh_proxy_url, + settings.terminal_proxy, + system_url.as_deref(), + ) +} + +/// 能交给 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, + } +} + +/// 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.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 TERMINAL_PROXY_VARIABLES { + if entries + .iter() + .any(|entry| entry.split('/').next().unwrap_or(entry).eq_ignore_ascii_case(name)) + { + continue; + } + entries.push(name.to_owned()); + } + env.retain(|key, _| !key.eq_ignore_ascii_case(WSLENV)); + env.insert(WSLENV.to_owned(), entries.join(":")); +} + /// HKCU\...\Internet Settings:`ProxyEnable` 非零时读 `ProxyServer` 与 /// `ProxyOverride`。值的解析拆成纯函数,跨平台可测。 #[cfg(windows)] @@ -1164,4 +1294,188 @@ 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("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] + 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_eq!(assigned_proxy(&custom, "PEBREL_HTTP_PROXY"), Some("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_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( + 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("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] + 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, + "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_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"))); + 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] + 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_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"))); + + 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())]); + 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")); + } + + #[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_settings/src/lib.rs b/nebula_settings/src/lib.rs index 2e72bb216..571923160 100644 --- a/nebula_settings/src/lib.rs +++ b/nebula_settings/src/lib.rs @@ -998,9 +998,12 @@ 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, + /// 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"; diff --git a/nebula_terminal/src/tty/windows/mod.rs b/nebula_terminal/src/tty/windows/mod.rs index cdd64ce67..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,6 +386,9 @@ function global:Get-NebulaBoolSetting { } } +"#, + include_str!("proxy.ps1"), + r#" # 用户自己的提示符($PROFILE 里的 oh-my-posh / starship / 手写 prompt)是不是 # 已经就位。判据只能看函数体:PowerShell 内置 prompt 固定引用 # $executionContext.SessionState.Path.CurrentLocation;而 oh-my-posh 那一类是经 @@ -1157,6 +1163,17 @@ mod test { assert!(NEBULA_PROMPT_PS1.contains("PSDefaultParameterValues['Get-Content:Encoding']")); } + #[test] + 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")); + assert!(NEBULA_PROMPT_PS1.contains("${command}: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); /// 托管 PowerShell 必须把它绑到 BackwardKillWord,否则仍是单字符退格。 #[test] @@ -1384,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); + } +} diff --git a/scripts/tests/test_ci_native_tests.py b/scripts/tests/test_ci_native_tests.py index 8db5eb4e0..4186b4ff0 100644 --- a/scripts/tests/test_ci_native_tests.py +++ b/scripts/tests/test_ci_native_tests.py @@ -184,7 +184,9 @@ 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)" + " or test(pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url)", "test-group": "theme-studio", }], })