app_workspace.go

  1package workspace
  2
  3import (
  4	"context"
  5	"errors"
  6	"fmt"
  7	"time"
  8
  9	tea "charm.land/bubbletea/v2"
 10	"github.com/charmbracelet/crush/internal/agent"
 11	mcptools "github.com/charmbracelet/crush/internal/agent/tools/mcp"
 12	"github.com/charmbracelet/crush/internal/app"
 13	"github.com/charmbracelet/crush/internal/commands"
 14	"github.com/charmbracelet/crush/internal/config"
 15	"github.com/charmbracelet/crush/internal/history"
 16	"github.com/charmbracelet/crush/internal/lsp"
 17	"github.com/charmbracelet/crush/internal/message"
 18	"github.com/charmbracelet/crush/internal/oauth"
 19	"github.com/charmbracelet/crush/internal/permission"
 20	"github.com/charmbracelet/crush/internal/session"
 21)
 22
 23// AppWorkspace implements the Workspace interface by delegating
 24// directly to an in-process [app.App] instance. This is the default
 25// mode when the client/server architecture is not enabled.
 26type AppWorkspace struct {
 27	app   *app.App
 28	store *config.ConfigStore
 29}
 30
 31// NewAppWorkspace creates a new AppWorkspace wrapping the given app
 32// and config store.
 33func NewAppWorkspace(a *app.App, store *config.ConfigStore) *AppWorkspace {
 34	return &AppWorkspace{
 35		app:   a,
 36		store: store,
 37	}
 38}
 39
 40// -- Sessions --
 41
 42func (w *AppWorkspace) CreateSession(ctx context.Context, title string) (session.Session, error) {
 43	return w.app.Sessions.Create(ctx, title)
 44}
 45
 46func (w *AppWorkspace) GetSession(ctx context.Context, sessionID string) (session.Session, error) {
 47	return w.app.Sessions.Get(ctx, sessionID)
 48}
 49
 50func (w *AppWorkspace) ListSessions(ctx context.Context) ([]session.Session, error) {
 51	return w.app.Sessions.List(ctx)
 52}
 53
 54func (w *AppWorkspace) SaveSession(ctx context.Context, sess session.Session) (session.Session, error) {
 55	return w.app.Sessions.Save(ctx, sess)
 56}
 57
 58func (w *AppWorkspace) DeleteSession(ctx context.Context, sessionID string) error {
 59	return w.app.Sessions.Delete(ctx, sessionID)
 60}
 61
 62func (w *AppWorkspace) CreateAgentToolSessionID(messageID, toolCallID string) string {
 63	return w.app.Sessions.CreateAgentToolSessionID(messageID, toolCallID)
 64}
 65
 66func (w *AppWorkspace) ParseAgentToolSessionID(sessionID string) (string, string, bool) {
 67	return w.app.Sessions.ParseAgentToolSessionID(sessionID)
 68}
 69
 70// -- Messages --
 71
 72func (w *AppWorkspace) ListMessages(ctx context.Context, sessionID string) ([]message.Message, error) {
 73	// Drain any debounced updates so the caller observes the latest
 74	// in-memory state. message.Service buffers streaming deltas and a
 75	// cold List would otherwise miss them at session-switch time.
 76	if err := w.app.Messages.FlushAll(ctx); err != nil {
 77		return nil, err
 78	}
 79	return w.app.Messages.List(ctx, sessionID)
 80}
 81
 82func (w *AppWorkspace) ListUserMessages(ctx context.Context, sessionID string) ([]message.Message, error) {
 83	return w.app.Messages.ListUserMessages(ctx, sessionID)
 84}
 85
 86func (w *AppWorkspace) ListAllUserMessages(ctx context.Context) ([]message.Message, error) {
 87	return w.app.Messages.ListAllUserMessages(ctx)
 88}
 89
 90// -- Agent --
 91
 92func (w *AppWorkspace) AgentRun(ctx context.Context, sessionID, prompt string, attachments ...message.Attachment) error {
 93	if w.app.AgentCoordinator == nil {
 94		return errors.New("agent coordinator not initialized")
 95	}
 96	_, err := w.app.AgentCoordinator.Run(ctx, sessionID, prompt, attachments...)
 97	return err
 98}
 99
100func (w *AppWorkspace) AgentCancel(sessionID string) {
101	if w.app.AgentCoordinator != nil {
102		w.app.AgentCoordinator.Cancel(sessionID)
103	}
104}
105
106func (w *AppWorkspace) AgentIsBusy() bool {
107	if w.app.AgentCoordinator == nil {
108		return false
109	}
110	return w.app.AgentCoordinator.IsBusy()
111}
112
113func (w *AppWorkspace) AgentIsSessionBusy(sessionID string) bool {
114	if w.app.AgentCoordinator == nil {
115		return false
116	}
117	return w.app.AgentCoordinator.IsSessionBusy(sessionID)
118}
119
120func (w *AppWorkspace) AgentModel() AgentModel {
121	if w.app.AgentCoordinator == nil {
122		return AgentModel{}
123	}
124	m := w.app.AgentCoordinator.Model()
125	return AgentModel{
126		CatwalkCfg: m.CatwalkCfg,
127		ModelCfg:   m.ModelCfg,
128	}
129}
130
131func (w *AppWorkspace) AgentIsReady() bool {
132	return w.app.AgentCoordinator != nil
133}
134
135func (w *AppWorkspace) AgentQueuedPrompts(sessionID string) int {
136	if w.app.AgentCoordinator == nil {
137		return 0
138	}
139	return w.app.AgentCoordinator.QueuedPrompts(sessionID)
140}
141
142func (w *AppWorkspace) AgentQueuedPromptsList(sessionID string) []string {
143	if w.app.AgentCoordinator == nil {
144		return nil
145	}
146	return w.app.AgentCoordinator.QueuedPromptsList(sessionID)
147}
148
149func (w *AppWorkspace) AgentClearQueue(sessionID string) {
150	if w.app.AgentCoordinator != nil {
151		w.app.AgentCoordinator.ClearQueue(sessionID)
152	}
153}
154
155func (w *AppWorkspace) AgentSummarize(ctx context.Context, sessionID string) error {
156	if w.app.AgentCoordinator == nil {
157		return errors.New("agent coordinator not initialized")
158	}
159	return w.app.AgentCoordinator.Summarize(ctx, sessionID)
160}
161
162func (w *AppWorkspace) UpdateAgentModel(ctx context.Context) error {
163	return w.app.UpdateAgentModel(ctx)
164}
165
166func (w *AppWorkspace) InitCoderAgent(ctx context.Context) error {
167	return w.app.InitCoderAgent(ctx)
168}
169
170func (w *AppWorkspace) GetDefaultSmallModel(providerID string) config.SelectedModel {
171	return w.app.GetDefaultSmallModel(providerID)
172}
173
174// -- Permissions --
175
176func (w *AppWorkspace) PermissionGrant(perm permission.PermissionRequest) {
177	w.app.Permissions.Grant(perm)
178}
179
180func (w *AppWorkspace) PermissionGrantPersistent(perm permission.PermissionRequest) {
181	w.app.Permissions.GrantPersistent(perm)
182}
183
184func (w *AppWorkspace) PermissionDeny(perm permission.PermissionRequest) {
185	w.app.Permissions.Deny(perm)
186}
187
188func (w *AppWorkspace) PermissionSkipRequests() bool {
189	return w.app.Permissions.SkipRequests()
190}
191
192func (w *AppWorkspace) PermissionSetSkipRequests(skip bool) {
193	w.app.Permissions.SetSkipRequests(skip)
194}
195
196// -- FileTracker --
197
198func (w *AppWorkspace) FileTrackerRecordRead(ctx context.Context, sessionID, path string) {
199	w.app.FileTracker.RecordRead(ctx, sessionID, path)
200}
201
202func (w *AppWorkspace) FileTrackerLastReadTime(ctx context.Context, sessionID, path string) time.Time {
203	return w.app.FileTracker.LastReadTime(ctx, sessionID, path)
204}
205
206func (w *AppWorkspace) FileTrackerListReadFiles(ctx context.Context, sessionID string) ([]string, error) {
207	return w.app.FileTracker.ListReadFiles(ctx, sessionID)
208}
209
210// -- History --
211
212func (w *AppWorkspace) ListSessionHistory(ctx context.Context, sessionID string) ([]history.File, error) {
213	return w.app.History.ListBySession(ctx, sessionID)
214}
215
216// -- LSP --
217
218func (w *AppWorkspace) LSPStart(ctx context.Context, path string) {
219	w.app.LSPManager.Start(ctx, path)
220}
221
222func (w *AppWorkspace) LSPStopAll(ctx context.Context) {
223	w.app.LSPManager.StopAll(ctx)
224}
225
226func (w *AppWorkspace) LSPGetStates() map[string]LSPClientInfo {
227	states := app.GetLSPStates()
228	result := make(map[string]LSPClientInfo, len(states))
229	for k, v := range states {
230		result[k] = LSPClientInfo{
231			Name:            v.Name,
232			State:           v.State,
233			Error:           v.Error,
234			DiagnosticCount: v.DiagnosticCount,
235			ConnectedAt:     v.ConnectedAt,
236		}
237	}
238	return result
239}
240
241func (w *AppWorkspace) LSPGetDiagnosticCounts(name string) lsp.DiagnosticCounts {
242	state, ok := app.GetLSPState(name)
243	if !ok || state.Client == nil {
244		return lsp.DiagnosticCounts{}
245	}
246	return state.Client.GetDiagnosticCounts()
247}
248
249// -- Config (read-only) --
250
251func (w *AppWorkspace) Config() *config.Config {
252	return w.store.Config()
253}
254
255func (w *AppWorkspace) WorkingDir() string {
256	return w.store.WorkingDir()
257}
258
259func (w *AppWorkspace) Resolver() config.VariableResolver {
260	return w.store.Resolver()
261}
262
263// -- Config mutations --
264
265func (w *AppWorkspace) UpdatePreferredModel(scope config.Scope, modelType config.SelectedModelType, model config.SelectedModel) error {
266	return w.store.UpdatePreferredModel(scope, modelType, model)
267}
268
269func (w *AppWorkspace) SetCompactMode(scope config.Scope, enabled bool) error {
270	return w.store.SetCompactMode(scope, enabled)
271}
272
273func (w *AppWorkspace) SetProviderAPIKey(scope config.Scope, providerID string, apiKey any) error {
274	return w.store.SetProviderAPIKey(scope, providerID, apiKey)
275}
276
277func (w *AppWorkspace) SetConfigField(scope config.Scope, key string, value any) error {
278	return w.store.SetConfigField(scope, key, value)
279}
280
281func (w *AppWorkspace) RemoveConfigField(scope config.Scope, key string) error {
282	return w.store.RemoveConfigField(scope, key)
283}
284
285func (w *AppWorkspace) ImportCopilot() (*oauth.Token, bool) {
286	return w.store.ImportCopilot()
287}
288
289func (w *AppWorkspace) RefreshOAuthToken(ctx context.Context, scope config.Scope, providerID string) error {
290	return w.store.RefreshOAuthToken(ctx, scope, providerID)
291}
292
293// -- Project lifecycle --
294
295func (w *AppWorkspace) ProjectNeedsInitialization() (bool, error) {
296	return config.ProjectNeedsInitialization(w.store)
297}
298
299func (w *AppWorkspace) MarkProjectInitialized() error {
300	return config.MarkProjectInitialized(w.store)
301}
302
303func (w *AppWorkspace) InitializePrompt() (string, error) {
304	return agent.InitializePrompt(w.store)
305}
306
307// -- MCP operations --
308
309func (w *AppWorkspace) MCPGetStates() map[string]mcptools.ClientInfo {
310	return mcptools.GetStates()
311}
312
313func (w *AppWorkspace) MCPRefreshPrompts(ctx context.Context, name string) {
314	mcptools.RefreshPrompts(ctx, name)
315}
316
317func (w *AppWorkspace) MCPRefreshResources(ctx context.Context, name string) {
318	mcptools.RefreshResources(ctx, name)
319}
320
321func (w *AppWorkspace) RefreshMCPTools(ctx context.Context, name string) {
322	mcptools.RefreshTools(ctx, w.store, name)
323}
324
325func (w *AppWorkspace) ReadMCPResource(ctx context.Context, name, uri string) ([]MCPResourceContents, error) {
326	contents, err := mcptools.ReadResource(ctx, w.store, name, uri)
327	if err != nil {
328		return nil, err
329	}
330	result := make([]MCPResourceContents, len(contents))
331	for i, c := range contents {
332		result[i] = MCPResourceContents{
333			URI:      c.URI,
334			MIMEType: c.MIMEType,
335			Text:     c.Text,
336			Blob:     c.Blob,
337		}
338	}
339	return result, nil
340}
341
342func (w *AppWorkspace) GetMCPPrompt(clientID, promptID string, args map[string]string) (string, error) {
343	return commands.GetMCPPrompt(w.store, clientID, promptID, args)
344}
345
346func (w *AppWorkspace) EnableDockerMCP(ctx context.Context) error {
347	mcpConfig, err := w.store.PrepareDockerMCPConfig()
348	if err != nil {
349		return err
350	}
351
352	if err := mcptools.InitializeSingle(ctx, config.DockerMCPName, w.store); err != nil {
353		disableErr := mcptools.DisableSingle(w.store, config.DockerMCPName)
354		delete(w.store.Config().MCP, config.DockerMCPName)
355		return fmt.Errorf("failed to start docker MCP: %w", errors.Join(err, disableErr))
356	}
357
358	if err := w.store.PersistDockerMCPConfig(mcpConfig); err != nil {
359		disableErr := mcptools.DisableSingle(w.store, config.DockerMCPName)
360		delete(w.store.Config().MCP, config.DockerMCPName)
361		return fmt.Errorf("docker MCP started but failed to persist configuration: %w", errors.Join(err, disableErr))
362	}
363
364	return nil
365}
366
367func (w *AppWorkspace) DisableDockerMCP() error {
368	if err := mcptools.DisableSingle(w.store, config.DockerMCPName); err != nil {
369		return fmt.Errorf("failed to disable docker MCP: %w", err)
370	}
371	return w.store.DisableDockerMCP()
372}
373
374// -- Lifecycle --
375
376func (w *AppWorkspace) Subscribe(program *tea.Program) {
377	w.app.Subscribe(program)
378}
379
380func (w *AppWorkspace) Shutdown() {
381	w.app.Shutdown()
382}
383
384// App returns the underlying app.App instance.
385func (w *AppWorkspace) App() *app.App {
386	return w.app
387}
388
389// Store returns the underlying config store.
390func (w *AppWorkspace) Store() *config.ConfigStore {
391	return w.store
392}
393
394// Compile-time check that AppWorkspace implements Workspace.
395var _ Workspace = (*AppWorkspace)(nil)