Skip to content

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

feat(08): 克隆档案 — full copy + auto-increment naming (#248)

CoderStoryecd5277036b4
diff --git a/src-tauri/src/bridge/profile.rs b/src-tauri/src/bridge/profile.rs
index b2216482..d31f173c 100644
--- a/src-tauri/src/bridge/profile.rs
+++ b/src-tauri/src/bridge/profile.rs
@@ -29,3 +29,9 @@ pub fn set_active_profile(app_handle: AppHandle, id: String) -> Result<profile::
pub fn remove_profile(app_handle: AppHandle, id: String) -> Result<(), String> {
profile::remove(&app_handle, &id)
}
+
+/// 克隆档案(全量复制源档案目录,自动递增命名或指定名称)
+#[tauri::command]
+pub fn clone_profile(app_handle: AppHandle, source_id: String, name: Option<String>) -> Result<profile::Profile, String> {
+ profile::clone(&app_handle, &source_id, name.as_deref())
+}
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index 2f4c4f80..506c2726 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -463,4 +463,4 @@ mod tests {
"写入 store 再读回后关闭行为应保持不变"
);
}
-}
+}
\ No newline at end of file
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 43470ac1..b3db1c4d 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -528,6 +528,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::create_profile,
crate::bridge::set_active_profile,
crate::bridge::remove_profile,
+ crate::bridge::clone_profile,
crate::bridge::backup_profile,
crate::bridge::restore_profile,
crate::bridge::list_backups,
diff --git a/src-tauri/src/service/migrate.rs b/src-tauri/src/service/migrate.rs
index 7b69055e..fdc5b9b1 100644
--- a/src-tauri/src/service/migrate.rs
+++ b/src-tauri/src/service/migrate.rs
@@ -176,7 +176,7 @@ fn src_newer(src: &Path, dst: &Path) -> bool {
///
/// 递归遍历目录:只处理名为 `node_modules` 的目录(查其下 `.modules.yaml`,不
/// 深入 node_modules 内部的海量子目录)。best-effort,删除失败仅告警。
-fn purge_carried_pnpm_metadata(root: &Path) {
+pub(crate) fn purge_carried_pnpm_metadata(root: &Path) {
let Ok(entries) = fs::read_dir(root) else {
return;
};
diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rs
index d19da748..c7fae228 100644
--- a/src-tauri/src/service/profile/mod.rs
+++ b/src-tauri/src/service/profile/mod.rs
@@ -272,6 +272,125 @@ pub fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {
fs::remove_dir_all(&dir).map_err(|e| format!("PROFILE_REMOVE_FAILED: {e}"))
}
+/// 克隆档案:全量复制源档案目录,自动递增命名(web → web-1 → web-2)。
+///
+/// - `source_id` 经 `fs_guard::validate_id` 校验,拒绝路径穿越;
+/// - `name` 为 `None` 时按 source_id 自动递增;`Some` 时规范化并校验冲突;
+/// - 复制后清除搬入的 pnpm 元数据(`.modules.yaml`),并重写 manifest name 为
+/// `dsh-profile-<new-id>`。
+pub fn clone(app_handle: &AppHandle, source_id: &str, name: Option<&str>) -> Result<Profile, String> {
+ let profiles_root = config::get_dsh_data_path(app_handle).join("profiles");
+ clone_with_root(&profiles_root, source_id, name)
+}
+
+/// 克隆实现(以 `profiles_root` 为根,便于单测注入临时目录)。
+pub fn clone_with_root(profiles_root: &Path, source_id: &str, name: Option<&str>) -> Result<Profile, String> {
+ fs_guard::validate_id(source_id)?;
+ let src_dir = fs_guard::join_safe(profiles_root, source_id)?;
+ if !src_dir.is_dir() {
+ return Err(format!("PROFILE_NOT_FOUND: profile {source_id} does not exist"));
+ }
+
+ let new_id = match name {
+ Some(n) => {
+ let trimmed = n.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 target = profiles_root.join(&id);
+ if target.is_dir() {
+ return Err(format!("PROFILE_EXISTS: profile {id} already exists"));
+ }
+ id
+ }
+ None => next_profile_id(profiles_root, source_id)?,
+ };
+
+ let dst_dir = profiles_root.join(&new_id);
+ copy_dir_tree(&src_dir, &dst_dir)?;
+ crate::service::migrate::purge_carried_pnpm_metadata(&dst_dir);
+ rewrite_manifest_name(&dst_dir, &new_id)?;
+
+ Ok(Profile {
+ id: new_id.clone(),
+ name: manifest_display_name(&dst_dir, &new_id),
+ default: false,
+ active: false,
+ })
+}
+
+/// 解析下一个未占用的自动递增 id(base → base-1 → base-2 …,上限 1000)。
+fn next_profile_id(profiles_root: &Path, base: &str) -> Result<String, String> {
+ let mut n = 1;
+ loop {
+ if n > 1000 {
+ return Err("PROFILE_CLONE_EXHAUSTED: too many clones".to_string());
+ }
+ let candidate = format!("{base}-{n}");
+ if !profiles_root.join(&candidate).is_dir() {
+ return Ok(candidate);
+ }
+ n += 1;
+ }
+}
+
+/// 递归复制目录树到全新目标(跳过 profile 根下隐藏目录,保留 `.npmrc`)。
+fn copy_dir_tree(src: &Path, dst: &Path) -> Result<(), String> {
+ fs::create_dir_all(dst).map_err(|e| format!("COPY_MKDIR: {e}"))?;
+ for entry in fs::read_dir(src).map_err(|e| format!("COPY_READ: {e}"))? {
+ let entry = entry.map_err(|e| format!("COPY_ENTRY: {e}"))?;
+ let name = entry.file_name();
+ if let Some(s) = name.to_str() {
+ if s.starts_with('.') && s != ".npmrc" {
+ let path = entry.path();
+ // 跳过隐藏目录(如 .dsh、.pnpm 内部)
+ if path.is_dir() {
+ continue;
+ }
+ // 隐藏文件(非 .npmrc)跳过
+ continue;
+ }
+ }
+ let src_path = entry.path();
+ let dst_path = dst.join(&name);
+ let ty = entry.file_type().map_err(|e| format!("COPY_TYPE: {e}"))?;
+ if ty.is_dir() {
+ copy_dir_tree(&src_path, &dst_path)?;
+ } else if ty.is_file() {
+ fs::copy(&src_path, &dst_path).map_err(|e| format!("COPY_FILE: {e}"))?;
+ }
+ }
+ Ok(())
+}
+
+/// 重写克隆档案 manifest 的 `name` 字段为 `dsh-profile-<new-id>`。
+fn rewrite_manifest_name(dir: &Path, new_id: &str) -> Result<(), String> {
+ let path = dir.join("package.json");
+ let content = fs::read_to_string(&path).map_err(|e| format!("MANIFEST_READ: {e}"))?;
+ let mut manifest: serde_json::Value =
+ serde_json::from_str(&content).map_err(|e| format!("MANIFEST_PARSE: {e}"))?;
+ if let Some(obj) = manifest.as_object_mut() {
+ obj.insert(
+ "name".to_string(),
+ serde_json::Value::String(format!("dsh-profile-{new_id}")),
+ );
+ }
+ let rendered = serde_json::to_string_pretty(&manifest)
+ .map_err(|e| format!("MANIFEST_RENDER: {e}"))?;
+ fs::write(&path, format!("{rendered}\n"))
+ .map_err(|e| format!("MANIFEST_WRITE: {e}"))
+}
+
/// 初始化档案目录:与官方 `dsh-app-boot::initProfile` 的产物一致
/// (web 模板 bundles;已有文件绝不覆盖,重跑为 no-op)。
fn init_profile_dir(dir: &Path, id: &str) -> Result<(), String> {
@@ -322,6 +441,125 @@ fn init_profile_dir(dir: &Path, id: &str) -> Result<(), String> {
Ok(())
}
+#[cfg(test)]
+mod clone_tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ /// 在 profiles 根目录下构造一个最小源档案目录,返回其路径。
+ fn scaffold_source(root: &PathBuf, id: &str) -> PathBuf {
+ let dir = root.join(id);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(
+ dir.join("package.json"),
+ format!(r#"{{"name":"dsh-profile-{id}","private":true}}"#),
+ )
+ .unwrap();
+ std::fs::write(dir.join("cordis.patch.yml"), "# patch\n[]\n").unwrap();
+ std::fs::create_dir_all(dir.join("sub")).unwrap();
+ std::fs::write(dir.join("sub/deep.txt"), "nested content").unwrap();
+ dir
+ }
+
+ #[test]
+ fn clone_produces_independent_copy_with_incremented_name() {
+ let tmp = std::env::temp_dir().join(format!("dsh-clone-ok-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let root = tmp.join("profiles");
+ scaffold_source(&root, "web");
+
+ let profile = clone_with_root(&root, "web", None).unwrap();
+ assert_eq!(profile.id, "web-1");
+ assert!(!profile.default);
+ assert!(!profile.active);
+
+ let dst = root.join("web-1");
+ assert!(dst.is_dir(), "cloned dir must exist");
+ assert!(dst.join("package.json").is_file());
+ assert!(dst.join("cordis.patch.yml").is_file());
+ assert!(dst.join("sub/deep.txt").is_file());
+
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+
+ #[test]
+ fn clone_skips_taken_names() {
+ let tmp = std::env::temp_dir().join(format!("dsh-clone-skip-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let root = tmp.join("profiles");
+ scaffold_source(&root, "web");
+ std::fs::create_dir_all(root.join("web-1")).unwrap();
+ std::fs::write(root.join("web-1/package.json"), r#"{"name":"dsh-profile-web-1"}"#).unwrap();
+
+ let profile = clone_with_root(&root, "web", None).unwrap();
+ assert_eq!(profile.id, "web-2");
+
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+
+ #[test]
+ fn clone_rewrites_manifest_name() {
+ let tmp = std::env::temp_dir().join(format!("dsh-clone-manifest-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let root = tmp.join("profiles");
+ scaffold_source(&root, "web");
+
+ let profile = clone_with_root(&root, "web", None).unwrap();
+ let dst = root.join(&profile.id);
+ let manifest: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(dst.join("package.json")).unwrap()).unwrap();
+ assert_eq!(manifest["name"], format!("dsh-profile-{}", profile.id));
+
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+
+ #[test]
+ fn clone_rejects_traversal_id() {
+ let tmp = std::env::temp_dir().join(format!("dsh-clone-traversal-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let root = tmp.join("profiles");
+ scaffold_source(&root, "web");
+
+ let err = clone_with_root(&root, "..", None).unwrap_err();
+ assert!(
+ err.contains("INVALID_ID") || err.contains("INVALID"),
+ "expected traversal rejection, got: {err}"
+ );
+
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+
+ #[test]
+ fn clone_of_missing_source_returns_not_found() {
+ let tmp = std::env::temp_dir().join(format!("dsh-clone-missing-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let root = tmp.join("profiles");
+
+ let err = clone_with_root(&root, "nonexistent", None).unwrap_err();
+ assert!(err.contains("PROFILE_NOT_FOUND"), "expected PROFILE_NOT_FOUND, got: {err}");
+
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+
+ #[test]
+ fn clone_purges_carried_pnpm_metadata() {
+ let tmp = std::env::temp_dir().join(format!("dsh-clone-pnpm-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let root = tmp.join("profiles");
+ scaffold_source(&root, "web");
+ let nm = root.join("web/node_modules");
+ std::fs::create_dir_all(&nm).unwrap();
+ std::fs::write(nm.join(".modules.yaml"), "lockfileVersion: '9.0'\nstoreDir: /old/store\n").unwrap();
+
+ let profile = clone_with_root(&root, "web", None).unwrap();
+ let dst_nm = root.join(&profile.id).join("node_modules");
+ assert!(dst_nm.is_dir(), "node_modules should be copied");
+ assert!(!dst_nm.join(".modules.yaml").exists(), "carried .modules.yaml must be purged");
+
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/components/config-profile.tsx b/src/components/config-profile.tsx
index 28f5d446..b5bce413 100644
--- a/src/components/config-profile.tsx
+++ b/src/components/config-profile.tsx
@@ -1,5 +1,5 @@
import { Plus } from '@gravity-ui/icons'
-import { Button, Checkbox, Chip, Description, Input, Label } from '@heroui/react'
+import { AlertDialog, Button, Checkbox, Chip, Description, Input, Label } from '@heroui/react'
import { useOverlay } from '@overlastic/react'
import { useState } from 'react'
@@ -26,7 +26,7 @@ export function ConfigProfile() {
* 桌面端把「当前档案」持久化在 store(`active_profile`),服务启动与插件管理
* 都以它为准。切换档案需要重启服务才生效(toast 内提供重启入口)。
*/
- const { profiles, loading, error, createProfile, activateProfile, removeProfile, busy } = useDshProfiles()
+ const { profiles, loading, error, createProfile, activateProfile, removeProfile, cloneProfile, busy } = useDshProfiles()
const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })
@@ -35,6 +35,50 @@ export function ConfigProfile() {
const [name, setName] = useState('')
const [activeView, setActiveView] = useState<ProfileView>('list')
+ // 克隆档案:命名对话框状态
+ const [cloning, setCloning] = useState<{ sourceId: string, sourceName: string } | null>(null)
+ const [cloneName, setCloneName] = useState('')
+
+ /** 推导下一个未占用的自动递增名称(仅作为建议,后端才是权威) */
+ function suggestCloneName(base: string): string {
+ const taken = new Set(profiles.map(p => p.id))
+ for (let n = 1; n <= 1000; n++) {
+ const candidate = `${base}-${n}`
+ if (!taken.has(candidate))
+ return candidate
+ }
+ return `${base}-1`
+ }
+
+ function openCloneDialog(profile: { id: string, name: string }) {
+ setCloning({ sourceId: profile.id, sourceName: profile.name })
+ setCloneName(suggestCloneName(profile.id))
+ }
+
+ async function commitClone() {
+ if (!cloning)
+ return
+ const trimmed = cloneName.trim()
+ if (!trimmed) {
+ toast(t('profiles.clone_empty'), {})
+ return
+ }
+ try {
+ await cloneProfile(cloning.sourceId, trimmed)
+ setCloning(null)
+ setCloneName('')
+ toast(t('profiles.clone_success', { name: trimmed }), {
+ variant: 'accent',
+ description: t('profiles.clone_success_hint'),
+ timeout: 10_000,
+ })
+ }
+ catch (err) {
+ console.error('[ConfigProfile] clone failed:', err)
+ toast(t('profiles.clone_failed'), {})
+ }
+ }
+
async function activate(id: string) {
const target = profiles.find(p => p.id === id)
if (!target || target.active || busy)
@@ -161,18 +205,6 @@ export function ConfigProfile() {
)}
right={(
<>
- <Chip
- className="rounded-md mr-1"
- variant="secondary"
- color="accent"
- size="sm"
- onClick={(event) => {
- event.stopPropagation()
- setActiveView({ profile: profile.id })
- }}
- >
- {t('backup.manage')}
- </Chip>
<Checkbox
isSelected={profile.active}
isDisabled={busy}
@@ -185,15 +217,38 @@ export function ConfigProfile() {
</Checkbox.Control>
</Checkbox.Content>
</Checkbox>
+ <Chip
+ className="rounded-md"
+ size="sm"
+ onClick={(event) => {
+ event.stopPropagation()
+ setActiveView({ profile: profile.id })
+ }}
+ >
+ {t('backup.manage')}
+ </Chip>
+ <Chip
+ className={`rounded-md${busy ? ' cursor-not-allowed opacity-50' : ' cursor-pointer'}`}
+ color="accent"
+ size="sm"
+ onClick={(event) => {
+ event.stopPropagation()
+ if (!busy)
+ openCloneDialog(profile)
+ }}
+ >
+ {t('profiles.clone')}
+ </Chip>
<If cond={!profile.default}>
<Chip
- className="rounded-md"
+ className={`rounded-md${busy ? ' cursor-not-allowed opacity-50' : ' cursor-pointer'}`}
variant="primary"
color="danger"
size="sm"
onClick={(event) => {
event.stopPropagation()
- remove(profile.id)
+ if (!busy)
+ remove(profile.id)
}}
>
{t('profiles.remove')}
@@ -248,6 +303,62 @@ export function ConfigProfile() {
</div>
</PanelState>
{dialogHolder}
+
+ {/* 克隆档案:命名对话框(创建型,accent;可编辑建议名称) */}
+ <AlertDialog
+ isOpen={cloning !== null}
+ onOpenChange={(open) => {
+ if (!open)
+ setCloning(null)
+ }}
+ >
+ <AlertDialog.Backdrop>
+ <AlertDialog.Container>
+ <AlertDialog.Dialog className="sm:max-w-[400px]">
+ <AlertDialog.CloseTrigger />
+ <AlertDialog.Header>
+ <AlertDialog.Icon status="accent" />
+ <AlertDialog.Heading>{t('profiles.clone_dialog_title')}</AlertDialog.Heading>
+ </AlertDialog.Header>
+ <AlertDialog.Body>
+ <p className="text-xs text-muted">
+ {cloning && t('profiles.clone_dialog_desc', { name: cloning.sourceName })}
+ </p>
+ <Input
+ autoFocus
+ variant="secondary"
+ className="h-8 rounded-md w-full my-2"
+ placeholder={t('profiles.clone_name_placeholder')}
+ value={cloneName}
+ onChange={e => setCloneName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter')
+ commitClone()
+ }}
+ />
+ {cloning && (
+ <p className="text-xs text-muted">
+ {t('profiles.clone_default_hint', { name: suggestCloneName(cloning.sourceId) })}
+ </p>
+ )}
+ </AlertDialog.Body>
+ <AlertDialog.Footer>
+ <Button className="rounded-md" variant="tertiary" onPress={() => setCloning(null)}>
+ {t('profiles.clone_cancel')}
+ </Button>
+ <Button
+ className="rounded-md"
+ variant="primary"
+ isDisabled={!cloneName.trim() || busy}
+ onPress={commitClone}
+ >
+ {t('profiles.clone_confirm')}
+ </Button>
+ </AlertDialog.Footer>
+ </AlertDialog.Dialog>
+ </AlertDialog.Container>
+ </AlertDialog.Backdrop>
+ </AlertDialog>
</div>
)
}
diff --git a/src/hooks/use-dsh-profiles.ts b/src/hooks/use-dsh-profiles.ts
index 4ae32d32..7aa35df4 100644
--- a/src/hooks/use-dsh-profiles.ts
+++ b/src/hooks/use-dsh-profiles.ts
@@ -25,7 +25,9 @@ export interface UseDshProfilesResult {
activateProfile: (id: string) => Promise<Profile>
/** 删除档案(默认/使用中的档案会被后端拒绝) */
removeProfile: (id: string) => Promise<void>
- /** 操作进行中标记(新建/切换/删除任一) */
+ /** 克隆档案(全量复制源档案,自动递增或指定名称) */
+ cloneProfile: (sourceId: string, name: string) => Promise<Profile>
+ /** 操作进行中标记(新建/切换/删除/克隆任一) */
busy: boolean
}
@@ -79,6 +81,10 @@ export function useDshProfiles(): UseDshProfilesResult {
mutationFn: (id: string) => invoke<void>('remove_profile', { id }),
onSuccess: invalidate,
})
+ const clone = useMutation({
+ mutationFn: (params: { sourceId: string, name: string }) => invoke<Profile>('clone_profile', params),
+ onSuccess: invalidate,
+ })
return {
profiles: data ?? [],
@@ -98,6 +104,11 @@ export function useDshProfiles(): UseDshProfilesResult {
await remove.mutateAsync(id)
await refetch()
},
- busy: create.isPending || activate.isPending || remove.isPending,
+ cloneProfile: async (sourceId, name) => {
+ const created = await clone.mutateAsync({ sourceId, name })
+ await refetch()
+ return created
+ },
+ busy: create.isPending || activate.isPending || remove.isPending || clone.isPending,
}
}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index edaeec60..ec89ce8e 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -155,6 +155,19 @@
"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",
+ "profiles.clone": "Clone",
+ "profiles.clone_dialog_title": "Clone Profile",
+ "profiles.clone_dialog_desc": "Create a full, independent copy of \"{{name}}\". The cloned profile is separate from the source.",
+ "profiles.clone_name_placeholder": "New profile name",
+ "profiles.clone_default_hint": "Suggested: {{name}} (editable)",
+ "profiles.clone_confirm": "Clone",
+ "profiles.clone_cancel": "Cancel",
+ "profiles.clone_success": "Cloned as \"{{name}}\"",
+ "profiles.clone_success_hint": "The new profile is in the list — switch to it anytime.",
+ "profiles.clone_failed": "Failed to clone profile",
+ "profiles.clone_exists": "A profile named \"{{name}}\" already exists.",
+ "profiles.clone_empty": "Please enter a profile name",
+ "profiles.clone_invalid": "Profile name contains invalid characters",
"backup.manage": "Backup",
"backup.title": "Backups",
"backup.tooltip": "Create and restore profile backups. Backups include profiles, sessions, and settings.",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 93b1cf1d..521efb9c 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -155,6 +155,19 @@
"profiles.remove_confirm_desc": "确定删除档案 {{name}} 吗?将同时删除其插件与设置,此操作不可撤销。",
"profiles.remove_confirm": "删除",
"profiles.remove_failed": "删除档案失败",
+ "profiles.clone": "克隆",
+ "profiles.clone_dialog_title": "克隆档案",
+ "profiles.clone_dialog_desc": "将「{{name}}」全量复制为一个独立档案。新档案与源档案互不影响,克隆后独立使用。",
+ "profiles.clone_name_placeholder": "新档案名称",
+ "profiles.clone_default_hint": "建议名称:{{name}}(可修改)",
+ "profiles.clone_confirm": "克隆",
+ "profiles.clone_cancel": "取消",
+ "profiles.clone_success": "已克隆为「{{name}}」",
+ "profiles.clone_success_hint": "新档案已加入列表,可切换使用",
+ "profiles.clone_failed": "克隆档案失败",
+ "profiles.clone_exists": "档案名称「{{name}}」已存在",
+ "profiles.clone_empty": "请输入档案名称",
+ "profiles.clone_invalid": "档案名称包含无效字符",
"backup.manage": "备份",
"backup.title": "备份",
"backup.tooltip": "创建和还原档案备份。备份包含档案、会话和设置。",
diff --git a/test/clone-profile.test.ts b/test/clone-profile.test.ts
new file mode 100644
index 00000000..e008028a
--- /dev/null
+++ b/test/clone-profile.test.ts
@@ -0,0 +1,125 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+
+/**
+ * Frontend contract test for profile cloning (TDD RED stage).
+ *
+ * Reads source files via readFileSync and asserts structural contracts,
+ * mirroring the close-action.test.ts pattern. The frontend is not mounted
+ * in unit tests — these assertions verify the wiring exists.
+ */
+describe('cloneProfile mutation shape', () => {
+ it('invokes clone_profile with sourceId + name and invalidates queries', () => {
+ const source = readFileSync(new URL('../src/hooks/use-dsh-profiles.ts', import.meta.url), 'utf8')
+
+ expect(source).toContain('clone_profile')
+ expect(source).toContain('sourceId')
+ expect(source).toContain('name')
+ expect(source).toMatch(/invoke\s*<\s*Profile\s*>\s*\(\s*['"]clone_profile['"]/)
+ expect(source).toMatch(/onSuccess:\s*invalidate/)
+ })
+
+ it('exposes cloneProfile in the return type and object', () => {
+ const source = readFileSync(new URL('../src/hooks/use-dsh-profiles.ts', import.meta.url), 'utf8')
+
+ expect(source).toMatch(/cloneProfile\s*[:(]/)
+ expect(source).toMatch(/UseDshProfilesResult/)
+ expect(source).toMatch(/cloneProfile\s*:\s*\(sourceId\s*:\s*string,\s*name\s*:\s*string\)\s*=>\s*Promise\s*<\s*Profile\s*>/)
+ })
+
+ it('extends busy to include clone.isPending', () => {
+ const source = readFileSync(new URL('../src/hooks/use-dsh-profiles.ts', import.meta.url), 'utf8')
+
+ expect(source).toMatch(/clone\.isPending/)
+ expect(source).toMatch(/busy:\s*create\.isPending\s*\|\|\s*activate\.isPending\s*\|\|\s*remove\.isPending\s*\|\|\s*clone\.isPending/)
+ })
+})
+
+describe('clone Chip + naming dialog in ConfigProfile', () => {
+ it('renders a Clone Chip on non-default rows with profiles.clone label', () => {
+ const source = readFileSync(new URL('../src/components/config-profile.tsx', import.meta.url), 'utf8')
+
+ expect(source).toMatch(/profiles\.clone['"]/)
+ expect(source).toMatch(/cond=\{!profile\.default\}/)
+ // Chip positioned before delete Chip
+ const cloneIdx = source.indexOf('profiles.clone')
+ const removeIdx = source.indexOf('profiles.remove')
+ expect(cloneIdx).toBeGreaterThan(-1)
+ expect(removeIdx).toBeGreaterThan(-1)
+ expect(cloneIdx).toBeLessThan(removeIdx)
+ })
+
+ it('disables the Clone Chip while busy', () => {
+ const source = readFileSync(new URL('../src/components/config-profile.tsx', import.meta.url), 'utf8')
+
+ expect(source).toMatch(/cursor-not-allowed opacity-50/)
+ })
+
+ it('provides a naming dialog with description, editable Input, and confirm button', () => {
+ const source = readFileSync(new URL('../src/components/config-profile.tsx', import.meta.url), 'utf8')
+
+ expect(source).toMatch(/profiles\.clone_dialog_desc/)
+ expect(source).toMatch(/profiles\.clone_confirm/)
+ expect(source).toMatch(/profiles\.clone_cancel/)
+ expect(source).toMatch(/<Input/)
+ expect(source).toMatch(/autoFocus/)
+ })
+
+ it('shows accent success toast with NO restart action', () => {
+ const source = readFileSync(new URL('../src/components/config-profile.tsx', import.meta.url), 'utf8')
+
+ expect(source).toMatch(/profiles\.clone_success/)
+ expect(source).toMatch(/variant:\s*['"]accent['"]/)
+ // clone success branch must NOT include a restart action (distinct from activate)
+ const cloneSuccessIdx = source.indexOf('profiles.clone_success')
+ expect(cloneSuccessIdx).toBeGreaterThan(-1)
+ const afterSuccess = source.slice(cloneSuccessIdx, cloneSuccessIdx + 500)
+ expect(afterSuccess).not.toMatch(/actionProps/)
+ expect(afterSuccess).not.toMatch(/restart/)
+ })
+
+ it('keeps dialog open on failure with an error toast', () => {
+ const source = readFileSync(new URL('../src/components/config-profile.tsx', import.meta.url), 'utf8')
+
+ expect(source).toMatch(/profiles\.clone_failed/)
+ })
+})
+
+describe('i18n parity', () => {
+ const keys = [
+ 'profiles.clone',
+ 'profiles.clone_dialog_title',
+ 'profiles.clone_dialog_desc',
+ 'profiles.clone_name_placeholder',
+ 'profiles.clone_default_hint',
+ 'profiles.clone_confirm',
+ 'profiles.clone_cancel',
+ 'profiles.clone_success',
+ 'profiles.clone_success_hint',
+ 'profiles.clone_failed',
+ 'profiles.clone_exists',
+ 'profiles.clone_empty',
+ 'profiles.clone_invalid',
+ ]
+
+ for (const locale of ['zh-CN', 'en-US']) {
+ it(`includes all profiles.clone* keys in ${locale}`, () => {
+ const content = readFileSync(new URL(`../src/i18n/locales/${locale}.json`, import.meta.url), 'utf8')
+ for (const key of keys) {
+ expect(content).toContain(`"${key}"`)
+ }
+ })
+ }
+})
+
+describe('shell conventions', () => {
+ it('does not use useCallback / useMemo / hardcoded user-facing strings', () => {
+ const source = readFileSync(new URL('../src/components/config-profile.tsx', import.meta.url), 'utf8')
+
+ expect(source).not.toContain('useCallback')
+ expect(source).not.toContain('useMemo')
+ // clone-related labels must come from t(), not hardcoded
+ expect(source).not.toMatch(/>\s*Clone\s*</)
+ expect(source).not.toMatch(/>\s*克隆\s*</)
+ })
+})