Skip to content

Commit e4ab3d4

Browse files
author
Peter Steinberger
committed
fix(ollama): honor model requests and pull completion contracts
1 parent fdcb321 commit e4ab3d4

9 files changed

Lines changed: 155 additions & 61 deletions

‎extensions/ollama/provider-discovery.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -215,11 +215,11 @@ describe("Ollama provider", () => {
215215
if (url.endsWith("/api/show")) {
216216
const rawBody = init?.body;
217217
const bodyText = typeof rawBody === "string" ? rawBody : "{}";
218-
const parsed = JSON.parse(bodyText) as { name?: string };
219-
if (parsed.name === "qwen3:32b") {
218+
const parsed = JSON.parse(bodyText) as { model?: string };
219+
if (parsed.model === "qwen3:32b") {
220220
return jsonResponse({ model_info: { "qwen3.context_length": 131072 } });
221221
}
222-
if (parsed.name === "llama3.3:70b") {
222+
if (parsed.model === "llama3.3:70b") {
223223
return jsonResponse({ model_info: { "llama.context_length": 65536 } });
224224
}
225225
}

‎extensions/ollama/src/node-inference.paired-node.e2e.test.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -607,13 +607,7 @@ async function handleFakeOllamaRequest(
607607
}
608608
if (requestPath === "/api/show") {
609609
const body = await readRequestJson(request);
610-
// Ollama documents `model`; the current provider sends its supported `name` alias.
611-
const modelName =
612-
typeof body.model === "string"
613-
? body.model
614-
: typeof body.name === "string"
615-
? body.name
616-
: undefined;
610+
const modelName = typeof body.model === "string" ? body.model : undefined;
617611
if (!modelName) {
618612
response.statusCode = 400;
619613
response.end(JSON.stringify({ error: "model is required" }));

‎extensions/ollama/src/node-inference.test.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,16 @@ async function withOllamaServer<T>(
7979
return;
8080
}
8181
if (request.url === "/api/show") {
82-
const body = (await readBody(request)) as { name?: string };
83-
if (body.name) {
84-
showRequests.push(body.name);
82+
const body = (await readBody(request)) as { model?: string };
83+
if (body.model) {
84+
showRequests.push(body.model);
8585
}
86-
if (body.name === "unknown:latest") {
86+
if (body.model === "unknown:latest") {
8787
response.statusCode = 500;
8888
response.end(JSON.stringify({ error: "show failed" }));
8989
return;
9090
}
91-
const embedding = body.name?.startsWith("embedding") === true;
91+
const embedding = body.model?.startsWith("embedding") === true;
9292
response.end(
9393
JSON.stringify({
9494
capabilities: embedding ? ["embedding"] : ["completion", "tools"],

‎extensions/ollama/src/provider-models.test.ts‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,18 @@ describe("ollama provider models", () => {
5050
expect(resolveOllamaApiBase("http://127.0.0.1:11434///")).toBe("http://127.0.0.1:11434");
5151
});
5252

53+
it("inspects local models using Ollama's canonical model request field", async () => {
54+
const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) =>
55+
jsonResponse({ model_info: {} }),
56+
);
57+
vi.stubGlobal("fetch", fetchMock);
58+
59+
await readOllamaModelShowInfo("http://127.0.0.1:11434", "gemma4:e2b");
60+
61+
const request = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined;
62+
expect(JSON.parse(requestBodyText(request?.body))).toEqual({ model: "gemma4:e2b" });
63+
});
64+
5365
it("caps local discovered runtime context while preserving native metadata", () => {
5466
const provider = capLocalOllamaProviderContext({
5567
api: "ollama",
@@ -93,8 +105,8 @@ describe("ollama provider models", () => {
93105
if (!url.endsWith("/api/show")) {
94106
throw new Error(`Unexpected fetch: ${url}`);
95107
}
96-
const body = JSON.parse(requestBodyText(init?.body)) as { name?: string };
97-
if (body.name === "llama3:8b") {
108+
const body = JSON.parse(requestBodyText(init?.body)) as { model?: string };
109+
if (body.model === "llama3:8b") {
98110
return jsonResponse({ model_info: { "llama.context_length": 65536 } });
99111
}
100112
return jsonResponse({});
@@ -161,8 +173,8 @@ describe("ollama provider models", () => {
161173
});
162174
}
163175
if (url.endsWith("/api/show")) {
164-
const body = JSON.parse(requestBodyText(init?.body)) as { name?: string };
165-
const completion = body.name === "qwen-chat:latest";
176+
const body = JSON.parse(requestBodyText(init?.body)) as { model?: string };
177+
const completion = body.model === "qwen-chat:latest";
166178
return jsonResponse({
167179
capabilities: completion ? ["completion", "tools"] : ["embedding"],
168180
model_info: completion ? { "qwen.context_length": 32_768 } : {},
@@ -275,14 +287,14 @@ describe("ollama provider models", () => {
275287
if (!url.endsWith("/api/show")) {
276288
throw new Error(`Unexpected fetch: ${url}`);
277289
}
278-
const body = JSON.parse(requestBodyText(init?.body)) as { name?: string };
279-
if (body.name === "kimi-k2.5:cloud") {
290+
const body = JSON.parse(requestBodyText(init?.body)) as { model?: string };
291+
if (body.model === "kimi-k2.5:cloud") {
280292
return jsonResponse({
281293
model_info: { "kimi-k2.context_length": 262144 },
282294
capabilities: ["vision", "thinking", "completion", "tools"],
283295
});
284296
}
285-
if (body.name === "glm-5.1:cloud") {
297+
if (body.model === "glm-5.1:cloud") {
286298
return jsonResponse({
287299
model_info: { "glm5.context_length": 202752 },
288300
capabilities: ["thinking", "completion", "tools"],
@@ -409,7 +421,7 @@ describe("ollama provider models", () => {
409421
const model: OllamaTagModel = { name: "qwen3:32b", digest: "sha256:normalized-base" };
410422
const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
411423
expect(requestUrl(input)).toBe("http://127.0.0.1:11434/api/show");
412-
expect(JSON.parse(requestBodyText(init?.body))).toEqual({ name: "qwen3:32b" });
424+
expect(JSON.parse(requestBodyText(init?.body))).toEqual({ model: "qwen3:32b" });
413425
return jsonResponse({
414426
model_info: { "qwen3.context_length": 131072 },
415427
capabilities: ["thinking", "tools"],

‎extensions/ollama/src/provider-models.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ export async function readOllamaModelShowInfo(
172172
init: {
173173
method: "POST",
174174
headers,
175-
body: JSON.stringify({ name: modelName }),
175+
body: JSON.stringify({ model: modelName }),
176176
},
177177
// Guard-owned timeoutMs also bounds DNS/proxy preflight; init.signal does not.
178178
timeoutMs: Math.min(opts?.timeoutMs ?? OLLAMA_SHOW_TIMEOUT_MS, OLLAMA_SHOW_TIMEOUT_MS),

‎extensions/ollama/src/setup-pull.test.ts‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { WizardPrompter } from "openclaw/plugin-sdk/setup";
22
import { afterEach, describe, expect, it, vi } from "vitest";
3-
import { pullOllamaModel } from "./setup-pull.js";
3+
import { pullOllamaModel, pullOllamaModelNonInteractive } from "./setup-pull.js";
44

55
const fetchWithSsrFGuardMock = vi.hoisted(() => vi.fn());
66

@@ -17,6 +17,81 @@ describe("Ollama onboarding model pulls", () => {
1717
fetchWithSsrFGuardMock.mockReset();
1818
});
1919

20+
it("uses the canonical Ollama model request field and requires its success terminal", async () => {
21+
const release = vi.fn(async () => {});
22+
fetchWithSsrFGuardMock.mockResolvedValue({
23+
response: new Response('{"status":"pulling manifest"}\n{"status":"success"}\n'),
24+
release,
25+
});
26+
const progress = { update: vi.fn(), stop: vi.fn() };
27+
const prompter = { progress: vi.fn(() => progress) } as unknown as WizardPrompter;
28+
29+
await expect(pullOllamaModel("http://127.0.0.1:11434", "gemma4:e2b", prompter)).resolves.toBe(
30+
true,
31+
);
32+
33+
const request = fetchWithSsrFGuardMock.mock.calls[0]?.[0] as { init?: { body?: string } };
34+
expect(JSON.parse(request.init?.body ?? "null")).toEqual({ model: "gemma4:e2b" });
35+
expect(progress.stop).toHaveBeenCalledWith("Downloaded gemma4:e2b");
36+
expect(release).toHaveBeenCalledOnce();
37+
});
38+
39+
it.each([
40+
{ label: "empty response", body: "" },
41+
{ label: "interrupted manifest download", body: '{"status":"pulling manifest"}\n' },
42+
{
43+
label: "interrupted model layer",
44+
body: '{"status":"pulling abcdef123456","total":100,"completed":40}\n',
45+
},
46+
{ label: "malformed stream", body: "not valid json\n" },
47+
{ label: "incomplete trailing record", body: '{"status":"success"' },
48+
])("does not report a completed model pull for an $label", async ({ body }) => {
49+
const release = vi.fn(async () => {});
50+
fetchWithSsrFGuardMock.mockResolvedValue({ response: new Response(body), release });
51+
const progress = { update: vi.fn(), stop: vi.fn() };
52+
const prompter = { progress: vi.fn(() => progress) } as unknown as WizardPrompter;
53+
54+
await expect(pullOllamaModel("http://127.0.0.1:11434", "gemma4:e2b", prompter)).resolves.toBe(
55+
false,
56+
);
57+
58+
expect(progress.stop).toHaveBeenCalledWith(
59+
"Failed to download gemma4:e2b: pull stream ended before success",
60+
);
61+
expect(release).toHaveBeenCalledOnce();
62+
});
63+
64+
it("accepts a final success record without a trailing newline", async () => {
65+
fetchWithSsrFGuardMock.mockResolvedValue({
66+
response: new Response('{"status":"success"}'),
67+
release: vi.fn(async () => {}),
68+
});
69+
const progress = { update: vi.fn(), stop: vi.fn() };
70+
const prompter = { progress: vi.fn(() => progress) } as unknown as WizardPrompter;
71+
72+
await expect(pullOllamaModel("http://127.0.0.1:11434", "gemma4:e2b", prompter)).resolves.toBe(
73+
true,
74+
);
75+
expect(progress.stop).toHaveBeenCalledWith("Downloaded gemma4:e2b");
76+
});
77+
78+
it("reports interrupted pulls as failures during non-interactive setup", async () => {
79+
fetchWithSsrFGuardMock.mockResolvedValue({
80+
response: new Response('{"status":"pulling manifest"}\n'),
81+
release: vi.fn(async () => {}),
82+
});
83+
const runtime = { log: vi.fn(), error: vi.fn() };
84+
85+
await expect(
86+
pullOllamaModelNonInteractive("http://127.0.0.1:11434", "gemma4:e2b", runtime as never),
87+
).resolves.toBe(false);
88+
89+
expect(runtime.error).toHaveBeenCalledWith(
90+
"Failed to download gemma4:e2b: pull stream ended before success",
91+
);
92+
expect(runtime.log).not.toHaveBeenCalledWith("Downloaded gemma4:e2b");
93+
});
94+
2095
it("coerces non-Error stream failures through the shared error contract", async () => {
2196
const release = vi.fn(async () => {});
2297
const response = new Response(

‎extensions/ollama/src/setup-pull.ts‎

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ async function pullOllamaModelCore(params: {
6868
init: {
6969
method: "POST",
7070
headers: { "Content-Type": "application/json" },
71-
body: JSON.stringify({ name: modelName }),
71+
body: JSON.stringify({ model: modelName }),
7272
},
7373
signal: params.signal
7474
? AbortSignal.any([responseController.signal, params.signal])
@@ -92,28 +92,25 @@ async function pullOllamaModelCore(params: {
9292
let pendingRecordBytes = 0;
9393
const layers = new Map<string, { total: number; completed: number }>();
9494

95-
const parseLine = (line: string): OllamaPullResult => {
96-
const trimmed = line.trim();
97-
if (!trimmed) {
98-
return { ok: true };
95+
const parseLine = (line: string): OllamaPullResult | undefined => {
96+
if (!line.trim()) {
97+
return undefined;
9998
}
10099
try {
101-
const chunk = JSON.parse(trimmed) as OllamaPullChunk;
100+
const chunk = JSON.parse(line) as OllamaPullChunk;
102101
if (chunk.error) {
103102
return { ok: false, message: `Download failed: ${chunk.error}` };
104103
}
105-
if (!chunk.status) {
106-
return { ok: true };
104+
if (!chunk.status || chunk.status === "success") {
105+
return chunk.status ? { ok: true } : undefined;
107106
}
108107
if (chunk.total && chunk.completed !== undefined) {
109108
layers.set(chunk.status, { total: chunk.total, completed: chunk.completed });
110-
const totals = [...layers.values()].reduce(
111-
(sum, layer) => ({
112-
total: sum.total + layer.total,
113-
completed: sum.completed + layer.completed,
114-
}),
115-
{ total: 0, completed: 0 },
116-
);
109+
const totals = { total: 0, completed: 0 };
110+
for (const layer of layers.values()) {
111+
totals.total += layer.total;
112+
totals.completed += layer.completed;
113+
}
117114
params.onStatus?.(
118115
chunk.status,
119116
totals.total > 0 ? Math.round((totals.completed / totals.total) * 100) : null,
@@ -124,22 +121,26 @@ async function pullOllamaModelCore(params: {
124121
} catch {
125122
// Ignore malformed streaming lines from Ollama.
126123
}
127-
return { ok: true };
124+
return undefined;
128125
};
129126

130127
try {
131128
for (;;) {
132129
const { done, value } = await readOllamaPullChunkWithIdleTimeout(reader);
133130
if (done) {
134-
return parseLine(buffer);
131+
const terminal = parseLine(buffer);
132+
if (terminal) {
133+
return terminal;
134+
}
135+
throw new Error("pull stream ended before success");
135136
}
136137
pendingRecordBytes = checkNdjsonRecordCap(value, pendingRecordBytes);
137138
buffer += decoder.decode(value, { stream: true });
138139
const lines = buffer.split("\n");
139140
buffer = lines.pop() ?? "";
140141
for (const line of lines) {
141142
const parsed = parseLine(line);
142-
if (!parsed.ok) {
143+
if (parsed) {
143144
return parsed;
144145
}
145146
}
@@ -154,8 +155,7 @@ async function pullOllamaModelCore(params: {
154155
await release();
155156
}
156157
} catch (err) {
157-
const reason = formatErrorMessage(err);
158-
return { ok: false, message: `Failed to download ${modelName}: ${reason}` };
158+
return { ok: false, message: `Failed to download ${modelName}: ${formatErrorMessage(err)}` };
159159
} finally {
160160
clearTimeout(responseTimeout);
161161
}

‎extensions/ollama/src/setup.non-interactive-auth.test.ts‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,11 @@ function createOllamaFetchMock(params: {
4444
return jsonResponse({ models: params.tags.map((name) => ({ name })) });
4545
}
4646
if (url.endsWith("/api/show")) {
47-
const body = JSON.parse(requestBodyText(init?.body)) as { name?: string };
48-
const contextWindow = body.name ? params.show?.[body.name] : undefined;
49-
const capabilities = body.name ? (params.capabilities?.[body.name] ?? ["tools"]) : ["tools"];
47+
const body = JSON.parse(requestBodyText(init?.body)) as { model?: string };
48+
const contextWindow = body.model ? params.show?.[body.model] : undefined;
49+
const capabilities = body.model
50+
? (params.capabilities?.[body.model] ?? ["tools"])
51+
: ["tools"];
5052
return jsonResponse({
5153
...(contextWindow ? { model_info: { "llama.context_length": contextWindow } } : {}),
5254
capabilities,
@@ -73,10 +75,21 @@ describe("Ollama non-interactive onboarding", () => {
7375
upsertAuthProfileWithLock.mockClear();
7476
});
7577

76-
it("does not persist local auth when non-interactive setup cannot select a model", async () => {
78+
it.each([
79+
{
80+
label: "Ollama reports a pull failure",
81+
body: '{"error":"disk full"}\n',
82+
error: "Download failed: disk full",
83+
},
84+
{
85+
label: "the model pull ends before success",
86+
body: '{"status":"pulling manifest"}\n',
87+
error: "Failed to download missing-model: pull stream ended before success",
88+
},
89+
])("does not persist unavailable local models when $label", async ({ body, error }) => {
7790
const fetchMock = createOllamaFetchMock({
7891
tags: [],
79-
pullResponse: new Response('{"error":"disk full"}\n', { status: 200 }),
92+
pullResponse: new Response(body, { status: 200 }),
8093
});
8194
vi.stubGlobal("fetch", fetchMock);
8295
const runtime = createRuntime();
@@ -91,7 +104,7 @@ describe("Ollama non-interactive onboarding", () => {
91104
runtime,
92105
});
93106

94-
expect(runtime.error).toHaveBeenCalledWith("Download failed: disk full");
107+
expect(runtime.error).toHaveBeenCalledWith(error);
95108
expect(runtime.error).toHaveBeenCalledWith(
96109
[
97110
"No Ollama models are available at http://127.0.0.1:11434.",
@@ -186,7 +199,7 @@ describe("Ollama non-interactive onboarding", () => {
186199
return false;
187200
}
188201
const init = call[1] as RequestInit | undefined;
189-
return JSON.parse(requestBodyText(init?.body)).name === modelId;
202+
return JSON.parse(requestBodyText(init?.body)).model === modelId;
190203
}),
191204
).toHaveLength(1);
192205
});

0 commit comments

Comments
 (0)