6119
My
mysis / files
mysis / internal / tui / runner.go
8.8 KB
1package tui 2 3import ( 4 "context" 5 "fmt" 6 "strings" 7 "sync" 8 "time" 9 10 tea "github.com/charmbracelet/bubbletea" 11 "github.com/rs/zerolog/log" 12 "github.com/xonecas/mysis/internal/features" 13 "github.com/xonecas/mysis/internal/llm" 14 "github.com/xonecas/mysis/internal/mcp" 15 "github.com/xonecas/mysis/internal/provider" 16 "github.com/xonecas/mysis/internal/session" 17) 18 19// Runner manages the TUI application lifecycle. 20type Runner struct { 21 program *tea.Program 22 sessionMgr *session.Manager 23 sessionID string 24 provider provider.Provider 25 proxy *mcp.Proxy 26 tools []mcp.Tool 27 autoplayService *features.Service // Autoplay service (display-agnostic) 28 29 // Conversation history maintained by runner 30 // This is the source of truth for history, separate from the TUI display 31 history []provider.Message 32 historyMu sync.Mutex 33} 34 35// NewRunner creates a new TUI runner. 36func NewRunner( 37 ctx context.Context, 38 sessionMgr *session.Manager, 39 sessionID string, 40 prov provider.Provider, 41 proxy *mcp.Proxy, 42 tools []mcp.Tool, 43 history []provider.Message, 44) (*Runner, error) { 45 // P2: Validate critical dependencies 46 if prov == nil { 47 return nil, fmt.Errorf("provider cannot be nil") 48 } 49 if proxy == nil { 50 return nil, fmt.Errorf("proxy cannot be nil") 51 } 52 53 model := NewModel(ctx) 54 model.SetMessages(history) 55 56 r := &Runner{ 57 sessionMgr: sessionMgr, 58 sessionID: sessionID, 59 provider: prov, 60 proxy: proxy, 61 tools: tools, 62 history: history, // Keep our own copy of history 63 } 64 65 // P0: Connect the mutex between Runner and Model 66 model.historyMu = &r.historyMu 67 68 // Set up message callback 69 model.SetOnSendMessage(r.handleSendMessage) 70 model.SetOnCommand(r.handleCommand) 71 72 // Create bubbletea program 73 r.program = tea.NewProgram( 74 model, 75 tea.WithAltScreen(), 76 tea.WithMouseCellMotion(), 77 ) 78 79 // Initialize autoplay service 80 r.initAutoplayService() 81 82 return r, nil 83} 84 85// Run starts the TUI application. 86func (r *Runner) Run() error { 87 _, err := r.program.Run() 88 return err 89} 90 91// Start creates a TUI runner and starts the application. 92// This is the main entry point for TUI mode. 93func Start( 94 ctx context.Context, 95 sessionMgr *session.Manager, 96 sessionID string, 97 prov provider.Provider, 98 proxy *mcp.Proxy, 99 tools []mcp.Tool, 100 history []provider.Message, 101) error { 102 runner, err := NewRunner(ctx, sessionMgr, sessionID, prov, proxy, tools, history) 103 if err != nil { 104 return fmt.Errorf("failed to create runner: %w", err) 105 } 106 return runner.Run() 107} 108 109// handleSendMessage sends a message through the LLM loop. 110func (r *Runner) handleSendMessage(content string) error { 111 // Create user message 112 userMsg := provider.Message{ 113 Role: "user", 114 Content: content, 115 CreatedAt: time.Now(), 116 } 117 118 // Add to our history and get a copy for processing 119 r.historyMu.Lock() 120 r.history = append(r.history, userMsg) 121 historyCopy := make([]provider.Message, len(r.history)) 122 copy(historyCopy, r.history) 123 r.historyMu.Unlock() 124 125 // Send user message to TUI for display 126 r.program.Send(MessageReceivedMsg{Message: userMsg}) 127 128 // Save user message 129 if err := r.sessionMgr.SaveMessage(r.sessionID, userMsg); err != nil { 130 log.Warn().Err(err).Msg("Failed to save user message") 131 } 132 133 // Process turn in background with panic recovery 134 go func() { 135 defer func() { 136 if rec := recover(); rec != nil { 137 log.Error().Interface("panic", rec).Msg("Panic in processTurn goroutine") 138 r.program.Send(ErrorMsg{Error: fmt.Sprintf("Internal error: %v", rec)}) 139 } 140 }() 141 // Use background context for normal messages (no cancellation needed) 142 r.processTurn(context.Background(), historyCopy) 143 }() 144 145 return nil 146} 147 148// processTurn handles LLM processing and tool calls. 149func (r *Runner) processTurn(ctx context.Context, history []provider.Message) { 150 151 // User message is already in history (added synchronously in handleSendMessage) 152 // No need to append it again 153 154 // Notify TUI of LLM activity 155 r.program.Send(LLMActivityMsg{}) 156 157 // Process turn 158 err := llm.ProcessTurn(ctx, llm.ProcessTurnOptions{ 159 Provider: r.provider, 160 Proxy: r.proxy, 161 Tools: r.tools, 162 History: history, 163 OnMessage: r.onMessage, 164 OnToolCall: r.onToolCall, 165 MaxToolRounds: 20, 166 HistoryKeepLast: 10, 167 SuppressOutput: true, // Suppress stdout in TUI mode 168 }) 169 170 if err != nil { 171 log.Error().Err(err).Msg("Failed to process turn") 172 r.program.Send(ErrorMsg{Error: err.Error()}) 173 } 174} 175 176// trimHistory trims the history to keep only the last 100 messages. 177// P1: Prevents unbounded memory growth. 178// Must be called with historyMu held. 179func (r *Runner) trimHistory() { 180 const maxHistorySize = 100 181 if len(r.history) > maxHistorySize { 182 // Keep the last 100 messages 183 r.history = r.history[len(r.history)-maxHistorySize:] 184 log.Debug().Int("trimmed_to", maxHistorySize).Msg("Trimmed history to prevent unbounded growth") 185 } 186} 187 188// onMessage is called when a message is added during LLM processing. 189func (r *Runner) onMessage(msg provider.Message) { 190 // Add to our history 191 r.historyMu.Lock() 192 r.history = append(r.history, msg) 193 r.trimHistory() 194 r.historyMu.Unlock() 195 196 // Send to TUI for display 197 r.program.Send(MessageReceivedMsg{Message: msg}) 198 199 // Save to database 200 if err := r.sessionMgr.SaveMessage(r.sessionID, msg); err != nil { 201 log.Warn().Err(err).Msg("Failed to save message") 202 } 203} 204 205// onToolCall is called when tool calls are about to be executed. 206func (r *Runner) onToolCall() { 207 // Notify TUI of MCP activity 208 r.program.Send(MCPActivityMsg{}) 209} 210 211// handleCommand handles slash commands. 212func (r *Runner) handleCommand(cmd string) error { 213 parts := strings.Fields(cmd) 214 if len(parts) == 0 { 215 return nil 216 } 217 218 switch parts[0] { 219 case "/autoplay": 220 return r.handleAutoplayCommand(cmd) 221 default: 222 log.Info().Str("command", cmd).Msg("Unknown command") 223 } 224 225 return nil 226} 227 228// SendMessage sends a message to the TUI (for external use). 229func (r *Runner) SendMessage(msg provider.Message) { 230 r.program.Send(MessageReceivedMsg{Message: msg}) 231} 232 233// SendError sends an error to the TUI (for external use). 234func (r *Runner) SendError(err string) { 235 r.program.Send(ErrorMsg{Error: err}) 236} 237 238// NotifyLLMActivity notifies the TUI of LLM activity. 239func (r *Runner) NotifyLLMActivity() { 240 r.program.Send(LLMActivityMsg{}) 241} 242 243// NotifyMCPActivity notifies the TUI of MCP activity. 244func (r *Runner) NotifyMCPActivity() { 245 r.program.Send(MCPActivityMsg{}) 246} 247 248// Stop stops the TUI application. 249func (r *Runner) Stop() { 250 if r.program != nil { 251 r.program.Send(tea.Quit()) 252 } 253} 254 255// initAutoplayService initializes the autoplay service with TUI-specific callbacks. 256// This should be called once when creating the Runner. 257func (r *Runner) initAutoplayService() { 258 r.autoplayService = features.NewAutoplayService(features.AutoplayCallbacks{ 259 OnStarted: func(message string, interval time.Duration) { 260 // Send started message to TUI - use goroutine to avoid deadlock if called from Update 261 go r.program.Send(AutoplayStartedMsg{Message: message}) 262 }, 263 OnStopped: func() { 264 r.program.Send(AutoplayStoppedMsg{}) 265 }, 266 OnTurn: func(ctx context.Context, message string) error { 267 // Create user message 268 userMsg := provider.Message{ 269 Role: "user", 270 Content: message, 271 CreatedAt: time.Now(), 272 } 273 274 // Add to our history 275 r.historyMu.Lock() 276 r.history = append(r.history, userMsg) 277 historyCopy := make([]provider.Message, len(r.history)) 278 copy(historyCopy, r.history) 279 r.historyMu.Unlock() 280 281 // Send message to TUI for display 282 r.program.Send(MessageReceivedMsg{Message: userMsg}) 283 284 // Save user message 285 if err := r.sessionMgr.SaveMessage(r.sessionID, userMsg); err != nil { 286 log.Warn().Err(err).Msg("Failed to save autoplay message") 287 } 288 289 // Process turn (synchronously for autoplay to prevent overlapping turns) 290 // Use background context - let the current turn complete even if autoplay is stopped 291 // The autoplay loop will check ctx.Done() after this returns 292 r.processTurn(context.Background(), historyCopy) 293 294 return nil 295 }, 296 OnError: func(err error) { 297 log.Error().Err(err).Msg("Autoplay error") 298 r.program.Send(ErrorMsg{Error: err.Error()}) 299 }, 300 }) 301} 302 303// handleAutoplayCommand handles the /autoplay command. 304func (r *Runner) handleAutoplayCommand(cmd string) error { 305 parts := strings.Fields(cmd) 306 307 // Check for "stop" subcommand 308 if len(parts) >= 2 && parts[1] == "stop" { 309 if err := r.autoplayService.Stop(); err != nil { 310 return err 311 } 312 log.Info().Msg("Autoplay stopped") 313 // The AutoplayStoppedMsg will be sent by the service's OnStopped callback 314 return nil 315 } 316 317 // Start autoplay - need a message 318 if len(parts) < 2 { 319 return fmt.Errorf("usage: /autoplay <message> or /autoplay stop") 320 } 321 322 message := strings.Join(parts[1:], " ") 323 if message == "" { 324 return fmt.Errorf("missing message for autoplay") 325 } 326 327 // Start autoplay 328 if err := r.autoplayService.Start(context.Background(), message); err != nil { 329 return fmt.Errorf("%s - use '/autoplay stop' first", err.Error()) 330 } 331 332 return nil 333}