From 09b8f9c671e091078b996f18b4d293d81e912319 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 14:30:03 +0800 Subject: [PATCH 1/5] fix: models loader no longer fails every request when models.dev is unreachable - The release build defines `OPENCODE_MODELS_DEV`, so core's loader has its bundled snapshot. - A failed first fetch, or a body that isn't JSON, serves an empty catalogue until a refresh succeeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvsr1G2qqFbMCyPZg3G --- packages/core/src/models-dev.ts | 19 +++++++++- packages/core/test/models.test.ts | 61 +++++++++++++++++++++++++++++++ packages/opencode/script/build.ts | 4 ++ 3 files changed, 82 insertions(+), 2 deletions(-) diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index 3f9f670374..979cab22d0 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -203,13 +203,28 @@ export const layer = Layer.effect( if (snapshot) return snapshot if (Flag.OPENCODE_DISABLE_MODELS_FETCH) return {} // Flock is cross-process: concurrent opencode CLIs can race on this cache file. - const text = yield* Effect.scoped( + // altimate_change start — a failed first load serves an empty catalogue instead of dying + // Plugin boot waits on this load, and agent state and every prompt wait on plugin boot, so + // dying here failed all of them on a machine with no cache that could not reach models.dev. + // The empty catalogue lasts until a refresh succeeds: `refresh` invalidates it and publishes + // `Refreshed`, and the models-dev plugin reloads. + const loaded = yield* Effect.scoped( Effect.gen(function* () { yield* Flock.effect(lockKey) return yield* fetchAndWrite() }), + ).pipe( + Effect.flatMap((text) => + Effect.try({ try: () => JSON.parse(text) as Record, catch: (error) => error }), + ), + Effect.catch((error) => + Effect.logError("Failed to load models.dev; serving an empty catalogue until a refresh succeeds", { + error, + }).pipe(Effect.as(undefined)), + ), ) - return JSON.parse(text) as Record + return loaded ?? {} + // altimate_change end }).pipe(Effect.withSpan("ModelsDev.populate"), Effect.orDie) const [cachedGet, invalidate] = yield* Effect.cachedInvalidateWithTTL(populate, Duration.infinity) diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index 31a3e57c10..4451853472 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -178,6 +178,67 @@ describe("ModelsDev Service", () => { }), ) + // No cache and no bundled snapshot (tests never define one), so the first get() has to fetch. + const withFetch = (eff: Effect.Effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + Flag.OPENCODE_DISABLE_MODELS_FETCH = false + }), + () => eff, + () => + Effect.sync(() => { + Flag.OPENCODE_DISABLE_MODELS_FETCH = true + }), + ) + + it.live("get() serves an empty catalogue when the first fetch fails", () => + Effect.gen(function* () { + const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" }) + const result = yield* withFetch( + provided( + state, + ModelsDev.Service.use((s) => s.get()), + ), + ) + expect(result).toEqual({}) + expect((yield* Ref.get(state)).calls.length).toBeGreaterThanOrEqual(1) + }), + ) + + it.live("get() serves an empty catalogue when models.dev answers with a body that is not JSON", () => + Effect.gen(function* () { + const state = yield* Ref.make({ ...initialState, body: "sign in to this network" }) + const result = yield* withFetch( + provided( + state, + ModelsDev.Service.use((s) => s.get()), + ), + ) + expect(result).toEqual({}) + }), + ) + + it.live("a refresh that succeeds replaces the empty catalogue served after a failed fetch", () => + Effect.gen(function* () { + const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" }) + const result = yield* withFetch( + provided( + state, + Effect.gen(function* () { + const svc = yield* ModelsDev.Service + const before = yield* svc.get() + yield* Ref.update(state, (s) => ({ ...s, status: 200, body: JSON.stringify(fixture) })) + yield* svc.refresh(true) + const after = yield* svc.get() + return { before, after } + }), + ), + ) + expect(result.before).toEqual({}) + expect(result.after).toEqual(fixture) + }), + ) + it.live("get() is single-flight under concurrent calls", () => Effect.gen(function* () { yield* writeCache(fixture) diff --git a/packages/opencode/script/build.ts b/packages/opencode/script/build.ts index e591f77314..509d565a64 100755 --- a/packages/opencode/script/build.ts +++ b/packages/opencode/script/build.ts @@ -656,6 +656,10 @@ for (const item of targets) { OPENCODE_MIGRATIONS: JSON.stringify(migrations), OPENCODE_BUILTIN_SKILLS: JSON.stringify(builtinSkills), OPENCODE_CHANGELOG: JSON.stringify(changelog), + // altimate_change start — the bundled snapshot for core's models loader (packages/core/src/models-dev.ts) + // Without it a release binary with no models cache has to fetch models.dev before it can serve a request. + OPENCODE_MODELS_DEV: modelsData, + // altimate_change end OPENCODE_WORKER_PATH: workerPath, OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath, }, From bea4d6b25bfd420cfb70a10dc4df2b7753cd0811 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 14:54:50 +0800 Subject: [PATCH 2/5] fix: core's models loader reuses the catalogue the build already ships Drops the build define, which embedded a second copy per bundle (+17.7MB). The entry points hand core the fork's snapshot module through `ModelsDev.provideSnapshot`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvsr1G2qqFbMCyPZg3G --- packages/core/src/models-dev.ts | 19 +++++++-- packages/core/test/models.test.ts | 39 +++++++++++++++++++ packages/opencode/script/build.ts | 4 -- .../src/altimate/models-snapshot-host.ts | 13 +++++++ packages/opencode/src/cli/tui/worker.ts | 3 ++ packages/opencode/src/index.ts | 3 ++ .../altimate/models-snapshot-host.test.ts | 37 ++++++++++++++++++ 7 files changed, 111 insertions(+), 7 deletions(-) create mode 100644 packages/opencode/src/altimate/models-snapshot-host.ts create mode 100644 packages/opencode/test/altimate/models-snapshot-host.test.ts diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index 979cab22d0..5b5e16edc1 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -117,6 +117,16 @@ export const Event = { declare const OPENCODE_MODELS_DEV: Record | undefined +// altimate_change start — a bundled catalogue the host process hands over at runtime +// A build that already ships the catalogue in its own module passes a loader for it here rather than defining +// OPENCODE_MODELS_DEV, which would embed a second copy of it in every bundle of the binary. +type SnapshotLoader = () => Promise | undefined> +let hostSnapshot: SnapshotLoader | undefined +export function provideSnapshot(load: SnapshotLoader | undefined) { + hostSnapshot = load +} +// altimate_change end + export interface Interface { readonly get: () => Effect.Effect> readonly refresh: (force?: boolean) => Effect.Effect @@ -177,9 +187,12 @@ export const layer = Layer.effect( Effect.map((v) => v as Record | undefined), ) - const loadSnapshot = Effect.sync(() => - typeof OPENCODE_MODELS_DEV === "undefined" ? undefined : OPENCODE_MODELS_DEV, - ) + // altimate_change start — with no build-time snapshot, the host's (provideSnapshot) + const loadSnapshot = Effect.promise(async () => { + if (typeof OPENCODE_MODELS_DEV !== "undefined") return OPENCODE_MODELS_DEV + return hostSnapshot ? await hostSnapshot().catch(() => undefined) : undefined + }) + // altimate_change end const fetchAndWrite = Effect.fn("ModelsDev.fetchAndWrite")(function* () { const text = yield* fetchApi() diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index 4451853472..ba844af102 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -239,6 +239,45 @@ describe("ModelsDev Service", () => { }), ) + const withHostSnapshot = (load: Parameters[0], eff: Effect.Effect) => + Effect.acquireUseRelease( + Effect.sync(() => ModelsDev.provideSnapshot(load)), + () => eff, + () => Effect.sync(() => ModelsDev.provideSnapshot(undefined)), + ) + + it.live("with no cache, get() serves the host's catalogue (provideSnapshot) without waiting on a fetch", () => + Effect.gen(function* () { + const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" }) + const result = yield* withHostSnapshot( + async () => fixture2, + withFetch( + provided( + state, + ModelsDev.Service.use((s) => s.get()), + ), + ), + ) + expect(result).toEqual(fixture2) + }), + ) + + it.live("a host catalogue that fails to load counts as none: get() fetches", () => + Effect.gen(function* () { + const state = yield* Ref.make(initialState) + const result = yield* withHostSnapshot( + () => Promise.reject(new Error("no snapshot module")), + withFetch( + provided( + state, + ModelsDev.Service.use((s) => s.get()), + ), + ), + ) + expect(result).toEqual(fixture) + }), + ) + it.live("get() is single-flight under concurrent calls", () => Effect.gen(function* () { yield* writeCache(fixture) diff --git a/packages/opencode/script/build.ts b/packages/opencode/script/build.ts index 509d565a64..e591f77314 100755 --- a/packages/opencode/script/build.ts +++ b/packages/opencode/script/build.ts @@ -656,10 +656,6 @@ for (const item of targets) { OPENCODE_MIGRATIONS: JSON.stringify(migrations), OPENCODE_BUILTIN_SKILLS: JSON.stringify(builtinSkills), OPENCODE_CHANGELOG: JSON.stringify(changelog), - // altimate_change start — the bundled snapshot for core's models loader (packages/core/src/models-dev.ts) - // Without it a release binary with no models cache has to fetch models.dev before it can serve a request. - OPENCODE_MODELS_DEV: modelsData, - // altimate_change end OPENCODE_WORKER_PATH: workerPath, OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath, }, diff --git a/packages/opencode/src/altimate/models-snapshot-host.ts b/packages/opencode/src/altimate/models-snapshot-host.ts new file mode 100644 index 0000000000..656539911e --- /dev/null +++ b/packages/opencode/src/altimate/models-snapshot-host.ts @@ -0,0 +1,13 @@ +// altimate_change - new file +// +// Hands core's models loader (packages/core/src/models-dev.ts) the catalogue this build already ships for the +// fork's loader (src/provider/models-snapshot.ts, regenerated by script/build.ts). Without it, core has no +// bundled catalogue, and a machine with no models cache that can't reach models.dev fails every request. +// Reusing the module keeps one copy of the catalogue per bundle; a build-time define would add another. +// Imported first by each entry point that runs the server (src/index.ts, src/cli/tui/worker.ts). +import { ModelsDev } from "@opencode-ai/core/models-dev" + +ModelsDev.provideSnapshot(() => + // @ts-ignore — the generated module's literal type is too large to check; the fork's loader imports it the same way + import("../provider/models-snapshot.js").then((m) => m.snapshot as unknown as Record), +) diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index f0d8daa516..a1371efa38 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -4,6 +4,9 @@ // rationale (this is the systemic fix for the log-flood class that regresses on every upstream merge). import "./worker-console-guard" // altimate_change end +// altimate_change start — core's models loader reads the catalogue this build already ships +import "@/altimate/models-snapshot-host" +// altimate_change end import { Server } from "@/server/server" import { InstanceRuntime } from "@/project/instance-runtime" import { Rpc } from "@/util/rpc" diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index f2a0152b03..c31c4e4573 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -3,6 +3,9 @@ import { hideBin } from "yargs/helpers" // altimate_change start - stdin tool arguments import { foldStdinArgs } from "./altimate/tool-cli/argv" // altimate_change end +// altimate_change start — core's models loader reads the catalogue this build already ships +import "./altimate/models-snapshot-host" +// altimate_change end import { RunCommand } from "./cli/cmd/run" import { GenerateCommand } from "./cli/cmd/generate" import { ConsoleCommand } from "./cli/cmd/account" diff --git a/packages/opencode/test/altimate/models-snapshot-host.test.ts b/packages/opencode/test/altimate/models-snapshot-host.test.ts new file mode 100644 index 0000000000..3306c111d9 --- /dev/null +++ b/packages/opencode/test/altimate/models-snapshot-host.test.ts @@ -0,0 +1,37 @@ +// altimate_change - new file +// +// The entry points import `models-snapshot-host` so core's models loader serves the catalogue the fork already +// ships (src/provider/models-snapshot.ts). This checks the wiring: with no cache and no fetch, core's `get()` +// returns that module's catalogue. +import { afterAll, beforeAll, expect, test } from "bun:test" +import { rm } from "fs/promises" +import path from "path" +import { Effect, Layer } from "effect" +import { Flag } from "@opencode-ai/core/flag/flag" +import { Global } from "@opencode-ai/core/global" +import { ModelsDev } from "@opencode-ai/core/models-dev" + +const ORIGINAL_MODELS_PATH = Flag.OPENCODE_MODELS_PATH +const ORIGINAL_DISABLE_FETCH = Flag.OPENCODE_DISABLE_MODELS_FETCH +beforeAll(async () => { + // preload.ts points the loader at a fixture file; this test needs the path where no cache exists. + Flag.OPENCODE_MODELS_PATH = undefined + Flag.OPENCODE_DISABLE_MODELS_FETCH = true + await rm(path.join(Global.Path.cache, "models.json"), { force: true }) +}) +afterAll(() => { + Flag.OPENCODE_MODELS_PATH = ORIGINAL_MODELS_PATH + Flag.OPENCODE_DISABLE_MODELS_FETCH = ORIGINAL_DISABLE_FETCH + ModelsDev.provideSnapshot(undefined) +}) + +test("with no models cache, core's loader serves the catalogue the build ships", async () => { + await import("../../src/altimate/models-snapshot-host") + // @ts-ignore — the generated module's literal type is too large to check + const { snapshot } = await import("../../src/provider/models-snapshot.js") + const catalogue = await Effect.runPromise( + ModelsDev.Service.use((s) => s.get()).pipe(Effect.provide(Layer.fresh(ModelsDev.defaultLayer))), + ) + expect(Object.keys(catalogue).length).toBeGreaterThan(50) + expect(Object.keys(catalogue).sort()).toEqual(Object.keys(snapshot).sort()) +}) From 9260ef92ddd8607e0fb3ea0498b018a336993d69 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 18:19:31 +0800 Subject: [PATCH 3/5] fix: models loader serves and caches only catalogues - A body or cache file that is JSON but not a catalogue is dropped; malformed entries are left out. - A fetched catalogue is served even if the cache write fails; a throwing snapshot loader counts as none. - Tests build the layer before enabling fetch; the entry-point imports are checked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvsr1G2qqFbMCyPZg3G --- packages/core/src/models-dev.ts | 59 +++++- packages/core/test/models.test.ts | 181 +++++++++++------- .../altimate/models-snapshot-host.test.ts | 34 +++- 3 files changed, 184 insertions(+), 90 deletions(-) diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index 5b5e16edc1..eb2b427ffb 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -127,6 +127,21 @@ export function provideSnapshot(load: SnapshotLoader | undefined) { } // altimate_change end +// altimate_change start — only a catalogue is served or cached +// A proxy or captive portal can answer 200 with JSON that isn't one (`{"error": ...}`). Served, or read back +// from the cache on every start, it failed plugin boot, which reads `id`, `env` and `models` on each provider. +// The provider entries shaped that way, or undefined when there are none (the fork's loader keeps the same rule). +function catalogOf(value: unknown): Record | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined + const entries = Object.entries(value).filter(([, entry]) => { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false + const { id, env, models } = entry as Record + return typeof id === "string" && Array.isArray(env) && !!models && typeof models === "object" && !Array.isArray(models) + }) + return entries.length > 0 ? (Object.fromEntries(entries) as Record) : undefined +} +// altimate_change end + export interface Interface { readonly get: () => Effect.Effect> readonly refresh: (force?: boolean) => Effect.Effect @@ -184,18 +199,39 @@ export const layer = Layer.effect( } return Effect.succeed(undefined) }), - Effect.map((v) => v as Record | undefined), + // altimate_change start — a cache that isn't a catalogue is dropped like a corrupt one + Effect.flatMap((v) => { + if (v === undefined) return Effect.succeed(undefined) + const catalogue = catalogOf(v) + if (catalogue || Flag.OPENCODE_MODELS_PATH !== undefined) return Effect.succeed(catalogue) + return fs.remove(filepath, { force: true }).pipe(Effect.ignore, Effect.as(undefined)) + }), + // altimate_change end ) // altimate_change start — with no build-time snapshot, the host's (provideSnapshot) const loadSnapshot = Effect.promise(async () => { if (typeof OPENCODE_MODELS_DEV !== "undefined") return OPENCODE_MODELS_DEV - return hostSnapshot ? await hostSnapshot().catch(() => undefined) : undefined + if (!hostSnapshot) return undefined + // A loader that throws, synchronously or not, counts as no snapshot. + try { + return await hostSnapshot() + } catch { + return undefined + } }) // altimate_change end - const fetchAndWrite = Effect.fn("ModelsDev.fetchAndWrite")(function* () { + // altimate_change start — fetch and check, then write, as separate steps + // Only a catalogue (`catalogOf`) is written to the cache. `populate` serves one even when the write fails. + const fetchCatalogue = Effect.fn("ModelsDev.fetchCatalogue")(function* () { const text = yield* fetchApi() + const catalogue = catalogOf(yield* Effect.try({ try: () => JSON.parse(text) as unknown, catch: (error) => error })) + if (!catalogue) return yield* Effect.fail(new Error("models.dev answered with JSON that is not a catalogue")) + return { text, catalogue } + }) + + const writeCache = Effect.fn("ModelsDev.writeCache")(function* (text: string) { const tempfile = `${filepath}.${process.pid}.${Date.now()}.tmp` yield* fs.writeWithDirs(tempfile, text).pipe( Effect.andThen(fs.rename(tempfile, filepath)), @@ -206,9 +242,15 @@ export const layer = Layer.effect( }), ), ) - return text }) + const fetchAndWrite = Effect.fn("ModelsDev.fetchAndWrite")(function* () { + const { text, catalogue } = yield* fetchCatalogue() + yield* writeCache(text) + return catalogue + }) + // altimate_change end + const populate = Effect.gen(function* () { const fromDisk = yield* loadFromDisk if (fromDisk) return fromDisk @@ -224,12 +266,13 @@ export const layer = Layer.effect( const loaded = yield* Effect.scoped( Effect.gen(function* () { yield* Flock.effect(lockKey) - return yield* fetchAndWrite() + const { text, catalogue } = yield* fetchCatalogue() + yield* writeCache(text).pipe( + Effect.catch((error) => Effect.logWarning("Failed to write the models cache; serving the catalogue anyway", { error })), + ) + return catalogue }), ).pipe( - Effect.flatMap((text) => - Effect.try({ try: () => JSON.parse(text) as Record, catch: (error) => error }), - ), Effect.catch((error) => Effect.logError("Failed to load models.dev; serving an empty catalogue until a refresh succeeds", { error, diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index ba844af102..5dac7543f6 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -7,7 +7,7 @@ import { Global } from "@opencode-ai/core/global" import { ModelsDev } from "@opencode-ai/core/models-dev" import { EventV2 } from "@opencode-ai/core/event" import { it } from "./lib/effect" -import { readFile, rm, writeFile, utimes, mkdir } from "fs/promises" +import { chmod, readFile, rm, writeFile, utimes, mkdir } from "fs/promises" import path from "path" // test/preload.ts pins OPENCODE_MODELS_PATH to a fixture so other tests can @@ -153,77 +153,129 @@ describe("ModelsDev Service", () => { }), ) - it.live("get() recovers from a corrupted cache file by fetching a fresh catalog", () => - Effect.gen(function* () { - yield* writeCacheText("{") - const state = yield* Ref.make({ ...initialState, body: JSON.stringify(fixture2) }) - const result = yield* Effect.acquireUseRelease( - Effect.sync(() => { - Flag.OPENCODE_DISABLE_MODELS_FETCH = false - }), - () => - provided( - state, - ModelsDev.Service.use((s) => s.get()), - ), - () => - Effect.sync(() => { - Flag.OPENCODE_DISABLE_MODELS_FETCH = true - }), - ) - expect(result).toEqual(fixture2) - expect(yield* Effect.promise(() => readFile(cacheFile, "utf8"))).toBe(JSON.stringify(fixture2)) - const final = yield* Ref.get(state) - expect(final.calls.length).toBe(1) - }), - ) - - // No cache and no bundled snapshot (tests never define one), so the first get() has to fetch. + // Fetching is on only inside `eff`. `provided` builds the layer before that, with fetching off, so the + // layer's eager background refresh never starts and every request a test sees is the one under test. const withFetch = (eff: Effect.Effect) => Effect.acquireUseRelease( Effect.sync(() => { Flag.OPENCODE_DISABLE_MODELS_FETCH = false }), () => eff, + // Back to this suite's value (beforeAll); afterAll restores the original. () => Effect.sync(() => { Flag.OPENCODE_DISABLE_MODELS_FETCH = true }), ) + const getWithFetch = (state: Ref.Ref) => + provided(state, withFetch(ModelsDev.Service.use((s) => s.get()))) + const cacheText = Effect.promise(() => readFile(cacheFile, "utf8").catch(() => "absent")) + const withHostSnapshot = (load: Parameters[0], eff: Effect.Effect) => + Effect.acquireUseRelease( + Effect.sync(() => ModelsDev.provideSnapshot(load)), + () => eff, + () => Effect.sync(() => ModelsDev.provideSnapshot(undefined)), + ) + + it.live("get() recovers from a corrupted cache file by fetching a fresh catalog", () => + Effect.gen(function* () { + yield* writeCacheText("{") + const state = yield* Ref.make({ ...initialState, body: JSON.stringify(fixture2) }) + expect(yield* getWithFetch(state)).toEqual(fixture2) + expect(yield* cacheText).toBe(JSON.stringify(fixture2)) + expect((yield* Ref.get(state)).calls.length).toBe(1) + }), + ) it.live("get() serves an empty catalogue when the first fetch fails", () => Effect.gen(function* () { const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" }) - const result = yield* withFetch( - provided( - state, - ModelsDev.Service.use((s) => s.get()), - ), - ) - expect(result).toEqual({}) + expect(yield* getWithFetch(state)).toEqual({}) expect((yield* Ref.get(state)).calls.length).toBeGreaterThanOrEqual(1) + expect(yield* cacheText).toBe("absent") }), ) it.live("get() serves an empty catalogue when models.dev answers with a body that is not JSON", () => Effect.gen(function* () { const state = yield* Ref.make({ ...initialState, body: "sign in to this network" }) - const result = yield* withFetch( - provided( - state, - ModelsDev.Service.use((s) => s.get()), - ), + expect(yield* getWithFetch(state)).toEqual({}) + expect(yield* cacheText).toBe("absent") + }), + ) + + it.live("JSON that isn't a catalogue is neither served nor cached", () => + Effect.gen(function* () { + const state = yield* Ref.make({ ...initialState, body: JSON.stringify({ error: "blocked by proxy" }) }) + expect(yield* getWithFetch(state)).toEqual({}) + expect(yield* cacheText).toBe("absent") + }), + ) + + it.live("a cache file that is JSON but not a catalogue is dropped, not served", () => + Effect.gen(function* () { + yield* writeCache({ error: "blocked by proxy" }) + const state = yield* Ref.make(initialState) + const result = yield* provided( + state, + ModelsDev.Service.use((s) => s.get()), ) - expect(result).toEqual({}) + expect(result).toEqual({}) // fetching is off here, and there is no snapshot + expect(yield* cacheText).toBe("absent") + }), + ) + + it.live("a refresh that answers with something other than a catalogue leaves the cache as it was", () => + Effect.gen(function* () { + yield* writeCache(fixture) + const state = yield* Ref.make({ ...initialState, body: JSON.stringify({ error: "blocked by proxy" }) }) + const result = yield* provided( + state, + Effect.gen(function* () { + const svc = yield* ModelsDev.Service + yield* svc.refresh(true) + return yield* svc.get() + }), + ) + expect(result).toEqual(fixture) + expect(yield* cacheText).toBe(JSON.stringify(fixture)) + }), + ) + + it.live("provider entries not shaped like one are left out", () => + Effect.gen(function* () { + yield* writeCache({ ...fixture, broken: { id: "broken", name: "Broken" }, note: "not a provider" }) + const state = yield* Ref.make(initialState) + const result = yield* provided( + state, + ModelsDev.Service.use((s) => s.get()), + ) + expect(result).toEqual(fixture) + }), + ) + + it.live("a fetched catalogue is served even when the cache can't be written", () => + Effect.gen(function* () { + const state = yield* Ref.make(initialState) + const result = yield* Effect.acquireUseRelease( + Effect.promise(async () => { + await mkdir(Global.Path.cache, { recursive: true }) + await chmod(Global.Path.cache, 0o555) + }), + () => getWithFetch(state), + () => Effect.promise(() => chmod(Global.Path.cache, 0o755)), + ) + expect(result).toEqual(fixture) + expect(yield* cacheText).toBe("absent") }), ) it.live("a refresh that succeeds replaces the empty catalogue served after a failed fetch", () => Effect.gen(function* () { const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" }) - const result = yield* withFetch( - provided( - state, + const result = yield* provided( + state, + withFetch( Effect.gen(function* () { const svc = yield* ModelsDev.Service const before = yield* svc.get() @@ -239,42 +291,27 @@ describe("ModelsDev Service", () => { }), ) - const withHostSnapshot = (load: Parameters[0], eff: Effect.Effect) => - Effect.acquireUseRelease( - Effect.sync(() => ModelsDev.provideSnapshot(load)), - () => eff, - () => Effect.sync(() => ModelsDev.provideSnapshot(undefined)), - ) - - it.live("with no cache, get() serves the host's catalogue (provideSnapshot) without waiting on a fetch", () => + it.live("with no cache, get() serves the host's catalogue (provideSnapshot) without a fetch", () => Effect.gen(function* () { const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" }) - const result = yield* withHostSnapshot( - async () => fixture2, - withFetch( - provided( - state, - ModelsDev.Service.use((s) => s.get()), - ), - ), - ) - expect(result).toEqual(fixture2) + expect(yield* withHostSnapshot(async () => fixture2, getWithFetch(state))).toEqual(fixture2) + expect((yield* Ref.get(state)).calls).toEqual([]) }), ) - it.live("a host catalogue that fails to load counts as none: get() fetches", () => + it.live("a host catalogue that fails to load, or whose loader throws, counts as none: get() fetches", () => Effect.gen(function* () { - const state = yield* Ref.make(initialState) - const result = yield* withHostSnapshot( + for (const load of [ () => Promise.reject(new Error("no snapshot module")), - withFetch( - provided( - state, - ModelsDev.Service.use((s) => s.get()), - ), - ), - ) - expect(result).toEqual(fixture) + () => { + throw new Error("no snapshot module") + }, + ]) { + yield* Effect.promise(() => rm(cacheFile, { force: true })) + const state = yield* Ref.make(initialState) + expect(yield* withHostSnapshot(load, getWithFetch(state))).toEqual(fixture) + expect((yield* Ref.get(state)).calls.length).toBe(1) + } }), ) diff --git a/packages/opencode/test/altimate/models-snapshot-host.test.ts b/packages/opencode/test/altimate/models-snapshot-host.test.ts index 3306c111d9..77fe478896 100644 --- a/packages/opencode/test/altimate/models-snapshot-host.test.ts +++ b/packages/opencode/test/altimate/models-snapshot-host.test.ts @@ -4,12 +4,13 @@ // ships (src/provider/models-snapshot.ts). This checks the wiring: with no cache and no fetch, core's `get()` // returns that module's catalogue. import { afterAll, beforeAll, expect, test } from "bun:test" -import { rm } from "fs/promises" +import { readFile, rm } from "fs/promises" import path from "path" import { Effect, Layer } from "effect" import { Flag } from "@opencode-ai/core/flag/flag" import { Global } from "@opencode-ai/core/global" import { ModelsDev } from "@opencode-ai/core/models-dev" +import { testEffect } from "../lib/effect" const ORIGINAL_MODELS_PATH = Flag.OPENCODE_MODELS_PATH const ORIGINAL_DISABLE_FETCH = Flag.OPENCODE_DISABLE_MODELS_FETCH @@ -25,13 +26,26 @@ afterAll(() => { ModelsDev.provideSnapshot(undefined) }) -test("with no models cache, core's loader serves the catalogue the build ships", async () => { - await import("../../src/altimate/models-snapshot-host") - // @ts-ignore — the generated module's literal type is too large to check - const { snapshot } = await import("../../src/provider/models-snapshot.js") - const catalogue = await Effect.runPromise( - ModelsDev.Service.use((s) => s.get()).pipe(Effect.provide(Layer.fresh(ModelsDev.defaultLayer))), - ) - expect(Object.keys(catalogue).length).toBeGreaterThan(50) - expect(Object.keys(catalogue).sort()).toEqual(Object.keys(snapshot).sort()) +const it = testEffect(Layer.fresh(ModelsDev.defaultLayer)) + +it.live("with no models cache, core's loader serves the catalogue the build ships", () => + Effect.gen(function* () { + yield* Effect.promise(() => import("../../src/altimate/models-snapshot-host")) + const { snapshot } = yield* Effect.promise( + // @ts-ignore — the generated module's literal type is too large to check + () => import("../../src/provider/models-snapshot.js") as Promise<{ snapshot: Record }>, + ) + const catalogue = yield* ModelsDev.Service.use((s) => s.get()) + expect(Object.keys(catalogue).length).toBeGreaterThan(50) + expect(Object.keys(catalogue).sort()).toEqual(Object.keys(snapshot).sort()) + }), +) + +test("both entry points that run the server import the host module", async () => { + // The test above imports the module itself, so it can't notice an entry point dropping the import. + const src = path.join(import.meta.dir, "..", "..", "src") + for (const entry of ["index.ts", path.join("cli", "tui", "worker.ts")]) { + const text = await readFile(path.join(src, entry), "utf8") + expect(text).toMatch(/^import "(\.\/|@\/)altimate\/models-snapshot-host"$/m) + } }) From 0aa211a4b5f16aae7bdc3927c5e284fbf31189d1 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 18:27:14 +0800 Subject: [PATCH 4/5] test: the unwritable-cache test runs only where a folder's mode blocks writes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvsr1G2qqFbMCyPZg3G --- packages/core/test/models.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index 5dac7543f6..6e4d488f05 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -7,7 +7,7 @@ import { Global } from "@opencode-ai/core/global" import { ModelsDev } from "@opencode-ai/core/models-dev" import { EventV2 } from "@opencode-ai/core/event" import { it } from "./lib/effect" -import { chmod, readFile, rm, writeFile, utimes, mkdir } from "fs/promises" +import { chmod, readFile, rm, stat, writeFile, utimes, mkdir } from "fs/promises" import path from "path" // test/preload.ts pins OPENCODE_MODELS_PATH to a fixture so other tests can @@ -254,16 +254,20 @@ describe("ModelsDev Service", () => { }), ) - it.live("a fetched catalogue is served even when the cache can't be written", () => + // A read-only folder blocks the write only where its mode is enforced: not on Windows, and not for root. + const modeBlocksWrites = process.platform !== "win32" && process.getuid?.() !== 0 + ;(modeBlocksWrites ? it.live : it.live.skip)("a fetched catalogue is served even when the cache can't be written", () => Effect.gen(function* () { const state = yield* Ref.make(initialState) const result = yield* Effect.acquireUseRelease( Effect.promise(async () => { await mkdir(Global.Path.cache, { recursive: true }) + const { mode } = await stat(Global.Path.cache) await chmod(Global.Path.cache, 0o555) + return mode }), () => getWithFetch(state), - () => Effect.promise(() => chmod(Global.Path.cache, 0o755)), + (mode) => Effect.promise(() => chmod(Global.Path.cache, mode)), ) expect(result).toEqual(fixture) expect(yield* cacheText).toBe("absent") From a049703b26ecaa5edb89849063b867d3ba9732d8 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 18:32:45 +0800 Subject: [PATCH 5/5] fix: a refresh fills the empty catalogue even when the cache can't be written `fetchAndWrite` logs a failed write and returns the catalogue, so `refresh` still invalidates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvsr1G2qqFbMCyPZg3G --- packages/core/src/models-dev.ts | 13 ++++++------- packages/core/test/models.test.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index eb2b427ffb..bbe8f273cd 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -223,7 +223,8 @@ export const layer = Layer.effect( // altimate_change end // altimate_change start — fetch and check, then write, as separate steps - // Only a catalogue (`catalogOf`) is written to the cache. `populate` serves one even when the write fails. + // Only a catalogue (`catalogOf`) is written to the cache. A failed write is logged and the catalogue still + // returned, so `populate` serves it and `refresh` still invalidates (the next load fetches it again). const fetchCatalogue = Effect.fn("ModelsDev.fetchCatalogue")(function* () { const text = yield* fetchApi() const catalogue = catalogOf(yield* Effect.try({ try: () => JSON.parse(text) as unknown, catch: (error) => error })) @@ -246,7 +247,9 @@ export const layer = Layer.effect( const fetchAndWrite = Effect.fn("ModelsDev.fetchAndWrite")(function* () { const { text, catalogue } = yield* fetchCatalogue() - yield* writeCache(text) + yield* writeCache(text).pipe( + Effect.catch((error) => Effect.logWarning("Failed to write the models cache; using the catalogue anyway", { error })), + ) return catalogue }) // altimate_change end @@ -266,11 +269,7 @@ export const layer = Layer.effect( const loaded = yield* Effect.scoped( Effect.gen(function* () { yield* Flock.effect(lockKey) - const { text, catalogue } = yield* fetchCatalogue() - yield* writeCache(text).pipe( - Effect.catch((error) => Effect.logWarning("Failed to write the models cache; serving the catalogue anyway", { error })), - ) - return catalogue + return yield* fetchAndWrite() }), ).pipe( Effect.catch((error) => diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index 6e4d488f05..e101b2b8dc 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -274,6 +274,37 @@ describe("ModelsDev Service", () => { }), ) + ;(modeBlocksWrites ? it.live : it.live.skip)("a refresh fills the empty catalogue even when the cache can't be written", () => + Effect.gen(function* () { + const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" }) + const result = yield* Effect.acquireUseRelease( + Effect.promise(async () => { + await mkdir(Global.Path.cache, { recursive: true }) + const { mode } = await stat(Global.Path.cache) + await chmod(Global.Path.cache, 0o555) + return mode + }), + () => + provided( + state, + withFetch( + Effect.gen(function* () { + const svc = yield* ModelsDev.Service + const before = yield* svc.get() + yield* Ref.update(state, (s) => ({ ...s, status: 200, body: JSON.stringify(fixture) })) + yield* svc.refresh(true) + return { before, after: yield* svc.get() } + }), + ), + ), + (mode) => Effect.promise(() => chmod(Global.Path.cache, mode)), + ) + expect(result.before).toEqual({}) + expect(result.after).toEqual(fixture) + expect(yield* cacheText).toBe("absent") + }), + ) + it.live("a refresh that succeeds replaces the empty catalogue served after a failed fetch", () => Effect.gen(function* () { const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" })