server.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { createSimpleContext } from "@opencode-ai/ui/context"
  2. import { type Accessor, batch, createEffect, createMemo, onCleanup } from "solid-js"
  3. import { createStore } from "solid-js/store"
  4. import { usePlatform } from "@/context/platform"
  5. import { Persist, persisted } from "@/utils/persist"
  6. import { checkServerHealth } from "@/utils/server-health"
  7. type StoredProject = { worktree: string; expanded: boolean }
  8. type StoredServer = string | ServerConnection.HttpBase | ServerConnection.Http
  9. const HEALTH_POLL_INTERVAL_MS = 10_000
  10. export function normalizeServerUrl(input: string) {
  11. const trimmed = input.trim()
  12. if (!trimmed) return
  13. const withProtocol = /^https?:\/\//.test(trimmed) ? trimmed : `http://${trimmed}`
  14. return withProtocol.replace(/\/+$/, "")
  15. }
  16. export function serverName(conn?: ServerConnection.Any, ignoreDisplayName = false) {
  17. if (!conn) return ""
  18. if (conn.displayName && !ignoreDisplayName) return conn.displayName
  19. return conn.http.url.replace(/^https?:\/\//, "").replace(/\/+$/, "")
  20. }
  21. function projectsKey(key: ServerConnection.Key) {
  22. if (!key) return ""
  23. if (key === "sidecar") return "local"
  24. if (isLocalHost(key)) return "local"
  25. return key
  26. }
  27. function isLocalHost(url: string) {
  28. const host = url.replace(/^https?:\/\//, "").split(":")[0]
  29. if (host === "localhost" || host === "127.0.0.1") return "local"
  30. }
  31. export namespace ServerConnection {
  32. type Base = { displayName?: string }
  33. export type HttpBase = {
  34. url: string
  35. username?: string
  36. password?: string
  37. }
  38. // Regular web connections
  39. export type Http = {
  40. type: "http"
  41. http: HttpBase
  42. } & Base
  43. export type Sidecar = {
  44. type: "sidecar"
  45. http: HttpBase
  46. } & (
  47. | // Regular desktop server
  48. { variant: "base" }
  49. // WSL server (windows only)
  50. | {
  51. variant: "wsl"
  52. distro: string
  53. }
  54. ) &
  55. Base
  56. // Remote server desktop can SSH into
  57. export type Ssh = {
  58. type: "ssh"
  59. host: string
  60. // SSH client exposes an HTTP server for the app to use as a proxy
  61. http: HttpBase
  62. } & Base
  63. export type Any =
  64. | Http
  65. // All these are desktop-only
  66. | (Sidecar | Ssh)
  67. export const key = (conn: Any): Key => {
  68. switch (conn.type) {
  69. case "http":
  70. return Key.make(conn.http.url)
  71. case "sidecar": {
  72. if (conn.variant === "wsl") return Key.make(`wsl:${conn.distro}`)
  73. return Key.make("sidecar")
  74. }
  75. case "ssh":
  76. return Key.make(`ssh:${conn.host}`)
  77. }
  78. }
  79. export type Key = string & { _brand: "Key" }
  80. export const Key = { make: (v: string) => v as Key }
  81. }
  82. export const { use: useServer, provider: ServerProvider } = createSimpleContext({
  83. name: "Server",
  84. init: (props: { defaultServer: ServerConnection.Key; servers?: Array<ServerConnection.Any> }) => {
  85. const platform = usePlatform()
  86. const [store, setStore, _, ready] = persisted(
  87. Persist.global("server", ["server.v3"]),
  88. createStore({
  89. list: [] as StoredServer[],
  90. projects: {} as Record<string, StoredProject[]>,
  91. lastProject: {} as Record<string, string>,
  92. }),
  93. )
  94. const url = (x: StoredServer) => (typeof x === "string" ? x : "type" in x ? x.http.url : x.url)
  95. const allServers = createMemo((): Array<ServerConnection.Any> => {
  96. const servers = [
  97. ...(props.servers ?? []),
  98. ...store.list.map((value) =>
  99. typeof value === "string"
  100. ? {
  101. type: "http" as const,
  102. http: { url: value },
  103. }
  104. : value,
  105. ),
  106. ]
  107. const deduped = new Map(
  108. servers.map((value) => {
  109. const conn: ServerConnection.Any = "type" in value ? value : { type: "http", http: value }
  110. return [ServerConnection.key(conn), conn]
  111. }),
  112. )
  113. return [...deduped.values()]
  114. })
  115. const [state, setState] = createStore({
  116. active: props.defaultServer,
  117. healthy: undefined as boolean | undefined,
  118. })
  119. const healthy = () => state.healthy
  120. function startHealthPolling(conn: ServerConnection.Any) {
  121. let alive = true
  122. let busy = false
  123. const run = () => {
  124. if (busy) return
  125. busy = true
  126. void check(conn)
  127. .then((next) => {
  128. if (!alive) return
  129. setState("healthy", next)
  130. })
  131. .finally(() => {
  132. busy = false
  133. })
  134. }
  135. run()
  136. const interval = setInterval(run, HEALTH_POLL_INTERVAL_MS)
  137. return () => {
  138. alive = false
  139. clearInterval(interval)
  140. }
  141. }
  142. function setActive(input: ServerConnection.Key) {
  143. if (state.active !== input) setState("active", input)
  144. }
  145. function add(input: ServerConnection.Http) {
  146. const url_ = normalizeServerUrl(input.http.url)
  147. if (!url_) return
  148. const conn = { ...input, http: { ...input.http, url: url_ } }
  149. return batch(() => {
  150. const existing = store.list.findIndex((x) => url(x) === url_)
  151. if (existing !== -1) {
  152. setStore("list", existing, conn)
  153. } else {
  154. setStore("list", store.list.length, conn)
  155. }
  156. setState("active", ServerConnection.key(conn))
  157. return conn
  158. })
  159. }
  160. function remove(key: ServerConnection.Key) {
  161. const list = store.list.filter((x) => url(x) !== key)
  162. batch(() => {
  163. setStore("list", list)
  164. if (state.active === key) {
  165. const next = list[0]
  166. setState("active", next ? ServerConnection.Key.make(url(next)) : props.defaultServer)
  167. }
  168. })
  169. }
  170. const isReady = createMemo(() => ready() && !!state.active)
  171. const fetcher = platform.fetch ?? globalThis.fetch
  172. const check = (conn: ServerConnection.Any) => checkServerHealth(conn.http, fetcher).then((x) => x.healthy)
  173. createEffect(() => {
  174. const current_ = current()
  175. if (!current_) return
  176. setState("healthy", undefined)
  177. onCleanup(startHealthPolling(current_))
  178. })
  179. const origin = createMemo(() => projectsKey(state.active))
  180. const projectsList = createMemo(() => store.projects[origin()] ?? [])
  181. const current: Accessor<ServerConnection.Any | undefined> = createMemo(
  182. () => allServers().find((s) => ServerConnection.key(s) === state.active) ?? allServers()[0],
  183. )
  184. const isLocal = createMemo(() => {
  185. const c = current()
  186. return (c?.type === "sidecar" && c.variant === "base") || (c?.type === "http" && isLocalHost(c.http.url))
  187. })
  188. return {
  189. ready: isReady,
  190. healthy,
  191. isLocal,
  192. get key() {
  193. return state.active
  194. },
  195. get name() {
  196. return serverName(current())
  197. },
  198. get list() {
  199. return allServers()
  200. },
  201. get current() {
  202. return current()
  203. },
  204. setActive,
  205. add,
  206. remove,
  207. projects: {
  208. list: projectsList,
  209. open(directory: string) {
  210. const key = origin()
  211. if (!key) return
  212. const current = store.projects[key] ?? []
  213. if (current.find((x) => x.worktree === directory)) return
  214. setStore("projects", key, [{ worktree: directory, expanded: true }, ...current])
  215. },
  216. close(directory: string) {
  217. const key = origin()
  218. if (!key) return
  219. const current = store.projects[key] ?? []
  220. setStore(
  221. "projects",
  222. key,
  223. current.filter((x) => x.worktree !== directory),
  224. )
  225. },
  226. expand(directory: string) {
  227. const key = origin()
  228. if (!key) return
  229. const current = store.projects[key] ?? []
  230. const index = current.findIndex((x) => x.worktree === directory)
  231. if (index !== -1) setStore("projects", key, index, "expanded", true)
  232. },
  233. collapse(directory: string) {
  234. const key = origin()
  235. if (!key) return
  236. const current = store.projects[key] ?? []
  237. const index = current.findIndex((x) => x.worktree === directory)
  238. if (index !== -1) setStore("projects", key, index, "expanded", false)
  239. },
  240. move(directory: string, toIndex: number) {
  241. const key = origin()
  242. if (!key) return
  243. const current = store.projects[key] ?? []
  244. const fromIndex = current.findIndex((x) => x.worktree === directory)
  245. if (fromIndex === -1 || fromIndex === toIndex) return
  246. const result = [...current]
  247. const [item] = result.splice(fromIndex, 1)
  248. result.splice(toIndex, 0, item)
  249. setStore("projects", key, result)
  250. },
  251. last() {
  252. const key = origin()
  253. if (!key) return
  254. return store.lastProject[key]
  255. },
  256. touch(directory: string) {
  257. const key = origin()
  258. if (!key) return
  259. setStore("lastProject", key, directory)
  260. },
  261. },
  262. }
  263. },
  264. })