DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(desktop): 多窗口按 Profile 隔离核心实例 (#1084)
Hairy0fe6d70380f6
diff --git a/src-tauri/src/bridge/backup.rs b/src-tauri/src/bridge/backup.rsindex e602a045..750118ae 100644--- a/src-tauri/src/bridge/backup.rs+++ b/src-tauri/src/bridge/backup.rs@@ -1,89 +1,112 @@//! 备份 / 还原 Tauri 命令。-//!-//! 薄封装:把 IPC 参数转成 `service::backup` 的调用,遵循 `bridge/profile.rs`-//! → `service::profile` 的分层模式。备份 / 还原均为异步命令,IO 密集的-//! 归档操作通过 `spawn_blocking` 脱离异步运行时,避免阻塞 UI。-use tauri::AppHandle;+use tauri::{AppHandle, WebviewWindow};-use crate::service::backup;+use crate::service::{backup, workflow::instances};#[tauri::command]pub async fn export_recovery_backup(app_handle: AppHandle,+ window: WebviewWindow,include_credentials: bool,) -> Result<backup::BackupInfo, String> {- let transition = crate::service::workflow::acquire_core_transition().await?;- let operation = crate::service::plugin::acquire_operation_lock().await;- crate::service::workflow::stop(app_handle.clone()).await?;- let source = crate::config::get_dsh_data_path(&app_handle);- let app_data = crate::config::get_base_dir(&app_handle);- tauri::async_runtime::spawn_blocking(move || {- let _transition = transition;- let _operation = operation;- backup::recovery::export(&source, &app_data, include_credentials)+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile.clone(), async move {+ let transition = crate::service::workflow::acquire_core_transition().await?;+ let operation = crate::service::plugin::acquire_operation_lock().await;+ crate::service::workflow::stop(app_handle.clone()).await?;+ let source = crate::config::get_dsh_data_path(&app_handle);+ let app_data = crate::config::get_base_dir(&app_handle);+ tauri::async_runtime::spawn_blocking(move || {+ instances::scope_sync(profile, || {+ let _transition = transition;+ let _operation = operation;+ backup::recovery::export(&source, &app_data, include_credentials)+ })+ })+ .await+ .map_err(|e| format!("RECOVERY_TASK: {e}"))?}).await- .map_err(|e| format!("RECOVERY_TASK: {e}"))?}-/// 创建当前 profile 的备份(不包含共享会话与工作区数据)。-///-/// 异步命令:zstd 多线程压缩 + 目录遍历在 `spawn_blocking` 线程池执行。#[tauri::command]pub async fn backup_profile(app_handle: AppHandle,+ window: WebviewWindow,include_credentials: bool,) -> Result<backup::BackupInfo, String> {- let app = app_handle.clone();+ let profile = instances::window_profile(&app_handle, window.label());let result = tauri::async_runtime::spawn_blocking(move || {- backup::create_backup(- &app,- backup::BackupOptions { include_credentials },- )+ instances::scope_sync(profile, || {+ backup::create_backup(+ &app_handle,+ backup::BackupOptions {+ include_credentials,+ },+ )+ })}).await.map_err(|e| format!("BACKUP_TASK: {e}"))?;match &result {- Ok(info) => log::info!("[backup] 创建成功: {} ({} bytes)", info.timestamp, info.size),+ Ok(info) => log::info!(+ "[backup] 创建成功: {} ({} bytes)",+ info.timestamp,+ info.size+ ),Err(e) => log::error!("[backup] 创建失败: {e}"),}result}-/// 从指定备份还原。-///-/// `as_new` = true 时创建新档案目录;false 时覆盖当前激活的 profile。-/// 异步命令:zstd 解压在 `spawn_blocking` 线程池执行。#[tauri::command]pub async fn restore_profile(app_handle: AppHandle,+ window: WebviewWindow,timestamp: String,as_new: bool,) -> Result<(), String> {- let mode = if as_new {- backup::RestoreMode::AsNew- } else {- backup::RestoreMode::Overwrite- };- let app = app_handle.clone();- tauri::async_runtime::spawn_blocking(move || {- backup::restore_backup(&app, ×tamp, mode)+ let transition = crate::service::workflow::acquire_core_transition().await?;+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile.clone(), async move {+ let mode = if as_new {+ backup::RestoreMode::AsNew+ } else {+ if instances::attached_elsewhere(&profile, window.label()) {+ return Err("PROFILE_IN_USE: detach other windows before restoring profile".into());+ }+ crate::service::workflow::stop(app_handle.clone()).await?;+ backup::RestoreMode::Overwrite+ };+ tauri::async_runtime::spawn_blocking(move || {+ instances::scope_sync(profile, || {+ let _transition = transition;+ backup::restore_backup(&app_handle, ×tamp, mode)+ })+ })+ .await+ .map_err(|e| format!("RESTORE_TASK: {e}"))?}).await- .map_err(|e| format!("RESTORE_TASK: {e}"))?}-/// 列出所有备份。#[tauri::command]-pub fn list_backups(app_handle: AppHandle) -> Vec<backup::BackupInfo> {- backup::list_backups(&app_handle)+pub fn list_backups(app_handle: AppHandle, window: WebviewWindow) -> Vec<backup::BackupInfo> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || backup::list_backups(&app_handle))}-/// 删除指定备份。#[tauri::command]-pub async fn delete_backup(app_handle: AppHandle, timestamp: String) -> Result<(), String> {- tauri::async_runtime::spawn_blocking(move || backup::delete_backup(&app_handle, ×tamp))- .await- .map_err(|e| format!("BACKUP_DELETE_TASK: {e}"))?+pub async fn delete_backup(+ app_handle: AppHandle,+ window: WebviewWindow,+ timestamp: String,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ tauri::async_runtime::spawn_blocking(move || {+ instances::scope_sync(profile, || backup::delete_backup(&app_handle, ×tamp))+ })+ .await+ .map_err(|e| format!("BACKUP_DELETE_TASK: {e}"))?}diff --git a/src-tauri/src/bridge/config.rs b/src-tauri/src/bridge/config.rsindex 29db07e0..e5b2dc89 100644--- a/src-tauri/src/bridge/config.rs+++ b/src-tauri/src/bridge/config.rs@@ -9,8 +9,18 @@ use tauri::AppHandle;/// 当前桌面端配置#[tauri::command]-pub async fn get_app_config(app_handle: AppHandle) -> Result<config::Setting, String> {- Ok(config::get_store_dat_setting(&app_handle))+pub async fn get_app_config(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<config::Setting, String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let mut setting = config::get_store_dat_setting(&app_handle);+ setting.active_profile = crate::service::profile::active_profile(&app_handle);+ setting.port = crate::service::workflow::instances::port(&app_handle);+ Ok(setting)+ })+ .await}/// 当前设置下 Harness 进程实际生效的 V8 old-space 上限(MB)。@@ -47,6 +57,7 @@ pub fn is_dev_build() -> bool {#[tauri::command]#[allow(clippy::too_many_arguments)]pub async fn update_app_config(+ window: tauri::WebviewWindow,app_handle: AppHandle,proxy_url: Option<String>,appearance: Option<config::Appearance>,@@ -112,6 +123,12 @@ pub async fn update_app_config(setting.backup_include_credentials = include;}});+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ let mut setting = setting;+ setting.active_profile = profile.clone();+ setting.port = crate::service::workflow::instances::scope_sync(profile, || {+ crate::service::workflow::instances::port(&app_handle)+ });Ok(setting)}diff --git a/src-tauri/src/bridge/core.rs b/src-tauri/src/bridge/core.rsindex f4186496..645ccbda 100644--- a/src-tauri/src/bridge/core.rs+++ b/src-tauri/src/bridge/core.rs@@ -18,19 +18,24 @@ pub async fn get_cores(app_handle: AppHandle) -> Vec<core::HarnessCore> {/// 互换;自动重启由前端负责)#[tauri::command]pub async fn set_active_core(+ window: tauri::WebviewWindow,app_handle: AppHandle,id: String,) -> Result<core::HarnessCore, String> {- core::set_active(&app_handle, &id).await+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, core::set_active(&app_handle, &id)).await}/// 下载指定 tag 的预打包核心到历史槽位(不激活;切换由 `set_active_core` 完成)#[tauri::command]pub async fn download_core(+ window: tauri::WebviewWindow,app_handle: AppHandle,tag: String,) -> Result<core::HarnessCore, String> {- core::download_version(&app_handle, &tag).await+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, core::download_version(&app_handle, &tag))+ .await}/// 卸载已下载的历史版本(激活中的版本不可卸载)@@ -42,6 +47,13 @@ pub async fn remove_core(app_handle: AppHandle, id: String) -> Result<(), String/// 通过用户包管理器 CLI 更新本地核心(npm `install -g @latest` //// pnpm `add -g @latest`),返回更新后的版本号。#[tauri::command]-pub async fn update_local_core(app_handle: AppHandle) -> Result<String, String> {- core::update_local_core(app_handle).await+pub async fn update_local_core(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<String, String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ core::update_local_core(app_handle).await+ })+ .await}diff --git a/src-tauri/src/bridge/data_dir.rs b/src-tauri/src/bridge/data_dir.rsindex 303e3e6a..018b6942 100644--- a/src-tauri/src/bridge/data_dir.rs+++ b/src-tauri/src/bridge/data_dir.rs@@ -12,22 +12,28 @@ use tauri::AppHandle;use crate::service::data_dir;// stop 会删掉本通道标记;不可读的先拒绝,已记录的 PID 留到停服后复核。-fn reject_unreadable_markers(recorded: [data_dir::HarnessMarker; 2]) -> Result<(), String> {+fn reject_unreadable_markers(+ recorded: impl IntoIterator<Item = data_dir::HarnessMarker>,+) -> Result<(), String> {use data_dir::HarnessMarker;recorded.into_iter()- .zip(crate::config::HARNESS_PID_MARKER_NAMES)- .try_for_each(|(marker, name)| match marker {+ .enumerate()+ .try_for_each(|(index, marker)| match marker {HarnessMarker::Invalid => Err(format!(- "DATA_DIR_HARNESS_MARKER_INVALID: {name} 读不出来,无法确认 Harness 是否已退出,请先退出所有实例再重试"+ "DATA_DIR_HARNESS_MARKER_INVALID: {} 读不出来,无法确认 Harness 是否已退出,请先退出所有实例再重试",+ crate::config::HARNESS_PID_MARKER_NAMES[index % 2])),HarnessMarker::Missing | HarnessMarker::Pid(_) => Ok(()),})}// DSH_HOME 仍然共享;只报告另一个通道的存活进程,不能替用户结束它。-fn confirm_harness_stopped(recorded: [data_dir::HarnessMarker; 2]) -> Result<(), String> {- reject_unreadable_markers(recorded)?;+fn confirm_harness_stopped(+ recorded: impl IntoIterator<Item = data_dir::HarnessMarker>,+) -> Result<(), String> {+ let recorded: Vec<_> = recorded.into_iter().collect();+ reject_unreadable_markers(recorded.clone())?;for marker in recorded {if let data_dir::HarnessMarker::Pid(pid) = marker {if data_dir::process_alive(pid) {@@ -93,42 +99,56 @@ pub async fn preview_data_dir_migration(/// 任务结束,期间任何安装 / 备份 / 核心切换请求都会排队等待。#[tauri::command]pub async fn migrate_data_dir(+ window: tauri::WebviewWindow,app_handle: AppHandle,parent: String,leaf: String,) -> Result<data_dir::MigrationOutcome, String> {- let transition = crate::service::workflow::acquire_core_transition().await?;- let operation = crate::service::plugin::acquire_operation_lock().await;- // 标记要在 `stop()` 之前读:停成功时它会顺手删掉标记,删掉之后就再也查不出- // 「崩溃残留、不在 owned 注册表里的 Harness」是否还在写这个目录。- let recorded = data_dir::harness_markers(&crate::config::get_dsh_data_path(&app_handle));- reject_unreadable_markers(recorded)?;- crate::service::workflow::stop(app_handle.clone()).await?;- confirm_harness_stopped(recorded)?;- let app = app_handle.clone();- let result = data_dir::migrate(app, PathBuf::from(parent), leaf).await;- drop(transition);- drop(operation);- result+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let transition = crate::service::workflow::acquire_core_transition().await?;+ crate::service::workflow::instances::require_exclusive_profile()?;+ let operation = crate::service::plugin::acquire_operation_lock().await;+ // 标记要在 `stop()` 之前读:停成功时它会顺手删掉标记,删掉之后就再也查不出+ // 「崩溃残留、不在 owned 注册表里的 Harness」是否还在写这个目录。+ let recorded =+ data_dir::all_harness_markers(&crate::config::get_dsh_data_path(&app_handle));+ reject_unreadable_markers(recorded.clone())?;+ crate::service::workflow::stop(app_handle.clone()).await?;+ confirm_harness_stopped(recorded)?;+ let app = app_handle.clone();+ let result = data_dir::migrate(app, PathBuf::from(parent), leaf).await;+ drop(transition);+ drop(operation);+ result+ })+ .await}/// 回滚到旧目录备份(`backup` 为空时按「会话数优先、时间戳其次」自动挑选)。#[tauri::command]pub async fn rollback_data_dir(+ window: tauri::WebviewWindow,app_handle: AppHandle,backup: Option<String>,) -> Result<data_dir::MigrationOutcome, String> {- let transition = crate::service::workflow::acquire_core_transition().await?;- let operation = crate::service::plugin::acquire_operation_lock().await;- let recorded = data_dir::harness_markers(&crate::config::get_dsh_data_path(&app_handle));- reject_unreadable_markers(recorded)?;- crate::service::workflow::stop(app_handle.clone()).await?;- confirm_harness_stopped(recorded)?;- let app = app_handle.clone();- let result = data_dir::rollback(app, backup.map(PathBuf::from)).await;- drop(transition);- drop(operation);- result+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let transition = crate::service::workflow::acquire_core_transition().await?;+ crate::service::workflow::instances::require_exclusive_profile()?;+ let operation = crate::service::plugin::acquire_operation_lock().await;+ let recorded =+ data_dir::all_harness_markers(&crate::config::get_dsh_data_path(&app_handle));+ reject_unreadable_markers(recorded.clone())?;+ crate::service::workflow::stop(app_handle.clone()).await?;+ confirm_harness_stopped(recorded)?;+ let app = app_handle.clone();+ let result = data_dir::rollback(app, backup.map(PathBuf::from)).await;+ drop(transition);+ drop(operation);+ result+ })+ .await}#[cfg(test)]diff --git a/src-tauri/src/bridge/lifecycle.rs b/src-tauri/src/bridge/lifecycle.rsindex 4cc4c0d7..c7d5cc84 100644--- a/src-tauri/src/bridge/lifecycle.rs+++ b/src-tauri/src/bridge/lifecycle.rs@@ -78,7 +78,13 @@ fn sync_cli_link(app_handle: &AppHandle) {////// 启动逻辑由前端显式调用 `launch_harness` 完成,避免重复拉起进程。#[tauri::command]-pub async fn install_dependencies(app_handle: AppHandle) -> Result<bool, String> {+pub async fn install_dependencies(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<bool, String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+// 并发/重入防护:使用独立互斥锁而非依赖 Status::Installing——// 失败路径会复位状态,若用状态判断则一次失败后所有后续调用都会被// “Installation process already running” 静默跳过直到重启应用。@@ -273,6 +279,8 @@ pub async fn install_dependencies(app_handle: AppHandle) -> Result<bool, String>config::set_store_dat_setting(&app_handle, setting);sync_cli_link(&app_handle);Ok(updated)++ }).await}/// 静默检查是否有新版 Harness 可用(只查不装,供进入页面后后台调用)@@ -355,20 +363,42 @@ pub async fn check_dsh_update(/// 启动 Harness 服务#[tauri::command]-pub async fn launch_harness(app_handle: AppHandle) -> Result<(), String> {- workflow::launch(app_handle).await+pub async fn launch_harness(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<(), String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ workflow::launch(app_handle).await+ })+ .await}/// 停止 Harness 服务#[tauri::command]-pub async fn shutdown_harness(app_handle: AppHandle) -> Result<(), String> {- workflow::stop(app_handle).await+pub async fn shutdown_harness(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<(), String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(+ profile,+ async move { workflow::stop(app_handle).await },+ )+ .await}/// 重启 Harness 服务#[tauri::command]-pub async fn restart_harness(app_handle: AppHandle) -> Result<(), String> {- workflow::restart(app_handle).await+pub async fn restart_harness(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<(), String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ workflow::restart(app_handle).await+ })+ .await}/// 进入安全模式:确保安全档案存在并切换为当前档案(不重启,由前端走标准重启链路)。@@ -393,21 +423,35 @@ pub async fn restart_harness(app_handle: AppHandle) -> Result<(), String> {/// 而不是假装已恢复。#[tauri::command]pub async fn enter_safe_mode(+ window: tauri::WebviewWindow,app_handle: AppHandle,) -> Result<crate::service::plugin::PatchQuarantineReport, String> {- crate::service::profile::ensure_safe_profile(&app_handle)?;- let report = crate::service::plugin::quarantine_patch_layers_in(- &crate::service::profile::profile_dir_of(- &app_handle,+ let _transition = crate::service::workflow::acquire_core_transition().await?;+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ crate::service::profile::ensure_safe_profile(&app_handle)?;+ let report = crate::service::plugin::quarantine_patch_layers_in(+ &crate::service::profile::profile_dir_of(+ &app_handle,+ crate::service::profile::SAFE_PROFILE,+ ),+ &config::get_dsh_data_path(&app_handle),+ );+ if report.has_failures() {+ return Err(crate::service::plugin::quarantine_failure_message(&report));+ }+ let old = crate::service::profile::active_profile(&app_handle);+ crate::service::profile::set_active(&app_handle, crate::service::profile::SAFE_PROFILE)?;+ crate::service::workflow::instances::bind_window(+ window.label(),crate::service::profile::SAFE_PROFILE,- ),- &config::get_dsh_data_path(&app_handle),- );- if report.has_failures() {- return Err(crate::service::plugin::quarantine_failure_message(&report));- }- crate::service::profile::set_active(&app_handle, crate::service::profile::SAFE_PROFILE)?;- Ok(report)+ );+ if !crate::service::workflow::instances::is_attached(&old) {+ workflow::stop(app_handle.clone()).await?;+ }+ Ok(report)+ })+ .await}/// 隔离解析失败的补丁层:当前档案层 + home 层(错误页「隔离损坏的补丁文件」入口)。@@ -419,13 +463,18 @@ pub async fn enter_safe_mode(/// 会立刻回到同一个解析失败。#[tauri::command]pub async fn quarantine_broken_patch_layers(+ window: tauri::WebviewWindow,app_handle: AppHandle,) -> Result<crate::service::plugin::PatchQuarantineReport, String> {- let report = crate::service::plugin::quarantine_active_patch_layers(&app_handle);- if report.has_failures() {- return Err(crate::service::plugin::quarantine_failure_message(&report));- }- Ok(report)+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let report = crate::service::plugin::quarantine_active_patch_layers(&app_handle);+ if report.has_failures() {+ return Err(crate::service::plugin::quarantine_failure_message(&report));+ }+ Ok(report)+ })+ .await}/// 移除补丁层里解析不到包的 `insert` 条目(错误页「移除悬空条目」入口)。@@ -439,15 +488,24 @@ pub async fn quarantine_broken_patch_layers(/// 移除的正是预检报出的那批条目;没有可移除项时返回空报告,前端照常重启。#[tauri::command]pub async fn strip_unresolved_patch_entries(+ window: tauri::WebviewWindow,app_handle: AppHandle,) -> Result<crate::service::plugin::PatchEntryStripReport, String> {- crate::service::plugin::strip_active_unresolved_entries(&app_handle)+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ crate::service::plugin::strip_active_unresolved_entries(&app_handle)+ })+ .await}/// 获取当前 Harness 服务状态#[tauri::command]-pub fn get_dsh_status() -> workflow::status::Status {- workflow::status::get_status()+pub fn get_dsh_status(+ app_handle: AppHandle,+ window: tauri::WebviewWindow,+) -> workflow::status::Status {+ let profile = workflow::instances::window_profile(&app_handle, window.label());+ workflow::instances::scope_sync(profile, workflow::status::get_status)}/// 运行时文件是否已全部在盘(Node / Dsh / pnpm;Windows 还要求 Git 可用,diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rsindex 34d9e695..1ed11315 100644--- a/src-tauri/src/bridge/plugin.rs+++ b/src-tauri/src/bridge/plugin.rs@@ -1,14 +1,8 @@//! 预装与已安装插件的增删改查、管理。-//!-//! 包括首次启动的预装插件引导(安装/取消/跳过/待办检测/打开仓库)、已安装-//! 插件的列表/升级/卸载,以及运行期异常的记录与「卸除此插件并继续检测」修复。use crate::config;-use crate::service::plugin;-use tauri::AppHandle;-use tauri::Emitter;-#[cfg(windows)]-use tauri::Manager;+use crate::service::{plugin, workflow::instances};+use tauri::{AppHandle, WebviewWindow};use tauri_plugin_opener::OpenerExt;fn mark_preinstall_done(app_handle: &AppHandle) {@@ -20,168 +14,168 @@ fn mark_preinstall_done(app_handle: &AppHandle) {config::set_store_dat_setting(app_handle, setting);}-/// 获取预装插件列表(含已安装检测结果),首次启动引导界面渲染用#[tauri::command]pub async fn get_preinstall_plugins(app_handle: AppHandle,+ window: WebviewWindow,) -> Result<Vec<plugin::PreinstallPlugin>, String> {- Ok(plugin::list(&app_handle))+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async { Ok(plugin::list(&app_handle)) }).await}-/// 安装选中的预装插件(`dsh plugin --profile web add <ids...>`),-/// 进程输出实时通过 `preinstall-log` 事件推送;成功后标记引导完成并记录预设指纹。-///-/// 同时支持卸载用户取消勾选的已安装插件(`uninstall_ids`):走-/// `dsh plugin remove`(与安装对称的命令行卸载),失败时自动回退离线精准卸载-/// (`plugin::uninstall_recovery`,直接改 profile 清单),不依赖网络兜底。#[tauri::command]pub async fn install_preinstall_plugins(app_handle: AppHandle,+ window: WebviewWindow,install_ids: Vec<String>,uninstall_ids: Vec<String>,) -> Result<(), String> {- // 安装与卸载均为空:无需操作,直接标记完成- if install_ids.is_empty() && uninstall_ids.is_empty() {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ if !uninstall_ids.is_empty() {+ plugin::remove_many(&app_handle, &uninstall_ids).await?;+ }+ if !install_ids.is_empty() {+ plugin::install(&app_handle, &install_ids).await?;+ }mark_preinstall_done(&app_handle);- return Ok(());- }-- // 先卸载取消勾选的已安装插件(走 dsh plugin remove,与安装对称)- // 卸载在前:避免新装插件与待卸载插件冲突;remove 内部会先停服务再执行- log::info!("[preinstall] uninstall_ids={uninstall_ids:?}, install_ids={install_ids:?}");- if !uninstall_ids.is_empty() {- log::info!("[preinstall] removing plugins {uninstall_ids:?} via dsh plugin remove");- plugin::remove_many(&app_handle, &uninstall_ids)- .await- .map_err(|e| {- log::error!("[preinstall] failed to remove plugins {uninstall_ids:?}: {e}");- e- })?;- log::info!("[preinstall] successfully removed plugins {uninstall_ids:?}");- }-- // 再安装新勾选的插件(会走 dsh plugin add)- if !install_ids.is_empty() {- log::info!("[preinstall] installing plugins {install_ids:?}");- plugin::install(&app_handle, &install_ids).await?;- }-- mark_preinstall_done(&app_handle);- Ok(())+ Ok(())+ })+ .await}-/// 取消正在进行的插件进程(安装/升级/卸载,网络抖动/限流卡住时用户点“取消”)。#[tauri::command]pub async fn cancel_plugin_processes(app_handle: AppHandle) {plugin::cancel(&app_handle).await;}-/// 按原始 spec 安装插件(插件市场 / 手动输入 entry):支持一次传入多个 spec,-/// 合并为单次 `dsh plugin add` 执行,输出同样经 `preinstall-log` 事件推送。-///-/// 与 `install_preinstall_plugins` 的区别只在 spec 来源:此处不走预设清单,-/// 因而没有捆绑目录与版本矩阵,spec 原样交给 pnpm 解析。#[tauri::command]-pub async fn install_plugin_specs(app_handle: AppHandle, specs: Vec<String>) -> Result<(), String> {- plugin::install_specs(&app_handle, &specs).await?;- plugin::watch::force_emit(&app_handle);- Ok(())+pub async fn install_plugin_specs(+ app_handle: AppHandle,+ window: WebviewWindow,+ specs: Vec<String>,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ plugin::install_specs(&app_handle, &specs).await?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+ })+ .await}-/// 本地插件热重载的当前状态:生效开关、补丁层路径与被监听的源码目录。#[tauri::command]-pub async fn get_local_plugin_hmr(app_handle: AppHandle) -> Result<plugin::LocalHmrStatus, String> {- Ok(plugin::local_plugin_hmr_status(&app_handle))+pub async fn get_local_plugin_hmr(+ app_handle: AppHandle,+ window: WebviewWindow,+) -> Result<plugin::LocalHmrStatus, String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ Ok(plugin::local_plugin_hmr_status(&app_handle))+ })+ .await}-/// 开关本地插件热重载:开关变化会立即复算补丁层,下次启动服务时生效。#[tauri::command]pub async fn set_local_plugin_hmr(app_handle: AppHandle,+ window: WebviewWindow,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))+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ 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))+ })+ .await}-/// 只读检查一组 spec 的兼容性(registry `latest` 上的 DSH 家族 peer 依赖),-/// 不改动本地 profile;失败项收敛为结果里的 `problem`,不整体报错。#[tauri::command]pub async fn inspect_plugin_specs(app_handle: AppHandle,+ window: WebviewWindow,specs: Vec<String>,dsh: Option<String>,) -> Result<Vec<plugin::compat::PluginInspect>, String> {- plugin::inspect_specs(&app_handle, &specs, dsh).await+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, plugin::inspect_specs(&app_handle, &specs, dsh)).await}-/// 授予「插件版本豁免」:为被核心版本兼容性拒绝的精确 `包名@版本` 组合写授权。-///-/// 前端在风险提示中让用户逐项确认后调用(授权项来自 `install_preinstall_plugins`-/// 返回的 `PLUGIN_VERSION_INCOMPATIBLE:` 载荷),随后重跑安装;豁免不随插件或-/// 核心升级继承,且只对列出的精确版本 + 运行时版本生效。#[tauri::command]pub async fn allow_plugin_versions(app_handle: AppHandle,+ window: WebviewWindow,versions: Vec<plugin::IncompatibleVersion>,) -> Result<(), String> {- plugin::allow_version_exemptions(&app_handle, &versions).await+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(+ profile,+ plugin::allow_version_exemptions(&app_handle, &versions),+ )+ .await}-/// 记录发布时长策略豁免:用户确认接受「刚发布、还在 24 小时窗口内」的精确版本后调用。-///-/// 授权项来自 `PLUGIN_POLICY_BLOCKED:` 载荷(pnpm 的 `minimumReleaseAge` 门禁——档案-/// 已声明这样的版本时,每次插件操作都会失败)。写的是精确 `包名@版本`,只让列出的条目-/// 过闸,其余解析照旧受窗口约束;随后由界面重跑原操作。与 `allow_plugin_versions`-/// (dsh 的版本兼容性豁免,写 `compatibility.json`)是两套互不相干的授权。#[tauri::command]pub async fn allow_plugin_policy_versions(app_handle: AppHandle,+ window: WebviewWindow,versions: Vec<plugin::PolicyBlockedVersion>,expected_profile: Option<String>,) -> Result<(), String> {- plugin::allow_policy_versions(&app_handle, &versions, expected_profile.as_deref())+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ plugin::allow_policy_versions(&app_handle, &versions, expected_profile.as_deref())+ })+ .await}-/// 跳过预装插件引导:记录状态与预设指纹,之后不再弹出(除非清单内容变更)#[tauri::command]-pub async fn skip_preinstall_plugins(app_handle: AppHandle) -> Result<(), String> {- mark_preinstall_done(&app_handle);- Ok(())+pub async fn skip_preinstall_plugins(+ app_handle: AppHandle,+ window: WebviewWindow,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ mark_preinstall_done(&app_handle);+ Ok(())+ })+ .await}-/// 内置插件启动自愈(供前端 boot 流程调用,独立于预装引导「继续/跳过」)。-///-/// 与 service 启动路径(`workflow::launch` 内)共用 `plugin::ensure_internal_plugins`-/// 同一实现:内部有并发锁、幂等,此后启动/重启路径会再核对但均为 no-op。-/// 错误返回前端,由启动状态机按 plugin-install 阶段展示精确错误与重试入口;-/// workflow 自启动路径仍保留最佳努力语义。#[tauri::command]-pub async fn ensure_internal_plugins(app_handle: AppHandle) -> Result<(), String> {- plugin::ensure_internal_plugins(&app_handle).await+pub async fn ensure_internal_plugins(+ app_handle: AppHandle,+ window: WebviewWindow,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, plugin::ensure_internal_plugins(&app_handle)).await}-/// 取消共享的内置插件自愈并等待子进程树退出,供启动阶段超时后清理。#[tauri::command]-pub async fn cancel_internal_plugins() -> Result<(), String> {- plugin::cancel_internal_plugins().await+pub async fn cancel_internal_plugins(+ app_handle: AppHandle,+ window: WebviewWindow,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, plugin::cancel_internal_plugins()).await}-/// 是否有新的预装插件需要引导:预设清单内容与上次记录不一致(或老用户无基线)。-/// 资源文件每次安装都被强制覆盖不可比对,只能比对 app-data 里记录的内容指纹。#[tauri::command]-pub fn get_preinstall_pending(app_handle: AppHandle) -> Result<bool, String> {- Ok(plugin::preinstall_pending(&app_handle))+pub fn get_preinstall_pending(+ app_handle: AppHandle,+ window: WebviewWindow,+) -> Result<bool, String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || Ok(plugin::preinstall_pending(&app_handle)))}-/// 在系统浏览器中打开预装插件的仓库地址(仅允许预装清单内的 id)#[tauri::command]pub async fn open_preinstall_repo(app_handle: AppHandle, id: String) -> Result<(), String> {let url = plugin::repo_url_of(&app_handle, &id)@@ -192,168 +186,191 @@ pub async fn open_preinstall_repo(app_handle: AppHandle, id: String) -> Result<(.map_err(|e| e.to_string())}-/// 当前 profile 已安装插件列表(含解析后的元信息),插件面板首次加载用;-/// 之后 Rust 侧监控插件文件,变化时通过 `dsh-plugins-updated` 事件实时推送。-/// 这里会并入 `updates` 模块的已知更新判定缓存(未判定时 `update_available=false`)。#[tauri::command]-pub fn get_dsh_plugins(app_handle: AppHandle) -> Vec<plugin::DshPlugin> {- let mut plugins = plugin::watch::list(&app_handle);- plugin::update::apply_cache(&app_handle, &mut plugins);- plugins+pub fn get_dsh_plugins(app_handle: AppHandle, window: WebviewWindow) -> Vec<plugin::DshPlugin> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || {+ let mut plugins = plugin::watch::list(&app_handle);+ plugin::update::apply_cache(&app_handle, &mut plugins);+ plugins+ })}-/// 重新探测已安装插件的更新可用性(网络 + 30min 缓存),返回带最新判定结果的列表。-///-/// 与 `get_dsh_plugins` 不同,此处会发起 registry / GitHub 请求(并行、失败静默按-/// 「无更新」处理)。前端在插件面板挂载后调用一次以补齐 `updateAvailable`,使升级-/// 按钮只在确有更新(或异常修复)时出现,而不是常驻。#[tauri::command]pub async fn refresh_plugin_updates(app_handle: AppHandle,+ window: WebviewWindow,) -> Result<Vec<plugin::DshPlugin>, String> {- plugin::update::refresh(&app_handle).await+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, plugin::update::refresh(&app_handle)).await}-/// 批量升级已安装插件:`dsh plugin --profile <当前档案> update <id...> --latest`,-/// 合并为单次子进程执行,输出通过 `preinstall-log` 事件实时推送;升级前逐项-/// 记录依赖指纹,命令返回后核验是否真实落盘(防 pnpm 假成功)。-///-/// `ids` 的每一项是 `<id>` 或 `<id>@<版本>`(保留参数名以免改动前端载荷键):面板显示着-/// 目标版本,带上它核验与显式安装兜底才有据可依(见 `plugin::update_many`)。#[tauri::command]-pub async fn update_dsh_plugins(app_handle: AppHandle, ids: Vec<String>) -> Result<(), String> {- plugin::update_many(&app_handle, &ids).await?;- plugin::watch::force_emit(&app_handle);- Ok(())+pub async fn update_dsh_plugins(+ app_handle: AppHandle,+ window: WebviewWindow,+ ids: Vec<String>,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ plugin::update_many(&app_handle, &ids).await?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+ })+ .await}-/// 批量卸载已安装插件:`dsh plugin --profile <当前档案> remove <ids...>`,-/// 合并为单次子进程执行,输出通过 `preinstall-log` 事件实时推送;命令后逐项核验,-/// 仍残留且可行动的插件回退离线精准卸载(不依赖网络)。#[tauri::command]-pub async fn remove_dsh_plugins(app_handle: AppHandle, ids: Vec<String>) -> Result<(), String> {- plugin::remove_many(&app_handle, &ids).await?;- plugin::watch::force_emit(&app_handle);- Ok(())+pub async fn remove_dsh_plugins(+ app_handle: AppHandle,+ window: WebviewWindow,+ ids: Vec<String>,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ plugin::remove_many(&app_handle, &ids).await?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+ })+ .await}-/// 上报插件运行期异常(内嵌页面 / dsh-tauri 桥调用),记录后立即推送新列表,-/// 并推送 `plugin-recovery-required` 让前端弹出「卸除此插件并继续检测」修复界面。#[tauri::command]pub fn report_plugin_error(app_handle: AppHandle,+ window: WebviewWindow,id: String,error: String,action: Option<String>,) -> Result<(), String> {- plugin::errors::record(- &app_handle,- &id,- action.as_deref().unwrap_or("runtime"),- &error,- )?;- plugin::watch::force_emit(&app_handle);- // 运行期异常:直接推送修复界面(应用仍在运行,前端以醒目对话框呈现)。- let info = plugin::PluginRecoveryInfo {- plugins: vec![id],- reason: "runtime".to_string(),- detail: String::new(),- raw_error: error,- };- let _ = app_handle.emit(plugin::recovery::RECOVERY_REQUIRED_EVENT, &info);- Ok(())+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || {+ plugin::errors::record(+ &app_handle,+ &id,+ action.as_deref().unwrap_or("runtime"),+ &error,+ )?;+ plugin::watch::force_emit(&app_handle);+ let info = plugin::PluginRecoveryInfo {+ plugins: vec![id],+ reason: "runtime".to_string(),+ detail: String::new(),+ raw_error: error,+ };+ instances::emit(+ &app_handle,+ plugin::recovery::RECOVERY_REQUIRED_EVENT,+ &info,+ );+ Ok(())+ })}-/// 从启动日志定位导致启动失败的问题插件(含归属到配置根插件)。-///-/// 前端在启动失败时已读过服务日志(`read_service_logs`),这里直接传入日志行,-/// 由 Rust 侧按错误特征提取引用并做证据式归属;未定位到具体插件时 `plugins` 为空。#[tauri::command]pub fn detect_plugin_recovery(app_handle: AppHandle,+ window: WebviewWindow,logs: Vec<String>,) -> plugin::PluginRecoveryInfo {- plugin::detect_recovery(&app_handle, &logs)+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || plugin::detect_recovery(&app_handle, &logs))}-/// 修复模式卸载单个插件:直接改 profile 清单(离线、精准),成功后推送新插件列表。-///-/// 与 `remove_dsh_plugins`(走 `dsh plugin remove`)不同,此命令不依赖网络,专用于-/// 「插件异常修复」场景;前端随后 `restart()` 重启并重新检测。#[tauri::command]-pub fn recover_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {- plugin::uninstall_recovery(&app_handle, &id)?;- plugin::watch::force_emit(&app_handle);- Ok(())+pub fn recover_plugin(+ app_handle: AppHandle,+ window: WebviewWindow,+ id: String,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || {+ plugin::uninstall_recovery(&app_handle, &id)?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+ })}-/// 禁用单个已安装插件:在 profile 的 `cordis.patch.yml` 写入 `disabled: true` 覆盖-/// (与官方 Plugins 页 / dshmarket 同一处状态)。与卸载不同,禁用保留 node_modules-/// 内的包体与 `dsh.profile.bundles` 选择,启用时无需重新下载。#[tauri::command]-pub fn disable_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {- plugin::disable(&app_handle, &id)?;- plugin::watch::force_emit(&app_handle);- Ok(())+pub fn disable_dsh_plugin(+ app_handle: AppHandle,+ window: WebviewWindow,+ id: String,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || {+ plugin::disable(&app_handle, &id)?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+ })}-/// 启用单个已禁用的插件:摘除 patch 里该插件的禁用覆盖(其余配置保留)。-///-/// 未能摘除时会返回 `ENABLE_NOT_DISABLED`,避免「声称启用成功、运行期却仍被禁用」-/// 的虚假成功(issue #399)。#[tauri::command]-pub fn enable_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {- plugin::enable(&app_handle, &id)?;- plugin::watch::force_emit(&app_handle);- Ok(())+pub fn enable_dsh_plugin(+ app_handle: AppHandle,+ window: WebviewWindow,+ id: String,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || {+ plugin::enable(&app_handle, &id)?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+ })}-/// 创建单个插件的快照(覆盖式:已存在则整体替换),存档于-/// `$DSH_HOME/.plugin-backups/<id>.tgz`。#[tauri::command]pub fn snapshot_plugin(app_handle: AppHandle,+ window: WebviewWindow,id: String,) -> Result<plugin::snapshot::SnapshotInfo, String> {- plugin::snapshot::create(&app_handle, &id)+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || plugin::snapshot::create(&app_handle, &id))}-/// 批量创建插件快照(升级前置自动快照):单项失败只记录在结果里,不阻断其它项。#[tauri::command]pub fn snapshot_plugins(app_handle: AppHandle,+ window: WebviewWindow,ids: Vec<String>,) -> Result<Vec<plugin::snapshot::SnapshotResult>, String> {- Ok(plugin::snapshot::create_many(&app_handle, &ids))+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || {+ Ok(plugin::snapshot::create_many(&app_handle, &ids))+ })}-/// 查询单个插件的快照信息(存在性 + 时间 + 大小 + 是否含配置段)。#[tauri::command]-pub fn get_plugin_backup(app_handle: AppHandle, id: String) -> plugin::snapshot::PluginBackupInfo {- plugin::snapshot::get(&app_handle, &id)+pub fn get_plugin_backup(+ app_handle: AppHandle,+ window: WebviewWindow,+ id: String,+) -> plugin::snapshot::PluginBackupInfo {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || plugin::snapshot::get(&app_handle, &id))}-/// 还原单个插件的快照(覆盖式,内部停服务;仅第三方可行动插件允许)。#[tauri::command]-pub async fn restore_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {- plugin::snapshot::restore(&app_handle, &id).await?;- plugin::watch::force_emit(&app_handle);- Ok(())+pub async fn restore_plugin(+ app_handle: AppHandle,+ window: WebviewWindow,+ id: String,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope(profile, async {+ plugin::snapshot::restore(&app_handle, &id).await?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+ })+ .await}-/// 弹出系统文件夹选择器,返回可直接安装的本地插件 `link:` spec(取消时为 `None`)。-///-/// Windows 的文件夹选择器是 COM 组件(`CoInitializeEx` 要求 STA 单元),而异步命令体跑在-/// 线程池上、线程的 COM 单元不确定;因此把对话框搬到主线程(tao 建窗时已初始化 STA),-/// 再同步等它关闭:阻塞的是原生对话框自身,异步运行时不阻塞。-/// 其余平台走 `rfd` 的异步对话框(与 `pick_data_dir` 同一条路):macOS 后端自己把面板-/// 派发到主线程、不设父窗也会挂到主窗,Linux 用 xdg-desktop-portal,没有 portal 的会话会-/// 回退 zenity。这两条路都拿不到用户选择时同样返回 `None`,与「用户取消」无法区分,-/// 前端按取消处理(不弹错)。#[tauri::command]pub async fn pick_local_plugin_dir(app_handle: AppHandle) -> Result<Option<String>, String> {#[cfg(windows)]{+ use tauri::Manager;let (sender, receiver) = tokio::sync::oneshot::channel();let app = app_handle.clone();app_handle@@ -385,8 +402,12 @@ pub async fn pick_local_plugin_dir(app_handle: AppHandle) -> Result<Option<Strin}}-/// 删除单个插件的快照(卸载级联清理 / 手动删除):幂等,无快照视为成功。#[tauri::command]-pub fn delete_plugin_backup(app_handle: AppHandle, id: String) -> Result<(), String> {- plugin::snapshot::delete(&app_handle, &id)+pub fn delete_plugin_backup(+ app_handle: AppHandle,+ window: WebviewWindow,+ id: String,+) -> Result<(), String> {+ let profile = instances::window_profile(&app_handle, window.label());+ instances::scope_sync(profile, || plugin::snapshot::delete(&app_handle, &id))}diff --git a/src-tauri/src/bridge/profile.rs b/src-tauri/src/bridge/profile.rsindex 9144fe33..714c07b1 100644--- a/src-tauri/src/bridge/profile.rs+++ b/src-tauri/src/bridge/profile.rs@@ -6,13 +6,14 @@use crate::config;use crate::service::profile;-use crate::service::profile::migrate::{MigrationAnalysis, MigrationDataKind, MigrateReport};+use crate::service::profile::migrate::{MigrateReport, MigrationAnalysis, MigrationDataKind};use tauri::AppHandle;/// 档案列表($DSH_HOME/profiles 下的目录,含 active/default 标记)#[tauri::command]-pub fn get_profiles(app_handle: AppHandle) -> Vec<profile::Profile> {- profile::list(&app_handle)+pub fn get_profiles(window: tauri::WebviewWindow, app_handle: AppHandle) -> Vec<profile::Profile> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope_sync(profile, || profile::list(&app_handle))}/// 新建档案(初始化 $DSH_HOME/profiles/<id>,web 模板)@@ -21,22 +22,65 @@ pub fn create_profile(app_handle: AppHandle, name: String) -> Result<profile::Prprofile::create(&app_handle, &name)}-/// 切换当前使用中的档案(持久化;重启服务后生效,由前端触发)+/// 切换当前窗口的档案并持久化下次启动默认档案。#[tauri::command]-pub fn set_active_profile(app_handle: AppHandle, id: String) -> Result<profile::Profile, String> {- profile::set_active(&app_handle, &id)+pub async fn set_active_profile(+ app_handle: AppHandle,+ window: tauri::WebviewWindow,+ id: String,+) -> Result<profile::Profile, String> {+ let _transition = crate::service::workflow::acquire_core_transition().await?;+ let old = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ let mut selected = profile::set_active(&app_handle, &id)?;+ selected.active = true;+ crate::service::workflow::instances::bind_window(window.label(), &id);+ if old != id && !crate::service::workflow::instances::is_attached(&old) {+ crate::service::workflow::instances::scope(old, crate::service::workflow::stop(app_handle))+ .await?;+ }+ Ok(selected)}/// 删除档案(默认档案与使用中的档案不可删除)#[tauri::command]-pub fn remove_profile(app_handle: AppHandle, id: String) -> Result<(), String> {- profile::remove(&app_handle, &id)+pub async fn remove_profile(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+ id: String,+) -> Result<(), String> {+ crate::service::fs_guard::validate_id(&id)?;+ if id == profile::DEFAULT_PROFILE {+ return Err("PROFILE_DEFAULT_NOT_REMOVABLE: the default profile cannot be removed".into());+ }+ let _transition = crate::service::workflow::acquire_core_transition().await?;+ let current = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ if id == current || crate::service::workflow::instances::is_attached(&id) {+ return Err("PROFILE_ACTIVE_NOT_REMOVABLE: the active profile cannot be removed".into());+ }+ crate::service::workflow::instances::scope(id.clone(), async {+ crate::service::workflow::stop(app_handle.clone()).await+ })+ .await?;+ crate::service::workflow::instances::scope_sync(current, || profile::remove(&app_handle, &id))}/// 重置档案(清空档案目录并按模板重新初始化;会话数据在档案目录之外,保留)#[tauri::command]-pub fn reset_profile(app_handle: AppHandle, id: String) -> Result<(), String> {- profile::reset(&app_handle, &id)+pub async fn reset_profile(+ app_handle: AppHandle,+ window: tauri::WebviewWindow,+ id: String,+) -> Result<(), String> {+ crate::service::fs_guard::validate_id(&id)?;+ let _transition = crate::service::workflow::acquire_core_transition().await?;+ if crate::service::workflow::instances::attached_elsewhere(&id, window.label()) {+ return Err("PROFILE_IN_USE: stop and detach profile before reset".into());+ }+ crate::service::workflow::instances::scope(id.clone(), async {+ crate::service::workflow::stop(app_handle.clone()).await?;+ profile::reset(&app_handle, &id)+ })+ .await}/// 克隆档案(全量复制源档案目录,自动递增命名或指定名称)。@@ -61,23 +105,101 @@ pub async fn clone_profile(/// 分析源档案的可迁移插件与档案级数据(只读,判定基准 = 当前核心版本)#[tauri::command]pub async fn analyze_profile_migration(+ window: tauri::WebviewWindow,app_handle: AppHandle,source_id: String,) -> Result<MigrationAnalysis, String> {- profile::migrate::analyze(&app_handle, &source_id).await+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ profile::migrate::analyze(&app_handle, &source_id).await+ })+ .await}/// 把源档案选中的数据并入当前档案(逐项独立,结果里逐项报告)#[tauri::command]pub async fn migrate_profile_data(+ window: tauri::WebviewWindow,app_handle: AppHandle,source_id: String,items: Vec<MigrationDataKind>,) -> Result<MigrateReport, String> {let handle = app_handle.clone();+ let profile_id =+ crate::service::workflow::instances::window_profile(&app_handle, window.label());tauri::async_runtime::spawn_blocking(move || {- profile::migrate::apply(&handle, &source_id, &items)+ crate::service::workflow::instances::scope_sync(profile_id, || {+ profile::migrate::apply(&handle, &source_id, &items)+ })}).await.map_err(|e| format!("PROFILE_MIGRATION_TASK: {e}"))?}++#[cfg(test)]+mod tests {+ #[test]+ fn profile_removal_waits_for_stop_before_deleting_detached_data() {+ let source = include_str!("profile.rs");+ let removal = source+ .split("pub async fn remove_profile(")+ .nth(1)+ .unwrap()+ .split("pub async fn reset_profile(")+ .next()+ .unwrap();+ let lock = removal.find("acquire_core_transition().await?").unwrap();+ let attached = removal.find("instances::is_attached(&id)").unwrap();+ let scope = removal.find("instances::scope(id.clone(),").unwrap();+ let stop = removal+ .find("workflow::stop(app_handle.clone()).await")+ .unwrap();+ let confirmed = stop + removal[stop..].find(".await?;").unwrap();+ let delete = removal.find("profile::remove(&app_handle, &id)").unwrap();+ assert!(lock < attached && attached < scope && scope < stop);+ assert!(stop < confirmed && confirmed < delete);+ }++ #[test]+ fn profile_binding_entrypoints_share_the_destructive_transition_lock() {+ for (source, entry, end) in [+ (+ include_str!("../desktop/window.rs"),+ "pub async fn create_app_window(",+ "fn session_window_path(",+ ),+ (+ include_str!("remote.rs"),+ "pub async fn remote_open_window(",+ "#[cfg(test)]",+ ),+ (+ include_str!("lifecycle.rs"),+ "pub async fn enter_safe_mode(",+ "pub async fn quarantine_broken_patch_layers(",+ ),+ (+ include_str!("profile.rs"),+ "pub async fn set_active_profile(",+ "pub async fn remove_profile(",+ ),+ ] {+ let body = source+ .split(entry)+ .nth(1)+ .unwrap()+ .split(end)+ .next()+ .unwrap();+ let lock = body.find("acquire_core_transition().await?").unwrap();+ let binding = body+ .find("instances::bind_window(")+ .or_else(|| body.find("build_extra_window("))+ .unwrap();+ assert!(+ lock < binding,+ "{entry} must serialize bindings with reset/restore/removal"+ );+ }+ }+}diff --git a/src-tauri/src/bridge/remote.rs b/src-tauri/src/bridge/remote.rsindex 7a40e65d..ad3a3b0d 100644--- a/src-tauri/src/bridge/remote.rs+++ b/src-tauri/src/bridge/remote.rs@@ -103,12 +103,16 @@ async fn remote_request(#[tauri::command]pub async fn remote(+ window: tauri::WebviewWindow,app_handle: AppHandle,method: String,payload: Option<Value>,) -> Result<Value, String> {let (method, path) = remote_method(&method)?;- let port = crate::config::get_store_dat_setting(&app_handle).port;+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ let port = crate::service::workflow::instances::scope_sync(profile, || {+ crate::service::workflow::instances::port(&app_handle)+ });remote_request(port, method, path, payload).await}@@ -178,18 +182,34 @@ fn open_window_args(machine_id: &str, url: &str) -> Result<(String, Option<tauriOk((label, parsed_url))}-/// 打开(已开则聚焦)`remote-<machineId>` 弹窗窗口,加载壳层应用。+fn profile_window_label(profile: &str, machine_id: &str) -> String {+ let profile: String = profile+ .as_bytes()+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect();+ format!(+ "{REMOTE_WINDOW_LABEL_PREFIX}{profile}--{}",+ sanitize_label_part(machine_id)+ )+}++/// 打开(已开则聚焦)当前档案的远端窗口。////// 壳不自存机器状态:前端按窗口 label 自解析目标机器并切换(机器状态经/// `/api/tauri/remote/machines` 轮询获取);`url` 只做回环校验。重复调用聚焦已有窗口(不/// 重复建窗);失败返回带前缀的可读错误,由调用方(S4 面板按钮)呈现。#[tauri::command]-pub fn remote_open_window(+pub async fn remote_open_window(+ window: tauri::WebviewWindow,app_handle: AppHandle,machine_id: String,url: String,) -> Result<(), String> {- let (label, _validated_url) = open_window_args(&machine_id, &url)?;+ let (_, _validated_url) = open_window_args(&machine_id, &url)?;+ let _transition = crate::service::workflow::acquire_core_transition().await?;+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ let label = profile_window_label(&profile, &machine_id);// 已有窗口:聚焦即可(再次「打开」同一机器的语义)。if let Some(existing) = app_handle.get_webview_window(&label) {let _ = existing.set_focus();@@ -199,8 +219,17 @@ pub fn remote_open_window(// 桥脚本按窗口注入、(Windows)WebView2 共用数据目录等,远端窗口与本体// 唯一区别是连接的后端。label 即机器寻址:前端 remote-<id> 自切换。let title = format!("DSH Remote · {machine_id}");- crate::desktop::builder::build_shell_window(&app_handle, label, &title, "index.html".into())+ crate::service::workflow::instances::bind_window(&label, &profile);+ let mut route = tauri::Url::parse("http://localhost/").expect("static URL");+ route+ .query_pairs_mut()+ .append_pair("remoteMachineId", &machine_id);+ let path = format!("index.html#{}", route.query().unwrap_or_default());+ crate::desktop::builder::build_shell_window(&app_handle, label.clone(), &title, path.into()).map(|_| ())+ .inspect_err(|_| {+ crate::service::workflow::instances::release_window(&label);+ }).map_err(|err| format!("REMOTE_WINDOW_FAILED: {err}"))}@@ -211,6 +240,22 @@ mod tests {use std::time::Duration;use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};+ #[test]+ fn remote_windows_are_isolated_by_profile() {+ assert_ne!(+ super::profile_window_label("a", "machine"),+ super::profile_window_label("b", "machine")+ );+ assert_eq!(+ super::profile_window_label("a", "machine"),+ super::profile_window_label("a", "machine")+ );+ assert_ne!(+ super::profile_window_label("a-b", "machine"),+ super::profile_window_label("a_b", "machine")+ );+ }+async fn response_server(status: &str,headers: &str,diff --git a/src-tauri/src/bridge/system_os.rs b/src-tauri/src/bridge/system_os.rsindex 9f8dfc11..ba01ebdf 100644--- a/src-tauri/src/bridge/system_os.rs+++ b/src-tauri/src/bridge/system_os.rs@@ -12,36 +12,65 @@ use tauri_plugin_opener::OpenerExt;/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)#[tauri::command]-pub async fn proxy_health_check(app_handle: AppHandle) -> Result<String, String> {- let port = config::get_store_dat_setting(&app_handle).port;- crate::service::workflow::proxy_health_check(port).await+pub async fn proxy_health_check(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<String, String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let port = crate::service::workflow::instances::port(&app_handle);+ crate::service::workflow::proxy_health_check(port).await+ })+ .await}/// 就绪提交窗口的 ownership 复核:只读后端进程槽位与启动守卫,不发 HTTP。////// 失败时返回与探测路径同一条 `HARNESS_NOT_OWNED` 信号,错误页据此识别进程退出。#[tauri::command]-pub fn harness_ownership() -> Result<(), String> {- crate::service::workflow::recheck_ownership()+pub fn harness_ownership(+ app_handle: AppHandle,+ window: tauri::WebviewWindow,+) -> Result<(), String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope_sync(+ profile,+ crate::service::workflow::recheck_ownership,+ )}/// 运行时/版本/诊断信息(侧边栏展示)#[tauri::command]-pub async fn get_runtime_info(app_handle: AppHandle) -> Result<config::RuntimeInfo, String> {- let port = config::get_store_dat_setting(&app_handle).port;- let mut info = config::runtime_info(&app_handle, port);- info.dsh_version = core::active_version(&app_handle).or(info.dsh_version);- Ok(info)+pub async fn get_runtime_info(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<config::RuntimeInfo, String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let port = crate::service::workflow::instances::port(&app_handle);+ let mut info = config::runtime_info(&app_handle, port);+ info.dsh_version = core::active_version(&app_handle).or(info.dsh_version);+ Ok(info)+ })+ .await}/// 在系统浏览器中打开 Harness 界面#[tauri::command]-pub async fn open_in_browser(app_handle: AppHandle) -> Result<(), String> {- let url = config::get_dsh_service_url(config::get_store_dat_setting(&app_handle).port);- app_handle- .opener()- .open_url(url, None::<&str>)- .map_err(|e| e.to_string())+pub async fn open_in_browser(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<(), String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let url =+ config::get_dsh_service_url(crate::service::workflow::instances::port(&app_handle));+ app_handle+ .opener()+ .open_url(url, None::<&str>)+ .map_err(|e| e.to_string())+ })+ .await}/// 复制 Harness 服务地址到剪贴板@@ -50,9 +79,17 @@ pub async fn open_in_browser(app_handle: AppHandle) -> Result<(), String> {/// Linux Wayland 合成器不支持 data-control 时 `tauri-plugin-clipboard-manager`/// 单例剪贴板导致的崩溃/挂死(同「复制日志」)。#[tauri::command]-pub async fn copy_service_url(app_handle: AppHandle) -> Result<(), String> {- let url = config::get_dsh_service_url(config::get_store_dat_setting(&app_handle).port);- crate::bridge::write_clipboard_text(url).await+pub async fn copy_service_url(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<(), String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let url =+ config::get_dsh_service_url(crate::service::workflow::instances::port(&app_handle));+ crate::bridge::write_clipboard_text(url).await+ })+ .await}/// 在系统文件管理器中定位指定文件(Session 日志下载完成后的"在文件夹中显示")@@ -112,28 +149,40 @@ fn tail_bytes(s: &str, max_bytes: usize) -> &str {/// 读取 dsh 服务日志#[tauri::command]pub async fn read_service_logs(+ window: tauri::WebviewWindow,app_handle: AppHandle,max_bytes: Option<usize>,) -> Result<String, String> {- let log_path = config::get_service_log_path(&app_handle);- if !log_path.exists() {- return Ok(String::new());- }-- let content = std::fs::read_to_string(&log_path).map_err(|e| e.to_string())?;- let max_bytes = max_bytes.unwrap_or(64 * 1024);- if content.len() <= max_bytes {- Ok(content)- } else {- Ok(tail_bytes(&content, max_bytes).to_string())- }+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let log_path = config::get_service_log_path(&app_handle);+ if !log_path.exists() {+ return Ok(String::new());+ }++ let content = std::fs::read_to_string(&log_path).map_err(|e| e.to_string())?;+ let max_bytes = max_bytes.unwrap_or(64 * 1024);+ if content.len() <= max_bytes {+ Ok(content)+ } else {+ Ok(tail_bytes(&content, max_bytes).to_string())+ }+ })+ .await}/// 清空 dsh 服务日志#[tauri::command]-pub async fn clear_service_logs(app_handle: AppHandle) -> Result<(), String> {- let log_path = config::get_service_log_path(&app_handle);- std::fs::write(&log_path, "").map_err(|e| e.to_string())+pub async fn clear_service_logs(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<(), String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {+ let log_path = config::get_service_log_path(&app_handle);+ std::fs::write(&log_path, "").map_err(|e| e.to_string())+ })+ .await}/// 拼装「复制日志」的环境信息段(纯函数,便于单测锁定报障格式)。@@ -185,7 +234,12 @@ fn format_env_info(/// 每段取末尾最多 `MAX_LINES` 行(前端日志量大,仅取一半 `FRONTEND_MAX_LINES`),/// 避免粘贴内容超出 GitHub issue 长度上限。#[tauri::command]-pub async fn read_run_logs(app_handle: AppHandle) -> Result<String, String> {+pub async fn read_run_logs(+ window: tauri::WebviewWindow,+ app_handle: AppHandle,+) -> Result<String, String> {+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ crate::service::workflow::instances::scope(profile, async move {const MAX_LINES: usize = 100;// 前端日志量大,复制的行数减半(避免粘贴内容过长);后端仍取满 MAX_LINESconst FRONTEND_MAX_LINES: usize = MAX_LINES / 2;@@ -237,6 +291,7 @@ pub async fn read_run_logs(app_handle: AppHandle) -> Result<String, String> {frontend_text.trim_end(),backend_text.trim_end()))+ }).await}fn read_tail(path: &std::path::Path, max_lines: usize, filter_frontend: bool) -> String {diff --git a/src-tauri/src/bridge/task_manager.rs b/src-tauri/src/bridge/task_manager.rsindex 7d728372..76386386 100644--- a/src-tauri/src/bridge/task_manager.rs+++ b/src-tauri/src/bridge/task_manager.rs@@ -178,10 +178,14 @@ pub async fn get_task_manager_processes(webview: tauri::Webview,) -> Result<Vec<TaskManagerProcess>, String> {ensure_shell(&webview)?;- tauri::async_runtime::spawn_blocking(|| {- let mut monitor = monitor().lock().unwrap_or_else(|error| error.into_inner());- monitor.refresh();- Ok(monitor.rows(std::process::id(), workflow::owned_process_pid()))+ let profile =+ workflow::instances::window_profile(webview.app_handle(), webview.window().label());+ tauri::async_runtime::spawn_blocking(move || {+ workflow::instances::scope_sync(profile, || {+ let mut monitor = monitor().lock().unwrap_or_else(|error| error.into_inner());+ monitor.refresh();+ Ok(monitor.rows(std::process::id(), workflow::owned_process_pid()))+ })}).await.map_err(|error| format!("TASK_MANAGER_READ: {error}"))?@@ -194,8 +198,10 @@ pub async fn end_task_manager_process(start_time: u64,) -> Result<(), String> {ensure_shell(&webview)?;+ let profile =+ workflow::instances::window_profile(webview.app_handle(), webview.window().label());let _transition = workflow::acquire_core_transition().await?;- tauri::async_runtime::spawn_blocking(move || {+ tauri::async_runtime::spawn_blocking(move || workflow::instances::scope_sync(profile, || {let mut current = Monitor::default();current.refresh();let rows = current.rows(std::process::id(), workflow::owned_process_pid());@@ -209,7 +215,7 @@ pub async fn end_task_manager_process(}monitor().lock().unwrap_or_else(|error| error.into_inner()).sampled_at = None;Ok(())- }).await.map_err(|error| format!("TASK_MANAGER_END: {error}"))?+ })).await.map_err(|error| format!("TASK_MANAGER_END: {error}"))?}#[cfg(test)]diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rsindex 37e6e4fe..b22351b0 100644--- a/src-tauri/src/config/runtime.rs+++ b/src-tauri/src/config/runtime.rs@@ -503,7 +503,11 @@ pub fn get_service_log_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {} else {"dsh-web.log"};- get_base_dir(app_handle).join("logs").join(name)+ let logs = get_base_dir(app_handle).join("logs");+ match crate::service::workflow::instances::current_profile() {+ Some(profile) => logs.join(profile).join(name),+ None => logs.join(name),+ }}/// 捆绑的 Node.js 版本号diff --git a/src-tauri/src/config/theme.rs b/src-tauri/src/config/theme.rsindex 38675bd5..73fe2513 100644--- a/src-tauri/src/config/theme.rs+++ b/src-tauri/src/config/theme.rs@@ -142,17 +142,15 @@ fn parse_theme_preference(content: &str) -> Option<DshTheme> {/// 可同步,无需(也无从)调用。#[cfg(target_os = "macos")]pub fn apply_window_theme(app_handle: &AppHandle, theme: DshTheme) {- let Some(window) = app_handle.get_webview_window("main") else {- log::debug!("apply_window_theme: main window not built yet");- return;- };let appearance = match theme {DshTheme::System => None,DshTheme::Light => Some(tauri::Theme::Light),DshTheme::Dark => Some(tauri::Theme::Dark),};- if let Err(err) = window.set_theme(appearance) {- log::warn!("[theme] failed to sync native window appearance: {err}");+ for window in app_handle.webview_windows().into_values() {+ if let Err(err) = window.set_theme(appearance) {+ log::warn!("[theme] failed to sync native window appearance: {err}");+ }}}@@ -273,14 +271,26 @@ mod tests {#[test]fn window_background_follows_preference() {let rgba = |c: Option<tauri::webview::Color>| c.map(|c| (c.0, c.1, c.2, c.3));- assert_eq!(rgba(window_background(DshTheme::Light, None)), Some((0xFF, 0xFF, 0xFF, 0xFF)));- assert_eq!(rgba(window_background(DshTheme::Dark, None)), Some((0x15, 0x15, 0x17, 0xFF)));assert_eq!(- rgba(window_background(DshTheme::System, Some(tauri::Theme::Dark))),+ rgba(window_background(DshTheme::Light, None)),+ Some((0xFF, 0xFF, 0xFF, 0xFF))+ );+ assert_eq!(+ rgba(window_background(DshTheme::Dark, None)),Some((0x15, 0x15, 0x17, 0xFF)));assert_eq!(- rgba(window_background(DshTheme::System, Some(tauri::Theme::Light))),+ rgba(window_background(+ DshTheme::System,+ Some(tauri::Theme::Dark)+ )),+ Some((0x15, 0x15, 0x17, 0xFF))+ );+ assert_eq!(+ rgba(window_background(+ DshTheme::System,+ Some(tauri::Theme::Light)+ )),Some((0xFF, 0xFF, 0xFF, 0xFF)));assert_eq!(window_background(DshTheme::System, None), None);@@ -294,15 +304,25 @@ mod tests {("ui-theme:\n preference: system\n", DshTheme::System),];for (content, expected) in cases {- assert_eq!(parse_theme_preference(content), Some(expected), "content={content:?}");+ assert_eq!(+ parse_theme_preference(content),+ Some(expected),+ "content={content:?}"+ );}}/// 未知取值与整段缺失都返回 `None`,由调用方回退 `DEFAULT_THEME`。#[test]fn rejects_unknown_and_missing_preference() {- assert_eq!(parse_theme_preference("ui-theme:\n preference: blue\n"), None);- assert_eq!(parse_theme_preference("ui-theme:\n density: compact\n"), None);+ assert_eq!(+ parse_theme_preference("ui-theme:\n preference: blue\n"),+ None+ );+ assert_eq!(+ parse_theme_preference("ui-theme:\n density: compact\n"),+ None+ );assert_eq!(parse_theme_preference("editor:\n fontSize: 12\n"), None);}}diff --git a/src-tauri/src/config/window_state.rs b/src-tauri/src/config/window_state.rsindex 451d8183..a62116e5 100644--- a/src-tauri/src/config/window_state.rs+++ b/src-tauri/src/config/window_state.rs@@ -390,6 +390,20 @@ pub fn restore_main_window<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindomod tests {use super::*;+ #[test]+ fn exit_geometry_does_not_sample_extra_or_remote_windows_without_main() {+ let app = tauri::test::mock_builder()+ .build(tauri::test::mock_context(tauri::test::noop_assets()))+ .unwrap();+ for label in ["window-geometry-test", "remote-geometry-test"] {+ tauri::WebviewWindowBuilder::new(&app, label, tauri::WebviewUrl::default())+ .build()+ .unwrap();+ }+ assert!(crate::utils::shell_window(app.handle()).is_some());+ save_main_window_geometry(app.handle());+ }+#[test]fn window_state_default_matches_builder_default() {let state = WindowState::default();diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 1c699ea0..acc5b3f2 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -128,6 +128,7 @@ pub fn setup(app_handle: tauri::AppHandle) {crate::service::profile::migrate_desktop_profile_name(&app_handle);// 启动进程监控(tick 检测 dsh 服务状态)+ crate::service::workflow::instances::window_profile(&app_handle, MAIN_WINDOW_LABEL);crate::service::scheduler::start(&app_handle);// `dsh://` 深链(成功页「打开应用」按钮):仅打包态注册协议并接管 open-url@@ -143,7 +144,14 @@ pub fn setup(app_handle: tauri::AppHandle) {log::debug!("auto_start disabled, skipping startup");return;}- if let Err(e) = crate::service::workflow::start(app_for_start).await {+ let profile =+ crate::service::workflow::instances::window_profile(&app_for_start, MAIN_WINDOW_LABEL);+ if let Err(e) = crate::service::workflow::instances::scope(+ profile,+ crate::service::workflow::start(app_for_start),+ )+ .await+ {log::error!("start failed: {}", e);}});@@ -1138,7 +1146,10 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::We/// macOS 未实现窗口底色接口,`set_background_color` 会返回错误并被忽略——那里由/// `config::apply_window_theme` 同步原生外观。fn apply_window_background(app: &tauri::AppHandle<Wry>, window: &tauri::WebviewWindow<Wry>) {- let background = if crate::config::get_store_dat_setting(app).appearance.transparency {+ let background = if crate::config::get_store_dat_setting(app)+ .appearance+ .transparency+ {Some(tauri::webview::Color(0, 0, 0, 0))} else {crate::config::window_background(crate::config::get_dsh_theme(app), window.theme().ok())@@ -1215,14 +1226,16 @@ pub fn build_shell_window(pub fn build_extra_window(app: &tauri::AppHandle<Wry>,path: std::path::PathBuf,+ profile: &str,) -> tauri::Result<tauri::WebviewWindow<Wry>> {let sequence = EXTRA_WINDOW_SEQ.fetch_add(1, Ordering::SeqCst) + 1;- build_shell_window(- app,- format!("window-{sequence}"),- crate::desktop::product_name(app),- path,- )+ let label = format!("window-{sequence}");+ crate::service::workflow::instances::bind_window(&label, profile);+ let result = build_shell_window(app, label.clone(), crate::desktop::product_name(app), path);+ if result.is_err() {+ crate::service::workflow::instances::release_window(&label);+ }+ result}#[cfg(all(test, windows))]@@ -1400,7 +1413,8 @@ mod security_tests {#[test]fn native_appearance_effects_are_local_shell_only() {let appearance: Value =- serde_json::from_str(include_str!("../../capabilities/appearance-effects.json")).unwrap();+ serde_json::from_str(include_str!("../../capabilities/appearance-effects.json"))+ .unwrap();// 这个能力一旦带上 remote,就会把窗口级 setEffects 暴露给回环承载的 Harness 页面。assert!(appearance.get("remote").is_none());@@ -1408,9 +1422,9 @@ mod security_tests {.as_array().expect("permissions must be an array").clone();- assert!(!default_permissions.iter().any(|permission| {- permission.as_str() == Some("core:window:allow-set-effects")- }));+ assert!(!default_permissions+ .iter()+ .any(|permission| { permission.as_str() == Some("core:window:allow-set-effects") }));}#[test]@@ -1802,7 +1816,13 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {}// 主窗口以外的附加窗口(「文件 → 新建窗口」)不驻留托盘:直接关闭// 销毁。隐藏它们既没有恢复入口,也不符合「关掉这个窗口」的直觉。- if window.label() != MAIN_WINDOW_LABEL {+ if (window.label() != MAIN_WINDOW_LABEL && !window.label().starts_with("window-"))+ || window.app_handle().webview_windows().values().any(|other| {+ other.label() != window.label()+ && (other.label() == MAIN_WINDOW_LABEL+ || other.label().starts_with("window-"))+ })+ {return;}// get_store_dat_setting 内部已归一化,取值只可能是 tray 或 quit@@ -1851,6 +1871,26 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {#[cfg(not(target_os = "macos"))]let _ = window.hide();}+ tauri::WindowEvent::Destroyed => {+ if let Some(profile) =+ crate::service::workflow::instances::release_window(window.label())+ {+ let app = window.app_handle().clone();+ tauri::async_runtime::spawn(async move {+ if let Ok(_transition) =+ crate::service::workflow::acquire_core_transition().await+ {+ if !crate::service::workflow::instances::is_attached(&profile) {+ let _ = crate::service::workflow::instances::scope(+ profile,+ crate::service::workflow::stop(app),+ )+ .await;+ }+ }+ });+ }+ }tauri::WindowEvent::ScaleFactorChanged { .. } => {if window.label() == crate::desktop::pet::PET_WINDOW_LABEL {crate::desktop::pet::apply_pet_size(window.app_handle());diff --git a/src-tauri/src/desktop/notification.rs b/src-tauri/src/desktop/notification.rsindex 8bd8a628..fdd464cf 100644--- a/src-tauri/src/desktop/notification.rs+++ b/src-tauri/src/desktop/notification.rs@@ -187,8 +187,14 @@ pub fn enable_notification_permissions(crate::config::get_dsh_service_url(crate::config::DSH_PORT),crate::config::get_dsh_service_url(crate::config::DSH_DEV_PORT),];- let store_port = crate::config::get_store_dat_setting(parent.app_handle()).port;- let store_origin = crate::config::get_dsh_service_url(store_port);+ let profile = crate::service::workflow::instances::window_profile(+ parent.app_handle(),+ parent.label(),+ );+ let port = crate::service::workflow::instances::scope_sync(profile, || {+ crate::service::workflow::instances::port(parent.app_handle())+ });+ let store_origin = crate::config::get_dsh_service_url(port);if !origins.contains(&store_origin) {origins.push(store_origin);}diff --git a/src-tauri/src/desktop/window.rs b/src-tauri/src/desktop/window.rsindex cbb2c227..1ef7a50a 100644--- a/src-tauri/src/desktop/window.rs+++ b/src-tauri/src/desktop/window.rs@@ -122,11 +122,22 @@ pub fn on_page_load(#[tauri::command]pub async fn create_app_window(app_handle: AppHandle<Wry>,+ window: WebviewWindow<Wry>,session_id: Option<String>,iframe_url: Option<String>,) -> Result<(), String> {- let path = session_window_path(session_id.as_deref(), iframe_url.as_deref())?;- crate::desktop::builder::build_extra_window(&app_handle, path)+ let _transition = crate::service::workflow::acquire_core_transition().await?;+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ let path = crate::service::workflow::instances::scope_sync(profile.clone(), || {+ let origin =+ config::get_dsh_service_url(crate::service::workflow::instances::port(&app_handle));+ session_window_path(+ session_id.as_deref(),+ session_id.as_ref().map(|_| origin.as_str()),+ )+ })?;+ let _ = iframe_url;+ crate::desktop::builder::build_extra_window(&app_handle, path, &profile).map(|_| ()).map_err(|error| format!("WINDOW_CREATE_FAILED: {error}"))}diff --git a/src-tauri/src/service/core/local.rs b/src-tauri/src/service/core/local.rsindex 63e1e6d7..252559b6 100644--- a/src-tauri/src/service/core/local.rs+++ b/src-tauri/src/service/core/local.rs@@ -370,6 +370,7 @@ fn local_core_uses_pnpm(app_handle: &AppHandle) -> bool {////// 返回更新后的版本号。失败返回错误(附进程输出尾部,便于排查)。pub async fn update_local_core(app_handle: AppHandle) -> Result<String, String> {+ crate::service::workflow::instances::require_exclusive_profile()?;let Some(core) = local_core(&app_handle) else {return Err("CORE_LOCAL_NOT_FOUND: no local core to update".to_string());};diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rsindex 1699a9ef..d43f4931 100644--- a/src-tauri/src/service/core/runtime.rs+++ b/src-tauri/src/service/core/runtime.rs@@ -1,10 +1,7 @@//! 活动预打包核心的运行时自愈:补齐插件入口并检查原生依赖(含 ABI 兼容性)。//!-//! dsh 的 loader 以核心安装目录作为裸包解析根,而 profile 中的插件实际位于-//! `$DSH_HOME/profiles/<profile>/node_modules`,应用内置插件则位于安装包资源目录。-//! 核心版本切换只移动 `dependencies/dsh`,不会自动重建这些入口,因此每次启动都要-//! 在启动 dsh 前按当前核心重新建立安全的目录链接。用户自行安装的 local 核心不归-//! 桌面端管理,明确跳过本模块。+//! 用户插件由各自 profile 解析;共享核心只链接安装包内置插件,避免跨档案覆盖入口。+//! 用户自行安装的 local 核心不归桌面端管理,明确跳过本模块。//!//! 除了入口链接,启动前还要确认核心的原生模块能真正被当前 Node 运行时加载://! 预打包核心的原生模块(`fs-ext` 这类 node-gyp 包)在 pkg 构建期编译,ABI 只与@@ -536,7 +533,7 @@ fn remove_core_package_residue(path: &Path) -> Result<(), String> {})}-/// 从活动 profile 与应用内置清单收集需要在核心根下解析的包,并逐个建立入口。+/// 共享核心只保留内置插件入口,并移除旧版投射的档案插件链接(issue #993)。fn link_required_plugins(app_handle: &AppHandle, core_root: &Path) -> Result<(), String> {let core_node_modules = core_root.join("node_modules");std::fs::create_dir_all(&core_node_modules).map_err(|e| {@@ -573,52 +570,71 @@ fn link_required_plugins(app_handle: &AppHandle, core_root: &Path) -> Result<(),ensure_package_link(name, &source, &core_node_modules)?;}- let profile = crate::service::plugin::profile_dir(app_handle);- let manifest_path = profile.join("package.json");- let Ok(raw) = std::fs::read_to_string(&manifest_path) else {- return Ok(());- };- let manifest = serde_json::from_str::<serde_json::Value>(&raw)- .map_err(|e| format!("CORE_PLUGIN_PROFILE_MANIFEST_INVALID: {manifest_path:?}: {e}"))?;-- let mut names = HashSet::new();- if let Some(dependencies) = manifest.get("dependencies").and_then(|v| v.as_object()) {- names.extend(dependencies.keys().cloned());- }- if let Some(bundles) = manifest- .get("dsh")- .and_then(|v| v.get("profile"))- .and_then(|v| v.get("bundles"))- .and_then(|v| v.as_array())- {- names.extend(bundles.iter().filter_map(|v| v.as_str().map(str::to_owned)));- }+ remove_profile_plugin_links(+ &core_node_modules,+ &crate::config::get_dsh_data_path(app_handle).join("profiles"),+ &internal_ids,+ )+}- // Core 自有依赖(尤其 @deepseek-ai/*)由发行包自己提供,不能被 profile 中同名- // 条目覆盖。internal 已按当前资源处理,剩余名字才从 profile 入口解析。- for name in names {- if internal_ids.contains(&name) || !is_safe_package_name(&name) {+fn remove_profile_plugin_links(+ core_modules: &Path,+ profiles: &Path,+ internal_ids: &HashSet<String>,+) -> Result<(), String> {+ let entries = match std::fs::read_dir(profiles) {+ Ok(entries) => entries,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(format!("CORE_PLUGIN_PROFILES_READ_FAILED: {error}")),+ };+ for entry in entries {+ let entry = entry.map_err(|error| format!("CORE_PLUGIN_PROFILE_READ_FAILED: {error}"))?;+ if !entry+ .file_type()+ .map_err(|error| format!("CORE_PLUGIN_PROFILE_STAT_FAILED: {error}"))?+ .is_dir()+ || entry.file_name() == "node_modules"+ {continue;}- let source = profile.join("node_modules").join(&name);- if !source.join("package.json").is_file() {- if read_package_name(&core_node_modules.join(&name).join("package.json"))- .ok()- .flatten()- .as_deref()- == Some(name.as_str())+ let manifest_path = entry.path().join("package.json");+ let Ok(raw) = std::fs::read_to_string(&manifest_path) else {+ continue;+ };+ let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&raw) else {+ continue;+ };+ let mut names = HashSet::new();+ if let Some(dependencies) = manifest+ .get("dependencies")+ .and_then(|value| value.as_object())+ {+ names.extend(dependencies.keys().map(String::as_str));+ }+ if let Some(bundles) = manifest+ .pointer("/dsh/profile/bundles")+ .and_then(|value| value.as_array())+ {+ names.extend(bundles.iter().filter_map(|value| value.as_str()));+ }+ for name in names {+ if internal_ids.contains(name) || !is_safe_package_name(name) {+ continue;+ }+ let destination = core_modules.join(name);+ if !std::fs::symlink_metadata(&destination)+ .is_ok_and(|metadata| metadata.file_type().is_symlink()){continue;}- log::warn!(- "CORE_PLUGIN_PROFILE_ENTRY_MISSING: {} is referenced by {}, source {} is unavailable",- name,- manifest_path.display(),- source.display()- );- continue;+ let source = entry.path().join("node_modules").join(name);+ if let (Ok(source), Ok(target)) = (source.canonicalize(), destination.canonicalize()) {+ if source == target {+ ensure_non_link_directory(destination.parent().unwrap(), core_modules)?;+ remove_link_only(&destination)?;+ }+ }}- ensure_package_link(&name, &source, &core_node_modules)?;}Ok(())}@@ -1761,10 +1777,8 @@ mod tests {/// 早先的 512 上限时同样如此 —— 那段规模正是这次改动才开始能缓存的。#[test]fn probe_stamp_detects_in_place_addon_overwrite_beyond_legacy_cap() {- let modules = std::env::temp_dir().join(format!(- "dsh-probe-stamp-overwrite-{}",- std::process::id()- ));+ let modules =+ std::env::temp_dir().join(format!("dsh-probe-stamp-overwrite-{}", std::process::id()));let _ = std::fs::remove_dir_all(&modules);let release = modules.join("sharp/build/Release");std::fs::create_dir_all(&release).unwrap();@@ -1795,10 +1809,8 @@ mod tests {/// 读不到」与「上次也没读到」得到同一个摘要,从而跳过一次本该做的探测。#[test]fn probe_stamp_requires_readable_artifact_metadata() {- let dir = std::env::temp_dir().join(format!(- "dsh-probe-stamp-artifact-{}",- std::process::id()- ));+ let dir =+ std::env::temp_dir().join(format!("dsh-probe-stamp-artifact-{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);std::fs::create_dir_all(&dir).unwrap();let addon = dir.join("sharp.node");@@ -1830,10 +1842,8 @@ mod tests {/// 会漏掉它并跳过探测。#[test]fn probe_stamp_detects_in_place_overwrite_below_nested_artifact_directory() {- let modules = std::env::temp_dir().join(format!(- "dsh-probe-stamp-nested-{}",- std::process::id()- ));+ let modules =+ std::env::temp_dir().join(format!("dsh-probe-stamp-nested-{}", std::process::id()));let _ = std::fs::remove_dir_all(&modules);let nested = modules.join("sharp/prebuilds/win32-x64");std::fs::create_dir_all(&nested).unwrap();@@ -1879,7 +1889,9 @@ mod tests {);let mut full = Vec::new();- assert!(collect_probe_stamp_entries(&dir, &mut full, NATIVE_PROBE_STAMP_MAX_ENTRIES).is_some());+ assert!(+ collect_probe_stamp_entries(&dir, &mut full, NATIVE_PROBE_STAMP_MAX_ENTRIES).is_some()+ );assert_eq!(full.len(), 100);std::fs::remove_dir_all(&dir).unwrap();@@ -1893,7 +1905,8 @@ mod tests {/// (`FileType::is_symlink()` 为真),正是这里要覆盖的形态。#[test]fn probe_stamp_rejects_a_directory_symlink_it_cannot_descend() {- let root = std::env::temp_dir().join(format!("dsh-probe-stamp-link-{}", std::process::id()));+ let root =+ std::env::temp_dir().join(format!("dsh-probe-stamp-link-{}", std::process::id()));let _ = std::fs::remove_dir_all(&root);let real = root.join("pkg/prebuilds/real");std::fs::create_dir_all(&real).unwrap();@@ -1914,7 +1927,7 @@ mod tests {&root.join("pkg/prebuilds"),"pkg/prebuilds",&mut out,- NATIVE_PROBE_STAMP_MAX_ENTRIES+ NATIVE_PROBE_STAMP_MAX_ENTRIES,).is_none();// 先断开链接再删树:`remove_dir_all` 会跟随 junction 去删目标(这里恰好是同一棵树,@@ -1924,7 +1937,6 @@ mod tests {assert!(rejected);}-fn probe_stamp_entries(dir: &Path) -> Vec<String> {let mut out = Vec::new();collect_probe_stamp_entries(dir, &mut out, NATIVE_PROBE_STAMP_MAX_ENTRIES).unwrap();@@ -1943,6 +1955,72 @@ mod tests {assert_ne!(probe_stamp_digest(&wide), probe_stamp_digest("pkg-0=1"));}+ #[test]+ fn profile_plugin_links_do_not_survive_in_shared_core() {+ fn package(modules: &Path, name: &str, version: &str) {+ let dir = modules.join(name);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(+ dir.join("package.json"),+ serde_json::json!({"name": name, "version": version}).to_string(),+ )+ .unwrap();+ }+ let root = tempfile::tempdir().unwrap();+ let profiles = root.path().join("profiles");+ let modules = root.path().join("core/node_modules");+ for (id, version) in [("a", "1.0.0"), ("b", "2.0.0")] {+ let profile = profiles.join(id);+ std::fs::create_dir_all(&profile).unwrap();+ std::fs::write(profile.join("package.json"), r#"{"dependencies":{"same-plugin":"*","@scope/plugin":"*","dsh-tauri":"*","core-owned":"*"}}"#).unwrap();+ for name in ["same-plugin", "@scope/plugin", "dsh-tauri", "core-owned"] {+ package(&profile.join("node_modules"), name, version);+ }+ }+ std::fs::create_dir_all(modules.join("@scope")).unwrap();+ for (name, id) in [+ ("same-plugin", "a"),+ ("@scope/plugin", "b"),+ ("dsh-tauri", "a"),+ ] {+ create_directory_link(+ &profiles+ .join(id)+ .join("node_modules")+ .join(name)+ .canonicalize()+ .unwrap(),+ &modules.join(name),+ )+ .unwrap();+ }+ package(&modules, "core-owned", "9.0.0");+ let internal = HashSet::from(["dsh-tauri".to_string()]);+ remove_profile_plugin_links(&modules, &profiles, &internal).unwrap();+ remove_profile_plugin_links(&modules, &profiles, &internal).unwrap();+ assert!(std::fs::symlink_metadata(modules.join("same-plugin")).is_err());+ assert!(std::fs::symlink_metadata(modules.join("@scope/plugin")).is_err());+ assert_eq!(+ read_package_version(&modules.join("dsh-tauri/package.json")).as_deref(),+ Some("1.0.0")+ );+ assert_eq!(+ read_package_version(&modules.join("core-owned/package.json")).as_deref(),+ Some("9.0.0")+ );+ assert_eq!(+ read_package_version(&profiles.join("a/node_modules/same-plugin/package.json"))+ .as_deref(),+ Some("1.0.0")+ );+ assert_eq!(+ read_package_version(&profiles.join("b/node_modules/same-plugin/package.json"))+ .as_deref(),+ Some("2.0.0")+ );+ remove_link_only(&modules.join("dsh-tauri")).unwrap();+ }+#[test]fn package_names_allow_plain_and_scoped_names_only() {assert!(is_safe_package_name("dshmarket"));diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rsindex 18679c05..225ee7c1 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -12,7 +12,7 @@ use crate::config;use crate::service::{download, fs_guard, workflow};use std::collections::HashSet;use std::path::{Path, PathBuf};-use tauri::{AppHandle, Manager};+use tauri::AppHandle;use super::local::{find_user_dsh_bin, local_core};use super::source::{@@ -170,7 +170,12 @@ fn rows_with_release_catalog(tag: String::new(),path: dir_str.clone(),dir: dir_str,- present: dir.join(config::dependencies::entry_relative(app_handle, config::dependencies::DEP_DSH)).is_file(),+ present: dir+ .join(config::dependencies::entry_relative(+ app_handle,+ config::dependencies::DEP_DSH,+ ))+ .is_file(),active: bundled_active,removable: false,preview: false,@@ -421,12 +426,16 @@ fn trusted_release_version(/// 停止并清扫旧核心进程,确保核心来源变更时不会继续使用旧入口。async fn stop_harness_for_core_switch(app_handle: &AppHandle) -> Result<(), String> {+ workflow::instances::require_exclusive_profile()?;if workflow::has_owned_process() {workflow::stop(app_handle.clone()).await?;}let handle = app_handle.clone();+ let profile = crate::service::profile::active_profile(app_handle);tauri::async_runtime::spawn_blocking(move || {- workflow::terminate_stale_harness_processes(&handle)+ workflow::instances::scope_sync(profile, || {+ workflow::terminate_stale_harness_processes(&handle)+ })}).await.map_err(|e| format!("CORE_SWITCH_STOP_FAILED: {e}"))??;@@ -518,6 +527,7 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Str// 从切换开始到目录互换完成持续持有与 launch 共用的转换锁,避免两个切换// 重叠,也避免 launch 在状态检查后插入并从旧的 dependencies/dsh 加载 DLL。let _transition_guard = workflow::acquire_core_transition().await?;+ workflow::instances::require_exclusive_profile()?;let deps = dependencies_dir(app_handle);// 槽位互换只在托管根内进行(映射可能把激活核心指向安装目录的捆绑副本);// 随包资源构建不互换,见下方分支。@@ -576,8 +586,11 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Str// taskkill(同步阻塞),移出 Tokio 线程。{let handle = app_handle.clone();+ let profile = crate::service::profile::active_profile(app_handle);tauri::async_runtime::spawn_blocking(move || {- workflow::terminate_stale_harness_processes(&handle)+ workflow::instances::scope_sync(profile, || {+ workflow::terminate_stale_harness_processes(&handle)+ })}).await.map_err(|e| format!("CORE_SWITCH_STOP_FAILED: {e}"))??;@@ -702,9 +715,8 @@ pub async fn download_version(app_handle: &AppHandle, tag: &str) -> Result<Harne// 2. 下载 + 校验 + 原子解压到历史槽位(两阶段进度:下载 0-50,解压 50-100)// 下载默认走 GitHub 官方直连,失败自动切换代理镜像兜底。- let window = app_handle- .get_webview_window("main")- .ok_or("WINDOW_NOT_FOUND: main window missing")?;+ let window = crate::utils::operation_window(app_handle)+ .ok_or("WINDOW_NOT_FOUND: current profile window missing")?;let mut tracker = download::ProgressTracker::new(&window, 2);tracker.start_phase("download", &format!("正在下载核心版本 {tag}"));let mut urls = vec![info.asset_url.clone()];diff --git a/src-tauri/src/service/data_dir/mod.rs b/src-tauri/src/service/data_dir/mod.rsindex 4d56f197..44579ccb 100644--- a/src-tauri/src/service/data_dir/mod.rs+++ b/src-tauri/src/service/data_dir/mod.rs@@ -139,8 +139,9 @@ pub fn status(app_handle: &AppHandle) -> DataDirStatus {let data_dir = crate::config::get_dsh_data_path(app_handle);let default_dir = env::default_home();let env_override = env::read_user_home().ok().flatten().unwrap_or_default();- let backups: Vec<MigrationBackup> =- migrate::find_backups(app_handle, &data_dir).into_iter().collect();+ let backups: Vec<MigrationBackup> = migrate::find_backups(app_handle, &data_dir)+ .into_iter()+ .collect();let rollback_available = !backups.is_empty();DataDirStatus {supported: !cfg!(debug_assertions),@@ -197,11 +198,7 @@ fn entries_in(root: &Path) -> Result<Vec<DataDirEntry>, String> {/// 迁移预检:目标合法性、磁盘空间、来源(是否用户上次用过的位置)。////// 预检与真正迁移共用 `migrate::plan`,避免「预检说没问题、执行时才拒绝」的错位。-pub fn preview(- app_handle: &AppHandle,- parent: &Path,- leaf: &str,-) -> Result<MigrationPlan, String> {+pub fn preview(app_handle: &AppHandle, parent: &Path, leaf: &str) -> Result<MigrationPlan, String> {let source = crate::config::get_dsh_data_path(app_handle);let target = join_leaf(parent, leaf)?;migrate::plan(app_handle, &source, &target)@@ -272,7 +269,27 @@ pub(crate) fn harness_markers(root: &Path) -> [HarnessMarker; 2] {crate::config::HARNESS_PID_MARKER_NAMES.map(|name| harness_marker_at(&root.join(name)))}-/// 无 `AppHandle` 版本:路径由调用方给出,便于用临时目录直接测三种分类。+pub(crate) fn all_harness_markers(root: &Path) -> Vec<HarnessMarker> {+ let mut markers = harness_markers(root).to_vec();+ match std::fs::read_dir(root.join("profiles")) {+ Ok(entries) => {+ for entry in entries {+ match entry {+ Ok(entry) if entry.path().is_dir() => {+ markers.extend(harness_markers(&entry.path()))+ }+ Ok(_) => {}+ Err(_) => markers.push(HarnessMarker::Invalid),+ }+ }+ }+ Err(error) if error.kind() == ErrorKind::NotFound => {}+ Err(_) => markers.push(HarnessMarker::Invalid),+ }+ markers+}++/// 无 AppHandle 的标记读取。fn harness_marker_at(marker: &Path) -> HarnessMarker {let text = match std::fs::read_to_string(marker) {Ok(text) => text,@@ -295,7 +312,7 @@ fn harness_marker_at(marker: &Path) -> HarnessMarker {// 两个通道共享 DSH_HOME;任一仍在运行或标记不可读都不能迁移。pub(super) fn harness_stopped(root: &Path) -> bool {- harness_markers(root)+ all_harness_markers(root).into_iter().all(|marker| match marker {HarnessMarker::Missing => true,@@ -343,10 +360,29 @@ fn join_leaf(parent: &Path, leaf: &str) -> Result<PathBuf, String> {mod tests {use super::*;+ #[test]+ fn profile_markers_block_migration_when_live_or_unreadable() {+ let root = std::env::temp_dir().join(format!("dsh-profile-marker-{}", std::process::id()));+ let profile = root.join("profiles").join("isolation-check");+ std::fs::create_dir_all(&profile).unwrap();+ let marker = profile.join(crate::config::HARNESS_PID_MARKER_NAMES[0]);+ std::fs::write(&marker, format!("{}\n41000\n", std::process::id())).unwrap();+ assert!(!harness_stopped(&root));+ assert!(all_harness_markers(&root).contains(&HarnessMarker::Pid(std::process::id())));+ std::fs::write(&marker, "invalid").unwrap();+ assert!(!harness_stopped(&root));+ std::fs::remove_file(marker).unwrap();+ assert!(harness_stopped(&root));+ std::fs::remove_dir_all(root).unwrap();+ }+#[test]fn join_leaf_accepts_plain_names_only() {let parent = Path::new("D:\\");- assert_eq!(join_leaf(parent, "DSHHome").unwrap(), parent.join("DSHHome"));+ assert_eq!(+ join_leaf(parent, "DSHHome").unwrap(),+ parent.join("DSHHome")+ );assert_eq!(join_leaf(parent, " DSH Home ").unwrap(),parent.join("DSH Home")@@ -421,7 +457,9 @@ mod tests {// 真正的读取错误仍要报出来,别把权限问题也当成空目录let file = root.with_extension("txt");std::fs::write(&file, "not a directory").unwrap();- assert!(entries_in(&file).unwrap_err().starts_with("DATA_DIR_READ: "));+ assert!(entries_in(&file)+ .unwrap_err()+ .starts_with("DATA_DIR_READ: "));let _ = std::fs::remove_file(&file);}diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsindex d495c51a..6be37fb3 100644--- a/src-tauri/src/service/plugin/install/mod.rs+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -41,7 +41,7 @@ use crate::service::profile::{use std::collections::HashMap;use std::ffi::OsString;use std::path::Path;-use tauri::{AppHandle, Emitter, Manager, WebviewWindow};+use tauri::{AppHandle, Emitter, WebviewWindow};// plugin 兄弟模块的再导出:子模块经 `super::` 统一从这里取,跨模块边界只在此定义。pub(crate) use super::ensure_profile_npmrc;@@ -89,8 +89,8 @@ 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;+use spec::{bundled_dir_of, normalize_git_spec, preset_spec_for_install, spec_argument};/// 允许构建重试的上限。每次重试解决 pnpm 报出的一个允许键(git depPath 或/// 传递构建包名),多个 git 插件 / 多个原生依赖各占一次,上限封顶防死循环。@@ -392,9 +392,8 @@ async fn install_with_cancel(return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());}- let window = app_handle- .get_webview_window("main")- .ok_or("WINDOW_NOT_FOUND: main window missing")?;+ let window = crate::utils::operation_window(app_handle)+ .ok_or("WINDOW_NOT_FOUND: current profile window missing")?;// 选定/补齐安装用的 pnpm:返回是否应强制使用捆绑版(版本感知,见 ensure_pnpm)let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window, owner).await?;@@ -641,9 +640,8 @@ pub async fn allow_version_exemptions(if versions.is_empty() {return Err("PLUGIN_EXEMPTION_EMPTY: no plugin version exemption to grant".to_string());}- let window = app_handle- .get_webview_window("main")- .ok_or("WINDOW_NOT_FOUND: main window missing")?;+ let window = crate::utils::operation_window(app_handle)+ .ok_or("WINDOW_NOT_FOUND: current profile window missing")?;let node = config::get_node_binary_path(app_handle);let dsh_bin = core::active_dsh_binary(app_handle);if !node.exists() {@@ -948,7 +946,10 @@ mod tests {/// 造一个真实存在的本地插件目录:本地 spec 的解析会 canonicalize,只有落盘/// 路径才能覆盖「尾斜杠 / 混用分隔符 / 短名」这些形态。- fn local_plugin_fixture(tag: &str, manifest: Option<&str>) -> (std::path::PathBuf, std::path::PathBuf) {+ 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");@@ -1043,7 +1044,10 @@ mod tests {let target = local_target(&other_dir, &base).unwrap();- assert_eq!(target.spec, format!("link:{}", spec::forward_slashes(&other_dir)));+ assert_eq!(+ target.spec,+ format!("link:{}", spec::forward_slashes(&other_dir))+ );assert_ne!(target.spec,format!("link:{}", spec::forward_slashes(&base.join("plugin")))diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rsindex 96c13051..510ca4cb 100644--- a/src-tauri/src/service/plugin/install/single.rs+++ b/src-tauri/src/service/plugin/install/single.rs@@ -6,7 +6,7 @@use std::collections::HashSet;use std::ffi::OsString;use std::path::Path;-use tauri::{AppHandle, Manager};+use tauri::AppHandle;use crate::config;use crate::service::cli;@@ -16,13 +16,13 @@ use crate::service::workflow;use super::artifact::{ensure_plugin_entry_built, installed_package_name};use super::build_plugin_envs;-use super::harness_prefer_bundled_pnpm;use super::diagnose::{git_transport_hint, incompatible_versions, network_error_hint, pick_error_message,policy_blocked_versions, policy_verification_network_failure, store_mismatch_hint,IncompatibleVersion, PolicyBlockedVersion,};use super::errors;+use super::harness_prefer_bundled_pnpm;use super::installed_name;use super::is_actionable_plugin_ref;use super::is_installed;@@ -49,10 +49,8 @@ use crate::service::profile::profile_release_age_excluded;/// 逐项核验的结果汇总成一条错误消息(见 [`update_failure_payload`]):两个阶段各自的结算都/// 保留下来,前一段装上的目标不会被后一段的一般错误抹掉(见 [`UpdateFailure`])。pub async fn update_many(app_handle: &AppHandle, specs: &[String]) -> Result<(), String> {- let mut requested: Vec<(String, Option<String>)> = specs- .iter()- .map(|spec| split_upgrade_spec(spec))- .collect();+ let mut requested: Vec<(String, Option<String>)> =+ specs.iter().map(|spec| split_upgrade_spec(spec)).collect();if requested.iter().any(|(_, version)| version.is_none()) {resolve_missing_targets(app_handle, &mut requested).await;}@@ -100,7 +98,9 @@ async fn resolve_missing_targets(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()) {+ if !is_registry_version(&latest)+ || installed_package_version(&profile, id).as_deref() == Some(latest.as_str())+ {continue;}*version = Some(latest);@@ -246,7 +246,11 @@ fn policy_refusal_from_specs(specs: &[String], failure: &str) -> Option<String>fn force_upgrade_spec(id: &str, failure: &str) -> Option<String> {let payload = failure.strip_prefix(UPDATE_HOLD_PREFIX)?;let payload: serde_json::Value = serde_json::from_str(payload).ok()?;- if payload.get("retryable").and_then(serde_json::Value::as_bool) != Some(false) {+ if payload+ .get("retryable")+ .and_then(serde_json::Value::as_bool)+ != Some(false)+ {return None;}let latest = payload.get("latest").and_then(serde_json::Value::as_str)?;@@ -329,21 +333,22 @@ fn update_failure_payload(failures: Vec<UpdateFailure>) -> Option<String> {let mut blocked = Vec::new();let mut holds = Vec::new();let mut others = Vec::new();- let push_blocked = |entries: Vec<PolicyBlockedVersion>, blocked: &mut Vec<PolicyBlockedVersion>| {+ let push_blocked = |entries: Vec<PolicyBlockedVersion>,+ blocked: &mut Vec<PolicyBlockedVersion>| {for entry in entries {if !blocked.contains(&entry) {blocked.push(entry);}}};- let push_incompatible = |entries: Vec<IncompatibleVersion>,- incompatible: &mut Vec<IncompatibleVersion>| {- for entry in entries {- if !incompatible.contains(&entry) {- incompatible.push(entry);+ let push_incompatible =+ |entries: Vec<IncompatibleVersion>, incompatible: &mut Vec<IncompatibleVersion>| {+ for entry in entries {+ if !incompatible.contains(&entry) {+ incompatible.push(entry);+ }}- }- };+ };for failure in failures {// 版本兼容性拒绝照原样提升到顶层:前端只认这一行里的载荷来挂「授权后重跑」的按钮,// 落进下面的逐项失败里用户就只能看着一条纯文本,无从授权(与批量安装路径同形状)。@@ -652,7 +657,11 @@ pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Resu////// 版本豁免授权(`allow-version`,见 [`super::allow_version_exemptions`])同样走/// 这个形状:dsh 在转发给 pnpm 之前先拦下该动词,`--profile` 的拼装完全一致。-pub(super) fn single_plugin_args(profile: &str, action: &str, sub_args: &[String]) -> Vec<OsString> {+pub(super) fn single_plugin_args(+ profile: &str,+ action: &str,+ sub_args: &[String],+) -> Vec<OsString> {let mut args = vec![OsString::from("plugin"),OsString::from("--profile"),@@ -675,9 +684,8 @@ async fn run_plugin_command(if ids.is_empty() {return Err("PLUGIN_EMPTY_ID: plugin id is empty".to_string());}- let window = app_handle- .get_webview_window("main")- .ok_or("WINDOW_NOT_FOUND: main window missing")?;+ let window = crate::utils::operation_window(app_handle)+ .ok_or("WINDOW_NOT_FOUND: current profile window missing")?;cli::ensure_shims(app_handle)?;@@ -846,7 +854,9 @@ async fn verify_update_landed(expected: Option<&str>,) -> Result<(), String> {let profile = profile_dir(app_handle);- match update_verify_step(&profile, id, before, expected, || known_latest(app_handle, id)) {+ match update_verify_step(&profile, id, before, expected, || {+ known_latest(app_handle, id)+ }) {UpdateVerifyStep::Hold { detail, latest } => {// 只有「新版本太新」这一种成因有出路(授权那个精确版本即可过闸),因此把// 目标版本与「是否已在豁免清单里」一并带出去:已经授权过还是不动,说明成因@@ -873,9 +883,8 @@ async fn verify_update_landed(log::warn!("plugin {id} not resolvable to a package name, skipping entry verify");return Ok(());};- let window = app_handle- .get_webview_window("main")- .ok_or("WINDOW_NOT_FOUND: main window missing")?;+ let window = crate::utils::operation_window(app_handle)+ .ok_or("WINDOW_NOT_FOUND: current profile window missing")?;let envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle).await?);let pkg_dir = profile_dir(app_handle).join("node_modules").join(name);if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await {@@ -910,15 +919,16 @@ fn update_verify_step(if !reached {if let Some(before) = before {if dependency_fingerprint(profile, id).as_deref() == Some(before) {- let detail = installed_package_version(profile, id)- .unwrap_or_else(|| before.to_string());+ let detail =+ installed_package_version(profile, id).unwrap_or_else(|| before.to_string());// 目标版本优先用本次请求带来的版本(面板显示的那个),探测缓存只在没有时// 兜底:缓存没命中会让 `latest` 为空,用户点升级就只剩一句「没有变化」。let latest = expected.filter(|expected| *expected != detail && is_registry_version(expected)).map(str::to_string).or_else(|| {- known_latest().filter(|latest| latest != &detail && is_registry_version(latest))+ known_latest()+ .filter(|latest| latest != &detail && is_registry_version(latest))});log::warn!("dsh plugin update made no change for {id}, still at {detail}, newest {latest:?}"@@ -1121,7 +1131,10 @@ mod tests {assert_eq!(force_upgrade_spec("a", &hold("0.1.174", true)), None);assert_eq!(force_upgrade_spec("a", &hold("main", false)), None);assert_eq!(force_upgrade_spec("a", &hold("", false)), None);- assert_eq!(force_upgrade_spec("a", "PLUGIN_ENTRY_MISSING: broken"), None);+ assert_eq!(+ force_upgrade_spec("a", "PLUGIN_ENTRY_MISSING: broken"),+ None+ );}/// 面板给的条目才带版本:`@scope` 包按最后一个 `@` 切,非 registry 版本(git ref、`next`)@@ -1161,7 +1174,10 @@ mod tests {.to_string()));- assert_eq!(policy_refusal_from_specs(&specs, "PLUGIN_ENTRY_MISSING: broken"), None);+ assert_eq!(+ policy_refusal_from_specs(&specs, "PLUGIN_ENTRY_MISSING: broken"),+ None+ );assert_eq!(policy_refusal_from_specs(&["aaa@next".to_string()], failure),None@@ -1234,7 +1250,8 @@ mod tests {serde_json::json!([{"name": "aaa", "version": "1.0.0", "runtime_version": "0.2.0-rc.2"}]));- let message = update_failure_payload(UpdateFailure::stage(&specs, refusal)).expect("message");+ let message =+ update_failure_payload(UpdateFailure::stage(&specs, refusal)).expect("message");let entries = payload_of(&message, INCOMPATIBLE_PREFIX);assert_eq!(entries.as_array().expect("array").len(), 1);@@ -1441,7 +1458,9 @@ mod tests {assert!(is_registry_version("0.1.174"));assert!(is_registry_version("1.66.5"));assert!(!is_registry_version("next"));- assert!(!is_registry_version("b3a69187e1bac1bf6162e3d37d005e58bc2ee74e"));+ assert!(!is_registry_version(+ "b3a69187e1bac1bf6162e3d37d005e58bc2ee74e"+ ));assert!(!is_registry_version(""));}@@ -1592,7 +1611,10 @@ mod tests {Some("0.19.0"),|| None,);- assert!(matches!(step, UpdateVerifyStep::Entry), "版本已达目标必须继续核验入口");+ assert!(+ matches!(step, UpdateVerifyStep::Entry),+ "版本已达目标必须继续核验入口"+ );std::fs::remove_dir_all(&dir).ok();}diff --git a/src-tauri/src/service/plugin/internal/mod.rs b/src-tauri/src/service/plugin/internal/mod.rsindex 26cce6c5..66530b29 100644--- a/src-tauri/src/service/plugin/internal/mod.rs+++ b/src-tauri/src/service/plugin/internal/mod.rs@@ -17,7 +17,7 @@use std::collections::{HashMap, HashSet};use std::future::Future;use std::path::{Path, PathBuf};-use tauri::{AppHandle, Emitter};+use tauri::AppHandle;use super::cancel::terminate_owned_install;use super::install::install_internal;@@ -195,11 +195,17 @@ impl EnsureCoordinator {}}-static ENSURE_LOCK: std::sync::OnceLock<tokio::sync::Mutex<EnsureCoordinator>> =- std::sync::OnceLock::new();--fn ensure_lock() -> &'static tokio::sync::Mutex<EnsureCoordinator> {- ENSURE_LOCK.get_or_init(|| tokio::sync::Mutex::new(EnsureCoordinator::default()))+fn ensure_lock(profile: &str) -> std::sync::Arc<tokio::sync::Mutex<EnsureCoordinator>> {+ static COORDINATORS: std::sync::OnceLock<+ std::sync::Mutex<HashMap<String, std::sync::Arc<tokio::sync::Mutex<EnsureCoordinator>>>>,+ > = std::sync::OnceLock::new();+ COORDINATORS+ .get_or_init(std::sync::Mutex::default)+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .entry(profile.to_string())+ .or_default()+ .clone()}/// 在启动 Harness 前修复旧桌面目录遗留的 profile loader 状态。@@ -316,6 +322,12 @@ fn ensure_fingerprint(app_handle: &AppHandle, internal: &[PreinstallPluginInfo])}pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {+ let profile = crate::service::profile::active_profile(app_handle);+ crate::service::workflow::instances::scope(profile, ensure_scoped(app_handle)).await+}++async fn ensure_scoped(app_handle: &AppHandle) -> Result<(), String> {+ let lock = ensure_lock(&crate::service::profile::active_profile(app_handle));let presets = load_presets(app_handle);// 被核心吸收的内置插件(当前核心已超出其声明的全部核心版本区间)自愈不再装回,// 与 `uninstall_deprecated_plugins` 的退役判定同源,避免两边互相拉扯。@@ -330,7 +342,7 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {let reused = if internal.is_empty() {false} else {- ensure_lock().lock().await.reuse(fingerprint)+ lock.lock().await.reuse(fingerprint)};if reused {log::debug!(@@ -363,8 +375,7 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {if outcome.is_ok() {// 记「完成后的」指纹:本轮自己写回的状态(去重/修复/安装)就是已被核对过的// 状态,后到的那一路按同一状态算指纹即可命中,不会白跑第二轮。- ensure_lock()- .lock()+ lock.lock().await.record(ensure_fingerprint(app_handle, &internal));}@@ -410,39 +421,46 @@ async fn subscribe_or_start(app_handle: &AppHandle,internal: &[PreinstallPluginInfo],) -> EnsureSubscription {- let mut coordinator = ensure_lock().lock().await;+ let profile = crate::service::profile::active_profile(app_handle);+ let lock = ensure_lock(&profile);+ let mut coordinator = lock.lock().await;match coordinator.subscribe() {Some(subscription) => subscription,None => {let (id, owner, result_tx, result_rx, cancel_tx, cancel_rx) = coordinator.start();let app_handle = app_handle.clone();let internal = internal.to_vec();- tauri::async_runtime::spawn(async move {- let mut outcome =- run_ensure_operation(&app_handle, &internal, owner, cancel_tx, cancel_rx).await;- // 强杀返回不等于持有句柄的 wait 已完成;必须等精确 owner 的 PID- // 守卫随 wait 退出,才能发布结果并允许 Retry 创建下一次 flight。-- if !wait_for_owner_release(owner, ENSURE_OWNER_DRAIN_TIMEOUT).await {- let reason = format!(+ let lock = lock.clone();+ tauri::async_runtime::spawn(crate::service::workflow::instances::scope(+ profile,+ async move {+ let mut outcome =+ run_ensure_operation(&app_handle, &internal, owner, cancel_tx, cancel_rx)+ .await;+ // 强杀返回不等于持有句柄的 wait 已完成;必须等精确 owner 的 PID+ // 守卫随 wait 退出,才能发布结果并允许 Retry 创建下一次 flight。++ if !wait_for_owner_release(owner, ENSURE_OWNER_DRAIN_TIMEOUT).await {+ let reason = format!("INTERNAL_PLUGIN_PROCESS_REAP_TIMEOUT: plugin process owner {owner:?} remained active for {} seconds",ENSURE_OWNER_DRAIN_TIMEOUT.as_secs());- log::error!("{reason}");- outcome = Err(reason.clone());- let _ = result_tx.send(Some(outcome));- ensure_lock().lock().await.mark_cleanup_failed(id, reason);- // 保留 cleanup-failed flight 与唯一 owner;进程锁仍由 wait 线程持有。- // 若系统最终完成 reap,再释放 flight 允许后续 Retry。- while super::process::active_plugin_pid(owner).is_some() {- tokio::time::sleep(ENSURE_OWNER_DRAIN_INTERVAL).await;+ log::error!("{reason}");+ outcome = Err(reason.clone());+ let _ = result_tx.send(Some(outcome));+ lock.lock().await.mark_cleanup_failed(id, reason);+ // 保留 cleanup-failed flight 与唯一 owner;进程锁仍由 wait 线程持有。+ // 若系统最终完成 reap,再释放 flight 允许后续 Retry。+ while super::process::active_plugin_pid(owner).is_some() {+ tokio::time::sleep(ENSURE_OWNER_DRAIN_INTERVAL).await;+ }+ lock.lock().await.finish(id);+ return;}- ensure_lock().lock().await.finish(id);- return;- }- ensure_lock().lock().await.finish(id);- let _ = result_tx.send(Some(outcome));- });+ lock.lock().await.finish(id);+ let _ = result_tx.send(Some(outcome));+ },+ ));EnsureSubscription::Running(result_rx)}}@@ -518,7 +536,10 @@ async fn receive_flight_result(/// 取消共享的内置插件安装并等待拥有者完成清理,确保 Retry 不会叠加新进程。pub(crate) async fn cancel() -> Result<(), String> {let mut result = {- let mut coordinator = ensure_lock().lock().await;+ let profile =+ crate::service::workflow::instances::current_profile().unwrap_or_else(|| "web".into());+ let lock = ensure_lock(&profile);+ let mut coordinator = lock.lock().await;let Some(active) = &coordinator.active else {return Ok(());};@@ -609,7 +630,8 @@ fn emit_phase(completed: usize,total: usize,) {- let _ = app_handle.emit(+ crate::service::workflow::instances::emit(+ app_handle,"internal-plugins-phase",InternalPluginsPhase {phase,@@ -856,7 +878,8 @@ async fn ensure_inner(// 桌面端自建链接并补齐清单,让内置插件落盘、启动继续,而不是把应用永久// 卡在 Plugin installation 阶段(见 [`materialize`])。if is_link_materialization_failure(&e, &need) {- let _ = app_handle.emit(+ crate::service::workflow::instances::emit(+ app_handle,PREINSTALL_LOG_EVENT,PreinstallLogPayload {line: "[harness] pnpm 无法回读新建的插件链接,改由应用直接建立链接…"@@ -1143,6 +1166,42 @@ fn is_legacy_profile_fallback_target(target: &Path) -> bool {#[cfg(test)]mod tests {+ #[tokio::test]+ async fn unscoped_flight_cleanup_uses_the_acquired_coordinator() {+ use crate::service::workflow::instances;+ let acquired = super::ensure_lock("ensure-stored-profile");+ let (id, _, _, _, _, _) = acquired.lock().await.start();+ instances::scope("ensure-stored-profile".into(), async {+ let spawned = super::ensure_lock(&instances::current_profile().unwrap());+ assert!(std::sync::Arc::ptr_eq(&acquired, &spawned));+ spawned.lock().await.finish(id);+ })+ .await;+ assert!(acquired.lock().await.subscribe().is_none());+ }++ #[tokio::test]+ async fn internal_plugin_flights_are_shared_only_within_profile() {+ use crate::service::workflow::instances;+ instances::scope("ensure-profile-a".into(), async {+ let first = super::ensure_lock(&instances::current_profile().unwrap());+ assert!(std::sync::Arc::ptr_eq(+ &first,+ &super::ensure_lock(&instances::current_profile().unwrap())+ ));+ let (id, _, _, _, _, _) = first.lock().await.start();+ instances::scope("ensure-profile-b".into(), async {+ let second = super::ensure_lock(&instances::current_profile().unwrap());+ assert!(!std::sync::Arc::ptr_eq(&first, &second));+ assert!(second.lock().await.subscribe().is_none());+ })+ .await;+ assert!(first.lock().await.subscribe().is_some());+ first.lock().await.finish(id);+ })+ .await;+ }+use super::*;#[test]diff --git a/src-tauri/src/service/plugin/process.rs b/src-tauri/src/service/plugin/process.rsindex afde0d61..f3d703d3 100644--- a/src-tauri/src/service/plugin/process.rs+++ b/src-tauri/src/service/plugin/process.rs@@ -12,7 +12,7 @@ use std::io::{BufRead, BufReader, Read};use std::path::Path;use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, Mutex, OnceLock};-use tauri::{Emitter, WebviewWindow};+use tauri::{Emitter, Manager, WebviewWindow};use crate::utils::decode_process_line;@@ -323,6 +323,7 @@ pub(crate) async fn run_plugin_process(window: &WebviewWindow,owner: ProcessOwner,) -> Result<(i32, String), String> {+ let profile = crate::service::profile::active_profile(window.app_handle());let process_guard = acquire_process_lock().await?;let captured = Arc::new(Mutex::new(String::new()));@@ -339,22 +340,24 @@ pub(crate) async fn run_plugin_process(let handle = WaitableHandle(handle);let exit_code = tauri::async_runtime::spawn_blocking(move || {- let _process_guard = process_guard;- let _pid_guard = pid_guard;- use windows_sys::Win32::Foundation::CloseHandle;- use windows_sys::Win32::System::Threading::{- GetExitCodeProcess, WaitForSingleObject, INFINITE,- };- let handle = handle;- unsafe {- let wait = WaitForSingleObject(handle.0, INFINITE);- let mut code: u32 = 0;- if GetExitCodeProcess(handle.0, &mut code) == 0 {- code = wait;+ crate::service::workflow::instances::scope_sync(profile, || {+ let _process_guard = process_guard;+ let _pid_guard = pid_guard;+ use windows_sys::Win32::Foundation::CloseHandle;+ use windows_sys::Win32::System::Threading::{+ GetExitCodeProcess, WaitForSingleObject, INFINITE,+ };+ let handle = handle;+ unsafe {+ let wait = WaitForSingleObject(handle.0, INFINITE);+ let mut code: u32 = 0;+ if GetExitCodeProcess(handle.0, &mut code) == 0 {+ code = wait;+ }+ CloseHandle(handle.0);+ code as i32}- CloseHandle(handle.0);- code as i32- }+ })}).await.map_err(|e| format!("PREINSTALL_WAIT: {e}"))?;@@ -393,9 +396,11 @@ pub(crate) async fn run_plugin_process(}let exit_code = tauri::async_runtime::spawn_blocking(move || {- let _process_guard = process_guard;- let _pid_guard = pid_guard;- child.wait().map(|s| s.code().unwrap_or(1)).unwrap_or(1)+ crate::service::workflow::instances::scope_sync(profile, || {+ let _process_guard = process_guard;+ let _pid_guard = pid_guard;+ child.wait().map(|s| s.code().unwrap_or(1)).unwrap_or(1)+ })}).await.map_err(|e| format!("PREINSTALL_WAIT: {e}"))?;@@ -465,6 +470,22 @@ fn spawn_line_emitter<R: Read + Send + 'static>(mod tests {use super::*;+ #[tokio::test]+ async fn blocking_plugin_task_retains_captured_profile() {+ use crate::service::workflow::instances;+ instances::scope("plugin-window-profile".into(), async {+ let profile = instances::current_profile().unwrap();+ let captured = tauri::async_runtime::spawn_blocking(move || {+ instances::scope_sync(profile, instances::current_profile)+ })+ .await+ .unwrap();+ assert_eq!(captured.as_deref(), Some("plugin-window-profile"));+ })+ .await;+ assert_eq!(instances::current_profile(), None);+ }+#[test]fn drain_captured_preserves_exact_output_and_clears_shared_buffer() {let captured = Arc::new(Mutex::new(diff --git a/src-tauri/src/service/plugin/verify.rs b/src-tauri/src/service/plugin/verify.rsindex 5913d556..0beac63c 100644--- a/src-tauri/src/service/plugin/verify.rs+++ b/src-tauri/src/service/plugin/verify.rs@@ -20,7 +20,7 @@use std::collections::HashMap;use std::ffi::OsString;use std::path::{Path, PathBuf};-use tauri::{AppHandle, Manager};+use tauri::AppHandle;use crate::config;use crate::service::cli;@@ -152,9 +152,8 @@ async fn repair_with_pnpm_install(app_handle: &AppHandle, profile: &Path) -> Res.any(|arg| arg.as_os_str() == bundled.as_os_str());args.push(OsString::from("install"));- let window = app_handle- .get_webview_window("main")- .ok_or("WINDOW_NOT_FOUND: main window missing")?;+ let window = crate::utils::operation_window(app_handle)+ .ok_or("WINDOW_NOT_FOUND: current profile window missing")?;let envs = build_plugin_envs(app_handle, prefer_bundled);log::info!("repairing profile node_modules via pnpm install in {}",diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rsindex f7a1df57..ea66e9d0 100644--- a/src-tauri/src/service/plugin/watch.rs+++ b/src-tauri/src/service/plugin/watch.rs@@ -11,12 +11,13 @@//! 的勾选态,这里解析「实际已安装」的插件元信息(名称/版本/描述/仓库地址///! 是否启动加载),供前端做已安装列表展示与后续插件管理。+use crate::service::workflow::instances;use serde::{Deserialize, Serialize};use std::collections::{HashMap, HashSet};use std::path::{Path, PathBuf};use std::sync::{Mutex, OnceLock};use std::time::{Duration, Instant};-use tauri::{AppHandle, Emitter};+use tauri::AppHandle;use super::errors::{self, PluginError};use super::installed::{installed_name, profile_dir, ProfilePackageJson};@@ -244,10 +245,12 @@ pub fn list(app_handle: &AppHandle) -> Vec<DshPlugin> {/// 同时把监控指纹同步到当前状态,避免紧接着的下一次轮询重复推送同一列表。pub fn force_emit(app_handle: &AppHandle) {let fp = fingerprint(app_handle);- let mut state = STATE.get_or_init(Mutex::default).lock().unwrap();+ let profile = crate::service::profile::active_profile(app_handle);+ let mut states = STATE.get_or_init(Mutex::default).lock().unwrap();+ let state = states.entry(profile).or_default();state.pending_fp = None;state.last_fp = fp;- drop(state);+ drop(states);emit(app_handle);}@@ -289,13 +292,21 @@ struct WatchState {pending_fp: Option<String>,}-static STATE: OnceLock<Mutex<WatchState>> = OnceLock::new();+static STATE: OnceLock<Mutex<HashMap<String, WatchState>>> = OnceLock::new();/// 秒级轮询入口(由 scheduler 永久循环调用):指纹变化且超过防抖窗口时,/// 重新解析插件列表并推送 `dsh-plugins-updated` 事件。pub fn check_and_emit(app_handle: &AppHandle) {+ if instances::current_profile().is_none() {+ for profile in instances::profiles() {+ instances::scope_sync(profile, || check_and_emit(app_handle));+ }+ return;+ }let fp = fingerprint(app_handle);- let mut state = STATE.get_or_init(Mutex::default).lock().unwrap();+ let profile = crate::service::profile::active_profile(app_handle);+ let mut states = STATE.get_or_init(Mutex::default).lock().unwrap();+ let state = states.entry(profile).or_default();if state.last_fp.as_deref() == fp.as_deref() {return;@@ -321,7 +332,7 @@ fn emit(app_handle: &AppHandle) {"dsh plugins changed, emitting {} plugin(s) to frontend",plugins.len());- let _ = app_handle.emit(PLUGINS_UPDATED_EVENT, &plugins);+ instances::emit(app_handle, PLUGINS_UPDATED_EVENT, &plugins);}#[cfg(test)]diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rsindex 1b1689ad..675cbc74 100644--- a/src-tauri/src/service/profile/mod.rs+++ b/src-tauri/src/service/profile/mod.rs@@ -159,7 +159,10 @@ pub(crate) fn ensure_profile_pnpm_policy(app_handle: &AppHandle) -> Result<(), S.iter().map(|package| (*package).to_string()).collect();- release_age_excludes_at(&profile_dir_of(app_handle, &active_profile(app_handle)), &entries)+ release_age_excludes_at(+ &profile_dir_of(app_handle, &active_profile(app_handle)),+ &entries,+ )}/// 档案的 `minimumReleaseAgeExclude` 里是否已经有这个精确 `包名@版本`。@@ -311,6 +314,9 @@ pub(crate) fn release_age_excludes_at(dir: &Path, entries: &[String]) -> Result</// 清理),回退默认 web。全新机器上 `profiles/` 尚未初始化时同样回退 web/// (web 由 dsh 启动/插件操作时按需初始化)。pub fn active_profile(app_handle: &AppHandle) -> String {+ if let Some(profile) = crate::service::workflow::instances::current_profile() {+ return profile;+ }let stored = config::get_store_dat_setting(app_handle).active_profile;if !stored.is_empty()&& stored != DEFAULT_PROFILE@@ -645,7 +651,7 @@ pub fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {"PROFILE_DEFAULT_NOT_REMOVABLE: the default profile cannot be removed".to_string(),);}- if id == active_profile(app_handle) {+ if id == active_profile(app_handle) || crate::service::workflow::instances::is_attached(id) {return Err("PROFILE_ACTIVE_NOT_REMOVABLE: the active profile cannot be removed".to_string(),);diff --git a/src-tauri/src/service/scheduler/mod.rs b/src-tauri/src/service/scheduler/mod.rsindex 7ea4f472..bb58a7f4 100644--- a/src-tauri/src/service/scheduler/mod.rs+++ b/src-tauri/src/service/scheduler/mod.rs@@ -20,25 +20,33 @@ async fn scheduler_permanent_loop(app_handle: AppHandle) {let mut interval = time::interval(Duration::from_secs(5));loop {- let current_status = status::get_status();- let port = crate::config::get_store_dat_setting(&app_handle).port;- let is_dsh_running =- crate::service::workflow::has_owned_process() && utils::is_dsh_running(port).await;- log::trace!("DSH status check: dsh_running={}", is_dsh_running);- if is_dsh_running && current_status != Status::Running {- status::set_status(Status::Running);- status::emit_status(&app_handle);- }- if !crate::service::workflow::has_owned_process() && current_status == Status::Running {- log::warn!(+ for profile in crate::service::workflow::instances::profiles() {+ crate::service::workflow::instances::scope(profile, async {+ let current_status = status::get_status();+ let port = crate::service::workflow::instances::port(&app_handle);+ let is_dsh_running = crate::service::workflow::has_owned_process()+ && utils::is_dsh_running(port).await;+ log::trace!("DSH status check: dsh_running={}", is_dsh_running);+ if is_dsh_running && current_status != Status::Running {+ status::set_status(Status::Running);+ status::emit_status(&app_handle);+ }+ if !crate::service::workflow::has_owned_process()+ && current_status == Status::Running+ {+ log::warn!("DSH status check: no owned process yet status Running; resetting to Stopped");- status::set_status(Status::Stopped);- status::emit_status(&app_handle);+ status::set_status(Status::Stopped);+ status::emit_status(&app_handle);+ }++ // 已安装插件文件监控:指纹变化(防抖后)推送 `dsh-plugins-updated`+ crate::service::plugin::watch::check_and_emit(&app_handle);+ })+ .await;}crate::config::check_and_emit_theme(&app_handle);- // 已安装插件文件监控:指纹变化(防抖后)推送 `dsh-plugins-updated`- crate::service::plugin::watch::check_and_emit(&app_handle);interval.tick().await;}}diff --git a/src-tauri/src/service/update/install.rs b/src-tauri/src/service/update/install.rsindex d71ea583..9e097d47 100644--- a/src-tauri/src/service/update/install.rs+++ b/src-tauri/src/service/update/install.rs@@ -769,18 +769,15 @@ pub async fn open_installer(app_handle: &AppHandle, path: String) -> Result<(),"UPDATE_CHANNEL_UNSUPPORTED: nightly builds do not install stable updates".into(),);}- // 更新前先停下本应用持有的 Harness 服务:安装器在安装时会强杀桌面端进程- // (CheckIfAppIsRunning → taskkill),跳过正常退出路径的 stop_on_exit,导致- // Harness 子进程变成孤儿继续占用配置端口。若此刻不提前停掉,更新后新实例- // 启动会撞上 EADDRINUSE(旧 Harness 仍占着端口),表现为「更新后进不去」。- // 提前停止 → 端口释放并清掉 .harness.pid 标记,更新后启动即可绑定原端口。- // 仅在确有持有进程时才停(stop 在无持有进程时也会短暂等待端口释放,白耗- // 约 0.8s);停止失败只告警不阻断——它是避免端口冲突的辅助手段,打开失败- // 另有 UPDATE_OPEN 的错误提示。- if workflow::has_owned_process() {- if let Err(e) = workflow::stop(app_handle.clone()).await {- log::warn!("Failed to stop Harness before opening installer: {}", e);- }+ let _transition = workflow::acquire_core_transition().await?;+ for profile in workflow::instances::profiles() {+ workflow::instances::scope(profile, async {+ if workflow::has_owned_process() {+ workflow::stop(app_handle.clone()).await?;+ }+ Ok::<(), String>(())+ })+ .await?;}open_installer_now(app_handle, &path)?;// 安装包已交给系统 → 清除「待安装」标记,避免退出应用时重复拉起安装器。@@ -802,6 +799,35 @@ pub async fn open_installer(app_handle: &AppHandle, path: String) -> Result<(),mod tests {use super::*;+ #[test]+ fn immediate_installer_stops_every_profile_before_handoff_and_propagates_failure() {+ let source = include_str!("install.rs");+ let opening = source+ .split("pub async fn open_installer(")+ .nth(1)+ .unwrap()+ .split("#[cfg(test)]")+ .next()+ .unwrap();+ let transition = opening+ .find("workflow::acquire_core_transition().await?")+ .unwrap();+ let profiles = opening+ .find("for profile in workflow::instances::profiles()")+ .unwrap();+ let scope = opening+ .find("workflow::instances::scope(profile, async {")+ .unwrap();+ let stop = opening+ .find("workflow::stop(app_handle.clone()).await?")+ .unwrap();+ let handoff = opening+ .find("open_installer_now(app_handle, &path)?")+ .unwrap();+ assert!(transition < profiles && profiles < scope && scope < stop && stop < handoff);+ assert!(opening[stop..handoff].contains(".await?;"));+ }+#[test]fn prune_installers_keeps_up_to_five() {let dir = tempfile::tempdir().unwrap();diff --git a/src-tauri/src/service/workflow/health.rs b/src-tauri/src/service/workflow/health.rsindex 07507a0f..0b9309d6 100644--- a/src-tauri/src/service/workflow/health.rs+++ b/src-tauri/src/service/workflow/health.rs@@ -6,7 +6,7 @@ use futures_util::StreamExt;use crate::config;-use super::process::{has_owned_process, LAUNCH_GUARD};+use super::process::{has_owned_process, launch_guard};use super::startup;use super::utils;@@ -134,7 +134,7 @@ async fn probe_client_bundles(/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)pub async fn proxy_health_check(port: u16) -> Result<String, String> {if !has_owned_process() {- return Err(not_owned_probe_signal(LAUNCH_GUARD.load(Ordering::SeqCst)).to_string());+ return Err(not_owned_probe_signal(launch_guard().load(Ordering::SeqCst)).to_string());}let client = utils::loopback_http_client(config::HEALTH_CHECK_TIMEOUT).map_err(|e| format!("HARNESS_HEALTH_CLIENT_FAILED: {e}"))?;@@ -166,7 +166,7 @@ fn ownership_recheck_signal(owned: bool, launch_in_progress: bool) -> Result<(),/// 这里重跑完整健康探测,代价是重新拉取全部客户端 bundle(实测 93 个 / 18MB / 311ms),/// 而 ownership 只取决于进程槽位与启动守卫,故改用这条查询。pub fn recheck_ownership() -> Result<(), String> {- ownership_recheck_signal(has_owned_process(), LAUNCH_GUARD.load(Ordering::SeqCst))+ ownership_recheck_signal(has_owned_process(), launch_guard().load(Ordering::SeqCst))}#[cfg(test)]@@ -230,7 +230,7 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let port = listener.local_addr().unwrap().port();- let (release, mut hold) = tokio::sync::oneshot::channel::<()>();+ let (release, hold) = tokio::sync::oneshot::channel::<()>();let server = tokio::spawn(async move {if let Ok((mut socket, _)) = listener.accept().await {let mut request = [0; 4096];diff --git a/src-tauri/src/service/workflow/install.rs b/src-tauri/src/service/workflow/install.rsindex 1cb64368..cd0ff446 100644--- a/src-tauri/src/service/workflow/install.rs+++ b/src-tauri/src/service/workflow/install.rs@@ -4,7 +4,6 @@use crate::config;use crate::service::download;use crate::service::download::Installable;-use tauri::Manager;use super::process::{has_owned_process, stop, terminate_stale_harness_processes};@@ -17,6 +16,8 @@ pub async fn install(app_handle: &tauri::AppHandle,mut dsh_latest: Option<download::LatestDshPkg>,) -> Result<bool, String> {+ let _transition = super::process::acquire_core_transition().await?;+ super::instances::require_exclusive_profile()?;log::info!("Starting installation process");// dsh 任务实际下载解压时置 truelet mut dsh_updated = false;@@ -36,14 +37,16 @@ pub async fn install(// 枚举/结束涉及 powershell 枚举与 taskkill(同步阻塞),移出 Tokio 线程。{let handle = app_handle.clone();- tauri::async_runtime::spawn_blocking(move || terminate_stale_harness_processes(&handle))- .await- .map_err(|e| format!("STOP_FAILED: {e}"))??;+ let profile = crate::service::profile::active_profile(app_handle);+ tauri::async_runtime::spawn_blocking(move || {+ super::instances::scope_sync(profile, || terminate_stale_harness_processes(&handle))+ })+ .await+ .map_err(|e| format!("STOP_FAILED: {e}"))??;}- let window = app_handle- .get_webview_window("main")- .ok_or("Failed to get main window")?;+ let window = crate::utils::operation_window(app_handle)+ .ok_or("WINDOW_NOT_FOUND: current profile window missing")?;log::debug!("Main window obtained");// 依赖任务清单的唯一构造点在下载层,安装流程与映射回写共用同一组任务。let tasks = download::tasks();@@ -227,3 +230,28 @@ pub async fn install(Ok(dsh_updated)}++#[cfg(test)]+mod tests {+ #[test]+ fn installation_holds_core_transition_before_checks_and_shared_file_changes() {+ let source = include_str!("install.rs")+ .split("#[cfg(test)]")+ .next()+ .unwrap();+ let transition = source+ .find("let _transition = super::process::acquire_core_transition().await?;")+ .unwrap();+ for effect in [+ "super::instances::require_exclusive_profile()?",+ "if has_owned_process()",+ "download::ensure_extract",+ ] {+ assert!(+ transition < source.find(effect).unwrap(),+ "{effect} must be serialized with launch"+ );+ }+ assert!(!source.contains("drop(_transition)"));+ }+}diff --git a/src-tauri/src/service/workflow/instances.rs b/src-tauri/src/service/workflow/instances.rsnew file mode 100644index 00000000..7cf97d2e--- /dev/null+++ b/src-tauri/src/service/workflow/instances.rs@@ -0,0 +1,266 @@+use std::collections::HashMap;+use std::future::Future;+use std::sync::{Arc, Mutex, OnceLock};++use super::status::Status;++tokio::task_local! {+ static PROFILE: String;+}++#[derive(Default)]+struct Registry {+ windows: HashMap<String, String>,+ instances: HashMap<String, Arc<Instance>>,+}++pub(super) struct Instance {+ pub process: Mutex<Option<super::process::OwnedProcess>>,+ pub launching: Arc<std::sync::atomic::AtomicBool>,+ pub status: Mutex<Status>,+ pub port: Mutex<Option<u16>>,+}++impl Default for Instance {+ fn default() -> Self {+ Self {+ process: Mutex::new(None),+ launching: Arc::new(std::sync::atomic::AtomicBool::new(false)),+ status: Mutex::new(Status::Initial),+ port: Mutex::new(None),+ }+ }+}++fn registry() -> &'static Mutex<Registry> {+ static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();+ REGISTRY.get_or_init(|| Mutex::new(Registry::default()))+}++pub fn current_profile() -> Option<String> {+ PROFILE.try_with(Clone::clone).ok()+}++pub async fn scope<T>(profile: String, future: impl Future<Output = T>) -> T {+ PROFILE.scope(profile, future).await+}++pub fn scope_sync<T>(profile: String, operation: impl FnOnce() -> T) -> T {+ PROFILE.sync_scope(profile, operation)+}++pub(super) fn instance() -> Arc<Instance> {+ let profile = current_profile().unwrap_or_else(|| "web".into());+ instance_of(&profile)+}++pub(super) fn instance_of(profile: &str) -> Arc<Instance> {+ registry()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .instances+ .entry(profile.to_string())+ .or_default()+ .clone()+}++pub fn profiles() -> Vec<String> {+ registry()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .instances+ .keys()+ .cloned()+ .collect()+}++pub fn window_profile(app: &tauri::AppHandle, label: &str) -> String {+ let mut registry = registry().lock().unwrap_or_else(|error| error.into_inner());+ registry+ .windows+ .entry(label.to_string())+ .or_insert_with(|| crate::service::profile::active_profile(app))+ .clone()+}++pub fn window_uses_profile(label: &str, profile: &str) -> bool {+ registry()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .windows+ .get(label)+ .is_some_and(|value| value == profile)+}++pub fn bind_window(label: &str, profile: &str) -> Option<String> {+ registry()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .windows+ .insert(label.into(), profile.into())+}++pub fn release_window(label: &str) -> Option<String> {+ let mut registry = registry().lock().unwrap_or_else(|error| error.into_inner());+ let profile = registry.windows.remove(label)?;+ (!registry.windows.values().any(|value| value == &profile)).then_some(profile)+}++pub fn attached_elsewhere(profile: &str, label: &str) -> bool {+ registry()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .windows+ .iter()+ .any(|(window, value)| window != label && value == profile)+}++pub fn require_exclusive_profile() -> Result<(), String> {+ let profile = current_profile().unwrap_or_else(|| "web".into());+ let registry = registry().lock().unwrap_or_else(|error| error.into_inner());+ if registry.windows.values().any(|value| value != &profile)+ || registry.instances.iter().any(|(id, instance)| {+ id != &profile+ && instance+ .process+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .is_some()+ })+ {+ return Err("CORE_IN_USE: close windows using other profiles before changing shared core or data files".into());+ }+ Ok(())+}++pub fn is_attached(profile: &str) -> bool {+ registry()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .windows+ .values()+ .any(|value| value == profile)+}++pub fn emit<R: tauri::Runtime, S: serde::Serialize + Clone>(+ app: &tauri::AppHandle<R>,+ event: &str,+ payload: S,+) {+ use tauri::Emitter;+ let Some(profile) = current_profile() else {+ let _ = app.emit(event, payload);+ return;+ };+ let labels: Vec<String> = registry()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .windows+ .iter()+ .filter(|(_, value)| **value == profile)+ .map(|(label, _)| label.clone())+ .collect();+ for label in labels {+ let _ = app.emit_to(+ tauri::EventTarget::webview_window(label),+ event,+ payload.clone(),+ );+ }+}++pub fn port(app: &tauri::AppHandle) -> u16 {+ instance()+ .port+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .unwrap_or_else(|| crate::config::get_store_dat_setting(app).port)+}++pub fn set_port(port: u16) {+ *instance()+ .port+ .lock()+ .unwrap_or_else(|error| error.into_inner()) = Some(port);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn profile_instances_reuse_and_isolate_runtime_state() {+ scope("instance-test-a".into(), async {+ set_port(41001);+ *instance().status.lock().unwrap() = Status::Running;+ let first = instance();+ assert!(Arc::ptr_eq(&first, &instance()));+ scope("instance-test-b".into(), async {+ assert!(!Arc::ptr_eq(&first, &instance()));+ assert_eq!(*instance().port.lock().unwrap(), None);+ assert_eq!(*instance().status.lock().unwrap(), Status::Initial);+ set_port(41002);+ })+ .await;+ assert_eq!(*instance().port.lock().unwrap(), Some(41001));+ assert_eq!(*instance().status.lock().unwrap(), Status::Running);+ })+ .await;+ assert_eq!(current_profile(), None);+ }++ #[tokio::test]+ async fn concurrent_profiles_keep_scope_and_launch_guards_separate() {+ let (a, b) = tokio::join!(+ scope("concurrent-profile-a".into(), async {+ instance()+ .launching+ .store(true, std::sync::atomic::Ordering::SeqCst);+ tokio::task::yield_now().await;+ assert_eq!(current_profile().as_deref(), Some("concurrent-profile-a"));+ instance()+ .launching+ .store(false, std::sync::atomic::Ordering::SeqCst);+ instance()+ }),+ scope("concurrent-profile-b".into(), async {+ tokio::task::yield_now().await;+ assert!(!instance()+ .launching+ .load(std::sync::atomic::Ordering::SeqCst));+ assert_eq!(current_profile().as_deref(), Some("concurrent-profile-b"));+ instance()+ })+ );+ assert!(!Arc::ptr_eq(&a, &b));+ }++ #[tokio::test]+ async fn synchronous_override_restores_async_scope_even_after_panic() {+ scope("outer-scope".into(), async {+ scope_sync("inner-scope".into(), || {+ assert_eq!(current_profile().as_deref(), Some("inner-scope"));+ });+ assert_eq!(current_profile().as_deref(), Some("outer-scope"));+ let _ =+ std::panic::catch_unwind(|| scope_sync("panic-scope".into(), || panic!("test")));+ assert_eq!(current_profile().as_deref(), Some("outer-scope"));+ })+ .await;+ assert_eq!(current_profile(), None);+ }++ #[test]+ fn window_release_only_reclaims_last_profile_reference() {+ bind_window("instance-window-a", "window-profile-a");+ bind_window("instance-window-b", "window-profile-a");+ assert_eq!(release_window("instance-window-a"), None);+ bind_window("instance-window-b", "window-profile-b");+ assert!(!is_attached("window-profile-a"));+ assert!(is_attached("window-profile-b"));+ assert_eq!(+ release_window("instance-window-b"),+ Some("window-profile-b".into())+ );+ }+}diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rsindex e97cbd2e..445602a4 100644--- a/src-tauri/src/service/workflow/launch.rs+++ b/src-tauri/src/service/workflow/launch.rs@@ -19,8 +19,8 @@ use super::process::set_owned_process_with_handle;#[cfg(unix)]use super::process::warn_if_inotify_watch_limit_low;use super::process::{- has_owned_process, on_owned_process_exit, stop, take_startup_sweep,- terminate_stale_harness_processes, LaunchGuard, LAUNCH_GUARD,+ has_owned_process, launch_guard, on_owned_process_exit, stop, take_startup_sweep,+ terminate_stale_harness_processes, LaunchGuard,};use super::status;use super::sweep::persist_harness_pid;@@ -309,6 +309,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {*phase_started = now;};let mut setting = config::get_store_dat_setting(&app_handle);+ setting.port = super::instances::port(&app_handle);let node_binary_path = config::get_node_binary_path(&app_handle);let _transition_guard = super::process::acquire_core_transition().await?;let dsh_binary_path = crate::service::core::active_dsh_binary(&app_handle);@@ -333,7 +334,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {log::info!("Owned Harness process is already running, skipping launch");return Ok(());}- if LAUNCH_GUARD+ if launch_guard().compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err(){@@ -353,19 +354,22 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// 一次全量枚举约 0.3–0.6s),因此只在尚未清扫时才执行。{let handle = app_handle.clone();+ let profile = crate::service::profile::active_profile(&app_handle);tauri::async_runtime::spawn_blocking(move || {- if take_startup_sweep() {- let result = terminate_stale_harness_processes(&handle);- if result.is_err() {- super::process::retry_startup_sweep();+ super::instances::scope_sync(profile, || {+ if take_startup_sweep() {+ let result = terminate_stale_harness_processes(&handle);+ if result.is_err() {+ super::process::retry_startup_sweep();+ }+ result+ } else {+ log::debug!(+ "Skipping pre-launch stale Harness sweep: already swept during this launch"+ );+ Ok(())}- result- } else {- log::debug!(- "Skipping pre-launch stale Harness sweep: already swept during this launch"- );- Ok(())- }+ })}).await.map_err(|error| format!("HARNESS_SWEEP_FAILED: {error}"))??;@@ -377,9 +381,12 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// wait_for_port_release 探测:既然放弃旧端口,就无需等它释放。let heal_target = setting.manual_port.unwrap_or(config::default_port());let entry = dsh_binary_path.clone();+ let profile = crate::service::profile::active_profile(&app_handle);let heal_target_free = tauri::async_runtime::spawn_blocking(move || {- wait_for_port_release(heal_target, PORT_RELEASE_WAIT);- prepare_port(&entry, heal_target)+ super::instances::scope_sync(profile, || {+ wait_for_port_release(heal_target, PORT_RELEASE_WAIT);+ prepare_port(&entry, heal_target)+ })}).await.map_err(|error| format!("HARNESS_CLEANUP_FAILED: {error}"))??;@@ -391,7 +398,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {healed_port);setting.port = healed_port;- config::set_store_dat_setting(&app_handle, setting.clone());+ super::instances::set_port(setting.port);}// 端口冲突时从当前值开始逐个递增,并持久化最终选择供所有调用方复用。@@ -403,11 +410,14 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// 有界轮询是阻塞等待,交给阻塞线程池,避免占用启动所在的 Tokio 执行线程。let port = setting.port;let entry = dsh_binary_path.clone();+ let profile = crate::service::profile::active_profile(&app_handle);let available_port = tauri::async_runtime::spawn_blocking(move || {- if port != heal_target {- wait_for_port_release(port, PORT_RELEASE_WAIT);- }- find_available_port(port, &entry)+ super::instances::scope_sync(profile, || {+ if port != heal_target {+ wait_for_port_release(port, PORT_RELEASE_WAIT);+ }+ find_available_port(port, &entry)+ })}).await.map_err(|error| format!("HARNESS_CLEANUP_FAILED: {error}"))??;@@ -418,8 +428,9 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {available_port);setting.port = available_port;- config::set_store_dat_setting(&app_handle, setting.clone());+ super::instances::set_port(setting.port);}+ super::instances::set_port(setting.port);mark_phase("stale_sweep_and_port", &mut phase_started);// 构造环境变量:隔离的 $DSH_HOME + 隐私默认(关闭遥测)@@ -912,26 +923,29 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {set_owned_process_with_handle(pid, handle_value);let exit_app_handle = app_handle.clone();let exit_log_path = log_path.clone();- std::thread::spawn(move || unsafe {- let process_handle = handle_value as HANDLE;- WaitForSingleObject(process_handle, INFINITE);- // 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为- // Stopped(原有实现只清 PID、状态永远停留在 Running)。- // 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。- // take 返回值里的句柄由本线程负责关闭(不会与- // terminate_owned_process 重复 close——进程已 exit,- // 通常是本线程取走)。- let owned = on_owned_process_exit(&exit_app_handle, pid, |owned| {- log_fatal_report(&exit_log_path, &report_path);- let handle = owned.handle as HANDLE;- let mut exit_code: u32 = 0;- (GetExitCodeProcess(handle, &mut exit_code) != 0)- .then_some(i64::from(exit_code))- });- if let Some(owned) = owned {- let h = owned.handle as HANDLE;- CloseHandle(h);- }+ let exit_profile = active_profile.clone();+ std::thread::spawn(move || {+ super::instances::scope_sync(exit_profile, || unsafe {+ let process_handle = handle_value as HANDLE;+ WaitForSingleObject(process_handle, INFINITE);+ // 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为+ // Stopped(原有实现只清 PID、状态永远停留在 Running)。+ // 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。+ // take 返回值里的句柄由本线程负责关闭(不会与+ // terminate_owned_process 重复 close——进程已 exit,+ // 通常是本线程取走)。+ let owned = on_owned_process_exit(&exit_app_handle, pid, |owned| {+ log_fatal_report(&exit_log_path, &report_path);+ let handle = owned.handle as HANDLE;+ let mut exit_code: u32 = 0;+ (GetExitCodeProcess(handle, &mut exit_code) != 0)+ .then_some(i64::from(exit_code))+ });+ if let Some(owned) = owned {+ let h = owned.handle as HANDLE;+ CloseHandle(h);+ }+ })});(Some(stdout), Some(stderr), pid)})@@ -1033,12 +1047,15 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {set_owned_process(pid);let exit_app_handle = app_handle.clone();let exit_log_path = log_path.clone();+ let exit_profile = active_profile.clone();std::thread::spawn(move || {- let code = child.wait().ok().and_then(|status| status.code());- let _ = on_owned_process_exit(&exit_app_handle, pid, |_| {- log_fatal_report(&exit_log_path, &report_path);- code.map(i64::from)- });+ super::instances::scope_sync(exit_profile, || {+ let code = child.wait().ok().and_then(|status| status.code());+ let _ = on_owned_process_exit(&exit_app_handle, pid, |_| {+ log_fatal_report(&exit_log_path, &report_path);+ code.map(i64::from)+ });+ })});Ok((stdout, stderr, pid))}diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsindex b8ba31b0..3584cd63 100644--- a/src-tauri/src/service/workflow/mod.rs+++ b/src-tauri/src/service/workflow/mod.rs@@ -12,6 +12,7 @@//! - [`startup`]:启动耗时观测(spawn → 首个 HTTP 响应 → 客户端模块就绪)//! - [`status`] / [`utils`] / [`win_inspector`] / [`win_spawn`]:既有子模块+pub mod instances;pub mod status;pub mod utils;pub(crate) mod win_inspector;diff --git a/src-tauri/src/service/workflow/process.rs b/src-tauri/src/service/workflow/process.rsindex b116e415..1532f39e 100644--- a/src-tauri/src/service/workflow/process.rs+++ b/src-tauri/src/service/workflow/process.rs@@ -11,8 +11,8 @@ use std::process::Command;#[cfg(windows)]use std::process::Stdio;use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, Mutex, OnceLock};-use tauri::{AppHandle, Emitter};+use std::sync::{Arc, OnceLock};+use tauri::AppHandle;use super::status;use super::sweep::harness_pid_path;@@ -33,7 +33,9 @@ pub(super) struct HarnessProcessExitedPayload {const PORT_RELEASE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);/// 启动守卫:并发调用 `launch` 时只允许一个真正拉起 dsh 进程-pub(crate) static LAUNCH_GUARD: AtomicBool = AtomicBool::new(false);+pub(crate) fn launch_guard() -> Arc<AtomicBool> {+ Arc::clone(&super::instances::instance().launching)+}/// 当前进程内由桌面端创建的 Harness 根进程(PID + Windows 句柄)。///@@ -50,11 +52,6 @@ pub(super) struct OwnedProcess {pub(super) handle: usize,}-fn owned_process_lock() -> &'static Mutex<Option<OwnedProcess>> {- static OWNED_PROCESS: OnceLock<Mutex<Option<OwnedProcess>>> = OnceLock::new();- OWNED_PROCESS.get_or_init(|| Mutex::new(None))-}-/// 本次启动是否已按 dsh 入口路径清扫过历史残留。////// 启动期的两处清扫(setup 的 sweep_orphan_harness 与 launch 前的那次)读的是同一份@@ -76,28 +73,25 @@ pub(super) fn retry_startup_sweep() {/// 记录新持有的 Harness 根进程(Unix,启动成功后调用)。#[cfg(not(windows))]pub(super) fn set_owned_process(pid: u32) {- let mut guard = owned_process_lock()- .lock()- .unwrap_or_else(|e| e.into_inner());+ let instance = super::instances::instance();+ let mut guard = instance.process.lock().unwrap_or_else(|e| e.into_inner());*guard = Some(OwnedProcess { pid });- STARTUP_SWEEP_DONE.store(false, Ordering::SeqCst);}/// 若调用方 owns 该进程(Windows 额外存句柄),记录之。#[cfg(windows)]pub(super) fn set_owned_process_with_handle(pid: u32, handle: usize) {- let mut guard = owned_process_lock()- .lock()- .unwrap_or_else(|e| e.into_inner());+ let instance = super::instances::instance();+ let mut guard = instance.process.lock().unwrap_or_else(|e| e.into_inner());*guard = Some(OwnedProcess { pid, handle });// 本应用此后持有自己的 Harness:再次启动前必须重新确认没有残留- STARTUP_SWEEP_DONE.store(false, Ordering::SeqCst);}/// 原子取出持有的进程(PID+句柄一起)。取走者负责关闭 Windows 句柄;/// 无条件取出(停止/退出路径)。fn take_owned_process() -> Option<OwnedProcess> {- owned_process_lock()+ crate::service::workflow::instances::instance()+ .process.lock().unwrap_or_else(|e| e.into_inner()).take()@@ -119,7 +113,7 @@ pub(crate) struct LaunchGuard;impl Drop for LaunchGuard {fn drop(&mut self) {- LAUNCH_GUARD.store(false, Ordering::SeqCst);+ launch_guard().store(false, Ordering::SeqCst);}}@@ -157,14 +151,16 @@ pub async fn acquire_core_transition() -> Result<tokio::sync::OwnedMutexGuard<()/// 是否持有 Harness 进程。与其它访问器一致:锁被毒化(panic 残留)时取回/// 毒化守卫继续读取,而不是把「已登记进程」误报为「无」。pub fn has_owned_process() -> bool {- owned_process_lock()+ crate::service::workflow::instances::instance()+ .process.lock().unwrap_or_else(|e| e.into_inner()).is_some()}pub fn owned_process_pid() -> Option<u32> {- owned_process_lock()+ crate::service::workflow::instances::instance()+ .process.lock().unwrap_or_else(|error| error.into_inner()).as_ref()@@ -188,7 +184,9 @@ pub(super) fn on_owned_process_exit<R: tauri::Runtime>(exit_code: impl FnOnce(&OwnedProcess) -> Option<i64>,) -> Option<OwnedProcess> {let (owned, exit_code) = {- let mut guard = owned_process_lock()+ let instance = super::instances::instance();+ let mut guard = instance+ .process.lock().unwrap_or_else(|error| error.into_inner());let owned = take_owned_process_if_matching(&mut guard, pid)?;@@ -223,9 +221,7 @@ pub(super) fn on_owned_process_exit<R: tauri::Runtime>(pid: owned.pid,exit_code,};- if let Err(error) = app_handle.emit(HARNESS_PROCESS_EXITED_EVENT, payload) {- log::warn!("Failed to emit Harness process exit event: {error}");- }+ super::instances::emit(app_handle, HARNESS_PROCESS_EXITED_EVENT, payload);Some(owned)}@@ -248,7 +244,9 @@ fn terminate_owned_process() -> Result<bool, ()> {}if let Err(error) = terminate_windows_process(owned.pid, handle, kill_pid_tree) {log::error!("{error}");- let mut guard = owned_process_lock()+ let instance = super::instances::instance();+ let mut guard = instance+ .process.lock().unwrap_or_else(|error| error.into_inner());if guard.is_none() {@@ -450,7 +448,9 @@ fn terminate_stale_harness_processes_at(dsh_bin: &Path) -> Result<(), String> {let dsh_bin = dsh_bin.to_str().ok_or("HARNESS_SWEEP_FAILED: invalid entry path")?;- let owned_pid = owned_process_lock()+ let instance = super::instances::instance();+ let owned_pid = instance+ .process.lock().unwrap_or_else(|error| error.into_inner()).as_ref()@@ -582,6 +582,12 @@ pub(super) fn reclaim_orphan_port(dsh_bin: &Path, port: u16) -> Result<bool, Strlog::warn!("PORT_OWNER: port={port} pid=unknown ownership=unknown");return Ok(false);};+ if super::instances::profiles()+ .into_iter()+ .any(|profile| super::instances::scope_sync(profile, owned_process_pid) == Some(pid))+ {+ return Ok(false);+ }let output = match windows_process_snapshot(Some(pid)) {Ok(output) => output,Err(error) => {@@ -743,6 +749,12 @@ fn is_harness_command_line(cmdline: &str, dsh_bin: &str) -> bool {/// 因此转发层与其下方的真身会被分别命中,不存在 Windows 的转发层漏杀问题/// (debug 构建跳过该分支,只按 `.harness.pid` 标记回收)。pub fn terminate_stale_harness_processes(app_handle: &tauri::AppHandle) -> Result<(), String> {+ if super::instances::profiles()+ .into_iter()+ .any(|profile| super::instances::scope_sync(profile, has_owned_process))+ {+ return Ok(());+ }#[cfg(windows)]{terminate_stale_harness_processes_at(&config::get_dsh_binary_path(app_handle))?;@@ -799,40 +811,46 @@ pub(super) fn warn_if_inotify_watch_limit_low() {/// 停止 Harness 服务pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {- log::info!("Stopping Harness service...");- // 重置启动守卫,确保后续 launch 可以重新拉起;仅结束持有的根进程树。- // 进程终止涉及 WaitForSingleObject(至多 5s)与 taskkill/kill 等同步阻塞- // 调用,移出 Tokio 执行线程避免卡住其他并发任务(WARN-7/P2-#20)。- LAUNCH_GUARD.store(false, Ordering::SeqCst);- tauri::async_runtime::spawn_blocking(terminate_owned_process)+ let profile = super::instances::current_profile()+ .unwrap_or_else(|| crate::service::profile::active_profile(&app_handle));+ super::instances::scope(profile.clone(), async move {+ log::info!("Stopping Harness service...");+ // 重置启动守卫,确保后续 launch 可以重新拉起;仅结束持有的根进程树。+ // 进程终止涉及 WaitForSingleObject(至多 5s)与 taskkill/kill 等同步阻塞+ // 调用,移出 Tokio 执行线程避免卡住其他并发任务(WARN-7/P2-#20)。+ launch_guard().store(false, Ordering::SeqCst);+ tauri::async_runtime::spawn_blocking(move || {+ super::instances::scope_sync(profile, terminate_owned_process)+ }).await.map_err(|e| format!("STOP_FAILED: {e}"))?.map_err(|()| "STOP_FAILED: Harness process did not stop".to_string())?;- // 清理孤儿清扫标记:正常停止的实例不应被下次启动当作残留- let _ = fs::remove_file(harness_pid_path(&app_handle));+ // 清理孤儿清扫标记:正常停止的实例不应被下次启动当作残留+ let _ = fs::remove_file(harness_pid_path(&app_handle));- // 端口释放滞后是毫秒级,固定睡眠只会把这段时间放大成白等;以端口真正- // 回落为准,最坏情况仍退化为原先的等待上限。- {- let port = config::get_store_dat_setting(&app_handle).port;+ let port = super::instances::port(&app_handle);#[cfg(windows)]let entry = crate::service::core::active_dsh_binary(&app_handle);- tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {- if !wait_for_port_release(port, PORT_RELEASE_WAIT) {- #[cfg(windows)]- {- reclaim_orphan_port(&entry, port)?;+ let profile = super::instances::current_profile().unwrap();+ tauri::async_runtime::spawn_blocking(move || {+ super::instances::scope_sync(profile, || -> Result<(), String> {+ if !wait_for_port_release(port, PORT_RELEASE_WAIT) {+ #[cfg(windows)]+ {+ reclaim_orphan_port(&entry, port)?;+ }}- }- Ok(())+ Ok(())+ })}).await.map_err(|error| format!("STOP_FAILED: {error}"))??;- }- status::set_status(status::Status::Stopped);- status::emit_status(&app_handle);- Ok(())+ status::set_status(status::Status::Stopped);+ status::emit_status(&app_handle);+ Ok(())+ })+ .await}/// 交付安装包前的同步停服:结束持有的 Harness 进程树 → 等端口释放 → 清清扫标记。@@ -846,7 +864,7 @@ pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {/// 同步、可在退出路径调用(无 async 运行时依赖):进程从 SIGKILL 返回那一刻已死,/// 但内核回收监听套接字仍有短暂滞后,故结束过进程后补一次有界等待,让紧随其后的/// 安装器/新实例看到端口已释放。没持有进程时不等待,避免在用户可见路径上白耗。-pub fn stop_for_installer(app_handle: &tauri::AppHandle) -> Result<(), String> {+fn stop_instance_for_installer(app_handle: &tauri::AppHandle) -> Result<(), String> {let terminated = terminate_owned_process().map_err(|()| "STOP_FAILED: Harness process did not stop".to_string())?;#[cfg(not(windows))]@@ -857,7 +875,7 @@ pub fn stop_for_installer(app_handle: &tauri::AppHandle) -> Result<(), String> {let _ = terminated;// 正常停止路径同样清理清扫标记(崩溃路径才需要下次启动清扫)let _ = fs::remove_file(harness_pid_path(app_handle));- let port = config::get_store_dat_setting(app_handle).port;+ let port = super::instances::port(app_handle);if !wait_for_port_release(port, PORT_RELEASE_WAIT) {#[cfg(windows)]{@@ -872,6 +890,22 @@ pub fn stop_for_installer(app_handle: &tauri::AppHandle) -> Result<(), String> {////// 退出路径上不更新状态,只结束当前应用持有的 Harness 进程树(与安装器交接共用/// [`stop_for_installer`],保证两条路径行为一致)。+pub fn stop_for_installer(app_handle: &tauri::AppHandle) -> Result<(), String> {+ let mut profiles = super::instances::profiles();+ if profiles.is_empty() {+ profiles.push(crate::service::profile::active_profile(app_handle));+ }+ let mut result = Ok(());+ for profile in profiles {+ if let Err(error) =+ super::instances::scope_sync(profile, || stop_instance_for_installer(app_handle))+ {+ result = Err(error);+ }+ }+ result+}+pub fn stop_on_exit(app_handle: &tauri::AppHandle) {if let Err(error) = stop_for_installer(app_handle) {log::error!("Harness exit cleanup failed: {error}");@@ -882,6 +916,57 @@ pub fn stop_on_exit(app_handle: &tauri::AppHandle) {mod tests {use super::*;+ #[test]+ fn stop_keeps_all_instance_effects_in_resolved_profile_scope() {+ let source = include_str!("process.rs");+ let stop = source+ .split("pub async fn stop(")+ .nth(1)+ .unwrap()+ .split("/// 交付安装包前")+ .next()+ .unwrap();+ let scope = stop+ .find("super::instances::scope(profile.clone(), async move {")+ .unwrap();+ for effect in [+ "launch_guard().store",+ "spawn_blocking",+ "harness_pid_path",+ "super::instances::port",+ "status::set_status",+ "status::emit_status",+ ] {+ assert!(+ stop.find(effect).unwrap() > scope,+ "{effect} must run inside resolved profile scope"+ );+ }+ assert!(stop+ .chars()+ .filter(|character| !character.is_whitespace())+ .collect::<String>()+ .ends_with("}).await}"));+ }++ #[test]+ fn orphan_port_reclaim_preserves_every_registered_profile_process() {+ let source = include_str!("process.rs");+ let reclaim = source+ .split("pub(super) fn reclaim_orphan_port(")+ .nth(1)+ .unwrap()+ .split("#[cfg(windows)]\n#[derive")+ .next()+ .unwrap();+ assert!(+ reclaim.find("super::instances::profiles()").unwrap()+ < reclaim.find("windows_process_snapshot(Some(pid))").unwrap()+ );+ assert!(reclaim+ .contains("super::instances::scope_sync(profile, owned_process_pid) == Some(pid)"));+ }+/// 构造一个测试用 `OwnedProcess`(跨平台处理 Windows 句柄字段)。#[cfg(windows)]fn test_owned(pid: u32) -> OwnedProcess {@@ -921,7 +1006,10 @@ mod tests {let app = tauri::test::mock_app();let root = tempfile::tempdir().unwrap();let marker = root.path().join("fatal-report.log");- *owned_process_lock().lock().unwrap() = Some(test_owned(42));+ *crate::service::workflow::instances::instance()+ .process+ .lock()+ .unwrap() = Some(test_owned(42));let (entered_tx, entered_rx) = mpsc::channel();let (resume_tx, resume_rx) = mpsc::channel();let timeout = Duration::from_secs(5);@@ -939,7 +1027,9 @@ mod tests {});entered_rx.recv_timeout(timeout).unwrap();let callback_holds_ownership = matches!(- owned_process_lock().try_lock(),+ crate::service::workflow::instances::instance()+ .process+ .try_lock(),Err(std::sync::TryLockError::WouldBlock));let observer = scope.spawn(|| {diff --git a/src-tauri/src/service/workflow/status.rs b/src-tauri/src/service/workflow/status.rsindex 2640013c..a940ea91 100644--- a/src-tauri/src/service/workflow/status.rs+++ b/src-tauri/src/service/workflow/status.rs@@ -1,6 +1,4 @@-use std::sync::{Mutex, OnceLock};use tauri::AppHandle;-use tauri::Emitter;#[derive(Debug, Clone, serde::Serialize, PartialEq)]pub enum Status {@@ -11,26 +9,21 @@ pub enum Status {Stopped,}-// 使用静态变量在模块内部管理状态-static DSH_STATUS: OnceLock<Mutex<Status>> = OnceLock::new();--pub fn get_status_lock() -> &'static Mutex<Status> {- DSH_STATUS.get_or_init(|| Mutex::new(Status::Initial))-}-pub fn set_status(status: Status) {- // 中毒安全:忽略此前 panic 造成的锁中毒,避免连锁 panic 导致进程退出- *get_status_lock().lock().unwrap_or_else(|e| e.into_inner()) = status;+ *super::instances::instance()+ .status+ .lock()+ .unwrap_or_else(|error| error.into_inner()) = status;}pub fn emit_status<R: tauri::Runtime>(app_handle: &AppHandle<R>) {- let status = get_status();- let _ = app_handle.emit("dsh-status-updated", &status);+ super::instances::emit(app_handle, "dsh-status-updated", get_status());}pub fn get_status() -> Status {- get_status_lock()+ super::instances::instance()+ .status.lock()- .unwrap_or_else(|e| e.into_inner())+ .unwrap_or_else(|error| error.into_inner()).clone()}diff --git a/src-tauri/src/service/workflow/sweep.rs b/src-tauri/src/service/workflow/sweep.rsindex a8796a7b..8ad906c2 100644--- a/src-tauri/src/service/workflow/sweep.rs+++ b/src-tauri/src/service/workflow/sweep.rs@@ -19,7 +19,12 @@ pub(super) fn harness_pid_path<R: tauri::Runtime>(app_handle: &tauri::AppHandle<R>,) -> std::path::PathBuf {let channel = usize::from(app_handle.config().identifier == "dsh-tauri-nightly");- config::get_dsh_data_path(app_handle).join(config::HARNESS_PID_MARKER_NAMES[channel])+ let root = config::get_dsh_data_path(app_handle);+ let name = config::HARNESS_PID_MARKER_NAMES[channel];+ match super::instances::current_profile() {+ Some(profile) => root.join("profiles").join(profile).join(name),+ None => root.join(name),+ }}#[cfg(test)]@@ -27,6 +32,20 @@ mod tests {use super::harness_pid_path;use tauri::test::{mock_builder, mock_context, noop_assets};+ #[test]+ fn harness_markers_are_isolated_by_profile() {+ let app = mock_builder().build(mock_context(noop_assets())).unwrap();+ let a = super::super::instances::scope_sync("marker-profile-a".into(), || {+ harness_pid_path(app.handle())+ });+ let b = super::super::instances::scope_sync("marker-profile-b".into(), || {+ harness_pid_path(app.handle())+ });+ assert_ne!(a, b);+ assert_eq!(a.parent().unwrap().file_name().unwrap(), "marker-profile-a");+ assert_eq!(a.file_name(), b.file_name());+ }+#[test]fn harness_pid_marker_is_isolated_by_channel() {for (identifier, marker) in [@@ -57,6 +76,18 @@ pub(super) fn persist_harness_pid(app_handle: &tauri::AppHandle, pid: u32, port:/// - 其余情况(标记不可解析、端口被其他程序占用、无法探测占用者)一律不动,/// 绝不凭端口猜进程、绝不杀未知进程。pub fn sweep_orphan_harness(app_handle: &tauri::AppHandle) {+ if super::instances::current_profile().is_none() {+ let root = config::get_dsh_data_path(app_handle).join("profiles");+ if let Ok(entries) = fs::read_dir(root) {+ for entry in entries.flatten().filter(|entry| entry.path().is_dir()) {+ if let Some(profile) = entry.file_name().to_str() {+ super::instances::scope_sync(profile.into(), || {+ sweep_orphan_harness(app_handle)+ });+ }+ }+ }+ }if has_owned_process() {return;}diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rsindex 9e6dfd99..330f1d31 100644--- a/src-tauri/src/utils/mod.rs+++ b/src-tauri/src/utils/mod.rs@@ -2,7 +2,6 @@ use std::path::{Path, PathBuf};use tauri::{AppHandle, Manager, Runtime, WebviewWindow};-use crate::config;use crate::service::core::active_core_dir;/// 对某个 dsh 包文件的一次性幂等补丁判定结果。@@ -75,8 +74,29 @@ pub fn show_window<R: Runtime>(window: &WebviewWindow<R>) {/// 显示主窗口:托盘「打开面板」、托盘左键点击、macOS Dock 图标点击共用。/// 关闭按钮只隐藏窗口(见 builder 的 on_window_event),所以这里取到即可 show;/// 若窗口确实不存在(非预期路径),仅记录日志,不重建。+pub fn shell_window<R: Runtime>(app: &AppHandle<R>) -> Option<WebviewWindow<R>> {+ app.get_webview_window("main").or_else(|| {+ app.webview_windows().into_values().find(|window| {+ window.label().starts_with("window-") || window.label().starts_with("remote-")+ })+ })+}++pub fn operation_window<R: Runtime>(app: &AppHandle<R>) -> Option<WebviewWindow<R>> {+ use crate::service::workflow::instances;+ let profile = instances::current_profile()?;+ app.get_webview_window("main")+ .filter(|window| instances::window_uses_profile(window.label(), &profile))+ .or_else(|| {+ app.webview_windows().into_values().find(|window| {+ (window.label().starts_with("window-") || window.label().starts_with("remote-"))+ && instances::window_uses_profile(window.label(), &profile)+ })+ })+}+pub fn show_main_window<R: Runtime>(app: &AppHandle<R>) {- if let Some(window) = app.get_webview_window("main") {+ if let Some(window) = shell_window(app) {// 关窗驻留用的是应用级 hide(NSApp hide:,见 builder 的 CloseRequested),// 恢复前必须先 unhide 整个应用,否则 window.show() 在隐藏态应用上不可见。#[cfg(target_os = "macos")]@@ -267,6 +287,38 @@ mod tests {#[cfg(windows)]use super::{decode_multibyte, encode_multibyte, short_path};+ #[tokio::test]+ async fn operation_window_never_falls_back_to_another_profile() {+ use crate::service::workflow::instances;+ let app = tauri::test::mock_builder()+ .build(tauri::test::mock_context(tauri::test::noop_assets()))+ .unwrap();+ for label in ["main", "window-operation-test", "remote-operation-test"] {+ tauri::WebviewWindowBuilder::new(&app, label, tauri::WebviewUrl::default())+ .build()+ .unwrap();+ }+ instances::bind_window("main", "operation-main-profile");+ instances::bind_window("window-operation-test", "operation-extra-profile");+ instances::bind_window("remote-operation-test", "operation-remote-profile");+ assert!(super::operation_window(app.handle()).is_none());+ for (profile, expected) in [+ ("operation-main-profile", Some("main")),+ ("operation-extra-profile", Some("window-operation-test")),+ ("operation-remote-profile", Some("remote-operation-test")),+ ("operation-missing-profile", None),+ ] {+ instances::scope(profile.into(), async {+ let window = super::operation_window(app.handle());+ assert_eq!(window.as_ref().map(|window| window.label()), expected);+ })+ .await;+ }+ for label in ["main", "window-operation-test", "remote-operation-test"] {+ instances::release_window(label);+ }+ }+#[test]fn keeps_valid_utf8_untouched() {let text = "系统找不到指定的路径。";@@ -300,7 +352,10 @@ mod tests {assert!(!gbk.is_ascii());assert_eq!(decode_multibyte(&gbk, 936).as_deref(), Some(text));// UTF-8 代码页不看 `lpUsedDefaultChar`,直接给出等价字节。- assert_eq!(encode_multibyte(text, 65001).as_deref(), Some(text.as_bytes()));+ assert_eq!(+ encode_multibyte(text, 65001).as_deref(),+ Some(text.as_bytes())+ );}/// 该代码页表示不了的字符必须报 `None`,不能靠「近似字符」蒙混过关。diff --git a/src/hooks/use-remote.test.ts b/src/hooks/use-remote.test.tsindex 1f1276ee..fe67c0e6 100644--- a/src/hooks/use-remote.test.ts+++ b/src/hooks/use-remote.test.ts@@ -179,6 +179,16 @@ describe('useRemote 查询、降级与启动寻址', () => {expect(invoke.mock.calls.filter(call => call[1].method.endsWith('/machines'))).toHaveLength(2)})+ it.each(['remote-776562--m1', 'remote-7461757269--m1'])('profile-scoped window %s reads its explicit machine target', async (label) => {+ windowInfo.label = label+ window.location.hash = new URLSearchParams({ remoteMachineId: 'machine--with spaces' }).toString()+ rows = [machineOf({ id: 'machine--with spaces', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]+ const { result } = await ready()+ await waitFor(() => expect(result.current.activeId).toBe('machine--with spaces'))+ expect(result.current.activeTunnelUrl).toBe('http://127.0.0.1:4001')+ expect(connect).not.toHaveBeenCalled()+ })+it('remote-窗口已连接目标直接切换', async () => {windowInfo.label = 'remote-m1'rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]diff --git a/src/hooks/use-remote.ts b/src/hooks/use-remote.tsindex fa211aca..21ee52ef 100644--- a/src/hooks/use-remote.ts+++ b/src/hooks/use-remote.ts@@ -22,10 +22,13 @@ interface SwitcherTargets {function initialMachineId(): string | null {if (!('__TAURI_INTERNALS__' in window))return null+ const parameters = new URLSearchParams(window.location.hash.slice(1))+ const machineId = parameters.get('remoteMachineId')+ if (machineId)+ return machineIdconst label = getCurrentWindow().labelif (label.startsWith('remote-'))return label.slice('remote-'.length) || null- const parameters = new URLSearchParams(window.location.hash.slice(1))const url = parameters.has('sessionId') ? parameters.get('iframeUrl') : nullreturn url && URL.canParse(url) ? new URL(url).origin : null}diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.tsindex ca540a77..fa6b8d10 100644--- a/src/store/modules/harness/store.ts+++ b/src/store/modules/harness/store.ts@@ -766,6 +766,31 @@ export const harness = defineStore({this.serviceRunning = keepServiceRunning},+ async switchProfile(id: string) {+ if (this.busyAction)+ return+ this.busyAction = 'start'+ ++bootToken+ const healthy = this.serviceHealthy+ this.serviceHealthy = false+ try {+ await invoke<Profile>('set_active_profile', { id })+ }+ catch (error) {+ this.serviceHealthy = healthy+ this.busyAction = null+ throw error+ }+ try {+ this.serviceRunning = false+ void hooks['config.dialog.hidden'].trigger()+ await this.boot()+ }+ finally {+ this.busyAction = null+ }+ },+/** 重启服务:先强杀再拉起,最终回到就绪/错误态 */restart(): Promise<void> {return restartFlight.run(async () => {@@ -870,7 +895,10 @@ export const harness = defineStore({finally {this.busyAction = null}- await this.restart()+ if (action === 'safe-mode')+ await this.start()+ else+ await this.restart()},/** 停止服务并回到停止态界面 */diff --git a/src/ui/config/profile.tsx b/src/ui/config/profile.tsxindex fb26bb85..cfa936c5 100644--- a/src/ui/config/profile.tsx+++ b/src/ui/config/profile.tsx@@ -34,13 +34,6 @@ const PROFILE_ERROR_KEYS: Record<string, string> = {}export function ConfigProfile() {- /**- * 「档案」面板:展示 & 切换 dsh 配置档案,支持新建/删除。- *- * 档案 = `$DSH_HOME/profiles/<id>` 目录,与官方 dsh CLI 的 profile 语义一致;- * 桌面端把「当前档案」持久化在 store(`active_profile`),服务启动与插件管理- * 都以它为准。切换档案需要重启服务才生效(toast 内提供重启入口)。- */const queryClient = useQueryClient()const { data: profileList, isLoading, error: profileError, refetch } = useQuery({queryKey: queryKeys.profiles,@@ -59,7 +52,7 @@ export function ConfigProfile() {onSuccess: invalidate,})const activate = useMutation({- mutationFn: (id: string) => invoke<Profile>('set_active_profile', { id }),+ mutationFn: (id: string) => store.harness.switchProfile(id),onSuccess: invalidate,})const remove = useMutation({@@ -82,10 +75,9 @@ export function ConfigProfile() {return created}- async function activateProfile(id: string): Promise<Profile> {- const activated = await activate.mutateAsync(id)+ async function activateProfile(id: string): Promise<void> {+ await activate.mutateAsync(id)await refetch()- return activated}async function removeProfile(id: string) {@@ -223,18 +215,6 @@ export function ConfigProfile() {}try {await activateProfile(id)- const key = toast(t('profiles.activate_toast', { name: target.name }), {- variant: 'accent',- description: t('profiles.activate_restart_hint'),- timeout: 10_000,- actionProps: {- children: t('app.restart'),- onPress: () => {- store.harness.restart()- toast.close(key)- },- },- })}catch (err) {console.error('[ConfigProfile] activate failed:', err)diff --git a/test/data-dir.test.ts b/test/data-dir.test.tsindex 60128b37..920b996c 100644--- a/test/data-dir.test.ts+++ b/test/data-dir.test.ts@@ -165,8 +165,15 @@ describe('migration safety contract', () => {.filter(body => body.includes('workflow::stop'))expect(bodies.length).toBe(2)for (const body of bodies) {- const recorded = body.indexOf('let recorded = data_dir::harness_markers(&crate::config::get_dsh_data_path(&app_handle));')- const reject = body.indexOf('reject_unreadable_markers(recorded)?;')+ const recorded = body.search(/let recorded\s*=\s*data_dir::all_harness_markers\(&crate::config::get_dsh_data_path\(&app_handle\)\);/)+ const reject = body.indexOf('reject_unreadable_markers(recorded.clone())?;')+ const transition = body.indexOf('acquire_core_transition().await?;')+ const exclusive = body.indexOf('require_exclusive_profile()?;')+ expect(body).toContain('window_profile(&app_handle, window.label())')+ expect(body).toContain('instances::scope(profile, async move')+ expect(transition).toBeGreaterThan(-1)+ expect(exclusive).toBeGreaterThan(transition)+ expect(recorded).toBeGreaterThan(exclusive)const stop = body.indexOf('crate::service::workflow::stop(app_handle.clone()).await?;')const confirm = body.indexOf('confirm_harness_stopped(recorded)?;')expect(recorded).toBeGreaterThan(-1)@@ -180,7 +187,7 @@ describe('migration safety contract', () => {// 停之前那道检查必须放行「存活 PID」分支expect(bridge).toContain('HarnessMarker::Missing | HarnessMarker::Pid(_) => Ok(())')// 停之前那一步必须排在 `stop()` 前面,否则标记已经被删、什么都查不出- expect(bridge.indexOf('reject_unreadable_markers(recorded)?;')).toBeLessThan(bridge.indexOf('workflow::stop'))+ expect(bridge.indexOf('reject_unreadable_markers(recorded.clone())?;')).toBeLessThan(bridge.indexOf('workflow::stop'))expect(bridge).toContain('DATA_DIR_HARNESS_RUNNING')expect(bridge).toContain('DATA_DIR_HARNESS_MARKER_INVALID')// 标记读不出来与标记不在必须分开:前者要先拒绝,否则 `stop()` 删掉标记后@@ -191,7 +198,11 @@ describe('migration safety contract', () => {expect(module).toContain('pub(crate) enum HarnessMarker {')expect(module).toContain('pub(crate) fn harness_markers(root: &Path) -> [HarnessMarker; 2] {')expect(module).toContain('HARNESS_PID_MARKER_NAMES.map(|name| harness_marker_at(&root.join(name)))')- expect(module).toMatch(/harness_markers\(root\)\s*\.into_iter\(\)\s*\.all\(\|marker\| match marker \{/)+ expect(module).toContain('pub(crate) fn all_harness_markers(root: &Path) -> Vec<HarnessMarker> {')+ expect(module).toContain('let mut markers = harness_markers(root).to_vec();')+ expect(module).toContain('std::fs::read_dir(root.join("profiles"))')+ expect(module).toContain('markers.extend(harness_markers(&entry.path()))')+ expect(module).toMatch(/all_harness_markers\(root\)\s*\.into_iter\(\)\s*\.all\(\|marker\| match marker \{/)})it('moves a non-empty rollback target aside instead of overwriting it', () => {diff --git a/test/e2e/desktop/boot.e2e.ts b/test/e2e/desktop/boot.e2e.tsindex 0c40fb0f..d831c9c7 100644--- a/test/e2e/desktop/boot.e2e.ts+++ b/test/e2e/desktop/boot.e2e.ts@@ -1,5 +1,5 @@import type { DesktopApp } from '../support/desktop'-import { existsSync } from 'node:fs'+import { existsSync, readFileSync } from 'node:fs'import { join } from 'node:path'import process from 'node:process'import { afterAll, beforeAll, describe, expect, it } from 'vitest'@@ -139,6 +139,105 @@ describe.skipIf(process.platform === 'darwin')('桌面端启动冒烟', () => {expect(shellErrors, '壳层出现报错').toEqual([])}, ASSEMBLY_TIMEOUT_MS)+ it('TC-DSK-L3-993 原生窗口继承档案、复用同档案核心且切换与关闭不重启其他核心', async () => {+ const windows: string[] = []+ async function invoke<T>(command: string, args: Record<string, unknown> = {}): Promise<T> {+ return browser.execute(async (command, args) => {+ const bridge = (window as unknown as { __TAURI_INTERNALS__: { invoke: (command: string, args: Record<string, unknown>) => Promise<T> } }).__TAURI_INTERNALS__+ return bridge.invoke(command, args)+ }, command, args)+ }+ async function activeProfile() {+ const profiles = await invoke<{ id: string, active: boolean }[]>('get_profiles')+ const active = profiles.find(profile => profile.active)+ expect(active, '当前原生窗口必须有活动档案').toBeDefined()+ return active!.id+ }+ async function openWindow() {+ const before = await browser.getWindowHandles()+ await invoke('create_app_window')+ await browser.waitUntil(async () => (await browser.getWindowHandles()).some(handle => !before.includes(handle)), { timeout: 30_000, timeoutMsg: '原生新窗口未创建' })+ const handle = (await browser.getWindowHandles()).find(handle => !before.includes(handle))!+ windows.push(handle)+ await browser.switchToWindow(handle)+ await browser.$(SHELL_ROOT).waitForExist({ timeout: 30_000 })+ return handle+ }+ async function healthy() {+ return invoke<string>('proxy_health_check')+ }+ let clonedProfile: string | undefined+ let switchedProfile = false+ await browser.switchToWindow('main')+ const originalProfile = await activeProfile()+ const originalRuntime = await invoke<{ service_url: string }>('get_runtime_info')+ expect(await healthy(), '原窗口核心必须已就绪').toMatch(/^healthy - \d+\/\d+ client modules ready$/)+ const profilesRoot = join(app!.home, 'home', '.dsh.dev', 'profiles')+ const originalMarkerPath = join(profilesRoot, originalProfile, '.harness.pid')+ const originalMarker = readFileSync(originalMarkerPath, 'utf8')+ try {+ const clone = await invoke<{ id: string }>('clone_profile', { sourceId: originalProfile, name: 'native-window-993' })+ clonedProfile = clone.id+ const second = await openWindow()+ expect(await activeProfile(), '新窗口必须继承发起窗口档案').toBe(originalProfile)+ expect((await invoke<{ service_url: string }>('get_runtime_info')).service_url, '同档案新窗口必须复用服务端口').toBe(originalRuntime.service_url)+ await invoke('set_active_profile', { id: clone.id })+ switchedProfile = true+ await invoke('launch_harness')+ await browser.waitUntil(async () => {+ const result = await browser.execute(async () => {+ const bridge = (window as unknown as { __TAURI_INTERNALS__: { invoke: (command: string) => Promise<string> } }).__TAURI_INTERNALS__+ return bridge.invoke('proxy_health_check').then(value => value.startsWith('healthy - '), (error: unknown) => {+ if (String(error).startsWith('HARNESS_NOT_READY:'))+ return false+ throw error+ })+ })+ return result+ }, { timeout: ASSEMBLY_TIMEOUT_MS, timeoutMsg: '第二档案核心未就绪' })+ expect(await activeProfile(), '切换应只改变第二窗口档案').toBe(clone.id)+ const secondRuntime = await invoke<{ service_url: string }>('get_runtime_info')+ expect(secondRuntime.service_url, '不同档案必须使用独立服务端口').not.toBe(originalRuntime.service_url)+ const clonedMarkerPath = join(profilesRoot, clone.id, '.harness.pid')+ const clonedMarker = readFileSync(clonedMarkerPath, 'utf8')+ expect(clonedMarker.split('\n')[0], '不同档案必须持有不同核心进程').not.toBe(originalMarker.split('\n')[0])+ const third = await openWindow()+ await invoke('launch_harness')+ expect(await activeProfile(), '第三窗口必须继承第二窗口档案').toBe(clone.id)+ expect((await invoke<{ service_url: string }>('get_runtime_info')).service_url, '第二档案的窗口必须复用核心端口').toBe(secondRuntime.service_url)+ expect(readFileSync(clonedMarkerPath, 'utf8'), '同档案新窗口不得重启已有核心').toBe(clonedMarker)+ await browser.switchToWindow('main')+ expect(await activeProfile(), '其他窗口切档案不得改变原窗口档案').toBe(originalProfile)+ expect((await invoke<{ service_url: string }>('get_runtime_info')).service_url, '其他窗口切档案不得改变原核心端口').toBe(originalRuntime.service_url)+ expect(readFileSync(originalMarkerPath, 'utf8'), '其他窗口切档案不得重启原核心').toBe(originalMarker)+ expect(await healthy(), '第二档案启动后原核心必须仍健康').toMatch(/^healthy - /)+ await browser.switchToWindow(third)+ await browser.closeWindow()+ await browser.switchToWindow(second)+ expect(await healthy(), '关闭同档案的非最后窗口不得停止核心').toMatch(/^healthy - /)+ await browser.closeWindow()+ await browser.switchToWindow('main')+ await browser.waitUntil(async () => !existsSync(clonedMarkerPath), { timeout: 30_000, timeoutMsg: '关闭档案最后窗口后核心 PID 标记未回收' })+ expect(readFileSync(originalMarkerPath, 'utf8'), '关闭其他档案窗口不得重启原核心').toBe(originalMarker)+ expect(await healthy(), '关闭其他档案最后窗口后原核心必须仍健康').toMatch(/^healthy - /)+ }+ finally {+ for (const handle of windows.reverse()) {+ if ((await browser.getWindowHandles()).includes(handle)) {+ await browser.switchToWindow(handle)+ await browser.closeWindow()+ }+ }+ await browser.switchToWindow('main')+ if (switchedProfile)+ await invoke('set_active_profile', { id: originalProfile })+ if (clonedProfile) {+ await browser.waitUntil(async () => !existsSync(join(profilesRoot, clonedProfile!, '.harness.pid')), { timeout: 30_000, timeoutMsg: '测试档案核心未完成关闭回收' })+ await invoke('remove_profile', { id: clonedProfile })+ }+ }+ }, ASSEMBLY_TIMEOUT_MS)+it('persists appearance through the native bridge and restores defaults', async () => {expect(await browser.execute(() => (window as unknown as { __DSH_STORE_FILE__: string }).__DSH_STORE_FILE__), '前端必须使用原生测试配置文件').toBe('.store.test.dat')async function click(id: string) {diff --git a/test/harness-boot-policy.test.ts b/test/harness-boot-policy.test.tsindex 008375e5..03ddf0a1 100644--- a/test/harness-boot-policy.test.ts+++ b/test/harness-boot-policy.test.ts@@ -64,10 +64,14 @@ beforeEach(() => {preinstall.error = ''preinstall.installing = falsepreinstall.policyBlocked = []- invoke.mockImplementation(async (command: string) => {+ invoke.mockImplementation(async (command: string, args?: { id: string }) => {switch (command) {- case 'get_runtime_info': return { service_url: 'http://127.0.0.1:3081' }+ case 'set_active_profile':+ activeProfile = args!.id+ return { id: activeProfile, active: true }+ case 'get_runtime_info': return { service_url: activeProfile === 'other' ? 'http://127.0.0.1:3082' : 'http://127.0.0.1:3081' }case 'get_app_config': return { installed: true }+ case 'enter_safe_mode': return { quarantined: [], failures: [] }case 'runtime_ready': return truecase 'get_profiles': return [{ id: activeProfile, active: true }]case 'ensure_internal_plugins':@@ -101,6 +105,52 @@ afterEach(() => {vi.restoreAllMocks()})+describe('window profile connection', () => {+ it('connects the selected profile without restarting either shared runtime', async () => {+ ensureFailure = undefined+ harness.serviceHealthy = true+ harness.serviceRunning = true+ await harness.switchProfile('other')++ expect(activeProfile).toBe('other')+ expect(harness.serviceUrl).toBe('http://127.0.0.1:3082')+ expect(harness.iframeSrc).toContain('http://127.0.0.1:3082')+ expect(harness.serviceHealthy).toBe(true)+ expect(harness.busyAction).toBe(null)+ expect(invoke).toHaveBeenCalledWith('set_active_profile', { id: 'other' })+ expect(invoke).toHaveBeenCalledWith('launch_harness')+ expect(invoke).not.toHaveBeenCalledWith('shutdown_harness')+ expect(invoke).not.toHaveBeenCalledWith('restart_harness')+ })++ it('enters the safe profile without restarting another window already using it', async () => {+ ensureFailure = undefined+ await harness.enterSafeMode()++ expect(invoke).toHaveBeenCalledWith('enter_safe_mode')+ expect(invoke).toHaveBeenCalledWith('launch_harness')+ expect(invoke).not.toHaveBeenCalledWith('shutdown_harness')+ expect(harness.serviceHealthy).toBe(true)+ expect(harness.busyAction).toBe(null)+ })++ it('keeps the previous connection when profile binding fails', async () => {+ harness.serviceHealthy = true+ harness.serviceRunning = true+ harness.serviceUrl = 'http://127.0.0.1:3081'+ invoke.mockRejectedValueOnce(new Error('PROFILE_NOT_FOUND: missing'))+ await expect(harness.switchProfile('missing')).rejects.toThrow('PROFILE_NOT_FOUND')++ expect(activeProfile).toBe('web')+ expect(harness.serviceUrl).toBe('http://127.0.0.1:3081')+ expect(harness.serviceHealthy).toBe(true)+ expect(harness.serviceRunning).toBe(true)+ expect(harness.busyAction).toBe(null)+ expect(invoke).not.toHaveBeenCalledWith('launch_harness')+ expect(invoke).not.toHaveBeenCalledWith('shutdown_harness')+ })+})+describe('harness boot policy refusal recovery', () => {it.each([REFUSAL, `PLUGIN_POLICY_BLOCKED: ${JSON.stringify(POLICY)}`])('continues core startup with an exact-version authorization action for %s', async (failure) => {ensureFailure = failure