Skip to content

mission control for agent skills

Improve TUI navigation responsiveness

alvinreale25a71723824
diff --git a/internal/tui/detail_profile_test.go b/internal/tui/detail_profile_test.go
index 8bfaf46..0d00daa 100644
--- a/internal/tui/detail_profile_test.go
+++ b/internal/tui/detail_profile_test.go
@@ -7,6 +7,8 @@ import (
"testing"
"time"
+ tea "github.com/charmbracelet/bubbletea"
+
"github.com/alvinunreal/lazyskills/internal/scan"
)
@@ -32,6 +34,14 @@ type sourceProfileSample struct {
lineCount int
}
+type navProfileSample struct {
+ selected int
+ name string
+ update time.Duration
+ view time.Duration
+ total time.Duration
+}
+
func TestProfileRealSkillDetailTimings(t *testing.T) {
if os.Getenv("LAZYSKILLS_PROFILE_DETAIL") == "" {
t.Skip("set LAZYSKILLS_PROFILE_DETAIL=1 to profile real skill detail timings")
@@ -222,6 +232,95 @@ func TestProfileRealSourceModalTimings(t *testing.T) {
logSourceStageSummary(t, "total", samples, func(s sourceProfileSample) time.Duration { return s.total })
}
+func TestProfileRepeatedJNavigationTimings(t *testing.T) {
+ if os.Getenv("LAZYSKILLS_PROFILE_NAV") == "" {
+ t.Skip("set LAZYSKILLS_PROFILE_NAV=1 to profile repeated j navigation 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
+ m.focus = focusSkills
+ m.syncViewport()
+
+ rows := m.visibleRows()
+ steps := len(rows) - 1
+ if steps > 40 {
+ steps = 40
+ }
+ if steps <= 0 {
+ t.Fatal("not enough visible rows to profile navigation")
+ }
+
+ t.Logf("snapshot=%s skills=%d visible_rows=%d steps=%d", snapshotDuration, len(result.Skills), len(rows), steps)
+
+ samples := make([]navProfileSample, 0, steps)
+ key := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'j'}}
+
+ for i := 0; i < steps; i++ {
+ totalStart := time.Now()
+
+ start = time.Now()
+ updated, _ := m.Update(key)
+ updateDuration := time.Since(start)
+ m = updated.(appModel)
+
+ start = time.Now()
+ _ = m.View()
+ viewDuration := time.Since(start)
+
+ totalDuration := time.Since(totalStart)
+ rows = m.visibleRows()
+ name := ""
+ if m.selected >= 0 && m.selected < len(rows) {
+ row := rows[m.selected]
+ if row.isHeader {
+ name = "source:" + row.groupName
+ } else if row.skill != nil {
+ name = row.skill.Name
+ }
+ }
+ s := navProfileSample{selected: m.selected, name: name, update: updateDuration, view: viewDuration, total: totalDuration}
+ samples = append(samples, s)
+ t.Logf("step=%d selected=%d item=%q update=%s view=%s total=%s", i+1, s.selected, s.name, s.update, s.view, s.total)
+ }
+
+ logNavStageSummary(t, "update", samples, func(s navProfileSample) time.Duration { return s.update })
+ logNavStageSummary(t, "view", samples, func(s navProfileSample) time.Duration { return s.view })
+ logNavStageSummary(t, "total", samples, func(s navProfileSample) time.Duration { return s.total })
+}
+
+func logNavStageSummary(t *testing.T, name string, samples []navProfileSample, pick func(navProfileSample) 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 logSourceStageSummary(t *testing.T, name string, samples []sourceProfileSample, pick func(sourceProfileSample) time.Duration) {
t.Helper()
values := make([]time.Duration, 0, len(samples))
diff --git a/internal/tui/perf_debug.go b/internal/tui/perf_debug.go
new file mode 100644
index 0000000..c65ec27
--- /dev/null
+++ b/internal/tui/perf_debug.go
@@ -0,0 +1,36 @@
+package tui
+
+import (
+ "fmt"
+ "os"
+ "sync"
+ "time"
+)
+
+var perfDebug struct {
+ once sync.Once
+ mu sync.Mutex
+ file *os.File
+ path string
+}
+
+func perfLogf(format string, args ...any) {
+ perfDebug.once.Do(func() {
+ perfDebug.path = os.Getenv("LAZYSKILLS_PERF_LOG")
+ if perfDebug.path == "" {
+ return
+ }
+ file, err := os.OpenFile(perfDebug.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+ if err == nil {
+ perfDebug.file = file
+ }
+ })
+ if perfDebug.file == nil {
+ return
+ }
+ perfDebug.mu.Lock()
+ defer perfDebug.mu.Unlock()
+ _, _ = fmt.Fprintf(perfDebug.file, "%s ", time.Now().Format(time.RFC3339Nano))
+ _, _ = fmt.Fprintf(perfDebug.file, format, args...)
+ _, _ = fmt.Fprintln(perfDebug.file)
+}
diff --git a/internal/tui/state.go b/internal/tui/state.go
index 6af488f..0326559 100644
--- a/internal/tui/state.go
+++ b/internal/tui/state.go
@@ -3,6 +3,7 @@ package tui
import (
"fmt"
"strings"
+ "time"
"github.com/alvinunreal/lazyskills/internal/actions"
"github.com/alvinunreal/lazyskills/internal/compat"
@@ -10,6 +11,11 @@ import (
)
func (m *appModel) syncViewport() {
+ start := time.Now()
+ defer func() {
+ m.viewportSyncFingerprint = m.currentViewportSyncFingerprint()
+ perfLogf("sync selected=%d focus=%d modal=%t source=%q preview_pending=%t duration=%s", m.selected, m.focus, m.detailModal, m.modalSource, m.previewPending, time.Since(start))
+ }()
layout := newAppLayout(m.width, m.height)
if layout.Small {
m.viewport.Width = 0
@@ -51,6 +57,30 @@ func (m *appModel) syncViewport() {
m.clampViewportOffset()
}
+func (m appModel) currentViewportSyncFingerprint() string {
+ selectedKey := m.currentSelectedKey()
+ collapsed := false
+ if strings.HasPrefix(selectedKey, "group:") {
+ collapsed = m.isCollapsed(strings.TrimPrefix(selectedKey, "group:"))
+ }
+ return fmt.Sprintf("%d\x00%d\x00%d\x00%d\x00%s\x00%s\x00%t\x00%t\x00%t\x00%s\x00%d\x00%t\x00%s\x00%t",
+ m.width,
+ m.height,
+ m.selected,
+ m.focus,
+ m.agent,
+ m.search,
+ m.detailModal,
+ m.commands,
+ m.helpOpen,
+ m.modalSource,
+ m.modalSelected,
+ m.previewPending,
+ selectedKey,
+ collapsed,
+ )
+}
+
type skillsRow struct {
isHeader bool
groupName string
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
index 1f62e6f..8f23e42 100644
--- a/internal/tui/tui.go
+++ b/internal/tui/tui.go
@@ -53,40 +53,43 @@ type SourceDiscovery struct {
}
type appModel struct {
- cwd string
- result model.ScanResult
- err error
- selected int
- filter scopeFilter
- agent string
- search string
- searching bool
- commands bool
- selectedKeys map[string]bool
- action int
- confirming bool
- confirmInput string
- confirmError string
- running bool
- runningTitle string
- actionResult *runner.Result
- width int
- height int
- viewport viewport.Model
- metadataViewport viewport.Model
- previewViewport viewport.Model
- detailsFocused bool
- detailModal bool
- helpOpen bool
- focus focusState
- collapsedGroups map[string]bool
- discovery map[string]SourceDiscovery
- previewCache map[previewCacheKey][]string
- skillSearchText map[*model.Skill]string
- modalSelected int
- modalSource string
- pendingG bool // saw a lone "g"; a second "g" jumps to top
- pendingAction *actions.CommandPreview // action awaiting confirm (decoupled from selection)
+ cwd string
+ result model.ScanResult
+ err error
+ selected int
+ filter scopeFilter
+ agent string
+ search string
+ searching bool
+ commands bool
+ selectedKeys map[string]bool
+ action int
+ confirming bool
+ confirmInput string
+ confirmError string
+ running bool
+ runningTitle string
+ actionResult *runner.Result
+ width int
+ height int
+ viewport viewport.Model
+ metadataViewport viewport.Model
+ previewViewport viewport.Model
+ detailsFocused bool
+ detailModal bool
+ helpOpen bool
+ focus focusState
+ collapsedGroups map[string]bool
+ discovery map[string]SourceDiscovery
+ previewCache map[previewCacheKey][]string
+ previewPending bool
+ previewGeneration int
+ viewportSyncFingerprint string
+ skillSearchText map[*model.Skill]string
+ modalSelected int
+ modalSource string
+ pendingG bool // saw a lone "g"; a second "g" jumps to top
+ pendingAction *actions.CommandPreview // action awaiting confirm (decoupled from selection)
}
type paneLayout struct {
diff --git a/internal/tui/update.go b/internal/tui/update.go
index 2cb5242..028cc10 100644
--- a/internal/tui/update.go
+++ b/internal/tui/update.go
@@ -17,7 +17,21 @@ import (
"github.com/alvinunreal/lazyskills/internal/runner"
)
+const previewRefreshDelay = 300 * time.Millisecond
+
+type previewRefreshMsg struct {
+ generation int
+}
+
func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ updateStart := time.Now()
+ if keyMsg, ok := msg.(tea.KeyMsg); ok {
+ key := keyMsg.String()
+ selectedBefore := m.selected
+ defer func() {
+ perfLogf("update key=%q selected_before=%d selected_after=%d focus=%d modal=%t source=%q preview_pending=%t generation=%d duration=%s", key, selectedBefore, m.selected, m.focus, m.detailModal, m.modalSource, m.previewPending, m.previewGeneration, time.Since(updateStart))
+ }()
+ }
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
@@ -26,6 +40,9 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.syncViewport()
case snapshotMsg:
m.result = msg.result
+ m.previewCache = make(map[previewCacheKey][]string)
+ m.previewPending = false
+ m.previewGeneration++
sortSkills(m.result.Skills)
m.rebuildSkillSearchText()
m.err = msg.err
@@ -76,8 +93,16 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if msg.mutates && (succeeded || msg.partialSuccess) {
return m, loadSnapshot(m.cwd)
}
+ case previewRefreshMsg:
+ refreshStart := time.Now()
+ if msg.generation == m.previewGeneration {
+ m.previewPending = false
+ 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 tea.KeyMsg:
key := msg.String()
+ var postKeyCmd tea.Cmd
if m.running {
if key == "ctrl+c" || key == "q" {
return m, tea.Quit
@@ -321,6 +346,26 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// "gg" jumps to top: a lone g arms the flag, any other key disarms it.
gPending := m.pendingG
m.pendingG = false
+ if count := repeatedRuneKeyCount(key, 'j'); count > 1 {
+ m, postKeyCmd = m.moveSelectionBy(count)
+ m.clampSelection()
+ m.clampAction()
+ m.syncViewport()
+ if postKeyCmd != nil {
+ return m, postKeyCmd
+ }
+ return m, nil
+ }
+ if count := repeatedRuneKeyCount(key, 'k'); count > 1 {
+ m, postKeyCmd = m.moveSelectionBy(-count)
+ m.clampSelection()
+ m.clampAction()
+ m.syncViewport()
+ if postKeyCmd != nil {
+ return m, postKeyCmd
+ }
+ return m, nil
+ }
switch key {
case "esc":
@@ -503,13 +548,7 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.previewViewport.LineDown(1)
m.clampViewportOffset()
} else {
- rows := m.visibleRows()
- if m.selected < len(rows)-1 {
- m.selected++
- m.actionResult = nil
- m.metadataViewport.GotoTop()
- m.previewViewport.GotoTop()
- }
+ m, postKeyCmd = m.moveSelectionBy(1)
}
case "up", "k":
if m.focus == focusMetadata {
@@ -519,12 +558,7 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.previewViewport.LineUp(1)
m.clampViewportOffset()
} else {
- if m.selected > 0 {
- m.selected--
- m.actionResult = nil
- m.metadataViewport.GotoTop()
- m.previewViewport.GotoTop()
- }
+ m, postKeyCmd = m.moveSelectionBy(-1)
}
case "pgdown", "ctrl+d":
var cmd tea.Cmd
@@ -562,10 +596,60 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.clampSelection()
m.clampAction()
m.syncViewport()
+ if postKeyCmd != nil {
+ return m, postKeyCmd
+ }
}
return m, nil
}
+func repeatedRuneKeyCount(key string, r rune) int {
+ if key == "" {
+ return 0
+ }
+ count := 0
+ for _, ch := range key {
+ if ch != r {
+ return 0
+ }
+ count++
+ }
+ return count
+}
+
+func (m appModel) moveSelectionBy(delta int) (appModel, tea.Cmd) {
+ if delta == 0 {
+ return m, nil
+ }
+ rows := m.visibleRows()
+ if len(rows) == 0 {
+ return m, nil
+ }
+ previous := m.selected
+ m.selected += delta
+ if m.selected < 0 {
+ m.selected = 0
+ }
+ if m.selected >= len(rows) {
+ m.selected = len(rows) - 1
+ }
+ if m.selected == previous {
+ return m, nil
+ }
+ m.actionResult = nil
+ m.metadataViewport.GotoTop()
+ m.previewViewport.GotoTop()
+ m.previewGeneration++
+ m.previewPending = true
+ return m, schedulePreviewRefresh(m.previewGeneration)
+}
+
+func schedulePreviewRefresh(generation int) tea.Cmd {
+ return tea.Tick(previewRefreshDelay, func(time.Time) tea.Msg {
+ return previewRefreshMsg{generation: generation}
+ })
+}
+
func (m *appModel) clampAction() {
actions := m.currentActions()
if len(actions) == 0 {
diff --git a/internal/tui/view.go b/internal/tui/view.go
index 985d8d0..8a7d8d6 100644
--- a/internal/tui/view.go
+++ b/internal/tui/view.go
@@ -3,6 +3,7 @@ package tui
import (
"fmt"
"strings"
+ "time"
"charm.land/glamour/v2"
"charm.land/glamour/v2/ansi"
@@ -14,6 +15,10 @@ import (
)
func (m appModel) View() string {
+ viewStart := time.Now()
+ defer func() {
+ perfLogf("view selected=%d focus=%d modal=%t source=%q preview_pending=%t duration=%s", m.selected, m.focus, m.detailModal, m.modalSource, m.previewPending, time.Since(viewStart))
+ }()
if m.err != nil {
return fitToScreen(errorStyle.Render(fmt.Sprintf("LazySkills error: %s\n\nPress q to quit.", compat.SanitizeMetadata(m.err.Error()))), viewWidth(m.width), viewHeight(m.height))
}
@@ -38,14 +43,20 @@ func (m appModel) View() string {
return m.commandsOverlay(layout)
}
- // Keep View pure for callers: sync a local copy so render-time fallback
- // sizing does not mutate the model stored by Bubble Tea.
viewModel := m
viewModel.width = layout.Width
viewModel.height = layout.Height
- viewModel.syncViewport()
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)
+ if needsSync {
+ // Keep View pure for callers: sync a local copy only when render-time
+ // fallback sizing is needed. Normal Update paths already call syncViewport;
+ // doing it again here makes every navigation frame recompute details and
+ // previews a second time.
+ viewModel.syncViewport()
+ }
listLayout := newPaneLayout(listWidth, viewModel.height-1)
metadataLayout := newPaneLayout(rightWidth, topHeight)
@@ -71,6 +82,14 @@ func (m appModel) View() string {
return view + "\n" + footer
}
+func (m appModel) needsViewportSync(rightWidth, topHeight, bottomHeight int) bool {
+ return m.metadataViewport.Width != max(1, rightWidth-4) ||
+ m.metadataViewport.Height != max(1, topHeight-2) ||
+ m.previewViewport.Width != max(1, rightWidth-4) ||
+ m.previewViewport.Height != max(1, bottomHeight-2) ||
+ m.viewportSyncFingerprint != m.currentViewportSyncFingerprint()
+}
+
func scopeBadge(scope string) string {
switch scope {
case string(model.ScopeProject):
@@ -670,6 +689,9 @@ func (m appModel) previewLinesForRows(rows []skillsRow, width int) []string {
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.")}
+ }
return m.renderMarkdownPreviewCached(view.Preview, width)
}
@@ -692,6 +714,14 @@ func (m appModel) renderMarkdownPreviewCached(markdown string, width int) []stri
return lines
}
+func (m appModel) hasRenderedMarkdownPreview(markdown string, width int) bool {
+ if m.previewCache == nil {
+ return false
+ }
+ _, ok := m.previewCache[previewCacheKey{markdown: markdown, width: width}]
+ return ok
+}
+
func renderMarkdownPreview(markdown string, width int) []string {
markdown = stripMarkdownFrontmatter(markdown)
if strings.TrimSpace(markdown) == "" {