child-store.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import { createRoot, createSignal, getOwner, onCleanup, runWithOwner, type Owner } from "solid-js"
  2. import { createStore, type SetStoreFunction, type Store } from "solid-js/store"
  3. import { Persist, persisted } from "@/utils/persist"
  4. import type { VcsInfo } from "@opencode-ai/sdk/v2/client"
  5. import {
  6. DIR_IDLE_TTL_MS,
  7. MAX_DIR_STORES,
  8. type ChildOptions,
  9. type DirState,
  10. type IconCache,
  11. type MetaCache,
  12. type ProjectMeta,
  13. type State,
  14. type VcsCache,
  15. } from "./types"
  16. import { canDisposeDirectory, pickDirectoriesToEvict } from "./eviction"
  17. import { useQuery } from "@tanstack/solid-query"
  18. import { QueryOptionsApi } from "../server-sync"
  19. import { directoryKey, type DirectoryKey } from "./utils"
  20. import { NormalizedProviderListResponse } from "@opencode-ai/ui/context"
  21. export function createChildStoreManager(input: {
  22. owner: Owner
  23. isBooting: (directory: string) => boolean
  24. isLoadingSessions: (directory: string) => boolean
  25. onBootstrap: (directory: string) => void
  26. onMcp: (directory: string, setStore: SetStoreFunction<State>) => void
  27. onDispose: (directory: string) => void
  28. translate: (key: string, vars?: Record<string, string | number>) => string
  29. queryOptions: QueryOptionsApi
  30. global: {
  31. provider: NormalizedProviderListResponse
  32. }
  33. }) {
  34. const children: Record<string, [Store<State>, SetStoreFunction<State>]> = {}
  35. const vcsCache = new Map<string, VcsCache>()
  36. const metaCache = new Map<string, MetaCache>()
  37. const iconCache = new Map<string, IconCache>()
  38. const lifecycle = new Map<string, DirState>()
  39. const pins = new Map<string, number>()
  40. const ownerPins = new WeakMap<object, Set<string>>()
  41. const disposers = new Map<string, () => void>()
  42. const mcpDirectories = new Set<string>()
  43. const mcpToggles = new Map<string, (enabled: boolean) => void>()
  44. const markKey = (key: DirectoryKey) => {
  45. if (!key) return
  46. lifecycle.set(key, { lastAccessAt: Date.now() })
  47. runEviction(key)
  48. }
  49. const mark = (directory: string) => {
  50. const key = directoryKey(directory)
  51. markKey(key)
  52. }
  53. const pin = (directory: string) => {
  54. const key = directoryKey(directory)
  55. if (!key) return
  56. pins.set(key, (pins.get(key) ?? 0) + 1)
  57. markKey(key)
  58. }
  59. const unpin = (directory: string) => {
  60. const key = directoryKey(directory)
  61. if (!key) return
  62. const next = (pins.get(key) ?? 0) - 1
  63. if (next > 0) {
  64. pins.set(key, next)
  65. return
  66. }
  67. pins.delete(key)
  68. runEviction()
  69. }
  70. const pinned = (directory: string) => (pins.get(directoryKey(directory)) ?? 0) > 0
  71. const pinForOwner = (directory: string) => {
  72. const current = getOwner()
  73. if (!current) return
  74. if (current === input.owner) return
  75. const key = current as object
  76. const set = ownerPins.get(key)
  77. if (set?.has(directory)) return
  78. if (set) set.add(directory)
  79. if (!set) ownerPins.set(key, new Set([directory]))
  80. pin(directory)
  81. onCleanup(() => {
  82. const set = ownerPins.get(key)
  83. if (set) {
  84. set.delete(directory)
  85. if (set.size === 0) ownerPins.delete(key)
  86. }
  87. unpin(directory)
  88. })
  89. }
  90. function disposeDirectory(directory: DirectoryKey) {
  91. const key = directory
  92. if (
  93. !canDisposeDirectory({
  94. directory: key,
  95. hasStore: !!children[key],
  96. pinned: pinned(key),
  97. booting: input.isBooting(key),
  98. loadingSessions: input.isLoadingSessions(key),
  99. })
  100. ) {
  101. return false
  102. }
  103. vcsCache.delete(key)
  104. metaCache.delete(key)
  105. iconCache.delete(key)
  106. lifecycle.delete(key)
  107. mcpDirectories.delete(key)
  108. mcpToggles.delete(key)
  109. const dispose = disposers.get(key)
  110. if (dispose) {
  111. dispose()
  112. disposers.delete(key)
  113. }
  114. delete children[key]
  115. input.onDispose(key)
  116. return true
  117. }
  118. function runEviction(skip?: string) {
  119. const stores = Object.keys(children)
  120. if (stores.length === 0) return
  121. const list = pickDirectoriesToEvict({
  122. stores,
  123. state: lifecycle,
  124. pins: new Set(stores.filter(pinned)),
  125. max: MAX_DIR_STORES,
  126. ttl: DIR_IDLE_TTL_MS,
  127. now: Date.now(),
  128. }).filter((directory) => directory !== skip)
  129. if (list.length === 0) return
  130. for (const directory of list) {
  131. if (!disposeDirectory(directoryKey(directory))) continue
  132. }
  133. }
  134. function ensureChild(directory: string) {
  135. const key = directoryKey(directory)
  136. if (!key) console.error("No directory provided")
  137. if (!children[key]) {
  138. const vcs = runWithOwner(input.owner, () =>
  139. persisted(
  140. Persist.workspace(directory, "vcs", ["vcs.v1"]),
  141. createStore({ value: undefined as VcsInfo | undefined }),
  142. ),
  143. )
  144. if (!vcs) throw new Error(input.translate("error.childStore.persistedCacheCreateFailed"))
  145. const vcsStore = vcs[0]
  146. vcsCache.set(key, { store: vcsStore, setStore: vcs[1], ready: vcs[3] })
  147. const meta = runWithOwner(input.owner, () =>
  148. persisted(
  149. Persist.workspace(directory, "project", ["project.v1"]),
  150. createStore({ value: undefined as ProjectMeta | undefined }),
  151. ),
  152. )
  153. if (!meta) throw new Error(input.translate("error.childStore.persistedProjectMetadataCreateFailed"))
  154. metaCache.set(key, { store: meta[0], setStore: meta[1], ready: meta[3] })
  155. const icon = runWithOwner(input.owner, () =>
  156. persisted(
  157. Persist.workspace(directory, "icon", ["icon.v1"]),
  158. createStore({ value: undefined as string | undefined }),
  159. ),
  160. )
  161. if (!icon) throw new Error(input.translate("error.childStore.persistedProjectIconCreateFailed"))
  162. iconCache.set(key, { store: icon[0], setStore: icon[1], ready: icon[3] })
  163. const init = () =>
  164. createRoot((dispose) => {
  165. const initialMeta = meta[0].value
  166. const initialIcon = icon[0].value
  167. const [mcpEnabled, setMcpEnabled] = createSignal(false)
  168. const pathQuery = useQuery(() => input.queryOptions.path(key))
  169. const mcpQuery = useQuery(() => ({ ...input.queryOptions.mcp(key), enabled: mcpEnabled() }))
  170. const lspQuery = useQuery(() => input.queryOptions.lsp(key))
  171. const providerQuery = useQuery(() => input.queryOptions.providers(key))
  172. const child = createStore<State>({
  173. project: "",
  174. projectMeta: initialMeta,
  175. icon: initialIcon,
  176. get provider_ready() {
  177. return !providerQuery.isLoading
  178. },
  179. get provider() {
  180. const EMPTY = { all: new Map(), connected: [], default: {} }
  181. if (providerQuery.isLoading) return EMPTY
  182. if (providerQuery.data?.all.size === 0 && input.global.provider.all.size > 0) return input.global.provider
  183. return providerQuery.data ?? EMPTY
  184. },
  185. config: {},
  186. get path() {
  187. if (pathQuery.data) return pathQuery.data
  188. return { state: "", config: "", worktree: "", directory, home: "" }
  189. },
  190. status: "loading" as const,
  191. agent: [],
  192. command: [],
  193. session: [],
  194. sessionTotal: 0,
  195. session_status: {},
  196. session_working(id: string) {
  197. const type = this.session_status[id]?.type
  198. return (type ?? "idle") !== "idle"
  199. },
  200. session_diff: {},
  201. todo: {},
  202. permission: {},
  203. question: {},
  204. get mcp_ready() {
  205. return !mcpQuery.isLoading
  206. },
  207. get mcp() {
  208. return mcpQuery.isLoading ? {} : (mcpQuery.data ?? {})
  209. },
  210. get lsp_ready() {
  211. return !lspQuery.isLoading
  212. },
  213. get lsp() {
  214. return lspQuery.isLoading ? [] : (lspQuery.data ?? [])
  215. },
  216. vcs: vcsStore.value,
  217. limit: 5,
  218. message: {},
  219. part: {},
  220. part_text_accum_delta: {},
  221. })
  222. children[key] = child
  223. disposers.set(key, dispose)
  224. mcpToggles.set(key, setMcpEnabled)
  225. const onPersistedInit = (init: Promise<string> | string | null, run: () => void) => {
  226. if (!(init instanceof Promise)) return
  227. void init.then(() => {
  228. if (children[key] !== child) return
  229. run()
  230. })
  231. }
  232. onPersistedInit(vcs[2], () => {
  233. const cached = vcsStore.value
  234. if (!cached?.branch) return
  235. child[1]("vcs", (value) => value ?? cached)
  236. })
  237. onPersistedInit(meta[2], () => {
  238. if (child[0].projectMeta !== initialMeta) return
  239. child[1]("projectMeta", meta[0].value)
  240. })
  241. onPersistedInit(icon[2], () => {
  242. if (child[0].icon !== initialIcon) return
  243. child[1]("icon", icon[0].value)
  244. })
  245. })
  246. runWithOwner(input.owner, init)
  247. }
  248. markKey(key)
  249. const childStore = children[key]
  250. if (!childStore) throw new Error(input.translate("error.childStore.storeCreateFailed"))
  251. return childStore
  252. }
  253. function child(directory: string, options: ChildOptions = {}) {
  254. const key = directoryKey(directory)
  255. const childStore = ensureChild(directory)
  256. pinForOwner(key)
  257. if (options.mcp) enableMcp(directory, key, childStore)
  258. const shouldBootstrap = options.bootstrap ?? true
  259. if (shouldBootstrap && childStore[0].status === "loading") {
  260. input.onBootstrap(directory)
  261. }
  262. return childStore
  263. }
  264. function peek(directory: string, options: ChildOptions = {}) {
  265. const key = directoryKey(directory)
  266. const childStore = ensureChild(directory)
  267. if (options.mcp) enableMcp(directory, key, childStore)
  268. const shouldBootstrap = options.bootstrap ?? true
  269. if (shouldBootstrap && childStore[0].status === "loading") {
  270. input.onBootstrap(directory)
  271. }
  272. return childStore
  273. }
  274. function enableMcp(directory: string, key: DirectoryKey, childStore: [Store<State>, SetStoreFunction<State>]) {
  275. if (mcpDirectories.has(key)) return
  276. mcpDirectories.add(key)
  277. mcpToggles.get(key)?.(true)
  278. if (childStore[0].status !== "loading") input.onMcp(directory, childStore[1])
  279. }
  280. function disableMcp(directory: string) {
  281. const key = directoryKey(directory)
  282. if (!mcpDirectories.delete(key)) return
  283. mcpToggles.get(key)?.(false)
  284. }
  285. function projectMeta(directory: string, patch: ProjectMeta) {
  286. const key = directoryKey(directory)
  287. const [store, setStore] = ensureChild(directory)
  288. const cached = metaCache.get(key)
  289. if (!cached) return
  290. const previous = store.projectMeta ?? {}
  291. const icon = patch.icon ? { ...previous.icon, ...patch.icon } : previous.icon
  292. const commands = patch.commands ? { ...previous.commands, ...patch.commands } : previous.commands
  293. const next = {
  294. ...previous,
  295. ...patch,
  296. icon,
  297. commands,
  298. }
  299. cached.setStore("value", next)
  300. setStore("projectMeta", next)
  301. }
  302. function projectIcon(directory: string, value: string | undefined) {
  303. const key = directoryKey(directory)
  304. const [store, setStore] = ensureChild(directory)
  305. const cached = iconCache.get(key)
  306. if (!cached) return
  307. if (store.icon === value) return
  308. cached.setStore("value", value)
  309. setStore("icon", value)
  310. }
  311. return {
  312. children,
  313. ensureChild,
  314. child,
  315. peek,
  316. projectMeta,
  317. projectIcon,
  318. mark,
  319. pin,
  320. unpin,
  321. pinned,
  322. mcp: (directory: string) => mcpDirectories.has(directoryKey(directory)),
  323. disableMcp,
  324. disposeDirectory,
  325. runEviction,
  326. vcsCache,
  327. metaCache,
  328. iconCache,
  329. }
  330. }