Skip to content

Commit 2082091

Browse files
committed
fix(workflows): keep condition and router branch connections when an edit re-sends the branches
An operations edit that re-sent a condition's conditions or a router's routes reassigned every row id by position (<blockId>-if, -else-if-N, -else, -routeN). Rows the canvas added have ids like <blockId>-else-if-<timestamp>, and stored edges name rows as condition-<id> / router-<id>, so the edit left those edges naming no row: the branch matched at run time but routed nowhere. After a canvas reorder the renamed ids could also attach an edge to another branch's expression. Re-sent rows now keep the stored id of the same branch: the stored row with the same expression first, then the row in the same slot. New rows get the canonical id, or a fresh one when a stored row holds it. Edges from rows the edit removed are dropped in the same mutation.
1 parent f86f3ab commit 2082091

3 files changed

Lines changed: 471 additions & 32 deletions

File tree

Lines changed: 347 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,347 @@
1+
/**
2+
* Real PostgreSQL coverage for what an operations edit that re-sends a condition's or router's
3+
* branch list persists: the stored edges must still name the stored rows, read back from the
4+
* normalized tables. The canvas mints row ids such as `<blockId>-else-if-<timestamp>` and keeps
5+
* them when a branch is moved, so stored ids are not positional.
6+
*/
7+
import { db } from '@sim/db'
8+
import { auditLog, permissions, user, workflow, workspace } from '@sim/db/schema'
9+
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
10+
import { createSessionPrincipal } from '@sim/testing/factories/principal.factory'
11+
import { featureFlagsMock } from '@sim/testing/mocks/feature-flags.mock'
12+
import { realtimeNotifyMock } from '@sim/testing/mocks/realtime-notify.mock'
13+
import { generateId } from '@sim/utils/id'
14+
import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save'
15+
import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow'
16+
import { eq } from 'drizzle-orm'
17+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
18+
import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server'
19+
import { applyWorkflowOperations } from '@/lib/workflows/application/apply-workflow-operations'
20+
import type { EditWorkflowOperation } from '@/lib/workflows/editing/types'
21+
import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils'
22+
23+
vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock)
24+
vi.mock('@/lib/realtime/notify', () => realtimeNotifyMock)
25+
26+
const ownerId = generateId()
27+
const workspaceId = generateId()
28+
const principal = createSessionPrincipal({ userId: ownerId, sessionId: generateId() })
29+
30+
interface BranchRow {
31+
id: string
32+
title: string
33+
value: string
34+
}
35+
36+
type BranchKind = 'condition' | 'router_v2'
37+
38+
/** Where each branch block kind stores its rows and how its edges name them. */
39+
const KINDS = {
40+
condition: { key: 'conditions', inputType: 'condition-input', handlePrefix: 'condition' },
41+
router_v2: { key: 'routes', inputType: 'router-input', handlePrefix: 'router' },
42+
} as const
43+
44+
function block(id: string, type: string, name: string, subBlocks: BlockState['subBlocks'] = {}) {
45+
return {
46+
id,
47+
type,
48+
name,
49+
position: { x: 0, y: 0 },
50+
subBlocks,
51+
outputs: {},
52+
enabled: true,
53+
data: {},
54+
} satisfies BlockState
55+
}
56+
57+
interface Fixture {
58+
kind: BranchKind
59+
workflowId: string
60+
branchId: string
61+
targets: Record<string, string>
62+
}
63+
64+
/**
65+
* Seeds a start block, branch block `branchId` with `rows`, and one function block per row, each
66+
* wired from its row's handle. `targets` maps each row's value to the block it routes to.
67+
*/
68+
async function seedBranches(
69+
kind: BranchKind,
70+
branchId: string,
71+
rows: BranchRow[]
72+
): Promise<Fixture> {
73+
const { key, inputType, handlePrefix } = KINDS[kind]
74+
const workflowId = generateId()
75+
const targets: Record<string, string> = {}
76+
const blocks: BlockState[] = [
77+
block(generateId(), 'starter', 'Start'),
78+
block(branchId, kind, 'Branch', {
79+
[key]: { id: key, type: inputType, value: JSON.stringify(rows) },
80+
}),
81+
]
82+
const edges: WorkflowState['edges'] = []
83+
rows.forEach((row, index) => {
84+
const target = generateId()
85+
targets[row.value] = target
86+
blocks.push(block(target, 'function', `Target ${index}`))
87+
edges.push({
88+
id: generateId(),
89+
source: branchId,
90+
target,
91+
sourceHandle: `${handlePrefix}-${row.id}`,
92+
targetHandle: 'target',
93+
})
94+
})
95+
const now = new Date()
96+
await db.insert(workflow).values({
97+
id: workflowId,
98+
userId: ownerId,
99+
workspaceId,
100+
name: `Branch edits ${workflowId}`,
101+
lastSynced: now,
102+
createdAt: now,
103+
updatedAt: now,
104+
})
105+
const saved = await saveWorkflowToNormalizedTables(workflowId, {
106+
blocks: Object.fromEntries(blocks.map((entry) => [entry.id, entry])),
107+
edges,
108+
loops: {},
109+
parallels: {},
110+
})
111+
if (!saved.success) throw new Error(`Seeding the workflow failed: ${saved.error}`)
112+
return { kind, workflowId, branchId, targets }
113+
}
114+
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'>>) {
117+
const operations: EditWorkflowOperation[] = [
118+
{
119+
operation_type: 'edit',
120+
block_id: fixture.branchId,
121+
params: { inputs: { [KINDS[fixture.kind].key]: rows } },
122+
},
123+
]
124+
return withPermissionGroupScope(() =>
125+
applyWorkflowOperations.execute({
126+
principal,
127+
input: { workflowId: fixture.workflowId, operations, atomic: true },
128+
})
129+
)
130+
}
131+
132+
/**
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.
135+
*/
136+
async function storedRouting(fixture: Fixture) {
137+
const loaded = await loadWorkflowFromNormalizedTables(fixture.workflowId)
138+
if (!loaded) throw new Error('The workflow did not load')
139+
const { key, handlePrefix } = KINDS[fixture.kind]
140+
const rows: BranchRow[] = JSON.parse(String(loaded.blocks[fixture.branchId].subBlocks[key].value))
141+
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
145+
.filter((edge) => edge.sourceHandle === `${handlePrefix}-${row.id}`)
146+
.map((edge) => edge.target)
147+
}
148+
const rowHandles = new Set(rows.map((row) => `${handlePrefix}-${row.id}`))
149+
const dangling = outgoing.filter((edge) => !rowHandles.has(edge.sourceHandle ?? ''))
150+
return { rows, routing, dangling }
151+
}
152+
153+
beforeAll(async () => {
154+
const now = new Date()
155+
await db.insert(user).values({
156+
id: ownerId,
157+
name: 'Branch edits fixture',
158+
email: `${ownerId}@branch-edits.invalid`,
159+
emailVerified: true,
160+
createdAt: now,
161+
updatedAt: now,
162+
})
163+
await insertWorkspaceFixture(db, {
164+
id: workspaceId,
165+
name: 'Branch edits',
166+
ownerId,
167+
billedAccountUserId: ownerId,
168+
})
169+
await db.insert(permissions).values({
170+
id: generateId(),
171+
userId: ownerId,
172+
entityType: 'workspace',
173+
entityId: workspaceId,
174+
permissionType: 'admin',
175+
})
176+
})
177+
178+
afterAll(async () => {
179+
await db.delete(auditLog).where(eq(auditLog.workspaceId, workspaceId))
180+
await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId))
181+
await db.delete(user).where(eq(user.id, ownerId))
182+
})
183+
184+
describe('an edit that re-sends a condition block’s branches', () => {
185+
it('keeps the connection of a branch the canvas added', async () => {
186+
const id = generateId()
187+
const fixture = await seedBranches('condition', id, [
188+
{ id: `${id}-if`, title: 'if', value: '<start.input> == 1' },
189+
{ id: `${id}-else-if-1763700000000`, title: 'else if', value: '<start.input> == 2' },
190+
{ id: `${id}-else`, title: 'else', value: '' },
191+
])
192+
193+
await resendBranches(fixture, [
194+
{ title: 'if', value: '<start.input> == 1' },
195+
{ title: 'else if', value: '<start.input> == 3' },
196+
{ title: 'else', value: '' },
197+
])
198+
199+
const { routing, dangling } = await storedRouting(fixture)
200+
expect(dangling).toEqual([])
201+
expect(routing).toEqual({
202+
'<start.input> == 1': [fixture.targets['<start.input> == 1']],
203+
'<start.input> == 3': [fixture.targets['<start.input> == 2']],
204+
'': [fixture.targets['']],
205+
})
206+
})
207+
208+
it('keeps each position routed where it was after the canvas reordered the rows', async () => {
209+
const id = generateId()
210+
const fixture = await seedBranches('condition', id, [
211+
{ id: `${id}-else-if-1763700000000`, title: 'if', value: 'first' },
212+
{ id: `${id}-if`, title: 'else if', value: 'second' },
213+
{ id: `${id}-else`, title: 'else', value: '' },
214+
])
215+
216+
await resendBranches(fixture, [
217+
{ title: 'if', value: 'first' },
218+
{ title: 'else if', value: 'second' },
219+
{ title: 'else', value: '' },
220+
])
221+
222+
const { routing, dangling } = await storedRouting(fixture)
223+
expect(dangling).toEqual([])
224+
expect(routing).toEqual({
225+
first: [fixture.targets.first],
226+
second: [fixture.targets.second],
227+
'': [fixture.targets['']],
228+
})
229+
})
230+
231+
it('removes the connection of a branch the edit removes and keeps the rest', async () => {
232+
const id = generateId()
233+
const fixture = await seedBranches('condition', id, [
234+
{ id: `${id}-if`, title: 'if', value: 'a' },
235+
{ id: `${id}-else-if-1763700000000`, title: 'else if', value: 'b' },
236+
{ id: `${id}-else`, title: 'else', value: '' },
237+
])
238+
239+
await resendBranches(fixture, [
240+
{ title: 'if', value: 'a' },
241+
{ title: 'else', value: '' },
242+
])
243+
244+
const { routing, dangling } = await storedRouting(fixture)
245+
expect(dangling).toEqual([])
246+
expect(routing).toEqual({ a: [fixture.targets.a], '': [fixture.targets['']] })
247+
})
248+
249+
it('gives an added branch its own row without taking another branch’s connection', async () => {
250+
const id = generateId()
251+
// An edit wrote else-if-0 and else-if-1, then the canvas deleted else-if-0: the row now in
252+
// the else-if-0 slot holds the id an added else-if-1 would be given.
253+
const fixture = await seedBranches('condition', id, [
254+
{ id: `${id}-if`, title: 'if', value: 'a' },
255+
{ id: `${id}-else-if-1`, title: 'else if', value: 'b' },
256+
{ id: `${id}-else`, title: 'else', value: '' },
257+
])
258+
259+
await resendBranches(fixture, [
260+
{ title: 'if', value: 'a' },
261+
{ title: 'else if', value: 'b' },
262+
{ title: 'else if', value: 'c' },
263+
{ title: 'else', value: '' },
264+
])
265+
266+
const { rows, routing, dangling } = await storedRouting(fixture)
267+
expect(dangling).toEqual([])
268+
expect(new Set(rows.map((row) => row.id)).size).toBe(4)
269+
expect(routing).toEqual({
270+
a: [fixture.targets.a],
271+
b: [fixture.targets.b],
272+
c: [],
273+
'': [fixture.targets['']],
274+
})
275+
})
276+
277+
it('keeps each remaining branch connected when the edit removes a middle branch', async () => {
278+
const id = generateId()
279+
const fixture = await seedBranches('condition', id, [
280+
{ id: `${id}-if`, title: 'if', value: 'a' },
281+
{ id: `${id}-else-if-1763700000000`, title: 'else if', value: 'b' },
282+
{ id: `${id}-else-if-1763700000001`, title: 'else if', value: 'c' },
283+
{ id: `${id}-else`, title: 'else', value: '' },
284+
])
285+
286+
await resendBranches(fixture, [
287+
{ title: 'if', value: 'a' },
288+
{ title: 'else if', value: 'c' },
289+
{ title: 'else', value: '' },
290+
])
291+
292+
const { routing, dangling } = await storedRouting(fixture)
293+
expect(dangling).toEqual([])
294+
expect(routing).toEqual({
295+
a: [fixture.targets.a],
296+
c: [fixture.targets.c],
297+
'': [fixture.targets['']],
298+
})
299+
})
300+
301+
it('leaves an inserted middle branch unconnected and the branch after it in place', async () => {
302+
const id = generateId()
303+
const fixture = await seedBranches('condition', id, [
304+
{ id: `${id}-if`, title: 'if', value: 'a' },
305+
{ id: `${id}-else-if-1763700000000`, title: 'else if', value: 'b' },
306+
{ id: `${id}-else`, title: 'else', value: '' },
307+
])
308+
309+
await resendBranches(fixture, [
310+
{ title: 'if', value: 'a' },
311+
{ title: 'else if', value: 'new' },
312+
{ title: 'else if', value: 'b' },
313+
{ title: 'else', value: '' },
314+
])
315+
316+
const { routing, dangling } = await storedRouting(fixture)
317+
expect(dangling).toEqual([])
318+
expect(routing).toEqual({
319+
a: [fixture.targets.a],
320+
new: [],
321+
b: [fixture.targets.b],
322+
'': [fixture.targets['']],
323+
})
324+
})
325+
})
326+
327+
describe('an edit that re-sends a router’s routes', () => {
328+
it('keeps the connection of a route the canvas added', async () => {
329+
const id = generateId()
330+
const fixture = await seedBranches('router_v2', id, [
331+
{ id: `${id}-route1`, title: 'route1', value: 'billing questions' },
332+
{ id: `${id}-route-1763700000000`, title: 'route-1763700000000', value: 'bug reports' },
333+
])
334+
335+
await resendBranches(fixture, [
336+
{ title: 'route1', value: 'billing questions' },
337+
{ title: 'route2', value: 'bug reports and crashes' },
338+
])
339+
340+
const { routing, dangling } = await storedRouting(fixture)
341+
expect(dangling).toEqual([])
342+
expect(routing).toEqual({
343+
'billing questions': [fixture.targets['billing questions']],
344+
'bug reports and crashes': [fixture.targets['bug reports']],
345+
})
346+
})
347+
})

0 commit comments

Comments
 (0)