Skip to content

Commit 4c7ad8c

Browse files
authored
fix(models): accept models ollama can serve and refuse a denied sim-auto (#10341)
* fix(models): accept models ollama can serve and refuse a denied sim-auto The editing validator rejected any model id outside the static catalog on the router, evaluator, translate and guardrails blocks. At runtime an id that no provider claims runs on Ollama, so a locally installed model (llama3.1:8b, user/model library names) could not be written by an edit, the workflow-state API or workflow-as-code, and replacing a workflow that already used one failed outright. Where Ollama can serve a model (reachable and not blacklisted), the validator now accepts an Ollama-shaped name that no provider claims, mirroring the runtime. Ids a provider claims, free text, and sim-auto are still rejected. Whether this deployment can reach Ollama is now one helper, isOllamaReachable, used by the chat and embedding model lists, the embedding client and the access-request catalog, which each restated it. resolveAutoModel now checks the configured sim-auto against the workspace's permission group before routing. A group that denied sim-auto still ran it as whichever pool or default model it allowed; the editor already hid Auto for such a group, and execution now refuses it the same way it refuses any other denied model. * fix(models): keep the ollama url check private and import mocks directly
1 parent 4c65d95 commit 4c7ad8c

14 files changed

Lines changed: 201 additions & 65 deletions

File tree

‎apps/sim/app/api/providers/ollama/models/route.test.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { createMockRequest, resetEnvFlagsMock, setEnvFlags } from '@sim/testing'
2+
import { setEnv } from '@sim/testing/mocks/env.mock'
23
import { providersUtilsMock, providersUtilsMockFns } from '@sim/testing/mocks/providers-utils.mock'
3-
import { urlsMockFns } from '@sim/testing/mocks/urls.mock'
44
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
55

66
const mockFetch = vi.hoisted(() => vi.fn())
@@ -10,13 +10,12 @@ vi.mock('@/providers/utils', () => providersUtilsMock)
1010
import { GET } from '@/app/api/providers/ollama/models/route'
1111

1212
const { mockFilterBlacklistedModels, mockIsProviderBlacklisted } = providersUtilsMockFns
13-
const mockIsOllamaUrlConfigured = urlsMockFns.mockIsOllamaUrlConfigured
1413

1514
const request = () => createMockRequest('GET')
1615

1716
describe('ollama models route', () => {
1817
beforeEach(() => {
19-
mockIsOllamaUrlConfigured.mockReturnValue(false)
18+
setEnv({ OLLAMA_URL: undefined })
2019
mockIsProviderBlacklisted.mockReturnValue(false)
2120
mockFilterBlacklistedModels.mockImplementation((models: string[]) => models)
2221
vi.stubGlobal('fetch', mockFetch)
@@ -36,7 +35,7 @@ describe('ollama models route', () => {
3635

3736
it('still honours an explicit OLLAMA_URL on the hosted platform', async () => {
3837
setEnvFlags({ isHosted: true })
39-
mockIsOllamaUrlConfigured.mockReturnValue(true)
38+
setEnv({ OLLAMA_URL: 'http://ollama.internal:11434' })
4039
mockFetch.mockResolvedValue({ ok: true, json: async () => ({ models: [{ name: 'llama3' }] }) })
4140

4241
const response = await GET(request())

‎apps/sim/app/api/providers/ollama/models/route.ts‎

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@ import {
55
ollamaUpstreamResponseSchema,
66
providerModelsResponseSchema,
77
} from '@/lib/api/contracts/providers'
8-
import { isHosted } from '@/lib/core/config/env-flags'
9-
import { getOllamaUrl, isOllamaUrlConfigured } from '@/lib/core/utils/urls'
8+
import { getOllamaUrl, isOllamaAvailable } from '@/lib/core/utils/urls'
109
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
11-
import { filterBlacklistedModels, isProviderBlacklisted } from '@/providers/utils'
10+
import { filterBlacklistedModels } from '@/providers/utils'
1211

1312
const logger = createLogger('OllamaModelsAPI')
1413
const OLLAMA_HOST = getOllamaUrl()
@@ -17,23 +16,16 @@ const OLLAMA_HOST = getOllamaUrl()
1716
* Get available Ollama models
1817
*/
1918
export const GET = withRouteHandler(async (_request: NextRequest) => {
20-
if (isProviderBlacklisted('ollama')) {
21-
logger.info('Ollama provider is blacklisted, returning empty models')
22-
return NextResponse.json({ models: [] })
23-
}
24-
2519
/**
26-
* Ollama runs alongside the app it serves, so the hosted platform never has one
27-
* and `OLLAMA_URL`'s loopback default cannot answer there. Skip the probe rather
28-
* than dial an address known to refuse on every poll.
29-
*
30-
* Only the unconfigured default is skipped: an explicit `OLLAMA_URL` states an
31-
* intent to reach a real server and is still honoured. Self-hosted deployments
32-
* are untouched either way, including the localhost default that needs no
33-
* configuration to work.
20+
* Ollama runs alongside the app it serves, so the hosted platform never has one and
21+
* `OLLAMA_URL`'s loopback default cannot answer there: skip the probe rather than dial an
22+
* address known to refuse on every poll. An explicit `OLLAMA_URL` is still honoured, and
23+
* self-hosted deployments probe the localhost default that needs no configuration.
3424
*/
35-
if (isHosted && !isOllamaUrlConfigured()) {
36-
logger.info('Ollama is not available on the hosted platform, returning empty models')
25+
if (!isOllamaAvailable()) {
26+
logger.info(
27+
'Ollama is blacklisted or not configured on this deployment, returning empty models'
28+
)
3729
return NextResponse.json({ models: [] })
3830
}
3931

‎apps/sim/ee/access-requests/lib/catalog-registry.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ import { env } from '@/lib/core/config/env'
33
import {
44
getAllowedIntegrationsFromEnv,
55
getBlacklistedProvidersFromEnv,
6-
isHosted,
76
} from '@/lib/core/config/env-flags'
8-
import { isOllamaUrlConfigured } from '@/lib/core/utils/urls'
7+
import { isOllamaReachable } from '@/lib/core/utils/urls'
98
import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability'
109
import {
1110
isIntegrationDeploymentAvailableForVisibility,
@@ -37,7 +36,7 @@ export interface AccessRequestCatalogContext {
3736
}
3837

3938
function isProviderDeploymentAvailable(providerId: string): boolean {
40-
if (providerId === 'ollama') return !isHosted || isOllamaUrlConfigured()
39+
if (providerId === 'ollama') return isOllamaReachable()
4140
if (providerId === 'vllm') return Boolean(env.VLLM_BASE_URL?.trim())
4241
if (providerId === 'litellm') return Boolean(env.LITELLM_BASE_URL?.trim())
4342
return true

‎apps/sim/ee/access-requests/lib/catalog.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
providersModelsMockFns,
1818
} from '@sim/testing/mocks/providers-models.mock'
1919
import { providersUtilsMock, providersUtilsMockFns } from '@sim/testing/mocks/providers-utils.mock'
20-
import { resetUrlsMock, urlsMockFns } from '@sim/testing/mocks/urls.mock'
20+
import { resetUrlsMock } from '@sim/testing/mocks/urls.mock'
2121
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
2222

2323
vi.mock('@/lib/core/config/block-visibility', () => blockVisibilityMock)
@@ -111,7 +111,7 @@ setEnvFlags({
111111
isSandboxesEnabled: false,
112112
isSsoEnabled: false,
113113
})
114-
urlsMockFns.mockIsOllamaUrlConfigured.mockReturnValue(false)
114+
setEnv({ OLLAMA_URL: undefined })
115115

116116
afterAll(() => {
117117
resetEnvMock()

‎apps/sim/lib/core/utils/urls.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
/**
22
* @vitest-environment jsdom
33
*/
4+
45
import { envMockFns, setEnv } from '@sim/testing/mocks/env.mock'
6+
import { envFlagsMockFns, resetEnvFlagsMock, setEnvFlags } from '@sim/testing/mocks/env-flags.mock'
57
import { beforeEach, describe, expect, it, vi } from 'vitest'
68

79
vi.unmock('@/lib/core/utils/urls')
@@ -11,6 +13,7 @@ import {
1113
getSocketUrl,
1214
isLocalhostUrl,
1315
isNonCanonicalSimHost,
16+
isOllamaAvailable,
1417
isSafeHttpUrl,
1518
parseOriginList,
1619
} from '@/lib/core/utils/urls'
@@ -230,3 +233,26 @@ describe('isNonCanonicalSimHost', () => {
230233
expect(isNonCanonicalSimHost('')).toBe(false)
231234
})
232235
})
236+
237+
describe('isOllamaAvailable', () => {
238+
beforeEach(() => {
239+
resetEnvFlagsMock()
240+
setEnv({ OLLAMA_URL: undefined })
241+
})
242+
243+
it('reaches the loopback default on a self-hosted deployment', () => {
244+
expect(isOllamaAvailable()).toBe(true)
245+
})
246+
247+
it('needs OLLAMA_URL on the hosted platform', () => {
248+
setEnvFlags({ isHosted: true })
249+
expect(isOllamaAvailable()).toBe(false)
250+
setEnv({ OLLAMA_URL: 'http://ollama.internal:11434' })
251+
expect(isOllamaAvailable()).toBe(true)
252+
})
253+
254+
it('is never available when the provider is blacklisted', () => {
255+
envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama'])
256+
expect(isOllamaAvailable()).toBe(false)
257+
})
258+
})

‎apps/sim/lib/core/utils/urls.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { isLoopbackHostname } from '@sim/security/hostnames'
22
import { SIM_SITE_URL } from '@sim/utils/site'
33
import { env, getEnv } from '@/lib/core/config/env'
4-
import { isProd } from '@/lib/core/config/env-flags'
4+
import { getBlacklistedProvidersFromEnv, isHosted, isProd } from '@/lib/core/config/env-flags'
55

66
/** Canonical base URL for the public-facing marketing site. No trailing slash. */
77
export const SITE_URL = SIM_SITE_URL
@@ -299,6 +299,24 @@ export function getOllamaUrl(): string {
299299
* back to the loopback default. Callers use this to tell "someone pointed us at
300300
* an Ollama" apart from "nobody configured one".
301301
*/
302-
export function isOllamaUrlConfigured(): boolean {
302+
function isOllamaUrlConfigured(): boolean {
303303
return Boolean(env.OLLAMA_URL)
304304
}
305+
306+
/**
307+
* Whether this deployment has an Ollama server to talk to. Self-hosted deployments run
308+
* alongside their own Ollama, so the loopback default {@link getOllamaUrl} falls back to is a
309+
* working configuration that needs no env var. Hosted Sim runs none, so there the address
310+
* must be stated or there is nothing to reach.
311+
*
312+
* The chat and embedding model lists, the embedding client and the access-request catalog
313+
* all answer through this, so a picker never lists models its client then refuses.
314+
*/
315+
export function isOllamaReachable(): boolean {
316+
return !isHosted || isOllamaUrlConfigured()
317+
}
318+
319+
/** Whether Ollama can serve a model here: {@link isOllamaReachable}, and not blacklisted. */
320+
export function isOllamaAvailable(): boolean {
321+
return !getBlacklistedProvidersFromEnv().includes('ollama') && isOllamaReachable()
322+
}

‎apps/sim/lib/embeddings/client.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
readResponseJsonWithLimit,
2626
readResponseTextWithLimit,
2727
} from '@/lib/core/utils/stream-limits'
28-
import { getOllamaUrl } from '@/lib/core/utils/urls'
28+
import { getOllamaUrl, isOllamaReachable } from '@/lib/core/utils/urls'
2929
import { EmbeddingAPIError } from '@/lib/embeddings/api-error'
3030
import {
3131
DEFAULT_EMBEDDING_MODEL,
@@ -38,7 +38,6 @@ import {
3838
import { EmbeddingConfigurationError } from '@/lib/embeddings/configuration-error'
3939
import { getEmbeddingResponseDiagnostic } from '@/lib/embeddings/error-diagnostics'
4040
import { resolveProviderKey } from '@/lib/embeddings/keys'
41-
import { isOllamaServerConfigured } from '@/lib/embeddings/ollama-model-catalog.server'
4241
import { DEFAULT_OPENROUTER_EMBEDDING_MODEL } from '@/lib/embeddings/openrouter-models'
4342
import { getAdapterFactory } from '@/lib/embeddings/providers'
4443
import {
@@ -406,7 +405,7 @@ async function resolveProvider(
406405
* would have made this stricter than the selector that offers the models.
407406
*/
408407
if (info.provider === 'ollama') {
409-
if (!isOllamaServerConfigured()) {
408+
if (!isOllamaReachable()) {
410409
throw new EmbeddingConfigurationError()
411410
}
412411
const baseUrl = getOllamaUrl().replace(/\/+$/, '')

‎apps/sim/lib/embeddings/ollama-model-catalog.server.ts‎

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@ import {
55
ollamaShowUpstreamResponseSchema,
66
ollamaUpstreamResponseSchema,
77
} from '@/lib/api/contracts/providers'
8-
import { isHosted } from '@/lib/core/config/env-flags'
98
import { readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits'
10-
import { getOllamaUrl, isOllamaUrlConfigured } from '@/lib/core/utils/urls'
9+
import { getOllamaUrl, isOllamaReachable } from '@/lib/core/utils/urls'
1110
import { isOllamaEmbeddingModel, ollamaEmbeddingModelName } from '@/lib/embeddings/catalog'
1211

1312
const logger = createLogger('OllamaEmbeddingCatalog')
@@ -27,22 +26,6 @@ export interface OllamaEmbeddingModel {
2726
dimensions?: number
2827
}
2928

30-
/**
31-
* Whether this deployment has an Ollama server to talk to.
32-
*
33-
* Self-hosted deployments run alongside their own Ollama, so the loopback
34-
* default `getOllamaUrl` falls back to is a working configuration that needs no
35-
* env var — the same rule the chat provider's model route applies. Hosted Sim
36-
* runs none, so there the address must be stated or there is nothing to reach.
37-
*
38-
* Exported because the selector, this module's width lookup, and the embedding
39-
* client all have to answer it identically: a selector that lists models the
40-
* client then refuses to embed with is worse than either behaviour alone.
41-
*/
42-
export function isOllamaServerConfigured(): boolean {
43-
return !isHosted || isOllamaUrlConfigured()
44-
}
45-
4629
export class OllamaEmbeddingModelNotFoundError extends Error {
4730
constructor(model: string) {
4831
super(
@@ -127,7 +110,7 @@ async function loadOllamaEmbeddingModelCatalog(
127110
signal?: AbortSignal
128111
): Promise<{ models: OllamaEmbeddingModel[]; unreachable?: string }> {
129112
/** Nothing to dial: an unconfigured hosted deployment has no server to reach. */
130-
if (!isOllamaServerConfigured()) return { models: [] }
113+
if (!isOllamaReachable()) return { models: [] }
131114

132115
let names: string[]
133116
try {
@@ -191,7 +174,7 @@ export async function getOllamaEmbeddingModelMetadata(
191174
const name = isOllamaEmbeddingModel(model) ? ollamaEmbeddingModelName(model) : model
192175
if (!name) throw new OllamaEmbeddingModelNotFoundError(model)
193176
/** The same rule the selector and the embedding client apply. */
194-
if (!isOllamaServerConfigured()) {
177+
if (!isOllamaReachable()) {
195178
throw new OllamaUnreachableError('OLLAMA_URL is not configured')
196179
}
197180

‎apps/sim/lib/model-router/resolve.test.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,9 @@ describe('resolveAutoModel', () => {
210210

211211
it('falls back when every pool model is denied by workspace permissions', async () => {
212212
mockFetchWorker.mockResolvedValue(routerResponse({ choice: '1' }))
213-
mockValidateModelProvider.mockRejectedValue(new Error('provider blocked'))
213+
mockValidateModelProvider.mockImplementation(async (_userId, _workspaceId, model) => {
214+
if (model !== 'sim-auto') throw new Error('provider blocked')
215+
})
214216
const result = await resolveAutoModel({
215217
ctx,
216218
blockId: 'b1',
@@ -220,4 +222,36 @@ describe('resolveAutoModel', () => {
220222
expect(result.model).toBe('claude-sonnet-5')
221223
expect(result.decidedBy).toBe('fallback')
222224
})
225+
226+
it('refuses a denied sim-auto instead of running a pool or fallback model', async () => {
227+
mockFetchWorker.mockResolvedValue(routerResponse({ choice: '1' }))
228+
const denied = new Error('Model sim-auto is not allowed')
229+
mockValidateModelProvider.mockImplementation(async (_userId, _workspaceId, model) => {
230+
if (model === 'sim-auto') throw denied
231+
})
232+
233+
await expect(
234+
resolveAutoModel({
235+
ctx,
236+
blockId: 'b1',
237+
signals: makeSignals(),
238+
fallbackModel: 'claude-sonnet-5',
239+
})
240+
).rejects.toBe(denied)
241+
expect(mockFetchWorker).not.toHaveBeenCalled()
242+
243+
setEnvFlags({ isHosted: false })
244+
try {
245+
await expect(
246+
resolveAutoModel({
247+
ctx,
248+
blockId: 'b1',
249+
signals: makeSignals(),
250+
fallbackModel: 'claude-sonnet-5',
251+
})
252+
).rejects.toBe(denied)
253+
} finally {
254+
setEnvFlags({ isHosted: true })
255+
}
256+
})
223257
})

‎apps/sim/lib/model-router/resolve.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { getMothershipBaseURL } from '@/lib/mothership/server/agent-url'
1313
import { validateModelProvider } from '@/ee/access-control/utils/permission-check'
1414
import type { ExecutionContext } from '@/executor/types'
1515
import type { ModelCost } from '@/providers/cost-policy'
16+
import { SIM_AUTO_MODEL_ID } from '@/providers/models'
1617
import { getProviderFromModel } from '@/providers/utils'
1718

1819
const logger = createLogger('ModelRouter')
@@ -248,9 +249,10 @@ async function callModelRouter(
248249

249250
/**
250251
* Resolves the sim-auto pseudo-model to a concrete model for one block
251-
* execution. Never throws and never fails the workflow: any error, timeout,
252-
* non-hosted deployment, or fully unavailable pool column falls back to
253-
* `fallbackModel` (the block's standard default). Callers must supply the same already-projected
252+
* execution. Like any model check it throws when the workspace's permission group
253+
* denies sim-auto itself or its permission config cannot be loaded. Otherwise it never fails
254+
* the workflow: any error, timeout, non-hosted deployment, or fully unavailable
255+
* pool column falls back to `fallbackModel` (the block's standard default). Callers must supply the same already-projected
254256
* model-facing signals they pass to their provider boundary; this router never rescans them.
255257
*/
256258
export async function resolveAutoModel(args: {
@@ -260,6 +262,8 @@ export async function resolveAutoModel(args: {
260262
fallbackModel: string
261263
}): Promise<AutoRoutingResult> {
262264
const { ctx, blockId, signals, fallbackModel } = args
265+
// Before any fallback: a denied sim-auto must not run as whichever pool or default model is allowed.
266+
await validateModelProvider(ctx.userId, ctx.workspaceId ?? undefined, SIM_AUTO_MODEL_ID, ctx)
263267
const fallback: AutoRoutingResult = {
264268
model: fallbackModel,
265269
tier: null,

0 commit comments

Comments
 (0)