on main help sign in
fix(server): display available skills in client
commitd025403923d4f2fc8523d962f5e9d51a854ac801 authorChristian Rocha <christian@rocha.is> dateTue 19 May 2026, 15:33 (5 months ago) parent27a35c9
16 files changed+1130−85
internal/agent/coordinator.go+49−64 internal/app/app.go+12−3 internal/backend/backend.go+67−11 internal/backend/backend_test.go+170 internal/client/proto.go+4 internal/cmd/root.go+29−1 internal/proto/proto.go+4 internal/proto/skills.go+28 internal/pubsub/events.go+1 internal/server/events.go+27 internal/server/events_test.go+39 internal/skills/manager.go+180 internal/skills/manager_test.go+249 internal/ui/model/session_test.go+142 internal/workspace/client_workspace.go+50−6 internal/workspace/client_workspace_test.go+79
internal/agent/coordinator.go+49−64
@@ -26,7 +26,6 @@ import (
2626 "github.com/charmbracelet/crush/internal/event"
2727 "github.com/charmbracelet/crush/internal/filetracker"
2828 "github.com/charmbracelet/crush/internal/history"
29− "github.com/charmbracelet/crush/internal/home"
3029 "github.com/charmbracelet/crush/internal/hooks"
3130 "github.com/charmbracelet/crush/internal/log"
3231 "github.com/charmbracelet/crush/internal/lsp"
@@ -118,9 +117,19 @@ func NewCoordinator(
118117 filetracker filetracker.Service,
119118 lspManager *lsp.Manager,
120119 notify pubsub.Publisher[notify.Notification],
120+ skillsMgr *skills.Manager,
121121) (Coordinator, error) {
122− // Discover skills once at session start.
123− allSkills, activeSkills := discoverSkills(cfg)
122+ // Skills are pre-discovered by the caller (see app.New /
123+ // backend.CreateWorkspace) and passed in via the manager. If no
124+ // manager was provided (legacy callers), fall back to an in-line
125+ // discovery so the coordinator still works.
126+ var allSkills, activeSkills []*skills.Skill
127+ if skillsMgr != nil {
128+ allSkills = skillsMgr.AllSkills()
129+ activeSkills = skillsMgr.ActiveSkills()
130+ } else {
131+ allSkills, activeSkills = discoverSkills(cfg)
132+ }
124133 skillTracker := skills.NewTracker(activeSkills)
125134
126135 c := &coordinator{
@@ -1138,53 +1147,31 @@ func (c *coordinator) updateParentSessionCost(ctx context.Context, childSessionI
11381147 return nil
11391148}
11401149
1141−// discoverSkills runs the skill discovery pipeline and returns both the
1142−// pre-filter (all discovered, after dedup) and post-filter (active) lists.
1143−// It also emits a single diagnostic log line summarising the outcome to
1144−// help track skill-loading health over time.
1150+// discoverSkills is a thin fallback wrapper used only when no
1151+// skills.Manager has been threaded through to the coordinator. All
1152+// production call sites (backend.CreateWorkspace, setupLocalWorkspace)
1153+// run discovery in advance and pass the results via the manager;
1154+// reaching this path means a caller bypassed both. It deliberately does
1155+// NOT publish to the package-level broker — there are no subscribers in
1156+// that case, so doing so would be misleading without delivering the
1157+// snapshot anywhere useful.
11451158func discoverSkills(cfg *config.ConfigStore) (allSkills, activeSkills []*skills.Skill) {
1146− builtin, builtinStates := skills.DiscoverBuiltinWithStates()
1147− discovered := append([]*skills.Skill(nil), builtin...)
1148−
1149− var userStates []*skills.SkillState
1150− var userPaths []string
1151−
11521159 opts := cfg.Config().Options
1153− if opts != nil && len(opts.SkillsPaths) > 0 {
1154− userPaths = make([]string, 0, len(opts.SkillsPaths))
1155− for _, pth := range opts.SkillsPaths {
1156− expanded := home.Long(pth)
1157− if strings.HasPrefix(expanded, "$") {
1158− if resolved, err := cfg.Resolver().ResolveValue(expanded); err == nil {
1159− expanded = resolved
1160− }
1161− }
1162− userPaths = append(userPaths, expanded)
1163− }
1164− var userSkills []*skills.Skill
1165− userSkills, userStates = skills.DiscoverWithStates(userPaths)
1166− discovered = append(discovered, userSkills...)
1167− }
1168−
1169− allSkills = skills.Deduplicate(discovered)
1170− var disabledSkills []string
1160+ var paths, disabled []string
11711161 if opts != nil {
1172− disabledSkills = opts.DisabledSkills
1162+ paths = opts.SkillsPaths
1163+ disabled = opts.DisabledSkills
11731164 }
1174− activeSkills = skills.Filter(allSkills, disabledSkills)
1175−
1176− allStates := append([]*skills.SkillState(nil), builtinStates...)
1177− allStates = append(allStates, userStates...)
1178−
1179− allStates = skills.DeduplicateStates(allStates)
1180−
1181− slices.SortStableFunc(allStates, func(a, b *skills.SkillState) int {
1182− return strings.Compare(strings.ToLower(a.Path), strings.ToLower(b.Path))
1165+ var resolver func(string) (string, error)
1166+ if r := cfg.Resolver(); r != nil {
1167+ resolver = r.ResolveValue
1168+ }
1169+ allSkills, activeSkills, states := skills.DiscoverFromConfig(skills.DiscoveryConfig{
1170+ SkillsPaths: paths,
1171+ DisabledSkills: disabled,
1172+ Resolver: resolver,
11831173 })
1184− skills.SetLatestStates(allStates)
1185− skills.PublishStates(allStates)
1186−
1187− logDiscoveryStats(builtin, builtinStates, userStates, userPaths, allSkills, activeSkills, disabledSkills)
1174+ logDiscoveryStats(states, paths, allSkills, activeSkills, disabled)
11881175 return allSkills, activeSkills
11891176}
11901177
@@ -1232,28 +1219,26 @@ func logTurnSkillUsage(
12321219
12331220// logDiscoveryStats emits a single structured log line summarising skill
12341221// discovery for the current session. It is intentionally low-volume: one
1235−// line per session start.
1222+// line per session start. Builtin vs user counts are derived from the
1223+// SkillState.Path — builtin states use the "builtin/" embed prefix.
12361224func logDiscoveryStats(
1237− builtin []*skills.Skill,
1238− builtinStates, userStates []*skills.SkillState,
1225+ states []*skills.SkillState,
12391226 userPaths []string,
12401227 allSkills, activeSkills []*skills.Skill,
12411228 disabled []string,
12421229) {
1243− countErrors := func(states []*skills.SkillState) int {
1244− n := 0
1245− for _, s := range states {
1246− if s.State == skills.StateError {
1247− n++
1248− }
1249− }
1250− return n
1251− }
1252−
1253− userOK := 0
1254− for _, s := range userStates {
1255− if s.State == skills.StateNormal {
1230+ var builtinOK, builtinErr, userOK, userErr int
1231+ for _, s := range states {
1232+ isBuiltin := strings.HasPrefix(s.Path, "builtin/")
1233+ switch {
1234+ case isBuiltin && s.State == skills.StateNormal:
1235+ builtinOK++
1236+ case isBuiltin && s.State == skills.StateError:
1237+ builtinErr++
1238+ case !isBuiltin && s.State == skills.StateNormal:
12561239 userOK++
1240+ case !isBuiltin && s.State == skills.StateError:
1241+ userErr++
12571242 }
12581243 }
12591244
@@ -1267,10 +1252,10 @@ func logDiscoveryStats(
12671252 slog.Info(
12681253 "Skill discovery complete",
12691254 "component", "skills",
1270− "builtin_ok", len(builtin),
1271− "builtin_errors", countErrors(builtinStates),
1255+ "builtin_ok", builtinOK,
1256+ "builtin_errors", builtinErr,
12721257 "user_ok", userOK,
1273− "user_errors", countErrors(userStates),
1258+ "user_errors", userErr,
12741259 "user_paths", len(userPaths),
12751260 "deduped_total", len(allSkills),
12761261 "active", len(activeSkills),
internal/app/app.go+12−3
@@ -62,6 +62,8 @@ type App struct {
6262
6363 LSPManager *lsp.Manager
6464
65+ Skills *skills.Manager
66+
6567 config *config.ConfigStore
6668
6769 serviceEventsWG *sync.WaitGroup
@@ -75,8 +77,11 @@ type App struct {
7577 agentNotifications *pubsub.Broker[notify.Notification]
7678}
7779
78−// New initializes a new application instance.
79−func New(ctx context.Context, conn *sql.DB, store *config.ConfigStore) (*App, error) {
80+// New initializes a new application instance. skillsMgr carries the
81+// per-workspace skill discovery results computed by the caller; the
82+// caller is responsible for constructing it (typically via
83+// skills.NewManager + skills.DiscoverFromConfig).
84+func New(ctx context.Context, conn *sql.DB, store *config.ConfigStore, skillsMgr *skills.Manager) (*App, error) {
8085 q := db.New(conn)
8186 sessions := session.NewService(q, conn)
8287 messages := message.NewService(q)
@@ -95,6 +100,7 @@ func New(ctx context.Context, conn *sql.DB, store *config.ConfigStore) (*App, er
95100 Permissions: permission.NewPermissionService(store.WorkingDir(), skipPermissionsRequests, allowedTools),
96101 FileTracker: filetracker.NewService(q),
97102 LSPManager: lsp.NewManager(store),
103+ Skills: skillsMgr,
98104
99105 globalCtx: ctx,
100106
@@ -481,7 +487,9 @@ func (app *App) setupEvents() {
481487 setupSubscriber(ctx, app.serviceEventsWG, "agent-notifications", app.agentNotifications.Subscribe, app.events)
482488 setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
483489 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
484− setupSubscriber(ctx, app.serviceEventsWG, "skills", skills.SubscribeEvents, app.events)
490+ if app.Skills != nil {
491+ setupSubscriber(ctx, app.serviceEventsWG, "skills", app.Skills.SubscribeEvents, app.events)
492+ }
485493 cleanupFunc := func(context.Context) error {
486494 cancel()
487495 app.serviceEventsWG.Wait()
@@ -532,6 +540,7 @@ func (app *App) InitCoderAgent(ctx context.Context) error {
532540 app.FileTracker,
533541 app.LSPManager,
534542 app.agentNotifications,
543+ app.Skills,
535544 )
536545 if err != nil {
537546 slog.Error("Failed to create coder agent", "err", err)
internal/backend/backend.go+67−11
@@ -15,6 +15,7 @@ import (
1515 "github.com/charmbracelet/crush/internal/csync"
1616 "github.com/charmbracelet/crush/internal/db"
1717 "github.com/charmbracelet/crush/internal/proto"
18+ "github.com/charmbracelet/crush/internal/skills"
1819 "github.com/charmbracelet/crush/internal/ui/util"
1920 "github.com/charmbracelet/crush/internal/version"
2021 "github.com/google/uuid"
@@ -47,10 +48,11 @@ type Backend struct {
4748// associated resources and state.
4849type Workspace struct {
4950 *app.App
50− ID string
51− Path string
52− Cfg *config.ConfigStore
53− Env []string
51+ ID string
52+ Path string
53+ Cfg *config.ConfigStore
54+ Env []string
55+ Skills *skills.Manager
5456}
5557
5658// New creates a new [Backend].
@@ -106,17 +108,25 @@ func (b *Backend) CreateWorkspace(args proto.Workspace) (*Workspace, proto.Works
106108 return nil, proto.Workspace{}, fmt.Errorf("failed to connect to database: %w", err)
107109 }
108110
109− appWorkspace, err := app.New(b.ctx, conn, cfg)
111+ // Discover skills once per workspace, before app.New. The backend
112+ // hosts multiple workspaces concurrently, so the manager is
113+ // constructed WITHOUT WithGlobalMirror to prevent last-writer-wins
114+ // cross-talk between workspaces.
115+ allSkills, activeSkills, skillStates := skills.DiscoverFromConfig(skillsDiscoveryConfig(cfg))
116+ skillsMgr := skills.NewManager(allSkills, activeSkills, skillStates)
117+
118+ appWorkspace, err := app.New(b.ctx, conn, cfg, skillsMgr)
110119 if err != nil {
111120 return nil, proto.Workspace{}, fmt.Errorf("failed to create app workspace: %w", err)
112121 }
113122
114123 ws := &Workspace{
115− App: appWorkspace,
116− ID: id,
117− Path: args.Path,
118− Cfg: cfg,
119− Env: args.Env,
124+ App: appWorkspace,
125+ ID: id,
126+ Path: args.Path,
127+ Cfg: cfg,
128+ Env: args.Env,
129+ Skills: skillsMgr,
120130 }
121131
122132 b.workspaces.Set(id, ws)
@@ -141,11 +151,53 @@ func (b *Backend) CreateWorkspace(args proto.Workspace) (*Workspace, proto.Works
141151 YOLO: cfg.Overrides().SkipPermissionRequests,
142152 Config: cfg.Config(),
143153 Env: args.Env,
154+ Skills: skillStatesToProto(skillStates),
144155 }
145156
146157 return ws, result, nil
147158}
148159
160+// skillsDiscoveryConfig adapts a *config.ConfigStore to the
161+// skills.DiscoveryConfig that DiscoverFromConfig consumes.
162+func skillsDiscoveryConfig(cfg *config.ConfigStore) skills.DiscoveryConfig {
163+ opts := cfg.Config().Options
164+ var paths, disabled []string
165+ if opts != nil {
166+ paths = opts.SkillsPaths
167+ disabled = opts.DisabledSkills
168+ }
169+ var resolver func(string) (string, error)
170+ if r := cfg.Resolver(); r != nil {
171+ resolver = r.ResolveValue
172+ }
173+ return skills.DiscoveryConfig{
174+ SkillsPaths: paths,
175+ DisabledSkills: disabled,
176+ Resolver: resolver,
177+ }
178+}
179+
180+// skillStatesToProto converts internal skill discovery states into the
181+// wire format.
182+func skillStatesToProto(states []*skills.SkillState) []proto.SkillState {
183+ if len(states) == 0 {
184+ return nil
185+ }
186+ out := make([]proto.SkillState, len(states))
187+ for i, s := range states {
188+ entry := proto.SkillState{
189+ Name: s.Name,
190+ Path: s.Path,
191+ State: proto.SkillDiscoveryState(s.State),
192+ }
193+ if s.Err != nil {
194+ entry.Error = s.Err.Error()
195+ }
196+ out[i] = entry
197+ }
198+ return out
199+}
200+
149201// DeleteWorkspace shuts down and removes a workspace. If it was the
150202// last workspace, the shutdown callback is invoked.
151203func (b *Backend) DeleteWorkspace(id string) {
@@ -195,7 +247,7 @@ func (b *Backend) Shutdown() {
195247
196248func workspaceToProto(ws *Workspace) proto.Workspace {
197249 cfg := ws.Cfg.Config()
198− return proto.Workspace{
250+ out := proto.Workspace{
199251 ID: ws.ID,
200252 Path: ws.Path,
201253 YOLO: ws.Cfg.Overrides().SkipPermissionRequests,
@@ -203,4 +255,8 @@ func workspaceToProto(ws *Workspace) proto.Workspace {
203255 Debug: cfg.Options.Debug,
204256 Config: cfg,
205257 }
258+ if ws.Skills != nil {
259+ out.Skills = skillStatesToProto(ws.Skills.States())
260+ }
261+ return out
206262}
internal/backend/backend_test.gonew file+170
@@ -0,0 +1,170 @@
1+package backend_test
2+
3+import (
4+ "context"
5+ "fmt"
6+ "os"
7+ "path/filepath"
8+ "testing"
9+ "time"
10+
11+ tea "charm.land/bubbletea/v2"
12+ "github.com/charmbracelet/crush/internal/backend"
13+ "github.com/charmbracelet/crush/internal/config"
14+ "github.com/charmbracelet/crush/internal/proto"
15+ "github.com/charmbracelet/crush/internal/pubsub"
16+ "github.com/charmbracelet/crush/internal/skills"
17+ "github.com/stretchr/testify/require"
18+)
19+
20+// TestBackend_WorkspaceSkillsIsolation verifies that skill discovery
21+// state and SSE events are per-workspace, not process-global. This
22+// guards the structural change in §5 of the plan: two workspaces in the
23+// same backend process must not see each other's discoveries (either in
24+// their initial snapshot or in subsequent PublishStates events).
25+//
26+// Before that change landed, the package-level latestStates cache and
27+// the package-level broker meant that:
28+// - workspace A's PublishStates would arrive on workspace B's SSE
29+// stream, and
30+// - the most recent SetLatestStates would silently overwrite the
31+// other workspace's cache.
32+//
33+// This test fails on either scenario.
34+func TestBackend_WorkspaceSkillsIsolation(t *testing.T) {
35+ // Isolate all of config.Init's filesystem reads from the host. The
36+ // project-local .agents/skills/<name>/SKILL.md per working dir is
37+ // what we actually want each workspace to see; everything else
38+ // (global skills, XDG dirs, etc.) must be empty/deterministic.
39+ hostHome := t.TempDir()
40+ t.Setenv("HOME", hostHome)
41+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(hostHome, ".config"))
42+ t.Setenv("XDG_DATA_HOME", filepath.Join(hostHome, ".local", "share"))
43+ t.Setenv("XDG_CACHE_HOME", filepath.Join(hostHome, ".cache"))
44+ t.Setenv("CRUSH_SKILLS_DIR", t.TempDir())
45+
46+ // Each workspace gets its own working directory containing a
47+ // distinct project-local skill so the discovery output differs.
48+ wdA := t.TempDir()
49+ wdB := t.TempDir()
50+ writeSkill(t, wdA, "wsa-only-skill", "Workspace A only skill.")
51+ writeSkill(t, wdB, "wsb-only-skill", "Workspace B only skill.")
52+
53+ srvCfg, err := config.Init(wdA, "", false)
54+ require.NoError(t, err)
55+ b := backend.New(t.Context(), srvCfg, nil)
56+
57+ wsA, _, err := b.CreateWorkspace(proto.Workspace{
58+ Path: wdA,
59+ DataDir: filepath.Join(wdA, ".crush"),
60+ })
61+ require.NoError(t, err)
62+ t.Cleanup(func() { b.DeleteWorkspace(wsA.ID) })
63+
64+ wsB, _, err := b.CreateWorkspace(proto.Workspace{
65+ Path: wdB,
66+ DataDir: filepath.Join(wdB, ".crush"),
67+ })
68+ require.NoError(t, err)
69+ t.Cleanup(func() { b.DeleteWorkspace(wsB.ID) })
70+
71+ require.NotNil(t, wsA.Skills, "workspace A must have its own skills.Manager")
72+ require.NotNil(t, wsB.Skills, "workspace B must have its own skills.Manager")
73+ require.NotSame(t, wsA.Skills, wsB.Skills, "managers must be distinct instances per workspace")
74+
75+ // Initial snapshots see each workspace's own filesystem skill, and
76+ // neither sees the other's.
77+ statesA := wsA.Skills.States()
78+ statesB := wsB.Skills.States()
79+ require.True(t, containsSkillName(statesA, "wsa-only-skill"),
80+ "workspace A snapshot missing its own skill")
81+ require.False(t, containsSkillName(statesA, "wsb-only-skill"),
82+ "workspace A snapshot leaked workspace B's skill")
83+ require.True(t, containsSkillName(statesB, "wsb-only-skill"),
84+ "workspace B snapshot missing its own skill")
85+ require.False(t, containsSkillName(statesB, "wsa-only-skill"),
86+ "workspace B snapshot leaked workspace A's skill")
87+
88+ // Subscribe to each workspace's SSE event stream.
89+ ctxA, cancelA := context.WithCancel(t.Context())
90+ t.Cleanup(cancelA)
91+ chA, err := b.SubscribeEvents(ctxA, wsA.ID)
92+ require.NoError(t, err)
93+
94+ ctxB, cancelB := context.WithCancel(t.Context())
95+ t.Cleanup(cancelB)
96+ chB, err := b.SubscribeEvents(ctxB, wsB.ID)
97+ require.NoError(t, err)
98+
99+ // Trigger a republish on workspace A only. The marker name lets us
100+ // distinguish this event from any incidental backend activity.
101+ const marker = "wsa-republish-marker"
102+ wsA.Skills.PublishStates([]*skills.SkillState{
103+ {Name: marker, State: skills.StateNormal},
104+ })
105+
106+ // Workspace A must receive its own event.
107+ require.True(t,
108+ waitForSkillsEvent(t, chA, marker, 2*time.Second),
109+ "workspace A never received its own skills event")
110+
111+ // Workspace B must NOT receive workspace A's event.
112+ require.False(t,
113+ waitForSkillsEvent(t, chB, marker, 250*time.Millisecond),
114+ "workspace B leaked workspace A's skills event")
115+
116+ // And A's published states are now visible on its manager's
117+ // snapshot (verifies PublishStates updates the cache, not just the
118+ // broker).
119+ updatedA := wsA.Skills.States()
120+ require.True(t, containsSkillName(updatedA, marker),
121+ "PublishStates must update Manager.States()")
122+
123+ // B's manager snapshot is untouched.
124+ require.False(t, containsSkillName(wsB.Skills.States(), marker),
125+ "workspace B's Manager.States() leaked workspace A's republish")
126+}
127+
128+func writeSkill(t *testing.T, workingDir, name, desc string) {
129+ t.Helper()
130+ skillDir := filepath.Join(workingDir, ".agents", "skills", name)
131+ require.NoError(t, os.MkdirAll(skillDir, 0o755))
132+ content := fmt.Sprintf("---\nname: %s\ndescription: %s\n---\n%s\n", name, desc, desc)
133+ require.NoError(t, os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(content), 0o644))
134+}
135+
136+func containsSkillName(states []*skills.SkillState, name string) bool {
137+ for _, s := range states {
138+ if s.Name == name {
139+ return true
140+ }
141+ }
142+ return false
143+}
144+
145+// waitForSkillsEvent drains the given event channel until either a
146+// pubsub.Event[skills.Event] containing a state named marker arrives or
147+// the timeout elapses. Non-skills events on the channel are silently
148+// skipped — the backend fans in many event types and we only care
149+// about skills here.
150+func waitForSkillsEvent(t *testing.T, ch <-chan pubsub.Event[tea.Msg], marker string, timeout time.Duration) bool {
151+ t.Helper()
152+ deadline := time.After(timeout)
153+ for {
154+ select {
155+ case ev, ok := <-ch:
156+ if !ok {
157+ return false
158+ }
159+ se, ok := ev.Payload.(pubsub.Event[skills.Event])
160+ if !ok {
161+ continue
162+ }
163+ if containsSkillName(se.Payload.States, marker) {
164+ return true
165+ }
166+ case <-deadline:
167+ return false
168+ }
169+ }
170+}
internal/client/proto.go+4
@@ -168,6 +168,10 @@ func (c *Client) SubscribeEvents(ctx context.Context, id string) (<-chan any, er
168168 var e pubsub.Event[proto.AgentEvent]
169169 _ = json.Unmarshal(p.Payload, &e)
170170 sendEvent(ctx, events, e)
171+ case pubsub.PayloadTypeSkillsEvent:
172+ var e pubsub.Event[proto.SkillsEvent]
173+ _ = json.Unmarshal(p.Payload, &e)
174+ sendEvent(ctx, events, e)
171175 default:
172176 slog.Warn("Unknown event type", "type", p.Type)
173177 continue
internal/cmd/root.go+29−1
@@ -34,6 +34,7 @@ import (
3434 "github.com/charmbracelet/crush/internal/proto"
3535 "github.com/charmbracelet/crush/internal/server"
3636 "github.com/charmbracelet/crush/internal/session"
37+ "github.com/charmbracelet/crush/internal/skills"
3738 "github.com/charmbracelet/crush/internal/ui/common"
3839 ui "github.com/charmbracelet/crush/internal/ui/model"
3940 "github.com/charmbracelet/crush/internal/version"
@@ -286,7 +287,14 @@ func setupLocalWorkspace(cmd *cobra.Command) (workspace.Workspace, func(), error
286287 logFile := filepath.Join(cfg.Options.DataDirectory, "logs", "crush.log")
287288 crushlog.Setup(logFile, debug)
288289
289− appInstance, err := app.New(ctx, conn, store)
290+ // Discover skills once before app.New. Local mode hosts a single
291+ // workspace per process, so WithGlobalMirror keeps the package
292+ // globals (which the TUI reads via skills.GetLatestStates) in sync
293+ // with the manager.
294+ allSkills, activeSkills, skillStates := skills.DiscoverFromConfig(localSkillsDiscoveryConfig(store))
295+ skillsMgr := skills.NewManager(allSkills, activeSkills, skillStates, skills.WithGlobalMirror())
296+
297+ appInstance, err := app.New(ctx, conn, store, skillsMgr)
290298 if err != nil {
291299 _ = conn.Close()
292300 slog.Error("Failed to create app instance", "error", err)
@@ -302,6 +310,26 @@ func setupLocalWorkspace(cmd *cobra.Command) (workspace.Workspace, func(), error
302310 return ws, cleanup, nil
303311}
304312
313+// localSkillsDiscoveryConfig adapts a *config.ConfigStore to the inputs
314+// skills.DiscoverFromConfig expects.
315+func localSkillsDiscoveryConfig(store *config.ConfigStore) skills.DiscoveryConfig {
316+ opts := store.Config().Options
317+ var paths, disabled []string
318+ if opts != nil {
319+ paths = opts.SkillsPaths
320+ disabled = opts.DisabledSkills
321+ }
322+ var resolver func(string) (string, error)
323+ if r := store.Resolver(); r != nil {
324+ resolver = r.ResolveValue
325+ }
326+ return skills.DiscoveryConfig{
327+ SkillsPaths: paths,
328+ DisabledSkills: disabled,
329+ Resolver: resolver,
330+ }
331+}
332+
305333// setupClientServerWorkspace connects to a server process and wraps the
306334// result in a ClientWorkspace.
307335func setupClientServerWorkspace(cmd *cobra.Command) (workspace.Workspace, func(), error) {
internal/proto/proto.go+4
@@ -21,6 +21,10 @@ type Workspace struct {
2121 Version string `json:"version,omitempty"`
2222 Config *config.Config `json:"config,omitempty"`
2323 Env []string `json:"env,omitempty"`
24+ // Skills carries the snapshot of skill discovery state at workspace
25+ // creation time. Subsequent updates flow through the SSE event
26+ // stream.
27+ Skills []SkillState `json:"skills,omitempty"`
2428}
2529
2630// Error represents an error response.
internal/proto/skills.gonew file+28
@@ -0,0 +1,28 @@
1+package proto
2+
3+// SkillDiscoveryState mirrors skills.DiscoveryState across the wire.
4+// Values must stay in sync with internal/skills.DiscoveryState; do not
5+// reorder without a coordinated server/client bump.
6+type SkillDiscoveryState int
7+
8+const (
9+ // SkillStateNormal indicates the skill was parsed and validated
10+ // successfully.
11+ SkillStateNormal SkillDiscoveryState = iota
12+ // SkillStateError indicates discovery encountered a scan/parse/validate
13+ // error.
14+ SkillStateError
15+)
16+
17+// SkillState is the wire representation of skills.SkillState.
18+type SkillState struct {
19+ Name string `json:"name"`
20+ Path string `json:"path"`
21+ State SkillDiscoveryState `json:"state"`
22+ Error string `json:"error,omitempty"`
23+}
24+
25+// SkillsEvent is the wire representation of skills.Event.
26+type SkillsEvent struct {
27+ States []SkillState `json:"states"`
28+}
internal/pubsub/events.go+1
@@ -24,6 +24,7 @@ const (
2424 PayloadTypeSession PayloadType = "session"
2525 PayloadTypeFile PayloadType = "file"
2626 PayloadTypeAgentEvent PayloadType = "agent_event"
27+ PayloadTypeSkillsEvent PayloadType = "skills_event"
2728)
2829
2930// Payload wraps a discriminated JSON payload with a type tag.
internal/server/events.go+27
@@ -14,6 +14,7 @@ import (
1414 "github.com/charmbracelet/crush/internal/proto"
1515 "github.com/charmbracelet/crush/internal/pubsub"
1616 "github.com/charmbracelet/crush/internal/session"
17+ "github.com/charmbracelet/crush/internal/skills"
1718)
1819
1920// wrapEvent converts a raw tea.Msg (a pubsub.Event[T] from the app
@@ -91,6 +92,11 @@ func wrapEvent(ev any) *pubsub.Payload {
9192 Type: proto.AgentEventType(e.Payload.Type),
9293 },
9394 })
95+ case pubsub.Event[skills.Event]:
96+ return envelope(pubsub.PayloadTypeSkillsEvent, pubsub.Event[proto.SkillsEvent]{
97+ Type: e.Type,
98+ Payload: skillsEventToProto(e.Payload),
99+ })
94100 default:
95101 slog.Warn("Unrecognized event type for SSE wrapping", "type", fmt.Sprintf("%T", ev))
96102 return nil
@@ -224,6 +230,27 @@ func messageToProto(m message.Message) proto.Message {
224230 return msg
225231}
226232
233+// skillsEventToProto converts a skills.Event into its wire form. Errors
234+// are flattened to strings because error does not round-trip over JSON.
235+func skillsEventToProto(e skills.Event) proto.SkillsEvent {
236+ if len(e.States) == 0 {
237+ return proto.SkillsEvent{}
238+ }
239+ out := proto.SkillsEvent{States: make([]proto.SkillState, len(e.States))}
240+ for i, s := range e.States {
241+ entry := proto.SkillState{
242+ Name: s.Name,
243+ Path: s.Path,
244+ State: proto.SkillDiscoveryState(s.State),
245+ }
246+ if s.Err != nil {
247+ entry.Error = s.Err.Error()
248+ }
249+ out.States[i] = entry
250+ }
251+ return out
252+}
253+
227254func messagesToProto(msgs []message.Message) []proto.Message {
228255 out := make([]proto.Message, len(msgs))
229256 for i, m := range msgs {
internal/server/events_test.go+39
@@ -1,10 +1,14 @@
11package server
22
33import (
4+ "encoding/json"
5+ "errors"
46 "testing"
57
68 "github.com/charmbracelet/crush/internal/message"
79 "github.com/charmbracelet/crush/internal/proto"
10+ "github.com/charmbracelet/crush/internal/pubsub"
11+ "github.com/charmbracelet/crush/internal/skills"
812 "github.com/stretchr/testify/require"
913)
1014
@@ -44,3 +48,38 @@ func TestMessageToProtoToolResult(t *testing.T) {
4448 require.Equal(t, `{"file_path":"/tmp/x","content":"hi"}`, tr.Metadata)
4549 require.False(t, tr.IsError)
4650}
51+
52+// TestSkillsEventToProto_RoundTrip verifies that a pubsub.Event[skills.Event]
53+// can be wrapped, marshaled, and unmarshaled back through the SSE
54+// envelope without losing state values or error messages.
55+func TestSkillsEventToProto_RoundTrip(t *testing.T) {
56+ t.Parallel()
57+
58+ src := pubsub.Event[skills.Event]{
59+ Type: pubsub.UpdatedEvent,
60+ Payload: skills.Event{
61+ States: []*skills.SkillState{
62+ {Name: "ok", Path: "/p/ok", State: skills.StateNormal},
63+ {Name: "broken", Path: "/p/broken", State: skills.StateError, Err: errors.New("bad frontmatter")},
64+ },
65+ },
66+ }
67+
68+ env := wrapEvent(src)
69+ require.NotNil(t, env)
70+ require.Equal(t, pubsub.PayloadTypeSkillsEvent, env.Type)
71+
72+ var decoded pubsub.Event[proto.SkillsEvent]
73+ require.NoError(t, json.Unmarshal(env.Payload, &decoded))
74+ require.Equal(t, pubsub.UpdatedEvent, decoded.Type)
75+ require.Len(t, decoded.Payload.States, 2)
76+
77+ require.Equal(t, "ok", decoded.Payload.States[0].Name)
78+ require.Equal(t, "/p/ok", decoded.Payload.States[0].Path)
79+ require.Equal(t, proto.SkillStateNormal, decoded.Payload.States[0].State)
80+ require.Empty(t, decoded.Payload.States[0].Error)
81+
82+ require.Equal(t, "broken", decoded.Payload.States[1].Name)
83+ require.Equal(t, proto.SkillStateError, decoded.Payload.States[1].State)
84+ require.Equal(t, "bad frontmatter", decoded.Payload.States[1].Error)
85+}
internal/skills/manager.gonew file+180
@@ -0,0 +1,180 @@
1+package skills
2+
3+import (
4+ "context"
5+ "slices"
6+ "strings"
7+ "sync"
8+
9+ "github.com/charmbracelet/crush/internal/home"
10+ "github.com/charmbracelet/crush/internal/pubsub"
11+)
12+
13+// Manager owns per-workspace skill discovery state: the latest discovery
14+// snapshot, the full skill metadata (with Instructions) for the
15+// coordinator, and a pubsub broker for change events. There is exactly
16+// one Manager per workspace.
17+//
18+// Package-level helpers (GetLatestStates, SetLatestStates,
19+// PublishStates, SubscribeEvents) are preserved for callers that share a
20+// process with the TUI. To bridge a Manager to those globals, construct
21+// it with WithGlobalMirror. Only do this when the process hosts a single
22+// workspace (local mode or a client process); the backend server hosts
23+// multiple workspaces concurrently and must not enable mirroring.
24+type Manager struct {
25+ mu sync.RWMutex
26+ allSkills []*Skill
27+ activeSkills []*Skill
28+ states []*SkillState
29+
30+ broker *pubsub.Broker[Event]
31+ globalMirror bool
32+}
33+
34+// ManagerOption configures a Manager at construction time.
35+type ManagerOption func(*Manager)
36+
37+// WithGlobalMirror causes the manager to forward SetLatestStates and
38+// PublishStates calls to the package-level cache and broker. Only safe
39+// when the process hosts at most one Manager (e.g. local mode or the
40+// client process).
41+func WithGlobalMirror() ManagerOption {
42+ return func(m *Manager) {
43+ m.globalMirror = true
44+ }
45+}
46+
47+// NewManager constructs a workspace-scoped Manager with the given
48+// pre-computed discovery results. The slices are stored as-is; callers
49+// should not mutate them afterwards.
50+func NewManager(allSkills, activeSkills []*Skill, states []*SkillState, opts ...ManagerOption) *Manager {
51+ m := &Manager{
52+ allSkills: allSkills,
53+ activeSkills: activeSkills,
54+ states: states,
55+ broker: pubsub.NewBroker[Event](),
56+ }
57+ for _, opt := range opts {
58+ opt(m)
59+ }
60+ if m.globalMirror {
61+ SetLatestStates(states)
62+ }
63+ return m
64+}
65+
66+// AllSkills returns the deduplicated list of all discovered skills.
67+func (m *Manager) AllSkills() []*Skill {
68+ m.mu.RLock()
69+ defer m.mu.RUnlock()
70+ return m.allSkills
71+}
72+
73+// ActiveSkills returns the post-filter list of active skills (after
74+// removing disabled entries).
75+func (m *Manager) ActiveSkills() []*Skill {
76+ m.mu.RLock()
77+ defer m.mu.RUnlock()
78+ return m.activeSkills
79+}
80+
81+// States returns a clone of the latest discovery state snapshot.
82+func (m *Manager) States() []*SkillState {
83+ m.mu.RLock()
84+ defer m.mu.RUnlock()
85+ return cloneStates(m.states)
86+}
87+
88+// SetLatestStates updates the manager's cached discovery snapshot.
89+func (m *Manager) SetLatestStates(states []*SkillState) {
90+ m.mu.Lock()
91+ m.states = cloneStates(states)
92+ m.mu.Unlock()
93+ if m.globalMirror {
94+ SetLatestStates(states)
95+ }
96+}
97+
98+// PublishStates updates the manager's cached snapshot and publishes a
99+// discovery event to subscribers. Callers should not call
100+// SetLatestStates separately — PublishStates is the single mutation
101+// point, keeping Manager.States(), workspaceToProto, and (when
102+// WithGlobalMirror is set) skills.GetLatestStates consistent with what
103+// subscribers observe.
104+func (m *Manager) PublishStates(states []*SkillState) {
105+ m.mu.Lock()
106+ m.states = cloneStates(states)
107+ m.mu.Unlock()
108+ if m.globalMirror {
109+ SetLatestStates(states)
110+ }
111+ m.broker.Publish(pubsub.UpdatedEvent, Event{States: cloneStates(states)})
112+ if m.globalMirror {
113+ PublishStates(states)
114+ }
115+}
116+
117+// SubscribeEvents returns a channel of discovery events for the
118+// manager's workspace.
119+func (m *Manager) SubscribeEvents(ctx context.Context) <-chan pubsub.Event[Event] {
120+ return m.broker.Subscribe(ctx)
121+}
122+
123+// Shutdown releases broker resources.
124+func (m *Manager) Shutdown() {
125+ if m.broker != nil {
126+ m.broker.Shutdown()
127+ }
128+}
129+
130+// DiscoverFromConfig walks the embedded builtin FS and every path in
131+// cfg.Options.SkillsPaths (after home / env expansion), then dedups and
132+// filters by cfg.Options.DisabledSkills. It returns the three slices the
133+// rest of the system needs:
134+//
135+// - allSkills: deduplicated, pre-filter (includes disabled).
136+// - activeSkills: post-filter (DisabledSkills removed).
137+// - states: per-file discovery outcome for diagnostics/UI.
138+func DiscoverFromConfig(cfg DiscoveryConfig) (allSkills, activeSkills []*Skill, states []*SkillState) {
139+ builtin, builtinStates := DiscoverBuiltinWithStates()
140+ discovered := append([]*Skill(nil), builtin...)
141+
142+ var userStates []*SkillState
143+ var userPaths []string
144+ if len(cfg.SkillsPaths) > 0 {
145+ userPaths = make([]string, 0, len(cfg.SkillsPaths))
146+ for _, pth := range cfg.SkillsPaths {
147+ expanded := home.Long(pth)
148+ if strings.HasPrefix(expanded, "$") && cfg.Resolver != nil {
149+ if resolved, err := cfg.Resolver(expanded); err == nil {
150+ expanded = resolved
151+ }
152+ }
153+ userPaths = append(userPaths, expanded)
154+ }
155+ var userSkills []*Skill
156+ userSkills, userStates = DiscoverWithStates(userPaths)
157+ discovered = append(discovered, userSkills...)
158+ }
159+
160+ allSkills = Deduplicate(discovered)
161+ activeSkills = Filter(allSkills, cfg.DisabledSkills)
162+
163+ allStates := append([]*SkillState(nil), builtinStates...)
164+ allStates = append(allStates, userStates...)
165+ allStates = DeduplicateStates(allStates)
166+ slices.SortStableFunc(allStates, func(a, b *SkillState) int {
167+ return strings.Compare(strings.ToLower(a.Path), strings.ToLower(b.Path))
168+ })
169+ return allSkills, activeSkills, allStates
170+}
171+
172+// DiscoveryConfig contains the inputs DiscoverFromConfig needs. Using a
173+// dedicated struct (rather than importing internal/config) keeps the
174+// skills package's dependency graph small.
175+type DiscoveryConfig struct {
176+ SkillsPaths []string
177+ DisabledSkills []string
178+ // Resolver expands $VAR-style references in paths. May be nil.
179+ Resolver func(string) (string, error)
180+}
internal/skills/manager_test.gonew file+249
@@ -0,0 +1,249 @@
1+package skills
2+
3+import (
4+ "context"
5+ "errors"
6+ "os"
7+ "path/filepath"
8+ "testing"
9+ "time"
10+
11+ "github.com/stretchr/testify/require"
12+)
13+
14+func TestManager_NoGlobalMirrorByDefault(t *testing.T) {
15+ // Not parallel - touches package-level cache.
16+ prev := GetLatestStates()
17+ t.Cleanup(func() { SetLatestStates(prev) })
18+
19+ SetLatestStates(nil)
20+
21+ mgrA := NewManager(nil, nil, []*SkillState{{Name: "a", State: StateNormal}})
22+ mgrB := NewManager(nil, nil, []*SkillState{{Name: "b", State: StateNormal}})
23+
24+ mgrA.PublishStates(mgrA.States())
25+ mgrB.PublishStates(mgrB.States())
26+
27+ // Without WithGlobalMirror, the package-level cache must not be
28+ // touched by manager construction or PublishStates calls.
29+ require.Nil(t, GetLatestStates(), "package global must remain untouched")
30+ require.Equal(t, "a", mgrA.States()[0].Name)
31+ require.Equal(t, "b", mgrB.States()[0].Name)
32+}
33+
34+func TestManager_GlobalMirror(t *testing.T) {
35+ // Not parallel - touches package-level cache.
36+ prev := GetLatestStates()
37+ t.Cleanup(func() { SetLatestStates(prev) })
38+
39+ SetLatestStates(nil)
40+
41+ mgr := NewManager(nil, nil, []*SkillState{{Name: "x", State: StateNormal}}, WithGlobalMirror())
42+
43+ got := GetLatestStates()
44+ require.Len(t, got, 1)
45+ require.Equal(t, "x", got[0].Name)
46+
47+ // PublishStates with mirror enabled forwards to the global cache.
48+ mgr.SetLatestStates([]*SkillState{{Name: "y", State: StateNormal}})
49+ got = GetLatestStates()
50+ require.Len(t, got, 1)
51+ require.Equal(t, "y", got[0].Name)
52+}
53+
54+func TestManager_PublishStatesUpdatesCache(t *testing.T) {
55+ // Not parallel - exercises WithGlobalMirror, which touches the
56+ // package-level cache.
57+ prev := GetLatestStates()
58+ t.Cleanup(func() { SetLatestStates(prev) })
59+
60+ SetLatestStates(nil)
61+
62+ mgr := NewManager(nil, nil, []*SkillState{{Name: "old"}}, WithGlobalMirror())
63+ t.Cleanup(mgr.Shutdown)
64+
65+ // PublishStates must update every observable snapshot, not just the
66+ // SSE subscribers: Manager.States() (used by workspaceToProto on
67+ // the backend) and skills.GetLatestStates() (read by the TUI on the
68+ // client process and in local mode) must reflect the new value.
69+ mgr.PublishStates([]*SkillState{{Name: "new"}})
70+
71+ got := mgr.States()
72+ require.Len(t, got, 1)
73+ require.Equal(t, "new", got[0].Name)
74+
75+ cached := GetLatestStates()
76+ require.Len(t, cached, 1)
77+ require.Equal(t, "new", cached[0].Name)
78+}
79+
80+func TestManager_SubscribeReceivesPublishedStates(t *testing.T) {
81+ t.Parallel()
82+
83+ mgr := NewManager(nil, nil, nil)
84+ t.Cleanup(mgr.Shutdown)
85+
86+ ctx, cancel := context.WithCancel(context.Background())
87+ t.Cleanup(cancel)
88+ ch := mgr.SubscribeEvents(ctx)
89+
90+ want := []*SkillState{{Name: "k", State: StateNormal}}
91+ go mgr.PublishStates(want)
92+
93+ select {
94+ case ev := <-ch:
95+ require.Equal(t, "k", ev.Payload.States[0].Name)
96+ case <-time.After(2 * time.Second):
97+ t.Fatal("timed out waiting for manager event")
98+ }
99+}
100+
101+func TestManager_ConcurrentWorkspacesAreIsolated(t *testing.T) {
102+ t.Parallel()
103+
104+ // Two managers without WithGlobalMirror should not see each other's
105+ // events; this models the multi-workspace backend.
106+ mgrA := NewManager(nil, nil, nil)
107+ mgrB := NewManager(nil, nil, nil)
108+ t.Cleanup(mgrA.Shutdown)
109+ t.Cleanup(mgrB.Shutdown)
110+
111+ ctx, cancel := context.WithCancel(context.Background())
112+ t.Cleanup(cancel)
113+ chA := mgrA.SubscribeEvents(ctx)
114+ chB := mgrB.SubscribeEvents(ctx)
115+
116+ go mgrA.PublishStates([]*SkillState{{Name: "from-a"}})
117+
118+ select {
119+ case ev := <-chA:
120+ require.Equal(t, "from-a", ev.Payload.States[0].Name)
121+ case <-time.After(2 * time.Second):
122+ t.Fatal("workspace A never received its own event")
123+ }
124+
125+ select {
126+ case ev := <-chB:
127+ t.Fatalf("workspace B received workspace A's event: %v", ev)
128+ case <-time.After(100 * time.Millisecond):
129+ // Expected — B's stream is isolated.
130+ }
131+}
132+
133+func TestDiscoverFromConfig(t *testing.T) {
134+ t.Parallel()
135+
136+ tmp := t.TempDir()
137+ skillDir := filepath.Join(tmp, "custom-skill")
138+ require.NoError(t, os.MkdirAll(skillDir, 0o755))
139+ require.NoError(t, os.WriteFile(
140+ filepath.Join(skillDir, SkillFileName),
141+ []byte("---\nname: custom-skill\ndescription: A custom skill for tests.\n---\nDo a thing.\n"),
142+ 0o644,
143+ ))
144+
145+ allSkills, activeSkills, states := DiscoverFromConfig(DiscoveryConfig{
146+ SkillsPaths: []string{tmp},
147+ DisabledSkills: nil,
148+ })
149+
150+ // Builtins plus our one custom skill.
151+ require.NotEmpty(t, allSkills)
152+ require.NotEmpty(t, activeSkills)
153+ require.GreaterOrEqual(t, len(allSkills), 2)
154+ require.GreaterOrEqual(t, len(activeSkills), 2)
155+
156+ // The custom skill is present with full Instructions populated, so
157+ // the coordinator can render system prompts without re-walking the
158+ // filesystem.
159+ var custom *Skill
160+ for _, s := range allSkills {
161+ if s.Name == "custom-skill" {
162+ custom = s
163+ break
164+ }
165+ }
166+ require.NotNil(t, custom)
167+ require.NotEmpty(t, custom.Instructions, "DiscoverFromConfig must return Skill.Instructions")
168+
169+ // State snapshot includes the custom skill too.
170+ foundCustom := false
171+ for _, s := range states {
172+ if s.Name == "custom-skill" {
173+ foundCustom = true
174+ require.Equal(t, StateNormal, s.State)
175+ }
176+ }
177+ require.True(t, foundCustom, "states slice should include the custom skill")
178+}
179+
180+func TestDiscoverFromConfig_DisabledFiltered(t *testing.T) {
181+ t.Parallel()
182+
183+ tmp := t.TempDir()
184+ skillDir := filepath.Join(tmp, "off-skill")
185+ require.NoError(t, os.MkdirAll(skillDir, 0o755))
186+ require.NoError(t, os.WriteFile(
187+ filepath.Join(skillDir, SkillFileName),
188+ []byte("---\nname: off-skill\ndescription: Should be filtered.\n---\nx\n"),
189+ 0o644,
190+ ))
191+
192+ allSkills, activeSkills, states := DiscoverFromConfig(DiscoveryConfig{
193+ SkillsPaths: []string{tmp},
194+ DisabledSkills: []string{"off-skill"},
195+ })
196+
197+ // All discovered: yes; active: no.
198+ hasInAll := false
199+ for _, s := range allSkills {
200+ if s.Name == "off-skill" {
201+ hasInAll = true
202+ }
203+ }
204+ require.True(t, hasInAll, "DisabledSkills must not be removed from allSkills")
205+
206+ for _, s := range activeSkills {
207+ require.NotEqual(t, "off-skill", s.Name, "DisabledSkills must be removed from activeSkills")
208+ }
209+
210+ // State snapshot still carries discovered entries (UI re-applies filter).
211+ hasInStates := false
212+ for _, s := range states {
213+ if s.Name == "off-skill" {
214+ hasInStates = true
215+ }
216+ }
217+ require.True(t, hasInStates)
218+}
219+
220+func TestDiscoverFromConfig_Resolver(t *testing.T) {
221+ t.Parallel()
222+
223+ tmp := t.TempDir()
224+ skillDir := filepath.Join(tmp, "envvar-skill")
225+ require.NoError(t, os.MkdirAll(skillDir, 0o755))
226+ require.NoError(t, os.WriteFile(
227+ filepath.Join(skillDir, SkillFileName),
228+ []byte("---\nname: envvar-skill\ndescription: Env-resolved.\n---\nx\n"),
229+ 0o644,
230+ ))
231+
232+ allSkills, _, _ := DiscoverFromConfig(DiscoveryConfig{
233+ SkillsPaths: []string{"$CUSTOM_SKILLS_DIR"},
234+ Resolver: func(s string) (string, error) {
235+ if s == "$CUSTOM_SKILLS_DIR" {
236+ return tmp, nil
237+ }
238+ return s, errors.New("unknown")
239+ },
240+ })
241+
242+ found := false
243+ for _, s := range allSkills {
244+ if s.Name == "envvar-skill" {
245+ found = true
246+ }
247+ }
248+ require.True(t, found, "DiscoverFromConfig must expand $VAR via Resolver")
249+}
internal/ui/model/session_test.gonew file+142
@@ -0,0 +1,142 @@
1+package model
2+
3+import (
4+ "strings"
5+ "testing"
6+
7+ "charm.land/lipgloss/v2"
8+ "github.com/charmbracelet/crush/internal/history"
9+ "github.com/charmbracelet/crush/internal/ui/styles"
10+ "github.com/stretchr/testify/require"
11+)
12+
13+func TestFileList(t *testing.T) {
14+ t.Parallel()
15+
16+ t.Run("empty stats no truncation needed", func(t *testing.T) {
17+ t.Parallel()
18+
19+ st := minimalFileStyles()
20+ files := []SessionFile{
21+ {FirstVersion: history.File{Path: "main.go"}, Additions: 0, Deletions: 0},
22+ }
23+ got := fileList(st, "/", files, 30, 10)
24+ require.Contains(t, stripANSI(got), "main.go")
25+ })
26+
27+ t.Run("empty stats path truncates to width", func(t *testing.T) {
28+ t.Parallel()
29+
30+ st := minimalFileStyles()
31+ files := []SessionFile{
32+ {FirstVersion: history.File{Path: "/very/long/path/to/some/deeply/nested/file.go"}, Additions: 0, Deletions: 0},
33+ }
34+ got := fileList(st, "/", files, 10, 10)
35+ plain := stripANSI(got)
36+ for _, line := range strings.Split(plain, "\n") {
37+ require.LessOrEqual(t, lipgloss.Width(line), 10, "line exceeds sidebar width: %q", line)
38+ }
39+ })
40+
41+ t.Run("with additions and deletions fits within width", func(t *testing.T) {
42+ t.Parallel()
43+
44+ st := minimalFileStyles()
45+ files := []SessionFile{
46+ {FirstVersion: history.File{Path: "main.go"}, Additions: 5, Deletions: 3},
47+ }
48+ got := fileList(st, "/", files, 20, 10)
49+ plain := stripANSI(got)
50+ require.Contains(t, plain, "+5")
51+ require.Contains(t, plain, "-3")
52+ for _, line := range strings.Split(plain, "\n") {
53+ require.LessOrEqual(t, lipgloss.Width(line), 20, "line exceeds sidebar width: %q", line)
54+ }
55+ })
56+
57+ t.Run("narrow width with stats clamps path to zero", func(t *testing.T) {
58+ t.Parallel()
59+
60+ st := minimalFileStyles()
61+ files := []SessionFile{
62+ {FirstVersion: history.File{Path: "main.go"}, Additions: 100, Deletions: 200},
63+ }
64+ got := fileList(st, "/", files, 5, 10)
65+ plain := stripANSI(got)
66+ require.NotContains(t, plain, "main.go")
67+ require.Equal(t, "+100 -200", strings.TrimSpace(plain))
68+ })
69+
70+ t.Run("single addition only", func(t *testing.T) {
71+ t.Parallel()
72+
73+ st := minimalFileStyles()
74+ files := []SessionFile{
75+ {FirstVersion: history.File{Path: "main.go"}, Additions: 3, Deletions: 0},
76+ }
77+ got := fileList(st, "/", files, 20, 10)
78+ plain := stripANSI(got)
79+ require.Contains(t, plain, "+3")
80+ require.NotContains(t, plain, "-0")
81+ for _, line := range strings.Split(plain, "\n") {
82+ require.LessOrEqual(t, lipgloss.Width(line), 20, "line exceeds sidebar width: %q", line)
83+ }
84+ })
85+
86+ t.Run("single deletion only", func(t *testing.T) {
87+ t.Parallel()
88+
89+ st := minimalFileStyles()
90+ files := []SessionFile{
91+ {FirstVersion: history.File{Path: "main.go"}, Additions: 0, Deletions: 7},
92+ }
93+ got := fileList(st, "/", files, 20, 10)
94+ plain := stripANSI(got)
95+ require.NotContains(t, plain, "+0")
96+ require.Contains(t, plain, "-7")
97+ for _, line := range strings.Split(plain, "\n") {
98+ require.LessOrEqual(t, lipgloss.Width(line), 20, "line exceeds sidebar width: %q", line)
99+ }
100+ })
101+
102+ t.Run("max items zero returns empty", func(t *testing.T) {
103+ t.Parallel()
104+
105+ st := minimalFileStyles()
106+ files := []SessionFile{
107+ {FirstVersion: history.File{Path: "main.go"}, Additions: 1, Deletions: 1},
108+ }
109+ got := fileList(st, "/", files, 20, 0)
110+ require.Empty(t, got)
111+ })
112+}
113+
114+func minimalFileStyles() *styles.Styles {
115+ st := styles.CharmtonePantera()
116+ st.Files.Path = lipgloss.NewStyle()
117+ st.Files.Additions = lipgloss.NewStyle()
118+ st.Files.Deletions = lipgloss.NewStyle()
119+ st.Files.SectionTitle = lipgloss.NewStyle()
120+ st.Files.EmptyMessage = lipgloss.NewStyle()
121+ st.Files.TruncationHint = lipgloss.NewStyle()
122+ return &st
123+}
124+
125+func stripANSI(s string) string {
126+ var b strings.Builder
127+ esc := false
128+ for i := 0; i < len(s); i++ {
129+ if s[i] == '\x1b' {
130+ esc = true
131+ continue
132+ }
133+ if esc {
134+ if s[i] >= 'a' && s[i] <= 'z' || s[i] >= 'A' && s[i] <= 'Z' {
135+ esc = false
136+ }
137+ continue
138+ }
139+ b.WriteByte(s[i])
140+ }
141+ return b.String()
142+}
internal/workspace/client_workspace.go+50−6
@@ -2,6 +2,7 @@ package workspace
22
33import (
44 "context"
5+ "errors"
56 "fmt"
67 "log/slog"
78 "strings"
@@ -22,6 +23,7 @@ import (
2223 "github.com/charmbracelet/crush/internal/proto"
2324 "github.com/charmbracelet/crush/internal/pubsub"
2425 "github.com/charmbracelet/crush/internal/session"
26+ "github.com/charmbracelet/crush/internal/skills"
2527 "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
2628)
2729
@@ -32,20 +34,29 @@ import (
3234type ClientWorkspace struct {
3335 client *client.Client
3436
35− mu sync.RWMutex
36− ws proto.Workspace
37+ mu sync.RWMutex
38+ ws proto.Workspace
39+ skills *skills.Manager
3740}
3841
3942// NewClientWorkspace creates a new ClientWorkspace that proxies all
4043// operations through the given client SDK. The ws parameter is the
41−// proto.Workspace snapshot returned by the server at creation time.
44+// proto.Workspace snapshot returned by the server at creation time. The
45+// snapshot's Skills field seeds a process-local skills.Manager so the
46+// TUI sees discovery state before the first SSE event arrives. The
47+// manager is constructed with WithGlobalMirror because the client
48+// process represents exactly one workspace and the TUI reads
49+// skills.GetLatestStates directly at construction time.
4250func NewClientWorkspace(c *client.Client, ws proto.Workspace) *ClientWorkspace {
4351 if ws.Config != nil {
4452 ws.Config.SetupAgents()
4553 }
54+ states := protoToSkillStates(ws.Skills)
55+ mgr := skills.NewManager(nil, nil, states, skills.WithGlobalMirror())
4656 return &ClientWorkspace{
4757 client: c,
4858 ws: ws,
59+ skills: mgr,
4960 }
5061}
5162
@@ -552,7 +563,7 @@ func (w *ClientWorkspace) Subscribe(program *tea.Program) {
552563 }
553564
554565 for ev := range evc {
555− translated := translateEvent(ev)
566+ translated := w.translateEvent(ev)
556567 if translated != nil {
557568 program.Send(translated)
558569 }
@@ -564,8 +575,10 @@ func (w *ClientWorkspace) Shutdown() {
564575}
565576
566577// translateEvent converts proto-typed SSE events into the domain types
567−// that the TUI's Update() method expects.
568−func translateEvent(ev any) tea.Msg {
578+// that the TUI's Update() method expects. Skills events also update the
579+// process-local skills.Manager so callers reading
580+// skills.GetLatestStates see fresh data.
581+func (w *ClientWorkspace) translateEvent(ev any) tea.Msg {
569582 switch e := ev.(type) {
570583 case pubsub.Event[proto.LSPEvent]:
571584 return pubsub.Event[LSPEvent]{
@@ -640,6 +653,15 @@ func translateEvent(ev any) tea.Msg {
640653 Type: notify.Type(e.Payload.Type),
641654 },
642655 }
656+ case pubsub.Event[proto.SkillsEvent]:
657+ states := protoToSkillStates(e.Payload.States)
658+ if w.skills != nil {
659+ w.skills.SetLatestStates(states)
660+ }
661+ return pubsub.Event[skills.Event]{
662+ Type: e.Type,
663+ Payload: skills.Event{States: states},
664+ }
643665 default:
644666 slog.Warn("Unknown event type in translateEvent", "type", fmt.Sprintf("%T", ev))
645667 return nil
@@ -792,6 +814,28 @@ func sessionToProto(s session.Session) proto.Session {
792814 }
793815}
794816
817+// protoToSkillStates reconstructs internal skill state slices from
818+// their wire representation. Non-empty Error strings are turned into
819+// synthetic error values; the TUI never type-asserts on Err.
820+func protoToSkillStates(in []proto.SkillState) []*skills.SkillState {
821+ if len(in) == 0 {
822+ return nil
823+ }
824+ out := make([]*skills.SkillState, len(in))
825+ for i, s := range in {
826+ state := &skills.SkillState{
827+ Name: s.Name,
828+ Path: s.Path,
829+ State: skills.DiscoveryState(s.State),
830+ }
831+ if s.Error != "" {
832+ state.Err = errors.New(s.Error)
833+ }
834+ out[i] = state
835+ }
836+ return out
837+}
838+
795839func todosToProto(todos []session.Todo) []proto.Todo {
796840 if len(todos) == 0 {
797841 return nil
internal/workspace/client_workspace_test.go+79
@@ -5,6 +5,8 @@ import (
55
66 "github.com/charmbracelet/crush/internal/message"
77 "github.com/charmbracelet/crush/internal/proto"
8+ "github.com/charmbracelet/crush/internal/pubsub"
9+ "github.com/charmbracelet/crush/internal/skills"
810 "github.com/stretchr/testify/require"
911)
1012
@@ -44,3 +46,80 @@ func TestProtoToMessageToolResult(t *testing.T) {
4446 require.Equal(t, `{"file_path":"/tmp/x","content":"hi"}`, tr.Metadata)
4547 require.False(t, tr.IsError)
4648}
49+
50+// TestProtoToSkillStates verifies that the wire representation of skill
51+// discovery states reconstructs identical values on the client,
52+// including synthetic errors derived from Error strings.
53+func TestProtoToSkillStates(t *testing.T) {
54+ t.Parallel()
55+
56+ in := []proto.SkillState{
57+ {Name: "ok", Path: "/p/ok", State: proto.SkillStateNormal},
58+ {Name: "broken", Path: "/p/broken", State: proto.SkillStateError, Error: "bad frontmatter"},
59+ }
60+
61+ got := protoToSkillStates(in)
62+ require.Len(t, got, 2)
63+ require.Equal(t, "ok", got[0].Name)
64+ require.Equal(t, skills.StateNormal, got[0].State)
65+ require.NoError(t, got[0].Err)
66+ require.Equal(t, "broken", got[1].Name)
67+ require.Equal(t, skills.StateError, got[1].State)
68+ require.EqualError(t, got[1].Err, "bad frontmatter")
69+}
70+
71+// TestTranslateEvent_Skills verifies that an incoming proto.SkillsEvent
72+// is converted into pubsub.Event[skills.Event] and that the
73+// client-process skill cache is updated as a side effect, so callers
74+// reading skills.GetLatestStates see fresh data after each delta.
75+func TestTranslateEvent_Skills(t *testing.T) {
76+ // Not parallel - touches the package-level skills cache via the
77+ // manager constructed with WithGlobalMirror.
78+ prev := skills.GetLatestStates()
79+ t.Cleanup(func() { skills.SetLatestStates(prev) })
80+
81+ skills.SetLatestStates(nil)
82+
83+ w := NewClientWorkspace(nil, proto.Workspace{})
84+ ev := pubsub.Event[proto.SkillsEvent]{
85+ Type: pubsub.UpdatedEvent,
86+ Payload: proto.SkillsEvent{
87+ States: []proto.SkillState{
88+ {Name: "from-server", Path: "/p", State: proto.SkillStateNormal},
89+ },
90+ },
91+ }
92+
93+ out := w.translateEvent(ev)
94+ got, ok := out.(pubsub.Event[skills.Event])
95+ require.True(t, ok, "expected pubsub.Event[skills.Event], got %T", out)
96+ require.Len(t, got.Payload.States, 1)
97+ require.Equal(t, "from-server", got.Payload.States[0].Name)
98+
99+ // Manager (with WithGlobalMirror) propagated to the package cache.
100+ cached := skills.GetLatestStates()
101+ require.Len(t, cached, 1)
102+ require.Equal(t, "from-server", cached[0].Name)
103+}
104+
105+// TestNewClientWorkspace_SeedsSkillsCache verifies that the snapshot in
106+// proto.Workspace.Skills populates the package-level cache the TUI
107+// reads at construction time, eliminating the race between TUI startup
108+// and the first SSE event.
109+func TestNewClientWorkspace_SeedsSkillsCache(t *testing.T) {
110+ // Not parallel - touches the package-level skills cache.
111+ prev := skills.GetLatestStates()
112+ t.Cleanup(func() { skills.SetLatestStates(prev) })
113+
114+ skills.SetLatestStates(nil)
115+
116+ _ = NewClientWorkspace(nil, proto.Workspace{
117+ Skills: []proto.SkillState{
118+ {Name: "seeded", Path: "/p", State: proto.SkillStateNormal},
119+ },
120+ })
121+
122+ got := skills.GetLatestStates()
123+ require.Len(t, got, 1)
124+ require.Equal(t, "seeded", got[0].Name)
125+}