app.go 8.5 KB

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