A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
fix(skills): fall back to a directory junction when Windows refuses symlinks
Jason27b0a3875ed7
diff --git a/src-tauri/src/services/skill/sync.rs b/src-tauri/src/services/skill/sync.rsindex 4224a894b..8edcb8e9e 100644--- a/src-tauri/src/services/skill/sync.rs+++ b/src-tauri/src/services/skill/sync.rs@@ -8,7 +8,10 @@ impl SkillService {/// 创建符号链接(跨平台)////// - Unix: 使用 std::os::unix::fs::symlink- /// - Windows: 使用 std::os::windows::fs::symlink_dir+ /// - Windows: 先用 std::os::windows::fs::symlink_dir;没开开发者模式、也不是管理员时+ /// 它报缺权限,这时退回目录联接(junction),普通用户也能建。std 把 junction 也当+ /// 符号链接(`is_symlink` 为真、`read_link` 读得出目标、`remove_dir` 只删链接),+ /// 所以检测、校验和删除不用另写分支。////// 命令层用 `to_string()` 把错误交给前端,只显示最外层 context,所以系统错误/// (如 Windows 的 `os error 5`)必须写进消息本身,否则用户只看到「失败」。@@ -16,7 +19,26 @@ impl SkillService {#[cfg(unix)]let result = std::os::unix::fs::symlink(src, dest);#[cfg(windows)]- let result = std::os::windows::fs::symlink_dir(src, dest);+ let result = match std::os::windows::fs::symlink_dir(src, dest) {+ Ok(()) => Ok(()),+ // 1314 = ERROR_PRIVILEGE_NOT_HELD:缺建符号链接的权限。其他错误(目标已存在、+ // WSL 共享拒绝等)junction 一样建不成,原样报出。+ Err(error) if error.raw_os_error() != Some(1314) => Err(error),+ Err(error) => match Self::create_junction(src, dest) {+ Ok(()) => {+ log::info!(+ "目录符号链接创建失败({error}),已改用目录联接: {} -> {}",+ src.display(),+ dest.display()+ );+ Ok(())+ }+ Err(junction_error) => {+ log::warn!("目录联接也创建失败: {junction_error}");+ Err(error)+ }+ },+ };result.map_err(|error| {anyhow!("创建符号链接失败: {} -> {}: {error}",@@ -26,6 +48,49 @@ impl SkillService {})}+ /// 用 `mklink /J` 建目录联接。junction 只认绝对路径,目标先转成绝对路径。+ ///+ /// 路径里有来自技能仓库的目录名,而 `cmd` 会解释 `&`、`|` 等元字符,`Command::arg`+ /// 的转义防不住它,所以两个路径都自己加双引号、经 `raw_arg` 原样交给 cmd:引号里的+ /// 元字符按字面处理;`/V:OFF` 关掉 `!` 延迟展开,`/D` 不跑注册表里的 AutoRun。引号里+ /// 仍会展开的 `%` 直接拒绝(Windows 路径本来就不能含 `"`)。+ #[cfg(windows)]+ pub(super) fn create_junction(src: &Path, dest: &Path) -> std::io::Result<()> {+ use std::os::windows::process::CommandExt;+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;++ fn quoted(path: &Path) -> std::io::Result<String> {+ match path.to_str() {+ Some(text) if !text.contains(['"', '%']) => Ok(format!("\"{text}\"")),+ _ => Err(std::io::Error::new(+ std::io::ErrorKind::InvalidInput,+ format!("路径不能交给 mklink: {}", path.display()),+ )),+ }+ }++ let link = std::path::absolute(dest)?;+ let target = std::path::absolute(src)?;+ let output = std::process::Command::new("cmd")+ .raw_arg(format!(+ "/D /V:OFF /C mklink /J {} {}",+ quoted(&link)?,+ quoted(&target)?+ ))+ .creation_flags(CREATE_NO_WINDOW)+ .stdin(std::process::Stdio::null())+ .output()?;+ if output.status.success() {+ Ok(())+ } else {+ Err(std::io::Error::other(format!(+ "mklink /J 失败({}): {}",+ output.status,+ String::from_utf8_lossy(&output.stderr).trim()+ )))+ }+ }+/// 检查路径是否为符号链接pub(super) fn is_symlink(path: &Path) -> bool {path.symlink_metadata()diff --git a/src-tauri/src/services/skill/tests.rs b/src-tauri/src/services/skill/tests.rsindex 165ad28ea..91281ac6e 100644--- a/src-tauri/src/services/skill/tests.rs+++ b/src-tauri/src/services/skill/tests.rs@@ -4810,3 +4810,49 @@ fn resync_all_apps_leaves_openclaw_skills_dir_alone() {SkillService::sync_to_app(&db, &AppType::OpenClaw).expect("no-op sync");assert!(own_skill.exists());}++/// 没开开发者模式时 `create_symlink` 退回目录联接;检测、校验和删除都按 std 把 junction+/// 当符号链接的语义写,这里直接建一个 junction 锁住这些前提。+#[cfg(windows)]+#[test]+fn junction_fallback_is_treated_as_a_managed_link() {+ let temp = tempdir().expect("tempdir");+ let ssot_dir = temp.path().join("ssot");+ let source = ssot_dir.join("demo");+ write_skill(&source, "demo");+ let app_dir = temp.path().join("app-skills");+ fs::create_dir_all(&app_dir).unwrap();+ let native = app_dir.join("demo");++ SkillService::create_junction(&source, &native).expect("create junction");++ assert!(SkillService::is_symlink(&native));+ assert!(native.join("SKILL.md").is_file());+ assert!(SkillService::is_symlink_to_ssot(&native, &ssot_dir));+ assert!(matches!(+ SkillService::inspect_pi_skill_destination(&source, &native, "demo", &AppType::Pi),+ Ok(Some(PiSkillDeployment::Symlink { .. }))+ ));++ SkillService::remove_path(&native).expect("remove junction");+ assert!(!native.exists() && !SkillService::is_symlink(&native));+ assert!(+ source.join("SKILL.md").is_file(),+ "removing the junction must not touch the managed copy"+ );++ // 目录名来自技能仓库:cmd 元字符必须按字面落成路径,不能拆出第二条命令;`%` 直接拒绝。+ let probe = "ccswitch-junction-injection-probe";+ let odd_name = format!("a&md {probe}&(1)^");+ let odd_source = ssot_dir.join(&odd_name);+ write_skill(&odd_source, "odd");+ let odd_native = app_dir.join(&odd_name);+ SkillService::create_junction(&odd_source, &odd_native).expect("metacharacters stay literal");+ assert!(SkillService::is_symlink(&odd_native));+ assert!(odd_native.join("SKILL.md").is_file());+ assert!(!std::env::current_dir().unwrap().join(probe).exists());++ let percent_source = ssot_dir.join("%PATH%");+ write_skill(&percent_source, "percent");+ assert!(SkillService::create_junction(&percent_source, &app_dir.join("%PATH%")).is_err());+}diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.jsonindex df1f49532..b5e889652 100644--- a/src/i18n/locales/de.json+++ b/src/i18n/locales/de.json@@ -3726,7 +3726,7 @@"syncTitle": "Wie Skills zu den Apps gelangen","syncAuto": "Automatisch: zuerst Symlink, bei Fehlschlag kopieren (empfohlen)","syncSymlink": "Nur Symlink",- "syncSymlinkDesc": "Erfordert den Entwicklermodus unter Windows",+ "syncSymlinkDesc": "Unter Windows ohne Entwicklermodus wird stattdessen eine Verzeichnisverbindung (Junction) verwendet, ohne Administratorrechte","syncCopy": "Nur kopieren","syncCopyDesc": "Belegt mehr Speicherplatz; wird nach jedem Update erneut kopiert","moveHint": "Beim Umstellen werden {{count}} Skills an den neuen Ort verschoben."diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.jsonindex e20d568b9..00b6495c8 100644--- a/src/i18n/locales/en.json+++ b/src/i18n/locales/en.json@@ -3726,7 +3726,7 @@"syncTitle": "How Skills reach each app","syncAuto": "Automatic: symlink first, copy if that fails (recommended)","syncSymlink": "Symlink only",- "syncSymlinkDesc": "Requires Developer Mode on Windows",+ "syncSymlinkDesc": "On Windows without Developer Mode, a directory junction is used instead (no admin rights needed)","syncCopy": "Copy only","syncCopyDesc": "Uses more disk space; copied again after each update","moveHint": "Switching moves {{count}} Skills to the new location."diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.jsonindex 9660fd567..dbbb54598 100644--- a/src/i18n/locales/ja.json+++ b/src/i18n/locales/ja.json@@ -3726,7 +3726,7 @@"syncTitle": "各アプリへの同期方式","syncAuto": "自動:シンボリックリンクを優先し、失敗したらコピー(推奨)","syncSymlink": "シンボリックリンクのみ",- "syncSymlinkDesc": "Windows では開発者モードが必要です",+ "syncSymlinkDesc": "Windows で開発者モードがオフのときはディレクトリ ジャンクション(junction)を使います(管理者権限は不要)","syncCopy": "コピーのみ","syncCopyDesc": "ディスク容量を多く使い、更新のたびにコピーし直します","moveHint": "場所を切り替えると {{count}} 個の Skill を移動します。"diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.jsonindex 7edf327e7..5159f92d7 100644--- a/src/i18n/locales/ko.json+++ b/src/i18n/locales/ko.json@@ -3726,7 +3726,7 @@"syncTitle": "앱별 스킬 동기화 방식","syncAuto": "자동: 먼저 심볼릭 링크를 연결하고, 실패하면 복사합니다(권장)","syncSymlink": "심볼릭 링크만",- "syncSymlinkDesc": "Windows에서는 개발자 모드가 필요합니다.",+ "syncSymlinkDesc": "Windows에서 개발자 모드가 꺼져 있으면 대신 디렉터리 정션(junction)을 사용합니다(관리자 권한 불필요).","syncCopy": "복사만 사용","syncCopyDesc": "더 많은 디스크 공간을 사용합니다. 업데이트할 때마다 다시 복사됨","moveHint": "전환하면 스킬 {{count}}개가 새 위치로 이동됩니다."diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.jsonindex 922a49073..ec5d13e13 100644--- a/src/i18n/locales/ru.json+++ b/src/i18n/locales/ru.json@@ -3724,7 +3724,7 @@"syncTitle": "Как навыки попадают в каждое приложение","syncAuto": "Автоматически: сначала символическая ссылка, при неудаче копирование (рекомендуется)","syncSymlink": "Только символическая ссылка",- "syncSymlinkDesc": "В Windows требуется режим разработчика",+ "syncSymlinkDesc": "В Windows без режима разработчика вместо неё используется соединение каталогов (junction), права администратора не нужны","syncCopy": "Только копирование","syncCopyDesc": "Занимает больше места на диске; копируется заново после каждого обновления","moveHint": "При переключении навыки ({{count}}) будут перемещены в новое место."diff --git a/src/i18n/locales/tr.json b/src/i18n/locales/tr.jsonindex 175c90ee3..4116c07e8 100644--- a/src/i18n/locales/tr.json+++ b/src/i18n/locales/tr.json@@ -3655,7 +3655,7 @@"syncTitle": "Beceriler her uygulamaya nasıl ulaşır?","syncAuto": "Otomatik: önce sembolik bağlantı, başarısız olursa kopyala (önerilir)","syncSymlink": "Yalnızca sembolik bağlantı",- "syncSymlinkDesc": "Windows'de Geliştirici Modu gerektirir",+ "syncSymlinkDesc": "Geliştirici Modu kapalı Windows'ta bunun yerine dizin bağlantısı (junction) kullanılır; yönetici izni gerekmez","syncCopy": "Yalnızca kopyala","syncCopyDesc": "Daha fazla disk alanı kullanır; her güncellemeden sonra tekrar kopyalandı","moveHint": "Geçiş, {{count}} Becerilerini yeni konuma taşır."diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.jsonindex 35efbc720..8e77fab19 100644--- a/src/i18n/locales/zh-TW.json+++ b/src/i18n/locales/zh-TW.json@@ -3726,7 +3726,7 @@"syncTitle": "同步到各應用的方式","syncAuto": "自動:優先用軟連結,失敗時複製(推薦)","syncSymlink": "只用軟連結",- "syncSymlinkDesc": "Windows 需要開啟開發人員模式",+ "syncSymlinkDesc": "Windows 未開啟開發人員模式時改用目錄連接(junction),不需要系統管理員權限","syncCopy": "只用複製","syncCopyDesc": "佔用更多空間,更新後會重新複製","moveHint": "切換位置會把 {{count}} 個 Skill 移動過去。"diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.jsonindex 7530d573a..d5a012655 100644--- a/src/i18n/locales/zh.json+++ b/src/i18n/locales/zh.json@@ -3726,7 +3726,7 @@"syncTitle": "同步到各应用的方式","syncAuto": "自动:优先用软链接,失败时复制(推荐)","syncSymlink": "只用软链接",- "syncSymlinkDesc": "Windows 需要开启开发者模式",+ "syncSymlinkDesc": "Windows 没开开发者模式时改用目录联接(junction),无需管理员权限","syncCopy": "只用复制","syncCopyDesc": "占用更多空间,更新后会重新复制","moveHint": "切换位置会把 {{count}} 个 Skill 移动过去。"