Repository navigation
Expand file tree
/
Copy pathmessageStore.test.ts
More file actions
1157 lines (957 loc) · 44 KB
/
Copy pathmessageStore.test.ts
File metadata and controls
1157 lines (957 loc) · 44 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 type { AssistantMessage, UserMessage } from '../api/types'
import { contentEntries } from '../types/api/message'
import { messageStore } from './messageStore'
import type { SessionMessageInfo } from './messageStoreTypes'
// ============================================
// 原生(v2)语义说明
//
// store 里存的是**原生** `SessionMessageInfo`,没有 `{ info, parts }`:
// - 消息判别走 `message.type`(user / assistant / synthetic / idle / ...)
// - 助手内容读 `message.content: Array<Text | Reasoning | Tool>`
// - 流式增量是独立事件,且**加载态靠 findLast 定位**(不是按 ordinal / 下标):
// text.delta → 最后一个 text 片段
// reasoning.delta → 最后一个 time.completed 缺省的 reasoning 片段
// tool.* → content 里 id 相同的最后一个 tool 片段
// - `session.step.started` 才是「创建助手消息」的事件
// ============================================
const SESSION = 'session-1'
/** 构造一条原生助手消息(自带 content) */
function createAssistantMessage(
id: string,
content: AssistantMessage['content'] = [],
completed?: number,
): AssistantMessage {
return {
id,
type: 'assistant',
agent: 'build',
model: { id: 'model-1', providerID: 'provider-1' },
content,
time: { created: 1, ...(completed != null ? { completed } : {}) },
}
}
function createUserMessage(id: string, created = 1): UserMessage {
return { id, type: 'user', time: { created }, text: id }
}
function textContent(text: string): AssistantMessage['content'] {
return [{ type: 'text', text }]
}
// ---- 读取助手 content 的小工具 ----
function assistantAt(sessionId: string, msgIndex = 0): AssistantMessage {
const message = messageStore.getSessionState(sessionId)?.messages[msgIndex]
if (message?.type !== 'assistant') throw new Error('expected an assistant message')
return message
}
function contentAt(sessionId: string, msgIndex = 0, contentIndex = 0): AssistantMessage['content'][number] | undefined {
return assistantAt(sessionId, msgIndex).content[contentIndex]
}
function textAt(sessionId: string, msgIndex = 0, contentIndex = 0): string | undefined {
const item = contentAt(sessionId, msgIndex, contentIndex)
return item && item.type === 'text' ? item.text : undefined
}
function toolAt(sessionId: string, contentIndex = 0) {
const item = contentAt(sessionId, 0, contentIndex)
if (item?.type !== 'tool') throw new Error('expected a tool item')
return item
}
function messageIds(sessionId: string): string[] {
return messageStore.getSessionState(sessionId)?.messages.map(message => message.id) ?? []
}
// ---- 事件负载小工具(sessionID 一律是作用域后的 id) ----
const stepStartedData = (assistantMessageID = 'message-1', started = 100) => ({
sessionID: SESSION,
assistantMessageID,
agent: 'build',
model: { id: 'model-1', providerID: 'provider-1' },
started,
})
const textStartedData = (ordinal = 0, assistantMessageID = 'message-1') => ({
sessionID: SESSION,
assistantMessageID,
ordinal,
})
const textDeltaData = (delta: string, ordinal = 0, assistantMessageID = 'message-1', sessionID = SESSION) => ({
sessionID,
assistantMessageID,
ordinal,
delta,
})
const reasoningStartedData = (ordinal = 0, assistantMessageID = 'message-1') => ({
sessionID: SESSION,
assistantMessageID,
ordinal,
})
const reasoningDeltaData = (delta: string, ordinal = 0, assistantMessageID = 'message-1') => ({
sessionID: SESSION,
assistantMessageID,
ordinal,
delta,
})
// 流式 delta 通过 requestAnimationFrame 节流,测试里收集回调后手动 flush
const rafQueue: Array<(time: number) => void> = []
function flushFrames(): void {
while (rafQueue.length > 0) {
rafQueue.shift()?.(0)
}
}
describe('messageStore(原生 v2 消息)', () => {
beforeEach(() => {
vi.restoreAllMocks()
rafQueue.length = 0
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => {
rafQueue.push(cb as (time: number) => void)
return rafQueue.length
})
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => undefined)
messageStore.clearAll()
})
it('setMessages 补种 durable 会话级 agent/model(SessionInfo 来源),但不覆盖 live SSE 的值', () => {
// 新鲜客户端:live 状态空缺 → 服务端快照补种
messageStore.setMessages(SESSION, [createUserMessage('msg-1')], {
agent: 'plan',
model: { id: 'gpt-4o', providerID: 'openai', variant: 'high' },
})
let state = messageStore.getSessionState(SESSION)
expect(state?.agent).toBe('plan')
expect(state?.model).toEqual({ id: 'gpt-4o', providerID: 'openai', variant: 'high' })
// live SSE 先落定过的会话:快照重拉不覆盖
messageStore.handleAgentSelected({ sessionID: SESSION, agent: 'build' })
messageStore.handleModelSelected({ sessionID: SESSION, model: { id: 'gpt-5', providerID: 'openai' } })
messageStore.setMessages(SESSION, [createUserMessage('msg-1')], {
agent: 'plan',
model: { id: 'gpt-4o', providerID: 'openai' },
})
state = messageStore.getSessionState(SESSION)
expect(state?.agent).toBe('build')
expect(state?.model).toEqual({ id: 'gpt-5', providerID: 'openai' })
})
it('updateSessionMetadata 同样只补空缺的 agent/model', () => {
messageStore.setMessages(SESSION, [createUserMessage('msg-1')])
messageStore.updateSessionMetadata(SESSION, { agent: 'plan', model: { id: 'gpt-4o', providerID: 'openai' } })
expect(messageStore.getSessionState(SESSION)?.agent).toBe('plan')
expect(messageStore.getSessionState(SESSION)?.model).toEqual({ id: 'gpt-4o', providerID: 'openai' })
messageStore.updateSessionMetadata(SESSION, { agent: 'build', model: { id: 'gpt-5', providerID: 'openai' } })
expect(messageStore.getSessionState(SESSION)?.agent).toBe('plan')
expect(messageStore.getSessionState(SESSION)?.model).toEqual({ id: 'gpt-4o', providerID: 'openai' })
})
it('handleSessionMoved 更新目录并插入 location-switched(带 previous)', () => {
messageStore.setMessages(SESSION, [createUserMessage('msg-1')], { directory: '/repo' })
messageStore.handleSessionMoved(
{
sessionID: SESSION,
location: { directory: '/repo/wt-feature' },
projectID: 'project-1',
subpath: 'wt-feature',
},
{ id: 'evt_moved', created: 123 },
)
const state = messageStore.getSessionState(SESSION)
expect(state?.directory).toBe('/repo/wt-feature')
expect(state?.messages.at(-1)).toMatchObject({
id: 'msg_moved',
type: 'location-switched',
location: { directory: '/repo/wt-feature' },
projectID: 'project-1',
subpath: 'wt-feature',
previous: { location: { directory: '/repo' } },
time: { created: 123 },
})
})
// ============================================
// 整条落库
// ============================================
it('handleMessageUpdated 按原生形状落库(无 info / parts)', () => {
messageStore.handleMessageUpdated(createAssistantMessage('message-1', textContent('hello')), SESSION)
const state = messageStore.getSessionState(SESSION)
expect(state?.messages).toHaveLength(1)
expect(state?.messages[0].type).toBe('assistant')
expect(state?.messages[0].id).toBe('message-1')
expect(textAt(SESSION)).toBe('hello')
})
it('handleMessageUpdated 落库原生用户消息(正文就是 text)', () => {
messageStore.handleMessageUpdated(createUserMessage('user-1'), SESSION)
const message = messageStore.getSessionState(SESSION)?.messages[0]
expect(message?.type).toBe('user')
expect(message && message.type === 'user' ? message.text : undefined).toBe('user-1')
expect(messageStore.extractUserText(message as SessionMessageInfo)).toBe('user-1')
})
it('handleMessageContent 用权威快照整体替换 content', () => {
messageStore.handleMessageUpdated(createAssistantMessage('message-1', textContent('streamed partial')), SESSION)
messageStore.handleMessageContent('message-1', SESSION, textContent('server final text'))
expect(textAt(SESSION)).toBe('server final text')
})
it('content 快照在助手消息不存在时也能落地(快照可能先到)', () => {
messageStore.handleMessageContent('message-snap', SESSION, textContent('from snapshot'))
expect(messageIds(SESSION)).toEqual(['message-snap'])
expect(textAt(SESSION)).toBe('from snapshot')
})
// ============================================
// step.started:创建 / 重置助手消息
// ============================================
it('step.started 创建助手消息:content 空、time.created 用 data.started、带上 agent/model', () => {
messageStore.handleStepStarted(stepStartedData('message-1', 90))
const message = assistantAt(SESSION)
expect(message.content).toEqual([])
expect(message.time.created).toBe(90)
expect(message.agent).toBe('build')
expect(message.model).toEqual({ id: 'model-1', providerID: 'provider-1' })
expect(message.time.completed).toBeUndefined()
})
it('step.started 对同 id 的助手消息就地重置元信息(不清空已流出的 content)', () => {
messageStore.handleStepStarted(stepStartedData('message-1', 90))
messageStore.handleTextStarted(textStartedData())
messageStore.handleTextDelta(textDeltaData('partial'))
messageStore.handleStepStarted({ ...stepStartedData('message-1', 95), agent: 'plan' })
const message = assistantAt(SESSION)
expect(message.time.created).toBe(95)
expect(message.agent).toBe('plan')
expect(message.time.completed).toBeUndefined()
// text.started 可能先到;重置元信息不能把已经流出来的内容丢掉
expect(message.content).toHaveLength(1)
})
it('新的一步会给上一条仍开着的助手消息补 time.completed = event.created', () => {
messageStore.handleStepStarted(stepStartedData('message-a', 100), { id: 'evt-1', created: 100 })
messageStore.handleStepStarted(stepStartedData('message-b', 200), { id: 'evt-2', created: 200 })
const messages = messageStore.getSessionState(SESSION)?.messages ?? []
expect(messages).toHaveLength(2)
expect(messages[0].type === 'assistant' ? messages[0].time.completed : undefined).toBe(200)
expect(messages[1].type === 'assistant' ? messages[1].time.completed : undefined).toBeUndefined()
})
it('step.ended / step.failed 定稿助手消息', () => {
messageStore.handleStepStarted(stepStartedData('message-1', 100))
messageStore.handleStepEnded(
{
sessionID: SESSION,
assistantMessageID: 'message-1',
finish: 'stop',
cost: 0.01,
tokens: { input: 1, output: 2, reasoning: 0, cache: { read: 0, write: 0 } },
},
{ id: 'evt-1', created: 150 },
)
const ended = assistantAt(SESSION)
expect(ended.time.completed).toBe(150)
expect(ended.finish).toBe('stop')
expect(ended.cost).toBe(0.01)
messageStore.handleStepStarted(stepStartedData('message-2', 200))
messageStore.handleStepFailed(
{
sessionID: SESSION,
assistantMessageID: 'message-2',
error: { type: 'provider_error', message: 'boom' },
},
{ id: 'evt-2', created: 250 },
)
const failed = assistantAt(SESSION, 1)
expect(failed.time.completed).toBe(250)
expect(failed.finish).toBe('error')
expect(failed.error).toEqual({ type: 'provider_error', message: 'boom' })
})
// ============================================
// 文本流
// ============================================
it('1) text.started 追加一个空文本片段;delta 追加到最后一个;ended 覆盖该片段', () => {
messageStore.handleStepStarted(stepStartedData())
messageStore.handleTextStarted(textStartedData())
expect(assistantAt(SESSION).content).toEqual([{ type: 'text', text: '' }])
messageStore.handleTextDelta(textDeltaData('hello'))
flushFrames()
messageStore.handleTextDelta(textDeltaData(' world'))
flushFrames()
expect(textAt(SESSION)).toBe('hello world')
messageStore.handleTextEnded({
sessionID: SESSION,
assistantMessageID: 'message-1',
ordinal: 0,
text: 'hello world (authoritative)',
})
expect(textAt(SESSION)).toBe('hello world (authoritative)')
})
it('2) 文本与推理交错时,delta 命中**最后一个**文本片段(不是第一个、也不是按下标)', () => {
messageStore.handleMessageUpdated(
createAssistantMessage('message-1', [
{ type: 'text', text: 'first' },
{ type: 'reasoning', text: 'thinking' },
{ type: 'text', text: 'second' },
]),
SESSION,
)
// ordinal 传 0 也不该写到第一段文本上:定位一律用 findLast
messageStore.handleTextDelta(textDeltaData(' +more', 0))
flushFrames()
const content = assistantAt(SESSION).content
expect(content[0]).toMatchObject({ type: 'text', text: 'first' })
expect(content[2]).toMatchObject({ type: 'text', text: 'second +more' })
})
it('未装载的助手消息收到 delta 时被丢弃(不会凭空建会话)', () => {
messageStore.handleTextDelta(textDeltaData('x', 0, 'missing'))
expect(messageStore.getSessionState(SESSION)).toBeUndefined()
})
// ============================================
// 推理流
// ============================================
it('3) reasoning.delta 只写最后一个 time.completed 缺省的推理片段', () => {
messageStore.handleMessageUpdated(
createAssistantMessage('message-1', [
{ type: 'reasoning', text: 'done', time: { created: 1, completed: 2 } },
{ type: 'reasoning', text: 'live', time: { created: 3 } },
]),
SESSION,
)
messageStore.handleReasoningDelta(reasoningDeltaData(' +more'))
flushFrames()
const content = assistantAt(SESSION).content
expect(content[0]).toMatchObject({ text: 'done' })
expect(content[1]).toMatchObject({ text: 'live +more' })
})
it('3b) 只有已完成的推理片段时,delta 无处可写(不会新建片段)', () => {
messageStore.handleMessageUpdated(
createAssistantMessage('message-1', [{ type: 'reasoning', text: 'done', time: { created: 1, completed: 2 } }]),
SESSION,
)
messageStore.handleReasoningDelta(reasoningDeltaData(' should not land'))
flushFrames()
expect(assistantAt(SESSION).content).toHaveLength(1)
expect(contentAt(SESSION)).toMatchObject({ text: 'done' })
})
it('reasoning.started 追加空片段并记 time.created;ended 覆盖文本并标记完成', () => {
messageStore.handleStepStarted(stepStartedData())
messageStore.handleReasoningStarted(reasoningStartedData(0), { id: 'evt-1', created: 120 })
expect(contentAt(SESSION)).toMatchObject({ type: 'reasoning', text: '', time: { created: 120 } })
messageStore.handleReasoningEnded(
{ sessionID: SESSION, assistantMessageID: 'message-1', ordinal: 0, text: 'final thought' },
{ id: 'evt-2', created: 130 },
)
expect(contentAt(SESSION)).toMatchObject({
type: 'reasoning',
text: 'final thought',
time: { created: 120, completed: 130 },
})
})
// ============================================
// 工具生命周期
// ============================================
it('4) input.started 建 streaming 片段;delta 拼字符串;ended 覆盖;called 换成 running 对象', () => {
messageStore.handleStepStarted(stepStartedData())
messageStore.handleToolEvent({
type: 'session.tool.input.started',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-1', name: 'bash' },
facts: { id: 'evt-1', created: 101 },
})
expect(toolAt(SESSION)).toMatchObject({
type: 'tool',
id: 'tool-1',
name: 'bash',
time: { created: 101 },
state: { status: 'streaming', input: '' },
})
messageStore.handleToolEvent({
type: 'session.tool.input.delta',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-1', delta: '{"cmd"' },
})
expect(toolAt(SESSION).state).toMatchObject({ status: 'streaming', input: '{"cmd"' })
messageStore.handleToolEvent({
type: 'session.tool.input.ended',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-1', text: '{"cmd":"ls"}' },
})
expect(toolAt(SESSION).state).toMatchObject({ status: 'streaming', input: '{"cmd":"ls"}' })
messageStore.handleToolEvent({
type: 'session.tool.called',
data: {
sessionID: SESSION,
assistantMessageID: 'message-1',
id: 'tool-1',
input: { cmd: 'ls' },
executed: true,
},
facts: { id: 'evt-2', created: 104 },
})
const tool = toolAt(SESSION)
expect(tool.state).toEqual({ status: 'running', input: { cmd: 'ls' }, metadata: {} })
expect(tool.executed).toBe(true)
expect(tool.time.ran).toBe(104)
})
it('tool.progress 只在 running 时写 metadata;success / failed 收尾', () => {
messageStore.handleStepStarted(stepStartedData())
messageStore.handleToolEvent({
type: 'session.tool.input.started',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-1', name: 'bash' },
})
// 还在 streaming:progress 不该写 metadata
messageStore.handleToolEvent({
type: 'session.tool.progress',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-1', metadata: { step: 1 } },
})
expect(toolAt(SESSION).state).toEqual({ status: 'streaming', input: '' })
messageStore.handleToolEvent({
type: 'session.tool.called',
data: {
sessionID: SESSION,
assistantMessageID: 'message-1',
id: 'tool-1',
input: { cmd: 'ls' },
executed: true,
},
})
messageStore.handleToolEvent({
type: 'session.tool.progress',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-1', metadata: { step: 1 } },
})
expect(toolAt(SESSION).state).toEqual({ status: 'running', input: { cmd: 'ls' }, metadata: { step: 1 } })
messageStore.handleToolEvent({
type: 'session.tool.success',
data: {
sessionID: SESSION,
assistantMessageID: 'message-1',
id: 'tool-1',
content: [{ type: 'text', text: 'file.txt' }],
metadata: { exit: 0 },
executed: true,
},
facts: { id: 'evt-3', created: 110 },
})
expect(toolAt(SESSION)).toMatchObject({
state: {
status: 'completed',
input: { cmd: 'ls' },
metadata: { exit: 0 },
content: [{ type: 'text', text: 'file.txt' }],
},
time: { completed: 110 },
})
messageStore.handleToolEvent({
type: 'session.tool.input.started',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-2', name: 'read' },
})
messageStore.handleToolEvent({
type: 'session.tool.failed',
data: {
sessionID: SESSION,
assistantMessageID: 'message-1',
id: 'tool-2',
error: { type: 'tool.error', message: 'nope' },
metadata: {},
executed: false,
},
facts: { id: 'evt-4', created: 120 },
})
expect(toolAt(SESSION, 1)).toMatchObject({
state: { status: 'error', error: { type: 'tool.error', message: 'nope' }, input: {} },
time: { completed: 120 },
})
})
it('5) 未知工具 id 的事件被丢弃(助手消息存在,但没有该 tool 片段)', () => {
messageStore.handleStepStarted(stepStartedData())
messageStore.handleToolEvent({
type: 'session.tool.progress',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-unknown', metadata: { step: 1 } },
})
messageStore.handleToolEvent({
type: 'session.tool.success',
data: {
sessionID: SESSION,
assistantMessageID: 'message-1',
id: 'tool-unknown',
content: [{ type: 'text', text: 'ignored' }],
executed: true,
},
})
expect(assistantAt(SESSION).content).toEqual([])
})
it('progress 先于 called 处理时暂存 metadata,called 时合并(subagent sessionID 不丢)', () => {
// 乱序/批处理场景:part 还在 streaming 时 progress 先到。
// subagent 的 metadata.sessionID 若在这里丢掉,子会话内联与权限挂载整条链失效。
messageStore.handleStepStarted(stepStartedData())
messageStore.handleToolEvent({
type: 'session.tool.input.started',
data: { sessionID: SESSION, assistantMessageID: 'message-1', id: 'tool-1', name: 'subagent' },
})
messageStore.handleToolEvent({
type: 'session.tool.progress',
data: {
sessionID: SESSION,
assistantMessageID: 'message-1',
id: 'tool-1',
metadata: { sessionID: 'ses_child', status: 'running' },
},
})
// streaming 态本身不受影响(live 路径语义不变)
expect(toolAt(SESSION).state).toEqual({ status: 'streaming', input: '' })
messageStore.handleToolEvent({
type: 'session.tool.called',
data: {
sessionID: SESSION,
assistantMessageID: 'message-1',
id: 'tool-1',
input: { agent: 'explore', description: 'task', prompt: 'p' },
executed: true,
},
})
expect(toolAt(SESSION).state).toEqual({
status: 'running',
input: { agent: 'explore', description: 'task', prompt: 'p' },
metadata: { sessionID: 'ses_child', status: 'running' },
})
// 终态事件清掉暂存:success 的权威 metadata 覆盖
messageStore.handleToolEvent({
type: 'session.tool.success',
data: {
sessionID: SESSION,
assistantMessageID: 'message-1',
id: 'tool-1',
content: [{ type: 'text', text: 'done' }],
metadata: { sessionID: 'ses_child', status: 'completed' },
executed: true,
},
})
expect(toolAt(SESSION).state).toMatchObject({ status: 'completed', metadata: { status: 'completed' } })
})
it('助手消息尚不存在时也能建出 tool 片段(工具先于文本出现)', () => {
messageStore.handleToolEvent({
type: 'session.tool.input.started',
data: { sessionID: SESSION, assistantMessageID: 'message-fresh', id: 'tool-1', name: 'bash' },
})
expect(messageIds(SESSION)).toEqual(['message-fresh'])
expect(toolAt(SESSION)).toMatchObject({ type: 'tool', id: 'tool-1', name: 'bash' })
})
// ============================================
// 重试
// ============================================
describe('6) 重试排期(session.retry.scheduled)', () => {
it('把 retry 挂到助手消息上(原生结构,不做错误翻译)', () => {
messageStore.handleRetryScheduled({
sessionID: SESSION,
assistantMessageID: 'message-1',
attempt: 2,
at: 1700,
error: { type: 'provider_error', message: 'overloaded', status: 503 },
})
expect(assistantAt(SESSION).retry).toEqual({
attempt: 2,
at: 1700,
error: { type: 'provider_error', message: 'overloaded', status: 503 },
})
})
it('助手消息不存在时也能建(重试可能早于任何文本)', () => {
messageStore.handleRetryScheduled({
sessionID: SESSION,
assistantMessageID: 'message-fresh',
attempt: 1,
at: 10,
error: { type: 'x', message: 'boom' },
})
expect(messageIds(SESSION)).toEqual(['message-fresh'])
expect(assistantAt(SESSION).retry).toMatchObject({ attempt: 1, at: 10 })
})
it('重放同一 attempt 只留最后一条 retry(助手消息上只有一个 retry 字段)', () => {
const payload = {
sessionID: SESSION,
assistantMessageID: 'message-1',
attempt: 3,
at: 20,
error: { type: 'x', message: 'again' },
}
messageStore.handleRetryScheduled({ ...payload })
messageStore.handleRetryScheduled({ ...payload })
expect(assistantAt(SESSION).retry).toMatchObject({ attempt: 3, at: 20 })
})
it('step.started 会清掉 retry', () => {
messageStore.handleRetryScheduled({
sessionID: SESSION,
assistantMessageID: 'message-1',
attempt: 1,
at: 10,
error: { type: 'x', message: 'boom' },
})
expect(assistantAt(SESSION).retry).toBeDefined()
messageStore.handleStepStarted(stepStartedData('message-1', 50))
expect(assistantAt(SESSION).retry).toBeUndefined()
})
it('execution 结束会清掉 retry', () => {
messageStore.handleRetryScheduled({
sessionID: SESSION,
assistantMessageID: 'message-1',
attempt: 1,
at: 10,
error: { type: 'x', message: 'boom' },
})
messageStore.handleExecutionFailed({ sessionID: SESSION, error: { type: 'x', message: 'boom' } })
expect(assistantAt(SESSION).retry).toBeUndefined()
})
})
// ============================================
// 执行生命周期
// ============================================
describe('7) 执行结束(session.execution.*)', () => {
it('succeeded → 会话 idle + 插入 outcome=succeeded 的 idle 消息(id 由事件 id 派生)', () => {
messageStore.handleExecutionStarted({ sessionID: SESSION })
expect(messageStore.getIsStreaming(SESSION)).toBe(true)
messageStore.handleExecutionSucceeded({ sessionID: SESSION }, { id: 'evt_done', created: 200 })
const state = messageStore.getSessionState(SESSION)
expect(state?.isStreaming).toBe(false)
const idle = state?.messages.at(-1)
expect(idle).toMatchObject({ id: 'msg_done', type: 'idle', outcome: 'succeeded', time: { created: 200 } })
})
it('failed → outcome=failed + 错误挂到 idle 标记上(官方 idle("failed", error),丢了就永不渲染)', () => {
messageStore.handleExecutionFailed({ sessionID: SESSION, error: { type: 'x', message: 'boom' } })
expect(messageStore.getSessionState(SESSION)?.messages.at(-1)).toMatchObject({
type: 'idle',
outcome: 'failed',
error: { type: 'x', message: 'boom' },
})
})
it('interrupted(reason=user)→ outcome=interrupted', () => {
messageStore.handleExecutionInterrupted({ sessionID: SESSION, reason: 'user' })
expect(messageStore.getSessionState(SESSION)?.messages.at(-1)).toMatchObject({
type: 'idle',
outcome: 'interrupted',
})
})
it('interrupted + reason=shutdown → 不插入 idle 消息', () => {
messageStore.handleExecutionInterrupted({ sessionID: SESSION, reason: 'shutdown' })
expect(messageStore.getSessionState(SESSION)?.messages).toEqual([])
expect(messageStore.getIsStreaming(SESSION)).toBe(false)
})
})
// ============================================
// 压缩
// ============================================
describe('8) 压缩(session.compaction.*)', () => {
it('started 插入 running 压缩消息,delta 追加到 summary,ended 改写成 completed', () => {
messageStore.handleCompactionStarted(
{ sessionID: SESSION, reason: 'auto', recent: 'recent-context' },
{ id: 'evt_compact', created: 300 },
)
expect(messageStore.getSessionState(SESSION)?.messages.at(-1)).toMatchObject({
id: 'msg_compact',
type: 'compaction',
status: 'running',
summary: '',
recent: 'recent-context',
time: { created: 300 },
})
messageStore.handleCompactionDelta({ sessionID: SESSION, text: 'sum' })
messageStore.handleCompactionDelta({ sessionID: SESSION, text: 'mary' })
expect(messageStore.getSessionState(SESSION)?.messages.at(-1)).toMatchObject({ summary: 'summary' })
messageStore.handleCompactionEnded(
{ sessionID: SESSION, reason: 'auto', text: 'final summary', recent: 'r2' },
{ id: 'evt_ended', created: 320 },
)
expect(messageStore.getSessionState(SESSION)?.messages.at(-1)).toMatchObject({
id: 'msg_compact',
type: 'compaction',
status: 'completed',
summary: 'final summary',
recent: 'r2',
})
})
it('没有 running 压缩时,ended 会新插一条 completed', () => {
messageStore.handleCompactionEnded(
{ sessionID: SESSION, reason: 'manual', text: 'late', recent: 'r' },
{ id: 'evt_late', created: 400 },
)
expect(messageStore.getSessionState(SESSION)?.messages.at(-1)).toMatchObject({
id: 'msg_late',
type: 'compaction',
status: 'completed',
summary: 'late',
})
})
it('failed 把 running 压缩改写成 failed(id 沿用 running 那条)', () => {
messageStore.handleCompactionStarted(
{ sessionID: SESSION, reason: 'auto', recent: 'r' },
{ id: 'evt_compact', created: 300 },
)
messageStore.handleCompactionFailed({
sessionID: SESSION,
reason: 'auto',
error: { type: 'compaction.failed', message: 'boom' },
})
const failed = messageStore.getSessionState(SESSION)?.messages.at(-1)
expect(failed).toMatchObject({ id: 'msg_compact', type: 'compaction', status: 'failed' })
expect(failed && failed.type === 'compaction' && failed.status === 'failed' ? failed.error : undefined).toEqual({
type: 'compaction.failed',
message: 'boom',
})
})
})
// ============================================
// content id 契约
// ============================================
describe('9) content 派生 id(contentEntries,按 kind 各自计数)', () => {
it('[text, reasoning, text] → :text:0 / :reasoning:0 / :text:1', () => {
const message = createAssistantMessage('message-1', [
{ type: 'text', text: 'first' },
{ type: 'reasoning', text: 'thinking' },
{ type: 'text', text: 'second' },
])
expect(contentEntries(message).map(entry => entry.id)).toEqual([
'message-1:text:0',
'message-1:reasoning:0',
'message-1:text:1',
])
})
it('派生 id 与流式 delta 的目标一致(第二段文本 + 唯一的推理片段)', () => {
messageStore.handleMessageUpdated(
createAssistantMessage('message-1', [
{ type: 'text', text: 'first' },
{ type: 'reasoning', text: 'thinking' },
{ type: 'text', text: 'second' },
]),
SESSION,
)
messageStore.handleTextDelta(textDeltaData(' +more', 1))
messageStore.handleReasoningDelta(reasoningDeltaData(' +deeper', 0))
flushFrames()
const entries = contentEntries(assistantAt(SESSION))
expect(entries.map(entry => entry.id)).toEqual(['message-1:text:0', 'message-1:reasoning:0', 'message-1:text:1'])
expect(entries[0].content).toMatchObject({ text: 'first' })
expect(entries[1].content).toMatchObject({ text: 'thinking +deeper' })
expect(entries[2].content).toMatchObject({ text: 'second +more' })
})
})
// ============================================
// store 基础设施
// ============================================
it('重连后标记 stale,重新装载后清掉标记', () => {
messageStore.setMessages(SESSION, [createAssistantMessage('message-1', textContent('hello'))])
expect(messageStore.isSessionStale(SESSION)).toBe(false)
messageStore.markAllSessionsStale()
expect(messageStore.isSessionStale(SESSION)).toBe(true)
messageStore.setMessages(SESSION, [createAssistantMessage('message-1', textContent('hello again'))])
expect(messageStore.isSessionStale(SESSION)).toBe(false)
})
it('truncateAfterRevert 截断撤销点之后的消息', () => {
messageStore.setMessages(SESSION, [
createAssistantMessage('message-1', textContent('one')),
createAssistantMessage('message-2', textContent('two')),
createAssistantMessage('message-3', textContent('three')),
])
messageStore.setRevertState(SESSION, { messageId: 'message-2', history: [] })
messageStore.truncateAfterRevert(SESSION)
expect(messageIds(SESSION)).toEqual(['message-1'])
expect(messageStore.getRevertState(SESSION)).toBeNull()
})
it('applyRevertCommitted 按事件边界就地裁剪并清除 revert 态(官方 data.ts:1076-1092 同款)', () => {
messageStore.setMessages(SESSION, [
createAssistantMessage('message-1', textContent('one')),
createAssistantMessage('message-2', textContent('two')),
createAssistantMessage('message-3', textContent('three')),
])
messageStore.setRevertState(SESSION, { messageId: 'message-2', history: [] })
messageStore.applyRevertCommitted(SESSION, 'message-2')
// 与 truncateAfterRevert 不同:即便本地 revert 态不存在也要裁剪
//(另一客户端落盘的 undo)
expect(messageIds(SESSION)).toEqual(['message-1'])
expect(messageStore.getRevertState(SESSION)).toBeNull()
// 本地无 revert 态时同样生效
messageStore.setMessages(SESSION, [
createAssistantMessage('message-1', textContent('one')),
createAssistantMessage('message-2', textContent('two')),
])
messageStore.applyRevertCommitted(SESSION, 'message-2')
expect(messageIds(SESSION)).toEqual(['message-1'])
// 边界之外不裁剪
messageStore.setMessages(SESSION, [createAssistantMessage('message-1', textContent('one'))])
messageStore.applyRevertCommitted(SESSION, 'message-99')
expect(messageIds(SESSION)).toEqual(['message-1'])
})
it('deep undo:边界不在首屏时按 id 隐藏已撤销消息,翻页补齐后重建逐条 redo 历史', () => {
// 首屏只有最近三条(m3/m4/m5),回退边界 m2 在更深的历史里
messageStore.setMessages(
SESSION,
[createUserMessage('m3', 3), createUserMessage('m4', 4), createUserMessage('m5', 5)],
{ revertState: { messageID: 'm2' } },
)
// 边界没加载也要存边界标记,并按 id 比较隐藏已撤销消息(不「复活」)
expect(messageStore.getRevertState(SESSION)?.messageId).toBe('m2')
expect(messageStore.getRevertState(SESSION)?.history).toEqual([])
expect(messageStore.getVisibleMessages(SESSION).map(m => m.id)).toEqual([])
// 有边界标记即可 redo(全恢复兜底,不需要边界本体)
expect(messageStore.canRedo(SESSION)).toBe(true)
// 边界消息没翻进来前,rebuildRevertHistory 返回 false(还需继续翻)
expect(messageStore.rebuildRevertHistory(SESSION)).toBe(false)
// 往回翻一页,把 m1/m2 补进内存
messageStore.prependMessages(SESSION, [createUserMessage('m1', 1), createUserMessage('m2', 2)], false, null)
// 重建逐条 redo 历史
expect(messageStore.rebuildRevertHistory(SESSION)).toBe(true)
expect(messageStore.getRevertState(SESSION)?.history.map(h => h.messageId)).toEqual(['m2', 'm3', 'm4', 'm5'])
// 边界加载后:可见 = 边界之前(m1),边界及之后(m2 起)仍隐藏
expect(messageStore.getVisibleMessages(SESSION).map(m => m.id)).toEqual(['m1'])
expect(messageStore.getRedoSteps(SESSION)).toBe(4)
expect(messageStore.getCurrentRevertedContent(SESSION)?.messageId).toBe('m2')
})
it('prependMessages 去重后前插历史页', () => {
messageStore.setMessages(SESSION, [createAssistantMessage('message-2', textContent('two'))])
messageStore.prependMessages(
SESSION,
[
createAssistantMessage('message-1', textContent('one')),
createAssistantMessage('message-2', textContent('duplicate')),
],
true,
)
expect(messageIds(SESSION)).toEqual(['message-1', 'message-2'])
expect(messageStore.getHasMoreHistory(SESSION)).toBe(true)
})
it('setStreaming 会建会话;对不存在的会话关流不会建', () => {
messageStore.setStreaming(SESSION, true)
expect(messageStore.getSessionState(SESSION)?.isStreaming).toBe(true)
expect(messageStore.getSessionState(SESSION)?.messages).toHaveLength(0)
expect(messageStore.getLoadState(SESSION)).toBe('idle')
messageStore.setStreaming('session-2', false)
expect(messageStore.getSessionState('session-2')).toBeUndefined()
})
it('仍在流式输出时保留本地更长的 live 文本', () => {
messageStore.handleStepStarted(stepStartedData())
messageStore.handleTextStarted(textStartedData())
messageStore.handleTextDelta(textDeltaData('hello world from live'))
// 服务端列表滞后(只有前缀)→ 不能把 live 文本截短
messageStore.handleMessageUpdated(createAssistantMessage('message-1', textContent('hello')), SESSION)
expect(textAt(SESSION)).toBe('hello world from live')
})
it('服务端定稿后强制采用服务端文本(哪怕本地 live 更长)', () => {
messageStore.setMessages(SESSION, [createAssistantMessage('message-1', textContent('hello world extra'))])
messageStore.setMessages(SESSION, [createAssistantMessage('message-1', textContent('hello world'), 99)])
expect(textAt(SESSION)).toBe('hello world')
})
it('handleMessageUpdated 对定稿消息强制采用服务端', () => {
messageStore.setMessages(SESSION, [createAssistantMessage('message-1', textContent('hello world extra'), 10)])
messageStore.handleMessageUpdated(createAssistantMessage('message-1', textContent('hello world'), 10), SESSION)
expect(textAt(SESSION)).toBe('hello world')
})
it('setMessages 保留服务端列表还没有的本地流式助手消息', () => {
messageStore.handleStepStarted(stepStartedData('message-live', 500))
messageStore.handleTextStarted(textStartedData(0, 'message-live'))
messageStore.setMessages(SESSION, [createAssistantMessage('message-1', textContent('server'), 9)])
expect(messageIds(SESSION)).toContain('message-live')
})
it('setMessages 保留本地乐观插入(upsertLocalMessage)的消息', () => {