Skip to content

mission control for agent skills

Optimize scan and preview rendering performance

alvinrealbb59163a6176
diff --git a/internal/scan/scan.go b/internal/scan/scan.go
index ada290a..fb3ffad 100644
--- a/internal/scan/scan.go
+++ b/internal/scan/scan.go
@@ -71,14 +71,16 @@ func Run(cwd string) (model.ScanResult, error) {
res.HealthIssues = append(res.HealthIssues, model.HealthIssue{Type: "corrupt_global_lock", Severity: "warning", Message: err.Error(), Path: res.GlobalLock})
}
+ activeScanCache := map[locationScanCacheKey][]scannedLocationRecord{}
for _, loc := range agents.Locations(absCwd) {
- scanLocation(loc, skills)
+ scanLocationCached(loc, skills, activeScanCache)
scanDisabledLocation(loc, skills)
}
- correlateLocks(skills, localLock.Skills, globalLock.Skills)
+ index := newLockMatchIndex(skills)
+ correlateLocksIndexed(skills, localLock.Skills, globalLock.Skills)
for key, entry := range localLock.Skills {
- if !hasLockMatch(skills, model.ScopeProject, key) {
+ if !index.hasMatch(model.ScopeProject, key) {
sk := ensureSkill(skills, model.ScopeProject, key, key, "")
e := entry
sk.LocalLock = &e
@@ -86,7 +88,7 @@ func Run(cwd string) (model.ScanResult, error) {
}
}
for key, entry := range globalLock.Skills {
- if !hasLockMatch(skills, model.ScopeGlobal, key) {
+ if !index.hasMatch(model.ScopeGlobal, key) {
sk := ensureSkill(skills, model.ScopeGlobal, key, key, "")
e := entry
sk.GlobalLock = &e
@@ -289,11 +291,43 @@ func scanDisabledLocation(loc agents.Location, skills map[string]*model.Skill) {
}
}
+type locationScanCacheKey struct {
+ root string
+ scope model.Scope
+ canonical bool
+}
+
+type scannedLocationRecord struct {
+ keyHint string
+ name string
+ description string
+ skillPath string
+ preview string
+ canonicalPath string
+ observed model.ObservedPath
+ healthIssues []model.HealthIssue
+}
+
+func scanLocationCached(loc agents.Location, skills map[string]*model.Skill, cache map[locationScanCacheKey][]scannedLocationRecord) {
+ key := locationScanCacheKey{root: loc.Root, scope: loc.Scope, canonical: loc.Canonical}
+ records, ok := cache[key]
+ if !ok {
+ records = scanLocationRecords(loc)
+ cache[key] = records
+ }
+ applyScannedLocationRecords(loc, skills, records)
+}
+
func scanLocation(loc agents.Location, skills map[string]*model.Skill) {
+ applyScannedLocationRecords(loc, skills, scanLocationRecords(loc))
+}
+
+func scanLocationRecords(loc agents.Location) []scannedLocationRecord {
entries, err := os.ReadDir(loc.Root)
if err != nil {
- return
+ return nil
}
+ records := make([]scannedLocationRecord, 0, len(entries))
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), ".") {
continue
@@ -317,9 +351,17 @@ func scanLocation(loc agents.Location, skills map[string]*model.Skill) {
observed.TargetPath = filepath.Clean(target)
if st, err := os.Stat(path); err != nil || !st.IsDir() {
observed.Status = model.StatusBrokenSymlink
- sk := ensureSkill(skills, loc.Scope, entry.Name(), entry.Name(), "")
- addObservedPath(sk, observed)
- sk.AddHealthIssue(model.HealthIssue{Type: "broken_symlink", Severity: "error", Message: "skill path is a broken symlink", Path: path})
+ records = append(records, scannedLocationRecord{
+ keyHint: entry.Name(),
+ name: entry.Name(),
+ observed: model.ObservedPath{
+ Path: observed.Path,
+ Scope: observed.Scope,
+ Status: observed.Status,
+ TargetPath: observed.TargetPath,
+ },
+ healthIssues: []model.HealthIssue{{Type: "broken_symlink", Severity: "error", Message: "skill path is a broken symlink", Path: path}},
+ })
continue
}
observed.Status = model.StatusSymlink
@@ -331,27 +373,64 @@ func scanLocation(loc agents.Location, skills map[string]*model.Skill) {
skillFile := filepath.Join(parseDir, "SKILL.md")
doc, err := frontmatter.ParseFile(skillFile)
if err != nil {
- sk := ensureSkill(skills, loc.Scope, entry.Name(), entry.Name(), "")
- addObservedPath(sk, observed)
issueType := "invalid_frontmatter"
if errors.Is(err, os.ErrNotExist) {
issueType = "missing_skill_md"
}
- sk.AddHealthIssue(model.HealthIssue{Type: issueType, Severity: "error", Message: fmt.Sprintf("invalid SKILL.md: %v", err), Path: skillFile})
+ records = append(records, scannedLocationRecord{
+ keyHint: entry.Name(),
+ name: entry.Name(),
+ observed: model.ObservedPath{
+ Path: observed.Path,
+ Scope: observed.Scope,
+ Status: observed.Status,
+ TargetPath: observed.TargetPath,
+ },
+ healthIssues: []model.HealthIssue{{Type: issueType, Severity: "error", Message: fmt.Sprintf("invalid SKILL.md: %v", err), Path: skillFile}},
+ })
continue
}
- sk := ensureSkill(skills, loc.Scope, entry.Name(), doc.Name, doc.Description)
- if loc.Canonical && sk.CanonicalPath == "" {
- sk.CanonicalPath = path
+ canonicalPath := ""
+ if loc.Canonical {
+ canonicalPath = path
+ }
+ records = append(records, scannedLocationRecord{
+ keyHint: entry.Name(),
+ name: doc.Name,
+ description: doc.Description,
+ skillPath: skillFile,
+ preview: doc.Raw,
+ canonicalPath: canonicalPath,
+ observed: model.ObservedPath{
+ Path: observed.Path,
+ Scope: observed.Scope,
+ Status: observed.Status,
+ TargetPath: observed.TargetPath,
+ },
+ })
+ }
+ return records
+}
+
+func applyScannedLocationRecords(loc agents.Location, skills map[string]*model.Skill, records []scannedLocationRecord) {
+ for _, record := range records {
+ sk := ensureSkill(skills, loc.Scope, record.keyHint, record.name, record.description)
+ if record.canonicalPath != "" && sk.CanonicalPath == "" {
+ sk.CanonicalPath = record.canonicalPath
}
- if sk.SkillPath == "" {
- sk.SkillPath = skillFile
+ if record.skillPath != "" && sk.SkillPath == "" {
+ sk.SkillPath = record.skillPath
}
- if sk.Preview == "" {
- sk.Preview = doc.Raw
+ if record.preview != "" && sk.Preview == "" {
+ sk.Preview = record.preview
}
+ observed := record.observed
+ observed.Agent = loc.AgentName
addObservedPath(sk, observed)
+ for _, issue := range record.healthIssues {
+ sk.AddHealthIssue(issue)
+ }
}
}
@@ -402,6 +481,118 @@ func correlateLocks(skills map[string]*model.Skill, local map[string]model.Local
}
}
+func correlateLocksIndexed(skills map[string]*model.Skill, local map[string]model.LocalLockEntry, global map[string]model.GlobalLockEntry) {
+ localIndex := newLocalLockLookup(local)
+ globalIndex := newGlobalLockLookup(global)
+ for _, sk := range skills {
+ if sk.Scope == model.ScopeProject {
+ if e, ok := localIndex.find(sk); ok {
+ entry := e
+ sk.LocalLock = &entry
+ }
+ }
+ if sk.Scope == model.ScopeGlobal {
+ if e, ok := globalIndex.find(sk); ok {
+ entry := e
+ sk.GlobalLock = &entry
+ }
+ }
+ }
+}
+
+type localLockLookup struct {
+ byKey map[string]model.LocalLockEntry
+ byNormalized map[string]model.LocalLockEntry
+}
+
+func newLocalLockLookup(lock map[string]model.LocalLockEntry) localLockLookup {
+ lookup := localLockLookup{byKey: map[string]model.LocalLockEntry{}, byNormalized: map[string]model.LocalLockEntry{}}
+ for key, entry := range lock {
+ lookup.byKey[key] = entry
+ normalized := compat.NormalizeName(key)
+ if _, exists := lookup.byNormalized[normalized]; !exists {
+ lookup.byNormalized[normalized] = entry
+ }
+ }
+ return lookup
+}
+
+func (lookup localLockLookup) find(sk *model.Skill) (model.LocalLockEntry, bool) {
+ for _, candidate := range candidateLockKeys(sk) {
+ if entry, ok := lookup.byKey[candidate]; ok {
+ return entry, true
+ }
+ if entry, ok := lookup.byKey[compat.SanitizeName(candidate)]; ok {
+ return entry, true
+ }
+ if entry, ok := lookup.byNormalized[compat.NormalizeName(candidate)]; ok {
+ return entry, true
+ }
+ }
+ return model.LocalLockEntry{}, false
+}
+
+type globalLockLookup struct {
+ byKey map[string]model.GlobalLockEntry
+ byNormalized map[string]model.GlobalLockEntry
+}
+
+func newGlobalLockLookup(lock map[string]model.GlobalLockEntry) globalLockLookup {
+ lookup := globalLockLookup{byKey: map[string]model.GlobalLockEntry{}, byNormalized: map[string]model.GlobalLockEntry{}}
+ for key, entry := range lock {
+ lookup.byKey[key] = entry
+ normalized := compat.NormalizeName(key)
+ if _, exists := lookup.byNormalized[normalized]; !exists {
+ lookup.byNormalized[normalized] = entry
+ }
+ }
+ return lookup
+}
+
+func (lookup globalLockLookup) find(sk *model.Skill) (model.GlobalLockEntry, bool) {
+ for _, candidate := range candidateLockKeys(sk) {
+ if entry, ok := lookup.byKey[candidate]; ok {
+ return entry, true
+ }
+ if entry, ok := lookup.byKey[compat.SanitizeName(candidate)]; ok {
+ return entry, true
+ }
+ if entry, ok := lookup.byNormalized[compat.NormalizeName(candidate)]; ok {
+ return entry, true
+ }
+ }
+ return model.GlobalLockEntry{}, false
+}
+
+type lockMatchIndex struct {
+ project map[string]bool
+ global map[string]bool
+}
+
+func newLockMatchIndex(skills map[string]*model.Skill) lockMatchIndex {
+ index := lockMatchIndex{project: map[string]bool{}, global: map[string]bool{}}
+ for _, sk := range skills {
+ target := index.project
+ if sk.Scope == model.ScopeGlobal {
+ target = index.global
+ }
+ for _, candidate := range candidateLockKeys(sk) {
+ target[candidate] = true
+ target[compat.SanitizeName(candidate)] = true
+ target[compat.NormalizeName(candidate)] = true
+ }
+ }
+ return index
+}
+
+func (index lockMatchIndex) hasMatch(scope model.Scope, key string) bool {
+ target := index.project
+ if scope == model.ScopeGlobal {
+ target = index.global
+ }
+ return target[key] || target[compat.NormalizeName(key)]
+}
+
func candidateLockKeys(sk *model.Skill) []string {
keys := []string{sk.Name, compat.SanitizeName(sk.Name)}
for _, p := range sk.ObservedPaths {
diff --git a/internal/scan/scan_profile_test.go b/internal/scan/scan_profile_test.go
new file mode 100644
index 0000000..ecd3388
--- /dev/null
+++ b/internal/scan/scan_profile_test.go
@@ -0,0 +1,195 @@
+package scan
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/alvinunreal/lazyskills/internal/agents"
+ "github.com/alvinunreal/lazyskills/internal/locks"
+ "github.com/alvinunreal/lazyskills/internal/model"
+)
+
+func TestProfileStartupScanPhases(t *testing.T) {
+ if os.Getenv("LAZYSKILLS_PROFILE_SCAN") == "" {
+ t.Skip("set LAZYSKILLS_PROFILE_SCAN=1 to profile startup scan phases")
+ }
+
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cwd = strings.TrimSuffix(cwd, "/internal/scan")
+
+ startTotal := time.Now()
+
+ start := time.Now()
+ absCwd, err := filepath.Abs(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st, err := os.Stat(absCwd); err != nil {
+ t.Fatal(err)
+ } else if !st.IsDir() {
+ t.Fatalf("cwd is not a directory: %s", absCwd)
+ }
+ validateDuration := time.Since(start)
+
+ res := model.ScanResult{
+ Cwd: absCwd,
+ ProjectLock: locks.ProjectLockPath(absCwd),
+ GlobalLock: locks.GlobalLockPath(),
+ }
+
+ start = time.Now()
+ res.Preflight = checkPreflight()
+ preflightDuration := time.Since(start)
+
+ start = time.Now()
+ res.Agents = agentStates(absCwd)
+ agentStatesDuration := time.Since(start)
+
+ skills := map[string]*model.Skill{}
+
+ start = time.Now()
+ localLock, err := locks.ReadLocal(res.ProjectLock)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ res.HealthIssues = append(res.HealthIssues, model.HealthIssue{Type: "corrupt_project_lock", Severity: "warning", Message: err.Error(), Path: res.ProjectLock})
+ }
+ readLocalDuration := time.Since(start)
+
+ start = time.Now()
+ globalLock, err := locks.ReadGlobal(res.GlobalLock)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ res.HealthIssues = append(res.HealthIssues, model.HealthIssue{Type: "corrupt_global_lock", Severity: "warning", Message: err.Error(), Path: res.GlobalLock})
+ }
+ readGlobalDuration := time.Since(start)
+
+ start = time.Now()
+ locations := agents.Locations(absCwd)
+ locationsDuration := time.Since(start)
+
+ type locationSample struct {
+ name string
+ root string
+ scope model.Scope
+ active time.Duration
+ disabled time.Duration
+ }
+ locationSamples := make([]locationSample, 0, len(locations))
+ activeScanCache := map[locationScanCacheKey][]scannedLocationRecord{}
+ start = time.Now()
+ for _, loc := range locations {
+ activeStart := time.Now()
+ scanLocationCached(loc, skills, activeScanCache)
+ activeDuration := time.Since(activeStart)
+
+ disabledStart := time.Now()
+ scanDisabledLocation(loc, skills)
+ disabledDuration := time.Since(disabledStart)
+
+ locationSamples = append(locationSamples, locationSample{
+ name: loc.AgentName,
+ root: loc.Root,
+ scope: loc.Scope,
+ active: activeDuration,
+ disabled: disabledDuration,
+ })
+ }
+ scanLocationsDuration := time.Since(start)
+
+ start = time.Now()
+ index := newLockMatchIndex(skills)
+ correlateLocksIndexed(skills, localLock.Skills, globalLock.Skills)
+ correlateDuration := time.Since(start)
+
+ start = time.Now()
+ for key, entry := range localLock.Skills {
+ if !index.hasMatch(model.ScopeProject, key) {
+ sk := ensureSkill(skills, model.ScopeProject, key, key, "")
+ e := entry
+ sk.LocalLock = &e
+ sk.AddHealthIssue(model.HealthIssue{Type: "lock_without_files", Severity: "warning", Message: "project lock entry has no matching skill on disk"})
+ }
+ }
+ for key, entry := range globalLock.Skills {
+ if !index.hasMatch(model.ScopeGlobal, key) {
+ sk := ensureSkill(skills, model.ScopeGlobal, key, key, "")
+ e := entry
+ sk.GlobalLock = &e
+ sk.AddHealthIssue(model.HealthIssue{Type: "lock_without_files", Severity: "warning", Message: "global lock entry has no matching skill on disk"})
+ }
+ }
+ missingLocksDuration := time.Since(start)
+
+ start = time.Now()
+ addDuplicateAndShadowingIssues(skills)
+ duplicatesDuration := time.Since(start)
+
+ start = time.Now()
+ for _, sk := range skills {
+ if len(sk.ObservedPaths) > 0 {
+ if sk.Scope == model.ScopeProject && sk.LocalLock == nil {
+ sk.AddHealthIssue(model.HealthIssue{Type: "missing_project_lock", Severity: "warning", Message: "project skill is present on disk but not found in project lock"})
+ }
+ if sk.Scope == model.ScopeGlobal && sk.GlobalLock == nil {
+ sk.AddHealthIssue(model.HealthIssue{Type: "missing_global_lock", Severity: "warning", Message: "global skill is present on disk but not found in global lock"})
+ }
+ if sk.CanonicalPath == "" && hasNonCanonicalObservation(sk) {
+ sk.AddHealthIssue(model.HealthIssue{Type: "ghost_agent_skill", Severity: "warning", Message: "skill exists in an agent-specific directory without a canonical .agents/skills copy"})
+ }
+ }
+ sk.Visibility = skillVisibility(sk, res.Agents)
+
+ hasActive := false
+ hasDisabled := false
+ for _, obs := range sk.ObservedPaths {
+ if obs.Status == model.StatusDisabled {
+ hasDisabled = true
+ } else {
+ hasActive = true
+ }
+ }
+ sk.Disabled = hasDisabled && !hasActive
+
+ res.Skills = append(res.Skills, sk)
+ }
+ finalizeSkillsDuration := time.Since(start)
+
+ start = time.Now()
+ sort.Slice(res.Skills, func(i, j int) bool {
+ left, right := strings.ToLower(res.Skills[i].Name), strings.ToLower(res.Skills[j].Name)
+ if left == right {
+ return res.Skills[i].Scope < res.Skills[j].Scope
+ }
+ return left < right
+ })
+ sortDuration := time.Since(start)
+
+ totalDuration := time.Since(startTotal)
+
+ t.Logf("scan_total=%s cwd=%s skills=%d locations=%d active_scan_cache_entries=%d agents=%d local_lock_entries=%d global_lock_entries=%d", totalDuration, absCwd, len(res.Skills), len(locations), len(activeScanCache), len(res.Agents), len(localLock.Skills), len(globalLock.Skills))
+ t.Logf("phase validate=%s preflight=%s agent_states=%s read_local=%s read_global=%s locations=%s scan_locations=%s correlate=%s missing_locks=%s duplicates=%s finalize=%s sort=%s", validateDuration, preflightDuration, agentStatesDuration, readLocalDuration, readGlobalDuration, locationsDuration, scanLocationsDuration, correlateDuration, missingLocksDuration, duplicatesDuration, finalizeSkillsDuration, sortDuration)
+
+ sort.Slice(locationSamples, func(i, j int) bool {
+ return locationSamples[i].active+locationSamples[i].disabled > locationSamples[j].active+locationSamples[j].disabled
+ })
+ for i, s := range locationSamples {
+ if i >= 12 {
+ break
+ }
+ t.Logf("location rank=%d agent=%s scope=%s active=%s disabled=%s total=%s root=%s", i+1, s.name, s.scope, s.active, s.disabled, s.active+s.disabled, s.root)
+ }
+
+ measured := validateDuration + preflightDuration + agentStatesDuration + readLocalDuration + readGlobalDuration + locationsDuration + scanLocationsDuration + correlateDuration + missingLocksDuration + duplicatesDuration + finalizeSkillsDuration + sortDuration
+ t.Logf("phase_measured_sum=%s phase_unattributed=%s", measured, totalDuration-measured)
+
+ if len(res.Skills) == 0 {
+ t.Fatal(fmt.Errorf("scan found no skills"))
+ }
+}
diff --git a/internal/tui/detail_profile_test.go b/internal/tui/detail_profile_test.go
new file mode 100644
index 0000000..8bfaf46
--- /dev/null
+++ b/internal/tui/detail_profile_test.go
@@ -0,0 +1,257 @@
+package tui
+
+import (
+ "os"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/alvinunreal/lazyskills/internal/scan"
+)
+
+type detailProfileSample struct {
+ name string
+ metadata time.Duration
+ preview time.Duration
+ actions time.Duration
+ detail time.Duration
+ sync time.Duration
+ view time.Duration
+ total time.Duration
+}
+
+type sourceProfileSample struct {
+ name string
+ children time.Duration
+ detail time.Duration
+ sync time.Duration
+ view time.Duration
+ total time.Duration
+ childRows int
+ lineCount int
+}
+
+func TestProfileRealSkillDetailTimings(t *testing.T) {
+ if os.Getenv("LAZYSKILLS_PROFILE_DETAIL") == "" {
+ t.Skip("set LAZYSKILLS_PROFILE_DETAIL=1 to profile real skill detail timings")
+ }
+
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cwd = strings.TrimSuffix(cwd, "/internal/tui")
+
+ var snapshotDuration time.Duration
+ var resultErr error
+ start := time.Now()
+ result, resultErr := scan.Snapshot(cwd)
+ snapshotDuration = time.Since(start)
+ if resultErr != nil {
+ t.Fatal(resultErr)
+ }
+ if len(result.Skills) == 0 {
+ t.Fatalf("no real skills found from %s", cwd)
+ }
+
+ m := newModel(cwd)
+ m.result = result
+ m.width = 120
+ m.height = 40
+
+ rowsStart := time.Now()
+ rows := m.visibleRows()
+ rowsDuration := time.Since(rowsStart)
+
+ var skillRows []int
+ for i, row := range rows {
+ if !row.isHeader && row.skill != nil {
+ skillRows = append(skillRows, i)
+ }
+ }
+ if len(skillRows) == 0 {
+ t.Fatal("no selectable skill rows found")
+ }
+ if len(skillRows) > 10 {
+ skillRows = skillRows[:10]
+ }
+
+ t.Logf("snapshot=%s skills=%d visible_rows=%d visible_rows_time=%s sampled_skill_rows=%d", snapshotDuration, len(result.Skills), len(rows), rowsDuration, len(skillRows))
+
+ samples := make([]detailProfileSample, 0, len(skillRows))
+ for _, selected := range skillRows {
+ m.selected = selected
+ row := rows[selected]
+
+ totalStart := time.Now()
+
+ start = time.Now()
+ _ = m.metadataLinesForRows(rows, 56)
+ metadataDuration := time.Since(start)
+
+ start = time.Now()
+ _ = m.previewLinesForRows(rows, 56)
+ previewDuration := time.Since(start)
+
+ start = time.Now()
+ _ = m.currentActions()
+ actionsDuration := time.Since(start)
+
+ start = time.Now()
+ _ = m.detailLines(80)
+ detailDuration := time.Since(start)
+
+ start = time.Now()
+ m.syncViewport()
+ syncDuration := time.Since(start)
+
+ start = time.Now()
+ _ = m.View()
+ viewDuration := time.Since(start)
+
+ totalDuration := time.Since(totalStart)
+
+ s := detailProfileSample{
+ name: row.skill.Name,
+ metadata: metadataDuration,
+ preview: previewDuration,
+ actions: actionsDuration,
+ detail: detailDuration,
+ sync: syncDuration,
+ view: viewDuration,
+ total: totalDuration,
+ }
+ samples = append(samples, s)
+ t.Logf("skill=%q metadata=%s preview=%s actions=%s detail=%s sync=%s view=%s total=%s", s.name, s.metadata, s.preview, s.actions, s.detail, s.sync, s.view, s.total)
+ }
+
+ logStageSummary(t, "metadata", samples, func(s detailProfileSample) time.Duration { return s.metadata })
+ logStageSummary(t, "preview", samples, func(s detailProfileSample) time.Duration { return s.preview })
+ logStageSummary(t, "actions", samples, func(s detailProfileSample) time.Duration { return s.actions })
+ logStageSummary(t, "detail", samples, func(s detailProfileSample) time.Duration { return s.detail })
+ logStageSummary(t, "sync", samples, func(s detailProfileSample) time.Duration { return s.sync })
+ logStageSummary(t, "view", samples, func(s detailProfileSample) time.Duration { return s.view })
+ logStageSummary(t, "total", samples, func(s detailProfileSample) time.Duration { return s.total })
+}
+
+func TestProfileRealSourceModalTimings(t *testing.T) {
+ if os.Getenv("LAZYSKILLS_PROFILE_SOURCE") == "" {
+ t.Skip("set LAZYSKILLS_PROFILE_SOURCE=1 to profile real source modal timings")
+ }
+
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cwd = strings.TrimSuffix(cwd, "/internal/tui")
+
+ start := time.Now()
+ result, err := scan.Snapshot(cwd)
+ snapshotDuration := time.Since(start)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ m := newModel(cwd)
+ m.result = result
+ m.width = 120
+ m.height = 40
+
+ rows := m.visibleRows()
+ var headerRows []int
+ for i, row := range rows {
+ if row.isHeader {
+ headerRows = append(headerRows, i)
+ }
+ }
+ if len(headerRows) == 0 {
+ t.Fatal("no source header rows found")
+ }
+ if len(headerRows) > 10 {
+ headerRows = headerRows[:10]
+ }
+
+ t.Logf("snapshot=%s skills=%d visible_rows=%d sampled_source_rows=%d", snapshotDuration, len(result.Skills), len(rows), len(headerRows))
+
+ samples := make([]sourceProfileSample, 0, len(headerRows))
+ for _, selected := range headerRows {
+ m.selected = selected
+ m.detailModal = true
+ m.modalSource = rows[selected].groupName
+ m.modalSelected = 0
+ m.viewport.GotoTop()
+
+ totalStart := time.Now()
+
+ start = time.Now()
+ children := m.modalChildRows(m.modalSource)
+ childrenDuration := time.Since(start)
+
+ start = time.Now()
+ lines := m.sourceModalDetailLines(80)
+ detailDuration := time.Since(start)
+
+ start = time.Now()
+ m.syncViewport()
+ syncDuration := time.Since(start)
+
+ start = time.Now()
+ _ = m.View()
+ viewDuration := time.Since(start)
+
+ totalDuration := time.Since(totalStart)
+ s := sourceProfileSample{
+ name: m.modalSource,
+ children: childrenDuration,
+ detail: detailDuration,
+ sync: syncDuration,
+ view: viewDuration,
+ total: totalDuration,
+ childRows: len(children),
+ lineCount: len(lines),
+ }
+ samples = append(samples, s)
+ t.Logf("source=%q children=%s child_rows=%d detail=%s lines=%d sync=%s view=%s total=%s", s.name, s.children, s.childRows, s.detail, s.lineCount, s.sync, s.view, s.total)
+ }
+
+ logSourceStageSummary(t, "children", samples, func(s sourceProfileSample) time.Duration { return s.children })
+ logSourceStageSummary(t, "detail", samples, func(s sourceProfileSample) time.Duration { return s.detail })
+ logSourceStageSummary(t, "sync", samples, func(s sourceProfileSample) time.Duration { return s.sync })
+ logSourceStageSummary(t, "view", samples, func(s sourceProfileSample) time.Duration { return s.view })
+ logSourceStageSummary(t, "total", samples, func(s sourceProfileSample) time.Duration { return s.total })
+}
+
+func logSourceStageSummary(t *testing.T, name string, samples []sourceProfileSample, pick func(sourceProfileSample) time.Duration) {
+ t.Helper()
+ values := make([]time.Duration, 0, len(samples))
+ var sum time.Duration
+ for _, s := range samples {
+ v := pick(s)
+ values = append(values, v)
+ sum += v
+ }
+ sort.Slice(values, func(i, j int) bool { return values[i] < values[j] })
+ avg := time.Duration(0)
+ if len(values) > 0 {
+ avg = sum / time.Duration(len(values))
+ }
+ t.Logf("summary stage=%s min=%s p50=%s max=%s avg=%s", name, values[0], values[len(values)/2], values[len(values)-1], avg)
+}
+
+func logStageSummary(t *testing.T, name string, samples []detailProfileSample, pick func(detailProfileSample) time.Duration) {
+ t.Helper()
+ values := make([]time.Duration, 0, len(samples))
+ var sum time.Duration
+ for _, s := range samples {
+ v := pick(s)
+ values = append(values, v)
+ sum += v
+ }
+ sort.Slice(values, func(i, j int) bool { return values[i] < values[j] })
+ avg := time.Duration(0)
+ if len(values) > 0 {
+ avg = sum / time.Duration(len(values))
+ }
+ t.Logf("summary stage=%s min=%s p50=%s max=%s avg=%s", name, values[0], values[len(values)/2], values[len(values)-1], avg)
+}
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
index 574927a..1f62e6f 100644
--- a/internal/tui/tui.go
+++ b/internal/tui/tui.go
@@ -81,6 +81,7 @@ type appModel struct {
focus focusState
collapsedGroups map[string]bool
discovery map[string]SourceDiscovery
+ previewCache map[previewCacheKey][]string
skillSearchText map[*model.Skill]string
modalSelected int
modalSource string
@@ -176,6 +177,7 @@ func newModel(cwd string) appModel {
previewViewport: viewport.New(0, 0),
collapsedGroups: make(map[string]bool),
discovery: make(map[string]SourceDiscovery),
+ previewCache: make(map[previewCacheKey][]string),
}
}
diff --git a/internal/tui/view.go b/internal/tui/view.go
index fbbfc97..985d8d0 100644
--- a/internal/tui/view.go
+++ b/internal/tui/view.go
@@ -671,7 +671,25 @@ func (m appModel) previewLinesForRows(rows []skillsRow, width int) []string {
return []string{dimStyle.Render("No preview available for this skill.")}
}
- return renderMarkdownPreview(view.Preview, width)
+ return m.renderMarkdownPreviewCached(view.Preview, width)
+}
+
+type previewCacheKey struct {
+ markdown string
+ width int
+}
+
+func (m appModel) renderMarkdownPreviewCached(markdown string, width int) []string {
+ if m.previewCache == nil {
+ return renderMarkdownPreview(markdown, width)
+ }
+ key := previewCacheKey{markdown: markdown, width: width}
+ if lines, ok := m.previewCache[key]; ok {
+ return append([]string(nil), lines...)
+ }
+ lines := renderMarkdownPreview(markdown, width)
+ m.previewCache[key] = append([]string(nil), lines...)
+ return lines
}
func renderMarkdownPreview(markdown string, width int) []string {