error.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import { TextField } from "@opencode-ai/ui/text-field"
  2. import * as Sentry from "@sentry/solid"
  3. import { Logo } from "@opencode-ai/ui/logo"
  4. import { Button } from "@opencode-ai/ui/button"
  5. import { Component, createSignal, onMount, Show } from "solid-js"
  6. import { createStore } from "solid-js/store"
  7. import { usePlatform } from "@/context/platform"
  8. import { useLanguage } from "@/context/language"
  9. import { Icon } from "@opencode-ai/ui/icon"
  10. export type InitError = {
  11. name: string
  12. data: Record<string, unknown>
  13. }
  14. type Translator = ReturnType<typeof useLanguage>["t"]
  15. const CHAIN_SEPARATOR = "\n" + "─".repeat(40) + "\n"
  16. function isIssue(value: unknown): value is { message: string; path: string[] } {
  17. if (!value || typeof value !== "object") return false
  18. if (!("message" in value) || !("path" in value)) return false
  19. const message = (value as { message: unknown }).message
  20. const path = (value as { path: unknown }).path
  21. if (typeof message !== "string") return false
  22. if (!Array.isArray(path)) return false
  23. return path.every((part) => typeof part === "string")
  24. }
  25. function isInitError(error: unknown): error is InitError {
  26. return (
  27. typeof error === "object" &&
  28. error !== null &&
  29. "name" in error &&
  30. "data" in error &&
  31. typeof (error as InitError).data === "object"
  32. )
  33. }
  34. function safeJson(value: unknown, circular: string): string {
  35. const seen = new WeakSet<object>()
  36. const json = JSON.stringify(
  37. value,
  38. (_key, val) => {
  39. if (typeof val === "bigint") return val.toString()
  40. if (typeof val === "object" && val) {
  41. if (seen.has(val)) return circular
  42. seen.add(val)
  43. }
  44. return val
  45. },
  46. 2,
  47. )
  48. return json ?? String(value)
  49. }
  50. function formatInitError(error: InitError, t: Translator): string {
  51. const data = error.data
  52. const json = (value: unknown) => safeJson(value, t("error.page.circular"))
  53. switch (error.name) {
  54. case "MCPFailed": {
  55. const name = typeof data.name === "string" ? data.name : ""
  56. return t("error.chain.mcpFailed", { name })
  57. }
  58. case "ProviderAuthError": {
  59. const providerID = typeof data.providerID === "string" ? data.providerID : t("common.unknown")
  60. const message = typeof data.message === "string" ? data.message : json(data.message)
  61. return t("error.chain.providerAuthFailed", { provider: providerID, message })
  62. }
  63. case "APIError": {
  64. const message = typeof data.message === "string" ? data.message : t("error.chain.apiError")
  65. const lines: string[] = [message]
  66. if (typeof data.statusCode === "number") {
  67. lines.push(t("error.chain.status", { status: data.statusCode }))
  68. }
  69. if (typeof data.isRetryable === "boolean") {
  70. lines.push(t("error.chain.retryable", { retryable: data.isRetryable }))
  71. }
  72. if (typeof data.responseBody === "string" && data.responseBody) {
  73. lines.push(t("error.chain.responseBody", { body: data.responseBody }))
  74. }
  75. return lines.join("\n")
  76. }
  77. case "ProviderModelNotFoundError": {
  78. const { providerID, modelID, suggestions } = data as {
  79. providerID: string
  80. modelID: string
  81. suggestions?: string[]
  82. }
  83. const suggestionsLine =
  84. Array.isArray(suggestions) && suggestions.length
  85. ? [t("error.chain.didYouMean", { suggestions: suggestions.join(", ") })]
  86. : []
  87. return [
  88. t("error.chain.modelNotFound", { provider: providerID, model: modelID }),
  89. ...suggestionsLine,
  90. t("error.chain.checkConfig"),
  91. ].join("\n")
  92. }
  93. case "ProviderInitError": {
  94. const providerID = typeof data.providerID === "string" ? data.providerID : t("common.unknown")
  95. return t("error.chain.providerInitFailed", { provider: providerID })
  96. }
  97. case "ConfigJsonError": {
  98. const path = typeof data.path === "string" ? data.path : json(data.path)
  99. const message = typeof data.message === "string" ? data.message : ""
  100. if (message) return t("error.chain.configJsonInvalidWithMessage", { path, message })
  101. return t("error.chain.configJsonInvalid", { path })
  102. }
  103. case "ConfigDirectoryTypoError": {
  104. const path = typeof data.path === "string" ? data.path : json(data.path)
  105. const dir = typeof data.dir === "string" ? data.dir : json(data.dir)
  106. const suggestion = typeof data.suggestion === "string" ? data.suggestion : json(data.suggestion)
  107. return t("error.chain.configDirectoryTypo", { dir, path, suggestion })
  108. }
  109. case "ConfigFrontmatterError": {
  110. const path = typeof data.path === "string" ? data.path : json(data.path)
  111. const message = typeof data.message === "string" ? data.message : json(data.message)
  112. return t("error.chain.configFrontmatterError", { path, message })
  113. }
  114. case "ConfigInvalidError": {
  115. const issues = Array.isArray(data.issues)
  116. ? data.issues.filter(isIssue).map((issue) => "↳ " + issue.message + " " + issue.path.join("."))
  117. : []
  118. const message = typeof data.message === "string" ? data.message : ""
  119. const path = typeof data.path === "string" ? data.path : json(data.path)
  120. const line = message
  121. ? t("error.chain.configInvalidWithMessage", { path, message })
  122. : t("error.chain.configInvalid", { path })
  123. return [line, ...issues].join("\n")
  124. }
  125. case "UnknownError":
  126. return typeof data.message === "string" ? data.message : json(data)
  127. default:
  128. if (typeof data.message === "string") return data.message
  129. return json(data)
  130. }
  131. }
  132. function formatErrorChain(error: unknown, t: Translator, depth = 0, parentMessage?: string): string {
  133. const json = (value: unknown) => safeJson(value, t("error.page.circular"))
  134. if (!error) return t("error.chain.unknown")
  135. if (isInitError(error)) {
  136. const message = formatInitError(error, t)
  137. if (depth > 0 && parentMessage === message) return ""
  138. const indent = depth > 0 ? `\n${CHAIN_SEPARATOR}${t("error.chain.causedBy")}\n` : ""
  139. return indent + `${error.name}\n${message}`
  140. }
  141. if (error instanceof Error) {
  142. const isDuplicate = depth > 0 && parentMessage === error.message
  143. const parts: string[] = []
  144. const indent = depth > 0 ? `\n${CHAIN_SEPARATOR}${t("error.chain.causedBy")}\n` : ""
  145. const header = `${error.name}${error.message ? `: ${error.message}` : ""}`
  146. const stack = error.stack?.trim()
  147. if (stack) {
  148. const startsWithHeader = stack.startsWith(header)
  149. if (isDuplicate && startsWithHeader) {
  150. const trace = stack.split("\n").slice(1).join("\n").trim()
  151. if (trace) {
  152. parts.push(indent + trace)
  153. }
  154. }
  155. if (isDuplicate && !startsWithHeader) {
  156. parts.push(indent + stack)
  157. }
  158. if (!isDuplicate && startsWithHeader) {
  159. parts.push(indent + stack)
  160. }
  161. if (!isDuplicate && !startsWithHeader) {
  162. parts.push(indent + `${header}\n${stack}`)
  163. }
  164. }
  165. if (!stack && !isDuplicate) {
  166. parts.push(indent + header)
  167. }
  168. if (error.cause) {
  169. const causeResult = formatErrorChain(error.cause, t, depth + 1, error.message)
  170. if (causeResult) {
  171. parts.push(causeResult)
  172. }
  173. }
  174. return parts.join("\n\n")
  175. }
  176. if (typeof error === "string") {
  177. if (depth > 0 && parentMessage === error) return ""
  178. const indent = depth > 0 ? `\n${CHAIN_SEPARATOR}${t("error.chain.causedBy")}\n` : ""
  179. return indent + error
  180. }
  181. const indent = depth > 0 ? `\n${CHAIN_SEPARATOR}${t("error.chain.causedBy")}\n` : ""
  182. return indent + json(error)
  183. }
  184. function formatError(error: unknown, t: Translator): string {
  185. return formatErrorChain(error, t, 0)
  186. }
  187. interface ErrorPageProps {
  188. error: unknown
  189. }
  190. export const ErrorPage: Component<ErrorPageProps> = (props) => {
  191. const platform = usePlatform()
  192. const language = useLanguage()
  193. const formattedError = () => formatError(props.error, language.t)
  194. let recordedFatalError: Promise<void> | undefined
  195. const [store, setStore] = createStore({
  196. checking: false,
  197. version: undefined as string | undefined,
  198. actionError: undefined as string | undefined,
  199. })
  200. function ensureFatalErrorRecorded() {
  201. recordedFatalError ??=
  202. platform.recordFatalRendererError?.({
  203. error: formattedError(),
  204. url: location.href,
  205. version: platform.version,
  206. platform: platform.platform,
  207. os: platform.os,
  208. }) ?? Promise.resolve()
  209. return recordedFatalError
  210. }
  211. onMount(() => {
  212. void ensureFatalErrorRecorded().catch(() => undefined)
  213. })
  214. async function checkForUpdates() {
  215. if (!platform.checkUpdate) return
  216. setStore("checking", true)
  217. await platform
  218. .checkUpdate()
  219. .then((result) => {
  220. setStore("actionError", undefined)
  221. if (result.updateAvailable && result.version) setStore("version", result.version)
  222. })
  223. .catch((err) => {
  224. setStore("actionError", formatError(err, language.t))
  225. })
  226. .finally(() => {
  227. setStore("checking", false)
  228. })
  229. }
  230. async function installUpdate() {
  231. if (!platform.updateAndRestart) return
  232. await platform
  233. .updateAndRestart()
  234. .then(() => setStore("actionError", undefined))
  235. .catch((err) => {
  236. setStore("actionError", formatError(err, language.t))
  237. })
  238. }
  239. async function exportDebugLogs() {
  240. const exportLogs = platform.exportDebugLogs
  241. if (!exportLogs) return
  242. await ensureFatalErrorRecorded()
  243. .then(() => exportLogs())
  244. .then(() => setStore("actionError", undefined))
  245. .catch((err) => {
  246. setStore("actionError", formatError(err, language.t))
  247. })
  248. }
  249. return (
  250. <div class="relative flex-1 h-screen w-screen min-h-0 flex flex-col items-center justify-center bg-background-base font-sans">
  251. <div class="w-2/3 max-w-3xl flex flex-col items-center justify-center gap-8">
  252. <Logo class="w-58.5 opacity-12 shrink-0" />
  253. <div class="flex flex-col items-center gap-2 text-center">
  254. <h1 class="text-lg font-medium text-text-strong">{language.t("error.page.title")}</h1>
  255. <p class="text-sm text-text-weak">{language.t("error.page.description")}</p>
  256. </div>
  257. <TextField
  258. value={formattedError()}
  259. readOnly
  260. copyable
  261. multiline
  262. class="max-h-96 w-full font-mono text-xs no-scrollbar"
  263. label={language.t("error.page.details.label")}
  264. hideLabel
  265. />
  266. <div class="flex flex-row items-center justify-center gap-3 flex-wrap max-w-64">
  267. <Button size="large" onClick={platform.restart}>
  268. {language.t("error.page.action.restart")}
  269. </Button>
  270. <Show when={platform.platform === "desktop" && platform.exportDebugLogs}>
  271. <Button size="large" variant="ghost" onClick={exportDebugLogs}>
  272. {language.t("error.page.action.exportLogs")}
  273. </Button>
  274. </Show>
  275. <Show when={Sentry.isEnabled}>
  276. {(_) => {
  277. const [reported, setReported] = createSignal(false)
  278. return (
  279. <Button
  280. size="large"
  281. disabled={reported()}
  282. onClick={() => {
  283. Sentry.captureException(props.error)
  284. setReported(true)
  285. }}
  286. >
  287. {language.t(reported() ? "error.page.action.reported" : "error.page.action.report")}
  288. </Button>
  289. )
  290. }}
  291. </Show>
  292. <Show when={platform.checkUpdate}>
  293. <Show
  294. when={store.version}
  295. fallback={
  296. <Button size="large" variant="ghost" onClick={checkForUpdates} disabled={store.checking}>
  297. {store.checking
  298. ? language.t("error.page.action.checking")
  299. : language.t("error.page.action.checkUpdates")}
  300. </Button>
  301. }
  302. >
  303. <Button size="large" onClick={installUpdate}>
  304. {language.t("error.page.action.updateTo", { version: store.version ?? "" })}
  305. </Button>
  306. </Show>
  307. </Show>
  308. </div>
  309. <Show when={store.actionError}>
  310. {(message) => <p class="text-xs text-text-danger-base text-center max-w-2xl">{message()}</p>}
  311. </Show>
  312. <div class="flex flex-col items-center gap-2">
  313. <div class="flex items-center justify-center gap-1">
  314. {language.t("error.page.report.prefix")}
  315. <button
  316. type="button"
  317. class="flex items-center text-text-interactive-base gap-1"
  318. onClick={() => platform.openLink("https://opencode.ai/desktop-feedback")}
  319. >
  320. <div>{language.t("error.page.report.discord")}</div>
  321. <Icon name="discord" class="text-text-interactive-base" />
  322. </button>
  323. </div>
  324. <Show when={platform.version}>
  325. {(version) => (
  326. <p class="text-xs text-text-weak">{language.t("error.page.version", { version: version() })}</p>
  327. )}
  328. </Show>
  329. </div>
  330. </div>
  331. </div>
  332. )
  333. }