diff --git a/apps/sim/app/api/providers/ollama/models/route.test.ts b/apps/sim/app/api/providers/ollama/models/route.test.ts index c815c43c360..0ff9e7c3d6d 100644 --- a/apps/sim/app/api/providers/ollama/models/route.test.ts +++ b/apps/sim/app/api/providers/ollama/models/route.test.ts @@ -1,6 +1,6 @@ import { createMockRequest, resetEnvFlagsMock, setEnvFlags } from '@sim/testing' +import { setEnv } from '@sim/testing/mocks/env.mock' import { providersUtilsMock, providersUtilsMockFns } from '@sim/testing/mocks/providers-utils.mock' -import { urlsMockFns } from '@sim/testing/mocks/urls.mock' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' const mockFetch = vi.hoisted(() => vi.fn()) @@ -10,13 +10,12 @@ vi.mock('@/providers/utils', () => providersUtilsMock) import { GET } from '@/app/api/providers/ollama/models/route' const { mockFilterBlacklistedModels, mockIsProviderBlacklisted } = providersUtilsMockFns -const mockIsOllamaUrlConfigured = urlsMockFns.mockIsOllamaUrlConfigured const request = () => createMockRequest('GET') describe('ollama models route', () => { beforeEach(() => { - mockIsOllamaUrlConfigured.mockReturnValue(false) + setEnv({ OLLAMA_URL: undefined }) mockIsProviderBlacklisted.mockReturnValue(false) mockFilterBlacklistedModels.mockImplementation((models: string[]) => models) vi.stubGlobal('fetch', mockFetch) @@ -36,7 +35,7 @@ describe('ollama models route', () => { it('still honours an explicit OLLAMA_URL on the hosted platform', async () => { setEnvFlags({ isHosted: true }) - mockIsOllamaUrlConfigured.mockReturnValue(true) + setEnv({ OLLAMA_URL: 'http://ollama.internal:11434' }) mockFetch.mockResolvedValue({ ok: true, json: async () => ({ models: [{ name: 'llama3' }] }) }) const response = await GET(request()) diff --git a/apps/sim/app/api/providers/ollama/models/route.ts b/apps/sim/app/api/providers/ollama/models/route.ts index 13274f69d6e..f32075c02d9 100644 --- a/apps/sim/app/api/providers/ollama/models/route.ts +++ b/apps/sim/app/api/providers/ollama/models/route.ts @@ -5,10 +5,9 @@ import { ollamaUpstreamResponseSchema, providerModelsResponseSchema, } from '@/lib/api/contracts/providers' -import { isHosted } from '@/lib/core/config/env-flags' -import { getOllamaUrl, isOllamaUrlConfigured } from '@/lib/core/utils/urls' +import { getOllamaUrl, isOllamaAvailable } from '@/lib/core/utils/urls' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { filterBlacklistedModels, isProviderBlacklisted } from '@/providers/utils' +import { filterBlacklistedModels } from '@/providers/utils' const logger = createLogger('OllamaModelsAPI') const OLLAMA_HOST = getOllamaUrl() @@ -17,23 +16,16 @@ const OLLAMA_HOST = getOllamaUrl() * Get available Ollama models */ export const GET = withRouteHandler(async (_request: NextRequest) => { - if (isProviderBlacklisted('ollama')) { - logger.info('Ollama provider is blacklisted, returning empty models') - return NextResponse.json({ models: [] }) - } - /** - * Ollama runs alongside the app it serves, so the hosted platform never has one - * and `OLLAMA_URL`'s loopback default cannot answer there. Skip the probe rather - * than dial an address known to refuse on every poll. - * - * Only the unconfigured default is skipped: an explicit `OLLAMA_URL` states an - * intent to reach a real server and is still honoured. Self-hosted deployments - * are untouched either way, including the localhost default that needs no - * configuration to work. + * Ollama runs alongside the app it serves, so the hosted platform never has one and + * `OLLAMA_URL`'s loopback default cannot answer there: skip the probe rather than dial an + * address known to refuse on every poll. An explicit `OLLAMA_URL` is still honoured, and + * self-hosted deployments probe the localhost default that needs no configuration. */ - if (isHosted && !isOllamaUrlConfigured()) { - logger.info('Ollama is not available on the hosted platform, returning empty models') + if (!isOllamaAvailable()) { + logger.info( + 'Ollama is blacklisted or not configured on this deployment, returning empty models' + ) return NextResponse.json({ models: [] }) } diff --git a/apps/sim/ee/access-requests/lib/catalog-registry.ts b/apps/sim/ee/access-requests/lib/catalog-registry.ts index bb45379fac7..cdb35a5b375 100644 --- a/apps/sim/ee/access-requests/lib/catalog-registry.ts +++ b/apps/sim/ee/access-requests/lib/catalog-registry.ts @@ -3,9 +3,8 @@ import { env } from '@/lib/core/config/env' import { getAllowedIntegrationsFromEnv, getBlacklistedProvidersFromEnv, - isHosted, } from '@/lib/core/config/env-flags' -import { isOllamaUrlConfigured } from '@/lib/core/utils/urls' +import { isOllamaReachable } from '@/lib/core/utils/urls' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { isIntegrationDeploymentAvailableForVisibility, @@ -37,7 +36,7 @@ export interface AccessRequestCatalogContext { } function isProviderDeploymentAvailable(providerId: string): boolean { - if (providerId === 'ollama') return !isHosted || isOllamaUrlConfigured() + if (providerId === 'ollama') return isOllamaReachable() if (providerId === 'vllm') return Boolean(env.VLLM_BASE_URL?.trim()) if (providerId === 'litellm') return Boolean(env.LITELLM_BASE_URL?.trim()) return true diff --git a/apps/sim/ee/access-requests/lib/catalog.test.ts b/apps/sim/ee/access-requests/lib/catalog.test.ts index d73504d5745..271c027a7bb 100644 --- a/apps/sim/ee/access-requests/lib/catalog.test.ts +++ b/apps/sim/ee/access-requests/lib/catalog.test.ts @@ -17,7 +17,7 @@ import { providersModelsMockFns, } from '@sim/testing/mocks/providers-models.mock' import { providersUtilsMock, providersUtilsMockFns } from '@sim/testing/mocks/providers-utils.mock' -import { resetUrlsMock, urlsMockFns } from '@sim/testing/mocks/urls.mock' +import { resetUrlsMock } from '@sim/testing/mocks/urls.mock' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('@/lib/core/config/block-visibility', () => blockVisibilityMock) @@ -111,7 +111,7 @@ setEnvFlags({ isSandboxesEnabled: false, isSsoEnabled: false, }) -urlsMockFns.mockIsOllamaUrlConfigured.mockReturnValue(false) +setEnv({ OLLAMA_URL: undefined }) afterAll(() => { resetEnvMock() diff --git a/apps/sim/lib/core/utils/urls.test.ts b/apps/sim/lib/core/utils/urls.test.ts index b145091223e..455fc635d67 100644 --- a/apps/sim/lib/core/utils/urls.test.ts +++ b/apps/sim/lib/core/utils/urls.test.ts @@ -1,7 +1,9 @@ /** * @vitest-environment jsdom */ + import { envMockFns, setEnv } from '@sim/testing/mocks/env.mock' +import { envFlagsMockFns, resetEnvFlagsMock, setEnvFlags } from '@sim/testing/mocks/env-flags.mock' import { beforeEach, describe, expect, it, vi } from 'vitest' vi.unmock('@/lib/core/utils/urls') @@ -11,6 +13,7 @@ import { getSocketUrl, isLocalhostUrl, isNonCanonicalSimHost, + isOllamaAvailable, isSafeHttpUrl, parseOriginList, } from '@/lib/core/utils/urls' @@ -230,3 +233,26 @@ describe('isNonCanonicalSimHost', () => { expect(isNonCanonicalSimHost('')).toBe(false) }) }) + +describe('isOllamaAvailable', () => { + beforeEach(() => { + resetEnvFlagsMock() + setEnv({ OLLAMA_URL: undefined }) + }) + + it('reaches the loopback default on a self-hosted deployment', () => { + expect(isOllamaAvailable()).toBe(true) + }) + + it('needs OLLAMA_URL on the hosted platform', () => { + setEnvFlags({ isHosted: true }) + expect(isOllamaAvailable()).toBe(false) + setEnv({ OLLAMA_URL: 'http://ollama.internal:11434' }) + expect(isOllamaAvailable()).toBe(true) + }) + + it('is never available when the provider is blacklisted', () => { + envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama']) + expect(isOllamaAvailable()).toBe(false) + }) +}) diff --git a/apps/sim/lib/core/utils/urls.ts b/apps/sim/lib/core/utils/urls.ts index 7283966aa82..144bd84faa1 100644 --- a/apps/sim/lib/core/utils/urls.ts +++ b/apps/sim/lib/core/utils/urls.ts @@ -1,7 +1,7 @@ import { isLoopbackHostname } from '@sim/security/hostnames' import { SIM_SITE_URL } from '@sim/utils/site' import { env, getEnv } from '@/lib/core/config/env' -import { isProd } from '@/lib/core/config/env-flags' +import { getBlacklistedProvidersFromEnv, isHosted, isProd } from '@/lib/core/config/env-flags' /** Canonical base URL for the public-facing marketing site. No trailing slash. */ export const SITE_URL = SIM_SITE_URL @@ -299,6 +299,24 @@ export function getOllamaUrl(): string { * back to the loopback default. Callers use this to tell "someone pointed us at * an Ollama" apart from "nobody configured one". */ -export function isOllamaUrlConfigured(): boolean { +function isOllamaUrlConfigured(): boolean { return Boolean(env.OLLAMA_URL) } + +/** + * Whether this deployment has an Ollama server to talk to. Self-hosted deployments run + * alongside their own Ollama, so the loopback default {@link getOllamaUrl} falls back to is a + * working configuration that needs no env var. Hosted Sim runs none, so there the address + * must be stated or there is nothing to reach. + * + * The chat and embedding model lists, the embedding client and the access-request catalog + * all answer through this, so a picker never lists models its client then refuses. + */ +export function isOllamaReachable(): boolean { + return !isHosted || isOllamaUrlConfigured() +} + +/** Whether Ollama can serve a model here: {@link isOllamaReachable}, and not blacklisted. */ +export function isOllamaAvailable(): boolean { + return !getBlacklistedProvidersFromEnv().includes('ollama') && isOllamaReachable() +} diff --git a/apps/sim/lib/embeddings/client.ts b/apps/sim/lib/embeddings/client.ts index 5da2987e9d0..acdcaaef2c5 100644 --- a/apps/sim/lib/embeddings/client.ts +++ b/apps/sim/lib/embeddings/client.ts @@ -25,7 +25,7 @@ import { readResponseJsonWithLimit, readResponseTextWithLimit, } from '@/lib/core/utils/stream-limits' -import { getOllamaUrl } from '@/lib/core/utils/urls' +import { getOllamaUrl, isOllamaReachable } from '@/lib/core/utils/urls' import { EmbeddingAPIError } from '@/lib/embeddings/api-error' import { DEFAULT_EMBEDDING_MODEL, @@ -38,7 +38,6 @@ import { import { EmbeddingConfigurationError } from '@/lib/embeddings/configuration-error' import { getEmbeddingResponseDiagnostic } from '@/lib/embeddings/error-diagnostics' import { resolveProviderKey } from '@/lib/embeddings/keys' -import { isOllamaServerConfigured } from '@/lib/embeddings/ollama-model-catalog.server' import { DEFAULT_OPENROUTER_EMBEDDING_MODEL } from '@/lib/embeddings/openrouter-models' import { getAdapterFactory } from '@/lib/embeddings/providers' import { @@ -406,7 +405,7 @@ async function resolveProvider( * would have made this stricter than the selector that offers the models. */ if (info.provider === 'ollama') { - if (!isOllamaServerConfigured()) { + if (!isOllamaReachable()) { throw new EmbeddingConfigurationError() } const baseUrl = getOllamaUrl().replace(/\/+$/, '') diff --git a/apps/sim/lib/embeddings/ollama-model-catalog.server.ts b/apps/sim/lib/embeddings/ollama-model-catalog.server.ts index 464b9451f5b..b2598340f02 100644 --- a/apps/sim/lib/embeddings/ollama-model-catalog.server.ts +++ b/apps/sim/lib/embeddings/ollama-model-catalog.server.ts @@ -5,9 +5,8 @@ import { ollamaShowUpstreamResponseSchema, ollamaUpstreamResponseSchema, } from '@/lib/api/contracts/providers' -import { isHosted } from '@/lib/core/config/env-flags' import { readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits' -import { getOllamaUrl, isOllamaUrlConfigured } from '@/lib/core/utils/urls' +import { getOllamaUrl, isOllamaReachable } from '@/lib/core/utils/urls' import { isOllamaEmbeddingModel, ollamaEmbeddingModelName } from '@/lib/embeddings/catalog' const logger = createLogger('OllamaEmbeddingCatalog') @@ -27,22 +26,6 @@ export interface OllamaEmbeddingModel { dimensions?: number } -/** - * Whether this deployment has an Ollama server to talk to. - * - * Self-hosted deployments run alongside their own Ollama, so the loopback - * default `getOllamaUrl` falls back to is a working configuration that needs no - * env var — the same rule the chat provider's model route applies. Hosted Sim - * runs none, so there the address must be stated or there is nothing to reach. - * - * Exported because the selector, this module's width lookup, and the embedding - * client all have to answer it identically: a selector that lists models the - * client then refuses to embed with is worse than either behaviour alone. - */ -export function isOllamaServerConfigured(): boolean { - return !isHosted || isOllamaUrlConfigured() -} - export class OllamaEmbeddingModelNotFoundError extends Error { constructor(model: string) { super( @@ -127,7 +110,7 @@ async function loadOllamaEmbeddingModelCatalog( signal?: AbortSignal ): Promise<{ models: OllamaEmbeddingModel[]; unreachable?: string }> { /** Nothing to dial: an unconfigured hosted deployment has no server to reach. */ - if (!isOllamaServerConfigured()) return { models: [] } + if (!isOllamaReachable()) return { models: [] } let names: string[] try { @@ -191,7 +174,7 @@ export async function getOllamaEmbeddingModelMetadata( const name = isOllamaEmbeddingModel(model) ? ollamaEmbeddingModelName(model) : model if (!name) throw new OllamaEmbeddingModelNotFoundError(model) /** The same rule the selector and the embedding client apply. */ - if (!isOllamaServerConfigured()) { + if (!isOllamaReachable()) { throw new OllamaUnreachableError('OLLAMA_URL is not configured') } diff --git a/apps/sim/lib/model-router/resolve.test.ts b/apps/sim/lib/model-router/resolve.test.ts index 98542cb5202..b1fa4775dcf 100644 --- a/apps/sim/lib/model-router/resolve.test.ts +++ b/apps/sim/lib/model-router/resolve.test.ts @@ -210,7 +210,9 @@ describe('resolveAutoModel', () => { it('falls back when every pool model is denied by workspace permissions', async () => { mockFetchWorker.mockResolvedValue(routerResponse({ choice: '1' })) - mockValidateModelProvider.mockRejectedValue(new Error('provider blocked')) + mockValidateModelProvider.mockImplementation(async (_userId, _workspaceId, model) => { + if (model !== 'sim-auto') throw new Error('provider blocked') + }) const result = await resolveAutoModel({ ctx, blockId: 'b1', @@ -220,4 +222,36 @@ describe('resolveAutoModel', () => { expect(result.model).toBe('claude-sonnet-5') expect(result.decidedBy).toBe('fallback') }) + + it('refuses a denied sim-auto instead of running a pool or fallback model', async () => { + mockFetchWorker.mockResolvedValue(routerResponse({ choice: '1' })) + const denied = new Error('Model sim-auto is not allowed') + mockValidateModelProvider.mockImplementation(async (_userId, _workspaceId, model) => { + if (model === 'sim-auto') throw denied + }) + + await expect( + resolveAutoModel({ + ctx, + blockId: 'b1', + signals: makeSignals(), + fallbackModel: 'claude-sonnet-5', + }) + ).rejects.toBe(denied) + expect(mockFetchWorker).not.toHaveBeenCalled() + + setEnvFlags({ isHosted: false }) + try { + await expect( + resolveAutoModel({ + ctx, + blockId: 'b1', + signals: makeSignals(), + fallbackModel: 'claude-sonnet-5', + }) + ).rejects.toBe(denied) + } finally { + setEnvFlags({ isHosted: true }) + } + }) }) diff --git a/apps/sim/lib/model-router/resolve.ts b/apps/sim/lib/model-router/resolve.ts index 327c4624ad0..6ca74caad39 100644 --- a/apps/sim/lib/model-router/resolve.ts +++ b/apps/sim/lib/model-router/resolve.ts @@ -13,6 +13,7 @@ import { getMothershipBaseURL } from '@/lib/mothership/server/agent-url' import { validateModelProvider } from '@/ee/access-control/utils/permission-check' import type { ExecutionContext } from '@/executor/types' import type { ModelCost } from '@/providers/cost-policy' +import { SIM_AUTO_MODEL_ID } from '@/providers/models' import { getProviderFromModel } from '@/providers/utils' const logger = createLogger('ModelRouter') @@ -248,9 +249,10 @@ async function callModelRouter( /** * Resolves the sim-auto pseudo-model to a concrete model for one block - * execution. Never throws and never fails the workflow: any error, timeout, - * non-hosted deployment, or fully unavailable pool column falls back to - * `fallbackModel` (the block's standard default). Callers must supply the same already-projected + * execution. Like any model check it throws when the workspace's permission group + * denies sim-auto itself or its permission config cannot be loaded. Otherwise it never fails + * the workflow: any error, timeout, non-hosted deployment, or fully unavailable + * pool column falls back to `fallbackModel` (the block's standard default). Callers must supply the same already-projected * model-facing signals they pass to their provider boundary; this router never rescans them. */ export async function resolveAutoModel(args: { @@ -260,6 +262,8 @@ export async function resolveAutoModel(args: { fallbackModel: string }): Promise { const { ctx, blockId, signals, fallbackModel } = args + // Before any fallback: a denied sim-auto must not run as whichever pool or default model is allowed. + await validateModelProvider(ctx.userId, ctx.workspaceId ?? undefined, SIM_AUTO_MODEL_ID, ctx) const fallback: AutoRoutingResult = { model: fallbackModel, tier: null, diff --git a/apps/sim/lib/workflows/editing/validation-models.test.ts b/apps/sim/lib/workflows/editing/validation-models.test.ts index 58b33d7127e..e52b1e40df9 100644 --- a/apps/sim/lib/workflows/editing/validation-models.test.ts +++ b/apps/sim/lib/workflows/editing/validation-models.test.ts @@ -1,4 +1,5 @@ -import { resetEnvFlagsMock, setEnvFlags } from '@sim/testing' +import { setEnv } from '@sim/testing/mocks/env.mock' +import { envFlagsMockFns, resetEnvFlagsMock, setEnvFlags } from '@sim/testing/mocks/env-flags.mock' import type { Mock } from 'vitest' import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest' import { validateInputsForBlock } from '@/lib/workflows/editing/validation' @@ -35,6 +36,8 @@ beforeEach(() => { afterEach(() => { setEnvFlags({ isHosted: false }) + setEnv({ OLLAMA_URL: undefined }) + envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReset().mockImplementation(() => []) }) describe('agent model field', () => { @@ -82,3 +85,56 @@ describe('translate and guardrails model fields', () => { } ) }) + +describe('model ids no provider declares', () => { + const CATALOG_BLOCKS = ['router_v2', 'evaluator', 'translate', 'guardrails'] + + it.each(CATALOG_BLOCKS)( + 'accepts an installed Ollama model on %s where Ollama is reachable', + (blockType) => { + expect(validateModel(blockType, 'llama3.1:8b')).toEqual({ errors: [], model: 'llama3.1:8b' }) + setEnvFlags({ isHosted: true }) + setEnv({ OLLAMA_URL: 'http://ollama.internal:11434' }) + expect(validateModel(blockType, 'qwen3:latest')).toEqual({ + errors: [], + model: 'qwen3:latest', + }) + } + ) + + it.each(CATALOG_BLOCKS)('rejects it on %s on hosted Sim with no Ollama', (blockType) => { + setEnvFlags({ isHosted: true }) + const { errors, model } = validateModel(blockType, 'llama3.1:8b') + expect(model).toBeUndefined() + expect(errors[0]?.error).toContain('Unknown model id') + }) + + it.each(['hhao/qwen2.5-coder-tools', 'hf.co/bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M'])( + 'accepts a namespaced Ollama library name such as %s', + (model) => { + expect(validateModel('router_v2', model)).toEqual({ errors: [], model }) + } + ) + + it.each(['best available model', 'llama3.1:8b:extra', 'model/'])( + 'still rejects %s, which is not an Ollama model name', + (model) => { + const { errors } = validateModel('router_v2', model) + expect(errors[0]?.error).toContain('Unknown model id') + } + ) + + it.each(['claude-sonnet-4.6', 'groq/'])( + 'still rejects %s, which a provider claims, so it never reaches Ollama', + (model) => { + const { errors } = validateModel('router_v2', model) + expect(errors[0]?.error).toContain('Unknown model id') + } + ) + + it('rejects it when the Ollama provider is blacklisted', () => { + envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama']) + const { errors } = validateModel('router_v2', 'llama3.1:8b') + expect(errors[0]?.error).toContain('Unknown model id') + }) +}) diff --git a/apps/sim/lib/workflows/editing/validation.test.ts b/apps/sim/lib/workflows/editing/validation.test.ts index 5926a2a2343..6838c8beb74 100644 --- a/apps/sim/lib/workflows/editing/validation.test.ts +++ b/apps/sim/lib/workflows/editing/validation.test.ts @@ -723,7 +723,6 @@ describe('validateInputsForBlock', () => { 'nvidia/', 'ollama/', 'ollama-cloud/', - 'unknown/model', ])('rejects incomplete or unsupported cloud namespaces: %s', (model) => { const result = validateInputsForBlock('agent', { model }, 'agent-1') expect(result.validInputs.model).toBeUndefined() diff --git a/apps/sim/lib/workflows/editing/validation.ts b/apps/sim/lib/workflows/editing/validation.ts index 94855ca6b2a..57a4b7b0854 100644 --- a/apps/sim/lib/workflows/editing/validation.ts +++ b/apps/sim/lib/workflows/editing/validation.ts @@ -9,6 +9,7 @@ import { resolveCanonicalMode, } from '@sim/workflow-code/catalog/canonical-index' import { isHosted as isHostedDeployment } from '@/lib/core/config/env-flags' +import { isOllamaAvailable } from '@/lib/core/utils/urls' import { isIntegrationDeploymentAvailableForVisibility } from '@/lib/integrations/availability.server' import { mcpOperationPolicySchema } from '@/lib/mcp/operation-policy' import { MCP_SERVER_ADVANCED_TOOL_TYPE } from '@/lib/mcp/shared' @@ -44,6 +45,7 @@ import { MODEL_OPTION_SOURCES } from '@/blocks/utils' import { overlayVisibility } from '@/blocks/visibility/context' import { BlockType, EDGE, normalizeName } from '@/executor/constants' import { + findProviderFromModel, getHostedModels, isAutoModel, isCustomModelId, @@ -587,6 +589,9 @@ function isStoredFile(value: unknown): boolean { return isPlainRecord(value) && Boolean(value.name) && Boolean(value.path) } +/** An Ollama model name: `[namespace/]name[:tag]`, e.g. `llama3.1:8b` or `hf.co/org/model:Q4_K_M`. */ +const OLLAMA_MODEL_NAME = /^[\w.-]+(\/[\w.-]+)*(:[\w.-]+)?$/ + /** * Validates a value against its expected subBlock type * Returns validation result with the value or an error @@ -998,10 +1003,22 @@ export function validateValueForSubBlockType( } // sim-auto is valid only where the source offers Auto, which it does on hosted Sim // only; writes of it anywhere else are rejected as unknown. - if (isAutoModel(trimmed) && modelSource.auto && isHostedDeployment) { + const isAuto = isAutoModel(trimmed) + if (isAuto && modelSource.auto && isHostedDeployment) { return { valid: true, value: trimmed.toLowerCase() } } - if (trimmed !== '' && !isKnownModelId(trimmed) && !isCustomModelId(trimmed)) { + // An id no provider claims runs on Ollama (`getProviderFromModel`'s default), so + // wherever an Ollama server is reachable an Ollama-shaped name may be a locally + // installed model. The server cannot list what is installed, so a mistyped name of + // that shape fails at execution instead. sim-auto is never one: it never reaches a + // provider as itself. + const isUnknown = !isKnownModelId(trimmed) && !isCustomModelId(trimmed) + const mayBeLocalModel = + !isAuto && + OLLAMA_MODEL_NAME.test(trimmed) && + findProviderFromModel(trimmed) === null && + isOllamaAvailable() + if (trimmed !== '' && isUnknown && !mayBeLocalModel) { const suggestions = suggestModelIdsForUnknownModel(trimmed) const suggestionText = suggestions.length > 0 ? ` Valid options include: ${suggestions.join(', ')}.` : '' diff --git a/packages/testing/src/mocks/urls.mock.ts b/packages/testing/src/mocks/urls.mock.ts index 51746a394c6..6fb4ab68bf7 100644 --- a/packages/testing/src/mocks/urls.mock.ts +++ b/packages/testing/src/mocks/urls.mock.ts @@ -163,8 +163,15 @@ function getOllamaUrlImpl(): string { return (typeof value === 'string' && value) || DEFAULT_OLLAMA_URL } -function isOllamaUrlConfiguredImpl(): boolean { - return Boolean(mockEnvObject.OLLAMA_URL) +function isOllamaReachableImpl(): boolean { + return !envFlagsMock.isHosted || Boolean(mockEnvObject.OLLAMA_URL) +} + +function isOllamaAvailableImpl(): boolean { + return ( + !envFlagsMock.getBlacklistedProvidersFromEnv().includes('ollama') && + urlsMockFns.mockIsOllamaReachable() + ) } /** @@ -195,7 +202,8 @@ export const urlsMockFns = { mockGetSocketServerUrl: vi.fn(getSocketServerUrlImpl), mockGetSocketUrl: vi.fn(getSocketUrlImpl), mockGetOllamaUrl: vi.fn(getOllamaUrlImpl), - mockIsOllamaUrlConfigured: vi.fn(isOllamaUrlConfiguredImpl), + mockIsOllamaReachable: vi.fn(isOllamaReachableImpl), + mockIsOllamaAvailable: vi.fn(isOllamaAvailableImpl), } /** @@ -217,7 +225,8 @@ export function resetUrlsMock(): void { urlsMockFns.mockGetSocketServerUrl.mockReset().mockImplementation(getSocketServerUrlImpl) urlsMockFns.mockGetSocketUrl.mockReset().mockImplementation(getSocketUrlImpl) urlsMockFns.mockGetOllamaUrl.mockReset().mockImplementation(getOllamaUrlImpl) - urlsMockFns.mockIsOllamaUrlConfigured.mockReset().mockImplementation(isOllamaUrlConfiguredImpl) + urlsMockFns.mockIsOllamaReachable.mockReset().mockImplementation(isOllamaReachableImpl) + urlsMockFns.mockIsOllamaAvailable.mockReset().mockImplementation(isOllamaAvailableImpl) } /** @@ -247,5 +256,6 @@ export const urlsMock = { getSocketServerUrl: urlsMockFns.mockGetSocketServerUrl, getSocketUrl: urlsMockFns.mockGetSocketUrl, getOllamaUrl: urlsMockFns.mockGetOllamaUrl, - isOllamaUrlConfigured: urlsMockFns.mockIsOllamaUrlConfigured, + isOllamaReachable: urlsMockFns.mockIsOllamaReachable, + isOllamaAvailable: urlsMockFns.mockIsOllamaAvailable, }