GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(site): bound the models.dev fetch behind opencode.models() · developing-today-forks/opencode@d29a20a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • services/site
    • src/lib
      • console-api.ts
      • models-dev.ts
    • test
      • console-models.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎services/site/src/lib/console-api.ts‎

Copy file name to clipboardExpand all lines: services/site/src/lib/console-api.ts
+4-13Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { desktopBuilds, desktopInstall, detectOS, getDownloadHref } from "~/lib/
55
import { detectPlatform } from "~/lib/platform"
66
import { modules, type Letter } from "~/lib/font-content"
77
import { freeModels } from "~/lib/get-started"
8+
import { fetchFreeModels } from "~/lib/models-dev"
89
import { sdkInstalls } from "~/lib/install-commands"
910
import { liteQuitKey } from "~/lib/console-stub"
1011

@@ -226,14 +227,9 @@ export function install() {
226227
return manifest.sdk.install
227228
},
228229
async models() {
229-
const live = await fetch("https://models.dev/api.json")
230-
.then((response) => response.json() as Promise<ModelsDev>)
231-
.then((data) =>
232-
Object.values(data.opencode?.models ?? {}).filter(
233-
(model) => model.cost?.input === 0 && model.cost?.output === 0 && model.status !== "deprecated",
234-
),
235-
)
236-
.catch(() => [])
230+
// fetchFreeModels is deadline- and size-bounded, so a stalled models.dev
231+
// settles into the catch and the freeModels fallback below instead of hanging.
232+
const live = await fetchFreeModels().catch(() => [])
237233
if (!live.length) {
238234
say([`Free models include ${freeModels.join(", ")}. No account needed.`])
239235
return freeModels
@@ -296,11 +292,6 @@ export function install() {
296292
return { api, startLite, greet: () => greet(colors, say) }
297293
}
298294

299-
type ModelsDev = Record<
300-
string,
301-
{ models?: Record<string, { id: string; name: string; status?: string; cost?: { input?: number; output?: number } }> }
302-
>
303-
304295
/** Loads a Text.js console app built by packages/console/textjs; its manifest maps names to hashed files. */
305296
async function textjs<T>(name: "lite" | "picker") {
306297
const files = (await fetch("/textjs/manifest.json").then((response) => response.json())) as Record<string, string>
Collapse file

‎services/site/src/lib/models-dev.ts‎

Copy file name to clipboard
+57Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Bounded fetch of the free-model list from models.dev, for the DevTools console API
2+
// (opencode.models() in console-api.ts). models.dev can stall before responding or
3+
// mid-body; without a deadline and a size bound the call would stay pending forever
4+
// and never reach the freeModels fallback. One AbortSignal deadline covers both the
5+
// request and the body read, and the body is rejected as soon as it grows past the
6+
// limit instead of being buffered whole.
7+
8+
export const modelsDevTimeoutMs = 10_000
9+
export const modelsDevMaxBytes = 16 * 1024 * 1024
10+
11+
export type ModelsDevModel = {
12+
id: string
13+
name: string
14+
status?: string
15+
cost?: { input?: number; output?: number }
16+
}
17+
18+
type ModelsDev = Record<string, { models?: Record<string, ModelsDevModel> }>
19+
20+
export async function fetchFreeModels(options?: {
21+
timeoutMs?: number
22+
maxBytes?: number
23+
fetch?: typeof fetch
24+
}): Promise<ModelsDevModel[]> {
25+
const load = options?.fetch ?? fetch
26+
const response = await load("https://models.dev/api.json", {
27+
signal: AbortSignal.timeout(options?.timeoutMs ?? modelsDevTimeoutMs),
28+
})
29+
const data = JSON.parse(await readBounded(response, options?.maxBytes ?? modelsDevMaxBytes)) as ModelsDev
30+
return Object.values(data.opencode?.models ?? {}).filter(
31+
(model) => model.cost?.input === 0 && model.cost?.output === 0 && model.status !== "deprecated",
32+
)
33+
}
34+
35+
async function readBounded(response: Response, maxBytes: number): Promise<string> {
36+
if (!response.body) throw new Error("models.dev response had no body")
37+
const reader = response.body.getReader()
38+
const chunks: Uint8Array[] = []
39+
let total = 0
40+
while (true) {
41+
const { done, value } = await reader.read()
42+
if (done) break
43+
total += value.byteLength
44+
if (total > maxBytes) {
45+
await reader.cancel()
46+
throw new Error(`models.dev response exceeded ${maxBytes} bytes`)
47+
}
48+
chunks.push(value)
49+
}
50+
const bytes = new Uint8Array(total)
51+
let offset = 0
52+
for (const chunk of chunks) {
53+
bytes.set(chunk, offset)
54+
offset += chunk.byteLength
55+
}
56+
return new TextDecoder().decode(bytes)
57+
}
Collapse file

‎services/site/test/console-models.test.ts‎

Copy file name to clipboard
+54Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { fetchFreeModels } from "../src/lib/models-dev"
3+
4+
// Oracle: the returned model list and bounded settlement. opencode.models()
5+
// (console-api.ts) falls back to freeModels whenever fetchFreeModels rejects,
6+
// so each stall case must reject promptly instead of staying pending.
7+
8+
const valid = JSON.stringify({
9+
opencode: {
10+
models: {
11+
free: { id: "free", name: "Free", cost: { input: 0, output: 0 } },
12+
paid: { id: "paid", name: "Paid", cost: { input: 1, output: 0 } },
13+
retired: { id: "retired", name: "Retired", status: "deprecated", cost: { input: 0, output: 0 } },
14+
unpriced: { id: "unpriced", name: "Unpriced" },
15+
},
16+
},
17+
})
18+
19+
describe("fetchFreeModels", () => {
20+
test("returns the non-deprecated zero-cost models from a valid response", async () => {
21+
const load = (async () => new Response(valid)) as typeof fetch
22+
const models = await fetchFreeModels({ fetch: load })
23+
expect(models.map((model) => model.id)).toEqual(["free"])
24+
})
25+
26+
test("a stalled request settles within the deadline", async () => {
27+
const load = ((_input: RequestInfo | URL, init?: RequestInit) =>
28+
new Promise<Response>((_resolve, reject) => {
29+
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason))
30+
})) as typeof fetch
31+
const start = Date.now()
32+
await expect(fetchFreeModels({ fetch: load, timeoutMs: 25 })).rejects.toThrow()
33+
expect(Date.now() - start).toBeLessThan(5_000)
34+
})
35+
36+
test("a never-ending response body settles within the deadline", async () => {
37+
const load = (async (_input: RequestInfo | URL, init?: RequestInit) => {
38+
const body = new ReadableStream<Uint8Array>({
39+
start(controller) {
40+
init?.signal?.addEventListener("abort", () => controller.error(init.signal?.reason))
41+
},
42+
})
43+
return new Response(body)
44+
}) as typeof fetch
45+
const start = Date.now()
46+
await expect(fetchFreeModels({ fetch: load, timeoutMs: 25 })).rejects.toThrow()
47+
expect(Date.now() - start).toBeLessThan(5_000)
48+
})
49+
50+
test("an over-limit body is rejected before full buffering", async () => {
51+
const load = (async () => new Response(valid)) as typeof fetch
52+
await expect(fetchFreeModels({ fetch: load, maxBytes: 16 })).rejects.toThrow("exceeded 16 bytes")
53+
})
54+
})

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.