server-sync.test.ts 7.0 KB

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