models.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import { describe, expect, beforeAll, beforeEach, afterAll } from "bun:test"
  2. import { Effect, Layer, Ref } from "effect"
  3. import { HttpClient, HttpClientResponse } from "effect/unstable/http"
  4. import { FSUtil } from "@opencode-ai/core/fs-util"
  5. import { Flag } from "@opencode-ai/core/flag/flag"
  6. import { Global } from "@opencode-ai/core/global"
  7. import { ModelsDev } from "@opencode-ai/core/models-dev"
  8. import { EventV2 } from "@opencode-ai/core/event"
  9. import { it } from "./lib/effect"
  10. import { rm, writeFile, utimes, mkdir } from "fs/promises"
  11. import path from "path"
  12. // test/preload.ts pins OPENCODE_MODELS_PATH to a fixture so other tests can
  13. // resolve providers without network. These tests need to drive the on-disk
  14. // cache themselves and silence the eager refresh fork. Save/restore around
  15. // the suite — never leak the mutation to subsequent test files in the same
  16. // bun process.
  17. const ORIGINAL_MODELS_PATH = Flag.OPENCODE_MODELS_PATH
  18. const ORIGINAL_DISABLE_FETCH = Flag.OPENCODE_DISABLE_MODELS_FETCH
  19. beforeAll(() => {
  20. Flag.OPENCODE_MODELS_PATH = undefined
  21. Flag.OPENCODE_DISABLE_MODELS_FETCH = true
  22. })
  23. afterAll(() => {
  24. Flag.OPENCODE_MODELS_PATH = ORIGINAL_MODELS_PATH
  25. Flag.OPENCODE_DISABLE_MODELS_FETCH = ORIGINAL_DISABLE_FETCH
  26. })
  27. const cacheFile = path.join(Global.Path.cache, "models.json")
  28. const fixture: Record<string, ModelsDev.Provider> = {
  29. acme: {
  30. id: "acme",
  31. name: "Acme",
  32. env: ["ACME_API_KEY"],
  33. models: {
  34. "acme-1": {
  35. id: "acme-1",
  36. name: "Acme One",
  37. release_date: "2026-01-01",
  38. attachment: false,
  39. reasoning: false,
  40. temperature: true,
  41. tool_call: true,
  42. limit: { context: 128000, output: 8192 },
  43. },
  44. },
  45. },
  46. }
  47. const fixture2: Record<string, ModelsDev.Provider> = {
  48. beta: {
  49. id: "beta",
  50. name: "Beta",
  51. env: ["BETA_API_KEY"],
  52. models: {
  53. "beta-1": {
  54. id: "beta-1",
  55. name: "Beta One",
  56. release_date: "2026-02-01",
  57. attachment: false,
  58. reasoning: true,
  59. temperature: false,
  60. tool_call: false,
  61. limit: { context: 64000, output: 4096 },
  62. },
  63. },
  64. },
  65. }
  66. interface MockState {
  67. body: string
  68. status: number
  69. calls: Array<{ url: string; userAgent: string | null }>
  70. }
  71. const makeMockClient = (state: Ref.Ref<MockState>) =>
  72. HttpClient.make((request) =>
  73. Effect.gen(function* () {
  74. yield* Ref.update(state, (s) => ({
  75. ...s,
  76. calls: [...s.calls, { url: request.url, userAgent: request.headers["user-agent"] ?? null }],
  77. }))
  78. const s = yield* Ref.get(state)
  79. return HttpClientResponse.fromWeb(request, new Response(s.body, { status: s.status }))
  80. }),
  81. )
  82. const buildLayer = (state: Ref.Ref<MockState>) =>
  83. // Layer.fresh is required: ModelsDev.layer is a module-level Layer constant,
  84. // and Effect.provide uses a process-global MemoMap by default — without fresh,
  85. // every test would reuse the cachedInvalidateWithTTL state from the first run.
  86. Layer.fresh(ModelsDev.layer).pipe(
  87. Layer.provide(Layer.succeed(HttpClient.HttpClient, makeMockClient(state))),
  88. Layer.provide(FSUtil.defaultLayer),
  89. Layer.provide(EventV2.defaultLayer),
  90. )
  91. const writeCache = (data: object, mtimeMs?: number) =>
  92. Effect.promise(async () => {
  93. await mkdir(Global.Path.cache, { recursive: true })
  94. await writeFile(cacheFile, JSON.stringify(data))
  95. if (mtimeMs !== undefined) {
  96. const t = mtimeMs / 1000
  97. await utimes(cacheFile, t, t)
  98. }
  99. })
  100. const provided = <A, E>(state: Ref.Ref<MockState>, eff: Effect.Effect<A, E, ModelsDev.Service>) =>
  101. eff.pipe(Effect.provide(buildLayer(state)))
  102. beforeEach(async () => {
  103. await rm(cacheFile, { force: true })
  104. })
  105. afterAll(async () => {
  106. await rm(cacheFile, { force: true })
  107. })
  108. const initialState: MockState = {
  109. body: JSON.stringify(fixture),
  110. status: 200,
  111. calls: [],
  112. }
  113. describe("ModelsDev Service", () => {
  114. it.live("get() returns providers from disk when cache file exists", () =>
  115. Effect.gen(function* () {
  116. yield* writeCache(fixture)
  117. const state = yield* Ref.make(initialState)
  118. const result = yield* provided(
  119. state,
  120. ModelsDev.Service.use((s) => s.get()),
  121. )
  122. expect(result).toEqual(fixture)
  123. const final = yield* Ref.get(state)
  124. expect(final.calls).toEqual([])
  125. }),
  126. )
  127. it.live("get() returns empty catalog when disk empty, fetch disabled, and no bundled snapshot is injected", () =>
  128. Effect.gen(function* () {
  129. const state = yield* Ref.make(initialState)
  130. const result = yield* provided(
  131. state,
  132. ModelsDev.Service.use((s) => s.get()),
  133. )
  134. expect(result).toEqual({})
  135. const final = yield* Ref.get(state)
  136. expect(final.calls).toEqual([])
  137. }),
  138. )
  139. it.live("get() is single-flight under concurrent calls", () =>
  140. Effect.gen(function* () {
  141. yield* writeCache(fixture)
  142. const state = yield* Ref.make(initialState)
  143. const results = yield* provided(
  144. state,
  145. Effect.gen(function* () {
  146. const svc = yield* ModelsDev.Service
  147. return yield* Effect.all([svc.get(), svc.get(), svc.get(), svc.get(), svc.get()], {
  148. concurrency: "unbounded",
  149. })
  150. }),
  151. )
  152. for (const result of results) expect(result).toEqual(fixture)
  153. }),
  154. )
  155. it.live("get() caches across calls (later disk writes are ignored until invalidate)", () =>
  156. Effect.gen(function* () {
  157. yield* writeCache(fixture)
  158. const state = yield* Ref.make(initialState)
  159. const first = yield* provided(
  160. state,
  161. Effect.gen(function* () {
  162. const svc = yield* ModelsDev.Service
  163. const a = yield* svc.get()
  164. // mutate disk between calls — cache should mask the change
  165. yield* writeCache(fixture2)
  166. const b = yield* svc.get()
  167. return { a, b }
  168. }),
  169. )
  170. expect(first.a).toEqual(fixture)
  171. expect(first.b).toEqual(fixture)
  172. }),
  173. )
  174. it.live("refresh(true) fetches via HttpClient and updates the cache", () =>
  175. Effect.gen(function* () {
  176. yield* writeCache(fixture)
  177. const state = yield* Ref.make({ ...initialState, body: JSON.stringify(fixture2) })
  178. const result = yield* provided(
  179. state,
  180. Effect.gen(function* () {
  181. const svc = yield* ModelsDev.Service
  182. const before = yield* svc.get()
  183. yield* svc.refresh(true)
  184. const after = yield* svc.get()
  185. return { before, after }
  186. }),
  187. )
  188. expect(result.before).toEqual(fixture)
  189. expect(result.after).toEqual(fixture2)
  190. const final = yield* Ref.get(state)
  191. expect(final.calls.length).toBe(1)
  192. expect(final.calls[0].url).toContain("/api.json")
  193. expect(final.calls[0].userAgent).toContain("/cli")
  194. }),
  195. )
  196. it.live("refresh(false) skips fetch when on-disk file is fresh", () =>
  197. Effect.gen(function* () {
  198. // Fresh: mtime within the 5-minute TTL.
  199. yield* writeCache(fixture, Date.now() - 1000)
  200. const state = yield* Ref.make({ ...initialState, body: JSON.stringify(fixture2) })
  201. yield* provided(
  202. state,
  203. ModelsDev.Service.use((s) => s.refresh(false)),
  204. )
  205. const final = yield* Ref.get(state)
  206. expect(final.calls).toEqual([])
  207. }),
  208. )
  209. it.live("refresh(false) fetches when on-disk file is stale", () =>
  210. Effect.gen(function* () {
  211. // Stale: mtime 10 minutes ago, beyond the 5-minute TTL.
  212. yield* writeCache(fixture, Date.now() - 10 * 60 * 1000)
  213. const state = yield* Ref.make({ ...initialState, body: JSON.stringify(fixture2) })
  214. const after = yield* provided(
  215. state,
  216. Effect.gen(function* () {
  217. const svc = yield* ModelsDev.Service
  218. yield* svc.refresh(false)
  219. return yield* svc.get()
  220. }),
  221. )
  222. const final = yield* Ref.get(state)
  223. expect(final.calls.length).toBe(1)
  224. expect(after).toEqual(fixture2)
  225. }),
  226. )
  227. it.live("refresh swallows HTTP errors and leaves cache intact", () =>
  228. Effect.gen(function* () {
  229. yield* writeCache(fixture)
  230. const state = yield* Ref.make({ ...initialState, status: 500, body: "boom" })
  231. const result = yield* provided(
  232. state,
  233. Effect.gen(function* () {
  234. const svc = yield* ModelsDev.Service
  235. yield* svc.refresh(true)
  236. return yield* svc.get()
  237. }),
  238. )
  239. expect(result).toEqual(fixture)
  240. // retryTransient retries 5xx, so calls may be > 1.
  241. const final = yield* Ref.get(state)
  242. expect(final.calls.length).toBeGreaterThanOrEqual(1)
  243. }),
  244. )
  245. })