Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions apps/sim/app/api/providers/ollama/models/route.test.ts
Original file line number Diff line number Diff line change
@@ -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())
Expand All @@ -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)
Expand All @@ -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())
Expand Down
28 changes: 10 additions & 18 deletions apps/sim/app/api/providers/ollama/models/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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: [] })
}

Expand Down
5 changes: 2 additions & 3 deletions apps/sim/ee/access-requests/lib/catalog-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/ee/access-requests/lib/catalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -111,7 +111,7 @@ setEnvFlags({
isSandboxesEnabled: false,
isSsoEnabled: false,
})
urlsMockFns.mockIsOllamaUrlConfigured.mockReturnValue(false)
setEnv({ OLLAMA_URL: undefined })

afterAll(() => {
resetEnvMock()
Expand Down
26 changes: 26 additions & 0 deletions apps/sim/lib/core/utils/urls.test.ts
Original file line number Diff line number Diff line change
@@ -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')
Expand All @@ -11,6 +13,7 @@ import {
getSocketUrl,
isLocalhostUrl,
isNonCanonicalSimHost,
isOllamaAvailable,
isSafeHttpUrl,
parseOriginList,
} from '@/lib/core/utils/urls'
Expand Down Expand Up @@ -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)
})
})
22 changes: 20 additions & 2 deletions apps/sim/lib/core/utils/urls.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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()
}
5 changes: 2 additions & 3 deletions apps/sim/lib/embeddings/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down Expand Up @@ -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(/\/+$/, '')
Expand Down
23 changes: 3 additions & 20 deletions apps/sim/lib/embeddings/ollama-model-catalog.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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(
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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')
}

Expand Down
36 changes: 35 additions & 1 deletion apps/sim/lib/model-router/resolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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 })
}
})
})
10 changes: 7 additions & 3 deletions apps/sim/lib/model-router/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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: {
Expand All @@ -260,6 +262,8 @@ export async function resolveAutoModel(args: {
fallbackModel: string
}): Promise<AutoRoutingResult> {
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,
Expand Down
Loading
Loading