DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(profile): manage dsh profiles with create/switch/remove and active profile in launch
hairyf16ba7f1f2034
diff --git a/src-tauri/src/bridge/cmd.rs b/src-tauri/src/bridge/cmd.rsindex 6cdc6dcb..59162ce6 100644--- a/src-tauri/src/bridge/cmd.rs+++ b/src-tauri/src/bridge/cmd.rs@@ -2,6 +2,7 @@ use crate::config;use crate::service::cli;use crate::service::download::{self, Installable};use crate::service::plugin;+use crate::service::profile;use crate::service::update;use crate::service::workflow;use tauri::AppHandle;@@ -306,6 +307,33 @@ pub fn get_dsh_plugins(app_handle: AppHandle) -> Vec<plugin::DshPlugin> {plugin::watch::list(&app_handle)}+/// 档案列表($DSH_HOME/profiles 下的目录,含 active/default 标记)+#[tauri::command]+pub fn get_profiles(app_handle: AppHandle) -> Vec<profile::Profile> {+ profile::list(&app_handle)+}++/// 新建档案(初始化 $DSH_HOME/profiles/<id>,web 模板)+#[tauri::command]+pub fn create_profile(app_handle: AppHandle, name: String) -> Result<profile::Profile, String> {+ profile::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)+}++/// 删除档案(默认档案与使用中的档案不可删除)+#[tauri::command]+pub fn remove_profile(app_handle: AppHandle, id: String) -> Result<(), String> {+ profile::remove(&app_handle, &id)+}+/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)#[tauri::command]diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rsindex aa5b087e..e2835410 100644--- a/src-tauri/src/config/setting.rs+++ b/src-tauri/src/config/setting.rs@@ -31,6 +31,15 @@ pub struct Setting {/// 幂等标记:迁移成功并删除旧目录后置位,避免重复合并。#[serde(default)]pub dsh_home_migrated: bool,+ /// 当前使用的档案 id(`$DSH_HOME/profiles/<id>`,默认 web)。+ /// 桌面端启动服务与插件管理都以它为准(见 service::profile)。+ #[serde(default = "default_active_profile")]+ pub active_profile: String,+}++/// 默认档案:桌面端内置的 web 档案+fn default_active_profile() -> String {+ "web".to_string()}/// 命令行集成默认开启(开发者工具场景,安装完成即可用)@@ -60,6 +69,7 @@ impl Default for Setting {preinstall_done: false,preset_hash: None,dsh_home_migrated: false,+ active_profile: default_active_profile(),}}}diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 74c9096f..3070ff52 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -199,6 +199,10 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::cmd::skip_preinstall_plugins,crate::bridge::cmd::open_preinstall_repo,crate::bridge::cmd::get_dsh_plugins,+ crate::bridge::cmd::get_profiles,+ crate::bridge::cmd::create_profile,+ crate::bridge::cmd::set_active_profile,+ crate::bridge::cmd::remove_profile,crate::bridge::cmd::proxy_health_check,crate::bridge::cmd::get_runtime_info,crate::bridge::cmd::runtime_ready,diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rsindex 20940346..99abdbd9 100644--- a/src-tauri/src/service/mod.rs+++ b/src-tauri/src/service/mod.rs@@ -2,6 +2,7 @@ pub mod cli;pub mod download;pub mod migrate;pub mod plugin;+pub mod profile;pub mod scheduler;pub mod update;pub mod workflow;diff --git a/src-tauri/src/service/plugin/cancel.rs b/src-tauri/src/service/plugin/cancel.rsindex a26e40f8..3a4dc150 100644--- a/src-tauri/src/service/plugin/cancel.rs+++ b/src-tauri/src/service/plugin/cancel.rs@@ -33,11 +33,13 @@ pub async fn cancel(app_handle: &AppHandle) {#[cfg(windows)]{+ // 按当前档案匹配命令行:`dsh plugin --profile <当前档案> add`(不再写死 web)+ let profile = crate::service::profile::active_profile(app_handle);let base = config::get_dsh_install_path(app_handle).to_string_lossy().replace('\\', "\\\\");let ps_cmd = format!(- "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Where-Object {{ ($_.CommandLine -like '*plugin*--profile*web*add*') -and ($_.ExecutablePath -like '{base}\\*') }} | ForEach-Object {{ taskkill /PID $_.ProcessId /T /F 2>$null }}"+ "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Where-Object {{ ($_.CommandLine -like '*plugin*--profile*{profile}*add*') -and ($_.ExecutablePath -like '{base}\\*') }} | ForEach-Object {{ taskkill /PID $_.ProcessId /T /F 2>$null }}");let mut cmd = Command::new("powershell");diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rsnew file mode 100644index 00000000..8384f275--- /dev/null+++ b/src-tauri/src/service/profile/mod.rs@@ -0,0 +1,313 @@+//! 档案管理。+//!+//! 档案 = `$DSH_HOME/profiles/<id>` 目录,与官方 dsh CLI 的 profile 语义一致+//! (`dsh --profile <id>` 启动 / `dsh plugin --profile <id>` 管理插件)。+//! 桌面端把「当前使用哪个档案」持久化在自己的 store 设置(`active_profile`,+//! 默认 `web`),服务启动、插件安装/升级/卸载全部以它为准——不再写死 web。+//!+//! 新建档案时按官方 `dsh-app-boot` 的 `initProfile` 形态初始化目录:+//! `package.json`(含 web 模板 bundles)+ `cordis.patch.yml` + `pnpm-workspace.yaml`,+//! 与 CLI 侧产物完全一致,两边可互相操作。++use crate::config;+use serde::Serialize;+use std::fs;+use std::path::{Path, PathBuf};+use tauri::AppHandle;++/// 桌面端默认档案(内置,不可删除)+pub const DEFAULT_PROFILE: &str = "web";++/// 新建档案的初始 bundles:web 模板(`@deepseek-ai/dsh-base` ++/// `@deepseek-ai/dsh-web-app`,与 dsh-app-boot `PROFILE_TEMPLATES.web` 一致)。+/// 桌面端内嵌的是 dsh web 应用,新档案不带 `dsh-web-app` 将无法渲染任何界面。+const WEB_PROFILE_BUNDLES: [&str; 2] = ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app"];++/// dsh `initProfile` 生成的空 patch 层(与官方一致)+const PROFILE_PATCH_TEMPLATE: &str = "# Your patch layer for this dsh profile, applied after every bundle layer:\n# a top-level YAML array of loader patch entries (id-targeted config\n# overrides, disables, and insert lists; `!!js` expressions allowed).\n[]\n";++/// dsh `initProfile` 生成的 pnpm 设置(与官方一致)+const PROFILE_PNPM_WORKSPACE: &str = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";++/// 档案行(序列化 camelCase 给前端)+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Profile {+ /// 档案 id(目录名,npm 包名语义)+ pub id: String,+ /// 展示名(manifest.name 去 `dsh-profile-` 前缀,缺失回落 id)+ pub name: String,+ /// 是否桌面端内置默认档案(web)+ pub default: bool,+ /// 是否当前使用中的档案+ pub active: bool,+}++/// 指定档案的目录(`$DSH_HOME/profiles/<id>`)+pub fn profile_dir_of(app_handle: &AppHandle, id: &str) -> PathBuf {+ config::get_dsh_data_path(app_handle)+ .join("profiles")+ .join(id)+}++/// 当前使用的档案 id。+///+/// 读取桌面端持久化的 `active_profile`;若记录的档案目录已不存在(被删除/外部+/// 清理),回退默认 web。全新机器上 `profiles/` 尚未初始化时同样回退 web+/// (web 由 dsh 启动/插件操作时按需初始化)。+pub fn active_profile(app_handle: &AppHandle) -> String {+ let stored = config::get_store_dat_setting(app_handle).active_profile;+ if !stored.is_empty() && stored != DEFAULT_PROFILE && profile_dir_of(app_handle, &stored).is_dir()+ {+ stored+ } else {+ DEFAULT_PROFILE.to_string()+ }+}++/// 读取档案 manifest 的展示名:`dsh-profile-<id>` → `<id>`(首字母大写)。+fn manifest_display_name(dir: &Path, id: &str) -> String {+ let raw = fs::read_to_string(dir.join("package.json"))+ .ok()+ .and_then(|content| serde_json::from_str::<serde_json::Value>(&content).ok())+ .and_then(|v| v.get("name").and_then(|n| n.as_str()).map(String::from))+ .unwrap_or_default();+ let stripped = raw+ .strip_prefix("dsh-profile-")+ .filter(|s| !s.is_empty())+ .map(String::from)+ .unwrap_or_else(|| raw);+ let fallback = id.to_string();+ let name = if stripped.is_empty() { fallback } else { stripped };+ // 首字母大写,与既有「Web」展示风格一致+ let mut chars = name.chars();+ match chars.next() {+ Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),+ None => name,+ }+}++/// 档案列表(含 active/default 标记)。web 未初始化(全新安装)时也展示默认档案。+pub fn list(app_handle: &AppHandle) -> Vec<Profile> {+ let active = active_profile(app_handle);+ let profiles_root = config::get_dsh_data_path(app_handle).join("profiles");+ let mut out: Vec<Profile> = Vec::new();+ if let Ok(entries) = fs::read_dir(&profiles_root) {+ for entry in entries.flatten() {+ let path = entry.path();+ if !path.is_dir() {+ continue;+ }+ let Some(id) = path.file_name().and_then(|n| n.to_str()) else {+ continue;+ };+ // 跳过隐藏/系统目录(如 node_modules 回退链接区、.dsh 内部目录)+ if id.starts_with('.') || id == "node_modules" {+ continue;+ }+ out.push(Profile {+ id: id.to_string(),+ name: manifest_display_name(&path, id),+ default: id == DEFAULT_PROFILE,+ active: id == active,+ });+ }+ }+ if !out.iter().any(|p| p.id == DEFAULT_PROFILE) {+ out.push(Profile {+ id: DEFAULT_PROFILE.to_string(),+ name: "Web".to_string(),+ default: true,+ active: active == DEFAULT_PROFILE,+ });+ }+ // 稳定排序:默认档案在前,其余按 id 字典序+ out.sort_by_key(|p| (!p.default, p.id.clone()));+ out+}++/// 把展示名规范为档案 id:小写、非字母数字转 `-`(连续分隔符合并)、去首尾 `-`。+fn normalize_profile_id(name: &str) -> String {+ let mut out = String::with_capacity(name.len());+ let mut pending_sep = false;+ for c in name.to_lowercase().chars() {+ if c.is_ascii_alphanumeric() {+ if pending_sep && !out.is_empty() {+ out.push('-');+ }+ pending_sep = false;+ out.push(c);+ } else if c == ' ' || c == '-' || c == '_' {+ pending_sep = true;+ }+ // 其余字符(中文/符号)丢弃+ }+ out.trim_matches('-').to_string()+}++/// 新建档案:初始化 `$DSH_HOME/profiles/<id>`(manifest + patch + pnpm 设置)。+pub fn create(app_handle: &AppHandle, name: &str) -> Result<Profile, String> {+ let trimmed = name.trim();+ if trimmed.is_empty() {+ return Err("PROFILE_EMPTY_NAME: profile name is empty".to_string());+ }+ let id = normalize_profile_id(trimmed);+ if id.is_empty() {+ return Err("PROFILE_INVALID_NAME: profile name has no usable characters".to_string());+ }+ if id.len() > 64 {+ return Err("PROFILE_NAME_TOO_LONG: profile id exceeds 64 characters".to_string());+ }+ if id == DEFAULT_PROFILE {+ return Err("PROFILE_RESERVED: this name is reserved".to_string());+ }+ let dir = profile_dir_of(app_handle, &id);+ if dir.is_dir() {+ return Err(format!("PROFILE_EXISTS: profile {id} already exists"));+ }+ init_profile_dir(&dir, &id)?;+ Ok(Profile {+ id,+ name: trimmed.to_string(),+ default: false,+ active: false,+ })+}++/// 切换当前使用中的档案(持久化到桌面端 store)。+pub fn set_active(app_handle: &AppHandle, id: &str) -> Result<Profile, String> {+ let dir = profile_dir_of(app_handle, id);+ if id != DEFAULT_PROFILE && !dir.is_dir() {+ return Err(format!("PROFILE_NOT_FOUND: profile {id} does not exist"));+ }+ let mut setting = config::get_store_dat_setting(app_handle);+ setting.active_profile = id.to_string();+ config::set_store_dat_setting(app_handle, setting);+ list(app_handle)+ .into_iter()+ .find(|p| p.id == id)+ .ok_or_else(|| "PROFILE_NOT_FOUND: profile disappeared after switch".to_string())+}++/// 删除档案(默认档案与使用中的档案不可删除)。+pub fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {+ if id == DEFAULT_PROFILE {+ return Err("PROFILE_DEFAULT_NOT_REMOVABLE: the default profile cannot be removed".to_string());+ }+ if id == active_profile(app_handle) {+ return Err("PROFILE_ACTIVE_NOT_REMOVABLE: the active profile cannot be removed".to_string());+ }+ let dir = profile_dir_of(app_handle, id);+ if !dir.is_dir() {+ return Err(format!("PROFILE_NOT_FOUND: profile {id} does not exist"));+ }+ fs::remove_dir_all(&dir).map_err(|e| format!("PROFILE_REMOVE_FAILED: {e}"))+}++/// 初始化档案目录:与官方 `dsh-app-boot::initProfile` 的产物一致+/// (web 模板 bundles;已有文件绝不覆盖,重跑为 no-op)。+fn init_profile_dir(dir: &Path, id: &str) -> Result<(), String> {+ fs::create_dir_all(dir).map_err(|e| format!("PROFILE_MKDIR: {e}"))?;++ let manifest_path = dir.join("package.json");+ if !manifest_path.exists() {+ let manifest = serde_json::json!({+ "name": format!("dsh-profile-{id}"),+ "private": true,+ "dependencies": {},+ "dsh": { "profile": { "bundles": WEB_PROFILE_BUNDLES } }+ });+ let content = serde_json::to_string_pretty(&manifest)+ .map_err(|e| format!("PROFILE_MANIFEST_RENDER: {e}"))?;+ fs::write(&manifest_path, format!("{content}\n"))+ .map_err(|e| format!("PROFILE_MANIFEST_WRITE: {e}"))?;+ }++ let patch_path = dir.join("cordis.patch.yml");+ if !patch_path.exists() {+ fs::write(&patch_path, PROFILE_PATCH_TEMPLATE)+ .map_err(|e| format!("PROFILE_PATCH_WRITE: {e}"))?;+ }++ let workspace_path = dir.join("pnpm-workspace.yaml");+ if !workspace_path.exists() {+ fs::write(&workspace_path, PROFILE_PNPM_WORKSPACE)+ .map_err(|e| format!("PROFILE_WORKSPACE_WRITE: {e}"))?;+ }++ // pnpm 无 TTY 环境重装/更新会触发交互确认(ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY),+ // 与 ensure_profile_npmrc 一致地预写 .npmrc(幂等,绝不覆盖已有配置)。+ let npmrc_path = dir.join(".npmrc");+ let npmrc_existing = fs::read_to_string(&npmrc_path).unwrap_or_default();+ if !npmrc_existing.lines().any(|l| l.trim() == "confirmModulesPurge=false") {+ let mut content = npmrc_existing;+ if !content.is_empty() && !content.ends_with('\n') {+ content.push('\n');+ }+ content.push_str("confirmModulesPurge=false\n");+ fs::write(&npmrc_path, content).map_err(|e| format!("PROFILE_NPMRC_WRITE: {e}"))?;+ }++ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn normalize_id_lowercases_and_joins() {+ assert_eq!(normalize_profile_id("My Work Space"), "my-work-space");+ assert_eq!(normalize_profile_id(" dev--stage "), "dev-stage");+ assert_eq!(normalize_profile_id("中文档案"), "");+ assert_eq!(normalize_profile_id("a_b-c"), "a-b-c");+ }++ #[test]+ fn display_name_strips_manifest_prefix() {+ let dir = std::env::temp_dir().join(format!("dsh-profile-name-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ // 无 manifest → 回落 id+ assert_eq!(manifest_display_name(&dir, "beta"), "Beta");+ // manifest 带 dsh-profile- 前缀 → 剥离后首字母大写+ std::fs::write(+ dir.join("package.json"),+ r#"{"name":"dsh-profile-beta","private":true}"#,+ )+ .unwrap();+ assert_eq!(manifest_display_name(&dir, "beta"), "Beta");+ // 非标准 name → 原样+ std::fs::write(dir.join("package.json"), r#"{"name":"my-profile"}"#).unwrap();+ assert_eq!(manifest_display_name(&dir, "beta"), "My-profile");+ std::fs::remove_dir_all(&dir).ok();+ }++ #[test]+ fn init_profile_dir_scaffolds_official_shape() {+ let dir = std::env::temp_dir().join(format!("dsh-profile-init-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ init_profile_dir(&dir, "beta").unwrap();++ let manifest: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(dir.join("package.json")).unwrap())+ .unwrap();+ assert_eq!(manifest["name"], "dsh-profile-beta");+ assert_eq!(manifest["dependencies"], serde_json::json!({}));+ assert_eq!(+ manifest["dsh"]["profile"]["bundles"],+ serde_json::json!(["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app"])+ );+ assert!(dir.join("cordis.patch.yml").is_file());+ assert!(dir.join("pnpm-workspace.yaml").is_file());+ let npmrc = std::fs::read_to_string(dir.join(".npmrc")).unwrap();+ assert!(npmrc.contains("confirmModulesPurge=false"));++ // 幂等:再次初始化不报错、不重复写 .npmrc+ init_profile_dir(&dir, "beta").unwrap();+ let npmrc2 = std::fs::read_to_string(dir.join(".npmrc")).unwrap();+ assert_eq!(npmrc, npmrc2);++ std::fs::remove_dir_all(&dir).ok();+ }+}diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsindex 95fcfe84..687531da 100644--- a/src-tauri/src/service/workflow/mod.rs+++ b/src-tauri/src/service/workflow/mod.rs@@ -530,13 +530,14 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// Windows 打包版是 GUI 进程(没有控制台)。直接以 CREATE_NO_WINDOW 启动// node 会让 dsh 派生的子进程各自新建可见控制台窗口(频繁闪烁 cmd 黑窗),// 因此 Windows 上改用“隐藏控制台”方式启动,见 win_spawn 模块。+ let active_profile = crate::service::profile::active_profile(&app_handle);let spawn_result = {#[cfg(windows)]{let mut args: Vec<OsString> = vec![dsh_binary_path.as_os_str().to_os_string(),OsString::from("--profile"),- OsString::from("web"),+ OsString::from(active_profile.as_str()),OsString::from("--host"),OsString::from("127.0.0.1"),OsString::from("--port"),@@ -593,7 +594,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {let mut cmd = Command::new(&node_binary_path);cmd.arg(&dsh_binary_path).arg("--profile")- .arg("web")+ .arg(active_profile.as_str()).arg("--host").arg("127.0.0.1").arg("--port")diff --git a/src-tauri/src/service/workflow/win_inspector.rs b/src-tauri/src/service/workflow/win_inspector.rsindex c62a490c..66a261bd 100644--- a/src-tauri/src/service/workflow/win_inspector.rs+++ b/src-tauri/src/service/workflow/win_inspector.rs@@ -69,11 +69,12 @@ mod imp {r"C:\Program Files (x86)\Git\usr\bin\bash.exe",];- /// web profile 目录:`<DSH_HOME>/profiles/web`。+ /// 当前档案的 profile 目录:`<DSH_HOME>/profiles/<当前档案>`。fn profile_dir(app_handle: &tauri::AppHandle) -> PathBuf {- crate::config::get_dsh_data_path(app_handle)- .join("profiles")- .join("web")+ crate::service::profile::profile_dir_of(+ app_handle,+ &crate::service::profile::active_profile(app_handle),+ )}/// dsh 用户数据目录(`$DSH_HOME`)。diff --git a/src/components/config-profile.tsx b/src/components/config-profile.tsxindex a0b1a067..ea09a007 100644--- a/src/components/config-profile.tsx+++ b/src/components/config-profile.tsx@@ -5,63 +5,58 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import { If } from 'react-if-lite'+import { store } from '@/store'import { toast } from '@/utils'+import { useDshProfiles } from '../hooks/use-dsh-profiles'import { Dialog } from './dialog'import { Ellipsis } from './ellipsis'-/** 档案行:一个 dsh 配置档案(隔离的插件/补丁/设置集合) */-export interface Profile {- id: string- name: string- /** 是否为默认档案 */- default: boolean- /** 是否为当前使用的档案 */- active: boolean- /** 简短说明的 i18n key(可选) */- description?: string-}-export function ConfigProfile() {/**- * 「档案」面板:展示 & 切换 dsh 配置档案,支持新建。- *- * 列表用 HeroUI `ListBox` 标准用法渲染:`selectionMode="single"` + 受控- * `selectedKeys` 表示当前激活档案,`ListBox.ItemIndicator` 渲染选中标记。+ * 「档案」面板:展示 & 切换 dsh 配置档案,支持新建/删除。*- * 注意:后端尚无 get_profiles / set_active_profile / create_profile 命令,- * 按需求约定「仅前端 + 内置示范数据」在此用本地状态驱动 UI(含本地交互演示);- * 后端命令落地后,把 `useState` 初始值换成真实查询、把本地更新换成接口调用即可。+ * 数据来自 `useDshProfiles`(`get_profiles` 查询 + `setting_updated` 事件刷新):+ * 档案 = `$DSH_HOME/profiles/<id>` 目录,与官方 dsh CLI 的 profile 语义一致;+ * 桌面端把「当前档案」持久化在 store(`active_profile`),服务启动与插件管理+ * 都以它为准。切换档案需要重启服务才生效(toast 内提供重启入口)。*/- const DEMO_PROFILES: Profile[] = [- { id: 'web', name: 'Web', default: true, active: true, description: '官方默认' },- ]+ const { profiles, loading, error, createProfile, activateProfile, removeProfile, busy } = useDshProfiles()const [dialogHolder, openDialog] = useOverlay(Dialog, { type: 'holder' })const { t } = useTranslation()- const [profiles, setProfiles] = useState<Profile[]>(DEMO_PROFILES)const [creating, setCreating] = useState(false)const [name, setName] = useState('')async function activate(id: string) {const target = profiles.find(p => p.id === id)- if (!target || target.active)+ if (!target || target.active || busy)returnawait openDialog({status: 'warning',- title: '确认切换档案?',+ title: t('profiles.activate_confirm_title'),description: (<p>- 切换至- {' '}- <strong>{target.name}</strong>- {' '}- 档案,相应的插件与设置将被一同切换。+ {t('profiles.activate_confirm_desc', { name: target.name })}</p>),})- setProfiles(prev => prev.map(p => ({ ...p, active: p.id === id })))- toast(t('profiles.activate_toast', { name: target.name }), {})+ try {+ await activateProfile(id)+ 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(),+ },+ })+ }+ catch (err) {+ console.error('[ConfigProfile] activate failed:', err)+ toast(t('profiles.activate_failed', { name: target.name }), {})+ }}function startCreate() {@@ -74,40 +69,44 @@ export function ConfigProfile() {setName('')}- function commitCreate() {+ async function commitCreate() {const trimmed = name.trim()if (!trimmed)return- const id = trimmed.toLowerCase().replace(/\s+/g, '-')- setProfiles(prev => [- ...prev,- { id, name: trimmed, default: false, active: false },- ])- setCreating(false)- setName('')- toast(t('profiles.created_toast', { name: trimmed }), {})+ try {+ // 创建成功后列表已刷新出新档案,UI 本身就有变化,不再弹成功 toast+ await createProfile(trimmed)+ setCreating(false)+ setName('')+ }+ catch (err) {+ console.error('[ConfigProfile] create failed:', err)+ toast(t('profiles.create_failed'), {})+ }}async function remove(id: string) {const target = profiles.find(p => p.id === id)- if (!target)+ if (!target || busy)returnawait openDialog({- title: 'Remove Profile',+ title: t('profiles.remove_confirm_title'),status: 'danger',description: (<p>- This will permanently delete- {' '}- <strong>{target.name}</strong>- {' '}- and all of its- data. This action cannot be undone.+ {t('profiles.remove_confirm_desc', { name: target.name })}</p>),+ confirmText: t('profiles.remove_confirm'),})- setProfiles(prev => prev.filter(p => p.id !== id))- toast(t('profiles.removed_toast', { name: id }), {})+ try {+ // 删除成功后列表已移除该档案,UI 本身就有变化,不再弹成功 toast+ await removeProfile(id)+ }+ catch (err) {+ console.error('[ConfigProfile] remove failed:', err)+ toast(t('profiles.remove_failed'), {})+ }}return (@@ -122,92 +121,115 @@ export function ConfigProfile() {</Typography></div>- <div className="space-y-3 flex-wrap gap-2">- {profiles.map(profile => (- <Card key={profile.id} className="bg-[#f5f5f5] rounded-md py-3 cursor-pointer" onClick={() => activate(profile.id)}>- <Card.Content className="flex flex-row justify-between">- <div className="flex items-center gap-1">- <Label className="min-w-0 truncate text-sm font-medium text-ink">- {profile.name}- </Label>- <If cond={profile.description != null}>- <Description className="min-w-0 text-xs text-muted">- <Ellipsis>{t(profile.description as string)}</Ellipsis>- </Description>- </If>- </div>- <div className="flex items-center gap-2">- <Checkbox- isSelected={profile.active}- aria-label={profile.name}- className="shrink-0"- >- <Checkbox.Content>- <Checkbox.Control>- <Checkbox.Indicator />- </Checkbox.Control>- </Checkbox.Content>- </Checkbox>- <If cond={!profile.default}>- <Chip- className="rounded-md"- variant="primary"- color="danger"- size="sm"- onClick={(event) => {- event.stopPropagation()- remove(profile.id)- }}+ {/* 加载 / 失败 / 列表 */}+ <If+ cond={!loading && error === ''}+ else={(+ <If+ cond={loading}+ else={(+ <p className="rounded-md border border-danger/30 bg-danger/5 p-3 text-xs text-danger">+ {t('plugins.error')}+ :+ {error}+ </p>+ )}+ >+ <div className="flex items-center justify-center gap-2 p-4 text-xs text-muted">+ {t('plugins.loading')}+ </div>+ </If>+ )}+ >+ <div className="space-y-3 flex-wrap gap-2">+ {profiles.map(profile => (+ <Card key={profile.id} className="bg-[#f5f5f5] rounded-md py-3 cursor-pointer" onClick={() => activate(profile.id)}>+ <Card.Content className="flex flex-row justify-between">+ <div className="flex items-center gap-1">+ <Label className="min-w-0 truncate text-sm font-medium text-ink">+ {profile.name}+ </Label>+ <If cond={profile.default}>+ <Description className="min-w-0 text-xs text-muted">+ <Ellipsis>{t('profiles.default_desc')}</Ellipsis>+ </Description>+ </If>+ </div>+ <div className="flex items-center gap-2">+ <Checkbox+ isSelected={profile.active}+ isDisabled={busy}+ aria-label={profile.name}+ className="shrink-0">- 删除- </Chip>- </If>+ <Checkbox.Content>+ <Checkbox.Control>+ <Checkbox.Indicator />+ </Checkbox.Control>+ </Checkbox.Content>+ </Checkbox>+ <If cond={!profile.default}>+ <Chip+ className="rounded-md"+ variant="primary"+ color="danger"+ size="sm"+ onClick={(event) => {+ event.stopPropagation()+ remove(profile.id)+ }}+ >+ {t('profiles.remove')}+ </Chip>+ </If>+ </div>+ </Card.Content>+ </Card>+ ))}+ {/* 新建档案:内联输入 or 触发入口 */}+ <If+ cond={!creating}+ else={(+ <div className="flex items-center gap-2 px-1">+ <Input+ autoFocus+ variant="secondary"+ className="h-8 flex-1 rounded-md"+ placeholder={t('profiles.name_placeholder')}+ value={name}+ onChange={e => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter')+ commitCreate()+ }}+ />+ <Button size="sm" variant="tertiary" className="h-8 rounded-md" onPress={cancelCreate}>+ {t('profiles.create_cancel')}+ </Button>+ <Button+ size="sm"+ variant="primary"+ className="h-8 rounded-md"+ isDisabled={!name.trim() || busy}+ onPress={commitCreate}+ >+ {t('profiles.create_confirm')}+ </Button></div>- </Card.Content>- </Card>- ))}- {/* 新建档案:内联输入 or 触发入口 */}- <If- cond={!creating}- else={(- <div className="flex items-center gap-2 px-1">- <Input- autoFocus- variant="secondary"- className="h-8 flex-1 rounded-md"- placeholder={t('profiles.name_placeholder')}- value={name}- onChange={e => setName(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter')- commitCreate()- }}- />- <Button size="sm" variant="tertiary" className="h-8 rounded-md" onPress={cancelCreate}>- {t('profiles.create_cancel')}- </Button>- <Button- size="sm"- variant="primary"- className="h-8 rounded-md"- isDisabled={!name.trim()}- onPress={commitCreate}- >- {t('profiles.create_confirm')}- </Button>- </div>- )}- >- <Button- onClick={startCreate}- variant="tertiary"- className="flex w-full rounded-md"+ )}>- <Plus className="size-3.5" />- <span>{t('profiles.new_profile')}</span>- </Button>- </If>- </div>+ <Button+ onClick={startCreate}+ variant="tertiary"+ className="flex w-full rounded-md"+ isDisabled={busy}+ >+ <Plus className="size-3.5" />+ <span>{t('profiles.new_profile')}</span>+ </Button>+ </If>+ </div>+ </If>{dialogHolder}</div>)diff --git a/src/hooks/use-dsh-profiles.ts b/src/hooks/use-dsh-profiles.tsnew file mode 100644index 00000000..b7726028--- /dev/null+++ b/src/hooks/use-dsh-profiles.ts@@ -0,0 +1,98 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import { useEffect } from 'react'++/** Rust 侧 service::profile::Profile 的序列化形态(camelCase) */+export interface Profile {+ /** 档案 id($DSH_HOME/profiles/<id> 目录名) */+ id: string+ /** 展示名(manifest name 去 dsh-profile- 前缀,首字母大写) */+ name: string+ /** 是否桌面端内置默认档案(web) */+ default: boolean+ /** 是否当前使用中的档案 */+ active: boolean+}++export interface UseDshProfilesResult {+ profiles: Profile[]+ loading: boolean+ error: string+ /** 新建档案(返回新档案;不自动激活) */+ createProfile: (name: string) => Promise<Profile>+ /** 切换当前使用中的档案(持久化;重启服务后生效) */+ activateProfile: (id: string) => Promise<Profile>+ /** 删除档案(默认/使用中的档案会被后端拒绝) */+ removeProfile: (id: string) => Promise<void>+ /** 操作进行中标记(新建/切换/删除任一) */+ busy: boolean+}++/**+ * 档案列表与操作(react-query)。+ *+ * 查询键 `['profiles']`:`set_active_profile` 会写桌面端 store(触发+ * `setting_updated` 事件),这里监听该事件一并失效重拉,保证与后端设置一致。+ */+export function useDshProfiles(): UseDshProfilesResult {+ const queryClient = useQueryClient()++ const { data, isLoading, error, refetch } = useQuery({+ queryKey: ['profiles'],+ queryFn: () => invoke<Profile[]>('get_profiles'),+ })++ // 后端设置变更(切换档案等)后刷新档案列表+ useEffect(() => {+ let unlisten: (() => void) | undefined+ listen('setting_updated', () => {+ void queryClient.invalidateQueries({ queryKey: ['profiles'] })+ })+ .then((fn) => {+ unlisten = fn+ })+ .catch(() => {})+ return () => {+ unlisten?.()+ }+ }, [queryClient])++ const invalidate = () => {+ void queryClient.invalidateQueries({ queryKey: ['profiles'] })+ }++ const create = useMutation({+ mutationFn: (name: string) => invoke<Profile>('create_profile', { name }),+ onSuccess: invalidate,+ })+ const activate = useMutation({+ mutationFn: (id: string) => invoke<Profile>('set_active_profile', { id }),+ onSuccess: invalidate,+ })+ const remove = useMutation({+ mutationFn: (id: string) => invoke<void>('remove_profile', { id }),+ onSuccess: invalidate,+ })++ return {+ profiles: data ?? [],+ loading: isLoading,+ error: error ? String(error) : '',+ createProfile: async (name) => {+ const created = await create.mutateAsync(name)+ await refetch()+ return created+ },+ activateProfile: async (id) => {+ const activated = await activate.mutateAsync(id)+ await refetch()+ return activated+ },+ removeProfile: async (id) => {+ await remove.mutateAsync(id)+ await refetch()+ },+ busy: create.isPending || activate.isPending || remove.isPending,+ }+}diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex 5aa74661..8de91859 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -72,7 +72,7 @@"download.failed": "Session log download failed","download.show_in_folder": "Open","errors.service_start_timeout": "DeepSeek Harness startup timeout. Please check whether port {{port}} is occupied or the startup is too slow.",- "errors.plugin_route_conflict": "Detected a plugin route conflict: two plugins registered the same route twice. Uninstall the recently added plugin (e.g. dsh-web-ui-all / dsh-better-sidebar) from the Plugins panel, or run dsh plugin --profile web remove <package> and retry.",+ "errors.plugin_route_conflict": "Detected a plugin route conflict: two plugins registered the same route twice. Uninstall the recently added plugin (e.g. dsh-web-ui-all / dsh-better-sidebar) from the Plugins panel, or run dsh plugin --profile <profile> remove <package> for the active profile and retry.","errors.install_verify_failed": "Package downloaded but installation verification failed.","errors.network_timeout": "Network download timeout. Please check your network connection.","errors.unknown": "Unknown error",@@ -144,7 +144,16 @@"profiles.create_cancel": "Cancel","profiles.create_confirm": "Create","profiles.activate_toast": "{{name}} is now the active profile",- "profiles.created_toast": "Created profile {{name}}",+ "profiles.activate_confirm_title": "Switch profile?",+ "profiles.activate_confirm_desc": "Switch to the {{name}} profile? Its plugins and settings will be used from now on.",+ "profiles.activate_restart_hint": "Takes effect after the service restarts. Restart now?",+ "profiles.activate_failed": "Failed to switch to {{name}}",+ "profiles.create_failed": "Failed to create profile",+ "profiles.remove": "Delete",+ "profiles.remove_confirm_title": "Delete profile",+ "profiles.remove_confirm_desc": "Delete {{name}} permanently? Its plugins and settings will be removed. This cannot be undone.",+ "profiles.remove_confirm": "Delete",+ "profiles.remove_failed": "Failed to delete profile","plugins.panel_tooltip": "Installed plugins, read-only. Plugins normally need no management here — upgrade or uninstall one only when it is causing problems.","plugins.uninstall": "Uninstall","plugins.upgrade": "Upgrade",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex a9c4843b..8f8853a7 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -72,7 +72,7 @@"download.failed": "Session 日志下载失败","download.show_in_folder": "打开","errors.service_start_timeout": "DeepSeek Harness 启动超时,请检查端口 {{port}} 是否被占用或启动过慢。",- "errors.plugin_route_conflict": "检测到插件路由冲突:两个插件重复注册了同一路由。请在「插件」面板卸载最近安装的插件(如 dsh-web-ui-all / dsh-better-sidebar),或在终端执行 dsh plugin --profile web remove <包名> 后重试。",+ "errors.plugin_route_conflict": "检测到插件路由冲突:两个插件重复注册了同一路由。请在「插件」面板卸载最近安装的插件(如 dsh-web-ui-all / dsh-better-sidebar),或在终端对当前档案执行 dsh plugin --profile <档案名> remove <包名> 后重试。","errors.install_verify_failed": "资源包已下载,但安装校验失败。","errors.network_timeout": "网络下载超时,请检查网络连接后重试。","errors.unknown": "未知错误",@@ -138,13 +138,22 @@"profiles.title": "档案","profiles.tooltip": "档案是 dsh 中一组相互隔离的配置集合,包含各自的插件、补丁与设置。桌面端运行在默认的 web 档案中;新建档案可试用不同的插件组合而不影响当前配置。","profiles.active": "使用中",- "profiles.default_desc": "桌面端默认档案",+ "profiles.default_desc": "默认档案","profiles.new_profile": "新建档案","profiles.name_placeholder": "档案名称","profiles.create_cancel": "取消","profiles.create_confirm": "创建","profiles.activate_toast": "已将 {{name}} 设为使用中",- "profiles.created_toast": "已创建档案 {{name}}",+ "profiles.activate_confirm_title": "确认切换档案?",+ "profiles.activate_confirm_desc": "切换至 {{name}} 档案,相应的插件与设置将被一同切换。",+ "profiles.activate_restart_hint": "重启服务后生效,是否立即重启?",+ "profiles.activate_failed": "切换档案 {{name}} 失败",+ "profiles.create_failed": "创建档案失败",+ "profiles.remove": "删除",+ "profiles.remove_confirm_title": "删除档案",+ "profiles.remove_confirm_desc": "确定删除档案 {{name}} 吗?将同时删除其插件与设置,此操作不可撤销。",+ "profiles.remove_confirm": "删除",+ "profiles.remove_failed": "删除档案失败","plugins.panel_tooltip": "该面板只读展示已安装插件。插件通常无需在此管理;仅当某个插件出现问题时,才需要在这里升级或卸载它。","plugins.uninstall": "卸载","plugins.upgrade": "升级",diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.tsindex 481b06f5..8ae5390b 100644--- a/src/store/modules/harness/store.ts+++ b/src/store/modules/harness/store.ts@@ -253,6 +253,8 @@ export const harness = defineStore({void queryClient.invalidateQueries({ queryKey: ['info'] })void queryClient.invalidateQueries({ queryKey: ['config'] })void queryClient.invalidateQueries({ queryKey: ['cli_status'] })+ // 档案/核心切换后重启:当前档案的插件列表、核心来源状态一并刷新+ void queryClient.invalidateQueries({ queryKey: ['profiles'] })}catch (err) {// 失败时附上服务日志里的真实错误行,供错误界面展示而不是只显示超时文案