diff --git a/internal/server/agent_helpers.go b/internal/server/agent_helpers.go new file mode 100644 index 000000000..bdc73d224 --- /dev/null +++ b/internal/server/agent_helpers.go @@ -0,0 +1,57 @@ +package server + +import ( + "skillshare/internal/config" + "skillshare/internal/resource" +) + +// Kind constants for diff/sync operations. +const ( + kindSkill = "skill" + kindAgent = "agent" +) + +// discoverActiveAgents discovers agents from the given source directory, +// returning only non-disabled agents. Returns nil if source is empty. +func discoverActiveAgents(agentsSource string) []resource.DiscoveredResource { + if agentsSource == "" { + return nil + } + discovered, _ := resource.AgentKind{}.Discover(agentsSource) + return resource.ActiveAgents(discovered) +} + +// resolveAgentPath returns the expanded agent target path for a target, +// checking user config first, then builtin defaults. Returns "" if no path. +func resolveAgentPath(target config.TargetConfig, builtinAgents map[string]config.TargetConfig, name string) string { + if ac := target.AgentsConfig(); ac.Path != "" { + return config.ExpandPath(ac.Path) + } + if builtin, ok := builtinAgents[name]; ok { + return config.ExpandPath(builtin.Path) + } + return "" +} + +// builtinAgentTargets returns the builtin agent target map for the server's mode. +func (s *Server) builtinAgentTargets() map[string]config.TargetConfig { + if s.IsProjectMode() { + return config.ProjectAgentTargets() + } + return config.DefaultAgentTargets() +} + +// mergeAgentDiffItems appends agent diff items into the existing diffs slice, +// merging with an existing target entry or creating a new one. +func mergeAgentDiffItems(diffs []diffTarget, name string, items []diffItem) []diffTarget { + for i := range diffs { + if diffs[i].Target == name { + diffs[i].Items = append(diffs[i].Items, items...) + return diffs + } + } + return append(diffs, diffTarget{ + Target: name, + Items: items, + }) +} diff --git a/internal/server/handler_agent_diff.go b/internal/server/handler_agent_diff.go index de2d13223..efbdabe57 100644 --- a/internal/server/handler_agent_diff.go +++ b/internal/server/handler_agent_diff.go @@ -41,7 +41,7 @@ func computeAgentTargetDiff(targetDir string, agents []resource.DiscoveredResour Skill: flatName, Action: "link", Reason: "source only", - Kind: "agent", + Kind: kindAgent, }) continue } @@ -54,7 +54,7 @@ func computeAgentTargetDiff(targetDir string, agents []resource.DiscoveredResour Skill: flatName, Action: "update", Reason: "link target unreadable", - Kind: "agent", + Kind: kindAgent, }) continue } @@ -64,7 +64,7 @@ func computeAgentTargetDiff(targetDir string, agents []resource.DiscoveredResour Skill: flatName, Action: "update", Reason: "symlink points elsewhere", - Kind: "agent", + Kind: kindAgent, }) } // else: in sync, no item emitted @@ -82,14 +82,14 @@ func computeAgentTargetDiff(targetDir string, agents []resource.DiscoveredResour Skill: name, Action: "prune", Reason: "orphan symlink", - Kind: "agent", + Kind: kindAgent, }) } else { items = append(items, diffItem{ Skill: name, Action: "local", Reason: "local file", - Kind: "agent", + Kind: kindAgent, }) } } diff --git a/internal/server/handler_diff_stream.go b/internal/server/handler_diff_stream.go index 84de9b8c1..3b5da4733 100644 --- a/internal/server/handler_diff_stream.go +++ b/internal/server/handler_diff_stream.go @@ -7,7 +7,6 @@ import ( "path/filepath" "skillshare/internal/config" - "skillshare/internal/resource" ssync "skillshare/internal/sync" "skillshare/internal/utils" ) @@ -68,59 +67,21 @@ func (s *Server) handleDiffStream(w http.ResponseWriter, r *http.Request) { }) } - // Agent diffs — discover agents and compute per-target diffs - var agents []resource.DiscoveredResource - if agentsSource != "" { - discovered, _ := resource.AgentKind{}.Discover(agentsSource) - agents = resource.ActiveAgents(discovered) - } - - if len(agents) > 0 { - var builtinAgents map[string]config.TargetConfig - if s.IsProjectMode() { - builtinAgents = config.ProjectAgentTargets() - } else { - builtinAgents = config.DefaultAgentTargets() - } - + // Agent diffs + if agents := discoverActiveAgents(agentsSource); len(agents) > 0 { + builtinAgents := s.builtinAgentTargets() for name, target := range targets { select { case <-ctx.Done(): return default: } - - ac := target.AgentsConfig() - agentPath := ac.Path - if agentPath == "" { - if builtin, ok := builtinAgents[name]; ok { - agentPath = builtin.Path - } - } + agentPath := resolveAgentPath(target, builtinAgents, name) if agentPath == "" { continue } - agentPath = config.ExpandPath(agentPath) - - agentItems := computeAgentTargetDiff(agentPath, agents) - if len(agentItems) == 0 { - continue - } - - // Merge into existing diff for this target - merged := false - for i := range diffs { - if diffs[i].Target == name { - diffs[i].Items = append(diffs[i].Items, agentItems...) - merged = true - break - } - } - if !merged { - diffs = append(diffs, diffTarget{ - Target: name, - Items: agentItems, - }) + if items := computeAgentTargetDiff(agentPath, agents); len(items) > 0 { + diffs = mergeAgentDiffItems(diffs, name, items) } } } @@ -144,7 +105,7 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc if mode == "symlink" { status := ssync.CheckStatus(sc.Path, source) if status != ssync.StatusLinked { - dt.Items = append(dt.Items, diffItem{Skill: "(entire directory)", Action: "link", Reason: "source only", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: "(entire directory)", Action: "link", Reason: "source only", Kind: kindSkill}) } return dt } @@ -159,7 +120,7 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc TargetNaming: sc.TargetNaming, }, filtered) if err != nil { - dt.Items = append(dt.Items, diffItem{Skill: "(target naming)", Action: "skip", Reason: err.Error(), Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: "(target naming)", Action: "skip", Reason: err.Error(), Kind: kindSkill}) return dt } // Surface collision/validation stats so the UI can show why skills were skipped @@ -177,23 +138,23 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc if !isManaged { if info, statErr := os.Stat(targetSkillPath); statErr == nil { if info.IsDir() { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "skip", Reason: "local copy (sync --force to replace)", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "skip", Reason: "local copy (sync --force to replace)", Kind: kindSkill}) } else { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "target entry is not a directory", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "target entry is not a directory", Kind: kindSkill}) } } else if os.IsNotExist(statErr) { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "link", Reason: "source only", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "link", Reason: "source only", Kind: kindSkill}) } else { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "cannot access target entry", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "cannot access target entry", Kind: kindSkill}) } } else { targetInfo, statErr := os.Stat(targetSkillPath) if os.IsNotExist(statErr) { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "link", Reason: "missing (deleted from target)", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "link", Reason: "missing (deleted from target)", Kind: kindSkill}) } else if statErr != nil { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "cannot access target entry", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "cannot access target entry", Kind: kindSkill}) } else if !targetInfo.IsDir() { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "target entry is not a directory", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "target entry is not a directory", Kind: kindSkill}) } else { oldMtime := manifest.Mtimes[resolved.TargetName] currentMtime, mtimeErr := ssync.DirMaxMtime(skill.SourcePath) @@ -202,9 +163,9 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc } srcChecksum, checksumErr := ssync.DirChecksum(skill.SourcePath) if checksumErr != nil { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "cannot compute checksum", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "cannot compute checksum", Kind: kindSkill}) } else if srcChecksum != oldChecksum { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "content changed", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "content changed", Kind: kindSkill}) } } } @@ -214,7 +175,7 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc continue } if !validNames[managedName] { - dt.Items = append(dt.Items, diffItem{Skill: managedName, Action: "prune", Reason: "orphan copy", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: managedName, Action: "prune", Reason: "orphan copy", Kind: kindSkill}) } } return dt @@ -227,7 +188,7 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc _, err := os.Lstat(targetSkillPath) if err != nil { if os.IsNotExist(err) { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "link", Reason: "source only", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "link", Reason: "source only", Kind: kindSkill}) } continue } @@ -235,15 +196,15 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc if utils.IsSymlinkOrJunction(targetSkillPath) { absLink, linkErr := utils.ResolveLinkTarget(targetSkillPath) if linkErr != nil { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "link target unreadable", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "link target unreadable", Kind: kindSkill}) continue } absSource, _ := filepath.Abs(skill.SourcePath) if !utils.PathsEqual(absLink, absSource) { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "symlink points elsewhere", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "update", Reason: "symlink points elsewhere", Kind: kindSkill}) } } else { - dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "skip", Reason: "local copy (sync --force to replace)", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: resolved.TargetName, Action: "skip", Reason: "local copy (sync --force to replace)", Kind: kindSkill}) } } @@ -271,16 +232,16 @@ func (s *Server) computeTargetDiff(name string, target config.TargetConfig, disc } absSource, _ := filepath.Abs(source) if utils.PathHasPrefix(absLink, absSource+string(filepath.Separator)) { - dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "prune", Reason: "orphan symlink", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "prune", Reason: "orphan symlink", Kind: kindSkill}) } } else if info.IsDir() { if _, inManifest := manifest.Managed[eName]; inManifest { - dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "prune", Reason: "orphan managed directory (manifest)", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "prune", Reason: "orphan managed directory (manifest)", Kind: kindSkill}) } else { if resolution.Naming == "flat" && (utils.HasNestedSeparator(eName) || utils.IsTrackedRepoDir(eName)) { - dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "prune", Reason: "orphan managed directory", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "prune", Reason: "orphan managed directory", Kind: kindSkill}) } else { - dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "local", Reason: "local only", Kind: "skill"}) + dt.Items = append(dt.Items, diffItem{Skill: eName, Action: "local", Reason: "local only", Kind: kindSkill}) } } } diff --git a/internal/server/handler_sync.go b/internal/server/handler_sync.go index b5b4cd5e8..c7f63ff8e 100644 --- a/internal/server/handler_sync.go +++ b/internal/server/handler_sync.go @@ -7,7 +7,6 @@ import ( "time" "skillshare/internal/config" - "skillshare/internal/resource" "skillshare/internal/skillignore" ssync "skillshare/internal/sync" ) @@ -57,7 +56,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { // Default to non-dry-run, non-force, empty kind (both) } - if body.Kind != "" && body.Kind != "skill" && body.Kind != "agent" { + if body.Kind != "" && body.Kind != kindSkill && body.Kind != kindAgent { writeError(w, http.StatusBadRequest, "invalid kind: must be 'skill', 'agent', or empty") return } @@ -79,7 +78,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { var ignoreStats *skillignore.IgnoreStats // Skill sync (skip when kind == "agent") - if body.Kind != "agent" { + if body.Kind != kindAgent { var allSkills []ssync.DiscoveredSkill var err error allSkills, ignoreStats, err = ssync.DiscoverSourceSkillsWithStats(s.cfg.Source) @@ -174,83 +173,60 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { } // Agent sync (skip when kind == "skill") - if body.Kind != "skill" { + if body.Kind != kindSkill { agentsSource := s.agentsSource() - if agentsSource != "" { - agentDiscovered, _ := resource.AgentKind{}.Discover(agentsSource) - agents := resource.ActiveAgents(agentDiscovered) + if agents := discoverActiveAgents(agentsSource); len(agents) > 0 { + builtinAgents := s.builtinAgentTargets() - if len(agents) > 0 { - var builtinAgents map[string]config.TargetConfig - if s.IsProjectMode() { - builtinAgents = config.ProjectAgentTargets() - } else { - builtinAgents = config.DefaultAgentTargets() + for name, target := range s.cfg.Targets { + agentPath := resolveAgentPath(target, builtinAgents, name) + if agentPath == "" { + continue } - for name, target := range s.cfg.Targets { - ac := target.AgentsConfig() - agentPath := ac.Path - if agentPath == "" { - if builtin, ok := builtinAgents[name]; ok { - agentPath = builtin.Path - } - } - if agentPath == "" { - continue - } - agentPath = config.ExpandPath(agentPath) + agentMode := target.AgentsConfig().Mode + if agentMode == "" { + agentMode = "merge" + } - agentMode := ac.Mode - if agentMode == "" { - agentMode = "merge" - } + agentResult, err := ssync.SyncAgents(agents, agentsSource, agentPath, agentMode, body.DryRun, body.Force) + if err != nil { + warnings = append(warnings, "agent sync failed for "+name+": "+err.Error()) + continue + } - agentResult, err := ssync.SyncAgents(agents, agentsSource, agentPath, agentMode, body.DryRun, body.Force) - if err != nil { - warnings = append(warnings, "agent sync failed for "+name+": "+err.Error()) - continue + // Find or create result entry for this target + idx := -1 + for i := range results { + if results[i].Target == name { + idx = i + break } + } + if idx >= 0 { + results[idx].Linked = append(results[idx].Linked, agentResult.Linked...) + results[idx].Updated = append(results[idx].Updated, agentResult.Updated...) + results[idx].Skipped = append(results[idx].Skipped, agentResult.Skipped...) + } else if len(agentResult.Linked) > 0 || len(agentResult.Updated) > 0 || len(agentResult.Skipped) > 0 { + results = append(results, syncTargetResult{ + Target: name, + Linked: agentResult.Linked, + Updated: agentResult.Updated, + Skipped: agentResult.Skipped, + Pruned: make([]string, 0), + }) + idx = len(results) - 1 + } - // Merge into existing result or create new - merged := false - for i := range results { - if results[i].Target == name { - results[i].Linked = append(results[i].Linked, agentResult.Linked...) - results[i].Updated = append(results[i].Updated, agentResult.Updated...) - results[i].Skipped = append(results[i].Skipped, agentResult.Skipped...) - merged = true - break - } - } - if !merged && (len(agentResult.Linked) > 0 || len(agentResult.Updated) > 0 || len(agentResult.Skipped) > 0) { - results = append(results, syncTargetResult{ - Target: name, - Linked: agentResult.Linked, - Updated: agentResult.Updated, - Skipped: agentResult.Skipped, - Pruned: make([]string, 0), - }) - } - - // Prune orphan agents - if agentMode == "merge" { - pruned, _ := ssync.PruneOrphanAgentLinks(agentPath, agents, body.DryRun) - for i := range results { - if results[i].Target == name { - results[i].Pruned = append(results[i].Pruned, pruned...) - break - } - } - } else if agentMode == "copy" { - pruned, _ := ssync.PruneOrphanAgentCopies(agentPath, agents, body.DryRun) - for i := range results { - if results[i].Target == name { - results[i].Pruned = append(results[i].Pruned, pruned...) - break - } - } - } + // Prune orphan agents — reuse idx to avoid re-scanning + var pruned []string + if agentMode == "merge" { + pruned, _ = ssync.PruneOrphanAgentLinks(agentPath, agents, body.DryRun) + } else if agentMode == "copy" { + pruned, _ = ssync.PruneOrphanAgentCopies(agentPath, agents, body.DryRun) + } + if idx >= 0 && len(pruned) > 0 { + results[idx].Pruned = append(results[idx].Pruned, pruned...) } } } @@ -317,57 +293,19 @@ func (s *Server) handleDiff(w http.ResponseWriter, r *http.Request) { diffs = append(diffs, s.computeTargetDiff(name, target, discovered, globalMode, source)) } - // Agent diffs — discover agents and compute per-target diffs - var agents []resource.DiscoveredResource - if agentsSource != "" { - discovered, _ := resource.AgentKind{}.Discover(agentsSource) - agents = resource.ActiveAgents(discovered) - } - - if len(agents) > 0 { - var builtinAgents map[string]config.TargetConfig - if s.IsProjectMode() { - builtinAgents = config.ProjectAgentTargets() - } else { - builtinAgents = config.DefaultAgentTargets() - } - + // Agent diffs + if agents := discoverActiveAgents(agentsSource); len(agents) > 0 { + builtinAgents := s.builtinAgentTargets() for name, target := range targets { if filterTarget != "" && filterTarget != name { continue } - - ac := target.AgentsConfig() - agentPath := ac.Path - if agentPath == "" { - if builtin, ok := builtinAgents[name]; ok { - agentPath = builtin.Path - } - } + agentPath := resolveAgentPath(target, builtinAgents, name) if agentPath == "" { continue } - agentPath = config.ExpandPath(agentPath) - - agentItems := computeAgentTargetDiff(agentPath, agents) - if len(agentItems) == 0 { - continue - } - - // Merge into existing diff for this target - merged := false - for i := range diffs { - if diffs[i].Target == name { - diffs[i].Items = append(diffs[i].Items, agentItems...) - merged = true - break - } - } - if !merged { - diffs = append(diffs, diffTarget{ - Target: name, - Items: agentItems, - }) + if items := computeAgentTargetDiff(agentPath, agents); len(items) > 0 { + diffs = mergeAgentDiffItems(diffs, name, items) } } } diff --git a/ui/src/pages/SyncPage.tsx b/ui/src/pages/SyncPage.tsx index d2f101cd8..d20c73fbf 100644 --- a/ui/src/pages/SyncPage.tsx +++ b/ui/src/pages/SyncPage.tsx @@ -122,30 +122,24 @@ export default function SyncPage() { // Derived ignored skills list const ignoredSkills = ignoreSources?.ignored_skills ?? []; - // Calculate diff summary by kind + // Calculate diff summary by kind (single pass) const diffs = diffData ?? []; - const allItems = diffs.flatMap((d) => d.items ?? []); + const counts = useMemo(() => { + const c = { skill: { link: 0, update: 0, prune: 0, skip: 0, local: 0 }, agent: { link: 0, update: 0, prune: 0, skip: 0, local: 0 } }; + for (const d of diffs) { + for (const i of d.items ?? []) { + const kind = (i.kind ?? 'skill') as 'skill' | 'agent'; + const action = i.action as keyof typeof c.skill; + if (c[kind] && action in c[kind]) c[kind][action]++; + } + } + return c; + }, [diffs]); - const countByKindAction = (kind: string, action: string) => - allItems.filter((i) => (i.kind ?? 'skill') === kind && i.action === action).length; - - const skillLinks = countByKindAction('skill', 'link'); - const skillUpdates = countByKindAction('skill', 'update'); - const skillPrunes = countByKindAction('skill', 'prune'); - const skillSkips = countByKindAction('skill', 'skip'); - const skillLocal = countByKindAction('skill', 'local'); - const skillSync = skillLinks + skillUpdates + skillPrunes + skillSkips; - - const agentLinks = countByKindAction('agent', 'link'); - const agentUpdates = countByKindAction('agent', 'update'); - const agentPrunes = countByKindAction('agent', 'prune'); - const agentSkips = countByKindAction('agent', 'skip'); - const agentLocal = countByKindAction('agent', 'local'); - const agentSync = agentLinks + agentUpdates + agentPrunes + agentSkips; - - const totalActions = allItems.length; - const pendingLocal = skillLocal + agentLocal; - const syncActions = totalActions - pendingLocal; + const skillSync = counts.skill.link + counts.skill.update + counts.skill.prune + counts.skill.skip; + const agentSync = counts.agent.link + counts.agent.update + counts.agent.prune + counts.agent.skip; + const pendingLocal = counts.skill.local + counts.agent.local; + const syncActions = skillSync + agentSync; return (
@@ -227,19 +221,19 @@ export default function SyncPage() { {skillSync > 0 && (
- {skillLinks > 0 && {skillLinks} to link} - {skillUpdates > 0 && {skillUpdates} to update} - {skillSkips > 0 && {skillSkips} skipped} - {skillPrunes > 0 && {skillPrunes} to prune} + {counts.skill.link > 0 && {counts.skill.link} to link} + {counts.skill.update > 0 && {counts.skill.update} to update} + {counts.skill.skip > 0 && {counts.skill.skip} skipped} + {counts.skill.prune > 0 && {counts.skill.prune} to prune}
)} {agentSync > 0 && (
- {agentLinks > 0 && {agentLinks} to link} - {agentUpdates > 0 && {agentUpdates} to update} - {agentSkips > 0 && {agentSkips} skipped} - {agentPrunes > 0 && {agentPrunes} to prune} + {counts.agent.link > 0 && {counts.agent.link} to link} + {counts.agent.update > 0 && {counts.agent.update} to update} + {counts.agent.skip > 0 && {counts.agent.skip} skipped} + {counts.agent.prune > 0 && {counts.agent.prune} to prune}
)} {pendingLocal > 0 && {pendingLocal} local only}