Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

chore: release v0.22.0 (#900)

Mao Mr1544ef5033ab
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0bbade9e..ff9022a6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -267,6 +267,17 @@ jobs:
run: cargo test --all-features --locked
working-directory: src-tauri
+ # 与下面的「Check startup regression stability」同形:`for` 必须以 `done` 收尾,
+ # 且必须显式声明 working-directory —— 否则 cargo 会在仓库根目录执行、
+ # 找不到 workspace(Cargo.toml 在 src-tauri/ 下)。
+ - name: Check plugin update cache stability
+ shell: bash
+ run: |
+ for iteration in 1 2 3 4 5; do
+ cargo test --all-features --locked service::plugin::update::tests:: -- --test-threads=1 || exit 1
+ done
+ working-directory: src-tauri
+
- name: Check startup regression stability
shell: bash
run: |
diff --git a/README.en.md b/README.en.md
index 8ef363eb..6ac4c6db 100644
--- a/README.en.md
+++ b/README.en.md
@@ -103,6 +103,10 @@ brew install dsh-tauri/desktop/deepseek-harness
- Local execution is not fully offline: model services, plugin installation, updates, and preset pet media can still use network.
- For Linux display, Wayland, AppImage, and permission workarounds, see the [installation and troubleshooting docs](https://dshtauri.mintlify.site).
+- In the startup window, open **Configuration → Network** to set an HTTP, HTTPS, SOCKS5 or SOCKS5H proxy for desktop runtime/core downloads, update checks and plugin metadata queries. Leave it empty to inherit system/environment proxy settings. Changes apply to new requests; retry failed downloads after saving. SOCKS5H resolves destination names through the proxy, and loopback connections stay direct. This setting does not change Harness model requests or plugin subprocess networking.
+
+The proxy URL, including any credentials, is stored in the local desktop configuration. Prefer an HTTPS proxy when authenticating to a remote proxy: an HTTP proxy connection does not encrypt proxy credentials, even when the destination website uses HTTPS.
+
## Runtime
On Windows, `STARTUP_LOW_INTEGRITY` means the process is running below Medium integrity and cannot write normal user data. This can happen when an installation folder has an inherited Low integrity label: a replacement executable can inherit it during an update. Inspect the folder and executable with `icacls`; restore the trusted installation's labels to Medium, or reinstall into a normal folder. Running the same Low-labeled executable as administrator does not remove its integrity restriction. Keep sessions and `DSH_HOME` unchanged. Startup failures now show a native Windows dialog with the underlying error.
diff --git a/README.md b/README.md
index 417ffa42..6b45c776 100644
--- a/README.md
+++ b/README.md
@@ -103,6 +103,10 @@ brew install dsh-tauri/desktop/deepseek-harness
- 本地运行不等于完全离线:模型服务、插件安装、更新与桌宠预设素材仍可能联网。
- Linux 显示、Wayland、AppImage 与权限问题的处理见[安装与故障排查文档](https://dshtauri.mintlify.site)。
+- 启动界面的「配置 → 网络」可设置 HTTP、HTTPS、SOCKS5 或 SOCKS5H 代理,用于桌面端依赖/核心下载、更新检查及插件元数据查询。留空沿用系统/环境代理;保存后对新请求生效,下载失败后可重试。SOCKS5H 通过代理解析目标域名,本机回环连接始终直连。此设置不修改 Harness 模型请求或插件子进程的网络配置。
+
+代理 URL(包括填入的账号密码)保存在本机桌面配置中。远程代理需要账号密码时,建议使用 HTTPS 代理;HTTP 代理连接不会加密代理认证信息,即使请求的目标网站使用 HTTPS。
+
## 运行方式
Windows 上出现 `STARTUP_LOW_INTEGRITY` 表示进程以低于 Medium 的完整性级别运行,无法写入正常用户的数据目录。安装目录若带有可继承的 Low 标签,更新替换的可执行文件可能继承该标签。可用 `icacls` 检查安装目录及可执行文件,将可信安装的标签恢复为 Medium,或重新安装到正常目录。以管理员身份运行同一个 Low 标签程序不会移除其完整性限制。无需删除会话或修改 `DSH_HOME`;启动失败时会通过原生 Windows 对话框显示具体错误。
diff --git a/package.json b/package.json
index a164718f..83f4f308 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "deepseek-harness-desktop",
"type": "module",
- "version": "0.21.2",
+ "version": "0.22.0",
"private": true,
"packageManager": "[email protected]",
"description": "Desktop application for DeepSeek Harness (dsh) — one-click local install and launch, no Node.js setup required.",
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index af40cadd..63d8dced 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -1040,7 +1040,7 @@ dependencies = [
[[package]]
name = "deepseek-harness-desktop"
-version = "0.21.2"
+version = "0.22.0"
dependencies = [
"arboard",
"async-trait",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 4cdc8559..0d76ab5c 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "deepseek-harness-desktop"
-version = "0.21.2"
+version = "0.22.0"
description = "Desktop application for DeepSeek Harness (dsh)"
authors = [ "deepseek-harness-desktop contributors" ]
edition = "2021"
@@ -85,7 +85,8 @@ tracing-log = "0.2"
time = { version = "0.3", features = [ "formatting" ] }
reqwest = { version = "0.12", features = [
"json",
- "stream"
+ "stream",
+ "socks"
] }
rdev = "0.5.3"
zip = "0.6"
diff --git a/src-tauri/src/bridge/config.rs b/src-tauri/src/bridge/config.rs
index f59b7971..2ba10992 100644
--- a/src-tauri/src/bridge/config.rs
+++ b/src-tauri/src/bridge/config.rs
@@ -36,6 +36,7 @@ pub fn is_dev_build() -> bool {
#[allow(clippy::too_many_arguments)]
pub async fn update_app_config(
app_handle: AppHandle,
+ proxy_url: Option<String>,
appearance: Option<config::Appearance>,
port: Option<u16>,
zoom_factor: Option<f64>,
@@ -46,6 +47,10 @@ pub async fn update_app_config(
backup_retention_count: Option<u32>,
backup_include_credentials: Option<bool>,
) -> Result<config::Setting, String> {
+ let proxy_url = proxy_url
+ .as_deref()
+ .map(config::proxy::normalize_proxy_url)
+ .transpose()?;
if let Some(port) = port {
if port == 0 {
return Err("port must be a positive number".to_string());
@@ -61,6 +66,9 @@ pub async fn update_app_config(
}
}
let setting = config::update_store_dat_setting(&app_handle, |setting| {
+ if let Some(proxy_url) = proxy_url {
+ setting.proxy_url = proxy_url;
+ }
if let Some(appearance) = appearance {
setting.appearance = appearance;
}
diff --git a/src-tauri/src/bridge/lifecycle.rs b/src-tauri/src/bridge/lifecycle.rs
index 2eb10623..4cc4c0d7 100644
--- a/src-tauri/src/bridge/lifecycle.rs
+++ b/src-tauri/src/bridge/lifecycle.rs
@@ -159,8 +159,8 @@ pub async fn install_dependencies(app_handle: AppHandle) -> Result<bool, String>
None
} else {
Some(match recommended_version {
- Some(version) => download::fetch_dsh_pkg_version(&version).await,
- None => download::fetch_latest_dsh_pkg_info().await,
+ Some(version) => download::fetch_dsh_pkg_version(&app_handle, &version).await,
+ None => download::fetch_latest_dsh_pkg_info(&app_handle).await,
})
};
@@ -177,7 +177,7 @@ pub async fn install_dependencies(app_handle: AppHandle) -> Result<bool, String>
// 老记录没有 tag,反查 pkg 仓库 tags 列表确认记录对应的发布版本;
// 反查失败时由 resolve_update 回退到“以实际文件为准”的保守分支
let legacy_tags = if record_tag.is_none() {
- download::fetch_dsh_pkg_tags().await.unwrap_or_default()
+ download::fetch_dsh_pkg_tags(&app_handle).await.unwrap_or_default()
} else {
Vec::new()
};
@@ -304,7 +304,7 @@ pub async fn check_dsh_update(
return Ok(None);
}
- let latest = download::fetch_latest_dsh_pkg_info().await?;
+ let latest = download::fetch_latest_dsh_pkg_info(&app_handle).await?;
// 关键修复1:最新 release 的版本号已经在已装核心列表里(含 active 和非 active
// 槽位),就不提示更新。避免「老版本激活 + 新版已下载但未切换」场景下白点一次
diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rs
index 2e1fc0f7..89ee9cbe 100644
--- a/src-tauri/src/bridge/pet.rs
+++ b/src-tauri/src/bridge/pet.rs
@@ -544,6 +544,15 @@ pub fn move_pet_window(app: AppHandle, delta_x: i32, delta_y: i32) -> Result<(),
pet_window::move_pet_window(&app, delta_x, delta_y)
}
+/// 拖拽收尾:把桌宠窗口当前位置落盘,不做显示器夹取。
+///
+/// 位置由前端按宠物本体边界夹好(贴边也算合法),整窗夹取会在松手瞬间把宠物从
+/// 屏幕边缘推开;见 `desktop::pet::persist_pet_window_position` 的文档。
+#[tauri::command]
+pub fn persist_pet_window_position(app: AppHandle) -> Result<(), String> {
+ pet_window::persist_pet_window_position(&app)
+}
+
/// 串行化桌宠窗口的可见性操作,保证「关闭 → 再启用」按调用顺序执行。
fn pet_window_op_lock() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rs
index 0ea3314e..0f146d30 100644
--- a/src-tauri/src/bridge/plugin.rs
+++ b/src-tauri/src/bridge/plugin.rs
@@ -7,6 +7,8 @@ use crate::config;
use crate::service::plugin;
use tauri::AppHandle;
use tauri::Emitter;
+#[cfg(windows)]
+use tauri::Manager;
use tauri_plugin_opener::OpenerExt;
fn mark_preinstall_done(app_handle: &AppHandle) {
@@ -86,6 +88,29 @@ pub async fn install_plugin_specs(app_handle: AppHandle, specs: Vec<String>) ->
Ok(())
}
+/// 本地插件热重载的当前状态:生效开关、补丁层路径与被监听的源码目录。
+#[tauri::command]
+pub async fn get_local_plugin_hmr(app_handle: AppHandle) -> Result<plugin::LocalHmrStatus, String> {
+ Ok(plugin::local_plugin_hmr_status(&app_handle))
+}
+
+/// 开关本地插件热重载:开关变化会立即复算补丁层,下次启动服务时生效。
+#[tauri::command]
+pub async fn set_local_plugin_hmr(
+ app_handle: AppHandle,
+ enabled: bool,
+) -> Result<plugin::LocalHmrStatus, String> {
+ config::update_store_dat_setting(&app_handle, |setting| {
+ setting.local_plugin_hmr = enabled;
+ });
+ let patch = plugin::local_plugin_hmr_sync(&app_handle);
+ log::info!(
+ "[hmr] local plugin hot reload set to {enabled}, layer: {:?}",
+ patch.as_ref().map(|path| path.display().to_string())
+ );
+ Ok(plugin::local_plugin_hmr_status(&app_handle))
+}
+
/// 只读检查一组 spec 的兼容性(registry `latest` 上的 DSH 家族 peer 依赖),
/// 不改动本地 profile;失败项收敛为结果里的 `problem`,不整体报错。
#[tauri::command]
@@ -321,6 +346,43 @@ pub async fn restore_plugin(app_handle: AppHandle, id: String) -> Result<(), Str
Ok(())
}
+/// 弹出系统文件夹选择器,返回可直接安装的本地插件 `link:` spec(取消时为 `None`)。
+///
+/// Windows 的文件夹选择器是 COM 组件(`CoInitializeEx` 要求 STA 单元),而异步命令体跑在
+/// 线程池上、线程的 COM 单元不确定;因此把对话框搬到主线程(tao 建窗时已初始化 STA),
+/// 再同步等它关闭:阻塞的是原生对话框自身,异步运行时不阻塞。
+/// 其余平台没有可用的原生选择器,直接拒绝,由前端隐藏入口。
+#[tauri::command]
+pub async fn pick_local_plugin_dir(app_handle: AppHandle) -> Result<Option<String>, String> {
+ #[cfg(windows)]
+ {
+ let (sender, receiver) = tokio::sync::oneshot::channel();
+ let app = app_handle.clone();
+ app_handle
+ .run_on_main_thread(move || {
+ let mut dialog = rfd::FileDialog::new().set_title("选择本地插件目录");
+ if let Some(window) =
+ app.get_webview_window(crate::desktop::builder::MAIN_WINDOW_LABEL)
+ {
+ dialog = dialog.set_parent(&window);
+ }
+ let picked = dialog
+ .pick_folder()
+ .map(|dir| plugin::local_spec_from_path(&dir));
+ let _ = sender.send(picked);
+ })
+ .map_err(|error| format!("PLUGIN_PICK_FOLDER_FAILED: {error}"))?;
+ receiver
+ .await
+ .map_err(|error| format!("PLUGIN_PICK_FOLDER_FAILED: {error}"))
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = app_handle;
+ Err("PLUGIN_PICK_FOLDER_UNSUPPORTED: native folder picker is Windows-only".to_string())
+ }
+}
+
/// 删除单个插件的快照(卸载级联清理 / 手动删除):幂等,无快照视为成功。
#[tauri::command]
pub fn delete_plugin_backup(app_handle: AppHandle, id: String) -> Result<(), String> {
diff --git a/src-tauri/src/bridge/updater.rs b/src-tauri/src/bridge/updater.rs
index 36162d38..53777242 100644
--- a/src-tauri/src/bridge/updater.rs
+++ b/src-tauri/src/bridge/updater.rs
@@ -30,6 +30,6 @@ pub async fn open_desktop_installer(app_handle: AppHandle, path: String) -> Resu
/// 关于对话框信息(版本 / 发布时间 / 版权 / 仓库)
#[tauri::command]
-pub async fn get_desktop_about() -> Result<update::DesktopAboutInfo, String> {
- Ok(update::about().await)
+pub async fn get_desktop_about(app_handle: AppHandle) -> Result<update::DesktopAboutInfo, String> {
+ Ok(update::about(&app_handle).await)
}
diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs
index ff3ff447..f27cf50d 100644
--- a/src-tauri/src/config/mod.rs
+++ b/src-tauri/src/config/mod.rs
@@ -4,6 +4,7 @@ mod constants;
pub mod dependencies;
pub mod i18n;
pub mod manifest;
+pub mod proxy;
mod region;
mod runtime;
mod setting;
diff --git a/src-tauri/src/config/proxy.rs b/src-tauri/src/config/proxy.rs
new file mode 100644
index 00000000..253b2582
--- /dev/null
+++ b/src-tauri/src/config/proxy.rs
@@ -0,0 +1,246 @@
+use reqwest::{ClientBuilder, NoProxy, Proxy, Url};
+use tauri::{AppHandle, Runtime};
+
+pub fn normalize_proxy_url(value: &str) -> Result<String, String> {
+ let value = value.trim();
+ if value.is_empty() {
+ return Ok(String::new());
+ }
+ let invalid = || {
+ "PROXY_INVALID: use an HTTP, HTTPS, SOCKS5 or SOCKS5H proxy URL without a path, query or fragment".to_string()
+ };
+ if !value.contains("://") || value.chars().any(char::is_whitespace) {
+ return Err(invalid());
+ }
+ let url = Url::parse(value).map_err(|_| invalid())?;
+ if !matches!(url.scheme(), "http" | "https" | "socks5" | "socks5h")
+ || url.host_str().is_none()
+ || url.port() == Some(0)
+ || !matches!(url.path(), "" | "/")
+ || url.query().is_some()
+ || url.fragment().is_some()
+ {
+ return Err(invalid());
+ }
+ Proxy::all(url.as_str()).map_err(|_| invalid())?;
+ Ok(url.to_string())
+}
+
+pub fn http_client_builder<R: Runtime>(app: &AppHandle<R>) -> Result<ClientBuilder, String> {
+ client_builder(&super::get_store_dat_setting(app).proxy_url)
+}
+
+pub(crate) fn client_builder(value: &str) -> Result<ClientBuilder, String> {
+ let url = normalize_proxy_url(value)?;
+ let builder = reqwest::Client::builder();
+ if url.is_empty() {
+ return Ok(builder);
+ }
+ let proxy = Proxy::all(&url)
+ .map_err(|_| "PROXY_INVALID: unsupported proxy URL".to_string())?
+ .no_proxy(NoProxy::from_string("localhost,.localhost,127.0.0.0/8,::1"));
+ Ok(builder.no_proxy().proxy(proxy))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::TcpListener;
+
+ async fn read_headers(stream: &mut tokio::net::TcpStream) -> String {
+ let mut bytes = Vec::new();
+ while !bytes.ends_with(b"\r\n\r\n") {
+ assert!(bytes.len() < 4096);
+ bytes.push(stream.read_u8().await.unwrap());
+ }
+ String::from_utf8(bytes).unwrap()
+ }
+
+ #[test]
+ fn accepts_supported_proxy_schemes_and_empty_inheritance() {
+ for value in [
+ "http://localhost:7897",
+ "https://proxy.example:8443",
+ "socks5://127.0.0.1:1080",
+ "socks5h://[::1]:1080",
+ "http://user:[email protected]:8080",
+ ] {
+ assert!(normalize_proxy_url(value).is_ok(), "{value}");
+ }
+ assert_eq!(normalize_proxy_url(" ").unwrap(), "");
+ assert_eq!(
+ normalize_proxy_url(" http://localhost:7897 ").unwrap(),
+ "http://localhost:7897/"
+ );
+ }
+
+ #[test]
+ fn rejects_invalid_proxy_addresses_without_echoing_credentials() {
+ for value in [
+ "localhost:7897",
+ "http:proxy.example",
+ "ftp://proxy.example",
+ "http://",
+ "http://proxy.example:0",
+ "http://proxy.example:65536",
+ "http://proxy.example/path",
+ "http://proxy.example?q=1",
+ "http://proxy.example#fragment",
+ "http://user:[email protected]/path",
+ "http://proxy. example",
+ ] {
+ let error = normalize_proxy_url(value).unwrap_err();
+ assert!(error.starts_with("PROXY_INVALID:"));
+ assert!(!error.contains("secret"));
+ }
+ }
+
+ #[tokio::test]
+ async fn external_http_request_reaches_the_configured_proxy() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let proxy = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let request = read_headers(&mut stream).await;
+ stream
+ .write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\nproxied",
+ )
+ .await
+ .unwrap();
+ request
+ });
+ let client = client_builder(&format!("http://{address}"))
+ .unwrap()
+ .timeout(std::time::Duration::from_secs(3))
+ .build()
+ .unwrap();
+ let response = client
+ .get("http://dsh-proxy-test.invalid/resource")
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.text().await.unwrap(), "proxied");
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_secs(3), proxy)
+ .await
+ .unwrap()
+ .unwrap()
+ .starts_with("GET http://dsh-proxy-test.invalid/resource HTTP/1.1\r\n")
+ );
+ }
+
+ #[tokio::test]
+ async fn loopback_request_bypasses_an_unreachable_explicit_proxy() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ read_headers(&mut stream).await;
+ stream
+ .write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\ndirect",
+ )
+ .await
+ .unwrap();
+ });
+ let client = client_builder("http://127.0.0.1:1")
+ .unwrap()
+ .timeout(std::time::Duration::from_secs(3))
+ .build()
+ .unwrap();
+ let response = client
+ .get(format!("http://{address}/health"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.text().await.unwrap(), "direct");
+ server.await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn https_request_uses_connect_with_proxy_authentication() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let proxy = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let request = read_headers(&mut stream).await;
+ stream
+ .write_all(
+ b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ )
+ .await
+ .unwrap();
+ request
+ });
+ let client = client_builder(&format!("http://user:secret@{address}"))
+ .unwrap()
+ .timeout(std::time::Duration::from_secs(3))
+ .build()
+ .unwrap();
+ assert!(client
+ .get("https://dsh-proxy-test.invalid/resource")
+ .send()
+ .await
+ .is_err());
+ let request = tokio::time::timeout(std::time::Duration::from_secs(3), proxy)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(request.starts_with("CONNECT dsh-proxy-test.invalid:443 HTTP/1.1\r\n"));
+ assert!(request
+ .to_ascii_lowercase()
+ .contains("proxy-authorization: basic dxnlcjpzzwnyzxq=\r\n"));
+ }
+
+ #[tokio::test]
+ async fn socks5h_resolves_the_destination_at_the_proxy() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let proxy = tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ assert_eq!(stream.read_u8().await.unwrap(), 5);
+ let count = stream.read_u8().await.unwrap();
+ let mut methods = vec![0; count as usize];
+ stream.read_exact(&mut methods).await.unwrap();
+ assert!(methods.contains(&0));
+ stream.write_all(&[5, 0]).await.unwrap();
+ let mut command = [0; 4];
+ stream.read_exact(&mut command).await.unwrap();
+ assert_eq!(command, [5, 1, 0, 3]);
+ let length = stream.read_u8().await.unwrap();
+ let mut host = vec![0; length as usize];
+ stream.read_exact(&mut host).await.unwrap();
+ assert_eq!(host, b"dsh-proxy-test.invalid");
+ assert_eq!(stream.read_u16().await.unwrap(), 80);
+ stream
+ .write_all(&[5, 0, 0, 1, 127, 0, 0, 1, 0, 80])
+ .await
+ .unwrap();
+ let request = read_headers(&mut stream).await;
+ assert!(request.starts_with("GET /resource HTTP/1.1\r\n"));
+ stream
+ .write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\nproxied",
+ )
+ .await
+ .unwrap();
+ });
+ let client = client_builder(&format!("socks5h://{address}"))
+ .unwrap()
+ .timeout(std::time::Duration::from_secs(3))
+ .build()
+ .unwrap();
+ let response = client
+ .get("http://dsh-proxy-test.invalid/resource")
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.text().await.unwrap(), "proxied");
+ tokio::time::timeout(std::time::Duration::from_secs(3), proxy)
+ .await
+ .unwrap()
+ .unwrap();
+ }
+}
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index eda64f63..ee69b4fc 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -7,6 +7,8 @@ use tauri_plugin_store::StoreExt;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Setting {
+ #[serde(default)]
+ pub proxy_url: String,
#[serde(default)]
pub appearance: super::Appearance,
pub installed: bool,
@@ -86,6 +88,10 @@ pub struct Setting {
/// 代价是主窗口也一并经 XWayland 渲染。默认关闭,由用户显式开启。
#[serde(default)]
pub force_xwayland: bool,
+ /// 本地插件热重载:把已挂载的本地路径插件源码目录交给核心 HMR 监听,
+ /// 源码改动即时生效(无需重启服务)。没有本地插件时不产生任何补丁层。
+ #[serde(default = "default_local_plugin_hmr")]
+ pub local_plugin_hmr: bool,
}
pub const ZOOM_FACTOR_MIN: f64 = 0.5;
@@ -125,6 +131,12 @@ pub fn default_backup_retention_count() -> u32 {
10
}
+/// 本地插件热重载默认开启:只有确实装了本地路径插件时才会产生监听目录,
+/// 未使用该能力的用户完全不受影响。
+pub fn default_local_plugin_hmr() -> bool {
+ true
+}
+
/// 把外部或旧存储中的关闭行为收敛到白名单,未知值一律回落到默认行为。
///
/// 只做精确匹配:不做 `trim()`、不做大小写折叠——store 可被手工编辑、旧版本或其它
@@ -156,6 +168,7 @@ pub fn normalize_backup_retention(retention_count: u32) -> u32 {
}
fn normalize_setting(setting: &mut Setting) {
+ setting.proxy_url = super::proxy::normalize_proxy_url(&setting.proxy_url).unwrap_or_default();
setting.appearance.normalize();
setting.zoom_factor = normalize_zoom_factor(setting.zoom_factor);
setting.harness_max_heap_mb = normalize_harness_max_heap_mb(setting.harness_max_heap_mb);
@@ -175,6 +188,7 @@ pub fn default_port() -> u16 {
impl Default for Setting {
fn default() -> Self {
Self {
+ proxy_url: String::new(),
appearance: super::Appearance::default(),
installed: false,
port: default_port(),
@@ -198,6 +212,7 @@ impl Default for Setting {
active_pet: None,
pet_size: None,
force_xwayland: false,
+ local_plugin_hmr: default_local_plugin_hmr(),
}
}
}
@@ -309,7 +324,7 @@ fn setting_from_value(value: Option<&serde_json::Value>) -> Setting {
setting
}
-fn read_store_dat_setting<R: Runtime>(app_handle: &AppHandle<R>) -> Setting {
+pub(crate) fn read_store_dat_setting<R: Runtime>(app_handle: &AppHandle<R>) -> Setting {
let store = app_handle
.store(store_dat_file_name())
.expect("Failed to load store");
@@ -334,6 +349,7 @@ fn emit_setting(app_handle: &AppHandle, value: &serde_json::Value) {
}
fn preserve_persisted_fields(mut replacement: Setting, current: &Setting) -> Setting {
+ replacement.proxy_url.clone_from(&current.proxy_url);
replacement.appearance.clone_from(&current.appearance);
replacement.zoom_factor = normalize_zoom_factor(current.zoom_factor);
replacement.harness_max_heap_mb = normalize_harness_max_heap_mb(current.harness_max_heap_mb);
@@ -342,11 +358,12 @@ fn preserve_persisted_fields(mut replacement: Setting, current: &Setting) -> Set
replacement.active_pet.clone_from(&current.active_pet);
replacement.pet_size = current.pet_size;
replacement.force_xwayland = current.force_xwayland;
+ replacement.local_plugin_hmr = current.local_plugin_hmr;
replacement
}
-/// 兼容旧调用方的整对象写入,但始终保留锁内读到的最新缩放、关窗动作与桌宠
-/// 持久字段,避免长流程用陈旧 `Setting` 覆盖精确更新路径刚写入的值(丢更新)。
+/// 兼容旧调用方的整对象写入,但始终保留锁内读到的最新缩放、关窗动作、桌宠与本地
+/// 插件热重载等持久字段,避免长流程用陈旧 `Setting` 覆盖精确更新路径刚写入的值(丢更新)。
pub fn set_store_dat_setting(app_handle: &AppHandle, mut setting: Setting) {
let value = {
let _guard = setting_write_lock()
@@ -693,10 +710,12 @@ mod tests {
active_pet: Some("chat:stale".to_string()),
pet_size: Some(80.0),
force_xwayland: false,
+ local_plugin_hmr: false,
..Default::default()
};
let current = Setting {
+ proxy_url: "socks5h://127.0.0.1:1080".to_string(),
appearance: super::super::Appearance {
palette: "nord".into(),
terminal: true,
@@ -711,11 +730,13 @@ mod tests {
active_pet: Some("codex:latest".to_string()),
pet_size: Some(140.0),
force_xwayland: true,
+ local_plugin_hmr: true,
..Default::default()
};
let merged = preserve_persisted_fields(stale, &current);
+ assert_eq!(merged.proxy_url, current.proxy_url);
assert!(merged.installed);
assert_eq!(merged.language, "en-US");
assert_eq!(merged.port, 4099);
@@ -737,6 +758,24 @@ mod tests {
merged.force_xwayland,
"整对象写入不得覆盖最新的 XWayland 开关"
);
+ assert!(
+ merged.local_plugin_hmr,
+ "整对象写入不得覆盖最新的本地插件热重载开关"
+ );
+ }
+
+ #[test]
+ fn proxy_setting_survives_serialization_and_defaults_for_legacy_settings() {
+ let setting = Setting {
+ proxy_url: "socks5h://127.0.0.1:1080".to_string(),
+ ..Default::default()
+ };
+ let mut value = serde_json::to_value(&setting).unwrap();
+ let restored: Setting = serde_json::from_value(value.clone()).unwrap();
+ assert_eq!(restored.proxy_url, "socks5h://127.0.0.1:1080");
+ value.as_object_mut().unwrap().remove("proxy_url");
+ let legacy: Setting = serde_json::from_value(value).unwrap();
+ assert_eq!(legacy.proxy_url, "");
}
#[test]
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 4cbe0172..e68a700e 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1490,6 +1490,9 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::install_preinstall_plugins,
crate::bridge::install_plugin_specs,
crate::bridge::inspect_plugin_specs,
+ crate::bridge::get_local_plugin_hmr,
+ crate::bridge::set_local_plugin_hmr,
+ crate::bridge::pick_local_plugin_dir,
crate::bridge::cancel_plugin_processes,
crate::bridge::allow_plugin_versions,
crate::bridge::allow_plugin_policy_versions,
@@ -1573,6 +1576,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::set_pet_size,
crate::bridge::push_pet_session,
crate::bridge::move_pet_window,
+ crate::bridge::persist_pet_window_position,
crate::bridge::set_pet_ignore_cursor_events,
crate::bridge::list_pets,
crate::bridge::import_pet,
diff --git a/src-tauri/src/desktop/pet.rs b/src-tauri/src/desktop/pet.rs
index 0d2a3fc9..fa53c05a 100644
--- a/src-tauri/src/desktop/pet.rs
+++ b/src-tauri/src/desktop/pet.rs
@@ -281,6 +281,35 @@ pub fn move_pet_window<R: Runtime>(
Ok(())
}
+/// 只把桌宠窗口当前位置落盘,不做任何显示器夹取。
+///
+/// # 为什么不复用 `move_pet_window(app, 0, 0)`
+///
+/// `move_pet_window` 夹的是**整个窗口**,而宠物只是窗口底部居中的一小块,四周是
+/// 透明留白(`PET_WINDOW_PAD_X` / `PET_WINDOW_TOP_PAD` / 窗口最小宽度
+/// `PET_WINDOW_MIN_WIDTH`)。前端跟手时按「宠物本体 / 脚底」边界把窗口夹进显示器
+/// 工作区(与飞行共用边界),整窗夹取会把这些留白也算进去,于是贴边松手的瞬间把
+/// 宠物从边缘推开一段(100% 大小时左侧约 `(420 - 220) / 2 = 100` 物理像素)。
+///
+/// 因此拖拽收尾只负责持久化:位置由前端保证在可见工作区内(见
+/// `src/pet/hooks/use-pet-window-clamp.ts` 与 `src/hooks/use-window-draggable.ts`)。
+pub fn persist_pet_window_position<R: Runtime>(app: &AppHandle<R>) -> Result<(), String> {
+ let window = app
+ .get_webview_window(PET_WINDOW_LABEL)
+ .ok_or_else(|| "PET_WINDOW_NOT_FOUND: pet window has not been created".to_string())?;
+ let current = window.outer_position().map_err(|error| {
+ format!("PET_WINDOW_POSITION_FAILED: failed to read pet window position: {error}")
+ })?;
+ save_pet_window_position(
+ app,
+ &PetWindowPosition {
+ x: Some(current.x),
+ y: Some(current.y),
+ },
+ );
+ Ok(())
+}
+
/// 确保桌宠窗口存在并恢复位置。
///
/// 幂等:已注册时直接复用返回;不存在(首次启用,或上次收起时已被销毁)时
diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rs
index af09a685..6850ab49 100644
--- a/src-tauri/src/service/core/version.rs
+++ b/src-tauri/src/service/core/version.rs
@@ -74,20 +74,20 @@ fn read_manifest_dsh_version(dir: &Path) -> Option<String> {
/// tags(无 label,预览标记按 tag 命名兜底),再失败降级为磁盘扫描,只列出
/// 本地、激活与已下载的历史版本。
pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {
- let (release_metas, remote_catalog_available) = fetch_release_catalog().await;
+ let (release_metas, remote_catalog_available) = fetch_release_catalog(app_handle).await;
rows_with_release_catalog(app_handle, release_metas, remote_catalog_available)
}
/// 版本行数据源:GitHub releases → git tags → 空(离线/限流时调用方降级为磁盘扫描)。
-async fn fetch_release_catalog() -> (Vec<download::DshPkgReleaseMeta>, bool) {
- match download::fetch_dsh_pkg_releases().await {
+async fn fetch_release_catalog(app_handle: &AppHandle) -> (Vec<download::DshPkgReleaseMeta>, bool) {
+ match download::fetch_dsh_pkg_releases(app_handle).await {
Ok(metas) => (metas, true),
Err(e) => {
log::warn!(
"Failed to fetch dsh pkg releases ({}), falling back to git tags",
e
);
- match download::fetch_dsh_pkg_tags().await {
+ match download::fetch_dsh_pkg_tags(app_handle).await {
Ok(tags) => (
tags.into_iter()
.map(|(tag, _)| download::DshPkgReleaseMeta {
@@ -542,7 +542,7 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Str
// 切回随包内核只是把根指回去(见 `set_active` 的 `app-bundled` 分支)。
if config::dependencies::bundled_core_dir(app_handle).is_some() {
stop_harness_for_core_switch(app_handle).await?;
- let commit = match download::fetch_dsh_pkg_tags().await {
+ let commit = match download::fetch_dsh_pkg_tags(app_handle).await {
Ok(tags) => tags.into_iter().find(|(t, _)| t == tag).map(|(_, c)| c),
Err(e) => {
log::warn!("failed to resolve commit for tag {tag}: {e}");
@@ -650,7 +650,7 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Str
}
// 3. 记录切换:tag + commit(commit 从 tags 列表反查,失败保留原值)
- let commit = match download::fetch_dsh_pkg_tags().await {
+ let commit = match download::fetch_dsh_pkg_tags(app_handle).await {
Ok(tags) => tags.into_iter().find(|(t, _)| t == tag).map(|(_, c)| c),
Err(e) => {
log::warn!("failed to resolve commit for tag {tag}: {e}");
@@ -693,7 +693,7 @@ pub async fn download_version(app_handle: &AppHandle, tag: &str) -> Result<Harne
// 1. 拉该 tag 的资产地址 + 可信摘要(digest 缺失时安全中止,沿用
// DSH_INTEGRITY_UNAVAILABLE 设计:不下载无法验证完整性的内容)
- let info = download::fetch_dsh_pkg_asset(tag)
+ let info = download::fetch_dsh_pkg_asset(app_handle, tag)
.await
.map_err(|e| format!("CORE_METADATA_FAILED: {e}"))?;
let digest = info.digest.ok_or_else(|| {
diff --git a/src-tauri/src/service/data_dir/migrate.rs b/src-tauri/src/service/data_dir/migrate.rs
index f0dfd90c..44dc9407 100644
--- a/src-tauri/src/service/data_dir/migrate.rs
+++ b/src-tauri/src/service/data_dir/migrate.rs
@@ -128,6 +128,7 @@ pub(super) fn run(
source.display()
));
}
+ validate_target(source, target)?;
emit(step("migrate", "scan", 0, 0, 0, 0));
let mut expected = TreeStats::default();
fs_ops::scan_tree(source, &mut expected)?;
@@ -340,6 +341,10 @@ fn validate_target(source: &Path, target: &Path) -> Result<(), String> {
if !target.is_absolute() {
return Err(format!("DATA_DIR_TARGET_NOT_ABSOLUTE: {}", target.display()));
}
+ let resolved_source = resolved_path(source)?;
+ let resolved_target = resolved_path(target)?;
+ let source = resolved_source.as_path();
+ let target = resolved_target.as_path();
if same_path(source, target) {
return Err(format!("DATA_DIR_SAME_AS_SOURCE: {}", target.display()));
}
@@ -361,6 +366,39 @@ fn validate_target(source: &Path, target: &Path) -> Result<(), String> {
Ok(())
}
+fn resolved_path(path: &Path) -> Result<PathBuf, String> {
+ let mut existing = path;
+ let mut missing = Vec::new();
+ loop {
+ match fs::canonicalize(existing) {
+ Ok(mut resolved) => {
+ if !missing.is_empty() && !resolved.is_dir() {
+ return Err(format!("DATA_DIR_TARGET_NOT_DIR: {}", existing.display()));
+ }
+ for name in missing.iter().rev() {
+ resolved.push(name);
+ }
+ return Ok(resolved);
+ }
+ Err(error) => {
+ if error.kind() == std::io::ErrorKind::NotFound
+ && matches!(fs::symlink_metadata(existing), Err(ref metadata_error) if metadata_error.kind() == std::io::ErrorKind::NotFound)
+ {
+ if let (Some(name), Some(parent)) = (existing.file_name(), existing.parent()) {
+ missing.push(name);
+ existing = parent;
+ continue;
+ }
+ }
+ return Err(format!(
+ "DATA_DIR_PATH_RESOLVE: {}: {error}",
+ path.display()
+ ));
+ }
+ }
+ }
+}
+
/// 重写 CLI shim 与 pnpm 元数据(best-effort)。
///
/// shim 内容里烘焙着 `DSH_HOME`,不改写的话终端里的 `dsh` 仍指向旧目录;pnpm 的
@@ -449,6 +487,116 @@ fn step(
mod tests {
use super::*;
+ #[test]
+ fn validate_rejects_nested_targets_hidden_by_parent_components() {
+ let root = temp_dir("resolved-parent");
+ let source = root.join("home");
+ fs::create_dir_all(&source).unwrap();
+ fs::create_dir_all(root.join("other")).unwrap();
+ let target = root.join("other").join("..").join("home").join("copy");
+ let result = validate_target(&source, &target);
+ assert!(
+ matches!(result, Err(ref error) if error.starts_with("DATA_DIR_TARGET_INSIDE_SOURCE:")),
+ "{result:?}"
+ );
+ assert!(!source.join("copy").exists());
+ fs::remove_dir_all(root).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn validate_rejects_nested_targets_reached_through_symlinked_parents() {
+ let root = temp_dir("resolved-link");
+ let source = root.join("home");
+ fs::create_dir_all(&source).unwrap();
+ fs::write(source.join("sentinel"), "preserve").unwrap();
+ let alias = root.join("alias");
+ std::os::unix::fs::symlink(&source, &alias).unwrap();
+ let result = validate_target(&source, &alias.join("copy"));
+ assert!(
+ matches!(result, Err(ref error) if error.starts_with("DATA_DIR_TARGET_INSIDE_SOURCE:")),
+ "{result:?}"
+ );
+ assert!(!source.join("copy").exists());
+ assert_eq!(
+ fs::read_to_string(source.join("sentinel")).unwrap(),
+ "preserve"
+ );
+ fs::remove_dir_all(root).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn validate_resolves_the_source_before_comparing_target_boundaries() {
+ let root = temp_dir("resolved-source");
+ let source = root.join("home");
+ fs::create_dir_all(&source).unwrap();
+ let alias = root.join("alias");
+ std::os::unix::fs::symlink(&source, &alias).unwrap();
+ let result = validate_target(&alias, &source.join("copy"));
+ assert!(
+ matches!(result, Err(ref error) if error.starts_with("DATA_DIR_TARGET_INSIDE_SOURCE:")),
+ "{result:?}"
+ );
+ let result = validate_target(&alias, &source);
+ assert!(
+ matches!(result, Err(ref error) if error.starts_with("DATA_DIR_SAME_AS_SOURCE:")),
+ "{result:?}"
+ );
+ fs::remove_dir_all(root).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn validate_allows_separate_targets_under_symlinked_parents() {
+ let root = temp_dir("separate-link");
+ let source = root.join("home");
+ let destination = root.join("separate");
+ fs::create_dir_all(&source).unwrap();
+ fs::create_dir_all(&destination).unwrap();
+ let alias = root.join("alias");
+ std::os::unix::fs::symlink(&destination, &alias).unwrap();
+ assert_eq!(
+ validate_target(&source, &alias.join("new").join("home")),
+ Ok(())
+ );
+ assert!(!destination.join("new").exists());
+ fs::remove_dir_all(root).unwrap();
+ }
+
+ #[test]
+ fn validate_rejects_targets_below_a_regular_file() {
+ let root = temp_dir("file-parent");
+ let source = root.join("home");
+ fs::create_dir_all(&source).unwrap();
+ let file = root.join("file");
+ fs::write(&file, "preserve").unwrap();
+ assert!(validate_target(&source, &file.join("copy")).is_err());
+ assert_eq!(fs::read_to_string(file).unwrap(), "preserve");
+ fs::remove_dir_all(root).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn validate_rejects_dangling_and_cyclic_destination_links() {
+ let root = temp_dir("broken-link");
+ let source = root.join("home");
+ fs::create_dir_all(&source).unwrap();
+ let dangling = root.join("dangling");
+ std::os::unix::fs::symlink(root.join("missing"), &dangling).unwrap();
+ let cyclic = root.join("cyclic");
+ std::os::unix::fs::symlink(&cyclic, &cyclic).unwrap();
+ for parent in [&dangling, &cyclic] {
+ let result = validate_target(&source, &parent.join("copy"));
+ assert!(
+ matches!(result, Err(ref error) if error.starts_with("DATA_DIR_PATH_RESOLVE:")),
+ "{result:?}"
+ );
+ }
+ assert!(!root.join("missing").exists());
+ fs::remove_dir_all(root).unwrap();
+ }
+
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"dsh-data-dir-migrate-{tag}-{}-{}",
diff --git a/src-tauri/src/service/download/core.rs b/src-tauri/src/service/download/core.rs
index fdf2aa09..456b801f 100644
--- a/src-tauri/src/service/download/core.rs
+++ b/src-tauri/src/service/download/core.rs
@@ -8,7 +8,7 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::service::download::ProgressTracker;
-use tauri::Runtime;
+use tauri::{Manager, Runtime};
/// 下载文件到内存
///
@@ -83,7 +83,7 @@ async fn download_with_retry<'a, R: Runtime>(
tracker.update(0.0, String::new(), format!("Download {}", url));
// 创建具备 User-Agent 的客户端
- let client = reqwest::Client::builder()
+ let client = crate::config::proxy::http_client_builder(tracker.window.app_handle())?
.user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (deepseek-harness-desktop)")
.connect_timeout(std::time::Duration::from_secs(20))
.read_timeout(Duration::from_secs(30))
@@ -291,12 +291,12 @@ pub fn verify_sha256(buffer: &[u8], expected: &str) -> Result<(), String> {
}
/// 从 Node.js 官方同版本 SHASUMS256.txt 中读取当前平台包的摘要。
-pub async fn fetch_node_sha256(download_url: &str) -> Result<String, String> {
+pub async fn fetch_node_sha256(app_handle: &tauri::AppHandle, download_url: &str) -> Result<String, String> {
let (base, filename) = download_url.rsplit_once('/').ok_or_else(|| {
"INTEGRITY_METADATA_INVALID: Node.js download URL has no filename".to_string()
})?;
let checksums_url = format!("{base}/SHASUMS256.txt");
- let checksums = reqwest::Client::builder()
+ let checksums = crate::config::proxy::http_client_builder(app_handle)?
.user_agent("deepseek-harness-desktop")
.timeout(Duration::from_secs(20))
.build()
diff --git a/src-tauri/src/service/download/github.rs b/src-tauri/src/service/download/github.rs
index 174b2225..1e9d93da 100644
--- a/src-tauri/src/service/download/github.rs
+++ b/src-tauri/src/service/download/github.rs
@@ -31,8 +31,8 @@ pub struct LatestDshPkg {
}
/// 构造带 User-Agent 与超时的 GitHub 请求客户端。
-fn github_client() -> Result<reqwest::Client, String> {
- reqwest::Client::builder()
+fn github_client(app_handle: &tauri::AppHandle) -> Result<reqwest::Client, String> {
+ config::proxy::http_client_builder(app_handle)?
.user_agent("deepseek-harness-desktop")
.timeout(std::time::Duration::from_secs(5))
.build()
@@ -160,8 +160,8 @@ fn first_non_preview_tag_from_atom(body: &str) -> Option<String> {
/// atom 条目:预览版(Pre-release label 发布、tag 命名含预览标记)一律跳过,
/// 只取最新一条非预览版——避免限流窗口内把预览版误当「最新 release」推给用户
/// (见 [`is_preview_tag`])。
-async fn fetch_latest_dsh_tag_from_atom() -> Result<String, String> {
- let client = github_client()?;
+async fn fetch_latest_dsh_tag_from_atom(app_handle: &tauri::AppHandle) -> Result<String, String> {
+ let client = github_client(app_handle)?;
let body = client
.get(format!("{DSH_PKG_REPO}/releases.atom"))
.send()
@@ -242,8 +242,8 @@ async fn fetch_dsh_digest_from_expanded_assets(
/// 回退到最新一条非预览版 release 供更新/安装判定(issue #299:最新 alpha 发布后
/// 旧实现直接回 Err,导致初始化流程报 `DSH_INTEGRITY_UNAVAILABLE` 卡死)。仅当所有
/// release 都是预览版(找不到非预览版)时才返回 Err,由调用方保持本地安装、不提示。
-pub async fn fetch_latest_dsh_pkg_info() -> Result<LatestDshPkg, String> {
- let client = github_client()?;
+pub async fn fetch_latest_dsh_pkg_info(app_handle: &tauri::AppHandle) -> Result<LatestDshPkg, String> {
+ let client = github_client(app_handle)?;
let expected_name = config::get_dsh_download_url()?
.rsplit('/')
.next()
@@ -276,7 +276,7 @@ pub async fn fetch_latest_dsh_pkg_info() -> Result<LatestDshPkg, String> {
.and_then(|v| v.as_str())
.ok_or_else(|| "Missing tag_name in latest release response".to_string())?
.to_string(),
- None => fetch_latest_dsh_tag_from_atom().await?,
+ None => fetch_latest_dsh_tag_from_atom(app_handle).await?,
};
// 2b. 预览版不参与更新判定:`/releases/latest` 已按 label 排除 Pre-release,
@@ -289,7 +289,7 @@ pub async fn fetch_latest_dsh_pkg_info() -> Result<LatestDshPkg, String> {
"DSH_SKIP_PREVIEW: latest release {} is a preview, falling back to latest non-preview release",
tag_name
);
- return fetch_latest_non_preview().await;
+ return fetch_latest_non_preview(app_handle).await;
}
// 3. commit:优先 API /commits/{tag},失败用 tag 内嵌 build-id 兜底
@@ -374,13 +374,13 @@ pub async fn fetch_latest_dsh_pkg_info() -> Result<LatestDshPkg, String> {
/// 推荐版本可能是 pre-release,不能使用 GitHub 的 `/releases/latest`;该端点会
/// 排除标记为 pre-release 的发行版。先从完整 release 列表按解析后的 SemVer 精确匹配
/// tag,再复用固定 tag 的资产与摘要查询,确保下载内容与校验摘要属于同一发布。
-pub async fn fetch_dsh_pkg_version(version: &str) -> Result<LatestDshPkg, String> {
- let release = fetch_dsh_pkg_releases()
+pub async fn fetch_dsh_pkg_version(app_handle: &tauri::AppHandle, version: &str) -> Result<LatestDshPkg, String> {
+ let release = fetch_dsh_pkg_releases(app_handle)
.await?
.into_iter()
.find(|release| parse_version_from_tag(&release.tag).as_deref() == Some(version))
.ok_or_else(|| format!("DSH_RECOMMENDED_NOT_FOUND: no release found for {version}"))?;
- fetch_dsh_pkg_asset(&release.tag).await
+ fetch_dsh_pkg_asset(app_handle, &release.tag).await
}
/// 最新非预览版 release:仅当最新 release 是预览版时由 [`fetch_latest_dsh_pkg_info`] 调用。
@@ -390,8 +390,8 @@ pub async fn fetch_dsh_pkg_version(version: &str) -> Result<LatestDshPkg, String
/// 见 [`is_preview_tag`]),再复用固定 tag 的资产/摘要查询,确保下载内容与校验摘要
/// 属于同一发布。找不到非预览版(全部是预览版)时返回错误,调用方保持不更新——
/// 不把预览版推给用户自动更新,也不再以「最新是预览版」整段卡死初始化流程。
-async fn fetch_latest_non_preview() -> Result<LatestDshPkg, String> {
- let tag = fetch_dsh_pkg_releases()
+async fn fetch_latest_non_preview(app_handle: &tauri::AppHandle) -> Result<LatestDshPkg, String> {
+ let tag = fetch_dsh_pkg_releases(app_handle)
.await?
.into_iter()
.find(|m| !m.prerelease && !is_preview_tag(&m.tag))
@@ -399,15 +399,15 @@ async fn fetch_latest_non_preview() -> Result<LatestDshPkg, String> {
.ok_or_else(|| {
"DSH_PREVIEW_RELEASE: no non-preview release available, not an update".to_string()
})?;
- fetch_dsh_pkg_asset(&tag).await
+ fetch_dsh_pkg_asset(app_handle, &tag).await
}
/// 拉取指定 tag 的发行版信息(资产 URL + 可信摘要),供核心面板按版本下载。
///
/// API 失败时资产 URL 按 tag 确定性构造,摘要从同一个 tag 的页面读取,避免
/// latest 地址与固定 tag 的摘要发生错配。
-pub async fn fetch_dsh_pkg_asset(tag: &str) -> Result<LatestDshPkg, String> {
- let client = github_client()?;
+pub async fn fetch_dsh_pkg_asset(app_handle: &tauri::AppHandle, tag: &str) -> Result<LatestDshPkg, String> {
+ let client = github_client(app_handle)?;
let expected_name = config::get_dsh_download_url()?
.rsplit('/')
.next()
@@ -697,8 +697,8 @@ async fn fetch_dsh_pkg_releases_from_html(
/// Pre-release label,无法区分预览版;releases 列表还能天然排除 draft(未发布
/// 对匿名请求不可见)。API 失败时先读取 github.com Releases 页面,再失败时
/// 由调用方回退 git tags,预览标记按 tag 命名([`is_preview_tag`])兜底。
-pub async fn fetch_dsh_pkg_releases() -> Result<Vec<DshPkgReleaseMeta>, String> {
- let client = github_client()?;
+pub async fn fetch_dsh_pkg_releases(app_handle: &tauri::AppHandle) -> Result<Vec<DshPkgReleaseMeta>, String> {
+ let client = github_client(app_handle)?;
let mut all_releases = Vec::new();
let mut page = 1;
loop {
@@ -759,8 +759,8 @@ pub async fn fetch_dsh_pkg_releases() -> Result<Vec<DshPkgReleaseMeta>, String>
///
/// 仅在更新判定需要反查“无 tag 的老记录”时调用,失败时由调用方回退到
/// “以实际文件为准”的保守分支。
-pub async fn fetch_dsh_pkg_tags() -> Result<Vec<(String, String)>, String> {
- let client = github_client()?;
+pub async fn fetch_dsh_pkg_tags(app_handle: &tauri::AppHandle) -> Result<Vec<(String, String)>, String> {
+ let client = github_client(app_handle)?;
let tags: serde_json::Value = github_api_get(
&client,
&format!("{}/tags?per_page=100", DSH_PKG_GITHUB_API),
diff --git a/src-tauri/src/service/download/progress.rs b/src-tauri/src/service/download/progress.rs
index 89d8830c..3d4f853e 100644
--- a/src-tauri/src/service/download/progress.rs
+++ b/src-tauri/src/service/download/progress.rs
@@ -16,7 +16,7 @@ pub struct ProgressPayload {
}
pub struct ProgressTracker<'a, R: Runtime> {
- window: &'a WebviewWindow<R>,
+ pub(super) window: &'a WebviewWindow<R>,
total_phases: usize,
current_phase: usize,
current_title: String,
diff --git a/src-tauri/src/service/plugin/hmr.rs b/src-tauri/src/service/plugin/hmr.rs
new file mode 100644
index 00000000..bd976aaf
--- /dev/null
+++ b/src-tauri/src/service/plugin/hmr.rs
@@ -0,0 +1,675 @@
+//! 本地插件热重载:把用户以本地路径安装的插件源码目录折算成一组 watch root,
+//! 写进桌面端独占的补丁层文件,随启动以 `--patch <文件>` 注入核心 HMR。
+//!
+//! 核心自带 `@deepseek-ai/dsh-hmr` 在档案下恒为启用状态,缺的只是「监听哪些目录」
+//! ——`config.root` 默认为空。补上这组 root 后,本地插件源码的改动由核心 HMR 直接
+//! 热重载(dispose + 重新 import + 重建插件 fiber),无需重启服务。
+//!
+//! 为什么单独一个文件:`$DSH_HOME/cordis.patch.yml` 与档案层 `cordis.patch.yml` 都是
+//! 用户手写资产(见 [`super::patch_guard`] 的约定),桌面端只在显式恢复流程里改写。
+//! HMR 是随安装状态变化的运行期状态,必须有自己的文件;该文件只在启动前复算,不被
+//! 任何清理流程触碰,无本地插件时直接删除(`--patch` 指向不存在的文件会让核心大声
+//! 失败,见 `dsh-app-boot` 的 `loadOverlayPatches`)。
+//!
+//! 三条硬约束(均为实测结论):
+//! 1. 补丁的 `config` 是整体替换(逐键浅覆盖),条目里必须写完整配置对象;
+//! 2. watch root 必须是真实长路径:Windows 8.3 短名会让 chokidar 原生断言崩溃;
+//! 3. 相对 root 里一旦出现 `..`,忽略规则会被拼成跨盘串而全部失效,故同盘 root 用
+//! 不含 `..` 的相对路径、跨盘 root 用绝对路径。
+
+use std::collections::BTreeSet;
+use std::path::{Component, Path, PathBuf};
+
+use tauri::{AppHandle, Manager};
+
+use super::installed::{profile_dir, ProfilePackageJson};
+use super::patch_guard::now_stamp;
+use crate::config;
+
+/// 桌面端独占的 HMR 补丁层文件名(与用户手写的 `cordis.patch.yml` 区分开)。
+pub(crate) const HMR_PATCH_FILENAME: &str = "cordis.hmr.patch.yml";
+
+/// 补丁条目必须逐字命中核心内置的 HMR 服务:`name` 写错会被静默跳过。
+const HMR_ENTRY_ID: &str = "hmr";
+const HMR_ENTRY_NAME: &str = "@deepseek-ai/dsh-hmr";
+
+/// picomatch 的「转义反斜杠」写法 `[/\]` 需要两个真实反斜杠字符:裸反斜杠在 Windows
+/// 上永不匹配(核心默认的 `**/node_modules` 在本机因此是失效的,这里连同 `cache` /
+/// `data` 一起显式给出,逐条实测过 16 组路径)。
+const BS: &str = "\\\\";
+
+/// 与核心默认值一致的 debounce(毫秒);显式写出因为 `config` 是整体替换。
+const HMR_DEBOUNCE_MS: u64 = 100;
+
+/// 当前本地插件热重载状态(前端展示用)。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalHmrStatus {
+ /// 用户开关的持久化值(与「此刻是否真的在监听」无关)。
+ pub enabled: bool,
+ /// 当前是否真的有本地插件源目录被监听(开关打开且存在待监听的目录)。
+ pub watching: bool,
+ /// 生效时注入的补丁层路径。
+ pub patch_path: Option<String>,
+ /// 被监听的本地插件源目录(真实长路径)。
+ pub roots: Vec<String>,
+}
+
+/// HMR 补丁层路径(app-data 下,与用户补丁层无关)。
+pub(crate) fn patch_path(app_handle: &AppHandle) -> PathBuf {
+ config::get_base_dir(app_handle).join(HMR_PATCH_FILENAME)
+}
+
+/// 复算并写出 HMR 补丁层:需要热重载时返回其路径,否则删除残留并返回 `None`。
+///
+/// 每次启动都要重算:`--patch` 只在本次进程有效,而本地插件的安装状态可能已经变化。
+/// 任何一步失败都退化为「不传 `--patch`」(热重载只是便利功能,不该阻断启动)。
+pub(crate) fn sync_layer(app_handle: &AppHandle) -> Option<PathBuf> {
+ let path = patch_path(app_handle);
+ let roots = local_watch_roots(app_handle);
+ let rendered = if hmr_enabled(app_handle) {
+ render_layer(&roots)
+ } else {
+ None
+ };
+ let Some(rendered) = rendered else {
+ remove_layer(&path);
+ return None;
+ };
+ if std::fs::read_to_string(&path).is_ok_and(|current| current == rendered) {
+ return Some(path);
+ }
+ match write_layer(&path, &rendered) {
+ Ok(()) => {
+ log::info!("HMR layer written: {}", path.display());
+ Some(path)
+ }
+ Err(error) => {
+ log::warn!("HMR_LAYER_WRITE_FAILED: {error}");
+ None
+ }
+ }
+}
+
+/// 当前本地插件热重载状态。
+pub(crate) fn status(app_handle: &AppHandle) -> LocalHmrStatus {
+ let path = patch_path(app_handle);
+ let roots = local_watch_roots(app_handle);
+ let enabled = hmr_enabled(app_handle);
+ LocalHmrStatus {
+ enabled,
+ watching: enabled && !roots.is_empty(),
+ patch_path: path.exists().then(|| path.display().to_string()),
+ roots: roots.iter().map(|dir| dir.display().to_string()).collect(),
+ }
+}
+
+fn hmr_enabled(app_handle: &AppHandle) -> bool {
+ config::read_store_dat_setting(app_handle).local_plugin_hmr
+}
+
+/// 需要热重载的本地插件源码目录:已装且已挂载(在 `dsh.profile.bundles` 里)、以
+/// `link:` / `file:` 声明、目录真实存在、且不属于随包分发的内置插件。
+pub(crate) fn local_watch_roots(app_handle: &AppHandle) -> Vec<PathBuf> {
+ let profile = profile_dir(app_handle);
+ let Some(manifest) = read_manifest(&profile) else {
+ return Vec::new();
+ };
+ watch_roots_in(&profile, &manifest, |_name, dir| {
+ is_bundled(app_handle, dir)
+ })
+}
+
+fn watch_roots_in(
+ profile: &Path,
+ manifest: &ProfilePackageJson,
+ is_excluded: impl Fn(&str, &Path) -> bool,
+) -> Vec<PathBuf> {
+ let bundles: BTreeSet<&str> = manifest
+ .dsh
+ .as_ref()
+ .and_then(|dsh| dsh.profile.as_ref())
+ .map(|inner| inner.bundles.iter().map(String::as_str).collect())
+ .unwrap_or_default();
+ let mut roots = BTreeSet::new();
+ for (name, spec) in &manifest.dependencies {
+ if !bundles.contains(name.as_str()) {
+ continue;
+ }
+ let Some(raw) = local_dep_path(spec) else {
+ continue;
+ };
+ let Some(dir) = resolve_dir(&raw, profile) else {
+ continue;
+ };
+ if is_excluded(name, &dir) {
+ continue;
+ }
+ roots.insert(dir);
+ }
+ prune_nested(roots.into_iter().collect())
+}
+
+fn read_manifest(profile: &Path) -> Option<ProfilePackageJson> {
+ let content = std::fs::read_to_string(profile.join("package.json")).ok()?;
+ serde_json::from_str(&content).ok()
+}
+
+/// 本地依赖的原始路径部分:`link:` / `file:` 前缀之外的一律不是本地目录。
+fn local_dep_path(spec: &str) -> Option<String> {
+ let raw = spec
+ .strip_prefix("link:")
+ .or_else(|| spec.strip_prefix("file:"))?;
+ let trimmed = raw.trim().trim_end_matches(['/', '\\']);
+ (!trimmed.is_empty()).then(|| trimmed.to_string())
+}
+
+/// 解析成真实长路径:pnpm 的 `link:` 是目录联接,必须落到源码目录本身,
+/// 且必须是长名(8.3 短名会让 chokidar 原生断言崩溃)。
+fn resolve_dir(raw: &str, profile: &Path) -> Option<PathBuf> {
+ let normalized = raw.replace('/', std::path::MAIN_SEPARATOR_STR);
+ let path = Path::new(&normalized);
+ let joined = if path.is_absolute() {
+ path.to_path_buf()
+ } else {
+ profile.join(path)
+ };
+ let resolved = dunce::canonicalize(&joined).ok()?;
+ resolved.is_dir().then_some(resolved)
+}
+
+/// 随包分发的内置插件源码目录:改它没有意义(升级即被覆盖),不该进 watch root。
+fn is_bundled(app_handle: &AppHandle, dir: &Path) -> bool {
+ let Ok(resource_dir) = app_handle.path().resource_dir() else {
+ return false;
+ };
+ let flatten = |path: &Path| {
+ let mut text = path
+ .to_string_lossy()
+ .replace('/', std::path::MAIN_SEPARATOR_STR);
+ if !text.ends_with(std::path::MAIN_SEPARATOR) {
+ text.push_str(std::path::MAIN_SEPARATOR_STR);
+ }
+ text.to_lowercase()
+ };
+ flatten(dir).starts_with(&flatten(dunce::simplified(&resource_dir)))
+}
+
+/// 去掉被父目录覆盖的子目录:chokidar 递归监听父目录即可,重复 root 只增开销。
+fn prune_nested(dirs: Vec<PathBuf>) -> Vec<PathBuf> {
+ let mut kept: Vec<PathBuf> = Vec::new();
+ for dir in dirs {
+ if kept.iter().any(|parent| dir.starts_with(parent)) {
+ continue;
+ }
+ kept.retain(|child| !child.starts_with(&dir));
+ kept.push(dir);
+ }
+ kept
+}
+
+/// 一组 root 的 `base`:取成员最多的卷(同卷才能算出不含 `..` 的相对路径)。
+///
+/// 跨卷(本地插件分别装在 C:/D:)时只能给其中一个卷配 `base`,其余 root 用绝对
+/// 路径;`relative(base, 绝对路径)` 在 Windows 上原样返回绝对路径,忽略规则对那
+/// 部分 root 失效(只是多监听几个文件,不影响正确性)。
+fn pick_base(roots: &[PathBuf]) -> Option<PathBuf> {
+ let mut groups: Vec<(std::ffi::OsString, Vec<PathBuf>)> = Vec::new();
+ for root in roots {
+ let key = root
+ .components()
+ .next()
+ .map(|part| part.as_os_str().to_os_string())
+ .unwrap_or_default();
+ match groups.iter_mut().find(|(existing, _)| *existing == key) {
+ Some((_, members)) => members.push(root.clone()),
+ None => groups.push((key, vec![root.clone()])),
+ }
+ }
+ let mut best: Option<Vec<PathBuf>> = None;
+ for (_, members) in groups {
+ if best
+ .as_ref()
+ .is_none_or(|current| members.len() > current.len())
+ {
+ best = Some(members);
+ }
+ }
+ common_ancestor(&best?)
+}
+
+/// 一组绝对路径的最深公共祖先;跨卷(首个分量不同)时返回 `None`。
+fn common_ancestor(paths: &[PathBuf]) -> Option<PathBuf> {
+ let first = paths.first()?;
+ let mut shared: Vec<Component> = first.components().collect();
+ for path in &paths[1..] {
+ let mut index = 0;
+ for (left, right) in shared.iter().zip(path.components()) {
+ if *left != right {
+ break;
+ }
+ index += 1;
+ }
+ shared.truncate(index);
+ }
+ let ancestor: PathBuf = shared.into_iter().collect();
+ ancestor.is_absolute().then_some(ancestor)
+}
+
+fn relative_root(base: &Path, root: &Path) -> String {
+ let text = root
+ .strip_prefix(base)
+ .unwrap_or(root)
+ .to_string_lossy()
+ .replace(std::path::MAIN_SEPARATOR, "/");
+ let trimmed = text.trim_matches('/');
+ if trimmed.is_empty() {
+ ".".to_string()
+ } else {
+ trimmed.to_string()
+ }
+}
+
+/// `file://` URL:核心用 `fileURLToPath(new URL(config.base, ctx.baseUrl))` 还原目录,
+/// 只认 file 协议(裸 `D:/x` 会抛 ERR_INVALID_URL_SCHEME)。
+///
+/// 用 `Url::from_file_path` 而不是拼字符串:路径里的保留字符必须百分号编码,否则
+/// `#` 会被 `new URL()` 当成 fragment 起始符,`fileURLToPath` 只还原出 `#` 之前的
+/// 半截目录(实测 `D:/my#plugin` ⇒ `D:/my`);编码后 `%23` 能逐字还原。非 UTF-8
+/// 路径、非磁盘盘符(UNC)以及含 `..` 的相对路径都返回 `None`。
+fn file_url(dir: &Path) -> Option<String> {
+ if dir
+ .components()
+ .any(|part| matches!(part, Component::CurDir | Component::ParentDir))
+ {
+ return None;
+ }
+ tauri::Url::from_file_path(dir)
+ .ok()
+ .map(|url| url.as_str().to_string())
+}
+
+fn render_layer(roots: &[PathBuf]) -> Option<String> {
+ let base = pick_base(roots)?;
+ let base_url = file_url(&base)?;
+ let mut yaml = String::from("- id: ");
+ yaml.push_str(HMR_ENTRY_ID);
+ yaml.push_str(
+ "
+ name: '",
+ );
+ yaml.push_str(HMR_ENTRY_NAME);
+ yaml.push_str(
+ "'
+ config:
+ base: ",
+ );
+ yaml.push_str(&base_url);
+ yaml.push_str(
+ "
+ root:",
+ );
+ for root in roots {
+ yaml.push_str(
+ "
+ - ",
+ );
+ yaml.push_str(&root_value(&base, root));
+ }
+ yaml.push_str(
+ "
+ ignored:",
+ );
+ for pattern in ignore_patterns() {
+ yaml.push_str(
+ "
+ - '",
+ );
+ yaml.push_str(&pattern);
+ yaml.push('\'');
+ }
+ yaml.push_str(
+ "
+ debounce: ",
+ );
+ yaml.push_str(&HMR_DEBOUNCE_MS.to_string());
+ yaml.push('\n');
+ Some(yaml)
+}
+
+fn root_value(base: &Path, root: &Path) -> String {
+ if root.starts_with(base) {
+ relative_root(base, root)
+ } else {
+ root.to_string_lossy()
+ .replace(std::path::MAIN_SEPARATOR, "/")
+ }
+}
+
+fn ignore_patterns() -> Vec<String> {
+ vec![
+ format!("**[/{BS}]node_modules"),
+ format!("**[/{BS}]node_modules[/{BS}]**"),
+ format!("node_modules[/{BS}]**"),
+ format!("**[/{BS}].*"),
+ "cache".to_string(),
+ "data".to_string(),
+ ]
+}
+
+fn write_layer(path: &Path, rendered: &str) -> Result<(), String> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|e| format!("HMR_LAYER_MKDIR_FAILED: {}: {e}", parent.display()))?;
+ }
+ let temp = path.with_file_name(format!("{HMR_PATCH_FILENAME}.tmp-{}", now_stamp()));
+ std::fs::write(&temp, rendered).map_err(|e| {
+ let _ = std::fs::remove_file(&temp);
+ format!("HMR_LAYER_WRITE_FAILED: {}: {e}", temp.display())
+ })?;
+ std::fs::rename(&temp, path).map_err(|e| {
+ let _ = std::fs::remove_file(&temp);
+ format!("HMR_LAYER_WRITE_FAILED: {}: {e}", path.display())
+ })
+}
+
+fn remove_layer(path: &Path) {
+ if !path.exists() {
+ return;
+ }
+ match std::fs::remove_file(path) {
+ Ok(()) => log::info!("HMR layer removed: {}", path.display()),
+ Err(error) => log::warn!("HMR_LAYER_REMOVE_FAILED: {}: {error}", path.display()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::HashMap;
+
+ fn tmp_dir(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("dsh-hmr-{}-{tag}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dunce::canonicalize(&dir).unwrap()
+ }
+
+ fn manifest(dependencies: &[(&str, String)], bundles: &[&str]) -> ProfilePackageJson {
+ let deps: HashMap<String, String> = dependencies
+ .iter()
+ .map(|(name, spec)| (name.to_string(), spec.clone()))
+ .collect();
+ serde_json::from_value(serde_json::json!({
+ "name": "dsh-profile-test",
+ "private": true,
+ "dependencies": deps,
+ "dsh": { "profile": { "bundles": bundles } },
+ }))
+ .unwrap()
+ }
+
+ fn plugin_dir(profile: &Path, name: &str) -> PathBuf {
+ let dir = profile.join(name);
+ std::fs::create_dir_all(&dir).unwrap();
+ dunce::canonicalize(&dir).unwrap()
+ }
+
+ #[test]
+ fn ignore_patterns_escape_the_backslash_twice() {
+ let patterns = ignore_patterns();
+ assert_eq!(
+ patterns,
+ vec![
+ "**[/\\\\]node_modules".to_string(),
+ "**[/\\\\]node_modules[/\\\\]**".to_string(),
+ "node_modules[/\\\\]**".to_string(),
+ "**[/\\\\].*".to_string(),
+ "cache".to_string(),
+ "data".to_string(),
+ ]
+ );
+ // 每个 `[/\]` 转义段都必须落成两个真实反斜杠:单个反斜杠在 picomatch 里
+ // 被当成转义符,模式永不匹配(这正是核心默认规则在本机失效的原因)。
+ for pattern in &patterns {
+ assert!(!pattern.contains("[/\\]"), "{pattern}");
+ }
+ }
+
+ #[test]
+ fn local_dep_path_accepts_both_prefixes_and_trims_separators() {
+ assert_eq!(
+ local_dep_path("link:D:/plugins/mine/"),
+ Some("D:/plugins/mine".to_string())
+ );
+ assert_eq!(
+ local_dep_path("file:D:\\plugins\\mine"),
+ Some("D:\\plugins\\mine".to_string())
+ );
+ assert_eq!(local_dep_path("^1.2.3"), None);
+ assert_eq!(local_dep_path("github:user/repo"), None);
+ assert_eq!(local_dep_path("link:"), None);
+ }
+
+ #[test]
+ fn resolve_dir_needs_a_real_directory() {
+ let profile = tmp_dir("resolve");
+ let dir = plugin_dir(&profile, "mine");
+ assert_eq!(resolve_dir("mine", &profile), Some(dir.clone()));
+ assert_eq!(resolve_dir("./mine", &profile), Some(dir));
+ assert_eq!(resolve_dir("missing", &profile), None);
+ let _ = std::fs::remove_dir_all(&profile);
+ }
+
+ #[test]
+ fn watch_roots_only_cover_mounted_local_plugins() {
+ let profile = tmp_dir("watch-roots");
+ let local = plugin_dir(&profile, "local");
+ let sibling = plugin_dir(&profile, "plain");
+ let excluded = plugin_dir(&profile, "excluded");
+ let unbundled = plugin_dir(&profile, "unbundled");
+ let manifest = manifest(
+ &[
+ ("local", format!("link:{}", local.display())),
+ ("sibling", "link:plain".to_string()),
+ ("unbundled", format!("link:{}", unbundled.display())),
+ ("excluded", format!("link:{}", excluded.display())),
+ ("registry", "^1.0.0".to_string()),
+ ("ghost", "link:no-such-dir".to_string()),
+ ],
+ &[
+ "local",
+ "sibling",
+ "unbundled",
+ "excluded",
+ "registry",
+ "ghost",
+ ],
+ );
+
+ let roots = watch_roots_in(&profile, &manifest, |name, _| name == "excluded");
+ assert_eq!(roots, vec![local, sibling, unbundled]);
+ let _ = std::fs::remove_dir_all(&profile);
+ }
+
+ #[test]
+ fn prune_nested_keeps_the_topmost_directory() {
+ let root = PathBuf::from("X:\\hmr-tmp").join("prune");
+ let outside = PathBuf::from("X:\\hmr-tmp").join("outside");
+ let roots = prune_nested(vec![
+ root.join("a\\b"),
+ root.clone(),
+ root.join("a\\b\\c"),
+ root.join("ab"),
+ outside.clone(),
+ ]);
+ assert_eq!(roots, vec![root.clone(), outside]);
+
+ // 前缀相同但不是祖先目录的兄弟目录必须保留(按路径分量比较,不是字符串前缀)
+ let sibling = prune_nested(vec![root.join("a\\b"), root.join("a\\bc")]);
+ assert_eq!(sibling, vec![root.join("a\\b"), root.join("a\\bc")]);
+ }
+
+ #[test]
+ fn common_ancestor_stops_at_the_shared_prefix() {
+ // 夹具必须落在真实临时目录上:`X:\hmr-tmp` 这类 Windows 字面量在 Unix 上
+ // 只是单个相对分量(不是绝对路径),公共祖先会直接算成 `None`。
+ let root = tmp_dir("common");
+ assert_eq!(
+ common_ancestor(&[root.join("a").join("b"), root.join("a").join("c")]),
+ Some(root.join("a"))
+ );
+ assert_eq!(
+ common_ancestor(std::slice::from_ref(&root)),
+ Some(root.clone())
+ );
+ assert_eq!(common_ancestor(&[]), None);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn pick_base_prefers_the_volume_with_more_roots() {
+ let root = tmp_dir("pick-base");
+ let single = vec![root.join("only")];
+ assert_eq!(pick_base(&single), Some(single[0].clone()));
+
+ let roots = vec![root.join("a").join("p1"), root.join("a").join("p2")];
+ assert_eq!(pick_base(&roots), Some(root.join("a")));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn render_layer_writes_a_complete_hmr_config() {
+ // 夹具必须是真实的绝对目录:`X:\hmr-tmp` 在 Unix 上不是绝对路径,`pick_base`
+ // 会返回 `None`。base 行按同一实现函数算出(盘符大小写、分隔符都取真实临时
+ // 目录的形态,不硬编码平台),其余字节逐字固定。
+ let root = tmp_dir("render").join("plugins");
+ std::fs::create_dir_all(&root).unwrap();
+ let roots = vec![root.join("mine"), root.join("other").join("sub")];
+ let yaml = render_layer(&roots).expect("render");
+
+ let entries: Vec<serde_yaml::Value> = serde_yaml::from_str(&yaml).expect("parse");
+ assert_eq!(entries.len(), 1);
+ let entry = &entries[0];
+ assert_eq!(entry["id"].as_str(), Some(HMR_ENTRY_ID));
+ assert_eq!(entry["name"].as_str(), Some(HMR_ENTRY_NAME));
+ let config = &entry["config"];
+ let base = config["base"].as_str().expect("base");
+ assert!(base.starts_with("file:///"), "{base}");
+ assert_eq!(config["root"].as_sequence().unwrap().len(), 2, "{yaml}");
+ assert_eq!(config["root"][0].as_str(), Some("mine"));
+ assert_eq!(config["root"][1].as_str(), Some("other/sub"));
+ assert_eq!(config["ignored"].as_sequence().unwrap().len(), 6);
+ assert_eq!(config["debounce"].as_u64(), Some(HMR_DEBOUNCE_MS));
+
+ // 逐字固定整份补丁层:核心按 id 整块替换 config,任何字段写错或漏写都会被静默忽略。
+ let base_line = format!(" base: {}", file_url(&root).expect("file url"));
+ let golden = [
+ "- id: hmr",
+ " name: '@deepseek-ai/dsh-hmr'",
+ " config:",
+ base_line.as_str(),
+ " root:",
+ " - mine",
+ " - other/sub",
+ " ignored:",
+ " - '**[/\\\\]node_modules'",
+ " - '**[/\\\\]node_modules[/\\\\]**'",
+ " - 'node_modules[/\\\\]**'",
+ " - '**[/\\\\].*'",
+ " - 'cache'",
+ " - 'data'",
+ " debounce: 100",
+ ]
+ .join("\n")
+ + "\n";
+ assert_eq!(yaml, golden);
+ }
+
+ /// 含保留字符(`#`)的真实目录:源码路径带 `#` 时 URL 必须百分号编码,否则
+ /// `new URL()` 把它当 fragment 起始符,核心会去监听被截断的父目录。
+ fn reserved_dir(tag: &str) -> PathBuf {
+ let dir = tmp_dir(tag).join("my#plugin");
+ std::fs::create_dir_all(&dir).unwrap();
+ dunce::canonicalize(&dir).unwrap()
+ }
+
+ #[test]
+ fn render_layer_percent_encodes_reserved_characters() {
+ let source = reserved_dir("reserved");
+ let yaml = render_layer(std::slice::from_ref(&source)).expect("render");
+ // 与往返测试同理:把生产字节落到临时目录,实机验证直接复用。
+ std::fs::write(
+ std::env::temp_dir().join("dsh-hmr-layer-hash-out.yml"),
+ &yaml,
+ )
+ .unwrap();
+ let entries: Vec<serde_yaml::Value> = serde_yaml::from_str(&yaml).expect("parse");
+ let config = &entries[0]["config"];
+ let base = config["base"].as_str().expect("base");
+ assert!(base.contains("my%23plugin"), "{base}");
+ assert!(!base.contains('#'), "{base}");
+
+ // 还原必须逐字回到真实源码目录:`#` 直接写进 URL 时这里只会得到 `my`。
+ let restored = tauri::Url::parse(base).expect("parse url").to_file_path();
+ assert_eq!(restored.ok(), Some(source));
+ }
+
+ #[test]
+ fn render_layer_round_trips_a_real_link_dependency() {
+ let home = tmp_dir("roundtrip");
+ let profile = home.join("profiles").join("p3");
+ std::fs::create_dir_all(&profile).unwrap();
+ let profile = dunce::canonicalize(&profile).unwrap();
+ let source = plugin_dir(&profile, "mine");
+ let spec = super::super::install::local_spec_from_path(&source);
+ let manifest = manifest(&[("probe-hmr-plugin", spec)], &["probe-hmr-plugin"]);
+
+ let roots = watch_roots_in(&profile, &manifest, |_name, _dir| false);
+ assert_eq!(roots, vec![source.clone()]);
+
+ // 实机热重载验证直接复用这份字节:把渲染结果落到临时目录,省掉手工重写补丁层。
+ let yaml = render_layer(&roots).expect("render");
+ std::fs::write(std::env::temp_dir().join("dsh-hmr-layer-out.yml"), &yaml).unwrap();
+
+ let entries: Vec<serde_yaml::Value> = serde_yaml::from_str(&yaml).expect("parse");
+ let config = &entries[0]["config"];
+ // `file://` 之后 Windows 还多一层根斜杠(`file:///C:/x`),Unix 剥完即是绝对路径。
+ let raw = config["base"]
+ .as_str()
+ .expect("base")
+ .trim_start_matches("file://");
+ #[cfg(windows)]
+ let raw = raw.trim_start_matches('/');
+ let base = PathBuf::from(raw);
+ let resolved = config["root"]
+ .as_sequence()
+ .expect("root")
+ .iter()
+ .map(|item| base.join(item.as_str().expect("root item")))
+ .collect::<Vec<_>>();
+ // base 与 root 拼回来必须正好是插件的真实源码目录:任何一步的形态偏差都会让
+ // 核心监听一个不存在的目录(chokidar 对缺失的监听根目录是静默的)。
+ assert_eq!(resolved, vec![source]);
+ }
+
+ #[test]
+ fn render_layer_needs_at_least_one_root() {
+ assert_eq!(render_layer(&[]), None);
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn render_layer_keeps_foreign_volumes_absolute() {
+ let roots = vec![
+ PathBuf::from("D:\\plugins\\mine"),
+ PathBuf::from("C:\\other\\plugin"),
+ ];
+ let yaml = render_layer(&roots).expect("render");
+ let entries: Vec<serde_yaml::Value> = serde_yaml::from_str(&yaml).expect("parse");
+ let config = &entries[0]["config"];
+ assert_eq!(config["base"].as_str(), Some("file:///D:/plugins/mine"));
+ assert_eq!(config["root"][0].as_str(), Some("."));
+ assert_eq!(config["root"][1].as_str(), Some("C:/other/plugin"));
+ }
+}
diff --git a/src-tauri/src/service/plugin/install/inspect.rs b/src-tauri/src/service/plugin/install/inspect.rs
index c83bfdca..6c9c3039 100644
--- a/src-tauri/src/service/plugin/install/inspect.rs
+++ b/src-tauri/src/service/plugin/install/inspect.rs
@@ -1,7 +1,11 @@
//! 插件 spec 兼容性只读检查:解析包名与声明的版本 → 读 npm registry 对应清单 →
//! 提取 `@deepseek-ai/dsh` 家族依赖 → 用 [`crate::service::plugin::compat`] 判定
//! 是否匹配运行时核心版本。全程不落盘、不起子进程,供插件市场在安装前提示。
+//!
+//! 本地目录 spec 走完全离线的另一条路:直接读目标目录的 `package.json`,联网
+//! 检查对它既无意义(包不在 registry 上)也无从进行(没有可查询的包名)。
+use std::path::Path;
use std::time::Duration;
use semver::Version;
@@ -26,22 +30,33 @@ pub async fn inspect_specs(
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.or_else(|| crate::service::core::active_version(app_handle));
- let client = reqwest::Client::builder()
+ let client = crate::config::proxy::http_client_builder(app_handle)?
.timeout(INSPECT_TIMEOUT)
.build()
.map_err(|e| format!("INSPECT_CLIENT: {e}"))?;
+ // 与安装同源:本地 spec 的相对路径按 `dsh plugin add` 子进程的 cwd 解析。
+ let base = crate::config::get_dsh_install_path(app_handle);
let mut results = Vec::with_capacity(specs.len());
for raw in specs {
- results.push(inspect_one(&client, raw, runtime.as_deref()).await);
+ results.push(inspect_one(&client, raw, &base, runtime.as_deref()).await);
}
Ok(results)
}
-/// 单条 spec:静态解析不出包名(git / 本地路径 / 非法写法)时不做网络请求。
-async fn inspect_one(client: &reqwest::Client, spec: &str, runtime: Option<&str>) -> PluginInspect {
+/// 单条 spec:本地目录离线读清单,静态解析不出包名(git / URL / 非法写法)时不做
+/// 网络请求。
+async fn inspect_one(
+ client: &reqwest::Client,
+ spec: &str,
+ base: &Path,
+ runtime: Option<&str>,
+) -> PluginInspect {
let raw = spec.trim();
- let Some(name) = spec::package_name_of_spec(raw) else {
+ if spec::local_path_spec(raw).is_some() {
+ return inspect_local(raw, base, runtime);
+ }
+ let Some(name) = spec::package_name_of_spec(raw, base) else {
return problem_result(raw, None, "invalid-spec");
};
@@ -100,6 +115,44 @@ async fn inspect_one(client: &reqwest::Client, spec: &str, runtime: Option<&str>
}
}
+/// 本地目录 spec 的离线检查:目录与 `package.json` 缺一都算 `local-missing`
+/// (安装前就能报出确定的原因,而不是等 pnpm 装出一个没有清单的联接)。
+///
+/// 兼容性判定与 registry 路径同源:清单里的 DSH 家族依赖 × 运行时核心版本,
+/// 本地源码没有「已发布版本」的概念,因此不做区间退回、直接判定。
+fn inspect_local(raw: &str, base: &Path, runtime: Option<&str>) -> PluginInspect {
+ let Some(dir) = spec::local_dir_of(raw, base) else {
+ return problem_result(raw, None, "local-missing");
+ };
+ let Ok(content) = std::fs::read_to_string(dir.join("package.json")) else {
+ return problem_result(raw, None, "local-missing");
+ };
+ let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&content) else {
+ return problem_result(raw, None, "local-missing");
+ };
+ let name = manifest
+ .get("name")
+ .and_then(serde_json::Value::as_str)
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(String::from)
+ .or_else(|| spec::local_package_name(&dir));
+ let version = manifest
+ .get("version")
+ .and_then(serde_json::Value::as_str)
+ .map(String::from);
+ let peers = compat::peers_from_manifest(&manifest);
+ let compatible = runtime.and_then(|runtime| compat::evaluate(&peers, runtime));
+ PluginInspect {
+ spec: raw.to_string(),
+ name,
+ version,
+ compatible,
+ peers: (!peers.is_empty()).then_some(peers),
+ problem: None,
+ }
+}
+
/// spec 里在包名之后显式声明的版本片段(`[email protected]` / `@scope/aaa@^1.0.0`)。
fn requested_version(raw: &str, name: &str) -> Option<String> {
raw.strip_prefix(name)
@@ -120,3 +173,115 @@ fn problem_result(spec: &str, name: Option<String>, problem: &str) -> PluginInsp
problem: Some(problem.to_string()),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ fn fixture(tag: &str, manifest: Option<&str>) -> (PathBuf, PathBuf) {
+ let base = std::env::temp_dir().join(format!("dsh-inspect-{}-{tag}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ let dir = base.join("plugin");
+ std::fs::create_dir_all(&dir).unwrap();
+ if let Some(manifest) = manifest {
+ std::fs::write(dir.join("package.json"), manifest).unwrap();
+ }
+ // `temp_dir()` 在 Windows 上是 8.3 短名(`IUUUUU~1`),本地 spec 解析按
+ // 设计展开成真实长名——夹具必须站在同一口径上比较。
+ let base = dunce::simplified(&std::fs::canonicalize(&base).unwrap()).to_path_buf();
+ let dir = base.join("plugin");
+ (base, dir)
+ }
+
+ #[test]
+ fn local_spec_is_inspected_offline_from_its_manifest() {
+ // 本地插件不在 registry 上:检查必须完全离线,并给出清单里声明的名字、
+ // 版本与 DSH 家族依赖,供安装前的兼容性提示使用。
+ let (base, dir) = fixture(
+ "ok",
+ Some(
+ r#"{"name":"dsh-reverse-skill","version":"1.0.2","peerDependencies":{"@deepseek-ai/cordis":"^4.0.4"}}"#,
+ ),
+ );
+
+ let result = inspect_local("./plugin", &base, Some("0.2.0-rc.2"));
+
+ assert_eq!(result.spec, "./plugin");
+ assert_eq!(result.name.as_deref(), Some("dsh-reverse-skill"));
+ assert_eq!(result.version.as_deref(), Some("1.0.2"));
+ assert_eq!(result.problem, None);
+ assert_eq!(result.compatible, None, "非 DSH 家族 peer:无从判定");
+ assert!(result.peers.is_none());
+ assert_eq!(
+ spec::local_dir_of("./plugin", &base).as_deref(),
+ Some(dir.as_path())
+ );
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn local_spec_reports_dsh_peer_compatibility_without_network() {
+ let (base, _) = fixture(
+ "peer",
+ Some(r#"{"name":"dsh-probe","peerDependencies":{"@deepseek-ai/dsh":"^0.2.0"}}"#),
+ );
+
+ let compatible = inspect_local("./plugin", &base, Some("0.2.1"));
+ assert_eq!(compatible.compatible, Some(true));
+ assert_eq!(
+ compatible
+ .peers
+ .as_ref()
+ .and_then(|p| p.get("@deepseek-ai/dsh"))
+ .map(String::as_str),
+ Some("^0.2.0")
+ );
+
+ let incompatible = inspect_local("./plugin", &base, Some("0.1.7"));
+ assert_eq!(incompatible.compatible, Some(false));
+
+ // 运行时版本未知(核心未装):保留 peers 但不判定,前端按 Fail-Open 放行
+ let unknown = inspect_local("./plugin", &base, None);
+ assert_eq!(unknown.compatible, None);
+ assert!(unknown.peers.is_some());
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn local_spec_reports_local_missing_for_absent_dir_or_manifest() {
+ // 三种「本地路径但拿不到清单」的形态都必须落到 local-missing,而不是
+ // invalid-spec / not-found —— 后两者会让用户以为要改写法或去 registry 找包。
+ let (base, dir) = fixture("absent", None);
+
+ let missing_dir = inspect_local("./never-existed", &base, Some("0.2.0"));
+ assert_eq!(missing_dir.problem.as_deref(), Some("local-missing"));
+ assert_eq!(missing_dir.name, None);
+ assert_eq!(missing_dir.compatible, None);
+
+ let missing_manifest = inspect_local("./plugin", &base, Some("0.2.0"));
+ assert_eq!(missing_manifest.problem.as_deref(), Some("local-missing"));
+
+ std::fs::write(dir.join("package.json"), "{ not json").unwrap();
+ let broken = inspect_local("./plugin", &base, Some("0.2.0"));
+ assert_eq!(broken.problem.as_deref(), Some("local-missing"));
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn local_spec_name_falls_back_to_the_directory_name() {
+ // 清单没有 name:目录名是唯一可用标识(也是 pnpm 落盘 / 产物核验用的键)。
+ let (base, _) = fixture("noname", Some(r#"{"version":"1.0.0"}"#));
+
+ let result = inspect_local("./plugin", &base, Some("0.2.0"));
+
+ assert_eq!(result.problem, None);
+ assert_eq!(result.name.as_deref(), Some("plugin"));
+ assert_eq!(result.version.as_deref(), Some("1.0.0"));
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+}
diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rs
index 8b1bafd7..bc8cdea0 100644
--- a/src-tauri/src/service/plugin/install/mod.rs
+++ b/src-tauri/src/service/plugin/install/mod.rs
@@ -86,6 +86,7 @@ use diagnose::{
use pnpm::ensure_pnpm;
use single::single_plugin_args;
use spec::{bundled_dir_of, normalize_git_spec, preset_spec_for_install, spec_argument};
+pub(crate) use spec::local_spec_from_path;
/// 允许构建重试的上限。每次重试解决 pnpm 报出的一个允许键(git depPath 或
/// 传递构建包名),多个 git 插件 / 多个原生依赖各占一次,上限封顶防死循环。
@@ -132,6 +133,7 @@ fn policy_verification_retry_delay(retry: usize) -> std::time::Duration {
/// 一次安装操作的目标:`id` 是稳定标识(错误记录 / 快照 / bundles 对账),
/// `name` 是 `node_modules` 下的目录名(产物核验与入口补构建用,无法解析时为
/// `None`,此时跳过这两步),`spec` 是最终交给 `dsh plugin add` 的参数。
+#[derive(Debug)]
pub(crate) struct InstallTarget {
pub id: String,
pub name: Option<String>,
@@ -158,7 +160,7 @@ pub(crate) async fn install_internal(
/// 按原始 spec 安装(插件市场 / 手动输入):与预装路径共用同一套编排,只是目标
/// 不再来自预设清单,因而没有捆绑目录与版本矩阵——spec 原样交给 pnpm 解析。
pub async fn install_specs(app_handle: &AppHandle, specs: &[String]) -> Result<(), String> {
- let targets = spec_targets(app_handle, specs);
+ let targets = spec_targets(app_handle, specs)?;
if targets.is_empty() {
return Err("PLUGIN_SPECS_EMPTY: no plugin specs provided".to_string());
}
@@ -213,22 +215,35 @@ fn preset_targets(app_handle: &AppHandle, ids: &[String]) -> Result<Vec<InstallT
Ok(targets)
}
-/// 原始 spec → 安装目标:`link:`/`file:` 读目标包名(读不到回落目录名),npm 形态
-/// 剥离版本后缀,git / URL 形态无法静态得知包名,回落 spec 本身并放弃产物核验。
+/// 原始 spec → 安装目标:本地目录 spec 规范成 `link:<绝对路径>` 并读目标包名
+/// (读不到回落目录名),npm 形态剥离版本后缀,git / URL 形态无法静态得知包名,
+/// 回落 spec 本身并放弃产物核验。
///
/// 命中资源清单的 spec 走 [`preset_targets`] 同一套解析:同一条目无论从预装引导页
/// (预设 id)还是从面板 / 市场(原始 spec)进入,都必须解析出相同的安装目标——内置
/// 插件的捆绑 `link:` 目录与清单版本矩阵只能在这一侧得到。解析失败(内置插件缺
/// 捆绑产物,属发布缺陷)时退回裸 spec,让 pnpm 报出真实原因而不是静默跳过该条目。
-fn spec_targets(app_handle: &AppHandle, specs: &[String]) -> Vec<InstallTarget> {
+///
+/// 本地目录在交给 pnpm 之前先校验:目录与 `package.json` 缺一都会让 pnpm 装出
+/// 一个没有清单的联接,随后的产物核验只会报出「命令成功但没有产物」这种与真实
+/// 原因无关的错误。
+fn spec_targets(app_handle: &AppHandle, specs: &[String]) -> Result<Vec<InstallTarget>, String> {
let core_version = crate::service::core::active_version(app_handle);
let presets = load_presets(app_handle);
+ // 相对路径的基准:`dsh plugin` 不切换 cwd,pnpm 在 `$AppData/dependencies/dsh`
+ // 下执行(与 [`install_with_cancel`] 传入的 cwd 同源),故本地 spec 必须在这里
+ // 先绝对化,用户输入的 `./plugins/x` 才不会被解析到应用安装目录里。
+ let base = config::get_dsh_install_path(app_handle);
let mut targets = Vec::with_capacity(specs.len());
for spec in specs {
let spec = spec.trim();
if spec.is_empty() {
continue;
}
+ if let Some(local) = spec::local_path_spec(spec) {
+ targets.push(local_target(&local, &base)?);
+ continue;
+ }
if let Some(preset) = presets
.iter()
.find(|preset| preset.id == spec || preset.spec == spec)
@@ -247,14 +262,38 @@ fn spec_targets(app_handle: &AppHandle, specs: &[String]) -> Vec<InstallTarget>
}
}
let raw = normalize_git_spec(spec);
- let name = spec::package_name_of_spec(&raw);
+ let name = spec::package_name_of_spec(&raw, &base);
targets.push(InstallTarget {
id: name.clone().unwrap_or_else(|| raw.clone()),
name,
spec: spec_argument(&raw, core_version.as_deref()),
});
}
- targets
+ Ok(targets)
+}
+
+/// 本地目录 spec → 安装目标:目录与清单都必须在场,spec 统一改写成 `link:` 绝对路径。
+///
+/// `id` 取包名(产物核验、快照、错误记录都以包名为键);清单读不出时回落绝对路径
+/// ——它是这条 spec 唯一的稳定标识,且与 pnpm 落盘的依赖键(`link:<路径>`)可读地对应。
+fn local_target(raw: &Path, base: &Path) -> Result<InstallTarget, String> {
+ let spec = raw.to_string_lossy();
+ let Some(dir) = spec::local_dir_of(&spec, base) else {
+ return Err(format!("PLUGIN_LOCAL_SPEC_INVALID: {spec}"));
+ };
+ if !dir.is_dir() {
+ return Err(format!(
+ "PLUGIN_LOCAL_DIR_MISSING: local plugin directory not found: {}",
+ dir.display()
+ ));
+ }
+ let name = spec::local_package_name(&dir);
+ let link = format!("link:{}", spec::forward_slashes(&dir));
+ Ok(InstallTarget {
+ id: name.clone().unwrap_or_else(|| link.clone()),
+ name,
+ spec: link,
+ })
}
/// 被门禁拦下的条目**全部**已在 lock 中时,返回该补写的豁免条目(精确 `包名@版本`)。
@@ -912,6 +951,115 @@ pub(super) fn append_command_output(all_output: &mut String, captured: &str) {
mod tests {
use super::*;
+ // ---- 本地目录 spec 的安装目标解析 ----
+
+ /// 造一个真实存在的本地插件目录:本地 spec 的解析会 canonicalize,只有落盘
+ /// 路径才能覆盖「尾斜杠 / 混用分隔符 / 短名」这些形态。
+ fn local_plugin_fixture(tag: &str, manifest: Option<&str>) -> (std::path::PathBuf, std::path::PathBuf) {
+ let base = std::env::temp_dir().join(format!("dsh-local-{}-{tag}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ let dir = base.join("plugin");
+ std::fs::create_dir_all(&dir).unwrap();
+ if let Some(manifest) = manifest {
+ std::fs::write(dir.join("package.json"), manifest).unwrap();
+ }
+ // `temp_dir()` 在 Windows 上是 8.3 短名(`IUUUUU~1`),而安装 spec 按设计
+ // 展开成真实长名——夹具必须站在同一口径上比较。
+ let base = dunce::simplified(&std::fs::canonicalize(&base).unwrap()).to_path_buf();
+ let dir = base.join("plugin");
+ (base, dir)
+ }
+
+ #[test]
+ fn local_target_emits_link_absolute_spec_and_manifest_name() {
+ let (base, dir) = local_plugin_fixture(
+ "manifest",
+ Some("{\"name\":\"dsh-reverse-skill\",\"version\":\"1.0.2\"}"),
+ );
+
+ let target = local_target(std::path::Path::new("./plugin"), &base).unwrap();
+
+ assert_eq!(target.id, "dsh-reverse-skill");
+ assert_eq!(target.name.as_deref(), Some("dsh-reverse-skill"));
+ assert_eq!(target.spec, format!("link:{}", spec::forward_slashes(&dir)));
+ assert!(target.spec.starts_with("link:"));
+ assert!(
+ !target.spec.contains('\\'),
+ "pnpm 只接受正斜杠形态: {}",
+ target.spec
+ );
+ assert!(!target.spec.ends_with('/'));
+ assert!(
+ std::path::Path::new(target.spec.trim_start_matches("link:")).is_absolute(),
+ "相对输入必须绝对化:pnpm 的 cwd 是 dsh 安装目录,不是调用方目录: {}",
+ target.spec
+ );
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn local_target_falls_back_to_directory_name_without_manifest() {
+ // 无 package.json 时不在这里报错:dsh 会把这类依赖装成普通依赖(非 profile
+ // 层),pnpm 的目录名就是唯一可用的标识,也是产物核验要看的目录。
+ let (base, dir) = local_plugin_fixture("bare", None);
+
+ let target = local_target(std::path::Path::new("./plugin"), &base).unwrap();
+
+ assert_eq!(target.id, "plugin");
+ assert_eq!(target.name.as_deref(), Some("plugin"));
+ assert_eq!(target.spec, format!("link:{}", spec::forward_slashes(&dir)));
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn local_target_rejects_missing_directory_before_pnpm_runs() {
+ // 目录缺失必须在这里拦下:交给 pnpm 只会得到 ERR_PNPM_LINKED_PKG_DIR_NOT_FOUND
+ // 或一个空联接,用户看不出到底哪里不对。
+ let (base, _) = local_plugin_fixture("missing", None);
+
+ let err = local_target(std::path::Path::new("./absent"), &base).unwrap_err();
+
+ assert!(err.starts_with("PLUGIN_LOCAL_DIR_MISSING"), "{err}");
+ assert!(err.contains("absent"), "错误里要给出解析后的路径: {err}");
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn local_target_rejects_a_file_path() {
+ // 粘贴到文件(而非目录)同样要提前拒绝,否则 pnpm 装出一个没有清单的联接,
+ // 产物核验只会报「命令成功但没有产物」这种与真实原因无关的错误。
+ let (base, dir) = local_plugin_fixture("file", None);
+ let file = dir.join("index.js");
+ std::fs::write(&file, "").unwrap();
+
+ let err = local_target(&file, &base).unwrap_err();
+
+ assert!(err.starts_with("PLUGIN_LOCAL_DIR_MISSING"), "{err}");
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn local_target_honours_absolute_paths_verbatim() {
+ // 绝对路径不受 base 影响:用户从别的盘粘过来的插件目录必须指向它自己。
+ let (base, _) = local_plugin_fixture("absolute", None);
+ let (other_base, other_dir) = local_plugin_fixture("absolute-other", None);
+
+ let target = local_target(&other_dir, &base).unwrap();
+
+ assert_eq!(target.spec, format!("link:{}", spec::forward_slashes(&other_dir)));
+ assert_ne!(
+ target.spec,
+ format!("link:{}", spec::forward_slashes(&base.join("plugin")))
+ );
+
+ let _ = std::fs::remove_dir_all(&base);
+ let _ = std::fs::remove_dir_all(&other_base);
+ }
+
#[test]
fn locked_release_age_exemptions_require_every_blocked_entry_to_be_locked() {
let dir = std::env::temp_dir().join(format!("dsh-heal-{}", std::process::id()));
diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rs
index 0ab164ea..f6ce9d1f 100644
--- a/src-tauri/src/service/plugin/install/single.rs
+++ b/src-tauri/src/service/plugin/install/single.rs
@@ -95,7 +95,7 @@ async fn resolve_missing_targets(
if version.is_some() {
continue;
}
- let Some(latest) = known_latest(id) else {
+ let Some(latest) = known_latest(app_handle, id) else {
continue;
};
if !is_registry_version(&latest) || installed_package_version(&profile, id).as_deref() == Some(latest.as_str()) {
@@ -329,7 +329,7 @@ pub(super) const RELEASE_AGE_RELAXED_FLAG: &str = "--config.minimumReleaseAge=0"
/// 目标版本取更新探测缓存([`known_latest`],不新发网络请求);git 托管插件的「最新」是
/// 提交 SHA、`next` 这类 ref 都不是版本,不能进发布时长豁免清单,按形状挡掉。
fn release_age_target(app_handle: &AppHandle, profile: &Path, id: &str) -> (bool, bool) {
- let target = known_latest(id);
+ let target = known_latest(app_handle, id);
let target = target.as_deref().filter(|latest| is_registry_version(latest));
let Some(target) = target else {
return (false, false);
@@ -823,7 +823,7 @@ async fn verify_update_landed(
.filter(|expected| *expected != detail && is_registry_version(expected))
.map(str::to_string)
.or_else(|| {
- known_latest(id).filter(|latest| latest != &detail && is_registry_version(latest))
+ known_latest(app_handle, id).filter(|latest| latest != &detail && is_registry_version(latest))
});
let retryable = latest.as_deref().is_some_and(|latest| {
!profile_release_age_excluded(app_handle, &format!("{id}@{latest}"))
diff --git a/src-tauri/src/service/plugin/install/spec.rs b/src-tauri/src/service/plugin/install/spec.rs
index 7dfed702..fb5ac361 100644
--- a/src-tauri/src/service/plugin/install/spec.rs
+++ b/src-tauri/src/service/plugin/install/spec.rs
@@ -1,6 +1,6 @@
-//! 安装 spec 准备:内置插件捆绑目录解析(`link:` 本地依赖——pnpm 对 `file:` 的
-//! 盘符绝对路径会按相对解析)、GitHub 简写规范化(绕开 pnpm 的 HTTPS→SSH 回退
-//! 缺陷)与 Windows 下含空格 spec 的引号化(dsh CLI 只在 win32 用 shell 拼接参数)。
+//! 安装 spec 准备:本地目录 spec 的判定与规范化(统一改写成 `link:` 绝对路径)、
+//! 内置插件捆绑目录解析、GitHub 简写规范化(绕开 pnpm 的 HTTPS→SSH 回退缺陷)
+//! 与 Windows 下含空格 spec 的引号化(dsh CLI 只在 win32 用 shell 拼接参数)。
use std::path::{Path, PathBuf};
use tauri::AppHandle;
@@ -9,20 +9,129 @@ use super::bundled_dep_spec;
use super::bundled_plugin_dir;
use super::PreinstallPluginInfo;
+/// 本地目录 spec 的判定:`link:` / `file:` 前缀、UNC、盘符绝对路径、`/` 起始的
+/// 根路径与 `./` / `../` 显式相对路径都算;返回尚未绝对化的原始路径。
+///
+/// 判定必须先于 [`package_name_of_spec`] 里「含 `:` 即放弃」的形态检查:Windows
+/// 盘符自带冒号,裸路径否则会被当成 git / URL 形态丢掉包名,安装前的只读检查也会
+/// 误报 `invalid-spec`。
+pub(super) fn local_path_spec(spec: &str) -> Option<PathBuf> {
+ let trimmed = unquote(spec.trim());
+ if trimmed.is_empty() {
+ return None;
+ }
+ for prefix in ["link:", "file:"] {
+ if let Some(rest) = trimmed.strip_prefix(prefix) {
+ let rest = strip_file_url(rest);
+ if rest.is_empty() {
+ return None;
+ }
+ return Some(PathBuf::from(rest));
+ }
+ }
+ if trimmed.starts_with('/') || trimmed.starts_with("\\\\") {
+ return Some(PathBuf::from(trimmed));
+ }
+ if has_drive_prefix(trimmed) {
+ return Some(PathBuf::from(trimmed));
+ }
+ if trimmed.starts_with("./") || trimmed.starts_with("../") {
+ return Some(PathBuf::from(trimmed));
+ }
+ if trimmed.starts_with(".\\") || trimmed.starts_with("..\\") {
+ return Some(PathBuf::from(trimmed));
+ }
+ None
+}
+
+/// 目录选择器给出的路径 → 安装 spec:一律写成 `link:` + 正斜杠绝对路径。
+///
+/// 与 [`local_dir_of`] 的区别是这里还没有目录:用户在安装框里手打的路径同样经
+/// 这里统一形态,面板把结果回填进输入框后走的是与手打完全相同的安装链路。
+pub(crate) fn local_spec_from_path(path: &Path) -> String {
+ format!("link:{}", forward_slashes(path))
+}
+
+/// 剥掉成对的首尾引号:Windows 资源管理器「复制为路径」给出的正是 `"D:\x"`,
+/// 这对引号会被 pnpm 当成路径的一部分而报 `ERR_PNPM_SPEC_NOT_SUPPORTED`。
+fn unquote(spec: &str) -> &str {
+ for quote in ['"', '\''] {
+ if let Some(rest) = spec
+ .strip_prefix(quote)
+ .and_then(|rest| rest.strip_suffix(quote))
+ {
+ return rest.trim();
+ }
+ }
+ spec
+}
+
+/// 盘符绝对路径(`D:\x` / `D:/x`):两个 ASCII 字母之外的盘符不存在,其余形态
+/// 一律不按本地路径处理。
+fn has_drive_prefix(spec: &str) -> bool {
+ let bytes = spec.as_bytes();
+ bytes.len() > 2
+ && bytes[0].is_ascii_alphabetic()
+ && bytes[1] == b':'
+ && (bytes[2] == b'/' || bytes[2] == b'\\')
+}
+
+/// `file:` 后的正文:`file:///D:/x` 的盘符形态还原成 `D:/x`,其余原样返回。
+///
+/// 不还原就会得到 `///D:/x`——在 Windows 上被解析成一个带 `\\` 前缀的怪路径,
+/// 拼进 `link:` 后 pnpm 报 `ERR_PNPM_SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER`。
+fn strip_file_url(rest: &str) -> &str {
+ let trimmed = rest.trim();
+ let stripped = trimmed.trim_start_matches('/');
+ if has_drive_prefix(stripped) {
+ stripped
+ } else {
+ trimmed
+ }
+}
+
+/// 本地 spec 的绝对目录:相对路径以 `base`(`dsh plugin add` 子进程的 cwd)为基准。
+///
+/// 存在的路径走 `canonicalize`:pnpm 与 chokidar 都按真实长名工作,Windows 8.3
+/// 短名(`PROGRA~1` 一类)会让 chokidar 的原生事件层断言失败直接终止进程,必须在
+/// 进入这两条链路之前展开;`dunce::simplified` 去掉 canonicalize 的 `\\?\` 前缀,
+/// 否则 pnpm 会把该前缀当成路径的一部分。
+pub(super) fn local_dir_of(spec: &str, base: &Path) -> Option<PathBuf> {
+ let path = local_path_spec(spec)?;
+ let joined = if path.is_absolute() {
+ path
+ } else {
+ base.join(path)
+ };
+ Some(
+ std::fs::canonicalize(&joined)
+ .map(|resolved| dunce::simplified(&resolved).to_path_buf())
+ .unwrap_or_else(|_| dunce::simplified(&joined).to_path_buf()),
+ )
+}
+
+/// 路径的 `/` 分隔、无尾斜杠字符串(pnpm 落盘与 dsh 对账都用这一形态)。
+pub(super) fn forward_slashes(path: &Path) -> String {
+ path.to_string_lossy()
+ .replace('\\', "/")
+ .trim_end_matches('/')
+ .to_string()
+}
+
/// 从安装 spec 解析包名,供「产物核验」与「入口补构建」定位
/// `node_modules/<name>`。
///
-/// - `link:` / `file:` 本地依赖:读目标目录的 `package.json` 的 `name`(最准确),
-/// 读不到时回落目录名(pnpm 落盘的目录名通常是包名,但 `link:` 目标目录名未必
-/// 与包名一致,故以清单为准);
+/// - 本地目录(`link:` / `file:` / 裸路径):读目标目录的 `package.json` 的 `name`
+/// (最准确),读不到时回落目录名(pnpm 落盘的目录名通常是包名,但 `link:` 目标
+/// 目录名未必与包名一致,故以清单为准);
/// - npm 形态(含 scoped):剥离末尾 `@版本/区间`,`@scope/name` 里的 `@` 不算分隔符;
/// - git / URL / 其他含 `:` 或空白的形态:install 后的目录名无法静态得知,返回 `None`
/// ——调用方跳过产物核验而不是把 `node_modules/<整条 spec>` 当成必然缺失。
-pub(super) fn package_name_of_spec(spec: &str) -> Option<String> {
- for prefix in ["link:", "file:"] {
- if let Some(path) = spec.strip_prefix(prefix) {
- return local_package_name(Path::new(path.trim()));
- }
+pub(super) fn package_name_of_spec(spec: &str, base: &Path) -> Option<String> {
+ if let Some(dir) = local_dir_of(spec, base) {
+ // 目录不在场时不给名字:这条路径已被 `local_target` 提前拒绝,把不存在的
+ // 目录名当成落盘目录只会让产物核验报一个与真实原因无关的缺失。
+ return dir.is_dir().then(|| local_package_name(&dir)).flatten();
}
if spec.contains(':') || spec.contains(char::is_whitespace) {
return None;
@@ -35,8 +144,8 @@ pub(super) fn package_name_of_spec(spec: &str) -> Option<String> {
}
}
-/// `link:` / `file:` 目标目录的包名:优先读其 `package.json`,回落目录名。
-fn local_package_name(path: &Path) -> Option<String> {
+/// 本地目录的包名:优先读其 `package.json`,回落目录名。
+pub(super) fn local_package_name(path: &Path) -> Option<String> {
if let Ok(content) = std::fs::read_to_string(path.join("package.json")) {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(name) = value.get("name").and_then(|v| v.as_str()) {
@@ -257,7 +366,10 @@ mod tests {
fn install_spec_passthrough_for_regular_preset() {
// 普通插件:spec 原样返回,与捆绑目录无关
let p = preset("dshmarket", "dshmarket", false);
- assert_eq!(preset_spec_for_install(&p, None, None).unwrap(), "dshmarket");
+ assert_eq!(
+ preset_spec_for_install(&p, None, None).unwrap(),
+ "dshmarket"
+ );
assert_eq!(
preset_spec_for_install(&p, Some(PathBuf::from("/ignored")), None).unwrap(),
"dshmarket"
@@ -514,6 +626,200 @@ mod tests {
assert!(!joins_pnpm_args_in_shell(Some("not-a-version")));
}
+ // ---- 本地目录 spec(issue 需求的本地安装链路)----
+
+ /// 造一个真实存在的本地插件目录:本地 spec 必须走 canonicalize,只有真实路径
+ /// 才能覆盖「短名展开」「尾斜杠剥除」「大小写归一」这些只有落盘才成立的形态。
+ fn temp_plugin_dir(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("dsh-spec-{}-{tag}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ // `temp_dir()` 在 Windows 上是 8.3 短名(`IUUUUU~1`),而实现按设计展开成
+ // 真实长名——夹具必须站在同一口径上比较,否则断言只是在比短名。
+ canonical(&dir)
+ }
+
+ fn canonical(path: &Path) -> PathBuf {
+ dunce::simplified(&std::fs::canonicalize(path).unwrap()).to_path_buf()
+ }
+
+ #[test]
+ fn local_path_spec_recognizes_every_local_form() {
+ for spec in [
+ "link:D:/plugins/probe",
+ "file:D:/plugins/probe",
+ "file:///D:/plugins/probe",
+ "D:\\plugins\\probe",
+ "D:/plugins/probe",
+ "./plugins/probe",
+ "../plugins/probe",
+ ".\\plugins\\probe",
+ "..\\plugins\\probe",
+ "/opt/dsh/plugins/probe",
+ "link:/opt/dsh/plugins/probe",
+ "file:///opt/dsh/plugins/probe",
+ "\\\\server\\share\\probe",
+ " D:/plugins/probe ",
+ ] {
+ assert!(local_path_spec(spec).is_some(), "应识别为本地 spec: {spec}");
+ }
+ assert_eq!(
+ local_path_spec("file:///D:/plugins/probe"),
+ Some(PathBuf::from("D:/plugins/probe"))
+ );
+ }
+
+ #[test]
+ fn local_path_spec_ignores_registry_and_git_specs() {
+ // 回归:裸包名、scoped 包名、带版本、GitHub 简写、git / https / ssh 形态
+ // 都不能被当成路径——否则普通安装会被重写成 `link:<拼出来的怪路径>`。
+ for spec in [
+ "dshmarket",
+ "@scope/dsh-plugin",
+ "dshmarket@^2.12.0",
+ "@scope/[email protected]",
+ "github:user/repo#next",
+ "git+https://github.com/user/repo.git",
+ "git+ssh://[email protected]/user/repo.git",
+ "https://example.com/x.tgz",
+ "",
+ " ",
+ "link:",
+ "file:",
+ ] {
+ assert!(
+ local_path_spec(spec).is_none(),
+ "不得识别为本地 spec: {spec}"
+ );
+ }
+ }
+
+ #[test]
+ fn local_path_spec_strips_pasted_quotes() {
+ // 资源管理器「复制为路径」粘贴出来是带引号的;引号必须剥掉,否则 pnpm
+ // 收到的路径里带着字面 `"` 而直接报 spec 不支持。
+ assert_eq!(
+ local_path_spec("\"D:/plugins/probe\""),
+ Some(PathBuf::from("D:/plugins/probe"))
+ );
+ assert_eq!(
+ local_path_spec("'D:/plugins/probe'"),
+ Some(PathBuf::from("D:/plugins/probe"))
+ );
+ assert!(local_path_spec("\"\"").is_none());
+ }
+
+ #[test]
+ fn local_dir_of_resolves_relative_against_the_install_cwd() {
+ // 相对路径的基准是 `dsh plugin add` 子进程的 cwd(`$AppData/dependencies/dsh`),
+ // 不是 profile 目录,也不是应用进程自己的 cwd。
+ let base = temp_plugin_dir("base");
+ let dir = base.join("plugins").join("probe");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(
+ dir.join("package.json"),
+ "{\"name\":\"dsh-probe\",\"version\":\"1.2.3\"}",
+ )
+ .unwrap();
+
+ assert_eq!(local_dir_of("./plugins/probe", &base), Some(dir.clone()));
+ assert_eq!(
+ local_dir_of("plugins/probe", &base),
+ None,
+ "裸相对路径不是本地 spec,须显式 ./ 或 ../"
+ );
+ assert_eq!(
+ local_dir_of(&format!("link:{}", forward_slashes(&dir)), &base),
+ Some(dir.clone())
+ );
+ // 尾斜杠 / 原生分隔符 / 大小写都归一到同一真实路径
+ assert_eq!(
+ local_dir_of(&format!("link:{}/", forward_slashes(&dir)), &base),
+ Some(dir.clone()),
+ "尾斜杠要剥掉"
+ );
+ assert_eq!(
+ local_dir_of(&format!("link:{}", dir.display()), &base),
+ Some(dir.clone()),
+ "原生分隔符要归一到同一真实路径"
+ );
+
+ #[cfg(windows)]
+ assert_eq!(
+ local_dir_of(&format!("file:///{}", forward_slashes(&dir)), &base),
+ Some(dir.clone()),
+ "file:/// 的盘符还原只在 Windows 成立(Unix 上 /D:/x 不是绝对路径)"
+ );
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn local_dir_of_keeps_missing_paths_for_the_caller_to_reject() {
+ // 不存在的目录不在这里报错(调用方要按目录 / 清单分别给出可读原因),
+ // 但仍要绝对化并去掉尾斜杠。
+ let base = temp_plugin_dir("missing");
+ assert_eq!(
+ local_dir_of("./nowhere/", &base),
+ Some(base.join("nowhere"))
+ );
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn package_name_of_spec_reads_local_manifest_then_falls_back_to_dir_name() {
+ let base = temp_plugin_dir("name");
+ let named = base.join("weird-dir-name");
+ std::fs::create_dir_all(&named).unwrap();
+ std::fs::write(
+ named.join("package.json"),
+ "{\"name\":\"dsh-reverse-skill\"}",
+ )
+ .unwrap();
+ // 清单里的包名优先于目录名(link: 目标目录名未必等于包名,pnpm 落盘用包名)
+ assert_eq!(
+ package_name_of_spec(&format!("link:{}", forward_slashes(&named)), &base),
+ Some("dsh-reverse-skill".to_string())
+ );
+ assert_eq!(
+ package_name_of_spec("./weird-dir-name", &base),
+ Some("dsh-reverse-skill".to_string())
+ );
+
+ // 清单缺失 / 无 name:回落目录名,产物核验仍能定位 node_modules/<目录名>
+ let bare = base.join("bare-dir");
+ std::fs::create_dir_all(&bare).unwrap();
+ assert_eq!(
+ package_name_of_spec("./bare-dir", &base),
+ Some("bare-dir".to_string())
+ );
+ assert_eq!(package_name_of_spec("./never-existed", &base), None);
+
+ // 回归:注册表与 git 形态照旧解析成包名或 None,不受本地分支影响
+ assert_eq!(
+ package_name_of_spec("dshmarket@^2.12.0", &base),
+ Some("dshmarket".to_string())
+ );
+ assert_eq!(
+ package_name_of_spec("@scope/[email protected]", &base),
+ Some("@scope/dsh-plugin".to_string())
+ );
+ assert_eq!(
+ package_name_of_spec("github:user/repo", &base),
+ None,
+ "含 `:` 且非本地形态:装后目录名不可静态得知"
+ );
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn forward_slashes_normalizes_separators_and_trailing_slash() {
+ assert_eq!(forward_slashes(Path::new("D:\\a\\b\\")), "D:/a/b");
+ assert_eq!(forward_slashes(Path::new("D:/a/b/")), "D:/a/b");
+ assert_eq!(forward_slashes(Path::new("D:\\a")), "D:/a");
+ }
+
#[test]
fn spec_argument_keeps_space_spec_bare_for_argv_cores() {
// issue #647:0.1.6-alpha.2 起 spec 作为单个 argv 直达 pnpm,Windows 上的
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index 2c170a11..f366f16c 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -31,11 +31,14 @@
//! - [`patch_entries`]:补丁层悬空 `insert` 条目的启动前预检与显式清理(错误页恢复入口)
//! - [`cancel`]:Windows 下取消正在进行的安装
//! - [`watch`]:已安装插件文件监控(轮询指纹比对 + `dsh-plugins-updated` 事件推送)
+//! - [`hmr`]:本地路径插件的热重载(把已挂载的本地插件源码目录写进桌面端独占的
+//! 补丁层,随启动以 `--patch` 注入核心 HMR,源码改动即时生效)
mod cancel;
pub mod compat;
pub mod disable;
pub mod errors;
+mod hmr;
mod install;
mod installed;
mod internal;
@@ -55,6 +58,7 @@ pub use cancel::cancel;
pub(crate) use cancel::terminate_active_installs_blocking;
pub(crate) use process::acquire_operation_lock;
pub(crate) use install::harness_prefer_bundled_pnpm;
+pub(crate) use install::local_spec_from_path;
pub(crate) use install::uninstall_deprecated_plugins;
pub use install::{
allow_policy_versions, allow_version_exemptions, inspect_specs, install, install_specs,
@@ -64,6 +68,8 @@ pub(crate) use installed::{
declared_packages, ensure_profile_npmrc, installed_name, list_installed, profile_dir,
};
pub use installed::{list, PreinstallPlugin};
+pub(crate) use hmr::{status as local_plugin_hmr_status, sync_layer as local_plugin_hmr_sync};
+pub use hmr::LocalHmrStatus;
pub(crate) use internal::cancel as cancel_internal_plugins;
pub(crate) use internal::ensure as ensure_internal_plugins;
pub use preset::repo_url_of;
diff --git a/src-tauri/src/service/plugin/update.rs b/src-tauri/src/service/plugin/update.rs
index c2fe963e..288c60e6 100644
--- a/src-tauri/src/service/plugin/update.rs
+++ b/src-tauri/src/service/plugin/update.rs
@@ -14,7 +14,7 @@
//! `latest > installed` 才视为有更新(避免把 `latest` 指向更旧版本误判为可升级)。
//!
//! 与 market 相同的兜底:任何一次判定失败都报告「无更新」,绝不因一次网络抖动或
-//! 404 让整个插件管理器不可用;结果按 (id, spec, 版本, Git 锁定提交) 缓存 30 分钟
+//! 404 让整个插件管理器不可用;结果按 (id, 代理, spec, 版本, Git 锁定提交) 缓存 30 分钟
//! (TTL),期间
//! 重复调用直接命中缓存、不重复打网络。缓存缺失/未判定时 `update_available=false`,
//! 前端由 `refresh_plugin_updates` 在挂载后补齐,因此首次展示短暂无按钮、随后自动
@@ -56,23 +56,33 @@ fn cache() -> &'static Mutex<HashMap<String, CacheEntry>> {
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}
-/// 缓存键:spec、版本或该直接依赖的 Git 锁定提交变化后,旧结果自动失效。
-fn cache_key(id: &str, spec: &str, version: &str, locked: &HashMap<String, String>) -> String {
+/// 缓存键包含请求使用的代理,防止切换代理后复用旧失败或被旧请求回填覆盖。
+fn cache_key(
+ id: &str,
+ spec: &str,
+ version: &str,
+ locked: &HashMap<String, String>,
+ proxy_url: &str,
+) -> String {
let locked_commit = extract_github_target(spec)
.and_then(|_| locked.get(id))
.map(String::as_str)
.unwrap_or_default();
- format!("{id}\u{0}{spec}\u{0}{version}\u{0}{locked_commit}")
+ format!("{id}\u{0}{proxy_url}\u{0}{spec}\u{0}{version}\u{0}{locked_commit}")
}
/// 探测缓存里该插件的「最新版本」;没探测过或缓存里没有它时返回 `None`。
///
/// 升级「以 0 退出但版本没动」时需要知道本该装到哪个版本:发布时长豁免是按精确
/// `包名@版本` 写的,没有目标版本就给不出可授权的条目。这里只读缓存、不新发请求
-/// (探测由 [`refresh`] 统一负责),缓存键以 `id` 开头(见 [`cache_key`])。
-pub(crate) fn known_latest(id: &str) -> Option<String> {
- let cache = cache().lock().unwrap();
- let prefix = format!("{id}\u{0}");
+/// (探测由 [`refresh`] 统一负责),仅采信当前代理下的结果。
+pub(crate) fn known_latest(app_handle: &AppHandle, id: &str) -> Option<String> {
+ let proxy_url = crate::config::get_store_dat_setting(app_handle).proxy_url;
+ cached_latest(&cache().lock().unwrap(), id, &proxy_url)
+}
+
+fn cached_latest(cache: &HashMap<String, CacheEntry>, id: &str, proxy_url: &str) -> Option<String> {
+ let prefix = format!("{id}\u{0}{proxy_url}\u{0}");
cache
.iter()
.filter(|(key, _)| key.starts_with(&prefix))
@@ -535,11 +545,12 @@ async fn compute_update(
pub fn apply_cache(app_handle: &AppHandle, plugins: &mut [DshPlugin]) {
let specs = read_specs(app_handle);
let locked = read_locked_commits(&profile_dir(app_handle), &specs);
+ let proxy_url = crate::config::get_store_dat_setting(app_handle).proxy_url;
let cache = cache().lock().unwrap();
let now = Instant::now();
for p in plugins.iter_mut() {
let spec = specs.get(&p.id).cloned().unwrap_or_default();
- let key = cache_key(&p.id, &spec, &p.version, &locked);
+ let key = cache_key(&p.id, &spec, &p.version, &locked, &proxy_url);
if let Some(entry) = cache.get(&key) {
if now.duration_since(entry.at) < UPDATES_TTL {
p.update_available = entry.info.update_available;
@@ -557,7 +568,8 @@ pub async fn refresh(app_handle: &AppHandle) -> Result<Vec<DshPlugin>, String> {
let mut plugins = super::watch::list(app_handle);
let specs = read_specs(app_handle);
let locked = read_locked_commits(&profile_dir(app_handle), &specs);
- let client = reqwest::Client::builder()
+ let proxy_url = crate::config::get_store_dat_setting(app_handle).proxy_url;
+ let client = crate::config::proxy::client_builder(&proxy_url)?
.user_agent("deepseek-harness-desktop")
.timeout(Duration::from_secs(10))
.build()
@@ -577,7 +589,7 @@ pub async fn refresh(app_handle: &AppHandle) -> Result<Vec<DshPlugin>, String> {
let cache = cache().lock().unwrap();
for (idx, p) in plugins.iter_mut().enumerate() {
let spec = specs.get(&p.id).cloned().unwrap_or_default();
- let key = cache_key(&p.id, &spec, &p.version, &locked);
+ let key = cache_key(&p.id, &spec, &p.version, &locked, &proxy_url);
if let Some(entry) = cache.get(&key) {
if now.duration_since(entry.at) < UPDATES_TTL {
p.update_available = entry.info.update_available;
@@ -634,6 +646,118 @@ pub async fn refresh(app_handle: &AppHandle) -> Result<Vec<DshPlugin>, String> {
mod tests {
use super::*;
+ #[test]
+ fn failed_update_cache_is_not_reused_after_proxy_changes() {
+ let locked = HashMap::new();
+ for (before, after) in [
+ ("", "http://127.0.0.1:7897/"),
+ ("http://127.0.0.1:7897/", "socks5h://127.0.0.1:1080"),
+ ("http://127.0.0.1:7897/", ""),
+ (
+ "http://user:[email protected]/",
+ "http://user:[email protected]/",
+ ),
+ ] {
+ let entries = HashMap::from([(
+ cache_key("plugin", "^1.0.0", "1.0.0", &locked, before),
+ CacheEntry {
+ info: UpdateInfo {
+ update_available: false,
+ latest: None,
+ },
+ at: Instant::now(),
+ },
+ )]);
+ let key = cache_key("plugin", "^1.0.0", "1.0.0", &locked, after);
+ assert!(
+ !entries.contains_key(&key),
+ "proxy change reused a cached failure"
+ );
+ }
+ }
+
+ #[test]
+ fn normalized_equivalent_proxies_reuse_update_cache() {
+ let locked = HashMap::new();
+ let before =
+ crate::config::proxy::normalize_proxy_url(" HTTP://proxy.example:80 ").unwrap();
+ let after = crate::config::proxy::normalize_proxy_url("http://proxy.example/").unwrap();
+ let entries = HashMap::from([(
+ cache_key("plugin", "^1.0.0", "1.0.0", &locked, &before),
+ CacheEntry {
+ info: UpdateInfo {
+ update_available: true,
+ latest: Some("2.0.0".into()),
+ },
+ at: Instant::now(),
+ },
+ )]);
+ let key = cache_key("plugin", "^1.0.0", "1.0.0", &locked, &after);
+ let entry = entries
+ .get(&key)
+ .expect("unchanged proxy lost its cached result");
+ assert!(entry.info.update_available);
+ assert_eq!(entry.info.latest.as_deref(), Some("2.0.0"));
+ assert_eq!(
+ cached_latest(&entries, "plugin", &after).as_deref(),
+ Some("2.0.0")
+ );
+ }
+
+ #[test]
+ fn late_old_proxy_result_does_not_replace_current_update_or_install_target() {
+ let locked = HashMap::new();
+ let proxy = "http://127.0.0.1:7897/";
+ let key = cache_key("plugin", "^1.0.0", "1.0.0", &locked, proxy);
+ let now = Instant::now();
+ let mut entries = HashMap::from([(
+ key.clone(),
+ CacheEntry {
+ info: UpdateInfo {
+ update_available: true,
+ latest: Some("2.0.0".into()),
+ },
+ at: now,
+ },
+ )]);
+ entries.insert(
+ cache_key("plugin", "^1.0.0", "1.0.0", &locked, ""),
+ CacheEntry {
+ info: UpdateInfo {
+ update_available: false,
+ latest: Some("1.0.0".into()),
+ },
+ at: now + Duration::from_millis(1),
+ },
+ );
+ let entry = entries.get(&key).unwrap();
+ assert!(entry.info.update_available);
+ assert_eq!(entry.info.latest.as_deref(), Some("2.0.0"));
+ assert_eq!(
+ cached_latest(&entries, "plugin", proxy).as_deref(),
+ Some("2.0.0")
+ );
+ }
+
+ #[test]
+ fn cached_install_target_ignores_another_proxy() {
+ let entries = HashMap::from([(
+ cache_key("plugin", "^1.0.0", "1.0.0", &HashMap::new(), ""),
+ CacheEntry {
+ info: UpdateInfo {
+ update_available: true,
+ latest: Some("2.0.0".into()),
+ },
+ at: Instant::now(),
+ },
+ )]);
+ assert_eq!(
+ cached_latest(&entries, "plugin", "http://127.0.0.1:7897/"),
+ None
+ );
+ assert_eq!(cached_latest(&entries, "different-plugin", ""), None);
+ }
+
#[test]
fn hex_value_accepts_only_ascii_hex_nibbles() {
for byte in 0..=u8::MAX {
@@ -1036,11 +1160,11 @@ importers:\n .:\n dependencies:\n stable-plugin:\n specifier: gi
std::fs::write(&path, format!("{prefix}1111111\n")).unwrap();
let before = read_locked_commits(&dir, &specs);
- let before_key = cache_key("plugin", "github:owner/repo", "1.0.0", &before);
+ let before_key = cache_key("plugin", "github:owner/repo", "1.0.0", &before, "");
std::fs::write(&path, format!("{prefix}2222222\n")).unwrap();
let after = read_locked_commits(&dir, &specs);
- let after_key = cache_key("plugin", "github:owner/repo", "1.0.0", &after);
+ let after_key = cache_key("plugin", "github:owner/repo", "1.0.0", &after, "");
assert_eq!(before.get("plugin"), Some(&"1111111".to_string()));
assert_eq!(after.get("plugin"), Some(&"2222222".to_string()));
@@ -1113,23 +1237,23 @@ importers:\n .:\n dependencies:\n plugin:\n specifier: github:ow
#[test]
fn cache_key_changes_with_version() {
let locked = HashMap::new();
- let a = cache_key("p", "spec", "1.0.0", &locked);
- let b = cache_key("p", "spec", "1.0.1", &locked);
+ let a = cache_key("p", "spec", "1.0.0", &locked, "");
+ let b = cache_key("p", "spec", "1.0.1", &locked, "");
assert_ne!(a, b);
- let c = cache_key("p", "spec2", "1.0.0", &locked);
+ let c = cache_key("p", "spec2", "1.0.0", &locked, "");
assert_ne!(a, c);
}
#[test]
fn cache_key_changes_with_locked_git_commit() {
let missing = HashMap::new();
- let missing_key = cache_key("p", "github:Owner/Repo", "1.0.0", &missing);
+ let missing_key = cache_key("p", "github:Owner/Repo", "1.0.0", &missing, "");
let mut locked = HashMap::from([("p".into(), "aaaaaaa".into())]);
- let a = cache_key("p", "github:Owner/Repo", "1.0.0", &locked);
+ let a = cache_key("p", "github:Owner/Repo", "1.0.0", &locked, "");
let cache = HashMap::from([(a.clone(), true)]);
locked.insert("p".into(), "bbbbbbb".into());
- let b = cache_key("p", "github:Owner/Repo", "1.0.0", &locked);
+ let b = cache_key("p", "github:Owner/Repo", "1.0.0", &locked, "");
assert_ne!(missing_key, a);
assert_ne!(a, b);
@@ -1139,10 +1263,10 @@ importers:\n .:\n dependencies:\n plugin:\n specifier: github:ow
#[test]
fn registry_cache_key_ignores_unrelated_git_commits() {
let mut locked = HashMap::from([("other-plugin".into(), "aaaaaaa".into())]);
- let a = cache_key("p", "^1.0.0", "1.0.0", &locked);
+ let a = cache_key("p", "^1.0.0", "1.0.0", &locked, "");
locked.insert("other-plugin".into(), "bbbbbbb".into());
- let b = cache_key("p", "^1.0.0", "1.0.0", &locked);
+ let b = cache_key("p", "^1.0.0", "1.0.0", &locked, "");
assert_eq!(a, b);
}
diff --git a/src-tauri/src/service/update/about.rs b/src-tauri/src/service/update/about.rs
index 1ed93dd4..7f3f1f56 100644
--- a/src-tauri/src/service/update/about.rs
+++ b/src-tauri/src/service/update/about.rs
@@ -17,8 +17,8 @@ pub struct DesktopAboutInfo {
/// 关于信息:版本来自编译常量,发布时间每次实时查询最新 Release(不缓存),
/// 查询失败则留空、不影响展示。
-pub async fn about() -> DesktopAboutInfo {
- let published_at = fetch_releases_meta()
+pub async fn about(app_handle: &tauri::AppHandle) -> DesktopAboutInfo {
+ let published_at = fetch_releases_meta(app_handle)
.await
.ok()
.and_then(|releases| releases.first().map(|(_, p)| p.clone()))
diff --git a/src-tauri/src/service/update/install.rs b/src-tauri/src/service/update/install.rs
index eeea6a7a..d3731d74 100644
--- a/src-tauri/src/service/update/install.rs
+++ b/src-tauri/src/service/update/install.rs
@@ -53,7 +53,7 @@ pub struct DesktopUpdateInfo {
/// 检查是否有新版本可用(含安装包是否已下载)
pub async fn check(app_handle: &AppHandle) -> Result<Option<DesktopUpdateInfo>, String> {
- match fetch_latest_release().await? {
+ match fetch_latest_release(app_handle).await? {
None => Ok(None),
Some(r) => {
let path = installer_path(app_handle, &r.asset_name)?;
@@ -132,8 +132,8 @@ async fn download_from_source(
/// 安装包下载客户端:长超时(安装包可达数百 MB,慢镜像需要更久),
/// 与检查更新用的 5s `http_client()` 区分。
-fn download_client() -> Result<reqwest::Client, String> {
- reqwest::Client::builder()
+fn download_client(app_handle: &AppHandle) -> Result<reqwest::Client, String> {
+ config::proxy::http_client_builder(app_handle)?
.user_agent("deepseek-harness-desktop")
.timeout(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
.connect_timeout(Duration::from_secs(15))
@@ -217,7 +217,7 @@ fn verify_installer_sha256(path: &std::path::Path, expected: &str) -> Result<(),
/// 宁可失败,防止第三方镜像投毒未被察觉;官方 GitHub 直连在摘要缺失时仍可
/// 按旧行为下载(兼容早期未填摘要的发布),下载后若有摘要则强制校验。
pub async fn download(app_handle: &AppHandle) -> Result<DesktopUpdateInfo, String> {
- let release = fetch_latest_release()
+ let release = fetch_latest_release(app_handle)
.await?
.ok_or_else(|| "UPDATE_NONE".to_string())?;
let path = installer_path(app_handle, &release.asset_name)?;
@@ -232,7 +232,7 @@ pub async fn download(app_handle: &AppHandle) -> Result<DesktopUpdateInfo, Strin
.ok_or_else(|| "UPDATE_NONE".to_string());
}
- let client = download_client()?;
+ let client = download_client(app_handle)?;
// 官方直连 → (可选)ghfast.top 镜像兜底。安装包无 SHA-256 元数据,切换源时
// 丢弃上一源的部分字节从头下载,避免混用两个源的字节流。
diff --git a/src-tauri/src/service/update/meta.rs b/src-tauri/src/service/update/meta.rs
index b8021fcb..4536db83 100644
--- a/src-tauri/src/service/update/meta.rs
+++ b/src-tauri/src/service/update/meta.rs
@@ -28,8 +28,8 @@ pub(super) struct LatestRelease {
}
/// 构造带统一 UA 的 HTTP 客户端(并发小、超时短)。
-fn http_client() -> Result<reqwest::Client, String> {
- reqwest::Client::builder()
+fn http_client(app_handle: &tauri::AppHandle) -> Result<reqwest::Client, String> {
+ crate::config::proxy::http_client_builder(app_handle)?
.user_agent("deepseek-harness-desktop")
.timeout(Duration::from_secs(5))
.build()
@@ -69,8 +69,8 @@ fn parse_atom_entries(body: &str) -> Vec<(String, String)> {
}
/// 拉取 releases.atom 并解析全部 release(不走 api.github.com,不受未认证限流约束)。
-pub(super) async fn fetch_releases_meta() -> Result<Vec<(String, String)>, String> {
- let body = http_client()?
+pub(super) async fn fetch_releases_meta(app_handle: &tauri::AppHandle) -> Result<Vec<(String, String)>, String> {
+ let body = http_client(app_handle)?
.get(format!("{REPO_URL}/releases.atom"))
.send()
.await
@@ -134,8 +134,8 @@ fn parse_digest_from_expanded_assets(body: &str, expected_name: &str) -> Option<
/// expanded_assets 会列出所有平台的安装包,各带一个 `sha256:`,不能取「页面里
/// 第一个能解析出摘要的资产」,否则会把别的资产的摘要套到当前平台安装包上,
/// 导致完整性校验必然失败(见 `fetch_latest_release`)。
-async fn fetch_expanded_assets(tag: &str) -> Result<(Vec<String>, String), String> {
- let body = http_client()?
+async fn fetch_expanded_assets(app_handle: &tauri::AppHandle, tag: &str) -> Result<(Vec<String>, String), String> {
+ let body = http_client(app_handle)?
.get(format!("{REPO_URL}/releases/expanded_assets/{tag}"))
.send()
.await
@@ -158,9 +158,9 @@ async fn fetch_expanded_assets(tag: &str) -> Result<(Vec<String>, String), Strin
///
/// 返回 `Ok(Some(LatestRelease))` 表示有更新且匹配到当前平台安装包;
/// `Ok(None)` 表示无更新(或未匹配到资产)。网络失败返回 Err。
-pub(super) async fn fetch_latest_release() -> Result<Option<LatestRelease>, String> {
+pub(super) async fn fetch_latest_release(app_handle: &tauri::AppHandle) -> Result<Option<LatestRelease>, String> {
let current = current_version();
- for (tag, published_at) in fetch_releases_meta().await? {
+ for (tag, published_at) in fetch_releases_meta(app_handle).await? {
let version = tag.trim_start_matches('v').to_string();
let Some(parsed) = parse_version(&version) else {
log::debug!("UPDATE_SKIP: {tag} 非法 semver(手动测试 release?),跳过");
@@ -174,7 +174,7 @@ pub(super) async fn fetch_latest_release() -> Result<Option<LatestRelease>, Stri
log::debug!("UPDATE_SKIP: {tag} 不高于当前版本 {current}");
continue;
}
- if let Some(release) = fetch_release_assets(&tag, &version, &published_at).await? {
+ if let Some(release) = fetch_release_assets(app_handle, &tag, &version, &published_at).await? {
return Ok(Some(release));
}
}
@@ -190,12 +190,13 @@ pub(super) async fn fetch_latest_release() -> Result<Option<LatestRelease>, Stri
///
/// 返回 `None` 表示该 release 无匹配当前平台的安装包(调用方继续看更旧的正式版)。
async fn fetch_release_assets(
+ app_handle: &tauri::AppHandle,
tag: &str,
version: &str,
published_at: &str,
) -> Result<Option<LatestRelease>, String> {
// 一次拉取 expanded_assets 页面,得到资产名列表与原始 HTML(避免两次请求)
- let (names, body) = fetch_expanded_assets(tag).await?;
+ let (names, body) = fetch_expanded_assets(app_handle, tag).await?;
let Some(asset_name) = pick_asset(&names) else {
log::debug!("UPDATE_SKIP: {tag} 无当前平台安装包,继续看更旧的正式版");
return Ok(None);
diff --git a/src-tauri/src/service/workflow/install.rs b/src-tauri/src/service/workflow/install.rs
index 9169a333..817a4e0f 100644
--- a/src-tauri/src/service/workflow/install.rs
+++ b/src-tauri/src/service/workflow/install.rs
@@ -56,8 +56,8 @@ pub async fn install(
if dsh_latest.is_none() && dsh_missing {
for attempt in 0..3 {
let metadata = match config::recommended_dsh_version(app_handle) {
- Some(version) => download::fetch_dsh_pkg_version(&version).await,
- None => download::fetch_latest_dsh_pkg_info().await,
+ Some(version) => download::fetch_dsh_pkg_version(app_handle, &version).await,
+ None => download::fetch_latest_dsh_pkg_info(app_handle).await,
};
match metadata {
Ok(info) => {
@@ -172,7 +172,7 @@ pub async fn install(
log::info!("Download completed, file size: {} bytes", buffer.len());
let expected_digest = match kind {
download::InstallKind::Node => {
- download::fetch_node_sha256(task.get_download_url()?.as_str()).await?
+ download::fetch_node_sha256(app_handle, task.get_download_url()?.as_str()).await?
}
download::InstallKind::Dsh => {
// 元数据已在安装任务开始前获取,确保下载地址与摘要来自同一 release。
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index cb052838..e3b5ebba 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -5,9 +5,9 @@ use crate::config;
use std::collections::HashMap;
use std::ffi::OsString;
use std::fs;
-use std::path::Path;
#[cfg(not(windows))]
use std::io::Read;
+use std::path::Path;
#[cfg(not(windows))]
use std::process::{Command, Stdio};
use std::sync::atomic::Ordering;
@@ -46,13 +46,30 @@ type SpawnResult = Result<
/// 复用配置端口;到期仍未释放才按“真占用”逐级递增。
const PORT_RELEASE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);
-fn build_harness_args(dsh_binary: &Path, profile: &str, port: u16, heap_mb: Option<u32>) -> Vec<OsString> {
- let mut args = Vec::with_capacity(7);
+/// 组装启动 Harness 的参数:`[--max-old-space-size] <dsh> --profile <档案>
+/// [--patch <补丁层>] --port <端口> --no-open`。
+///
+/// `--patch` 必须排在子命令参数之前(`dsh` 的选项收集器把第一个非选项参数之后
+/// 的内容整段透传给内层应用,排在后面的 `--patch` 会被判为 `unknown option`)。
+fn build_harness_args(
+ dsh_binary: &Path,
+ profile: &str,
+ patch: Option<&Path>,
+ port: u16,
+ heap_mb: Option<u32>,
+) -> Vec<OsString> {
+ let mut args = Vec::with_capacity(9);
args.extend(super::heap::heap_option_arg(heap_mb));
args.extend([
dsh_binary.as_os_str().to_os_string(),
OsString::from("--profile"),
OsString::from(profile),
+ ]);
+ if let Some(patch) = patch {
+ args.push(OsString::from("--patch"));
+ args.push(patch.as_os_str().to_os_string());
+ }
+ args.extend([
OsString::from("--port"),
OsString::from(port.to_string()),
OsString::from("--no-open"),
@@ -639,6 +656,15 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
// Windows 分支的「早期退出重试」兜底。
reset_active_profile_root(&app_handle);
+ // 本地插件热重载:把已挂载的本地路径插件源码目录折算成桌面端独占的补丁层,
+ // 随启动以 `--patch` 注入核心 HMR(本地插件没有版本号可升级,改源码即时生效)。
+ // 该层只在本次进程有效,每次启动都要按当前安装状态重算;没有本地插件时不传
+ // `--patch`(指向不存在的文件会让核心在读取补丁层时直接失败)。
+ let hmr_patch = crate::service::plugin::local_plugin_hmr_sync(&app_handle);
+ if let Some(path) = hmr_patch.as_deref() {
+ log::info!("Injecting local plugin HMR layer: {}", path.display());
+ }
+
// Windows 打包版是 GUI 进程(没有控制台)。直接以 CREATE_NO_WINDOW 启动
// node 会让 dsh 派生的子进程各自新建可见控制台窗口(频繁闪烁 cmd 黑窗),
// 因此 Windows 上改用“隐藏控制台”方式启动,见 win_spawn 模块。
@@ -664,7 +690,13 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
GetExitCodeProcess, WaitForSingleObject, INFINITE,
};
- let args = build_harness_args(&dsh_binary_path, active_profile.as_str(), setting.port, heap_mb);
+ let args = build_harness_args(
+ &dsh_binary_path,
+ active_profile.as_str(),
+ hmr_patch.as_deref(),
+ setting.port,
+ heap_mb,
+ );
// 只负责 spawn 并返回管道/PID/句柄:探测与重试期间不登记、不挂
// 监视线程——只有最终采用的那个进程才登记,否则旧监视线程会通过
@@ -767,7 +799,13 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
{
use std::os::unix::process::CommandExt;
let mut cmd = Command::new(&node_binary_path);
- cmd.args(build_harness_args(&dsh_binary_path, active_profile.as_str(), setting.port, heap_mb));
+ cmd.args(build_harness_args(
+ &dsh_binary_path,
+ active_profile.as_str(),
+ hmr_patch.as_deref(),
+ setting.port,
+ heap_mb,
+ ));
cmd.envs(&envs)
.current_dir(&core_dir)
// 核心修正:提供一个空的 stdin 防止 setRawMode 报错
@@ -803,7 +841,13 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
);
reset_active_profile_root(&app_handle);
cmd = Command::new(&node_binary_path);
- cmd.args(build_harness_args(&dsh_binary_path, active_profile.as_str(), setting.port, heap_mb));
+ cmd.args(build_harness_args(
+ &dsh_binary_path,
+ active_profile.as_str(),
+ hmr_patch.as_deref(),
+ setting.port,
+ heap_mb,
+ ));
cmd.envs(&envs)
.current_dir(&core_dir)
.stdin(Stdio::null())
@@ -888,6 +932,55 @@ mod tests {
assert!(error.starts_with("PORT_EXHAUSTED:"));
}
+ fn text_args(args: &[OsString]) -> Vec<String> {
+ args.iter()
+ .map(|arg| arg.to_string_lossy().into_owned())
+ .collect()
+ }
+
+ /// `--patch` 必须排在子命令参数之前:`dsh` 的选项收集器在遇到第一个非选项
+ /// 参数(内层应用名)之后会把剩余参数整段透传,排在其后的 `--patch` 会被内层
+ /// 应用判为未知选项并立刻退出(实测)。
+ #[test]
+ fn patch_layer_argument_precedes_the_port_flags() {
+ let patch = Path::new("D:/app-data/cordis.hmr.patch.yml");
+ let args = build_harness_args(
+ Path::new("D:/core/lib/bin.js"),
+ "tauri",
+ Some(patch),
+ 3080,
+ None,
+ );
+ assert_eq!(
+ text_args(&args),
+ vec![
+ "D:/core/lib/bin.js".to_string(),
+ "--profile".to_string(),
+ "tauri".to_string(),
+ "--patch".to_string(),
+ "D:/app-data/cordis.hmr.patch.yml".to_string(),
+ "--port".to_string(),
+ "3080".to_string(),
+ "--no-open".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn heap_option_stays_ahead_of_the_script_path() {
+ let args = build_harness_args(
+ Path::new("D:/core/lib/bin.js"),
+ "tauri",
+ None,
+ 3081,
+ Some(4096),
+ );
+ let text = text_args(&args);
+ assert_eq!(text[0], "--max-old-space-size=4096");
+ assert_eq!(text[1], "D:/core/lib/bin.js");
+ assert!(!text.contains(&"--patch".to_string()));
+ }
+
/// 模拟“上个会话残留进程刚被杀、端口仍在释放”的场景:先占用端口,随后在
/// 另一线程释放。验证 `wait_for_port_release` 在端口回落后立即返回,而不是
/// 等到完整等待窗口——这正是避免端口永久顶高(dev 热更新下 3081→3082→…)
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 944dde75..b72ae10d 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Deepseek Harness Desktop",
- "version": "0.21.2",
+ "version": "0.22.0",
"identifier": "dsh-tauri",
"build": {
"beforeDevCommand": "pnpm dev",
diff --git a/src/config/query-keys.ts b/src/config/query-keys.ts
index 4fbb76e9..321982d8 100644
--- a/src/config/query-keys.ts
+++ b/src/config/query-keys.ts
@@ -17,6 +17,8 @@ export const queryKeys = {
cores: ['cores'] as const,
/** 已安装 dsh 插件列表(面板 / 配置对话框角标 / 导航栏共用) */
plugins: ['plugins'] as const,
+ /** 本地插件热重载开关与监听状态(插件面板) */
+ localPluginHmr: ['local_plugin_hmr'] as const,
/** dsh 档案列表 */
profiles: ['profiles'] as const,
/** 当前档案的备份快照列表 */
diff --git a/src/hooks/use-omit-ignore-cursor-events.ts b/src/hooks/use-omit-ignore-cursor-events.ts
index d3340083..8a8651e7 100644
--- a/src/hooks/use-omit-ignore-cursor-events.ts
+++ b/src/hooks/use-omit-ignore-cursor-events.ts
@@ -2,7 +2,7 @@ import type { RefObject } from 'react'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
import { getCurrentWindow } from '@tauri-apps/api/window'
-import { useEffect } from 'react'
+import { useEffect, useRef } from 'react'
interface DeviceMousePosition {
x: number
@@ -36,8 +36,32 @@ interface RustPetStatus {
*
* issue #394 的「延后到首个 device-mouse-move 再应用」仍然保留:避免挂载时
* 立刻与事件循环竞争,但真正防止 panic 的是上面的两层可见性保护。
+ *
+ * # 拖拽期间必须可交互(`dragging`)
+ *
+ * 命中判定只看「光标是否在命中区内」:拖拽跟手有弹簧延迟,快速甩动时窗口会落在指针
+ * 后面,光标一出框就会被判成穿透 —— 那次拖拽的松手会落到桌面(别的窗口)上,指针
+ * 事件也随之中断。因此拖拽期间固定 `ignore = false`,并在 `dragging` 翻回 false 时
+ * 立刻按最近一次光标样本重算,不用等下一个样本。
+ *
+ * # 命中判定跟着窗口自己动
+ *
+ * 宠物甩出时是窗口在动、光标不动(`device-mouse-move` 只在光标真的移动时才来),
+ * 因此窗口 `Moved` 之后也要按最近光标样本重算一次:宠物飞离指针就切回穿透,飞到
+ * 指针下方就恢复可交互,点击落在「宠物现在的位置」上。
*/
-export function useOmitIgnoreCursorEvents(elementRef: RefObject<HTMLElement | null>): void {
+export function useOmitIgnoreCursorEvents(elementRef: RefObject<HTMLElement | null>, dragging = false): void {
+ /** 拖拽态最新值:主 effect 只挂一次,事件回调与重算入口都按 ref 读取。 */
+ const draggingRef = useRef(dragging)
+ draggingRef.current = dragging
+ /** 主 effect 暴露的「按当前状态重算并应用穿透」入口,供拖拽开始/结束时立即生效。 */
+ const refreshRef = useRef<() => void>(() => {})
+
+ // 拖拽开始/结束立即应用:拖拽中固定可交互,结束后按最近光标重算。
+ useEffect(() => {
+ refreshRef.current()
+ }, [dragging])
+
useEffect(() => {
const appWindow = getCurrentWindow()
let disposed = false
@@ -51,6 +75,8 @@ export function useOmitIgnoreCursorEvents(elementRef: RefObject<HTMLElement | nu
let ignoreRequestRevision = 0
let windowPosition: { x: number, y: number } | undefined
let geometryRevision = 0
+ // 最近一次光标样本:拖拽结束时按它立即重算穿透态,不用等下一个样本。
+ let lastCursor: DeviceMousePosition | undefined
let unlistenMouseMove: (() => void) | undefined
let unlistenMoved: (() => void) | undefined
let unlistenResized: (() => void) | undefined
@@ -109,6 +135,22 @@ export function useOmitIgnoreCursorEvents(elementRef: RefObject<HTMLElement | nu
return x >= left && x <= left + width && y >= top && y <= top + height
}
+ // 按「当前」状态应用穿透:拖拽期间恒为可交互,其余情况按最近光标命中判定
+ // (见函数上方的拖拽说明)。挂载时没有光标样本则什么都不做,保持 #394 的
+ // 「延后到首个 device-mouse-move 再应用」。
+ function refreshFromState(): void {
+ if (draggingRef.current) {
+ setIgnoreCursorEvents(false)
+ return
+ }
+ if (lastCursor === undefined)
+ return
+ const inElement = isCursorInElement(lastCursor.x, lastCursor.y)
+ if (inElement !== undefined)
+ setIgnoreCursorEvents(!inElement)
+ }
+ refreshRef.current = refreshFromState
+
// 初始整窗穿透延后应用(见上方 #394 说明):这里只启动鼠标流、可见性与窗口
// 几何追踪,首个 device-mouse-move 事件到来后再按命中区决定穿透态。
void invoke('start_pet_mouse_stream').catch(() => {})
@@ -119,7 +161,10 @@ export function useOmitIgnoreCursorEvents(elementRef: RefObject<HTMLElement | nu
}).catch(() => {})
const movedPromise = appWindow.onMoved(() => {
- void refreshWindowPosition()
+ // 命中判定同时依赖「窗口在哪」与「最近光标样本」,而甩出时是窗口在动、光标不动
+ // (`device-mouse-move` 不会再来):位置读回来后立刻按最近样本重算,宠物飞离指针
+ // 就切回穿透、飞到指针下方就恢复可交互,点击落在「宠物现在在哪」上。
+ void refreshWindowPosition().then(refreshFromState).catch(() => {})
})
const resizedPromise = appWindow.onResized(() => {
void refreshWindowPosition()
@@ -130,13 +175,12 @@ export function useOmitIgnoreCursorEvents(elementRef: RefObject<HTMLElement | nu
handleVisibility(payload.enabled !== false && payload.visible !== false)
})
const mouseMovePromise = listen<DeviceMousePosition>('device-mouse-move', ({ payload }) => {
+ lastCursor = payload
// 挂载时的位置刷新是异步的,首个事件到来时可能还没拿到窗口坐标;补拉一次,
// 让初始命中判定尽快给出明确结果,由此把初始穿透态一次应用到位。
if (windowPosition === undefined)
void refreshWindowPosition()
- const inElement = isCursorInElement(payload.x, payload.y)
- if (inElement !== undefined)
- setIgnoreCursorEvents(!inElement)
+ refreshFromState()
})
void Promise.all([movedPromise, resizedPromise, mouseMovePromise, statusPromise]).then(([moved, resized, mouseMove, status]) => {
@@ -156,6 +200,7 @@ export function useOmitIgnoreCursorEvents(elementRef: RefObject<HTMLElement | nu
return () => {
disposed = true
+ refreshRef.current = () => {}
geometryRevision++
unlistenMoved?.()
unlistenResized?.()
diff --git a/src/hooks/use-window-draggable.test.ts b/src/hooks/use-window-draggable.test.ts
index aa81da68..28fd2330 100644
--- a/src/hooks/use-window-draggable.test.ts
+++ b/src/hooks/use-window-draggable.test.ts
@@ -1,14 +1,14 @@
// @vitest-environment jsdom
+import type { PointerEvent as ReactPointerEvent } from 'react'
+import type { UseWindowDraggableOptions, UseWindowDraggableResult } from './use-window-draggable'
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useWindowDraggable } from './use-window-draggable'
-interface MovedEvent { payload: { x: number, y: number } }
-type MovedHandler = (event: MovedEvent) => void
-
/**
- * 本文件把 `useListen` 替换成同步登记表:拖拽收尾依赖后端设备流事件,而真实
- * `listen` 要走 Tauri IPC,在 jsdom 里无法投递。
+ * 本文件把 `useListen` 替换成同步登记表:跟手的坐标来源(`device-mouse-move`)与
+ * 松手信号(`device-mouse-button`)都来自后端设备流,而真实 `listen` 要走 Tauri
+ * IPC,在 jsdom 里无法投递。
*/
const deviceListeners = vi.hoisted(() => new Map<string, (event: { payload: unknown }) => void>())
@@ -18,130 +18,399 @@ vi.mock('@/hooks/use-listen', () => ({
},
}))
-const windowMocks = vi.hoisted(() => ({
- startDragging: vi.fn<() => Promise<void>>(),
- onMoved: vi.fn<(handler: MovedHandler) => Promise<() => void>>(),
-}))
+const invokeMock = vi.hoisted(() => vi.fn<(command: string, args?: Record<string, number>) => Promise<void>>())
-vi.mock('@tauri-apps/api/window', () => ({
- getCurrentWindow: () => windowMocks,
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: invokeMock,
}))
-const invokeMock = vi.hoisted(() => vi.fn<(command: string) => Promise<void>>())
+/** 只 mock 窗口位置读写:跟手就是每帧把窗口绝对定位到弹簧算出的位置。 */
+const windowMock = vi.hoisted(() => ({
+ outerPosition: vi.fn<() => Promise<{ x: number, y: number }>>(),
+ setPosition: vi.fn<(position: { x: number, y: number }) => Promise<void>>(),
+}))
-vi.mock('@tauri-apps/api/core', () => ({
- invoke: invokeMock,
+vi.mock('@tauri-apps/api/window', () => ({
+ getCurrentWindow: () => windowMock,
+ PhysicalPosition: class PhysicalPosition {
+ x: number
+ y: number
+ constructor(x: number, y: number) {
+ this.x = x
+ this.y = y
+ }
+ },
}))
-/** 与 `use-window-draggable.ts` 的 `DRAG_SESSION_TIMEOUT` 一致(模块私有,不导出)。 */
+/** 与 `use-window-draggable.ts` 的常量一致(模块私有,不导出)。 */
+const DRAG_START_THRESHOLD = 5
+const DRAG_DIRECTION_IDLE_TIMEOUT = 350
const DRAG_SESSION_TIMEOUT = 1500
+/** jsdom 的 `devicePixelRatio` 恒为 1(门槛按 `5 * SCALE` 换算)。 */
+const SCALE = globalThis.devicePixelRatio || 1
+/** 按下时的窗口左上角(物理像素)。 */
+const BASE = { x: 1000, y: 500 }
+/** 按下时的光标位置(物理像素,与窗口同一坐标系)。 */
+const CURSOR = { x: 500, y: 300 }
+
+/**
+ * 默认不夹取:本文件验证弹簧与手势本身,夹取边界另有专门用例。真实宿主必须给
+ * `clampPosition`(宠物靠它保证贴边合法,见 `use-pet-window-clamp.ts`)。
+ */
+const noClamp = (position: { x: number, y: number }): { x: number, y: number } => position
+
+function useDraggable(options: Partial<UseWindowDraggableOptions> = {}): UseWindowDraggableResult {
+ return useWindowDraggable({ clampPosition: noClamp, ...options })
+}
-let movedHandlers: MovedHandler[] = []
+/** 造一个命中箱指针事件:hook 只用按钮/指针 id/主指针标记。 */
+function pointerEvent(options: { button?: number, isPrimary?: boolean, pointerId?: number } = {}): ReactPointerEvent<HTMLDivElement> {
+ return {
+ button: options.button ?? 0,
+ pointerId: options.pointerId ?? 1,
+ isPrimary: options.isPrimary ?? true,
+ } as unknown as ReactPointerEvent<HTMLDivElement>
+}
+
+/** 让在途的 promise 回调(如按下的 `outerPosition()`)落地。 */
+async function settlePromises(): Promise<void> {
+ await act(async () => {
+ for (let index = 0; index < 4; index += 1)
+ await Promise.resolve()
+ })
+}
+
+async function press(draggable: UseWindowDraggableResult, options?: { button?: number, pointerId?: number }): Promise<void> {
+ act(() => {
+ draggable.onPointerDown(pointerEvent(options))
+ })
+ // 按下要异步读窗口原位:不等它落地,滚动门槛时手势拿不到基准点。
+ await settlePromises()
+}
-/** 按下左键:webview 收到 pointerdown 后才会开启拖拽会话。 */
-function pressPointer(): void {
- const event = new Event('pointerdown', { bubbles: true })
- Object.defineProperty(event, 'button', { value: 0 })
+function release(draggable: UseWindowDraggableResult, options?: { button?: number, pointerId?: number }): void {
act(() => {
- window.dispatchEvent(event)
+ draggable.onPointerUp(pointerEvent(options))
})
}
-/** 原生拖拽期间窗口移动(Windows 上拖拽会话吞掉按钮事件,只剩 Moved)。 */
-function moveWindow(x: number, y: number): void {
+/** 后端设备流上报的光标位置(虚拟屏幕物理像素)。 */
+function emitCursor(x: number, y: number): void {
+ const handler = deviceListeners.get('device-mouse-move')
+ if (handler === undefined)
+ throw new Error('未订阅 device-mouse-move:跟手拿不到坐标')
act(() => {
- for (const handler of [...movedHandlers])
- handler({ payload: { x, y } })
+ handler({ payload: { x, y } })
})
}
-/** 后端设备流的左键状态事件。 */
-function pressMouse(pressed: boolean): void {
+/** 后端设备流上报的左键状态。 */
+function emitButton(pressed: boolean): void {
const handler = deviceListeners.get('device-mouse-button')
if (handler === undefined)
- throw new Error('未订阅 device-mouse-button:松开判断退回 1.5s 停歇兜底(Bug 复现)')
+ throw new Error('未订阅 device-mouse-button:丢 pointerup 时无法收尾')
act(() => {
handler({ payload: { pressed } })
})
}
-/** 按下并拖过 `DRAG_START_THRESHOLD`,进入拖拽态。 */
-function startDraggingSession(): void {
- pressPointer()
- moveWindow(100, 100)
- moveWindow(120, 100)
+/**
+ * 推进 rAF 帧(每帧 16ms)。注意 `useRafFn` 在 `resume()` 后的首帧 delta 为 0,
+ * 弹簧积分从第 2 帧才开始,所以「一步积分」需要至少 2 帧。
+ */
+function frames(count = 1): void {
+ act(() => {
+ vi.advanceTimersByTime(16 * count)
+ })
+}
+
+/** 按下并移动 `dx/dy` 物理像素,越过门槛进入拖拽态(真实场景按下前就有光标样本)。 */
+async function startDrag(draggable: UseWindowDraggableResult, dx = 12, dy = 0): Promise<void> {
+ emitCursor(CURSOR.x, CURSOR.y)
+ await press(draggable)
+ emitCursor(CURSOR.x + dx, CURSOR.y + dy)
+}
+
+/** 最近一次下发的窗口位置。 */
+function lastPosition(): { x: number, y: number } {
+ const last = windowMock.setPosition.mock.calls.at(-1)
+ if (last === undefined)
+ throw new Error('setPosition 从未被调用')
+ return last[0]
}
beforeEach(() => {
vi.useFakeTimers()
- movedHandlers = []
deviceListeners.clear()
- windowMocks.startDragging.mockResolvedValue(undefined)
- windowMocks.onMoved.mockImplementation(async (handler) => {
- movedHandlers.push(handler)
- return () => {
- movedHandlers = movedHandlers.filter(item => item !== handler)
- }
- })
+ invokeMock.mockReset()
invokeMock.mockResolvedValue(undefined)
+ windowMock.outerPosition.mockReset()
+ windowMock.outerPosition.mockResolvedValue({ x: BASE.x, y: BASE.y })
+ windowMock.setPosition.mockReset()
+ windowMock.setPosition.mockResolvedValue(undefined)
})
afterEach(() => {
cleanup()
vi.useRealTimers()
+ vi.unstubAllGlobals()
vi.restoreAllMocks()
})
describe('useWindowDraggable', () => {
- it('松开左键时立即结束拖拽,不等 Moved 停歇超时', () => {
- const { result } = renderHook(() => useWindowDraggable())
+ it('门槛内不移动窗口:位移不足时按单击处理', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ emitCursor(CURSOR.x, CURSOR.y)
+ await press(result.current)
+ emitCursor(CURSOR.x + DRAG_START_THRESHOLD * SCALE - 1, CURSOR.y)
+ frames(4)
+
+ expect(result.current.dragging).toBe(false)
+ expect(windowMock.setPosition).not.toHaveBeenCalled()
+
+ release(result.current)
+ expect(invokeMock).not.toHaveBeenCalledWith('move_pet_window', expect.anything())
+ expect(invokeMock).not.toHaveBeenCalledWith('persist_pet_window_position')
+ })
- startDraggingSession()
+ it('越门槛后进入拖拽态,窗口从原位起步缓慢追光标(第 1 帧只走一小段)', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ await startDrag(result.current, 40)
expect(result.current.dragging).toBe(true)
+
+ frames(2)
+ const first = lastPosition()
+ expect(first.x).toBeGreaterThan(BASE.x)
+ // 40px 的目标,第 1 帧只走几个像素 —— 这就是上游 playground 的「缓慢跟手」。
+ expect(first.x).toBeLessThan(BASE.x + 40)
+ expect(first.y).toBe(BASE.y)
+ })
+
+ it('窗口最终收敛到光标处:不会滞留在指针后面', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ await startDrag(result.current, 40, 15)
+ frames(60)
+
+ expect(lastPosition()).toEqual({ x: BASE.x + 40, y: BASE.y + 15 })
+ })
+
+ it('弹簧追的是绝对位置:门槛前丢掉的位移会在越过门槛后补上', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ emitCursor(CURSOR.x, CURSOR.y)
+ await press(result.current)
+ // 门槛内先走 4px,再越门槛 —— 目标始终按「按下位置」算,不按增量累加。
+ emitCursor(CURSOR.x + 4, CURSOR.y)
+ expect(result.current.dragging).toBe(false)
+ emitCursor(CURSOR.x + 8, CURSOR.y)
+ expect(result.current.dragging).toBe(true)
+
+ frames(60)
+ expect(lastPosition()).toEqual({ x: BASE.x + 8, y: BASE.y })
+ })
+
+ it('手势门槛按 devicePixelRatio 换算成物理像素', async () => {
+ vi.stubGlobal('devicePixelRatio', 2)
+ const { result } = renderHook(() => useDraggable())
+
+ emitCursor(CURSOR.x, CURSOR.y)
+ await press(result.current)
+ // 缩放 2 倍时门槛是 10 物理像素。
+ emitCursor(CURSOR.x + 8, CURSOR.y)
+ expect(result.current.dragging).toBe(false)
+
+ emitCursor(CURSOR.x + 12, CURSOR.y)
+ expect(result.current.dragging).toBe(true)
+ })
+
+ it('方向按相邻样本的水平位移判定,拖拽停顿时归零', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ await startDrag(result.current, 12)
+ // 越过门槛的那一帧没有上一个样本,方向先不判定(与上游轨迹语义一致)。
+ expect(result.current.direction).toBeUndefined()
+
+ emitCursor(CURSOR.x + 16, CURSOR.y)
expect(result.current.direction).toBe('right')
- pressMouse(false)
+ emitCursor(CURSOR.x + 12, CURSOR.y)
+ expect(result.current.direction).toBe('left')
+
+ act(() => {
+ vi.advanceTimersByTime(DRAG_DIRECTION_IDLE_TIMEOUT)
+ })
+ expect(result.current.direction).toBeUndefined()
+ expect(result.current.dragging).toBe(true)
+
+ emitCursor(CURSOR.x + 20, CURSOR.y)
+ expect(result.current.direction).toBe('right')
+ })
+
+ it('pointerup 收尾,且只认同一个 pointerId', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ await startDrag(result.current, 12)
+ expect(result.current.dragging).toBe(true)
+
+ release(result.current, { pointerId: 2 })
+ expect(result.current.dragging).toBe(true)
+
+ release(result.current, { pointerId: 1 })
+ expect(result.current.dragging).toBe(false)
+ expect(result.current.direction).toBeUndefined()
+ })
+
+ it('收尾时只持久化位置:整窗夹取会把贴边宠物推开', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ await startDrag(result.current, 12)
+ release(result.current)
+
+ expect(invokeMock).toHaveBeenCalledWith('persist_pet_window_position')
+ // 不再走整窗夹取:宠物四周的透明留白会被算进去,贴边松手时把宠物推开一段。
+ expect(invokeMock).not.toHaveBeenCalledWith('move_pet_window', expect.anything())
+ })
+
+ it('每帧按 clampPosition 夹取:顶到边界就停住,越界位移不会攒起来', async () => {
+ const bound = { x: BASE.x + 30, y: BASE.y + 10 }
+ const clampPosition = vi.fn((position: { x: number, y: number }): { x: number, y: number } => ({
+ x: Math.min(position.x, bound.x),
+ y: Math.min(position.y, bound.y),
+ }))
+ const { result } = renderHook(() => useDraggable({ clampPosition }))
+
+ // 光标一路推到边界外 200px:弹簧被夹在边界上,而不是先跟到光标再回弹。
+ await startDrag(result.current, 200, 60)
+ frames(60)
+
+ expect(clampPosition).toHaveBeenCalled()
+ expect(lastPosition()).toEqual(bound)
+ expect(windowMock.setPosition.mock.calls.every(([position]) => position.x <= bound.x && position.y <= bound.y)).toBe(true)
+
+ // 松手后停在边缘:收尾不再有第二次「夹回屏幕内」的移动。
+ release(result.current)
+ expect(lastPosition()).toEqual(bound)
+ })
+
+ it('每个手势只报一次松开:pointerup 与设备流重复上报不会重复结算', async () => {
+ const onRelease = vi.fn()
+ const { result } = renderHook(() => useDraggable({ onRelease }))
+
+ // 单击(没过门槛)同样要报:抓取时物理层已进入「按住」,松手必须清掉。
+ await press(result.current)
+ release(result.current)
+ expect(onRelease).toHaveBeenCalledTimes(1)
+
+ // 同一次松开的设备流上报随后到达:不该再结算一遍。
+ emitButton(false)
+ expect(onRelease).toHaveBeenCalledTimes(1)
+
+ // 下一次手势照常只报一次(这次由设备流收尾)。
+ await startDrag(result.current, 12)
+ emitButton(false)
+ expect(onRelease).toHaveBeenCalledTimes(2)
+ })
+
+ it('后端设备流报告松开时立即收尾,不等停歇阈值', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ await startDrag(result.current, 12)
+ expect(result.current.dragging).toBe(true)
+
+ emitButton(false)
expect(result.current.dragging).toBe(false)
expect(result.current.direction).toBeUndefined()
})
- it('左键仍按下时不结束拖拽', () => {
- const { result } = renderHook(() => useWindowDraggable())
+ it('设备流确认仍按住时,停歇超时不结束拖拽(按住不动再拖不会被误杀)', async () => {
+ const { result } = renderHook(() => useDraggable())
- startDraggingSession()
- pressMouse(true)
+ await startDrag(result.current, 12)
+ emitButton(true)
+ act(() => {
+ vi.advanceTimersByTime(DRAG_SESSION_TIMEOUT)
+ })
expect(result.current.dragging).toBe(true)
+
+ emitCursor(CURSOR.x + 60, CURSOR.y)
+ frames(60)
+ expect(lastPosition()).toEqual({ x: BASE.x + 60, y: BASE.y })
})
- it('设备流失联时仍由 Moved 停歇兜底结束', () => {
- const { result } = renderHook(() => useWindowDraggable())
+ it('设备流失联时仍由停歇阈值兜底收尾(丢 pointerup 不会永久粘住)', async () => {
+ const { result } = renderHook(() => useDraggable())
+
+ await startDrag(result.current, 12)
+ expect(result.current.dragging).toBe(true)
- startDraggingSession()
act(() => {
vi.advanceTimersByTime(DRAG_SESSION_TIMEOUT)
})
expect(result.current.dragging).toBe(false)
+ expect(invokeMock).toHaveBeenCalledWith('persist_pet_window_position')
})
- it('松开后再次按下并移动可重新进入拖拽', () => {
- const { result } = renderHook(() => useWindowDraggable())
+ it('只认左键:右键按下不开启会话、不移动窗口', () => {
+ const { result } = renderHook(() => useDraggable())
+
+ act(() => {
+ result.current.onPointerDown(pointerEvent({ button: 2 }))
+ })
+ emitCursor(CURSOR.x + 40, CURSOR.y)
+ frames(4)
- startDraggingSession()
- pressMouse(false)
expect(result.current.dragging).toBe(false)
+ expect(windowMock.setPosition).not.toHaveBeenCalled()
+ })
- pressPointer()
- moveWindow(200, 200)
- moveWindow(230, 200)
+ it('命中箱左键按下即通知抓取(不等手势门槛);右键/非主指针/重复按下都不通知', () => {
+ const onGrab = vi.fn()
+ const { result } = renderHook(() => useDraggable({ onGrab }))
- expect(result.current.dragging).toBe(true)
+ act(() => {
+ result.current.onPointerDown(pointerEvent({ button: 2 }))
+ result.current.onPointerDown(pointerEvent({ isPrimary: false }))
+ })
+ expect(onGrab).not.toHaveBeenCalled()
+
+ // 门槛前就通知:抓取刹车要发生在按下的那一刻,跟手才等 5px。
+ act(() => {
+ result.current.onPointerDown(pointerEvent())
+ })
+ expect(onGrab).toHaveBeenCalledTimes(1)
+
+ // 手势进行中的第二次按下不再重复通知宿主。
+ act(() => {
+ result.current.onPointerDown(pointerEvent({ pointerId: 2 }))
+ })
+ expect(onGrab).toHaveBeenCalledTimes(1)
+
+ release(result.current)
+ act(() => {
+ result.current.onPointerDown(pointerEvent({ pointerId: 3 }))
+ })
+ expect(onGrab).toHaveBeenCalledTimes(2)
+ })
+
+ it('读不到窗口原位时放弃这次手势,窗口保持不动', async () => {
+ windowMock.outerPosition.mockRejectedValue(new Error('window unavailable'))
+ const { result } = renderHook(() => useDraggable())
+
+ await startDrag(result.current, 40)
+ frames(4)
+
+ expect(result.current.dragging).toBe(false)
+ expect(windowMock.setPosition).not.toHaveBeenCalled()
})
it('挂载时拉起后端鼠标设备流', () => {
- renderHook(() => useWindowDraggable())
+ renderHook(() => useDraggable())
expect(invokeMock).toHaveBeenCalledWith('start_pet_mouse_stream')
})
diff --git a/src/hooks/use-window-draggable.ts b/src/hooks/use-window-draggable.ts
index 521d4dc1..0f496d60 100644
--- a/src/hooks/use-window-draggable.ts
+++ b/src/hooks/use-window-draggable.ts
@@ -1,12 +1,22 @@
-import { useEventListener, useTimeoutFn } from '@reause/core'
+import type { PointerEvent as ReactPointerEvent } from 'react'
+import { useRafFn, useTimeoutFn } from '@reause/core'
import { invoke } from '@tauri-apps/api/core'
-import { getCurrentWindow } from '@tauri-apps/api/window'
+import { getCurrentWindow, PhysicalPosition } from '@tauri-apps/api/window'
import { useEffect, useRef, useState } from 'react'
import { useListen } from '@/hooks/use-listen'
/** 拖拽的水平方向。 */
type DragDirection = 'left' | 'right'
+/**
+ * `device-mouse-move` 事件载荷:全局光标位置(虚拟屏幕物理像素,
+ * 与窗口 `outerPosition()` 同一坐标系)。对应后端 `MouseCursorPos`。
+ */
+interface DeviceMousePosition {
+ x: number
+ y: number
+}
+
/**
* `device-mouse-button` 事件载荷:全局鼠标左键是否按下。
* 与后端 `src-tauri/src/desktop/pet_mouse.rs` 的 `MouseButtonState` 一一对应。
@@ -16,178 +26,359 @@ interface MouseButtonState {
}
export interface UseWindowDraggableResult {
- /** 原生拖拽会话进行中(按下后位移超过阈值才算,结束/超时后为 false)。 */
+ /** 拖拽会话进行中(越过手势门槛才算,松手或兜底收尾后为 false)。 */
dragging: boolean
/** 当前拖拽方向;未拖拽、位移不足或拖拽停顿时为 undefined。 */
direction: DragDirection | undefined
+ /** 命中箱 pointerdown(`<Pet>` 的 `onHitboxPointerDown`):开启手势并记录按下位置。 */
+ onPointerDown: (event: ReactPointerEvent<HTMLDivElement>) => void
+ /** 命中箱 pointerup(`<Pet>` 的 `onHitboxPointerUp`):指针侧即时收尾。 */
+ onPointerUp: (event: ReactPointerEvent<HTMLDivElement>) => void
+}
+
+/** 拖拽钩子的夹取与回调。 */
+export interface UseWindowDraggableOptions {
+ /**
+ * 每帧把弹簧算出的窗口位置夹进可见区域(物理像素,与窗口 `outerPosition()` 同一
+ * 坐标系),返回夹取后的位置。
+ *
+ * 等价于上游 playground `usePetDrag` 的 `getBounds`:上游在弹簧循环里就把盒子夹进
+ * 舞台,因此「按在边界不放」不会在弹簧里攒下越界位移、松手后突然弹出去。这里同样在
+ * 积分之后、下发 `setPosition` 之前调用。边界必须与飞行共用(桌宠用
+ * `src/pet/hooks/use-pet-window-clamp.ts`,边界取自 `bodyBounds` 的宠物本体/脚底),
+ * 否则贴边松手会被飞行的越界修正弹回来。
+ */
+ clampPosition: (position: { x: number, y: number }) => { x: number, y: number }
+ /**
+ * 命中箱上按下左键(真正「抓住宠物」)时触发,早于读窗口位置的异步调用;右键、
+ * 非主指针、以及已有手势进行中的按下都不会触发。
+ *
+ * 宿主用它做「抓取刹车」这类动作:后端 `device-mouse-button` 是**全屏**左键流,
+ * 分不清「抓住宠物」与「在别处点击」(见 `src/pet/hooks/use-pet-physics.ts`)。
+ */
+ onGrab?: () => void
+ /**
+ * 手势结束时触发一次(含没有位移的单击、以及设备流/兜底计时结束的那一次),宿主用它
+ * 结算甩动并清掉「按住」状态。
+ *
+ * 后端 `device-mouse-button` 只是 OS 侧的兜底信号,可能丢事件;命中箱的 `pointerup`
+ * 更早也更可靠。两条路都汇到这里,同一个手势重复结束只报一次(见
+ * `src/pet/hooks/use-pet-physics.ts` 的 `onRelease`)。
+ */
+ onRelease?: () => void
}
-/** 判定方向的水平位移阈值(物理像素),滤除拖拽起始时刻的抖动/初始跳变。 */
-const DRAG_DIRECTION_THRESHOLD = 3
/**
- * 判定「真正开始拖拽」的累计位移阈值(物理像素,逻辑像素 5 的同量级):按下后累计
- * 位移未达阈值不算拖拽 —— 单击不进入拖拽、不播放拖动动画(点击回应由 `<Pet>` 内置
- * 的双击判定驱动)。位移按 X/Y 双轴累计(Math.hypot):垂直拖拽 X 位移可能很小,
- * 不能因此把拖拽误判为点击。
+ * 手势门槛(CSS px):与上游 playground `usePetDrag` 的 `Math.hypot(dx, dy) < 5` 一致,
+ * 门槛内按单击处理(组件的挤压反馈)。换算成物理像素时乘 `devicePixelRatio`。
*/
-const DRAG_START_THRESHOLD = 8
+const DRAG_START_THRESHOLD = 5
+/** 方向判定阈值(CSS px):与上游 `Math.abs(x - last.x) >= 3` 一致。 */
+const DRAG_DIRECTION_THRESHOLD = 3
/**
- * 方向停摆阈值:超过此时长没有新的窗口 Moved 事件,方向归零(宠物回到 idle/会话动画)。
- * 拖拽中短暂停顿(重新抓握)后继续移动会重新产生方向。
+ * 弹簧参数(上游 playground 同值):刚度 K=200 /s²、阻尼 C=30 /s。
+ * 阻尼比 C / (2√K) ≈ 1.06,略过阻尼 —— 这是「缓慢跟手、不振荡」的来源。
*/
+const FOLLOW_STIFFNESS = 200
+const FOLLOW_DAMPING = 30
+/** 单帧积分上限与子步上限:与上游一致,大帧切成 1/120 子步,显式弹簧不会发散。 */
+const MAX_FRAME_DELTA = 0.05
+const MAX_SUBSTEP = 1 / 120
+/** 方向停摆阈值:超过此时长没有新的光标样本,方向归零(宠物回到 idle/会话动画)。 */
const DRAG_DIRECTION_IDLE_TIMEOUT = 350
-/**
- * 拖拽会话硬结束阈值:超过此时长没有 Moved 事件即认为原生拖拽已结束。
- * Windows 拖拽结束时 webview 收不到 pointerup(按钮事件被系统模态循环吞掉),
- * 只能靠 Moved 事件流停歇判结束;该阈值同时允许拖拽中较长的停顿后继续。
- */
+/** 会话兜底阈值:超过此时长没有新的光标样本,且左键状态未知/已松开时收尾拖拽。 */
const DRAG_SESSION_TIMEOUT = 1500
+/** 一次拖拽手势的状态(位置/速度与窗口、光标流同一坐标系:虚拟屏幕物理像素)。 */
+interface Gesture {
+ /** 指针 id:只有同一根指针的 pointerup 才结束会话。 */
+ pointerId: number
+ /** 手势原点:按下瞬间的光标位置;按下时设备流还没有样本则顺延到首个样本。 */
+ anchor: { x: number, y: number } | undefined
+ /** 手势原点处的窗口左上角;读窗口位置是异步的,读到之前不进入跟手。 */
+ base: { x: number, y: number } | undefined
+ /** 弹簧积分出的窗口位置。 */
+ x: number
+ y: number
+ /** 弹簧速度。 */
+ vx: number
+ vy: number
+ /** 是否越过手势门槛(门槛前窗口不动,位移由门槛后的弹簧按原点补齐)。 */
+ engaged: boolean
+ /** 方向判定用的上一个样本(上游拿轨迹末段比较)。 */
+ lastSample: { x: number, y: number } | undefined
+}
+
/**
- * Tauri 窗口拖拽(桌宠窗口在用):用原生窗口拖动移动窗口,并借用窗口 `Moved` 事件
- * 采样位移方向(原生拖拽期间 webview 收不到 pointermove),供上层切换 moving-left/right。
+ * 桌宠窗口拖拽(桌宠窗口在用):按上游 playground 的「弹簧跟手」移动窗口。
+ *
+ * # 手感来自上游 playground 的 `usePetDrag`
+ *
+ * 上游官方用例拖动时是「缓慢跟手」:5px 手势门槛、指针为弹簧目标、K=200/C=30 的
+ * 显式弹簧每帧积分,位置在门槛之后才更新。这里逐条照搬(含 `Math.hypot` 门槛、
+ * 3px 方向判定、单帧 0.05s 与 1/120 子步上限),只把「舞台里的 DOM 盒子」换成
+ * 「显示器里的窗口」:盒子用 `style.left/top` 定位,窗口用 `setPosition` 定位。
*
- * # 为什么监听 window 而不是命中箱
+ * # 指针位置为什么取后端 `device-mouse-move`,而不是 DOM `pointermove`
*
- * 桌宠窗口平时按命中箱矩形对光标穿透(`useOmitIgnoreCursorEvents`),能到达页面的
- * 指针事件本来就只发生在命中箱附近,因此 `window` 级监听与命中箱监听效果等价;而
- * reause 的 `useEventListener` 在渲染期解析 ref 目标,命中箱由 `<Pet>` 在提交阶段
- * 才挂上,用 ref 当目标会漏绑定。
+ * 上游的盒子在固定视口里,`clientX/clientY` 与盒子位置互不影响;桌宠的「盒子」
+ * 就是窗口本身,`clientX` 是相对窗口的坐标 —— 窗口一移动,同一个光标位置的
+ * `clientX` 就反向变化,形成「窗口动过 → 增量变小 → 窗口不再动」的反馈:既抖,
+ * 又会把窗口留在指针后面追不上。后端设备流给的是**与窗口位置同一坐标系**的全局
+ * 物理像素,与窗口自身的移动无关,因此弹簧目标可以写成绝对量
+ * `base + (cursor - anchor)`,窗口必然收敛到指针处(静止时零偏移)。
+ * 附带好处:命中箱一旦被判定为「指针已离开」而切成穿透态,DOM `pointermove`
+ * 会断流,全局流不受影响(`useOmitIgnoreCursorEvents` 的命中判定用的也是它)。
*
- * # 生命周期不依赖 `startDragging()` 的 Promise 时机
+ * # 结束时刻:设备流为主,指针事件为快路径
*
- * tao(Windows)用 `PostMessageW(WM_NCLBUTTONDOWN, HTCAPTION)` 发起原生拖拽后立即
- * 返回,Promise 瞬间 resolve —— 它不代表拖拽结束,不能在 await 后清理拖拽态;
- * 因此「拖拽进行中」= 按下后 Moved 事件持续到来,由两级停歇判断收尾(见上方两个
- * 超时常量),pointerup / pointercancel 仅作兜底。
+ * 后端设备流用 `device-mouse-button` 上报 OS 侧左键状态,松开即收尾;命中箱的
+ * `pointerup` 是更快的同源信号(同一 `pointerId` 才认)。**不认 `pointercancel`**:
+ * 拖拽中命中区可能被判成「指针已离开」而切成穿透态,webview 会因此取消指针会话,
+ * 若把它当作结束,窗口就会定格在半路(正是要修的「滞留在后面」)。收尾兜底是
+ * `DRAG_SESSION_TIMEOUT`,且设备流确认仍按住时只重新计时,不误杀「按住不动再拖」。
*
- * # 松开时刻来自后端设备流
+ * # 跟手期间的夹取
*
- * 原生拖拽跑在系统模态循环里、按钮事件被它吞掉:webview 在整个拖拽期间(含松手
- * 瞬间)都收不到 pointerup / pointercancel,只靠 Moved 停歇兜底会让拖拽动画在松手
- * 后多挂 `DRAG_SESSION_TIMEOUT`(1.5s),比网页版(指针事件即时生效)慢半拍。
- * 后端全局鼠标流用 `device-mouse-button` 上报 OS 侧看到的左键状态,松开即收尾,
- * 停歇阈值退化为纯粹的「事件流失联」兜底(也覆盖拖拽时鼠标静止不动的停顿)。
+ * 每帧夹一次(`clampPosition`,上游 `getBounds` 的等价物):位置一旦贴到可见区域边界
+ * 就不再越界累积,光标继续往外推也只是让弹簧顶在边界上,松手时宠物正好停在边缘 ——
+ * 「左右上边缘松开就被弹开」的另一半原因(跟手期间窗口跑到飞行边界之外,松手后飞行
+ * 积分把越界位置一次性修正回来)由此消除。
+ *
+ * # 收尾写回
+ *
+ * 跟手期间每帧直接 `setPosition`(与飞行同一套做法,绝对定位不会累积漂移);
+ * 结束时只调 `persist_pet_window_position` 把当前位置落盘,**不再**走
+ * `move_pet_window(0, 0)`:后者夹的是整个窗口,而宠物只是窗口底部居中的一块,四周
+ * 是透明留白(`PET_WINDOW_PAD_X` / 窗口最小宽度),贴边松手的瞬间会把宠物从边缘推开
+ * 一段(100% 大小时左侧约 100 物理像素,即「没办法在边缘放置宠物」)。
+ * 位置合法性由前端每帧的 `clampPosition` 保证,后端不必再夹一遍。
+ *
+ * # 抓取回调(`onGrab`)
+ *
+ * 命中箱上的左键按下同时是「抓住宠物」的语义信号,宿主靠它给甩出中的宠物刹车
+ * (见 `src/pet/hooks/use-pet-physics.ts`)。回调落在门槛之前:刹车要在按下的那一刻
+ * 发生,而跟手本身要等 5px 门槛;也因此在「按下不动」的单击里同样会触发。
+ *
+ * # 松开回调(`onRelease`)
+ *
+ * 每个手势(含没有位移的单击)结束时通知一次,物理层靠它结算甩动并清掉「按住」状态
+ * (见 `src/pet/hooks/use-pet-physics.ts` 的 `onRelease`)。不只依赖后端设备流的原因:
+ * 设备流可能丢事件,一旦丢了,物理层会一直以为按钮还按着,把很久以后一次无关点击当成
+ * 甩出;命中箱 `pointerup` 更早也更可靠,于是两条路都汇进同一个幂等结算。手势对象在
+ * `endDrag()` 里已被清空,因此「设备流松手 + `pointerup`」只会报一次。
*/
-export function useWindowDraggable(): UseWindowDraggableResult {
- const activeRef = useRef(false)
- const engagedRef = useRef(false)
- const originRef = useRef<{ x: number, y: number } | undefined>(undefined)
- const moveXRef = useRef<number | undefined>(undefined)
+export function useWindowDraggable(options: UseWindowDraggableOptions): UseWindowDraggableResult {
+ // 回调走 ref:拖拽期间每帧重渲染,闭包里的旧回调会把信号落到过期实例上。
+ const onGrabRef = useRef(options.onGrab)
+ onGrabRef.current = options.onGrab
+ // 松开同样走 ref:拖拽期间每帧重渲染,闭包里的旧回调会把信号落到过期实例上。
+ const onReleaseRef = useRef(options.onRelease)
+ onReleaseRef.current = options.onRelease
+ // 夹取同样走 ref:拖拽期间每帧重渲染,闭包可能抓到过期的 `pet.geometry` 快照。
+ const clampRef = useRef(options.clampPosition)
+ clampRef.current = options.clampPosition
+ const gestureRef = useRef<Gesture | null>(null)
+ /** 后端设备流最近一次上报的光标位置。 */
+ const cursorRef = useRef<{ x: number, y: number } | undefined>(undefined)
+ /**
+ * 后端设备流最近一次上报的左键状态。`true` = 确认仍按下(拖拽中长时间静止不算结束);
+ * `undefined` = 本次会话没有收到过上报(设备流失联,停歇兜底按「未知」收尾)。
+ * 不在 pointerdown 里重置:按下与设备流上报没有固定先后,清掉新会话的 `true` 会让
+ * 「按住不动再拖」被停歇阈值误杀;改为在会话结束时重置。
+ */
+ const pressedRef = useRef<boolean | undefined>(undefined)
+ /** useRafFn 每渲染返回新对象,弹簧循环统一走 ref,避免闭包抓到旧的 pause/resume。 */
+ const rafRef = useRef<{ pause: () => void, resume: () => void } | null>(null)
+ /** 最近一次已下发的取整位置:位置没变就不重复发 IPC(按住不动时每帧一次没有意义)。 */
+ const appliedRef = useRef<{ x: number, y: number } | undefined>(undefined)
const [dragging, setDragging] = useState(false)
const [direction, setDirection] = useState<DragDirection | undefined>(undefined)
// reause 的 `useTimeoutFn` 缺省在挂载时就开始计时,这里必须 `immediate: false`:
- // 只有窗口 Moved 事件才重新 `start()`(等价于「重置计时」)。回调始终读取最新闭包,
- // 且只操作 ref 与 setState,因此不需要额外的 clearTimeout 记账。
+ // 只有拖拽中的事件才重新 `start()`(等价于「重置计时」)。
const { start: armDirectionTimer, stop: stopDirectionTimer } = useTimeoutFn(
parkDirection,
DRAG_DIRECTION_IDLE_TIMEOUT,
{ immediate: false },
)
const { start: armSessionTimer, stop: stopSessionTimer } = useTimeoutFn(
- endDrag,
+ handleSessionTimeout,
DRAG_SESSION_TIMEOUT,
{ immediate: false },
)
- /** 暂停移动:方向与位移基准归零,但拖拽会话保持存活。 */
+ // 弹簧积分循环:与上游 playground 的 `useRafFn` 回调逐行对应(目标取绝对位置,
+ // 因此门槛前丢掉的位移会在门槛后一次性补上,而不是像增量累加那样永久丢失)。
+ const raf = useRafFn(({ delta }) => {
+ const gesture = gestureRef.current
+ const cursor = cursorRef.current
+ if (gesture === null || !gesture.engaged || gesture.anchor === undefined || gesture.base === undefined || cursor === undefined) {
+ rafRef.current?.pause()
+ return
+ }
+ const targetX = gesture.base.x + (cursor.x - gesture.anchor.x)
+ const targetY = gesture.base.y + (cursor.y - gesture.anchor.y)
+ let remaining = Math.min(MAX_FRAME_DELTA, Math.max(0, delta / 1000))
+ // resume 后的首帧 delta 为 0(时间戳起点),空帧不产生位移也不需要下发 IPC。
+ if (remaining <= 0)
+ return
+ while (remaining > 0) {
+ const dt = Math.min(remaining, MAX_SUBSTEP)
+ gesture.vx += ((targetX - gesture.x) * FOLLOW_STIFFNESS - gesture.vx * FOLLOW_DAMPING) * dt
+ gesture.vy += ((targetY - gesture.y) * FOLLOW_STIFFNESS - gesture.vy * FOLLOW_DAMPING) * dt
+ gesture.x += gesture.vx * dt
+ gesture.y += gesture.vy * dt
+ remaining -= dt
+ }
+ // 先夹取再取整(见 `clampPosition`):把弹簧状态本身限制在可见区域内,
+ // 越界位移不会攒起来在松手后弹出去(上游同样在弹簧循环里夹盒子)。
+ const clamped = clampRef.current({ x: gesture.x, y: gesture.y })
+ gesture.x = clamped.x
+ gesture.y = clamped.y
+ // 窗口位置取整:亚像素位置在 Windows 上会被系统四舍五入,抖动比丢精度更显眼。
+ const nextX = Math.round(gesture.x)
+ const nextY = Math.round(gesture.y)
+ if (appliedRef.current?.x === nextX && appliedRef.current.y === nextY)
+ return
+ appliedRef.current = { x: nextX, y: nextY }
+ void getCurrentWindow()
+ .setPosition(new PhysicalPosition(nextX, nextY))
+ .catch(() => {})
+ }, { immediate: false })
+ rafRef.current = raf
+
+ /** 暂停移动:方向归零(宠物回到 idle/会话动画),但拖拽会话保持存活。 */
function parkDirection(): void {
- moveXRef.current = undefined
setDirection(undefined)
}
+ /** 拖拽会话兜底:光标样本停歇超过 `DRAG_SESSION_TIMEOUT` 时触发(见 hook 文档)。 */
+ function handleSessionTimeout(): void {
+ if (gestureRef.current !== null && pressedRef.current === true) {
+ armSessionTimer()
+ return
+ }
+ endDrag()
+ }
+
function endDrag(): void {
- activeRef.current = false
- engagedRef.current = false
- originRef.current = undefined
- moveXRef.current = undefined
+ const gesture = gestureRef.current
+ gestureRef.current = null
+ pressedRef.current = undefined
+ appliedRef.current = undefined
stopDirectionTimer()
stopSessionTimer()
+ rafRef.current?.pause()
setDragging(false)
setDirection(undefined)
+ if (gesture !== null) {
+ // 每个手势只报一次松开:物理层据此结算甩动并清掉「按住」状态(见 hook 文档)。
+ onReleaseRef.current?.()
+ }
+ if (gesture?.engaged === true) {
+ // 只落盘、不夹取:位置已由每帧的 `clampPosition` 保证在可见区域内,整窗夹取
+ // 反而会把贴边松手的宠物推开一段(见 hook 文档「收尾写回」)。
+ void invoke('persist_pet_window_position').catch(() => {})
+ }
}
- function handlePointerDown(event: PointerEvent): void {
- if (event.button !== 0)
+ function handlePointerDown(event: ReactPointerEvent<HTMLDivElement>): void {
+ if (event.button !== 0 || event.isPrimary === false || gestureRef.current !== null)
return
+ // 先通知宿主「抓住宠物」:这一步早于手势门槛与异步读窗口位置。
+ onGrabRef.current?.()
+ const latest = cursorRef.current
+ const gesture: Gesture = {
+ pointerId: event.pointerId,
+ anchor: latest === undefined ? undefined : { x: latest.x, y: latest.y },
+ base: undefined,
+ x: 0,
+ y: 0,
+ vx: 0,
+ vy: 0,
+ engaged: false,
+ lastSample: undefined,
+ }
+ gestureRef.current = gesture
+ // 按下即开始兜底计时:设备流与指针事件同时中断时也能收尾。
+ armSessionTimer()
// 不调用 preventDefault:取消 pointerdown 会抑制兼容鼠标事件,文本选择/触屏滚动
- // 已由样式(select-none / touch-none)防护。先清理残留状态(快速连续拖拽时上一轮
- // 的空闲计时可能还没到)。
- endDrag()
- activeRef.current = true
- // 参考 dsh-pet:按下仅记录会话,不立即进入拖拽动画(单击不播放拖动浮动),
- // 位移超过 DRAG_START_THRESHOLD 后才把 dragging 置 true。
- void getCurrentWindow().startDragging().catch(() => {})
+ // 已由样式(select-none / touch-none)防护。
+ void getCurrentWindow().outerPosition().then((position) => {
+ if (gestureRef.current !== gesture)
+ return
+ gesture.base = { x: position.x, y: position.y }
+ }).catch(() => {
+ // 读不到窗口位置就无法把光标位移映射成窗口位置:放弃这次手势(单击反馈照常)。
+ if (gestureRef.current === gesture)
+ endDrag()
+ })
}
- function handlePointerUp(): void {
+ function handlePointerUp(event: ReactPointerEvent<HTMLDivElement>): void {
+ if (event.button !== 0 || gestureRef.current?.pointerId !== event.pointerId)
+ return
endDrag()
}
- useEventListener('pointerdown', handlePointerDown)
- useEventListener('pointerup', handlePointerUp)
- useEventListener('pointercancel', handlePointerUp)
+ useListen<DeviceMousePosition>('device-mouse-move', ({ payload }) => {
+ cursorRef.current = { x: payload.x, y: payload.y }
+ const gesture = gestureRef.current
+ if (gesture === null)
+ return
+ // 事件流仍在推进:重置「会话兜底」计时。
+ armSessionTimer()
+ if (gesture.anchor === undefined) {
+ // 设备流首个样本:手势原点顺延到这里(按下时还没有样本,等价于从此刻起跟手)。
+ gesture.anchor = { x: payload.x, y: payload.y }
+ gesture.lastSample = { x: payload.x, y: payload.y }
+ return
+ }
+ const scale = globalThis.devicePixelRatio || 1
+ const dx = payload.x - gesture.anchor.x
+ const dy = payload.y - gesture.anchor.y
+ if (!gesture.engaged) {
+ // 门槛前窗口不动;越过门槛时从窗口原位起步,弹簧目标始终按原点算。
+ if (Math.hypot(dx, dy) < DRAG_START_THRESHOLD * scale || gesture.base === undefined)
+ return
+ gesture.x = gesture.base.x
+ gesture.y = gesture.base.y
+ gesture.vx = 0
+ gesture.vy = 0
+ gesture.engaged = true
+ appliedRef.current = undefined
+ setDragging(true)
+ rafRef.current?.resume()
+ }
+ const last = gesture.lastSample
+ if (last !== undefined && Math.abs(payload.x - last.x) >= DRAG_DIRECTION_THRESHOLD * scale)
+ setDirection(payload.x > last.x ? 'right' : 'left')
+ gesture.lastSample = { x: payload.x, y: payload.y }
+ armDirectionTimer()
+ })
- // 只认松开:拖拽会话由 handlePointerDown 开启,后端设备流补的是 OS 侧的结束时刻。
+ // 只认松开:拖拽会话由 onPointerDown 开启,后端设备流补的是 OS 侧的结束时刻
+ // (命中箱切成穿透态后收不到 pointerup 时,靠它保证拖拽不粘住/不半路定格)。
useListen<MouseButtonState>('device-mouse-button', ({ payload }) => {
- if (!payload.pressed)
- endDrag()
+ if (payload.pressed) {
+ pressedRef.current = true
+ return
+ }
+ pressedRef.current = false
+ endDrag()
})
- // keep:effect 拉起后端鼠标设备流(左键状态是拖拽结束的唯一可靠信号);命令幂等,
+ // keep:effect 拉起后端鼠标设备流(光标位置与左键状态都来自它);命令幂等,
// 渲染期调用会在每次重渲染重复发起 IPC。
useEffect(() => {
void invoke('start_pet_mouse_stream').catch(() => {})
}, [])
- useEffect(() => {
- let disposed = false
- let unlisten: (() => void) | undefined
- void getCurrentWindow().onMoved((event) => {
- // 只依赖共享 ref 判断拖拽态:startDragging 的 resolve 时机(平台差异)与
- // effect 重建(StrictMode)都不应影响方向采样。
- if (!activeRef.current)
- return
- // 新的位移说明拖拽仍在进行:重置两级停歇计时。
- armDirectionTimer()
- armSessionTimer()
- const { x, y } = event.payload
- const origin = originRef.current
- if (origin === undefined) {
- // 首个 Moved 事件作为位移基准:吞掉 startDragging 可能带来的初始跳变,
- // 以及暂停与恢复之间的坐标不连续。方向采样同样以它起步。
- originRef.current = { x, y }
- moveXRef.current = x
- return
- }
- if (!engagedRef.current) {
- // 未达拖拽阈值:单击/轻微抖动不算拖拽,不采样方向(基准保持不动)。
- if (Math.hypot(x - origin.x, y - origin.y) < DRAG_START_THRESHOLD)
- return
- engagedRef.current = true
- setDragging(true)
- }
- const lastX = moveXRef.current
- moveXRef.current = x
- if (lastX === undefined) {
- // 停顿(parkDirection)后恢复移动:重新建立方向采样基准。
- return
- }
- const dx = x - lastX
- if (Math.abs(dx) >= DRAG_DIRECTION_THRESHOLD)
- setDirection(dx > 0 ? 'right' : 'left')
- }).then((dispose) => {
- if (disposed)
- dispose()
- else
- unlisten = dispose
- }).catch(() => {})
- return () => {
- disposed = true
- unlisten?.()
- }
- }, [armDirectionTimer, armSessionTimer])
-
- return { dragging, direction }
+ return {
+ dragging,
+ direction,
+ onPointerDown: handlePointerDown,
+ onPointerUp: handlePointerUp,
+ }
}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 8d9e2aa0..2138adee 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -134,7 +134,7 @@
"ui.launch_on_login": "Launch app at login",
"ui.launch_on_login_hint": "Starts the desktop app after you sign in. Harness service startup is configured separately.",
"ui.close_action": "Close action",
- "ui.close_action_hint": "What happens when you close the main window. “Hide to tray” keeps the app running in the background — click the tray icon to reopen it. On macOS, while in the background it does not appear in the ⌘-Tab app switcher.",
+ "ui.close_action_hint": "Choose whether closing the main window hides the app to the tray or quits it.",
"ui.close_action_tray": "Hide to tray",
"ui.close_action_quit": "Quit app",
"ui.cli_link": "CLI Integration",
@@ -364,6 +364,14 @@
"plugins.search_network": "Registry lookup failed",
"plugins.search_unsupported": "Source not supported yet",
"plugins.search_unknown": "Check failed",
+ "plugins.search_local_missing": "Local directory is missing or has no package.json",
+ "plugins.local_dir": "Choose a local folder",
+ "plugins.hmr": "Local plugin hot reload",
+ "plugins.hmr_hint": "Watch local plugin source folders and reload on change; takes effect after the service restarts",
+ "plugins.hmr_idle": "No mounted local plugin source folder right now",
+ "plugins.hmr_save_failed": "Failed to update the local plugin hot reload setting",
+ "plugins.local_dir_failed": "Failed to open the folder picker",
+ "plugins.hmr_restart_hint": "Hot reload setting updated — restart the service to apply",
"core.title": "Harness Core",
"core.refresh": "Refresh",
"core.refreshed_toast": "Core list refreshed",
@@ -593,5 +601,12 @@
"task_manager.restart": "Restart Harness service",
"task_manager.restart_description": "This interrupts local running tasks and reconnects the Harness service.",
"task_manager.logs_failed": "Failed to read run logs. Close and reopen logs to retry.",
- "task_manager.paused": "Refresh paused"
+ "task_manager.paused": "Refresh paused",
+ "config.network": "Network",
+ "network.proxy_url": "Proxy URL",
+ "network.description": "Use a proxy for desktop downloads, update checks and plugin metadata. Leave empty to use the system or environment proxy. Saved changes apply to new requests; retry a failed download after saving.",
+ "network.formats": "Supports HTTP, HTTPS, SOCKS5 and SOCKS5H. SOCKS5H resolves destination names through the proxy. Local connections stay direct.",
+ "network.saved": "Proxy settings saved",
+ "network.invalid": "Enter a valid proxy URL without a path, query or fragment.",
+ "network.save_failed": "Could not save proxy settings"
}
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 203942ed..9c6da5a8 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -127,14 +127,14 @@
"errors.patch_layer_parse_failed": "补丁层存在 YAML 语法错误,Harness 无法解析:{{detail}}。常见原因是 `!!js` 表达式里含 `:` 或 `?` 却未加引号——请改成 `!!js \"…\"`(或块标量 `|-`)后重试;也可以点「隔离损坏的补丁文件」,把该文件改名为 `.broken-<时间戳>` 备份后先启动(修好语法后改回原名即可恢复)。",
"errors.patch_quarantine_failed": "无法隔离损坏的补丁文件(改名失败):{{detail}}。文件仍在原处,重启会再次报同样的解析错误。请先关闭占用该文件的程序(编辑器 / 同步网盘 / 杀毒软件),或手动把该文件改名为 `.broken-<时间戳>` 备份,然后重试。",
"ui.service_url": "服务地址",
- "ui.port": "端口",
+ "ui.port": "服务端口",
"ui.heap_limit": "服务内存上限",
"ui.heap_limit_auto": "自动",
"ui.zoom": "界面缩放",
"ui.launch_on_login": "开机自启动",
"ui.launch_on_login_hint": "登录系统后启动桌面应用;Harness 服务的自动运行配置与此项相互独立。",
"ui.close_action": "关闭行为",
- "ui.close_action_hint": "关闭主窗口时的行为;选择「隐藏到托盘」后应用继续在后台运行,可点击菜单栏托盘图标重新打开。macOS 上后台运行期间不会出现在 ⌘-Tab 应用切换器中。",
+ "ui.close_action_hint": "关闭主窗口时选择隐藏到托盘或退出应用。",
"ui.close_action_tray": "隐藏到托盘",
"ui.close_action_quit": "退出应用",
"ui.cli_link": "命令行集成",
@@ -142,9 +142,9 @@
"ui.cli_link_hint": "在新终端中运行 dsh --help 查看用法",
"ui.cli_link_user_dsh_preserved": "检测到你已自行安装 dsh,已保留未覆盖;终端中的 dsh 仍指向你自己的安装与配置",
"ui.current_version": "当前版本",
- "ui.dsh_version": "Harness 版本",
- "ui.node_version": "Node.js 运行时",
- "ui.platform": "平台",
+ "ui.dsh_version": "Harness",
+ "ui.node_version": "Node.js",
+ "ui.platform": "Platform",
"ui.data_dir": "数据目录",
"ui.iframe_error": "无法加载 DeepSeek Harness 界面。",
"ui.ensure_running": "请确认服务正在 {{url}} 运行。",
@@ -364,6 +364,14 @@
"plugins.search_network": "联网查询失败",
"plugins.search_unsupported": "暂不支持该来源",
"plugins.search_unknown": "检查失败",
+ "plugins.search_local_missing": "本地目录不存在或缺少 package.json",
+ "plugins.local_dir": "选择本地目录",
+ "plugins.hmr": "本地插件热重载",
+ "plugins.hmr_hint": "监听本地插件源码目录,改动后自动重载;需要重启服务才能开始监听",
+ "plugins.hmr_idle": "当前没有已挂载的本地插件源码目录",
+ "plugins.hmr_save_failed": "更新本地插件热重载设置失败",
+ "plugins.local_dir_failed": "打开目录选择器失败",
+ "plugins.hmr_restart_hint": "热重载设置已更新 — 重启服务后生效",
"core.title": "核心引擎",
"core.refresh": "刷新",
"core.refreshed_toast": "核心列表已刷新",
@@ -593,5 +601,12 @@
"task_manager.restart": "重启 Harness 服务",
"task_manager.restart_description": "这会中断本机正在运行的任务,并重新连接 Harness 服务。",
"task_manager.logs_failed": "读取运行日志失败,请重新打开日志重试。",
- "task_manager.paused": "已暂停刷新"
+ "task_manager.paused": "已暂停刷新",
+ "config.network": "网络",
+ "network.proxy_url": "代理地址",
+ "network.description": "为桌面端下载、更新检查和插件元数据请求设置代理。留空沿用系统或环境变量代理。保存后对新请求生效,下载失败时请在保存后重试。",
+ "network.formats": "支持 HTTP、HTTPS、SOCKS5 和 SOCKS5H。SOCKS5H 由代理解析目标域名,本机连接保持直连。",
+ "network.saved": "代理设置已保存",
+ "network.invalid": "请输入有效的代理地址,不要包含路径、查询参数或片段。",
+ "network.save_failed": "无法保存代理设置"
}
diff --git a/src/pet/app.tsx b/src/pet/app.tsx
index 51a032b4..f872fb75 100644
--- a/src/pet/app.tsx
+++ b/src/pet/app.tsx
@@ -13,52 +13,46 @@ import { usePetPhysics } from './hooks/use-pet-physics'
import { usePetSource } from './hooks/use-pet-source'
import { normalizeSizePercent, usePetStatus } from './hooks/use-pet-status'
import { usePetWindowSize } from './hooks/use-pet-window'
+import { usePetWindowClamp } from './hooks/use-pet-window-clamp'
import { reportPetIssue } from './utils/log'
-/**
- * 桌宠窗口的唯一组合入口。
- *
- * 三条输入各管一段,互不越界:
- * - 设置状态(`usePetStatus`)→ 选哪个宠物、多大、是否可见;
- * - 会话气泡(`useBubbleTracker`)→ 经 `pet.bubble(...)` 下发,**动作随气泡走**;
- * - 手势(`useWindowDraggable`)→ 拖动期间的方向动作。
- *
- * v0.2.0 起气泡完全由 `dsh-pet-component` 托管(叠加、原地更新、定时收起、多会话动作
- * 优先级),渲染细节(动画池解析、双视频缓冲、雪碧图、缓存、双击回应)同样如此:
- * 宿主只把 `motion` prop 留给拖动方向,会话档位随各自的气泡走。
- */
export function App() {
const petRef = useRef<PetRef>(null)
const pet = useControllablePet(petRef)
const status = usePetStatus()
-
- // issue #469:桌宠动画是常驻播放的 <video>,Chromium 会因此持有 Video Wake Lock
- // 让系统无法息屏;本窗口没有常亮的正当需求,唤醒锁一旦生效就立刻释放。
const activedPet = status?.active_pet ?? ''
const { source, error } = usePetSource(activedPet)
const hitboxRef = useRef<HTMLDivElement>(null)
- const draggable = useWindowDraggable()
+ // 甩动:松手后按窗口轨迹估速请求组件甩出,飞行积分与落地 Q 弹都在宿主(见 hook 文档)。
+ // 抓取信号来自命中箱 `pointerdown`(经拖拽 hook 的 `onGrab`):`device-mouse-button`
+ // 是全屏左键流,在桌面别处的点击不能给甩出中的宠物刹车。松开由拖拽 hook 统一上报
+ // (`onRelease`,命中箱 `pointerup` 与设备流两条路只结算一次),物理层据此估速并清状态。
+ const { onFling, onGrab, onRelease } = usePetPhysics(pet, source?.kind)
+ // 跟手期间按「宠物本体 / 脚底」把窗口夹进显示器工作区(与飞行共用边界):贴边松手
+ // 不会被整窗夹取推开,也不会跑出飞行边界而在松手瞬间被修正回来。
+ const { clampPosition, refreshWorkAreas } = usePetWindowClamp(pet, source?.kind)
+ const draggable = useWindowDraggable({ onGrab: handleGrab, onRelease, clampPosition })
+
+ /** 抓取时顺手刷新显示器工作区(插拔显示器后立刻生效),再交给物理层刹车。 */
+ function handleGrab(): void {
+ refreshWorkAreas()
+ onGrab()
+ }
const visible = status === null || (status.enabled !== false && status.visible !== false)
const width = (source?.width ?? PET_BASE_WIDTH) * normalizeSizePercent(status?.pet_size) / 100
useBubbleTracker(pet, source)
- // 甩动:松手后按窗口轨迹估速请求组件甩出,飞行积分与落地 Q 弹都在宿主(见 hook 文档)。
- const onFling = usePetPhysics(pet, source?.kind)
usePetWindowSize(width, source?.aspect ?? PET_DSH_ASPECT, visible)
- useOmitIgnoreCursorEvents(hitboxRef)
+ useOmitIgnoreCursorEvents(hitboxRef, draggable.dragging)
useEventListener('contextmenu', event => event.preventDefault())
useWakelockRelease()
- // 手势优先于会话档位:拖动期间按方向播走路动画(dsh-pet 渲染器内部强制走 drag 池,
- // 会忽略这里的方向,由组件保证);拖动结束即回落 `undefined`,交给气泡聚合出的档位。
const motion: PetRenderMotion | undefined = draggable.dragging
? (draggable.direction === undefined ? undefined : `moving-${draggable.direction}`)
: undefined
return (
- // 外层只负责铺满透明窗口并让宠物锚定底部居中;窗口内可交互面只有命中箱,
- // 其余区域由 useOmitIgnoreCursorEvents 按命中箱矩形整体穿透。
<main className={`pointer-events-none fixed inset-0 flex items-end justify-center ${visible ? '' : 'invisible'}`}>
{source && (
<Pet
@@ -74,21 +68,16 @@ export function App() {
cache={true}
hidden={!visible}
hitboxRef={hitboxRef}
+ onHitboxPointerDown={draggable.onPointerDown}
+ onHitboxPointerUp={draggable.onPointerUp}
onError={reportPetAssetError}
/>
)}
- {/* 选中了宠物但资源解析不出来(导入的宠物被删除、清单里没有该 id):必须给出
- 可见提示 —— 透明窗口里「空」与「在加载」观感相同,静默留空等于让用户以为坏了。 */}
<If cond={error !== null} then={<Hint petId={activedPet} />} />
</main>
)
}
-/**
- * 资源加载/播放失败的出口:组件内部抓取失败会静默降级为「直接播远端地址」
- * (`useCachedMediaUrl` 的 catch 只调 `onError`),而桌宠窗口的 console 要手动
- * F12 才看得见 —— 不接这个回调,「IndexedDB 一次都没写进去」就无从察觉。
- */
function reportPetAssetError(error: unknown): void {
reportPetIssue('asset', error)
}
diff --git a/src/pet/hooks/use-pet-physics.test.ts b/src/pet/hooks/use-pet-physics.test.ts
index d14dc9c7..deafe2a5 100644
--- a/src/pet/hooks/use-pet-physics.test.ts
+++ b/src/pet/hooks/use-pet-physics.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import type { PetPhysicsEvent, PetRef } from 'dsh-pet-component'
+import type { PetPhysicsControls } from './use-pet-physics'
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { usePetPhysics } from './use-pet-physics'
@@ -71,6 +72,13 @@ function pressMouse(pressed: boolean): void {
})
}
+/** 抓住宠物:命中箱上的左键按下(`useWindowDraggable({ onGrab })` 转来的信号)。 */
+function grab(controls: PetPhysicsControls): void {
+ act(() => {
+ controls.onGrab()
+ })
+}
+
/** 投喂窗口 Moved:`clock` 控制采样时刻,采样值 = 物理像素 / dpr。 */
function dragWindow(clock: { now: number }, samples: Array<{ t: number, x: number, y: number }>): void {
for (const sample of samples) {
@@ -110,11 +118,11 @@ describe('usePetPhysics', () => {
vi.restoreAllMocks()
})
- it('松开左键时按窗口轨迹估速并请求组件甩出,轨迹随下一次抓取清空', () => {
+ it('抓住宠物后松开左键,按窗口轨迹估速并请求组件甩出,轨迹随下一次抓取清空', () => {
const pet = createPet()
- renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
- pressMouse(true)
+ grab(result.current)
dragWindow(clock, [
{ t: 0, x: 1000, y: 500 },
{ t: 40, x: 1200, y: 500 },
@@ -129,17 +137,60 @@ describe('usePetPhysics', () => {
expect(velocity.vx).toBeGreaterThan(0)
expect(velocity.vy).toBeCloseTo(0, 6)
- pressMouse(true)
+ grab(result.current)
clock.now = 400
pressMouse(false)
expect(pet.fling).toHaveBeenCalledTimes(1)
})
+ it('宿主转来的命中箱松开结算一次甩动,设备流的同一次松开不再重复结算', () => {
+ const pet = createPet()
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+
+ grab(result.current)
+ dragWindow(clock, [
+ { t: 0, x: 1000, y: 500 },
+ { t: 40, x: 1200, y: 500 },
+ { t: 80, x: 1400, y: 500 },
+ { t: 120, x: 1600, y: 500 },
+ ])
+ clock.now = 121
+ act(() => {
+ result.current.onRelease()
+ })
+
+ expect(pet.fling).toHaveBeenCalledTimes(1)
+
+ // 设备流的同一次松开随后到达:`pressedRef` 已清,不再结算(也就不会用陈旧轨迹甩出去)。
+ clock.now = 130
+ pressMouse(false)
+ act(() => {
+ result.current.onRelease()
+ })
+ expect(pet.fling).toHaveBeenCalledTimes(1)
+ })
+
+ it('没有抓取时的松开是空操作:清状态不会凭空甩出宠物', () => {
+ const pet = createPet()
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+
+ dragWindow(clock, [
+ { t: 0, x: 1000, y: 500 },
+ { t: 40, x: 1600, y: 500 },
+ ])
+ act(() => {
+ result.current.onRelease()
+ })
+ pressMouse(false)
+
+ expect(pet.fling).not.toHaveBeenCalled()
+ })
+
it('窗口几乎没动(低于 500 CSS px/s)的松手不甩', () => {
const pet = createPet()
- renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
- pressMouse(true)
+ grab(result.current)
dragWindow(clock, [
{ t: 0, x: 1000, y: 500 },
{ t: 100, x: 1010, y: 500 },
@@ -155,7 +206,7 @@ describe('usePetPhysics', () => {
const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
act(() => {
- result.current(flingEvent(600, 0))
+ result.current.onFling(flingEvent(600, 0))
})
await act(async () => {})
@@ -173,12 +224,12 @@ describe('usePetPhysics', () => {
expect(Math.max(...positions.map(position => position.y))).toBeLessThanOrEqual(980)
})
- it('飞行中按下左键立刻停住窗口(抓取刹车,不等落地)', async () => {
+ it('飞行中在别处点击(全屏左键按下)不停窗口,也不会被当成甩动', async () => {
const pet = createPet()
const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
act(() => {
- result.current(flingEvent(600, 0))
+ result.current.onFling(flingEvent(600, 0))
})
await act(async () => {})
advanceFrames(2)
@@ -187,6 +238,27 @@ describe('usePetPhysics', () => {
pressMouse(true)
advanceFrames(10)
+ // 全屏左键流分不清「抓宠物」与「在别处点击」:飞行必须继续。
+ expect(mocks.window.setPosition.mock.calls.length).toBeGreaterThan(calls)
+
+ pressMouse(false)
+ expect(pet.fling).not.toHaveBeenCalled()
+ })
+
+ it('抓住宠物(命中箱按下)立刻停住飞行,不等落地', async () => {
+ const pet = createPet()
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+
+ act(() => {
+ result.current.onFling(flingEvent(600, 0))
+ })
+ await act(async () => {})
+ advanceFrames(2)
+
+ const calls = mocks.window.setPosition.mock.calls.length
+ grab(result.current)
+ advanceFrames(10)
+
expect(mocks.window.setPosition).toHaveBeenCalledTimes(calls)
})
})
diff --git a/src/pet/hooks/use-pet-physics.ts b/src/pet/hooks/use-pet-physics.ts
index ec7128ad..e01c8a0b 100644
--- a/src/pet/hooks/use-pet-physics.ts
+++ b/src/pet/hooks/use-pet-physics.ts
@@ -16,9 +16,15 @@ const TRAIL_LIMIT = 64
* 组件 0.2.3 起把甩动物理留给宿主(见组件 `docs/spec/pet-interactions.md` 的职责划分),
* 桌宠宿主的舞台就是显示器工作区、宠物本体就是窗口,于是飞行 = 每帧 `setPosition`:
*
- * - **轨迹来自窗口 `Moved`**:原生拖拽跑在系统模态循环里,webview 收不到 pointermove,
- * 窗口位移是唯一能看出「甩得多快」的信号;`device-mouse-button` 给的是 OS 侧的松开
- * 时刻(见 `use-window-draggable.ts`),两者拼出一次甩动;
+ * - **轨迹来自窗口 `Moved`**:拖拽由 `use-window-draggable.ts` 的弹簧每帧 `setPosition`
+ * 驱动,命中箱的 `pointermove` 是相对窗口的坐标、会自我反馈,因此窗口位移仍是能看出
+ * 「甩得多快」的信号;松开时刻有两条路 —— 命中箱 `pointerup`(更早、更可靠)与
+ * `device-mouse-button`(OS 侧兜底),两条都汇到 `onRelease` 且只结算一次
+ * (见 `use-window-draggable.ts`),与窗口位移一起拼出一次甩动;
+ * - **抓取只认命中箱**:`device-mouse-button` 是**全屏**左键流,在桌面别处的点击同样会
+ * 上报「按下」;拿它当抓取会让甩出中的宠物被无关点击刹车。真正的抓取信号是命中箱上的
+ * `pointerdown`(`useWindowDraggable({ onGrab })` → `onGrab`),它同时给这次甩动开
+ * 轨迹;
* - **增益只在 `onFling` 里施加**:松手时先用 `throwPower = 1` 判断「这一下要不要甩」,
* 组件回吐的 `PetPhysicsEvent` 才带着合并后的 `physics`(prop > 配置 > 默认),速度的
* `throwPower` 放大因此只能在那里做 —— 默认值 1 时与组件参考实现完全等价;
@@ -26,8 +32,9 @@ const TRAIL_LIMIT = 64
* `devicePixelRatio` 换成物理像素;Retina 上不去换算,观感速度会差一倍;
* - 单宠物窗口没有宠物间碰撞,`physics.petCollision` 与 `pet.bounce` 不适用。
*/
-export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): (event: PetPhysicsEvent) => void {
+export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): PetPhysicsControls {
const trailRef = useRef<DragSample[]>([])
+ /** 是否抓住了宠物(信号来自命中箱 `pointerdown`,见 `onGrab`):轨迹只在抓取后采样。 */
const pressedRef = useRef(false)
const flightRef = useRef<Flight | null>(null)
// 飞行代号:起飞行要 await 显示器与窗口位置,期间可能被「抓取取消」或下一次甩动顶掉。
@@ -63,7 +70,7 @@ export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): (
rafRef.current = raf
useEffect(() => {
- // keep:effect 原生拖拽期间 webview 收不到 pointermove,只能靠窗口 Moved 采轨迹
+ // keep:effect 拖拽的每帧 setPosition 同样触发 Moved,甩动轨迹以窗口位移为准
let disposed = false
let unlisten: (() => void) | undefined
@@ -91,15 +98,47 @@ export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): (
}
}, [])
+ // 只认松开:`device-mouse-button` 是全屏左键流,别处的点击也会上报按下,
+ // 因此「抓取」不能看它 —— 那会让甩出中的宠物被无关点击刹车。抓取走 `onGrab`
+ // (命中箱 `pointerdown`);松开统一走 `onRelease`,这里只是设备流这条路径。
useListen<MouseButtonState>('device-mouse-button', ({ payload }) => {
- if (payload.pressed) {
- // 抓取即落地刹车:组件自己会取消挤压动画,这里只要停下窗口飞行。
- pressedRef.current = true
- trailRef.current = []
- stopFlight()
+ if (payload.pressed)
return
- }
+ onRelease()
+ })
+
+ /** 终止飞行(含尚未起飞的请求):抓取、下一次甩出、卸载都走这里。 */
+ function stopFlight(): void {
+ flightIdRef.current += 1
+ if (flightRef.current === null)
+ return
+ flightRef.current = null
+ rafRef.current?.pause()
+ }
+
+ return { onFling, onGrab, onRelease }
+
+ /**
+ * 抓住宠物(命中箱上的左键按下):立刻刹车 + 清空轨迹。
+ *
+ * 组件自己会取消挤压动画,这里只要停下窗口飞行;轨迹从抓取这一刻重新计时,
+ * 抓取前的窗口位移不再算进这次甩动的速度。刹车发生在按下瞬间(不等拖拽门槛),
+ * 因此「接住飞过来的宠物」和「按下不动」都能让它停住。
+ */
+ function onGrab(): void {
+ pressedRef.current = true
+ trailRef.current = []
+ stopFlight()
+ }
+ /**
+ * 松开宠物:结算一次甩动,并清掉「按住」状态。
+ *
+ * 命中箱的 `pointerup`(经 `useWindowDraggable({ onRelease })`)与后端设备流的松开都
+ * 指向这里,重复的松开只生效一次。少了这条「谁先到谁结算」的路径,漏掉的松开会让
+ * `pressedRef` 一直是 true:轨迹继续采样窗口位移,很久以后一次无关点击就能把宠物甩出去。
+ */
+ function onRelease(): void {
if (!pressedRef.current)
return
pressedRef.current = false
@@ -109,18 +148,10 @@ export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): (
const release = estimateReleaseVelocity(trail, performance.now(), 1)
if (release !== null)
pet.fling(release)
- })
-
- /** 终止飞行(含尚未起飞的请求):抓取、下一次甩出、卸载都走这里。 */
- function stopFlight(): void {
- flightIdRef.current += 1
- if (flightRef.current === null)
- return
- flightRef.current = null
- rafRef.current?.pause()
}
- return (event: PetPhysicsEvent): void => {
+ /** 组件校验后的甩出请求:读出几何与屏幕工作区,把这次甩动变成一次飞行。 */
+ function onFling(event: PetPhysicsEvent): void {
const id = flightIdRef.current + 1
flightIdRef.current = id
flightRef.current = null
@@ -191,3 +222,19 @@ interface Flight {
interface MouseButtonState {
pressed: boolean
}
+
+/** 甩动控制的出口:`onFling` 接组件回吐的甩出请求,`onGrab`/`onRelease` 接命中箱上的抓取与松开。 */
+export interface PetPhysicsControls {
+ /** 组件校验后的甩出请求(接到 `<Pet onFling>`)。 */
+ onFling: (event: PetPhysicsEvent) => void
+ /**
+ * 抓住宠物:接到命中箱的 `pointerdown`(经 `useWindowDraggable({ onGrab })`,
+ * 见 `src/pet/app.tsx`)。
+ */
+ onGrab: () => void
+ /**
+ * 松开宠物:接到拖拽手势结束时的那一次通知(经 `useWindowDraggable({ onRelease })`)。
+ * 与后端 `device-mouse-button` 的松开共用同一条结算路径,重复上报只生效一次。
+ */
+ onRelease: () => void
+}
diff --git a/src/pet/hooks/use-pet-window-clamp.test.ts b/src/pet/hooks/use-pet-window-clamp.test.ts
new file mode 100644
index 00000000..f4b56a88
--- /dev/null
+++ b/src/pet/hooks/use-pet-window-clamp.test.ts
@@ -0,0 +1,154 @@
+// @vitest-environment jsdom
+import type { PetGeometry, PetRef } from 'dsh-pet-component'
+import type { PetWorkArea } from './use-pet-window-clamp'
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { clampPetWindowPosition, usePetWindowClamp } from './use-pet-window-clamp'
+
+/**
+ * 夹取边界必须与飞行共用 `bodyBounds`(宠物本体 / 脚底),而不是整个窗口:
+ * 窗口比宠物宽出一圈透明留白,按整窗夹取会让贴边松手的宠物被推开一段
+ * (「左右上边缘松开,会弹开 Pet」)。
+ */
+
+const availableMonitorsMock = vi.hoisted(() => vi.fn<() => Promise<unknown[]>>())
+
+vi.mock('@tauri-apps/api/window', () => ({
+ availableMonitors: availableMonitorsMock,
+}))
+
+/** 100% dsh 大小、底部居中的宠物:窗口 420 宽,本体 220 宽(左右各 100 透明留白)。 */
+const GEOMETRY: PetGeometry = {
+ x: 300,
+ y: 100,
+ width: 220,
+ height: 200,
+ body: { left: 400, top: 180, right: 620, bottom: 380 },
+}
+
+/** 单个显示器工作区(物理像素,scale = 1)。 */
+const MONITOR: PetWorkArea = { x: 0, y: 0, width: 1920, height: 1080 }
+/** 缩放 2 倍时的同一个工作区。 */
+const MONITOR_SCALED: PetWorkArea = { x: 0, y: 0, width: 3840, height: 2160 }
+
+function clampAt(
+ position: { x: number, y: number },
+ options: { dsh?: boolean, areas?: readonly PetWorkArea[], scale?: number } = {},
+): { x: number, y: number } {
+ return clampPetWindowPosition(position, GEOMETRY, options.dsh ?? true, options.areas ?? [MONITOR], options.scale ?? 1)
+}
+
+function fakePetRef(geometry: PetGeometry | null): PetRef {
+ return { geometry } as unknown as PetRef
+}
+
+/** 让在途的 `availableMonitors()` 回调落地。 */
+async function settlePromises(): Promise<void> {
+ await act(async () => {
+ for (let index = 0; index < 4; index += 1)
+ await Promise.resolve()
+ })
+}
+
+beforeEach(() => {
+ availableMonitorsMock.mockReset()
+ availableMonitorsMock.mockResolvedValue([{ workArea: { position: { x: 0, y: 0 }, size: { width: 1920, height: 1080 } } }])
+})
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+describe('clampPetWindowPosition', () => {
+ it('工作区内不动', () => {
+ expect(clampAt({ x: 900, y: 400 })).toEqual({ x: 900, y: 400 })
+ })
+
+ it('左边缘:窗口探出屏幕 100px,宠物本体正好贴边', () => {
+ const clamped = clampAt({ x: -500, y: 400 })
+
+ expect(clamped.x).toBe(-400)
+ // 本体左缘正好落在工作区左缘:留白可以留在屏幕外,宠物本身必须完整可见。
+ expect(clamped.x + GEOMETRY.body.left).toBe(MONITOR.x)
+ })
+
+ it('右边缘:本体右缘贴住工作区右缘', () => {
+ const clamped = clampAt({ x: 5000, y: 400 })
+
+ expect(clamped.x).toBe(1300)
+ expect(clamped.x + GEOMETRY.body.right).toBe(MONITOR.x + MONITOR.width)
+ })
+
+ it('上边缘:按容器顶边(与飞行同一套 bodyBounds)', () => {
+ expect(clampAt({ x: 900, y: -500 }).y).toBe(-100)
+ })
+
+ it('下边缘:按 dsh 的脚底比例留出脚下空间', () => {
+ // feet = height * 330 / 360 ≈ 183.33;窗口下界 = 1080 - feet - y(100) ≈ 796.67。
+ expect(clampAt({ x: 900, y: 5000 }).y).toBeCloseTo(796.6667, 3)
+ })
+
+ it('codex 用本体底边当脚底,可用高度与 dsh 不同', () => {
+ expect(clampAt({ x: 900, y: 5000 }, { dsh: false }).y).toBe(700)
+ })
+
+ it('多显示器:本体中心落在哪块屏就用哪块屏的边界', () => {
+ const monitors: PetWorkArea[] = [MONITOR, { x: 1920, y: 0, width: 1280, height: 1024 }]
+
+ // 本体中心在第二块屏内:位置合法,不该被第一块屏的右边界拉回来。
+ expect(clampAt({ x: 2000, y: 400 }, { areas: monitors }).x).toBe(2000)
+ // 第二块屏的右界(3200)才是这里的边界:本体右缘贴住它。
+ expect(clampAt({ x: 5000, y: 400 }, { areas: monitors }).x).toBe(2580)
+ // 同一位置若只有第一块屏,就会被夹到 1300 —— 证明选屏确实生效。
+ expect(clampAt({ x: 2000, y: 400 }).x).toBe(1300)
+ })
+
+ it('屏幕间隙:取最近的工作区', () => {
+ const gapped: PetWorkArea[] = [MONITOR, { x: 2200, y: 0, width: 1280, height: 1024 }]
+
+ // 本体中心 2110 落在 1920–2200 的间隙里,最近的第二块屏左界把窗口顶到 1800。
+ expect(clampAt({ x: 1600, y: 400 }, { areas: gapped }).x).toBe(1800)
+ })
+
+ it('缩放按 devicePixelRatio 换算物理像素', () => {
+ expect(clampAt({ x: -5000, y: 400 }, { areas: [MONITOR_SCALED], scale: 2 }).x).toBe(-800)
+ expect(clampAt({ x: 5000, y: 400 }, { areas: [MONITOR_SCALED], scale: 2 }).x).toBe(2600)
+ })
+
+ it('还没读到显示器工作区时不夹取', () => {
+ expect(clampAt({ x: 5000, y: 5000 }, { areas: [] })).toEqual({ x: 5000, y: 5000 })
+ })
+})
+
+describe('usePetWindowClamp', () => {
+ it('geometry 未就绪时原样返回', () => {
+ const { result } = renderHook(() => usePetWindowClamp(fakePetRef(null), 'dsh'))
+
+ expect(result.current.clampPosition({ x: 5000, y: 5000 })).toEqual({ x: 5000, y: 5000 })
+ })
+
+ it('挂载时读取显示器工作区,之后按本体夹取', async () => {
+ const { result } = renderHook(() => usePetWindowClamp(fakePetRef(GEOMETRY), 'dsh'))
+ await settlePromises()
+
+ const clamped = result.current.clampPosition({ x: 5000, y: 5000 })
+
+ expect(clamped.x).toBe(1300)
+ expect(clamped.y).toBeCloseTo(796.6667, 3)
+ })
+
+ it('refreshWorkAreas 重新读取显示器列表(插拔显示器后立刻生效)', async () => {
+ const { result } = renderHook(() => usePetWindowClamp(fakePetRef(GEOMETRY), 'dsh'))
+ await settlePromises()
+ availableMonitorsMock.mockResolvedValue([{ workArea: { position: { x: -1280, y: 0 }, size: { width: 1280, height: 1024 } } }])
+
+ act(() => {
+ result.current.refreshWorkAreas()
+ })
+ await settlePromises()
+
+ // 新的工作区在左侧:左界变成 -1280 - 100 - 300 = -1680。
+ expect(result.current.clampPosition({ x: -5000, y: 400 }).x).toBe(-1680)
+ })
+})
diff --git a/src/pet/hooks/use-pet-window-clamp.ts b/src/pet/hooks/use-pet-window-clamp.ts
new file mode 100644
index 00000000..57b57ee9
--- /dev/null
+++ b/src/pet/hooks/use-pet-window-clamp.ts
@@ -0,0 +1,163 @@
+import type { Monitor } from '@tauri-apps/api/window'
+import type { PetGeometry, PetRef } from 'dsh-pet-component'
+import { availableMonitors } from '@tauri-apps/api/window'
+import { useEffect, useRef } from 'react'
+import { bodyBounds } from './use-pet-physics.helpers'
+
+/** 显示器工作区(物理像素,与窗口 `outerPosition()`、设备光标流同一坐标系)。 */
+export interface PetWorkArea {
+ x: number
+ y: number
+ width: number
+ height: number
+}
+
+/** 窗口左上角位置(物理像素)。 */
+export interface PetWindowPosition {
+ x: number
+ y: number
+}
+
+/**
+ * 把窗口位置夹进显示器工作区 —— 边界取**宠物本体 / 脚底**,与飞行共用 `bodyBounds`。
+ *
+ * # 为什么不夹整个窗口
+ *
+ * 宠物只是窗口底部居中的一块,四周是透明留白(`PET_WINDOW_PAD_X`、窗口最小宽度
+ * `PET_BUBBLE_MIN_WIDTH`):按整窗夹取会把留白算成宠物的一部分,于是贴到左右/上边缘
+ * 松手时被推开一段(100% 大小时左侧约 `(420 - 220) / 2 = 100` 物理像素),看起来就是
+ * 「没办法在边缘放置宠物」。按本体夹取时窗口的一部分可以留在屏幕外,宠物本体始终
+ * 完整可见且贴得住边缘。
+ *
+ * 与飞行的边界一致还有第二个好处:跟手期间窗口不会跑到飞行边界之外,松手时飞行
+ * 积分不必把越界位置一次性修正回来(那就是「松开就弹开」的另半个原因)。
+ *
+ * 换算与 `src/pet/hooks/use-pet-physics.ts` 的 `startFlight` 完全一致:工作区换算到
+ * 逻辑像素当舞台,`bodyBounds` 给出本体相对舞台的边界,再减去 `geometry.x/y` 得到窗口
+ * 位置(窗口逻辑位置 = 容器逻辑位置 − `geometry.x/y`),最后乘回 `scale` 得物理像素。
+ */
+export function clampPetWindowPosition(
+ position: PetWindowPosition,
+ geometry: PetGeometry,
+ dsh: boolean,
+ areas: readonly PetWorkArea[],
+ scale: number,
+): PetWindowPosition {
+ if (areas.length === 0)
+ return position
+ const area = selectWorkArea(position, geometry, areas, scale)
+ const stage = {
+ x: area.x / scale,
+ y: area.y / scale,
+ width: area.width / scale,
+ height: area.height / scale,
+ }
+ const local = bodyBounds(geometry, stage.width, stage.height, dsh)
+ return {
+ x: clamp(position.x, (stage.x + local.minX - geometry.x) * scale, (stage.x + local.maxX - geometry.x) * scale),
+ y: clamp(position.y, (stage.y + local.minY - geometry.y) * scale, (stage.y + local.maxY - geometry.y) * scale),
+ }
+}
+
+/**
+ * 钳制到上下限之间;上下限反了(工作区比宠物还小)时退化成上限,与后端
+ * `clamp_window_position` 的 `.clamp(left, max_x)` 行为一致。
+ */
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(Math.max(value, min), Math.max(min, max))
+}
+
+/**
+ * 选宠物本体所在的显示器工作区:本体中心落在哪个工作区就用哪个,跨屏间隙时取最近的
+ * 一个(与后端 `move_pet_window` 按窗口中心选屏、间隙取最近显示器同理,只是这里用
+ * 本体中心,与夹取边界同一套计算)。
+ */
+function selectWorkArea(
+ position: PetWindowPosition,
+ geometry: PetGeometry,
+ areas: readonly PetWorkArea[],
+ scale: number,
+): PetWorkArea {
+ const centerX = position.x + ((geometry.body.left + geometry.body.right) / 2) * scale
+ const centerY = position.y + ((geometry.body.top + geometry.body.bottom) / 2) * scale
+ const containing = areas.find(area =>
+ centerX >= area.x
+ && centerX < area.x + area.width
+ && centerY >= area.y
+ && centerY < area.y + area.height)
+ if (containing !== undefined)
+ return containing
+ return areas.reduce((best, area) =>
+ distanceSquared(area, centerX, centerY) < distanceSquared(best, centerX, centerY) ? area : best)
+}
+
+/** 点到工作区的距离平方(在工作区内为 0)。 */
+function distanceSquared(area: PetWorkArea, x: number, y: number): number {
+ const right = area.x + area.width
+ const bottom = area.y + area.height
+ const dx = x < area.x ? area.x - x : x >= right ? x - right + 1 : 0
+ const dy = y < area.y ? area.y - y : y >= bottom ? y - bottom + 1 : 0
+ return dx * dx + dy * dy
+}
+
+/** 读取显示器工作区列表并写入 ref;失败时保留上一次的列表。 */
+function loadWorkAreas(areasRef: { current: readonly PetWorkArea[] }): void {
+ void availableMonitors()
+ .then((monitors) => { areasRef.current = monitors.map(toWorkArea) })
+ .catch(() => {})
+}
+
+function toWorkArea(monitor: Monitor): PetWorkArea {
+ return {
+ x: monitor.workArea.position.x,
+ y: monitor.workArea.position.y,
+ width: monitor.workArea.size.width,
+ height: monitor.workArea.size.height,
+ }
+}
+
+/** 桌宠窗口的「按本体夹取」控制器。 */
+export interface PetWindowClampControls {
+ /**
+ * 传给 `useWindowDraggable({ clampPosition })`:用实时 `pet.geometry` 与缓存的显示器
+ * 工作区夹取窗口位置(物理像素)。`geometry` 还没就绪或工作区还没读到时不夹取。
+ */
+ clampPosition: (position: PetWindowPosition) => PetWindowPosition
+ /** 重新读取显示器工作区:抓取时调用,插拔显示器后立刻生效(无需重开应用)。 */
+ refreshWorkAreas: () => void
+}
+
+/**
+ * 桌宠窗口的夹取来源:挂载时读一次显示器工作区列表,之后每次抓取都刷新;每帧的边界
+ * 用实时 `pet.geometry` 现算(`PetRef.geometry` 是同步 getter)。
+ */
+export function usePetWindowClamp(pet: PetRef, kind: 'dsh' | 'codex' | undefined): PetWindowClampControls {
+ const areasRef = useRef<readonly PetWorkArea[]>([])
+ const kindRef = useRef(kind)
+ kindRef.current = kind
+
+ // keep:effect 挂载时先取一次显示器列表(拖拽可能早于下一次抓取刷新);之后由
+ // `refreshWorkAreas` 在每次抓取时更新,显示器热插拔不用重开应用。
+ useEffect(() => {
+ loadWorkAreas(areasRef)
+ }, [])
+
+ function refreshWorkAreas(): void {
+ loadWorkAreas(areasRef)
+ }
+
+ function clampPosition(position: PetWindowPosition): PetWindowPosition {
+ const geometry = pet.geometry
+ if (geometry === null)
+ return position
+ return clampPetWindowPosition(
+ position,
+ geometry,
+ kindRef.current === 'dsh',
+ areasRef.current,
+ globalThis.devicePixelRatio || 1,
+ )
+ }
+
+ return { clampPosition, refreshWorkAreas }
+}
diff --git a/src/store/modules/plugins/types.ts b/src/store/modules/plugins/types.ts
index ee2fdd4d..5a228f43 100644
--- a/src/store/modules/plugins/types.ts
+++ b/src/store/modules/plugins/types.ts
@@ -73,7 +73,7 @@ export interface PluginManagerLog {
processId?: string
}
-export type PluginSearchProblem = 'invalid-spec' | 'not-found' | 'network' | 'unsupported' | 'unknown'
+export type PluginSearchProblem = 'invalid-spec' | 'not-found' | 'local-missing' | 'network' | 'unsupported' | 'unknown'
export interface PluginSearchResult {
spec: string
diff --git a/src/store/modules/setting/store.ts b/src/store/modules/setting/store.ts
index 28f1533b..e1591006 100644
--- a/src/store/modules/setting/store.ts
+++ b/src/store/modules/setting/store.ts
@@ -12,6 +12,7 @@ let zoomQueue = Promise.resolve()
export const setting = defineStore({
state: () => ({
+ proxy_url: '',
appearance: normalizeAppearance(APPEARANCE_DEFAULTS),
installed: false,
port: 3080,
diff --git a/src/store/modules/setting/types/index.ts b/src/store/modules/setting/types/index.ts
index 7031c060..4bdc79bc 100644
--- a/src/store/modules/setting/types/index.ts
+++ b/src/store/modules/setting/types/index.ts
@@ -1,6 +1,7 @@
import type { Appearance } from '../../../../../packages/dsh-tauri/src/shared/appearance'
export interface AppSettingUpdate {
+ proxyUrl?: string
appearance?: Appearance
port?: number
zoomFactor?: number
diff --git a/src/ui/config/components/close-action.tsx b/src/ui/config/components/close-action.tsx
index 1158f549..3a63c3ac 100644
--- a/src/ui/config/components/close-action.tsx
+++ b/src/ui/config/components/close-action.tsx
@@ -1,4 +1,4 @@
-import { Description, ListBox, Select } from '@heroui/react'
+import { ListBox, Select } from '@heroui/react'
import { useMutation } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { useStore } from 'valtio-define'
@@ -64,9 +64,7 @@ export function ConfigCloseAction() {
</Select.Popover>
</Select>
</div>
- <Description className="text-[10px] text-muted/70">
- {t('ui.close_action_hint')}
- </Description>
+ <p className="text-[10px] text-muted/70">{t('ui.close_action_hint')}</p>
</div>
)
}
diff --git a/src/ui/config/components/launch-on-login.tsx b/src/ui/config/components/launch-on-login.tsx
index 5269e43f..e9f3fc07 100644
--- a/src/ui/config/components/launch-on-login.tsx
+++ b/src/ui/config/components/launch-on-login.tsx
@@ -1,4 +1,4 @@
-import { Description, Switch } from '@heroui/react'
+import { Switch } from '@heroui/react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { invoke } from '@tauri-apps/api/core'
import { useTranslation } from 'react-i18next'
@@ -39,9 +39,7 @@ export function ConfigLaunchOnLogin() {
</Switch.Content>
</Switch>
</div>
- <Description className="text-[10px] text-muted/70">
- {t('ui.launch_on_login_hint')}
- </Description>
+ <p className="text-[10px] text-muted/70">{t('ui.launch_on_login_hint')}</p>
</div>
)
}
diff --git a/src/ui/config/debug.test.tsx b/src/ui/config/debug.test.tsx
new file mode 100644
index 00000000..69b9cc3e
--- /dev/null
+++ b/src/ui/config/debug.test.tsx
@@ -0,0 +1,173 @@
+// @vitest-environment jsdom
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ConfigDebug } from './debug'
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ toast: vi.fn(),
+ update: vi.fn(),
+ build: vi.fn(),
+ settingState: { proxy_url: '', port: 3080, zoom_factor: 1, harness_max_heap_mb: null } as Record<string, unknown>,
+ harnessState: { serviceRunning: true, busyAction: null } as Record<string, unknown>,
+ harnessUpdaterState: { updateInfo: null } as Record<string, unknown>,
+}))
+
+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }))
+vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async () => () => {}) }))
+vi.mock('@/utils/toast', () => ({ toast: mocks.toast }))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN', changeLanguage: vi.fn() } }),
+}))
+vi.mock('@/hooks/use-listen', () => ({ useListen: () => {} }))
+vi.mock('@/ui/config/components/close-action', () => ({ ConfigCloseAction: () => null }))
+vi.mock('@/ui/config/components/launch-on-login', () => ({ ConfigLaunchOnLogin: () => null }))
+vi.mock('@/ui/config/hooks/use-core-breaking-confirm', () => ({
+ useCoreBreakingConfirm: () => ({ holder: null, confirmCoreBreaking: vi.fn() }),
+}))
+vi.mock('@/ui/config/hooks/use-core-profile-switch', () => ({
+ useCoreProfileSwitch: () => ({ holder: null, guardCoreUpgrade: vi.fn() }),
+}))
+vi.mock('valtio-define', () => {
+ const store = (state: unknown) => ({
+ $state: state,
+ update: mocks.update,
+ build: mocks.build,
+ refresh: vi.fn(),
+ launchAndWait: vi.fn(),
+ })
+ return {
+ defineStore: (name: unknown) => store(name),
+ useStore: (value: { $state: Record<string, unknown> }) => value.$state,
+ }
+})
+vi.mock('@/store/modules/setting', () => ({
+ HARNESS_HEAP_MIN_MB: 512,
+ HARNESS_HEAP_MAX_MB: 32768,
+ setting: { $state: mocks.settingState, update: mocks.update },
+}))
+vi.mock('@/store/modules/harness', () => ({
+ harness: { $state: mocks.harnessState, restart: vi.fn(), shutdown: vi.fn(), openBrowser: vi.fn() },
+}))
+vi.mock('@/store/modules/harness-updater', () => ({
+ harnessUpdater: { $state: mocks.harnessUpdaterState, showToast: vi.fn(), handleUpdate: vi.fn() },
+}))
+vi.mock('@/store', () => ({
+ store: {
+ setting: { $state: mocks.settingState, update: mocks.update },
+ harness: { $state: mocks.harnessState, restart: vi.fn(), shutdown: vi.fn(), openBrowser: vi.fn() },
+ harnessUpdater: { $state: mocks.harnessUpdaterState, showToast: vi.fn(), handleUpdate: vi.fn() },
+ },
+}))
+
+const SAVED = 'socks5h://127.0.0.1:1080'
+const EDITED = 'http://127.0.0.1:7897'
+
+/** 让 `store.setting.update` 挂起,模拟「保存仍在途」。 */
+function deferUpdate() {
+ let release!: () => void
+ const pending = new Promise<void>((resolve) => {
+ release = () => resolve()
+ })
+ mocks.update.mockReturnValue(pending)
+ return release
+}
+
+function renderDebug() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
+ return render(
+ <QueryClientProvider client={client}>
+ <ConfigDebug />
+ </QueryClientProvider>,
+ )
+}
+
+function proxyInput(): HTMLInputElement {
+ return screen.getByTestId('dsh-proxy-url') as HTMLInputElement
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.settingState.proxy_url = SAVED
+ mocks.settingState.port = 3080
+ mocks.settingState.zoom_factor = 1
+ mocks.settingState.harness_max_heap_mb = null
+ mocks.harnessState.serviceRunning = true
+ mocks.harnessState.busyAction = null
+ mocks.harnessUpdaterState.updateInfo = null
+ mocks.invoke.mockImplementation((command: string) => {
+ if (command === 'get_app_config')
+ return Promise.resolve({ ...mocks.settingState })
+ if (command === 'get_runtime_info')
+ return Promise.resolve({ app_version: '1.0.0', dsh_version: '1.0.0', node_version: '22.0.0', platform: 'linux', arch: 'x64', service_url: 'http://127.0.0.1:3080', harness_path: '', data_dir: '', node_path: '', pnpm_path: '' })
+ if (command === 'get_cli_link_status')
+ return Promise.resolve({ enabled: false, shim_exists: false, path_registered: false, user_dsh_preserved: false, bin_dir: '', shim_path: '' })
+ return Promise.resolve(null)
+ })
+})
+
+afterEach(() => {
+ cleanup()
+})
+
+describe('配置面板代理地址保存', () => {
+ it('保存成功且期间未再编辑时,输入框回落到已保存值', async () => {
+ const release = deferUpdate()
+ renderDebug()
+
+ await waitFor(() => expect(proxyInput().value).toBe(SAVED))
+
+ fireEvent.change(proxyInput(), { target: { value: EDITED } })
+ fireEvent.click(screen.getByTestId('dsh-proxy-save'))
+ await waitFor(() => expect(mocks.update).toHaveBeenCalledWith({ proxyUrl: EDITED }))
+
+ await act(async () => {
+ release()
+ await Promise.resolve()
+ })
+
+ await waitFor(() => expect(proxyInput().value).toBe(SAVED))
+ })
+
+ it('保存期间用户又改了输入时,不抹掉在途的新输入', async () => {
+ const release = deferUpdate()
+ renderDebug()
+
+ await waitFor(() => expect(proxyInput().value).toBe(SAVED))
+
+ fireEvent.change(proxyInput(), { target: { value: EDITED } })
+ fireEvent.click(screen.getByTestId('dsh-proxy-save'))
+ await waitFor(() => expect(mocks.update).toHaveBeenCalledWith({ proxyUrl: EDITED }))
+
+ const inflight = 'https://user:[email protected]:8443'
+ fireEvent.change(proxyInput(), { target: { value: inflight } })
+
+ await act(async () => {
+ release()
+ await Promise.resolve()
+ })
+
+ expect(proxyInput().value).toBe(inflight)
+ })
+
+ it('保存期间改回与提交值一致时,仍按已保存值收拢编辑态', async () => {
+ const release = deferUpdate()
+ renderDebug()
+
+ await waitFor(() => expect(proxyInput().value).toBe(SAVED))
+
+ fireEvent.change(proxyInput(), { target: { value: EDITED } })
+ fireEvent.click(screen.getByTestId('dsh-proxy-save'))
+ await waitFor(() => expect(mocks.update).toHaveBeenCalledWith({ proxyUrl: EDITED }))
+
+ fireEvent.change(proxyInput(), { target: { value: ` ${EDITED} ` } })
+
+ await act(async () => {
+ release()
+ await Promise.resolve()
+ })
+
+ await waitFor(() => expect(proxyInput().value).toBe(SAVED))
+ })
+})
diff --git a/src/ui/config/debug.tsx b/src/ui/config/debug.tsx
index 6c1af275..e8839a60 100644
--- a/src/ui/config/debug.tsx
+++ b/src/ui/config/debug.tsx
@@ -1,6 +1,6 @@
import type { RuntimeInfo } from '@/types'
-import { ArrowRotateRight, ArrowUpRightFromSquare, ChevronRight, Copy, Power } from '@gravity-ui/icons'
-import { Button, Chip, Description, Input, Link, ListBox, Select, Spinner, Switch } from '@heroui/react'
+import { ArrowRotateRight, ArrowUpRightFromSquare, ChevronRight, CircleInfo, Copy, Power } from '@gravity-ui/icons'
+import { Button, Chip, Description, Input, Link, ListBox, Select, Spinner, Switch, Tooltip } from '@heroui/react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { invoke } from '@tauri-apps/api/core'
import { useState } from 'react'
@@ -41,6 +41,7 @@ export function ConfigDebug() {
// 端口编辑态:用户尚未输入时为 undefined,展示值始终以 store 中已保存的端口为准。
// 初值不写入 state(避免渲染期副作用),用户一旦输入即以输入值为准。
const [portInput, setPortInput] = useState<number>()
+ const [proxyInput, setProxyInput] = useState<string>()
const [heapInput, setHeapInput] = useState<string>()
const { data: info, refetch: refreshInfo } = useQuery({
@@ -53,8 +54,9 @@ export function ConfigDebug() {
void refreshInfo()
})
- const { port: savedPort, zoom_factor: zoomFactor, harness_max_heap_mb: savedHeapMb } = useStore(store.setting)
+ const { port: savedPort, proxy_url: savedProxy, zoom_factor: zoomFactor, harness_max_heap_mb: savedHeapMb } = useStore(store.setting)
const port = portInput ?? savedPort
+ const proxy = proxyInput ?? savedProxy
const heapValue = heapInput ?? String(savedHeapMb ?? '')
/** 空输入代表自动值(null),其余按数字解析,非法值交给保存前的整数校验拦下 */
const parsedHeap = heapValue.trim() === '' ? null : Number(heapValue)
@@ -160,6 +162,38 @@ export function ConfigDebug() {
},
})
+ const { mutate: onSaveProxy } = useMutation({
+ mutationFn: async (value: string) => {
+ const proxyUrl = value.trim()
+ if (proxyUrl) {
+ let url: URL
+ try {
+ url = new URL(proxyUrl)
+ }
+ catch {
+ throw new Error('PROXY_INVALID')
+ }
+ if (!proxyUrl.includes('://') || /\s/.test(proxyUrl)
+ || !['http:', 'https:', 'socks5:', 'socks5h:'].includes(url.protocol)
+ || !url.hostname || url.port === '0' || !['', '/'].includes(url.pathname)
+ || url.search || url.hash) {
+ throw new Error('PROXY_INVALID')
+ }
+ }
+ await store.setting.update({ proxyUrl })
+ return proxyUrl
+ },
+ onSuccess: (submitted) => {
+ // 保存期间用户可能又改了输入:只在输入仍等于本次提交值时才收拢编辑态,
+ // 否则会把在途的新输入抹掉。
+ setProxyInput(current => (current !== undefined && current.trim() !== submitted ? current : undefined))
+ toast(t('network.saved'))
+ },
+ onError: (error: unknown) => {
+ toast(t(String(error).includes('PROXY_INVALID') ? 'network.invalid' : 'network.save_failed'), { variant: 'danger' })
+ },
+ })
+
const { mutate: onSaveHeap } = useMutation({
mutationFn: async (mb: number | null) => {
// 空输入 = 交回自动值;Rust 侧把 0 归一化为 None(物理内存一半,见 workflow/heap.rs)
@@ -300,83 +334,7 @@ export function ConfigDebug() {
<div className="space-y-1.5">
<ConfigLaunchOnLogin />
<ConfigCloseAction />
- <div>
- <div className="flex items-center justify-between">
- <span className="text-xs font-medium text-ink">{t('ui.cli_link_enabled')}</span>
- <Switch
- isSelected={cliStatus?.enabled ?? false}
- onChange={onToggleCliLink}
- aria-label={t('ui.cli_link_enabled')}
- >
- <Switch.Content>
- <Switch.Control>
- <Switch.Thumb />
- </Switch.Control>
- </Switch.Content>
- </Switch>
- </div>
- <If cond={cliStatus != null}>
- <div className="flex flex-col">
- <If
- cond={!cliStatus?.user_dsh_preserved}
- else={(
- <Description className="text-[10px] text-muted/70">
- {t('ui.cli_link_user_dsh_preserved')}
- </Description>
- )}
- >
- <Description className="text-[10px] text-muted/70">{cliStatus?.bin_dir}</Description>
- <Description className="text-[10px] text-muted/70">
- {t('ui.cli_link_hint')}
- </Description>
- </If>
- </div>
- </If>
- </div>
- <div className="flex items-center justify-between gap-2">
- <span className="text-xs font-medium text-ink">{t('ui.port')}</span>
- <div className="flex items-center gap-1.5">
- <Input
- type="number"
- variant="secondary"
- value={String(port)}
- onChange={e => setPortInput(Number(e.target.value))}
- className="w-24 h-8 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- aria-label={t('ui.port')}
- />
- <Button
- size="sm"
- variant="primary"
- className="h-8"
- onPress={() => onSavePort(port)}
- >
- {t('buttons.save')}
- </Button>
- </div>
- </div>
- <div className="flex items-center justify-between gap-2">
- <span className="text-xs font-medium text-ink">{t('ui.heap_limit')}</span>
- <div className="flex items-center gap-1.5">
- <Input
- type="number"
- variant="secondary"
- value={heapValue}
- placeholder={t('ui.heap_limit_auto')}
- onChange={e => setHeapInput(e.target.value)}
- className="w-24 h-8 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- aria-label={t('ui.heap_limit')}
- />
- <Button
- size="sm"
- variant="primary"
- className="h-8"
- onPress={() => onSaveHeap(parsedHeap)}
- >
- {t('buttons.save')}
- </Button>
- </div>
- </div>
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-ink">{t('ui.language')}</span>
<Select
@@ -427,6 +385,124 @@ export function ConfigDebug() {
</Select.Popover>
</Select>
</div>
+
+ <div className="border-t border-line/30" />
+
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex items-center gap-1 text-xs font-medium text-ink">
+ {t('network.proxy_url')}
+ <Tooltip delay={0}>
+ <Button isIconOnly size="sm" variant="ghost" className="size-5 text-muted" aria-label={t('network.description')}>
+ <CircleInfo className="size-3.5" />
+ </Button>
+ <Tooltip.Content className="max-w-[320px]">{`${t('network.description')} ${t('network.formats')}`}</Tooltip.Content>
+ </Tooltip>
+ </span>
+ <div className="flex items-center gap-1.5">
+ <Input
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ variant="secondary"
+ value={proxy}
+ placeholder="http://127.0.0.1:7897"
+ onChange={e => setProxyInput(e.target.value)}
+ className="w-52 h-8"
+ aria-label={t('network.proxy_url')}
+ data-testid="dsh-proxy-url"
+ />
+ <Button
+ size="sm"
+ variant="primary"
+ className="h-8"
+ onPress={() => onSaveProxy(proxy)}
+ isDisabled={proxy === savedProxy}
+ data-testid="dsh-proxy-save"
+ >
+ {t('buttons.save')}
+ </Button>
+ </div>
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-ink">{t('ui.port')}</span>
+ <div className="flex items-center gap-1.5">
+ <Input
+ type="number"
+ variant="secondary"
+ value={String(port)}
+ onChange={e => setPortInput(Number(e.target.value))}
+ className="w-24 h-8 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ aria-label={t('ui.port')}
+ />
+ <Button
+ size="sm"
+ variant="primary"
+ className="h-8"
+ onPress={() => onSavePort(port)}
+ >
+ {t('buttons.save')}
+ </Button>
+ </div>
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-ink">{t('ui.heap_limit')}</span>
+ <div className="flex items-center gap-1.5">
+ <Input
+ type="number"
+ variant="secondary"
+ value={heapValue}
+ placeholder={t('ui.heap_limit_auto')}
+ onChange={e => setHeapInput(e.target.value)}
+ className="w-24 h-8 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ aria-label={t('ui.heap_limit')}
+ />
+ <Button
+ size="sm"
+ variant="primary"
+ className="h-8"
+ onPress={() => onSaveHeap(parsedHeap)}
+ >
+ {t('buttons.save')}
+ </Button>
+ </div>
+ </div>
+
+ <div className="border-t border-line/30" />
+
+ <div>
+ <div className="flex items-center justify-between">
+ <span className="flex items-center gap-1 text-xs font-medium text-ink">
+ {t('ui.cli_link_enabled')}
+ <Tooltip delay={0}>
+ <Button isIconOnly size="sm" variant="ghost" className="size-5 text-muted" aria-label={t('ui.cli_link_hint')}>
+ <CircleInfo className="size-3.5" />
+ </Button>
+ <Tooltip.Content>{t('ui.cli_link_hint')}</Tooltip.Content>
+ </Tooltip>
+ </span>
+ <Switch
+ isSelected={cliStatus?.enabled ?? false}
+ onChange={onToggleCliLink}
+ aria-label={t('ui.cli_link_enabled')}
+ >
+ <Switch.Content>
+ <Switch.Control>
+ <Switch.Thumb />
+ </Switch.Control>
+ </Switch.Content>
+ </Switch>
+ </div>
+ <If cond={cliStatus != null}>
+ <div className="flex flex-col">
+ <If
+ cond={!cliStatus?.user_dsh_preserved}
+ else={<Description className="text-[10px] text-muted/70">{t('ui.cli_link_user_dsh_preserved')}</Description>}
+ >
+ <Description className="text-[10px] text-muted/70">{cliStatus?.bin_dir}</Description>
+ </If>
+ </div>
+ </If>
+ </div>
</div>
</div>
diff --git a/src/ui/config/plugin.test.tsx b/src/ui/config/plugin.test.tsx
index e9f3dc90..6236e16f 100644
--- a/src/ui/config/plugin.test.tsx
+++ b/src/ui/config/plugin.test.tsx
@@ -1,21 +1,44 @@
// @vitest-environment jsdom
import type { ReactNode } from 'react'
import type { Plugin } from '@/store/modules/plugins'
-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ConfigPlugin } from './plugin'
-const { manager, openDialog } = vi.hoisted(() => ({
- manager: { installed: [] as Plugin[], processes: [], loading: false, error: '', disable: vi.fn(), enable: vi.fn() },
+const { manager, openDialog, mocks, hmrStatus } = vi.hoisted(() => ({
+ manager: { installed: [] as Plugin[], processes: [], loading: false, error: '', disable: vi.fn(), enable: vi.fn(), search: vi.fn(), install: vi.fn() },
openDialog: vi.fn(),
+ mocks: {
+ invoke: vi.fn(),
+ toast: Object.assign(vi.fn(), { close: vi.fn() }),
+ restart: vi.fn(),
+ setQueryData: vi.fn(),
+ invalidate: vi.fn(),
+ },
+ hmrStatus: { data: undefined as { enabled: boolean, watching: boolean, patchPath: string | null, roots: string[] } | undefined, isFetching: false },
}))
vi.mock('@/hooks/use-plugins-manager', () => ({ useDshPluginsManager: () => manager }))
vi.mock('@overlastic/react', () => ({ useOverlay: () => [null, openDialog] }))
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))
-vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({}), useMutation: () => ({}) }))
-vi.mock('@/store', () => ({ store: { preinstall: { open: vi.fn(), installing: false } } }))
-vi.mock('@/utils/toast', () => ({ toast: vi.fn() }))
+// useMutation 桩会真正执行传入的 mutationFn:命令名与参数由用例断言,而不是断言「调用了 mutate」。
+vi.mock('@tanstack/react-query', () => ({
+ useQueryClient: () => ({ invalidateQueries: mocks.invalidate, setQueryData: mocks.setQueryData }),
+ useQuery: () => hmrStatus,
+ useMutation: (options: { mutationFn?: (variables: never) => Promise<unknown>, onSuccess?: (data: unknown) => void, onError?: (error: unknown) => void } = {}) => ({
+ mutate: (variables: never) => {
+ void Promise.resolve(options.mutationFn?.(variables))
+ .then(data => options.onSuccess?.(data))
+ .catch(error => options.onError?.(error))
+ },
+ mutateAsync: (variables: never) => Promise.resolve(options.mutationFn?.(variables)),
+ isPending: false,
+ }),
+}))
+vi.mock('@/store', () => ({ store: { preinstall: { open: vi.fn(), installing: false }, harness: { restart: mocks.restart } } }))
+vi.mock('@/utils/toast', () => ({ toast: mocks.toast }))
+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }))
+vi.mock('@tauri-apps/plugin-os', () => ({ type: () => 'windows' }))
vi.mock('@/components/modal', () => ({ Modal: () => null }))
vi.mock('@/components/item', () => ({ Item: ({ left, right }: { left: ReactNode, right: ReactNode }) => (
<div>
@@ -27,12 +50,26 @@ vi.mock('@/components/ellipsis', () => ({ Ellipsis: ({ children }: { children: R
vi.mock('@/components/panel', () => ({ Panel: { Header: () => null, Loadable: ({ children }: { children: ReactNode }) => <div>{children}</div> } }))
vi.mock('@heroui/react', () => ({
Chip: ({ children, onClick }: { children: ReactNode, onClick?: () => void }) => <button type="button" onClick={onClick}>{children}</button>,
- Button: ({ children, onPress }: { children: ReactNode, onPress?: () => void }) => <button type="button" onClick={onPress}>{children}</button>,
- Input: () => null,
+ Button: ({ children, onPress, isDisabled, 'aria-label': ariaLabel }: { 'children': ReactNode, 'onPress'?: () => void, 'isDisabled'?: boolean, 'aria-label'?: string }) => (
+ <button type="button" aria-label={ariaLabel} disabled={isDisabled} onClick={onPress}>{children}</button>
+ ),
+ Description: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+ Input: ({ value, onChange, placeholder, 'aria-label': ariaLabel }: { 'value'?: string, 'onChange'?: (event: { target: { value: string } }) => void, 'placeholder'?: string, 'aria-label'?: string }) => (
+ <input aria-label={ariaLabel} placeholder={placeholder} value={value} onChange={event => onChange?.(event)} />
+ ),
Label: ({ children }: { children: ReactNode }) => <span>{children}</span>,
Spinner: () => null,
- Switch: () => null,
- Tooltip: () => null,
+ // Switch 的复合结构在桩里展开成原生 switch,好让用例断言选中态与回调值。
+ Switch: Object.assign(
+ ({ children, isSelected, isDisabled, onChange, 'aria-label': ariaLabel }: { 'children'?: ReactNode, 'isSelected'?: boolean, 'isDisabled'?: boolean, 'onChange'?: (selected: boolean) => void, 'aria-label'?: string }) => (
+ <button type="button" role="switch" aria-label={ariaLabel} aria-checked={isSelected} disabled={isDisabled} onClick={() => onChange?.(!isSelected)}>{children}</button>
+ ),
+ { Content: ({ children }: { children: ReactNode }) => <>{children}</>, Control: ({ children }: { children: ReactNode }) => <>{children}</>, Thumb: () => null },
+ ),
+ Tooltip: Object.assign(
+ ({ children }: { children: ReactNode }) => <>{children}</>,
+ { Content: () => null },
+ ),
}))
function plugin(overrides: Partial<Plugin> = {}): Plugin {
@@ -67,7 +104,17 @@ beforeEach(() => {
manager.installed = [plugin()]
manager.disable.mockReset().mockResolvedValue(undefined)
manager.enable.mockReset().mockResolvedValue(undefined)
+ manager.search.mockReset().mockResolvedValue([])
+ manager.install.mockReset().mockResolvedValue(undefined)
openDialog.mockReset()
+ mocks.invoke.mockReset().mockResolvedValue(null)
+ mocks.toast.mockReset()
+ mocks.toast.close.mockReset()
+ mocks.restart.mockReset()
+ mocks.setQueryData.mockReset()
+ mocks.invalidate.mockReset()
+ hmrStatus.data = undefined
+ hmrStatus.isFetching = false
})
afterEach(() => {
@@ -127,3 +174,81 @@ describe('built-in plugin toggles', () => {
expect(openDialog).not.toHaveBeenCalled()
})
})
+
+describe('local plugin folder picking', () => {
+ /** 目录选择器只在 Windows 构建上存在,这里让 get_local_plugin_hmr 与 pick 各自返回固定值。 */
+ function mockLocalCommands(picked: string | null) {
+ mocks.invoke.mockImplementation(async (command: string) => {
+ if (command === 'get_local_plugin_hmr')
+ return { enabled: false, watching: false, patchPath: null, roots: [] }
+ if (command === 'pick_local_plugin_dir')
+ return picked
+ throw new Error(`Unexpected command: ${command}`)
+ })
+ }
+
+ it('installs the picked folder as a link spec through the normal install chain', async () => {
+ mockLocalCommands('link:D:/plugins/mine')
+ render(<ConfigPlugin />)
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.local_dir' })))
+ const input = screen.getByPlaceholderText('plugins.install_placeholder') as HTMLInputElement
+ expect(input.value).toBe('link:D:/plugins/mine')
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.install' })))
+ await waitFor(() => expect(manager.search).toHaveBeenCalledExactlyOnceWith(['link:D:/plugins/mine']))
+ expect(manager.install).toHaveBeenCalledExactlyOnceWith(['link:D:/plugins/mine'])
+ })
+
+ it('keeps the install box untouched when the folder picker is cancelled', async () => {
+ mockLocalCommands(null)
+ render(<ConfigPlugin />)
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.local_dir' })))
+ expect(mocks.invoke).toHaveBeenCalledWith('pick_local_plugin_dir')
+ expect((screen.getByPlaceholderText('plugins.install_placeholder') as HTMLInputElement).value).toBe('')
+ expect(mocks.toast).not.toHaveBeenCalled()
+ })
+
+ it('reports a failed folder picker instead of silently doing nothing', async () => {
+ mocks.invoke.mockImplementation(async (command: string) => {
+ if (command === 'get_local_plugin_hmr')
+ return { enabled: false, watching: false, patchPath: null, roots: [] }
+ if (command === 'pick_local_plugin_dir')
+ throw new Error('PLUGIN_PICK_FOLDER_FAILED: boom')
+ throw new Error(`Unexpected command: ${command}`)
+ })
+ render(<ConfigPlugin />)
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.local_dir' })))
+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith('plugins.local_dir_failed', { variant: 'danger' }))
+ })
+})
+
+describe('local plugin hot reload switch', () => {
+ it('sends the new value to the host and offers a restart', async () => {
+ hmrStatus.data = { enabled: false, watching: false, patchPath: null, roots: [] }
+ mocks.invoke.mockImplementation(async (command: string) => {
+ if (command === 'get_local_plugin_hmr')
+ return { enabled: false, watching: false, patchPath: null, roots: [] }
+ if (command === 'set_local_plugin_hmr')
+ return { enabled: true, watching: true, patchPath: 'D:/home/cordis.hmr.patch.yml', roots: ['D:/plugins/mine'] }
+ throw new Error(`Unexpected command: ${command}`)
+ })
+ render(<ConfigPlugin />)
+ await act(async () => fireEvent.click(screen.getByRole('switch', { name: 'plugins.hmr' })))
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith('set_local_plugin_hmr', { enabled: true }))
+ expect(mocks.setQueryData).toHaveBeenCalledWith(['local_plugin_hmr'], expect.objectContaining({ enabled: true }))
+ expect(mocks.toast).toHaveBeenCalledWith('plugins.hmr_restart_hint', expect.objectContaining({ variant: 'accent' }))
+ })
+
+ it('surfaces a failed hot reload update to the user', async () => {
+ mocks.invoke.mockImplementation(async (command: string) => {
+ if (command === 'get_local_plugin_hmr')
+ return { enabled: true, watching: true, patchPath: null, roots: ['D:/plugins/mine'] }
+ if (command === 'set_local_plugin_hmr')
+ throw new Error('HMR_LAYER_WRITE_FAILED: disk full')
+ throw new Error(`Unexpected command: ${command}`)
+ })
+ render(<ConfigPlugin />)
+ await act(async () => fireEvent.click(screen.getByRole('switch', { name: 'plugins.hmr' })))
+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith('plugins.hmr_save_failed', { variant: 'danger' }))
+ expect(mocks.toast).not.toHaveBeenCalledWith('plugins.hmr_restart_hint', expect.anything())
+ })
+})
diff --git a/src/ui/config/plugin.tsx b/src/ui/config/plugin.tsx
index cbfd8a30..e690a622 100644
--- a/src/ui/config/plugin.tsx
+++ b/src/ui/config/plugin.tsx
@@ -1,10 +1,11 @@
import type { Plugin, PluginProcess, PluginSearchProblem, PluginSearchResult } from '@/store/modules/plugins'
-import { ChevronRight, CircleExclamation } from '@gravity-ui/icons'
-import { Button, Chip, Input, Label, Spinner, Switch, Tooltip } from '@heroui/react'
+import { ChevronRight, CircleExclamation, FolderOpen } from '@gravity-ui/icons'
+import { Button, Chip, Description, Input, Label, Spinner, Switch, Tooltip } from '@heroui/react'
import { useOverlay } from '@overlastic/react'
import { useToggle } from '@reause/core'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { invoke } from '@tauri-apps/api/core'
+import { type } from '@tauri-apps/plugin-os'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
@@ -45,12 +46,34 @@ const QUEUED_ACTIONS: Record<PluginProcess['type'], string> = {
/** 兼容性检查的问题码 → i18n key:管理器把宿主返回的 problem 原样透传给调用方 */
const searchProblemKeys: Record<PluginSearchProblem, string> = {
'invalid-spec': 'plugins.search_invalid_spec',
+ 'local-missing': 'plugins.search_local_missing',
'not-found': 'plugins.search_not_found',
'network': 'plugins.search_network',
'unsupported': 'plugins.search_unsupported',
'unknown': 'plugins.search_unknown',
}
+/** 宿主 `get_local_plugin_hmr` 的返回:开关值、补丁层路径与当前真正被监听的源码目录。 */
+interface LocalHmrStatus {
+ enabled: boolean
+ watching: boolean
+ patchPath: string | null
+ roots: string[]
+}
+
+/** 原生文件夹选择器只有 Windows 构建提供,其它平台宿主直接拒绝;据此隐藏入口。 */
+function pickFolderSupported(): boolean {
+ try {
+ return type() === 'windows'
+ }
+ catch (error) {
+ console.warn('[ConfigPlugin] failed to read the OS type, hiding the folder picker:', error)
+ return false
+ }
+}
+
+const PICK_FOLDER_SUPPORTED = pickFolderSupported()
+
/**
* 「插件」面板:已安装插件的安装/升级/卸载/禁用/启用全部经 `useDshPluginsManager` 收口
* (队列、授权、Toast、组结算重启由管理器统一负责),面板只保留确认对话框与行内 busy。
@@ -118,6 +141,57 @@ export function ConfigPlugin() {
},
})
+ /** 热重载状态只读展示:补丁层与被监听的源码目录都由后端按已挂载的本地插件算出来。 */
+ const hmr = useQuery({
+ queryKey: queryKeys.localPluginHmr,
+ queryFn: () => invoke<LocalHmrStatus>('get_local_plugin_hmr'),
+ })
+ const setHmr = useMutation({
+ mutationFn: (nextEnabled: boolean) => invoke<LocalHmrStatus>('set_local_plugin_hmr', { enabled: nextEnabled }),
+ onSuccess: (status) => {
+ queryClient.setQueryData(queryKeys.localPluginHmr, status)
+ const key = toast(t('plugins.hmr_restart_hint'), {
+ variant: 'accent',
+ timeout: 10_000,
+ actionProps: {
+ children: t('app.restart'),
+ onPress: () => {
+ store.harness.restart()
+ toast.close(key)
+ },
+ },
+ })
+ },
+ onError: (error: unknown) => {
+ console.error('[ConfigPlugin] local plugin hot reload update failed:', error)
+ toast(t('plugins.hmr_save_failed'), { variant: 'danger' })
+ },
+ })
+
+ /**
+ * 目录选择器只把选中的目录回填进安装框(`link:` spec),安装仍走与手打完全相同的链路:
+ * 用户可以先核对路径再点安装,也能就地改掉。
+ */
+ async function onPickLocalDir() {
+ if (installing)
+ return
+ setInstalling(true)
+ try {
+ const spec = await invoke<string | null>('pick_local_plugin_dir')
+ if (spec == null)
+ return
+ setInstallRef(spec)
+ setSearchResults(null)
+ }
+ catch (e) {
+ console.error('[ConfigPlugin] pick local plugin dir failed:', e)
+ toast(t('plugins.local_dir_failed'), { variant: 'danger' })
+ }
+ finally {
+ setInstalling(false)
+ }
+ }
+
/** 该插件在管理器队列里的进程类型(不在队列里为 null)。 */
function queuedType(id: string): PluginProcess['type'] | null {
return manager.processes.find(process => process.name === id)?.type ?? null
@@ -597,7 +671,7 @@ export function ConfigPlugin() {
<div className="flex flex-col gap-4">
{/* 安装入口:接受 npm spec(可逗号/空白分隔多个),先经管理器只读预检再入队 */}
<div className="flex flex-col gap-2">
- <div className="flex items-center gap-2 px-1">
+ <div className="flex items-center gap-2">
<Input
variant="secondary"
className="h-8 flex-1 font-mono text-xs"
@@ -622,6 +696,24 @@ export function ConfigPlugin() {
{t('plugins.install')}
</span>
</Button>
+ <If cond={PICK_FOLDER_SUPPORTED}>
+ <Tooltip delay={0}>
+ <Button
+ isIconOnly
+ size="sm"
+ variant="tertiary"
+ className="size-8 shrink-0"
+ isDisabled={installing}
+ aria-label={t('plugins.local_dir')}
+ onPress={() => void onPickLocalDir()}
+ >
+ <FolderOpen />
+ </Button>
+ <Tooltip.Content className="max-w-[320px]">
+ <p>{t('plugins.local_dir')}</p>
+ </Tooltip.Content>
+ </Tooltip>
+ </If>
</div>
<If cond={searchResults != null}>
<div className="flex flex-col gap-1 px-1">
@@ -649,6 +741,29 @@ export function ConfigPlugin() {
</If>
</div>
+ <div className="flex flex-col gap-1 px-1">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-ink">{t('plugins.hmr')}</span>
+ <Switch
+ size="sm"
+ isSelected={hmr.data?.enabled ?? false}
+ isDisabled={hmr.isFetching || setHmr.isPending}
+ onChange={enabled => setHmr.mutate(enabled)}
+ aria-label={t('plugins.hmr')}
+ >
+ <Switch.Content>
+ <Switch.Control>
+ <Switch.Thumb />
+ </Switch.Control>
+ </Switch.Content>
+ </Switch>
+ </div>
+ <Description className="text-[10px] text-muted/70">{t('plugins.hmr_hint')}</Description>
+ <If cond={hmr.data != null && !hmr.data.watching}>
+ <Description className="text-[10px] text-warning">{t('plugins.hmr_idle')}</Description>
+ </If>
+ </div>
+
<If cond={managedPlugins.length > 0} else={<Empty>{t('plugins.empty')}</Empty>}>
{managedPlugins.map(plugin => renderPluginRow(plugin))}
</If>
diff --git a/src/ui/dialog/config.tsx b/src/ui/dialog/config.tsx
index 385a2708..b2238870 100644
--- a/src/ui/dialog/config.tsx
+++ b/src/ui/dialog/config.tsx
@@ -55,7 +55,7 @@ export function ConfigDialog(props: ConfigDialogProps) {
<Modal isOpen={disclosure.visible} onOpenChange={disclosure.cancel}>
<Modal.Backdrop>
<Modal.Container size="lg">
- <Modal.Dialog data-testid="dsh-config-dialog" className="w-[800px] max-w-[calc(100vw-48px)] h-[min(720px,calc(100vh-96px))] pr-2.5">
+ <Modal.Dialog data-testid="dsh-config-dialog" className="w-[840px] max-w-[calc(100vw-48px)] h-[min(720px,calc(100vh-96px))] pr-2.5">
<Modal.CloseTrigger data-testid="dsh-config-dialog-close" />
<Modal.Header className="mb-3">
<Modal.Heading>
@@ -90,7 +90,7 @@ export function ConfigDialog(props: ConfigDialogProps) {
})}
</nav>
</aside>
- <div data-testid="dsh-config-panel-body" className="flex flex-col flex-1 overflow-auto min-h-0 pr-2.5">
+ <div data-testid="dsh-config-panel-body" className="flex flex-col flex-1 overflow-auto min-h-0 pr-2.5 px-1">
<Switch value={activeTab} as="div">
<Case cond="application">
<ConfigDebug />
diff --git a/test/data-dir.test.ts b/test/data-dir.test.ts
index ed17ddba..01b66039 100644
--- a/test/data-dir.test.ts
+++ b/test/data-dir.test.ts
@@ -101,8 +101,8 @@ describe('migration safety contract', () => {
})
it('never links the new home into place', () => {
- const source = readSource(MIGRATE)
- expect(source).not.toContain('symlink')
+ const source = readSource(MIGRATE).split('#[cfg(test)]')[0]
+ expect(source).not.toMatch(/\bsymlink(?:_dir|_file)?\b/)
expect(source).not.toContain('junction')
expect(source).toContain('fs_ops::copy_tree(source, target, &progress)?;')
})
diff --git a/test/pet-dragging.test.ts b/test/pet-dragging.test.ts
new file mode 100644
index 00000000..76f5b41b
--- /dev/null
+++ b/test/pet-dragging.test.ts
@@ -0,0 +1,76 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest'
+import { readSource } from './setup/read-source'
+
+describe('pet dragging follows the pointer (upstream spring feel)', () => {
+ const hook = readSource('src/hooks/use-window-draggable.ts')
+ const app = readSource('src/pet/app.tsx')
+ const cursorEvents = readSource('src/hooks/use-omit-ignore-cursor-events.ts')
+ const physics = readSource('src/pet/hooks/use-pet-physics.ts')
+
+ // 只守住跨文件的接线契约;弹簧积分、门槛、收尾等行为由
+ // `src/hooks/use-window-draggable.test.ts` 的 jsdom 用例覆盖。
+ it('drives the window from the backend cursor stream instead of DOM deltas', () => {
+ expect(hook).toContain('\'device-mouse-move\'')
+ expect(hook).toContain('\'device-mouse-button\'')
+ expect(hook).toContain('.setPosition(')
+ // 文档注释里会提到原生 `startDragging()` 作为对照,这里断言的是不再调用它。
+ expect(hook).not.toContain('.startDragging(')
+ })
+
+ it('uses the upstream playground spring constants for the follow motion', () => {
+ expect(hook).toContain('const FOLLOW_STIFFNESS = 200')
+ expect(hook).toContain('const FOLLOW_DAMPING = 30')
+ expect(hook).toContain('const DRAG_START_THRESHOLD = 5')
+ expect(hook).toContain('const DRAG_DIRECTION_THRESHOLD = 3')
+ })
+
+ it('passes the pointer lifecycle from the hitbox to the drag hook', () => {
+ expect(app).toContain('onHitboxPointerDown={draggable.onPointerDown}')
+ expect(app).toContain('onHitboxPointerUp={draggable.onPointerUp}')
+ // 跟手不依赖 DOM pointermove(窗口移动会让 clientX 反向变化),也不认
+ // pointercancel(穿透态切换会取消指针会话)。
+ expect(app).not.toContain('onHitboxPointerMove=')
+ expect(app).not.toContain('onHitboxPointerCancel=')
+ })
+
+ it('keeps the window interactive while dragging so the release is delivered', () => {
+ expect(app).toContain('useOmitIgnoreCursorEvents(hitboxRef, draggable.dragging)')
+ expect(cursorEvents).toContain('dragging = false')
+ })
+
+ it('brakes a thrown pet only on a real grab, never on a click elsewhere', () => {
+ // 抓取信号来自命中箱 pointerdown,经拖拽 hook 的 onGrab 转给甩动物理。
+ expect(app).toContain('useWindowDraggable({ onGrab: handleGrab, onRelease, clampPosition })')
+ expect(app).toContain('const { onFling, onGrab, onRelease } = usePetPhysics(pet, source?.kind)')
+ expect(hook).toContain('onGrabRef.current?.()')
+ // 全屏左键流只用来取「松开」时刻:任何位置的按下都不能刹车。
+ expect(physics).toContain('if (payload.pressed)')
+ expect(physics).toContain('export interface PetPhysicsControls')
+ })
+
+ it('routes both release paths through one idempotent physics release', () => {
+ // 命中箱 pointerup 与后端设备流汇到同一个 `onRelease`,同一个手势只结算一次:
+ // 设备流丢事件时物理层不会一直以为还按着,把很久以后一次无关点击当成甩出。
+ expect(hook).toContain('onRelease?: () => void')
+ expect(hook).toContain('onReleaseRef.current?.()')
+ expect(physics).toContain('function onRelease(): void {')
+ expect(physics).toContain('return { onFling, onGrab, onRelease }')
+ expect(physics).toContain('onRelease: () => void')
+ })
+
+ it('clamps every follow frame to the pet body bounds so edge drops stay on the edge', () => {
+ // 跟手每帧夹取(上游 `getBounds` 的等价物),边界与飞行共用 `bodyBounds`。
+ expect(app).toContain('const { clampPosition, refreshWorkAreas } = usePetWindowClamp(pet, source?.kind)')
+ expect(hook).toContain('clampRef.current({ x: gesture.x, y: gesture.y })')
+ expect(readSource('src/pet/hooks/use-pet-window-clamp.ts')).toContain('bodyBounds(geometry, stage.width, stage.height, dsh)')
+ // 收尾只落盘:整窗夹取会把贴边松手的宠物推开一段(透明留白的宽度)。
+ expect(hook).toContain('void invoke(\'persist_pet_window_position\').catch(() => {})')
+ expect(hook).not.toContain('invoke(\'move_pet_window\'')
+ })
+
+ it('recomputes click-through when the window itself moves', () => {
+ // 甩出时窗口在动、光标不动:`Moved` 之后要按最近光标样本重算命中。
+ expect(cursorEvents).toContain('refreshWindowPosition().then(refreshFromState)')
+ })
+})