Skip to content

Commit 79081df

Browse files
authored
fix(workflow-code): json-text mapping escaping, client bundle, source find follow-ups (#10446)
* fix(workflow-code): escape references in JSON-text input mappings, keep compiler out of client bundles, source find edge cases * fix(sim-cli): join wrapped wiring statements at line breaks only; refuse names that normalize empty
1 parent 9ba6dbc commit 79081df

18 files changed

Lines changed: 182 additions & 57 deletions

File tree

‎apps/docs/content/docs/cli/reference.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8865,7 +8865,7 @@ sim workflows source find <block> [options]
88658865

88668866
</CommandTable>
88678867

8868-
Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. &lt;block&gt; is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir.
8868+
Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. &lt;block&gt; is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false).
88698869

88708870
Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory.
88718871

‎apps/docs/content/docs/cli/workflows.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1597,7 +1597,7 @@ sim workflows source find <block> [options]
15971597

15981598
</CommandTable>
15991599

1600-
Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. &lt;block&gt; is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir.
1600+
Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. &lt;block&gt; is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false).
16011601

16021602
Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory.
16031603

‎apps/sim/executor/variables/resolver.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { StartBlockPath } from '@/lib/workflows/triggers/triggers'
1919
import { AgentBlock } from '@/blocks/blocks/agent'
2020
import { ResponseBlock } from '@/blocks/blocks/response'
2121
import { TableV2Block } from '@/blocks/blocks/table_v2'
22+
import { WorkflowInputBlock } from '@/blocks/blocks/workflow_input'
2223
import { getBlock } from '@/blocks/registry'
2324
import type { BlockConfig } from '@/blocks/types'
2425
import { BlockType } from '@/executor/constants'
@@ -1296,6 +1297,7 @@ describe('VariableResolver JSON text inputs', () => {
12961297
[BlockType.AGENT]: AgentBlock,
12971298
[BlockType.RESPONSE]: ResponseBlock,
12981299
table_v2: TableV2Block,
1300+
[BlockType.WORKFLOW_INPUT]: WorkflowInputBlock,
12991301
}
13001302

13011303
beforeEach(() => {
@@ -1452,6 +1454,18 @@ describe('VariableResolver JSON text inputs', () => {
14521454
expect(JSON.parse(resolved.data)).toEqual({ body: awkwardText })
14531455
})
14541456

1457+
it('escapes references in a child workflow input mapping stored as JSON text', async () => {
1458+
const { resolve } = createJsonResolver(BlockType.WORKFLOW_INPUT, {
1459+
workflowId: 'child',
1460+
inputMapping: '{"summary": "<producer.text>", "record": "<producer.record>"}',
1461+
})
1462+
const resolved = await resolve()
1463+
expect(JSON.parse(resolved.inputMapping)).toEqual({
1464+
summary: awkwardText,
1465+
record: JSON.stringify({ name: 'Ada "the first"', tags: ['x', 'y'] }),
1466+
})
1467+
})
1468+
14551469
it('leaves quoted references in non-JSON fields raw', async () => {
14561470
const { resolve } = createJsonResolver(BlockType.AGENT, {
14571471
userPrompt: '{"note": "<producer.text>"}',

‎apps/sim/executor/variables/resolver.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createLogger } from '@sim/logger'
22
import { toError } from '@sim/utils/errors'
3+
import { JSON_TEXT_CONTAINER_TYPES } from '@sim/workflow-code/json-text'
34
import { isUserFileWithMetadata } from '@/lib/core/utils/user-file'
45
import { mergeLargeValueKeys } from '@/lib/execution/payloads/access-keys'
56
import { isLargeArrayManifest } from '@/lib/execution/payloads/large-array-manifest-metadata'
@@ -322,16 +323,19 @@ interface TemplateResolutionOptions {
322323
jsonText?: boolean
323324
}
324325

325-
/** Whether `key` is a block input the editor stores as JSON text (a JSON code field). */
326-
function isJsonCodeInput(block: SerializedBlock | undefined, key: string): boolean {
326+
/**
327+
* Whether `key` is a block input that may hold JSON text: a JSON code field, or a container field
328+
* (`JSON_TEXT_CONTAINER_TYPES`) whose runtime parses text and objects alike.
329+
*/
330+
function isJsonTextInput(block: SerializedBlock | undefined, key: string): boolean {
327331
const blockType = block?.metadata?.id
328332
if (!blockType) return false
329333
return (
330334
getBlock(blockType)?.subBlocks.some(
331335
(subBlock) =>
332-
subBlock.type === 'code' &&
333-
subBlock.language === 'json' &&
334-
(subBlock.id === key || subBlock.canonicalParamId === key)
336+
(subBlock.id === key || subBlock.canonicalParamId === key) &&
337+
((subBlock.type === 'code' && subBlock.language === 'json') ||
338+
JSON_TEXT_CONTAINER_TYPES.has(subBlock.type))
335339
) ?? false
336340
)
337341
}
@@ -516,7 +520,7 @@ export class VariableResolver {
516520
resolved[key] = await this.resolveValue(ctx, currentNodeId, value, undefined, block, {
517521
allowLargeValueRefs: this.canResolveInputToLargeValueRef(block, key),
518522
inputPath: [key],
519-
jsonText: typeof value === 'string' && isJSONString(value) && isJsonCodeInput(block, key),
523+
jsonText: typeof value === 'string' && isJSONString(value) && isJsonTextInput(block, key),
520524
})
521525
}
522526
return resolved

‎apps/sim/lib/workflows/canonical/subblock-value.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '@sim/workflow-code'
1+
import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '@sim/workflow-code/json-text'
22
import {
33
normalizedStringify,
44
sanitizeInputFormat,

‎apps/sim/lib/workflows/code/api-built-source.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,3 +168,26 @@ describe('a child workflow call whose input mapping the operations route stored
168168
expect(typeCheckAgainstSdk(workDir, 'edited', [file])).toBe('')
169169
}, 120_000)
170170
})
171+
172+
describe('a child workflow call whose input mapping is one whole reference', () => {
173+
it('stores an object written over the reference natively, not as JSON text', () => {
174+
const stored = builtWorkflow()
175+
const call = createBlockFromParams('call-block', {
176+
type: 'workflow_input',
177+
name: 'Record Audit',
178+
inputs: { workflowId: 'child-workflow', inputMapping: '<start.input>' },
179+
})
180+
stored.blocks[call.id] = { ...call, position: { x: 800, y: 0 } }
181+
const written = getThenApply(stored, (text) =>
182+
text.replace(
183+
'inputMapping: start.input,',
184+
"inputMapping: { ticketId: start.input, source: 'api' },"
185+
)
186+
)
187+
expect(written.errors).toEqual([])
188+
expect(written.state.blocks['call-block']?.subBlocks.inputMapping?.value).toEqual({
189+
ticketId: '<start.input>',
190+
source: 'api',
191+
})
192+
})
193+
})

‎packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ beforeEach(() => {
6060
writeFileSync(join(dir, 'workflow.ts'), WORKFLOW_TS)
6161
writeFileSync(
6262
join(dir, 'functions/score.js'),
63-
"const s = 1\nreturn $ref.fetchpolicy.data\nconst tag = '<fetchpolicy.status>'\n"
63+
"const s = 1\nreturn $ref.fetchpolicy.data ?? $ref.fetchpolicy.status\nconst tag = '<fetchpolicy.status>'\n"
6464
)
6565
writeFileSync(join(dir, 'functions/audit.py'), 'import json\nprint(<fetchpolicy.data>)\n')
6666
vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config'))
@@ -128,4 +128,30 @@ describe('sim workflows source find', () => {
128128
message: expect.stringContaining('Did you mean Fetch Policy?'),
129129
})
130130
})
131+
132+
it('says the source does not compile instead of only that no block matches', async () => {
133+
writeFileSync(
134+
join(dir, 'workflow.ts'),
135+
WORKFLOW_TS.replace("api('Fetch Policy', {", "api('Fetch Policy', {{")
136+
)
137+
await expect(find('Fetch Policy')).rejects.toMatchObject({
138+
code: 'BLOCK_UNKNOWN',
139+
message: expect.stringContaining('does not compile'),
140+
})
141+
})
142+
143+
it('reads a wiring statement the printer wrapped as one statement', async () => {
144+
const wrapped = WORKFLOW_TS.replace('fetchPolicy.to(audit)', 'fetchPolicy.to(\n audit,\n )')
145+
writeFileSync(join(dir, 'workflow.ts'), wrapped)
146+
await find('Audit')
147+
const [block] = stdoutJson().blocks
148+
expect(block.incoming).toMatchObject([
149+
{ block: 'Fetch Policy', statement: 'fetchPolicy.to(audit)' },
150+
])
151+
})
152+
153+
it('refuses an empty name rather than matching every block', async () => {
154+
await expect(find(' ')).rejects.toMatchObject({ code: 'BLOCK_UNKNOWN' })
155+
await expect(find('.')).rejects.toMatchObject({ code: 'BLOCK_UNKNOWN' })
156+
})
131157
})

‎packages/sim-cli/src/commands/protocol/workflow-source-find.ts‎

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
fromCodeFile,
1212
LineIndex,
1313
referencedHeads,
14+
type SourceSpan,
1415
type StoredEdgeRef,
1516
} from '@sim/workflow-code'
1617
import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
@@ -35,6 +36,7 @@ incoming and outgoing edges, and every block that reads its outputs (a param, a
3536
function file's $ref), each as file:line. <block> is a block name (Security Score), its key
3637
(securityscore) or its identifier (securityScore); with no exact match, every block whose name
3738
contains it is printed (at most ${MAX_FOUND}). Run it from a workflow source directory, or pass --dir.
39+
When the source does not compile, readers are left out (JSON output carries compiles: false).
3840
3941
Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the
4042
directory is not a workflow source directory.`
@@ -132,7 +134,11 @@ function blockFields(block: CanonicalBlock): Array<{ field: string; texts: strin
132134
*/
133135
function readersByKey(index: SourceIndex): Map<BlockKey, Reader[]> {
134136
const readers = new Map<BlockKey, Reader[]>()
137+
const seen = new Set<string>()
135138
const add = (key: BlockKey, reader: Reader) => {
139+
const id = JSON.stringify([key, reader.file, reader.line, reader.block, reader.field])
140+
if (seen.has(id)) return
141+
seen.add(id)
136142
const list = readers.get(key)
137143
if (list) list.push(reader)
138144
else readers.set(key, [reader])
@@ -184,14 +190,38 @@ function matchBlocks(index: SourceIndex, query: string): BlockKey[] {
184190
.filter((key) => key.includes(normalized) || index.nameOf(key).toLowerCase().includes(needle))
185191
}
186192

187-
/** The refusal for a query no block matches, naming the closest block. */
193+
/**
194+
* The refusal for a query no block matches, naming the closest block, and saying so when the
195+
* source does not compile (a parse failure names no blocks at all).
196+
*/
188197
function unknownBlock(index: SourceIndex, query: string): CliUsageError {
189198
const names = index
190199
.keys()
191200
.map((key) => index.nameOf(key))
192201
.sort(compareStrings)
193202
const hint = didYouMean(query, names) ?? `It has ${names.length} blocks.`
194-
return new CliUsageError(`No block is named ${query}. ${hint}`, { code: 'BLOCK_UNKNOWN' })
203+
const compileNote =
204+
index.compiled.workflow === null
205+
? ' The source does not compile: run `sim workflows source check`.'
206+
: ''
207+
return new CliUsageError(`No block is named ${query}. ${hint}${compileNote}`, {
208+
code: 'BLOCK_UNKNOWN',
209+
})
210+
}
211+
212+
/**
213+
* A wiring statement's text on one line, so a fan-out the printer wrapped reads whole. Only the
214+
* line breaks are rewritten, so a raw handle's text is printed as written.
215+
*/
216+
function statementText(index: SourceIndex, span: SourceSpan): string {
217+
const lines = index.linesOf(span.file)?.lines.slice(span.line - 1, span.endLine) ?? []
218+
return lines
219+
.map((line) => line.trim())
220+
.reduce((joined, line) => {
221+
if (joined === '') return line
222+
if (line.startsWith(')')) return `${joined.replace(/,$/, '')}${line}`
223+
return joined.endsWith('(') ? `${joined}${line}` : `${joined} ${line}`
224+
}, '')
195225
}
196226

197227
function describeBlock(
@@ -209,9 +239,7 @@ function describeBlock(
209239
port: ref.port,
210240
file: written?.file ?? SOURCE_ENTRY_FILE,
211241
line: written?.line ?? span?.line ?? 0,
212-
statement: written
213-
? (index.linesOf(written.file)?.lines[written.line - 1]?.trim() ?? '')
214-
: '',
242+
statement: written ? statementText(index, written) : '',
215243
}
216244
}
217245
const ends = (side: 'from' | 'to', other: 'from' | 'to') =>
@@ -273,6 +301,9 @@ export function attachWorkflowSourceFind(source: Command): void {
273301
await assertSourceDirKind(options.dir, 'workflow')
274302
const catalog = await lookupCatalog(options.dir, profile)
275303
const { compiled, files } = await compileWorkflowDir(options.dir, catalog)
304+
if (normalizeWorkflowBlockName(query) === '') {
305+
throw new CliUsageError('Name a block.', { code: 'BLOCK_UNKNOWN' })
306+
}
276307
const index = new SourceIndex(compiled, files)
277308
const keys = matchBlocks(index, query)
278309
if (keys.length === 0) throw unknownBlock(index, query)
@@ -283,7 +314,11 @@ export function attachWorkflowSourceFind(source: Command): void {
283314
.sort(byLine)
284315
const more = keys.length - found.length
285316
if (isMachine(profile.output)) {
286-
printProtocolResult(profile.output, { blocks: found, ...(more > 0 ? { more } : {}) })
317+
printProtocolResult(profile.output, {
318+
blocks: found,
319+
compiles: compiled.workflow !== null,
320+
...(more > 0 ? { more } : {}),
321+
})
287322
return
288323
}
289324
if (compiled.workflow === null) {

‎packages/workflow-code/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@
2222
"types": "./src/diagnostics/codes.ts",
2323
"default": "./src/diagnostics/codes.ts"
2424
},
25+
"./json-text": {
26+
"types": "./src/json-text.ts",
27+
"default": "./src/json-text.ts"
28+
},
2529
"./code-files/references": {
2630
"types": "./src/code-files/references.ts",
2731
"default": "./src/code-files/references.ts"

‎packages/workflow-code/src/canonicalize/params.ts‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ import { isConditionClause } from '../catalog/conditions'
55
import type { CatalogBlock, CatalogCondition, CatalogSubBlock } from '../catalog/types'
66
import { declarationsOf } from '../catalog/view'
77
import { diagnostic } from '../diagnostics/factory'
8+
import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '../json-text'
89
import type { BlockKey, CanonicalParam, SubBlockId, Value } from '../model'
9-
import { parseJsonContainer, setOwn } from '../records'
10+
import { setOwn } from '../records'
1011
import { structuredCodec } from '../structured'
1112
import type { CanonContext } from './context'
1213
import { liftTools } from './tools'
@@ -60,18 +61,6 @@ function holdsJsonText(declaration: CatalogSubBlock): boolean {
6061
return declaration.structured !== undefined || declaration.storage === 'json-string'
6162
}
6263

63-
/**
64-
* Field types whose runtime reads JSON text and the container it encodes alike: the workflow
65-
* handler and the tool runners parse a child workflow's `inputMapping` either way, and the
66-
* operations route stores either. Canonicalize decodes the text so it prints as the object source
67-
* can type, and deploy-change detection takes the two encodings as one value. Any other native
68-
* container field stays as stored, since its runtime reads only one form.
69-
*/
70-
export const JSON_TEXT_CONTAINER_TYPES: ReadonlySet<string> = new Set([
71-
'input-mapping',
72-
'workflow-input-mapper',
73-
])
74-
7564
/** A field of a {@link JSON_TEXT_CONTAINER_TYPES} type; text that does not parse stays a value. */
7665
function holdsNativeContainer(declaration: CatalogSubBlock): boolean {
7766
return JSON_TEXT_CONTAINER_TYPES.has(declaration.type)

0 commit comments

Comments
 (0)