Skip to content

[BUG REPORT] Windows sessions read the registry for their shell and environment - #5

Merged
Raiden-MeixElysia merged 4 commits into
ELY-Open-Source:mainfrom
zcg:fix/windows-default-shell-and-env
Oct 22, 2026
Merged

Raiden-MeixElysia merged 4 commits into
ELY-Open-Source:mainfrom
zcg:fix/windows-default-shell-and-env

Conversation

@zcg

@zcg zcg commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Type

  • [BUG REPORT]: a bug fix

What and why

在 Windows 上,ELYTerminal 有三处没有跟随系统状态,导致 PowerShell 7 用户的 profile 不加载、PATH 停留在启动瞬间的快照,且 PATH 长到 cmd.exe 读不完全。

问题一:默认 shell 被写死成 Windows PowerShell 5.1

src/term/shell.rs 的 default_shell() 直接返回 "powershell.exe"。那是 Windows PowerShell 5.1,不是 PowerShell 7。两者的 profile 目录完全不同:

profile 路径
PS 5.1 Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
PS 7 Documents\PowerShell\Microsoft.PowerShell_profile.ps1

所以设置里 shell 留空的用户,进入的是 5.1,自己的 PS7 profile 一行都不会执行——别名、函数、Tab 补全全部失效。而 Windows Terminal 的默认 profile 走的是 pwsh。

问题二:PATH 是进程启动那一刻的快照,且 %NAME% 未展开

src/term/pty.rs 把 ELYTerminal 自己的环境块原样交给 ConPTY。后果有两个:

  1. ELYTerminal 启动后新增的目录,任何新会话都看不到——必须重启应用。
  2. 注册表里以 REG_EXPAND_SZ 保存的值带着字面量 %NAME% 传给子进程。实测这台机器上 PATH 里就有一个 %SCOOP_PATH%,从未被展开。

第 2 点是实际故障:rpi.exe 确实存在于 D:\Applications\Scoop\shims,该目录也确实在注册表的 %SCOOP_PATH% 里,但在会话中执行 where.exe rpi 返回 "Could not find files"。用户会认为程序坏了或环境变量缺失。

Windows Terminal 不是这样做的。ConptyConnection 按 compatibility.reloadEnvironmentVariables(默认 true)在建连接时调用 til::env::regenerate(),从注册表重建环境块。

问题三:PATH 太长,cmd.exe 读不完

Windows 自己的 machine 与 user 两个 Path 键里,同一个目录被列了多次。实测这台机器上展开后是 201 条目、8634 字符,其中 81 条重复。加上进程独有的目录后是 8709 字符。

cmd.exe 对 PATH 有 8191 字符上限,超出的部分直接丢弃。于是从 PowerShell 里输入 cmd 切过去之后,cmd 拿到的是被截断的 PATH——where 都找不到,更不用说 pwsh:

D:\Projects\gpui\ELYTerminal>pwsh
'pwsh' is not recognized as an internal or external command,
operable program or batch file.

这解释了「在 ELYTerminal 里切到 cmd 就回不去了」的现象。

实测这个上限(用真实的 cmd.exe 加递增长度的 PATH 探测 where 是否可达):

PATH 长度 where 可达
8179 及以下 是
8199 及以上 否
8709(本机未去重时) 否
4833(本机去重后) 是

边界落在 8191,与 Windows 文档所写的 cmd.exe 上限一致。

与 Windows Terminal 的对照

src/inc/til/env.h 的 til::env::regenerate() 注释写明它「generally replicates the behavior of shell32!RegenerateUserEnvironment」,顺序是:15 个具名变量取自进程 PEB,再依次读 HKLM\\...\\Session Manager\\Environment、HKCU\\Environment、HKCU\\Volatile Environment 与 ...\\Volatile Environment\\<SessionId>。路径变量走 concat_var 累加而非覆盖,所以 machine 在前、user 在后,与本实现一致。

本实现有两处刻意不同:

  1. 保留进程独有的变量。WT 的 _initialEnv 从空 map 起,只有那 15 个具名变量来自 PEB,regenerate() 之后父进程传下来的其他变量全部丢失。本实现把它们追加在末尾(本机是 C:\\Users\\zcg\\.pi\\agent\\bin 与 ...\\js_runtime\\node\\24.16.0 两条)。
  2. 对 PATH 去重。WT 的 concat_var 是盲目追加,不做去重;本机上它同样会拼出 8634 字符的 PATH,同样会让 cmd.exe 截断。去重比 WT 更进一步。

另需说明:读取 HKLM 下的环境变量键不需要管理员权限(该键默认对 Users 组开放 KEY_READ),只有写入才需要。PATH 在 Windows 上一直是 machine 与 user 拼接而来,机器变量必然参与——否则任何用户进程都找不到 System32。

Bug details

  • Steps to reproduce:

    1. 安装 PowerShell 7,在 Documents\PowerShell\Microsoft.PowerShell_profile.ps1 写一个函数或 Set-PSReadLineKeyHandler。
    2. ELYTerminal 设置里 shell 留空,开一个新会话。
    3. 该函数不存在,Tab 补全不弹菜单(5.1 的 PSReadLine 2.0 是 TabCompleteNext)。
    4. 在 ELYTerminal 里新建一个目录并加入用户 PATH,再开会话,where.exe 找不到其中的程序。
    5. 用户 PATH 若含 %SCOOP_PATH% 之类的 REG_EXPAND_SZ 引用,子进程拿到的是字面量。
    6. PATH 展开后超过 8191 字符时,在会话里输入 cmd,cmd 内 pwsh 与 where 均不可用。
  • Expected: 新会话使用系统当前的 shell 与环境;cmd 能读到完整的 PATH。

  • Actual: 使用硬编码的 5.1、启动瞬间的环境快照,以及超过 cmd.exe 上限的 PATH。

  • Cause and fix: 见上;改法是让 default_shell() 按 pwsh → powershell → cmd 查找,新增 src/term/env.rs 在每次 spawn 时从注册表重建环境块,并对 PATH 去重。

改动内容

1. src/term/shell.rs — 默认 shell 按顺序查找

#[cfg(windows)]
fn default_shell() -> anyhow::Result<String> {
    for name in ["pwsh", "powershell", "cmd"] {
        match crate::settings::program_path(name) {
            // An App Execution Alias is a stub that starts only while its package is installed.
            Ok(found) if !alias(&found) => return Ok(found),
            Ok(found) => log::info!("shell integration: {found} is an alias, so passed by"),
            Err(error) => log::info!("shell integration: no {name}: {error:#}"),
        }
    }
    anyhow::bail!("shell integration: neither pwsh, powershell nor cmd lies on PATH")
}

alias() 跳过 WindowsApps 目录。该目录下的 pwsh.exe 是 0 字节的 App Execution Alias(重解析点),只在对应 Store 包已安装时才能启动;它在 PATH 里位置靠前,会盖住常规安装的 C:\Program Files\PowerShell\7\pwsh.exe。没有这层过滤,没装 Store 版的用户会拿到一个启动即失败的 shell。

没有 pwsh 时回退到 5.1,再回退到 cmd,三者皆无才报错——不会静默失败。

2. src/term/env.rs(新增)— 每次 spawn 重建环境块

对齐 Windows Terminal 的 til::env::regenerate():

  • 依次读 HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment、HKCU\Environment、HKCU\Volatile Environment。
  • 路径变量累加而非覆盖。machine 与 user 两个键都叫 Path,直接 HashMap::extend 会让 user 覆盖 machine,丢掉整个系统 PATH。这里按 til::env::concat_var 的语义累加。
  • Path / LibPath / Os2LibPath 走拼接,其余变量覆盖。
  • 所有名字到齐后再统一展开 %NAME%,最多 8 轮。PATH 里的 %SystemRoot% 依赖 SystemRoot 这个变量,若边读边展开就会拿到字面量。
  • 只接受 REG_SZ 与 REG_EXPAND_SZ。两者缺一不可:这台机器上 Path、PSModulePath、SCOOP_PATH、TEMP 都是 REG_EXPAND_SZ,但 SystemRoot、USERPROFILE、APPDATA 等 102 个变量是 REG_SZ。只认其一会丢掉另一批——实测只收 REG_EXPAND_SZ 只能读到 12 个变量。
  • PATH 去重(本次追加):同一个目录只列出一次,保留注册表顺序(machine 在前),进程独有且注册表没有的目录追加在末尾。
// A folder once is enough; Windows' own keys list many twice, and cmd.exe reads 8191
// characters of PATH at most. The registry's order stands: the machine's first.
let mut seen: HashSet<String> = HashSet::new();
let mut joined = String::with_capacity(value.len());
let mut push = |entry: &str, joined: &mut String| {
    if seen.insert(entry.trim_end_matches('\\').to_lowercase()) {
        if !joined.is_empty() {
            joined.push(';');
        }
        joined.push_str(entry);
    }
};
for entry in value.split(';').filter(|entry| !entry.is_empty()) {
    push(entry, &mut joined);
}
if let Some(previous) = lookup(key, &held) {
    for entry in previous.split(';').filter(|entry| !entry.is_empty()) {
        // A `%NAME%` this process was started with is stale, since the registry's expansion replaced it.
        if entry.contains('%') {
            continue;
        }
        push(entry, &mut joined);
    }
}

带 % 的旧值仍然丢弃——注册表的展开结果才是有效的。

windows-sys 增加 Win32_System_Registry feature(仅 cfg(windows) 依赖)。

How it was tested

cargo fmt 干净,cargo clippy --all-targets -- -D warnings 干净,cargo test 252 个测试全部通过。

新增 14 个测试(复审后又加了 6 个):

  • src/term/env/tests.rs(13 个):%NAME% 展开、未知名字保留原文、跨 map 查找、大小写不敏感、路径变量识别、嵌套展开;以及一个读真实注册表的测试,断言 无重复目录、仍包含 system32、会话持有的名字没有以文本形式留在 PATH 里。
  • src/term/shell.rs(1 个,cfg(all(test, windows))):alias() 识别 WindowsApps,大小写不敏感,不误判常规安装路径。

人工验证(Windows 11,PowerShell 7.6.7):

读取 release 二进制真正 spawn 的 pwsh.exe 子进程的环境块:

修复前 修复后
PATH 字符数 6922 8739 → 去重后 4833
PATH 条目数 169 204 → 去重后 122
%NAME% 残留 %SCOOP_PATH% 无
where.exe rpi 找不到 找到 D:\Applications\Scoop\shims\rpi.exe
会话内 cmd 后 pwsh not recognized 正常可用

会话内确认:$PSVersionTable.PSVersion 为 7.6.7,profile 中的函数可调用,Tab 绑定为 MenuComplete,PSModulePath 从 4 条增至 7 条。

启动日志:shell integration: C:\Program Files\PowerShell\7\pwsh.exe as pwsh。

环境块大小 138 个变量 / 18161 字符,对 Windows 的 32767 上限留有充足余量。

回退路径验证:从 PATH 中移除 PowerShell 7 目录后,日志显示正确回退到 powershell.exe;三条路径皆不可用时给出明确错误。

跨平台影响

改动全部限定在 Windows:

  • src/term/env.rs 在 src/term/mod.rs 中以 #[cfg(windows)] mod env; 声明,其他平台不编译该文件。
  • src/term/pty.rs 用 #[cfg(windows)] / #[cfg(not(windows))] 分成两条分支,非 Windows 分支保持原有的 HashMap::from([...]) 原样。
  • default_shell() 的 Unix 版本未改动,仍走 unix::login_shell_path();macOS 的 /usr/bin/login + exec -a 登录 shell 语义不受影响。
  • Cargo.toml 的 Win32_System_Registry 只加在 [target.'cfg(windows)'.dependencies]。
  • 原有 #[cfg(unix)] 测试未改动。

Checklist

  • The title starts with [FEATURE REQUEST], [BUG REPORT] or [Other]
  • Tests and the build pass locally
  • Docs are updated if behaviour changed

复审后的修正(2026-10-21)

上面两个提交被复审了一遍,发现四处问题,都已修好(提交 06cc508):

  1. PATH 大小写不同会变成两个变量,子进程拿到哪一个是随机的。 机器键写 Path、用户键写 PATH 时,二者不会被拼接,而是各自独立;加上进程环境里的旧 Path 也还在。alacritty 的 convert_custom_env 按大小写去重、保留 HashMap 迭代顺序里的第一个,而 HashMap 的顺序每个进程随机 —— 于是这次修复有一半的概率等于没做,或者会话的 PATH 里少了机器的那一半。现在名字按 Windows 的方式匹配:机器的 Path 与用户的 PATH 是一个变量,会拼接,进程持有的同名项被丢掉。
  2. 找默认 shell 用的仍是进程启动时的 PATH:program_path 读的是 env::var_os("PATH")。整个分支的立意是"启动之后加进 PATH 的目录要能到会话里",而 shell 查找恰恰看不到。现在用注册表的新 PATH(term::env::path())来查。
  3. cmd 兜底其实不会跑 cmd。 Windows 没有自己的 login shell,Launch.program 为空时 alacritty 会跑它写死的 powershell;而 cmd 落在没有集成脚本的那个分支里,程序没有被显式设置,于是跑的既不是 cmd,也不是找到的 cmd.exe。现在选中的程序就那样运行。
  4. 带空格的程序路径起不来。 alacritty 把程序名原样拼进命令行(tty/windows/mod.rs 的 cmd.push_str(&shell.program)),而 CreateProcessW 的 lpApplicationName 为空,Windows 按空格切命令行:C:\Program Files\PowerShell\7\pwsh.exe 被切成 C:\Program,会话直接起不来。这个问题在"用户自己设置 shell"时就有,本次改动把它变成了默认路径,所以现在给带空格的路径补上引号。

另外三处小的:

  • 环境块的大小按 Windows 的 32767 字符上限检查一次,超了记一条错误。
  • 不是文本的环境变量记一条 debug,不再被静默丢掉。
  • term::win32 的测试原来断言 Windows 为回车键打出的字符(13),而那个字符随用户当时按着的修饰键变(按住左 Ctrl 就是 10)—— 测试会在用户手按 Ctrl 时变红。现在它只读不随修饰键变的字段:键、扫描码、按下还是松开、记录自己的标记(提交 ed15c7e)。

term::env 的测试也改了:原来断言 PATH 里不含 %NAME%,而一个谁都解析不出的 %NAME% 是故意保留原样的,那条断言在某些机器上必然失败。现在断言的是代码真正保证的三件事:目录只列一次、系统的目录还在、会话持有的名字没有以文本形式留在 PATH 里。

cargo fmt --check、cargo clippy --all-targets -- -D warnings、cargo test(252 个测试)都过,scripts/check.sh 的两条家规(不连续两行注释、没有文件超过 500 行)也过。Windows 上的 release 构建已出:target/release/elyterminal.exe,scripts/windows-zip.ps1 也打了包。应用本身还没有人工跑过。

zcg added 4 commits October 20, 2026 18:25
…nvironment

Windows named `powershell.exe` as the login shell and handed each session the
environment ELYTerminal was started with, so a PowerShell 7 profile never loaded
and `PATH` was a stale snapshot: a folder added afterwards never reached a
session, and a `%SCOOP_PATH%` a `REG_EXPAND_SZ` names arrived as that text.

Fixes both:

- `shell::default_shell` runs `pwsh` where `PATH` names one, falling back to
  `powershell`, then `cmd`. An App Execution Alias under `WindowsApps` is passed
  by, since it starts only while its Store package is installed.
- `term::env` builds each session's environment from the registry, as Windows
  Terminal's `compatibility.reloadEnvironmentVariables` does: the machine key,
  then the user's, then the volatile one; a path variable joins what the earlier
  key listed, as `til::env::concat_var` does; every value expands once all names
  are in place, so a `%NAME%` in `PATH` reaches its value.

Windows only; `src/term/env.rs` is compiled under `cfg(windows)` and the other
platforms keep the environment they had.
Windows' own machine and user `Path` keys list the same folders many times: on
the machine this was found on, 201 entries expand to 81 duplicates, so a session
received 8739 characters. cmd.exe reads 8191 characters of PATH at most, so a
`cmd` started from a session lost the rest of the list and could not find
`pwsh` or even `where` after typing `cmd` in PowerShell.

A folder is now listed once: the registry's order stands, with the machine's
first, and a folder only this process holds still comes after it. The same
machine now builds 122 entries in 4833 characters, well inside cmd.exe's limit.

The test asserts against the registry of the machine it runs on that PATH holds
no folder twice and stays within 8191 characters.
…nce more

A review of the two commits above found four faults, all fixed here.

- A name is matched as Windows matches it, so the machine's `Path` and the
  user's `PATH` are one variable: they are joined, and the name this process
  holds is dropped, else alacritty's own de-duplication would keep either of
  the two at random, since a hash map's order is random, and the session's
  `PATH` would be the stale one half the time.
- The default shell is looked up in the registry's `PATH`, not in the one this
  process started with, so a shell in a folder added since ELYTerminal opened
  is found.
- The program runs as it was chosen: a program with no integration of its own,
  `cmd` among them, runs as that program, where before Windows ran
  alacritty's own `powershell`.
- A path with a space is quoted for the command line, since alacritty puts the
  program into it as it is and Windows reads the first word of it, so
  `C:\Program Files\PowerShell\7\pwsh.exe` starts where it did not.

The environment block's size is checked against Windows' 32767 characters, a
variable that is not text is logged and left to the system, and the test of
the machine's own registry asserts what the code promises: a folder once, the
system's own folders there, and no name of the session left waiting in the
path as text.
`term::win32`'s test asked for the character Windows types for the return key,
which changes with the modifier keys the user happens to hold while the tests
run: with the left control key down the key types a line feed, and the test
failed on a machine whose owner was holding it. The test now reads the fields
that do not move: the key, its scan code, the press and the record's own mark.
@Raiden-MeixElysia
Raiden-MeixElysia merged commit e82f7f8 into ELY-Open-Source:main Oct 22, 2026
Raiden-MeixElysia added a commit that referenced this pull request Oct 22, 2026
… default, its acceptance row; the contributor's own .gitignore entries dropped
@Raiden-MeixElysia

Copy link
Copy Markdown
Contributor

感谢 PR!已合并,随 v0.1.8 发布。https://github.com/ELY-Open-Source/ELYTerminal/releases/tag/v0.1.8

Raiden-MeixElysia added a commit that referenced this pull request Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants