Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Show Ollama as Ollama: its mark, pulled models and why it can't answer (#5100)

Milind Soni29df0fb05e12
diff --git a/apps/docs/content/docs/providers/model-providers.mdx b/apps/docs/content/docs/providers/model-providers.mdx
index 3621a4b773..ed78a790ff 100644
--- a/apps/docs/content/docs/providers/model-providers.mdx
+++ b/apps/docs/content/docs/providers/model-providers.mdx
@@ -239,6 +239,23 @@ list only over HTTPS or to this computer. Check that:
- The gateway serves the right protocol for the agent and lists models for
your key.
+## Ollama
+
+A chat engine whose address is Ollama shows up as **Ollama**, with Ollama's
+mark, in Settings and the model picker. MausBot treats an address as Ollama
+when it uses Ollama's port (11434), or when an address on this computer or your
+network answers Ollama's own API. An
+address you added before keeps its name, key and model.
+
+- Ollama needs no API key.
+- The picker lists the models you pulled, with their size, parameter count and
+ quantization. Embedding models are left out.
+- A model that can't call tools still chats, but its turns run without tools.
+ The picker marks it **No tools**. Pick a model with tool support, such as
+ `llama3.2` or `qwen3`, for work that needs tools.
+- When Ollama isn't running, can't be reached, or has no models yet, Settings
+ says so and how to fix it. To get a first model, run `ollama pull llama3.2`.
+
## Ollama's context window
Below 23 GB of graphics memory, Ollama gives a model a 4,096-token context window
diff --git a/server/contracts.ts b/server/contracts.ts
index 82756bd679..e2c1c0dcca 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -6,6 +6,7 @@ import type { EffortLevel } from "../shared/wire.ts";
import type {
DriverKind, InstanceId, ModelVariantOption, RuntimeEventListener, ThreadId, TurnId,
} from "../shared/runtime-events.ts";
+import type { LocalModelFacts } from "../shared/local-model.ts";
import type { ProviderIcon } from "../shared/provider-icon.ts";
export type { CloudBackend, EffortLevel, ModelSelection } from "../shared/wire.ts";
@@ -482,6 +483,7 @@ export interface ModelCatalog {
variants?: ModelVariantOption[];
/** The organization of the signed-in account turned this model off: the engine would answer with another. */
orgBlocked?: true;
+ local?: LocalModelFacts;
}>;
}
diff --git a/server/drivers/ollama.test.ts b/server/drivers/ollama.test.ts
new file mode 100644
index 0000000000..82a9709f28
--- /dev/null
+++ b/server/drivers/ollama.test.ts
@@ -0,0 +1,373 @@
+import { randomUUID } from "node:crypto";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { recordEvents } from "../testing/events.ts";
+import { instanceLook } from "../provider-icon.ts";
+import { forgetServedModels } from "./ollama-context.ts";
+import {
+ answeredAsOllama, findOllama, forgetOllamaAnswers, isOllamaServer, ollamaOrigin, ollamaTags, ollamaUnavailable,
+ probeOllama, showCapabilities,
+} from "./ollama.ts";
+import { OpenAICompatDriver } from "./openai-compat.ts";
+
+const GB = 1e9;
+const running: Server[] = [];
+
+afterEach(async () => {
+ forgetOllamaAnswers();
+ forgetServedModels();
+ for (const server of running.splice(0)) {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+});
+
+interface FakeModel { name: string; size?: number; details?: Record<string, unknown>; capabilities?: string[] }
+
+/** A server speaking Ollama's own routes and its OpenAI-compatible chat, recording each chat request. */
+async function fakeOllama(options: { models?: FakeModel[]; version?: string | null; tags?: boolean } = {}) {
+ // Read per request, so a test can change what the server answers.
+ const models = options.models ?? [];
+ const chats: Array<{ model: string; tools?: unknown[] }> = [];
+ const asked: string[] = [];
+ const server = createServer(async (request, response) => {
+ let data = "";
+ for await (const part of request) data += part.toString();
+ const path = request.url ?? "";
+ asked.push(path);
+ const json = (body: unknown, status = 200) => {
+ response.writeHead(status, { "content-type": "application/json" });
+ response.end(JSON.stringify(body));
+ };
+ if (path === "/api/tags" && options.tags !== false) return json({ models });
+ if (path === "/api/version" && options.version !== null) return json({ version: options.version ?? "0.12.6" });
+ if (path === "/api/show") {
+ const model = models.find((entry) => entry.name === (JSON.parse(data) as { model: string }).model);
+ return model ? json({ capabilities: model.capabilities, model_info: { "llama.context_length": 131_072 } }) : json({ error: "not found" }, 404);
+ }
+ if (path === "/api/ps") return json({ models: [] });
+ if (path === "/api/create") return json({ status: "success" });
+ if (path === "/v1/models") return json({ data: models.map((model) => ({ id: model.name })) });
+ if (path === "/v1/chat/completions") {
+ chats.push(JSON.parse(data) as { model: string; tools?: unknown[] });
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: "Hi." }, finish_reason: "stop" }] })}\n\n`);
+ return response.end("data: [DONE]\n\n");
+ }
+ json({ error: "not found" }, 404);
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ running.push(server);
+ return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, chats, asked };
+}
+
+/** An address nothing listens on. */
+async function closedPort(): Promise<string> {
+ const server = createServer();
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const { port } = server.address() as AddressInfo;
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ return `http://127.0.0.1:${port}`;
+}
+
+/** A server that takes the connection and never answers. */
+async function silentServer(): Promise<string> {
+ const server = createServer(() => {});
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ running.push(server);
+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}
+
+const LLAMA: FakeModel = {
+ name: "llama3.2:latest", size: 2_019_393_189,
+ details: { family: "llama", parameter_size: "3.2B", quantization_level: "Q4_K_M" }, capabilities: ["completion", "tools"],
+};
+const GEMMA: FakeModel = {
+ name: "gemma2:2b", size: 1_629_518_495,
+ details: { family: "gemma2", parameter_size: "2.6B", quantization_level: "Q4_0" }, capabilities: ["completion"],
+};
+const EMBED: FakeModel = { name: "nomic-embed-text:latest", size: 274_302_450, details: { family: "nomic-bert" } };
+
+describe("Ollama's model list", () => {
+ it("keeps the chat models with their size, parameters and quantization", () => {
+ expect(ollamaTags({ models: [LLAMA, EMBED, { name: "llama3.2:latest-omb-32k", size: GB }, { name: "mxbai-embed-large" }, LLAMA] })).toEqual([
+ { name: "llama3.2:latest", bytes: 2_019_393_189, parameters: "3.2B", quantization: "Q4_K_M" },
+ ]);
+ });
+
+ it("is no list for an answer that is not one", () => {
+ expect(ollamaTags({ data: [] })).toBeNull();
+ expect(ollamaTags(null)).toBeNull();
+ expect(ollamaTags({ models: [] })).toEqual([]);
+ });
+
+ it("reads what a model can do, and nothing from a server that does not say", () => {
+ expect(showCapabilities({ capabilities: ["completion", "tools", "vision"] })).toEqual({ tools: true, vision: true });
+ expect(showCapabilities({ capabilities: ["completion"] })).toEqual({ tools: false, vision: false });
+ expect(showCapabilities({ model_info: {} })).toEqual({});
+ });
+
+ it("drops the /v1 the OpenAI-compatible routes sit under", () => {
+ expect(ollamaOrigin("http://127.0.0.1:11434/v1/")).toBe("http://127.0.0.1:11434");
+ expect(ollamaOrigin("http://gpu-box.local:11434")).toBe("http://gpu-box.local:11434");
+ });
+});
+
+describe("finding Ollama", () => {
+ it("is ready with the pulled models, and asks each what it can do only when told to", async () => {
+ const { url } = await fakeOllama({ models: [LLAMA, GEMMA, EMBED] });
+ expect(await probeOllama(`${url}/v1`)).toEqual({
+ state: "ready", url, version: "0.12.6",
+ models: [
+ { name: "llama3.2:latest", bytes: 2_019_393_189, parameters: "3.2B", quantization: "Q4_K_M" },
+ { name: "gemma2:2b", bytes: 1_629_518_495, parameters: "2.6B", quantization: "Q4_0" },
+ ],
+ });
+ const asked = await probeOllama(url, { capabilities: true });
+ expect(asked.models.map(({ name, tools, vision }) => ({ name, tools, vision }))).toEqual([
+ { name: "llama3.2:latest", tools: true, vision: false },
+ { name: "gemma2:2b", tools: false, vision: false },
+ ]);
+ expect(answeredAsOllama(url)).toBe(true);
+ });
+
+ it("goes by what a model can do over what it is called, once the server says", async () => {
+ const assistant: FakeModel = { name: "embedded-assistant:latest", details: { family: "llama" }, capabilities: ["completion"] };
+ const vectors: FakeModel = { name: "search-vectors:latest", details: { family: "custom" }, capabilities: ["embedding"] };
+ const { url } = await fakeOllama({ models: [assistant, vectors] });
+ expect((await probeOllama(url, { capabilities: true })).models.map((model) => model.name)).toEqual(["embedded-assistant:latest"]);
+ });
+
+ it("says when nothing is pulled yet, with the command that pulls a model", async () => {
+ const { url } = await fakeOllama({ models: [EMBED] });
+ const status = await probeOllama(url);
+ expect(status).toMatchObject({ state: "no-models", models: [] });
+ expect(ollamaUnavailable(status)).toMatch(/no models yet\. Run `ollama pull llama3\.2`/);
+ });
+
+ it("says when nothing listens at the address", async () => {
+ const url = await closedPort();
+ const status = await probeOllama(url);
+ expect(status).toEqual({ state: "not-running", url, models: [] });
+ expect(ollamaUnavailable(status)).toBe(`Ollama isn't running at ${url}. Open the Ollama app or run \`ollama serve\`.`);
+ expect(answeredAsOllama(url)).toBeUndefined();
+ });
+
+ it("is unreachable when the server does not answer in time", async () => {
+ const url = await silentServer();
+ const status = await probeOllama(url, { timeoutMs: 150 });
+ expect(status).toEqual({ state: "unreachable", url, models: [], problem: "timeout" });
+ expect(ollamaUnavailable(status)).toMatch(/^Can't reach Ollama at .*: it did not answer in time\./);
+ });
+
+ it("is unreachable when the host is unknown", async () => {
+ const status = await probeOllama("http://ollama.invalid:11434", { timeoutMs: 2_000 });
+ expect(status).toMatchObject({ state: "unreachable", problem: expect.stringMatching(/^(network|timeout)$/) });
+ });
+
+ it("tells another server apart, and leaves it to its OpenAI-compatible routes", async () => {
+ const other = await fakeOllama({ models: [LLAMA], tags: false });
+ expect(await probeOllama(other.url)).toEqual({ state: "unreachable", url: other.url, models: [], problem: "not-ollama" });
+ expect(ollamaUnavailable(await probeOllama(other.url))).toBeNull();
+ // Some servers imitate /api/tags, but never /api/version.
+ const imitation = await fakeOllama({ models: [LLAMA], version: null });
+ expect((await probeOllama(imitation.url)).state).toBe("ready");
+ expect(answeredAsOllama(imitation.url)).toBe(false);
+ });
+
+ it("keeps a yes through a failed version request, but not through a server that stops answering as Ollama", async () => {
+ const options: Parameters<typeof fakeOllama>[0] = { models: [LLAMA] };
+ const { url } = await fakeOllama(options);
+ await probeOllama(url);
+ options.version = null;
+ await probeOllama(url);
+ expect(answeredAsOllama(url)).toBe(true);
+ options.tags = false;
+ await probeOllama(url);
+ expect(answeredAsOllama(url)).toBe(false);
+ });
+
+ it("takes the first address that runs, else what the first address said", async () => {
+ const { url } = await fakeOllama({ models: [LLAMA] });
+ const closed = await closedPort();
+ expect(await findOllama([closed], { localUrls: [url] })).toMatchObject({ state: "ready", url });
+ const silent = await silentServer();
+ expect(await findOllama([closed, silent], { timeoutMs: 150, localUrls: [] })).toMatchObject({ state: "unreachable", url: silent });
+ });
+});
+
+describe("an OpenAI-compatible server that is really Ollama", () => {
+ it("is one when added as Ollama, on Ollama's port, or when it answered as Ollama", async () => {
+ expect(isOllamaServer({ url: "http://gpu-box.local:8080/v1", catalog: "ollama" })).toBe(true);
+ expect(isOllamaServer({ url: "http://127.0.0.1:11434/v1" })).toBe(true);
+ expect(isOllamaServer({ url: "http://127.0.0.1:11434/v1", catalog: "lmstudio" })).toBe(false);
+ expect(isOllamaServer({ url: "https://openrouter.ai/api/v1" })).toBe(false);
+ const { url } = await fakeOllama({ models: [LLAMA] });
+ expect(isOllamaServer({ url: `${url}/v1` })).toBe(false);
+ await probeOllama(url);
+ expect(isOllamaServer({ url: `${url}/v1` })).toBe(true);
+ });
+
+ it("stops being one on Ollama's port once something else has answered there", async () => {
+ const config = { url: "http://127.0.0.1:11434/v1" };
+ expect(isOllamaServer(config)).toBe(true);
+ await probeOllama(config.url, { fetchImpl: (async () => new Response("{}", { status: 404 })) as typeof fetch });
+ expect(isOllamaServer(config)).toBe(false);
+ expect(instanceLook({ driver: "openai-compat", config })).toEqual({});
+ });
+
+ it("shows as Ollama: its mark, and its name unless someone named it", () => {
+ const builtIn = { driver: "openai-compat", config: { url: "http://localhost:11434/v1" } };
+ expect(instanceLook(builtIn)).toEqual({ icon: { kind: "preset", preset: "ollama" }, serverKind: "ollama", displayName: "Ollama" });
+ expect(instanceLook({ ...builtIn, displayName: "Studio box" })).toEqual({ icon: { kind: "preset", preset: "ollama" }, serverKind: "ollama" });
+ const custom = { kind: "custom", dataUrl: "data:image/png;base64,iVBORw0KGgo=" } as const;
+ expect(instanceLook({ ...builtIn, icon: custom })).toMatchObject({ icon: custom, serverKind: "ollama" });
+ expect(instanceLook({ driver: "openai-compat", config: { url: "https://api.deepseek.com/v1" } })).toEqual({ icon: { kind: "preset", preset: "deepseek" } });
+ });
+});
+
+describe("the chat engine on Ollama", () => {
+ const create = (config: Record<string, unknown>, environment: Record<string, string> = {}) => OpenAICompatDriver.create({
+ instanceId: randomUUID(), displayName: undefined, enabled: true, config: OpenAICompatDriver.decodeConfig(config), environment,
+ });
+
+ it("needs no key, lists the pulled models with their facts, and is available", async () => {
+ const { url } = await fakeOllama({ models: [LLAMA, GEMMA] });
+ const instance = await create({ url: `${url}/v1`, catalog: "ollama" });
+ try {
+ await instance.refreshModels?.();
+ expect(instance.models).toEqual({
+ default: "llama3.2:latest",
+ options: [
+ { id: "llama3.2:latest", label: "llama3.2:latest", custom: true, local: { bytes: 2_019_393_189, parameters: "3.2B", quantization: "Q4_K_M", tools: true, vision: false } },
+ { id: "gemma2:2b", label: "gemma2:2b", custom: true, local: { bytes: 1_629_518_495, parameters: "2.6B", quantization: "Q4_0", tools: false, vision: false } },
+ ],
+ });
+ expect(await instance.snapshot()).toMatchObject({ state: "available", authenticated: true });
+ } finally { await instance.dispose(); }
+ });
+
+ it("is unavailable, saying why, while Ollama is not running or has nothing to run", async () => {
+ const closed = await create({ url: `${await closedPort()}/v1`, catalog: "ollama" });
+ try {
+ expect(await closed.snapshot()).toMatchObject({ state: "unavailable", reason: expect.stringMatching(/^Ollama isn't running at /) });
+ expect(closed.models).toEqual({ default: "", options: [] });
+ } finally { await closed.dispose(); }
+ const { url } = await fakeOllama({ models: [] });
+ const empty = await create({ url: `${url}/v1`, catalog: "ollama" });
+ try {
+ await empty.refreshModels?.();
+ expect(await empty.snapshot()).toMatchObject({ state: "unavailable", reason: expect.stringContaining("ollama pull llama3.2") });
+ } finally { await empty.dispose(); }
+ });
+
+ it("recognises a server someone added as OpenAI-compatible, and keeps its saved key and model", async () => {
+ const { url } = await fakeOllama({ models: [LLAMA, GEMMA] });
+ const config = { url: `${url}/v1`, apiKeyEnv: "FIXTURE_KEY", model: "gemma2:2b" };
+ const instance = await create(config, { FIXTURE_KEY: "fixture-key" });
+ try {
+ await instance.refreshModels?.();
+ expect(instance.models.default).toBe("gemma2:2b");
+ expect(instance.models.options.map((option) => option.id)).toEqual(["llama3.2:latest", "gemma2:2b"]);
+ expect(instanceLook({ driver: "openai-compat", displayName: "Local", config })).toMatchObject({ icon: { kind: "preset", preset: "ollama" }, serverKind: "ollama" });
+ } finally { await instance.dispose(); }
+ });
+
+ it("leaves a server that is not Ollama to its OpenAI-compatible model list", async () => {
+ const { url } = await fakeOllama({ models: [LLAMA], tags: false });
+ const instance = await create({ url: `${url}/v1`, apiKeyEnv: "FIXTURE_KEY" }, { FIXTURE_KEY: "fixture-key" });
+ try {
+ await instance.refreshModels?.();
+ expect(instance.models.options).toEqual([{ id: "llama3.2:latest", label: "llama3.2:latest", custom: true }]);
+ expect(await instance.snapshot()).toMatchObject({ state: "available" });
+ expect(instanceLook({ driver: "openai-compat", displayName: "Local", config: { url: `${url}/v1` } })).toEqual({});
+ } finally { await instance.dispose(); }
+ });
+
+ it("keeps a fixed model list on Ollama, and still knows which of them can call tools", async () => {
+ const { url, chats } = await fakeOllama({ models: [LLAMA, GEMMA] });
+ const instance = await create({ url: `${url}/v1`, catalog: "ollama", managedModels: ["gemma2:2b"] });
+ const recorder = recordEvents(instance.adapter);
+ try {
+ await instance.refreshModels?.();
+ expect(instance.models).toEqual({ default: "gemma2:2b", options: [{ id: "gemma2:2b", label: "gemma2:2b" }] });
+ const threadId = randomUUID();
+ await instance.adapter.sendTurn({ threadId, text: "hi", model: "gemma2:2b" });
+ await recorder.until((event) => event.type === "turn.completed" && event.threadId === threadId);
+ expect(chats[0]!.tools).toBeUndefined();
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+
+ it("tells a text-only model on the network about an attachment instead of refusing the turn", async () => {
+ const replies: Record<string, unknown> = {
+ "/api/tags": { models: [GEMMA] }, "/api/version": { version: "0.12.6" }, "/api/show": { capabilities: ["completion"] }, "/api/ps": { models: [] }, "/api/create": { status: "success" },
+ };
+ const bodies: string[] = [];
+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (url, init) => {
+ const path = new URL(String(url)).pathname;
+ if (path === "/v1/chat/completions") {
+ bodies.push(String(init!.body));
+ return new Response(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: "Hi." }, finish_reason: "stop" }] })}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } });
+ }
+ return new Response(JSON.stringify(replies[path] ?? {}), { status: replies[path] ? 200 : 404 });
+ }));
+ const instance = await create({ url: "http://192.168.1.20:11434/v1", catalog: "ollama" });
+ const recorder = recordEvents(instance.adapter);
+ try {
+ await instance.refreshModels?.();
+ const threadId = randomUUID();
+ await instance.adapter.sendTurn({ threadId, text: "what is this?", model: "gemma2:2b", images: [{ path: "/not-read.png", mime: "image/png", bytes: 1 }] });
+ await recorder.until((event) => event.type === "turn.completed" && event.threadId === threadId);
+ expect(bodies[0]).toContain("this model cannot see images");
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("never asks another server on this network for Ollama's model list", async () => {
+ const { url, asked } = await fakeOllama({ models: [LLAMA], version: null });
+ const instance = await create({ url: `${url}/v1`, apiKeyEnv: "FIXTURE_KEY" }, { FIXTURE_KEY: "fixture-key" });
+ try {
+ await instance.refreshModels?.();
+ await instance.snapshot();
+ expect(asked).toContain("/api/version");
+ expect(asked).not.toContain("/api/tags");
+ expect(instance.models.options.map((option) => option.id)).toEqual(["llama3.2:latest"]);
+ } finally { await instance.dispose(); }
+ });
+
+ it("asks nothing of a server on this network that has a fixed model list", async () => {
+ const { url } = await fakeOllama({ models: [LLAMA] });
+ const instance = await create({ url: `${url}/v1`, apiKeyEnv: "FIXTURE_KEY", managedModels: ["llama3.2:latest"] }, { FIXTURE_KEY: "fixture-key" });
+ try {
+ await instance.snapshot();
+ expect(answeredAsOllama(url)).toBeUndefined();
+ } finally { await instance.dispose(); }
+ });
+
+ it("sends tools only to a model that can call them", async () => {
+ const { url, chats } = await fakeOllama({ models: [LLAMA, GEMMA] });
+ const instance = await create({ url: `${url}/v1`, catalog: "ollama" });
+ const recorder = recordEvents(instance.adapter);
+ try {
+ await instance.refreshModels?.();
+ for (const model of ["llama3.2:latest", "gemma2:2b"]) {
+ const threadId = randomUUID();
+ await instance.adapter.sendTurn({ threadId, text: "hi", model });
+ await recorder.until((event) => event.type === "turn.completed" && event.threadId === threadId);
+ }
+ expect(chats.map((chat) => Boolean(chat.tools?.length))).toEqual([true, false]);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+});
diff --git a/server/drivers/ollama.ts b/server/drivers/ollama.ts
new file mode 100644
index 0000000000..090bb0bf11
--- /dev/null
+++ b/server/drivers/ollama.ts
@@ -0,0 +1,191 @@
+// Ollama's own API (docs/api.md in github.com/ollama/ollama): /api/tags lists the pulled models with their size and
+// details, /api/version answers with a version, and /api/show names a model's capabilities ("tools", "vision") from
+// v0.6.4. A default install takes no key on these routes or on the OpenAI-compatible ones under /v1.
+import { isContextName } from "./ollama-context.ts";
+
+export const OLLAMA_PORT = "11434";
+/** Where `ollama serve` listens unless OLLAMA_HOST says otherwise. */
+export const OLLAMA_LOCAL_URLS: readonly string[] = ["http://127.0.0.1:11434", "http://localhost:11434"];
+/** Ollama ignores the key; the OpenAI-compatible request still carries one. */
+export const OLLAMA_PLACEHOLDER_KEY = "ollama";
+export const OLLAMA_PULL_COMMAND = "ollama pull llama3.2";
+
+/** A pulled model, as /api/tags and /api/show describe it. */
+export interface OllamaModel {
+ name: string;
+ /** Bytes on disk. */
+ bytes?: number;
+ /** As Ollama writes it, such as "3.2B". */
+ parameters?: string;
+ /** As Ollama writes it, such as "Q4_K_M". */
+ quantization?: string;
+ /** Absent when the server does not say (before v0.6.4). */
+ tools?: boolean;
+ vision?: boolean;
+}
+
+/** `ready`: running with models. `no-models`: running, nothing pulled. `not-running`: nothing listens there.
+ * `unreachable`: no answer in time, the host or network is unknown, or something else answers there. */
+export type OllamaState = "ready" | "no-models" | "not-running" | "unreachable";
+
+export interface OllamaStatus {
+ state: OllamaState;
+ url: string;
+ version?: string;
+ models: OllamaModel[];
+ /** Why an `unreachable` server could not be used. */
+ problem?: "timeout" | "network" | "not-ollama";
+}
+
+/** The server's own address: the base URL without the /v1 the OpenAI-compatible routes sit under. */
+export function ollamaOrigin(baseUrl: string): string {
+ return baseUrl.trim().replace(/\/+$/, "").replace(/\/v1$/, "");
+}
+
+export function onOllamaPort(url: string): boolean {
+ try { return new URL(url).port === OLLAMA_PORT; } catch { return false; }
+}
+
+const EMBEDDING = /embed|(?:^|[/:-])bge-|minilm/i;
+const text = (value: unknown) => typeof value === "string" && value.trim() ? value.trim() : undefined;
+
+/** The chat models in an /api/tags answer, or null when the answer is not one. An embedding model answers no chat (its
+ * name only counts where Ollama gives no family), and a name that carries a context window is the model it was made from. */
+export function ollamaTags(payload: unknown): OllamaModel[] | null {
+ const rows = payload && typeof payload === "object" ? (payload as { models?: unknown }).models : undefined;
+ if (!Array.isArray(rows)) return null;
+ const seen = new Set<string>();
+ const models: OllamaModel[] = [];
+ for (const row of rows) {
+ if (!row || typeof row !== "object") continue;
+ const entry = row as { name?: unknown; model?: unknown; size?: unknown; details?: unknown };
+ const name = text(entry.name) ?? text(entry.model);
+ const details = (entry.details && typeof entry.details === "object" ? entry.details : {}) as { family?: unknown; families?: unknown; parameter_size?: unknown; quantization_level?: unknown };
+ const families = [details.family, ...(Array.isArray(details.families) ? details.families : [])].filter((family): family is string => typeof family === "string");
+ if (!name || seen.has(name) || isContextName(name) || families.some((family) => /bert$/i.test(family)) || (!families.length && EMBEDDING.test(name))) continue;
+ seen.add(name);
+ const parameters = text(details.parameter_size), quantization = text(details.quantization_level);
+ models.push({
+ name,
+ ...(typeof entry.size === "number" && Number.isSafeInteger(entry.size) && entry.size > 0 ? { bytes: entry.size } : {}),
+ ...(parameters ? { parameters } : {}),
+ ...(quantization ? { quantization } : {}),
+ });
+ }
+ return models;
+}
+
+/** What /api/show says a model can do; empty when the server predates capabilities. */
+export function showCapabilities(show: unknown): Pick<OllamaModel, "tools" | "vision"> {
+ const capabilities = show && typeof show === "object" ? (show as { capabilities?: unknown }).capabilities : undefined;
+ if (!Array.isArray(capabilities) || !capabilities.every((entry) => typeof entry === "string")) return {};
+ return { tools: capabilities.includes("tools"), vision: capabilities.includes("vision") };
+}
+
+/** False only for a model /api/show says cannot chat. */
+function answersChats(show: unknown): boolean {
+ const capabilities = show && typeof show === "object" ? (show as { capabilities?: unknown }).capabilities : undefined;
+ return !Array.isArray(capabilities) || capabilities.includes("completion");
+}
+
+function nobodyListening(error: unknown): boolean {
+ const cause = (error as { cause?: { code?: unknown; errors?: unknown } } | undefined)?.cause;
+ if (cause?.code === "ECONNREFUSED") return true;
+ return Array.isArray(cause?.errors) && cause.errors.length > 0 && cause.errors.every((entry) => (entry as { code?: unknown }).code === "ECONNREFUSED");
+}
+
+const timedOut = (error: unknown) => (error as { name?: unknown } | undefined)?.name === "TimeoutError";
+
+const answered = new Map<string, boolean>();
+
+/** Whether this server has answered as Ollama: /api/tags with a list and /api/version with a version (some other servers
+ * imitate /api/tags alone). Undefined until asked; a failed version request alone doesn't undo a yes. */
+export function answeredAsOllama(url: string): boolean | undefined {
+ return answered.get(ollamaOrigin(url));
+}
+
+export interface ProbeOptions {
+ fetchImpl?: typeof fetch;
+ timeoutMs?: number;
+ /** Sent as a bearer token, for an Ollama behind a proxy that asks for one. */
+ key?: string;
+ /** Also ask /api/show what each model can do. */
+ capabilities?: boolean;
+ /** Where "this computer" is looked for, when not Ollama's defaults. */
+ localUrls?: readonly string[];
+}
+
+/** Never throws. */
+export async function probeOllama(url: string, options: ProbeOptions = {}): Promise<OllamaStatus> {
+ const origin = ollamaOrigin(url);
+ const fetchImpl = options.fetchImpl ?? fetch;
+ const timeoutMs = options.timeoutMs ?? 2_000;
+ const headers = options.key ? { authorization: `Bearer ${options.key}` } : undefined;
+ const ask = (path: string, init: RequestInit = {}) =>
+ fetchImpl(`${origin}${path}`, { ...init, headers: { ...headers, ...init.headers as Record<string, string> }, redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
+ let models: OllamaModel[] | null;
+ let version: string | undefined;
+ try {
+ const [tags, about] = await Promise.all([
+ ask("/api/tags"),
+ ask("/api/version").then((response) => response.ok ? response.json() : null).catch(() => null),
+ ]);
+ models = tags.ok ? ollamaTags(await tags.json().catch(() => null)) : null;
+ version = text((about as { version?: unknown } | null)?.version);
+ } catch (error) {
+ if (nobodyListening(error)) return { state: "not-running", url: origin, models: [] };
+ return { state: "unreachable", url: origin, models: [], problem: timedOut(error) ? "timeout" : "network" };
+ }
+ if (models === null) answered.set(origin, false);
+ else if (version) answered.set(origin, true);
+ else if (!answered.has(origin)) answered.set(origin, false);
+ if (!models) return { state: "unreachable", url: origin, models: [], problem: "not-ollama" };
+ if (options.capabilities) {
+ const asked = await Promise.all(models.map(async (model) => {
+ try {
+ const response = await ask("/api/show", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: model.name }) });
+ if (!response.ok) return model;
+ const show: unknown = await response.json();
+ return answersChats(show) ? { ...model, ...showCapabilities(show) } : null;
+ } catch {
+ return model;
+ }
+ }));
+ models = asked.filter((model) => model !== null);
+ }
+ return { state: models.length ? "ready" : "no-models", url: origin, ...(version ? { version } : {}), models };
+}
+
+/** What stops an Ollama from answering, for the engine list; null when it can, or when something else answers there. */
+export function ollamaUnavailable(status: OllamaStatus): string | null {
+ switch (status.state) {
+ case "ready": return null;
+ case "no-models": return `Ollama has no models yet. Run \`${OLLAMA_PULL_COMMAND}\`, then check again.`;
+ case "not-running": return `Ollama isn't running at ${status.url}. Open the Ollama app or run \`ollama serve\`.`;
+ case "unreachable": return status.problem === "not-ollama" ? null
+ : `Can't reach Ollama at ${status.url}${status.problem === "timeout" ? ": it did not answer in time" : ""}. Check the address and that this computer can reach it.`;
+ }
+}
+
+const RANK: Record<OllamaState, number> = { ready: 0, "no-models": 1, unreachable: 2, "not-running": 3 };
+
+/** Ollama on this computer, or at an address someone set: the first that runs, else the most telling answer. */
+export async function findOllama(urls: readonly string[] = [], options: ProbeOptions = {}): Promise<OllamaStatus> {
+ const origins = [...new Set([...urls, ...(options.localUrls ?? OLLAMA_LOCAL_URLS)].map(ollamaOrigin))];
+ const found = await Promise.all(origins.map((origin) => probeOllama(origin, options)));
+ return found.reduce((best, status) => RANK[status.state] < RANK[best.state] ? status : best);
+}
+
+/** An OpenAI-compatible instance that is really Ollama: added as Ollama, it answered as Ollama, or it is on Ollama's port
+ * and nothing there has answered otherwise. */
+export function isOllamaServer(config: unknown): boolean {
+ const { url, catalog } = (config && typeof config === "object" ? config : {}) as { url?: unknown; catalog?: unknown };
+ if (catalog === "ollama") return true;
+ if (catalog !== undefined || typeof url !== "string") return false;
+ const answer = answeredAsOllama(url);
+ return answer === true || (answer === undefined && onOllamaPort(url));
+}
+
+export function forgetOllamaAnswers(): void {
+ answered.clear();
+}
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 3d1a9186fb..7f831c4889 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -115,6 +115,10 @@ interface RuntimeOptions<Config> {
computerUse?: boolean;
/** A text-only model keeps the computer and browser tools but never receives a screenshot or attachment. */
imageInput?: (model: string) => boolean;
+ /** False for a model its server says cannot call tools: its turns go without them instead of being refused. */
+ toolUse?: (model: string) => boolean;
+ /** Why the server cannot answer now (not running, nothing to run), asked before the key is. */
+ serverUnavailable?: () => Promise<string | null>;
/** The name to send for a model, when its server knows it by another. */
servedModel?: (model: string) => Promise<string>;
/** Smaller models announce a step and end the turn without calling a tool; such a reply gets a nudge, at most three
@@ -511,7 +515,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const sendTurn = async (turn: SendTurnInput) => {
if (!options.apiKey) throw new Error(options.missingKeyError);
if (active.has(turn.threadId)) throw new Error("a turn is already running on this thread");
- if (options.computerUse && (turn.images?.length || turn.integrations?.localComputer || turn.integrations?.browser)) assertImageTransport(options.apiUrl);
+ if (options.computerUse && ((turn.images?.length && seesImages(turn)) || turn.integrations?.localComputer || turn.integrations?.browser)) assertImageTransport(options.apiUrl);
const turnId = newId();
const abort = new AbortController();
@@ -599,11 +603,12 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const parsed = parseToolScope(turn.toolScope);
if (!parsed.ok) throw new Error(parsed.error);
const scope = parsed.scope;
- tools = await mountChatTools(options.tools === false ? undefined : turn.integrations, abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,
+ const toolsOff = options.tools === false || options.toolUse?.(model) === false;
+ tools = await mountChatTools(toolsOff ? undefined : turn.integrations, abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,
toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model));
noteToolBudget(turn.botId, tools.budget);
for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
- const questionAllowed = options.tools !== false && allowsTool(scope, { kind: "native", name: ASK_USER_TOOL });
+ const questionAllowed = !toolsOff && allowsTool(scope, { kind: "native", name: ASK_USER_TOOL });
let optionalQuestionOnly = questionAllowed && tools.definitions.length === 0;
// An MCP server squatting ask_user cannot shadow it (dispatch intercepts the name); skip its definition.
if (questionAllowed && !tools.definitions.some((definition) => definition.function.name === ASK_USER_TOOL)) {
@@ -932,6 +937,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
},
...(options.refreshModels ? { refreshModels: options.refreshModels } : {}),
snapshot: async () => {
+ const down = await options.serverUnavailable?.();
+ if (down) return { state: "unavailable", reason: down };
if (!options.apiKey) return { state: "unavailable", reason: options.unavailableReason };
if (keyRejected(options.apiUrl, options.apiKey)) return { state: "available", authenticated: false, reason: KEY_REJECTED_REASON, version: null };
return { state: "available", authenticated: true, version: null, ...(options.billing ? { billing: options.billing } : {}) };
diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.ts
index af78e49f24..606e3b5bd9 100644
--- a/server/drivers/openai-compat.ts
+++ b/server/drivers/openai-compat.ts
@@ -4,6 +4,7 @@ import type { ModelCatalog, ProviderDriver } from "../contracts.ts";
import { isLoopback } from "../provider-key-check.ts";
import { lmStudioV1Catalog } from "./local-inject.ts";
import { isContextName, isOllama, serveWithWindow } from "./ollama-context.ts";
+import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, ollamaOrigin, ollamaUnavailable, onOllamaPort, probeOllama, type OllamaModel, type OllamaStatus } from "./ollama.ts";
import { createOpenAIChatRuntime } from "./openai-chat.ts";
import {
freeDefault, freeFallbackCatalog, freeLabel, freeToolModels, freeToolsFirst, isOpenRouterOrigin, openRouterFreeTier,
@@ -37,6 +38,14 @@ const DEFAULT_MODELS: ModelCatalog = {
],
};
+const NO_MODELS: ModelCatalog = { default: "", options: [] };
+const OLLAMA_STATUS_MS = 5_000;
+
+const localFacts = ({ bytes, parameters, quantization, tools, vision }: OllamaModel) => ({
+ ...(bytes ? { bytes } : {}), ...(parameters ? { parameters } : {}), ...(quantization ? { quantization } : {}),
+ ...(tools !== undefined ? { tools } : {}), ...(vision !== undefined ? { vision } : {}),
+});
+
const DEFAULT_KEY_ENV = "OPENAI_COMPAT_API_KEY";
/** A provider's own key: such an instance never falls back to the workspace OpenAI-compatible key, URL,
* model or routing. */
@@ -75,8 +84,9 @@ export interface OpenAICompatConfig {
tools?: boolean;
url: string;
apiKeyEnv: string;
- /** Which model list the server serves besides /models: OpenAI's own, or LM Studio's native /api/v1/models. */
- catalog?: "openai" | "lmstudio";
+ /** Which model list the server serves besides /models: OpenAI's own, LM Studio's native /api/v1/models, or
+ * Ollama's /api/tags. */
+ catalog?: "openai" | "lmstudio" | "ollama";
key?: string;
model?: string;
provider?: string;
@@ -85,6 +95,7 @@ export interface OpenAICompatConfig {
replyWaitMinutes?: number;
}
+const CATALOGS = ["openai", "lmstudio", "ollama"] as const;
export const MAX_REPLY_WAIT_MINUTES = 60;
const isReplyWait = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 1 && (value as number) <= MAX_REPLY_WAIT_MINUTES;
@@ -128,7 +139,7 @@ function decodeConfig(raw: unknown): OpenAICompatConfig {
if (config.tools !== undefined && typeof config.tools !== "boolean") throw new Error("tools must be a boolean");
if (config.managedModels !== undefined && (!Array.isArray(config.managedModels) || !config.managedModels.length || config.managedModels.some(model => typeof model !== "string" || !model.trim()))) throw new Error("Invalid managed models.");
const ownKey = typeof config.apiKeyEnv === "string" && OWN_KEY_ENVS.has(config.apiKeyEnv);
- if (config.catalog !== undefined && config.catalog !== "openai" && config.catalog !== "lmstudio") throw new Error("catalog must be \"openai\" or \"lmstudio\"");
+ if (config.catalog !== undefined && !CATALOGS.includes(config.catalog as never)) throw new Error("catalog must be \"openai\", \"lmstudio\" or \"ollama\"");
if (config.replyWaitMinutes !== undefined && !isReplyWait(config.replyWaitMinutes)) throw new Error(`replyWaitMinutes must be a whole number from 1 to ${MAX_REPLY_WAIT_MINUTES}`);
const envUrl = ownKey ? undefined : process.env.OPENAI_COMPAT_URL;
return {
@@ -140,7 +151,7 @@ function decodeConfig(raw: unknown): OpenAICompatConfig {
apiKeyEnv: typeof config.apiKeyEnv === "string" && config.apiKeyEnv
? config.apiKeyEnv
: DEFAULT_KEY_ENV,
- ...(config.catalog === "openai" || config.catalog === "lmstudio" ? { catalog: config.catalog } : {}),
+ ...(CATALOGS.includes(config.catalog as never) ? { catalog: config.catalog as OpenAICompatConfig["catalog"] } : {}),
key: typeof config.key === "string" && config.key ? config.key : undefined,
model: typeof config.model === "string" && config.model
? config.model
@@ -172,17 +183,23 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {
const { config } = input;
// An instance naming its own key variable reads only that one: the workspace key must not reach its host.
const ownKeyVariable = config.apiKeyEnv !== DEFAULT_KEY_ENV;
- const apiKey =
+ const savedKey =
config.key ??
input.environment[config.apiKeyEnv] ??
(ownKeyVariable ? undefined : input.environment[DEFAULT_KEY_ENV]) ??
process.env[config.apiKeyEnv] ??
(ownKeyVariable ? undefined : process.env[DEFAULT_KEY_ENV]) ??
"";
+ // A server someone gave a fixed model list to is not asked what else it might be, unless it is on Ollama's own port.
+ const ollamaCandidate = config.catalog === "ollama" || (config.catalog === undefined && (onOllamaPort(config.url) || (onThisNetwork(config.url) && !config.managedModels)));
+ // Another server on this network is only asked for Ollama's model list once it has answered Ollama's version route.
+ const answersAsOllama = () => isOllamaServer(config) || isOllama(ollamaOrigin(config.url));
+ if (!savedKey && ollamaCandidate && !isOllamaServer(config) && await answersAsOllama()) await probeOllama(config.url, { timeoutMs: 1_500 });
+ const apiKey = savedKey || (ollamaCandidate && isOllamaServer(config) ? OLLAMA_PLACEHOLDER_KEY : "");
const missingKey = !ownKeyVariable || OWN_KEY_ENVS.has(config.apiKeyEnv)
? "No API key — open Settings → API keys."
: `no API key — set ${config.apiKeyEnv} or add it to the instance config`;
- const seeded = config.catalog === "openai" ? OPENAI_MODELS : DEFAULT_MODELS;
+ const seeded = config.catalog === "openai" ? OPENAI_MODELS : isOllamaServer(config) ? NO_MODELS : DEFAULT_MODELS;
let catalog: ModelCatalog = config.managedModels
? { default: config.managedModels[0], options: config.managedModels.map(id => ({ id, label: id })) }
: config.model
@@ -197,9 +214,31 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {
const gemini = isGeminiOrigin(config.url);
const freeTier = () => openRouter ? openRouterFreeTier(apiKey, config.url) : Promise.resolve(null);
+ const facts = new Map<string, OllamaModel>();
+ const fact = (model: string) => facts.get(model) ?? facts.get(`${model}:latest`);
+ let ollama: { at: number; status: Promise<OllamaStatus> } | null = null;
+ const checkOllama = () => {
+ if (!ollama || Date.now() - ollama.at > OLLAMA_STATUS_MS) ollama = { at: Date.now(), status: probeOllama(config.url, { key: apiKey, timeoutMs: 3_000 }) };
+ return ollama.status;
+ };
+ const listOllama = async (): Promise<boolean> => {
+ if (!await answersAsOllama()) return false;
+ const status = await probeOllama(config.url, { key: apiKey, timeoutMs: 8_000, capabilities: true });
+ ollama = { at: Date.now(), status: Promise.resolve(status) };
+ if (!isOllamaServer(config) || (status.state !== "ready" && status.state !== "no-models")) return false;
+ facts.clear();
+ for (const model of status.models) facts.set(model.name, model);
+ if (config.managedModels) return true;
+ const options: ModelCatalog["options"] = status.models.map((model) => ({ id: model.name, label: model.name, custom: true, local: localFacts(model) }));
+ if (config.model && !options.some((model) => model.id === config.model)) options.unshift({ id: config.model, label: config.model, custom: true });
+ catalog = { default: config.model ?? options[0]?.id ?? "", options };
+ return true;
+ };
+
const fetchModels = async () => {
- if (config.managedModels) return;
if (!apiKey) return;
+ if (ollamaCandidate && await listOllama()) return;
+ if (config.managedModels) return;
try {
// Only a server added as LM Studio: any other local server would get a request it never serves.
const nativeUrl = config.catalog === "lmstudio" ? loopbackLmStudioV1Url(config.url) : null;
@@ -313,6 +352,13 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {
nudgeAnnouncedAction: true,
models: () => catalog,
refreshModels: fetchModels,
+ imageInput: (model) => fact(model)?.vision ?? true,
+ toolUse: (model) => fact(model)?.tools ?? true,
+ ...(ollamaCandidate ? {
+ serverUnavailable: async () => {
+ return isOllamaServer(config) ? ollamaUnavailable(await checkOllama()) : null;
+ },
+ } : {}),
requestBody: (model, messages, stream) => ({
model,
messages,
diff --git a/server/index.ts b/server/index.ts
index de95acaf59..a6df1f43ff 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -289,7 +289,7 @@ import { CloudCreditProvider } from "./cloud-credit-provider.ts";
import { createCreditMoves } from "./cloud-credit-moves.ts"; import { createRoutineHoldsHost } from "./host/routine-holds-host.ts";
import { TRIAL_CREDIT_OWN_AI, TRIAL_KEY_HELD } from "./trial-credit.ts"; import { createHeldKeys } from "./cloud-held-keys.ts";
import type { ProviderInstance } from "./contracts.ts";
-import { readyToRun, selectDefaultModelSelection, withInstanceConfig, withNewBotEffort, type SelectableInstance } from "./default-model-selection.ts"; import { configIdentity, createTestedAi } from "./tested-ai.ts"; import { instanceIcon } from "./provider-icon.ts";
+import { readyToRun, selectDefaultModelSelection, withInstanceConfig, withNewBotEffort, type SelectableInstance } from "./default-model-selection.ts"; import { configIdentity, createTestedAi } from "./tested-ai.ts"; import { instanceLook } from "./provider-icon.ts";
import { threadModelFallback, type ThreadEngine } from "./thread-model.ts";
import { computerEngineMoveText, removedComputerInstanceIds, writeComputerEngineMoveLines } from "./computer-engine-removal.ts";
import { cancelPeerApprovalsFor, cancelPeerApprovalsForThread, dismissStalePeerCards, peerApprovalFailure, requestPeerApproval, resolvePeerComms, type ApprovalBus } from "./peer-approval.ts";
@@ -11871,7 +11871,7 @@ async function describeInstances() {
const entry = configs[instance.instanceId];
const described = {
...instance, ...testedAi.info(instance), ...engineUpdates.shown(instance.driverKind),
- ...instanceIcon(entry),
+ ...instanceLook(entry),
...(entry?.access ? { access: entry.access } : {}), ...(entry?.driver === "openai-compat" && typeof (entry.config as { replyWaitMinutes?: unknown } | undefined)?.replyWaitMinutes === "number" ? { replyWaitMinutes: (entry.config as { replyWaitMinutes: number }).replyWaitMinutes } : {}), ...(heldKeys?.refusal(instance.instanceId) ? { snapshot: { state: "unavailable" as const, reason: TRIAL_KEY_HELD } } : {}),
};
if (hostedModels) return { ...described, readOnly: true,
diff --git a/server/openai-compat-endpoints.ts b/server/openai-compat-endpoints.ts
index ba42c3a7a2..3440dd0b53 100644
--- a/server/openai-compat-endpoints.ts
+++ b/server/openai-compat-endpoints.ts
@@ -30,7 +30,7 @@ export const addEndpointSchema = z.object({
url: z.string().max(512),
key: z.string().trim().min(1).max(4096),
models: z.array(z.string().trim().min(1).max(200)).max(64).optional(),
- catalog: z.literal("lmstudio").optional(),
+ catalog: z.enum(["lmstudio", "ollama"]).optional(),
}).strict();
export type AddEndpoint = z.infer<typeof addEndpointSchema>;
diff --git a/server/provider-icon.test.ts b/server/provider-icon.test.ts
index 0acec9e146..abb19d048f 100644
--- a/server/provider-icon.test.ts
+++ b/server/provider-icon.test.ts
@@ -94,6 +94,11 @@ describe("an instance's mark", () => {
expect(instanceIcon(server("https://workspace-123.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"))).toEqual({ icon: { kind: "preset", preset: "qwen" } });
});
+ it("is Ollama's mark for a server on Ollama's port or added as Ollama", () => {
+ expect(instanceIcon(server("http://127.0.0.1:11434/v1"))).toEqual({ icon: { kind: "preset", preset: "ollama" } });
+ expect(instanceIcon({ driver: "openai-compat", config: { url: "http://gpu-box.local:8080/v1", catalog: "ollama" } })).toEqual({ icon: { kind: "preset", preset: "ollama" } });
+ });
+
it("keeps a stored icon, preset or custom, over the server's", () => {
const preset = { kind: "preset", preset: "cohere" } as const;
const custom = { kind: "custom", dataUrl: "data:image/png;base64,iVBORw0KGgo=" } as const;
@@ -105,7 +110,7 @@ describe("an instance's mark", () => {
it("leaves the driver's own mark for an unknown or missing address and for other drivers", () => {
expect(instanceIcon(server("https://llm.example.test/v1"))).toEqual({});
- expect(instanceIcon(server("http://127.0.0.1:11434/v1"))).toEqual({});
+ expect(instanceIcon(server("http://127.0.0.1:1234/v1"))).toEqual({});
expect(instanceIcon(server(42))).toEqual({});
expect(instanceIcon({ driver: "openai-compat" })).toEqual({});
expect(instanceIcon({ driver: "openai-compat", config: null })).toEqual({});
diff --git a/server/provider-icon.ts b/server/provider-icon.ts
index 5bb4bcada3..73d1a63f70 100644
--- a/server/provider-icon.ts
+++ b/server/provider-icon.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
import { persistableInstanceConfigs, type AppConfig } from "./config.ts";
import type { InstanceConfig } from "./contracts.ts";
import { PROVIDER_ICON_PRESETS, type ProviderIcon, type ProviderIconPreset } from "../shared/provider-icon.ts";
+import { isOllamaServer } from "./drivers/ollama.ts";
const iconSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("preset"), preset: z.enum(PROVIDER_ICON_PRESETS) }).strict(),
@@ -21,7 +22,7 @@ export function withInstanceIcon(cfg: AppConfig, instanceId: string, icon: Provi
}
/** Who runs a server, by its host. `*` is one DNS label, or the rest of one. Only providers we have a mark for:
- * Groq, Together, Fireworks, Ollama and LM Studio servers keep the driver's own mark. */
+ * Groq, Together, Fireworks and LM Studio servers keep the driver's own mark; Ollama isn't told by its host. */
const SERVER_HOSTS: Record<string, ProviderIconPreset> = {
"api.openai.com": "openai", "*.api.openai.com": "openai",
"*.openai.azure.com": "azure", "*.services.ai.azure.com": "azure", "*.cognitiveservices.azure.com": "azure",
@@ -55,11 +56,21 @@ export function serverIconPreset(url: string): ProviderIconPreset | undefined {
return SERVER_MARKS.find(([pattern]) => pattern.test(host))?.[1];
}
+const servesOllama = (entry: InstanceConfig | undefined) => entry?.driver === "openai-compat" && isOllamaServer(entry.config);
+
/** The mark an instance shows everywhere the instance list goes: a stored icon (set before v0.1.102) wins; an
* OpenAI-compatible server otherwise shows the mark of whoever runs it; anything else keeps its driver's mark. */
export function instanceIcon(entry: InstanceConfig | undefined): { icon?: ProviderIcon } {
if (entry?.icon) return { icon: entry.icon };
+ if (servesOllama(entry)) return { icon: { kind: "preset", preset: "ollama" } };
const url = entry?.driver === "openai-compat" ? (entry.config as { url?: unknown } | undefined)?.url : undefined;
const preset = typeof url === "string" ? serverIconPreset(url) : undefined;
return preset ? { icon: { kind: "preset", preset } } : {};
}
+
+/** How the instance list shows an instance: its mark, and for an OpenAI-compatible server that is really Ollama,
+ * `serverKind` and Ollama's name in place of the driver's own (a name someone gave it stays). */
+export function instanceLook(entry: InstanceConfig | undefined): { icon?: ProviderIcon; serverKind?: "ollama"; displayName?: string } {
+ if (!servesOllama(entry)) return instanceIcon(entry);
+ return { ...instanceIcon(entry), serverKind: "ollama", ...(entry!.displayName ? {} : { displayName: "Ollama" }) };
+}
diff --git a/shared/local-model.ts b/shared/local-model.ts
new file mode 100644
index 0000000000..66fd80975d
--- /dev/null
+++ b/shared/local-model.ts
@@ -0,0 +1,9 @@
+/** A model a server on this machine or network holds, as that server describes it: bytes on disk, parameter count
+ * and quantization in its own words, and whether it can call tools or see images when it says. */
+export interface LocalModelFacts {
+ bytes?: number;
+ parameters?: string;
+ quantization?: string;
+ tools?: boolean;
+ vision?: boolean;
+}
diff --git a/shared/provider-icon.ts b/shared/provider-icon.ts
index c4fdee23f4..ef6e9170a7 100644
--- a/shared/provider-icon.ts
+++ b/shared/provider-icon.ts
@@ -1,6 +1,6 @@
export const PROVIDER_ICON_PRESETS = [
"openai", "anthropic", "google", "azure", "aws", "xai", "deepseek",
- "meta", "mistral", "qwen", "moonshot", "cohere", "openrouter",
+ "meta", "mistral", "qwen", "moonshot", "cohere", "openrouter", "ollama",
] as const;
export type ProviderIconPreset = typeof PROVIDER_ICON_PRESETS[number];
@@ -27,6 +27,7 @@ export const PROVIDER_ICON_LABELS: Record<ProviderIconPreset, string> = {
moonshot: "Moonshot AI",
cohere: "Cohere",
openrouter: "OpenRouter",
+ ollama: "Ollama",
};
function decodedBase64Bytes(value: string): number {
diff --git a/src/components/EngineSetup.test.ts b/src/components/EngineSetup.test.ts
index 8ce721f8db..6beacddfca 100644
--- a/src/components/EngineSetup.test.ts
+++ b/src/components/EngineSetup.test.ts
@@ -350,3 +350,18 @@ describe("API-key engine setup", () => {
expect(render(instance({ state: "unavailable", reason: "`kimi` CLI not found" }))).not.toContain("data-engine-setup-api-key");
});
});
+
+describe("Ollama setup", () => {
+ it("says why Ollama can't answer instead of asking for an API key", () => {
+ vi.stubGlobal("window", { ogb: { platform: "darwin" } });
+ const reason = "Ollama isn't running at http://127.0.0.1:11434. Open the Ollama app or run `ollama serve`.";
+ const ollama: InstanceInfo = {
+ instanceId: "openaiCompat", driverKind: "openai-compat", displayName: "Ollama", access: "api", serverKind: "ollama",
+ models: { default: "", options: [] }, snapshot: { state: "unavailable", reason },
+ install: { docsUrl: "https://openrouter.ai/keys", settings: "connections", signInCommand: "Save an OpenAI-compatible API key." },
+ };
+ const markup = renderToStaticMarkup(createElement(StoreProvider, null, createElement(EngineSetup, { instance: ollama })));
+ expect(markup).toContain("Ollama isn&#x27;t running at http://127.0.0.1:11434");
+ expect(markup).not.toContain("API key");
+ });
+});
diff --git a/src/components/EngineSetup.tsx b/src/components/EngineSetup.tsx
index 370fd0425d..dc101d41d3 100644
--- a/src/components/EngineSetup.tsx
+++ b/src/components/EngineSetup.tsx
@@ -411,7 +411,7 @@ export function hasSavedApiKey(instance: InstanceInfo): boolean {
}
function apiKeySetup(instance: InstanceInfo): boolean {
- if (!(isApiKeyEngine(instance) || instance.install?.settings === "connections") || instance.snapshot.authenticationUnavailableReason) return false;
+ if (!(isApiKeyEngine(instance) || instance.install?.settings === "connections") || instance.snapshot.authenticationUnavailableReason || instance.serverKind === "ollama") return false;
// A key engine with its own CLI (DeepSeek Harness) is installed first, then given the key.
if (instance.snapshot.state !== "available") return !installCommandFor(instance.install);
return instance.snapshot.authenticated === false;
@@ -582,7 +582,7 @@ export function EngineSetup({
return <GrokKeyInstead className={className} unframed={unframed} />;
}
- if (!install || instance.snapshot.authenticationUnavailableReason) {
+ if (!install || instance.snapshot.authenticationUnavailableReason || instance.serverKind === "ollama") {
return (
<div className={cn(!unframed && "rounded-xl border border-hairline/40 bg-control/30 p-3", className)}>
<div className="text-[13px] font-semibold text-ink">{t("engineSetup.notReady", { name: engineDisplayName(instance) })}</div>
diff --git a/src/components/ProviderIcons.tsx b/src/components/ProviderIcons.tsx
index 066214d696..a4d1d490a2 100644
--- a/src/components/ProviderIcons.tsx
+++ b/src/components/ProviderIcons.tsx
@@ -204,8 +204,8 @@ export function ProviderMark({ driverKind, size, className }: IconProps & { driv
/** Built-in provider identities for an instance override. Existing driver
* marks remain the source of truth whenever no override is configured.
- * Paths for Gemini, Azure, AWS, DeepSeek, Meta, Mistral, and OpenRouter are
- * from Simple Icons (CC0 1.0). The Cohere path is from Lobe Icons (MIT). */
+ * Paths for Gemini, Azure, AWS, DeepSeek, Meta, Mistral, Ollama, and OpenRouter
+ * are from Simple Icons (CC0 1.0). The Cohere path is from Lobe Icons (MIT). */
export function PresetProviderMark({ preset, size = 16, className }: IconProps & { preset: ProviderIconPreset }) {
switch (preset) {
case "openai": return <CodexMark size={size} className={className} />;
@@ -234,6 +234,8 @@ export function PresetProviderMark({ preset, size = 16, className }: IconProps &
return <svg width={size} height={size} viewBox="0 0 24 24" className={className} aria-hidden="true"><path fill="#94A3B8" d="M16.778 1.844v1.919q-.569-.026-1.138-.032-.708-.008-1.415.037c-1.93.126-4.023.728-6.149 2.237-2.911 2.066-2.731 1.95-4.14 2.75-.792.447-2.497.904-3.936 1.131v4.229c1.31.184 2.908.627 3.795 1.132 1.41.798 1.228.683 4.14 2.75 2.126 1.509 4.22 2.11 6.148 2.236.88.058 1.716.041 2.555.005v1.918L24 15.038l-7.222-4.17v2.176c-.86.038-1.611.065-2.278.021-1.364-.09-2.417-.357-3.979-1.465-2.244-1.593-2.866-2.027-3.68-2.508.889-.518 1.449-.906 3.822-2.59 1.56-1.109 2.614-1.377 3.978-1.466.667-.044 1.418-.017 2.278.02v2.176L24 6.014Z" /></svg>;
case "deepseek":
return <DeepSeekMark size={size} className={className} />;
+ case "ollama":
+ return <svg width={size} height={size} viewBox="0 0 24 24" className={className} aria-hidden="true"><path fill="var(--color-ink)" d="M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z" /></svg>;
}
}
diff --git a/src/components/SimpleModelMenu.tsx b/src/components/SimpleModelMenu.tsx
index 24d97f6de9..f116c9eb57 100644
--- a/src/components/SimpleModelMenu.tsx
+++ b/src/components/SimpleModelMenu.tsx
@@ -60,8 +60,8 @@ function MenuModel({ instance, row, onPick }: { instance: InstanceInfo; row: Men
data-org-blocked={row.blocked || undefined}
disabled={row.blocked}
aria-pressed={row.current}
- aria-label={[modelOptionLabel(option), option.provider, reason].filter(Boolean).join(" · ")}
- title={[modelOptionLabel(option), option.provider, reason].filter(Boolean).join(" · ")}
+ aria-label={[modelOptionLabel(option), option.provider, row.detail, reason].filter(Boolean).join(" · ")}
+ title={[modelOptionLabel(option), option.provider, row.detail, reason].filter(Boolean).join(" · ")}
tabIndex={-1}
onClick={() => onPick(instance, row.model ?? option.id, row.variant)}
className={SIMPLE_MENU_ROW}
@@ -69,6 +69,7 @@ function MenuModel({ instance, row, onPick }: { instance: InstanceInfo; row: Men
<Gutter />
<RowLines label={row.label}>
{row.route && <span data-simple-route className={SIMPLE_MENU_META}>{row.route}</span>}
+ {row.detail && <span data-simple-model-detail className={SIMPLE_MENU_META}>{row.detail}</span>}
{reason && <span data-simple-org-blocked className={SIMPLE_MENU_META}>{reason}</span>}
</RowLines>
{row.current && <Check size={14} className="shrink-0 text-ink" aria-hidden="true" />}
diff --git a/src/components/provider-mark-fade.ts b/src/components/provider-mark-fade.ts
index 8f92ca6a0a..8d1603f317 100644
--- a/src/components/provider-mark-fade.ts
+++ b/src/components/provider-mark-fade.ts
@@ -3,7 +3,7 @@ import type { InstanceInfo } from "@/state/store";
export type ProviderMarkTone = "brand" | "mono";
const BRAND_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "mistral", "meta", "museCode", "kimiAgent", "qwenAgent", "deepseekAgent", "greenference", "kiroAgent"]);
-const MONO_PRESETS: ReadonlySet<string> = new Set(["openai", "xai"]);
+const MONO_PRESETS: ReadonlySet<string> = new Set(["openai", "xai", "ollama"]);
export function providerMarkTone(instance: Pick<InstanceInfo, "driverKind" | "icon">): ProviderMarkTone {
if (instance.icon?.kind === "custom") return "brand";
diff --git a/src/lib/local-model.ts b/src/lib/local-model.ts
new file mode 100644
index 0000000000..d91c3298b5
--- /dev/null
+++ b/src/lib/local-model.ts
@@ -0,0 +1,12 @@
+import type { LocalModelFacts } from "../../shared/local-model";
+import { intlLocale, t } from "./i18n";
+
+/** "3.2B · Q4_K_M · 2 GB": what a local server says about a model, sizes in decimal units as Ollama's own list shows them. */
+export function localModelDetail(facts: LocalModelFacts | undefined): string | undefined {
+ if (!facts) return undefined;
+ const size = facts.bytes ? new Intl.NumberFormat(intlLocale(), {
+ style: "unit", unit: facts.bytes >= 1e9 ? "gigabyte" : "megabyte", unitDisplay: "short", maximumFractionDigits: 1,
+ }).format(facts.bytes / (facts.bytes >= 1e9 ? 1e9 : 1e6)) : undefined;
+ const parts = [facts.parameters, facts.quantization, size, facts.tools === false ? t("model.local.noTools") : undefined].filter(Boolean);
+ return parts.length ? parts.join(" · ") : undefined;
+}
diff --git a/src/lib/simple-model-menu.test.ts b/src/lib/simple-model-menu.test.ts
index ea446dc353..32b9c628d2 100644
--- a/src/lib/simple-model-menu.test.ts
+++ b/src/lib/simple-model-menu.test.ts
@@ -51,6 +51,32 @@ const rows = (built: Menu, index = 0) => {
};
const body = (built: Menu, index = 0) => built.groups[index]!.body;
+describe("Ollama in the Simple model menu", () => {
+ const ollama = engine("openaiCompat", "openai-compat", "Ollama", "api", [
+ { id: "llama3.2:latest", label: "llama3.2:latest", custom: true, local: { bytes: 2_019_393_189, parameters: "3.2B", quantization: "Q4_K_M", tools: true } },
+ { id: "gemma2:2b", label: "gemma2:2b", custom: true, local: { bytes: 912_000_000, parameters: "2.6B", tools: false } },
+ ], { serverKind: "ollama" });
+
+ it("is headed Ollama, with no API key, and says what each pulled model is", () => {
+ const built = menu([ollama], { selection: { instanceId: "openaiCompat", model: "" } });
+ expect(built.groups.map((group) => group.label)).toEqual(["Ollama"]);
+ const body = built.groups[0]!.body;
+ expect(body.kind === "models" && body.rows.map((row) => [row.label, row.detail])).toEqual([
+ ["llama3.2:latest", "3.2B · Q4_K_M · 2 GB"],
+ ["gemma2:2b", "2.6B · 912 MB · No tools"],
+ ]);
+ });
+
+ it("says what the selected model is too", () => {
+ const built = menu([ollama], { selection: { instanceId: "openaiCompat", model: "gemma2:2b" } });
+ expect(built.current).toMatchObject({ label: "gemma2:2b", meta: "2.6B · 912 MB · No tools", title: "Ollama · gemma2:2b · 2.6B · 912 MB · No tools" });
+ });
+
+ it("keeps the API key heading for another OpenAI-compatible server", () => {
+ expect(menu([openaiKey]).groups.map((group) => group.label)).toEqual(["OpenAI · API key"]);
+ });
+});
+
describe("the Simple model menu", () => {
it("puts the current model on top, then the rest of its provider under a heading, in short names", () => {
const built = menu([claude()]);
diff --git a/src/lib/simple-model-menu.ts b/src/lib/simple-model-menu.ts
index fa3433b0d7..d69d3a4a8e 100644
--- a/src/lib/simple-model-menu.ts
+++ b/src/lib/simple-model-menu.ts
@@ -4,6 +4,7 @@ import { t } from "./i18n";
import { modelOptionLabel } from "./model-label";
import { filterCustomModels, partitionCustomModels, suggestedModels } from "./custom-models";
import { engineDisplayName, isCustomOnly, SIGN_IN_FAMILY_LABEL, signInFamily, splitEngineRail } from "./engine-rail";
+import { localModelDetail } from "./local-model";
import { displayModelLabel, shortModelLabel } from "./model-friendly";
import { choiceIsSelected, modelChoices, takesTypedModels, type ModelChoice } from "./model-choices";
@@ -19,6 +20,8 @@ export interface MenuModelRow {
variant?: string;
label: string;
route?: string;
+ /** What a local server says about the model: parameters, quantization, size. */
+ detail?: string;
current: boolean;
blocked: boolean;
}
@@ -128,6 +131,7 @@ function localFrom(rows: readonly MenuModelRow[], mixed: boolean): number | null
function heading(instance: InstanceInfo, listed: readonly InstanceInfo[]): Pick<MenuGroup, "label" | "provider" | "account"> {
const provider = providerName(instance);
const family = signInFamily(instance);
+ if (instance.serverKind === "ollama") return { label: provider, provider };
if (instance.access === "api") return { label: `${provider} · ${t("model.simple.apiKey")}`, provider };
const several = family !== undefined && listed.filter((other) => signInFamily(other) === family).length > 1;
const account = several && engineDisplayName(instance) !== provider ? engineDisplayName(instance) : undefined;
@@ -139,7 +143,8 @@ function currentRow(input: SimpleMenuInput): MenuCurrent {
const active = instances.find((instance) => instance.instanceId === selection.instanceId);
const option = active?.models.options.find((candidate) => candidate.id === selection.model);
const name = option ? modelOptionLabel(option) : selection.model;
- const row = { instance: active, label: modelName(active, selection.model, selection.variant), title: active ? `${engineDisplayName(active)} · ${name}${variantSuffix(active, selection.model, selection.variant)}` : name, warning: false, pending: false };
+ const detail = localModelDetail(option?.local);
+ const row = { instance: active, label: modelName(active, selection.model, selection.variant), title: `${active ? `${engineDisplayName(active)} · ${name}${variantSuffix(active, selection.model, selection.variant)}` : name}${detail ? ` · ${detail}` : ""}`, warning: false, pending: false };
if (!active) return loading ? { ...row, pending: true } : { ...row, meta: t("model.simple.unavailable"), warning: true };
if (!option && input.refreshing === active.instanceId) return { ...row, pending: true };
if (option?.orgBlocked) return { ...row, meta: t("model.orgBlocked"), warning: true, blocked: true };
@@ -150,7 +155,7 @@ function currentRow(input: SimpleMenuInput): MenuCurrent {
const family = signInFamily(active);
const accounts = family ? instances.filter((instance) => signInFamily(instance) === family).length : 0;
if (accounts > 1 || active.snapshot.chatgptPlan) return { ...row, meta: engineDisplayName(active) };
- return option?.provider ? { ...row, meta: option.provider } : row;
+ return option?.provider || detail ? { ...row, meta: option?.provider ?? detail } : row;
}
export function simpleModelMenu(input: SimpleMenuInput): SimpleMenu {
@@ -172,15 +177,19 @@ export function simpleModelMenu(input: SimpleMenuInput): SimpleMenu {
const currentSelection = instance.instanceId === selection.instanceId ? selection : undefined;
const repeated = repeatedModelLabels(all);
const botSelection = bot.follows === false && bot.selection.instanceId === instance.instanceId ? bot.selection : undefined;
- const row = (option: ModelChoice): MenuModelRow => ({
- option,
- ...(option.nativeModel ? { model: option.nativeModel } : {}),
- ...(option.variant ? { variant: option.variant } : {}),
- label: shortModelLabel(modelOptionLabel(option), provider),
- ...(repeated.has(option.label) && option.provider ? { route: option.provider } : {}),
- current: currentSelection ? choiceIsSelected(option, currentSelection) : false,
- blocked: option.orgBlocked === true,
- });
+ const row = (option: ModelChoice): MenuModelRow => {
+ const detail = localModelDetail(option.local);
+ return {
+ option,
+ ...(option.nativeModel ? { model: option.nativeModel } : {}),
+ ...(option.variant ? { variant: option.variant } : {}),
+ label: shortModelLabel(modelOptionLabel(option), provider),
+ ...(repeated.has(option.label) && option.provider ? { route: option.provider } : {}),
+ ...(detail ? { detail } : {}),
+ current: currentSelection ? choiceIsSelected(option, currentSelection) : false,
+ blocked: option.orgBlocked === true,
+ };
+ };
const mixed = own.length > 0 && own.length < all.length;
if (query) {
const rows = filterCustomModels(all, query).map(row);
diff --git a/src/locales/en.json b/src/locales/en.json
index 7c35949f3f..d0eb2dfb9b 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -3111,6 +3111,7 @@
"model.refreshTitle": "Refresh models",
"model.unconfirmed": "{name} hasn't listed its models yet. These may be out of date.",
"model.localModels": "Local models",
+ "model.local.noTools": "No tools",
"model.localHint": "Run this agent with a model already on your machine.",
"model.apiKeyHint": "Runs on your API key. The provider bills you for what it uses.",
"model.chooseHint": "Choose a model for this bot.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index b1cb6ce84c..b3488299c2 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2981,6 +2981,7 @@
"model.refreshTitle": "Atualizar os modelos",
"model.unconfirmed": "{name} ainda não informou quais modelos oferece. Esta lista pode estar desatualizada.",
"model.localModels": "Modelos locais",
+ "model.local.noTools": "Sem ferramentas",
"model.localHint": "Rode este agente com um modelo que já está na sua máquina.",
"model.apiKeyHint": "Usa sua chave de API. O provedor cobra pelo uso.",
"model.chooseHint": "Escolha um modelo para este bot.",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index cf6b3b7e00..202856078f 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -458,7 +458,7 @@ export interface InstanceInfo extends InstanceEndpointInfo {
instanceId: string;
driverKind: string;
displayName: string;
- icon?: import("../../shared/provider-icon").ProviderIcon;
+ icon?: import("../../shared/provider-icon").ProviderIcon; /** An OpenAI-compatible server recognised as Ollama. */ serverKind?: "ollama";
readOnly?: boolean;
trialCredit?: "active" | "used_up" | "ended";
managed?: { organizationId: string; organizationName: string };
@@ -481,7 +481,7 @@ export interface InstanceInfo extends InstanceEndpointInfo {
aiTest?: import("../../shared/ai-ranking").AiTestState;
/** Why it didn't answer, in plain words, when it said (signed out, a used-up limit…). */
aiTestError?: string;
- models: { default: string; options: Array<{ id: string; label: string; custom?: boolean; loaded?: boolean; provider?: string; variants?: ModelVariantOption[]; orgBlocked?: true }> };
+ models: { default: string; options: Array<{ id: string; label: string; custom?: boolean; loaded?: boolean; provider?: string; variants?: ModelVariantOption[]; orgBlocked?: true; local?: import("../../shared/local-model").LocalModelFacts }> };
capabilities?: {
computerMcp?: boolean;
agentsMcp?: boolean;