From b9fe88a7487e4ccecd7fdada011007dffde79d17 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 13:48:47 -0800 Subject: [PATCH 1/5] fix(workflow-code): keep stored values an unchanged source round trip used to rewrite - condition/router branch values that do not lift into rows (retired native rows, '') print as raw(...) and are written back verbatim instead of being cleared - an inputFormat holding a non-list object prints as raw(...) instead of compiling as record sugar into invented start fields - a value creation mints (webhook token) that source leaves out keeps its stored value on apply - a JSON code field stored as a native object or array compiles back native, not as JSON text - files mode no longer emits codeFile() for a code param printed under meta.extra - an agent tool whose params repeat its pinned operation prints as raw(tool) Regression fixtures: stored-shapes corpus cases, an agent-tools case, and a re-apply corpus the re-apply property runs. --- .../workflows/code/corpus/generate.test.ts | 12 +- .../sim/lib/workflows/code/corpus/generate.ts | 172 +++++++++++++++++- apps/sim/lib/workflows/code/corpus/index.ts | 1 + .../code/corpus/roundtrip.corpus.test.ts | 20 +- packages/workflow-code/src/compile/blocks.ts | 25 ++- .../workflow-code/src/materialize/block.ts | 2 +- .../workflow-code/src/materialize/params.ts | 14 +- .../workflow-code/src/materialize/preserve.ts | 16 ++ packages/workflow-code/src/print/params.ts | 35 +++- packages/workflow-code/src/print/printer.ts | 16 +- packages/workflow-code/src/print/tools.ts | 13 ++ .../src/structured/input-format.ts | 3 + 12 files changed, 304 insertions(+), 25 deletions(-) diff --git a/apps/sim/lib/workflows/code/corpus/generate.test.ts b/apps/sim/lib/workflows/code/corpus/generate.test.ts index 7f9ccac52c5..2fc2f445949 100644 --- a/apps/sim/lib/workflows/code/corpus/generate.test.ts +++ b/apps/sim/lib/workflows/code/corpus/generate.test.ts @@ -28,6 +28,13 @@ import { getBlockRegistry } from '@/blocks/registry' const corpus = generateRegistryCorpus() const known = corpus.filter((c) => !c.unknownTypes) +/** Field types whose stored value a `legacy-stored-value` case holds in a shape their validator refuses. */ +const LEGACY_SHAPE_TYPES: ReadonlySet = new Set([ + 'condition-input', + 'router-input', + 'input-format', +]) + function valueProblems(corpusCase: CorpusCase): string[] { const problems: string[] = [] for (const block of Object.values(corpusCase.state.blocks)) { @@ -47,7 +54,10 @@ function valueProblems(corpusCase: CorpusCase): string[] { corpusCase.storedQuirk === 'legacy-scalar-text' && typeof subBlock.value === 'string' && declarations.some((declared) => declared.type === 'switch' || declared.type === 'slider') - if (!legacyText && !results.some((result) => result.valid)) { + const legacyShape = + corpusCase.storedQuirk === 'legacy-stored-value' && + declarations.some((declared) => LEGACY_SHAPE_TYPES.has(declared.type)) + if (!legacyText && !legacyShape && !results.some((result) => result.valid)) { problems.push(`${block.type}.${id}: ${results[0]?.error?.error}`) } } diff --git a/apps/sim/lib/workflows/code/corpus/generate.ts b/apps/sim/lib/workflows/code/corpus/generate.ts index 2a9b80caade..3f3f59bef7c 100644 --- a/apps/sim/lib/workflows/code/corpus/generate.ts +++ b/apps/sim/lib/workflows/code/corpus/generate.ts @@ -61,6 +61,7 @@ type CorpusCaseKind = | 'crlf-text' | 'agent-tools' | 'legacy-scalars' + | 'stored-shapes' export interface CorpusCase { /** Stable and unique: `::`. */ @@ -78,9 +79,10 @@ export interface CorpusCase { * A stored shape the editor's write-time validators refuse but real workflows hold: * `implicit-branch-handle` is an edge on `condition--if` while the rows were never * persisted. `legacy-scalar-text` is a switch or slider holding the text registry defaults once - * seeded (`'true'`, `'0.7'`), which the switch validator now refuses. + * seeded (`'true'`, `'0.7'`), which the switch validator now refuses. `legacy-stored-value` is a + * value the editor no longer writes in that shape but stored workflows hold (`storedShapeCases`). */ - storedQuirk?: 'implicit-branch-handle' | 'legacy-scalar-text' + storedQuirk?: 'implicit-branch-handle' | 'legacy-scalar-text' | 'legacy-stored-value' } interface CorpusOptions { @@ -888,7 +890,8 @@ function crlfCases(registry: Registry, seed: number): CorpusCase[] { /** * Agent tool entries the editor's tool picker writes (tool-input.tsx): an MCP server tool with its * input schema snapshot, a deployed workflow as a tool (`workflow_input`), a block operation as a - * tool (Slack send to a picked channel) and a workspace custom tool by id. + * tool (Slack send to a picked channel), one whose params repeat its operation, and a workspace + * custom tool by id. */ function agentToolCases(registry: Registry, seed: number): CorpusCase[] { const agent = registry.byType.get('agent') @@ -942,6 +945,22 @@ function agentToolCases(registry: Registry, seed: number): CorpusCase[] { isExpanded: false, usageControl: 'auto', }) + // Stored tool entries can also hold the operation in params, beside the entry's own operation. + const operationInParamsTool = () => ({ + type: 'postgresql', + operation: 'query', + usageControl: 'auto', + isExpanded: true, + params: { + operation: 'query', + host: 'db.example.com', + port: '5432', + database: 'db', + username: 'reader', + password: '{{PG_PASSWORD}}', + ssl: 'preferred', + }, + }) const customTool = () => ({ type: 'custom-tool', customToolId: 'corpus-custom-tool', @@ -952,6 +971,7 @@ function agentToolCases(registry: Registry, seed: number): CorpusCase[] { toolCase('workflow-input', (b) => [workflowTool(b)]), toolCase('mcp-and-workflow-input', (b) => [mcpTool(b), workflowTool(b)]), toolCase('builder-and-custom', () => [builderTool(), customTool()]), + toolCase('params-repeat-operation', () => [operationInParamsTool()]), toolCase('every-kind', (b) => [ builderTool(), customTool(), @@ -961,6 +981,112 @@ function agentToolCases(registry: Registry, seed: number): CorpusCase[] { ] } +/** + * Values stored workflows hold in shapes the editor no longer writes, each of which an unchanged + * `source get` → `source apply` must leave byte-identical: condition rows in the retired native + * `{ id, next, label, expression }` shape and an empty-string branch value (neither lifts into + * branches), an inputFormat holding a pasted schema object or its JSON text instead of a field + * list, a JSON code field holding a native object or array instead of JSON text, and a code param + * the builder's type leaves out (printed under `meta.extra`) in files mode. + */ +function storedShapeCases(registry: Registry, seed: number): CorpusCase[] { + const cases: CorpusCase[] = [] + const at = (type: string) => registry.byType.get(type) + const fn = at('function') + const quirk = { storedQuirk: 'legacy-stored-value' } as const + const setValue = (block: BlockState, id: string, value: unknown) => { + const subBlock = block.subBlocks[id] + if (subBlock) subBlock.value = value as typeof subBlock.value + else block.subBlocks[id] = { id, type: 'short-input', value: value as never } + } + + const condition = at('condition') + if (condition && fn) { + const builder = new CaseBuilder(seed, 'stored-shapes:condition:native-legacy-rows') + const start = startBlock(builder, registry) + const { block } = subject(builder, registry, condition, { name: 'Check' }) + builder.connect(start, block.id) + const target = subject(builder, registry, fn, { name: 'Big' }) + const rowIds = [builder.newId(), builder.newId()] + setValue(block, 'conditions', [ + { id: rowIds[0], next: target.block.id, label: 'is big', expression: ' > 5' }, + { id: rowIds[1], next: target.block.id, label: 'else', expression: 'true' }, + ]) + builder.connect(block.id, target.block.id, `condition-${rowIds[0]}`) + cases.push(builder.build('stored-shapes', quirk)) + } + for (const [type, param] of [ + ['condition', 'conditions'], + ['router_v2', 'routes'], + ] as const) { + const config = at(type) + if (!config) continue + const builder = new CaseBuilder(seed, `stored-shapes:${type}:empty-string-branches`) + const start = startBlock(builder, registry) + const { block } = subject(builder, registry, config, { name: 'Decide' }) + builder.connect(start, block.id) + setValue(block, param, '') + cases.push(builder.build('stored-shapes', quirk)) + } + + const pastedSchema = { + name: 'order_event', + type: 'object', + schema: { type: 'object', properties: { event: { type: 'string' } } }, + description: 'incoming', + } + for (const [detail, value] of [ + ['input-format-schema-object', pastedSchema], + ['input-format-object-text', JSON.stringify(pastedSchema, null, 2)], + ] as const) { + const builder = new CaseBuilder(seed, `stored-shapes:start_trigger:${detail}`) + const start = startBlock(builder, registry) + setValue(builder.blocks[start], 'inputFormat', value) + cases.push(builder.build('stored-shapes', quirk)) + } + + for (const [type, param, value, extra] of [ + ['api', 'body', { query: '', count: 1, tags: ['a', 'b'] }, { method: 'POST' }], + ['api', 'body', ['', 2], { method: 'POST' }], + ['response', 'data', { answer: '', ok: true }, { dataMode: 'json' }], + ] as const) { + const config = at(type) + if (!config) continue + const shape = Array.isArray(value) ? 'array' : 'object' + const builder = new CaseBuilder(seed, `stored-shapes:${type}:native-json-${shape}`) + const start = startBlock(builder, registry) + const { block } = subject(builder, registry, config) + for (const [id, text] of Object.entries(extra)) setValue(block, id, text) + setValue(block, param, value) + builder.connect(start, block.id) + cases.push(builder.build('stored-shapes', quirk)) + } + + const apollo = at('apollo') + if (apollo) { + const builder = new CaseBuilder(seed, 'stored-shapes:apollo:extra-code-param') + const start = startBlock(builder, registry) + const id = builder.newId() + builder.add({ + id, + type: 'apollo', + name: 'Apollo', + position: builder.nextPosition(), + subBlocks: { + operation: { id: 'operation', type: 'dropdown', value: 'organization_search' }, + apiKey: { id: 'apiKey', type: 'short-input', value: CORPUS_TEXT }, + person_titles: { id: 'person_titles', type: 'code', value: '["CEO", "CTO"]' }, + }, + outputs: {}, + enabled: true, + }) + builder.connect(start, id) + cases.push(builder.build('stored-shapes')) + } + + return cases +} + /** A switch or slider value as registry defaults once seeded it: `'true'`, `'0.7'`, `'1.0'`. */ function legacyText(value: unknown): unknown { if (typeof value === 'boolean') return String(value) @@ -1096,10 +1222,50 @@ export function generateRegistryCorpus(options: CorpusOptions = {}): CorpusCase[ ...crlfCases(registry, seed), ...agentToolCases(registry, seed), ...legacyScalarCases(configs, registry, seed), + ...storedShapeCases(registry, seed), ...unknownTypeCases(registry, seed), ] } +/** + * Stored workflows whose print leaves out a value creation mints per block (`mintsFreshValue`: a + * webhook token stored `null`), so applying the print as a new workflow mints one and applying it + * again must keep it. Serializing such a workflow mints a fresh value per call, so execution + * parity cannot judge it; only the re-apply property runs these. + */ +export function generateReapplyCorpus(options: CorpusOptions = {}): CorpusCase[] { + const seed = options.seed ?? DEFAULT_CORPUS_SEED + const { registry } = buildRegistry(options) + const webhook = registry.byType.get('generic_webhook') + if (!webhook) return [] + return [true, false].map((requireAuth) => { + const builder = new CaseBuilder( + seed, + `reapply:generic_webhook:minted-token${requireAuth ? '-require-auth' : ''}` + ) + const id = builder.newId() + const switchValue: unknown = requireAuth + builder.add({ + id, + type: 'generic_webhook', + name: 'Webhook', + position: builder.nextPosition(), + subBlocks: { + token: { id: 'token', type: 'short-input', value: null }, + requireAuth: { + id: 'requireAuth', + type: 'switch', + value: switchValue as BlockState['subBlocks'][string]['value'], + }, + }, + outputs: {}, + enabled: true, + triggerMode: true, + }) + return builder.build('trigger', {}, { withVariable: false }) + }) +} + /** A stored shape source cannot express: print and compile must fail with `code`. */ interface RejectedCase { id: string diff --git a/apps/sim/lib/workflows/code/corpus/index.ts b/apps/sim/lib/workflows/code/corpus/index.ts index 4f12a0b3a1a..8b80f4dcb2e 100644 --- a/apps/sim/lib/workflows/code/corpus/index.ts +++ b/apps/sim/lib/workflows/code/corpus/index.ts @@ -2,6 +2,7 @@ export { CORPUS_CRLF_TEXT, type CorpusCase, DEFAULT_CORPUS_SEED, + generateReapplyCorpus, generateRegistryCorpus, generateRejectedCorpus, } from './generate' diff --git a/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts b/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts index a8842d85d27..c342668b07c 100644 --- a/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts +++ b/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts @@ -33,7 +33,7 @@ import { printWorkflow, } from '@sim/workflow-code' import { registryCatalog as catalog } from '@/lib/workflows/code/catalog/registry-catalog.test-helpers' -import { generateRejectedCorpus } from '@/lib/workflows/code/corpus' +import { generateReapplyCorpus, generateRejectedCorpus } from '@/lib/workflows/code/corpus' import { CORPUS_RESOURCES, corpusBudgetMs, @@ -73,6 +73,13 @@ const SERIALIZING_PROPERTIES: ReadonlySet = new Set(['P2', 'O2']) const subjects: ProofSubject[] = corpusSubjects() +/** Subjects only the re-apply property judges (`generateReapplyCorpus`). */ +const reapplySubjects: ProofSubject[] = generateReapplyCorpus().map((corpusCase) => ({ + id: corpusCase.id, + blockTypes: corpusCase.blockTypes, + state: corpusCase.state, +})) + /** Cases the registry corpus generates from one block's declarations, every value one it can hold. */ const REGISTRY_CASE = /^(operation|trigger|standalone-advanced|error-edge):/ @@ -334,14 +341,18 @@ describe(`round-trip corpus (${subjects.length} workflows)`, () => { 'applies printed source as a new workflow, then re-applies it as a no-op', () => { const notNoop: string[] = [] + const refused: string[] = [] let applied = 0 - for (const subject of subjects) { + for (const subject of [...subjects, ...reapplySubjects]) { if (subject.unknownTypes) continue const [entry, ...codeFiles] = sourceRun(subject).printed.files const files = new Map(codeFiles.map((file) => [file.path, file.text])) const first = compileWorkflow({ entry, files, catalog, sdkMajor: catalog.sdkMajor }) // `stored()` keeps a value only a stored workflow holds; a fresh apply refuses it. - if (!first.workflow || first.diagnostics.some((d) => d.severity === 'error')) continue + if (!first.workflow || first.diagnostics.some((d) => d.severity === 'error')) { + refused.push(subject.id) + continue + } applied++ const stored = materialized(first.workflow) const base = canonicalize(stored, { @@ -373,6 +384,9 @@ describe(`round-trip corpus (${subjects.length} workflows)`, () => { if (!diff.noop || !identity.ok) notNoop.push(subject.id) } expect(applied).toBeGreaterThan(subjects.length / 2) + expect(refused.filter((id) => reapplySubjects.some((subject) => subject.id === id))).toEqual( + [] + ) expect(notNoop).toEqual([]) }, corpusBudgetMs(subjects.length, PROPERTY_BUDGET_MS) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 7bc14648ed5..7e2e7542944 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -849,6 +849,18 @@ function keepStored( if (field && mode) setOwn(modes, field.param, mode) } +/** + * Whether the stored block this one continues holds `id` as a native object or array rather than + * JSON text. A JSON code field written as a literal keeps that encoding: it compiles to the plain + * value instead of JSON text, so an unchanged print writes nothing. + */ +function storedNative(ctx: CompileContext, state: BlockState, id: SubBlockId): boolean { + const stored = ctx.stored ? getOwn(ctx.stored.blocks, state.decl.key) : undefined + if (!stored || stored.type !== catalogBlockOf(state.decl)?.type) return false + const param = getOwn(stored.params, id) + return param?.kind === 'value' && param.value !== null && typeof param.value === 'object' +} + /** Compiles one catalog param into its member subBlock (`pairMode` picks a pair's member). */ function compileField( ctx: CompileContext, @@ -878,7 +890,7 @@ function compileField( : field.kind === 'single' ? field.sub : undefined - if (jsonTarget?.type === 'code') { + if (jsonTarget?.type === 'code' && !storedNative(ctx, state, jsonTarget.id)) { const value = compileJsonField(ctx, property.value, site, params, jsonTarget.id) if (value === undefined) return if (mode && isModalPair(field)) setOwn(modes, field.param, mode) @@ -1103,11 +1115,20 @@ function compileWrittenParams( addItem(property, encodeAnchor({ kind: 'param', block: decl.key, param: name })) recordSpan(ctx, { kind: 'param', block: decl.key, param: name }, property) if (branchField && key === branchField.subBlockId) { + if (property.value.type === 'CallExpression') { + // `raw(v)`: a stored branch value that does not lift into rows, kept verbatim. + const compiled = compileValue(ctx, property.value, site) + if (compiled?.kind === 'value' && compiled.form === 'raw') { + setOwn(params, key, { kind: 'value', value: compiled.value }) + continue + } + if (!compiled) continue + } if (property.value.type !== 'ObjectExpression') { unsupported( ctx, property.value, - 'Branches are an object literal.', + 'Branches are an object literal, or raw(value) for a stored value kept verbatim.', 'Write { if: js`...`, else: true }.', decl.key ) diff --git a/packages/workflow-code/src/materialize/block.ts b/packages/workflow-code/src/materialize/block.ts index 951de5e8288..fe22042e792 100644 --- a/packages/workflow-code/src/materialize/block.ts +++ b/packages/workflow-code/src/materialize/block.ts @@ -165,7 +165,7 @@ export function buildBlock(inputs: BlockInputs, context: MaterializeContext): Bu prevRaw: existing?.value, prevParam: previous, itemIds: itemSources(paramId), - forceText: paramId === branchSubBlockId, + verbatim: paramId === branchSubBlockId, }, context ) diff --git a/packages/workflow-code/src/materialize/params.ts b/packages/workflow-code/src/materialize/params.ts index c1a7523b76a..32064515372 100644 --- a/packages/workflow-code/src/materialize/params.ts +++ b/packages/workflow-code/src/materialize/params.ts @@ -22,8 +22,11 @@ export interface ParamSite { prevParam: CanonicalParam | undefined /** Ids to give inputFormat fields, by name, in preference order (lock first, then prev). */ itemIds: LockItem[] - /** Branch lists are always stored as text: the canvas reads them with `toString()`. */ - forceText: boolean + /** + * A stored branch value canonicalize could not lift into rows: written in the encoding source + * gives it (`raw(v)`), since its shape is not one any encoding rule knows. + */ + verbatim: boolean } /** @@ -41,14 +44,13 @@ function storesAsText(site: ParamSite): boolean { } /** - * The encoding a decoded value is written in: JSON text when the site forces text, or when the - * field is one canonicalize decodes and {@link storesAsText}; native otherwise. Scalars are always + * The encoding a decoded value is written in: as given when the site is verbatim, JSON text when + * the field is one canonicalize decodes and {@link storesAsText}; native otherwise. Scalars are always * native, and a field canonicalize never decodes keeps a structured value native so it reads back * unchanged. */ function encodeStorage(json: unknown, site: ParamSite): unknown { - if (typeof json !== 'object' || json === null) return json - if (site.forceText) return JSON.stringify(json) + if (typeof json !== 'object' || json === null || site.verbatim) return json if (!shouldDecode(site.declaration)) return json return storesAsText(site) ? JSON.stringify(json) : json } diff --git a/packages/workflow-code/src/materialize/preserve.ts b/packages/workflow-code/src/materialize/preserve.ts index 7b07c7c3eb8..3c420fd7dce 100644 --- a/packages/workflow-code/src/materialize/preserve.ts +++ b/packages/workflow-code/src/materialize/preserve.ts @@ -9,6 +9,8 @@ * editor defaults compile filled into fields that never run; * - the config fields of the loop or parallel types not in effect, and prev's spelling of a config * that runs the same (`count: 0` and `count: 5`); + * - a value creation minted (`mintsFreshValue`, a webhook token) that source leaves out, since + * source cannot state it and leaving it out asks for the minted value, not for none; * - unknown `block.data` extra data source does not carry; * - a container's subBlocks `block.data` supersedes (`SUPERSEDED_CONTAINER_PARAMS`). * @@ -19,6 +21,7 @@ import { SUBFLOW_DATA_KEYS, SUPERSEDED_CONTAINER_PARAMS } from '../canonicalize/subflows' import { canonicalActivityInputs, isInactive, withStoredValue } from '../catalog/activity' import { type CanonicalGroup, isCanonicalPair } from '../catalog/canonical-index' +import { mintsFreshValue } from '../catalog/defaults' import { serializedCanonicalIndex } from '../catalog/surface' import type { BlockCatalog, CatalogBlock } from '../catalog/types' import { catalogBlock, declarationsOf } from '../catalog/view' @@ -163,6 +166,18 @@ function restoreInactive( } } +/** + * Restores prev's minted value of each field creation mints per block that source leaves out: + * applying the source that created the block again keeps the value its first apply minted. + */ +function restoreMinted(next: CanonicalBlock, prev: CanonicalBlock, declared: CatalogBlock): void { + for (const subBlock of declared.subBlocks) { + if (!mintsFreshValue(subBlock) || getOwn(next.params, subBlock.id) !== undefined) continue + const minted = getOwn(prev.params, subBlock.id) + if (minted) setOwn(next.params, subBlock.id, minted) + } +} + /** Fields of a loop or parallel config that the executor reads for its type. */ function liveFields(spec: LoopSpec | ParallelSpec): Set { return new Set(Object.keys(executableSubflow(spec).config)) @@ -245,6 +260,7 @@ export function restorePreserved( if (declared) { restorePairs(next, prev, declared, catalog) restoreInactive(next, prev, declared, catalog) + restoreMinted(next, prev, declared) } if (target.subflow) { next.subflow = restoreSubflow(target.subflow, prev.subflow) diff --git a/packages/workflow-code/src/print/params.ts b/packages/workflow-code/src/print/params.ts index ed047962ac8..b580dd77b15 100644 --- a/packages/workflow-code/src/print/params.ts +++ b/packages/workflow-code/src/print/params.ts @@ -120,13 +120,23 @@ export function fieldContext( } } +/** + * Where a param prints: as a builder param (`typed`), whose type takes a code file, and, for a + * single field (not a pair member), a JSON code field's object or array literal; anything else + * goes under `meta.extra`, which compile reads verbatim and where `codeFile()` is refused. + */ +interface ParamPosition { + typed: boolean + single: boolean +} + function printParamValue( ctx: PrintContext, block: CanonicalBlock, declared: CatalogBlock | undefined, id: string, sb: CatalogSubBlock | undefined, - single = false + position: ParamPosition ): PrintedValue | null { const param = getOwn(block.params, id) if (!param) return null @@ -134,7 +144,13 @@ function printParamValue( if (holdsSecret(sb, param.value)) { return storedSecret(ctx, block, sb?.id ?? id, sb?.password === true) } - if (single && sb?.type === 'code' && sb.valueKind === 'json' && typeof param.value === 'string') { + if ( + position.typed && + position.single && + sb?.type === 'code' && + sb.valueKind === 'json' && + typeof param.value === 'string' + ) { const literal = printJsonField(ctx, block, param.value) if (literal) return literal } @@ -147,6 +163,7 @@ function printParamValue( if (structured) return structured if ( ctx.options.functionCode === 'files' && + position.typed && sb?.valueKind === 'code' && (context.tag === 'js' || context.tag === 'py' || context.tag === 'sh') && typeof param.value === 'string' && @@ -352,7 +369,10 @@ export function collectParams( if (hasValue(block, effective.id)) { if (inactiveIds.has(effective.id)) continue if (mode === 'basic' && member === field.basic && isDefault(effective.id)) continue - const printed = printParamValue(ctx, block, declared, effective.id, effective) + const printed = printParamValue(ctx, block, declared, effective.id, effective, { + typed, + single: false, + }) if (printed) { if (typed) push(params, field.name, printed) else push(extra, effective.id, printed) @@ -385,9 +405,7 @@ export function collectParams( continue } if (inactiveIds.has(sb.id) || isDefault(sb.id)) continue - // A JSON code field prints as an object literal only as a builder param: compile reads - // `extra` verbatim, so there the stored text is written as text. - const printed = printParamValue(ctx, block, declared, sb.id, sb, typed) + const printed = printParamValue(ctx, block, declared, sb.id, sb, { typed, single: true }) if (printed) { if (typed) push(params, field.name, printed) else push(extra, sb.id, printed) @@ -399,7 +417,10 @@ export function collectParams( .filter((id) => !handled.has(id) && !inactiveIds.has(id)) .sort(compareStrings) for (const id of rest) { - const printed = printParamValue(ctx, block, declared, id, undefined) + const printed = printParamValue(ctx, block, declared, id, undefined, { + typed: !declared, + single: false, + }) if (printed) push(declared ? extra : params, id, printed) } return { params, extra } diff --git a/packages/workflow-code/src/print/printer.ts b/packages/workflow-code/src/print/printer.ts index 18eca8e2bb0..e4abdd44299 100644 --- a/packages/workflow-code/src/print/printer.ts +++ b/packages/workflow-code/src/print/printer.ts @@ -21,7 +21,7 @@ import { branchesAtTopLevel, printsAsElseTrue } from '../forms/condition' import { readResponseForm } from '../forms/response' import { printedConfig } from '../forms/subflow' import { SOURCE_ENTRY_FILE } from '../limits' -import type { SourceHintBlock, SourceHints } from '../lock' +import { isJson, type SourceHintBlock, type SourceHints } from '../lock' import type { AnchorKey, BlockKey, CanonicalBlock, Json } from '../model' import { getOwn, pushTo, setOwn } from '../records' import { type BlockMetaKey, GENERIC_BUILDER, SDK_MODULE, type TemplateTag } from '../sdk' @@ -152,7 +152,19 @@ function blockCall(ctx: PrintContext, block: CanonicalBlock): Expr { let generic = found === null let topLevel: Property[] = paramProps - if (block.branches && branchSpec) { + const unlifted = branchSpec ? getOwn(block.params, branchSpec.subBlockId) : undefined + if (branchSpec && unlifted?.kind === 'value' && isJson(unlifted.value)) { + // A stored branch value canonicalize could not lift into rows is written back verbatim. The + // condition builder's params are its branches, so there it takes the generic form. + if (branchesAtTopLevel(branchSpec.kind, !generic)) generic = true + topLevel = [ + ...paramProps, + { + key: printKey(branchSpec.subBlockId), + value: ctx.values.call('raw', [ctx.values.json(unlifted.value)]), + }, + ] + } else if (block.branches && branchSpec) { const collides = paramProps.some((prop) => branchProps.some((branch) => branch.key === prop.key) ) diff --git a/packages/workflow-code/src/print/tools.ts b/packages/workflow-code/src/print/tools.ts index 460872038f8..8a7f12ed946 100644 --- a/packages/workflow-code/src/print/tools.ts +++ b/packages/workflow-code/src/print/tools.ts @@ -203,6 +203,7 @@ export function printTools( !declared || !hasToolForm(found.path, found.builder, declared) || Object.keys(tool.params).some((id) => aliasNames.has(id)) || + pinsDropParam(tool, found.builder) || !toolParamsTyped(tool, declared, found.builder) ) { return rawToolCall(ctx, block, tool, declared, aliases) @@ -257,6 +258,18 @@ export function printTools( return arrayExpr(elements) } +/** + * Whether the builder form would lose a stored param: compile writes the builder's pinned + * `operation` to the tool entry only and its `fixed` values into params, so a params `operation` + * or a fixed param holding another value does not come back. + */ +function pinsDropParam(tool: CanonicalTool, builder: CatalogBuilder): boolean { + const fixed = builder.fixed ?? {} + return [...builderPins(builder).keys()].some( + (id) => Object.hasOwn(tool.params, id) && getOwn(tool.params, id) !== getOwn(fixed, id) + ) +} + /** * Whether every stored param of a tool is one its builder's tool type declares: a field written * under its own id (a pair under its canonical id) that the builder's pinned values leave diff --git a/packages/workflow-code/src/structured/input-format.ts b/packages/workflow-code/src/structured/input-format.ts index 0216cc4d007..52dc36f33c2 100644 --- a/packages/workflow-code/src/structured/input-format.ts +++ b/packages/workflow-code/src/structured/input-format.ts @@ -315,6 +315,9 @@ export const INPUT_FORMAT_CODEC: StructuredCodec = { return inputFormatItems(value) }, print(value, { values, block }) { + // A stored object that is not a field list (a pasted schema) would compile as the record + // sugar into invented fields; it is kept verbatim. + if (isPlainRecord(value) && isJson(value)) return values.call('raw', [values.json(value)]) if (!Array.isArray(value)) return null const sugar = inputFormatSugar(value) if (sugar) return printRecord(values, block, sugar) From 5e3cc8ed9113c18e17b1151d7218a2fa884862ec Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 14:00:27 -0800 Subject: [PATCH 2/5] refactor(workflow-code): simplify round-trip fixes and pin their fixtures - one storedParamOf lookup in compile, ValuePrinter.raw for raw(json) prints, the branch print arms merged, the pinned-param check folded into toolParamsTyped - shared caseSubject for corpus subjects; the generator test pins every regression fixture id and the re-apply test pins its cases --- .../code/corpus/fixtures.test-helpers.ts | 17 ++++-- .../workflows/code/corpus/generate.test.ts | 17 +++++- .../sim/lib/workflows/code/corpus/generate.ts | 11 ++-- .../code/corpus/roundtrip.corpus.test.ts | 20 +++---- packages/workflow-code/src/compile/blocks.ts | 60 +++++++++---------- packages/workflow-code/src/print/params.ts | 33 ++++------ packages/workflow-code/src/print/printer.ts | 26 +++----- packages/workflow-code/src/print/tools.ts | 21 ++----- packages/workflow-code/src/print/values.ts | 7 ++- .../src/structured/input-format.ts | 6 +- .../workflow-code/src/structured/skills.ts | 4 +- 11 files changed, 107 insertions(+), 115 deletions(-) diff --git a/apps/sim/lib/workflows/code/corpus/fixtures.test-helpers.ts b/apps/sim/lib/workflows/code/corpus/fixtures.test-helpers.ts index c6672ae89ff..6cd4d34c78b 100644 --- a/apps/sim/lib/workflows/code/corpus/fixtures.test-helpers.ts +++ b/apps/sim/lib/workflows/code/corpus/fixtures.test-helpers.ts @@ -201,6 +201,16 @@ export function sampleCorpus( const CASES_PER_BLOCK_TYPE = 3 const FUZZ_RUNS = 50 +/** A generated corpus case as a proof subject, in the shape the normalized tables store. */ +export function caseSubject(corpusCase: CorpusCase): ProofSubject { + return { + id: corpusCase.id, + blockTypes: corpusCase.blockTypes, + state: persistedShape(corpusCase.state), + ...(corpusCase.unknownTypes && { unknownTypes: true as const }), + } +} + /** * Every workflow a corpus property runs against: the generated registry corpus (sampled unless * `ROUNDTRIP_CORPUS_FULL=1`), the landing templates, the `@sim/testing` states, redacted production @@ -214,12 +224,7 @@ export function corpusSubjects(): ProofSubject[] { process.env.ROUNDTRIP_CORPUS_FULL === '1' ? generated : sampleCorpus(generated, { perType: CASES_PER_BLOCK_TYPE }) - ).map((corpusCase) => ({ - id: corpusCase.id, - blockTypes: corpusCase.blockTypes, - state: persistedShape(corpusCase.state), - ...(corpusCase.unknownTypes && { unknownTypes: true as const }), - })) + ).map(caseSubject) return [ ...corpus, ...loadLandingTemplateStates().map(fixtureSubject), diff --git a/apps/sim/lib/workflows/code/corpus/generate.test.ts b/apps/sim/lib/workflows/code/corpus/generate.test.ts index 2fc2f445949..dffc02aa679 100644 --- a/apps/sim/lib/workflows/code/corpus/generate.test.ts +++ b/apps/sim/lib/workflows/code/corpus/generate.test.ts @@ -149,11 +149,26 @@ describe('generateRegistryCorpus', () => { 'unicode-names', 'crlf-text', 'agent-tools', + 'stored-shapes', ]) { expect(kinds).toContain(kind) } expect(corpus.some((c) => c.id.endsWith(':advanced'))).toBe(true) - expect(corpus.some((c) => c.id === 'branches:condition:null-rows')).toBe(true) + const ids = new Set(corpus.map((c) => c.id)) + const pinned = [ + 'branches:condition:null-rows', + 'agent-tools:agent:params-repeat-operation', + 'stored-shapes:condition:native-legacy-rows', + 'stored-shapes:condition:empty-string-branches', + 'stored-shapes:router_v2:empty-string-branches', + 'stored-shapes:start_trigger:input-format-schema-object', + 'stored-shapes:start_trigger:input-format-object-text', + 'stored-shapes:api:native-json-object', + 'stored-shapes:api:native-json-array', + 'stored-shapes:response:native-json-object', + 'stored-shapes:apollo:extra-code-param', + ] + expect(pinned.filter((id) => !ids.has(id))).toEqual([]) const toolLists = known .filter((c) => c.kind !== 'agent-tools') .flatMap((c) => diff --git a/apps/sim/lib/workflows/code/corpus/generate.ts b/apps/sim/lib/workflows/code/corpus/generate.ts index 3f3f59bef7c..b9c58dd9601 100644 --- a/apps/sim/lib/workflows/code/corpus/generate.ts +++ b/apps/sim/lib/workflows/code/corpus/generate.ts @@ -186,7 +186,7 @@ function operationsOf(config: BlockConfig): string[] { return (resolveOptions(operation, {}) ?? []).map((option) => option.id) } -function startBlock(builder: CaseBuilder, registry: Registry, inputFormat?: unknown[]): string { +function startBlock(builder: CaseBuilder, registry: Registry, inputFormat?: unknown): string { const config = registry.byType.get('start_trigger') if (!config) throw new Error('The registry has no start_trigger block') const fixture = buildBlockFixture({ @@ -202,7 +202,7 @@ function startBlock(builder: CaseBuilder, registry: Registry, inputFormat?: unkn position: { x: 0, y: 0 }, }) const inputFormatState = fixture.block.subBlocks.inputFormat - if (inputFormat && inputFormatState) { + if (inputFormat !== undefined && inputFormatState) { inputFormatState.value = inputFormat as typeof inputFormatState.value } return builder.add(fixture.block) @@ -996,8 +996,8 @@ function storedShapeCases(registry: Registry, seed: number): CorpusCase[] { const quirk = { storedQuirk: 'legacy-stored-value' } as const const setValue = (block: BlockState, id: string, value: unknown) => { const subBlock = block.subBlocks[id] - if (subBlock) subBlock.value = value as typeof subBlock.value - else block.subBlocks[id] = { id, type: 'short-input', value: value as never } + if (!subBlock) throw new Error(`The ${block.type} fixture has no ${id} subBlock`) + subBlock.value = value as typeof subBlock.value } const condition = at('condition') @@ -1040,8 +1040,7 @@ function storedShapeCases(registry: Registry, seed: number): CorpusCase[] { ['input-format-object-text', JSON.stringify(pastedSchema, null, 2)], ] as const) { const builder = new CaseBuilder(seed, `stored-shapes:start_trigger:${detail}`) - const start = startBlock(builder, registry) - setValue(builder.blocks[start], 'inputFormat', value) + startBlock(builder, registry, value) cases.push(builder.build('stored-shapes', quirk)) } diff --git a/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts b/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts index c342668b07c..214d3625c0f 100644 --- a/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts +++ b/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts @@ -36,6 +36,7 @@ import { registryCatalog as catalog } from '@/lib/workflows/code/catalog/registr import { generateReapplyCorpus, generateRejectedCorpus } from '@/lib/workflows/code/corpus' import { CORPUS_RESOURCES, + caseSubject, corpusBudgetMs, corpusSubjects, type ProofSubject, @@ -74,11 +75,7 @@ const SERIALIZING_PROPERTIES: ReadonlySet = new Set(['P2', 'O2']) const subjects: ProofSubject[] = corpusSubjects() /** Subjects only the re-apply property judges (`generateReapplyCorpus`). */ -const reapplySubjects: ProofSubject[] = generateReapplyCorpus().map((corpusCase) => ({ - id: corpusCase.id, - blockTypes: corpusCase.blockTypes, - state: corpusCase.state, -})) +const reapplySubjects: ProofSubject[] = generateReapplyCorpus().map(caseSubject) /** Cases the registry corpus generates from one block's declarations, every value one it can hold. */ const REGISTRY_CASE = /^(operation|trigger|standalone-advanced|error-edge):/ @@ -341,7 +338,8 @@ describe(`round-trip corpus (${subjects.length} workflows)`, () => { 'applies printed source as a new workflow, then re-applies it as a no-op', () => { const notNoop: string[] = [] - const refused: string[] = [] + const reapplyIds = new Set(reapplySubjects.map((subject) => subject.id)) + const refusedReapply: string[] = [] let applied = 0 for (const subject of [...subjects, ...reapplySubjects]) { if (subject.unknownTypes) continue @@ -350,7 +348,7 @@ describe(`round-trip corpus (${subjects.length} workflows)`, () => { const first = compileWorkflow({ entry, files, catalog, sdkMajor: catalog.sdkMajor }) // `stored()` keeps a value only a stored workflow holds; a fresh apply refuses it. if (!first.workflow || first.diagnostics.some((d) => d.severity === 'error')) { - refused.push(subject.id) + if (reapplyIds.has(subject.id)) refusedReapply.push(subject.id) continue } applied++ @@ -384,9 +382,11 @@ describe(`round-trip corpus (${subjects.length} workflows)`, () => { if (!diff.noop || !identity.ok) notNoop.push(subject.id) } expect(applied).toBeGreaterThan(subjects.length / 2) - expect(refused.filter((id) => reapplySubjects.some((subject) => subject.id === id))).toEqual( - [] - ) + expect([...reapplyIds].sort(compareStrings)).toEqual([ + 'reapply:generic_webhook:minted-token', + 'reapply:generic_webhook:minted-token-require-auth', + ]) + expect(refusedReapply).toEqual([]) expect(notNoop).toEqual([]) }, corpusBudgetMs(subjects.length, PROPERTY_BUDGET_MS) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 7e2e7542944..ad32875d78d 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -849,16 +849,15 @@ function keepStored( if (field && mode) setOwn(modes, field.param, mode) } -/** - * Whether the stored block this one continues holds `id` as a native object or array rather than - * JSON text. A JSON code field written as a literal keeps that encoding: it compiles to the plain - * value instead of JSON text, so an unchanged print writes nothing. - */ -function storedNative(ctx: CompileContext, state: BlockState, id: SubBlockId): boolean { - const stored = ctx.stored ? getOwn(ctx.stored.blocks, state.decl.key) : undefined - if (!stored || stored.type !== catalogBlockOf(state.decl)?.type) return false - const param = getOwn(stored.params, id) - return param?.kind === 'value' && param.value !== null && typeof param.value === 'object' +/** The stored param `id` of the block `decl` continues, when the stored block has the same type. */ +function storedParamOf( + ctx: CompileContext, + decl: BlockDecl, + id: SubBlockId +): CanonicalParam | undefined { + const stored = ctx.stored ? getOwn(ctx.stored.blocks, decl.key) : undefined + if (!stored || stored.type !== catalogBlockOf(decl)?.type) return undefined + return getOwn(stored.params, id) } /** Compiles one catalog param into its member subBlock (`pairMode` picks a pair's member). */ @@ -872,12 +871,8 @@ function compileField( const firstSub = field.kind === 'single' ? field.sub : field.members[0] const site = fieldSite(state.site, firstSub) if (firstSub?.valueKind === 'tools') { - const storedBlock = ctx.stored ? getOwn(ctx.stored.blocks, decl.key) : undefined - const storedParam = storedBlock ? getOwn(storedBlock.params, firstSub.id) : undefined - const storedTools = - storedBlock?.type === catalogBlockOf(decl)?.type && storedParam?.kind === 'tools' - ? storedParam.tools - : [] + const storedParam = storedParamOf(ctx, decl, firstSub.id) + const storedTools = storedParam?.kind === 'tools' ? storedParam.tools : [] const tools = compileToolList(ctx, property.value, site, storedTools) if (tools) setOwn(params, firstSub.id, { kind: 'tools', tools }) return @@ -890,7 +885,12 @@ function compileField( : field.kind === 'single' ? field.sub : undefined - if (jsonTarget?.type === 'code' && !storedNative(ctx, state, jsonTarget.id)) { + // A field stored as a native object or array keeps that encoding: it compiles as a plain + // value below, not as JSON text, so an unchanged print writes nothing. + const stored = jsonTarget && storedParamOf(ctx, decl, jsonTarget.id) + const storedNative = + stored?.kind === 'value' && stored.value !== null && typeof stored.value === 'object' + if (jsonTarget?.type === 'code' && !storedNative) { const value = compileJsonField(ctx, property.value, site, params, jsonTarget.id) if (value === undefined) return if (mode && isModalPair(field)) setOwn(modes, field.param, mode) @@ -1115,23 +1115,23 @@ function compileWrittenParams( addItem(property, encodeAnchor({ kind: 'param', block: decl.key, param: name })) recordSpan(ctx, { kind: 'param', block: decl.key, param: name }, property) if (branchField && key === branchField.subBlockId) { - if (property.value.type === 'CallExpression') { + if (property.value.type !== 'ObjectExpression') { // `raw(v)`: a stored branch value that does not lift into rows, kept verbatim. - const compiled = compileValue(ctx, property.value, site) + const compiled = + property.value.type === 'CallExpression' + ? compileValue(ctx, property.value, site) + : undefined if (compiled?.kind === 'value' && compiled.form === 'raw') { setOwn(params, key, { kind: 'value', value: compiled.value }) - continue + } else if (compiled !== null) { + unsupported( + ctx, + property.value, + 'Branches are an object literal, or raw(value) for a stored value kept verbatim.', + 'Write { if: js`...`, else: true }.', + decl.key + ) } - if (!compiled) continue - } - if (property.value.type !== 'ObjectExpression') { - unsupported( - ctx, - property.value, - 'Branches are an object literal, or raw(value) for a stored value kept verbatim.', - 'Write { if: js`...`, else: true }.', - decl.key - ) continue } const rows = objectEntries(ctx, property.value, (duplicate, name) => { diff --git a/packages/workflow-code/src/print/params.ts b/packages/workflow-code/src/print/params.ts index b580dd77b15..d715b65c97f 100644 --- a/packages/workflow-code/src/print/params.ts +++ b/packages/workflow-code/src/print/params.ts @@ -121,22 +121,18 @@ export function fieldContext( } /** - * Where a param prints: as a builder param (`typed`), whose type takes a code file, and, for a - * single field (not a pair member), a JSON code field's object or array literal; anything else - * goes under `meta.extra`, which compile reads verbatim and where `codeFile()` is refused. + * One param's printed value. `typed`: written as a builder param, where a code field may print as + * a code file (`meta.extra` takes neither form). `jsonLiteral`: a JSON code field's text may print + * as the object or array literal compile turns back into it. */ -interface ParamPosition { - typed: boolean - single: boolean -} - function printParamValue( ctx: PrintContext, block: CanonicalBlock, declared: CatalogBlock | undefined, id: string, sb: CatalogSubBlock | undefined, - position: ParamPosition + typed: boolean, + jsonLiteral = false ): PrintedValue | null { const param = getOwn(block.params, id) if (!param) return null @@ -145,8 +141,7 @@ function printParamValue( return storedSecret(ctx, block, sb?.id ?? id, sb?.password === true) } if ( - position.typed && - position.single && + jsonLiteral && sb?.type === 'code' && sb.valueKind === 'json' && typeof param.value === 'string' @@ -163,7 +158,7 @@ function printParamValue( if (structured) return structured if ( ctx.options.functionCode === 'files' && - position.typed && + typed && sb?.valueKind === 'code' && (context.tag === 'js' || context.tag === 'py' || context.tag === 'sh') && typeof param.value === 'string' && @@ -369,10 +364,7 @@ export function collectParams( if (hasValue(block, effective.id)) { if (inactiveIds.has(effective.id)) continue if (mode === 'basic' && member === field.basic && isDefault(effective.id)) continue - const printed = printParamValue(ctx, block, declared, effective.id, effective, { - typed, - single: false, - }) + const printed = printParamValue(ctx, block, declared, effective.id, effective, typed) if (printed) { if (typed) push(params, field.name, printed) else push(extra, effective.id, printed) @@ -405,7 +397,9 @@ export function collectParams( continue } if (inactiveIds.has(sb.id) || isDefault(sb.id)) continue - const printed = printParamValue(ctx, block, declared, sb.id, sb, { typed, single: true }) + // Under `meta.extra`, which compile reads verbatim, a code field is never a code file and a + // JSON code field's text stays text. + const printed = printParamValue(ctx, block, declared, sb.id, sb, typed, typed) if (printed) { if (typed) push(params, field.name, printed) else push(extra, sb.id, printed) @@ -417,10 +411,7 @@ export function collectParams( .filter((id) => !handled.has(id) && !inactiveIds.has(id)) .sort(compareStrings) for (const id of rest) { - const printed = printParamValue(ctx, block, declared, id, undefined, { - typed: !declared, - single: false, - }) + const printed = printParamValue(ctx, block, declared, id, undefined, false) if (printed) push(declared ? extra : params, id, printed) } return { params, extra } diff --git a/packages/workflow-code/src/print/printer.ts b/packages/workflow-code/src/print/printer.ts index e4abdd44299..8803f62262d 100644 --- a/packages/workflow-code/src/print/printer.ts +++ b/packages/workflow-code/src/print/printer.ts @@ -152,31 +152,21 @@ function blockCall(ctx: PrintContext, block: CanonicalBlock): Expr { let generic = found === null let topLevel: Property[] = paramProps - const unlifted = branchSpec ? getOwn(block.params, branchSpec.subBlockId) : undefined - if (branchSpec && unlifted?.kind === 'value' && isJson(unlifted.value)) { - // A stored branch value canonicalize could not lift into rows is written back verbatim. The - // condition builder's params are its branches, so there it takes the generic form. - if (branchesAtTopLevel(branchSpec.kind, !generic)) generic = true - topLevel = [ - ...paramProps, - { - key: printKey(branchSpec.subBlockId), - value: ctx.values.call('raw', [ctx.values.json(unlifted.value)]), - }, - ] - } else if (block.branches && branchSpec) { + // A stored branch value canonicalize could not lift into rows prints verbatim under its own key. + const storedParam = branchSpec ? getOwn(block.params, branchSpec.subBlockId) : undefined + const unlifted = + storedParam?.kind === 'value' && isJson(storedParam.value) ? storedParam.value : undefined + if (branchSpec && (block.branches || unlifted !== undefined)) { const collides = paramProps.some((prop) => branchProps.some((branch) => branch.key === prop.key) ) const atTopLevel = branchesAtTopLevel(branchSpec.kind, !generic) - if (atTopLevel && !collides) { + if (atTopLevel && !collides && unlifted === undefined) { topLevel = [...branchProps, ...paramProps] } else { if (atTopLevel) generic = true - topLevel = [ - ...paramProps, - { key: printKey(branchSpec.subBlockId), value: objectExpr(branchProps) }, - ] + const value = unlifted === undefined ? objectExpr(branchProps) : ctx.values.raw(unlifted) + topLevel = [...paramProps, { key: printKey(branchSpec.subBlockId), value }] } } let triggerMode: boolean | undefined diff --git a/packages/workflow-code/src/print/tools.ts b/packages/workflow-code/src/print/tools.ts index 8a7f12ed946..ed7360cc94a 100644 --- a/packages/workflow-code/src/print/tools.ts +++ b/packages/workflow-code/src/print/tools.ts @@ -203,7 +203,6 @@ export function printTools( !declared || !hasToolForm(found.path, found.builder, declared) || Object.keys(tool.params).some((id) => aliasNames.has(id)) || - pinsDropParam(tool, found.builder) || !toolParamsTyped(tool, declared, found.builder) ) { return rawToolCall(ctx, block, tool, declared, aliases) @@ -258,22 +257,12 @@ export function printTools( return arrayExpr(elements) } -/** - * Whether the builder form would lose a stored param: compile writes the builder's pinned - * `operation` to the tool entry only and its `fixed` values into params, so a params `operation` - * or a fixed param holding another value does not come back. - */ -function pinsDropParam(tool: CanonicalTool, builder: CatalogBuilder): boolean { - const fixed = builder.fixed ?? {} - return [...builderPins(builder).keys()].some( - (id) => Object.hasOwn(tool.params, id) && getOwn(tool.params, id) !== getOwn(fixed, id) - ) -} - /** * Whether every stored param of a tool is one its builder's tool type declares: a field written * under its own id (a pair under its canonical id) that the builder's pinned values leave - * visible (`typedForBuilder`). Anything else prints the tool as `raw(tool)`. + * visible (`typedForBuilder`), or a pinned param holding what compile writes for it (a `fixed` + * value; compile writes a pinned `operation` to the entry only). Anything else prints the tool as + * `raw(tool)`. */ function toolParamsTyped( tool: CanonicalTool, @@ -285,7 +274,7 @@ function toolParamsTyped( const index = buildFieldIndex(declared, false, pinned) const pinnedValues = Object.fromEntries(pins) return Object.keys(tool.params).every((id) => { - if (pinned.has(id)) return true + if (pinned.has(id)) return getOwn(tool.params, id) === getOwn(builder.fixed ?? {}, id) const field = index.fields.get(id) ?? index.aliased.get(id) if (!field || field.param !== id) return false const members = field.kind === 'pair' ? field.members : [field.sub] @@ -319,7 +308,7 @@ function rawToolCall( passwordIds.has(id) ? isLiteralSecret(value) : holdsDetectedSecret(value) const json = asToolJson(tool, tool) if (!isPlainRecord(json) || !Object.entries(tool.params).some(([id, v]) => secret(id, v))) { - return ctx.values.call('raw', [ctx.values.json(json)]) + return ctx.values.raw(json) } const params = objectExpr( Object.entries(tool.params).map(([id, value]) => ({ diff --git a/packages/workflow-code/src/print/values.ts b/packages/workflow-code/src/print/values.ts index b93d941cb85..f5c56384f00 100644 --- a/packages/workflow-code/src/print/values.ts +++ b/packages/workflow-code/src/print/values.ts @@ -103,6 +103,11 @@ export class ValuePrinter { return objectExpr(properties) } + /** `raw(value)`: the canonical value verbatim, which compile stores as written. */ + raw(value: Json): Expr { + return this.call('raw', [this.json(value)]) + } + /** Plain JSON with no ref or SimNode interpretation, as `literal()` and `raw()` take it. */ json(value: Json): Expr { if (value === null) return { doc: 'null', shape: 'literal', depth: 1 } @@ -132,7 +137,7 @@ export class ValuePrinter { const callee = getOwn(SDK_RESOURCE_CALLS, node.kind) if (callee) return { ...this.call(callee, [this.string(node.key)]), selector: true } } - return this.call('raw', [this.json(simNodeJson(node))]) + return this.raw(simNodeJson(node)) } /** Text with its references; plain text is a string, or `raw()` of one when `rawPlain`. */ diff --git a/packages/workflow-code/src/structured/input-format.ts b/packages/workflow-code/src/structured/input-format.ts index 52dc36f33c2..125056d397d 100644 --- a/packages/workflow-code/src/structured/input-format.ts +++ b/packages/workflow-code/src/structured/input-format.ts @@ -317,14 +317,14 @@ export const INPUT_FORMAT_CODEC: StructuredCodec = { print(value, { values, block }) { // A stored object that is not a field list (a pasted schema) would compile as the record // sugar into invented fields; it is kept verbatim. - if (isPlainRecord(value) && isJson(value)) return values.call('raw', [values.json(value)]) - if (!Array.isArray(value)) return null + if (!Array.isArray(value)) + return isPlainRecord(value) && isJson(value) ? values.raw(value) : null const sugar = inputFormatSugar(value) if (sugar) return printRecord(values, block, sugar) // The record form is the only one the SDK types: an empty list is `{}`, and a list the // record cannot carry (an integer-like or repeated name, an unknown key) is kept verbatim. if (value.length === 0) return objectExpr([]) - if (isJson(value)) return values.call('raw', [values.json(value)]) + if (isJson(value)) return values.raw(value) return null }, encode(value, site, context) { diff --git a/packages/workflow-code/src/structured/skills.ts b/packages/workflow-code/src/structured/skills.ts index f7ec267fa06..7f56f02a645 100644 --- a/packages/workflow-code/src/structured/skills.ts +++ b/packages/workflow-code/src/structured/skills.ts @@ -84,9 +84,7 @@ export const SKILLS_CODEC: StructuredCodec = { // `SkillRef[]` types only `skill('key')`; an entry kept verbatim prints as `raw(...)`. return arrayExpr( value.map((item) => - !isSimNode(item) && isJson(item) - ? values.call('raw', [values.json(item)]) - : values.value(item, context) + !isSimNode(item) && isJson(item) ? values.raw(item) : values.value(item, context) ) ) }, From d70c0d9c077b755d4f348683caefe4733be4dd0f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 17:21:53 -0800 Subject: [PATCH 3/5] fix(workflow-code): let an explicit null clear a minted value Leaving a minted field (webhook token) out of source keeps the stored value; writing it as null now compiles to an explicit null param, so apply clears it instead of restoring it. --- .../code/corpus/editing.corpus.test.ts | 25 ++++++++++++++++++- packages/workflow-code/src/compile/blocks.ts | 9 +++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts b/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts index bfaca18698c..9312e29df09 100644 --- a/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts +++ b/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts @@ -30,9 +30,10 @@ import { executableView, setOwn, } from '@sim/workflow-code' +import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import { registryCatalog as catalog } from '@/lib/workflows/code/catalog/registry-catalog.test-helpers' -import { DEFAULT_CORPUS_SEED } from '@/lib/workflows/code/corpus' +import { DEFAULT_CORPUS_SEED, generateReapplyCorpus } from '@/lib/workflows/code/corpus' import { applyCanvasOp, CANVAS_OP_KINDS, @@ -967,3 +968,25 @@ describe('renaming a block in source keeps the stored block it continues', () => expect(codeEditFailure(state, got, renameEdit(got, key, 'Renamed In Source'))).toBeNull() }) }) + +describe('a webhook token creation minted', () => { + it('is cleared by an explicit null in source instead of coming back from the stored block', () => { + const [webhookCase] = generateReapplyCorpus() + if (!webhookCase) throw new Error('the registry has no generic_webhook block') + const state = structuredClone(webhookCase.state) + const [webhook] = Object.values(state.blocks) + const token = webhook?.subBlocks.token + if (!webhook || !token) throw new Error('the webhook fixture has no token subBlock') + token.value = 'minted-token-value' + const got = getSource(state, catalog) + const entry = got.files[SOURCE_ENTRY_FILE] ?? '' + expect(entry).toContain('token: stored()') + const applied = applySource( + state, + got, + { ...got.files, [SOURCE_ENTRY_FILE]: entry.replace('token: stored()', 'token: null') }, + catalog + ) + expect(applied.materialized?.state.blocks[webhook.id]?.subBlocks.token?.value).toBeNull() + }) +}) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index ad32875d78d..a0848b5157b 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -27,7 +27,7 @@ import { } from '../canonicalize/subflows' import { REFERENCE_CANDIDATE } from '../canonicalize/values' import { canonicalActivityInputs, isInactive, withStoredValue } from '../catalog/activity' -import { editorDefaults } from '../catalog/defaults' +import { editorDefaults, mintsFreshValue } from '../catalog/defaults' import { builderPins, buildFieldIndex, @@ -907,8 +907,13 @@ function compileField( const compiled = compileValue(ctx, property.value, site) if (!compiled) return if (compiled.kind === 'absent' || compiled.kind === 'todo') { - for (const member of field.kind === 'pair' ? field.members : [field.sub]) + for (const member of field.kind === 'pair' ? field.members : [field.sub]) { state.unset.add(member.id) + // Leaving out a field creation mints keeps the stored value; a written `null` clears it. + if (compiled.kind === 'absent' && mintsFreshValue(member)) { + setOwn(params, member.id, { kind: 'value', value: null }) + } + } if (compiled.kind === 'todo') state.todos.set(field.name, property) return } From 908acbf1c05247b0b51272b068139dd6ca2a2456 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 18:01:46 -0800 Subject: [PATCH 4/5] fix(workflow-code): keep a null over an already-cleared minted value a no-op An explicit null on a minted field now compiles to a clear only when the stored block holds a value, so re-applying it over a cleared token no longer reports a change. --- .../code/corpus/editing.corpus.test.ts | 21 +++++++++++++++++++ packages/workflow-code/src/compile/blocks.ts | 9 ++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts b/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts index 9312e29df09..d9517002040 100644 --- a/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts +++ b/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts @@ -989,4 +989,25 @@ describe('a webhook token creation minted', () => { ) expect(applied.materialized?.state.blocks[webhook.id]?.subBlocks.token?.value).toBeNull() }) + + it('re-applies an explicit null over a cleared token as a no-op', () => { + const [webhookCase] = generateReapplyCorpus() + if (!webhookCase) throw new Error('the registry has no generic_webhook block') + const state = structuredClone(webhookCase.state) + const [webhook] = Object.values(state.blocks) + const token = webhook?.subBlocks.token + if (!webhook || !token) throw new Error('the webhook fixture has no token subBlock') + token.value = null + const got = getSource(state, catalog) + const entry = got.files[SOURCE_ENTRY_FILE] ?? '' + expect(entry).toContain('{ requireAuth: true }') + const withNull = entry.replace('{ requireAuth: true }', '{ requireAuth: true, token: null }') + const applied = applySource( + state, + got, + { ...got.files, [SOURCE_ENTRY_FILE]: withNull }, + catalog + ) + expect(applied.noop).toBe(true) + }) }) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index a0848b5157b..e240643ea23 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -909,8 +909,13 @@ function compileField( if (compiled.kind === 'absent' || compiled.kind === 'todo') { for (const member of field.kind === 'pair' ? field.members : [field.sub]) { state.unset.add(member.id) - // Leaving out a field creation mints keeps the stored value; a written `null` clears it. - if (compiled.kind === 'absent' && mintsFreshValue(member)) { + // Leaving out a field creation mints keeps the stored value; a written `null` clears a + // stored one (nothing to clear when none is stored, so an unchanged apply stays a no-op). + if ( + compiled.kind === 'absent' && + mintsFreshValue(member) && + storedParamOf(ctx, decl, member.id) !== undefined + ) { setOwn(params, member.id, { kind: 'value', value: null }) } } From 2cb1a12073a6010b390432a3e9d319154bcc131d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 19:29:54 -0800 Subject: [PATCH 5/5] fix(workflow-code): keep an explicit null on a new minted field A new block's `token: null` compiled to nothing after the no-op fix, so create minted a token and the next apply cleared it. The clearing null is now written for a new block as well as over a stored value, and skipped only when the stored block already holds none. --- .../code/corpus/editing.corpus.test.ts | 32 +++++++++++++++++++ packages/workflow-code/src/compile/blocks.ts | 17 ++++++---- 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts b/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts index d9517002040..9a9cc52e242 100644 --- a/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts +++ b/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts @@ -1010,4 +1010,36 @@ describe('a webhook token creation minted', () => { ) expect(applied.noop).toBe(true) }) + + it('keeps an explicit null on a new webhook, and re-applying it is a no-op', () => { + const [webhookCase] = generateReapplyCorpus() + if (!webhookCase) throw new Error('the registry has no generic_webhook block') + const state = structuredClone(webhookCase.state) + const got = getSource(state, catalog) + const entry = got.files[SOURCE_ENTRY_FILE] ?? '' + const added = + " const hookTwo = trigger.webhook('Hook Two', { token: null }, { triggerMode: true })\n})" + expect(entry.trimEnd().endsWith('})')).toBe(true) + const withNew = `${entry.trimEnd().slice(0, -2)}${added}\n` + const created = applySource(state, got, { ...got.files, [SOURCE_ENTRY_FILE]: withNew }, catalog) + const next = created.materialized?.state + if (!next) throw new Error('adding the webhook did not apply') + const hookTwo = Object.values(next.blocks).find((block) => block.name === 'Hook Two') + expect(hookTwo?.subBlocks.token?.value ?? null).toBeNull() + + const again = getSource(next, catalog) + const againEntry = again.files[SOURCE_ENTRY_FILE] ?? '' + const reapplied = againEntry.replace( + "trigger.webhook('Hook Two', {", + "trigger.webhook('Hook Two', { token: null," + ) + expect(reapplied).toContain("trigger.webhook('Hook Two', { token: null,") + const second = applySource( + next, + again, + { ...again.files, [SOURCE_ENTRY_FILE]: reapplied }, + catalog + ) + expect(second.noop).toBe(true) + }) }) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index e240643ea23..133d77f7d52 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -849,15 +849,20 @@ function keepStored( if (field && mode) setOwn(modes, field.param, mode) } +/** The stored block `decl` continues, when it exists with the same type. */ +function storedBlockOf(ctx: CompileContext, decl: BlockDecl): CanonicalBlock | undefined { + const stored = ctx.stored ? getOwn(ctx.stored.blocks, decl.key) : undefined + return stored && stored.type === catalogBlockOf(decl)?.type ? stored : undefined +} + /** The stored param `id` of the block `decl` continues, when the stored block has the same type. */ function storedParamOf( ctx: CompileContext, decl: BlockDecl, id: SubBlockId ): CanonicalParam | undefined { - const stored = ctx.stored ? getOwn(ctx.stored.blocks, decl.key) : undefined - if (!stored || stored.type !== catalogBlockOf(decl)?.type) return undefined - return getOwn(stored.params, id) + const stored = storedBlockOf(ctx, decl) + return stored ? getOwn(stored.params, id) : undefined } /** Compiles one catalog param into its member subBlock (`pairMode` picks a pair's member). */ @@ -909,12 +914,12 @@ function compileField( if (compiled.kind === 'absent' || compiled.kind === 'todo') { for (const member of field.kind === 'pair' ? field.members : [field.sub]) { state.unset.add(member.id) - // Leaving out a field creation mints keeps the stored value; a written `null` clears a - // stored one (nothing to clear when none is stored, so an unchanged apply stays a no-op). + // Leaving out a field creation mints keeps the stored value; a written `null` stores null + // on a new block and clears a stored value (none stored: nothing to write, still a no-op). if ( compiled.kind === 'absent' && mintsFreshValue(member) && - storedParamOf(ctx, decl, member.id) !== undefined + (!storedBlockOf(ctx, decl) || storedParamOf(ctx, decl, member.id) !== undefined) ) { setOwn(params, member.id, { kind: 'value', value: null }) }