-
Notifications
You must be signed in to change notification settings - Fork 557
Expand file tree
/
Copy pathhistory-hydration.spec.ts
More file actions
1277 lines (1207 loc) · 49 KB
/
Copy pathhistory-hydration.spec.ts
File metadata and controls
1277 lines (1207 loc) · 49 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 { expect, test, type Page } from '@playwright/test'
import {
chatHistoryPayload,
sessionMessagesHydratePayload,
sessionMessagesSnapshotPayload,
sessionMessagesSubscribePayload,
} from './support/session-read-fixtures'
const CONTROL_URL = '/control/'
const SESSION_KEY = 'agent:main:webchat:e2e-history-hydration'
const SESSION_A = 'agent:main:webchat:e2e-history-stale-a'
const SESSION_B = 'agent:main:webchat:e2e-history-stale-b'
function successResponse(id: string, payload: unknown) {
return JSON.stringify({ type: 'res', id, ok: true, payload })
}
function replyToPing(
ws: { send(message: string): void },
frame: { type?: unknown },
): boolean {
if (frame?.type !== 'ping') return false
ws.send(JSON.stringify({ type: 'pong' }))
return true
}
function helloResponse(tickIntervalMs: number) {
return JSON.stringify({
protocol: 3,
policy: {
tick_interval_ms: tickIntervalMs,
concurrent_history_reads: true,
},
})
}
function requestSessionKey(
frame: { params?: Record<string, unknown> },
fallback = SESSION_KEY,
): string {
return String(frame.params?.key || frame.params?.sessionKey || fallback)
}
function basePayload(method: string, sessionKey = SESSION_KEY): unknown {
const payloads: Record<string, unknown> = {
'agents.list': { agents: [] },
'commands.list_for_surface': { commands: [] },
'config.get': {
squilla_router: { enabled: false, rollout_phase: 'observe', tiers: {} },
permissions: {},
skills: {},
},
'models.routing.get': { mode: 'direct' },
'sessions.list': { sessions: [], has_more: false },
'sessions.messages.snapshot': sessionMessagesSnapshotPayload(sessionKey),
'sessions.messages.subscribe': sessionMessagesSubscribePayload(sessionKey),
'sessions.messages.hydrate': sessionMessagesHydratePayload(sessionKey),
'usage.status': { sessions: [] },
}
return payloads[method] ?? {}
}
function longHistoryMessages(
count = 50,
finalText = 'Hydration complete.',
) {
const now = Math.floor(Date.now() / 1000)
return Array.from({ length: count }, (_, index) => ({
role: index % 2 === 0 ? 'user' : 'assistant',
text: index === count - 1
? finalText
: `History row ${index + 1}. ${'Deterministic long-session content. '.repeat(8)}`,
id: `hydrated-message-${index + 1}`,
timestamp: now - (count - index) * 30,
}))
}
async function stubApprovals(page: Page) {
await page.route('**/api/approvals', route => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ pending: [] }),
}))
}
test('keeps the conversation usable while startup and long history are delayed', async ({ page }) => {
let historyReleased = false
const pendingHistoryResponses: Array<() => void> = []
let chatSendRequests = 0
let usageRequests = 0
const receivedMethods: string[] = []
const sessionRequestOrder: string[] = []
await page.setViewportSize({ width: 1280, height: 900 })
await page.addInitScript(() => {
const state = { emptySeen: false }
Object.defineProperty(window, '__opensquillaHistoryHydrationTest', { value: state })
const markEmpty = () => {
if (document.querySelector('.chat-empty')) state.emptySeen = true
}
new MutationObserver(markEmpty).observe(document, { childList: true, subtree: true })
markEmpty()
})
await stubApprovals(page)
await page.routeWebSocket(/\/ws$/, ws => {
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: {} }))
ws.onMessage(message => {
try {
const frame = JSON.parse(String(message))
if (replyToPing(ws, frame)) return
if (frame?.type !== 'req') return
if (frame.method === 'connect') {
ws.send(helloResponse(30000))
return
}
const method = String(frame.method || '')
receivedMethods.push(method)
if (method.startsWith('sessions.messages.') || method === 'chat.history') {
sessionRequestOrder.push(method)
}
if (method === 'chat.history') {
const messages = longHistoryMessages()
const respond = () => ws.send(successResponse(
String(frame.id),
chatHistoryPayload(messages, {
has_more: true,
oldest_cursor: 'cursor-50',
newest_cursor: 'cursor-100',
history_scope: 'latest_window',
loaded_count: messages.length,
page_size: Number(frame.params?.limit) || 50,
}),
))
if (historyReleased) respond()
else pendingHistoryResponses.push(respond)
return
}
if (method === 'sessions.messages.snapshot') {
ws.send(successResponse(
String(frame.id),
sessionMessagesSnapshotPayload(requestSessionKey(frame)),
))
return
}
if (method === 'sessions.messages.subscribe') {
ws.send(successResponse(
String(frame.id),
sessionMessagesSubscribePayload(requestSessionKey(frame), {
hydration_complete: false,
}),
))
return
}
if (method === 'sessions.messages.hydrate') {
ws.send(successResponse(
String(frame.id),
sessionMessagesHydratePayload(requestSessionKey(frame)),
))
return
}
if (method === 'sessions.list') {
ws.send(successResponse(String(frame.id), {
sessions: [{
key: SESSION_KEY,
title: 'Visible while history is pending',
sessionKind: 'chat',
surface: 'webchat',
conversationKind: 'direct',
effectiveAgentId: 'main',
updatedAt: 100,
messageCount: 50,
status: 'ok',
runStatus: 'idle',
}],
has_more: false,
}))
return
}
if (method === 'chat.send') {
chatSendRequests += 1
ws.send(successResponse(String(frame.id), {
sessionKey: SESSION_KEY,
status: 'accepted',
task_id: 'e2e-history-interactive-send',
message_id: 'e2e-history-interactive-message',
}))
return
}
if (method === 'usage.status') usageRequests += 1
ws.send(successResponse(
String(frame.id),
basePayload(method, requestSessionKey(frame)),
))
} catch {}
})
})
await page.goto(CONTROL_URL + 'chat?session=' + encodeURIComponent(SESSION_KEY))
const hiddenRecovery = page.locator(
'[data-testid="chat-session-recovery-status"][data-recovery-state="history-loading"]',
)
const thread = page.locator('.chat-thread')
const composer = page.getByRole('textbox', { name: 'Message to send' })
await expect.poll(() => pendingHistoryResponses.length).toBeGreaterThan(0)
const criticalStartupOrder = [
'sessions.messages.subscribe',
'sessions.messages.snapshot',
'chat.history',
]
expect(receivedMethods.slice(0, criticalStartupOrder.length)).toEqual(
criticalStartupOrder,
)
expect(sessionRequestOrder.slice(0, criticalStartupOrder.length)).toEqual(
criticalStartupOrder,
)
// Critical ordering is preserved, but independent UI data starts as soon as
// those frames are queued instead of waiting for the history response.
for (const optionalMethod of [
'onboarding.status',
'sessions.subscribe',
'sessions.list',
'agents.list',
'config.get',
'commands.list_for_surface',
'usage.status',
]) {
await expect.poll(() => receivedMethods).toContain(optionalMethod)
}
await expect.poll(() => receivedMethods).toContain('sessions.messages.hydrate')
await expect.poll(() => usageRequests).toBeGreaterThan(0)
await expect(hiddenRecovery).toHaveCount(0)
await expect(page.getByTestId('chat-session-load-state')).toHaveCount(0)
await expect(thread).toHaveAttribute('aria-busy', 'false')
await expect(
page.locator('.sidebar-history-row[data-session-key]')
.filter({ hasText: 'Visible while history is pending' }),
).toBeVisible()
await expect(composer).toBeEditable()
await composer.fill('Draft remains editable while history loads.')
await expect(composer).toHaveValue('Draft remains editable while history loads.')
await expect(page.getByRole('button', { name: 'Send', exact: true })).toBeEnabled()
await expect(page.locator('.chat-empty')).toHaveCount(0)
const themeButton = page.getByRole('button', { name: 'Theme', exact: true })
await themeButton.click()
await expect(page.getByRole('menu', { name: 'Theme' })).toBeVisible()
await page.keyboard.press('Escape')
await expect(page.getByRole('menu', { name: 'Theme' })).toHaveCount(0)
await page.getByRole('button', { name: 'Send', exact: true }).click()
await expect.poll(() => chatSendRequests).toBe(1)
historyReleased = true
pendingHistoryResponses.splice(0).forEach(respond => respond())
await expect(page.getByText('Hydration complete.')).toBeVisible()
await expect(hiddenRecovery).toHaveCount(0)
await expect(page.getByTestId('history-load-sentinel')).toBeAttached()
await expect(composer).toHaveValue('')
await expect.poll(() => page.evaluate(() => {
const state = (window as unknown as {
__opensquillaHistoryHydrationTest?: { emptySeen?: boolean }
}).__opensquillaHistoryHydrationTest
return state?.emptySeen ?? true
})).toBe(false)
await expect.poll(() => page.evaluate(() => (
document.documentElement.scrollWidth <= document.documentElement.clientWidth
))).toBe(true)
})
test('recovers from stuck automatic metadata before sending', async ({ page }) => {
let socketCount = 0
let heldConfigRequests = 0
let chatSendSocket = 0
await stubApprovals(page)
await page.routeWebSocket(/\/ws$/, ws => {
const socketNumber = ++socketCount
let metadataStuck = false
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: {} }))
ws.onMessage(message => {
try {
const frame = JSON.parse(String(message))
if (replyToPing(ws, frame)) return
if (frame?.type !== 'req') return
const method = String(frame.method || '')
if (method === 'connect') {
ws.send(helloResponse(30000))
return
}
if (socketNumber === 1 && method === 'config.get') {
heldConfigRequests += 1
metadataStuck = true
return
}
// Model the Gateway's serial dispatcher: once the optional read is
// stuck, every later request on this socket remains queued behind it.
if (socketNumber === 1 && metadataStuck) return
if (method === 'sessions.messages.snapshot') {
ws.send(successResponse(
String(frame.id),
sessionMessagesSnapshotPayload(requestSessionKey(frame)),
))
return
}
if (method === 'sessions.messages.subscribe') {
ws.send(successResponse(
String(frame.id),
sessionMessagesSubscribePayload(requestSessionKey(frame)),
))
return
}
if (method === 'sessions.messages.hydrate') {
ws.send(successResponse(
String(frame.id),
sessionMessagesHydratePayload(requestSessionKey(frame)),
))
return
}
if (method === 'chat.history') {
ws.send(successResponse(
String(frame.id),
chatHistoryPayload([], {
page_size: Number(frame.params?.limit) || 50,
}),
))
return
}
if (method === 'chat.send') {
chatSendSocket = socketNumber
ws.send(successResponse(String(frame.id), {
sessionKey: SESSION_KEY,
status: 'accepted',
task_id: 'e2e-after-metadata-reconnect',
message_id: 'e2e-after-metadata-reconnect-message',
}))
return
}
ws.send(successResponse(
String(frame.id),
basePayload(method, requestSessionKey(frame)),
))
} catch {}
})
})
await page.goto(CONTROL_URL + 'chat?session=' + encodeURIComponent(SESSION_KEY))
await expect.poll(() => heldConfigRequests).toBeGreaterThan(0)
// The optional metadata budget is 10 seconds; leave time for the timeout
// handler to retire the stuck socket and finish the replacement handshake.
await expect.poll(() => socketCount, { timeout: 15_000 }).toBeGreaterThan(1)
const composer = page.getByRole('textbox', { name: 'Message to send' })
const send = page.getByRole('button', { name: 'Send', exact: true })
await expect(composer).toBeEditable()
await composer.fill('Send after automatic metadata recovery.')
await expect(send).toBeEnabled()
await send.click()
await expect.poll(() => chatSendSocket).toBeGreaterThan(1)
await expect(composer).toHaveValue('')
})
test('shows a recoverable initial failure and retries it', async ({ page }) => {
let historyRequests = 0
let allowHistoryRecovery = false
let releaseRetry: (() => void) | undefined
await stubApprovals(page)
await page.routeWebSocket(/\/ws$/, ws => {
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: {} }))
ws.onMessage(message => {
try {
const frame = JSON.parse(String(message))
if (replyToPing(ws, frame)) return
if (frame?.type !== 'req') return
if (frame.method === 'connect') {
ws.send(helloResponse(30000))
return
}
if (frame.method === 'config.get') {
ws.send(successResponse(String(frame.id), {
squilla_router: { enabled: false, rollout_phase: 'observe', tiers: {} },
permissions: {},
skills: {},
}))
return
}
if (frame.method === 'chat.history') {
historyRequests += 1
if (!allowHistoryRecovery) {
ws.send(JSON.stringify({
type: 'res',
id: String(frame.id),
ok: false,
error: { code: 'HISTORY_UNAVAILABLE', message: 'offline', retryable: true },
}))
} else {
const messages = [{
role: 'assistant',
text: 'History recovered after retry.',
id: 'history-recovered',
timestamp: Math.floor(Date.now() / 1000),
}]
releaseRetry = () => ws.send(successResponse(
String(frame.id),
chatHistoryPayload(messages, {
page_size: Number(frame.params?.limit) || 50,
}),
))
}
return
}
ws.send(successResponse(
String(frame.id),
basePayload(String(frame.method), requestSessionKey(frame)),
))
} catch {}
})
})
await page.goto(CONTROL_URL + 'chat?session=' + encodeURIComponent(SESSION_KEY))
const loadState = page.locator(
'[data-testid="chat-session-recovery-status"][data-recovery-state="history-error"]',
)
const retry = loadState.getByTestId('chat-session-recovery-retry')
const thread = page.locator('.chat-thread')
const composer = page.getByRole('textbox', { name: 'Message to send' })
await expect(loadState).toContainText('Conversation history temporarily unavailable')
await expect(loadState).toContainText(
'The connection may have been interrupted, or history is temporarily unavailable.',
)
await expect(loadState).toHaveAttribute('role', 'alert')
await expect(thread).toHaveAttribute('aria-busy', 'false')
await expect(composer).toBeEditable()
await expect(page.locator('.chat-empty')).toHaveCount(0)
const failedHistoryRequests = historyRequests
allowHistoryRecovery = true
await retry.click()
await expect.poll(() => historyRequests).toBe(failedHistoryRequests + 1)
await expect.poll(() => Boolean(releaseRetry)).toBe(true)
const retrying = page.locator(
'[data-testid="chat-session-recovery-status"][data-recovery-state="history-retrying"]',
)
await expect(retrying).toContainText('Reloading conversation history…')
await expect(thread).toHaveAttribute('aria-busy', 'false')
await expect(thread).toBeFocused()
releaseRetry?.()
await expect(page.getByText('History recovered after retry.')).toBeVisible()
await expect(retrying).toHaveCount(0)
expect(historyRequests).toBe(failedHistoryRequests + 1)
})
test('terminates stalled history and live hydration despite ongoing ticks, then recovers on a new socket', async ({ page }) => {
test.setTimeout(30_000)
const retainedTail = 'History recovered on a fresh connection.'
const seededTranscript = longHistoryMessages(320, retainedTail)
let allowRecovery = false
let faultInjected = false
let seedOffset = seededTranscript.length
let socketCount = 0
let tickCount = 0
let heldHistoryRequests = 0
let heldSubscribeRequests = 0
let recoveredHistorySocket = 0
let recoveredSubscribeSocket = 0
let disconnectSeedSocket: (() => Promise<void>) | undefined
const recoveredHistoryWindows: Array<{ requested: number, returned: number }> = []
const tickSenders: Array<() => void> = []
await page.clock.install({ time: new Date('2026-07-28T00:00:00Z') })
await stubApprovals(page)
await page.routeWebSocket(/\/ws$/, ws => {
const socketId = ++socketCount
if (socketId === 1) {
disconnectSeedSocket = () => ws.close({ code: 1012, reason: 'inject recovery' })
}
let tickSeq = 0
const sendTick = () => {
try {
ws.send(JSON.stringify({
type: 'event',
event: 'tick',
seq: ++tickSeq,
payload: { socket_id: socketId },
}))
tickCount += 1
} catch {
// A timed-out socket is intentionally retired while its replacement
// continues the same fault-injection scenario.
}
}
sendTick()
tickSenders.push(sendTick)
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: {} }))
ws.onMessage(message => {
try {
const frame = JSON.parse(String(message))
if (replyToPing(ws, frame)) return
if (frame?.type !== 'req') return
if (frame.method === 'connect') {
ws.send(helloResponse(1000))
return
}
if (frame.method === 'sessions.messages.snapshot') {
ws.send(successResponse(String(frame.id), {
key: SESSION_KEY,
task_id: null,
events: [],
stream_generation: 'history-hydration-generation',
current_stream_seq: 0,
}))
return
}
if (frame.method === 'chat.history') {
const requestedLimit = Math.max(
1,
Math.min(200, Number(frame.params?.limit) || 50),
)
if (!faultInjected) {
const end = seedOffset
const start = Math.max(0, end - requestedLimit)
const messages = seededTranscript.slice(start, end)
seedOffset = start
ws.send(successResponse(String(frame.id), {
messages,
has_more: start > 0,
oldest_cursor: start > 0 ? `cursor-${start}` : null,
newest_cursor: `cursor-${end}`,
history_scope: start > 0 ? 'latest_window' : 'complete',
loaded_count: messages.length,
page_size: requestedLimit,
canonical_available: true,
canonical_complete: true,
compaction_summaries: [],
turn_outcomes: [],
}))
return
}
if (!allowRecovery) {
heldHistoryRequests += 1
return
}
recoveredHistorySocket = socketId
const messages = seededTranscript.slice(-requestedLimit)
recoveredHistoryWindows.push({
requested: Number(frame.params?.limit),
returned: messages.length,
})
ws.send(successResponse(String(frame.id), {
messages,
has_more: messages.length < seededTranscript.length,
oldest_cursor: messages.length < seededTranscript.length
? `cursor-${seededTranscript.length - messages.length}`
: null,
newest_cursor: 'cursor-320',
history_scope: messages.length < seededTranscript.length
? 'latest_window'
: 'complete',
loaded_count: messages.length,
page_size: requestedLimit,
canonical_available: true,
canonical_complete: true,
compaction_summaries: [],
turn_outcomes: [],
}))
return
}
if (frame.method === 'sessions.messages.subscribe') {
if (faultInjected && !allowRecovery) {
heldSubscribeRequests += 1
return
}
if (faultInjected) recoveredSubscribeSocket = socketId
ws.send(successResponse(String(frame.id), {
subscribed: true,
key: SESSION_KEY,
stream_generation: 'history-hydration-generation',
replay_complete: true,
replay_gap_reason: null,
replayed_count: 0,
current_stream_seq: 0,
workspaceId: null,
projectWorkspace: null,
projectWorkspaceDeferred: false,
active_task_group_ids: [],
run_mode_lock: { locked: false },
pendingUserInputs: [],
collaboration: null,
routing: null,
currentPlan: null,
activePlanRun: null,
goal: null,
goalSnapshotStreamSeq: null,
tasks: [],
active_task: null,
last_task: null,
run_status: 'idle',
hydration_complete: true,
deferred_fields: [],
}))
return
}
ws.send(successResponse(
String(frame.id),
basePayload(String(frame.method), requestSessionKey(frame)),
))
} catch {}
})
})
await page.goto(CONTROL_URL + 'chat?session=' + encodeURIComponent(SESSION_KEY))
const thread = page.locator('.chat-thread')
// Keep this recovery proof locale-independent: browser locale follows the
// host on developer machines, so accessible names are not always English.
const composer = page.locator('.chat-textarea')
const send = page.locator('.chat-send-btn')
// Seed a protocol-realistic long transcript through ordinary 50-row
// history pages. The Gateway caps history responses, so the fault-recovery
// response below must never manufacture all 320 rows for one request.
await expect(page.getByText(retainedTail)).toBeVisible()
for (let pageIndex = 0; seedOffset > 0 && pageIndex < 7; pageIndex += 1) {
const previousOffset = seedOffset
await thread.evaluate(element => element.scrollTo({ top: 0 }))
await expect.poll(() => seedOffset).toBeLessThan(previousOffset)
}
expect(seedOffset).toBe(0)
await expect(page.locator('.chat-message-list')).toHaveAttribute('data-virtualized', 'true')
// Pagination is deliberate reader navigation and leaves live following
// paused. Reclaim it through the product control so the recovery assertion
// starts from an explicit live-edge lease rather than merely a DOM position
// that can still have autoScroll=false while the virtualizer settles.
const jumpToLatest = page.locator('.chat-jump-latest')
await expect(jumpToLatest).toBeVisible()
await jumpToLatest.click()
await page.clock.runFor(100)
await expect(jumpToLatest).toHaveCount(0)
await expect(page.getByText(retainedTail)).toBeVisible()
await expect(page.getByTestId('chat-session-load-state')).toHaveCount(0)
await expect(thread).toHaveAttribute('aria-busy', 'false')
await expect(composer).toBeEditable()
await composer.fill('Keep this draft through timeout and reconnect.')
await expect(composer).toHaveValue('Keep this draft through timeout and reconnect.')
faultInjected = true
await disconnectSeedSocket?.()
await expect.poll(() => heldHistoryRequests).toBeGreaterThan(0)
await expect.poll(() => heldSubscribeRequests).toBeGreaterThan(0)
// Advance past the 15-second aggregate bootstrap budget one second at a
// time, delivering a server tick after each increment. This models a socket
// that remains healthy while individual RPCs never produce responses.
// Leave enough headroom for the RPC round-trip between reading the mocked
// clock and pausing it. A 1 ms target can already be in the past on a busy
// hosted runner, which makes Playwright reject the retry before exercising
// the recovery contract.
await page.clock.pauseAt((await page.evaluate(() => Date.now())) + 1_000)
for (let elapsed = 0; elapsed < 16_000; elapsed += 1000) {
await page.clock.runFor(1000)
tickSenders.forEach(sendTick => sendTick())
}
expect(tickCount).toBeGreaterThan(15)
const historyFailure = page.locator(
'[data-testid="chat-session-recovery-status"][data-recovery-state="history-error"]',
)
await expect(historyFailure).toBeVisible()
await expect(historyFailure).toHaveAttribute('role', 'alert')
await expect(thread).toHaveAttribute('aria-busy', 'false')
await expect(composer).toBeEditable()
await expect(composer).toHaveValue('Keep this draft through timeout and reconnect.')
await expect(page.getByText(retainedTail)).toBeVisible()
await expect(send).toBeDisabled()
expect(socketCount).toBeGreaterThan(1)
await expect(thread).not.toHaveClass(/chat-thread--reading-history/)
allowRecovery = true
// The retry control lives above the long transcript. Playwright's ordinary
// locator click would first scroll that off-screen control into view and
// correctly transfer viewport ownership to the reader. Activate it in-page
// so this case isolates recovery while the existing live-edge lease remains
// intact; reader-owned navigation is covered separately.
await historyFailure.getByTestId('chat-session-recovery-retry')
.evaluate((button: HTMLButtonElement) => button.click())
// The deterministic clock also owns requestAnimationFrame. Let the long-
// history virtualizer measure and commit its tail window before asserting.
await page.clock.runFor(100)
await expect(page.getByText(retainedTail)).toBeVisible()
expect(recoveredHistorySocket).toBeGreaterThan(1)
expect(recoveredHistoryWindows).toContainEqual({ requested: 200, returned: 200 })
expect(recoveredHistoryWindows.every(window => window.returned <= window.requested)).toBe(true)
await expect(composer).toHaveValue('Keep this draft through timeout and reconnect.')
const liveFailure = page.locator(
'[data-testid="chat-session-recovery-status"][data-recovery-state="live-degraded"]',
)
// The page clock is paused for this deterministic timeout scenario. Keep
// advancing it after the history retry so an in-flight subscribe on the
// recycled socket can either recover or reach its bounded degraded state.
for (let elapsed = 0; elapsed < 16_000 && !await send.isEnabled(); elapsed += 1000) {
await page.clock.runFor(1000)
tickSenders.forEach(sendTick => sendTick())
}
// Depending on whether the replacement socket connected before or after
// recovery was allowed, the live phase may already be ready or may expose
// its explicit retry control. Both paths must converge without losing the
// recovered history or composer draft.
await expect.poll(async () => (
(await send.isEnabled()) || (await liveFailure.isVisible())
)).toBe(true)
if (await liveFailure.isVisible()) {
await expect(page.getByText(retainedTail)).toBeVisible()
await expect(thread).not.toHaveClass(/chat-thread--reading-history/)
await liveFailure.getByTestId('chat-session-recovery-retry')
.evaluate((button: HTMLButtonElement) => button.click())
}
await expect.poll(() => recoveredSubscribeSocket).toBeGreaterThan(1)
await expect(liveFailure).toHaveCount(0)
await expect(send).toBeEnabled()
await expect(page.getByText(retainedTail)).toBeVisible()
await expect(composer).toHaveValue('Keep this draft through timeout and reconnect.')
})
test('preserves a Sessions Hub auto-send draft when live recovery terminates', async ({ page }) => {
test.setTimeout(30_000)
let allowSubscription = false
let heldSubscribeRequests = 0
let chatSendRequests = 0
const tickSenders: Array<() => void> = []
await page.clock.install({ time: new Date('2026-07-28T00:00:00Z') })
await stubApprovals(page)
await page.routeWebSocket(/\/ws$/, ws => {
let tickSeq = 0
const sendTick = () => {
try {
ws.send(JSON.stringify({
type: 'event',
event: 'tick',
seq: ++tickSeq,
payload: {},
}))
} catch {}
}
sendTick()
tickSenders.push(sendTick)
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: {} }))
ws.onMessage(message => {
try {
const frame = JSON.parse(String(message))
if (replyToPing(ws, frame)) return
if (frame?.type !== 'req') return
if (frame.method === 'connect') {
ws.send(helloResponse(1000))
return
}
if (frame.method === 'sessions.messages.snapshot') {
ws.send(successResponse(
String(frame.id),
sessionMessagesSnapshotPayload(requestSessionKey(frame, 'session:new')),
))
return
}
if (frame.method === 'sessions.messages.subscribe') {
if (!allowSubscription) {
heldSubscribeRequests += 1
return
}
ws.send(successResponse(
String(frame.id),
sessionMessagesSubscribePayload(requestSessionKey(frame, 'session:new')),
))
return
}
if (frame.method === 'chat.send') {
chatSendRequests += 1
ws.send(successResponse(String(frame.id), {
sessionKey: String(frame.params?.sessionKey || ''),
task_id: 'unexpected-auto-send',
}))
return
}
ws.send(successResponse(
String(frame.id),
basePayload(
String(frame.method),
requestSessionKey(frame, 'session:new'),
),
))
} catch {}
})
})
await page.goto(CONTROL_URL + 'sessions')
const taskText = 'Keep this Sessions Hub draft until live updates recover.'
await page.locator('.hub-task__input').fill(taskText)
await page.getByRole('button', { name: 'Start task' }).click()
await expect(page).toHaveURL(/\/chat\/new/)
await expect.poll(() => heldSubscribeRequests).toBeGreaterThan(0)
const composer = page.getByRole('textbox', { name: 'Message to send' })
const send = page.getByRole('button', { name: 'Send', exact: true })
await expect(composer).toHaveValue(taskText)
await expect(composer).toBeEditable()
await expect(send).toBeDisabled()
await page.clock.pauseAt((await page.evaluate(() => Date.now())) + 1_000)
const liveFailure = page.locator(
'[data-testid="chat-session-recovery-status"][data-recovery-state="live-degraded"]',
)
// A replacement socket can begin one fresh bounded live-recovery budget
// after the original subscribe stalls. Advance through both budgets instead
// of assuming the first 16 seconds always lands on the terminal frame.
for (let elapsed = 0; elapsed < 40_000 && !await liveFailure.isVisible(); elapsed += 1000) {
await page.clock.runFor(1000)
tickSenders.forEach(sendTick => sendTick())
}
await expect(liveFailure).toBeVisible()
await expect(composer).toHaveValue(taskText)
await composer.press('Enter')
await expect(composer).toHaveValue(taskText)
expect(chatSendRequests).toBe(0)
allowSubscription = true
await liveFailure.getByTestId('chat-session-recovery-retry').click()
await expect(liveFailure).toHaveCount(0)
await expect(send).toBeEnabled()
await expect(composer).toHaveValue(taskText)
expect(chatSendRequests).toBe(0)
})
test('cancels delayed auto-send when the user edits the draft before live is ready', async ({ page }) => {
let releaseSubscription: (() => void) | undefined
let chatSendRequests = 0
await stubApprovals(page)
await page.routeWebSocket(/\/ws$/, ws => {
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: {} }))
ws.onMessage(message => {
try {
const frame = JSON.parse(String(message))
if (replyToPing(ws, frame)) return
if (frame?.type !== 'req') return
if (frame.method === 'connect') {
ws.send(helloResponse(30000))
return
}
if (frame.method === 'sessions.messages.snapshot') {
ws.send(successResponse(
String(frame.id),
sessionMessagesSnapshotPayload(requestSessionKey(frame, 'session:new')),
))
return
}
if (frame.method === 'sessions.messages.subscribe') {
releaseSubscription = () => ws.send(successResponse(
String(frame.id),
sessionMessagesSubscribePayload(requestSessionKey(frame, 'session:new')),
))
return
}
if (frame.method === 'chat.send') {
chatSendRequests += 1
ws.send(successResponse(String(frame.id), {
sessionKey: String(frame.params?.sessionKey || ''),
task_id: 'must-not-send-edited-draft',
}))
return
}
ws.send(successResponse(
String(frame.id),
basePayload(
String(frame.method),
requestSessionKey(frame, 'session:new'),
),
))
} catch {}
})
})
await page.goto(CONTROL_URL + 'sessions')
const original = 'Original Sessions Hub task.'
const edited = 'User-edited draft must remain unsent.'
await page.locator('.hub-task__input').fill(original)
await page.getByRole('button', { name: 'Start task' }).click()
await expect(page).toHaveURL(/\/chat\/new/)
await expect.poll(() => Boolean(releaseSubscription)).toBe(true)
const composer = page.getByRole('textbox', { name: 'Message to send' })
await expect(composer).toHaveValue(original)
await composer.fill(edited)
releaseSubscription?.()
await expect(page.getByRole('button', { name: 'Send', exact: true })).toBeEnabled()
await expect(composer).toHaveValue(edited)
expect(chatSendRequests).toBe(0)
})
test('keeps loaded messages visible when an earlier page fails and retries inline', async ({ page }) => {
let latestHistoryRequests = 0
let earlierHistoryRequests = 0
let allowEarlierRetry = false
let releaseEarlierRetry: (() => void) | undefined
await stubApprovals(page)
await page.routeWebSocket(/\/ws$/, ws => {
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: {} }))
ws.onMessage(message => {
try {
const frame = JSON.parse(String(message))
if (replyToPing(ws, frame)) return
if (frame?.type !== 'req') return
if (frame.method === 'connect') {
ws.send(helloResponse(30000))
return
}
if (frame.method === 'config.get') {
ws.send(successResponse(String(frame.id), {
squilla_router: { enabled: false, rollout_phase: 'observe', tiers: {} },
permissions: {},
skills: {},
}))
return
}
if (frame.method === 'chat.history') {
if (frame.params?.before == null) {
latestHistoryRequests += 1
const messages = longHistoryMessages()
ws.send(successResponse(String(frame.id), chatHistoryPayload(messages, {
has_more: true,
oldest_cursor: 'cursor-50',
newest_cursor: 'cursor-100',
history_scope: 'latest_window',
loaded_count: messages.length,
page_size: Number(frame.params?.limit) || 50,
})))
} else if (!allowEarlierRetry) {
earlierHistoryRequests += 1
ws.send(JSON.stringify({
type: 'res',
id: String(frame.id),
ok: false,
error: { code: 'HISTORY_UNAVAILABLE', message: 'offline', retryable: true },
}))
} else {
earlierHistoryRequests += 1
const messages = [{
role: 'assistant',
text: 'Earlier page recovered.',
id: 'earlier-message',
timestamp: Math.floor(Date.now() / 1000) - 3600,
}]
releaseEarlierRetry = () => ws.send(successResponse(
String(frame.id),
chatHistoryPayload(messages, {
newest_cursor: 'cursor-50',
page_size: Number(frame.params?.limit) || 50,
}),
))
}
return
}
ws.send(successResponse(
String(frame.id),
basePayload(String(frame.method), requestSessionKey(frame)),
))
} catch {}
})
})
await page.goto(CONTROL_URL + 'chat?session=' + encodeURIComponent(SESSION_KEY))
const thread = page.locator('.chat-thread')
const loadState = page.locator(
'[data-testid="chat-session-recovery-status"][data-recovery-state="history-error"]',
)
await expect(page.getByText('Hydration complete.')).toBeVisible()
await thread.evaluate(element => element.scrollTo({ top: 0 }))
await expect.poll(() => earlierHistoryRequests).toBe(1)
const retry = page.getByTestId('history-load-retry')
await expect(retry).toContainText('Earlier messages failed to load · Retry')
await expect(loadState).toHaveCount(0)
await expect(page.getByText(/History row 1\./).first()).toBeVisible()
allowEarlierRetry = true
await retry.click()
await expect.poll(() => earlierHistoryRequests).toBe(2)
await expect.poll(() => Boolean(releaseEarlierRetry)).toBe(true)
await expect(page.getByText('Loading earlier messages…')).toBeVisible()
await expect(thread).toBeFocused()
releaseEarlierRetry?.()