index.tsx 15 KB

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