index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. // @refresh reload
  2. import {
  3. ACCEPTED_FILE_EXTENSIONS,
  4. filePickerFilters,
  5. AppBaseProviders,
  6. AppInterface,
  7. handleNotificationClick,
  8. loadLocaleDict,
  9. normalizeLocale,
  10. type Locale,
  11. type Platform,
  12. PlatformProvider,
  13. ServerConnection,
  14. useCommand,
  15. } from "@opencode-ai/app"
  16. import type { AsyncStorage } from "@solid-primitives/storage"
  17. import { getCurrentWindow } from "@tauri-apps/api/window"
  18. import { readImage } from "@tauri-apps/plugin-clipboard-manager"
  19. import { getCurrent, onOpenUrl } from "@tauri-apps/plugin-deep-link"
  20. import { open, save } from "@tauri-apps/plugin-dialog"
  21. import { fetch as tauriFetch } from "@tauri-apps/plugin-http"
  22. import { isPermissionGranted, requestPermission } from "@tauri-apps/plugin-notification"
  23. import { type as ostype } from "@tauri-apps/plugin-os"
  24. import { relaunch } from "@tauri-apps/plugin-process"
  25. import { open as shellOpen } from "@tauri-apps/plugin-shell"
  26. import { Store } from "@tauri-apps/plugin-store"
  27. import { check, type Update } from "@tauri-apps/plugin-updater"
  28. import { createResource, onCleanup, onMount, Show } from "solid-js"
  29. import { render } from "solid-js/web"
  30. import pkg from "../package.json"
  31. import { initI18n, t } from "./i18n"
  32. import { UPDATER_ENABLED } from "./updater"
  33. import { webviewZoom } from "./webview-zoom"
  34. import "./styles.css"
  35. import { Channel } from "@tauri-apps/api/core"
  36. import { commands, type InitStep } from "./bindings"
  37. import { createMenu } from "./menu"
  38. const root = document.getElementById("root")
  39. if (import.meta.env.DEV && !(root instanceof HTMLElement)) {
  40. throw new Error(t("error.dev.rootNotFound"))
  41. }
  42. void initI18n()
  43. let update: Update | null = null
  44. const deepLinkEvent = "opencode:deep-link"
  45. const emitDeepLinks = (urls: string[]) => {
  46. if (urls.length === 0) return
  47. window.__OPENCODE__ ??= {}
  48. const pending = window.__OPENCODE__.deepLinks ?? []
  49. window.__OPENCODE__.deepLinks = [...pending, ...urls]
  50. window.dispatchEvent(new CustomEvent(deepLinkEvent, { detail: { urls } }))
  51. }
  52. const listenForDeepLinks = async () => {
  53. const startUrls = await getCurrent().catch(() => null)
  54. if (startUrls?.length) emitDeepLinks(startUrls)
  55. await onOpenUrl((urls) => emitDeepLinks(urls)).catch(() => undefined)
  56. }
  57. const createPlatform = (): Platform => {
  58. const os = (() => {
  59. const type = ostype()
  60. if (type === "macos" || type === "windows" || type === "linux") return type
  61. return undefined
  62. })()
  63. const wslHome = async () => {
  64. if (os !== "windows" || !window.__OPENCODE__?.wsl) return undefined
  65. return commands.wslPath("~", "windows").catch(() => undefined)
  66. }
  67. const handleWslPicker = async <T extends string | string[]>(result: T | null): Promise<T | null> => {
  68. if (!result || !window.__OPENCODE__?.wsl) return result
  69. if (Array.isArray(result)) {
  70. return Promise.all(result.map((path) => commands.wslPath(path, "linux").catch(() => path))) as any
  71. }
  72. return commands.wslPath(result, "linux").catch(() => result) as any
  73. }
  74. return {
  75. platform: "desktop",
  76. os,
  77. version: pkg.version,
  78. async openDirectoryPickerDialog(opts) {
  79. const defaultPath = await wslHome()
  80. const result = await open({
  81. directory: true,
  82. multiple: opts?.multiple ?? false,
  83. title: opts?.title ?? t("desktop.dialog.chooseFolder"),
  84. defaultPath,
  85. })
  86. return await handleWslPicker(result)
  87. },
  88. async openFilePickerDialog(opts) {
  89. const result = await open({
  90. directory: false,
  91. multiple: opts?.multiple ?? false,
  92. title: opts?.title ?? t("desktop.dialog.chooseFile"),
  93. filters: filePickerFilters(opts?.extensions ?? ACCEPTED_FILE_EXTENSIONS),
  94. })
  95. return handleWslPicker(result)
  96. },
  97. async saveFilePickerDialog(opts) {
  98. const result = await save({
  99. title: opts?.title ?? t("desktop.dialog.saveFile"),
  100. defaultPath: opts?.defaultPath,
  101. })
  102. return handleWslPicker(result)
  103. },
  104. openLink(url: string) {
  105. void shellOpen(url).catch(() => undefined)
  106. },
  107. async openPath(path: string, app?: string) {
  108. await commands.openPath(path, app ?? null)
  109. },
  110. back() {
  111. window.history.back()
  112. },
  113. forward() {
  114. window.history.forward()
  115. },
  116. storage: (() => {
  117. type StoreLike = {
  118. get(key: string): Promise<string | null | undefined>
  119. set(key: string, value: string): Promise<unknown>
  120. delete(key: string): Promise<unknown>
  121. clear(): Promise<unknown>
  122. keys(): Promise<string[]>
  123. length(): Promise<number>
  124. }
  125. const WRITE_DEBOUNCE_MS = 250
  126. const storeCache = new Map<string, Promise<StoreLike>>()
  127. const apiCache = new Map<string, AsyncStorage & { flush: () => Promise<void> }>()
  128. const memoryCache = new Map<string, StoreLike>()
  129. const flushAll = async () => {
  130. const apis = Array.from(apiCache.values())
  131. await Promise.all(apis.map((api) => api.flush().catch(() => undefined)))
  132. }
  133. if ("addEventListener" in globalThis) {
  134. const handleVisibility = () => {
  135. if (document.visibilityState !== "hidden") return
  136. void flushAll()
  137. }
  138. window.addEventListener("pagehide", () => void flushAll())
  139. document.addEventListener("visibilitychange", handleVisibility)
  140. }
  141. const createMemoryStore = () => {
  142. const data = new Map<string, string>()
  143. const store: StoreLike = {
  144. get: async (key) => data.get(key),
  145. set: async (key, value) => {
  146. data.set(key, value)
  147. },
  148. delete: async (key) => {
  149. data.delete(key)
  150. },
  151. clear: async () => {
  152. data.clear()
  153. },
  154. keys: async () => Array.from(data.keys()),
  155. length: async () => data.size,
  156. }
  157. return store
  158. }
  159. const getStore = (name: string) => {
  160. const cached = storeCache.get(name)
  161. if (cached) return cached
  162. const store = Store.load(name).catch(() => {
  163. const cached = memoryCache.get(name)
  164. if (cached) return cached
  165. const memory = createMemoryStore()
  166. memoryCache.set(name, memory)
  167. return memory
  168. })
  169. storeCache.set(name, store)
  170. return store
  171. }
  172. const createStorage = (name: string) => {
  173. const pending = new Map<string, string | null>()
  174. let timer: ReturnType<typeof setTimeout> | undefined
  175. let flushing: Promise<void> | undefined
  176. const flush = async () => {
  177. if (flushing) return flushing
  178. flushing = (async () => {
  179. const store = await getStore(name)
  180. while (pending.size > 0) {
  181. const batch = Array.from(pending.entries())
  182. pending.clear()
  183. for (const [key, value] of batch) {
  184. if (value === null) {
  185. await store.delete(key).catch(() => undefined)
  186. } else {
  187. await store.set(key, value).catch(() => undefined)
  188. }
  189. }
  190. }
  191. })().finally(() => {
  192. flushing = undefined
  193. })
  194. return flushing
  195. }
  196. const schedule = () => {
  197. if (timer) return
  198. timer = setTimeout(() => {
  199. timer = undefined
  200. void flush()
  201. }, WRITE_DEBOUNCE_MS)
  202. }
  203. const api: AsyncStorage & { flush: () => Promise<void> } = {
  204. flush,
  205. getItem: async (key: string) => {
  206. const next = pending.get(key)
  207. if (next !== undefined) return next
  208. const store = await getStore(name)
  209. const value = await store.get(key).catch(() => null)
  210. if (value === undefined) return null
  211. return value
  212. },
  213. setItem: async (key: string, value: string) => {
  214. pending.set(key, value)
  215. schedule()
  216. },
  217. removeItem: async (key: string) => {
  218. pending.set(key, null)
  219. schedule()
  220. },
  221. clear: async () => {
  222. pending.clear()
  223. const store = await getStore(name)
  224. await store.clear().catch(() => undefined)
  225. },
  226. key: async (index: number) => {
  227. const store = await getStore(name)
  228. return (await store.keys().catch(() => []))[index]
  229. },
  230. getLength: async () => {
  231. const store = await getStore(name)
  232. return await store.length().catch(() => 0)
  233. },
  234. get length() {
  235. return api.getLength()
  236. },
  237. }
  238. return api
  239. }
  240. return (name = "default.dat") => {
  241. const cached = apiCache.get(name)
  242. if (cached) return cached
  243. const api = createStorage(name)
  244. apiCache.set(name, api)
  245. return api
  246. }
  247. })(),
  248. checkUpdate: async () => {
  249. if (!UPDATER_ENABLED) return { updateAvailable: false }
  250. const next = await check().catch(() => null)
  251. if (!next) return { updateAvailable: false }
  252. const ok = await next
  253. .download()
  254. .then(() => true)
  255. .catch(() => false)
  256. if (!ok) return { updateAvailable: false }
  257. update = next
  258. return { updateAvailable: true, version: next.version }
  259. },
  260. updateAndRestart: async () => {
  261. if (!UPDATER_ENABLED || !update) return
  262. if (ostype() === "windows") await commands.killSidecar().catch(() => undefined)
  263. const installed = await update
  264. .install()
  265. .then(() => true)
  266. .catch(() => false)
  267. if (!installed) return
  268. await relaunch()
  269. },
  270. restart: async () => {
  271. await commands.killSidecar().catch(() => undefined)
  272. await relaunch()
  273. },
  274. notify: async (title, description, href) => {
  275. const granted = await isPermissionGranted().catch(() => false)
  276. const permission = granted ? "granted" : await requestPermission().catch(() => "denied")
  277. if (permission !== "granted") return
  278. const win = getCurrentWindow()
  279. const focused = await win.isFocused().catch(() => document.hasFocus())
  280. if (focused) return
  281. await Promise.resolve()
  282. .then(() => {
  283. const notification = new Notification(title, {
  284. body: description ?? "",
  285. icon: "https://opencode.ai/favicon-96x96-v3.png",
  286. })
  287. notification.onclick = () => {
  288. const win = getCurrentWindow()
  289. void win.show().catch(() => undefined)
  290. void win.unminimize().catch(() => undefined)
  291. void win.setFocus().catch(() => undefined)
  292. handleNotificationClick(href)
  293. notification.close()
  294. }
  295. })
  296. .catch(() => undefined)
  297. },
  298. fetch: (input, init) => {
  299. if (input instanceof Request) {
  300. return tauriFetch(input)
  301. } else {
  302. return tauriFetch(input, init)
  303. }
  304. },
  305. getWslEnabled: async () => {
  306. const next = await commands.getWslConfig().catch(() => null)
  307. if (next) return next.enabled
  308. return window.__OPENCODE__!.wsl ?? false
  309. },
  310. setWslEnabled: async (enabled) => {
  311. await commands.setWslConfig({ enabled })
  312. },
  313. getDefaultServer: async () => {
  314. const url = await commands.getDefaultServerUrl().catch(() => null)
  315. if (!url) return null
  316. return ServerConnection.Key.make(url)
  317. },
  318. setDefaultServer: async (url: string | null) => {
  319. await commands.setDefaultServerUrl(url)
  320. },
  321. getDisplayBackend: async () => {
  322. const result = await commands.getDisplayBackend().catch(() => null)
  323. return result
  324. },
  325. setDisplayBackend: async (backend) => {
  326. await commands.setDisplayBackend(backend)
  327. },
  328. parseMarkdown: (markdown: string) => commands.parseMarkdownCommand(markdown),
  329. webviewZoom,
  330. checkAppExists: async (appName: string) => {
  331. return commands.checkAppExists(appName)
  332. },
  333. async readClipboardImage() {
  334. const image = await readImage().catch(() => null)
  335. if (!image) return null
  336. const bytes = await image.rgba().catch(() => null)
  337. if (!bytes || bytes.length === 0) return null
  338. const size = await image.size().catch(() => null)
  339. if (!size) return null
  340. const canvas = document.createElement("canvas")
  341. canvas.width = size.width
  342. canvas.height = size.height
  343. const ctx = canvas.getContext("2d")
  344. if (!ctx) return null
  345. const imageData = ctx.createImageData(size.width, size.height)
  346. imageData.data.set(bytes)
  347. ctx.putImageData(imageData, 0, 0)
  348. return new Promise<File | null>((resolve) => {
  349. canvas.toBlob((blob) => {
  350. if (!blob) return resolve(null)
  351. resolve(
  352. new File([blob], `pasted-image-${Date.now()}.png`, {
  353. type: "image/png",
  354. }),
  355. )
  356. }, "image/png")
  357. })
  358. },
  359. }
  360. }
  361. let menuTrigger = null as null | ((id: string) => void)
  362. void createMenu((id) => {
  363. menuTrigger?.(id)
  364. })
  365. void listenForDeepLinks()
  366. render(() => {
  367. const platform = createPlatform()
  368. const loadLocale = async () => {
  369. const current = await platform.storage?.("opencode.global.dat").getItem("language")
  370. const legacy = current ? undefined : await platform.storage?.().getItem("language.v1")
  371. const raw = current ?? legacy
  372. if (!raw) return
  373. const locale = raw.match(/"locale"\s*:\s*"([^"]+)"/)?.[1]
  374. if (!locale) return
  375. const next = normalizeLocale(locale)
  376. if (next !== "en") await loadLocaleDict(next)
  377. return next satisfies Locale
  378. }
  379. // Fetch sidecar credentials from Rust (available immediately, before health check)
  380. const [sidecar] = createResource(() => commands.awaitInitialization(new Channel<InitStep>() as any))
  381. const [defaultServer] = createResource(() =>
  382. platform.getDefaultServer?.().then((url) => {
  383. if (url) return ServerConnection.key({ type: "http", http: { url } })
  384. }),
  385. )
  386. const [locale] = createResource(loadLocale)
  387. // Build the sidecar server connection once credentials arrive
  388. const servers = () => {
  389. const data = sidecar()
  390. if (!data) return []
  391. const http = {
  392. url: data.url,
  393. username: data.username ?? undefined,
  394. password: data.password ?? undefined,
  395. }
  396. const server: ServerConnection.Sidecar = {
  397. displayName: t("desktop.server.local"),
  398. type: "sidecar",
  399. variant: "base",
  400. http,
  401. }
  402. return [server] as ServerConnection.Any[]
  403. }
  404. function handleClick(e: MouseEvent) {
  405. const link = (e.target as HTMLElement).closest("a.external-link") as HTMLAnchorElement | null
  406. if (link?.href) {
  407. e.preventDefault()
  408. platform.openLink(link.href)
  409. }
  410. }
  411. function Inner() {
  412. const cmd = useCommand()
  413. menuTrigger = (id) => cmd.trigger(id)
  414. return null
  415. }
  416. onMount(() => {
  417. document.addEventListener("click", handleClick)
  418. onCleanup(() => {
  419. document.removeEventListener("click", handleClick)
  420. })
  421. })
  422. return (
  423. <PlatformProvider value={platform}>
  424. <AppBaseProviders locale={locale.latest}>
  425. <Show when={!defaultServer.loading && !sidecar.loading && !locale.loading}>
  426. {(_) => {
  427. return (
  428. <AppInterface
  429. defaultServer={defaultServer.latest ?? ServerConnection.Key.make("sidecar")}
  430. servers={servers()}
  431. >
  432. <Inner />
  433. </AppInterface>
  434. )
  435. }}
  436. </Show>
  437. </AppBaseProviders>
  438. </PlatformProvider>
  439. )
  440. }, root!)