app.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package app
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "log/slog"
  8. tea "github.com/charmbracelet/bubbletea"
  9. "github.com/sst/opencode/internal/config"
  10. "github.com/sst/opencode/internal/fileutil"
  11. "github.com/sst/opencode/internal/message"
  12. "github.com/sst/opencode/internal/session"
  13. "github.com/sst/opencode/internal/status"
  14. "github.com/sst/opencode/internal/tui/state"
  15. "github.com/sst/opencode/internal/tui/theme"
  16. "github.com/sst/opencode/internal/tui/util"
  17. "github.com/sst/opencode/pkg/client"
  18. )
  19. type App struct {
  20. Client *client.ClientWithResponses
  21. Events *client.Client
  22. Session *client.SessionInfo
  23. Messages []client.MessageInfo
  24. CurrentSessionOLD *session.Session
  25. SessionsOLD SessionService
  26. MessagesOLD MessageService
  27. LogsOLD any // TODO: Define LogService interface when needed
  28. HistoryOLD any // TODO: Define HistoryService interface when needed
  29. PermissionsOLD any // TODO: Define PermissionService interface when needed
  30. Status status.Service
  31. PrimaryAgentOLD AgentService
  32. watcherCancelFuncs []context.CancelFunc
  33. cancelFuncsMutex sync.Mutex
  34. watcherWG sync.WaitGroup
  35. // UI state
  36. filepickerOpen bool
  37. completionDialogOpen bool
  38. }
  39. func New(ctx context.Context) (*App, error) {
  40. // Initialize status service (still needed for UI notifications)
  41. err := status.InitService()
  42. if err != nil {
  43. slog.Error("Failed to initialize status service", "error", err)
  44. return nil, err
  45. }
  46. // Initialize file utilities
  47. fileutil.Init()
  48. // Create HTTP client
  49. url := "http://localhost:16713"
  50. httpClient, err := client.NewClientWithResponses(url)
  51. if err != nil {
  52. slog.Error("Failed to create client", "error", err)
  53. return nil, err
  54. }
  55. eventClient, err := client.NewClient(url)
  56. if err != nil {
  57. slog.Error("Failed to create event client", "error", err)
  58. return nil, err
  59. }
  60. // Create service bridges
  61. sessionBridge := NewSessionServiceBridge(httpClient)
  62. messageBridge := NewMessageServiceBridge(httpClient)
  63. agentBridge := NewAgentServiceBridge(httpClient)
  64. app := &App{
  65. Client: httpClient,
  66. Events: eventClient,
  67. Session: &client.SessionInfo{},
  68. CurrentSessionOLD: &session.Session{},
  69. SessionsOLD: sessionBridge,
  70. MessagesOLD: messageBridge,
  71. PrimaryAgentOLD: agentBridge,
  72. Status: status.GetService(),
  73. // TODO: These services need API endpoints:
  74. LogsOLD: nil, // logging.GetService(),
  75. HistoryOLD: nil, // history.GetService(),
  76. PermissionsOLD: nil, // permission.GetService(),
  77. }
  78. // Initialize theme based on configuration
  79. app.initTheme()
  80. return app, nil
  81. }
  82. // Create creates a new session
  83. func (a *App) SendChatMessage(ctx context.Context, text string, attachments []message.Attachment) tea.Cmd {
  84. var cmds []tea.Cmd
  85. if a.Session.Id == "" {
  86. resp, err := a.Client.PostSessionCreateWithResponse(ctx)
  87. if err != nil {
  88. status.Error(err.Error())
  89. return nil
  90. }
  91. if resp.StatusCode() != 200 {
  92. status.Error(fmt.Sprintf("failed to create session: %d", resp.StatusCode()))
  93. return nil
  94. }
  95. info := resp.JSON200
  96. a.Session = info
  97. // Convert to old session type for backwards compatibility
  98. newSession := session.Session{
  99. ID: info.Id,
  100. Title: info.Title,
  101. CreatedAt: time.Now(), // API doesn't provide this yet
  102. UpdatedAt: time.Now(), // API doesn't provide this yet
  103. }
  104. a.CurrentSessionOLD = &newSession
  105. cmds = append(cmds, util.CmdHandler(state.SessionSelectedMsg(&newSession)))
  106. }
  107. // TODO: Handle attachments when API supports them
  108. if len(attachments) > 0 {
  109. // For now, ignore attachments
  110. // return "", fmt.Errorf("attachments not supported yet")
  111. }
  112. part := client.MessagePart{}
  113. part.FromMessagePartText(client.MessagePartText{
  114. Type: "text",
  115. Text: text,
  116. })
  117. parts := []client.MessagePart{part}
  118. go a.Client.PostSessionChatWithResponse(ctx, client.PostSessionChatJSONRequestBody{
  119. SessionID: a.Session.Id,
  120. Parts: parts,
  121. ProviderID: "anthropic",
  122. ModelID: "claude-sonnet-4-20250514",
  123. })
  124. // The actual response will come through SSE
  125. // For now, just return success
  126. return tea.Batch(cmds...)
  127. }
  128. func (a *App) ListSessions(ctx context.Context) ([]session.Session, error) {
  129. resp, err := a.Client.PostSessionListWithResponse(ctx)
  130. if err != nil {
  131. return nil, err
  132. }
  133. if resp.StatusCode() != 200 {
  134. return nil, fmt.Errorf("failed to list sessions: %d", resp.StatusCode())
  135. }
  136. if resp.JSON200 == nil {
  137. return []session.Session{}, nil
  138. }
  139. infos := *resp.JSON200
  140. // Convert to old session type
  141. sessions := make([]session.Session, len(infos))
  142. for i, info := range infos {
  143. sessions[i] = session.Session{
  144. ID: info.Id,
  145. Title: info.Title,
  146. CreatedAt: time.Now(), // API doesn't provide this yet
  147. UpdatedAt: time.Now(), // API doesn't provide this yet
  148. }
  149. }
  150. return sessions, nil
  151. }
  152. // initTheme sets the application theme based on the configuration
  153. func (app *App) initTheme() {
  154. cfg := config.Get()
  155. if cfg == nil || cfg.TUI.Theme == "" {
  156. return // Use default theme
  157. }
  158. // Try to set the theme from config
  159. err := theme.SetTheme(cfg.TUI.Theme)
  160. if err != nil {
  161. slog.Warn("Failed to set theme from config, using default theme", "theme", cfg.TUI.Theme, "error", err)
  162. } else {
  163. slog.Debug("Set theme from config", "theme", cfg.TUI.Theme)
  164. }
  165. }
  166. // IsFilepickerOpen returns whether the filepicker is currently open
  167. func (app *App) IsFilepickerOpen() bool {
  168. return app.filepickerOpen
  169. }
  170. // SetFilepickerOpen sets the state of the filepicker
  171. func (app *App) SetFilepickerOpen(open bool) {
  172. app.filepickerOpen = open
  173. }
  174. // IsCompletionDialogOpen returns whether the completion dialog is currently open
  175. func (app *App) IsCompletionDialogOpen() bool {
  176. return app.completionDialogOpen
  177. }
  178. // SetCompletionDialogOpen sets the state of the completion dialog
  179. func (app *App) SetCompletionDialogOpen(open bool) {
  180. app.completionDialogOpen = open
  181. }
  182. // Shutdown performs a clean shutdown of the application
  183. func (app *App) Shutdown() {
  184. // Cancel all watcher goroutines
  185. app.cancelFuncsMutex.Lock()
  186. for _, cancel := range app.watcherCancelFuncs {
  187. cancel()
  188. }
  189. app.cancelFuncsMutex.Unlock()
  190. app.watcherWG.Wait()
  191. }