Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

Simplify Windows support after review

Claudef520ee3ed052
diff --git a/crates/wake-core/Cargo.toml b/crates/wake-core/Cargo.toml
index c083bdd..872ef70 100644
--- a/crates/wake-core/Cargo.toml
+++ b/crates/wake-core/Cargo.toml
@@ -20,13 +20,14 @@ zstd.workspace = true
[target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies]
trash = "5"
-# Win32 原语:MessageBox 致命弹窗 + CF_UNICODETEXT 剪贴板(clip.exe 按控制台
-# codepage 解码 stdin,非 ASCII 命令必乱,不走子进程管道)
+# Win32 原语:MessageBox 致命弹窗、CF_UNICODETEXT 剪贴板(clip.exe 按控制台
+# codepage 解码 stdin,非 ASCII 命令必乱,不走子进程管道)、进程创建旗标
[target.'cfg(target_os = "windows")'.dependencies]
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_System_DataExchange",
"Win32_System_Memory",
+ "Win32_System_Threading",
"Win32_UI_WindowsAndMessaging",
] }
diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rs
index c7d0671..1c29323 100644
--- a/crates/wake-core/src/adapters/mod.rs
+++ b/crates/wake-core/src/adapters/mod.rs
@@ -180,18 +180,21 @@ pub fn create_adapters_for(store: &crate::db::Store) -> Vec<Box<dyn AgentAdapter
create_adapters_with(&customs, &removed)
}
-/// 数据根是否拥有该会话文件路径。边界必须落在 '/'(目录型)或 '#'(SQLite
+/// 数据根是否拥有该会话文件路径。边界必须落在分隔符(目录型)或 '#'(SQLite
/// 虚拟路径 `<db>#<id>`)上,与 db 侧 counts_by_path_prefix 同判据——裸前缀
-/// 会把 `…/sessions-old` 记到 `…/sessions` 头上
+/// 会把 `…/sessions-old` 记到 `…/sessions` 头上。分隔符判定走
+/// std::path::is_separator(Windows 上 `\` 与 `/` 都算),POSIX 上行为
+/// 与旧 '/' 字面量逐位相同。
pub fn path_owns(root: &str, path: &str) -> bool {
- // 文件系统根:strip_prefix("/") 剥掉的正是分隔符本身,通用分支会把一切
- // 后代判为界外(2026-08-24 Codex review)
- if root == "/" {
- return path.starts_with('/');
+ // 文件系统根("/"、Windows 的 "C:\"):strip_prefix 剥掉的正是分隔符
+ // 本身,通用分支会把一切后代判为界外(2026-08-24 Codex review)。
+ // "根"即无父目录;空串 parent 也是 None,先挡掉,别让空根拥有一切
+ if !root.is_empty() && Path::new(root).parent().is_none() {
+ return path.starts_with(root);
}
match path.strip_prefix(root) {
Some("") => true,
- Some(rest) => rest.starts_with('/') || rest.starts_with('#'),
+ Some(rest) => rest.starts_with(std::path::is_separator) || rest.starts_with('#'),
None => false,
}
}
diff --git a/crates/wake-core/src/services/terminal/mod.rs b/crates/wake-core/src/services/terminal/mod.rs
index 190cf93..c5506d7 100644
--- a/crates/wake-core/src/services/terminal/mod.rs
+++ b/crates/wake-core/src/services/terminal/mod.rs
@@ -3,10 +3,11 @@
//! 原语(起终端、开目录、选中文件、进废纸篓、弹对话框、写剪贴板),各端
//! 导出同形接口(TerminalApp 变体集合各异,UI 只遍历不点名)。
//!
-//! POSIX 双端(macOS/Linux)共享本文件的 login shell 探测与 posix_quote
-//! 拼装;Windows 的三个前提全不成立(无 login shell、引号不是 POSIX 规则、
-//! 命令方言按终端宿主分 cmd/PowerShell 两派),这三件事经 probe_clis /
-//! compose_command / launch_in 三个接缝交回 windows.rs,策略流程本身不分叉。
+//! POSIX 双端(macOS/Linux)的共享层在 posix.rs(login shell 探测、
+//! posix_quote 拼装);Windows 的这些前提全不成立(无 login shell、引号
+//! 不是 POSIX 规则、命令方言按终端宿主分 cmd/PowerShell 两派),故
+//! probe_clis / compose_command / launch_shell 三个接缝按平台各取一份,
+//! 策略流程本身不分叉。
use crate::models::{AgentId, SessionMeta};
use std::collections::HashMap;
@@ -24,15 +25,30 @@ mod linux;
#[cfg(target_os = "linux")]
use linux as platform;
+// POSIX 共享层**正向**圈定,新平台不会静默继承(见 posix.rs 头注)。
+// pub(crate) 三件是 macos.rs / linux.rs 经 `super::` 取用的中转。
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+mod posix;
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+use posix::{compose_command, probe_clis};
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+pub(crate) use posix::{percent_encode, pipe_to};
+// posix_quote 只有 macos.rs 消费(kooky CLI 的命令拼装),Linux 上中转会空挂
+#[cfg(target_os = "macos")]
+pub(crate) use posix::posix_quote;
+
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
use windows as platform;
+#[cfg(target_os = "windows")]
+use windows::{compose_command, probe_clis};
-// 公共层默认走 POSIX 假设,新平台进来必须给出自己的模块并重审 probe_clis /
-// compose_command / launch_in 三个接缝(windows.rs 是完整先例),不能静默沿用
+// 新平台必须给出自己的模块并接上 probe_clis / compose_command /
+// launch_shell 三个接缝(windows.rs 是完整先例)——POSIX 共享层是正向
+// cfg,漏接的接缝直接是编译错误,不存在静默沿用
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
-compile_error!("wake terminal services: unsupported platform — add a platform module (POSIX assumptions throughout)");
+compile_error!("wake terminal services: unsupported platform — add a platform module wired into the probe_clis / compose_command / launch_shell seams");
pub use platform::{ensure_app_icons, installed_terminals, terminals_for, TerminalApp};
@@ -46,48 +62,6 @@ pub struct ResumeOutcome {
/// GUI 进程 PATH 不全(macOS/Linux 缺 ~/.local/bin 等),批量解析并缓存
static CLI_CACHE: Mutex<Option<HashMap<String, Option<String>>>> = Mutex::new(None);
-/// 解析 PATH 用的 login shell:macOS 固定 zsh(系统默认);Linux 尊重 $SHELL
-/// (bash/zsh/fish 对 `-lic` 与 `command -v` 语义一致),缺省 /bin/bash
-#[cfg(not(target_os = "windows"))]
-fn login_shell() -> String {
- if cfg!(target_os = "macos") {
- return "/bin/zsh".to_string();
- }
- std::env::var("SHELL")
- .ok()
- .filter(|s| s.starts_with('/'))
- .unwrap_or_else(|| "/bin/bash".to_string())
-}
-
-/// 批量探测缺失 bin 的绝对路径(POSIX:login shell 里 `command -v`,把
-/// 用户 rc 文件加进 PATH 的目录一并覆盖)。Windows 的 GUI 进程 PATH 来自
-/// 注册表、天然完整,探测在 windows.rs 用 PATH×PATHEXT 纯 Rust 遍历。
-#[cfg(not(target_os = "windows"))]
-fn probe_clis(missing: &[&str]) -> HashMap<String, String> {
- let script = missing
- .iter()
- .map(|b| format!("printf '%s\\t' {b}; command -v {b} || echo"))
- .collect::<Vec<_>>()
- .join("; ");
- let out = Command::new(login_shell()).args(["-lic", &script]).output();
- let stdout = out
- .ok()
- .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
- .unwrap_or_default();
- let mut found = HashMap::new();
- for line in stdout.lines() {
- if let Some((name, path)) = line.split_once('\t') {
- if path.starts_with('/') {
- found.insert(name.trim().to_string(), path.trim().to_string());
- }
- }
- }
- found
-}
-
-#[cfg(target_os = "windows")]
-use windows::probe_clis;
-
fn resolve_clis(bins: &[&str]) -> HashMap<String, Option<String>> {
let mut cache = CLI_CACHE.lock().unwrap();
let map = cache.get_or_insert_with(HashMap::new);
@@ -166,82 +140,6 @@ fn resume_args(agent: AgentId, id: &str) -> Option<(Vec<String>, bool)> {
}
}
-/// POSIX 单引号 quote
-#[cfg(not(target_os = "windows"))]
-pub fn posix_quote(s: &str) -> String {
- if !s.is_empty()
- && s.chars()
- .all(|c| c.is_ascii_alphanumeric() || "_-./:=".contains(c))
- {
- return s.to_string();
- }
- format!("'{}'", s.replace('\'', r"'\''"))
-}
-
-/// 展示/剪贴板/启动共用的一条可执行命令。POSIX 双端就是实际启动串;
-/// Windows 版(windows.rs)是 PowerShell 方言的"手动可粘"形态,实际启动
-/// 由 launch_in 按终端宿主重拼。
-#[cfg(not(target_os = "windows"))]
-fn compose_command(cli: &str, args: &[String], cwd: Option<&str>) -> String {
- let core = std::iter::once(cli)
- .chain(args.iter().map(|s| s.as_str()))
- .map(posix_quote)
- .collect::<Vec<_>>()
- .join(" ");
- match cwd {
- Some(dir) => format!("cd {} && {core}", posix_quote(dir)),
- None => core,
- }
-}
-
-#[cfg(target_os = "windows")]
-use windows::compose_command;
-
-/// 起终端跑恢复命令。POSIX 双端直接投喂拼好的 command;Windows 忽略
-/// command、拿结构化件重拼(cmd 宿主 cmd 方言、其余 PowerShell 方言)——
-/// 一条字符串塞不进两种引号规则,接缝只能开在这里。
-#[cfg(not(target_os = "windows"))]
-fn launch_in(
- term: TerminalApp,
- _cli: &str,
- _args: &[String],
- _cwd: Option<&str>,
- command: &str,
-) -> anyhow::Result<()> {
- platform::launch_shell(term, command)
-}
-
-#[cfg(target_os = "windows")]
-fn launch_in(
- term: TerminalApp,
- cli: &str,
- args: &[String],
- cwd: Option<&str>,
- _command: &str,
-) -> anyhow::Result<()> {
- windows::launch_shell(term, cli, args, cwd)
-}
-
-/// 保守 percent-encode(RFC 3986 unreserved 之外全编;keep_slash 供
-/// file:// URL 保路径分隔)。POSIX 两端共用,编码集只此一份。
-#[cfg(not(target_os = "windows"))]
-pub(crate) fn percent_encode(s: &str, keep_slash: bool) -> String {
- use std::fmt::Write;
- let mut out = String::with_capacity(s.len());
- for b in s.bytes() {
- match b {
- b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
- out.push(b as char)
- }
- b'/' if keep_slash => out.push('/'),
- _ => {
- let _ = write!(out, "%{b:02X}");
- }
- }
- }
- out
-}
-
pub fn resume_session_in(meta: &SessionMeta, term: TerminalApp) -> ResumeOutcome {
// 深链类目标(macOS Kooky)由平台整锅接管,不走 shell 命令构建;
// 新增非 shell 目标在平台的 deep_link_resume 里声明,这里无需加旁路
@@ -278,7 +176,14 @@ pub fn resume_session_in(meta: &SessionMeta, term: TerminalApp) -> ResumeOutcome
};
}
- let result = launch_in(term, &cli, &args, cwd, &command);
+ // 起终端:POSIX 直接投喂拼好的 command;Windows 的 launch_shell 另收
+ // 结构化件按宿主重拼方言(cmd 宿主 cmd 方言、其余复用 command 的
+ // PowerShell 形态)——一条字符串塞不进两种引号规则,平台差异只摊在
+ // 这一处调用点上。
+ #[cfg(not(target_os = "windows"))]
+ let result = platform::launch_shell(term, &command);
+ #[cfg(target_os = "windows")]
+ let result = platform::launch_shell(term, &cli, &args, cwd, &command);
match result {
Ok(()) => ResumeOutcome {
ok: true,
@@ -348,24 +253,6 @@ pub fn reveal_in_file_manager(path: &str) {
std::thread::spawn(move || platform::reveal_path(&real));
}
-/// 把 text 经管道写给 `bin args…` 的 stdin(POSIX 剪贴板工具用),按退出码
-/// 报成败——"copied to clipboard" 的用户提示以此为据,不能 spawn 成功就算数。
-/// 三家 Linux 工具与 pbcopy 都在拿到内容后自行 fork 常驻,wait 即刻返回。
-/// Windows 不走子进程管道(clip.exe 按控制台 codepage 解码,非 ASCII 必乱),
-/// windows.rs 直接调 Win32 剪贴板。
-#[cfg(not(target_os = "windows"))]
-pub(crate) fn pipe_to(bin: &str, args: &[&str], text: &str) -> bool {
- use std::io::Write;
- let Ok(mut child) = Command::new(bin).args(args).stdin(std::process::Stdio::piped()).spawn()
- else {
- return false;
- };
- if let Some(mut stdin) = child.stdin.take() {
- let _ = stdin.write_all(text.as_bytes());
- }
- child.wait().map(|s| s.success()).unwrap_or(false)
-}
-
/// 起子进程并**收尸**,spawn 失败上抛。`status()` 不能用:把调用线程阻塞
/// 到进程结束(文件管理器冷启上百毫秒);裸 `spawn()` 丢掉 Child 也不行:
/// Unix 上 Child 的 Drop 不 wait,实测点几次就攒几个 `<defunct>`,直到
diff --git a/crates/wake-core/src/services/terminal/posix.rs b/crates/wake-core/src/services/terminal/posix.rs
new file mode 100644
index 0000000..49427d7
--- /dev/null
+++ b/crates/wake-core/src/services/terminal/posix.rs
@@ -0,0 +1,105 @@
+//! POSIX 双端(macOS/Linux)共享层:login shell 探测、单引号 quote、
+//! shell 命令拼装、file:// 编码、剪贴板管道。整个模块由 mod.rs 以**正向**
+//! cfg 圈定——新平台不会静默继承这里的任何前提,想用得自己点名。
+//! macos.rs / linux.rs 经 `super::` 取用(mod.rs 中转 re-export)。
+
+use std::collections::HashMap;
+use std::process::Command;
+
+/// 解析 PATH 用的 login shell:macOS 固定 zsh(系统默认);Linux 尊重 $SHELL
+/// (bash/zsh/fish 对 `-lic` 与 `command -v` 语义一致),缺省 /bin/bash
+fn login_shell() -> String {
+ if cfg!(target_os = "macos") {
+ return "/bin/zsh".to_string();
+ }
+ std::env::var("SHELL")
+ .ok()
+ .filter(|s| s.starts_with('/'))
+ .unwrap_or_else(|| "/bin/bash".to_string())
+}
+
+/// 批量探测缺失 bin 的绝对路径:login shell 里 `command -v`,把用户 rc 文件
+/// 加进 PATH 的目录一并覆盖(GUI 进程 PATH 不含 ~/.local/bin 等)。
+/// Windows 的对应物在 windows.rs(注册表 PATH 天然完整,纯 Rust 遍历)。
+pub(super) fn probe_clis(missing: &[&str]) -> HashMap<String, String> {
+ let script = missing
+ .iter()
+ .map(|b| format!("printf '%s\\t' {b}; command -v {b} || echo"))
+ .collect::<Vec<_>>()
+ .join("; ");
+ let out = Command::new(login_shell()).args(["-lic", &script]).output();
+ let stdout = out
+ .ok()
+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
+ .unwrap_or_default();
+ let mut found = HashMap::new();
+ for line in stdout.lines() {
+ if let Some((name, path)) = line.split_once('\t') {
+ if path.starts_with('/') {
+ found.insert(name.trim().to_string(), path.trim().to_string());
+ }
+ }
+ }
+ found
+}
+
+/// POSIX 单引号 quote
+pub(crate) fn posix_quote(s: &str) -> String {
+ if !s.is_empty()
+ && s.chars()
+ .all(|c| c.is_ascii_alphanumeric() || "_-./:=".contains(c))
+ {
+ return s.to_string();
+ }
+ format!("'{}'", s.replace('\'', r"'\''"))
+}
+
+/// 展示/剪贴板/启动共用的一条可执行命令(POSIX 就是实际启动串;Windows 的
+/// 对应物是 PowerShell 方言的"手动可粘"形态,见 windows.rs)
+pub(super) fn compose_command(cli: &str, args: &[String], cwd: Option<&str>) -> String {
+ let core = std::iter::once(cli)
+ .chain(args.iter().map(|s| s.as_str()))
+ .map(posix_quote)
+ .collect::<Vec<_>>()
+ .join(" ");
+ match cwd {
+ Some(dir) => format!("cd {} && {core}", posix_quote(dir)),
+ None => core,
+ }
+}
+
+/// 保守 percent-encode(RFC 3986 unreserved 之外全编;keep_slash 供
+/// file:// URL 保路径分隔)。POSIX 两端共用,编码集只此一份。
+pub(crate) fn percent_encode(s: &str, keep_slash: bool) -> String {
+ use std::fmt::Write;
+ let mut out = String::with_capacity(s.len());
+ for b in s.bytes() {
+ match b {
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
+ out.push(b as char)
+ }
+ b'/' if keep_slash => out.push('/'),
+ _ => {
+ let _ = write!(out, "%{b:02X}");
+ }
+ }
+ }
+ out
+}
+
+/// 把 text 经管道写给 `bin args…` 的 stdin(剪贴板工具用),按退出码报成败
+/// ——"copied to clipboard" 的用户提示以此为据,不能 spawn 成功就算数。
+/// 三家 Linux 工具与 pbcopy 都在拿到内容后自行 fork 常驻,wait 即刻返回。
+/// Windows 不走子进程管道(clip.exe 按控制台 codepage 解码,非 ASCII 必乱),
+/// windows.rs 直接调 Win32 剪贴板。
+pub(crate) fn pipe_to(bin: &str, args: &[&str], text: &str) -> bool {
+ use std::io::Write;
+ let Ok(mut child) = Command::new(bin).args(args).stdin(std::process::Stdio::piped()).spawn()
+ else {
+ return false;
+ };
+ if let Some(mut stdin) = child.stdin.take() {
+ let _ = stdin.write_all(text.as_bytes());
+ }
+ child.wait().map(|s| s.success()).unwrap_or(false)
+}
diff --git a/crates/wake-core/src/services/terminal/windows.rs b/crates/wake-core/src/services/terminal/windows.rs
index 0b29be4..0751b53 100644
--- a/crates/wake-core/src/services/terminal/windows.rs
+++ b/crates/wake-core/src/services/terminal/windows.rs
@@ -10,19 +10,13 @@
//! 宿主)。展示/剪贴板形态同为 PowerShell 方言:现代 Windows 的默认 shell,
//! pwsh / Windows PowerShell / wt 默认 profile 粘贴均可跑。
-use super::{spawn_and_reap, ResumeOutcome};
+use super::{resolve_cli, resolve_clis, spawn_and_reap, ResumeOutcome};
use crate::models::{AgentId, SessionMeta};
use std::collections::HashMap;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
-
-/// 子进程创建旗标(文档钉死的值,不为两个常量拉 windows-sys feature):
-/// NEW_CONSOLE 给控制台宿主开自己的窗;NO_WINDOW 压掉 console 子系统
-/// launcher(wt.exe / wezterm.exe)从 GUI 进程起动时闪现的空控制台,
-/// 对 GUI 子进程无效果、可安全统一加。
-const CREATE_NEW_CONSOLE: u32 = 0x0000_0010;
-const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+use windows_sys::Win32::System::Threading::{CREATE_NEW_CONSOLE, CREATE_NO_WINDOW};
/// Open In 下拉的目标终端(Windows 家族)。wt/pwsh/powershell/cmd 覆盖
/// 系统自带面(cmd 与 Windows PowerShell 必装,探测恒真),第三方只列
@@ -85,28 +79,39 @@ impl TerminalApp {
pub(super) fn probe_clis(missing: &[&str]) -> HashMap<String, String> {
let mut found = HashMap::new();
let path_var = std::env::var_os("PATH").unwrap_or_default();
- let dirs: Vec<PathBuf> = std::env::split_paths(&path_var).collect();
let exts: Vec<String> = std::env::var("PATHEXT")
.unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into())
.split(';')
.filter(|e| e.starts_with('.'))
.map(str::to_string)
.collect();
- for want in missing {
- 'dirs: for dir in &dirs {
- if dir.as_os_str().is_empty() {
- continue;
- }
- for ext in &exts {
- let cand = dir.join(format!("{want}{ext}"));
+ // dirs 外层单遍 PATH、命中即从 pending 摘除:PATH 目录序 × PATHEXT 序的
+ // 首个命中语义不变,但 is_file(Windows 上每次都是一次 CreateFileW,还要
+ // 过 Defender)只付 O(PATH),不是 O(PATH × bins);候选文件名先算好,
+ // 循环里零 format!
+ let mut pending: Vec<(&str, Vec<String>)> = missing
+ .iter()
+ .map(|w| (*w, exts.iter().map(|e| format!("{w}{e}")).collect()))
+ .collect();
+ for dir in std::env::split_paths(&path_var) {
+ if pending.is_empty() {
+ break;
+ }
+ if dir.as_os_str().is_empty() {
+ continue;
+ }
+ pending.retain(|(want, names)| {
+ for name in names {
+ let cand = dir.join(name);
// WindowsApps 的 app-execution alias(wt.exe)是 0 字节
// reparse 文件,is_file 为真、可直接 spawn
if cand.is_file() {
found.insert(want.to_string(), cand.to_string_lossy().to_string());
- break 'dirs;
+ return false;
}
}
- }
+ true
+ });
}
found
}
@@ -161,6 +166,12 @@ fn wt_escape(s: &str) -> String {
s.replace(';', "\\;")
}
+/// NUL 结尾的 UTF-16(*W 系 API 的入参形制;NUL 是防越界读的护栏,
+/// 所有 Win32 宽字符串都走这一份)
+fn wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain(std::iter::once(0)).collect()
+}
+
/// Windows 无深链类恢复目标(Kooky 仅 macOS),全部走 shell 命令
pub(super) fn deep_link_resume(_meta: &SessionMeta, _term: TerminalApp) -> Option<ResumeOutcome> {
None
@@ -173,7 +184,7 @@ pub fn installed_terminals() -> &'static [TerminalApp] {
static CACHE: OnceLock<Vec<TerminalApp>> = OnceLock::new();
CACHE.get_or_init(|| {
let bins: Vec<&str> = TerminalApp::ALL.iter().map(|t| t.id()).collect();
- let found = super::resolve_clis(&bins);
+ let found = resolve_clis(&bins);
TerminalApp::ALL
.into_iter()
.filter(|t| matches!(found.get(t.id()), Some(Some(_))))
@@ -188,26 +199,35 @@ pub fn terminals_for(_agent: AgentId) -> Vec<TerminalApp> {
/// wt/第三方宿主内装的 shell:优先 pwsh(用户装了 7+ 就是它的默认),
/// 缺席退必装的 Windows PowerShell
-fn powershell_bin() -> Option<String> {
- super::resolve_cli("pwsh").or_else(|| super::resolve_cli("powershell"))
+fn powershell_bin() -> anyhow::Result<String> {
+ resolve_cli("pwsh")
+ .or_else(|| resolve_cli("powershell"))
+ .ok_or_else(|| anyhow::anyhow!("PowerShell not found"))
}
+/// PowerShell 会话前缀,`-Command` 后接脚本;`-NoExit` 即 keep-open
+const PS_SESSION: [&str; 3] = ["-NoLogo", "-NoExit", "-Command"];
+
/// 按宿主方言起终端。keep-open 与 POSIX 的 `exec $SHELL` 同位:cmd 用
-/// `/K`,PowerShell 用 `-NoExit`,命令跑完留在交互提示符。
+/// `/K`,PowerShell 用 `-NoExit`,命令跑完留在交互提示符。command 即
+/// mod.rs 经 compose_command 拼好的 PowerShell 形态,PowerShell 系宿主
+/// 直接复用;cmd 宿主方言不同,只能从结构化件重拼。
pub(super) fn launch_shell(
term: TerminalApp,
cli: &str,
args: &[String],
cwd: Option<&str>,
+ command: &str,
) -> anyhow::Result<()> {
let bin = term.id();
- let exe = super::resolve_cli(bin).ok_or_else(|| anyhow::anyhow!("{bin} not found"))?;
+ let exe = resolve_cli(bin).ok_or_else(|| anyhow::anyhow!("{bin} not found"))?;
let mut cmd = Command::new(&exe);
match term {
TerminalApp::Cmd => {
- // cmd 方言内联注入。raw_arg 绕过 std 的 argv 引号规则——cmd 不做
- // argv 解析,std 把整串再包一层引号反而会毁掉内层结构;串首是
- // `cd`/裸词而非引号,cmd 的引号保全规则生效,内层 "…" 原样送达
+ // cmd 方言内联注入(**不得**改用 command:那是 PowerShell 方言)。
+ // raw_arg 绕过 std 的 argv 引号规则——cmd 不做 argv 解析,std 把
+ // 整串再包一层引号反而会毁掉内层结构;串首是 `cd`/裸词而非引号,
+ // cmd 的引号保全规则生效,内层 "…" 原样送达
let mut line = String::from("/K ");
if let Some(dir) = cwd {
// /d:跨盘符 cd 也生效(会话在 D: 而 cmd 起在 C: 的情形)
@@ -219,37 +239,42 @@ pub(super) fn launch_shell(
line.push_str(&cmd_quote(a));
}
cmd.raw_arg(line);
- cmd.creation_flags(CREATE_NEW_CONSOLE);
}
TerminalApp::Pwsh | TerminalApp::WindowsPowershell => {
- cmd.args(["-NoLogo", "-NoExit", "-Command", &compose_command(cli, args, cwd)]);
- cmd.creation_flags(CREATE_NEW_CONSOLE);
+ cmd.args(PS_SESSION).arg(command);
}
TerminalApp::WindowsTerminal => {
// wt 装 PowerShell 会话。工作目录走 wt 自己的 -d,脚本只剩纯调用
// 段(见 ps_call);所有透传参数过 wt_escape——wt 的 `;` 切分
// 无视引号,不转义的分号会把命令行腰斩成两个面板
- let ps = powershell_bin().ok_or_else(|| anyhow::anyhow!("PowerShell not found"))?;
if let Some(dir) = cwd {
cmd.args(["-d", &wt_escape(dir)]);
}
- cmd.args([&wt_escape(&ps), "-NoLogo", "-NoExit", "-Command", &wt_escape(&ps_call(cli, args))]);
- cmd.creation_flags(CREATE_NO_WINDOW);
+ cmd.arg(wt_escape(&powershell_bin()?));
+ cmd.args(PS_SESSION).arg(wt_escape(&ps_call(cli, args)));
}
TerminalApp::Alacritty | TerminalApp::WezTerm => {
// 第三方宿主装 PowerShell 会话:脚本全单引号、无内层双引号,经
// 宿主的 argv 重引号(std → 宿主 → CreateProcess)往返无损;
// 两家 argv 直传、无 wt 那套 `;` 语义,cd 留在脚本里
- let ps = powershell_bin().ok_or_else(|| anyhow::anyhow!("PowerShell not found"))?;
if term == TerminalApp::WezTerm {
cmd.args(["start", "--"]);
} else {
cmd.arg("-e");
}
- cmd.args([ps.as_str(), "-NoLogo", "-NoExit", "-Command", &compose_command(cli, args, cwd)]);
- cmd.creation_flags(CREATE_NO_WINDOW);
+ cmd.arg(powershell_bin()?);
+ cmd.args(PS_SESSION).arg(command);
}
}
+ // 控制台宿主开自己的新窗即终端本体;wt/第三方的 CLI stub 是 console
+ // 子系统,NO_WINDOW 压掉从 GUI 进程起动时闪现的空控制台(对 GUI 子进程
+ // 无效果)
+ cmd.creation_flags(match term {
+ TerminalApp::Cmd | TerminalApp::Pwsh | TerminalApp::WindowsPowershell => CREATE_NEW_CONSOLE,
+ TerminalApp::WindowsTerminal | TerminalApp::Alacritty | TerminalApp::WezTerm => {
+ CREATE_NO_WINDOW
+ }
+ });
spawn_and_reap(cmd)?;
Ok(())
}
@@ -270,9 +295,10 @@ pub(super) fn copy_to_clipboard(text: &str) -> bool {
CloseClipboard, EmptyClipboard, OpenClipboard, SetClipboardData,
};
use windows_sys::Win32::System::Memory::{GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE};
+ // windows-sys 里它归 Win32_System_Ole feature,为一个钉死的小常量不拉
const CF_UNICODETEXT: u32 = 13;
- let wide: Vec<u16> = text.encode_utf16().chain(std::iter::once(0)).collect();
+ let wide = wide(text);
let bytes = wide.len() * 2;
unsafe {
let mut opened = false;
@@ -321,7 +347,6 @@ pub(super) fn alert_dialog(message: &str) {
use windows_sys::Win32::UI::WindowsAndMessaging::{
MessageBoxW, MB_ICONERROR, MB_OK, MB_SETFOREGROUND, MB_TOPMOST,
};
- let wide = |s: &str| s.encode_utf16().chain(std::iter::once(0)).collect::<Vec<u16>>();
let text = wide(message);
let caption = wide("Wake can't start");
unsafe {
diff --git a/crates/wake/build.rs b/crates/wake/build.rs
index d060ca2..92c391e 100644
--- a/crates/wake/build.rs
+++ b/crates/wake/build.rs
@@ -5,12 +5,14 @@
//! (scripts/make-windows.ps1 头注有再生成命令)。
fn main() {
+ // rerun 声明先于 early return:零声明的 build script 会退回"包内任一
+ // 文件变了就重跑",非 Windows 平台的增量构建也白付一次空转
+ println!("cargo:rerun-if-changed=assets/icon.ico");
// 按编译目标而非宿主判断:交叉构建(如 Linux 上 cargo check windows 目标)
// 也要走这支;宿主没有 rc/windres 工具链时降级为警告,不挡 check
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
- println!("cargo:rerun-if-changed=assets/icon.ico");
let mut res = winresource::WindowsResource::new();
res.set_icon("assets/icon.ico");
res.set("ProductName", "Wake");
diff --git a/crates/wake/src/ui.rs b/crates/wake/src/ui.rs
index c17406a..bd6f4c2 100644
--- a/crates/wake/src/ui.rs
+++ b/crates/wake/src/ui.rs
@@ -45,6 +45,12 @@ pub const REVEAL_IN_FM: &str = if cfg!(target_os = "macos") {
"Reveal in File Manager"
};
+/// 系统回收站的平台名词(macOS 与 freedesktop 都叫 Trash,Windows 是
+/// Recycle Bin)。删除确认/成功通知/菜单项一律引用,与 wake-core
+/// windows.rs 失败文案的名词保持同一个词。
+pub const TRASH_NOUN: &str =
+ if cfg!(target_os = "windows") { "Recycle Bin" } else { "Trash" };
+
/// ⌘K 面板的唯一绑定串——main.rs 的 bind_keys 与下方徽标同源,改键只动这里
pub const SEARCH_KEYSTROKE: &str = "secondary-k";
diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rs
index bab88f0..0c36c25 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -1264,17 +1264,14 @@ impl Workbench {
let expanded = expand_tilde(raw_text.trim());
// 尾分隔符归一(展示与重叠判定都吃这份);裸根("/"、"C:\")剪完会
// 失去绝对性,原样保留。is_absolute 三端同判据——starts_with('/')
- // 会把所有 Windows 盘符路径误拒
+ // 会把所有 Windows 盘符路径误拒(空串它也判 false,无需单独挡)
let trimmed = expanded.trim_end_matches(std::path::is_separator);
- let path = if std::path::Path::new(trimmed).is_absolute() {
- trimmed.to_string()
- } else {
- expanded
- };
- if path.is_empty() || !std::path::Path::new(&path).is_absolute() {
+ let path = if std::path::Path::new(trimmed).is_absolute() { trimmed } else { &expanded };
+ if !std::path::Path::new(path).is_absolute() {
window.push_notification(Notification::warning("Enter an absolute folder path"), cx);
return false;
}
+ let path = path.to_string();
// 各家归一化(codex:直选 sessions 树/平铺 archived 上提到家层,侧档
// 找回)。静态分派,不依赖该家实例是否还在 roster(默认被移除时也要
// 生效);归一化后再做无改动/重叠判定,选中默认根数据子目录会正确判"已覆盖"
@@ -1992,7 +1989,10 @@ impl Workbench {
if this.detail.as_ref().is_some_and(|d| d.meta.key == key) {
this.detail = None;
}
- window.push_notification(Notification::success("Session moved to Trash"), cx);
+ window.push_notification(
+ Notification::success(format!("Session moved to {TRASH_NOUN}")),
+ cx,
+ );
// 立刻把它从列表摘掉,不等 watcher 那 800ms 去抖
this.refresh(window, cx);
}
@@ -2031,14 +2031,16 @@ impl Workbench {
.confirm()
.button_props(
gpui_component::dialog::DialogButtonProps::default()
- .ok_text("Move to Trash")
+ .ok_text(format!("Move to {TRASH_NOUN}"))
.ok_variant(gpui_component::button::ButtonVariant::Danger),
)
.child(
v_flex()
.gap(SPACE_SM)
.text_size(FONT_BODY)
- .child("The session file will be moved to Trash. You can restore it anytime:")
+ .child(format!(
+ "The session file will be moved to {TRASH_NOUN}. You can restore it anytime:"
+ ))
.child(
div()
.px(SPACE_SM)
@@ -2687,7 +2689,7 @@ impl Workbench {
)
.separator()
.item(
- PopupMenuItem::new(" Move to Trash")
+ PopupMenuItem::new(format!(" Move to {TRASH_NOUN}"))
.icon(icon("icons/trash-2.svg").with_size(px(15.)))
.on_click(move |_, window, cx| {
delete_entity.update(cx, |this, cx| {
diff --git a/scripts/make-windows.ps1 b/scripts/make-windows.ps1
index e5b098e..2639735 100644
--- a/scripts/make-windows.ps1
+++ b/scripts/make-windows.ps1
@@ -20,8 +20,7 @@ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# 二进制名 Wake.exe 来自 [[bin]](macOS 菜单栏取进程名所需);Windows 惯例
# 首字母大写正好同形,不再改名
-$stageRoot = Join-Path ([System.IO.Path]::GetTempPath()) "wake-stage"
-$stage = Join-Path $stageRoot "wake-$version-windows-$arch"
+$stage = Join-Path ([System.IO.Path]::GetTempPath()) "wake-stage\wake-$version-windows-$arch"
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
New-Item -ItemType Directory -Path $stage -Force | Out-Null
Copy-Item (Join-Path $targetDir "release/Wake.exe") (Join-Path $stage "Wake.exe")