bootstrap.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import type {
  2. Config,
  3. OpencodeClient,
  4. Path,
  5. PermissionRequest,
  6. Project,
  7. ProviderAuthResponse,
  8. ProviderListResponse,
  9. QuestionRequest,
  10. Todo,
  11. } from "@opencode-ai/sdk/v2/client"
  12. import { showToast } from "@opencode-ai/ui/toast"
  13. import { getFilename } from "@opencode-ai/util/path"
  14. import { retry } from "@opencode-ai/util/retry"
  15. import { batch } from "solid-js"
  16. import { reconcile, type SetStoreFunction, type Store } from "solid-js/store"
  17. import type { State, VcsCache } from "./types"
  18. import { cmp, normalizeProviderList } from "./utils"
  19. import { formatServerError } from "@/utils/server-errors"
  20. type GlobalStore = {
  21. ready: boolean
  22. path: Path
  23. project: Project[]
  24. session_todo: {
  25. [sessionID: string]: Todo[]
  26. }
  27. provider: ProviderListResponse
  28. provider_auth: ProviderAuthResponse
  29. config: Config
  30. reload: undefined | "pending" | "complete"
  31. }
  32. export async function bootstrapGlobal(input: {
  33. globalSDK: OpencodeClient
  34. requestFailedTitle: string
  35. translate: (key: string, vars?: Record<string, string | number>) => string
  36. formatMoreCount: (count: number) => string
  37. setGlobalStore: SetStoreFunction<GlobalStore>
  38. }) {
  39. const tasks = [
  40. retry(() =>
  41. input.globalSDK.path.get().then((x) => {
  42. input.setGlobalStore("path", x.data!)
  43. }),
  44. ),
  45. retry(() =>
  46. input.globalSDK.global.config.get().then((x) => {
  47. input.setGlobalStore("config", x.data!)
  48. }),
  49. ),
  50. retry(() =>
  51. input.globalSDK.project.list().then((x) => {
  52. const projects = (x.data ?? [])
  53. .filter((p) => !!p?.id)
  54. .filter((p) => !!p.worktree && !p.worktree.includes("opencode-test"))
  55. .slice()
  56. .sort((a, b) => cmp(a.id, b.id))
  57. input.setGlobalStore("project", projects)
  58. }),
  59. ),
  60. retry(() =>
  61. input.globalSDK.provider.list().then((x) => {
  62. input.setGlobalStore("provider", normalizeProviderList(x.data!))
  63. }),
  64. ),
  65. ]
  66. const results = await Promise.allSettled(tasks)
  67. const errors = results.filter((r): r is PromiseRejectedResult => r.status === "rejected").map((r) => r.reason)
  68. if (errors.length) {
  69. const message = formatServerError(errors[0], input.translate)
  70. const more = errors.length > 1 ? input.formatMoreCount(errors.length - 1) : ""
  71. showToast({
  72. variant: "error",
  73. title: input.requestFailedTitle,
  74. description: message + more,
  75. })
  76. }
  77. input.setGlobalStore("ready", true)
  78. }
  79. function groupBySession<T extends { id: string; sessionID: string }>(input: T[]) {
  80. return input.reduce<Record<string, T[]>>((acc, item) => {
  81. if (!item?.id || !item.sessionID) return acc
  82. const list = acc[item.sessionID]
  83. if (list) list.push(item)
  84. if (!list) acc[item.sessionID] = [item]
  85. return acc
  86. }, {})
  87. }
  88. function projectID(directory: string, projects: Project[]) {
  89. return projects.find((project) => project.worktree === directory || project.sandboxes?.includes(directory))?.id
  90. }
  91. export async function bootstrapDirectory(input: {
  92. directory: string
  93. sdk: OpencodeClient
  94. store: Store<State>
  95. setStore: SetStoreFunction<State>
  96. vcsCache: VcsCache
  97. loadSessions: (directory: string) => Promise<void> | void
  98. translate: (key: string, vars?: Record<string, string | number>) => string
  99. global: {
  100. config: Config
  101. project: Project[]
  102. provider: ProviderListResponse
  103. }
  104. }) {
  105. const loading = input.store.status !== "complete"
  106. const seededProject = projectID(input.directory, input.global.project)
  107. if (seededProject) input.setStore("project", seededProject)
  108. if (input.store.provider.all.length === 0 && input.global.provider.all.length > 0) {
  109. input.setStore("provider", input.global.provider)
  110. }
  111. if (Object.keys(input.store.config).length === 0 && Object.keys(input.global.config).length > 0) {
  112. input.setStore("config", input.global.config)
  113. }
  114. if (loading) input.setStore("status", "partial")
  115. const results = await Promise.allSettled([
  116. seededProject
  117. ? Promise.resolve()
  118. : retry(() => input.sdk.project.current()).then((x) => input.setStore("project", x.data!.id)),
  119. retry(() =>
  120. input.sdk.provider.list().then((x) => {
  121. input.setStore("provider", normalizeProviderList(x.data!))
  122. }),
  123. ),
  124. retry(() => input.sdk.app.agents().then((x) => input.setStore("agent", x.data ?? []))),
  125. retry(() => input.sdk.config.get().then((x) => input.setStore("config", x.data!))),
  126. retry(() =>
  127. input.sdk.path.get().then((x) => {
  128. input.setStore("path", x.data!)
  129. const next = projectID(x.data?.directory ?? input.directory, input.global.project)
  130. if (next) input.setStore("project", next)
  131. }),
  132. ),
  133. retry(() => input.sdk.command.list().then((x) => input.setStore("command", x.data ?? []))),
  134. retry(() => input.sdk.session.status().then((x) => input.setStore("session_status", x.data!))),
  135. input.loadSessions(input.directory),
  136. retry(() => input.sdk.mcp.status().then((x) => input.setStore("mcp", x.data!))),
  137. retry(() => input.sdk.lsp.status().then((x) => input.setStore("lsp", x.data!))),
  138. retry(() =>
  139. input.sdk.vcs.get().then((x) => {
  140. const next = x.data ?? input.store.vcs
  141. input.setStore("vcs", next)
  142. if (next?.branch) input.vcsCache.setStore("value", next)
  143. }),
  144. ),
  145. retry(() =>
  146. input.sdk.permission.list().then((x) => {
  147. const grouped = groupBySession(
  148. (x.data ?? []).filter((perm): perm is PermissionRequest => !!perm?.id && !!perm.sessionID),
  149. )
  150. batch(() => {
  151. for (const sessionID of Object.keys(input.store.permission)) {
  152. if (grouped[sessionID]) continue
  153. input.setStore("permission", sessionID, [])
  154. }
  155. for (const [sessionID, permissions] of Object.entries(grouped)) {
  156. input.setStore(
  157. "permission",
  158. sessionID,
  159. reconcile(
  160. permissions.filter((p) => !!p?.id).sort((a, b) => cmp(a.id, b.id)),
  161. { key: "id" },
  162. ),
  163. )
  164. }
  165. })
  166. }),
  167. ),
  168. retry(() =>
  169. input.sdk.question.list().then((x) => {
  170. const grouped = groupBySession((x.data ?? []).filter((q): q is QuestionRequest => !!q?.id && !!q.sessionID))
  171. batch(() => {
  172. for (const sessionID of Object.keys(input.store.question)) {
  173. if (grouped[sessionID]) continue
  174. input.setStore("question", sessionID, [])
  175. }
  176. for (const [sessionID, questions] of Object.entries(grouped)) {
  177. input.setStore(
  178. "question",
  179. sessionID,
  180. reconcile(
  181. questions.filter((q) => !!q?.id).sort((a, b) => cmp(a.id, b.id)),
  182. { key: "id" },
  183. ),
  184. )
  185. }
  186. })
  187. }),
  188. ),
  189. ])
  190. const errors = results
  191. .filter((item): item is PromiseRejectedResult => item.status === "rejected")
  192. .map((item) => item.reason)
  193. if (errors.length > 0) {
  194. console.error("Failed to bootstrap instance", errors[0])
  195. const project = getFilename(input.directory)
  196. showToast({
  197. variant: "error",
  198. title: input.translate("toast.project.reloadFailed.title", { project }),
  199. description: formatServerError(errors[0], input.translate),
  200. })
  201. return
  202. }
  203. if (loading) input.setStore("status", "complete")
  204. }