-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathsummarizer_format_test.go
More file actions
2083 lines (1924 loc) · 67.5 KB
/
summarizer_format_test.go
File metadata and controls
2083 lines (1924 loc) · 67.5 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
package taskengine
import (
"context"
"fmt"
"math/big"
"os"
"strings"
"testing"
avsproto "github.com/AvaProtocol/EigenLayer-AVS/protobuf"
"google.golang.org/protobuf/types/known/structpb"
)
const (
// Default auth token for local context-memory tests
ContextMemoryAuthToken = "test-auth-token-12345"
)
type fakeSummarizer struct {
resp Summary
err error
}
func (f *fakeSummarizer) Summarize(ctx context.Context, vm *VM, currentStepName string) (Summary, error) {
return f.resp, f.err
}
func TestComposeSummarySmart_FallbackDeterministic(t *testing.T) {
SetSummarizer(nil)
vm := NewVM()
vm.mu.Lock()
vm.vars["settings"] = map[string]interface{}{"name": "Workflow X"}
vm.mu.Unlock()
vm.ExecutionLogs = []*avsproto.Execution_Step{{
Name: "Step A",
Success: true,
}}
s := ComposeSummarySmart(vm, "rest1")
if !strings.Contains(s.Subject, "Workflow X: succeeded") {
t.Fatalf("subject should contain 'Workflow X: succeeded', got: %q", s.Subject)
}
// Body should contain the workflow name and completion message
// The exact format may vary based on available context (smart wallet, owner, etc.)
// Just verify it contains the essential elements
if s.Body == "" {
t.Fatalf("body should not be empty")
}
if !strings.Contains(s.Body, "Workflow X") && !strings.Contains(s.Body, "Step A") {
t.Fatalf("body should mention workflow or step name, got: %q", s.Body)
}
}
func TestComposeSummarySmart_UsesAISummarizer(t *testing.T) {
defer SetSummarizer(nil)
// Check if we should use real context-memory API
authToken := os.Getenv("SERVICE_AUTH_TOKEN")
if authToken != "" {
// Use real context-memory API
baseURL := os.Getenv("CONTEXT_MEMORY_URL")
if baseURL == "" {
baseURL = ContextAPIURL // Default to production URL from source code
}
t.Logf("Using real context-memory API at: %s", baseURL)
summarizer := NewContextMemorySummarizer(baseURL, authToken)
SetSummarizer(summarizer)
vm := NewVM()
vm.mu.Lock()
vm.vars["settings"] = map[string]interface{}{"name": "Test Workflow"}
vm.mu.Unlock()
vm.ExecutionLogs = []*avsproto.Execution_Step{
{Id: "step1", Name: "test_step", Type: "balance", Success: true},
}
s := ComposeSummarySmart(vm, "current")
if s.Subject == "" {
t.Fatalf("AI summarizer should return non-empty subject, got empty")
}
if len(s.Body) < 40 {
t.Fatalf("AI summarizer body should be at least 40 characters, got %d", len(s.Body))
}
t.Logf("Real API response - Subject: %s, Body length: %d", s.Subject, len(s.Body))
} else {
// Fallback to mock for CI/testing without SERVICE_AUTH_TOKEN
// Body must be at least 40 characters to pass validation in ComposeSummarySmart
f := &fakeSummarizer{resp: Summary{
Subject: "AI subject",
Body: "This is a sufficiently long AI-generated body text that exceeds the 40 character minimum.",
}}
SetSummarizer(f)
vm := NewVM()
s := ComposeSummarySmart(vm, "current")
if s.Subject != "AI subject" {
t.Fatalf("ai summarizer subject not used: expected 'AI subject', got %q", s.Subject)
}
if !strings.Contains(s.Body, "AI-generated body text") {
t.Fatalf("ai summarizer body not used: got %q", s.Body)
}
}
}
func TestComposeSummarySmart_AIFailsFallback(t *testing.T) {
defer SetSummarizer(nil)
f := &fakeSummarizer{err: context.DeadlineExceeded}
SetSummarizer(f)
vm := NewVM()
vm.mu.Lock()
vm.vars["settings"] = map[string]interface{}{"name": "Workflow Y"}
vm.mu.Unlock()
vm.ExecutionLogs = []*avsproto.Execution_Step{{
Name: "Done",
Success: true,
}}
s := ComposeSummarySmart(vm, "rest1")
if !strings.Contains(s.Subject, "Workflow Y: succeeded") {
t.Fatalf("fallback failed, subject should contain 'Workflow Y: succeeded', got: %q", s.Subject)
}
}
func TestFormatForMessageChannels_Telegram(t *testing.T) {
tests := []struct {
name string
summary Summary
expectedContain []string
maxLength int
}{
{
name: "short summary with subject",
summary: Summary{
Subject: "Swap: succeeded (3 steps)",
Body: "Smart wallet 0xabc executed a swap on Uniswap V3.",
},
expectedContain: []string{"<b>Swap: succeeded (3 steps)</b>", "Smart wallet 0xabc executed a swap"},
maxLength: 300,
},
{
name: "long summary gets truncated",
summary: Summary{
Subject: "Trade: succeeded (5 steps)",
Body: "Smart wallet 0x123 executed multiple trades on Uniswap V3. " +
"First it approved 1000 USDC to the router contract at 0xdef. " +
"Then it swapped 100 USDC for approximately 0.025 WETH via the pool. " +
"Finally it performed another swap of 50 USDC for DAI tokens at contract 0x456. " +
"All transactions completed successfully on Base network.",
},
expectedContain: []string{"<b>Trade: succeeded (5 steps)</b>", "Smart wallet 0x123"},
maxLength: 300,
},
{
name: "empty body returns subject",
summary: Summary{
Subject: "Workflow: failed (1 step)",
Body: "",
},
expectedContain: []string{"Workflow: failed (1 step)"},
maxLength: 100,
},
{
name: "body with double newlines extracts first paragraph",
summary: Summary{
Subject: "Approve: succeeded (1 step)",
Body: "Smart wallet 0xabc approved 500 USDC to Uniswap router.\n\nThis allows future swaps without additional approvals.",
},
expectedContain: []string{"<b>Approve: succeeded (1 step)</b>", "Smart wallet 0xabc approved 500 USDC"},
maxLength: 300,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := FormatForMessageChannels(tt.summary, "telegram", nil)
// Check that result contains expected strings
for _, expected := range tt.expectedContain {
if !strings.Contains(result, expected) {
t.Errorf("expected result to contain %q, got: %s", expected, result)
}
}
// Check length constraint
if len(result) > tt.maxLength {
t.Errorf("result too long: %d chars (max %d), got: %s", len(result), tt.maxLength, result)
}
// Verify HTML parse mode compatibility (should have <b> tags)
if tt.summary.Subject != "" && tt.summary.Body != "" {
if !strings.HasPrefix(result, "<b>") {
t.Errorf("telegram message should start with <b> tag, got: %s", result)
}
}
})
}
}
func TestFormatForMessageChannels_Discord(t *testing.T) {
summary := Summary{
Subject: "Deploy: succeeded (2 steps)",
Body: "Contract deployed to 0xabc on Base network.",
}
result := FormatForMessageChannels(summary, "discord", nil)
// Discord should use markdown bold
if !strings.Contains(result, "**Deploy: succeeded (2 steps)**") {
t.Errorf("discord message should use markdown bold, got: %s", result)
}
if !strings.Contains(result, "Contract deployed to 0xabc") {
t.Errorf("discord message should contain body content, got: %s", result)
}
}
func TestFormatTransferMessage(t *testing.T) {
tests := []struct {
name string
data *TransferEventData
expected string
}{
{
name: "sent_eth",
data: &TransferEventData{
Direction: "sent",
FromAddress: "0x5d814Cc9E94B2656f59Ee439D44AA1b6ca21434f",
ToAddress: "0x0000000000000000000000000000000000000002",
Value: "1.5",
TokenSymbol: "ETH",
TokenName: "Ether",
BlockTimestamp: 1768943005000, // milliseconds
ChainName: "Sepolia",
},
expected: "⬆️ Sent <b>1.5 ETH</b> to <code>0x0000000000000000000000000000000000000002</code> on <b>Sepolia</b>",
},
{
name: "received_usdc",
data: &TransferEventData{
Direction: "received",
FromAddress: "0x1234567890123456789012345678901234567890",
ToAddress: "0x5d814Cc9E94B2656f59Ee439D44AA1b6ca21434f",
Value: "100.50",
TokenSymbol: "USDC",
TokenName: "USD Coin",
BlockTimestamp: 1768943005, // seconds
ChainName: "Ethereum",
},
expected: "⬇️ Received <b>100.50 USDC</b> from <code>0x1234567890123456789012345678901234567890</code> on <b>Ethereum</b>",
},
{
name: "nil_data",
data: nil,
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := FormatTransferMessage(tt.data)
if tt.expected == "" {
if result != "" {
t.Errorf("expected empty string, got: %s", result)
}
return
}
if !strings.Contains(result, tt.expected) {
t.Errorf("expected result to contain %q, got: %s", tt.expected, result)
}
})
}
}
// TestExtractTransferEventData_FromVars tests that transfer data can be extracted
// from vm.vars["transfer_monitor"] when ExecutionLogs has no Transfer event.
// This covers the single-node Telegram notification use case.
func TestExtractTransferEventData_FromVars(t *testing.T) {
vm := NewVM()
vm.mu.Lock()
vm.vars = map[string]any{
"transfer_monitor": map[string]interface{}{
"data": map[string]interface{}{
"eventName": "Transfer",
"direction": "sent",
"fromAddress": "0x5d814Cc9E94B2656f59Ee439D44AA1b6ca21434f",
"toAddress": "0x0000000000000000000000000000000000000002",
"value": "1.5",
"tokenSymbol": "ETH",
"tokenName": "Ether",
"blockTimestamp": int64(1768943005000),
},
},
"settings": map[string]interface{}{
"chain": "base",
},
}
vm.ExecutionLogs = []*avsproto.Execution_Step{} // Empty - no trigger step
vm.mu.Unlock()
got := ExtractTransferEventData(vm)
if got == nil {
t.Fatal("expected non-nil TransferEventData from vars, got nil")
}
if got.Direction != "sent" {
t.Errorf("expected Direction 'sent', got %q", got.Direction)
}
if got.Value != "1.5" {
t.Errorf("expected Value '1.5', got %q", got.Value)
}
if got.TokenSymbol != "ETH" {
t.Errorf("expected TokenSymbol 'ETH', got %q", got.TokenSymbol)
}
if got.FromAddress != "0x5d814Cc9E94B2656f59Ee439D44AA1b6ca21434f" {
t.Errorf("expected FromAddress, got %q", got.FromAddress)
}
if got.ToAddress != "0x0000000000000000000000000000000000000002" {
t.Errorf("expected ToAddress, got %q", got.ToAddress)
}
// ChainName should be resolved from settings (lowercase as stored)
if got.ChainName != "base" {
t.Errorf("expected ChainName 'base', got %q", got.ChainName)
}
// Verify FormatTransferMessage produces expected output
msg := FormatTransferMessage(got)
if !strings.Contains(msg, "1.5 ETH") {
t.Errorf("expected message to contain '1.5 ETH', got: %s", msg)
}
if !strings.Contains(msg, "Sent") {
t.Errorf("expected message to contain 'Sent', got: %s", msg)
}
if !strings.Contains(msg, "base") {
t.Errorf("expected message to contain 'base', got: %s", msg)
}
}
// TestExtractTransferEventData_ExecutionLogsTakesPrecedence verifies that
// ExecutionLogs data is used when present, even if transfer_monitor is also set.
func TestExtractTransferEventData_ExecutionLogsTakesPrecedence(t *testing.T) {
vm := NewVM()
// Create a protobuf struct for the event trigger data
eventData := map[string]interface{}{
"eventName": "Transfer",
"direction": "received",
"fromAddress": "0x1111111111111111111111111111111111111111",
"toAddress": "0x2222222222222222222222222222222222222222",
"value": "99.0",
"tokenSymbol": "USDC",
"tokenName": "USD Coin",
"blockTimestamp": float64(1768943005000),
}
// Convert to structpb.Value
protoData, _ := structpb.NewValue(eventData)
vm.mu.Lock()
vm.ExecutionLogs = []*avsproto.Execution_Step{
{
Id: "trigger",
Name: "eventTrigger",
Type: "eventTrigger",
Success: true,
OutputData: &avsproto.Execution_Step_EventTrigger{
EventTrigger: &avsproto.EventTrigger_Output{
Data: protoData,
},
},
},
}
// Also set transfer_monitor with different data
vm.vars = map[string]any{
"transfer_monitor": map[string]interface{}{
"data": map[string]interface{}{
"eventName": "Transfer",
"direction": "sent",
"value": "1.5",
"tokenSymbol": "ETH",
},
},
"settings": map[string]interface{}{
"chain": "ethereum",
},
}
vm.mu.Unlock()
got := ExtractTransferEventData(vm)
if got == nil {
t.Fatal("expected non-nil TransferEventData, got nil")
}
// Should use ExecutionLogs data (received USDC), not transfer_monitor (sent ETH)
if got.Direction != "received" {
t.Errorf("expected Direction 'received' from ExecutionLogs, got %q", got.Direction)
}
if got.TokenSymbol != "USDC" {
t.Errorf("expected TokenSymbol 'USDC' from ExecutionLogs, got %q", got.TokenSymbol)
}
if got.Value != "99.0" {
t.Errorf("expected Value '99.0' from ExecutionLogs, got %q", got.Value)
}
}
// TestFormatForMessageChannels_SingleNodeExample tests that single-node executions
// without transfer data show an example message with real workflow name and chain.
func TestFormatForMessageChannels_SingleNodeExample(t *testing.T) {
vm := NewVM()
vm.mu.Lock()
// Single node execution: no TaskID, exactly one TaskNode
vm.TaskNodes = map[string]*avsproto.TaskNode{
"node1": {Id: "node1", Name: "singleNodeExecution_restApi"},
}
vm.vars = map[string]any{
"settings": map[string]interface{}{
"name": "My Transfer Monitor",
"chain": "Base",
},
}
// No transfer_monitor data - should trigger example message
vm.ExecutionLogs = []*avsproto.Execution_Step{}
vm.mu.Unlock()
// Empty summary - no structured data
summary := Summary{}
result := FormatForMessageChannels(summary, "telegram", vm)
// Should contain workflow name from settings
if !strings.Contains(result, "My Transfer Monitor") {
t.Errorf("expected result to contain workflow name 'My Transfer Monitor', got: %s", result)
}
// Should contain chain name from settings
if !strings.Contains(result, "Base") {
t.Errorf("expected result to contain chain name 'Base', got: %s", result)
}
// Should contain the example execution line
if !strings.Contains(result, "(Simulated) On-chain transaction successfully completed") {
t.Errorf("expected result to contain example execution line, got: %s", result)
}
// Should contain the example notice
if !strings.Contains(result, "This is an example") {
t.Errorf("expected result to contain example notice, got: %s", result)
}
// Should be formatted as Telegram HTML
if !strings.Contains(result, "<b>") {
t.Errorf("expected Telegram HTML formatting with <b> tags, got: %s", result)
}
t.Logf("Example message:\n%s", result)
}
// TestFormatForMessageChannels_SingleNodeExample_Discord tests Discord formatting
func TestFormatForMessageChannels_SingleNodeExample_Discord(t *testing.T) {
vm := NewVM()
vm.mu.Lock()
vm.TaskNodes = map[string]*avsproto.TaskNode{
"node1": {Id: "node1", Name: "singleNodeExecution_restApi"},
}
vm.vars = map[string]any{
"settings": map[string]interface{}{
"name": "Price Alert",
"chain_id": 8453, // Base chain ID
},
}
vm.ExecutionLogs = []*avsproto.Execution_Step{}
vm.mu.Unlock()
summary := Summary{}
result := FormatForMessageChannels(summary, "discord", vm)
// Should use Discord markdown formatting
if !strings.Contains(result, "**Price Alert**") {
t.Errorf("expected Discord markdown with **workflow name**, got: %s", result)
}
// Chain should be resolved from chain_id
if !strings.Contains(result, "Base") {
t.Errorf("expected chain name 'Base' resolved from chain_id, got: %s", result)
}
t.Logf("Discord example message:\n%s", result)
}
// TestComposeSummarySmart_WithRealWorkflowState tests the full flow
// with realistic workflow state. Uses real context-memory API if SERVICE_AUTH_TOKEN is set.
func TestComposeSummarySmart_WithRealWorkflowState(t *testing.T) {
defer SetSummarizer(nil)
vm := NewVM()
vm.TaskID = "01K6H8R583M8WFXM2Z4APP7JTN"
// Simulate a workflow that ran 4 out of 7 steps
vm.ExecutionLogs = []*avsproto.Execution_Step{
{Id: "trigger", Name: "eventTrigger", Type: "eventTrigger", Success: true},
{Id: "step1", Name: "balance1", Type: "balance", Success: true},
{Id: "step2", Name: "branch1", Type: "branch", Success: true},
{Id: "step3", Name: "email_report", Type: "restApi", Success: true},
}
vm.mu.Lock()
vm.TaskNodes = map[string]*avsproto.TaskNode{
"node1": {Id: "node1", Name: "balance1"},
"node2": {Id: "node2", Name: "branch1"},
"node3": {Id: "node3", Name: "approve_token1"},
"node4": {Id: "node4", Name: "get_quote"},
"node5": {Id: "node5", Name: "run_swap"},
"node6": {Id: "node6", Name: "email_report"},
}
vm.vars = map[string]interface{}{
"settings": map[string]interface{}{
"name": "Test template",
"chain": "Sepolia",
"runner": "0xeCb88a770e1b2Ba303D0dC3B1c6F239fAB014bAE",
},
}
vm.mu.Unlock()
// Check if we should use real context-memory API
authToken := os.Getenv("SERVICE_AUTH_TOKEN")
if authToken != "" {
// Use real context-memory API (defaults to localhost:3000)
baseURL := os.Getenv("CONTEXT_MEMORY_URL")
if baseURL == "" {
baseURL = ContextAPIURL // Default to production URL from source code
}
t.Logf("Using real context-memory API at: %s", baseURL)
summarizer := NewContextMemorySummarizer(baseURL, authToken)
SetSummarizer(summarizer)
} else {
// Use deterministic fallback if no auth token
t.Log("SERVICE_AUTH_TOKEN not set, using deterministic fallback")
SetSummarizer(nil)
}
summary := ComposeSummarySmart(vm, "email_report")
// Should show workflow name and execution status
if !strings.Contains(summary.Subject, "Test template") {
t.Errorf("Subject should contain workflow name, got: %s", summary.Subject)
}
if summary.Body == "" {
t.Error("Body should not be empty")
}
t.Logf("Subject: %s", summary.Subject)
t.Logf("Body length: %d", len(summary.Body))
}
// TestComposeSummary_SimulationSubjectFormat tests that simulation workflows
// generate the correct subject format matching context-memory API expectations
func TestComposeSummary_SimulationSubjectFormat(t *testing.T) {
tests := []struct {
name string
workflowName string
executedSteps int
totalSteps int
hasFailures bool
hasSkippedNodes bool
isSimulation bool
expectedSubject string
expectedSummary string
}{
{
name: "simulation successfully completed",
workflowName: "Test Stoploss",
executedSteps: 7,
totalSteps: 7,
hasFailures: false,
hasSkippedNodes: false,
isSimulation: true,
expectedSubject: "Simulation: Test Stoploss successfully completed",
expectedSummary: "Your workflow 'Test Stoploss' executed 7 out of 7 total steps",
},
{
name: "simulation partially executed",
workflowName: "Test Stoploss",
executedSteps: 5,
totalSteps: 8,
hasFailures: false,
hasSkippedNodes: true,
isSimulation: true,
expectedSubject: "Simulation: Test Stoploss partially executed",
expectedSummary: "Your workflow 'Test Stoploss' executed 5 out of 8 total steps",
},
{
name: "simulation failed to execute",
workflowName: "Test Stoploss",
executedSteps: 3,
totalSteps: 8,
hasFailures: true,
hasSkippedNodes: false,
isSimulation: true,
expectedSubject: "Simulation: Test Stoploss failed to execute",
expectedSummary: "Your workflow 'Test Stoploss' executed 3 out of 8 total steps",
},
{
name: "deployed workflow succeeded",
workflowName: "Test Stoploss",
executedSteps: 7,
totalSteps: 7,
hasFailures: false,
hasSkippedNodes: false,
isSimulation: false,
expectedSubject: "Test Stoploss: succeeded (7 out of 7 steps)",
expectedSummary: "Your workflow 'Test Stoploss' executed 7 out of 7 total steps",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
vm := NewVM()
vm.IsSimulation = tt.isSimulation
// Set up workflow name
vm.mu.Lock()
vm.vars = map[string]interface{}{
"settings": map[string]interface{}{
"name": tt.workflowName,
"chain": "Sepolia",
},
}
// Set up task nodes (for total steps calculation)
vm.TaskNodes = make(map[string]*avsproto.TaskNode)
for i := 0; i < tt.totalSteps-1; i++ { // -1 because trigger is counted separately
nodeID := fmt.Sprintf("node%d", i)
vm.TaskNodes[nodeID] = &avsproto.TaskNode{
Id: nodeID,
Name: fmt.Sprintf("step%d", i),
}
}
// Set up execution logs
vm.ExecutionLogs = make([]*avsproto.Execution_Step, 0, tt.executedSteps)
// Add trigger (always first)
vm.ExecutionLogs = append(vm.ExecutionLogs, &avsproto.Execution_Step{
Id: "trigger",
Name: "eventTrigger",
Type: "TRIGGER_TYPE_EVENT",
Success: true,
})
// Add executed steps
for i := 0; i < tt.executedSteps-1; i++ { // -1 because trigger is already added
stepName := fmt.Sprintf("step%d", i)
success := true
if tt.hasFailures && i == tt.executedSteps-2 { // Last step fails
success = false
}
vm.ExecutionLogs = append(vm.ExecutionLogs, &avsproto.Execution_Step{
Id: fmt.Sprintf("step%d", i),
Name: stepName,
Type: "NODE_TYPE_BALANCE",
Success: success,
Error: func() string {
if !success {
return "test error"
}
return ""
}(),
})
}
// Mark some nodes as skipped if needed (by not including them in execution logs)
// The skipped count is calculated by comparing TaskNodes to ExecutionLogs
vm.mu.Unlock()
summary := ComposeSummary(vm, "email1")
// Verify subject format
if summary.Subject != tt.expectedSubject {
t.Errorf("Subject mismatch:\n expected: %q\n got: %q", tt.expectedSubject, summary.Subject)
}
// Verify summary line format
if summary.SummaryLine != tt.expectedSummary {
t.Errorf("SummaryLine mismatch:\n expected: %q\n got: %q", tt.expectedSummary, summary.SummaryLine)
}
// Verify body format - with the new structured format, Body starts with "Trigger: ..."
// The "Your workflow..." summary is now in SummaryLine field
if !strings.HasPrefix(summary.Body, "Trigger: ") {
t.Errorf("Body format mismatch:\n expected to start with: %q\n got: %q", "Trigger: ", summary.Body)
}
})
}
}
// TestComposeSummary_SimulationBodyFormat tests that simulation workflows
// generate the correct subject and summary line format matching context-memory API expectations
func TestComposeSummary_SimulationBodyFormat(t *testing.T) {
vm := NewVM()
vm.IsSimulation = true
vm.mu.Lock()
vm.vars = map[string]interface{}{
"settings": map[string]interface{}{
"name": "Test Stoploss",
"chain": "Sepolia",
},
}
vm.TaskNodes = map[string]*avsproto.TaskNode{
"node1": {Id: "node1", Name: "step1"},
"node2": {Id: "node2", Name: "step2"},
}
vm.mu.Unlock()
// Create execution logs
vm.ExecutionLogs = []*avsproto.Execution_Step{
{
Id: "trigger",
Name: "eventTrigger",
Type: "TRIGGER_TYPE_EVENT",
Success: true,
},
{
Id: "step1",
Name: "step1",
Type: "NODE_TYPE_BALANCE",
Success: true,
},
{
Id: "step2",
Name: "step2",
Type: "NODE_TYPE_BALANCE",
Success: true,
},
}
summary := ComposeSummary(vm, "email1")
// Verify subject format matches context-memory API expectations
expectedSubject := "Simulation: Test Stoploss successfully completed"
if summary.Subject != expectedSubject {
t.Errorf("Subject mismatch:\n expected: %q\n got: %q", expectedSubject, summary.Subject)
}
// Verify summary line format matches context-memory API expectations
expectedSummary := "Your workflow 'Test Stoploss' executed 3 out of 3 total steps"
if summary.SummaryLine != expectedSummary {
t.Errorf("SummaryLine mismatch:\n expected: %q\n got: %q", expectedSummary, summary.SummaryLine)
}
// Verify body format - with the new structured format, Body starts with "Trigger: ..."
// The "Your workflow..." summary is now in SummaryLine field
if !strings.HasPrefix(summary.Body, "Trigger: ") {
t.Errorf("Body format mismatch:\n expected to start with: %q\n got: %q", "Trigger: ", summary.Body)
}
// Verify SummaryLine contains the expected format
expectedSummaryLine := "Your workflow 'Test Stoploss' executed 3 out of 3 total steps"
if summary.SummaryLine != expectedSummaryLine {
t.Errorf("SummaryLine mismatch:\n expected: %q\n got: %q", expectedSummaryLine, summary.SummaryLine)
}
t.Logf("Subject: %s", summary.Subject)
t.Logf("SummaryLine: %s", summary.SummaryLine)
t.Logf("Body: %s", summary.Body)
}
// TestFormatTelegramFromStructured_PRDFormat tests the PRD-based Telegram format
// that uses body.network and body.executions array with emoji prepended by aggregator
func TestFormatTelegramFromStructured_PRDFormat(t *testing.T) {
tests := []struct {
name string
summary Summary
expectedContain []string
notContain []string
}{
{
name: "simulation with transfer - PRD format",
summary: Summary{
Subject: "Simulation: Recurring Payment successfully completed", // No emoji from API
Status: "success",
Network: "Sepolia",
Trigger: "(Simulated) Your scheduled task (every 3 days at 11:00 PM) triggered on Sepolia.",
TriggeredAt: "2026-01-22T04:51:18.509Z",
Executions: []ExecutionEntry{
{Description: "(Simulated) Transferred 0.01 ETH to 0xc60e...C788"},
},
},
expectedContain: []string{
"✅ <code>Simulation: Recurring Payment</code> successfully completed", // Prefix + name code-wrapped
"<b>Network:</b> Sepolia",
"<b>Time:</b> Jan 22, 2026 at 4:51 AM UTC",
"<b>Trigger:</b> (Simulated) Your scheduled task (every 3 days at 11:00 PM) triggered on Sepolia.",
"<b>Executed:</b>",
"• (Simulated) Transferred 0.01 ETH to 0xc60e...C788",
},
notContain: []string{},
},
{
name: "deployed run with transfer - PRD format",
summary: Summary{
Subject: "Run #3: Recurring Payment successfully completed", // No emoji from API
Status: "success",
Network: "Sepolia",
TriggeredAt: "2026-01-22T04:51:18.509Z",
Executions: []ExecutionEntry{
{Description: "Transferred 0.01 ETH to 0xc60e...C788"},
},
},
expectedContain: []string{
"✅ <code>Run #3: Recurring Payment</code> successfully completed", // Prefix + name code-wrapped
"<b>Network:</b> Sepolia",
"<b>Time:</b> Jan 22, 2026 at 4:51 AM UTC",
"<b>Executed:</b>",
"• Transferred 0.01 ETH to 0xc60e...C788",
},
notContain: []string{
"No on-chain transaction was executed", // No simulation notice for real runs
},
},
{
name: "failed run - PRD format",
summary: Summary{
Subject: "Run #5: Recurring Payment failed to execute", // No emoji from API
Status: "failed",
Network: "Sepolia",
TriggeredAt: "2026-01-22T04:51:18.509Z",
Errors: []string{"transfer1: Insufficient balance for transfer"},
},
expectedContain: []string{
"❌ <code>Run #5: Recurring Payment</code> failed to execute", // Prefix + name code-wrapped
"<b>Network:</b> Sepolia",
"<b>What Went Wrong:</b>",
"• transfer1: Insufficient balance for transfer",
},
notContain: []string{
"<b>Executed:</b>",
},
},
{
name: "success with skipped nodes renders warn emoji and skippedNote",
summary: Summary{
Subject: "Run #2: My Workflow successfully completed",
Status: "success",
SkippedSteps: 1,
SkippedNote: "1 node was skipped by Branch condition.",
Network: "Ethereum",
TriggeredAt: "2026-01-22T04:51:18.509Z",
Executions: []ExecutionEntry{
{Description: "Approved 100 USDC to router"},
},
},
expectedContain: []string{
"⚠️ <code>Run #2: My Workflow</code> successfully completed",
"<i>1 node was skipped by Branch condition.</i>",
"<b>Network:</b> Ethereum",
"<b>Executed:</b>",
"• Approved 100 USDC to router",
},
notContain: []string{},
},
{
name: "success with branch-skipped errors and backtick expression",
summary: Summary{
Subject: "Simulation: Copy of Test Recurring Batch Send successfully completed",
Status: "success",
SkippedSteps: 1,
SkippedNote: "1 node was skipped by Branch condition.",
Network: "Sepolia",
TriggeredAt: "2026-01-22T04:51:18.509Z",
Trigger: "(Simulated) Your scheduled task (every 3 minutes) triggered on Sepolia.",
Errors: []string{"loop1 - skipped due to condition not met: `code1.data.balance >= code1.data.totalNeeded` evaluated to false"},
},
expectedContain: []string{
"⚠️ <code>Simulation: Copy of Test Recurring Batch Send</code> successfully completed",
"<i>1 node was skipped by Branch condition.</i>",
"<b>Network:</b> Sepolia",
"<b>What Went Wrong:</b>",
"• loop1 - skipped due to condition not met: <code>code1.data.balance >= code1.data.totalNeeded</code> evaluated to false",
},
notContain: []string{
"<b>Executed:</b>",
"`", // backticks should be converted to <code> tags
},
},
{
name: "network fallback from workflow.chain",
summary: Summary{
Subject: "Simulation: Test successfully completed",
Status: "success",
Network: "", // Empty network from API
Workflow: &WorkflowInfo{
Chain: "Base",
ChainID: 8453,
},
Executions: []ExecutionEntry{{Description: "(Simulated) Test executed"}},
},
expectedContain: []string{
"<b>Network:</b> Base", // Falls back to workflow.chain
},
},
{
name: "network fallback from chainID",
summary: Summary{
Subject: "Simulation: Test successfully completed",
Status: "success",
Network: "", // Empty network from API
Workflow: &WorkflowInfo{
Chain: "", // Empty chain name
ChainID: 11155111,
},
Executions: []ExecutionEntry{{Description: "(Simulated) Test executed"}},
},
expectedContain: []string{
"<b>Network:</b> Sepolia", // Derived from chainID
},
},
{
name: "execution descriptions with backtick method names",
summary: Summary{
Subject: "Run #1: DeFi Bot successfully completed",
Status: "success",
Network: "Ethereum",
Executions: []ExecutionEntry{
{Description: "Called `approve` on 0xC364...42a0"},
{Description: "`getUserAccountData` returned healthFactor: 1.85"},
},
},
expectedContain: []string{
"<b>Executed:</b>",
"• Called <code>approve</code> on 0xC364...42a0",
"• <code>getUserAccountData</code> returned healthFactor: 1.85",
},
notContain: []string{
"`approve`", // backticks should be converted
"`getUserAccountData`",
},
},
{
name: "no on-chain executions - fallback populated by ComposeSummary",
summary: Summary{
Subject: "Simulation: My Workflow successfully completed",
Status: "success",
Network: "Sepolia",
TriggeredAt: "2026-01-28T07:31:51Z",
Trigger: "(Simulated) Scheduled task ran on Sepolia",
// ComposeSummary populates fallback execution entry when buildExecutionsArray returns empty
Executions: []ExecutionEntry{{Description: "(Simulated) On-chain transaction successfully completed"}},
},
expectedContain: []string{
"✅ <code>Simulation: My Workflow</code> successfully completed",
"<b>Network:</b> Sepolia",
"<b>Trigger:</b> (Simulated) Scheduled task ran on Sepolia",
"<b>Executed:</b>",
"• (Simulated) On-chain transaction successfully completed",
},
notContain: []string{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := FormatForMessageChannels(tt.summary, "telegram", nil)
// Check expected strings are present
for _, expected := range tt.expectedContain {
if !strings.Contains(result, expected) {
t.Errorf("expected result to contain %q\nGot:\n%s", expected, result)
}
}
// Check unwanted strings are not present
for _, notExpected := range tt.notContain {
if strings.Contains(result, notExpected) {
t.Errorf("result should NOT contain %q\nGot:\n%s", notExpected, result)
}
}
})
}
}
// TestFormatTelegramFromStructured_Annotation tests that annotation renders in italic for Telegram
func TestFormatTelegramFromStructured_Annotation(t *testing.T) {
summary := Summary{
Subject: "Run Node: My Workflow succeeded",
Status: "success",
Network: "Sepolia",
Executions: []ExecutionEntry{{Description: "Transferred 0.01 ETH"}},
Annotation: "This is an example. Actual execution details will appear when the workflow is simulated or triggered by a real event.",
}
result := FormatForMessageChannels(summary, "telegram", nil)
// Should contain annotation in italic
if !strings.Contains(result, "<i>This is an example.") {
t.Errorf("expected Telegram output to contain italic annotation, got:\n%s", result)
}
if !strings.Contains(result, "</i>") {
t.Errorf("expected Telegram output to close italic tag, got:\n%s", result)
}
// Without annotation, no italic tag
summaryNoAnnotation := Summary{
Subject: "Simulation: My Workflow successfully completed",