local.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import { createStore, produce, reconcile } from "solid-js/store"
  2. import { batch, createContext, createEffect, createMemo, useContext, type ParentProps } from "solid-js"
  3. import { uniqueBy } from "remeda"
  4. import type { FileContent, FileNode } from "@opencode-ai/sdk"
  5. import { useSDK, useEvent, useSync } from "@/context"
  6. export type LocalFile = FileNode &
  7. Partial<{
  8. loaded: boolean
  9. pinned: boolean
  10. expanded: boolean
  11. content: FileContent
  12. selection: { startLine: number; startChar: number; endLine: number; endChar: number }
  13. scrollTop: number
  14. view: "raw" | "diff-unified" | "diff-split"
  15. folded: string[]
  16. selectedChange: number
  17. }>
  18. export type TextSelection = LocalFile["selection"]
  19. export type View = LocalFile["view"]
  20. function init() {
  21. const sdk = useSDK()
  22. const sync = useSync()
  23. const list = createMemo(() => sync.data.agent.filter((x) => x.mode !== "subagent"))
  24. const agent = (() => {
  25. const [store, setStore] = createStore<{
  26. current: string
  27. }>({
  28. current: list()[0].name,
  29. })
  30. return {
  31. list,
  32. current() {
  33. return list().find((x) => x.name === store.current)!
  34. },
  35. set(name: string | undefined) {
  36. setStore("current", name ?? list()[0].name)
  37. },
  38. move(direction: 1 | -1) {
  39. let next = list().findIndex((x) => x.name === store.current) + direction
  40. if (next < 0) next = list().length - 1
  41. if (next >= list().length) next = 0
  42. const value = list()[next]
  43. setStore("current", value.name)
  44. if (value.model)
  45. model.set({
  46. providerID: value.model.providerID,
  47. modelID: value.model.modelID,
  48. })
  49. },
  50. }
  51. })()
  52. const model = (() => {
  53. const [store, setStore] = createStore<{
  54. model: Record<
  55. string,
  56. {
  57. providerID: string
  58. modelID: string
  59. }
  60. >
  61. recent: {
  62. providerID: string
  63. modelID: string
  64. }[]
  65. }>({
  66. model: {},
  67. recent: [],
  68. })
  69. const value = localStorage.getItem("model")
  70. setStore("recent", JSON.parse(value ?? "[]"))
  71. createEffect(() => {
  72. localStorage.setItem("model", JSON.stringify(store.recent))
  73. })
  74. const fallback = createMemo(() => {
  75. if (store.recent.length) return store.recent[0]
  76. const provider = sync.data.provider[0]
  77. const model = Object.values(provider.models)[0]
  78. return {
  79. providerID: provider.id,
  80. modelID: model.id,
  81. }
  82. })
  83. const current = createMemo(() => {
  84. const a = agent.current()
  85. return store.model[agent.current().name] ?? (a.model ? a.model : fallback())
  86. })
  87. const list = createMemo(() =>
  88. sync.data.provider.flatMap((x) => Object.values(x.models).map((m) => ({ providerID: x.id, modelID: m.id }))),
  89. )
  90. return {
  91. list,
  92. current,
  93. recent() {
  94. return store.recent
  95. },
  96. parsed: createMemo(() => {
  97. const value = current()
  98. const provider = sync.data.provider.find((x) => x.id === value.providerID)!
  99. const model = provider.models[value.modelID]
  100. return {
  101. provider: provider.name ?? value.providerID,
  102. model: model.name ?? value.modelID,
  103. }
  104. }),
  105. set(model: { providerID: string; modelID: string } | undefined, options?: { recent?: boolean }) {
  106. batch(() => {
  107. setStore("model", agent.current().name, model ?? fallback())
  108. if (options?.recent && model) {
  109. const uniq = uniqueBy([model, ...store.recent], (x) => x.providerID + x.modelID)
  110. if (uniq.length > 5) uniq.pop()
  111. setStore("recent", uniq)
  112. }
  113. })
  114. },
  115. }
  116. })()
  117. const file = (() => {
  118. const [store, setStore] = createStore<{
  119. node: Record<string, LocalFile>
  120. opened: string[]
  121. active?: string
  122. }>({
  123. node: Object.fromEntries(sync.data.node.map((x) => [x.path, x])),
  124. opened: [],
  125. })
  126. const active = createMemo(() => {
  127. if (!store.active) return undefined
  128. return store.node[store.active]
  129. })
  130. const opened = createMemo(() => store.opened.map((x) => store.node[x]))
  131. const changes = createMemo(() => new Set(sync.data.changes.map((f) => f.path)))
  132. const status = (path: string) => sync.data.changes.find((f) => f.path === path)
  133. const changed = (path: string) => {
  134. const set = changes()
  135. if (set.has(path)) return true
  136. for (const p of set) {
  137. if (p.startsWith(path ? path + "/" : "")) return true
  138. }
  139. return false
  140. }
  141. const resetNode = (path: string) => {
  142. setStore("node", path, {
  143. loaded: undefined,
  144. pinned: undefined,
  145. content: undefined,
  146. selection: undefined,
  147. scrollTop: undefined,
  148. folded: undefined,
  149. view: undefined,
  150. selectedChange: undefined,
  151. })
  152. }
  153. const load = async (path: string) => {
  154. const relative = path.replace(sync.data.path.directory + "/", "")
  155. sdk.file.read({ query: { path: relative } }).then((x) => {
  156. setStore(
  157. "node",
  158. relative,
  159. produce((draft) => {
  160. draft.loaded = true
  161. draft.content = x.data
  162. }),
  163. )
  164. })
  165. }
  166. const open = async (path: string) => {
  167. const relative = path.replace(sync.data.path.directory + "/", "")
  168. if (!store.node[relative]) {
  169. const parent = relative.split("/").slice(0, -1).join("/")
  170. if (parent) {
  171. await list(parent)
  172. }
  173. }
  174. setStore("opened", (x) => {
  175. if (x.includes(relative)) return x
  176. return [
  177. ...opened()
  178. .filter((x) => x.pinned)
  179. .map((x) => x.path),
  180. relative,
  181. ]
  182. })
  183. setStore("active", relative)
  184. if (store.node[relative].loaded) return
  185. return load(relative)
  186. }
  187. const list = async (path: string) => {
  188. return sdk.file.list({ query: { path: path + "/" } }).then((x) => {
  189. setStore(
  190. "node",
  191. produce((draft) => {
  192. x.data!.forEach((node) => {
  193. if (node.path in draft) return
  194. draft[node.path] = node
  195. })
  196. }),
  197. )
  198. })
  199. }
  200. const bus = useEvent()
  201. bus.listen((event) => {
  202. switch (event.type) {
  203. case "message.part.updated":
  204. const part = event.properties.part
  205. if (part.type === "tool" && part.state.status === "completed") {
  206. switch (part.tool) {
  207. case "read":
  208. console.log("read", part.state.input)
  209. break
  210. case "edit":
  211. load(part.state.input["filePath"] as string)
  212. break
  213. default:
  214. break
  215. }
  216. }
  217. break
  218. case "file.watcher.updated":
  219. load(event.properties.file)
  220. break
  221. }
  222. })
  223. return {
  224. active,
  225. opened,
  226. node: (path: string) => store.node[path],
  227. update: (path: string, node: LocalFile) => setStore("node", path, reconcile(node)),
  228. open,
  229. load,
  230. close(path: string) {
  231. setStore("opened", (opened) => opened.filter((x) => x !== path))
  232. if (store.active === path) {
  233. const index = store.opened.findIndex((f) => f === path)
  234. const previous = store.opened[Math.max(0, index - 1)]
  235. setStore("active", previous)
  236. }
  237. resetNode(path)
  238. },
  239. expand(path: string) {
  240. setStore("node", path, "expanded", true)
  241. if (store.node[path].loaded) return
  242. setStore("node", path, "loaded", true)
  243. list(path)
  244. },
  245. collapse(path: string) {
  246. setStore("node", path, "expanded", false)
  247. },
  248. select(path: string, selection: TextSelection | undefined) {
  249. setStore("node", path, "selection", selection)
  250. },
  251. scroll(path: string, scrollTop: number) {
  252. setStore("node", path, "scrollTop", scrollTop)
  253. },
  254. move(path: string, to: number) {
  255. const index = store.opened.findIndex((f) => f === path)
  256. if (index === -1) return
  257. setStore(
  258. "opened",
  259. produce((opened) => {
  260. opened.splice(to, 0, opened.splice(index, 1)[0])
  261. }),
  262. )
  263. setStore("node", path, "pinned", true)
  264. },
  265. view(path: string): View {
  266. const n = store.node[path]
  267. return n && n.view ? n.view : "raw"
  268. },
  269. setView(path: string, view: View) {
  270. setStore("node", path, "view", view)
  271. },
  272. unfold(path: string, key: string) {
  273. setStore("node", path, "folded", (xs) => {
  274. const a = xs ?? []
  275. if (a.includes(key)) return a
  276. return [...a, key]
  277. })
  278. },
  279. fold(path: string, key: string) {
  280. setStore("node", path, "folded", (xs) => (xs ?? []).filter((k) => k !== key))
  281. },
  282. folded(path: string) {
  283. const n = store.node[path]
  284. return n && n.folded ? n.folded : []
  285. },
  286. changeIndex(path: string) {
  287. return store.node[path]?.selectedChange
  288. },
  289. setChangeIndex(path: string, index: number | undefined) {
  290. setStore("node", path, "selectedChange", index)
  291. },
  292. changed,
  293. status,
  294. children(path: string) {
  295. return Object.values(store.node).filter(
  296. (x) =>
  297. x.path.startsWith(path) &&
  298. x.path !== path &&
  299. !x.path.replace(new RegExp(`^${path + "/"}`), "").includes("/"),
  300. )
  301. },
  302. }
  303. })()
  304. const layout = (() => {
  305. const [store, setStore] = createStore<{
  306. rightPane: boolean
  307. leftWidth: number
  308. rightWidth: number
  309. }>({
  310. rightPane: false,
  311. leftWidth: 200, // Default 50 * 4px (w-50 = 12.5rem = 200px)
  312. rightWidth: 320, // Default 80 * 4px (w-80 = 20rem = 320px)
  313. })
  314. const value = localStorage.getItem("layout")
  315. if (value) {
  316. const v = JSON.parse(value)
  317. if (typeof v?.rightPane === "boolean") setStore("rightPane", v.rightPane)
  318. if (typeof v?.leftWidth === "number") setStore("leftWidth", Math.max(150, Math.min(400, v.leftWidth)))
  319. if (typeof v?.rightWidth === "number") setStore("rightWidth", Math.max(200, Math.min(500, v.rightWidth)))
  320. }
  321. createEffect(() => {
  322. localStorage.setItem("layout", JSON.stringify(store))
  323. })
  324. return {
  325. rightPane() {
  326. return store.rightPane
  327. },
  328. leftWidth() {
  329. return store.leftWidth
  330. },
  331. rightWidth() {
  332. return store.rightWidth
  333. },
  334. toggleRightPane() {
  335. setStore("rightPane", (x) => !x)
  336. },
  337. openRightPane() {
  338. setStore("rightPane", true)
  339. },
  340. closeRightPane() {
  341. setStore("rightPane", false)
  342. },
  343. setLeftWidth(width: number) {
  344. setStore("leftWidth", Math.max(150, Math.min(400, width)))
  345. },
  346. setRightWidth(width: number) {
  347. setStore("rightWidth", Math.max(200, Math.min(500, width)))
  348. },
  349. }
  350. })()
  351. const session = (() => {
  352. const [store, setStore] = createStore<{
  353. active?: string
  354. }>({})
  355. const active = createMemo(() => {
  356. if (!store.active) return undefined
  357. return sync.session.get(store.active)
  358. })
  359. return {
  360. active,
  361. setActive(sessionId: string | undefined) {
  362. setStore("active", sessionId)
  363. },
  364. clearActive() {
  365. setStore("active", undefined)
  366. },
  367. }
  368. })()
  369. const result = {
  370. model,
  371. agent,
  372. file,
  373. layout,
  374. session,
  375. }
  376. return result
  377. }
  378. type LocalContext = ReturnType<typeof init>
  379. const ctx = createContext<LocalContext>()
  380. export function LocalProvider(props: ParentProps) {
  381. const value = init()
  382. return <ctx.Provider value={value}>{props.children}</ctx.Provider>
  383. }
  384. export function useLocal() {
  385. const value = useContext(ctx)
  386. if (!value) {
  387. throw new Error("useLocal must be used within a LocalProvider")
  388. }
  389. return value
  390. }