models.test.ts 9.5 KB

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