Skip to content

Commit b1f4fbb

Browse files
committed
fix(workflow-code): exact JSON-text equivalence, per-edge find locations, layout-aware tests
- Decode JSON text, and treat it as unchanged in deploy-change detection, only for input-mapping fields, whose runtime parses both forms (JSON_TEXT_CONTAINER_TYPES). Other container fields such as a checkbox list compare as stored again. - Compile records where each edge is written (edgeSpans), and `source find` reports every edge at its own statement. - `source find` reads function-file references the way compile does (codeFileRefs: parsed chains plus stored tags) in the file's own language. - Integration edits follow the interleaved wiring layout; docs baseline takes the new CLI reference code examples.
1 parent d84ee0f commit b1f4fbb

14 files changed

Lines changed: 1029 additions & 936 deletions

File tree

‎apps/docs/scripts/fixtures/content-baseline.json‎

Lines changed: 854 additions & 840 deletions
Large diffs are not rendered by default.

‎apps/sim/lib/workflows/application/apply-workflow-source.integration.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3008,9 +3008,10 @@ describe('renames in source', () => {
30083008
files = edit(renameIdent(files, ident, newIdent), `fn('${name}'`, `fn('${newName}'`)
30093009
}
30103010
files = edit(edit(files, 'return 1', 'return 10'), 'return 2', 'return 20')
3011+
files = edit(edit(files, ' start.to(bang)\n', ''), ' bang.to(total)\n', '')
30113012
files = edit(
30123013
files,
3013-
' start.to(bang)\n bang.to(total)\n total.to(report)',
3014+
' total.to(report)',
30143015
' start.to(report)\n report.to(bang)\n report.to(total)'
30153016
)
30163017

@@ -3054,12 +3055,16 @@ describe('renames in source', () => {
30543055
...edit(
30553056
edit(
30563057
edit(
3057-
source.files,
3058-
" const tally = fn('Tally', { language: null, code: codeFile('./functions/tally.js') })\n",
3059-
" const fresh = fn('Fresh', { code: js`return 'unrelated'` })\n"
3058+
edit(
3059+
source.files,
3060+
" const tally = fn('Tally', { language: null, code: codeFile('./functions/tally.js') })\n",
3061+
" const fresh = fn('Fresh', { code: js`return 'unrelated'` })\n"
3062+
),
3063+
' boom.to(tally)\n',
3064+
' start.to(fresh)\n'
30603065
),
3061-
' boom.to(tally)\n tally.to(report)',
3062-
' boom.to(report)\n start.to(fresh)'
3066+
' tally.to(report)',
3067+
' boom.to(report)'
30633068
),
30643069
'import { codeFile, fn,',
30653070
'import { codeFile, fn, js,'
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Deploy-change detection takes JSON text and the container it encodes as one value only where the
3+
* runtime reads both alike (a child workflow's `inputMapping`); anywhere else the encoding is a
4+
* change, because the runtime reads one form only (a Jina `readUrlOptions` held as text sends no
5+
* options).
6+
*/
7+
import { describe, expect, it, vi } from 'vitest'
8+
9+
vi.unmock('@/blocks/registry')
10+
vi.mock('@/blocks/registry-maps', async () => {
11+
const { partialBlockRegistry } = await import('@sim/testing/mocks/block-registry.mock')
12+
return partialBlockRegistry(
13+
await import('@/blocks/blocks/jina'),
14+
await import('@/blocks/blocks/workflow_input')
15+
)
16+
})
17+
18+
import { hasWorkflowChanged } from '@/lib/workflows/comparison/compare'
19+
import type { WorkflowState } from '@/stores/workflows/workflow/types'
20+
21+
function withValue(type: string, subBlockId: string, subBlockType: string, value: unknown) {
22+
return {
23+
blocks: {
24+
block: {
25+
id: 'block',
26+
type,
27+
name: 'Block',
28+
position: { x: 0, y: 0 },
29+
subBlocks: { [subBlockId]: { id: subBlockId, type: subBlockType, value } },
30+
outputs: {},
31+
enabled: true,
32+
},
33+
},
34+
edges: [],
35+
loops: {},
36+
parallels: {},
37+
} as unknown as WorkflowState
38+
}
39+
40+
describe('deploy-change detection over JSON text', () => {
41+
it('takes an input mapping as text and as an object as one value', () => {
42+
const text = withValue('workflow_input', 'inputMapping', 'input-mapping', '{"id":"<start.id>"}')
43+
const object = withValue('workflow_input', 'inputMapping', 'input-mapping', {
44+
id: '<start.id>',
45+
})
46+
expect(hasWorkflowChanged(object, text)).toBe(false)
47+
})
48+
49+
it('reports a checkbox list moving between text and an object, which runs differently', () => {
50+
const text = withValue('jina', 'readUrlOptions', 'checkbox-list', '{"gatherLinks":true}')
51+
const object = withValue('jina', 'readUrlOptions', 'checkbox-list', { gatherLinks: true })
52+
expect(hasWorkflowChanged(object, text)).toBe(true)
53+
})
54+
})

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

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { parseJsonContainer } from '@sim/workflow-code'
2-
import { holdsNativeContainer } from '@/lib/workflows/code/catalog/value-kind'
1+
import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '@sim/workflow-code'
32
import {
43
normalizedStringify,
54
sanitizeInputFormat,
@@ -59,12 +58,15 @@ export function shapeSubBlockValue(
5958
}
6059

6160
/**
62-
* JSON text in a field that holds a container natively (an `inputMapping` the operations route
63-
* stored as text) is that container: the executor parses both alike, so a change of encoding alone
64-
* is no change to deploy. The diff view still shows the encoding (`shapeSubBlockValue`).
61+
* JSON text in a field whose runtime parses it like the container it encodes (a child workflow's
62+
* `inputMapping`, `JSON_TEXT_CONTAINER_TYPES`) is that container, so a change of encoding alone is
63+
* no change to deploy. Every other field compares as stored, and the diff view still shows the
64+
* encoding (`shapeSubBlockValue`).
6565
*/
6666
function decodeNativeContainer(value: unknown, spec: CanonicalFieldSpec | undefined): unknown {
67-
if (typeof value !== 'string' || !spec?.type || !holdsNativeContainer(spec.type)) return value
67+
if (typeof value !== 'string' || !spec?.type || !JSON_TEXT_CONTAINER_TYPES.has(spec.type)) {
68+
return value
69+
}
6870
return parseJsonContainer(value) ?? value
6971
}
7072

‎apps/sim/lib/workflows/code/catalog/value-kind.ts‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import type {
44
ParamStorage,
55
ResourceKind,
66
} from '@sim/workflow-code'
7-
import { getOwn } from '@sim/workflow-code'
87
import type { SubBlockConfig, SubBlockType } from '@/blocks/types'
98

109
/**
@@ -89,20 +88,6 @@ const TYPE_RULES: Record<SubBlockType, TypeRule> = {
8988
modal: { valueKind: 'none' },
9089
}
9190

92-
/**
93-
* Whether a field of `type` holds a JSON object or list natively: the editor writes the container,
94-
* while the operations route and older editors may store the same container as JSON text, which
95-
* the executor parses alike.
96-
*/
97-
export function holdsNativeContainer(type: string): boolean {
98-
const rule = getOwn(TYPE_RULES, type)
99-
return (
100-
(rule?.valueKind === 'object' || rule?.valueKind === 'array') &&
101-
rule.storage === undefined &&
102-
rule.structured === undefined
103-
)
104-
}
105-
10691
/**
10792
* Derives a subBlock's value shape from its type plus the few config flags that change it: a
10893
* JSON-language code field holds JSON, a multi-select dropdown holds an array, a `readOnly` field

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ export default workflow('W', {}, () => {
2626
fetchPolicy.to(score)
2727
const fallback = fn('Fallback', { code: js\`return 0\` })
2828
fetchPolicy.onError(fallback)
29+
const audit = fn('Audit', { language: 'python', code: codeFile('./functions/audit.py') })
30+
fetchPolicy.to(audit)
2931
const gate = condition('Gate', { if: js\`\${fetchPolicy.status} === 200\`, else: true })
3032
score.to(gate)
3133
})
@@ -56,7 +58,11 @@ beforeEach(() => {
5658
mkdirSync(join(dir, '.sim'))
5759
mkdirSync(join(dir, 'functions'))
5860
writeFileSync(join(dir, 'workflow.ts'), WORKFLOW_TS)
59-
writeFileSync(join(dir, 'functions/score.js'), 'const s = 1\nreturn $ref.fetchpolicy.data\n')
61+
writeFileSync(
62+
join(dir, 'functions/score.js'),
63+
"const s = 1\nreturn $ref.fetchpolicy.data\nconst tag = '<fetchpolicy.status>'\n"
64+
)
65+
writeFileSync(join(dir, 'functions/audit.py'), 'import json\nprint(<fetchpolicy.data>)\n')
6066
vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config'))
6167
cacheCatalogText(join(dir, 'config'), null, FIXTURE_TEXT)
6268
writeFileSync(
@@ -91,9 +97,17 @@ describe('sim workflows source find', () => {
9197
outgoing: [
9298
{ block: 'Score', port: 'out', line: lineOf('fetchPolicy.to(score)') },
9399
{ block: 'Fallback', port: 'error', line: lineOf('fetchPolicy.onError(fallback)') },
100+
{
101+
block: 'Audit',
102+
port: 'out',
103+
line: lineOf('fetchPolicy.to(audit)'),
104+
statement: 'fetchPolicy.to(audit)',
105+
},
94106
],
95107
readers: [
108+
{ block: 'Audit', file: 'functions/audit.py', line: 2 },
96109
{ block: 'Score', file: 'functions/score.js', line: 2 },
110+
{ block: 'Score', file: 'functions/score.js', line: 3 },
97111
{ block: 'Gate', file: 'workflow.ts', line: lineOf("condition('Gate'") },
98112
],
99113
})

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

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import {
44
type BlockKey,
55
type CanonicalBlock,
66
type CompileResult,
7+
codeFileLanguage,
8+
codeFileRefs,
79
didYouMean,
810
encodeAnchor,
911
fromCodeFile,
@@ -142,10 +144,9 @@ function readersByKey(index: SourceIndex): Map<BlockKey, Reader[]> {
142144
const heads = new Set(texts.flatMap(referencedHeads))
143145
heads.delete(readerKey)
144146
if (heads.size === 0) continue
145-
const parsed =
146-
field === 'code' && codeLines ? fromCodeFile(codeLines.text, 'javascript') : null
147-
if (codeFile && codeLines && parsed?.ok) {
148-
for (const ref of parsed.refs) {
147+
if (field === 'code' && codeFile && codeLines) {
148+
const parsed = fromCodeFile(codeLines.text, codeFileLanguage(codeFile) ?? 'javascript')
149+
for (const ref of codeFileRefs(parsed.ok ? parsed.refs : [], codeLines.text)) {
149150
const [head] = ref.kind === 'ref' ? ref.segments : []
150151
if (head?.kind !== 'name' || !heads.has(head.name)) continue
151152
const { line } = codeLines.position(ref.start)
@@ -199,19 +200,22 @@ function describeBlock(
199200
key: BlockKey
200201
): FoundBlock {
201202
const span = index.span({ kind: 'block', block: key })
202-
const edge = (ref: StoredEdgeRef, other: BlockKey): FoundEdge => {
203-
const at = index.span({ kind: 'edges', block: ref.from, port: ref.port })
203+
const { edges, edgeSpans } = index.compiled
204+
const edge = (at: number, other: BlockKey): FoundEdge => {
205+
const ref = edges[at]
206+
const written = edgeSpans[at]
204207
return {
205208
block: index.nameOf(other),
206209
port: ref.port,
207-
file: at?.file ?? SOURCE_ENTRY_FILE,
208-
line: at?.line ?? span?.line ?? 0,
209-
statement: at
210-
? (index.linesOf(at.file)?.lines[at.line - 1]?.trim() ?? '')
211-
: '(implied by the container)',
210+
file: written?.file ?? SOURCE_ENTRY_FILE,
211+
line: written?.line ?? span?.line ?? 0,
212+
statement: written
213+
? (index.linesOf(written.file)?.lines[written.line - 1]?.trim() ?? '')
214+
: '',
212215
}
213216
}
214-
const { edges } = index.compiled
217+
const ends = (side: 'from' | 'to', other: 'from' | 'to') =>
218+
edges.flatMap((ref, at) => (ref[side] === key ? [edge(at, ref[other])] : [])).sort(byLine)
215219
return {
216220
name: index.nameOf(key),
217221
key,
@@ -221,14 +225,8 @@ function describeBlock(
221225
line: span?.line ?? 0,
222226
endLine: span?.endLine ?? 0,
223227
codeFile: index.codeFileOf(key),
224-
incoming: edges
225-
.filter((ref) => ref.to === key)
226-
.map((ref) => edge(ref, ref.from))
227-
.sort(byLine),
228-
outgoing: edges
229-
.filter((ref) => ref.from === key)
230-
.map((ref) => edge(ref, ref.to))
231-
.sort(byLine),
228+
incoming: ends('to', 'from'),
229+
outgoing: ends('from', 'to'),
232230
readers: [...(readers.get(key) ?? [])].sort(byLine),
233231
}
234232
}

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

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,16 +61,20 @@ function holdsJsonText(declaration: CatalogSubBlock): boolean {
6161
}
6262

6363
/**
64-
* A native object or list field (a child workflow's `inputMapping`, a message list). The operations
65-
* route and older editors may store it as JSON text, which would never type-check if printed as
66-
* text, so it decodes like a structured field; text that does not parse is a value of its own (a
67-
* reference to a whole list), not a warning.
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.
6869
*/
70+
export const JSON_TEXT_CONTAINER_TYPES: ReadonlySet<string> = new Set([
71+
'input-mapping',
72+
'workflow-input-mapper',
73+
])
74+
75+
/** A field of a {@link JSON_TEXT_CONTAINER_TYPES} type; text that does not parse stays a value. */
6976
function holdsNativeContainer(declaration: CatalogSubBlock): boolean {
70-
return (
71-
!holdsJsonText(declaration) &&
72-
(declaration.valueKind === 'object' || declaration.valueKind === 'array')
73-
)
77+
return JSON_TEXT_CONTAINER_TYPES.has(declaration.type)
7478
}
7579

7680
/** Whether canonicalize decodes this subBlock's JSON text. */

‎packages/workflow-code/src/code-files/from-file.ts‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import { type ParserOptions, parse } from '@babel/parser'
22
import type { Expression, MemberExpression, Node } from '@babel/types'
3-
import { isLikelyWorkflowReferenceSegment } from '@sim/utils/workflow-references'
3+
import {
4+
findWorkflowReferenceTokens,
5+
isLikelyWorkflowReferenceSegment,
6+
} from '@sim/utils/workflow-references'
47
import { babelErrorShape, babelMessage, childNodes, memberSegment } from '../babel'
5-
import { ENV_VAR_NAME, formatStoredPath, type RefSegment } from './ref-path'
8+
import { ENV_VAR_NAME, formatStoredPath, parseStoredPath, type RefSegment } from './ref-path'
69
import { type CodeFileLanguage, ENV_ROOT, REF_ROOT } from './to-file'
710

811
interface CodeFileSyntaxError {
@@ -202,3 +205,34 @@ function collectReplacements(program: Node): Replacement[] {
202205
}
203206
return replacements
204207
}
208+
209+
/**
210+
* The `<key.path>` references a code file writes as text, found by the runtime's own scanner (a
211+
* JavaScript string, a Python or shell line): the run resolves each one, so compile checks them as
212+
* it checks a `$ref` chain. A token with no path (`<b>` in HTML text) is no reference.
213+
*/
214+
function referenceTags(text: string): CodeFileRef[] {
215+
const tags: CodeFileRef[] = []
216+
for (const token of findWorkflowReferenceTokens(text)) {
217+
if (token.kind === 'environment') {
218+
const name = token.value.slice(2, -2).trim()
219+
if (ENV_VAR_NAME.test(name)) {
220+
tags.push({ kind: 'env', name, start: token.start, end: token.end })
221+
}
222+
continue
223+
}
224+
if (token.kind !== 'workflow') continue
225+
const segments = parseStoredPath(token.value.slice(1, -1))
226+
if (!segments || segments.length < 2) continue
227+
tags.push({ kind: 'ref', segments, start: token.start, end: token.end, tag: true })
228+
}
229+
return tags
230+
}
231+
232+
/**
233+
* Every reference a code file makes as compile reads it, in file order: the `$ref`/`$env` chains
234+
* {@link fromCodeFile} parsed from `text` (`parsed`), plus the stored tags any language keeps.
235+
*/
236+
export function codeFileRefs(parsed: readonly CodeFileRef[], text: string): CodeFileRef[] {
237+
return [...parsed, ...referenceTags(text)].sort((a, b) => a.start - b.start)
238+
}

‎packages/workflow-code/src/code-files/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
export { checkCodeFileBijection } from './bijection'
2-
export { type CodeFileRef, fromCodeFile } from './from-file'
2+
export { type CodeFileRef, codeFileRefs, fromCodeFile } from './from-file'
33
export { createJsContextScanner } from './lexer'
44
export {
55
ENV_VAR_NAME,

0 commit comments

Comments
 (0)