Skip to content

Commit 64f153c

Browse files
authored
fix(models): keep existing blocks' models, check Auto keys without resolving them (#10649)
* fix(models): keep existing blocks' models, check Auto keys without resolving them * fix(models): count Sim's key only where the platform holds one for the provider * test(models): type the hosted key pool mock like the real check
1 parent 43d5d5a commit 64f153c

8 files changed

Lines changed: 296 additions & 96 deletions

File tree

‎apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/combobox/combobox.tsx‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/c
1818
import { useActiveSearchTarget } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/providers/active-search-target-provider'
1919
import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-accessible-reference-prefixes'
2020
import type { SubBlockConfig } from '@/blocks/types'
21-
import { getModelFieldDefaults, offersAutoModel } from '@/blocks/utils'
2221
import { useDebounce } from '@/hooks/use-debounce'
2322
import { usePermissionConfig } from '@/hooks/use-permission-config'
2423
import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model'
@@ -326,17 +325,10 @@ export const ComboBox = memo(function ComboBox({
326325

327326
/**
328327
* Determines the default option value to use.
329-
* Priority: Auto on hosted Sim for a model field that offers it > explicit defaultValue >
330-
* DEFAULT_BLOCK_MODEL for model field > first option
328+
* Priority: explicit defaultValue > DEFAULT_BLOCK_MODEL for model field > first option.
329+
* Names the model an empty field runs on; a new block's Auto start is seeded at creation.
331330
*/
332331
const defaultOptionValue = useMemo(() => {
333-
if (offersAutoModel(config)) {
334-
const autoInOptions = getModelFieldDefaults(config, deploymentShape.hosted).find((model) =>
335-
evaluatedOptions.some((opt) => getOptionValue(opt) === model)
336-
)
337-
if (autoInOptions) return autoInOptions
338-
}
339-
340332
if (defaultValue !== undefined) {
341333
// Validate that the default value exists in the available (filtered) options
342334
const defaultInOptions = evaluatedOptions.find((opt) => getOptionValue(opt) === defaultValue)
@@ -371,7 +363,7 @@ export const ComboBox = memo(function ComboBox({
371363
}
372364

373365
return undefined
374-
}, [defaultValue, evaluatedOptions, subBlockId, getOptionValue, config, deploymentShape.hosted])
366+
}, [defaultValue, evaluatedOptions, subBlockId, getOptionValue, config.emptyIsValid])
375367

376368
/**
377369
* Resolve the user-facing text for the current stored value.

‎apps/sim/blocks/utils.test.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -403,17 +403,22 @@ describe('getModelFieldDefaults', () => {
403403
options: getAgentModelOptions,
404404
defaultValue: DEFAULT_BLOCK_MODEL,
405405
}
406+
afterEach(() => setEnvFlags({ isHosted: false }))
406407

407408
it('starts a field that offers Auto on Auto on hosted Sim, then its declared default', () => {
408-
expect(getModelFieldDefaults(agentModel, true)).toEqual(['sim-auto', DEFAULT_BLOCK_MODEL])
409-
expect(
410-
getModelFieldDefaults({ ...agentModel, options: getModelOptionsWithAuto }, true)
411-
).toEqual(['sim-auto', DEFAULT_BLOCK_MODEL])
409+
setEnvFlags({ isHosted: true })
410+
expect(getModelFieldDefaults(agentModel)).toEqual(['sim-auto', DEFAULT_BLOCK_MODEL])
411+
expect(getModelFieldDefaults({ ...agentModel, options: getModelOptionsWithAuto })).toEqual([
412+
'sim-auto',
413+
DEFAULT_BLOCK_MODEL,
414+
])
412415
})
413416

414417
it('keeps the declared default on self-hosted Sim and where the field offers no Auto', () => {
415-
expect(getModelFieldDefaults(agentModel, false)).toEqual([DEFAULT_BLOCK_MODEL])
416-
expect(getModelFieldDefaults({ ...agentModel, options: getModelOptions }, true)).toEqual([
418+
setEnvFlags({ isHosted: false })
419+
expect(getModelFieldDefaults(agentModel)).toEqual([DEFAULT_BLOCK_MODEL])
420+
setEnvFlags({ isHosted: true })
421+
expect(getModelFieldDefaults({ ...agentModel, options: getModelOptions })).toEqual([
417422
DEFAULT_BLOCK_MODEL,
418423
])
419424
})

‎apps/sim/blocks/utils.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -306,11 +306,12 @@ export function offersAutoModel(subBlock: Pick<SubBlockConfig, 'id' | 'options'>
306306
* Self-hosted deployments have no Auto, so they keep the declared default.
307307
*/
308308
export function getModelFieldDefaults(
309-
subBlock: Pick<SubBlockConfig, 'id' | 'options' | 'defaultValue'>,
310-
hosted: boolean = getDeploymentShape().hosted
309+
subBlock: Pick<SubBlockConfig, 'id' | 'options' | 'defaultValue'>
311310
): string[] {
312311
const declared = typeof subBlock.defaultValue === 'string' ? [subBlock.defaultValue] : []
313-
return hosted && offersAutoModel(subBlock) ? [SIM_AUTO_MODEL_ID, ...declared] : declared
312+
return getDeploymentShape().hosted && offersAutoModel(subBlock)
313+
? [SIM_AUTO_MODEL_ID, ...declared]
314+
: declared
314315
}
315316

316317
function buildModelOptions({

‎apps/sim/lib/api-key/byok.test.ts‎

Lines changed: 83 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,12 @@ vi.mock('@/lib/api-key/byok-entitlement', () => ({
2323

2424
vi.mock('@/lib/core/config/api-keys', () => ({
2525
getRotatingApiKey: mockGetRotatingApiKey,
26+
hasRotatingApiKey: mockHasRotatingApiKey,
2627
}))
2728

28-
const { mockGetRotatingApiKey } = vi.hoisted(() => ({
29+
const { mockGetRotatingApiKey, mockHasRotatingApiKey } = vi.hoisted(() => ({
2930
mockGetRotatingApiKey: vi.fn(),
31+
mockHasRotatingApiKey: vi.fn((_pool: string) => true),
3032
}))
3133

3234
const { mockMayUseHostedKey } = vi.hoisted(() => ({
@@ -46,7 +48,7 @@ vi.mock('@/stores/providers/store', () => ({
4648
useProvidersStore: { getState: vi.fn() },
4749
}))
4850

49-
import { getApiKeyWithBYOK, getBYOKKey } from '@/lib/api-key/byok'
51+
import { getApiKeyWithBYOK, getBYOKKey, hasHostedModelKey } from '@/lib/api-key/byok'
5052
import { useProvidersStore } from '@/stores/providers/store'
5153

5254
const mockDecryptSecret = encryptionMockFns.mockDecryptSecret
@@ -231,6 +233,85 @@ describe('getBYOKKey', () => {
231233
})
232234
})
233235

236+
describe('hasHostedModelKey', () => {
237+
const HOSTED_MODEL = 'fireworks/glm-5.3'
238+
239+
beforeEach(() => {
240+
resetDbChainMock()
241+
mockDecryptSecret.mockImplementation(async (encrypted: string) => ({
242+
decrypted: encrypted.replace('encrypted-', 'decrypted-'),
243+
}))
244+
mockIsOrganizationBYOKEntitled.mockResolvedValue(true)
245+
mockGetHostedModels.mockReturnValue([HOSTED_MODEL])
246+
mockMayUseHostedKey.mockResolvedValue(true)
247+
mockHasRotatingApiKey.mockReturnValue(true)
248+
})
249+
afterEach(() => setEnvFlags({ isHosted: true }))
250+
251+
it("answers from the payer's hosted-key access without a BYOK lookup", async () => {
252+
await expect(hasHostedModelKey('fireworks', HOSTED_MODEL, uniqueWorkspaceId())).resolves.toBe(
253+
true
254+
)
255+
expect(dbChainMockFns.orderBy).not.toHaveBeenCalled()
256+
})
257+
258+
it("finds a refused payer's BYOK key without decrypting it or advancing its rotation", async () => {
259+
mockMayUseHostedKey.mockResolvedValue(false)
260+
const workspaceId = uniqueWorkspaceId()
261+
dbChainMockFns.orderBy.mockResolvedValue([storedKey('key-1'), storedKey('key-2')])
262+
263+
await expect(hasHostedModelKey('fireworks', HOSTED_MODEL, workspaceId)).resolves.toBe(true)
264+
265+
expect(mockDecryptSecret).not.toHaveBeenCalled()
266+
await expect(getBYOKKey(workspaceId, 'fireworks')).resolves.toMatchObject({
267+
apiKey: 'decrypted-key-1',
268+
})
269+
})
270+
271+
it("follows the organization pool's entitlement like getBYOKKey", async () => {
272+
mockMayUseHostedKey.mockResolvedValue(false)
273+
const organizationId = uniqueOrganizationId()
274+
dbChainMockFns.orderBy
275+
.mockResolvedValueOnce([])
276+
.mockResolvedValueOnce([storedOrganizationKey(organizationId, 'org-key')])
277+
.mockResolvedValueOnce([])
278+
.mockResolvedValueOnce([storedOrganizationKey(organizationId, 'org-key')])
279+
mockIsOrganizationBYOKEntitled.mockResolvedValueOnce(true).mockResolvedValueOnce(false)
280+
281+
await expect(hasHostedModelKey('fireworks', HOSTED_MODEL, uniqueWorkspaceId())).resolves.toBe(
282+
true
283+
)
284+
await expect(hasHostedModelKey('fireworks', HOSTED_MODEL, uniqueWorkspaceId())).resolves.toBe(
285+
false
286+
)
287+
})
288+
289+
it("falls through to BYOK when the platform holds no key for the provider's pool", async () => {
290+
mockHasRotatingApiKey.mockImplementation((pool: string) => pool !== 'fireworks')
291+
const workspaceId = uniqueWorkspaceId()
292+
dbChainMockFns.orderBy.mockResolvedValueOnce([]).mockResolvedValueOnce([])
293+
await expect(hasHostedModelKey('fireworks', HOSTED_MODEL, workspaceId)).resolves.toBe(false)
294+
dbChainMockFns.orderBy.mockResolvedValueOnce([storedKey('key-1')])
295+
await expect(hasHostedModelKey('fireworks', HOSTED_MODEL, workspaceId)).resolves.toBe(true)
296+
})
297+
298+
it('checks Google models against the gemini key pool, as the provider call does', async () => {
299+
mockGetHostedModels.mockReturnValue(['gemini-3.8-flash'])
300+
await hasHostedModelKey('google', 'gemini-3.8-flash', uniqueWorkspaceId())
301+
expect(mockHasRotatingApiKey).toHaveBeenCalledWith('gemini')
302+
})
303+
304+
it('refuses a model outside the hosted catalog and self-hosted Sim', async () => {
305+
const workspaceId = uniqueWorkspaceId()
306+
await expect(hasHostedModelKey('fireworks', 'fireworks/custom', workspaceId)).resolves.toBe(
307+
false
308+
)
309+
setEnvFlags({ isHosted: false })
310+
await expect(hasHostedModelKey('fireworks', HOSTED_MODEL, workspaceId)).resolves.toBe(false)
311+
expect(mockMayUseHostedKey).not.toHaveBeenCalled()
312+
})
313+
})
314+
234315
describe('getApiKeyWithBYOK provider classification', () => {
235316
const dynamicProviders = [
236317
'ollama',

‎apps/sim/lib/api-key/byok.ts‎

Lines changed: 89 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
mayUseHostedKey,
1313
} from '@/lib/billing/core/hosted-key-access'
1414
import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade'
15-
import { getRotatingApiKey } from '@/lib/core/config/api-keys'
15+
import { getRotatingApiKey, hasRotatingApiKey } from '@/lib/core/config/api-keys'
1616
import { env } from '@/lib/core/config/env'
1717
import { isHosted } from '@/lib/core/config/env-flags'
1818
import { redactDatabaseQueryError } from '@/lib/core/errors/database-query-error'
@@ -76,11 +76,8 @@ function nextRotationIndex(poolKey: string, poolSize: number): number {
7676
* pool can never fall through to an organization pool.
7777
*/
7878
async function decryptBYOKPool(
79-
keys: readonly EncryptedBYOKKey[],
80-
rotationPoolKey: string,
81-
providerId: BYOKProviderId,
82-
scope: BYOKKeyScope,
83-
scopeName: BYOKKeyScopeName
79+
{ keys, rotationPoolKey, scope, scopeName }: BYOKKeyPool,
80+
providerId: BYOKProviderId
8481
): Promise<BYOKKeyResult> {
8582
const startIndex = nextRotationIndex(rotationPoolKey, keys.length)
8683
for (let offset = 0; offset < keys.length; offset++) {
@@ -122,13 +119,43 @@ export async function getBYOKKey(
122119
options: { signal?: AbortSignal } = {}
123120
): Promise<BYOKKeyResult | null> {
124121
if (!workspaceId) return null
122+
return withBYOKLookup(workspaceId, providerId, options.signal, async (signal) => {
123+
const pool = await findBYOKKeyPool(workspaceId, providerId, signal)
124+
return pool ? decryptBYOKPool(pool, providerId) : null
125+
})
126+
}
125127

128+
/**
129+
* Whether the workspace holds an eligible BYOK key for the provider, by the same rules as
130+
* {@link getBYOKKey}, without decrypting a key or advancing its pool's rotation.
131+
*/
132+
async function hasBYOKKey(
133+
workspaceId: string | undefined | null,
134+
providerId: BYOKProviderId,
135+
options: { signal?: AbortSignal } = {}
136+
): Promise<boolean> {
137+
if (!workspaceId) return false
138+
return withBYOKLookup(
139+
workspaceId,
140+
providerId,
141+
options.signal,
142+
async (signal) => (await findBYOKKeyPool(workspaceId, providerId, signal)) !== null
143+
)
144+
}
145+
146+
/** Runs one BYOK lookup under the shared deadline, retrying transient database reads. */
147+
function withBYOKLookup<T>(
148+
workspaceId: string,
149+
providerId: BYOKProviderId,
150+
parentSignal: AbortSignal | undefined,
151+
lookup: (signal: AbortSignal) => Promise<T>
152+
): Promise<T> {
126153
return withinDeadline(
127154
async (signal) => {
128155
for (let attempt = 1; ; attempt++) {
129156
signal.throwIfAborted()
130157
try {
131-
const result = await resolveBYOKKey(workspaceId, providerId, signal)
158+
const result = await lookup(signal)
132159
signal.throwIfAborted()
133160
return result
134161
} catch (error) {
@@ -150,15 +177,23 @@ export async function getBYOKKey(
150177
}
151178
},
152179
Date.now() + BYOK_LOOKUP_TIMEOUT_MS,
153-
options.signal
180+
parentSignal
154181
)
155182
}
156183

157-
async function resolveBYOKKey(
184+
interface BYOKKeyPool {
185+
keys: EncryptedBYOKKey[]
186+
rotationPoolKey: string
187+
scope: BYOKKeyScope
188+
scopeName: BYOKKeyScopeName
189+
}
190+
191+
/** Selects the one key pool a workspace's BYOK lookup may use, or null when none is eligible. */
192+
async function findBYOKKeyPool(
158193
workspaceId: string,
159194
providerId: BYOKProviderId,
160195
signal: AbortSignal
161-
): Promise<BYOKKeyResult | null> {
196+
): Promise<BYOKKeyPool | null> {
162197
const workspaceKeys = await db
163198
.select({ id: workspaceBYOKKeys.id, encryptedApiKey: workspaceBYOKKeys.encryptedApiKey })
164199
.from(workspaceBYOKKeys)
@@ -172,13 +207,12 @@ async function resolveBYOKKey(
172207

173208
signal.throwIfAborted()
174209
if (workspaceKeys.length) {
175-
return decryptBYOKPool(
176-
workspaceKeys,
177-
`${workspaceId}:${providerId}`,
178-
providerId,
179-
{ workspaceId },
180-
'workspace'
181-
)
210+
return {
211+
keys: workspaceKeys,
212+
rotationPoolKey: `${workspaceId}:${providerId}`,
213+
scope: { workspaceId },
214+
scopeName: 'workspace',
215+
}
182216
}
183217

184218
const organizationKeys = await db
@@ -223,13 +257,12 @@ async function resolveBYOKKey(
223257
return null
224258
}
225259

226-
return decryptBYOKPool(
227-
organizationKeys,
228-
`organization:${organizationId}:${providerId}`,
229-
providerId,
230-
{ workspaceId, organizationId },
231-
'organization'
232-
)
260+
return {
261+
keys: organizationKeys,
262+
rotationPoolKey: `organization:${organizationId}:${providerId}`,
263+
scope: { workspaceId, organizationId },
264+
scopeName: 'organization',
265+
}
233266
}
234267

235268
/**
@@ -277,6 +310,37 @@ async function resolveHostedModelKey(
277310
}
278311
}
279312

313+
/** The platform key pool that serves a provider's hosted models (Google's is `gemini`). */
314+
function hostedKeyPool(provider: string): string {
315+
return provider === 'google' ? 'gemini' : provider
316+
}
317+
318+
/**
319+
* Whether {@link getApiKeyWithBYOK} would find a key for a catalogued hosted model on hosted Sim,
320+
* with no caller key: Sim's key when the platform holds one for the provider and the payer may
321+
* use it, else the workspace's BYOK key for the provider. Answers without resolving the key, so
322+
* nothing is decrypted and no pool's rotation advances. Any other model, or a self-hosted
323+
* deployment, answers false.
324+
*/
325+
export async function hasHostedModelKey(
326+
provider: string,
327+
model: string,
328+
workspaceId: string,
329+
options: { billingAttribution?: UsageUpgradePayer; signal?: AbortSignal } = {}
330+
): Promise<boolean> {
331+
if (!isHosted) return false
332+
if (!getHostedModels().some((hosted) => hosted.toLowerCase() === model.toLowerCase())) {
333+
return false
334+
}
335+
if (
336+
hasRotatingApiKey(hostedKeyPool(provider)) &&
337+
(await mayUseHostedKey(workspaceId, options.billingAttribution))
338+
) {
339+
return true
340+
}
341+
return hasBYOKKey(workspaceId, provider as BYOKProviderId, { signal: options.signal })
342+
}
343+
280344
/**
281345
* Resolves credentials for the provider already selected by model routing.
282346
* Discovery lists must not override that provider and select a different key pool.
@@ -453,7 +517,7 @@ export async function getApiKeyWithBYOK(
453517

454518
if (isModelHosted) {
455519
return resolveHostedModelKey(
456-
isGeminiModel ? 'gemini' : provider,
520+
hostedKeyPool(provider),
457521
model,
458522
workspaceId,
459523
userProvidedKey,

0 commit comments

Comments
 (0)