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 9a9cc52e242..94c5c242d6c 100644 --- a/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts +++ b/apps/sim/lib/workflows/code/corpus/editing.corpus.test.ts @@ -33,7 +33,11 @@ import { 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, generateReapplyCorpus } from '@/lib/workflows/code/corpus' +import { + DEFAULT_CORPUS_SEED, + generateReapplyCorpus, + generateRegistryCorpus, +} from '@/lib/workflows/code/corpus' import { applyCanvasOp, CANVAS_OP_KINDS, @@ -1043,3 +1047,58 @@ describe('a webhook token creation minted', () => { expect(second.noop).toBe(true) }) }) + +describe('a condition branch value written as raw(...)', () => { + const storedShape = (detail: string) => { + const found = generateRegistryCorpus().find((c) => c.id === `stored-shapes:condition:${detail}`) + if (!found) throw new Error(`the registry corpus has no ${detail} condition case`) + const state = structuredClone(found.state) + const decide = Object.values(state.blocks).find((block) => block.type === 'condition') + if (!decide) throw new Error(`the ${detail} case has no condition block`) + return { state, decide } + } + + it('is stored as the JSON text the condition editor parses when it lifts into rows', () => { + const { state, decide } = storedShape('empty-string-branches') + const got = getSource(state, catalog) + const entry = got.files[SOURCE_ENTRY_FILE] ?? '' + expect(entry).toContain("conditions: raw('')") + const rows = [ + { id: `${decide.id}-if`, title: 'if', value: ' > 5' }, + { id: `${decide.id}-else`, title: 'else', value: '' }, + ] + const applied = applySource( + state, + got, + { + ...got.files, + [SOURCE_ENTRY_FILE]: entry.replace( + "conditions: raw('')", + `conditions: raw(${JSON.stringify(rows)})` + ), + }, + catalog + ) + const stored = applied.materialized?.state.blocks[decide.id]?.subBlocks.conditions?.value + expect(typeof stored).toBe('string') + expect(JSON.parse(String(stored))).toEqual(rows) + }) + + it('stays native when it does not lift into rows, so it reads back as the same raw value', () => { + const { state, decide } = storedShape('native-legacy-rows') + const got = getSource(state, catalog) + const entry = got.files[SOURCE_ENTRY_FILE] ?? '' + expect(entry).toContain("label: 'is big'") + const applied = applySource( + state, + got, + { ...got.files, [SOURCE_ENTRY_FILE]: entry.replace("label: 'is big'", "label: 'is huge'") }, + catalog + ) + const stored = applied.materialized?.state.blocks[decide.id]?.subBlocks.conditions?.value + expect(stored).toEqual([ + expect.objectContaining({ label: 'is huge', expression: ' > 5' }), + expect.objectContaining({ label: 'else', expression: 'true' }), + ]) + }) +}) diff --git a/packages/workflow-code/src/canonicalize/branches.ts b/packages/workflow-code/src/canonicalize/branches.ts index 09802faccca..e3a11abefaf 100644 --- a/packages/workflow-code/src/canonicalize/branches.ts +++ b/packages/workflow-code/src/canonicalize/branches.ts @@ -96,6 +96,44 @@ function derivedRowId(kind: CanonicalBranches['kind'], blockId: string, index: n return kind === 'router' ? `${blockId}-route${index + 1}` : `${blockId}-cond-${index}` } +type LiftFailure = { failure: 'not-list' | 'not-rows' } | { failure: 'shared-id'; sharedId: string } + +type StoredBranchRows = { rows: StoredRow[]; rowIds: string[] } | LiftFailure + +/** + * Parses a stored branch value into rows and their stored or derived ids, or says why it cannot + * lift: it is not a JSON list, not a list of `{ id?, title?, value }` rows, or two rows share an id. + */ +function storedBranchRows( + kind: CanonicalBranches['kind'], + blockId: string, + stored: unknown +): StoredBranchRows { + const rows = parseStoredList(stored) + if (!rows) return { failure: 'not-list' } + if (!rows.every(isStoredRow)) return { failure: 'not-rows' } + const rowIds = rows.map((row, index) => row.id ?? derivedRowId(kind, blockId, index)) + const seenRowIds = new Set() + const sharedId = rowIds.find((rowId) => { + if (seenRowIds.has(rowId)) return true + seenRowIds.add(rowId) + return false + }) + return sharedId === undefined ? { rows, rowIds } : { failure: 'shared-id', sharedId } +} + +/** + * Whether a stored branch value lifts into rows (the shape the canvas parses from branch text), + * by the same test {@link liftBranches} applies. + */ +export function liftsIntoRows( + kind: CanonicalBranches['kind'], + blockId: string, + stored: unknown +): boolean { + return 'rows' in storedBranchRows(kind, blockId, stored) +} + function uniqueKey(base: BranchKey, taken: ReadonlySet): BranchKey { if (!taken.has(base)) return base let n = 2 @@ -142,6 +180,17 @@ function unlifted( } } +function unliftedMessage(kind: CanonicalBranches['kind'], parsed: LiftFailure): string { + switch (parsed.failure) { + case 'not-list': + return `Stored ${kind} branches are not a JSON list; kept verbatim` + case 'not-rows': + return `Stored ${kind} branches are not a list of { id, title, value } rows; kept verbatim` + case 'shared-id': + return `Stored ${kind} branches use row id "${parsed.sharedId}" twice; kept verbatim` + } +} + /** * Lifts the `conditions` / `routes` subBlock into named branches. * Keys resolve lock (by row id) → persisted row `key` → positional default; a key @@ -163,58 +212,19 @@ export function liftBranches( ): LiftedBranches { if (stored === null || stored === undefined) return withImplicit(kind, blockId, null) - const storedRows = parseStoredList(stored) - if (!storedRows) { - if (typeof stored !== 'string' || stored.trim() !== '') { + const parsed = storedBranchRows(kind, blockId, stored) + if ('failure' in parsed) { + if (parsed.failure !== 'not-list' || typeof stored !== 'string' || stored.trim() !== '') { context.diagnostics.push( - diagnostic( - 'W_CANON_UNDECODABLE_JSON', - `Stored ${kind} branches are not a JSON list; kept verbatim`, - { - blockKey, - param, - } - ) + diagnostic('W_CANON_UNDECODABLE_JSON', unliftedMessage(kind, parsed), { blockKey, param }) ) } return unlifted(kind, blockId, stored) } - if (!storedRows.every(isStoredRow)) { - context.diagnostics.push( - diagnostic( - 'W_CANON_UNDECODABLE_JSON', - `Stored ${kind} branches are not a list of { id, title, value } rows; kept verbatim`, - { - blockKey, - param, - } - ) - ) - return unlifted(kind, blockId, stored) - } + const { rows: storedRows, rowIds } = parsed if (storedRows.length === 0) return withImplicit(kind, blockId, []) const count = storedRows.length - const rowIds = storedRows.map((row, index) => row.id ?? derivedRowId(kind, blockId, index)) - const seenRowIds = new Set() - const sharedId = rowIds.find((rowId) => { - if (seenRowIds.has(rowId)) return true - seenRowIds.add(rowId) - return false - }) - if (sharedId !== undefined) { - context.diagnostics.push( - diagnostic( - 'W_CANON_UNDECODABLE_JSON', - `Stored ${kind} branches use row id "${sharedId}" twice; kept verbatim`, - { - blockKey, - param, - } - ) - ) - return unlifted(kind, blockId, stored) - } const keys: Array = new Array(count) const taken = new Set() diff --git a/packages/workflow-code/src/materialize/block.ts b/packages/workflow-code/src/materialize/block.ts index fe22042e792..6210d2be89d 100644 --- a/packages/workflow-code/src/materialize/block.ts +++ b/packages/workflow-code/src/materialize/block.ts @@ -165,7 +165,10 @@ export function buildBlock(inputs: BlockInputs, context: MaterializeContext): Bu prevRaw: existing?.value, prevParam: previous, itemIds: itemSources(paramId), - verbatim: paramId === branchSubBlockId, + branch: + branchSpec && paramId === branchSubBlockId + ? { kind: branchSpec.kind, blockId: block.id } + : undefined, }, context ) diff --git a/packages/workflow-code/src/materialize/params.ts b/packages/workflow-code/src/materialize/params.ts index 32064515372..3ff6e91fe4b 100644 --- a/packages/workflow-code/src/materialize/params.ts +++ b/packages/workflow-code/src/materialize/params.ts @@ -1,11 +1,18 @@ import { isRecordLike } from '@sim/utils/object' import { mcpBinding, mcpToolId } from '../agent-tools' +import { liftsIntoRows } from '../canonicalize/branches' import { shouldDecode } from '../canonicalize/params' import { decodeToolParam, toolParamDeclaration } from '../canonicalize/tools' import type { CatalogSubBlock } from '../catalog/types' import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '../json-text' import type { LockItem } from '../lock' -import type { BlockKey, CanonicalParam, CanonicalTool, SubBlockId } from '../model' +import type { + BlockKey, + CanonicalBranches, + CanonicalParam, + CanonicalTool, + SubBlockId, +} from '../model' import { deepEqual, getOwn, parseStoredList, setOwn } from '../records' import { structuredCodec } from '../structured' import type { MaterializeContext } from './context' @@ -23,10 +30,10 @@ export interface ParamSite { /** Ids to give inputFormat fields, by name, in preference order (lock first, then prev). */ itemIds: LockItem[] /** - * 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. + * Set on a block's branch subBlock (`conditions` / `routes`), whose params are `raw(v)` values: + * its kind, and the block id that derived row ids are built from. */ - verbatim: boolean + branch: { kind: CanonicalBranches['kind']; blockId: string } | undefined } /** @@ -44,13 +51,19 @@ function storesAsText(site: ParamSite): boolean { } /** - * 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. + * The encoding a decoded value is written in. Scalars are always native. A branch value is JSON + * text when it lifts into rows, since the canvas reads branch rows with `toString()` and + * `JSON.parse`; any other branch value stays as written, so it reads back as the same `raw(v)`. + * Elsewhere it is JSON text when the field is one canonicalize decodes and {@link storesAsText}, + * and native otherwise: 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 || site.verbatim) return json + if (typeof json !== 'object' || json === null) return json + if (site.branch) { + const { kind, blockId } = site.branch + return liftsIntoRows(kind, blockId, json) ? JSON.stringify(json) : json + } if (!shouldDecode(site.declaration)) return json return storesAsText(site) ? JSON.stringify(json) : json }