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..9a9cc52e242 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,78 @@ 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() + }) + + 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) + }) + + 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/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 7f9ccac52c5..dffc02aa679 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}`) } } @@ -139,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 2a9b80caade..b9c58dd9601 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 { @@ -184,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({ @@ -200,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) @@ -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,111 @@ 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) throw new Error(`The ${block.type} fixture has no ${id} subBlock`) + subBlock.value = value as typeof subBlock.value + } + + 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}`) + startBlock(builder, registry, 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 +1221,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..214d3625c0f 100644 --- a/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts +++ b/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts @@ -33,9 +33,10 @@ 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, + caseSubject, corpusBudgetMs, corpusSubjects, type ProofSubject, @@ -73,6 +74,9 @@ 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(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):/ @@ -334,14 +338,19 @@ 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 reapplyIds = new Set(reapplySubjects.map((subject) => subject.id)) + const refusedReapply: 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')) { + if (reapplyIds.has(subject.id)) refusedReapply.push(subject.id) + continue + } applied++ const stored = materialized(first.workflow) const base = canonicalize(stored, { @@ -373,6 +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([...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 7bc14648ed5..133d77f7d52 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, @@ -849,6 +849,22 @@ 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 = storedBlockOf(ctx, decl) + return stored ? getOwn(stored.params, id) : undefined +} + /** Compiles one catalog param into its member subBlock (`pairMode` picks a pair's member). */ function compileField( ctx: CompileContext, @@ -860,12 +876,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 @@ -878,7 +890,12 @@ function compileField( : field.kind === 'single' ? field.sub : undefined - if (jsonTarget?.type === 'code') { + // 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) @@ -895,8 +912,18 @@ 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` 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) && + (!storedBlockOf(ctx, decl) || storedParamOf(ctx, decl, member.id) !== undefined) + ) { + setOwn(params, member.id, { kind: 'value', value: null }) + } + } if (compiled.kind === 'todo') state.todos.set(field.name, property) return } @@ -1104,13 +1131,22 @@ function compileWrittenParams( recordSpan(ctx, { kind: 'param', block: decl.key, param: name }, property) if (branchField && key === branchField.subBlockId) { if (property.value.type !== 'ObjectExpression') { - unsupported( - ctx, - property.value, - 'Branches are an object literal.', - 'Write { if: js`...`, else: true }.', - decl.key - ) + // `raw(v)`: a stored branch value that does not lift into rows, kept verbatim. + 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 }) + } 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 + ) + } continue } const rows = objectEntries(ctx, property.value, (duplicate, name) => { 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..d715b65c97f 100644 --- a/packages/workflow-code/src/print/params.ts +++ b/packages/workflow-code/src/print/params.ts @@ -120,13 +120,19 @@ export function fieldContext( } } +/** + * 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. + */ function printParamValue( ctx: PrintContext, block: CanonicalBlock, declared: CatalogBlock | undefined, id: string, sb: CatalogSubBlock | undefined, - single = false + typed: boolean, + jsonLiteral = false ): PrintedValue | null { const param = getOwn(block.params, id) if (!param) return null @@ -134,7 +140,12 @@ 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 ( + jsonLiteral && + sb?.type === 'code' && + sb.valueKind === 'json' && + typeof param.value === 'string' + ) { const literal = printJsonField(ctx, block, param.value) if (literal) return literal } @@ -147,6 +158,7 @@ function printParamValue( if (structured) return structured if ( ctx.options.functionCode === 'files' && + typed && sb?.valueKind === 'code' && (context.tag === 'js' || context.tag === 'py' || context.tag === 'sh') && typeof param.value === 'string' && @@ -352,7 +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) + 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) @@ -385,9 +397,9 @@ 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) + // 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) @@ -399,7 +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) + 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 18eca8e2bb0..8803f62262d 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,19 +152,21 @@ function blockCall(ctx: PrintContext, block: CanonicalBlock): Expr { let generic = found === null let topLevel: Property[] = paramProps - 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 460872038f8..ed7360cc94a 100644 --- a/packages/workflow-code/src/print/tools.ts +++ b/packages/workflow-code/src/print/tools.ts @@ -260,7 +260,9 @@ export function printTools( /** * 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, @@ -272,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] @@ -306,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 0216cc4d007..125056d397d 100644 --- a/packages/workflow-code/src/structured/input-format.ts +++ b/packages/workflow-code/src/structured/input-format.ts @@ -315,13 +315,16 @@ export const INPUT_FORMAT_CODEC: StructuredCodec = { return inputFormatItems(value) }, print(value, { values, block }) { - if (!Array.isArray(value)) return null + // 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 (!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) ) ) },