index.tsx 15 KB

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