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
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getTransitiveSubBlockDependents } from '@/lib/workflows/subblocks/dependencies'
import { omitConditionHiddenParams } from '@/lib/workflows/tool-input/hidden-params'
import type { StoredTool } from '@/lib/workflows/tool-input/types'
import { getBlock } from '@/blocks/registry'
import type { ToolMetadata } from '@/tools/metadata'
Expand Down Expand Up @@ -27,10 +28,14 @@ export function clearDependentToolParams(
return next ?? params
}

/** Keeps user-configured inputs that the newly selected operation accepts. */
/**
* Keeps user-configured inputs that the newly selected operation accepts and still shows: a
* value whose fields the operation hides would otherwise linger out of sight and still run.
*/
export function getParamsForToolOperation(
tool: Pick<StoredTool, 'type' | 'params'>,
nextTool: ToolMetadata
nextTool: ToolMetadata,
operation: string
): Record<string, string> {
const newParamIds = new Set(
Object.entries(nextTool.params ?? {})
Expand Down Expand Up @@ -64,5 +69,6 @@ export function getParamsForToolOperation(
Object.entries(tool.params || {}).forEach(([paramId, value]) => {
if (newParamIds.has(paramId) && value) preservedParams[paramId] = value
})
return clearDependentToolParams(tool.type, preservedParams, 'operation')
const visibleParams = omitConditionHiddenParams(subBlocks, preservedParams, operation)
return clearDependentToolParams(tool.type, visibleParams, 'operation')
}
Original file line number Diff line number Diff line change
Expand Up @@ -981,7 +981,7 @@ export const ToolInput = memo(function ToolInput({
return
}

const preservedParams = getParamsForToolOperation(tool, newToolConfig)
const preservedParams = getParamsForToolOperation(tool, newToolConfig, operation)

if (tool.type === 'jira') {
const subBlockStore = useSubBlockStore.getState()
Expand Down
16 changes: 10 additions & 6 deletions apps/sim/executor/handlers/human-in-the-loop/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
isCanonicalPair,
scopeCanonicalModesForTool,
} from '@/lib/workflows/subblocks/visibility'
import { omitConditionHiddenParams } from '@/lib/workflows/tool-input/hidden-params'
import { getBlock } from '@/blocks/registry'
import type { BlockOutput } from '@/blocks/types'
import {
Expand Down Expand Up @@ -422,10 +423,13 @@ export class HumanInTheLoopBlockHandler implements BlockHandler {
Object.values(buildCanonicalIndex(subBlocks).groupsById) as CanonicalGroup[]
).filter(isCanonicalPair)

const operation =
toolConfig.operation ??
(typeof storedParams.operation === 'string' ? storedParams.operation : undefined)
const visibleParams = omitConditionHiddenParams(subBlocks, storedParams, operation)

const { paramsTransform } = buildBlockToolParamsTransform({
operation:
toolConfig.operation ??
(typeof storedParams.operation === 'string' ? storedParams.operation : undefined),
operation,
blockSubBlocks: subBlocks,
blockParamsFn: notificationBlock?.tools?.config?.params,
blockInputDefs: notificationBlock?.inputs,
Expand All @@ -438,18 +442,18 @@ export class HumanInTheLoopBlockHandler implements BlockHandler {
),
})

if (!paramsTransform) return storedParams
if (!paramsTransform) return visibleParams

try {
return paramsTransform(storedParams)
return paramsTransform(visibleParams)
} catch (error) {
// Mirrors `prepareToolExecution`: a transform that throws must not take the
// notification down with it, so the raw params still go out.
logger.warn('Notification tool params transform failed, using raw params', {
toolId,
error,
})
return storedParams
return visibleParams
}
}

Expand Down
9 changes: 8 additions & 1 deletion apps/sim/executor/handlers/pi/local/sim-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,15 @@ function buildSimToolSpec(
if (!inputProjection.complete || !projectedTool) {
return unavailableToolResult()
}
// Only the stored keys the transform kept: a value the selected operation hides was
// dropped from `preseededParams`, so its projected copy must be dropped too.
const projectedPreseededParams = Object.fromEntries(
Object.entries(projectedTool.params || {}).filter(([key]) =>
Object.hasOwn(preseededParams, key)
)
)
const mergedProjectedParams = mergeToolParameters(
projectedTool.params || {},
projectedPreseededParams,
args as Record<string, unknown>
)

Expand Down
199 changes: 199 additions & 0 deletions apps/sim/lib/workflows/tool-input/hidden-params.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import { isRecordLike } from '@sim/utils/object'
import {
evaluateSubBlockCondition,
isNonEmptyValue,
type SubBlockCondition,
} from '@/lib/workflows/subblocks/visibility'
import type { SubBlockConfig } from '@/blocks/types'

type ConditionSubBlock = Pick<
SubBlockConfig,
| 'id'
| 'type'
| 'mode'
| 'condition'
| 'reactiveCondition'
| 'canonicalParamId'
| 'password'
| 'options'
>

/**
* Whether `operation` is one of the block's own operation choices. Only then can a condition on
* `operation` be decided: a stored row with no operation, or one holding a tool id the dropdown
* does not list, leaves every operation-gated field undecided.
*/
function isBlockOperation(
subBlocks: ConditionSubBlock[],
operation: string,
values: Record<string, unknown>
): boolean {
return subBlocks.some((subBlock) => {
if (subBlock.id !== 'operation' || subBlock.mode === 'trigger') return false
if (subBlock.mode === 'trigger-advanced' || !subBlock.options) return false
let options: unknown
try {
options =
typeof subBlock.options === 'function' ? subBlock.options({ values }) : subBlock.options
} catch {
return false
}
return (
Array.isArray(options) &&
options.some((option) => isRecordLike(option) && option.id === operation)
)
})
}

/** A stored scalar a condition can be decided against; JSON-shaped and empty values cannot. */
function isDecidableValue(value: unknown): boolean {
if (typeof value === 'boolean' || typeof value === 'number') return true
if (typeof value !== 'string') return false
const trimmed = value.trim()
return trimmed.length > 0 && !trimmed.startsWith('[') && !trimmed.startsWith('{')
}

/** The typed reading of a stored string, since a tool row stores `true` and `3` as text. */
function decodeScalar(value: unknown): unknown {
if (value === 'true') return true
if (value === 'false') return false
if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {
return Number(value)
}
return value
}

/**
* True only when the clause is decidably false. A clause on a field with no decidable value is
* treated as satisfiable, and a stored string is also tried in its typed reading, so every doubt
* resolves toward keeping the value.
*/
function isClauseFalse(
clause: SubBlockCondition,
values: Record<string, unknown>,
isDecidableField: (field: string) => boolean
): boolean {
const { field } = clause
if (!isDecidableField(field)) return false
const single: SubBlockCondition = { field, value: clause.value, not: clause.not }
if (evaluateSubBlockCondition(single, values)) return false
const decoded = decodeScalar(values[field])
return decoded === values[field] || !evaluateSubBlockCondition(single, { [field]: decoded })
}

/**
* Resolves a function condition, or `null` when it read a field the row cannot decide. A function
* condition names one field in what it returns but may branch on others (Video Generator gates a
* setting on the model, which the model itself supplies at call time), so every read is watched.
*/
function resolveFunctionCondition(
condition: (values?: Record<string, unknown>) => SubBlockCondition,
values: Record<string, unknown>,
isDecidableField: (field: string) => boolean
): SubBlockCondition | null {
let readUndecidedField = false
const watched = new Proxy(values, {
get(target, key, receiver) {
if (typeof key === 'string' && !isDecidableField(key)) readUndecidedField = true
return Reflect.get(target, key, receiver)
},
has(target, key) {
if (typeof key === 'string' && !isDecidableField(key)) readUndecidedField = true
return Reflect.has(target, key)
},
ownKeys(target) {
readUndecidedField = true
return Reflect.ownKeys(target)
},
})
const resolved = condition(watched)
return readUndecidedField ? null : resolved
}

function isCredentialSubBlock(subBlock: ConditionSubBlock): boolean {
return (
subBlock.type === 'oauth-input' ||
subBlock.canonicalParamId === 'oauthCredential' ||
subBlock.password === true
)
}

function isConditionHidden(
subBlock: ConditionSubBlock,
values: Record<string, unknown>,
isDecidableField: (field: string) => boolean
): boolean {
if (isCredentialSubBlock(subBlock) || !subBlock.condition || subBlock.reactiveCondition) {
return false
}
let condition: SubBlockCondition | null
try {
condition =
typeof subBlock.condition === 'function'
? resolveFunctionCondition(subBlock.condition, values, isDecidableField)
: subBlock.condition
} catch {
return false
}
if (!condition) return false
const clauses = condition.and ? [condition, condition.and] : [condition]
return clauses.some((clause) => isClauseFalse(clause, values, isDecidableField))
}

/**
* Every sub-block that stores a value under `paramId`: those whose id or canonical id it is,
* widened to the whole basic/advanced group, since either member may hold the group's value.
*/
function getWritingSubBlocks(subBlocks: ConditionSubBlock[], paramId: string): ConditionSubBlock[] {
const groups = new Set<string>()
for (const subBlock of subBlocks) {
if (
(subBlock.id === paramId || subBlock.canonicalParamId === paramId) &&
subBlock.canonicalParamId
) {
groups.add(subBlock.canonicalParamId)
}
}
return subBlocks.filter(
(subBlock) =>
subBlock.id === paramId ||
(subBlock.canonicalParamId !== undefined && groups.has(subBlock.canonicalParamId))
)
}

/**
* Drops stored tool-row values the selected operation hides.
*
* A tool row keeps values across operation switches, but renders only the sub-blocks whose
* `condition` holds for the selected operation. A value left by a previous operation is then
* invisible to the user, and because it counts as user-provided it is also withheld from the
* model's schema, yet it still reaches the block mapper and the tool. A value is dropped only
* when every sub-block that writes it is decidably hidden under `{ ...params, operation }`.
*
* Kept: values no sub-block writes (pure tool params), values any writing sub-block shows (a
* canonical pair counts as shown when any member is), credential and password fields, and any
* value whose condition depends on a field the row has no decidable value for. Returns `params`
* itself when nothing is dropped.
*/
export function omitConditionHiddenParams<T>(
subBlocks: ConditionSubBlock[] | undefined,
params: Record<string, T>,
operation: string | undefined
): Record<string, T> {
if (!subBlocks?.length) return params
const values: Record<string, unknown> = { ...params, operation }
const operationKnown = Boolean(operation && isBlockOperation(subBlocks, operation, values))
const isDecidableField = (field: string) =>
field === 'operation' ? operationKnown : isDecidableValue(values[field])
const isHidden = (paramId: string, value: T): boolean => {
if (paramId === 'operation' || !isNonEmptyValue(value)) return false
const writers = getWritingSubBlocks(subBlocks, paramId)
return (
writers.length > 0 &&
writers.every((subBlock) => isConditionHidden(subBlock, values, isDecidableField))
)
}
const entries = Object.entries(params)
const kept = entries.filter(([paramId, value]) => !isHidden(paramId, value))
return kept.length === entries.length ? params : Object.fromEntries(kept)
}
Loading
Loading