server-sync.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import { describe, expect, test } from "bun:test"
  2. import type { OpencodeClient } from "@opencode-ai/sdk/v2/client"
  3. import type {
  4. McpListInput,
  5. McpResourceCatalogInput,
  6. SessionApi,
  7. SessionInfo,
  8. SessionListInput,
  9. } from "@opencode-ai/client/promise"
  10. import { QueryClient } from "@tanstack/solid-query"
  11. import { canDisposeDirectory, pickDirectoriesToEvict } from "./global-sync/eviction"
  12. import { estimateRootSessionTotal, loadRootSessions } from "./global-sync/session-load"
  13. import { loadActiveSessionsQuery, loadMcpQuery, loadMcpResourcesQuery, seedActiveSessionStatuses } from "./server-sync"
  14. import { ServerScope } from "@/utils/server-scope"
  15. import { createServerSession } from "./server-session"
  16. import type { ServerApi } from "@/utils/server"
  17. type McpApi = ServerApi["mcp"]
  18. describe("MCP queries", () => {
  19. test("loads current servers for the requested location", async () => {
  20. const calls: unknown[] = []
  21. const queryClient = new QueryClient()
  22. const result = await queryClient.fetchQuery(
  23. loadMcpQuery(ServerScope.local, "/project", {
  24. list: async (input: McpListInput = {}) => {
  25. calls.push(input)
  26. return {
  27. location: { directory: "/project", project: { id: "project", directory: "/project" } },
  28. data: [
  29. { name: "docs", status: { status: "connected" } },
  30. { name: "search", status: { status: "pending" } },
  31. ],
  32. }
  33. },
  34. } as unknown as McpApi),
  35. )
  36. expect(calls).toEqual([{ location: { directory: "/project" } }])
  37. expect(result).toEqual({ docs: { status: "connected" }, search: { status: "pending" } })
  38. })
  39. test("loads and keys the current resource catalog", async () => {
  40. const calls: unknown[] = []
  41. const queryClient = new QueryClient()
  42. const result = await queryClient.fetchQuery(
  43. loadMcpResourcesQuery(ServerScope.local, "/project", {
  44. resource: {
  45. catalog: async (input: McpResourceCatalogInput = {}) => {
  46. calls.push(input)
  47. return {
  48. location: { directory: "/project", project: { id: "project", directory: "/project" } },
  49. data: {
  50. resources: [{ server: "docs", name: "Guide", uri: "docs://guide" }],
  51. templates: [],
  52. },
  53. }
  54. },
  55. },
  56. } as unknown as McpApi),
  57. )
  58. expect(calls).toEqual([{ location: { directory: "/project" } }])
  59. expect(result).toEqual({ "docs:docs://guide": { server: "docs", name: "Guide", uri: "docs://guide" } })
  60. })
  61. })
  62. describe("active session query", () => {
  63. test("loads active sessions immediately and once per server cache", async () => {
  64. let calls = 0
  65. const queryClient = new QueryClient()
  66. const options = loadActiveSessionsQuery(ServerScope.local, {
  67. active: async () => {
  68. calls++
  69. return { ses_running: { type: "running" } }
  70. },
  71. })
  72. expect(await queryClient.fetchQuery(options)).toEqual({ ses_running: { type: "running" } })
  73. expect(await queryClient.fetchQuery(options)).toEqual({ ses_running: { type: "running" } })
  74. expect(calls).toBe(1)
  75. expect(options.enabled).toBe(true)
  76. expect([...options.queryKey]).toEqual([ServerScope.local, "activeSessions"])
  77. })
  78. test("does not overwrite statuses already written by events", () => {
  79. const session = createServerSession({} as OpencodeClient)
  80. session.set("session_status", "ses_retry", { type: "retry", attempt: 2, message: "retrying", next: 10 })
  81. seedActiveSessionStatuses(session, {
  82. ses_running: { type: "running" },
  83. ses_retry: { type: "running" },
  84. })
  85. expect(session.data.session_status.ses_running).toEqual({ type: "busy" })
  86. expect(session.data.session_status.ses_retry).toEqual({
  87. type: "retry",
  88. attempt: 2,
  89. message: "retrying",
  90. next: 10,
  91. })
  92. })
  93. })
  94. describe("pickDirectoriesToEvict", () => {
  95. test("keeps pinned stores and evicts idle stores", () => {
  96. const now = 5_000
  97. const picks = pickDirectoriesToEvict({
  98. stores: ["a", "b", "c", "d"],
  99. state: new Map([
  100. ["a", { lastAccessAt: 1_000 }],
  101. ["b", { lastAccessAt: 4_900 }],
  102. ["c", { lastAccessAt: 4_800 }],
  103. ["d", { lastAccessAt: 3_000 }],
  104. ]),
  105. pins: new Set(["a"]),
  106. max: 2,
  107. ttl: 1_500,
  108. now,
  109. })
  110. expect(picks).toEqual(["d", "c"])
  111. })
  112. })
  113. describe("loadRootSessions", () => {
  114. test("loads and normalizes a limited page of root sessions", async () => {
  115. const calls: SessionListInput[] = []
  116. const result = await loadRootSessions({
  117. api: {
  118. list: async (query = {}) => {
  119. calls.push(query)
  120. return { data: [sessionInfo("session-1")], cursor: {} }
  121. },
  122. } satisfies Pick<SessionApi, "list">,
  123. directory: "dir",
  124. limit: 10,
  125. })
  126. expect(result.data).toEqual([
  127. expect.objectContaining({ id: "session-1", directory: "dir", slug: "session-1", version: "" }),
  128. ])
  129. expect(result.limited).toBe(true)
  130. expect(calls).toEqual([{ directory: "dir", parentID: null, limit: 10, order: "desc" }])
  131. })
  132. test("propagates list failures", () => {
  133. expect(
  134. loadRootSessions({
  135. api: {
  136. list: async () => {
  137. throw new Error("failed")
  138. },
  139. } satisfies Pick<SessionApi, "list">,
  140. directory: "dir",
  141. limit: 25,
  142. }),
  143. ).rejects.toThrow("failed")
  144. })
  145. })
  146. function sessionInfo(id: string) {
  147. return {
  148. id,
  149. projectID: "project-1",
  150. agent: "build",
  151. model: { id: "model-1", providerID: "provider-1" },
  152. cost: 0,
  153. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  154. time: { created: 1, updated: 1 },
  155. title: id,
  156. location: { directory: "dir" },
  157. } as SessionInfo
  158. }
  159. describe("estimateRootSessionTotal", () => {
  160. test("keeps exact total for full fetches", () => {
  161. expect(estimateRootSessionTotal({ count: 42, limit: 10, limited: false })).toBe(42)
  162. })
  163. test("marks has-more for full-limit limited fetches", () => {
  164. expect(estimateRootSessionTotal({ count: 10, limit: 10, limited: true })).toBe(11)
  165. })
  166. test("keeps exact total when limited fetch is under limit", () => {
  167. expect(estimateRootSessionTotal({ count: 9, limit: 10, limited: true })).toBe(9)
  168. })
  169. })
  170. describe("canDisposeDirectory", () => {
  171. test("rejects pinned or inflight directories", () => {
  172. expect(
  173. canDisposeDirectory({
  174. directory: "dir",
  175. hasStore: true,
  176. pinned: true,
  177. booting: false,
  178. loadingSessions: false,
  179. }),
  180. ).toBe(false)
  181. expect(
  182. canDisposeDirectory({
  183. directory: "dir",
  184. hasStore: true,
  185. pinned: false,
  186. booting: true,
  187. loadingSessions: false,
  188. }),
  189. ).toBe(false)
  190. expect(
  191. canDisposeDirectory({
  192. directory: "dir",
  193. hasStore: true,
  194. pinned: false,
  195. booting: false,
  196. loadingSessions: true,
  197. }),
  198. ).toBe(false)
  199. })
  200. test("accepts idle unpinned directory store", () => {
  201. expect(
  202. canDisposeDirectory({
  203. directory: "dir",
  204. hasStore: true,
  205. pinned: false,
  206. booting: false,
  207. loadingSessions: false,
  208. }),
  209. ).toBe(true)
  210. })
  211. })