Skip to content

Commit ae6256b

Browse files
committed
fix(workflows): reserve unchanged branch rows, prefer exact branch handles, reject malformed condition rows
- An unchanged row (same slot, same expression) keeps its id before any row is matched by expression, so editing a branch to repeat a later branch's expression no longer takes that branch's id and connection. - Condition and router handle resolution gives a row's own condition-<id> / router-<id> handle priority over another row's title or position alias, which can spell the same string after a reorder. - A condition row that is not an object is refused as invalid input instead of crashing the lint pass.
1 parent 2082091 commit ae6256b

3 files changed

Lines changed: 142 additions & 29 deletions

File tree

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

Lines changed: 77 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,13 @@ async function seedBranches(
112112
return { kind, workflowId, branchId, targets }
113113
}
114114

115-
/** Applies an operations edit that re-sends the branch block's rows and nothing else. */
116-
function resendBranches(fixture: Fixture, rows: Array<Omit<BranchRow, 'id'>>) {
115+
/** Applies an operations edit that re-sends the branch block's rows, and `connections` if given. */
116+
function resendBranches(fixture: Fixture, rows: unknown[], connections?: Record<string, string>) {
117117
const operations: EditWorkflowOperation[] = [
118118
{
119119
operation_type: 'edit',
120120
block_id: fixture.branchId,
121-
params: { inputs: { [KINDS[fixture.kind].key]: rows } },
121+
params: { inputs: { [KINDS[fixture.kind].key]: rows }, ...(connections && { connections }) },
122122
},
123123
]
124124
return withPermissionGroupScope(() =>
@@ -130,24 +130,24 @@ function resendBranches(fixture: Fixture, rows: Array<Omit<BranchRow, 'id'>>) {
130130
}
131131

132132
/**
133-
* What the stored workflow routes each branch to, by the branch's expression, plus the edges
134-
* from the branch block whose handle names no stored row.
133+
* What the stored workflow routes each branch to, by the branch's expression and by row
134+
* position, plus the edges from the branch block whose handle names no stored row.
135135
*/
136136
async function storedRouting(fixture: Fixture) {
137137
const loaded = await loadWorkflowFromNormalizedTables(fixture.workflowId)
138138
if (!loaded) throw new Error('The workflow did not load')
139139
const { key, handlePrefix } = KINDS[fixture.kind]
140140
const rows: BranchRow[] = JSON.parse(String(loaded.blocks[fixture.branchId].subBlocks[key].value))
141141
const outgoing = loaded.edges.filter((edge) => edge.source === fixture.branchId)
142-
const routing: Record<string, string[]> = {}
143-
for (const row of rows) {
144-
routing[row.value] = outgoing
142+
const byPosition = rows.map((row) =>
143+
outgoing
145144
.filter((edge) => edge.sourceHandle === `${handlePrefix}-${row.id}`)
146145
.map((edge) => edge.target)
147-
}
146+
)
147+
const routing = Object.fromEntries(rows.map((row, index) => [row.value, byPosition[index]]))
148148
const rowHandles = new Set(rows.map((row) => `${handlePrefix}-${row.id}`))
149149
const dangling = outgoing.filter((edge) => !rowHandles.has(edge.sourceHandle ?? ''))
150-
return { rows, routing, dangling }
150+
return { rows, routing, byPosition, dangling }
151151
}
152152

153153
beforeAll(async () => {
@@ -322,6 +322,50 @@ describe('an edit that re-sends a condition block’s branches', () => {
322322
'': [fixture.targets['']],
323323
})
324324
})
325+
326+
it('keeps an edited branch connected when its new expression repeats a later branch', async () => {
327+
const id = generateId()
328+
const fixture = await seedBranches('condition', id, [
329+
{ id: `${id}-if`, title: 'if', value: 'a' },
330+
{ id: `${id}-else-if-1763700000000`, title: 'else if', value: 'b' },
331+
{ id: `${id}-else-if-1763700000001`, title: 'else if', value: 'c' },
332+
{ id: `${id}-else`, title: 'else', value: '' },
333+
])
334+
335+
await resendBranches(fixture, [
336+
{ title: 'if', value: 'a' },
337+
{ title: 'else if', value: 'c' },
338+
{ title: 'else if', value: 'c' },
339+
{ title: 'else', value: '' },
340+
])
341+
342+
const { byPosition, dangling } = await storedRouting(fixture)
343+
expect(dangling).toEqual([])
344+
expect(byPosition).toEqual([
345+
[fixture.targets.a],
346+
[fixture.targets.b],
347+
[fixture.targets.c],
348+
[fixture.targets['']],
349+
])
350+
})
351+
352+
it('refuses a condition row that is not an object as invalid input and keeps every connection', async () => {
353+
const id = generateId()
354+
const fixture = await seedBranches('condition', id, [
355+
{ id: `${id}-if`, title: 'if', value: 'a' },
356+
{ id: `${id}-else`, title: 'else', value: '' },
357+
])
358+
359+
await expect(
360+
resendBranches(fixture, [null, { title: 'else', value: '' }])
361+
).rejects.toMatchObject({
362+
droppedInputs: [expect.objectContaining({ field: 'conditions' })],
363+
})
364+
365+
const { routing, dangling } = await storedRouting(fixture)
366+
expect(dangling).toEqual([])
367+
expect(routing).toEqual({ a: [fixture.targets.a], '': [fixture.targets['']] })
368+
})
325369
})
326370

327371
describe('an edit that re-sends a router’s routes', () => {
@@ -344,4 +388,27 @@ describe('an edit that re-sends a router’s routes', () => {
344388
'bug reports and crashes': [fixture.targets['bug reports']],
345389
})
346390
})
391+
it('resolves a stored route handle to its own route after the routes were reordered', async () => {
392+
const id = generateId()
393+
const fixture = await seedBranches('router_v2', id, [
394+
{ id: `${id}-route1`, title: 'route1', value: 'billing questions' },
395+
{ id: `${id}-route2`, title: 'route2', value: 'bug reports' },
396+
])
397+
398+
await resendBranches(
399+
fixture,
400+
[
401+
{ title: 'route1', value: 'bug reports' },
402+
{ title: 'route2', value: 'billing questions' },
403+
],
404+
{ [`router-${id}-route2`]: fixture.targets['bug reports'] }
405+
)
406+
407+
const { routing, dangling } = await storedRouting(fixture)
408+
expect(dangling).toEqual([])
409+
expect(routing).toEqual({
410+
'bug reports': [fixture.targets['bug reports']],
411+
'billing questions': [],
412+
})
413+
})
347414
})

‎apps/sim/lib/workflows/editing/builders.ts‎

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -550,11 +550,12 @@ function branchSlots(key: BranchListKey, count: number): string[] {
550550
}
551551

552552
/**
553-
* Assigns ids to branch `rows`, keeping stored ids where a row is the same branch. A row takes the
554-
* id of a stored row with the same non-empty expression first (so a branch keeps its edges when
555-
* the rows around it are inserted, removed or reordered), else the id of the stored row in its
556-
* slot, else its canonical id `<blockId>-<slot>`, or a fresh one when a stored row holds that.
557-
* An `else` row matches only by slot: its expression is ignored and usually empty.
553+
* Assigns ids to branch `rows`, keeping stored ids where a row is the same branch, in this order:
554+
* an unchanged row (same slot, same expression) keeps its id; then a row takes the id of a stored
555+
* row with the same non-empty expression (so a branch keeps its edges when the rows around it are
556+
* inserted, removed or reordered); then the id of the stored row in its slot; else its canonical
557+
* id `<blockId>-<slot>`, or a fresh one when a stored row holds that. An `else` row matches only
558+
* by slot: its expression is ignored and usually empty.
558559
*/
559560
function assignBranchIds(
560561
blockId: string,
@@ -564,28 +565,38 @@ function assignBranchIds(
564565
): unknown[] {
565566
const slots = branchSlots(key, rows.length)
566567
const storedSlots = branchSlots(key, stored.length)
568+
const storedInSlot = (index: number) => stored[storedSlots.indexOf(slots[index])]
569+
const ids: Array<string | undefined> = rows.map(() => undefined)
567570
const claimed = new Set<string>()
568-
const claim = (id: string | undefined) => {
569-
if (id === undefined || claimed.has(id)) return undefined
570-
claimed.add(id)
571-
return id
571+
const claimEach = (pick: (row: Record<string, unknown>, index: number) => string | undefined) => {
572+
rows.forEach((row, index) => {
573+
if (ids[index] !== undefined || !isRecordLike(row)) return
574+
const id = pick(row, index)
575+
if (id === undefined || claimed.has(id)) return
576+
claimed.add(id)
577+
ids[index] = id
578+
})
572579
}
573-
const byValue = rows.map((row, index) => {
574-
if (!isRecordLike(row) || slots[index] === 'else') return undefined
575-
if (typeof row.value !== 'string' || row.value === '') return undefined
576-
const match = stored.find(
580+
581+
claimEach((row, index) => {
582+
const same = storedInSlot(index)
583+
return same && same.value === row.value ? same.id : undefined
584+
})
585+
claimEach((row, index) => {
586+
if (slots[index] === 'else' || typeof row.value !== 'string' || row.value === '') return
587+
return stored.find(
577588
(candidate, at) =>
578589
storedSlots[at] !== 'else' && candidate.value === row.value && !claimed.has(candidate.id)
579-
)
580-
return claim(match?.id)
590+
)?.id
581591
})
592+
claimEach((_, index) => storedInSlot(index)?.id)
593+
582594
const taken = new Set(stored.map((row) => row.id))
583595
return rows.map((row, index) => {
584596
if (!isRecordLike(row)) return row
585-
const slot = slots[index]
586-
const kept = byValue[index] ?? claim(stored[storedSlots.indexOf(slot)]?.id)
597+
const kept = ids[index]
587598
if (kept !== undefined) return { ...row, id: kept }
588-
const canonical = `${blockId}-${slot}`
599+
const canonical = `${blockId}-${slots[index]}`
589600
const id = taken.has(canonical) ? `${canonical}-${generateShortId(8)}` : canonical
590601
taken.add(id)
591602
return { ...row, id }

‎apps/sim/lib/workflows/editing/validation.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -763,7 +763,29 @@ export function validateValueForSubBlockType(
763763
return { valid: true, value }
764764
}
765765

766-
case 'condition-input':
766+
case 'condition-input': {
767+
const parsedValue = parseArrayInput(value)
768+
const malformedAt = Array.isArray(parsedValue)
769+
? parsedValue.findIndex((condition: unknown) => !isPlainRecord(condition))
770+
: -1
771+
if (!Array.isArray(parsedValue) || malformedAt !== -1) {
772+
return {
773+
valid: false,
774+
error: {
775+
blockId,
776+
blockType,
777+
field: fieldName,
778+
value,
779+
error: Array.isArray(parsedValue)
780+
? `Invalid condition at index ${malformedAt}: expected an object with "title" and "value"`
781+
: `Invalid ${type} value for field "${fieldName}" - expected a JSON array`,
782+
},
783+
}
784+
}
785+
786+
return { valid: true, value }
787+
}
788+
767789
case 'knowledge-tag-filters':
768790
case 'document-tag-entry': {
769791
const parsedValue = parseArrayInput(value)
@@ -1209,6 +1231,13 @@ export function validateConditionHandle(
12091231
}
12101232
}
12111233

1234+
// A row's own id wins over another row's alias: after a reorder, a title or position alias can
1235+
// spell another row's stored handle.
1236+
for (const condition of conditions) {
1237+
if (condition.id)
1238+
handleToNormalized.set(`condition-${condition.id}`, `condition-${condition.id}`)
1239+
}
1240+
12121241
const normalizedHandle = handleToNormalized.get(sourceHandle)
12131242
if (normalizedHandle) {
12141243
return { valid: true, normalizedHandle }
@@ -1306,6 +1335,12 @@ export function validateRouterHandle(
13061335
}
13071336
}
13081337

1338+
// A row's own id wins over another row's alias: after a reorder, a title or position alias can
1339+
// spell another row's stored handle.
1340+
for (const route of routes) {
1341+
if (route.id) handleToNormalized.set(`router-${route.id}`, `router-${route.id}`)
1342+
}
1343+
13091344
const normalizedHandle = handleToNormalized.get(sourceHandle)
13101345
if (normalizedHandle) {
13111346
return { valid: true, normalizedHandle }

0 commit comments

Comments
 (0)