-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
664 lines (593 loc) · 18.3 KB
/
Copy pathapp.go
File metadata and controls
664 lines (593 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
package main
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"time"
"ccui/automation"
"ccui/backend"
"ccui/backend/anthropic"
"ccui/backend/tools"
"ccui/permission"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
type SessionMode = backend.SessionMode // Wails binding compatibility
type SessionInfo struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt string `json:"createdAt"`
ModeID string `json:"modeId"`
}
type SessionState struct {
ID, Name string
CreatedAt time.Time
Session backend.Session // unified session interface
EventChan chan backend.Event
}
// UserQuestion is emitted to frontend
type UserQuestion struct {
RequestID string `json:"requestId"`
Question string `json:"question"`
Options []Option `json:"options,omitempty"`
}
type Option struct {
Label string `json:"label"`
Description string `json:"description,omitempty"`
}
// UserAnswer received from frontend
type UserAnswer struct {
RequestID string `json:"requestId"`
Answer string `json:"answer"`
}
type App struct {
ctx context.Context
sessions map[string]*SessionState
activeSessionID string
sessionMu sync.RWMutex
ptyManager *PTYManager
responseCh chan UserAnswer // native AskUserQuestion channel
// backend infrastructure
backend backend.AgentBackend // unified backend
permLayer *permission.Layer
toolReg *tools.Registry
// automations
automationStore *automation.Store
runStore *automation.RunStore
engine *automation.Engine
scheduler *automation.Scheduler
}
func NewApp() *App {
return &App{
sessions: make(map[string]*SessionState),
}
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
a.responseCh = make(chan UserAnswer, 1)
// init permission layer with wails emitter
a.permLayer = permission.NewLayer(permission.DefaultRules(), &wailsEmitter{ctx: ctx})
// init tool registry
a.toolReg = tools.NewRegistry()
a.toolReg.Register(tools.NewReadTool())
a.toolReg.Register(tools.NewGlobTool())
a.toolReg.Register(tools.NewGrepTool())
a.toolReg.Register(tools.NewBashTool())
a.toolReg.Register(tools.NewWriteTool())
a.toolReg.Register(tools.NewEditTool())
apiKey := os.Getenv("ANTHROPIC_API_KEY")
if apiKey != "" {
a.backend = anthropic.NewAnthropicBackend(anthropic.BackendConfig{
APIKey: apiKey,
BaseURL: os.Getenv("ANTHROPIC_BASE_URL"),
Executor: a.toolReg,
PermLayer: a.permLayer,
})
slog.Info("anthropic backend initialized")
} else {
slog.Error("ANTHROPIC_API_KEY not set, backend not initialized")
}
// init automation infrastructure
homeDir, _ := os.UserHomeDir()
automationDir := filepath.Join(homeDir, ".ccui", "automations")
if store, err := automation.NewStore(automationDir); err != nil {
slog.Error("failed to init automation store", "error", err)
} else {
a.automationStore = store
}
if rs, err := automation.NewRunStore(filepath.Join(automationDir, "runs")); err != nil {
slog.Error("failed to init run store", "error", err)
} else {
a.runStore = rs
}
if a.automationStore != nil && a.runStore != nil {
emitter := &wailsEmitter{ctx: ctx}
skillStore := automation.NewSkillStore(filepath.Join(homeDir, ".ccui", "skills"))
a.engine = automation.NewEngine(a.backendFactory(ctx), a.runStore, emitter, skillStore)
a.scheduler = automation.NewScheduler(ctx, a.automationStore, a.engine)
a.scheduler.Start()
}
wailsRuntime.EventsOn(ctx, "send_message", a.handleSendMessage)
wailsRuntime.EventsOn(ctx, "permission_response", a.handlePermissionResponse)
wailsRuntime.EventsOn(ctx, "user_answer", a.handleUserAnswer)
wailsRuntime.EventsOn(ctx, "cancel", a.handleCancel)
wailsRuntime.EventsOn(ctx, "submit_review", a.handleSubmitReview)
a.StartTerminalListeners()
}
// backendFactory returns a function that creates backends for automation runs
func (a *App) backendFactory(ctx context.Context) automation.BackendFactory {
return func(backendType string) (backend.AgentBackend, error) {
apiKey := os.Getenv("ANTHROPIC_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("ANTHROPIC_API_KEY required for anthropic backend")
}
return anthropic.NewAnthropicBackend(anthropic.BackendConfig{
APIKey: apiKey,
BaseURL: os.Getenv("ANTHROPIC_BASE_URL"),
Executor: a.toolReg,
PermLayer: permission.NewLayer(permission.DefaultRules(), &noopEmitter{}),
}), nil
}
}
// noopEmitter for automation permission layers
type noopEmitter struct{}
func (n *noopEmitter) Emit(string, any) {}
// wailsEmitter adapts wails runtime to permission.EventEmitter
type wailsEmitter struct{ ctx context.Context }
func (e *wailsEmitter) Emit(eventName string, data any) {
wailsRuntime.EventsEmit(e.ctx, eventName, data)
}
func (a *App) CreateSession(name string) (string, error) {
cwd, _ := os.Getwd()
sessionID := fmt.Sprintf("session-%d", time.Now().UnixNano())
eventPrefix := fmt.Sprintf("session:%s:", sessionID)
eventChan := make(chan backend.Event, 100)
sess, err := a.backend.NewSession(a.ctx, backend.SessionOpts{
CWD: cwd,
EventChan: eventChan,
AskUser: a.askUser,
})
if err != nil {
close(eventChan)
return "", fmt.Errorf("create session: %w", err)
}
state := &SessionState{ID: sessionID, Name: name, CreatedAt: time.Now(), Session: sess, EventChan: eventChan}
go a.bridgeEvents(eventPrefix, eventChan, "chat_chunk")
a.sessionMu.Lock()
a.sessions[sessionID], a.activeSessionID = state, sessionID
a.sessionMu.Unlock()
wailsRuntime.EventsEmit(a.ctx, "sessions_updated", a.GetSessions())
wailsRuntime.EventsEmit(a.ctx, "active_session_changed", sessionID)
if modes := state.Session.AvailableModes(); len(modes) > 0 {
wailsRuntime.EventsEmit(a.ctx, eventPrefix+"modes_available", modes)
wailsRuntime.EventsEmit(a.ctx, eventPrefix+"mode_changed", state.Session.CurrentMode())
}
return sessionID, nil
}
func (a *App) bridgeEvents(prefix string, eventChan <-chan backend.Event, chunkEventName string) {
for event := range eventChan {
switch event.Type {
case backend.EventMessageChunk:
wailsRuntime.EventsEmit(a.ctx, prefix+chunkEventName, event.Data)
case backend.EventThoughtChunk:
wailsRuntime.EventsEmit(a.ctx, prefix+"chat_thought", event.Data)
case backend.EventToolState:
wailsRuntime.EventsEmit(a.ctx, prefix+"tool_state", event.Data)
case backend.EventModeChanged:
wailsRuntime.EventsEmit(a.ctx, prefix+"mode_changed", event.Data)
case backend.EventPlanUpdate:
wailsRuntime.EventsEmit(a.ctx, prefix+"plan_update", event.Data)
case backend.EventPromptComplete:
wailsRuntime.EventsEmit(a.ctx, prefix+"prompt_complete", event.Data)
case backend.EventTokenUsage:
wailsRuntime.EventsEmit(a.ctx, prefix+"token_usage", event.Data)
case backend.EventFileChanges:
wailsRuntime.EventsEmit(a.ctx, prefix+"file_changes_updated", event.Data)
case backend.EventContextFull:
wailsRuntime.EventsEmit(a.ctx, prefix+"context_full", event.Data)
}
}
}
func (a *App) SwitchSession(sessionID string) error {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
if a.sessions[sessionID] == nil {
return fmt.Errorf("session not found: %s", sessionID)
}
a.activeSessionID = sessionID
wailsRuntime.EventsEmit(a.ctx, "active_session_changed", sessionID)
return nil
}
func (a *App) CloseSession(sessionID string) error {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
state := a.sessions[sessionID]
if state == nil {
return fmt.Errorf("session not found: %s", sessionID)
}
if state.Session != nil {
go state.Session.Close()
}
if state.EventChan != nil {
close(state.EventChan)
}
delete(a.sessions, sessionID)
if a.activeSessionID == sessionID {
for id := range a.sessions {
a.activeSessionID = id
break
}
if len(a.sessions) == 0 {
a.activeSessionID = ""
}
}
wailsRuntime.EventsEmit(a.ctx, "sessions_updated", a.getSessionsLocked())
wailsRuntime.EventsEmit(a.ctx, "active_session_changed", a.activeSessionID)
return nil
}
func (a *App) GetSessions() []SessionInfo {
a.sessionMu.RLock()
defer a.sessionMu.RUnlock()
return a.getSessionsLocked()
}
func (a *App) getSessionsLocked() []SessionInfo {
result := make([]SessionInfo, 0, len(a.sessions))
for _, s := range a.sessions {
info := SessionInfo{ID: s.ID, Name: s.Name, CreatedAt: s.CreatedAt.Format(time.RFC3339)}
if s.Session != nil {
info.ModeID = s.Session.CurrentMode()
}
result = append(result, info)
}
return result
}
func (a *App) GetActiveSession() string {
a.sessionMu.RLock()
defer a.sessionMu.RUnlock()
return a.activeSessionID
}
func (a *App) getActiveSession() backend.Session {
a.sessionMu.RLock()
defer a.sessionMu.RUnlock()
if state := a.sessions[a.activeSessionID]; state != nil {
return state.Session
}
return nil
}
func (a *App) getActiveState() *SessionState {
a.sessionMu.RLock()
defer a.sessionMu.RUnlock()
return a.sessions[a.activeSessionID]
}
// askUser is the native AskUserQuestion callback for interactive sessions.
// Emits user_question event and blocks until frontend responds via user_answer.
func (a *App) askUser(ctx context.Context, input map[string]any) (string, error) {
question, _ := input["question"].(string)
if question == "" {
return "", fmt.Errorf("question is required")
}
var options []Option
if opts, ok := input["options"].([]interface{}); ok {
for _, opt := range opts {
if optMap, ok := opt.(map[string]interface{}); ok {
o := Option{}
if l, ok := optMap["label"].(string); ok {
o.Label = l
}
if d, ok := optMap["description"].(string); ok {
o.Description = d
}
if o.Label != "" {
options = append(options, o)
}
}
}
}
requestID := fmt.Sprintf("uq-%d", time.Now().UnixNano())
wailsRuntime.EventsEmit(a.ctx, "user_question", UserQuestion{
RequestID: requestID,
Question: question,
Options: options,
})
// Block until user responds or context cancelled
select {
case answer := <-a.responseCh:
return answer.Answer, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func (a *App) handleSendMessage(data ...interface{}) {
input, ok := firstAs[string](data)
if !ok {
return
}
go func() {
state := a.getActiveState()
if state == nil || state.Session == nil {
wailsRuntime.EventsEmit(a.ctx, "error", "No active session")
return
}
eventPrefix := fmt.Sprintf("session:%s:", state.ID)
if err := state.Session.SendPrompt(input, []string{}); err != nil {
slog.Error("prompt failed", "error", err)
wailsRuntime.EventsEmit(a.ctx, eventPrefix+"error", err.Error())
}
}()
}
func (a *App) handlePermissionResponse(data ...interface{}) {
if optionID, ok := firstAs[string](data); ok {
// Anthropic backend permission response
if a.permLayer != nil {
// extract toolCallId from data if present
if len(data) >= 2 {
if m, ok := data[1].(map[string]interface{}); ok {
if toolCallID, ok := m["toolCallId"].(string); ok {
a.permLayer.Respond(toolCallID, optionID)
return
}
}
}
}
}
}
func (a *App) handleUserAnswer(data ...interface{}) {
if m, ok := firstAs[map[string]interface{}](data); ok {
select {
case a.responseCh <- UserAnswer{RequestID: mapStr(m, "requestId"), Answer: mapStr(m, "answer")}:
default:
}
}
}
func (a *App) handleCancel(data ...interface{}) {
if sess := a.getActiveSession(); sess != nil {
sess.Cancel()
}
}
func (a *App) handleSubmitReview(data ...interface{}) {
if commentsRaw, ok := firstAs[[]interface{}](data); ok {
a.SubmitReview(parseReviewComments(commentsRaw))
}
}
func (a *App) shutdown(ctx context.Context) {
if a.scheduler != nil {
a.scheduler.Stop()
}
if a.ptyManager != nil {
a.ptyManager.StopAll()
}
a.sessionMu.Lock()
for _, s := range a.sessions {
if s.Session != nil {
s.Session.Close()
}
if s.EventChan != nil {
close(s.EventChan)
}
}
a.sessionMu.Unlock()
}
func (a *App) SetMode(modeID string) error {
if sess := a.getActiveSession(); sess != nil {
return sess.SetMode(modeID)
}
return fmt.Errorf("no active session")
}
func (a *App) GetModes() []SessionMode {
if sess := a.getActiveSession(); sess != nil {
return sess.AvailableModes()
}
return nil
}
func (a *App) GetCurrentMode() string {
if sess := a.getActiveSession(); sess != nil {
return sess.CurrentMode()
}
return ""
}
type ReviewComment struct{ ID, Type, FilePath, Text string; LineNumber, HunkIndex int }
func (a *App) SubmitReview(comments []ReviewComment) {
state := a.getActiveState()
if state == nil || state.Session == nil {
return
}
fileStore := state.Session.FileChangeStore()
if fileStore == nil {
return
}
changes := fileStore.GetAll()
if len(changes) == 0 && len(comments) == 0 {
return
}
eventPrefix := fmt.Sprintf("session:%s:", state.ID)
go func() {
wailsRuntime.EventsEmit(a.ctx, eventPrefix+"review_agent_running", true)
prompt := buildReviewPrompt(changes, comments)
cwd, _ := os.Getwd()
reviewEventChan := make(chan backend.Event, 100)
// Create review session with auto-permission and shared file store
reviewSession, err := a.backend.NewSession(a.ctx, backend.SessionOpts{
CWD: cwd,
EventChan: reviewEventChan,
AutoPermission: true,
SuppressToolEvents: true,
FileChangeStore: fileStore,
})
if err != nil {
wailsRuntime.EventsEmit(a.ctx, eventPrefix+"review_agent_chunk", "Error: "+err.Error())
wailsRuntime.EventsEmit(a.ctx, eventPrefix+"review_agent_complete", nil)
close(reviewEventChan)
return
}
go a.bridgeEvents(eventPrefix, reviewEventChan, "review_agent_chunk")
if err := reviewSession.SendPrompt(prompt, []string{}); err != nil {
wailsRuntime.EventsEmit(a.ctx, eventPrefix+"review_agent_chunk", "\nError: "+err.Error())
}
wailsRuntime.EventsEmit(a.ctx, eventPrefix+"review_agent_complete", nil)
go func() { reviewSession.Close(); close(reviewEventChan) }()
}()
}
func buildReviewPrompt(changes []backend.FileChange, comments []ReviewComment) string {
var b strings.Builder
b.WriteString("Review feedback for recent changes:\n\n")
for _, c := range changes {
fmt.Fprintf(&b, "## File: %s\n```diff\n", c.FilePath)
for _, h := range c.Hunks {
fmt.Fprintf(&b, "@@ -%d,%d +%d,%d @@\n", h.OldStart, h.OldLines, h.NewStart, h.NewLines)
for _, line := range h.Lines {
b.WriteString(line + "\n")
}
}
b.WriteString("```\n\n")
}
b.WriteString("## Review Comments:\n")
for _, c := range comments {
switch c.Type {
case "line":
fmt.Fprintf(&b, "- [%s:%d] %s\n", c.FilePath, c.LineNumber, c.Text)
case "hunk":
fmt.Fprintf(&b, "- [%s hunk %d] %s\n", c.FilePath, c.HunkIndex+1, c.Text)
default:
fmt.Fprintf(&b, "- [General] %s\n", c.Text)
}
}
b.WriteString("\nPlease address this feedback by making the necessary changes.")
return b.String()
}
func parseReviewComments(raw []interface{}) (comments []ReviewComment) {
for _, c := range raw {
if m, ok := c.(map[string]interface{}); ok {
comments = append(comments, ReviewComment{
ID: mapStr(m, "id"), Type: mapStr(m, "type"), Text: mapStr(m, "text"),
FilePath: mapStr(m, "filePath"), LineNumber: mapInt(m, "lineNumber"), HunkIndex: mapInt(m, "hunkIndex"),
})
}
}
return
}
func mapStr(m map[string]interface{}, key string) string {
if v, ok := m[key].(string); ok {
return v
}
return ""
}
func mapInt(m map[string]interface{}, key string) int {
if v, ok := m[key].(float64); ok {
return int(v)
}
return 0
}
func firstAs[T any](data []interface{}) (T, bool) {
var zero T
if len(data) == 0 {
return zero, false
}
v, ok := data[0].(T)
return v, ok
}
// Automation CRUD bindings
func (a *App) ListAutomations() []automation.Automation {
if a.automationStore == nil {
return nil
}
return a.automationStore.List()
}
func (a *App) GetAutomation(id string) (*automation.Automation, error) {
if a.automationStore == nil {
return nil, fmt.Errorf("automation store not initialized")
}
return a.automationStore.Get(id)
}
func (a *App) CreateAutomation(auto automation.Automation) (*automation.Automation, error) {
if a.automationStore == nil {
return nil, fmt.Errorf("automation store not initialized")
}
result, err := a.automationStore.Create(auto)
if err == nil && a.scheduler != nil {
a.scheduler.Sync()
}
return result, err
}
func (a *App) UpdateAutomation(auto automation.Automation) (*automation.Automation, error) {
if a.automationStore == nil {
return nil, fmt.Errorf("automation store not initialized")
}
result, err := a.automationStore.Update(auto)
if err == nil && a.scheduler != nil {
a.scheduler.Sync()
}
return result, err
}
func (a *App) DeleteAutomation(id string) error {
if a.automationStore == nil {
return fmt.Errorf("automation store not initialized")
}
err := a.automationStore.Delete(id)
if err == nil && a.scheduler != nil {
a.scheduler.Sync()
}
return err
}
// RunAutomationNow triggers immediate execution
func (a *App) RunAutomationNow(id string) error {
if a.automationStore == nil || a.engine == nil {
return fmt.Errorf("automation infrastructure not initialized")
}
auto, err := a.automationStore.Get(id)
if err != nil {
return err
}
go func() {
if _, err := a.engine.Execute(a.ctx, *auto); err != nil {
slog.Error("manual automation run failed", "id", id, "error", err)
}
}()
return nil
}
// GetAutomationRuns returns runs for an automation
func (a *App) GetAutomationRuns(automationID string) ([]automation.Run, error) {
if a.runStore == nil {
return nil, fmt.Errorf("run store not initialized")
}
return a.runStore.ListByAutomation(automationID)
}
// CancelAutomationRun stops a running automation
func (a *App) CancelAutomationRun(runID string) {
if a.engine != nil {
a.engine.CancelRun(runID)
}
}
// GetTriageItems returns unread runs with findings
func (a *App) GetTriageItems() ([]automation.Run, error) {
if a.runStore == nil {
return nil, fmt.Errorf("run store not initialized")
}
return a.runStore.UnreadWithFindings()
}
// MarkRunRead marks a run as read
func (a *App) MarkRunRead(automationID, runID string) error {
if a.runStore == nil {
return fmt.Errorf("run store not initialized")
}
run, err := a.runStore.Get(automationID, runID)
if err != nil {
return err
}
run.Read = true
return a.runStore.Update(*run)
}
// GetRunDetail returns full run details
func (a *App) GetRunDetail(automationID, runID string) (*automation.Run, error) {
if a.runStore == nil {
return nil, fmt.Errorf("run store not initialized")
}
return a.runStore.Get(automationID, runID)
}
func (a *App) BrowseDirectory() (string, error) {
return wailsRuntime.OpenDirectoryDialog(a.ctx, wailsRuntime.OpenDialogOptions{
Title: "Select Project Directory",
})
}