forked from vercel/chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.test.ts
More file actions
3110 lines (2606 loc) · 93.6 KB
/
thread.test.ts
File metadata and controls
3110 lines (2606 loc) · 93.6 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
import { beforeEach, describe, expect, it, vi } from "vitest";
import { Card } from "./cards";
import type { Message } from "./message";
import {
createMockAdapter,
createMockState,
createTestMessage,
mockLogger,
} from "./mock-adapter";
import { Plan } from "./plan";
import { StreamingPlan } from "./streaming-plan";
import { ThreadImpl } from "./thread";
import type { Adapter, ScheduledMessage, StreamChunk } from "./types";
import { NotImplementedError } from "./types";
describe("ThreadImpl", () => {
describe("Per-thread state", () => {
let thread: ThreadImpl<{ aiMode?: boolean; counter?: number }>;
let mockAdapter: Adapter;
let mockState: ReturnType<typeof createMockState>;
beforeEach(() => {
mockAdapter = createMockAdapter();
mockState = createMockState();
thread = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
});
});
it("should return null when no state has been set", async () => {
const state = await thread.state;
expect(state).toBeNull();
});
it("should return stored state", async () => {
// Pre-populate state in cache
mockState.cache.set("thread-state:slack:C123:1234.5678", {
aiMode: true,
});
const state = await thread.state;
expect(state).toEqual({ aiMode: true });
});
it("should set state and retrieve it", async () => {
await thread.setState({ aiMode: true });
const state = await thread.state;
expect(state).toEqual({ aiMode: true });
});
it("should merge state by default", async () => {
// Set initial state
await thread.setState({ aiMode: true });
// Set additional state - should merge
await thread.setState({ counter: 5 });
const state = await thread.state;
expect(state).toEqual({ aiMode: true, counter: 5 });
});
it("should overwrite existing keys when merging", async () => {
await thread.setState({ aiMode: true, counter: 1 });
await thread.setState({ counter: 10 });
const state = await thread.state;
expect(state).toEqual({ aiMode: true, counter: 10 });
});
it("should replace entire state when replace option is true", async () => {
await thread.setState({ aiMode: true, counter: 5 });
await thread.setState({ counter: 10 }, { replace: true });
const state = await thread.state;
expect(state).toEqual({ counter: 10 });
expect((state as { aiMode?: boolean }).aiMode).toBeUndefined();
});
it("should use correct key prefix for state storage", async () => {
await thread.setState({ aiMode: true });
expect(mockState.set).toHaveBeenCalledWith(
"thread-state:slack:C123:1234.5678",
{ aiMode: true },
expect.any(Number) // TTL
);
});
it("should call get with correct key", async () => {
await thread.state;
expect(mockState.get).toHaveBeenCalledWith(
"thread-state:slack:C123:1234.5678"
);
});
});
describe("post with different message formats", () => {
let thread: ThreadImpl;
let mockAdapter: Adapter;
let mockState: ReturnType<typeof createMockState>;
beforeEach(() => {
mockAdapter = createMockAdapter();
mockState = createMockState();
thread = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
});
});
it("should post a string message", async () => {
const result = await thread.post("Hello world");
expect(mockAdapter.postMessage).toHaveBeenCalledWith(
"slack:C123:1234.5678",
"Hello world"
);
expect(result.text).toBe("Hello world");
expect(result.id).toBe("msg-1");
});
it("should post a raw message", async () => {
const result = await thread.post({ raw: "raw text" });
expect(mockAdapter.postMessage).toHaveBeenCalledWith(
"slack:C123:1234.5678",
{ raw: "raw text" }
);
expect(result.text).toBe("raw text");
});
it("should post a markdown message", async () => {
const result = await thread.post({ markdown: "**bold** text" });
expect(result.text).toBe("bold text");
});
it("should set correct author on sent message", async () => {
const result = await thread.post("Hello");
expect(result.author.isBot).toBe(true);
expect(result.author.isMe).toBe(true);
expect(result.author.userId).toBe("self");
expect(result.author.userName).toBe("slack-bot");
});
it("should use threadId override from postMessage response", async () => {
(mockAdapter.postMessage as ReturnType<typeof vi.fn>).mockResolvedValue({
id: "msg-2",
threadId: "slack:C123:new-thread-id",
raw: {},
});
const result = await thread.post("Hello");
expect(result.threadId).toBe("slack:C123:new-thread-id");
});
});
describe("Streaming", () => {
let thread: ThreadImpl;
let mockAdapter: Adapter;
let mockState: ReturnType<typeof createMockState>;
beforeEach(() => {
mockAdapter = createMockAdapter();
mockState = createMockState();
thread = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
});
});
// Helper to create an async iterable from an array of chunks
async function* createTextStream(
chunks: string[],
delayMs = 0
): AsyncIterable<string> {
for (const chunk of chunks) {
if (delayMs > 0) {
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
yield chunk;
}
}
it("should use adapter native streaming when available", async () => {
const mockStream = vi.fn().mockResolvedValue({
id: "msg-stream",
threadId: "t1",
raw: "Hello World",
});
mockAdapter.stream = mockStream;
const textStream = createTextStream(["Hello", " ", "World"]);
await thread.post(textStream);
expect(mockStream).toHaveBeenCalledWith(
"slack:C123:1234.5678",
expect.any(Object), // The async iterable
expect.any(Object) // Stream options
);
// Should NOT call postMessage for fallback
expect(mockAdapter.postMessage).not.toHaveBeenCalled();
});
it("should fall back to post+edit when adapter has no native streaming", async () => {
// Ensure no stream method
mockAdapter.stream = undefined;
const textStream = createTextStream(["Hello", " ", "World"]);
await thread.post(textStream);
// Should post initial placeholder
expect(mockAdapter.postMessage).toHaveBeenCalledWith(
"slack:C123:1234.5678",
"..."
);
// Should edit with final content wrapped as markdown
expect(mockAdapter.editMessage).toHaveBeenLastCalledWith(
"slack:C123:1234.5678",
"msg-1",
{ markdown: "Hello World" }
);
});
it("should accumulate text chunks during streaming", async () => {
mockAdapter.stream = undefined;
const textStream = createTextStream([
"This ",
"is ",
"a ",
"test ",
"message.",
]);
const result = await thread.post(textStream);
// Final edit should have all accumulated text wrapped as markdown
expect(mockAdapter.editMessage).toHaveBeenLastCalledWith(
"slack:C123:1234.5678",
"msg-1",
{ markdown: "This is a test message." }
);
expect(result.text).toBe("This is a test message.");
});
it("should throttle edits to avoid rate limits", async () => {
vi.useFakeTimers();
mockAdapter.stream = undefined;
// Create a stream that yields chunks over time
const chunks = ["A", "B", "C", "D", "E"];
let chunkIndex = 0;
const textStream: AsyncIterable<string> = {
[Symbol.asyncIterator]() {
return {
async next() {
if (chunkIndex < chunks.length) {
const value = chunks[chunkIndex++];
return { value, done: false };
}
return { value: undefined, done: true };
},
};
},
};
const postPromise = thread.post(textStream);
// Initially should just post
await vi.advanceTimersByTimeAsync(0);
expect(mockAdapter.postMessage).toHaveBeenCalledTimes(1);
// Advance time and let stream complete
await vi.advanceTimersByTimeAsync(2000);
await postPromise;
// Should have final edit wrapped as markdown
expect(mockAdapter.editMessage).toHaveBeenLastCalledWith(
"slack:C123:1234.5678",
"msg-1",
{ markdown: "ABCDE" }
);
vi.useRealTimers();
});
it("should return SentMessage with edit and delete capabilities", async () => {
mockAdapter.stream = undefined;
const textStream = createTextStream(["Hello"]);
const result = await thread.post(textStream);
expect(result.id).toBe("msg-1");
expect(typeof result.edit).toBe("function");
expect(typeof result.delete).toBe("function");
expect(typeof result.addReaction).toBe("function");
expect(typeof result.removeReaction).toBe("function");
});
it("should handle empty stream", async () => {
mockAdapter.stream = undefined;
const textStream = createTextStream([]);
await thread.post(textStream);
// Should post initial placeholder
expect(mockAdapter.postMessage).toHaveBeenCalledWith(
"slack:C123:1234.5678",
"..."
);
// Should not edit with empty content
expect(mockAdapter.editMessage).not.toHaveBeenCalled();
});
it("should support disabling the placeholder for fallback streaming", async () => {
mockAdapter.stream = undefined;
const threadNoPlaceholder = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
fallbackStreamingPlaceholderText: null,
});
const textStream = createTextStream(["H", "i"]);
await threadNoPlaceholder.post(textStream);
expect(mockAdapter.postMessage).not.toHaveBeenCalledWith(
"slack:C123:1234.5678",
"..."
);
expect(mockAdapter.editMessage).toHaveBeenLastCalledWith(
"slack:C123:1234.5678",
"msg-1",
{ markdown: "Hi" }
);
});
it("should handle empty stream with disabled placeholder", async () => {
mockAdapter.stream = undefined;
const threadNoPlaceholder = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
fallbackStreamingPlaceholderText: null,
});
const textStream = createTextStream([]);
await threadNoPlaceholder.post(textStream);
// Should post a non-empty fallback since stream must return a SentMessage
expect(mockAdapter.postMessage).toHaveBeenCalledWith(
"slack:C123:1234.5678",
{ markdown: " " }
);
expect(mockAdapter.editMessage).not.toHaveBeenCalled();
});
it("should not post empty content when table is buffered with null placeholder", async () => {
mockAdapter.stream = undefined;
const threadNoPlaceholder = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
fallbackStreamingPlaceholderText: null,
});
const textStream = createTextStream([
"| A | B |\n",
"|---|---|\n",
"| 1 | 2 |\n",
]);
await threadNoPlaceholder.post(textStream);
const postCalls = (mockAdapter.postMessage as ReturnType<typeof vi.fn>)
.mock.calls;
for (const call of postCalls) {
const content = call[1];
if (typeof content === "object" && "markdown" in content) {
expect(content.markdown.trim().length).toBeGreaterThan(0);
}
}
});
it("should not edit placeholder to empty during LLM warm-up", async () => {
mockAdapter.stream = undefined;
const editFn = mockAdapter.editMessage as ReturnType<typeof vi.fn>;
const textStream = createTextStream(["Hello world"]);
await thread.post(textStream);
for (const call of editFn.mock.calls) {
const content = call[2];
if (typeof content === "object" && "markdown" in content) {
expect(content.markdown.trim().length).toBeGreaterThan(0);
}
}
});
it("should not post empty content during streaming with whitespace chunks", async () => {
mockAdapter.stream = undefined;
const threadNoPlaceholder = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
fallbackStreamingPlaceholderText: null,
});
const textStream = createTextStream([" ", "\n", " \n"]);
await threadNoPlaceholder.post(textStream);
const postCalls = (mockAdapter.postMessage as ReturnType<typeof vi.fn>)
.mock.calls;
for (const call of postCalls) {
const content = call[1];
if (typeof content === "object" && "markdown" in content) {
expect(content.markdown.length).toBeGreaterThan(0);
}
}
});
it("should preserve newlines in streamed text (native path)", async () => {
let capturedChunks: string[] = [];
const mockStream = vi
.fn()
.mockImplementation(
async (_threadId: string, textStream: AsyncIterable<string>) => {
capturedChunks = [];
for await (const chunk of textStream) {
capturedChunks.push(chunk);
}
return {
id: "msg-stream",
threadId: "t1",
raw: {},
};
}
);
mockAdapter.stream = mockStream;
// Simulate an LLM streaming two paragraphs with a single newline between them
const textStream = createTextStream([
"hello",
".",
"\n",
"how",
" are",
" you?",
]);
const result = await thread.post(textStream);
// The accumulated text should preserve the newline
expect(result.text).toBe("hello.\nhow are you?");
// All chunks should have been passed through to the adapter
expect(capturedChunks).toEqual([
"hello",
".",
"\n",
"how",
" are",
" you?",
]);
});
it("should preserve double newlines (paragraph breaks) in streamed text", async () => {
let capturedChunks: string[] = [];
const mockStream = vi
.fn()
.mockImplementation(
async (_threadId: string, textStream: AsyncIterable<string>) => {
capturedChunks = [];
for await (const chunk of textStream) {
capturedChunks.push(chunk);
}
return {
id: "msg-stream",
threadId: "t1",
raw: {},
};
}
);
mockAdapter.stream = mockStream;
// Simulate an LLM streaming two paragraphs with double newline
const textStream = createTextStream(["hello.", "\n\n", "how are you?"]);
const result = await thread.post(textStream);
// Plain text extraction from parsed markdown joins paragraphs without separator
// (mdast-util-to-string behavior). The formatted AST preserves paragraph structure.
expect(result.text).toBe("hello.how are you?");
expect(capturedChunks).toEqual(["hello.", "\n\n", "how are you?"]);
});
it("should concatenate multi-step text without separator (demonstrates bug)", async () => {
let capturedChunks: string[] = [];
const mockStream = vi
.fn()
.mockImplementation(
async (_threadId: string, textStream: AsyncIterable<string>) => {
capturedChunks = [];
for await (const chunk of textStream) {
capturedChunks.push(chunk);
}
return {
id: "msg-stream",
threadId: "t1",
raw: {},
};
}
);
mockAdapter.stream = mockStream;
// Simulate a multi-step AI agent where step 1 produces "hello."
// and step 2 produces "how are you?" with NO separator between steps.
// This is what happens with AI SDK's textStream across tool-call steps.
const textStream = createTextStream([
"hello",
".",
"how",
" are",
" you?",
]);
const result = await thread.post(textStream);
// BUG: text from separate steps is concatenated without any whitespace
expect(result.text).toBe("hello.how are you?");
});
it("should preserve newlines in fallback streaming path", async () => {
mockAdapter.stream = undefined;
const textStream = createTextStream(["hello.", "\n", "how are you?"]);
const result = await thread.post(textStream);
// Final edit should have all accumulated text with newline preserved, wrapped as markdown
expect(mockAdapter.editMessage).toHaveBeenLastCalledWith(
"slack:C123:1234.5678",
"msg-1",
{ markdown: "hello.\nhow are you?" }
);
expect(result.text).toBe("hello.\nhow are you?");
});
it("should close incomplete markdown in intermediate fallback edits", async () => {
mockAdapter.stream = undefined;
// Simulate streaming where intermediate state has unclosed bold marker
const textStream = createTextStream(["Hello **wor", "ld** done"], 50);
// Use short interval so intermediate edit fires between chunks
const threadWithInterval = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
streamingUpdateIntervalMs: 10,
});
const result = await threadWithInterval.post(textStream);
// Final result text is plain text (markdown formatting stripped)
expect(result.text).toBe("Hello world done");
// Check that intermediate edits used remend to close the bold marker
const editCalls = vi.mocked(mockAdapter.editMessage).mock.calls;
for (const [, , content] of editCalls) {
// Content should be wrapped as { markdown: string }
const markdownContent =
typeof content === "string"
? content
: (content as { markdown: string }).markdown;
// Every intermediate edit should have balanced markdown (no dangling **)
const openCount = (markdownContent.match(/\*\*/g) || []).length;
expect(openCount % 2).toBe(0);
}
});
it.each([
{
expectedTeamId: "T123",
label: "team_id",
raw: { team_id: "T123", type: "app_mention" },
},
{
expectedTeamId: "T234",
label: "team string",
raw: { team: "T234", type: "message" },
},
{
expectedTeamId: "T345",
label: "team.id",
raw: { team: { id: "T345" }, type: "block_actions" },
},
{
expectedTeamId: "T456",
label: "user.team_id fallback",
raw: {
type: "block_actions",
user: { team_id: "T456" },
},
},
])("should pass stream options from Slack current message context via $label", async ({
raw,
expectedTeamId,
}) => {
const mockStream = vi.fn().mockResolvedValue({
id: "msg-stream",
threadId: "t1",
raw: "Hello",
});
mockAdapter.stream = mockStream;
const threadWithContext = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
currentMessage: createTestMessage("original-msg", "test", {
raw,
author: {
userId: "U456",
userName: "user",
fullName: "Test User",
isBot: false,
isMe: false,
},
}),
});
const textStream = createTextStream(["Hello"]);
await threadWithContext.post(textStream);
expect(mockStream).toHaveBeenCalledWith(
"slack:C123:1234.5678",
expect.any(Object),
expect.objectContaining({
recipientUserId: "U456",
recipientTeamId: expectedTeamId,
})
);
});
it("should forward structured stream chunks to adapter.stream from an action-created thread", async () => {
const mockStream = vi.fn().mockResolvedValue({
id: "msg-stream",
threadId: "t1",
raw: "Hello",
});
mockAdapter.stream = mockStream;
const threadWithActionContext = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
currentMessage: createTestMessage("action-msg", "", {
raw: {
team: { domain: "workspace", id: "T123" },
type: "block_actions",
},
author: {
userId: "U456",
userName: "user",
fullName: "Test User",
isBot: false,
isMe: false,
},
}),
});
const taskChunk: StreamChunk = {
id: "task-1",
status: "pending",
title: "Thinking",
type: "task_update",
};
async function* structuredStream(): AsyncIterable<string | StreamChunk> {
yield "Picking option...";
yield taskChunk;
}
await threadWithActionContext.post(
structuredStream() as unknown as AsyncIterable<string>
);
expect(mockStream).toHaveBeenCalledTimes(1);
const [, passedStream] = mockStream.mock.calls[0];
const collected: Array<string | StreamChunk> = [];
for await (const chunk of passedStream as AsyncIterable<
string | StreamChunk
>) {
collected.push(chunk);
}
expect(collected).toContain("Picking option...");
expect(collected).toContainEqual(taskChunk);
});
it("should pass StreamingPlan PostableObject options to adapter.stream", async () => {
const mockStream = vi.fn().mockResolvedValue({
id: "msg-stream",
threadId: "t1",
raw: "Hello",
});
mockAdapter.stream = mockStream;
const textStream = createTextStream(["Hello"]);
const streamMsg = new StreamingPlan(textStream, {
groupTasks: "plan",
endWith: [{ type: "actions" }],
updateIntervalMs: 1000,
});
await thread.post(streamMsg);
expect(mockStream).toHaveBeenCalledWith(
"slack:C123:1234.5678",
expect.any(Object),
expect.objectContaining({
taskDisplayMode: "plan",
stopBlocks: [{ type: "actions" }],
updateIntervalMs: 1000,
})
);
});
it("should pass StreamingPlan with only groupTasks", async () => {
const mockStream = vi.fn().mockResolvedValue({
id: "msg-stream",
threadId: "t1",
raw: "Hello",
});
mockAdapter.stream = mockStream;
const textStream = createTextStream(["Hello"]);
await thread.post(
new StreamingPlan(textStream, { groupTasks: "timeline" })
);
expect(mockStream).toHaveBeenCalledWith(
"slack:C123:1234.5678",
expect.any(Object),
expect.objectContaining({
taskDisplayMode: "timeline",
})
);
const options = mockStream.mock.calls[0][2];
expect(options.stopBlocks).toBeUndefined();
});
it("should pass StreamingPlan with only endWith", async () => {
const mockStream = vi.fn().mockResolvedValue({
id: "msg-stream",
threadId: "t1",
raw: "Hello",
});
mockAdapter.stream = mockStream;
const textStream = createTextStream(["Hello"]);
await thread.post(
new StreamingPlan(textStream, { endWith: [{ type: "actions" }] })
);
expect(mockStream).toHaveBeenCalledWith(
"slack:C123:1234.5678",
expect.any(Object),
expect.objectContaining({
stopBlocks: [{ type: "actions" }],
})
);
const options = mockStream.mock.calls[0][2];
expect(options.taskDisplayMode).toBeUndefined();
});
it("should pass StreamingPlan with only updateIntervalMs", async () => {
const mockStream = vi.fn().mockResolvedValue({
id: "msg-stream",
threadId: "t1",
raw: "Hello",
});
mockAdapter.stream = mockStream;
const textStream = createTextStream(["Hello"]);
await thread.post(
new StreamingPlan(textStream, { updateIntervalMs: 2000 })
);
expect(mockStream).toHaveBeenCalledWith(
"slack:C123:1234.5678",
expect.any(Object),
expect.objectContaining({
updateIntervalMs: 2000,
})
);
const options = mockStream.mock.calls[0][2];
expect(options.taskDisplayMode).toBeUndefined();
expect(options.stopBlocks).toBeUndefined();
});
it("should route StreamingPlan through fallback when adapter has no native streaming", async () => {
mockAdapter.stream = undefined;
const textStream = createTextStream(["Hello", " ", "World"]);
await thread.post(
new StreamingPlan(textStream, {
groupTasks: "plan",
endWith: [{ type: "actions" }],
updateIntervalMs: 2000,
})
);
// Should post initial placeholder and edit with final content
expect(mockAdapter.postMessage).toHaveBeenCalledWith(
"slack:C123:1234.5678",
"..."
);
expect(mockAdapter.editMessage).toHaveBeenLastCalledWith(
"slack:C123:1234.5678",
"msg-1",
{ markdown: "Hello World" }
);
});
it("should still work without options (backward compat)", async () => {
const mockStream = vi.fn().mockResolvedValue({
id: "msg-stream",
threadId: "t1",
raw: "Hello",
});
mockAdapter.stream = mockStream;
const textStream = createTextStream(["Hello"]);
await thread.post(textStream);
expect(mockStream).toHaveBeenCalledWith(
"slack:C123:1234.5678",
expect.any(Object),
expect.any(Object)
);
const options = mockStream.mock.calls[0][2];
expect(options.taskDisplayMode).toBeUndefined();
expect(options.stopBlocks).toBeUndefined();
});
});
describe("fallback streaming error logging", () => {
it("should log when an intermediate edit fails", async () => {
const adapter = createMockAdapter();
const editError = new Error("422 Validation Failed");
vi.mocked(adapter.editMessage).mockRejectedValueOnce(editError);
const thread = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter,
channelId: "C123",
stateAdapter: createMockState(),
streamingUpdateIntervalMs: 10,
logger: mockLogger,
});
async function* slowStream(): AsyncIterable<string> {
yield "Hel";
await new Promise((r) => setTimeout(r, 50));
yield "lo";
}
await thread.post(slowStream());
expect(mockLogger.warn).toHaveBeenCalledWith(
"fallbackStream edit failed",
editError
);
});
});
describe("streaming with StreamChunk objects", () => {
let thread: ThreadImpl;
let mockAdapter: Adapter;
let mockState: ReturnType<typeof createMockState>;
beforeEach(() => {
mockAdapter = createMockAdapter();
mockState = createMockState();
thread = new ThreadImpl({
id: "slack:C123:1234.5678",
adapter: mockAdapter,
channelId: "C123",
stateAdapter: mockState,
});
});
it("should pass StreamChunk objects through to adapter.stream", async () => {
let capturedChunks: (string | StreamChunk)[] = [];
const mockStream = vi
.fn()
.mockImplementation(
async (
_threadId: string,
stream: AsyncIterable<string | StreamChunk>
) => {
capturedChunks = [];
for await (const chunk of stream) {
capturedChunks.push(chunk);
}
return { id: "msg-stream", threadId: "t1", raw: {} };
}
);
mockAdapter.stream = mockStream;
async function* mixedStream() {
yield "Hello ";
yield {
type: "task_update" as const,
id: "tool-1",
title: "Running bash",
details: "Installing dependencies",
status: "in_progress",
};
yield "world";
yield {
type: "task_update" as const,
id: "tool-1",
title: "Running bash",
details: "Installed dependencies",
status: "complete",
output: "Done",
};
}
const result = await thread.post(mixedStream() as AsyncIterable<string>);
// Should have been called with the mixed stream
expect(mockStream).toHaveBeenCalled();
// All chunks (strings and objects) should pass through
expect(capturedChunks).toHaveLength(4);
expect(capturedChunks[0]).toBe("Hello ");
expect(capturedChunks[1]).toEqual(
expect.objectContaining({
type: "task_update",
details: "Installing dependencies",
status: "in_progress",
})
);
expect(capturedChunks[2]).toBe("world");
expect(capturedChunks[3]).toEqual(
expect.objectContaining({
type: "task_update",
details: "Installed dependencies",
output: "Done",
status: "complete",
})
);
// Accumulated text should only include strings, not task_update chunks
expect(result.text).toBe("Hello world");
});
it("should accumulate text from markdown_text StreamChunks", async () => {
let capturedChunks: (string | StreamChunk)[] = [];
const mockStream = vi
.fn()
.mockImplementation(
async (
_threadId: string,
stream: AsyncIterable<string | StreamChunk>
) => {
capturedChunks = [];
for await (const chunk of stream) {
capturedChunks.push(chunk);
}
return { id: "msg-stream", threadId: "t1", raw: {} };
}
);
mockAdapter.stream = mockStream;
async function* mdChunkStream() {
yield { type: "markdown_text" as const, text: "Hello " };
yield { type: "plan_update" as const, title: "Analyzing code" };
yield { type: "markdown_text" as const, text: "World" };