models.test.ts 8.2 KB

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