directory-sync.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. import { batch, createMemo } from "solid-js"
  2. import { createStore, produce, reconcile } from "solid-js/store"
  3. import { Binary } from "@opencode-ai/core/util/binary"
  4. import { retry } from "@opencode-ai/core/util/retry"
  5. import {
  6. clearSessionPrefetch,
  7. getSessionPrefetch,
  8. getSessionPrefetchPromise,
  9. setSessionPrefetch,
  10. } from "./global-sync/session-prefetch"
  11. import { useGlobalSync } from "./global-sync"
  12. import type { Message, OpencodeClient, Part } from "@opencode-ai/sdk/v2/client"
  13. import { SESSION_CACHE_LIMIT, dropSessionCaches, pickSessionCacheEvictions } from "./global-sync/session-cache"
  14. import { diffs as list, message as clean } from "@/utils/diffs"
  15. const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
  16. function sortParts(parts: Part[]) {
  17. return parts.filter((part) => !!part?.id).sort((a, b) => cmp(a.id, b.id))
  18. }
  19. function runInflight(map: Map<string, Promise<void>>, key: string, task: () => Promise<void>) {
  20. const pending = map.get(key)
  21. if (pending) return pending
  22. const promise = task().finally(() => {
  23. map.delete(key)
  24. })
  25. map.set(key, promise)
  26. return promise
  27. }
  28. const keyFor = (directory: string, id: string) => `${directory}\n${id}`
  29. const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
  30. function merge<T extends { id: string }>(a: readonly T[], b: readonly T[]) {
  31. const map = new Map(a.map((item) => [item.id, item] as const))
  32. for (const item of b) map.set(item.id, item)
  33. return [...map.values()].sort((x, y) => cmp(x.id, y.id))
  34. }
  35. type OptimisticStore = {
  36. message: Record<string, Message[] | undefined>
  37. part: Record<string, Part[] | undefined>
  38. }
  39. type OptimisticAddInput = {
  40. sessionID: string
  41. message: Message
  42. parts: Part[]
  43. }
  44. type OptimisticRemoveInput = {
  45. sessionID: string
  46. messageID: string
  47. }
  48. type OptimisticItem = {
  49. message: Message
  50. parts: Part[]
  51. }
  52. type MessagePage = {
  53. session: Message[]
  54. part: { id: string; part: Part[] }[]
  55. cursor?: string
  56. complete: boolean
  57. }
  58. const hasParts = (parts: Part[] | undefined, want: Part[]) => {
  59. if (!parts) return want.length === 0
  60. return want.every((part) => Binary.search(parts, part.id, (item) => item.id).found)
  61. }
  62. const mergeParts = (parts: Part[] | undefined, want: Part[]) => {
  63. if (!parts) return sortParts(want)
  64. const next = [...parts]
  65. let changed = false
  66. for (const part of want) {
  67. const result = Binary.search(next, part.id, (item) => item.id)
  68. if (result.found) continue
  69. next.splice(result.index, 0, part)
  70. changed = true
  71. }
  72. if (!changed) return parts
  73. return next
  74. }
  75. export function mergeOptimisticPage(page: MessagePage, items: OptimisticItem[]) {
  76. if (items.length === 0) return { ...page, confirmed: [] as string[] }
  77. const session = [...page.session]
  78. const part = new Map(page.part.map((item) => [item.id, sortParts(item.part)]))
  79. const confirmed: string[] = []
  80. for (const item of items) {
  81. const result = Binary.search(session, item.message.id, (message) => message.id)
  82. const found = result.found
  83. if (!found) session.splice(result.index, 0, item.message)
  84. const current = part.get(item.message.id)
  85. if (found && hasParts(current, item.parts)) {
  86. confirmed.push(item.message.id)
  87. continue
  88. }
  89. part.set(item.message.id, mergeParts(current, item.parts))
  90. }
  91. return {
  92. cursor: page.cursor,
  93. complete: page.complete,
  94. session,
  95. part: [...part.entries()].sort((a, b) => cmp(a[0], b[0])).map(([id, part]) => ({ id, part })),
  96. confirmed,
  97. }
  98. }
  99. export function applyOptimisticAdd(draft: OptimisticStore, input: OptimisticAddInput) {
  100. const messages = draft.message[input.sessionID]
  101. if (messages) {
  102. const result = Binary.search(messages, input.message.id, (m) => m.id)
  103. messages.splice(result.index, 0, input.message)
  104. } else {
  105. draft.message[input.sessionID] = [input.message]
  106. }
  107. draft.part[input.message.id] = sortParts(input.parts)
  108. }
  109. export function applyOptimisticRemove(draft: OptimisticStore, input: OptimisticRemoveInput) {
  110. const messages = draft.message[input.sessionID]
  111. if (messages) {
  112. const result = Binary.search(messages, input.messageID, (m) => m.id)
  113. if (result.found) messages.splice(result.index, 1)
  114. }
  115. delete draft.part[input.messageID]
  116. }
  117. function setOptimisticAdd(setStore: (...args: unknown[]) => void, input: OptimisticAddInput) {
  118. setStore("message", input.sessionID, (messages: Message[] | undefined) => {
  119. if (!messages) return [input.message]
  120. const result = Binary.search(messages, input.message.id, (m) => m.id)
  121. const next = [...messages]
  122. next.splice(result.index, 0, input.message)
  123. return next
  124. })
  125. setStore("part", input.message.id, sortParts(input.parts))
  126. }
  127. function setOptimisticRemove(setStore: (...args: unknown[]) => void, input: OptimisticRemoveInput) {
  128. setStore("message", input.sessionID, (messages: Message[] | undefined) => {
  129. if (!messages) return messages
  130. const result = Binary.search(messages, input.messageID, (m) => m.id)
  131. if (!result.found) return messages
  132. const next = [...messages]
  133. next.splice(result.index, 1)
  134. return next
  135. })
  136. setStore("part", (part: Record<string, Part[] | undefined>) => {
  137. if (!(input.messageID in part)) return part
  138. const next = { ...part }
  139. delete next[input.messageID]
  140. return next
  141. })
  142. }
  143. export const createDirSyncContext = (client: OpencodeClient, directory: string) => {
  144. const globalSync = useGlobalSync()
  145. type Child = ReturnType<(typeof globalSync)["child"]>
  146. type Setter = Child[1]
  147. const current = createMemo(() => globalSync.child(directory))
  148. const target = (directory?: string) => {
  149. if (!directory || directory === directory) return current()
  150. return globalSync.child(directory)
  151. }
  152. const absolute = (path: string) => (current()[0].path.directory + "/" + path).replace("//", "/")
  153. const initialMessagePageSize = 80
  154. const historyMessagePageSize = 200
  155. const inflight = new Map<string, Promise<void>>()
  156. const inflightDiff = new Map<string, Promise<void>>()
  157. const inflightTodo = new Map<string, Promise<void>>()
  158. const optimistic = new Map<string, Map<string, OptimisticItem>>()
  159. const maxDirs = 30
  160. const seen = new Map<string, Set<string>>()
  161. const [meta, setMeta] = createStore({
  162. limit: {} as Record<string, number>,
  163. cursor: {} as Record<string, string | undefined>,
  164. complete: {} as Record<string, boolean>,
  165. loading: {} as Record<string, boolean>,
  166. })
  167. const getSession = (sessionID: string) => {
  168. const store = current()[0]
  169. const match = Binary.search(store.session, sessionID, (s) => s.id)
  170. if (match.found) return store.session[match.index]
  171. return undefined
  172. }
  173. const setOptimistic = (directory: string, sessionID: string, item: OptimisticItem) => {
  174. const key = keyFor(directory, sessionID)
  175. const list = optimistic.get(key)
  176. if (list) {
  177. list.set(item.message.id, { message: item.message, parts: sortParts(item.parts) })
  178. return
  179. }
  180. optimistic.set(key, new Map([[item.message.id, { message: item.message, parts: sortParts(item.parts) }]]))
  181. }
  182. const clearOptimistic = (directory: string, sessionID: string, messageID?: string) => {
  183. const key = keyFor(directory, sessionID)
  184. if (!messageID) {
  185. optimistic.delete(key)
  186. return
  187. }
  188. const list = optimistic.get(key)
  189. if (!list) return
  190. list.delete(messageID)
  191. if (list.size === 0) optimistic.delete(key)
  192. }
  193. const getOptimistic = (directory: string, sessionID: string) => [
  194. ...(optimistic.get(keyFor(directory, sessionID))?.values() ?? []),
  195. ]
  196. const seenFor = (directory: string) => {
  197. const existing = seen.get(directory)
  198. if (existing) {
  199. seen.delete(directory)
  200. seen.set(directory, existing)
  201. return existing
  202. }
  203. const created = new Set<string>()
  204. seen.set(directory, created)
  205. while (seen.size > maxDirs) {
  206. const first = seen.keys().next().value
  207. if (!first) break
  208. const stale = [...(seen.get(first) ?? [])]
  209. seen.delete(first)
  210. const [, setStore] = globalSync.child(first, { bootstrap: false })
  211. evict(first, setStore, stale)
  212. }
  213. return created
  214. }
  215. const clearMeta = (directory: string, sessionIDs: string[]) => {
  216. if (sessionIDs.length === 0) return
  217. for (const sessionID of sessionIDs) {
  218. clearOptimistic(directory, sessionID)
  219. }
  220. setMeta(
  221. produce((draft) => {
  222. for (const sessionID of sessionIDs) {
  223. const key = keyFor(directory, sessionID)
  224. delete draft.limit[key]
  225. delete draft.cursor[key]
  226. delete draft.complete[key]
  227. delete draft.loading[key]
  228. }
  229. }),
  230. )
  231. }
  232. const evict = (directory: string, setStore: Setter, sessionIDs: string[]) => {
  233. if (sessionIDs.length === 0) return
  234. clearSessionPrefetch(directory, sessionIDs)
  235. for (const sessionID of sessionIDs) {
  236. globalSync.todo.set(sessionID, undefined)
  237. }
  238. setStore(
  239. produce((draft) => {
  240. dropSessionCaches(draft, sessionIDs)
  241. }),
  242. )
  243. clearMeta(directory, sessionIDs)
  244. }
  245. const touch = (directory: string, setStore: Setter, sessionID: string) => {
  246. const stale = pickSessionCacheEvictions({
  247. seen: seenFor(directory),
  248. keep: sessionID,
  249. limit: SESSION_CACHE_LIMIT,
  250. })
  251. evict(directory, setStore, stale)
  252. }
  253. const fetchMessages = async (input: { client: typeof client; sessionID: string; limit: number; before?: string }) => {
  254. const messages = await retry(() =>
  255. input.client.session.messages({ sessionID: input.sessionID, limit: input.limit, before: input.before }),
  256. )
  257. const items = (messages.data ?? []).filter((x) => !!x?.info?.id)
  258. const session = items.map((x) => clean(x.info)).sort((a, b) => cmp(a.id, b.id))
  259. const part = items.map((message) => ({ id: message.info.id, part: sortParts(message.parts) }))
  260. const cursor = messages.response.headers.get("x-next-cursor") ?? undefined
  261. return {
  262. session,
  263. part,
  264. cursor,
  265. complete: !cursor,
  266. }
  267. }
  268. const tracked = (directory: string, sessionID: string) => seen.get(directory)?.has(sessionID) ?? false
  269. const loadMessages = async (input: {
  270. directory: string
  271. client: typeof client
  272. setStore: Setter
  273. sessionID: string
  274. limit: number
  275. before?: string
  276. mode?: "replace" | "prepend"
  277. }) => {
  278. const key = keyFor(input.directory, input.sessionID)
  279. if (meta.loading[key]) return
  280. setMeta("loading", key, true)
  281. await fetchMessages(input)
  282. .then((page) => {
  283. if (!tracked(input.directory, input.sessionID)) return
  284. const next = mergeOptimisticPage(page, getOptimistic(input.directory, input.sessionID))
  285. for (const messageID of next.confirmed) {
  286. clearOptimistic(input.directory, input.sessionID, messageID)
  287. }
  288. const [store] = globalSync.child(input.directory, { bootstrap: false })
  289. const cached = input.mode === "prepend" ? (store.message[input.sessionID] ?? []) : []
  290. const message = input.mode === "prepend" ? merge(cached, next.session) : next.session
  291. batch(() => {
  292. input.setStore("message", input.sessionID, reconcile(message, { key: "id" }))
  293. for (const p of next.part) {
  294. const filtered = p.part.filter((x) => !SKIP_PARTS.has(x.type))
  295. if (filtered.length) input.setStore("part", p.id, filtered)
  296. }
  297. setMeta("limit", key, message.length)
  298. setMeta("cursor", key, next.cursor)
  299. setMeta("complete", key, next.complete)
  300. setSessionPrefetch({
  301. directory: input.directory,
  302. sessionID: input.sessionID,
  303. limit: message.length,
  304. cursor: next.cursor,
  305. complete: next.complete,
  306. })
  307. })
  308. })
  309. .finally(() => {
  310. setMeta(
  311. produce((draft) => {
  312. if (!tracked(input.directory, input.sessionID)) {
  313. delete draft.loading[key]
  314. return
  315. }
  316. draft.loading[key] = false
  317. }),
  318. )
  319. })
  320. }
  321. return {
  322. get data() {
  323. return current()[0]
  324. },
  325. get set(): Setter {
  326. return current()[1]
  327. },
  328. get status() {
  329. return current()[0].status
  330. },
  331. get ready() {
  332. return current()[0].status !== "loading"
  333. },
  334. get project() {
  335. const store = current()[0]
  336. const match = Binary.search(globalSync.data.project, store.project, (p) => p.id)
  337. if (match.found) return globalSync.data.project[match.index]
  338. return undefined
  339. },
  340. session: {
  341. get: getSession,
  342. optimistic: {
  343. add(input: { directory?: string; sessionID: string; message: Message; parts: Part[] }) {
  344. const _directory = input.directory ?? directory
  345. const [, setStore] = target(input.directory)
  346. setOptimistic(_directory, input.sessionID, { message: input.message, parts: input.parts })
  347. setOptimisticAdd(setStore as (...args: unknown[]) => void, input)
  348. },
  349. remove(input: { directory?: string; sessionID: string; messageID: string }) {
  350. const _directory = input.directory ?? directory
  351. const [, setStore] = target(input.directory)
  352. clearOptimistic(_directory, input.sessionID, input.messageID)
  353. setOptimisticRemove(setStore as (...args: unknown[]) => void, input)
  354. },
  355. },
  356. addOptimisticMessage(input: {
  357. sessionID: string
  358. messageID: string
  359. parts: Part[]
  360. agent: string
  361. model: { providerID: string; modelID: string }
  362. variant?: string
  363. }) {
  364. const message: Message = {
  365. id: input.messageID,
  366. sessionID: input.sessionID,
  367. role: "user",
  368. time: { created: Date.now() },
  369. agent: input.agent,
  370. model: { ...input.model, variant: input.variant },
  371. }
  372. const [, setStore] = target()
  373. setOptimistic(directory, input.sessionID, { message, parts: input.parts })
  374. setOptimisticAdd(setStore as (...args: unknown[]) => void, {
  375. sessionID: input.sessionID,
  376. message,
  377. parts: input.parts,
  378. })
  379. },
  380. async sync(sessionID: string, opts?: { force?: boolean }) {
  381. const [store, setStore] = globalSync.child(directory)
  382. const key = keyFor(directory, sessionID)
  383. touch(directory, setStore, sessionID)
  384. const seeded = getSessionPrefetch(directory, sessionID)
  385. if (seeded && store.message[sessionID] !== undefined && meta.limit[key] === undefined) {
  386. batch(() => {
  387. setMeta("limit", key, seeded.limit)
  388. setMeta("cursor", key, seeded.cursor)
  389. setMeta("complete", key, seeded.complete)
  390. setMeta("loading", key, false)
  391. })
  392. }
  393. return runInflight(inflight, key, async () => {
  394. const pending = getSessionPrefetchPromise(directory, sessionID)
  395. if (pending) {
  396. await pending
  397. const seeded = getSessionPrefetch(directory, sessionID)
  398. if (seeded && store.message[sessionID] !== undefined && meta.limit[key] === undefined) {
  399. batch(() => {
  400. setMeta("limit", key, seeded.limit)
  401. setMeta("cursor", key, seeded.cursor)
  402. setMeta("complete", key, seeded.complete)
  403. setMeta("loading", key, false)
  404. })
  405. }
  406. }
  407. const hasSession = Binary.search(store.session, sessionID, (s) => s.id).found
  408. const cached = store.message[sessionID] !== undefined && meta.limit[key] !== undefined
  409. if (cached && hasSession && !opts?.force) return
  410. const limit = meta.limit[key] ?? initialMessagePageSize
  411. const sessionReq =
  412. hasSession && !opts?.force
  413. ? Promise.resolve()
  414. : retry(() => client.session.get({ sessionID })).then((session) => {
  415. if (!tracked(directory, sessionID)) return
  416. const data = session.data
  417. if (!data) return
  418. setStore(
  419. "session",
  420. produce((draft) => {
  421. const match = Binary.search(draft, sessionID, (s) => s.id)
  422. if (match.found) {
  423. draft[match.index] = data
  424. return
  425. }
  426. draft.splice(match.index, 0, data)
  427. }),
  428. )
  429. })
  430. const messagesReq =
  431. cached && !opts?.force
  432. ? Promise.resolve()
  433. : loadMessages({
  434. directory,
  435. client,
  436. setStore,
  437. sessionID,
  438. limit,
  439. })
  440. await Promise.all([sessionReq, messagesReq])
  441. })
  442. },
  443. async diff(sessionID: string, opts?: { force?: boolean }) {
  444. const [store, setStore] = globalSync.child(directory)
  445. touch(directory, setStore, sessionID)
  446. if (store.session_diff[sessionID] !== undefined && !opts?.force) return
  447. const key = keyFor(directory, sessionID)
  448. return runInflight(inflightDiff, key, () =>
  449. retry(() => client.session.diff({ sessionID })).then((diff) => {
  450. if (!tracked(directory, sessionID)) return
  451. setStore("session_diff", sessionID, reconcile(list(diff.data), { key: "file" }))
  452. }),
  453. )
  454. },
  455. async todo(sessionID: string, opts?: { force?: boolean }) {
  456. const [store, setStore] = globalSync.child(directory)
  457. touch(directory, setStore, sessionID)
  458. const existing = store.todo[sessionID]
  459. const cached = globalSync.data.session_todo[sessionID]
  460. if (existing !== undefined) {
  461. if (cached === undefined) {
  462. globalSync.todo.set(sessionID, existing)
  463. }
  464. if (!opts?.force) return
  465. }
  466. if (cached !== undefined) {
  467. setStore("todo", sessionID, reconcile(cached, { key: "id" }))
  468. }
  469. const key = keyFor(directory, sessionID)
  470. return runInflight(inflightTodo, key, () =>
  471. retry(() => client.session.todo({ sessionID })).then((todo) => {
  472. if (!tracked(directory, sessionID)) return
  473. const list = todo.data ?? []
  474. setStore("todo", sessionID, reconcile(list, { key: "id" }))
  475. globalSync.todo.set(sessionID, list)
  476. }),
  477. )
  478. },
  479. history: {
  480. more(sessionID: string) {
  481. const store = current()[0]
  482. const key = keyFor(directory, sessionID)
  483. if (store.message[sessionID] === undefined) return false
  484. if (meta.limit[key] === undefined) return false
  485. if (meta.complete[key]) return false
  486. return !!meta.cursor[key]
  487. },
  488. loading(sessionID: string) {
  489. const key = keyFor(directory, sessionID)
  490. return meta.loading[key] ?? false
  491. },
  492. async loadMore(sessionID: string, count?: number) {
  493. const [, setStore] = globalSync.child(directory)
  494. touch(directory, setStore, sessionID)
  495. const key = keyFor(directory, sessionID)
  496. const step = count ?? historyMessagePageSize
  497. if (meta.loading[key]) return
  498. if (meta.complete[key]) return
  499. const before = meta.cursor[key]
  500. if (!before) return
  501. await loadMessages({
  502. directory,
  503. client,
  504. setStore,
  505. sessionID,
  506. limit: step,
  507. before,
  508. mode: "prepend",
  509. })
  510. },
  511. },
  512. evict(sessionID: string, _directory = directory) {
  513. const [, setStore] = globalSync.child(_directory)
  514. seenFor(_directory).delete(sessionID)
  515. evict(_directory, setStore, [sessionID])
  516. },
  517. fetch: async (count = 10) => {
  518. const [store, setStore] = globalSync.child(directory)
  519. setStore("limit", (x) => x + count)
  520. await client.session.list().then((x) => {
  521. const sessions = (x.data ?? [])
  522. .filter((s) => !!s?.id)
  523. .sort((a, b) => cmp(a.id, b.id))
  524. .slice(0, store.limit)
  525. setStore("session", reconcile(sessions, { key: "id" }))
  526. })
  527. },
  528. more: createMemo(() => current()[0].session.length >= current()[0].limit),
  529. archive: async (sessionID: string) => {
  530. const [, setStore] = globalSync.child(directory)
  531. await client.session.update({ sessionID, time: { archived: Date.now() } })
  532. setStore(
  533. produce((draft) => {
  534. const match = Binary.search(draft.session, sessionID, (s) => s.id)
  535. if (match.found) draft.session.splice(match.index, 1)
  536. }),
  537. )
  538. },
  539. },
  540. absolute,
  541. get directory() {
  542. return current()[0].path.directory
  543. },
  544. }
  545. }