app.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package app
  2. import (
  3. "context"
  4. "fmt"
  5. "path/filepath"
  6. "sort"
  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/state"
  12. "github.com/sst/opencode/internal/status"
  13. "github.com/sst/opencode/internal/theme"
  14. "github.com/sst/opencode/internal/util"
  15. "github.com/sst/opencode/pkg/client"
  16. )
  17. type App struct {
  18. ConfigPath string
  19. Config *config.Config
  20. Client *client.ClientWithResponses
  21. Provider *client.ProviderInfo
  22. Model *client.ProviderModel
  23. Session *client.SessionInfo
  24. Messages []client.MessageInfo
  25. Status status.Service
  26. // UI state
  27. filepickerOpen bool
  28. completionDialogOpen bool
  29. }
  30. type AppInfo struct {
  31. client.AppInfo
  32. Version string
  33. }
  34. var Info AppInfo
  35. func New(ctx context.Context, version string, httpClient *client.ClientWithResponses) (*App, error) {
  36. err := status.InitService()
  37. if err != nil {
  38. slog.Error("Failed to initialize status service", "error", err)
  39. return nil, err
  40. }
  41. appInfoResponse, _ := httpClient.PostAppInfoWithResponse(ctx)
  42. appInfo := appInfoResponse.JSON200
  43. Info = AppInfo{Version: version}
  44. Info.Git = appInfo.Git
  45. Info.Path = appInfo.Path
  46. Info.Time = appInfo.Time
  47. Info.User = appInfo.User
  48. providersResponse, err := httpClient.PostProviderListWithResponse(ctx)
  49. if err != nil {
  50. return nil, err
  51. }
  52. providers := []client.ProviderInfo{}
  53. var defaultProvider *client.ProviderInfo
  54. var defaultModel *client.ProviderModel
  55. for i, provider := range providersResponse.JSON200.Providers {
  56. if i == 0 || provider.Id == "anthropic" {
  57. defaultProvider = &providersResponse.JSON200.Providers[i]
  58. if match, ok := providersResponse.JSON200.Default[provider.Id]; ok {
  59. model := defaultProvider.Models[match]
  60. defaultModel = &model
  61. } else {
  62. for _, model := range provider.Models {
  63. defaultModel = &model
  64. break
  65. }
  66. }
  67. }
  68. providers = append(providers, provider)
  69. }
  70. if len(providers) == 0 {
  71. return nil, fmt.Errorf("no providers found")
  72. }
  73. appConfigPath := filepath.Join(Info.Path.Config, "tui.toml")
  74. appConfig, err := config.LoadConfig(appConfigPath)
  75. if err != nil {
  76. slog.Info("No TUI config found, using default values", "error", err)
  77. appConfig = config.NewConfig("opencode", defaultProvider.Id, defaultModel.Id)
  78. config.SaveConfig(appConfigPath, appConfig)
  79. }
  80. var currentProvider *client.ProviderInfo
  81. var currentModel *client.ProviderModel
  82. for _, provider := range providers {
  83. if provider.Id == appConfig.Provider {
  84. currentProvider = &provider
  85. for _, model := range provider.Models {
  86. if model.Id == appConfig.Model {
  87. currentModel = &model
  88. }
  89. }
  90. }
  91. }
  92. app := &App{
  93. ConfigPath: appConfigPath,
  94. Config: appConfig,
  95. Client: httpClient,
  96. Provider: currentProvider,
  97. Model: currentModel,
  98. Session: &client.SessionInfo{},
  99. Messages: []client.MessageInfo{},
  100. Status: status.GetService(),
  101. }
  102. theme.SetTheme(appConfig.Theme)
  103. fileutil.Init()
  104. return app, nil
  105. }
  106. type Attachment struct {
  107. FilePath string
  108. FileName string
  109. MimeType string
  110. Content []byte
  111. }
  112. func (a *App) IsBusy() bool {
  113. if len(a.Messages) == 0 {
  114. return false
  115. }
  116. lastMessage := a.Messages[len(a.Messages)-1]
  117. return lastMessage.Metadata.Time.Completed == nil
  118. }
  119. func (a *App) SaveConfig() {
  120. config.SaveConfig(a.ConfigPath, a.Config)
  121. }
  122. func (a *App) InitializeProject(ctx context.Context) tea.Cmd {
  123. cmds := []tea.Cmd{}
  124. session, err := a.CreateSession(ctx)
  125. if err != nil {
  126. status.Error(err.Error())
  127. return nil
  128. }
  129. a.Session = session
  130. cmds = append(cmds, util.CmdHandler(state.SessionSelectedMsg(session)))
  131. go func() {
  132. // TODO: Handle no provider or model setup, yet
  133. response, err := a.Client.PostSessionInitialize(ctx, client.PostSessionInitializeJSONRequestBody{
  134. SessionID: a.Session.Id,
  135. ProviderID: a.Provider.Id,
  136. ModelID: a.Model.Id,
  137. })
  138. if err != nil {
  139. status.Error(err.Error())
  140. }
  141. if response != nil && response.StatusCode != 200 {
  142. status.Error(fmt.Sprintf("failed to initialize project: %d", response.StatusCode))
  143. }
  144. }()
  145. return tea.Batch(cmds...)
  146. }
  147. func (a *App) MarkProjectInitialized(ctx context.Context) error {
  148. response, err := a.Client.PostAppInitialize(ctx)
  149. if err != nil {
  150. slog.Error("Failed to mark project as initialized", "error", err)
  151. return err
  152. }
  153. if response != nil && response.StatusCode != 200 {
  154. return fmt.Errorf("failed to initialize project: %d", response.StatusCode)
  155. }
  156. return nil
  157. }
  158. func (a *App) CreateSession(ctx context.Context) (*client.SessionInfo, error) {
  159. resp, err := a.Client.PostSessionCreateWithResponse(ctx)
  160. if err != nil {
  161. return nil, err
  162. }
  163. if resp != nil && resp.StatusCode() != 200 {
  164. return nil, fmt.Errorf("failed to create session: %d", resp.StatusCode())
  165. }
  166. session := resp.JSON200
  167. return session, nil
  168. }
  169. func (a *App) SendChatMessage(ctx context.Context, text string, attachments []Attachment) tea.Cmd {
  170. var cmds []tea.Cmd
  171. if a.Session.Id == "" {
  172. session, err := a.CreateSession(ctx)
  173. if err != nil {
  174. status.Error(err.Error())
  175. return nil
  176. }
  177. a.Session = session
  178. cmds = append(cmds, util.CmdHandler(state.SessionSelectedMsg(session)))
  179. }
  180. // TODO: Handle attachments when API supports them
  181. if len(attachments) > 0 {
  182. // For now, ignore attachments
  183. // return "", fmt.Errorf("attachments not supported yet")
  184. }
  185. part := client.MessagePart{}
  186. part.FromMessagePartText(client.MessagePartText{
  187. Type: "text",
  188. Text: text,
  189. })
  190. parts := []client.MessagePart{part}
  191. go func() {
  192. response, err := a.Client.PostSessionChat(ctx, client.PostSessionChatJSONRequestBody{
  193. SessionID: a.Session.Id,
  194. Parts: parts,
  195. ProviderID: a.Provider.Id,
  196. ModelID: a.Model.Id,
  197. })
  198. if err != nil {
  199. slog.Error("Failed to send message", "error", err)
  200. status.Error(err.Error())
  201. }
  202. if response != nil && response.StatusCode != 200 {
  203. slog.Error("Failed to send message", "error", fmt.Sprintf("failed to send message: %d", response.StatusCode))
  204. status.Error(fmt.Sprintf("failed to send message: %d", response.StatusCode))
  205. }
  206. }()
  207. // The actual response will come through SSE
  208. // For now, just return success
  209. return tea.Batch(cmds...)
  210. }
  211. func (a *App) Cancel(ctx context.Context, sessionID string) error {
  212. response, err := a.Client.PostSessionAbort(ctx, client.PostSessionAbortJSONRequestBody{
  213. SessionID: sessionID,
  214. })
  215. if err != nil {
  216. slog.Error("Failed to cancel session", "error", err)
  217. status.Error(err.Error())
  218. return err
  219. }
  220. if response != nil && response.StatusCode != 200 {
  221. slog.Error("Failed to cancel session", "error", fmt.Sprintf("failed to cancel session: %d", response.StatusCode))
  222. status.Error(fmt.Sprintf("failed to cancel session: %d", response.StatusCode))
  223. return fmt.Errorf("failed to cancel session: %d", response.StatusCode)
  224. }
  225. return nil
  226. }
  227. func (a *App) ListSessions(ctx context.Context) ([]client.SessionInfo, error) {
  228. resp, err := a.Client.PostSessionListWithResponse(ctx)
  229. if err != nil {
  230. return nil, err
  231. }
  232. if resp.StatusCode() != 200 {
  233. return nil, fmt.Errorf("failed to list sessions: %d", resp.StatusCode())
  234. }
  235. if resp.JSON200 == nil {
  236. return []client.SessionInfo{}, nil
  237. }
  238. sessions := *resp.JSON200
  239. sort.Slice(sessions, func(i, j int) bool {
  240. return sessions[i].Time.Created-sessions[j].Time.Created > 0
  241. })
  242. return sessions, nil
  243. }
  244. func (a *App) ListMessages(ctx context.Context, sessionId string) ([]client.MessageInfo, error) {
  245. resp, err := a.Client.PostSessionMessagesWithResponse(ctx, client.PostSessionMessagesJSONRequestBody{SessionID: sessionId})
  246. if err != nil {
  247. return nil, err
  248. }
  249. if resp.StatusCode() != 200 {
  250. return nil, fmt.Errorf("failed to list messages: %d", resp.StatusCode())
  251. }
  252. if resp.JSON200 == nil {
  253. return []client.MessageInfo{}, nil
  254. }
  255. messages := *resp.JSON200
  256. return messages, nil
  257. }
  258. func (a *App) ListProviders(ctx context.Context) ([]client.ProviderInfo, error) {
  259. resp, err := a.Client.PostProviderListWithResponse(ctx)
  260. if err != nil {
  261. return nil, err
  262. }
  263. if resp.StatusCode() != 200 {
  264. return nil, fmt.Errorf("failed to list sessions: %d", resp.StatusCode())
  265. }
  266. if resp.JSON200 == nil {
  267. return []client.ProviderInfo{}, nil
  268. }
  269. providers := *resp.JSON200
  270. return providers.Providers, nil
  271. }
  272. // IsFilepickerOpen returns whether the filepicker is currently open
  273. func (app *App) IsFilepickerOpen() bool {
  274. return app.filepickerOpen
  275. }
  276. // SetFilepickerOpen sets the state of the filepicker
  277. func (app *App) SetFilepickerOpen(open bool) {
  278. app.filepickerOpen = open
  279. }
  280. // IsCompletionDialogOpen returns whether the completion dialog is currently open
  281. func (app *App) IsCompletionDialogOpen() bool {
  282. return app.completionDialogOpen
  283. }
  284. // SetCompletionDialogOpen sets the state of the completion dialog
  285. func (app *App) SetCompletionDialogOpen(open bool) {
  286. app.completionDialogOpen = open
  287. }
  288. // Shutdown performs a clean shutdown of the application
  289. func (app *App) Shutdown() {
  290. // TODO: cleanup?
  291. }