This repository was archived by the owner on Sep 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathapp.go
More file actions
200 lines (166 loc) · 5.19 KB
/
app.go
File metadata and controls
200 lines (166 loc) · 5.19 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
package app
import (
"context"
"database/sql"
"errors"
"fmt"
"maps"
"sync"
"time"
"github.com/opencode-ai/opencode/internal/config"
"github.com/opencode-ai/opencode/internal/db"
"github.com/opencode-ai/opencode/internal/format"
"github.com/opencode-ai/opencode/internal/history"
"github.com/opencode-ai/opencode/internal/llm/agent"
"github.com/opencode-ai/opencode/internal/logging"
"github.com/opencode-ai/opencode/internal/lsp"
"github.com/opencode-ai/opencode/internal/message"
"github.com/opencode-ai/opencode/internal/permission"
"github.com/opencode-ai/opencode/internal/session"
"github.com/opencode-ai/opencode/internal/tui/theme"
)
type App struct {
Sessions session.Service
Messages message.Service
History history.Service
Permissions permission.Service
CoderAgent agent.Service
LSPClients map[string]*lsp.Client
clientsMutex sync.RWMutex
watcherCancelFuncs []context.CancelFunc
cancelFuncsMutex sync.Mutex
watcherWG sync.WaitGroup
// Runtime options (e.g., from CLI flags)
RuntimeOptions RuntimeOptions
}
// RuntimeOptions contains runtime configuration options (e.g., from CLI flags)
type RuntimeOptions struct {
DeferredEnabled bool
DeferredTimeout string
}
func New(ctx context.Context, conn *sql.DB, opts ...RuntimeOptions) (*App, error) {
q := db.New(conn)
sessions := session.NewService(q)
messages := message.NewService(q)
files := history.NewService(q, conn)
app := &App{
Sessions: sessions,
Messages: messages,
History: files,
Permissions: permission.NewPermissionService(),
LSPClients: make(map[string]*lsp.Client),
}
// Apply runtime options if provided
if len(opts) > 0 {
app.RuntimeOptions = opts[0]
}
// Initialize theme based on configuration
app.initTheme()
// Initialize LSP clients in the background
go app.initLSPClients(ctx)
var err error
app.CoderAgent, err = agent.NewAgent(
config.AgentCoder,
app.Sessions,
app.Messages,
agent.CoderAgentTools(
app.Permissions,
app.Sessions,
app.Messages,
app.History,
app.LSPClients,
),
)
if err != nil {
logging.Error("Failed to create coder agent", err)
return nil, err
}
return app, nil
}
// initTheme sets the application theme based on the configuration
func (app *App) initTheme() {
cfg := config.Get()
if cfg == nil || cfg.TUI.Theme == "" {
return // Use default theme
}
// Try to set the theme from config
err := theme.SetTheme(cfg.TUI.Theme)
if err != nil {
logging.Warn("Failed to set theme from config, using default theme", "theme", cfg.TUI.Theme, "error", err)
} else {
logging.Debug("Set theme from config", "theme", cfg.TUI.Theme)
}
}
// RunNonInteractive handles the execution flow when a prompt is provided via CLI flag.
func (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat string, quiet bool) error {
logging.Info("Running in non-interactive mode")
// Start spinner if not in quiet mode
var spinner *format.Spinner
if !quiet {
spinner = format.NewSpinner("Thinking...")
spinner.Start()
defer spinner.Stop()
}
const maxPromptLengthForTitle = 100
titlePrefix := "Non-interactive: "
var titleSuffix string
if len(prompt) > maxPromptLengthForTitle {
titleSuffix = prompt[:maxPromptLengthForTitle] + "..."
} else {
titleSuffix = prompt
}
title := titlePrefix + titleSuffix
sess, err := a.Sessions.Create(ctx, title)
if err != nil {
return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
}
logging.Info("Created session for non-interactive run", "session_id", sess.ID)
// Automatically approve all permission requests for this non-interactive session
a.Permissions.AutoApproveSession(sess.ID)
done, err := a.CoderAgent.Run(ctx, sess.ID, prompt)
if err != nil {
return fmt.Errorf("failed to start agent processing stream: %w", err)
}
result := <-done
if result.Error != nil {
if errors.Is(result.Error, context.Canceled) || errors.Is(result.Error, agent.ErrRequestCancelled) {
logging.Info("Agent processing cancelled", "session_id", sess.ID)
return nil
}
return fmt.Errorf("agent processing failed: %w", result.Error)
}
// Stop spinner before printing output
if !quiet && spinner != nil {
spinner.Stop()
}
// Get the text content from the response
content := "No content available"
if result.Message.Content().String() != "" {
content = result.Message.Content().String()
}
fmt.Println(format.FormatOutput(content, outputFormat))
logging.Info("Non-interactive run completed", "session_id", sess.ID)
return nil
}
// Shutdown performs a clean shutdown of the application
func (app *App) Shutdown() {
// Cancel all watcher goroutines
app.cancelFuncsMutex.Lock()
for _, cancel := range app.watcherCancelFuncs {
cancel()
}
app.cancelFuncsMutex.Unlock()
app.watcherWG.Wait()
// Perform additional cleanup for LSP clients
app.clientsMutex.RLock()
clients := make(map[string]*lsp.Client, len(app.LSPClients))
maps.Copy(clients, app.LSPClients)
app.clientsMutex.RUnlock()
for name, client := range clients {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := client.Shutdown(shutdownCtx); err != nil {
logging.Error("Failed to shutdown LSP client", "name", name, "error", err)
}
cancel()
}
}