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
perf(skills): cut discovery traffic and stalls, resolve HEAD branches (#10061)
Allen Xudf5069cf023a
diff --git a/src-tauri/src/commands/skill.rs b/src-tauri/src/commands/skill.rsindex 756e7997f..b3ed789d0 100644--- a/src-tauri/src/commands/skill.rs+++ b/src-tauri/src/commands/skill.rs@@ -153,17 +153,16 @@ pub async fn import_skills_from_apps(/// 发现可安装的 Skills(从仓库获取),并逐仓库报告没读到的仓库///-/// `force_refresh` 为 true(手动刷新)时绕过按仓库的发现缓存。+/// `force_refresh` 为 true(手动刷新)时绕过按仓库的发现缓存(仍用远端 commit SHA 判重)。#[tauri::command]pub async fn discover_available_skills(force_refresh: Option<bool>,service: State<'_, SkillServiceState>,app_state: State<'_, AppState>,) -> Result<SkillDiscoveryResult, String> {- let repos = app_state.db.get_skill_repos()?;service.0- .discover_available_report(repos, force_refresh.unwrap_or(false))+ .discover_available_for_db(&app_state.db, force_refresh.unwrap_or(false)).await.map_err(|e| e.to_string())}@@ -184,7 +183,7 @@ pub async fn discover_repo_skills(else {return Ok(SkillDiscoveryResult::default());};- Ok(service.0.discover_repo(&repo).await)+ Ok(service.0.discover_repo_for_db(&app_state.db, &repo).await)}/// 检查 Skills 更新,并逐仓库报告没读到的仓库diff --git a/src-tauri/src/database/dao/skills.rs b/src-tauri/src/database/dao/skills.rsindex 746ac5249..654f87c94 100644--- a/src-tauri/src/database/dao/skills.rs+++ b/src-tauri/src/database/dao/skills.rs@@ -260,6 +260,25 @@ impl Database {Ok(())}+ /// 当仓库配置分支仍为发现启动时的哨兵值(空串或 HEAD)且同主机/仍启用时,回写解析出的真实分支。+ pub fn update_skill_repo_branch(+ &self,+ host: &str,+ owner: &str,+ name: &str,+ expected_branch: &str,+ resolved_branch: &str,+ ) -> Result<bool, AppError> {+ let conn = lock_conn!(self.conn);+ let affected = conn+ .execute(+ "UPDATE skill_repos SET branch = ?1 WHERE host = ?2 AND owner = ?3 AND name = ?4 AND branch = ?5 AND enabled = 1",+ params![resolved_branch, host, owner, name, expected_branch],+ )+ .map_err(|e| AppError::Database(e.to_string()))?;+ Ok(affected > 0)+ }+/// 删除 Skill 仓库pub fn delete_skill_repo(&self, owner: &str, name: &str) -> Result<(), AppError> {let conn = lock_conn!(self.conn);diff --git a/src-tauri/src/services/skill.rs b/src-tauri/src/services/skill.rsindex 58ae46256..8b8292f41 100644--- a/src-tauri/src/services/skill.rs+++ b/src-tauri/src/services/skill.rs@@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};use std::collections::{HashMap, HashSet};use std::fs;use std::path::{Component, Path, PathBuf};-use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::{Arc, Mutex, OnceLock, RwLock, RwLockReadGuard, RwLockWriteGuard};use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};use tokio::time::timeout;@@ -616,13 +616,37 @@ struct LocalSkillMetadataCandidate {new_hash: String,}+/// 发现缓存的单仓记录:进程内带 TTL,落盘后跨重启按 commit SHA 复用。+#[derive(Debug, Clone, Serialize, Deserialize)]+pub(super) struct CachedRepoDiscovery {+ #[serde(skip)]+ pub(super) fetched_at: Option<Instant>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub(super) commit_sha: Option<String>,+ pub(super) resolved_branch: String,+ pub(super) skills: Vec<DiscoverableSkill>,+}++/// 通过 Git Smart HTTP `info/refs` 探出的真实分支与最新 commit。+#[derive(Debug, Clone, PartialEq, Eq)]+pub(super) struct ProbedGitRef {+ pub(super) branch: String,+ pub(super) commit_sha: String,+ /// 分支名是否由远端 `symref=HEAD:refs/heads/<branch>` 明确给出(非 main/master 猜测)。+ pub(super) from_head_symref: bool,+}+pub struct SkillService {#[cfg(test)]repo_fixture: Option<PathBuf>,- /// 发现结果按仓库缓存(键是 owner/name/branch),只存读成功的仓库。- /// 发现要把每个仓库的归档整包下下来,添加、启用仓库或导入后的重拉不该把- /// 没变的仓库再下一遍;手动刷新会绕过它(`force_refresh`)。- discovery_cache: Mutex<HashMap<RepoCacheKey, (Instant, Vec<DiscoverableSkill>)>>,+ /// 发现结果按仓库缓存,只存读成功的仓库;跨重启持久化在本地缓存文件,+ /// 手动刷新时先比对远端分支 commit SHA,未变化直接跳过归档下载。+ discovery_cache: Mutex<HashMap<RepoCacheKey, CachedRepoDiscovery>>,+ /// 串行化发现缓存落盘,确保旧快照无法覆盖后发生的写盘或令牌清理。+ /// 锁序严格为 `discovery_disk_lock -> discovery_cache`,且永不跨 `.await` 持有。+ discovery_disk_lock: Mutex<()>,+ /// 本地发现缓存文件是否已载入内存(每进程懒加载一次)。+ discovery_cache_loaded: AtomicBool,/// 主机 → 平台的探测结果,进程内有效。只记探明的,见 `resolve_platform`。platform_cache: Mutex<HashMap<String, RepoPlatform>>,/// 访问令牌的代次,任何主机的令牌增删都加一。下载开始时记下它,探测结果回写缓存前@@ -632,11 +656,25 @@ pub struct SkillService {repo_tokens: Arc<RepoTokenStore>,}-/// host / owner / name / branch(branch 是配置值,不是解析后的分支)+/// host / owner / name / branch(branch 是配置值,哨兵 HEAD/空串会归一为解析后的真实分支)type RepoCacheKey = (String, String, String, String);/// 发现缓存的有效期:GitHub 归档本身也有几分钟的 CDN 缓存,再短意义不大const DISCOVERY_CACHE_TTL: Duration = Duration::from_secs(10 * 60);+/// 发现并发上限:避免启用多个大仓库时瞬间打满带宽与磁盘/CPU+const DISCOVERY_MAX_CONCURRENCY: usize = 3;+/// Git Smart HTTP `info/refs` 最多读取字节数(分支排在 pull/tags 前面,正常几 KB 即停)+const GIT_INFO_REFS_MAX_BYTES: usize = 512 * 1024;+/// 发现阶段单个 `SKILL.md` 的读取上限:frontmatter 在文件开头,限制体积防止压缩炸弹占满内存+const MAX_SKILL_MD_BYTES: u64 = 256 * 1024;+/// 单仓库发现扫描的累计解压预算(所有 SKILL.md 与 symlink 目标共用)+const MAX_DISCOVERY_SCAN_BYTES: u64 = 32 * 1024 * 1024;+/// 单仓库发现扫描保留的元数据内存上限(名称 + 描述累计字节)+const MAX_DISCOVERY_METADATA_BYTES: usize = 8 * 1024 * 1024;+/// 本地发现缓存文件名(仅存本机,不进数据库和云同步)+const DISCOVERY_CACHE_FILENAME: &str = "skill-discovery-cache.json";+/// 扫描语义变化时使旧 SHA 缓存失效,避免沿用曾漏掉符号链接的技能列表。+const DISCOVERY_SCAN_VERSION: u32 = 1;impl Default for SkillService {fn default() -> Self {@@ -650,6 +688,8 @@ impl SkillService {#[cfg(test)]repo_fixture: None,discovery_cache: Mutex::new(HashMap::new()),+ discovery_disk_lock: Mutex::new(()),+ discovery_cache_loaded: AtomicBool::new(false),platform_cache: Mutex::new(HashMap::new()),credential_epoch: AtomicU64::new(0),repo_tokens: Arc::new(RepoTokenStore::system()),diff --git a/src-tauri/src/services/skill/discovery.rs b/src-tauri/src/services/skill/discovery.rsindex a6a333634..69c63e69d 100644--- a/src-tauri/src/services/skill/discovery.rs+++ b/src-tauri/src/services/skill/discovery.rs@@ -1,9 +1,24 @@//! 发现功能:扫描仓库里的技能并解析元数据。use super::*;+use std::ffi::OsStr;++#[derive(Debug, Clone, Serialize, Deserialize)]+struct DiskDiscoveryCacheEntry {+ #[serde(default)]+ scan_version: u32,+ host: String,+ owner: String,+ name: String,+ branch: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ commit_sha: Option<String>,+ resolved_branch: String,+ skills: Vec<DiscoverableSkill>,+}impl SkillService {- // ========== 发现功能(保留原有逻辑)==========+ // ========== 发现功能 ==========/// 列出所有可发现的技能(从仓库获取)pub async fn discover_available(@@ -20,23 +35,56 @@ impl SkillService {&self,repos: Vec<SkillRepo>,force_refresh: bool,+ ) -> Result<SkillDiscoveryResult> {+ self.discover_available_inner(repos, force_refresh, None)+ .await+ }++ /// 从数据库读取仓库列表执行发现,并把哨兵分支(空串 / `HEAD`)解析出的真实分支回写数据库。+ pub(crate) async fn discover_available_for_db(+ &self,+ db: &Database,+ force_refresh: bool,+ ) -> Result<SkillDiscoveryResult> {+ let repos = db.get_skill_repos()?;+ self.discover_available_inner(repos, force_refresh, Some(db))+ .await+ }++ async fn discover_available_inner(+ &self,+ repos: Vec<SkillRepo>,+ force_refresh: bool,+ db: Option<&Database>,) -> Result<SkillDiscoveryResult> {let mut skills = Vec::new();let mut failures = Vec::new();// 仅使用启用的仓库let enabled_repos: Vec<SkillRepo> = repos.into_iter().filter(|repo| repo.enabled).collect();+ let semaphore = Arc::new(tokio::sync::Semaphore::new(DISCOVERY_MAX_CONCURRENCY));- let fetch_tasks = enabled_repos- .iter()- .map(|repo| self.fetch_repo_skills_cached(repo, force_refresh));+ let fetch_tasks = enabled_repos.iter().map(|repo| {+ let semaphore = Arc::clone(&semaphore);+ async move {+ let _permit = semaphore.acquire_owned().await.ok();+ self.fetch_repo_skills_cached(repo, force_refresh).await+ }+ });- let results: Vec<Result<Vec<DiscoverableSkill>>> =+ let results: Vec<Result<(Vec<DiscoverableSkill>, String, bool)>> =futures::future::join_all(fetch_tasks).await;for (repo, result) in enabled_repos.into_iter().zip(results) {match result {- Ok(repo_skills) => skills.extend(repo_skills),+ Ok((repo_skills, resolved_branch, from_head_symref)) => {+ if let Some(db) = db {+ if from_head_symref {+ Self::persist_resolved_branch(db, &repo, &resolved_branch);+ }+ }+ skills.extend(repo_skills);+ }Err(e) => {log::warn!("获取仓库 {}/{} 技能失败: {}", repo.owner, repo.name, e);failures.push(Self::repo_failure(&repo, e.to_string()));@@ -53,11 +101,32 @@ impl SkillService {/// 只发现一个仓库(添加、重新启用仓库时用),不碰其它仓库。pub async fn discover_repo(&self, repo: &SkillRepo) -> SkillDiscoveryResult {+ self.discover_repo_inner(repo, None).await+ }++ pub(crate) async fn discover_repo_for_db(+ &self,+ db: &Database,+ repo: &SkillRepo,+ ) -> SkillDiscoveryResult {+ self.discover_repo_inner(repo, Some(db)).await+ }++ async fn discover_repo_inner(+ &self,+ repo: &SkillRepo,+ db: Option<&Database>,+ ) -> SkillDiscoveryResult {if !repo.enabled {return SkillDiscoveryResult::default();}match self.fetch_repo_skills_cached(repo, false).await {- Ok(mut skills) => {+ Ok((mut skills, resolved_branch, from_head_symref)) => {+ if let Some(db) = db {+ if from_head_symref {+ Self::persist_resolved_branch(db, repo, &resolved_branch);+ }+ }Self::deduplicate_discoverable_skills(&mut skills);skills.sort_by_key(|skill| skill.name.to_lowercase());SkillDiscoveryResult {@@ -75,6 +144,28 @@ impl SkillService {}}+ pub(super) fn persist_resolved_branch(db: &Database, repo: &SkillRepo, resolved_branch: &str) {+ if Self::is_default_branch_sentinel(&repo.branch)+ && !Self::is_default_branch_sentinel(resolved_branch)+ {+ if let Err(e) = db.update_skill_repo_branch(+ &repo.host,+ &repo.owner,+ &repo.name,+ &repo.branch,+ resolved_branch,+ ) {+ log::warn!(+ "回写仓库 {}/{} 真实分支 {} 失败: {}",+ repo.owner,+ repo.name,+ resolved_branch,+ e+ );+ }+ }+ }+pub(super) fn discovery_cache_key(repo: &SkillRepo) -> RepoCacheKey {(repo.host.clone(),@@ -84,54 +175,612 @@ impl SkillService {)}- /// 先查缓存,过期或 `force_refresh` 时再下载;下载成功才写回缓存。+ pub(super) fn discovery_cache_path() -> PathBuf {+ get_app_config_dir().join(DISCOVERY_CACHE_FILENAME)+ }++ /// 懒加载本地发现缓存文件(损坏或缺失时忽略)。+ /// 使用 `discovery_disk_lock` 做双重检查锁定,保持 `discovery_disk_lock -> discovery_cache`+ /// 锁序,避免并发加载或 `forget_platform` 删令牌时看到未载完的空缓存。+ pub(super) fn ensure_discovery_cache_loaded(&self) {+ if self.discovery_cache_loaded.load(Ordering::Acquire) {+ return;+ }+ let _disk_guard = self.discovery_disk_lock.lock_recover();+ if self.discovery_cache_loaded.load(Ordering::Acquire) {+ return;+ }+ let path = Self::discovery_cache_path();+ if let Ok(raw) = fs::read_to_string(&path) {+ match serde_json::from_str::<Vec<DiskDiscoveryCacheEntry>>(&raw) {+ Ok(entries) => {+ let mut cache = self.discovery_cache.lock_recover();+ for entry in entries {+ let key = (entry.host, entry.owner, entry.name, entry.branch);+ cache.entry(key).or_insert(CachedRepoDiscovery {+ fetched_at: None,+ commit_sha: if entry.scan_version == DISCOVERY_SCAN_VERSION {+ entry.commit_sha+ } else {+ None+ },+ resolved_branch: entry.resolved_branch,+ skills: entry.skills,+ });+ }+ }+ Err(_) => {+ log::warn!("忽略损坏的技能发现缓存: {}", path.display());+ }+ }+ }+ self.discovery_cache_loaded.store(true, Ordering::Release);+ }++ /// 在串行落盘锁内读取内存最新快照并写入磁盘,确保旧扫描不会覆盖后发生的清理或更新。+ pub(super) fn persist_discovery_cache(&self) {+ let _disk_guard = self.discovery_disk_lock.lock_recover();+ let snapshot = self.discovery_cache.lock_recover().clone();+ Self::save_discovery_cache_to_disk(&snapshot);+ }++ pub(super) fn save_discovery_cache_to_disk(cache: &HashMap<RepoCacheKey, CachedRepoDiscovery>) {+ let entries: Vec<DiskDiscoveryCacheEntry> = cache+ .iter()+ .map(+ |((host, owner, name, branch), value)| DiskDiscoveryCacheEntry {+ scan_version: DISCOVERY_SCAN_VERSION,+ host: host.clone(),+ owner: owner.clone(),+ name: name.clone(),+ branch: branch.clone(),+ commit_sha: value.commit_sha.clone(),+ resolved_branch: value.resolved_branch.clone(),+ skills: value.skills.clone(),+ },+ )+ .collect();+ let Ok(bytes) = serde_json::to_vec(&entries) else {+ return;+ };+ let path = Self::discovery_cache_path();+ if let Err(e) = crate::config::atomic_write_private(&path, &bytes) {+ log::warn!("保存技能发现缓存失败 ({}): {}", path.display(), e);+ }+ }++ /// 先查缓存;需要刷新时先通过轻量 `info/refs` 比对 commit SHA,未变更直接跳过下载。///+ /// 返回 `(skills, resolved_branch, from_head_symref)`。/// 缓存时间记的是开始下载的时刻:前端取消请求停不掉这里的下载,较早开始、/// 较晚结束的旧下载不能覆盖之后(比如强制刷新)写入的结果。pub(super) async fn fetch_repo_skills_cached(&self,repo: &SkillRepo,force_refresh: bool,- ) -> Result<Vec<DiscoverableSkill>> {+ ) -> Result<(Vec<DiscoverableSkill>, String, bool)> {+ #[cfg(test)]+ let use_disk_cache = self.repo_fixture.is_none();+ #[cfg(not(test))]+ let use_disk_cache = true;++ if use_disk_cache {+ self.ensure_discovery_cache_loaded();+ }+let key = Self::discovery_cache_key(repo);if !force_refresh {let cache = self.discovery_cache.lock_recover();- if let Some((fetched_at, skills)) = cache.get(&key) {- if fetched_at.elapsed() < DISCOVERY_CACHE_TTL {- return Ok(skills.clone());+ if let Some(entry) = cache.get(&key) {+ if entry+ .fetched_at+ .is_some_and(|fetched_at| fetched_at.elapsed() < DISCOVERY_CACHE_TTL)+ {+ return Ok((entry.skills.clone(), entry.resolved_branch.clone(), false));}}}let started_at = Instant::now();- let skills = self.fetch_repo_skills(repo).await?;- let mut cache = self.discovery_cache.lock_recover();- if cache- .get(&key)- .is_none_or(|(fetched_at, _)| *fetched_at <= started_at)- {- cache.insert(key, (started_at, skills.clone()));+ let epoch = self.credential_epoch.load(Ordering::SeqCst);++ #[cfg(test)]+ if let Some(fixture) = &self.repo_fixture {+ Self::validate_repo(repo)?;+ let mut skills = Vec::new();+ let resolved_branch = if Self::is_default_branch_sentinel(&repo.branch) {+ "main".to_string()+ } else {+ repo.branch.clone()+ };+ let mut resolved_repo = repo.clone();+ resolved_repo.branch = resolved_branch.clone();+ self.scan_dir_recursive(fixture, fixture, &resolved_repo, &mut skills)?;+ Self::keep_one_per_install_name(&mut skills);+ self.store_discovery_cache(+ repo,+ started_at,+ epoch,+ None,+ resolved_branch.clone(),+ skills.clone(),+ false,+ false,+ );+ return Ok((skills, resolved_branch, false));}- Ok(skills)++ Self::validate_repo(repo)?;+ let token = self.repo_token(&repo.host).await?;+ let token_ref = token.as_deref();+ let platform = self.resolve_platform(&repo.host, token_ref, epoch).await;++ let probed = self.probe_repo_ref(repo, platform, token_ref).await;+ if let Some(probed) = &probed {+ let probed_key = (+ repo.host.clone(),+ repo.owner.clone(),+ repo.name.clone(),+ probed.branch.clone(),+ );+ let matched = {+ let mut cache = self.discovery_cache.lock_recover();+ let found = cache+ .get(&key)+ .or_else(|| cache.get(&probed_key))+ .filter(|entry| {+ entry.commit_sha.as_deref() == Some(probed.commit_sha.as_str())+ && entry.resolved_branch == probed.branch+ })+ .cloned();+ if let Some(mut entry) = found {+ if self.credential_epoch.load(Ordering::SeqCst) == epoch {+ entry.fetched_at = Some(started_at);+ let target_key = if Self::is_default_branch_sentinel(&repo.branch)+ && probed.from_head_symref+ {+ probed_key+ } else {+ key.clone()+ };+ cache.insert(target_key, entry.clone());+ }+ Some((entry.skills, entry.resolved_branch, probed.from_head_symref))+ } else {+ None+ }+ };+ if let Some(hit) = matched {+ return Ok(hit);+ }+ }++ // 优先按探测到的不可变 commit SHA 下载归档,确保扫描结果与缓存 SHA 严格对应;+ // 仅当 commit 归档 404(如探测与下载间隙被 force-push)或未探测到时才回退分支下载,+ // 且分支回退结果不绑定未校验的 SHA。+ let (archive_file, resolved_branch, verified_sha, from_head_symref) = match &probed {+ Some(probed) => match self+ .download_commit_archive_bounded(repo, platform, &probed.commit_sha, token_ref)+ .await+ {+ Ok(file) => (+ file,+ probed.branch.clone(),+ Some(probed.commit_sha.clone()),+ probed.from_head_symref,+ ),+ Err(e) if Self::is_branch_not_found(&e) => {+ let mut fallback_repo = repo.clone();+ fallback_repo.branch = probed.branch.clone();+ let (file, branch) = self+ .download_repo_archive_bounded(&fallback_repo, platform, token_ref)+ .await?;+ let trusted_symref = probed.from_head_symref && branch == probed.branch;+ (file, branch, None, trusted_symref)+ }+ Err(e) => return Err(e),+ },+ None => {+ let (file, branch) = self+ .download_repo_archive_bounded(repo, platform, token_ref)+ .await?;+ (file, branch, None, false)+ }+ };++ let mut resolved_repo = repo.clone();+ resolved_repo.branch = resolved_branch.clone();+ let skills = tokio::task::spawn_blocking(move || {+ Self::scan_skills_from_archive(archive_file, &resolved_repo, platform)+ })+ .await+ .map_err(|e| anyhow!("扫描仓库归档任务异常中止: {e}"))??;++ self.store_discovery_cache(+ repo,+ started_at,+ epoch,+ verified_sha,+ resolved_branch.clone(),+ skills.clone(),+ use_disk_cache,+ from_head_symref,+ );++ Ok((skills, resolved_branch, from_head_symref))}- /// 从仓库获取技能列表- pub(super) async fn fetch_repo_skills(+ #[allow(clippy::too_many_arguments)]+ pub(super) fn store_discovery_cache(&self,repo: &SkillRepo,+ started_at: Instant,+ epoch: u64,+ commit_sha: Option<String>,+ resolved_branch: String,+ skills: Vec<DiscoverableSkill>,+ persist_disk: bool,+ from_head_symref: bool,+ ) {+ let store_branch = if Self::is_default_branch_sentinel(&repo.branch) && from_head_symref {+ resolved_branch.clone()+ } else {+ repo.branch.clone()+ };+ let key = (+ repo.host.clone(),+ repo.owner.clone(),+ repo.name.clone(),+ store_branch,+ );+ let updated = {+ let mut cache = self.discovery_cache.lock_recover();+ if self.credential_epoch.load(Ordering::SeqCst) != epoch {+ return;+ }+ let can_write = cache+ .get(&key)+ .is_none_or(|entry| entry.fetched_at.is_none_or(|t| t <= started_at));+ if !can_write {+ return;+ }+ cache.insert(+ key,+ CachedRepoDiscovery {+ fetched_at: Some(started_at),+ commit_sha,+ resolved_branch,+ skills,+ },+ );+ true+ };+ if updated && persist_disk {+ self.persist_discovery_cache();+ }+ }++ /// 仅从 ZIP 归档中读取 `SKILL.md` 条目解析元数据,避免发现阶段把整个仓库解压落盘。+ ///+ /// 同时解析文件级与目录级符号链接,并对累计解压字节与保留元数据总量施加独立预算。+ pub(super) fn scan_skills_from_archive<R: std::io::Read + std::io::Seek>(+ reader: R,+ repo: &SkillRepo,+ platform: RepoPlatform,) -> Result<Vec<DiscoverableSkill>> {- let (temp_guard, resolved_branch) = self.download_repo_bounded(repo).await?;+ let mut archive = Self::open_downloaded_archive(reader)?;+ if archive.is_empty() {+ return Err(anyhow!(format_skill_error(+ "EMPTY_ARCHIVE",+ &[],+ Some("checkRepoUrl"),+ )));+ }+ if archive.len() > MAX_ARCHIVE_ENTRIES {+ let count = archive.len().to_string();+ let limit = MAX_ARCHIVE_ENTRIES.to_string();+ return Err(anyhow!(format_skill_error(+ "ARCHIVE_TOO_MANY_ENTRIES",+ &[("count", &count), ("limit", &limit)],+ Some("checkZipContent"),+ )));+ }++ let root_name = {+ let first = archive.by_index(0)?;+ first.name().split('/').next().unwrap_or("").to_string()+ };++ let mut regular_candidates: Vec<(String, String, SkillMetadata)> = Vec::new();+ let mut symlinks: Vec<(String, String)> = Vec::new();+ let mut scan_bytes: u64 = 0;+ let mut metadata_bytes: usize = 0;++ for i in 0..archive.len() {+ let mut file = archive.by_index(i)?;+ if file.is_dir() {+ continue;+ }+ let Some(safe_path) = file.enclosed_name() else {+ continue;+ };+ let Ok(relative_path) = safe_path.strip_prefix(&root_name) else {+ continue;+ };+ if relative_path+ .components()+ .any(|c| matches!(c, Component::ParentDir))+ {+ continue;+ }++ if file.is_symlink() {+ let Some(target) = Self::read_symlink_target_within(&mut file, &mut scan_bytes)?+ else {+ continue;+ };+ if let Some(resolved_target) =+ Self::resolve_archive_symlink_target(relative_path, &target)+ {+ let link_rel = relative_path.to_string_lossy().replace('\\', "/");+ // 防止目标包含链接自身(如 `dir/link -> ..`)造成递归膨胀+ if link_rel != resolved_target+ && !link_rel.starts_with(&format!("{resolved_target}/"))+ {+ symlinks.push((link_rel, resolved_target));+ }+ }+ continue;+ }++ if relative_path.file_name() != Some(OsStr::new("SKILL.md")) {+ continue;+ }++ let parent_rel = relative_path+ .parent()+ .map(|p| p.to_string_lossy().replace('\\', "/"))+ .unwrap_or_default();+ let doc_path = relative_path.to_string_lossy().replace('\\', "/");+ let content = Self::read_limited_utf8(&mut file, MAX_SKILL_MD_BYTES, &mut scan_bytes)?;+ let meta = Self::parse_skill_metadata_str(&content);+ Self::charge_metadata_budget(&mut metadata_bytes, &meta, &parent_rel)?;+ regular_candidates.push((parent_rel, doc_path, meta));+ }++ let symlink_targets: HashMap<String, String> = symlinks.iter().cloned().collect();+ let mut candidates = regular_candidates;++ for (link_rel, _) in &symlinks {+ let is_skill_md_link = link_rel == "SKILL.md" || link_rel.ends_with("/SKILL.md");+ if is_skill_md_link {+ let Some(resolved_target) = Self::resolve_archive_path(link_rel, &symlink_targets)+ else {+ continue;+ };+ let full_name = format!("{root_name}/{resolved_target}");+ let Ok(mut target_file) = archive.by_name(&full_name) else {+ continue;+ };+ if target_file.is_dir() || target_file.is_symlink() {+ continue;+ }+ let parent_rel = link_rel+ .rsplit_once('/')+ .map(|(head, _)| head.to_string())+ .unwrap_or_default();+ let content =+ Self::read_limited_utf8(&mut target_file, MAX_SKILL_MD_BYTES, &mut scan_bytes)?;+ let meta = Self::parse_skill_metadata_str(&content);+ Self::charge_metadata_budget(&mut metadata_bytes, &meta, &parent_rel)?;+ candidates.push((parent_rel, link_rel.clone(), meta));+ }+ }+ // 目录别名也要看到文件链接和其它目录别名解析出的 SKILL.md。+ // 工作队列传播这些候选;完整路径解析拒绝循环,去重和元数据预算限制展开量。+ let mut seen_docs: HashSet<String> = candidates+ .iter()+ .map(|(_, doc_path, _)| doc_path.clone())+ .collect();+ let mut next_candidate = 0;+ while next_candidate < candidates.len() {+ let (parent_rel, _, meta) = candidates[next_candidate].clone();+ next_candidate += 1;+ for (link_rel, resolved_target) in &symlinks {+ if link_rel == "SKILL.md" || link_rel.ends_with("/SKILL.md") {+ continue;+ }+ let target_prefix = format!("{resolved_target}/");+ let mapped_parent = if &parent_rel == resolved_target {+ link_rel.clone()+ } else if let Some(rest) = parent_rel.strip_prefix(&target_prefix) {+ format!("{link_rel}/{rest}")+ } else {+ continue;+ };+ let mapped_doc = format!("{mapped_parent}/SKILL.md");+ if seen_docs.contains(&mapped_doc)+ || Self::resolve_archive_path(&mapped_doc, &symlink_targets).is_none()+ {+ continue;+ }+ Self::charge_metadata_budget(&mut metadata_bytes, &meta, &mapped_parent)?;+ seen_docs.insert(mapped_doc.clone());+ candidates.push((mapped_parent, mapped_doc, meta.clone()));+ }+ }++ // 与 scan_dir_recursive 保持一致:父目录已有 SKILL.md 时不再收入其子目录。+ candidates.sort_by(|a, b| {+ let depth = |p: &str| {+ if p.is_empty() {+ 0+ } else {+ p.matches('/').count() + 1+ }+ };+ depth(&a.0).cmp(&depth(&b.0)).then_with(|| a.0.cmp(&b.0))+ });++ let mut accepted_dirs: HashSet<String> = HashSet::new();let mut skills = Vec::new();- let scan_dir = temp_guard.path();- let mut resolved_repo = repo.clone();- resolved_repo.branch = resolved_branch;- self.scan_dir_recursive(scan_dir, scan_dir, &resolved_repo, &mut skills)?;- Self::keep_one_per_install_name(&mut skills);+ for (parent_rel, doc_path, meta) in candidates {+ if accepted_dirs.contains("") || Self::has_ancestor_dir(&parent_rel, &accepted_dirs) {+ continue;+ }+ let directory = if parent_rel.is_empty() {+ repo.name.clone()+ } else {+ parent_rel.clone()+ };+ accepted_dirs.insert(parent_rel);+ skills.push(Self::build_skill_from_parsed_metadata(+ meta, &directory, &doc_path, repo, platform,+ ));+ }+ Self::keep_one_per_install_name(&mut skills);Ok(skills)}+ fn charge_discovery_scan_budget(total_bytes: &mut u64, amount: u64) -> Result<()> {+ if total_bytes.saturating_add(amount) > MAX_DISCOVERY_SCAN_BYTES {+ let limit_mb = (MAX_DISCOVERY_SCAN_BYTES / 1024 / 1024).to_string();+ return Err(anyhow!(format_skill_error(+ "ARCHIVE_TOO_LARGE",+ &[("limit_mb", &limit_mb)],+ Some("checkZipContent"),+ )));+ }+ *total_bytes += amount;+ Ok(())+ }++ fn charge_metadata_budget(+ total_bytes: &mut usize,+ meta: &SkillMetadata,+ parent_rel: &str,+ ) -> Result<()> {+ let entry_bytes = meta.name.as_deref().map_or(0, str::len)+ + meta.description.as_deref().map_or(0, str::len)+ + parent_rel.len();+ if total_bytes.saturating_add(entry_bytes) > MAX_DISCOVERY_METADATA_BYTES {+ let limit_mb = (MAX_DISCOVERY_METADATA_BYTES / 1024 / 1024).to_string();+ return Err(anyhow!(format_skill_error(+ "ARCHIVE_TOO_LARGE",+ &[("limit_mb", &limit_mb)],+ Some("checkZipContent"),+ )));+ }+ *total_bytes += entry_bytes;+ Ok(())+ }++ fn read_symlink_target_within<R: std::io::Read>(+ reader: &mut R,+ total_bytes: &mut u64,+ ) -> Result<Option<String>> {+ let mut raw = Vec::new();+ let mut limited = std::io::Read::take(reader, MAX_SYMLINK_TARGET_BYTES + 1);+ std::io::Read::read_to_end(&mut limited, &mut raw)?;+ Self::charge_discovery_scan_budget(total_bytes, raw.len() as u64)?;+ if raw.len() as u64 > MAX_SYMLINK_TARGET_BYTES {+ return Ok(None);+ }+ Ok(String::from_utf8(raw)+ .ok()+ .map(|target| target.trim().to_string()))+ }++ fn read_limited_utf8<R: std::io::Read>(+ reader: &mut R,+ limit: u64,+ total_bytes: &mut u64,+ ) -> Result<String> {+ let mut raw = Vec::new();+ let mut buf = [0u8; 8 * 1024];+ let mut remaining = limit;+ while remaining > 0 {+ let to_read = (remaining as usize).min(buf.len());+ let read = reader.read(&mut buf[..to_read])?;+ if read == 0 {+ break;+ }+ Self::charge_discovery_scan_budget(total_bytes, read as u64)?;+ raw.extend_from_slice(&buf[..read]);+ remaining -= read as u64;+ }+ Ok(String::from_utf8_lossy(&raw).into_owned())+ }++ fn resolve_archive_symlink_target(relative_symlink: &Path, target: &str) -> Option<String> {+ if target.is_empty() || target.starts_with('/') || target.starts_with('\\') {+ return None;+ }+ let mut parts: Vec<String> = relative_symlink+ .parent()+ .map(|p| {+ p.components()+ .filter_map(|c| match c {+ Component::Normal(s) => Some(s.to_string_lossy().to_string()),+ _ => None,+ })+ .collect()+ })+ .unwrap_or_default();+ for seg in target.split(['/', '\\']) {+ match seg {+ "" | "." => continue,+ ".." => {+ parts.pop()?;+ }+ other => parts.push(other.to_string()),+ }+ }+ (!parts.is_empty()).then(|| parts.join("/"))+ }++ /// 解析路径中任意一段的符号链接(包括目录前缀),重复经过同一链接即为循环。+ fn resolve_archive_path(path: &str, symlinks: &HashMap<String, String>) -> Option<String> {+ let mut path = path.to_string();+ let mut followed = HashSet::new();+ loop {+ let mut replacement = None;+ for end in path+ .match_indices('/')+ .map(|(index, _)| index)+ .chain(std::iter::once(path.len()))+ {+ if let Some((link, target)) = symlinks.get_key_value(&path[..end]) {+ if !followed.insert(link) {+ return None;+ }+ replacement = Some(format!("{target}{}", &path[end..]));+ break;+ }+ }+ match replacement {+ Some(resolved) => path = resolved,+ None => return Some(path),+ }+ }+ }++ fn has_ancestor_dir(parent_rel: &str, accepted: &HashSet<String>) -> bool {+ if accepted.contains(parent_rel) {+ return true;+ }+ let mut cursor = parent_rel;+ while let Some((head, _)) = cursor.rsplit_once('/') {+ if accepted.contains(head) {+ return true;+ }+ cursor = head;+ }+ false+ }+/// 同一仓库里安装目录名(路径最后一段)相同的技能只留一条。////// 安装只取最后一段当目录名,同仓库同名的第二条装下去只会复用第一条,@@ -216,14 +865,29 @@ impl SkillService {repo: &SkillRepo,) -> Result<DiscoverableSkill> {let meta = self.parse_skill_metadata(skill_md)?;+ Ok(Self::build_skill_from_parsed_metadata(+ meta,+ directory,+ doc_path,+ repo,+ self.known_platform(&repo.host),+ ))+ }- Ok(DiscoverableSkill {+ fn build_skill_from_parsed_metadata(+ meta: SkillMetadata,+ directory: &str,+ doc_path: &str,+ repo: &SkillRepo,+ platform: RepoPlatform,+ ) -> DiscoverableSkill {+ DiscoverableSkill {key: format!("{}/{}:{}", repo.owner, repo.name, directory),name: meta.name.unwrap_or_else(|| directory.to_string()),description: meta.description.unwrap_or_default(),directory: directory.to_string(),readme_url: Self::build_skill_doc_url(- self.known_platform(&repo.host),+ platform,&repo.host,&repo.owner,&repo.name,@@ -234,7 +898,7 @@ impl SkillService {repo_owner: repo.owner.clone(),repo_name: repo.name.clone(),repo_branch: repo.branch.clone(),- })+ }}/// 解析技能元数据@@ -245,23 +909,25 @@ impl SkillService {/// 静态方法:解析技能元数据pub(super) fn parse_skill_metadata_static(path: &Path) -> Result<SkillMetadata> {let content = fs::read_to_string(path)?;+ Ok(Self::parse_skill_metadata_str(&content))+ }++ pub(super) fn parse_skill_metadata_str(content: &str) -> SkillMetadata {let content = content.trim_start_matches('\u{feff}');let parts: Vec<&str> = content.splitn(3, "---").collect();if parts.len() < 3 {- return Ok(SkillMetadata {+ return SkillMetadata {name: None,description: None,- });+ };}let front_matter = parts[1].trim();- let meta: SkillMetadata = serde_yaml::from_str(front_matter).unwrap_or(SkillMetadata {+ serde_yaml::from_str(front_matter).unwrap_or(SkillMetadata {name: None,description: None,- });-- Ok(meta)+ })}/// 从 SKILL.md 读取名称和描述,不存在则用目录名兜底diff --git a/src-tauri/src/services/skill/download.rs b/src-tauri/src/services/skill/download.rsindex b45a1ec28..a748b14d8 100644--- a/src-tauri/src/services/skill/download.rs+++ b/src-tauri/src/services/skill/download.rs@@ -209,16 +209,11 @@ impl SkillService {) -> Result<(tempfile::TempDir, String)> {Self::validate_repo(repo)?;- // 守卫全程持有,成功后连同目录一起交给调用方(见 `extract_local_zip` 的说明)。- // 原来这里立刻 keep(),任何一步失败——下载超时、ARCHIVE_TOO_LARGE、解压出错- // ——都会把半个解压目录永久留在磁盘上,反复触发即可持续填盘。- let temp_dir = tempfile::tempdir()?;- let temp_path = temp_dir.path();-// Exercise the real install/update flow without network access in unit tests.#[cfg(test)]if let Some(fixture) = &self.repo_fixture {- Self::copy_dir_recursive(fixture, temp_path)?;+ let temp_dir = tempfile::tempdir()?;+ Self::copy_dir_recursive(fixture, temp_dir.path())?;return Ok((temp_dir, repo.branch.clone()));}@@ -226,15 +221,10 @@ impl SkillService {let token = self.repo_token(&repo.host).await?;let token = token.as_deref();let platform = self.resolve_platform(&repo.host, token, epoch).await;- let branch = Self::try_repo_branches(- repo,- platform,- token.is_some(),- temp_path,- |url| async move { self.download_and_extract(&url, temp_path, token).await },- )- .await?;- Ok((temp_dir, branch))+ Self::try_repo_branches(repo, platform, token.is_some(), |url| async move {+ self.download_and_extract_temp(&url, token).await+ })+ .await}/// 这台主机的访问令牌。读钥匙串在 macOS 上会起子进程,放到阻塞线程里做。@@ -264,16 +254,27 @@ impl SkillService {}/// 令牌变了,平台要按新身份重新探测:没令牌时强制登录的 Gitea 会被认成 GitLab。- /// 这台主机的发现缓存也作废:删了令牌,私有仓库的技能列表不该再显示 10 分钟。+ /// 这台主机的发现缓存也作废:删了令牌,私有仓库的技能列表不该再显示或留在磁盘缓存里。pub(super) fn forget_platform(&self, host: &str) {{let mut cache = self.platform_cache.lock_recover();self.credential_epoch.fetch_add(1, Ordering::SeqCst);cache.remove(host);}- self.discovery_cache- .lock_recover()- .retain(|key, _| key.0 != host);+ let had_disk_cache = self.discovery_cache_loaded.load(Ordering::Acquire)+ || Self::discovery_cache_path().exists();+ if had_disk_cache {+ self.ensure_discovery_cache_loaded();+ }+ let removed = {+ let mut cache = self.discovery_cache.lock_recover();+ let before = cache.len();+ cache.retain(|key, _| key.0 != host);+ cache.len() != before+ };+ if had_disk_cache && removed {+ self.persist_discovery_cache();+ }}#[cfg(test)]@@ -282,24 +283,23 @@ impl SkillService {self}- /// 依次尝试「配置分支 → main → master」,返回第一个下载成功的分支。+ /// 依次尝试「配置分支 → main → master」,返回第一个下载成功的结果及真实分支。////// 只有「分支不存在」(HTTP 404)才换下一个分支:超时、超过体积上限、解压失败、/// 网络错误换个分支也不会好,继续试只会让 master 的 404 盖掉真实原因,界面变成/// 「仓库或分支不存在」。抽成接收 `attempt` 的函数是为了不联网也能单测这条规则。- pub(super) async fn try_repo_branches<F, Fut>(+ pub(super) async fn try_repo_branches<T, F, Fut>(repo: &SkillRepo,platform: RepoPlatform,authenticated: bool,- temp_path: &Path,mut attempt: F,- ) -> Result<String>+ ) -> Result<(T, String)>whereF: FnMut(String) -> Fut,- Fut: std::future::Future<Output = Result<()>>,+ Fut: std::future::Future<Output = Result<T>>,{let mut branches = Vec::new();- if !repo.branch.is_empty() && !repo.branch.eq_ignore_ascii_case("HEAD") {+ if !Self::is_default_branch_sentinel(&repo.branch) {branches.push(repo.branch.as_str());}if !branches.contains(&"main") {@@ -314,12 +314,8 @@ impl SkillService {let url = Self::build_archive_url(repo, platform, branch, authenticated)?;match attempt(url).await {- Ok(()) => return Ok(branch.to_string()),+ Ok(value) => return Ok((value, branch.to_string())),Err(e) if Self::is_branch_not_found(&e) => {- // 每个分支各自重算预算,所以失败后必须把上一轮的残留清掉——- // 否则 N 个候选分支等于 N 倍的落盘量堆在同一个目录里。- let _ = fs::remove_dir_all(temp_path);- let _ = fs::create_dir_all(temp_path);last_error = Some(e);}Err(e) => return Err(Self::with_repo_context(e, repo)),@@ -331,6 +327,104 @@ impl SkillService {.unwrap_or_else(|| anyhow::anyhow!("所有分支下载失败")))}+ /// 探测仓库目标分支及最新 commit SHA(Git Smart HTTP `info/refs`)。+ ///+ /// 请求头与整段响应共用同一个 `PLATFORM_PROBE_TIMEOUT` 截止时间,防止慢速代理滴流阻塞。+ /// 失败、非 200、超时或超过上限一律返回 `None`,由调用方无感回退到归档下载。+ pub(super) async fn probe_repo_ref(+ &self,+ repo: &SkillRepo,+ platform: RepoPlatform,+ token: Option<&str>,+ ) -> Option<ProbedGitRef> {+ let url = Self::build_git_info_refs_url(repo).ok()?;+ let client = Self::http_client(token.is_some()).ok()?;+ let mut request = client+ .get(&url)+ .header(reqwest::header::USER_AGENT, SKILL_DOWNLOAD_USER_AGENT);+ if let Some(token) = token {+ let username = match platform {+ RepoPlatform::GitLab => "oauth2",+ RepoPlatform::GitHub | RepoPlatform::Gitea => "x-access-token",+ };+ request = Self::with_basic_auth(request, username, token).ok()?;+ }++ timeout(PLATFORM_PROBE_TIMEOUT, async {+ let mut response = request.send().await.ok()?;+ if !response.status().is_success() {+ return None;+ }++ let mut buf = Vec::new();+ loop {+ match response.chunk().await {+ Ok(Some(chunk)) => {+ let remaining = GIT_INFO_REFS_MAX_BYTES.saturating_sub(buf.len());+ let take = chunk.len().min(remaining);+ buf.extend_from_slice(&chunk[..take]);+ let hit_cap = buf.len() >= GIT_INFO_REFS_MAX_BYTES;+ // 传 `eof = false`:命中分支或越过 `refs/heads/` 立即返回 Complete;+ // 达到 512 KiB 上限仍未越过 `refs/heads/` 时返回 NeedMore,由下一分支回退。+ match Self::parse_git_info_refs(&buf, &repo.branch, false) {+ repo::GitRefParseOutcome::Complete(res) => return res,+ repo::GitRefParseOutcome::Invalid => return None,+ repo::GitRefParseOutcome::NeedMore if hit_cap => return None,+ repo::GitRefParseOutcome::NeedMore => {}+ }+ }+ Ok(None) => {+ return match Self::parse_git_info_refs(&buf, &repo.branch, true) {+ repo::GitRefParseOutcome::Complete(res) => res,+ repo::GitRefParseOutcome::Invalid+ | repo::GitRefParseOutcome::NeedMore => None,+ };+ }+ Err(_) => return None,+ }+ }+ })+ .await+ .ok()+ .flatten()+ }++ /// 按不可变 commit SHA 下载仓库归档到匿名临时文件,保证内容与缓存 SHA 严格一致。+ pub(super) async fn download_commit_archive_bounded(+ &self,+ repo: &SkillRepo,+ platform: RepoPlatform,+ commit_sha: &str,+ token: Option<&str>,+ ) -> Result<fs::File> {+ let url = Self::build_commit_archive_url(repo, platform, commit_sha, token.is_some())?;+ timeout(+ DOWNLOAD_TOTAL_TIMEOUT,+ self.download_archive_file(&url, token),+ )+ .await+ .map_err(|_| anyhow!(Self::download_timeout_error(repo)))?+ .map_err(|e| Self::with_repo_context(e, repo))+ }++ /// 仅下载仓库归档到匿名临时文件(不解压落盘),供发现阶段在内存中只读 `SKILL.md`。+ pub(super) async fn download_repo_archive_bounded(+ &self,+ repo: &SkillRepo,+ platform: RepoPlatform,+ token: Option<&str>,+ ) -> Result<(fs::File, String)> {+ Self::validate_repo(repo)?;+ timeout(+ DOWNLOAD_TOTAL_TIMEOUT,+ Self::try_repo_branches(repo, platform, token.is_some(), |url| async move {+ self.download_archive_file(&url, token).await+ }),+ )+ .await+ .map_err(|_| anyhow!(Self::download_timeout_error(repo)))?+ }+/// 归档地址返回 404,即这个分支(或整个仓库)不存在。pub(super) fn is_branch_not_found(error: &anyhow::Error) -> bool {serde_json::from_str::<serde_json::Value>(&error.to_string())@@ -360,13 +454,12 @@ impl SkillService {anyhow::anyhow!(value.to_string())}- /// 下载并解压 ZIP。`token` 是这台主机的访问令牌,没设置为 `None`。- pub(super) async fn download_and_extract(+ /// 流式下载归档到匿名临时文件,按实际字节数卡住上限。+ pub(super) async fn download_archive_file(&self,url: &str,- dest: &Path,token: Option<&str>,- ) -> Result<()> {+ ) -> Result<fs::File> {let client = Self::http_client(token.is_some())?;// 共享客户端不带默认 User-Agent;GitHub 归档下载对无 UA 请求更容易被限流成 429(#8813)let mut request = client@@ -417,9 +510,26 @@ impl SkillService {std::io::Write::write_all(&mut body, &chunk)?;}- let file = body.into_inner().map_err(|e| e.into_error())?;- let archive = Self::open_downloaded_archive(file)?;- Self::extract_repo_archive(archive, dest)+ body.into_inner()+ .map_err(|e| anyhow::Error::from(e.into_error()))+ }++ /// 下载并解压到独占临时目录。`TempDir` 守卫由阻塞任务全程持有,超时取消时由任务结束自动清理,+ /// 避免外层先 drop 守卫后阻塞解压继续重建目录留下残留。+ pub(super) async fn download_and_extract_temp(+ &self,+ url: &str,+ token: Option<&str>,+ ) -> Result<tempfile::TempDir> {+ let file = self.download_archive_file(url, token).await?;+ tokio::task::spawn_blocking(move || -> Result<tempfile::TempDir> {+ let temp_dir = tempfile::tempdir()?;+ let archive = Self::open_downloaded_archive(file)?;+ Self::extract_repo_archive(archive, temp_dir.path())?;+ Ok(temp_dir)+ })+ .await+ .map_err(|e| anyhow!("解压归档任务异常中止: {e}"))?}/// 打开下载到的归档。不兼容 GitHub / GitLab / Gitea 接口的站点(如 cnb.cool,#9812)diff --git a/src-tauri/src/services/skill/repo.rs b/src-tauri/src/services/skill/repo.rsindex 4afda7d89..0a071212f 100644--- a/src-tauri/src/services/skill/repo.rs+++ b/src-tauri/src/services/skill/repo.rs@@ -108,6 +108,11 @@ impl SkillService {.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))}+ /// 空串和 "HEAD" 都是「用仓库默认分支」的哨兵值,不作为真实分支名拼进 URL。+ pub(super) fn is_default_branch_sentinel(branch: &str) -> bool {+ branch.is_empty() || branch.eq_ignore_ascii_case("HEAD")+ }+/// git 分支名。////// 分支名合法含 `/`(`feature/x`),所以不能整体禁掉分隔符——按段做白名单。@@ -115,13 +120,7 @@ impl SkillService {/// `a/.../b` 这类变形。除 `git check-ref-format` 的规则外还额外禁掉 `#` 与 `%`:/// 前者会把 URL 后半截变成 fragment,后者可用百分号编码绕过字符检查。pub(super) fn is_valid_git_branch(branch: &str) -> bool {- // 空串和 "HEAD" 都是 `download_repo` 的哨兵,语义都是「用仓库默认分支」:- // 分支候选表对两者一视同仁地跳过,改试 main / master,所以它们**永远不会- // 被拼进 URL**,也就没有可校验的攻击面。空串必须放行——`skill_repos` 的- // 存量行可以是空 branch(建表默认值是 'main',但不禁止空串),前端两处- // `repo.branch || "main"` 就是照着这个前提写的。把它当非法会让那些仓库- // 在 download_repo 第一行就报 INVALID_REPO_REF,技能面板直接列不出来。- if branch.is_empty() || branch.eq_ignore_ascii_case("HEAD") {+ if Self::is_default_branch_sentinel(branch) {return true;}if branch.len() > 255 {@@ -571,6 +570,236 @@ impl SkillService {Ok(request.header(reqwest::header::AUTHORIZATION, value))}+ /// 按不可变 commit SHA 构造归档下载地址(避免探测与下载之间分支移动导致缓存错配)。+ pub(super) fn build_commit_archive_url(+ repo: &SkillRepo,+ platform: RepoPlatform,+ commit_sha: &str,+ authenticated: bool,+ ) -> Result<String> {+ Self::validate_repo(repo)?;+ let valid_sha = (commit_sha.len() == 40 || commit_sha.len() == 64)+ && commit_sha.bytes().all(|b| b.is_ascii_hexdigit())+ && !commit_sha.bytes().all(|b| b == b'0');+ if !valid_sha {+ return Err(anyhow!(format_skill_error(+ "INVALID_REPO_REF",+ &[("owner", &repo.owner), ("name", &repo.name)],+ Some("checkRepoUrl"),+ )));+ }++ if repo.is_github() && authenticated {+ let url = format!(+ "https://api.github.com/repos/{}/{}/zipball/{}",+ repo.owner, repo.name, commit_sha+ );+ let parsed = url::Url::parse(&url).map_err(|e| anyhow!("Invalid archive URL: {e}"))?;+ let expected = format!("/repos/{}/{}/zipball/{commit_sha}", repo.owner, repo.name);+ if parsed.scheme() != "https"+ || parsed.host_str() != Some("api.github.com")+ || parsed.port().is_some()+ || !parsed.username().is_empty()+ || parsed.password().is_some()+ || parsed.query().is_some()+ || parsed.fragment().is_some()+ || parsed.path() != expected+ {+ return Err(anyhow!(format_skill_error(+ "INVALID_REPO_REF",+ &[("owner", &repo.owner), ("name", &repo.name)],+ Some("checkRepoUrl"),+ )));+ }+ return Ok(url);+ }+ if repo.is_github() {+ let url = format!(+ "https://github.com/{}/{}/archive/{}.zip",+ repo.owner, repo.name, commit_sha+ );+ let parsed = url::Url::parse(&url).map_err(|e| anyhow!("Invalid archive URL: {e}"))?;+ let expected = format!("/{}/{}/archive/{commit_sha}.zip", repo.owner, repo.name);+ if parsed.scheme() != "https"+ || parsed.host_str() != Some("github.com")+ || parsed.path() != expected+ {+ return Err(anyhow!(format_skill_error(+ "INVALID_REPO_REF",+ &[("owner", &repo.owner), ("name", &repo.name)],+ Some("checkRepoUrl"),+ )));+ }+ return Ok(url);+ }++ // GitLab (?sha=<commit>) 与 Gitea (/archive/<commit>.zip) 复用同一套接口和出口断言。+ Self::build_archive_url(repo, platform, commit_sha, authenticated)+ }++ /// 构造 Git Smart HTTP `info/refs?service=git-upload-pack` 地址并做出口断言。+ pub(super) fn build_git_info_refs_url(repo: &SkillRepo) -> Result<String> {+ Self::validate_repo(repo)?;+ let expected_path = format!("/{}/{}.git/info/refs", repo.owner, repo.name);+ let url = format!(+ "https://{}{}?service=git-upload-pack",+ repo.host, expected_path+ );+ let parsed = url::Url::parse(&url).map_err(|e| anyhow!("Invalid git refs URL: {e}"))?;+ let parsed_host = match parsed.port() {+ Some(port) => format!("{}:{port}", parsed.host_str().unwrap_or_default()),+ None => parsed.host_str().unwrap_or_default().to_string(),+ };+ if parsed.scheme() != "https"+ || parsed_host != repo.host+ || !parsed.username().is_empty()+ || parsed.password().is_some()+ || parsed.fragment().is_some()+ || parsed.path() != expected_path+ || parsed.query() != Some("service=git-upload-pack")+ {+ return Err(anyhow!(format_skill_error(+ "INVALID_REPO_REF",+ &[("owner", &repo.owner), ("name", &repo.name)],+ Some("checkRepoUrl"),+ )));+ }+ Ok(url)+ }++ /// Git Smart HTTP 的 Basic 认证头(标记敏感,不进调试输出)。+ pub(super) fn with_basic_auth(+ request: reqwest::RequestBuilder,+ username: &str,+ token: &str,+ ) -> Result<reqwest::RequestBuilder> {+ use base64::Engine;+ let encoded =+ base64::engine::general_purpose::STANDARD.encode(format!("{username}:{token}"));+ let mut value = reqwest::header::HeaderValue::from_str(&format!("Basic {encoded}"))+ .map_err(|_| anyhow!("访问令牌含有不能放进请求头的字符"))?;+ value.set_sensitive(true);+ Ok(request.header(reqwest::header::AUTHORIZATION, value))+ }++ /// 流式解析 Git Smart HTTP v1 `info/refs` 响应,拿到目标分支及其最新 commit SHA。+ ///+ /// Git 按字典序发送引用(`HEAD` → `refs/heads/*` → `refs/pull/*` → `refs/tags/*`),+ /// 命中精确分支或越过 `refs/heads/` 即返回 `Complete`,无需读完大仓库后面的数万条 tag/PR。+ pub(super) fn parse_git_info_refs(+ data: &[u8],+ configured_branch: &str,+ eof: bool,+ ) -> GitRefParseOutcome {+ let mut pos = 0usize;+ let mut main_oid: Option<String> = None;+ let mut master_oid: Option<String> = None;+ let mut seen_past_heads = false;+ let mut truncated = false;+ let want_default = Self::is_default_branch_sentinel(configured_branch);++ while pos < data.len() {+ if pos + 4 > data.len() {+ truncated = eof;+ break;+ }+ let Ok(len_str) = std::str::from_utf8(&data[pos..pos + 4]) else {+ return GitRefParseOutcome::Invalid;+ };+ let Ok(len) = usize::from_str_radix(len_str, 16) else {+ return GitRefParseOutcome::Invalid;+ };+ if len == 0 || len == 1 || len == 2 {+ pos += 4;+ continue;+ }+ if len < 4 {+ return GitRefParseOutcome::Invalid;+ }+ if pos + len > data.len() {+ truncated = eof;+ break;+ }+ let payload = &data[pos + 4..pos + len];+ pos += len;++ let payload = payload.strip_suffix(b"\n").unwrap_or(payload);+ if payload.is_empty() || payload.starts_with(b"#") {+ continue;+ }+ let (ref_bytes, caps_bytes) = match payload.iter().position(|&b| b == 0) {+ Some(nul) => (&payload[..nul], Some(&payload[nul + 1..])),+ None => (payload, None),+ };+ let Ok(ref_line) = std::str::from_utf8(ref_bytes) else {+ continue;+ };+ let Some((oid, refname)) = ref_line.split_once(' ') else {+ continue;+ };+ let valid_oid = (oid.len() == 40 || oid.len() == 64)+ && oid.bytes().all(|b| b.is_ascii_hexdigit())+ && !oid.bytes().all(|b| b == b'0');+ if !valid_oid {+ continue;+ }++ if refname == "HEAD" && want_default {+ if let Some(caps) = caps_bytes.and_then(|b| std::str::from_utf8(b).ok()) {+ for cap in caps.split_ascii_whitespace() {+ if let Some(branch) = cap.strip_prefix("symref=HEAD:refs/heads/") {+ if Self::is_valid_git_branch(branch)+ && !Self::is_default_branch_sentinel(branch)+ {+ return GitRefParseOutcome::Complete(Some(ProbedGitRef {+ branch: branch.to_string(),+ commit_sha: oid.to_string(),+ from_head_symref: true,+ }));+ }+ }+ }+ }+ } else if let Some(branch) = refname.strip_prefix("refs/heads/") {+ if !want_default && branch == configured_branch {+ return GitRefParseOutcome::Complete(Some(ProbedGitRef {+ branch: branch.to_string(),+ commit_sha: oid.to_string(),+ from_head_symref: false,+ }));+ }+ if branch == "main" {+ main_oid = Some(oid.to_string());+ } else if branch == "master" {+ master_oid = Some(oid.to_string());+ }+ } else if refname > "refs/heads/" {+ seen_past_heads = true;+ break;+ }+ }++ if !eof && !seen_past_heads {+ return GitRefParseOutcome::NeedMore;+ }+ if truncated && !seen_past_heads {+ return GitRefParseOutcome::Complete(None);+ }++ let main = main_oid.map(|commit_sha| ProbedGitRef {+ branch: "main".to_string(),+ commit_sha,+ from_head_symref: false,+ });+ let master = master_oid.map(|commit_sha| ProbedGitRef {+ branch: "master".to_string(),+ commit_sha,+ from_head_symref: false,+ });++ GitRefParseOutcome::Complete(main.or(master))+ }+/// 下载、探测用的客户端。带令牌时换成只走 https 的:reqwest 只在换主机或端口时/// 去掉 `Authorization`,同主机非默认端口从 https 跳到 http 会把令牌明文发出去。/// 匿名请求仍用共享客户端,行为不变。@@ -582,3 +811,10 @@ impl SkillService {}}}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(super) enum GitRefParseOutcome {+ NeedMore,+ Invalid,+ Complete(Option<ProbedGitRef>),+}diff --git a/src-tauri/src/services/skill/tests.rs b/src-tauri/src/services/skill/tests.rsindex 1dd3242f3..165ad28ea 100644--- a/src-tauri/src/services/skill/tests.rs+++ b/src-tauri/src/services/skill/tests.rs@@ -332,10 +332,9 @@ async fn run_branch_fallback(repo: &SkillRepo,mut outcome: impl FnMut(&str) -> Result<()>,) -> (Result<String>, Vec<String>) {- let temp = tempdir().unwrap();let mut attempted = Vec::new();let platform = SkillService::default_platform(&repo.host);- let result = SkillService::try_repo_branches(repo, platform, false, temp.path(), |url| {+ let result = SkillService::try_repo_branches(repo, platform, false, |url| {let branch = url.rsplit('/').next()@@ -346,7 +345,8 @@ async fn run_branch_fallback(attempted.push(branch);async move { result }})- .await;+ .await+ .map(|((), branch)| branch);(result, attempted)}@@ -652,8 +652,10 @@ fn download_failure_hints_separate_missing_tokens_from_rejected_ones() {}#[tokio::test]+#[serial_test::serial]async fn set_and_delete_repo_token_reprobe_the_platform() {let dir = tempfile::tempdir().unwrap();+ let _home = TestHomeGuard::set(dir.path());let (store, secrets) = crate::services::skill_repo_tokens::tests::memory_store(dir.path());let service = SkillService::new().with_repo_tokens(store);service@@ -662,10 +664,15 @@ async fn set_and_delete_repo_token_reprobe_the_platform() {.insert("git.example.com".into(), RepoPlatform::GitLab);let cached = |host: &str| (host.to_string(), "o".into(), "n".into(), "main".into());for host in ["git.example.com", "other.example.com"] {- service- .discovery_cache- .lock_recover()- .insert(cached(host), (Instant::now(), Vec::new()));+ service.discovery_cache.lock_recover().insert(+ cached(host),+ CachedRepoDiscovery {+ fetched_at: Some(Instant::now()),+ commit_sha: Some("a".repeat(40)),+ resolved_branch: "main".to_string(),+ skills: Vec::new(),+ },+ );}// 匿名探测还在途中时保存了令牌let stale_epoch = service.credential_epoch.load(Ordering::SeqCst);@@ -713,21 +720,20 @@ async fn set_and_delete_repo_token_reprobe_the_platform() {#[tokio::test]async fn branch_fallback_walks_gitlab_branches_on_404() {let repo = gitlab_repo("gitlab.com", "group/sub", "skills", "develop");- let temp = tempdir().unwrap();let mut attempted = Vec::new();- let result =- SkillService::try_repo_branches(&repo, RepoPlatform::GitLab, false, temp.path(), |url| {- let found = url.ends_with("?sha=master");- attempted.push(url);- async move {- if found {- Ok(())- } else {- Err(http404_error())- }+ let result = SkillService::try_repo_branches(&repo, RepoPlatform::GitLab, false, |url| {+ let found = url.ends_with("?sha=master");+ attempted.push(url);+ async move {+ if found {+ Ok(())+ } else {+ Err(http404_error())}- })- .await;+ }+ })+ .await+ .map(|((), branch)| branch);assert_eq!(result.unwrap(), "master");let prefix = "https://gitlab.com/api/v4/projects/group%2Fsub%2Fskills/repository/archive.zip";assert_eq!(@@ -877,21 +883,20 @@ fn build_archive_url_targets_the_gitea_api() {#[tokio::test]async fn branch_fallback_walks_gitea_branches_on_404() {let repo = gitlab_repo("codeberg.org", "team", "skills", "develop");- let temp = tempdir().unwrap();let mut attempted = Vec::new();- let result =- SkillService::try_repo_branches(&repo, RepoPlatform::Gitea, false, temp.path(), |url| {- let found = url.ends_with("/master.zip");- attempted.push(url);- async move {- if found {- Ok(())- } else {- Err(http404_error())- }+ let result = SkillService::try_repo_branches(&repo, RepoPlatform::Gitea, false, |url| {+ let found = url.ends_with("/master.zip");+ attempted.push(url);+ async move {+ if found {+ Ok(())+ } else {+ Err(http404_error())}- })- .await;+ }+ })+ .await+ .map(|((), branch)| branch);assert_eq!(result.unwrap(), "master");let prefix = "https://codeberg.org/api/v1/repos/team/skills/archive";assert_eq!(@@ -4146,6 +4151,504 @@ async fn discover_repo_reports_failure_and_skips_disabled_repo() {assert!(disabled.failures.is_empty());}+fn pkt_line(payload: &[u8]) -> Vec<u8> {+ let mut out = format!("{:04x}", payload.len() + 4).into_bytes();+ out.extend_from_slice(payload);+ out+}++#[test]+fn parse_git_info_refs_resolves_head_symref_and_stops_before_tags() {+ use super::repo::GitRefParseOutcome;++ let sha_main = "1111111111111111111111111111111111111111";+ let sha_master = "2222222222222222222222222222222222222222";+ let sha_dev = "3333333333333333333333333333333333333333";++ let mut payload = Vec::new();+ payload.extend_from_slice(&pkt_line(b"# service=git-upload-pack\n"));+ payload.extend_from_slice(b"0000");+ payload.extend_from_slice(&pkt_line(+ format!("{sha_master} HEAD\0multi_ack symref=HEAD:refs/heads/master agent=git/2.40\n")+ .as_bytes(),+ ));+ payload.extend_from_slice(&pkt_line(format!("{sha_dev} refs/heads/dev\n").as_bytes()));+ payload.extend_from_slice(&pkt_line(+ format!("{sha_master} refs/heads/master\n").as_bytes(),+ ));+ // 越过 refs/heads/ 即应提前结束,无需读完后续 pull/tags+ payload.extend_from_slice(&pkt_line(+ format!("{sha_main} refs/pull/1/head\n").as_bytes(),+ ));+ payload.extend_from_slice(&pkt_line(b"not-reached-after-pull"));++ // HEAD / 空串直接取 symref 默认分支,首行即可命中并标记 from_head_symref = true+ assert_eq!(+ SkillService::parse_git_info_refs(&payload, "HEAD", false),+ GitRefParseOutcome::Complete(Some(ProbedGitRef {+ branch: "master".to_string(),+ commit_sha: sha_master.to_string(),+ from_head_symref: true,+ }))+ );+ assert_eq!(+ SkillService::parse_git_info_refs(&payload, "", false),+ GitRefParseOutcome::Complete(Some(ProbedGitRef {+ branch: "master".to_string(),+ commit_sha: sha_master.to_string(),+ from_head_symref: true,+ }))+ );+ // 显式分支命中即停+ assert_eq!(+ SkillService::parse_git_info_refs(&payload, "dev", false),+ GitRefParseOutcome::Complete(Some(ProbedGitRef {+ branch: "dev".to_string(),+ commit_sha: sha_dev.to_string(),+ from_head_symref: false,+ }))+ );+ // 配置 main 但仓库只有 master:越过 refs/heads/ 后回退到 master,不必等到 eof+ assert_eq!(+ SkillService::parse_git_info_refs(&payload, "main", false),+ GitRefParseOutcome::Complete(Some(ProbedGitRef {+ branch: "master".to_string(),+ commit_sha: sha_master.to_string(),+ from_head_symref: false,+ }))+ );+ // 非法 pkt-line(如 HTML 登录页)立判 Invalid+ assert_eq!(+ SkillService::parse_git_info_refs(b"<!DOCTYPE html>", "main", true),+ GitRefParseOutcome::Invalid+ );+ // 未读到 refs/heads/ 结束且未到 eof 时继续等下一块(即便落在完整 pkt-line 边界,+ // 用于 512 KiB 上限截断时返回 NeedMore 触发回退而非误判 EOF)+ let mut partial = pkt_line(b"# service=git-upload-pack\n");+ partial.extend_from_slice(b"0000");+ partial.extend_from_slice(&pkt_line(+ format!("{sha_master} refs/heads/master\n").as_bytes(),+ ));+ assert_eq!(+ SkillService::parse_git_info_refs(&partial, "main", false),+ GitRefParseOutcome::NeedMore+ );++ // 显式分支(非哨兵 HEAD/空串)在无 main/master 时不得回退到 HEAD symref,+ // 保持与 try_repo_branches / countRepoSkills 一致+ let mut develop_only = pkt_line(b"# service=git-upload-pack\n");+ develop_only.extend_from_slice(b"0000");+ develop_only.extend_from_slice(&pkt_line(+ format!("{sha_dev} HEAD\0symref=HEAD:refs/heads/develop\n").as_bytes(),+ ));+ develop_only.extend_from_slice(&pkt_line(+ format!("{sha_dev} refs/heads/develop\n").as_bytes(),+ ));+ assert_eq!(+ SkillService::parse_git_info_refs(&develop_only, "main", true),+ GitRefParseOutcome::Complete(None)+ );+ assert_eq!(+ SkillService::parse_git_info_refs(&develop_only, "HEAD", true),+ GitRefParseOutcome::Complete(Some(ProbedGitRef {+ branch: "develop".to_string(),+ commit_sha: sha_dev.to_string(),+ from_head_symref: true,+ }))+ );+}++#[test]+fn build_git_info_refs_and_commit_archive_urls_validate_host_and_sha() {+ let sha = "1111111111111111111111111111111111111111";+ let gh = branch_fallback_repo("HEAD");+ assert_eq!(+ SkillService::build_git_info_refs_url(&gh).unwrap(),+ "https://github.com/acme/skills.git/info/refs?service=git-upload-pack"+ );+ assert_eq!(+ SkillService::build_commit_archive_url(&gh, RepoPlatform::GitHub, sha, false).unwrap(),+ format!("https://github.com/acme/skills/archive/{sha}.zip")+ );+ assert_eq!(+ SkillService::build_commit_archive_url(&gh, RepoPlatform::GitHub, sha, true).unwrap(),+ format!("https://api.github.com/repos/acme/skills/zipball/{sha}")+ );+ assert!(+ SkillService::build_commit_archive_url(&gh, RepoPlatform::GitHub, "not-a-sha", false)+ .is_err()+ );++ let gitlab = gitlab_repo("gitlab.example.com:8443", "group/sub", "skills", "main");+ assert_eq!(+ SkillService::build_git_info_refs_url(&gitlab).unwrap(),+ "https://gitlab.example.com:8443/group/sub/skills.git/info/refs?service=git-upload-pack"+ );+ assert_eq!(+ SkillService::build_commit_archive_url(&gitlab, RepoPlatform::GitLab, sha, false).unwrap(),+ format!("https://gitlab.example.com:8443/api/v4/projects/group%2Fsub%2Fskills/repository/archive.zip?sha={sha}")+ );+ assert!(SkillService::build_git_info_refs_url(&repo("bad owner!", "skills", true)).is_err());+}++#[test]+fn scan_skills_from_archive_reads_only_skill_md_and_respects_nesting_and_symlinks() {+ use std::io::Write;+ use zip::write::SimpleFileOptions;++ let mut buf = Vec::new();+ {+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));+ let opts = SimpleFileOptions::default();++ zip.start_file("repo-main/README.md", opts).unwrap();+ zip.write_all(b"ignored").unwrap();++ // 正常技能+ zip.start_file("repo-main/skills/alpha/SKILL.md", opts)+ .unwrap();+ zip.write_all(b"---\nname: Alpha\ndescription: top\n---\n")+ .unwrap();+ // 父目录已有 SKILL.md,子目录里的 SKILL.md 必须被忽略(与 scan_dir_recursive 一致)+ zip.start_file("repo-main/skills/alpha/nested/SKILL.md", opts)+ .unwrap();+ zip.write_all(b"---\nname: Nested\n---\n").unwrap();+ // 同安装名更深路径会被 keep_one_per_install_name 去重+ zip.start_file("repo-main/plugins/p/skills/alpha/SKILL.md", opts)+ .unwrap();+ zip.write_all(b"---\nname: Alpha Dup\n---\n").unwrap();+ // 越界条目必须跳过+ zip.start_file("repo-main/../evil/SKILL.md", opts).unwrap();+ zip.write_all(b"---\nname: Evil\n---\n").unwrap();+ // 指向归档内文件的 symlink SKILL.md+ zip.add_symlink(+ "repo-main/skills/linked/SKILL.md",+ "../alpha/SKILL.md",+ opts,+ )+ .unwrap();+ // 指向技能目录的 symlink(不同安装名),必须照常发现+ zip.add_symlink("repo-main/skills/dir-alias", "alpha", opts)+ .unwrap();+ // 包含自身的目录 symlink 与越出归档根的 symlink 必须跳过+ zip.add_symlink("repo-main/skills/loop", "..", opts)+ .unwrap();+ zip.add_symlink(+ "repo-main/skills/escape/SKILL.md",+ "../../../etc/passwd",+ opts,+ )+ .unwrap();++ zip.finish().unwrap();+ }++ let r = branch_fallback_repo("main");+ let skills =+ SkillService::scan_skills_from_archive(std::io::Cursor::new(buf), &r, RepoPlatform::GitHub)+ .expect("scan archive");++ let dirs: Vec<&str> = skills.iter().map(|s| s.directory.as_str()).collect();+ assert_eq!(+ dirs,+ vec!["skills/alpha", "skills/dir-alias", "skills/linked"]+ );+ assert_eq!(skills[0].name, "Alpha");+ assert_eq!(+ skills[0].readme_url.as_deref(),+ Some("https://github.com/acme/skills/blob/main/skills/alpha/SKILL.md")+ );+ assert_eq!(+ skills[1].readme_url.as_deref(),+ Some("https://github.com/acme/skills/blob/main/skills/dir-alias/SKILL.md")+ );+ assert_eq!(skills[2].name, "Alpha");+}++#[test]+fn scan_skills_from_archive_preserves_chained_file_and_directory_links() {+ use std::io::Write;+ use zip::write::SimpleFileOptions;++ let mut buf = Vec::new();+ {+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));+ let opts = SimpleFileOptions::default();+ zip.start_file("repo-main/docs/template.md", opts).unwrap();+ zip.write_all(b"---\nname: Shared\ndescription: linked\n---\n")+ .unwrap();+ zip.start_file("repo-main/skills/base/script.py", opts)+ .unwrap();+ zip.write_all(b"pass\n").unwrap();+ zip.add_symlink("repo-main/docs/shared.md", "template.md", opts)+ .unwrap();+ zip.add_symlink(+ "repo-main/skills/base/SKILL.md",+ "../../docs/shared.md",+ opts,+ )+ .unwrap();+ zip.add_symlink("repo-main/skills/alias", "base", opts)+ .unwrap();+ zip.add_symlink("repo-main/skills/another", "alias", opts)+ .unwrap();+ zip.finish().unwrap();+ }++ let repo = branch_fallback_repo("main");+ let skills = SkillService::scan_skills_from_archive(+ std::io::Cursor::new(&buf),+ &repo,+ RepoPlatform::GitHub,+ )+ .unwrap();+ let dirs: Vec<_> = skills+ .iter()+ .map(|skill| skill.directory.as_str())+ .collect();+ assert_eq!(dirs, ["skills/alias", "skills/another", "skills/base"]);+ assert!(skills.iter().all(|skill| skill.name == "Shared"));++ // 与安装时实际解压并物化链接的结果对照,避免发现列表遗漏可安装的技能。+ let unpacked = tempdir().unwrap();+ SkillService::extract_repo_archive(+ SkillService::open_downloaded_archive(std::io::Cursor::new(&buf)).unwrap(),+ unpacked.path(),+ )+ .unwrap();+ let mut extracted = Vec::new();+ SkillService::new()+ .scan_dir_recursive(unpacked.path(), unpacked.path(), &repo, &mut extracted)+ .unwrap();+ SkillService::keep_one_per_install_name(&mut extracted);+ assert_eq!(+ dirs,+ extracted+ .iter()+ .map(|skill| skill.directory.as_str())+ .collect::<Vec<_>>()+ );+}++#[test]+fn scan_skills_from_archive_skips_link_cycles_without_losing_valid_skills() {+ use std::io::Write;+ use zip::write::SimpleFileOptions;++ let mut buf = Vec::new();+ {+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));+ let opts = SimpleFileOptions::default();+ zip.start_file("repo-main/a/valid/SKILL.md", opts).unwrap();+ zip.write_all(b"---\nname: Valid\n---\n").unwrap();+ zip.add_symlink("repo-main/b/back", "../a", opts).unwrap();+ zip.add_symlink("repo-main/a/forward", "../b", opts)+ .unwrap();+ zip.add_symlink("repo-main/cycle/SKILL.md", "loop.md", opts)+ .unwrap();+ zip.add_symlink("repo-main/cycle/loop.md", "SKILL.md", opts)+ .unwrap();+ zip.add_symlink("repo-main/escape/SKILL.md", "../outside.md", opts)+ .unwrap();+ zip.add_symlink("repo-main/outside.md", "../secret.md", opts)+ .unwrap();+ zip.finish().unwrap();+ }+ let skills = SkillService::scan_skills_from_archive(+ std::io::Cursor::new(buf),+ &branch_fallback_repo("main"),+ RepoPlatform::GitHub,+ )+ .unwrap();+ assert_eq!(skills.len(), 1);+ assert_eq!(skills[0].directory, "a/valid");+}++#[test]+fn scan_skills_from_archive_bounds_metadata_expanded_through_aliases() {+ use std::io::Write;+ use zip::write::SimpleFileOptions;++ let mut buf = Vec::new();+ {+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));+ let opts = SimpleFileOptions::default();+ zip.start_file("repo-main/base/SKILL.md", opts).unwrap();+ zip.write_all(+ format!(+ "---\nname: Base\ndescription: {}\n---\n",+ "x".repeat(100 * 1024)+ )+ .as_bytes(),+ )+ .unwrap();+ for i in 0..90 {+ zip.add_symlink(format!("repo-main/alias{i}"), "base", opts)+ .unwrap();+ }+ zip.finish().unwrap();+ }+ let error = SkillService::scan_skills_from_archive(+ std::io::Cursor::new(buf),+ &branch_fallback_repo("main"),+ RepoPlatform::GitHub,+ )+ .unwrap_err();+ assert!(error.to_string().contains("ARCHIVE_TOO_LARGE"));+}++#[test]+fn scan_skills_from_archive_enforces_cumulative_metadata_budget() {+ use std::io::Write;+ use zip::write::SimpleFileOptions;++ // 单份 description 约 100 KiB,重复 90 份超过 8 MiB 元数据预算但仍远小于单文件与总解压上限+ let desc = "x".repeat(100 * 1024);+ let body = format!("---\nname: big\ndescription: {desc}\n---\n");+ let mut buf = Vec::new();+ {+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));+ let opts = SimpleFileOptions::default();+ for i in 0..90 {+ zip.start_file(format!("repo-main/skills/s{i}/SKILL.md"), opts)+ .unwrap();+ zip.write_all(body.as_bytes()).unwrap();+ }+ zip.finish().unwrap();+ }++ let r = branch_fallback_repo("main");+ let err =+ SkillService::scan_skills_from_archive(std::io::Cursor::new(buf), &r, RepoPlatform::GitHub)+ .unwrap_err();+ assert!(+ err.to_string().contains("ARCHIVE_TOO_LARGE"),+ "expected ARCHIVE_TOO_LARGE, got: {err}"+ );+}++#[tokio::test]+async fn persist_resolved_branch_guards_host_branch_and_symref_provenance() {+ let remote = tempdir().expect("remote repo");+ write_skill(&remote.path().join("pdf"), "pdf");+ let db = Database::memory().expect("memory db");+ let orig = SkillRepo {+ host: "old.example.com".to_string(),+ owner: "team".to_string(),+ name: "skills".to_string(),+ branch: "HEAD".to_string(),+ enabled: true,+ };+ db.save_skill_repo(&orig).unwrap();++ // 1. 仅走本地回退(非 symref)时不永久改写 HEAD+ let service = SkillService {+ repo_fixture: Some(remote.path().to_path_buf()),+ ..SkillService::new()+ };+ let report = service+ .discover_available_for_db(&db, false)+ .await+ .expect("discover for db");+ assert_eq!(report.skills.len(), 1);+ assert_eq!(db.get_skill_repos().unwrap()[0].branch, "HEAD");++ // 2. 同名仓库已被替换到另一主机时,旧主机的 symref 解析结果不得改写新主机+ let replaced = SkillRepo {+ host: "new.example.com".to_string(),+ ..orig.clone()+ };+ db.save_skill_repo(&replaced).unwrap();+ SkillService::persist_resolved_branch(&db, &orig, "old-default");+ let current = &db.get_skill_repos().unwrap()[0];+ assert_eq!(current.host, "new.example.com");+ assert_eq!(current.branch, "HEAD");++ // 3. 主机、原始哨兵分支与启用状态一致时,回写成功+ SkillService::persist_resolved_branch(&db, &replaced, "develop");+ assert_eq!(db.get_skill_repos().unwrap()[0].branch, "develop");+}++#[test]+#[serial_test::serial]+fn discovery_disk_cache_round_trips_and_scrubs_on_token_change() {+ let home = tempdir().expect("home");+ let _home = TestHomeGuard::set(home.path());+ let target = gitlab_repo("git.example.com", "team", "skills", "main");+ let other = branch_fallback_repo("main");+ let sample_skill = DiscoverableSkill {+ key: "team/skills:demo".to_string(),+ name: "demo".to_string(),+ description: "desc".to_string(),+ directory: "demo".to_string(),+ readme_url: None,+ repo_host: "git.example.com".to_string(),+ repo_owner: "team".to_string(),+ repo_name: "skills".to_string(),+ repo_branch: "main".to_string(),+ };++ let writer = SkillService::new();+ let epoch = writer.credential_epoch.load(Ordering::SeqCst);+ writer.store_discovery_cache(+ &target,+ Instant::now(),+ epoch,+ Some("a".repeat(40)),+ "main".to_string(),+ vec![sample_skill.clone()],+ true,+ false,+ );+ writer.store_discovery_cache(+ &other,+ Instant::now(),+ epoch,+ Some("b".repeat(40)),+ "main".to_string(),+ Vec::new(),+ true,+ false,+ );++ // 模拟重启:新实例从磁盘载入缓存,commit_sha 与技能列表保留+ let reader = SkillService::new();+ reader.ensure_discovery_cache_loaded();+ {+ let cache = reader.discovery_cache.lock_recover();+ let loaded = cache+ .get(&SkillService::discovery_cache_key(&target))+ .expect("persisted entry");+ assert_eq!(loaded.commit_sha.as_deref(), Some("a".repeat(40).as_str()));+ assert_eq!(loaded.skills.len(), 1);+ assert_eq!(loaded.skills[0].name, "demo");+ }++ // 旧扫描版本可能遗漏链接技能;即使远端 SHA 未变,下次发现也必须重新扫描。+ let path = SkillService::discovery_cache_path();+ let mut entries: Vec<serde_json::Value> =+ serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();+ for entry in &mut entries {+ entry.as_object_mut().unwrap().remove("scan_version");+ }+ fs::write(&path, serde_json::to_vec(&entries).unwrap()).unwrap();+ let reader = SkillService::new();+ reader.ensure_discovery_cache_loaded();+ assert!(reader+ .discovery_cache+ .lock_recover()+ .values()+ .all(|entry| entry.commit_sha.is_none()));++ // 旧版缓存仍须参与令牌清理,不能因版本失效而将私有元数据遗留在磁盘。+ reader.forget_platform("git.example.com");+ let after = SkillService::new();+ after.ensure_discovery_cache_loaded();+ let cache = after.discovery_cache.lock_recover();+ assert!(!cache.contains_key(&SkillService::discovery_cache_key(&target)));+ assert!(cache.contains_key(&SkillService::discovery_cache_key(&other)));+}+#[tokio::test]#[serial_test::serial]async fn check_updates_report_lists_unreadable_repos() {diff --git a/src/components/skills/RepoManagerPanel.tsx b/src/components/skills/RepoManagerPanel.tsxindex f498edd1c..4abf09c59 100644--- a/src/components/skills/RepoManagerPanel.tsx+++ b/src/components/skills/RepoManagerPanel.tsx@@ -68,16 +68,47 @@ function resolvableBranches(branch: string | undefined): string[] {return branches;}+function isDefaultBranchSentinel(branch: string | undefined): boolean {+ const trimmed = branch?.trim() ?? "";+ return !trimmed || trimmed.toUpperCase() === "HEAD";+}++function sameRepoOrigin(skill: DiscoverableSkill, repo: SkillRepo): boolean {+ return (+ (skill.repoHost || GITHUB_HOST) === (repo.host || GITHUB_HOST) &&+ skill.repoOwner === repo.owner &&+ skill.repoName === repo.name+ );+}+export function countRepoSkills(skills: DiscoverableSkill[], repo: SkillRepo) {+ if (isDefaultBranchSentinel(repo.branch)) {+ return skills.filter((skill) => sameRepoOrigin(skill, repo)).length;+ }const branches = resolvableBranches(repo.branch);return skills.filter((skill) =>- skill.repoOwner === repo.owner &&- skill.repoName === repo.name &&+ sameRepoOrigin(skill, repo) &&branches.includes(skill.repoBranch || "main"),).length;}+/** 展示用分支名:存量哨兵值 HEAD / 空串优先显示发现结果里的真实分支。 */+export function displayRepoBranch(+ skills: DiscoverableSkill[],+ repo: SkillRepo,+): string {+ const configured = repo.branch?.trim();+ if (configured && configured.toUpperCase() !== "HEAD") return configured;+ const resolved = skills.find(+ (skill) =>+ sameRepoOrigin(skill, repo) &&+ skill.repoBranch &&+ skill.repoBranch.toUpperCase() !== "HEAD",+ )?.repoBranch;+ return resolved || "main";+}+/** 仓库管理(右侧抽屉,宽 420):添加、停用、删除 Skill 仓库。 */export function RepoManagerPanel({repos,@@ -260,7 +291,7 @@ export function RepoManagerPanel({{repo.host && repo.host !== GITHUB_HOST? `${repo.host} · `: ""}- {repo.branch || "main"}+ {displayRepoBranch(skills, repo)}{" · "}{!repo.enabled ? (t("skillsPage.repos.disabled")diff --git a/src/components/skills/SkillsPage.tsx b/src/components/skills/SkillsPage.tsxindex 5d7054be2..872522ee6 100644--- a/src/components/skills/SkillsPage.tsx+++ b/src/components/skills/SkillsPage.tsx@@ -48,7 +48,7 @@ import {import { cn } from "@/lib/utils";import { MatrixSearch } from "@/components/mcp/AppMatrix";import { CHECKBOX_CLASS } from "@/components/mcp/formBits";-import { countRepoSkills } from "./RepoManagerPanel";+import { countRepoSkills, displayRepoBranch } from "./RepoManagerPanel";import { describeRepoFailures, repoFailureKey } from "./repoFailures";import { GITHUB_HOST, repoWebUrl } from "./repoUrl";import { APP_IDS_WITH } from "@/config/appSpecs";@@ -93,7 +93,7 @@ export function useSkillRepoActions() {t("skills.repo.addSuccess", {owner: repo.owner,name: repo.name,- count: countRepoSkills(discovery?.skills ?? [], repo),+ count: discovery?.skills.length ?? 0,}),{ closeButton: true },);@@ -1063,7 +1063,7 @@ function RepoPopover({{id}</span><span className="shrink-0 text-caption text-fg-3">- {repo.branch || "main"}+ {displayRepoBranch(discoverable, repo)}</span>{failure ? (<spandiff --git a/src/hooks/useSkills.helpers.ts b/src/hooks/useSkills.helpers.tsindex b438cfcdd..1996e1939 100644--- a/src/hooks/useSkills.helpers.ts+++ b/src/hooks/useSkills.helpers.ts@@ -1,4 +1,23 @@-import type { InstalledSkill, SkillDiscoveryResult } from "@/lib/api/skills";+import type {+ InstalledSkill,+ SkillDiscoveryResult,+ SkillRepo,+} from "@/lib/api/skills";++/** 仓库配置也可能被数据库恢复或云同步替换,不能只靠本页的 mutation 使缓存失效。 */+export function skillRepoConfigKey(repos: SkillRepo[]): string {+ return JSON.stringify(+ repos+ .map((repo) => [+ repo.host || "github.com",+ repo.owner,+ repo.name,+ repo.branch,+ repo.enabled,+ ])+ .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),+ );+}/*** 合并本次导入结果到已安装缓存,按 id 去重。diff --git a/src/hooks/useSkills.ts b/src/hooks/useSkills.tsindex 3e09bc56e..7a0341522 100644--- a/src/hooks/useSkills.ts+++ b/src/hooks/useSkills.ts@@ -22,6 +22,7 @@ import type { AppId } from "@/lib/api/types";import {mergeImportedSkills,replaceRepoDiscovery,+ skillRepoConfigKey,} from "@/hooks/useSkills.helpers";import { readLocalCache, writeLocalCache } from "@/lib/localCache";import { runSequentialBulkAction } from "@/lib/utils/sequentialBulkAction";@@ -92,46 +93,72 @@ export function useDeleteSkillBackup() {/*** 发现可安装的 Skills(从仓库获取)- * 使用 staleTime: Infinity 和 placeholderData: keepPreviousData- * 实现首次进入使用缓存,只有刷新时才重新获取+ * 先显示本地缓存;挂载时只比对本地仓库配置,配置未变时不重新访问远端仓库。*/-// 发现要从 GitHub 下载每个仓库,很慢:上次的结果存在本地,打开时先显示,-// 每次启动只在后台重新拉一次(之后同一次运行里不再自动拉,手动刷新照常)const DISCOVER_CACHE_KEY = "skills.discoverable.v1";const DISCOVERABLE_QUERY_KEY = ["skills", "discoverable"];-let discoverRevalidated = false;+const DEFAULT_REPO_HOST = "github.com";+type CachedSkillDiscovery = SkillDiscoveryResult & { repoConfig?: string };+// 导入本地 Skill 或增删仓库令牌后置位:下一次挂载发现列表时拉一次最新结果+let discoverNeedsRefresh = false;// 下一次发现绕过后端按仓库的缓存(只有手动刷新会置位)let discoverForceNext = false;-// 按仓库改过缓存就加一:被取消的旧请求晚到时不能再覆盖本地缓存+// 按仓库改过缓存或变更令牌就加一:被取消的旧请求晚到时不能再覆盖本地缓存let discoverGeneration = 0;+// 凭据变更代次:防止令牌删改前发起的单仓发现把旧身份读到的私有结果写回缓存+let discoverTokenEpoch = 0;++function syncSentinelRepoBranches(queryClient: QueryClient) {+ const repos = queryClient.getQueryData<SkillRepo[]>(["skills", "repos"]);+ if (+ repos?.some((repo) => !repo.branch || repo.branch.toUpperCase() === "HEAD")+ ) {+ void queryClient.invalidateQueries({ queryKey: ["skills", "repos"] });+ }+}-const discoverableQuery = {- queryKey: DISCOVERABLE_QUERY_KEY,- queryFn: async () => {- const force = discoverForceNext;- discoverForceNext = false;- const generation = discoverGeneration;- const result = await skillsApi.discoverAvailable(force);- if (generation === discoverGeneration) {- discoverRevalidated = true;- writeLocalCache(DISCOVER_CACHE_KEY, result);- }- return result;- },- staleTime: Infinity,- initialData: () => readLocalCache<SkillDiscoveryResult>(DISCOVER_CACHE_KEY),- // 本地缓存是旧数据:时间记成 0,配合 refetchOnMount 在后台刷新- initialDataUpdatedAt: 0,- refetchOnMount: () => (discoverRevalidated ? false : ("always" as const)),- placeholderData: keepPreviousData,-};+function useDiscoverableQuery<T>(select: (result: SkillDiscoveryResult) => T) {+ const queryClient = useQueryClient();+ return useQuery({+ queryKey: DISCOVERABLE_QUERY_KEY,+ queryFn: async ({ signal }) => {+ const force = discoverForceNext;+ discoverForceNext = false;+ const generation = discoverGeneration;+ const repoConfig = skillRepoConfigKey(await skillsApi.getRepos());+ signal.throwIfAborted();+ const cached = readLocalCache<CachedSkillDiscovery>(DISCOVER_CACHE_KEY);+ if (+ !force &&+ !discoverNeedsRefresh &&+ cached?.repoConfig === repoConfig+ ) {+ return cached;+ }+ const result = await skillsApi.discoverAvailable(force);+ if (!signal.aborted && generation === discoverGeneration) {+ discoverNeedsRefresh = false;+ writeLocalCache(DISCOVER_CACHE_KEY, { ...result, repoConfig });+ }+ syncSentinelRepoBranches(queryClient);+ return result;+ },+ staleTime: Infinity,+ initialData: () => readLocalCache<SkillDiscoveryResult>(DISCOVER_CACHE_KEY),+ // 恢复数据库时查询可能尚未创建,invalidateQueries 无法作废 localStorage。+ // 每次挂载都检查本地仓库表,仅配置变化(或显式失效)才执行远端发现。+ refetchOnMount: "always",+ placeholderData: keepPreviousData,+ select,+ });+}export function useDiscoverableSkills() {- return useQuery({ ...discoverableQuery, select: selectDiscoveredSkills });+ return useDiscoverableQuery(selectDiscoveredSkills);}/**- * 手动刷新发现列表:绕过后端缓存,所有启用的仓库都重新下载+ * 手动刷新发现列表:绕过缓存 TTL,后端仍按 commit SHA 跳过未变化的归档。*/export function useRefreshDiscoverableSkills() {const queryClient = useQueryClient();@@ -175,16 +202,22 @@ async function patchRepoDiscovery(}// 同一仓库的增删改各记一个序号:单仓库发现要下载归档,期间如果又停用 /-// 删除 / 改了分支,晚到的旧结果不能再写回缓存+// 删除 / 改了分支或改了令牌,晚到的旧结果不能再写回缓存const repoMutationSeq = new Map<string, number>();const nextRepoMutation = (repo: { owner: string; name: string }) => {const key = `${repo.owner}/${repo.name}`;const seq = (repoMutationSeq.get(key) ?? 0) + 1;repoMutationSeq.set(key, seq);- return { key, seq };+ return { key, seq, tokenEpoch: discoverTokenEpoch };};-const isLatestRepoMutation = (ctx?: { key: string; seq: number }) =>- !!ctx && repoMutationSeq.get(ctx.key) === ctx.seq;+const isLatestRepoMutation = (ctx?: {+ key: string;+ seq: number;+ tokenEpoch: number;+}) =>+ !!ctx &&+ repoMutationSeq.get(ctx.key) === ctx.seq &&+ ctx.tokenEpoch === discoverTokenEpoch;const selectDiscoveredSkills = (result: SkillDiscoveryResult) => result.skills;const selectDiscoveryFailures = (result: SkillDiscoveryResult) =>@@ -194,7 +227,7 @@ const selectDiscoveryFailures = (result: SkillDiscoveryResult) =>* 发现时没读到的仓库(和 useDiscoverableSkills 共用一次请求)*/export function useDiscoverableSkillsFailures() {- return useQuery({ ...discoverableQuery, select: selectDiscoveryFailures });+ return useDiscoverableQuery(selectDiscoveryFailures);}/**@@ -390,10 +423,9 @@ export function useImportSkillsFromApps() {onSettled: () => {void queryClient.invalidateQueries({ queryKey: ["skills", "repos"] });// 导入可能新增了来源仓库。没人在看发现列表时 invalidate 不会马上重拉,- // 而 refetchOnMount 在本次运行验证过一次后就是 false,下次打开还是旧- // 结果(新仓库显示 0 个,#9273):清掉标记,下次挂载时重新发现。+ // 置位标记让下次挂载时重新发现一次(新仓库不再显示 0 个,#9273)。// 代次加一:导入前开始的整体发现读的是旧仓库表,晚到不能写回本地缓存- discoverRevalidated = false;+ discoverNeedsRefresh = true;discoverGeneration += 1;void queryClient.invalidateQueries({queryKey: ["skills", "discoverable"],@@ -431,7 +463,11 @@ export function useAddSkillRepo() {void queryClient.invalidateQueries({ queryKey: ["skills", "repos"] });if (!repo.enabled) return { skills: [], failures: [] };try {- return await skillsApi.discoverRepo(repo.owner, repo.name);+ const result = await skillsApi.discoverRepo(repo.owner, repo.name);+ if (!repo.branch || repo.branch.toUpperCase() === "HEAD") {+ void queryClient.invalidateQueries({ queryKey: ["skills", "repos"] });+ }+ return result;} catch (error) {console.error("[useAddSkillRepo] discover repo failed", error);return null;@@ -471,7 +507,30 @@ export function useSkillRepoTokens() {*/export function useSkillRepoTokenActions() {const queryClient = useQueryClient();- const onSuccess = () => {+ const onSuccess = async (host: string) => {+ discoverNeedsRefresh = true;+ discoverGeneration += 1;+ discoverTokenEpoch += 1;+ await queryClient.cancelQueries({+ queryKey: DISCOVERABLE_QUERY_KEY,+ exact: true,+ });+ const dropHost = (result: SkillDiscoveryResult): SkillDiscoveryResult => ({+ skills: result.skills.filter(+ (skill) => (skill.repoHost || DEFAULT_REPO_HOST) !== host,+ ),+ failures: result.failures,+ });+ const scrubbed = queryClient.setQueryData<SkillDiscoveryResult>(+ DISCOVERABLE_QUERY_KEY,+ (old) => (old ? dropHost(old) : old),+ );+ if (scrubbed) {+ writeLocalCache(DISCOVER_CACHE_KEY, scrubbed);+ } else {+ const stored = readLocalCache<SkillDiscoveryResult>(DISCOVER_CACHE_KEY);+ if (stored) writeLocalCache(DISCOVER_CACHE_KEY, dropHost(stored));+ }void queryClient.invalidateQueries({ queryKey: REPO_TOKENS_QUERY_KEY });void queryClient.invalidateQueries({queryKey: DISCOVERABLE_QUERY_KEY,diff --git a/tests/components/RepoManagerPanelCount.test.tsx b/tests/components/RepoManagerPanelCount.test.tsxindex b908804f6..d0c8d7602 100644--- a/tests/components/RepoManagerPanelCount.test.tsx+++ b/tests/components/RepoManagerPanelCount.test.tsx@@ -33,6 +33,8 @@ describe("countRepoSkills", () => {expect(countRepoSkills(skills, repo("head"))).toBe(2);expect(countRepoSkills(skills, repo(""))).toBe(2);expect(countRepoSkills([skill("master")], repo("HEAD"))).toBe(1);+ // info/refs 的 symref=HEAD 可以解析出非 main/master 的默认分支+ expect(countRepoSkills([skill("develop")], repo("HEAD"))).toBe(1);});it("counts skills when the configured branch fell back to master", () => {@@ -40,7 +42,6 @@ describe("countRepoSkills", () => {});it("does not count skills from a branch discovery could not have used", () => {- expect(countRepoSkills([skill("feature")], repo("HEAD"))).toBe(0);expect(countRepoSkills([skill("dev")], repo("main"))).toBe(0);expect(countRepoSkills([skill("dev")], repo("dev"))).toBe(1);});diff --git a/tests/components/skillRepoUrl.test.tsx b/tests/components/skillRepoUrl.test.tsxindex c9d8bef81..a80da2176 100644--- a/tests/components/skillRepoUrl.test.tsx+++ b/tests/components/skillRepoUrl.test.tsx@@ -1,6 +1,10 @@import { fireEvent, render, screen, waitFor } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";-import { RepoManagerPanel } from "@/components/skills/RepoManagerPanel";+import {+ countRepoSkills,+ displayRepoBranch,+ RepoManagerPanel,+} from "@/components/skills/RepoManagerPanel";import {isInsecureRepoUrl,parseRepoUrl,@@ -205,3 +209,86 @@ describe("RepoManagerPanel add form", () => {expect(onAdd).not.toHaveBeenCalled();});});++describe("displayRepoBranch", () => {+ it("replaces HEAD and empty sentinels with the resolved discovered branch", () => {+ const skills = [+ {+ key: "alibaba/open-code-review:review",+ name: "review",+ description: "",+ directory: "review",+ repoOwner: "alibaba",+ repoName: "open-code-review",+ repoBranch: "master",+ },+ ];+ expect(+ displayRepoBranch(skills, {+ owner: "alibaba",+ name: "open-code-review",+ branch: "HEAD",+ enabled: true,+ }),+ ).toBe("master");+ expect(+ displayRepoBranch([], {+ owner: "vercel-labs",+ name: "skills",+ branch: "HEAD",+ enabled: true,+ }),+ ).toBe("main");+ expect(+ displayRepoBranch(skills, {+ owner: "alibaba",+ name: "open-code-review",+ branch: "release",+ enabled: true,+ }),+ ).toBe("release");+ });++ it("counts HEAD repos resolved to non-main/master branches and respects host", () => {+ const skills = [+ {+ key: "team/skills:a",+ name: "a",+ description: "",+ directory: "a",+ repoHost: "gitlab.example.com",+ repoOwner: "team",+ repoName: "skills",+ repoBranch: "develop",+ },+ {+ key: "team/skills:b",+ name: "b",+ description: "",+ directory: "b",+ repoHost: "github.com",+ repoOwner: "team",+ repoName: "skills",+ repoBranch: "main",+ },+ ];+ expect(+ countRepoSkills(skills, {+ host: "gitlab.example.com",+ owner: "team",+ name: "skills",+ branch: "HEAD",+ enabled: true,+ }),+ ).toBe(1);+ expect(+ displayRepoBranch(skills, {+ host: "gitlab.example.com",+ owner: "team",+ name: "skills",+ branch: "HEAD",+ enabled: true,+ }),+ ).toBe("develop");+ });+});diff --git a/tests/hooks/useImportSkillsFromApps.test.tsx b/tests/hooks/useImportSkillsFromApps.test.tsxindex 94b4d6f5f..a0c1c0824 100644--- a/tests/hooks/useImportSkillsFromApps.test.tsx+++ b/tests/hooks/useImportSkillsFromApps.test.tsx@@ -14,6 +14,7 @@ import type { DiscoverableSkill, InstalledSkill } from "@/lib/api/skills";const apiMocks = vi.hoisted(() => ({discoverAvailable: vi.fn(),+ getRepos: vi.fn().mockResolvedValue([]),importFromApps: vi.fn(),installFromZip: vi.fn(),installUnified: vi.fn(),diff --git a/tests/hooks/useSkillRepoDiscovery.test.tsx b/tests/hooks/useSkillRepoDiscovery.test.tsxindex 389dc1ee2..9c6e611f6 100644--- a/tests/hooks/useSkillRepoDiscovery.test.tsx+++ b/tests/hooks/useSkillRepoDiscovery.test.tsx@@ -2,12 +2,17 @@ import type { PropsWithChildren } from "react";import { act, renderHook } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { beforeEach, describe, expect, it, vi } from "vitest";-import { replaceRepoDiscovery } from "@/hooks/useSkills.helpers";+import {+ replaceRepoDiscovery,+ skillRepoConfigKey,+} from "@/hooks/useSkills.helpers";+import { useBackupManager } from "@/hooks/useBackupManager";import {useAddSkillRepo,useDiscoverableSkills,useRefreshDiscoverableSkills,useRemoveSkillRepo,+ useSkillRepoTokenActions,} from "@/hooks/useSkills";import type {DiscoverableSkill,@@ -20,11 +25,24 @@ const apiMocks = vi.hoisted(() => ({removeRepo: vi.fn(),discoverRepo: vi.fn(),discoverAvailable: vi.fn(),+ getRepos: vi.fn(),+ listDbBackups: vi.fn(),+ restoreDbBackup: vi.fn(),+ setRepoToken: vi.fn(),+ deleteRepoToken: vi.fn(),}));vi.mock("@/lib/api/skills", () => ({skillsApi: apiMocks,}));+vi.mock("@/lib/api", () => ({ backupsApi: apiMocks }));++beforeEach(() => {+ localStorage.clear();+ Object.values(apiMocks).forEach((mock) => mock.mockReset());+ apiMocks.getRepos.mockResolvedValue([]);+ apiMocks.listDbBackups.mockResolvedValue([]);+});const DISCOVERABLE = ["skills", "discoverable"];@@ -92,7 +110,6 @@ describe("replaceRepoDiscovery", () => {describe("repo mutations patch discovery instead of refetching every repo", () => {beforeEach(() => {- Object.values(apiMocks).forEach((mock) => mock.mockReset());apiMocks.addRepo.mockResolvedValue(true);apiMocks.removeRepo.mockResolvedValue(true);});@@ -168,7 +185,6 @@ describe("repo mutation races", () => {beforeEach(() => {// 前面的用例会把发现结果写进本地缓存,它会成为 initialDatalocalStorage.clear();- Object.values(apiMocks).forEach((mock) => mock.mockReset());apiMocks.addRepo.mockResolvedValue(true);apiMocks.removeRepo.mockResolvedValue(true);});@@ -257,24 +273,188 @@ describe("repo mutation races", () => {});describe("useRefreshDiscoverableSkills", () => {- it("asks the backend to bypass its per-repo cache", async () => {- apiMocks.discoverAvailable.mockResolvedValue({ skills: [], failures: [] });+ it("shows cached discovery without auto-refetching on mount, and refreshes on demand", async () => {+ const repos = [{ ...repoA, owner: "b", name: "two" }];+ apiMocks.getRepos.mockResolvedValue(repos);+ const cached: SkillDiscoveryResult = {+ skills: [skill("b", "two", "beta")],+ failures: [],+ };+ localStorage.setItem(+ "cc-switch-cache:skills.discoverable.v1",+ JSON.stringify({ ...cached, repoConfig: skillRepoConfigKey(repos) }),+ );+ apiMocks.discoverAvailable.mockResolvedValue({+ skills: [skill("a", "one", "alpha")],+ failures: [],+ });+const { queryClient, wrapper } = setup();- // 需要一个活跃的 observer,refetchQueries 才会真正发请求;先等挂载时的- // 首次发现结束,否则刷新会直接复用那次在飞的请求const discover = renderHook(() => useDiscoverableSkills(), { wrapper });++ expect(discover.result.current.data).toEqual(cached.skills);await vi.waitFor(() =>expect(discover.result.current.isFetching).toBe(false),);+ expect(apiMocks.getRepos).toHaveBeenCalledTimes(1);+ expect(apiMocks.discoverAvailable).not.toHaveBeenCalled();- const { result } = renderHook(() => useRefreshDiscoverableSkills(), {- wrapper,- });+ const { result: refresh } = renderHook(+ () => useRefreshDiscoverableSkills(),+ { wrapper },+ );await act(async () => {- await result.current();+ await refresh.current();});+ expect(apiMocks.discoverAvailable).toHaveBeenCalledTimes(1);expect(apiMocks.discoverAvailable).toHaveBeenLastCalledWith(true);queryClient.clear();});++ it("checks restored repository configuration before reusing a cache on first mount", async () => {+ localStorage.setItem(+ "cc-switch-cache:skills.discoverable.v1",+ JSON.stringify({+ skills: [skill("a", "one", "removed")],+ failures: [],+ repoConfig: skillRepoConfigKey([repoA]),+ }),+ );+ apiMocks.restoreDbBackup.mockResolvedValue("restored");+ apiMocks.discoverAvailable.mockResolvedValue({ skills: [], failures: [] });+ const { queryClient, wrapper } = setup();+ const backup = renderHook(() => useBackupManager(), { wrapper });+ await act(async () => {+ await backup.result.current.restore("without-repo-a.db");+ });+ expect(queryClient.getQueryData(DISCOVERABLE)).toBeUndefined();++ const discovery = renderHook(() => useDiscoverableSkills(), { wrapper });+ await vi.waitFor(() => expect(discovery.result.current.data).toEqual([]));+ expect(apiMocks.discoverAvailable).toHaveBeenCalledWith(false);+ queryClient.clear();+ });++ it.each([+ { ...repoA, enabled: false },+ { ...repoA, branch: "develop" },+ { ...repoA, host: "git.example.com" },+ ])(+ "refreshes when a synced repository configuration changes: %j",+ async (repo) => {+ localStorage.setItem(+ "cc-switch-cache:skills.discoverable.v1",+ JSON.stringify({+ skills: [skill("a", "one", "old")],+ failures: [],+ repoConfig: skillRepoConfigKey([repoA]),+ }),+ );+ apiMocks.getRepos.mockResolvedValue([repo]);+ apiMocks.discoverAvailable.mockResolvedValue({+ skills: [],+ failures: [],+ });+ const { queryClient, wrapper } = setup();+ await queryClient.invalidateQueries();+ const discovery = renderHook(() => useDiscoverableSkills(), { wrapper });+ await vi.waitFor(() => expect(discovery.result.current.data).toEqual([]));+ expect(apiMocks.discoverAvailable).toHaveBeenCalledTimes(1);+ queryClient.clear();+ },+ );++ it("revalidates legacy caches without a repository configuration", async () => {+ localStorage.setItem(+ "cc-switch-cache:skills.discoverable.v1",+ JSON.stringify({ skills: [skill("a", "one", "old")], failures: [] }),+ );+ apiMocks.discoverAvailable.mockResolvedValue({ skills: [], failures: [] });+ const { queryClient, wrapper } = setup();+ const discovery = renderHook(() => useDiscoverableSkills(), { wrapper });+ await vi.waitFor(() => expect(discovery.result.current.data).toEqual([]));+ expect(apiMocks.discoverAvailable).toHaveBeenCalledTimes(1);+ queryClient.clear();+ });++ it("invalidates repos when a HEAD repo is resolved during discovery", async () => {+ apiMocks.discoverAvailable.mockResolvedValue({+ skills: [skill("alibaba", "open-code-review", "review")],+ failures: [],+ });+ const { queryClient, wrapper } = setup();+ queryClient.setQueryData<SkillRepo[]>(+ ["skills", "repos"],+ [+ {+ owner: "alibaba",+ name: "open-code-review",+ branch: "HEAD",+ enabled: true,+ },+ ],+ );+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");++ renderHook(() => useDiscoverableSkills(), { wrapper });++ await vi.waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: ["skills", "repos"],+ }),+ );+ queryClient.clear();+ });++ it("drops stale in-flight discovery and scrubs localStorage when a token is deleted", async () => {+ let resolveStale!: (value: SkillDiscoveryResult) => void;+ apiMocks.discoverAvailable+ .mockReturnValueOnce(+ new Promise<SkillDiscoveryResult>((resolve) => {+ resolveStale = resolve;+ }),+ )+ .mockResolvedValue({+ skills: [skill("pub", "repo", "public-skill")],+ failures: [],+ });+ apiMocks.deleteRepoToken.mockResolvedValue("git.example.com");++ const { queryClient, wrapper } = setup();+ renderHook(() => useDiscoverableSkills(), { wrapper });+ await vi.waitFor(() =>+ expect(apiMocks.discoverAvailable).toHaveBeenCalledTimes(1),+ );++ const { result: tokenActions } = renderHook(+ () => useSkillRepoTokenActions(),+ { wrapper },+ );+ await act(async () => {+ await tokenActions.current.deleteToken("git.example.com");+ });++ // 删令牌前发出的旧请求晚到:不得写回 localStorage+ await act(async () => {+ resolveStale({+ skills: [+ {+ ...skill("priv", "repo", "secret-skill"),+ repoHost: "git.example.com",+ },+ ],+ failures: [],+ });+ });++ await vi.waitFor(() =>+ expect(apiMocks.discoverAvailable).toHaveBeenCalledTimes(2),+ );+ const persisted = JSON.parse(+ localStorage.getItem("cc-switch-cache:skills.discoverable.v1") ?? "{}",+ ) as SkillDiscoveryResult;+ expect(persisted.skills?.map((s) => s.name)).toEqual(["public-skill"]);+ queryClient.clear();+ });});