Skip to content
Open
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
12 changes: 7 additions & 5 deletions apps/sim/lib/mothership/generated/mothership-stream-v1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
// The mothership-stream-v1 SSE wire: every `data:` frame the worker emits to Sim (each leg
// ends with a literal `data: [DONE]` line), and the vocabulary Sim re-emits to the browser
// (Sim adds `session` chat/title frames of its own).
// The zod schemas below are the single source (D122): every type is inferred from them, so the
// worker's emitter (apps/server/src/protocol/envelope.ts) fails typecheck on a frame that drifts,
// and a reader can validate a frame at runtime against the same definition. Each discriminant
// const below is checked against its payload union, because Sim's reader accepts exactly the
// const's values. Objects strip unknown keys: a newer emitter's extra field never fails a reader.
// The zod schemas below are the single source (D122): every payload type is inferred from them,
// so the worker's emitter (apps/server/src/protocol/envelope.ts) fails typecheck on a frame that
// drifts, and a reader can validate a frame at runtime against the same definition. Each
// discriminant const below is checked against its payload union, because Sim's reader accepts
// exactly the const's values. Objects strip unknown keys: a newer emitter's extra field never
// fails a reader, except in a `resource` payload's `resource.search.nativeQueries` entries, which
// reuse Sim's strict model tool-input schema.
// Its own optional fields are `?: T` (`.exactOptional()`); the protocol.ts fields it spreads
// are `?: T | undefined`.

Expand Down
7 changes: 5 additions & 2 deletions apps/sim/lib/mothership/generated/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@ export const SearchResource = z.object({
});
export type SearchResource = z.infer<typeof SearchResource>;

/** Resource frames and tool output cross versions, so an owner's unknown keys strip. */
const ResourceOwner = z.object(FileOwner.shape);

export const ResourceAddress = z.object({
owner: FileOwner.optional(),
owner: ResourceOwner.optional(),
workspaceId: z.uuid().optional(),
workspaceName: z.string().optional(),
type: ResourceType,
Expand Down Expand Up @@ -93,7 +96,7 @@ export const ResourceChange = z.discriminatedUnion("op", [
resource: z.union([
z.object({
type: ResourceType,
owner: FileOwner.optional(),
owner: ResourceOwner.optional(),
workspaceId: z.uuid().optional(),
id: z.string().regex(/\S/).optional(),
}),
Expand Down
35 changes: 13 additions & 22 deletions apps/sim/lib/mothership/request/session/contract-shadow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,6 @@ const { recordStreamContractDisagreement } = vi.hoisted(() => ({
}))
vi.mock('@/lib/mothership/request/metrics', () => ({ recordStreamContractDisagreement }))

vi.mock('@/lib/mothership/request/session/contract', async () => {
const actual = await vi.importActual<typeof import('@/lib/mothership/request/session/contract')>(
'@/lib/mothership/request/session/contract'
)
return {
...actual,
parsePersistedStreamEventEnvelope: vi.fn(actual.parsePersistedStreamEventEnvelope),
}
})

const logger = getMockLogger('StreamContractShadow')

const shell = {
Expand Down Expand Up @@ -209,24 +199,25 @@ describe('parseIngestedStreamEventEnvelope', () => {
)

it('keeps a rejection the schema would accept and reports it', () => {
const value = frame('tool', { ...toolCall, toolCallId: 'tool-accepted' })
const rejection = {
ok: false as const,
reason: 'invalid_stream_event' as const,
message: 'A stream event failed validation.',
errors: ['hypothetical'],
}
vi.mocked(parsePersistedStreamEventEnvelope).mockReturnValueOnce(rejection)
// The validator rejects a null activityReceipt; the schema does not declare the key and
// strips it. This fails by design once the two are aligned: then pick another real split.
const value = frame('run', { kind: 'compaction_start', activityReceipt: null })
const result = parseIngestedStreamEventEnvelope(value)

expect(parseIngestedStreamEventEnvelope(value)).toBe(rejection)
expect(result.ok).toBe(false)
expect(result).toEqual(parsePersistedStreamEventEnvelope(value))
expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith(
'schema_accepts',
'tool',
'call'
'run',
'compaction_start'
)
expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
'Stream contract schema disagrees with the stream validator',
expect.objectContaining({ direction: 'schema_accepts', validatorErrors: ['hypothetical'] })
expect.objectContaining({
direction: 'schema_accepts',
eventType: 'run',
variant: 'compaction_start',
})
)
})

Expand Down
9 changes: 6 additions & 3 deletions apps/sim/lib/mothership/request/session/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,12 @@ function isStreamScope(value: unknown): value is MothershipStreamV1StreamScope {
//
// Validates the envelope shell (v, seq, ts, stream, trace?, scope?) and that
// `type` is one of the known event types with a non-null payload object.
// Per-payload-variant validation is intentionally lightweight: the server
// already performs strict schema validation; the client only needs enough
// structural checking to safely dispatch inside the switch statement.
// This is the one verdict on every stream frame: on Sim's server (worker ingest,
// Redis buffer reads) and in the browser. Only a resource payload is checked
// against its generated schema (ResourcePayload). The generated envelope schema
// (MothershipStreamV1EventEnvelopeSchema) is not enforced at runtime: the
// worker's emitter is only typed against it, and on worker ingest it only
// shadows this verdict, counting disagreements (contract-shadow.ts).

/** The event types the contract names; a frame of any other type is invalid. */
export const KNOWN_EVENT_TYPES: ReadonlySet<string> = new Set(
Expand Down
17 changes: 17 additions & 0 deletions apps/sim/lib/workflows/editing/validation-models.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,23 @@ describe('model ids no provider declares', () => {
const { errors } = validateModel('router_v2', 'llama3.1:8b')
expect(errors[0]?.error).toContain('Unknown model id')
})

it('offers an ollama/ namespace example only where Ollama can serve it', () => {
expect(validateModel('router_v2', 'best available model').errors[0]?.error).toContain(
'"ollama/llama3.1:8b"'
)

setEnvFlags({ isHosted: true })
expect(validateModel('router_v2', 'best available model').errors[0]?.error).not.toContain(
'ollama/'
)

setEnvFlags({ isHosted: false })
envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama'])
expect(validateModel('router_v2', 'best available model').errors[0]?.error).not.toContain(
'ollama/'
)
})
})

describe('fallback model rows', () => {
Expand Down
11 changes: 10 additions & 1 deletion apps/sim/lib/workflows/editing/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1025,14 +1025,23 @@ export function validateValueForSubBlockType(
const suggestions = suggestModelIdsForUnknownModel(trimmed)
const suggestionText =
suggestions.length > 0 ? ` Valid options include: ${suggestions.join(', ')}.` : ''
const namespaceExamples = [
'azure/my-deployment',
'azure-anthropic/my-deployment',
'bedrock/my-inference-profile',
'vertex/my-model',
...(isOllamaAvailable() ? ['ollama/llama3.1:8b'] : []),
]
.map((example) => `"${example}"`)
.join(', ')
return {
valid: false,
error: {
blockId,
blockType,
field: fieldName,
value,
error: `Unknown model id "${trimmed}" for block "${blockType}". Read components/blocks/${blockType}.json (the model.options array) for valid ids; prefer entries with recommended: true and avoid deprecated: true. For user-configured models, use a supported provider namespace, e.g. "azure/my-deployment", "azure-anthropic/my-deployment", "bedrock/my-inference-profile", "vertex/my-model", "ollama/llama3.1:8b", or "openrouter/provider/model".${suggestionText}`,
error: `Unknown model id "${trimmed}" for block "${blockType}". Read components/blocks/${blockType}.json (the model.options array) for valid ids; prefer entries with recommended: true and avoid deprecated: true. For user-configured models, use a supported provider namespace, e.g. ${namespaceExamples}, or "openrouter/provider/model".${suggestionText}`,
},
}
}
Expand Down
Loading