Skip to content

mission control for agent skills

perf(tui): eliminate per-keypress lag and preview freezes

panudetjtcf64ddede321
diff --git a/internal/actions/actions.go b/internal/actions/actions.go
index 9ac6a66..f92bea0 100644
--- a/internal/actions/actions.go
+++ b/internal/actions/actions.go
@@ -6,6 +6,7 @@ import (
"os/exec"
"path/filepath"
"strings"
+ "sync"
"github.com/alvinunreal/lazyskills/internal/compat"
"github.com/alvinunreal/lazyskills/internal/model"
@@ -275,21 +276,62 @@ func openEditorAction(sk *model.Skill) (CommandPreview, bool, string) {
var LookPath = exec.LookPath
+// memoised results for HasSkillsOrNpx and ResolveSkillsCommand.
+// These depend only on PATH, which never changes during a session.
+var (
+ hasSkillsMu sync.Mutex
+ hasSkillsOK bool
+ hasSkillsAvail bool
+ hasSkillsReason string
+
+ resolveMu sync.Mutex
+ resolveOK bool
+ resolveProg string
+ resolveArgs []string
+)
+
+// ResetActionCaches clears the process-lifetime caches for HasSkillsOrNpx
+// and ResolveSkillsCommand. Tests that replace LookPath must call this
+// before and after the swap so the memo picks up the new value.
+func ResetActionCaches() {
+ hasSkillsMu.Lock()
+ hasSkillsOK = false
+ hasSkillsMu.Unlock()
+ resolveMu.Lock()
+ resolveOK = false
+ resolveMu.Unlock()
+}
+
func HasSkillsOrNpx() (bool, string) {
- if _, err := LookPath("skills"); err == nil {
- return true, ""
- }
- if _, err := LookPath("npx"); err == nil {
- return true, ""
+ hasSkillsMu.Lock()
+ if !hasSkillsOK {
+ ok, reason := true, ""
+ if _, err := LookPath("skills"); err == nil {
+ // ok
+ } else if _, err := LookPath("npx"); err == nil {
+ // ok
+ } else {
+ ok, reason = false, "neither 'skills' nor 'npx' is available in your PATH"
+ }
+ hasSkillsAvail, hasSkillsReason, hasSkillsOK = ok, reason, true
}
- return false, "neither 'skills' nor 'npx' is available in your PATH"
+ avail, reason := hasSkillsAvail, hasSkillsReason
+ hasSkillsMu.Unlock()
+ return avail, reason
}
func ResolveSkillsCommand() (string, []string) {
- if _, err := LookPath("skills"); err == nil {
- return "skills", nil
+ resolveMu.Lock()
+ if !resolveOK {
+ prog, args := "npx", []string{"--yes", "skills"}
+ if _, err := LookPath("skills"); err == nil {
+ prog, args = "skills", nil
+ }
+ resolveProg, resolveArgs, resolveOK = prog, args, true
}
- return "npx", []string{"--yes", "skills"}
+ prog, args := resolveProg, resolveArgs
+ resolveMu.Unlock()
+ return prog, args
}
func newPreview(id, title, program string, args []string, description string, mutates, confirm, dangerous bool, confirmValue string) CommandPreview {
diff --git a/internal/actions/actions_test.go b/internal/actions/actions_test.go
index 452bb6f..fad3995 100644
--- a/internal/actions/actions_test.go
+++ b/internal/actions/actions_test.go
@@ -288,12 +288,17 @@ func TestAppLevelActions(t *testing.T) {
func TestMissingDepsDisablesActions(t *testing.T) {
oldLookPath := LookPath
- defer func() { LookPath = oldLookPath }()
+ defer func() {
+ LookPath = oldLookPath
+ ResetActionCaches()
+ }()
+ ResetActionCaches()
// Simulate missing dependencies
LookPath = func(name string) (string, error) {
return "", os.ErrNotExist
}
+ ResetActionCaches()
sk := &model.Skill{
Name: "Deploy Skill",
@@ -319,9 +324,11 @@ func TestMissingDepsDisablesActions(t *testing.T) {
}
func TestForAvailableSkill(t *testing.T) {
+ ResetActionCaches()
LookPath = func(name string) (string, error) {
return "/usr/bin/" + name, nil
}
+ ResetActionCaches()
previews := ForAvailableSkill("owner/repo", "test-skill")
if len(previews) != 1 {
t.Fatalf("expected 1 install preview, got %d", len(previews))
diff --git a/internal/tui/state.go b/internal/tui/state.go
index 0326559..ff9da1b 100644
--- a/internal/tui/state.go
+++ b/internal/tui/state.go
@@ -7,6 +7,7 @@ import (
"github.com/alvinunreal/lazyskills/internal/actions"
"github.com/alvinunreal/lazyskills/internal/compat"
+ "github.com/alvinunreal/lazyskills/internal/display"
"github.com/alvinunreal/lazyskills/internal/model"
)
@@ -578,3 +579,32 @@ func (m appModel) getThreePaneLayout() (listWidth, rightWidth, topHeight, bottom
bottomHeight = height - topHeight
return
}
+
+// rebuildSkillViews pre-computes display.Skill for every skill in the current
+// snapshot. Called once per snapshotMsg; the pointer-valued map survives
+// Bubble Tea's value-copied model because maps are reference types.
+func (m *appModel) rebuildSkillViews() {
+ if len(m.result.Skills) == 0 {
+ m.skillViews = nil
+ return
+ }
+ m.skillViews = make(map[*model.Skill]*display.SkillView, len(m.result.Skills))
+ for _, sk := range m.result.Skills {
+ v := display.Skill(sk)
+ m.skillViews[sk] = &v
+ }
+}
+
+// cachedSkillView returns the cached SkillView for sk, falling back to
+// display.Skill for skills not in the snapshot (e.g. discovery skills).
+func (m appModel) cachedSkillView(sk *model.Skill) display.SkillView {
+ if sk == nil {
+ return display.SkillView{}
+ }
+ if m.skillViews != nil {
+ if v, ok := m.skillViews[sk]; ok {
+ return *v
+ }
+ }
+ return display.Skill(sk)
+}
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
index bfc6b0b..f1c8863 100644
--- a/internal/tui/tui.go
+++ b/internal/tui/tui.go
@@ -9,6 +9,7 @@ import (
"github.com/charmbracelet/lipgloss"
"github.com/alvinunreal/lazyskills/internal/actions"
+ "github.com/alvinunreal/lazyskills/internal/display"
"github.com/alvinunreal/lazyskills/internal/model"
"github.com/alvinunreal/lazyskills/internal/runner"
"github.com/alvinunreal/lazyskills/internal/scan"
@@ -85,9 +86,12 @@ type appModel struct {
discovery map[string]SourceDiscovery
previewCache map[previewCacheKey][]string
previewPending bool
+ previewRendering bool
previewGeneration int
viewportSyncFingerprint string
skillSearchText map[*model.Skill]string
+ skillViews map[*model.Skill]*display.SkillView
+ cachedActions []actions.CommandPreview
modalSelected int
modalSource string
pendingG bool // saw a lone "g"; a second "g" jumps to top
diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go
index b1143e0..d781219 100644
--- a/internal/tui/tui_test.go
+++ b/internal/tui/tui_test.go
@@ -267,7 +267,7 @@ func TestAgentFilterListMarksNonVisibleSkills(t *testing.T) {
Visibility: []model.SkillVisibility{{Agent: "claude-code", Display: "Claude Code", Visible: false, Reason: "missing_agent_link"}},
},
}}}
- out := compat.StripTerminalEscapes(m.listPane(20, 80))
+ out := compat.StripTerminalEscapes(m.listPane(20, 80, m.visibleRows()))
if !strings.Contains(out, "Visible [P] ✓") || !strings.Contains(out, "Missing [P] ×") {
t.Fatalf("expected list-level visibility badges, got %q", out)
}
@@ -282,7 +282,7 @@ func TestListRendersIssueRowsWithSeverityBadges(t *testing.T) {
{Name: "Warning", Scope: model.ScopeProject, HealthIssues: []model.HealthIssue{{Type: "missing_global_lock", Severity: "warning", Message: "not tracked"}}},
{Name: "Error", Scope: model.ScopeProject, HealthIssues: []model.HealthIssue{{Type: "missing_file", Severity: "error", Message: "missing SKILL.md"}}},
}}}
- out := m.listPane(20, 80)
+ out := m.listPane(20, 80, m.visibleRows())
if !strings.Contains(out, "Warning [P] ▲1") {
t.Fatalf("expected warning issue badge, got %q", out)
}
@@ -1301,6 +1301,11 @@ func TestMetadataShowsSkillDescription(t *testing.T) {
func TestDetailScrollKeysMoveViewport(t *testing.T) {
preview := strings.Repeat("- line\n", 80)
m := appModel{width: 100, height: 20, selected: 1, result: model.ScanResult{Skills: []*model.Skill{{Name: "Long", Description: "desc", Scope: model.ScopeProject, Preview: preview}}}}
+ _, rightWidth, _, _ := m.getThreePaneLayout()
+ previewWidth := max(1, rightWidth-4)
+ m.previewCache = map[previewCacheKey][]string{
+ {markdown: preview, width: previewWidth}: renderMarkdownPreview(preview, previewWidth),
+ }
m.syncViewport()
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyPgDown})
next := updated.(appModel)
@@ -1604,7 +1609,11 @@ func TestContextualFooterAndHelpModal(t *testing.T) {
}
return "", errors.New("not found")
}
- t.Cleanup(func() { actions.LookPath = oldLookPath })
+ actions.ResetActionCaches()
+ t.Cleanup(func() {
+ actions.LookPath = oldLookPath
+ actions.ResetActionCaches()
+ })
m := appModel{
width: 100,
@@ -1685,7 +1694,11 @@ func TestFooterHidesUnavailableSkillHotkeys(t *testing.T) {
}
return "", errors.New("not found")
}
- t.Cleanup(func() { actions.LookPath = oldLookPath })
+ actions.ResetActionCaches()
+ t.Cleanup(func() {
+ actions.LookPath = oldLookPath
+ actions.ResetActionCaches()
+ })
m := appModel{
width: 100,
@@ -1699,7 +1712,7 @@ func TestFooterHidesUnavailableSkillHotkeys(t *testing.T) {
}
m.syncViewport()
- footer := m.footerText(100)
+ footer := m.footerText(100, m.visibleRows(), m.currentActions())
if strings.Contains(footer, "u update") {
t.Fatalf("untracked skill footer should hide unavailable update hotkey, got %q", footer)
}
@@ -1727,7 +1740,7 @@ func TestSourceScanHintIgnoresBulkSelection(t *testing.T) {
m.selectedKeys = map[string]bool{skillKey(m.result.Skills[0]): true}
m.syncViewport()
- footer := m.footerText(120)
+ footer := m.footerText(120, m.visibleRows(), m.currentActions())
if !strings.Contains(footer, "d scan") {
t.Fatalf("source header should show scan even with bulk selection active, got %q", footer)
}
@@ -1784,7 +1797,11 @@ func TestSourceModalHelpIsCapabilityAware(t *testing.T) {
}
return "", errors.New("not found")
}
- t.Cleanup(func() { actions.LookPath = oldLookPath })
+ actions.ResetActionCaches()
+ t.Cleanup(func() {
+ actions.LookPath = oldLookPath
+ actions.ResetActionCaches()
+ })
t.Setenv("EDITOR", "")
m := appModel{
diff --git a/internal/tui/update.go b/internal/tui/update.go
index b054fd8..398623f 100644
--- a/internal/tui/update.go
+++ b/internal/tui/update.go
@@ -25,6 +25,13 @@ type previewRefreshMsg struct {
generation int
}
+// previewRenderedMsg carries the result of an async glamour markdown render.
+type previewRenderedMsg struct {
+ markdown string
+ width int
+ lines []string
+}
+
func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
updateStart := time.Now()
if keyMsg, ok := msg.(tea.KeyMsg); ok {
@@ -43,10 +50,12 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case snapshotMsg:
m.result = msg.result
m.previewCache = make(map[previewCacheKey][]string)
- m.previewPending = false
+ m.previewPending = true // prevent syncViewport from blocking on glamour
+ m.previewRendering = false
m.previewGeneration++
sortSkills(m.result.Skills)
m.rebuildSkillSearchText()
+ m.rebuildSkillViews()
m.err = msg.err
if m.agent != "" {
detected := false
@@ -63,7 +72,18 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.clampSelection()
m.pruneSelected()
m.actionResult = nil
+ // Seed with an empty (non-nil) slice so View's footer path doesn't
+ // fall back to currentActions (which calls exec.LookPath ≈4s on WSL2).
+ // clampAction in a later Update will populate the real actions.
+ m.cachedActions = []actions.CommandPreview{}
m.syncViewport()
+ // Immediately start the initial preview render off the main thread
+ // so the 2-3s glamour/chroma cost doesn't block the first frame.
+ if cmd := m.dispatchPreviewRender(); cmd != nil {
+ m.previewRendering = true
+ return m, cmd
+ }
+ m.previewPending = false
case discoveryResultMsg:
disc := SourceDiscovery{
Status: DiscoveryReady,
@@ -99,9 +119,28 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
refreshStart := time.Now()
if msg.generation == m.previewGeneration {
m.previewPending = false
+ if cmd := m.dispatchPreviewRender(); cmd != nil {
+ m.previewRendering = true
+ return m, cmd
+ }
m.syncViewport()
}
perfLogf("preview_refresh msg_generation=%d current_generation=%d applied=%t duration=%s", msg.generation, m.previewGeneration, msg.generation == m.previewGeneration, time.Since(refreshStart))
+ case previewRenderedMsg:
+ if m.previewCache == nil {
+ m.previewCache = make(map[previewCacheKey][]string)
+ }
+ key := previewCacheKey{markdown: msg.markdown, width: msg.width}
+ m.previewCache[key] = append([]string(nil), msg.lines...)
+ m.previewRendering = false
+ // Re-dispatch if the current skill's preview width differs from the
+ // rendered width (e.g. the terminal was resized between dispatch and
+ // completion). This ensures we never block View on a cache miss.
+ if cmd := m.dispatchPreviewRender(); cmd != nil {
+ m.previewRendering = true
+ return m, cmd
+ }
+ m.syncViewport()
case updatePlanMsg:
m.updatePlan = msg.plan
m.updatePlanErr = msg.err
@@ -692,8 +731,43 @@ func schedulePreviewRefresh(generation int) tea.Cmd {
})
}
+// dispatchPreviewRender checks whether the currently selected skill needs an
+// async glamour markdown render. Returns nil when the preview is already cached
+// or the skill has no preview content.
+func (m appModel) dispatchPreviewRender() tea.Cmd {
+ rows := m.visibleRows()
+ if len(rows) == 0 || m.selected < 0 || m.selected >= len(rows) {
+ return nil
+ }
+ row := rows[m.selected]
+ if row.isHeader || row.skill == nil {
+ return nil
+ }
+ view := m.cachedSkillView(row.skill)
+ if view.Preview == "" {
+ return nil
+ }
+ if m.previewCache == nil {
+ return nil // cache not initialized (bootstrapping)
+ }
+ _, rightWidth, _, _ := m.getThreePaneLayout()
+ previewWidth := max(1, rightWidth-4)
+ key := previewCacheKey{markdown: view.Preview, width: previewWidth}
+ if _, ok := m.previewCache[key]; ok {
+ return nil // already cached
+ }
+ // Capture by value — do NOT capture m (model is value-copied each Update).
+ markdown := view.Preview
+ width := previewWidth
+ return func() tea.Msg {
+ lines := renderMarkdownPreview(markdown, width)
+ return previewRenderedMsg{markdown: markdown, width: width, lines: lines}
+ }
+}
+
func (m *appModel) clampAction() {
actions := m.currentActions()
+ m.cachedActions = actions
if len(actions) == 0 {
m.action = 0
return
@@ -707,6 +781,13 @@ func (m *appModel) clampAction() {
}
func (m appModel) currentActions() []actions.CommandPreview {
+ return m.currentActionsForRows(nil)
+}
+
+// currentActionsForRows is like currentActions but accepts a precomputed rows
+// slice so callers can avoid a redundant visibleRows() re-derivation (which
+// walks SanitizeMetadata per skill). Pass nil to fall back to m.visibleRows().
+func (m appModel) currentActionsForRows(rows []skillsRow) []actions.CommandPreview {
if m.modalSource != "" {
child, ok := m.currentModalSelectedChild()
if ok {
@@ -720,7 +801,9 @@ func (m appModel) currentActions() []actions.CommandPreview {
if len(selected) > 0 {
return actions.ForSkills(selected)
}
- rows := m.visibleRows()
+ if rows == nil {
+ rows = m.visibleRows()
+ }
if len(rows) == 0 || m.selected < 0 || m.selected >= len(rows) {
return actions.AppLevelActions()
}
diff --git a/internal/tui/update_test.go b/internal/tui/update_test.go
index 88edc93..bf621a1 100644
--- a/internal/tui/update_test.go
+++ b/internal/tui/update_test.go
@@ -17,7 +17,7 @@ func TestTUIFooterUpdateNotice(t *testing.T) {
m.height = 30
// 1. Without update plan, no notice
- footer := m.footerText(100)
+ footer := m.footerText(100, m.visibleRows(), m.currentActions())
if strings.Contains(footer, "U update") {
t.Errorf("unexpected update notice in footer when no update is available: %q", footer)
}
@@ -30,13 +30,13 @@ func TestTUIFooterUpdateNotice(t *testing.T) {
Channel: "manual",
}
- footer = m.footerText(120)
+ footer = m.footerText(120, m.visibleRows(), m.currentActions())
if !strings.Contains(footer, "U update") || !strings.Contains(footer, "v1.1.0 available") {
t.Errorf("expected update notice in footer, got: %q", footer)
}
// 3. Notice omitted if width is too narrow
- footerNarrow := m.footerText(40)
+ footerNarrow := m.footerText(40, m.visibleRows(), m.currentActions())
if strings.Contains(footerNarrow, "U update") {
t.Errorf("expected update notice to be omitted in narrow viewport, got: %q", footerNarrow)
}
diff --git a/internal/tui/view.go b/internal/tui/view.go
index b90f8f5..c5e417e 100644
--- a/internal/tui/view.go
+++ b/internal/tui/view.go
@@ -3,6 +3,7 @@ package tui
import (
"fmt"
"strings"
+ "sync"
"time"
"charm.land/glamour/v2"
@@ -52,6 +53,12 @@ func (m appModel) View() string {
viewModel.width = layout.Width
viewModel.height = layout.Height
+ // Compute visibleRows once and thread it through all View consumers.
+ // Every consumer that previously called m.visibleRows() independently
+ // re-derived the filtered-skills walk (listGroupLabel → sourceInfo →
+ // SanitizeMetadata per skill), adding ~100ms per frame.
+ rows := viewModel.visibleRows()
+
listWidth, rightWidth, topHeight, bottomHeight := viewModel.getThreePaneLayout()
needsSync := viewModel.needsViewportSync(rightWidth, topHeight, bottomHeight)
perfLogf("view_pre selected=%d needs_sync=%t metadata_size=%dx%d preview_size=%dx%d", viewModel.selected, needsSync, viewModel.metadataViewport.Width, viewModel.metadataViewport.Height, viewModel.previewViewport.Width, viewModel.previewViewport.Height)
@@ -71,7 +78,7 @@ func (m appModel) View() string {
metadataStyle := paneStyle(metadataLayout, viewModel.focus == focusMetadata)
previewStyle := paneStyle(previewLayout, viewModel.focus == focusPreview)
- listContent := fitLines(viewModel.listPane(listLayout.ContentHeight, listLayout.ContentWidth), listLayout.ContentHeight)
+ listContent := fitLines(viewModel.listPane(listLayout.ContentHeight, listLayout.ContentWidth, rows), listLayout.ContentHeight)
list := decoratePane(listStyle.Render(listContent), listLayout, viewModel.focus == focusSkills, viewModel.listTitle())
metadataContent := fitLines(viewModel.metadataViewport.View(), metadataLayout.ContentHeight)
@@ -83,7 +90,11 @@ func (m appModel) View() string {
rightSide := lipgloss.JoinVertical(lipgloss.Left, metadata, preview)
view := lipgloss.JoinHorizontal(lipgloss.Top, list, rightSide)
- footer := viewModel.footerText(layout.Width)
+ footerActions := viewModel.cachedActions
+ if footerActions == nil {
+ footerActions = viewModel.currentActionsForRows(rows)
+ }
+ footer := viewModel.footerText(layout.Width, rows, footerActions)
return view + "\n" + footer
}
@@ -139,10 +150,9 @@ func (m appModel) listTitle() string {
return title
}
-func (m appModel) listPane(height, width int) string {
- vRows := m.visibleRows()
+func (m appModel) listPane(height, width int, rows []skillsRow) string {
var lines []string
- if len(vRows) == 0 {
+ if len(rows) == 0 {
var detail []string
if m.result.Preflight != nil && !m.result.Preflight.CanRunSkills {
detail = append(detail,
@@ -209,9 +219,9 @@ func (m appModel) listPane(height, width int) string {
if selectedRow >= visible {
start = selectedRow - visible + 1
}
- end := min(len(vRows), start+visible)
+ end := min(len(rows), start+visible)
- for idx, row := range vRows[start:end] {
+ for idx, row := range rows[start:end] {
rowIndex := start + idx
var line string
if row.isHeader {
@@ -230,7 +240,7 @@ func (m appModel) listPane(height, width int) string {
line = dimStyle.Render(truncate(headerText, width-lipgloss.Width(hint))) + dimStyle.Render(hint)
}
} else {
- view := display.Skill(row.skill)
+ view := m.cachedSkillView(row.skill)
mark := " "
if m.isSelected(row.skill) {
mark = "● "
@@ -433,7 +443,7 @@ func (m appModel) metadataLinesForRows(rows []skillsRow, width int) []string {
}
// Parse health issues
- view := display.Skill(sk)
+ view := m.cachedSkillView(sk)
skillIssues = append(skillIssues, view.HealthIssues...)
}
@@ -500,7 +510,7 @@ func (m appModel) metadataLinesForRows(rows []skillsRow, width int) []string {
return lines
}
- view := display.Skill(row.skill)
+ view := m.cachedSkillView(row.skill)
isEffectivelyDisabled := row.skill.Disabled
if m.agent != "" {
isEffectivelyDisabled = false
@@ -654,14 +664,16 @@ func (m appModel) previewLinesForRows(rows []skillsRow, width int) []string {
return wrapped
}
- view := display.Skill(row.skill)
+ view := m.cachedSkillView(row.skill)
if view.Preview == "" {
return []string{dimStyle.Render("No preview available for this skill.")}
}
if m.previewPending && !m.hasRenderedMarkdownPreview(view.Preview, width) {
return []string{dimStyle.Render("Preview updates when navigation pauses.")}
}
-
+ if !m.hasRenderedMarkdownPreview(view.Preview, width) && m.previewRendering {
+ return []string{dimStyle.Render("Rendering preview…")}
+ }
return m.renderMarkdownPreviewCached(view.Preview, width)
}
@@ -672,15 +684,16 @@ type previewCacheKey struct {
func (m appModel) renderMarkdownPreviewCached(markdown string, width int) []string {
if m.previewCache == nil {
- return renderMarkdownPreview(markdown, width)
+ return []string{dimStyle.Render("Rendering preview…")}
}
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
+ // Cache miss — never block the main thread. The async render was (or will
+ // be) dispatched from Update via dispatchPreviewRender. Show a placeholder
+ // until the result arrives.
+ return []string{dimStyle.Render("Rendering preview…")}
}
func (m appModel) hasRenderedMarkdownPreview(markdown string, width int) bool {
@@ -691,18 +704,50 @@ func (m appModel) hasRenderedMarkdownPreview(markdown string, width int) bool {
return ok
}
+var (
+ previewRenderersMu sync.Mutex
+ previewRenderers = map[int]*glamour.TermRenderer{}
+ glamourRenderMu sync.Mutex // serialises Render() calls; renderers are not documented thread-safe
+)
+
+// previewRenderer returns a glamour renderer for the given render width,
+// creating and caching one as needed. Construction is ~hundreds of ms the
+// first time; subsequent lookups are O(1).
+func previewRenderer(width int) *glamour.TermRenderer {
+ previewRenderersMu.Lock()
+ defer previewRenderersMu.Unlock()
+ if r, ok := previewRenderers[width]; ok {
+ return r
+ }
+ r, err := glamour.NewTermRenderer(
+ glamour.WithStyles(compactPreviewMarkdownStyle()),
+ glamour.WithWordWrap(width),
+ )
+ if err != nil {
+ return nil
+ }
+ // Keep the cache bounded: evict one entry if we exceed 12 widths.
+ if len(previewRenderers) > 12 {
+ for k := range previewRenderers {
+ delete(previewRenderers, k)
+ break
+ }
+ }
+ previewRenderers[width] = r
+ return r
+}
+
func renderMarkdownPreview(markdown string, width int) []string {
markdown = stripMarkdownFrontmatter(markdown)
if strings.TrimSpace(markdown) == "" {
return []string{dimStyle.Render("No preview available for this skill.")}
}
renderWidth := max(20, width-2)
- renderer, err := glamour.NewTermRenderer(
- glamour.WithStyles(compactPreviewMarkdownStyle()),
- glamour.WithWordWrap(renderWidth),
- )
- if err == nil {
+ renderer := previewRenderer(renderWidth)
+ if renderer != nil {
+ glamourRenderMu.Lock()
rendered, renderErr := renderer.Render(markdown)
+ glamourRenderMu.Unlock()
if renderErr == nil && strings.TrimSpace(rendered) != "" {
return strings.Split(strings.TrimRight(rendered, "\n"), "\n")
}
@@ -758,7 +803,7 @@ func (m appModel) detailLines(width int) []string {
if row.isHeader {
return m.metadataLines(width)
}
- view := display.Skill(row.skill)
+ view := m.cachedSkillView(row.skill)
lines := []string{
titleStyle.Render(view.Name),
"",
@@ -801,7 +846,7 @@ func (m appModel) sourceModalDetailLines(width int) []string {
globalCount++
}
- view := display.Skill(sk)
+ view := m.cachedSkillView(sk)
skillIssues = append(skillIssues, view.HealthIssues...)
}
@@ -973,7 +1018,7 @@ func (m appModel) sourceModalDetailLines(width int) []string {
}
} else {
sk := selectedChild.skill
- view := display.Skill(sk)
+ view := m.cachedSkillView(sk)
lockVal := display.LockSummary(view)
if lockVal == "not tracked" {
lockVal = warningStyle.Render("not tracked")
@@ -1246,7 +1291,7 @@ func (m appModel) renderActionResult(width int) []string {
return lines
}
-func (m appModel) footerText(width int) string {
+func (m appModel) footerText(width int, rows []skillsRow, actions []actions.CommandPreview) string {
var text string
if m.running {
text = "Working…"
@@ -1255,9 +1300,8 @@ func (m appModel) footerText(width int) string {
} else if m.searching {
text = "type search · enter apply · esc cancel · backspace edit"
} else if m.detailModal {
- modalActions := m.currentActions()
parts := []string{"↑/↓ scroll"}
- if hasAvailableAction(modalActions, "open_skill") {
+ if hasAvailableAction(actions, "open_skill") {
parts = append(parts, "o edit")
}
parts = append(parts, "c commands", "esc/q close")
@@ -1267,30 +1311,26 @@ func (m appModel) footerText(width int) string {
} else if m.helpOpen {
text = "esc/q/? close help"
} else if m.focus == focusMetadata {
- footerActions := m.currentActions()
parts := []string{"↑/↓ scroll metadata", "enter open", "c commands"}
- if hasAvailableToggleAction(footerActions) {
+ if hasAvailableToggleAction(actions) {
parts = append(parts, "e enable/disable")
}
parts = append(parts, "? help")
text = strings.Join(parts, " · ")
} else if m.focus == focusPreview {
- footerActions := m.currentActions()
parts := []string{"↑/↓ scroll preview", "enter open", "c commands"}
- if hasAvailableToggleAction(footerActions) {
+ if hasAvailableToggleAction(actions) {
parts = append(parts, "e enable/disable")
}
parts = append(parts, "? help")
text = strings.Join(parts, " · ")
} else {
// focusSkills
- rows := m.visibleRows()
if len(rows) > 0 && m.selected >= 0 && m.selected < len(rows) {
row := rows[m.selected]
- footerActions := m.currentActions()
if row.isHeader {
parts := []string{"enter browse"}
- if hasAvailableToggleAction(footerActions) {
+ if hasAvailableToggleAction(actions) {
parts = append(parts, "e enable/disable source")
}
if discoverable, _ := m.isSourceDiscoverable(row.groupName); discoverable {
@@ -1300,14 +1340,14 @@ func (m appModel) footerText(width int) string {
text = strings.Join(parts, " · ")
} else {
parts := []string{"enter open"}
- if hasAvailableToggleAction(footerActions) {
+ if hasAvailableToggleAction(actions) {
parts = append(parts, "e enable/disable")
}
parts = append(parts, "c actions")
- if hasAvailableAction(footerActions, preferredUpdateActionID(m.selectedCount())) {
+ if hasAvailableAction(actions, preferredUpdateActionID(m.selectedCount())) {
parts = append(parts, "u update")
}
- if hasAvailableAction(footerActions, preferredRemoveActionID(m.selectedCount())) {
+ if hasAvailableAction(actions, preferredRemoveActionID(m.selectedCount())) {
parts = append(parts, "x remove")
}
parts = append(parts, "? help")