forked from KunAgent/Kun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkflow-runtime.nodes.test.ts
More file actions
1424 lines (1311 loc) · 55.2 KB
/
Copy pathworkflow-runtime.nodes.test.ts
File metadata and controls
1424 lines (1311 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Per-node-type unit-test catalog for the workflow runtime.
//
// Goal: EVERY WorkflowNodeKind ("item") has at least one unit test here, and
// every meaningful mode/branch of the data-shaping nodes is exercised, so we can
// prove all node types actually work. A completeness guard at the bottom fails if
// a new kind is added to WORKFLOW_NODE_KINDS without a test landing here.
//
// Most non-trigger nodes are tested through `runtime.testNode()` — it runs a
// single node in isolation against a mock upstream payload and returns the node's
// result (status/message/outputJson/error/threadId) without touching the graph
// scheduler, which is the cleanest "unit" boundary for one node. Graph-level
// semantics (branch pruning, joins, the webhook server, secret redaction) live in
// workflow-runtime.run.test.ts; this file does not duplicate them.
import { spawnSync } from 'node:child_process'
import { existsSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
WORKFLOW_NODE_KINDS,
defaultClawSettings,
defaultDesignSettings,
defaultKeyboardShortcuts,
defaultKunRuntimeSettings,
defaultModelProviderSettings,
defaultScheduleSettings,
defaultWriteSettings,
defaultTerminalSettings,
mergeWorkflowSettings,
normalizeWorkflow,
normalizeWorkflowSettings,
type AppSettingsPatch,
type AppSettingsV1,
type WorkflowCustomModuleV1,
type WorkflowNodeKind,
type WorkflowNodeRunResultV1,
type WorkflowRunV1,
type WorkflowV1
} from '../shared/app-settings'
import {
computeWorkflowNextRunAt,
createWorkflowRuntime,
workflowHasScheduleTrigger,
type WorkflowRuntime
} from './workflow-runtime'
const imageGenerateMock = vi.hoisted(() => vi.fn(async () => ({
data: Buffer.from('PNG-BYTES'),
mimeType: 'image/png'
})))
// The generate-image node lazily imports the kun image client. Replace it with a
// stub so the test never hits a real provider (and never pulls native deps in).
vi.mock('../../kun/src/adapters/tool/image-gen-tool-provider.js', () => ({
createImageGenClient: () => ({
generate: imageGenerateMock
}),
mapImageSize: (
_aspectRatio: string | undefined,
_imageSize: string | undefined,
_defaultSize: string | undefined,
defaultResolution: 'auto' | '1K' | '2K' = '1K'
) => defaultResolution === 'auto'
? 'auto'
: defaultResolution === '2K' ? '2048x2048' : '1024x1024'
}))
const NOW = '2026-06-19T00:00:00.000Z'
const PYTHON_OK = spawnSync('python3', ['-c', 'pass']).status === 0
let workflowWorkspaceRoot = ''
// ---------------------------------------------------------------------------
// Loose builders — the runtime normalizes raw input, so tests pass partial
// configs and let normalizeWorkflow fill defaults (one explicit cast at the edge
// keeps the whole file type-clean).
// ---------------------------------------------------------------------------
type NodeSpec = {
id: string
type: WorkflowNodeKind
name?: string
disabled?: boolean
onError?: 'fail' | 'continue' | 'fallback'
retries?: number
inputs?: { key: string; type: 'text' | 'number' | 'boolean' | 'json'; source: string }[]
config?: Record<string, unknown>
}
type ConnSpec = { id: string; source: string; sourceHandle?: string; target: string; targetHandle?: string }
type WorkflowSpec = {
id: string
name?: string
enabled?: boolean
nodes: NodeSpec[]
connections?: ConnSpec[]
}
function wf(spec: WorkflowSpec): WorkflowV1 {
const raw = {
enabled: true,
...spec,
connections: (spec.connections ?? []).map((c) => ({
sourceHandle: 'out',
targetHandle: 'in',
...c
}))
}
return normalizeWorkflow(raw as unknown as Partial<WorkflowV1>, 0, NOW)
}
type SettingsPatch = (settings: AppSettingsV1) => AppSettingsV1
function buildSettings(
workflows: WorkflowV1[],
modules: WorkflowCustomModuleV1[] = [],
patch?: SettingsPatch
): AppSettingsV1 {
const base: AppSettingsV1 = {
version: 1,
locale: 'en',
theme: 'system',
uiFontScale: 0.82,
chatContentMaxWidthPx: 896,
composerSendKey: 'enter',
provider: defaultModelProviderSettings(),
agents: { kun: { ...defaultKunRuntimeSettings(), model: 'test-model', apiKey: 'test-key' } },
workspaceRoot: workflowWorkspaceRoot,
conversationWorkspaceRoot: '~/Documents/Kun',
log: { enabled: true, retentionDays: 7 },
checkpointCleanup: { createEnabled: false, enabled: false, intervalDays: 3 },
notifications: { turnComplete: true },
appBehavior: { openAtLogin: false, startMinimized: false, closeToTray: false },
keyboardShortcuts: defaultKeyboardShortcuts(),
write: defaultWriteSettings(),
claw: defaultClawSettings(),
schedule: defaultScheduleSettings(),
workflow: normalizeWorkflowSettings({ enabled: true, workflows, modules }),
design: defaultDesignSettings(),
terminal: defaultTerminalSettings(),
guiUpdate: { channel: 'stable' },
codePromptPrefix: '',
disabledSkillIds: []
}
return patch ? patch(base) : base
}
function createStore(initial: AppSettingsV1) {
let current = initial
return {
load: async () => current,
patch: async (partial: AppSettingsPatch) => {
current = { ...current, workflow: mergeWorkflowSettings(current.workflow, partial.workflow) }
return current
},
read: () => current
}
}
const okEmpty = { ok: false, status: 404, body: '{}' } as const
const defaultRuntimeRequest = (): ReturnType<typeof vi.fn> => vi.fn(async () => okEmpty)
/** Build a runtimeRequest mock that drives the thread→turn→poll path and returns `replyText`. */
function aiRuntimeRequest(replyText: string): ReturnType<typeof vi.fn> {
return vi.fn(async (_settings: AppSettingsV1, pathAndQuery: string, _init?: { body?: string }) => {
if (pathAndQuery === '/v1/threads') return { ok: true, status: 200, body: JSON.stringify({ id: 'thread-1' }) }
if (pathAndQuery.includes('/turns')) return { ok: true, status: 200, body: JSON.stringify({ turn: { id: 'turn-1' } }) }
if (pathAndQuery.startsWith('/v1/threads/')) {
return {
ok: true,
status: 200,
body: JSON.stringify({
turns: [
{ id: 'turn-1', status: 'completed', items: [{ kind: 'assistant_text', text: replyText, turnId: 'turn-1' }] }
]
})
}
}
return okEmpty
})
}
type TestNodeOpts = {
extraWorkflows?: WorkflowV1[]
modules?: WorkflowCustomModuleV1[]
runtimeRequest?: ReturnType<typeof vi.fn>
patch?: SettingsPatch
}
/** Run one node in isolation against `mockJson` and return its result (throws on a runtime lookup failure). */
async function testNode(node: NodeSpec, mockJson = '{}', opts: TestNodeOpts = {}): Promise<WorkflowNodeRunResultV1> {
const target = wf({ id: 'wf-under-test', name: 'wf-under-test', nodes: [node] })
const settings = buildSettings([target, ...(opts.extraWorkflows ?? [])], opts.modules, opts.patch)
const store = createStore(settings)
const runtime = createWorkflowRuntime({
store: store as never,
runtimeRequest: (opts.runtimeRequest ?? defaultRuntimeRequest()) as never,
logError: vi.fn()
})
try {
const res = await runtime.testNode('wf-under-test', node.id, mockJson)
if (!res.ok) throw new Error(res.message)
return res.result
} finally {
runtime.stop()
}
}
async function waitFor(predicate: () => Promise<boolean>, timeoutMs: number): Promise<void> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (await predicate()) return
await new Promise((resolve) => setTimeout(resolve, 30))
}
throw new Error('Timed out waiting for workflow run to finish')
}
/** Run a full workflow to completion and return the persisted run record. */
async function runToEnd(
runtime: WorkflowRuntime,
store: ReturnType<typeof createStore>,
workflowId: string,
input?: unknown
): Promise<WorkflowRunV1> {
const started = await runtime.runWorkflow(workflowId, input)
if (!started.ok || !started.runId) throw new Error(`runWorkflow failed: ${started.message}`)
const runId = started.runId
await waitFor(async () => {
const run = (await store.load()).workflow.workflows.find((w) => w.id === workflowId)?.runs.find((e) => e.id === runId)
return Boolean(run && run.status !== 'running')
}, 10_000)
return store.read().workflow.workflows.find((w) => w.id === workflowId)!.runs.find((e) => e.id === runId)!
}
function parseOut(result: WorkflowNodeRunResultV1): unknown {
return JSON.parse(result.outputJson)
}
/** Parse the JSON body of a recorded runtimeRequest call (call[2] = the request init). */
function callBody(call: unknown): Record<string, unknown> {
const init = (call as unknown[])[2] as { body?: string } | undefined
return init?.body ? (JSON.parse(init.body) as Record<string, unknown>) : {}
}
/** The prompt the AI node actually sent to the kun runtime (from the /turns request). */
function turnPrompt(rr: ReturnType<typeof vi.fn>): string {
const call = rr.mock.calls.find((c) => String((c as unknown[])[1]).includes('/turns'))
return call ? String(callBody(call).prompt ?? '') : ''
}
/** The workspace the AI node opened its thread in (from the POST /v1/threads request). */
function threadWorkspace(rr: ReturnType<typeof vi.fn>): string {
const call = rr.mock.calls.find((c) => (c as unknown[])[1] === '/v1/threads')
return call ? String(callBody(call).workspace ?? '') : ''
}
// Tracks which kinds this file actually tests; the completeness guard cross-checks
// it against WORKFLOW_NODE_KINDS so no node type can ship without coverage.
const COVERED = new Set<WorkflowNodeKind>()
function cover(kind: WorkflowNodeKind): WorkflowNodeKind {
COVERED.add(kind)
return kind
}
const FIELD = (over: Record<string, unknown>): Record<string, unknown> => ({
key: 'k',
label: 'K',
type: 'text',
required: false,
options: [],
defaultValue: '',
description: '',
...over
})
beforeEach(() => {
workflowWorkspaceRoot = mkdtempSync(join(tmpdir(), 'kun-workflow-nodes-'))
})
afterEach(() => {
vi.unstubAllGlobals()
if (workflowWorkspaceRoot) {
rmSync(workflowWorkspaceRoot, { recursive: true, force: true })
workflowWorkspaceRoot = ''
}
})
// ===========================================================================
// Triggers
// ===========================================================================
describe('manual-trigger', () => {
it('emits the run payload and lets the chain proceed', async () => {
cover('manual-trigger')
const store = createStore(
buildSettings([
wf({
id: 'mt',
nodes: [
{ id: 'm', type: 'manual-trigger', config: {} },
{ id: 'o', type: 'output', config: { mode: 'auto' } }
],
connections: [{ id: 'e1', source: 'm', target: 'o' }]
})
])
)
const runtime = createWorkflowRuntime({ store: store as never, runtimeRequest: defaultRuntimeRequest() as never, logError: vi.fn() })
const run = await runToEnd(runtime, store, 'mt')
expect(run.status).toBe('success')
expect(run.nodeResults.find((r) => r.nodeId === 'm')?.message).toBe('Triggered')
runtime.stop()
}, 15_000)
it('coerces typed inputs onto the initial payload', async () => {
const store = createStore(
buildSettings([
wf({
id: 'mt-in',
name: 'Inputs',
nodes: [
{
id: 'm',
type: 'manual-trigger',
config: { inputSchema: [FIELD({ key: 'n', label: 'N', type: 'number' })] }
},
{ id: 'o', type: 'output', config: { mode: 'auto' } }
],
connections: [{ id: 'e1', source: 'm', target: 'o' }]
})
])
)
const runtime = createWorkflowRuntime({ store: store as never, runtimeRequest: defaultRuntimeRequest() as never, logError: vi.fn() })
const result = await runtime.runWorkflowByRef('Inputs', { n: '5' })
expect(result.ok).toBe(true)
expect((JSON.parse(result.output) as { n: number }).n).toBe(5)
runtime.stop()
}, 15_000)
})
describe('schedule-trigger', () => {
it('runs as a trigger and emits its payload', async () => {
cover('schedule-trigger')
const store = createStore(
buildSettings([
wf({
id: 'st',
nodes: [
{ id: 's', type: 'schedule-trigger', config: { schedule: { kind: 'interval', everyMinutes: 30 } } },
{ id: 'sf', type: 'set-fields', config: { fields: [{ key: 'ran', value: 'yes' }], keepIncoming: false } }
],
connections: [{ id: 'e1', source: 's', target: 'sf' }]
})
])
)
const runtime = createWorkflowRuntime({ store: store as never, runtimeRequest: defaultRuntimeRequest() as never, logError: vi.fn() })
const run = await runToEnd(runtime, store, 'st')
expect(run.status).toBe('success')
expect(run.nodeResults.find((r) => r.nodeId === 's')?.message).toBe('Triggered')
expect(parseOut(run.nodeResults.find((r) => r.nodeId === 'sf')!)).toEqual({ ran: 'yes' })
runtime.stop()
}, 15_000)
it('computes the next fire time for every schedule kind', () => {
const from = new Date('2026-06-19T08:00:00.000Z')
const next = (schedule: Record<string, unknown>): string =>
computeWorkflowNextRunAt(
wf({ id: 'x', enabled: true, nodes: [{ id: 't', type: 'schedule-trigger', config: { schedule } }] }),
from
)
expect(next({ kind: 'interval', everyMinutes: 30 })).toBe(new Date(from.getTime() + 30 * 60_000).toISOString())
expect(next({ kind: 'cron', cron: '0 9 * * *' })).not.toBe('')
expect(Number.isFinite(Date.parse(next({ kind: 'daily', timeOfDay: '09:00' })))).toBe(true)
// 'manual' schedule never auto-fires.
expect(workflowHasScheduleTrigger(wf({ id: 'm', nodes: [{ id: 't', type: 'schedule-trigger', config: { schedule: { kind: 'manual' } } }] }))).toBe(false)
})
})
describe('webhook-trigger', () => {
it('runs as a trigger node and emits its payload to the chain', async () => {
cover('webhook-trigger')
// runWorkflow selects the webhook trigger as a fallback, exercising the node's
// execute path without binding a TCP port (the live server is covered in run.test).
const store = createStore(
buildSettings([
wf({
id: 'wh',
nodes: [
{ id: 'w', type: 'webhook-trigger', config: { path: '/hook', method: 'POST' } },
{ id: 'sf', type: 'set-fields', config: { fields: [{ key: 'hit', value: '1' }], keepIncoming: false } }
],
connections: [{ id: 'e1', source: 'w', target: 'sf' }]
})
])
)
const runtime = createWorkflowRuntime({ store: store as never, runtimeRequest: defaultRuntimeRequest() as never, logError: vi.fn() })
const run = await runToEnd(runtime, store, 'wh')
expect(run.status).toBe('success')
expect(run.nodeResults.find((r) => r.nodeId === 'w')?.message).toBe('Triggered')
runtime.stop()
}, 15_000)
})
// ===========================================================================
// AI nodes
// ===========================================================================
describe('ai-agent', () => {
it('runs the prompt through the kun runtime and returns the reply', async () => {
cover('ai-agent')
const result = await testNode(
{ id: 'a', type: 'ai-agent', config: { prompt: 'say hi', model: 'test-model' } },
'{}',
{ runtimeRequest: aiRuntimeRequest('HELLO WORLD') }
)
expect(result.status).toBe('success')
expect((parseOut(result) as { text: string }).text).toBe('HELLO WORLD')
expect(result.threadId).toBe('thread-1')
}, 15_000)
it('interpolates {{ }} from the upstream payload into the prompt', async () => {
const rr = aiRuntimeRequest('ok')
await testNode(
{ id: 'a', type: 'ai-agent', config: { prompt: 'echo {{json.name}}', model: 'test-model' } },
'{"name":"Kun"}',
{ runtimeRequest: rr }
)
// The template wins verbatim — the raw input is NOT also appended.
expect(turnPrompt(rr)).toBe('echo Kun')
}, 15_000)
it('appends the upstream input to the prompt when it uses no {{ }}', async () => {
const rr = aiRuntimeRequest('ok')
await testNode(
{ id: 'a', type: 'ai-agent', config: { prompt: 'say hi', model: 'test-model' } },
'{"name":"Kun"}',
{ runtimeRequest: rr }
)
const prompt = turnPrompt(rr)
expect(prompt).toContain('say hi')
expect(prompt).toContain('Kun')
}, 15_000)
it('leaves the prompt alone when there is no meaningful upstream input', async () => {
const rr = aiRuntimeRequest('ok')
await testNode({ id: 'a', type: 'ai-agent', config: { prompt: 'say hi', model: 'test-model' } }, '{}', {
runtimeRequest: rr
})
expect(turnPrompt(rr)).toBe('say hi')
}, 15_000)
it('passes the working directory in as a run parameter ({{json.dir}})', async () => {
const rr = aiRuntimeRequest('ok')
const customWorkspaceRoot = mkdtempSync(join(workflowWorkspaceRoot, 'custom-'))
const store = createStore(
buildSettings([
wf({
id: 'ws',
name: 'WS',
nodes: [
{
id: 'm',
type: 'manual-trigger',
config: { workspaceRoot: '{{json.dir}}', inputSchema: [FIELD({ key: 'dir', label: 'Dir' })] }
},
{ id: 'a', type: 'ai-agent', config: { prompt: 'hi', model: 'test-model' } }
],
connections: [{ id: 'e1', source: 'm', target: 'a' }]
})
])
)
const runtime = createWorkflowRuntime({ store: store as never, runtimeRequest: rr as never, logError: vi.fn() })
try {
const result = await runtime.runWorkflowByRef('WS', { dir: customWorkspaceRoot })
expect(result.ok).toBe(true)
expect(threadWorkspace(rr)).toBe(customWorkspaceRoot)
} finally {
runtime.stop()
}
}, 15_000)
it('fails the node when the runtime errors', async () => {
const rr = vi.fn(async (_s: AppSettingsV1, path: string) =>
path === '/v1/threads' ? { ok: false, status: 500, body: JSON.stringify({ message: 'boom' }) } : okEmpty
)
const result = await testNode({ id: 'a', type: 'ai-agent', config: { prompt: 'x', model: 'test-model' } }, '{}', {
runtimeRequest: rr
})
expect(result.status).toBe('error')
expect(result.error).toContain('boom')
}, 15_000)
})
describe('generate-image', () => {
it('generates an image and writes it to the output folder', async () => {
cover('generate-image')
imageGenerateMock.mockClear()
const dir = mkdtempSync(join(tmpdir(), 'wf-img-'))
try {
const result = await testNode(
{ id: 'g', type: 'generate-image', config: { prompt: 'a cat', outputDir: dir } },
'{}',
{
patch: (s) => ({
...s,
agents: {
kun: {
...s.agents.kun,
imageGeneration: {
...s.agents.kun.imageGeneration,
enabled: true,
providerId: '',
baseUrl: 'https://img.test/v1',
apiKey: 'sk-img',
model: 'img-model',
defaultResolution: '2K'
}
}
}
})
}
)
expect(result.status).toBe('success')
const out = parseOut(result) as { imagePath: string; mimeType: string }
expect(out.mimeType).toBe('image/png')
expect(out.imagePath.endsWith('.png')).toBe(true)
expect(existsSync(out.imagePath)).toBe(true)
expect(imageGenerateMock).toHaveBeenCalledWith(expect.objectContaining({ size: '2048x2048' }))
} finally {
rmSync(dir, { recursive: true, force: true })
}
}, 15_000)
it('errors when image generation is not configured', async () => {
const result = await testNode({ id: 'g', type: 'generate-image', config: { prompt: 'a cat' } }, '{}')
expect(result.status).toBe('error')
expect(result.error.toLowerCase()).toContain('not configured')
}, 15_000)
})
describe('parameter-extractor', () => {
it('extracts typed fields from text using the model reply', async () => {
cover('parameter-extractor')
const result = await testNode(
{
id: 'pe',
type: 'parameter-extractor',
config: {
source: '{{text}}',
fields: [FIELD({ key: 'city', label: 'City', type: 'text' }), FIELD({ key: 'temp', label: 'Temp', type: 'number' })],
model: 'test-model'
}
},
'It is 12 degrees in Paris.',
{ runtimeRequest: aiRuntimeRequest('```json\n{"city":"Paris","temp":"12"}\n```') }
)
expect(result.status).toBe('success')
expect(parseOut(result)).toEqual({ city: 'Paris', temp: 12 })
}, 15_000)
it('fails the node when the model run errors', async () => {
const rr = vi.fn(async (_s: AppSettingsV1, path: string) =>
path === '/v1/threads' ? { ok: false, status: 500, body: JSON.stringify({ message: 'down' }) } : okEmpty
)
const result = await testNode(
{
id: 'pe',
type: 'parameter-extractor',
config: { source: '{{text}}', fields: [FIELD({ key: 'city', label: 'City' })], model: 'test-model' }
},
'Paris',
{ runtimeRequest: rr }
)
expect(result.status).toBe('error')
expect(result.error).toContain('down')
}, 15_000)
})
describe('question-classifier', () => {
it('routes to the category the model picks by number', async () => {
cover('question-classifier')
const result = await testNode(
{
id: 'qc',
type: 'question-classifier',
config: {
source: '{{text}}',
categories: [
{ id: 'cat-feature', label: 'Feature' },
{ id: 'cat-bug', label: 'Bug' }
],
model: 'test-model'
}
},
'the app crashes on launch',
{ runtimeRequest: aiRuntimeRequest('2') }
)
expect(result.status).toBe('success')
expect(result.message).toBe('→ Bug')
}, 15_000)
it('defaults to the first category when the reply is out of range', async () => {
const result = await testNode(
{
id: 'qc',
type: 'question-classifier',
config: {
source: '{{text}}',
categories: [
{ id: 'cat-feature', label: 'Feature' },
{ id: 'cat-bug', label: 'Bug' }
],
model: 'test-model'
}
},
'anything',
{ runtimeRequest: aiRuntimeRequest('9') }
)
expect(result.message).toBe('→ Feature')
}, 15_000)
it('short-circuits with no model call when there are no categories', async () => {
const rr = aiRuntimeRequest('1')
const result = await testNode(
{ id: 'qc', type: 'question-classifier', config: { source: '{{text}}', categories: [], model: 'test-model' } },
'anything',
{ runtimeRequest: rr }
)
expect(result.message).toBe('no categories')
expect(rr).not.toHaveBeenCalled()
}, 15_000)
})
// ===========================================================================
// Branching / logic
// ===========================================================================
describe('condition', () => {
it('reports true/false for the chosen branch', async () => {
cover('condition')
const hit = await testNode(
{ id: 'c', type: 'condition', config: { leftExpr: 'json.v', operator: 'contains', rightValue: 'ell' } },
'{"v":"hello"}'
)
expect(hit.message).toBe('true')
const miss = await testNode(
{ id: 'c', type: 'condition', config: { leftExpr: 'json.v', operator: 'contains', rightValue: 'zzz' } },
'{"v":"hello"}'
)
expect(miss.message).toBe('false')
}, 15_000)
it('evaluates every operator correctly', async () => {
const cases: { op: string; left: unknown; right: string; expect: boolean }[] = [
{ op: 'equals', left: 'a', right: 'a', expect: true },
{ op: 'notEquals', left: 'a', right: 'b', expect: true },
{ op: 'startsWith', left: 'hello', right: 'he', expect: true },
{ op: 'endsWith', left: 'hello', right: 'lo', expect: true },
{ op: 'notContains', left: 'hello', right: 'zz', expect: true },
{ op: 'isEmpty', left: '', right: '', expect: true },
{ op: 'isNotEmpty', left: 'x', right: '', expect: true },
{ op: 'gt', left: 5, right: '3', expect: true },
{ op: 'gte', left: 3, right: '3', expect: true },
{ op: 'lt', left: 2, right: '3', expect: true },
{ op: 'lte', left: 3, right: '3', expect: true }
]
for (const c of cases) {
const result = await testNode(
{ id: 'c', type: 'condition', config: { leftExpr: 'json.v', operator: c.op, rightValue: c.right } },
JSON.stringify({ v: c.left })
)
expect(`${c.op}=${result.message}`).toBe(`${c.op}=${c.expect ? 'true' : 'false'}`)
}
}, 30_000)
it('honors caseSensitive and falls back to payload.text when leftExpr is empty', async () => {
// Empty leftExpr → compares against payload.text (here the raw mock string).
const insensitive = await testNode(
{ id: 'c', type: 'condition', config: { leftExpr: '', operator: 'equals', rightValue: 'hello', caseSensitive: false } },
'HELLO'
)
expect(insensitive.message).toBe('true')
const sensitive = await testNode(
{ id: 'c', type: 'condition', config: { leftExpr: '', operator: 'equals', rightValue: 'hello', caseSensitive: true } },
'HELLO'
)
expect(sensitive.message).toBe('false')
}, 15_000)
})
describe('switch', () => {
it('matches the first satisfied rule', async () => {
cover('switch')
const result = await testNode(
{
id: 'sw',
type: 'switch',
config: {
rules: [
{ leftExpr: 'json.v', operator: 'equals', rightValue: 'A', caseSensitive: false },
{ leftExpr: 'json.v', operator: 'equals', rightValue: 'B', caseSensitive: false }
],
fallback: false
}
},
'{"v":"B"}'
)
expect(result.message).toBe('case 2')
}, 15_000)
it('falls back when nothing matches and a fallback is enabled', async () => {
const result = await testNode(
{
id: 'sw',
type: 'switch',
config: { rules: [{ leftExpr: 'json.v', operator: 'equals', rightValue: 'A', caseSensitive: false }], fallback: true }
},
'{"v":"Z"}'
)
expect(result.message).toBe('fallback')
}, 15_000)
it('reports no match when nothing matches and there is no fallback', async () => {
const result = await testNode(
{
id: 'sw',
type: 'switch',
config: { rules: [{ leftExpr: 'json.v', operator: 'equals', rightValue: 'A', caseSensitive: false }], fallback: false }
},
'{"v":"Z"}'
)
expect(result.message).toBe('no match')
}, 15_000)
it('respects caseSensitive when matching a rule', async () => {
const rule = (caseSensitive: boolean): NodeSpec => ({
id: 'sw',
type: 'switch',
config: { rules: [{ leftExpr: 'json.v', operator: 'equals', rightValue: 'B', caseSensitive }], fallback: false }
})
expect((await testNode(rule(false), '{"v":"b"}')).message).toBe('case 1')
expect((await testNode(rule(true), '{"v":"b"}')).message).toBe('no match')
}, 15_000)
})
describe('filter', () => {
it('passes or blocks based on the condition', async () => {
cover('filter')
const pass = await testNode(
{ id: 'f', type: 'filter', config: { leftExpr: 'json.v', operator: 'equals', rightValue: 'B' } },
'{"v":"B"}'
)
expect(pass.message).toBe('pass')
const blocked = await testNode(
{ id: 'f', type: 'filter', config: { leftExpr: 'json.v', operator: 'equals', rightValue: 'C' } },
'{"v":"B"}'
)
expect(blocked.message).toBe('blocked')
}, 15_000)
})
describe('human-approval', () => {
it('auto-approves in single-node test mode', async () => {
cover('human-approval')
const result = await testNode(
{ id: 'h', type: 'human-approval', config: { title: 'Confirm', instruction: 'ok?', timeoutMs: 0, onTimeout: 'rejected' } },
'{"x":1}'
)
expect(result.status).toBe('success')
expect(result.message).toBe('approved (test)')
}, 15_000)
it('routes to the rejected branch when the approval times out', async () => {
const store = createStore(
buildSettings([
wf({
id: 'ha',
nodes: [
{ id: 'm', type: 'manual-trigger', config: {} },
{ id: 'a', type: 'human-approval', config: { title: 'x', instruction: '', timeoutMs: 50, onTimeout: 'rejected' } },
{ id: 'yes', type: 'set-fields', config: { fields: [{ key: 'p', value: 'approved' }], keepIncoming: false } },
{ id: 'no', type: 'set-fields', config: { fields: [{ key: 'p', value: 'rejected' }], keepIncoming: false } }
],
connections: [
{ id: 'e1', source: 'm', target: 'a' },
{ id: 'e2', source: 'a', sourceHandle: 'approved', target: 'yes' },
{ id: 'e3', source: 'a', sourceHandle: 'rejected', target: 'no' }
]
})
])
)
const runtime = createWorkflowRuntime({ store: store as never, runtimeRequest: defaultRuntimeRequest() as never, logError: vi.fn() })
const run = await runToEnd(runtime, store, 'ha')
expect(run.status).toBe('success')
expect(run.nodeResults.find((r) => r.nodeId === 'no')?.status).toBe('success')
expect(run.nodeResults.find((r) => r.nodeId === 'yes')).toBeUndefined()
runtime.stop()
}, 15_000)
it('pauses, then routes to the approved branch injecting _approved on a real decision', async () => {
const store = createStore(
buildSettings([
wf({
id: 'ha-ok',
nodes: [
{ id: 'm', type: 'manual-trigger', config: {} },
{ id: 'a', type: 'human-approval', config: { title: 'Confirm', instruction: 'ship it?', timeoutMs: 0, onTimeout: 'rejected' } },
{ id: 'out', type: 'output', config: { mode: 'auto' } }
],
connections: [
{ id: 'e1', source: 'm', target: 'a' },
{ id: 'e2', source: 'a', sourceHandle: 'approved', target: 'out' }
]
})
])
)
const runtime = createWorkflowRuntime({ store: store as never, runtimeRequest: defaultRuntimeRequest() as never, logError: vi.fn() })
const started = await runtime.runWorkflow('ha-ok')
if (!started.ok || !started.runId) throw new Error(`runWorkflow failed: ${started.message}`)
const runId = started.runId
// The node pauses until a decision arrives; it surfaces via status().
await waitFor(async () => (await runtime.status()).pendingApprovals.length > 0, 10_000)
const pending = (await runtime.status()).pendingApprovals[0]
expect(pending.title).toBe('Confirm')
expect(runtime.resolveApproval(pending.token, 'approved')).toBe(true)
await waitFor(async () => {
const run = store.read().workflow.workflows[0].runs.find((e) => e.id === runId)
return Boolean(run && run.status !== 'running')
}, 10_000)
const run = store.read().workflow.workflows[0].runs.find((e) => e.id === runId)!
expect(run.status).toBe('success')
// The approved payload carries _approved: true into the downstream node.
const out = run.nodeResults.find((r) => r.nodeId === 'out')!
expect(JSON.parse(out.outputJson)).toEqual({ _approved: true })
runtime.stop()
}, 20_000)
})
// ===========================================================================
// Data shaping
// ===========================================================================
describe('set-fields', () => {
it('replaces the payload and interpolates field values (payload scope)', async () => {
cover('set-fields')
const result = await testNode(
{
id: 's',
type: 'set-fields',
config: { fields: [{ key: 'greeting', value: 'hi {{json.name}}' }, { key: 'fixed', value: 'x' }], keepIncoming: false }
},
'{"name":"World"}'
)
expect(parseOut(result)).toEqual({ greeting: 'hi World', fixed: 'x' })
}, 15_000)
it('keeps the incoming fields when keepIncoming is set', async () => {
const result = await testNode(
{ id: 's', type: 'set-fields', config: { fields: [{ key: 'b', value: '2' }], keepIncoming: true } },
'{"a":"1"}'
)
expect(parseOut(result)).toEqual({ a: '1', b: '2' })
}, 15_000)
it('writes run-scoped vars and passes the payload through (run scope)', async () => {
const result = await testNode(
{ id: 's', type: 'set-fields', config: { scope: 'run', fields: [{ key: 'token', value: 'abc' }] } },
'{"keep":"me"}'
)
expect(result.message).toContain('run var')
expect(parseOut(result)).toEqual({ keep: 'me' })
}, 15_000)
it('exposes a run-scoped var to a downstream node as {{$run.key}}', async () => {
const store = createStore(
buildSettings([
wf({
id: 'rv',
nodes: [
{ id: 'm', type: 'manual-trigger', config: {} },
{ id: 's', type: 'set-fields', config: { scope: 'run', fields: [{ key: 'token', value: 'abc' }] } },
{ id: 't', type: 'template', config: { template: 'tok={{$run.token}}', outputMode: 'text' } }
],
connections: [
{ id: 'e1', source: 'm', target: 's' },
{ id: 'e2', source: 's', target: 't' }
]
})
])
)
const runtime = createWorkflowRuntime({ store: store as never, runtimeRequest: defaultRuntimeRequest() as never, logError: vi.fn() })
const run = await runToEnd(runtime, store, 'rv')
expect(run.status).toBe('success')
const tpl = run.nodeResults.find((r) => r.nodeId === 't')!
expect((JSON.parse(tpl.outputJson) as { text: string }).text).toBe('tok=abc')
runtime.stop()
}, 15_000)
})
describe('code', () => {
it('evaluates JavaScript against the payload', async () => {
cover('code')
const result = await testNode(
{ id: 'c', type: 'code', config: { code: 'return { doubled: Number($json.n) * 2 }' } },
'{"n":5}'
)
expect(parseOut(result)).toEqual({ doubled: 10 })
}, 15_000)
it('errors (and times out) on an infinite loop', async () => {
const result = await testNode({ id: 'c', type: 'code', config: { code: 'while (true) {}' } }, '{}')
expect(result.status).toBe('error')
expect(result.error.toLowerCase()).toContain('code')
}, 15_000)
it('runs a bash script with stdin/env input and parses stdout', async () => {
const result = await testNode(
{ id: 'c', type: 'code', config: { language: 'bash', code: 'echo "{\\"lang\\": \\"bash\\", \\"got\\": $WORKFLOW_JSON}"' } },
'{"n":"5"}'
)
expect(result.status).toBe('success')
const out = parseOut(result) as { lang: string; got: { n: string } }
expect(out.lang).toBe('bash')
expect(out.got.n).toBe('5')
}, 15_000)
it('errors when a bash script exits non-zero', async () => {
const result = await testNode({ id: 'c', type: 'code', config: { language: 'bash', code: 'echo oops >&2; exit 3' } }, '{}')
expect(result.status).toBe('error')
expect(result.error).toContain('exited with code 3')
}, 15_000)
it('wraps non-JSON bash stdout as { text }', async () => {
const result = await testNode({ id: 'c', type: 'code', config: { language: 'bash', code: 'echo hello there' } }, '{}')
expect(result.status).toBe('success')
expect(parseOut(result)).toEqual({ text: 'hello there' })
}, 15_000)
it.runIf(PYTHON_OK)('runs a python script and parses its stdout', async () => {
const result = await testNode(
{ id: 'c', type: 'code', config: { language: 'python', code: 'import json,os; print(json.dumps({"py": True, "n": json.loads(os.environ["WORKFLOW_JSON"])["n"]}))' } },
'{"n":7}'
)
expect(result.status).toBe('success')
expect(parseOut(result)).toEqual({ py: true, n: 7 })
}, 15_000)
})
describe('sort', () => {
it('orders an array by a numeric field ascending and descending', async () => {
cover('sort')
const asc = await testNode({ id: 'srt', type: 'sort', config: { field: 'v', order: 'asc', numeric: true } }, '[{"v":3},{"v":1},{"v":2}]')
expect(parseOut(asc)).toEqual([{ v: 1 }, { v: 2 }, { v: 3 }])
const desc = await testNode({ id: 'srt', type: 'sort', config: { field: 'v', order: 'desc', numeric: true } }, '[{"v":3},{"v":1},{"v":2}]')
expect(parseOut(desc)).toEqual([{ v: 3 }, { v: 2 }, { v: 1 }])
}, 15_000)
it('sorts strings lexically when numeric is off', async () => {
const result = await testNode({ id: 'srt', type: 'sort', config: { field: '', order: 'asc', numeric: false } }, '["banana","apple","cherry"]')
expect(parseOut(result)).toEqual(['apple', 'banana', 'cherry'])
}, 15_000)
})
describe('limit', () => {
it('keeps the first N items', async () => {
cover('limit')
const result = await testNode({ id: 'lim', type: 'limit', config: { count: 2, from: 'first' } }, '[1,2,3,4,5]')
expect(parseOut(result)).toEqual([1, 2])
}, 15_000)
it('keeps the last N items', async () => {
const result = await testNode({ id: 'lim', type: 'limit', config: { count: 2, from: 'last' } }, '[1,2,3,4,5]')
expect(parseOut(result)).toEqual([4, 5])
}, 15_000)
})
describe('aggregate', () => {
it('sums a field', async () => {
cover('aggregate')
const result = await testNode({ id: 'ag', type: 'aggregate', config: { mode: 'sum', field: 'price' } }, '[{"price":10},{"price":5},{"price":7}]')
expect(parseOut(result)).toEqual({ sum: 22 })
}, 15_000)
it('counts items', async () => {
const result = await testNode({ id: 'ag', type: 'aggregate', config: { mode: 'count' } }, '[1,2,3]')
expect(parseOut(result)).toEqual({ count: 3 })
}, 15_000)
it('joins a field with a separator', async () => {
const result = await testNode({ id: 'ag', type: 'aggregate', config: { mode: 'join', field: 'name', separator: ', ' } }, '[{"name":"a"},{"name":"b"}]')
expect(parseOut(result)).toEqual({ text: 'a, b' })
}, 15_000)
it('collects a field into an array', async () => {
const result = await testNode({ id: 'ag', type: 'aggregate', config: { mode: 'collect', field: 'id' } }, '[{"id":1},{"id":2}]')
expect(parseOut(result)).toEqual({ values: [1, 2] })
}, 15_000)
})
describe('merge', () => {
it('merges inputs into one object (object mode)', async () => {