diff --git a/apps/sim/lib/workflows/application/apply-workflow-operations-branches.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-operations-branches.integration.ts new file mode 100644 index 00000000000..d792f9faa8e --- /dev/null +++ b/apps/sim/lib/workflows/application/apply-workflow-operations-branches.integration.ts @@ -0,0 +1,414 @@ +/** + * Real PostgreSQL coverage for what an operations edit that re-sends a condition's or router's + * branch list persists: the stored edges must still name the stored rows, read back from the + * normalized tables. The canvas mints row ids such as `-else-if-` and keeps + * them when a branch is moved, so stored ids are not positional. + */ +import { db } from '@sim/db' +import { auditLog, permissions, user, workflow, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { featureFlagsMock } from '@sim/testing/mocks/feature-flags.mock' +import { realtimeNotifyMock } from '@sim/testing/mocks/realtime-notify.mock' +import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' +import { eq } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server' +import { applyWorkflowOperations } from '@/lib/workflows/application/apply-workflow-operations' +import type { EditWorkflowOperation } from '@/lib/workflows/editing/types' +import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' + +vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock) +vi.mock('@/lib/realtime/notify', () => realtimeNotifyMock) + +const ownerId = generateId() +const workspaceId = generateId() +const principal = createSessionPrincipal({ userId: ownerId, sessionId: generateId() }) + +interface BranchRow { + id: string + title: string + value: string +} + +type BranchKind = 'condition' | 'router_v2' + +/** Where each branch block kind stores its rows and how its edges name them. */ +const KINDS = { + condition: { key: 'conditions', inputType: 'condition-input', handlePrefix: 'condition' }, + router_v2: { key: 'routes', inputType: 'router-input', handlePrefix: 'router' }, +} as const + +function block(id: string, type: string, name: string, subBlocks: BlockState['subBlocks'] = {}) { + return { + id, + type, + name, + position: { x: 0, y: 0 }, + subBlocks, + outputs: {}, + enabled: true, + data: {}, + } satisfies BlockState +} + +interface Fixture { + kind: BranchKind + workflowId: string + branchId: string + targets: Record +} + +/** + * Seeds a start block, branch block `branchId` with `rows`, and one function block per row, each + * wired from its row's handle. `targets` maps each row's value to the block it routes to. + */ +async function seedBranches( + kind: BranchKind, + branchId: string, + rows: BranchRow[] +): Promise { + const { key, inputType, handlePrefix } = KINDS[kind] + const workflowId = generateId() + const targets: Record = {} + const blocks: BlockState[] = [ + block(generateId(), 'starter', 'Start'), + block(branchId, kind, 'Branch', { + [key]: { id: key, type: inputType, value: JSON.stringify(rows) }, + }), + ] + const edges: WorkflowState['edges'] = [] + rows.forEach((row, index) => { + const target = generateId() + targets[row.value] = target + blocks.push(block(target, 'function', `Target ${index}`)) + edges.push({ + id: generateId(), + source: branchId, + target, + sourceHandle: `${handlePrefix}-${row.id}`, + targetHandle: 'target', + }) + }) + const now = new Date() + await db.insert(workflow).values({ + id: workflowId, + userId: ownerId, + workspaceId, + name: `Branch edits ${workflowId}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const saved = await saveWorkflowToNormalizedTables(workflowId, { + blocks: Object.fromEntries(blocks.map((entry) => [entry.id, entry])), + edges, + loops: {}, + parallels: {}, + }) + if (!saved.success) throw new Error(`Seeding the workflow failed: ${saved.error}`) + return { kind, workflowId, branchId, targets } +} + +/** Applies an operations edit that re-sends the branch block's rows, and `connections` if given. */ +function resendBranches(fixture: Fixture, rows: unknown[], connections?: Record) { + const operations: EditWorkflowOperation[] = [ + { + operation_type: 'edit', + block_id: fixture.branchId, + params: { inputs: { [KINDS[fixture.kind].key]: rows }, ...(connections && { connections }) }, + }, + ] + return withPermissionGroupScope(() => + applyWorkflowOperations.execute({ + principal, + input: { workflowId: fixture.workflowId, operations, atomic: true }, + }) + ) +} + +/** + * What the stored workflow routes each branch to, by the branch's expression and by row + * position, plus the edges from the branch block whose handle names no stored row. + */ +async function storedRouting(fixture: Fixture) { + const loaded = await loadWorkflowFromNormalizedTables(fixture.workflowId) + if (!loaded) throw new Error('The workflow did not load') + const { key, handlePrefix } = KINDS[fixture.kind] + const rows: BranchRow[] = JSON.parse(String(loaded.blocks[fixture.branchId].subBlocks[key].value)) + const outgoing = loaded.edges.filter((edge) => edge.source === fixture.branchId) + const byPosition = rows.map((row) => + outgoing + .filter((edge) => edge.sourceHandle === `${handlePrefix}-${row.id}`) + .map((edge) => edge.target) + ) + const routing = Object.fromEntries(rows.map((row, index) => [row.value, byPosition[index]])) + const rowHandles = new Set(rows.map((row) => `${handlePrefix}-${row.id}`)) + const dangling = outgoing.filter((edge) => !rowHandles.has(edge.sourceHandle ?? '')) + return { rows, routing, byPosition, dangling } +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Branch edits fixture', + email: `${ownerId}@branch-edits.invalid`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Branch edits', + ownerId, + billedAccountUserId: ownerId, + }) + await db.insert(permissions).values({ + id: generateId(), + userId: ownerId, + entityType: 'workspace', + entityId: workspaceId, + permissionType: 'admin', + }) +}) + +afterAll(async () => { + await db.delete(auditLog).where(eq(auditLog.workspaceId, workspaceId)) + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, ownerId)) +}) + +describe('an edit that re-sends a condition block’s branches', () => { + it('keeps the connection of a branch the canvas added', async () => { + const id = generateId() + const fixture = await seedBranches('condition', id, [ + { id: `${id}-if`, title: 'if', value: ' == 1' }, + { id: `${id}-else-if-1763700000000`, title: 'else if', value: ' == 2' }, + { id: `${id}-else`, title: 'else', value: '' }, + ]) + + await resendBranches(fixture, [ + { title: 'if', value: ' == 1' }, + { title: 'else if', value: ' == 3' }, + { title: 'else', value: '' }, + ]) + + const { routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(routing).toEqual({ + ' == 1': [fixture.targets[' == 1']], + ' == 3': [fixture.targets[' == 2']], + '': [fixture.targets['']], + }) + }) + + it('keeps each position routed where it was after the canvas reordered the rows', async () => { + const id = generateId() + const fixture = await seedBranches('condition', id, [ + { id: `${id}-else-if-1763700000000`, title: 'if', value: 'first' }, + { id: `${id}-if`, title: 'else if', value: 'second' }, + { id: `${id}-else`, title: 'else', value: '' }, + ]) + + await resendBranches(fixture, [ + { title: 'if', value: 'first' }, + { title: 'else if', value: 'second' }, + { title: 'else', value: '' }, + ]) + + const { routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(routing).toEqual({ + first: [fixture.targets.first], + second: [fixture.targets.second], + '': [fixture.targets['']], + }) + }) + + it('removes the connection of a branch the edit removes and keeps the rest', async () => { + const id = generateId() + const fixture = await seedBranches('condition', id, [ + { id: `${id}-if`, title: 'if', value: 'a' }, + { id: `${id}-else-if-1763700000000`, title: 'else if', value: 'b' }, + { id: `${id}-else`, title: 'else', value: '' }, + ]) + + await resendBranches(fixture, [ + { title: 'if', value: 'a' }, + { title: 'else', value: '' }, + ]) + + const { routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(routing).toEqual({ a: [fixture.targets.a], '': [fixture.targets['']] }) + }) + + it('gives an added branch its own row without taking another branch’s connection', async () => { + const id = generateId() + // An edit wrote else-if-0 and else-if-1, then the canvas deleted else-if-0: the row now in + // the else-if-0 slot holds the id an added else-if-1 would be given. + const fixture = await seedBranches('condition', id, [ + { id: `${id}-if`, title: 'if', value: 'a' }, + { id: `${id}-else-if-1`, title: 'else if', value: 'b' }, + { id: `${id}-else`, title: 'else', value: '' }, + ]) + + await resendBranches(fixture, [ + { title: 'if', value: 'a' }, + { title: 'else if', value: 'b' }, + { title: 'else if', value: 'c' }, + { title: 'else', value: '' }, + ]) + + const { rows, routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(new Set(rows.map((row) => row.id)).size).toBe(4) + expect(routing).toEqual({ + a: [fixture.targets.a], + b: [fixture.targets.b], + c: [], + '': [fixture.targets['']], + }) + }) + + it('keeps each remaining branch connected when the edit removes a middle branch', async () => { + const id = generateId() + const fixture = await seedBranches('condition', id, [ + { id: `${id}-if`, title: 'if', value: 'a' }, + { id: `${id}-else-if-1763700000000`, title: 'else if', value: 'b' }, + { id: `${id}-else-if-1763700000001`, title: 'else if', value: 'c' }, + { id: `${id}-else`, title: 'else', value: '' }, + ]) + + await resendBranches(fixture, [ + { title: 'if', value: 'a' }, + { title: 'else if', value: 'c' }, + { title: 'else', value: '' }, + ]) + + const { routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(routing).toEqual({ + a: [fixture.targets.a], + c: [fixture.targets.c], + '': [fixture.targets['']], + }) + }) + + it('leaves an inserted middle branch unconnected and the branch after it in place', async () => { + const id = generateId() + const fixture = await seedBranches('condition', id, [ + { id: `${id}-if`, title: 'if', value: 'a' }, + { id: `${id}-else-if-1763700000000`, title: 'else if', value: 'b' }, + { id: `${id}-else`, title: 'else', value: '' }, + ]) + + await resendBranches(fixture, [ + { title: 'if', value: 'a' }, + { title: 'else if', value: 'new' }, + { title: 'else if', value: 'b' }, + { title: 'else', value: '' }, + ]) + + const { routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(routing).toEqual({ + a: [fixture.targets.a], + new: [], + b: [fixture.targets.b], + '': [fixture.targets['']], + }) + }) + + it('keeps an edited branch connected when its new expression repeats a later branch', async () => { + const id = generateId() + const fixture = await seedBranches('condition', id, [ + { id: `${id}-if`, title: 'if', value: 'a' }, + { id: `${id}-else-if-1763700000000`, title: 'else if', value: 'b' }, + { id: `${id}-else-if-1763700000001`, title: 'else if', value: 'c' }, + { id: `${id}-else`, title: 'else', value: '' }, + ]) + + await resendBranches(fixture, [ + { title: 'if', value: 'a' }, + { title: 'else if', value: 'c' }, + { title: 'else if', value: 'c' }, + { title: 'else', value: '' }, + ]) + + const { byPosition, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(byPosition).toEqual([ + [fixture.targets.a], + [fixture.targets.b], + [fixture.targets.c], + [fixture.targets['']], + ]) + }) + + it('refuses a condition row that is not an object as invalid input and keeps every connection', async () => { + const id = generateId() + const fixture = await seedBranches('condition', id, [ + { id: `${id}-if`, title: 'if', value: 'a' }, + { id: `${id}-else`, title: 'else', value: '' }, + ]) + + await expect( + resendBranches(fixture, [null, { title: 'else', value: '' }]) + ).rejects.toMatchObject({ + droppedInputs: [expect.objectContaining({ field: 'conditions' })], + }) + + const { routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(routing).toEqual({ a: [fixture.targets.a], '': [fixture.targets['']] }) + }) +}) + +describe('an edit that re-sends a router’s routes', () => { + it('keeps the connection of a route the canvas added', async () => { + const id = generateId() + const fixture = await seedBranches('router_v2', id, [ + { id: `${id}-route1`, title: 'route1', value: 'billing questions' }, + { id: `${id}-route-1763700000000`, title: 'route-1763700000000', value: 'bug reports' }, + ]) + + await resendBranches(fixture, [ + { title: 'route1', value: 'billing questions' }, + { title: 'route2', value: 'bug reports and crashes' }, + ]) + + const { routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(routing).toEqual({ + 'billing questions': [fixture.targets['billing questions']], + 'bug reports and crashes': [fixture.targets['bug reports']], + }) + }) + it('resolves a stored route handle to its own route after the routes were reordered', async () => { + const id = generateId() + const fixture = await seedBranches('router_v2', id, [ + { id: `${id}-route1`, title: 'route1', value: 'billing questions' }, + { id: `${id}-route2`, title: 'route2', value: 'bug reports' }, + ]) + + await resendBranches( + fixture, + [ + { title: 'route1', value: 'bug reports' }, + { title: 'route2', value: 'billing questions' }, + ], + { [`router-${id}-route2`]: fixture.targets['bug reports'] } + ) + + const { routing, dangling } = await storedRouting(fixture) + expect(dangling).toEqual([]) + expect(routing).toEqual({ + 'bug reports': [fixture.targets['bug reports']], + 'billing questions': [], + }) + }) +}) diff --git a/apps/sim/lib/workflows/editing/builders.ts b/apps/sim/lib/workflows/editing/builders.ts index 6d83044a862..4f95f631408 100644 --- a/apps/sim/lib/workflows/editing/builders.ts +++ b/apps/sim/lib/workflows/editing/builders.ts @@ -1,17 +1,21 @@ import { createLogger } from '@sim/logger' -import { generateId, isValidUuid } from '@sim/utils/id' -import { sortObjectKeysDeep } from '@sim/utils/object' +import { generateId, generateShortId, isValidUuid } from '@sim/utils/id' +import { isRecordLike, sortObjectKeysDeep } from '@sim/utils/object' import { buildCanonicalIndex, isCanonicalPair } from '@sim/workflow-code/catalog/canonical-index' import { type BlockRetryConfig, + getWorkflowBranchHandleId, normalizeBlockRetryTries, normalizeBlockRetryWaitMs, + type WorkflowBranchKind, + type WorkflowState, wouldCreateCycle, } from '@sim/workflow-types/workflow' import type { PermissionGroupConfig } from '@/lib/permission-groups/fields' import { resolveAvailableAgentDefaultModel } from '@/lib/permission-groups/model-access.server' import type { SeedValueGate } from '@/lib/permission-groups/operation-access' import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/outputs' +import { getConditionRows, getRouterRows } from '@/lib/workflows/dynamic-handle-topology' import { checkRetrySetting, createFieldValueGate, @@ -512,41 +516,140 @@ export function normalizeSubblockValue(key: string, value: unknown, blockType?: return JSON_STRING_SUBBLOCK_KEYS.has(key) ? JSON.stringify(normalized) : normalized } -/** - * Normalizes condition/router branch IDs to use canonical block-scoped format. - * The LLM provides branch structure (if/else-if/else or routes) but should not - * have to generate the internal IDs -- we assign them based on the block ID. - */ -export function normalizeConditionRouterIds(blockId: string, key: string, value: unknown): unknown { - if (key !== 'conditions' && key !== 'routes') return value +/** How each branch subBlock's rows are read back and named on their edges. */ +const BRANCH_LISTS = { + conditions: { kind: 'condition', storedRows: getConditionRows }, + routes: { kind: 'router', storedRows: getRouterRows }, +} as const satisfies Record< + string, + { + kind: WorkflowBranchKind + storedRows: (blockId: string, value: unknown) => ReadonlyArray<{ id: string }> + } +> - const parsed = parseJsonArray(value) - if (!parsed) return value +type BranchListKey = keyof typeof BRANCH_LISTS +function isBranchListKey(key: string): key is BranchListKey { + return Object.hasOwn(BRANCH_LISTS, key) +} + +/** + * The positional slot of each of `count` rows, spelled as its canonical id suffix: `if`, + * `else-if-0`, …, `else` for a condition, and `route1`, `route2`, … for a router (matching the + * canvas's first route id). + */ +function branchSlots(key: BranchListKey, count: number): string[] { let elseIfCounter = 0 - const normalized = parsed.map((item, index) => { - if (!item || typeof item !== 'object') return item - - let canonicalId: string - if (key === 'conditions') { - if (index === 0) { - canonicalId = `${blockId}-if` - } else if (index === parsed.length - 1) { - canonicalId = `${blockId}-else` - } else { - canonicalId = `${blockId}-else-if-${elseIfCounter}` - elseIfCounter++ - } - } else { - canonicalId = `${blockId}-route${index + 1}` - } + return Array.from({ length: count }, (_, index) => { + if (key === 'routes') return `route${index + 1}` + if (index === 0) return 'if' + if (index === count - 1) return 'else' + return `else-if-${elseIfCounter++}` + }) +} - return { ...item, id: canonicalId } +/** + * Assigns ids to branch `rows`, keeping stored ids where a row is the same branch, in this order: + * an unchanged row (same slot, same expression) keeps its id; then a row takes the id of a stored + * row with the same non-empty expression (so a branch keeps its edges when the rows around it are + * inserted, removed or reordered); then the id of the stored row in its slot; else its canonical + * id `-`, or a fresh one when a stored row holds that. An `else` row matches only + * by slot: its expression is ignored and usually empty. + */ +function assignBranchIds( + blockId: string, + key: BranchListKey, + rows: unknown[], + stored: ReadonlyArray<{ id: string; value?: unknown }> +): unknown[] { + const slots = branchSlots(key, rows.length) + const storedSlots = branchSlots(key, stored.length) + const storedInSlot = (index: number) => stored[storedSlots.indexOf(slots[index])] + const ids: Array = rows.map(() => undefined) + const claimed = new Set() + const claimEach = (pick: (row: Record, index: number) => string | undefined) => { + rows.forEach((row, index) => { + if (ids[index] !== undefined || !isRecordLike(row)) return + const id = pick(row, index) + if (id === undefined || claimed.has(id)) return + claimed.add(id) + ids[index] = id + }) + } + + claimEach((row, index) => { + const same = storedInSlot(index) + return same && same.value === row.value ? same.id : undefined + }) + claimEach((row, index) => { + if (slots[index] === 'else' || typeof row.value !== 'string' || row.value === '') return + return stored.find( + (candidate, at) => + storedSlots[at] !== 'else' && candidate.value === row.value && !claimed.has(candidate.id) + )?.id + }) + claimEach((_, index) => storedInSlot(index)?.id) + + const taken = new Set(stored.map((row) => row.id)) + return rows.map((row, index) => { + if (!isRecordLike(row)) return row + const kept = ids[index] + if (kept !== undefined) return { ...row, id: kept } + const canonical = `${blockId}-${slots[index]}` + const id = taken.has(canonical) ? `${canonical}-${generateShortId(8)}` : canonical + taken.add(id) + return { ...row, id } }) +} +/** + * Assigns canonical block-scoped branch ids to a new block's condition/router rows. The caller + * provides the branch structure (if/else-if/else or routes) but not the internal ids. + */ +export function normalizeConditionRouterIds(blockId: string, key: string, value: unknown): unknown { + if (!isBranchListKey(key)) return value + const parsed = parseJsonArray(value) + if (!parsed) return value + const normalized = assignBranchIds(blockId, key, parsed, []) return typeof value === 'string' ? JSON.stringify(normalized) : normalized } +/** + * Applies a re-sent condition/router branch list to existing block `blockId` in one mutation. + * Stored edges name rows as `condition-` / `router-`, and the canvas mints ids such as + * `-else-if-`, so a re-sent row that is the same branch keeps its stored id + * ({@link assignBranchIds}) instead of a positional one that would orphan its edges. The block's + * edges from a stored row the list no longer holds are removed rather than left naming no branch. + * Returns the value to store; any other key passes through. + */ +export function applyEditedBranchRows( + modifiedState: Pick, + blockId: string, + key: string, + value: unknown +): unknown { + if (!isBranchListKey(key)) return value + const parsed = parseJsonArray(value) + if (!parsed) return value + const { kind, storedRows } = BRANCH_LISTS[key] + const stored = storedRows(blockId, modifiedState.blocks[blockId]?.subBlocks?.[key]?.value) + const rows = assignBranchIds(blockId, key, parsed, stored) + + const keptIds = new Set(rows.map((row) => (isRecordLike(row) ? row.id : undefined))) + const droppedHandles = new Set( + stored + .filter((row) => !keptIds.has(row.id)) + .map((row) => getWorkflowBranchHandleId(kind, row.id)) + ) + if (droppedHandles.size > 0) { + modifiedState.edges = modifiedState.edges.filter( + (edge) => !(edge.source === blockId && droppedHandles.has(edge.sourceHandle ?? '')) + ) + } + return typeof value === 'string' ? JSON.stringify(rows) : rows +} + /** * Normalize responseFormat to ensure consistent storage * Handles both string (JSON) and object formats diff --git a/apps/sim/lib/workflows/editing/operations.ts b/apps/sim/lib/workflows/editing/operations.ts index 8acd21aca3b..1cca6165f56 100644 --- a/apps/sim/lib/workflows/editing/operations.ts +++ b/apps/sim/lib/workflows/editing/operations.ts @@ -13,11 +13,11 @@ import { normalizeName, RESERVED_BLOCK_NAMES } from '@/executor/constants' import { TRIGGER_RUNTIME_SUBBLOCK_IDS } from '@/triggers/constants' import { applyBlockRetry, + applyEditedBranchRows, applyTriggerConfigToBlockSubblocks, createBlockFromParams, createSubBlockInputGate, gateToolInputValue, - normalizeConditionRouterIds, normalizeResponseFormat, normalizeSubblockValue, updateCanonicalModesForInputs, @@ -356,7 +356,7 @@ function mergeNestedNodesForParent( if (TRIGGER_RUNTIME_SUBBLOCK_IDS.includes(key)) return if (!isInputAllowed(key, value)) return let sanitizedValue = normalizeSubblockValue(key, value, existingBlock.type) - sanitizedValue = normalizeConditionRouterIds(existingId, key, sanitizedValue) + sanitizedValue = applyEditedBranchRows(modifiedState, existingId, key, sanitizedValue) sanitizedValue = gateToolInputValue( { blockId: existingId, blockType: existingBlock.type, key, value, sanitizedValue }, permissionConfig, @@ -631,7 +631,7 @@ export function handleEditOperation(op: EditWorkflowOperation, ctx: OperationCon explicitInputKeys.add(key) let sanitizedValue = normalizeSubblockValue(key, value, block.type) - sanitizedValue = normalizeConditionRouterIds(block_id, key, sanitizedValue) + sanitizedValue = applyEditedBranchRows(modifiedState, block_id, key, sanitizedValue) sanitizedValue = gateToolInputValue( { blockId: block_id, blockType: block.type, key, value, sanitizedValue }, @@ -1095,7 +1095,7 @@ export function handleInsertIntoSubflowOperation( let sanitizedValue = normalizeSubblockValue(key, value, existingBlock.type) - sanitizedValue = normalizeConditionRouterIds(block_id, key, sanitizedValue) + sanitizedValue = applyEditedBranchRows(modifiedState, block_id, key, sanitizedValue) sanitizedValue = gateToolInputValue( { blockId: block_id, blockType: existingBlock.type, key, value, sanitizedValue }, diff --git a/apps/sim/lib/workflows/editing/validation.ts b/apps/sim/lib/workflows/editing/validation.ts index 0d09db54328..f2aeeb01c6c 100644 --- a/apps/sim/lib/workflows/editing/validation.ts +++ b/apps/sim/lib/workflows/editing/validation.ts @@ -763,7 +763,29 @@ export function validateValueForSubBlockType( return { valid: true, value } } - case 'condition-input': + case 'condition-input': { + const parsedValue = parseArrayInput(value) + const malformedAt = Array.isArray(parsedValue) + ? parsedValue.findIndex((condition: unknown) => !isPlainRecord(condition)) + : -1 + if (!Array.isArray(parsedValue) || malformedAt !== -1) { + return { + valid: false, + error: { + blockId, + blockType, + field: fieldName, + value, + error: Array.isArray(parsedValue) + ? `Invalid condition at index ${malformedAt}: expected an object with "title" and "value"` + : `Invalid ${type} value for field "${fieldName}" - expected a JSON array`, + }, + } + } + + return { valid: true, value } + } + case 'knowledge-tag-filters': case 'document-tag-entry': { const parsedValue = parseArrayInput(value) @@ -1209,6 +1231,13 @@ export function validateConditionHandle( } } + // A row's own id wins over another row's alias: after a reorder, a title or position alias can + // spell another row's stored handle. + for (const condition of conditions) { + if (condition.id) + handleToNormalized.set(`condition-${condition.id}`, `condition-${condition.id}`) + } + const normalizedHandle = handleToNormalized.get(sourceHandle) if (normalizedHandle) { return { valid: true, normalizedHandle } @@ -1306,6 +1335,12 @@ export function validateRouterHandle( } } + // A row's own id wins over another row's alias: after a reorder, a title or position alias can + // spell another row's stored handle. + for (const route of routes) { + if (route.id) handleToNormalized.set(`router-${route.id}`, `router-${route.id}`) + } + const normalizedHandle = handleToNormalized.get(sourceHandle) if (normalizedHandle) { return { valid: true, normalizedHandle }