client_workspace.go

  1package workspace
  2
  3import (
  4	"context"
  5	"fmt"
  6	"log/slog"
  7	"strings"
  8	"sync"
  9	"time"
 10
 11	tea "charm.land/bubbletea/v2"
 12	"github.com/charmbracelet/crush/internal/agent/notify"
 13	"github.com/charmbracelet/crush/internal/agent/tools/mcp"
 14	"github.com/charmbracelet/crush/internal/client"
 15	"github.com/charmbracelet/crush/internal/config"
 16	"github.com/charmbracelet/crush/internal/history"
 17	"github.com/charmbracelet/crush/internal/log"
 18	"github.com/charmbracelet/crush/internal/lsp"
 19	"github.com/charmbracelet/crush/internal/message"
 20	"github.com/charmbracelet/crush/internal/oauth"
 21	"github.com/charmbracelet/crush/internal/permission"
 22	"github.com/charmbracelet/crush/internal/proto"
 23	"github.com/charmbracelet/crush/internal/pubsub"
 24	"github.com/charmbracelet/crush/internal/session"
 25	"github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
 26)
 27
 28// ClientWorkspace implements the Workspace interface by delegating all
 29// operations to a remote server via the client SDK. It caches the
 30// proto.Workspace returned at creation time and refreshes it after
 31// config-mutating operations.
 32type ClientWorkspace struct {
 33	client *client.Client
 34
 35	mu sync.RWMutex
 36	ws proto.Workspace
 37}
 38
 39// NewClientWorkspace creates a new ClientWorkspace that proxies all
 40// operations through the given client SDK. The ws parameter is the
 41// proto.Workspace snapshot returned by the server at creation time.
 42func NewClientWorkspace(c *client.Client, ws proto.Workspace) *ClientWorkspace {
 43	if ws.Config != nil {
 44		ws.Config.SetupAgents()
 45	}
 46	return &ClientWorkspace{
 47		client: c,
 48		ws:     ws,
 49	}
 50}
 51
 52// refreshWorkspace re-fetches the workspace from the server, updating
 53// the cached snapshot. Called after config-mutating operations.
 54func (w *ClientWorkspace) refreshWorkspace() {
 55	updated, err := w.client.GetWorkspace(context.Background(), w.workspaceID())
 56	if err != nil {
 57		slog.Error("Failed to refresh workspace", "error", err)
 58		return
 59	}
 60	if updated.Config != nil {
 61		updated.Config.SetupAgents()
 62	}
 63	w.mu.Lock()
 64	w.ws = *updated
 65	w.mu.Unlock()
 66}
 67
 68// cached returns a snapshot of the cached workspace.
 69func (w *ClientWorkspace) cached() proto.Workspace {
 70	w.mu.RLock()
 71	defer w.mu.RUnlock()
 72	return w.ws
 73}
 74
 75// workspaceID returns the cached workspace ID.
 76func (w *ClientWorkspace) workspaceID() string {
 77	return w.cached().ID
 78}
 79
 80// -- Sessions --
 81
 82func (w *ClientWorkspace) CreateSession(ctx context.Context, title string) (session.Session, error) {
 83	sess, err := w.client.CreateSession(ctx, w.workspaceID(), title)
 84	if err != nil {
 85		return session.Session{}, err
 86	}
 87	return protoToSession(*sess), nil
 88}
 89
 90func (w *ClientWorkspace) GetSession(ctx context.Context, sessionID string) (session.Session, error) {
 91	sess, err := w.client.GetSession(ctx, w.workspaceID(), sessionID)
 92	if err != nil {
 93		return session.Session{}, err
 94	}
 95	return protoToSession(*sess), nil
 96}
 97
 98func (w *ClientWorkspace) ListSessions(ctx context.Context) ([]session.Session, error) {
 99	protoSessions, err := w.client.ListSessions(ctx, w.workspaceID())
100	if err != nil {
101		return nil, err
102	}
103	sessions := make([]session.Session, len(protoSessions))
104	for i, s := range protoSessions {
105		sessions[i] = protoToSession(s)
106	}
107	return sessions, nil
108}
109
110func (w *ClientWorkspace) SaveSession(ctx context.Context, sess session.Session) (session.Session, error) {
111	saved, err := w.client.SaveSession(ctx, w.workspaceID(), sessionToProto(sess))
112	if err != nil {
113		return session.Session{}, err
114	}
115	return protoToSession(*saved), nil
116}
117
118func (w *ClientWorkspace) DeleteSession(ctx context.Context, sessionID string) error {
119	return w.client.DeleteSession(ctx, w.workspaceID(), sessionID)
120}
121
122func (w *ClientWorkspace) CreateAgentToolSessionID(messageID, toolCallID string) string {
123	return fmt.Sprintf("%s$$%s", messageID, toolCallID)
124}
125
126func (w *ClientWorkspace) ParseAgentToolSessionID(sessionID string) (string, string, bool) {
127	parts := strings.Split(sessionID, "$$")
128	if len(parts) != 2 {
129		return "", "", false
130	}
131	return parts[0], parts[1], true
132}
133
134// -- Messages --
135
136func (w *ClientWorkspace) ListMessages(ctx context.Context, sessionID string) ([]message.Message, error) {
137	msgs, err := w.client.ListMessages(ctx, w.workspaceID(), sessionID)
138	if err != nil {
139		return nil, err
140	}
141	return protoToMessages(msgs), nil
142}
143
144func (w *ClientWorkspace) ListUserMessages(ctx context.Context, sessionID string) ([]message.Message, error) {
145	msgs, err := w.client.ListUserMessages(ctx, w.workspaceID(), sessionID)
146	if err != nil {
147		return nil, err
148	}
149	return protoToMessages(msgs), nil
150}
151
152func (w *ClientWorkspace) ListAllUserMessages(ctx context.Context) ([]message.Message, error) {
153	msgs, err := w.client.ListAllUserMessages(ctx, w.workspaceID())
154	if err != nil {
155		return nil, err
156	}
157	return protoToMessages(msgs), nil
158}
159
160// -- Agent --
161
162func (w *ClientWorkspace) AgentRun(ctx context.Context, sessionID, prompt string, attachments ...message.Attachment) error {
163	return w.client.SendMessage(ctx, w.workspaceID(), sessionID, prompt, attachments...)
164}
165
166func (w *ClientWorkspace) AgentCancel(sessionID string) {
167	_ = w.client.CancelAgentSession(context.Background(), w.workspaceID(), sessionID)
168}
169
170func (w *ClientWorkspace) AgentIsBusy() bool {
171	info, err := w.client.GetAgentInfo(context.Background(), w.workspaceID())
172	if err != nil {
173		return false
174	}
175	return info.IsBusy
176}
177
178func (w *ClientWorkspace) AgentIsSessionBusy(sessionID string) bool {
179	info, err := w.client.GetAgentSessionInfo(context.Background(), w.workspaceID(), sessionID)
180	if err != nil {
181		return false
182	}
183	return info.IsBusy
184}
185
186func (w *ClientWorkspace) AgentModel() AgentModel {
187	info, err := w.client.GetAgentInfo(context.Background(), w.workspaceID())
188	if err != nil {
189		return AgentModel{}
190	}
191	return AgentModel{
192		CatwalkCfg: info.Model,
193		ModelCfg:   info.ModelCfg,
194	}
195}
196
197func (w *ClientWorkspace) AgentIsReady() bool {
198	info, err := w.client.GetAgentInfo(context.Background(), w.workspaceID())
199	if err != nil {
200		return false
201	}
202	return info.IsReady
203}
204
205func (w *ClientWorkspace) AgentQueuedPrompts(sessionID string) int {
206	count, err := w.client.GetAgentSessionQueuedPrompts(context.Background(), w.workspaceID(), sessionID)
207	if err != nil {
208		return 0
209	}
210	return count
211}
212
213func (w *ClientWorkspace) AgentQueuedPromptsList(sessionID string) []string {
214	prompts, err := w.client.GetAgentSessionQueuedPromptsList(context.Background(), w.workspaceID(), sessionID)
215	if err != nil {
216		return nil
217	}
218	return prompts
219}
220
221func (w *ClientWorkspace) AgentClearQueue(sessionID string) {
222	_ = w.client.ClearAgentSessionQueuedPrompts(context.Background(), w.workspaceID(), sessionID)
223}
224
225func (w *ClientWorkspace) AgentSummarize(ctx context.Context, sessionID string) error {
226	return w.client.AgentSummarizeSession(ctx, w.workspaceID(), sessionID)
227}
228
229func (w *ClientWorkspace) UpdateAgentModel(ctx context.Context) error {
230	return w.client.UpdateAgent(ctx, w.workspaceID())
231}
232
233func (w *ClientWorkspace) InitCoderAgent(ctx context.Context) error {
234	return w.client.InitiateAgentProcessing(ctx, w.workspaceID())
235}
236
237func (w *ClientWorkspace) GetDefaultSmallModel(providerID string) config.SelectedModel {
238	model, err := w.client.GetDefaultSmallModel(context.Background(), w.workspaceID(), providerID)
239	if err != nil {
240		return config.SelectedModel{}
241	}
242	return *model
243}
244
245// -- Permissions --
246
247func (w *ClientWorkspace) PermissionGrant(perm permission.PermissionRequest) bool {
248	resolved, _ := w.client.GrantPermission(context.Background(), w.workspaceID(), proto.PermissionGrant{
249		Permission: proto.PermissionRequest{
250			ID:          perm.ID,
251			SessionID:   perm.SessionID,
252			ToolCallID:  perm.ToolCallID,
253			ToolName:    perm.ToolName,
254			Description: perm.Description,
255			Action:      perm.Action,
256			Path:        perm.Path,
257			Params:      perm.Params,
258		},
259		Action: proto.PermissionAllow,
260	})
261	return resolved
262}
263
264func (w *ClientWorkspace) PermissionGrantPersistent(perm permission.PermissionRequest) bool {
265	resolved, _ := w.client.GrantPermission(context.Background(), w.workspaceID(), proto.PermissionGrant{
266		Permission: proto.PermissionRequest{
267			ID:          perm.ID,
268			SessionID:   perm.SessionID,
269			ToolCallID:  perm.ToolCallID,
270			ToolName:    perm.ToolName,
271			Description: perm.Description,
272			Action:      perm.Action,
273			Path:        perm.Path,
274			Params:      perm.Params,
275		},
276		Action: proto.PermissionAllowForSession,
277	})
278	return resolved
279}
280
281func (w *ClientWorkspace) PermissionDeny(perm permission.PermissionRequest) bool {
282	resolved, _ := w.client.GrantPermission(context.Background(), w.workspaceID(), proto.PermissionGrant{
283		Permission: proto.PermissionRequest{
284			ID:          perm.ID,
285			SessionID:   perm.SessionID,
286			ToolCallID:  perm.ToolCallID,
287			ToolName:    perm.ToolName,
288			Description: perm.Description,
289			Action:      perm.Action,
290			Path:        perm.Path,
291			Params:      perm.Params,
292		},
293		Action: proto.PermissionDeny,
294	})
295	return resolved
296}
297
298func (w *ClientWorkspace) PermissionSkipRequests() bool {
299	skip, err := w.client.GetPermissionsSkipRequests(context.Background(), w.workspaceID())
300	if err != nil {
301		return false
302	}
303	return skip
304}
305
306func (w *ClientWorkspace) PermissionSetSkipRequests(skip bool) {
307	_ = w.client.SetPermissionsSkipRequests(context.Background(), w.workspaceID(), skip)
308}
309
310// -- FileTracker --
311
312func (w *ClientWorkspace) FileTrackerRecordRead(ctx context.Context, sessionID, path string) {
313	_ = w.client.FileTrackerRecordRead(ctx, w.workspaceID(), sessionID, path)
314}
315
316func (w *ClientWorkspace) FileTrackerLastReadTime(ctx context.Context, sessionID, path string) time.Time {
317	t, err := w.client.FileTrackerLastReadTime(ctx, w.workspaceID(), sessionID, path)
318	if err != nil {
319		return time.Time{}
320	}
321	return t
322}
323
324func (w *ClientWorkspace) FileTrackerListReadFiles(ctx context.Context, sessionID string) ([]string, error) {
325	return w.client.FileTrackerListReadFiles(ctx, w.workspaceID(), sessionID)
326}
327
328// -- History --
329
330func (w *ClientWorkspace) ListSessionHistory(ctx context.Context, sessionID string) ([]history.File, error) {
331	files, err := w.client.ListSessionHistoryFiles(ctx, w.workspaceID(), sessionID)
332	if err != nil {
333		return nil, err
334	}
335	return protoToFiles(files), nil
336}
337
338// -- LSP --
339
340func (w *ClientWorkspace) LSPStart(ctx context.Context, path string) {
341	_ = w.client.LSPStart(ctx, w.workspaceID(), path)
342}
343
344func (w *ClientWorkspace) LSPStopAll(ctx context.Context) {
345	_ = w.client.LSPStopAll(ctx, w.workspaceID())
346}
347
348func (w *ClientWorkspace) LSPGetStates() map[string]LSPClientInfo {
349	states, err := w.client.GetLSPs(context.Background(), w.workspaceID())
350	if err != nil {
351		return nil
352	}
353	result := make(map[string]LSPClientInfo, len(states))
354	for k, v := range states {
355		result[k] = LSPClientInfo{
356			Name:            v.Name,
357			State:           v.State,
358			Error:           v.Error,
359			DiagnosticCount: v.DiagnosticCount,
360			ConnectedAt:     v.ConnectedAt,
361		}
362	}
363	return result
364}
365
366func (w *ClientWorkspace) LSPGetDiagnosticCounts(name string) lsp.DiagnosticCounts {
367	diags, err := w.client.GetLSPDiagnostics(context.Background(), w.workspaceID(), name)
368	if err != nil {
369		return lsp.DiagnosticCounts{}
370	}
371	var counts lsp.DiagnosticCounts
372	for _, fileDiags := range diags {
373		for _, d := range fileDiags {
374			switch d.Severity {
375			case protocol.SeverityError:
376				counts.Error++
377			case protocol.SeverityWarning:
378				counts.Warning++
379			case protocol.SeverityInformation:
380				counts.Information++
381			case protocol.SeverityHint:
382				counts.Hint++
383			}
384		}
385	}
386	return counts
387}
388
389// -- Config (read-only) --
390
391func (w *ClientWorkspace) Config() *config.Config {
392	return w.cached().Config
393}
394
395func (w *ClientWorkspace) WorkingDir() string {
396	return w.cached().Path
397}
398
399func (w *ClientWorkspace) Resolver() config.VariableResolver {
400	return config.IdentityResolver()
401}
402
403// -- Config mutations --
404
405func (w *ClientWorkspace) UpdatePreferredModel(scope config.Scope, modelType config.SelectedModelType, model config.SelectedModel) error {
406	err := w.client.UpdatePreferredModel(context.Background(), w.workspaceID(), scope, modelType, model)
407	if err == nil {
408		w.refreshWorkspace()
409	}
410	return err
411}
412
413func (w *ClientWorkspace) SetCompactMode(scope config.Scope, enabled bool) error {
414	err := w.client.SetCompactMode(context.Background(), w.workspaceID(), scope, enabled)
415	if err == nil {
416		w.refreshWorkspace()
417	}
418	return err
419}
420
421func (w *ClientWorkspace) SetProviderAPIKey(scope config.Scope, providerID string, apiKey any) error {
422	err := w.client.SetProviderAPIKey(context.Background(), w.workspaceID(), scope, providerID, apiKey)
423	if err == nil {
424		w.refreshWorkspace()
425	}
426	return err
427}
428
429func (w *ClientWorkspace) SetConfigField(scope config.Scope, key string, value any) error {
430	err := w.client.SetConfigField(context.Background(), w.workspaceID(), scope, key, value)
431	if err == nil {
432		w.refreshWorkspace()
433	}
434	return err
435}
436
437func (w *ClientWorkspace) RemoveConfigField(scope config.Scope, key string) error {
438	err := w.client.RemoveConfigField(context.Background(), w.workspaceID(), scope, key)
439	if err == nil {
440		w.refreshWorkspace()
441	}
442	return err
443}
444
445func (w *ClientWorkspace) ImportCopilot() (*oauth.Token, bool) {
446	token, ok, err := w.client.ImportCopilot(context.Background(), w.workspaceID())
447	if err != nil {
448		return nil, false
449	}
450	if ok {
451		w.refreshWorkspace()
452	}
453	return token, ok
454}
455
456func (w *ClientWorkspace) RefreshOAuthToken(ctx context.Context, scope config.Scope, providerID string) error {
457	err := w.client.RefreshOAuthToken(ctx, w.workspaceID(), scope, providerID)
458	if err == nil {
459		w.refreshWorkspace()
460	}
461	return err
462}
463
464// -- Project lifecycle --
465
466func (w *ClientWorkspace) ProjectNeedsInitialization() (bool, error) {
467	return w.client.ProjectNeedsInitialization(context.Background(), w.workspaceID())
468}
469
470func (w *ClientWorkspace) MarkProjectInitialized() error {
471	return w.client.MarkProjectInitialized(context.Background(), w.workspaceID())
472}
473
474func (w *ClientWorkspace) InitializePrompt() (string, error) {
475	return w.client.GetInitializePrompt(context.Background(), w.workspaceID())
476}
477
478// -- MCP operations --
479
480func (w *ClientWorkspace) MCPGetStates() map[string]mcp.ClientInfo {
481	states, err := w.client.MCPGetStates(context.Background(), w.workspaceID())
482	if err != nil {
483		return nil
484	}
485	result := make(map[string]mcp.ClientInfo, len(states))
486	for k, v := range states {
487		result[k] = mcp.ClientInfo{
488			Name:  v.Name,
489			State: mcp.State(v.State),
490			Error: v.Error,
491			Counts: mcp.Counts{
492				Tools:     v.ToolCount,
493				Prompts:   v.PromptCount,
494				Resources: v.ResourceCount,
495			},
496			ConnectedAt: v.ConnectedAt,
497		}
498	}
499	return result
500}
501
502func (w *ClientWorkspace) MCPRefreshPrompts(ctx context.Context, name string) {
503	_ = w.client.MCPRefreshPrompts(ctx, w.workspaceID(), name)
504}
505
506func (w *ClientWorkspace) MCPRefreshResources(ctx context.Context, name string) {
507	_ = w.client.MCPRefreshResources(ctx, w.workspaceID(), name)
508}
509
510func (w *ClientWorkspace) RefreshMCPTools(ctx context.Context, name string) {
511	_ = w.client.RefreshMCPTools(ctx, w.workspaceID(), name)
512}
513
514func (w *ClientWorkspace) ReadMCPResource(ctx context.Context, name, uri string) ([]MCPResourceContents, error) {
515	contents, err := w.client.ReadMCPResource(ctx, w.workspaceID(), name, uri)
516	if err != nil {
517		return nil, err
518	}
519	result := make([]MCPResourceContents, len(contents))
520	for i, c := range contents {
521		result[i] = MCPResourceContents{
522			URI:      c.URI,
523			MIMEType: c.MIMEType,
524			Text:     c.Text,
525			Blob:     c.Blob,
526		}
527	}
528	return result, nil
529}
530
531func (w *ClientWorkspace) GetMCPPrompt(clientID, promptID string, args map[string]string) (string, error) {
532	return w.client.GetMCPPrompt(context.Background(), w.workspaceID(), clientID, promptID, args)
533}
534
535func (w *ClientWorkspace) EnableDockerMCP(ctx context.Context) error {
536	return w.client.EnableDockerMCP(ctx, w.workspaceID())
537}
538
539func (w *ClientWorkspace) DisableDockerMCP() error {
540	return w.client.DisableDockerMCP(context.Background(), w.workspaceID())
541}
542
543// -- Lifecycle --
544
545func (w *ClientWorkspace) Subscribe(program *tea.Program) {
546	defer log.RecoverPanic("ClientWorkspace.Subscribe", func() {
547		slog.Info("TUI subscription panic: attempting graceful shutdown")
548		program.Quit()
549	})
550
551	evc, err := w.client.SubscribeEvents(context.Background(), w.workspaceID())
552	if err != nil {
553		slog.Error("Failed to subscribe to events", "error", err)
554		return
555	}
556
557	w.consumeEvents(evc, program.Send)
558}
559
560// consumeEvents drives the workspace event loop. It is split out from
561// Subscribe so tests can drive it without a real *tea.Program.
562// ConfigChanged events trigger a workspace refresh; all other events
563// are translated into domain types and forwarded to send.
564func (w *ClientWorkspace) consumeEvents(evc <-chan any, send func(tea.Msg)) {
565	for ev := range evc {
566		if _, ok := ev.(pubsub.Event[proto.ConfigChanged]); ok {
567			w.refreshWorkspace()
568			continue
569		}
570		translated := translateEvent(ev)
571		if translated != nil && send != nil {
572			send(translated)
573		}
574	}
575}
576
577func (w *ClientWorkspace) Shutdown() {
578	_ = w.client.DeleteWorkspace(context.Background(), w.workspaceID())
579}
580
581// translateEvent converts proto-typed SSE events into the domain types
582// that the TUI's Update() method expects.
583func translateEvent(ev any) tea.Msg {
584	switch e := ev.(type) {
585	case pubsub.Event[proto.LSPEvent]:
586		return pubsub.Event[LSPEvent]{
587			Type: e.Type,
588			Payload: LSPEvent{
589				Type:            LSPEventType(e.Payload.Type),
590				Name:            e.Payload.Name,
591				State:           e.Payload.State,
592				Error:           e.Payload.Error,
593				DiagnosticCount: e.Payload.DiagnosticCount,
594			},
595		}
596	case pubsub.Event[proto.MCPEvent]:
597		return pubsub.Event[mcp.Event]{
598			Type: e.Type,
599			Payload: mcp.Event{
600				Type:  protoToMCPEventType(e.Payload.Type),
601				Name:  e.Payload.Name,
602				State: mcp.State(e.Payload.State),
603				Error: e.Payload.Error,
604				Counts: mcp.Counts{
605					Tools:     e.Payload.ToolCount,
606					Prompts:   e.Payload.PromptCount,
607					Resources: e.Payload.ResourceCount,
608				},
609			},
610		}
611	case pubsub.Event[proto.PermissionRequest]:
612		return pubsub.Event[permission.PermissionRequest]{
613			Type: e.Type,
614			Payload: permission.PermissionRequest{
615				ID:          e.Payload.ID,
616				SessionID:   e.Payload.SessionID,
617				ToolCallID:  e.Payload.ToolCallID,
618				ToolName:    e.Payload.ToolName,
619				Description: e.Payload.Description,
620				Action:      e.Payload.Action,
621				Path:        e.Payload.Path,
622				Params:      e.Payload.Params,
623			},
624		}
625	case pubsub.Event[proto.PermissionNotification]:
626		return pubsub.Event[permission.PermissionNotification]{
627			Type: e.Type,
628			Payload: permission.PermissionNotification{
629				ToolCallID: e.Payload.ToolCallID,
630				Granted:    e.Payload.Granted,
631				Denied:     e.Payload.Denied,
632			},
633		}
634	case pubsub.Event[proto.Message]:
635		return pubsub.Event[message.Message]{
636			Type:    e.Type,
637			Payload: protoToMessage(e.Payload),
638		}
639	case pubsub.Event[proto.Session]:
640		return pubsub.Event[session.Session]{
641			Type:    e.Type,
642			Payload: protoToSession(e.Payload),
643		}
644	case pubsub.Event[proto.File]:
645		return pubsub.Event[history.File]{
646			Type:    e.Type,
647			Payload: protoToFile(e.Payload),
648		}
649	case pubsub.Event[proto.AgentEvent]:
650		return pubsub.Event[notify.Notification]{
651			Type: e.Type,
652			Payload: notify.Notification{
653				SessionID:    e.Payload.SessionID,
654				SessionTitle: e.Payload.SessionTitle,
655				Type:         notify.Type(e.Payload.Type),
656			},
657		}
658	default:
659		slog.Warn("Unknown event type in translateEvent", "type", fmt.Sprintf("%T", ev))
660		return nil
661	}
662}
663
664func protoToMCPEventType(t proto.MCPEventType) mcp.EventType {
665	switch t {
666	case proto.MCPEventStateChanged:
667		return mcp.EventStateChanged
668	case proto.MCPEventToolsListChanged:
669		return mcp.EventToolsListChanged
670	case proto.MCPEventPromptsListChanged:
671		return mcp.EventPromptsListChanged
672	case proto.MCPEventResourcesListChanged:
673		return mcp.EventResourcesListChanged
674	default:
675		return mcp.EventStateChanged
676	}
677}
678
679// protoToSession converts a wire-level proto.Session into the domain
680// session.Session. Fields that exist only on the wire (computed-on-read
681// signals like IsBusy, and any future presence counters) are
682// intentionally dropped here: session.Session models persisted state,
683// not transient runtime signals. UI features that need those signals
684// should either extend session.Session or read them from the proto
685// payload directly before this conversion runs.
686func protoToSession(s proto.Session) session.Session {
687	return session.Session{
688		ID:               s.ID,
689		ParentSessionID:  s.ParentSessionID,
690		Title:            s.Title,
691		SummaryMessageID: s.SummaryMessageID,
692		MessageCount:     s.MessageCount,
693		PromptTokens:     s.PromptTokens,
694		CompletionTokens: s.CompletionTokens,
695		Cost:             s.Cost,
696		Todos:            protoToTodos(s.Todos),
697		CreatedAt:        s.CreatedAt,
698		UpdatedAt:        s.UpdatedAt,
699	}
700}
701
702func protoToTodos(todos []proto.Todo) []session.Todo {
703	if len(todos) == 0 {
704		return nil
705	}
706	out := make([]session.Todo, len(todos))
707	for i, t := range todos {
708		out[i] = session.Todo{
709			Content:    t.Content,
710			Status:     session.TodoStatus(t.Status),
711			ActiveForm: t.ActiveForm,
712		}
713	}
714	return out
715}
716
717func protoToFile(f proto.File) history.File {
718	return history.File{
719		ID:        f.ID,
720		SessionID: f.SessionID,
721		Path:      f.Path,
722		Content:   f.Content,
723		Version:   f.Version,
724		CreatedAt: f.CreatedAt,
725		UpdatedAt: f.UpdatedAt,
726	}
727}
728
729func protoToMessage(m proto.Message) message.Message {
730	msg := message.Message{
731		ID:        m.ID,
732		SessionID: m.SessionID,
733		Role:      message.MessageRole(m.Role),
734		Model:     m.Model,
735		Provider:  m.Provider,
736		CreatedAt: m.CreatedAt,
737		UpdatedAt: m.UpdatedAt,
738	}
739
740	for _, p := range m.Parts {
741		switch v := p.(type) {
742		case proto.TextContent:
743			msg.Parts = append(msg.Parts, message.TextContent{Text: v.Text})
744		case proto.ReasoningContent:
745			msg.Parts = append(msg.Parts, message.ReasoningContent{
746				Thinking:   v.Thinking,
747				Signature:  v.Signature,
748				StartedAt:  v.StartedAt,
749				FinishedAt: v.FinishedAt,
750			})
751		case proto.ToolCall:
752			msg.Parts = append(msg.Parts, message.ToolCall{
753				ID:       v.ID,
754				Name:     v.Name,
755				Input:    v.Input,
756				Finished: v.Finished,
757			})
758		case proto.ToolResult:
759			msg.Parts = append(msg.Parts, message.ToolResult{
760				ToolCallID: v.ToolCallID,
761				Name:       v.Name,
762				Content:    v.Content,
763				Data:       v.Data,
764				MIMEType:   v.MIMEType,
765				Metadata:   v.Metadata,
766				IsError:    v.IsError,
767			})
768		case proto.Finish:
769			msg.Parts = append(msg.Parts, message.Finish{
770				Reason:  message.FinishReason(v.Reason),
771				Time:    v.Time,
772				Message: v.Message,
773				Details: v.Details,
774			})
775		case proto.ImageURLContent:
776			msg.Parts = append(msg.Parts, message.ImageURLContent{URL: v.URL, Detail: v.Detail})
777		case proto.BinaryContent:
778			msg.Parts = append(msg.Parts, message.BinaryContent{Path: v.Path, MIMEType: v.MIMEType, Data: v.Data})
779		}
780	}
781
782	return msg
783}
784
785func protoToMessages(msgs []proto.Message) []message.Message {
786	out := make([]message.Message, len(msgs))
787	for i, m := range msgs {
788		out[i] = protoToMessage(m)
789	}
790	return out
791}
792
793func protoToFiles(files []proto.File) []history.File {
794	out := make([]history.File, len(files))
795	for i, f := range files {
796		out[i] = protoToFile(f)
797	}
798	return out
799}
800
801func sessionToProto(s session.Session) proto.Session {
802	return proto.Session{
803		ID:               s.ID,
804		ParentSessionID:  s.ParentSessionID,
805		Title:            s.Title,
806		SummaryMessageID: s.SummaryMessageID,
807		MessageCount:     s.MessageCount,
808		PromptTokens:     s.PromptTokens,
809		CompletionTokens: s.CompletionTokens,
810		Cost:             s.Cost,
811		Todos:            todosToProto(s.Todos),
812		CreatedAt:        s.CreatedAt,
813		UpdatedAt:        s.UpdatedAt,
814	}
815}
816
817func todosToProto(todos []session.Todo) []proto.Todo {
818	if len(todos) == 0 {
819		return nil
820	}
821	out := make([]proto.Todo, len(todos))
822	for i, t := range todos {
823		out[i] = proto.Todo{
824			Content:    t.Content,
825			Status:     string(t.Status),
826			ActiveForm: t.ActiveForm,
827		}
828	}
829	return out
830}