-
Notifications
You must be signed in to change notification settings - Fork 873
Expand file tree
/
Copy pathserver-lifecycle.test.ts
More file actions
1436 lines (1344 loc) · 51.9 KB
/
Copy pathserver-lifecycle.test.ts
File metadata and controls
1436 lines (1344 loc) · 51.9 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 } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { createConnection } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { chatGptWebTraceId } from "../src/adapters/chatgpt-web";
import type { ProviderAdapter } from "../src/adapters/base";
import { runStructuredCompactionOnce } from "../src/adapters/chatgpt-web/compaction-handoff";
import { ChatGptTextFeed, ChatGptTraceFeed, chatGptTurnSessions } from "../src/adapters/chatgpt-web/turn-execution";
import { callTurnBroker, closeTurnBrokers, RemoteTurnBroker, TurnBroker } from "../src/adapters/chatgpt-web/turn-broker";
import { defaultBrokerEndpoint, defaultConfig, providerConfig } from "../src/config";
import { parseRequest } from "../src/responses/parser";
import { compactRequest, HttpTurnCounter, responseRequest, routeChatGptWebRequest, startServer } from "../src/server";
test("DEV harness configuration cannot bind a Responses listener", () => {
const config = { ...defaultConfig("browser-only"), purpose: "dev-harness" as const, port: 0 };
expect(() => startServer(config)).toThrow("cannot start a Responses listener");
});
async function waitForTurnCount(turns: HttpTurnCounter, expected: number): Promise<void> {
const deadline = Date.now() + 1_000;
while (turns.count() !== expected && Date.now() < deadline) await Bun.sleep(5);
expect(turns.count()).toBe(expected);
}
test("HTTP turn tracking follows the response stream instead of Bun's global request count", async () => {
const turns = new HttpTurnCounter();
let source!: ReadableStreamDefaultController<Uint8Array>;
const response = await turns.track(async () => new Response(new ReadableStream<Uint8Array>({
start(controller) {
source = controller;
},
})));
const reader = response.body!.getReader();
expect(turns.count()).toBe(1);
source.enqueue(new TextEncoder().encode("data"));
expect((await reader.read()).done).toBe(false);
expect(turns.count()).toBe(1);
source.close();
expect((await reader.read()).done).toBe(true);
await waitForTurnCount(turns, 0);
});
test("HTTP turn tracking releases a cancelled response stream", async () => {
const failures: unknown[] = [];
const turns = new HttpTurnCounter(failure => failures.push(failure));
const request = new AbortController();
const response = await turns.track(
async () => new Response(new ReadableStream<Uint8Array>()),
request.signal,
);
expect(turns.count()).toBe(1);
const cancelled = response.body!.cancel();
request.abort("client disconnected");
await cancelled;
await waitForTurnCount(turns, 0);
expect(failures).toEqual([]);
});
test("HTTP turn tracking uses a tee branch on Windows", async () => {
const turns = new HttpTurnCounter();
let source!: ReadableStreamDefaultController<Uint8Array>;
const original = new ReadableStream<Uint8Array>({
start(controller) { source = controller; },
});
const response = await turns.track(async () => new Response(original), undefined, "win32");
const reader = response.body!.getReader();
source.enqueue(new TextEncoder().encode("safe"));
expect(new TextDecoder().decode((await reader.read()).value)).toBe("safe");
source.close();
expect((await reader.read()).done).toBe(true);
await waitForTurnCount(turns, 0);
});
test("HTTP turn tracking uses direct pull and cancellation outside Windows", async () => {
const turns = new HttpTurnCounter();
let source!: ReadableStreamDefaultController<Uint8Array>;
let sourceCancelled = false;
const original = new ReadableStream<Uint8Array>({
start(controller) { source = controller; },
cancel() { sourceCancelled = true; },
});
const response = await turns.track(async () => new Response(original), undefined, "darwin");
const reader = response.body!.getReader();
source.enqueue(new TextEncoder().encode("native-pull"));
expect(new TextDecoder().decode((await reader.read()).value)).toBe("native-pull");
await reader.cancel("client disconnected");
await waitForTurnCount(turns, 0);
expect(sourceCancelled).toBe(true);
});
test("HTTP turn tracking records privacy-safe client stream failure evidence", async () => {
const failures: unknown[] = [];
const turns = new HttpTurnCounter(failure => failures.push(failure));
let source!: ReadableStreamDefaultController<Uint8Array>;
const response = await turns.track(
async () => new Response(new ReadableStream<Uint8Array>({
start(controller) { source = controller; },
})),
undefined,
"darwin",
"responses",
);
const reader = response.body!.getReader();
source.enqueue(new TextEncoder().encode("safe"));
expect(new TextDecoder().decode((await reader.read()).value)).toBe("safe");
source.error(Object.assign(new TypeError("private upstream response fragment"), { code: "ECONNRESET" }));
await expect(reader.read()).rejects.toThrow("private upstream response fragment");
await waitForTurnCount(turns, 0);
expect(failures).toEqual([{
httpTurnId: 1,
endpoint: "responses",
reader: "client",
platform: "darwin",
chunks: 1,
bytes: 4,
errorName: "TypeError",
errorCode: "ECONNRESET",
}]);
expect(JSON.stringify(failures)).not.toContain("private upstream response fragment");
});
test("HTTP turn tracking records privacy-safe Windows lifecycle failure evidence", async () => {
const failures: unknown[] = [];
const turns = new HttpTurnCounter(failure => failures.push(failure));
let source!: ReadableStreamDefaultController<Uint8Array>;
const response = await turns.track(
async () => new Response(new ReadableStream<Uint8Array>({
start(controller) { source = controller; },
})),
undefined,
"win32",
"responses",
);
const reader = response.body!.getReader();
source.enqueue(new TextEncoder().encode("event"));
expect(new TextDecoder().decode((await reader.read()).value)).toBe("event");
source.error(Object.assign(new TypeError("sensitive socket detail"), { code: "ECONNRESET" }));
await expect(reader.read()).rejects.toThrow("sensitive socket detail");
await waitForTurnCount(turns, 0);
expect(failures).toEqual([{
httpTurnId: 1,
endpoint: "responses",
reader: "windows_lifecycle",
platform: "win32",
chunks: 1,
bytes: 5,
errorName: "TypeError",
errorCode: "ECONNRESET",
}]);
expect(JSON.stringify(failures)).not.toContain("sensitive socket detail");
});
test("HTTP stream diagnostics cannot replace the source failure or retain turn ownership", async () => {
const turns = new HttpTurnCounter(() => { throw new Error("diagnostic sink failed"); });
let source!: ReadableStreamDefaultController<Uint8Array>;
const response = await turns.track(
async () => new Response(new ReadableStream<Uint8Array>({
start(controller) { source = controller; },
})),
undefined,
"darwin",
"responses",
);
const reader = response.body!.getReader();
source.error(new TypeError("source connection reset"));
await expect(reader.read()).rejects.toThrow("source connection reset");
await waitForTurnCount(turns, 0);
});
test("HTTP turn tracking releases a stream whose client disconnected without cancelling", async () => {
const turns = new HttpTurnCounter();
const client = new AbortController();
let cancelled = false;
const response = await turns.track(
async () => new Response(new ReadableStream<Uint8Array>({
cancel() {
cancelled = true;
},
})),
client.signal,
);
expect(turns.count()).toBe(1);
client.abort();
await Bun.sleep(0);
expect(turns.count()).toBe(0);
expect(cancelled).toBe(true);
expect(response.body).not.toBeNull();
});
test("HTTP turn tracking releases a stream requested by an already disconnected client", async () => {
const turns = new HttpTurnCounter();
const client = new AbortController();
client.abort();
const response = await turns.track(async () => new Response(new ReadableStream<Uint8Array>()), client.signal);
expect(turns.count()).toBe(0);
expect(response.status).toBe(499);
expect(response.body).toBeNull();
});
test("a real HTTP peer disconnect releases a streaming turn", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
let source!: ReadableStreamDefaultController<Uint8Array>;
let sourceCancelled = false;
let markSourceReady!: () => void;
const sourceReady = new Promise<void>(resolve => { markSourceReady = resolve; });
const server = startServer(config, {
fetchUpstream: async () => new Response(new ReadableStream<Uint8Array>({
start(controller) {
source = controller;
markSourceReady();
},
cancel() {
sourceCancelled = true;
},
})),
});
const port = server.port;
if (port === undefined) throw new Error("test server did not bind a TCP port");
const endpoint = `http://127.0.0.1:${port}`;
const socket = createConnection({ host: "127.0.0.1", port });
try {
await new Promise<void>((resolve, reject) => {
socket.once("connect", resolve);
socket.once("error", reject);
});
const body = JSON.stringify({ query: "disconnect lifecycle proof" });
socket.write([
"POST /v1/alpha/search HTTP/1.1",
"Host: 127.0.0.1",
"Authorization: Bearer test-codex-session",
"Content-Type: application/json",
`Content-Length: ${Buffer.byteLength(body)}`,
"Connection: keep-alive",
"",
body,
].join("\r\n"));
await sourceReady;
source.enqueue(new TextEncoder().encode("stream-open"));
await new Promise<void>((resolve, reject) => {
socket.once("data", () => resolve());
socket.once("error", reject);
});
expect(await (await fetch(`${endpoint}/healthz`)).json()).toMatchObject({ active_http_turns: 1 });
socket.destroy();
const deadline = Date.now() + 1_000;
let activeHttpTurns = 1;
while (Date.now() < deadline && activeHttpTurns !== 0) {
const health = await (await fetch(`${endpoint}/healthz`)).json() as { active_http_turns: number };
activeHttpTurns = health.active_http_turns;
if (activeHttpTurns !== 0) await Bun.sleep(10);
}
expect(activeHttpTurns).toBe(0);
expect(sourceCancelled).toBe(true);
} finally {
socket.destroy();
await server.stop(true);
}
});
test("HTTP turn cancellation aborts the tracked request and waits for lifecycle release", async () => {
const turns = new HttpTurnCounter();
let observedAbort = false;
const tracked = turns.track(signal => new Promise<Response>((_resolve, reject) => {
signal.addEventListener("abort", () => {
observedAbort = true;
reject(signal.reason);
}, { once: true });
}));
await waitForTurnCount(turns, 1);
expect(await turns.cancelAll("launcher quit")).toBe(1);
await expect(tracked).rejects.toBe("launcher quit");
expect(observedAbort).toBe(true);
expect(turns.count()).toBe(0);
});
test("native Codex interrupt cancels only HTTP streams owned by the exact thread and turn", async () => {
const turns = new HttpTurnCounter();
const started: Promise<Response>[] = [];
const aborted: string[] = [];
for (const identity of [
{ threadId: "thread_exact", turnId: "turn_exact" },
{ threadId: "thread_other", turnId: "turn_other" },
]) {
started.push(turns.track((signal, bindIdentity) => {
bindIdentity(identity);
return new Promise<Response>((_resolve, reject) => {
signal.addEventListener("abort", () => {
aborted.push(identity.turnId);
reject(signal.reason);
}, { once: true });
});
}));
}
await waitForTurnCount(turns, 2);
expect(await turns.cancelTurn({ threadId: "thread_exact", turnId: "turn_exact" })).toBe(1);
expect(aborted).toEqual(["turn_exact"]);
expect(turns.count()).toBe(1);
await expect(started[0]!).rejects.toHaveProperty("name", "AbortError");
expect(await turns.cancelAll()).toBe(1);
await expect(started[1]!).rejects.toThrow("Active HTTP turns cancelled");
});
test("native Codex interrupt remains authoritative when it arrives before HTTP identity binding", async () => {
const turns = new HttpTurnCounter();
const identity = { threadId: "thread_interrupt_race", turnId: "turn_interrupt_race" };
let bind!: () => void;
const mayBind = new Promise<void>(resolve => { bind = resolve; });
let observedAbort = false;
const response = turns.track(async (signal, bindIdentity) => {
await mayBind;
bindIdentity(identity);
observedAbort = signal.aborted;
return new Response(new ReadableStream<Uint8Array>());
});
await waitForTurnCount(turns, 1);
expect(await turns.cancelTurn(identity)).toBe(0);
bind();
expect((await response).status).toBe(499);
expect(observedAbort).toBeTrue();
await waitForTurnCount(turns, 0);
});
test("native passthrough response and compaction requests expose their exact interrupt identity", async () => {
const config = defaultConfig("browser-only");
const responseIdentity = { threadId: "thread_native_response", turnId: "turn_native_response" };
let boundResponseIdentity: typeof responseIdentity | undefined;
const response = await responseRequest(new Request("http://127.0.0.1/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "gpt-5.6-sol",
client_metadata: {
"x-codex-turn-metadata": JSON.stringify({
thread_id: responseIdentity.threadId,
turn_id: responseIdentity.turnId,
}),
},
input: [],
}),
}), config, undefined, {
onTurnIdentity: identity => { boundResponseIdentity = identity; },
});
expect(boundResponseIdentity).toEqual(responseIdentity);
expect(response.status).toBe(502);
const compactIdentity = { threadId: "thread_native_compact", turnId: "turn_native_compact" };
let boundCompactIdentity: typeof compactIdentity | undefined;
const compact = await compactRequest(new Request("http://127.0.0.1/v1/responses/compact", {
method: "POST",
headers: {
"content-type": "application/json",
"x-codex-turn-metadata": JSON.stringify({
thread_id: compactIdentity.threadId,
turn_id: compactIdentity.turnId,
}),
},
body: JSON.stringify({ model: "gpt-5.6-sol", input: [] }),
}), config, undefined, {
onTurnIdentity: identity => { boundCompactIdentity = identity; },
});
expect(boundCompactIdentity).toEqual(compactIdentity);
expect(compact.status).toBe(502);
});
test("authenticated Interrupt hook endpoint releases the exact routed Web turn", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const threadId = "thread_interrupt_hook";
const turnId = "turn_interrupt_hook";
let adapterAborted = false;
let browserAborted = false;
let rejectBrowser!: (error: Error) => void;
const browser = new Promise<string>((_resolve, reject) => { rejectBrowser = reject; });
chatGptTurnSessions.clear();
chatGptTurnSessions.getOrCreate("interrupt-hook-browser", () => ({
mode: "read-only",
browser,
physicalSettlement: browser.then(() => undefined, () => undefined),
trace: new ChatGptTraceFeed(),
text: new ChatGptTextFeed(),
cancel: reason => {
browserAborted = true;
rejectBrowser(reason ?? new Error("native turn interrupted"));
},
}), "interrupt-hook-trace", "interrupt-hook-owner", turnId, threadId);
const server = startServer(config, {
adapterFactory: () => ({
name: "interrupt-test",
runTurn: (_parsed, incoming) => new Promise<void>((_resolve, reject) => {
incoming.abortSignal!.addEventListener("abort", () => {
adapterAborted = true;
reject(incoming.abortSignal!.reason);
}, { once: true });
}),
}),
});
const endpoint = `http://127.0.0.1:${server.port}`;
const response = fetch(`${endpoint}/v1/responses`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "chatgpt-web/high",
stream: true,
client_metadata: {
"x-codex-turn-metadata": JSON.stringify({ thread_id: threadId, turn_id: turnId }),
},
input: [{
type: "message",
role: "user",
content: [{ type: "input_text", text: "wait until interrupted" }],
internal_chat_message_metadata_passthrough: { turn_id: turnId },
}],
}),
});
try {
const deadline = Date.now() + 1_000;
let activeHttpTurns = 0;
while (Date.now() < deadline && activeHttpTurns !== 1) {
activeHttpTurns = (await (await fetch(`${endpoint}/healthz`)).json() as { active_http_turns: number }).active_http_turns;
if (activeHttpTurns !== 1) await Bun.sleep(5);
}
expect(activeHttpTurns).toBe(1);
const interrupted = await fetch(`${endpoint}/admin/interrupt-turn`, {
method: "POST",
headers: {
authorization: `Bearer ${config.controlToken}`,
"content-type": "application/json",
},
body: JSON.stringify({ threadId, turnId }),
});
expect(interrupted.status).toBe(200);
expect(await interrupted.json()).toMatchObject({
status: "ok",
cancelled_http_turns: 1,
cancelled_browser_turns: 1,
});
expect(adapterAborted).toBeTrue();
expect(browserAborted).toBeTrue();
await response;
} finally {
chatGptTurnSessions.clear();
await server.stop(true);
}
});
test("authenticated Interrupt hook endpoint also releases the exact native compaction request", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const threadId = "thread_interrupt_compact";
const turnId = "turn_interrupt_compact";
let adapterAborted = false;
const server = startServer(config, {
adapterFactory: () => ({
name: "interrupt-compact-test",
runTurn: (_parsed, incoming) => new Promise<void>((_resolve, reject) => {
incoming.abortSignal!.addEventListener("abort", () => {
adapterAborted = true;
reject(incoming.abortSignal!.reason);
}, { once: true });
}),
}),
});
const endpoint = `http://127.0.0.1:${server.port}`;
const compactResponse = fetch(`${endpoint}/v1/responses/compact`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-codex-turn-metadata": JSON.stringify({ thread_id: threadId, turn_id: turnId }),
},
body: JSON.stringify({
model: "chatgpt-web/high",
input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "compact me" }] }],
}),
});
try {
const deadline = Date.now() + 1_000;
let activeHttpTurns = 0;
while (Date.now() < deadline && activeHttpTurns !== 1) {
activeHttpTurns = (await (await fetch(`${endpoint}/healthz`)).json() as { active_http_turns: number }).active_http_turns;
if (activeHttpTurns !== 1) await Bun.sleep(5);
}
expect(activeHttpTurns).toBe(1);
const interrupted = await fetch(`${endpoint}/admin/interrupt-turn`, {
method: "POST",
headers: {
authorization: `Bearer ${config.controlToken}`,
"content-type": "application/json",
},
body: JSON.stringify({ threadId, turnId }),
});
expect(interrupted.status).toBe(200);
expect(await interrupted.json()).toMatchObject({
status: "ok",
cancelled_http_turns: 1,
cancelled_browser_turns: 0,
});
expect(adapterAborted).toBeTrue();
await compactResponse;
} finally {
await server.stop(true);
}
});
test("Interrupt acknowledges after exact browser cancellation starts without waiting for helper teardown", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const threadId = "thread_interrupt_slow_cleanup";
const turnId = "turn_interrupt_slow_cleanup";
let resolvePhysical!: () => void;
const physicalSettlement = new Promise<void>(resolve => { resolvePhysical = resolve; });
let cancelled = false;
let replacementStarted = false;
chatGptTurnSessions.clear();
chatGptTurnSessions.getOrCreate("slow-cleanup", () => ({
mode: "read-only",
browser: new Promise<string>(() => {}),
physicalSettlement,
trace: new ChatGptTraceFeed(),
text: new ChatGptTextFeed(),
cancel: () => { cancelled = true; },
}), "slow-cleanup-trace", "slow-cleanup-owner", turnId, threadId);
const server = startServer(config);
try {
const interrupted = await Promise.race([
fetch(`http://127.0.0.1:${server.port}/admin/interrupt-turn`, {
method: "POST",
headers: {
authorization: `Bearer ${config.controlToken}`,
"content-type": "application/json",
},
body: JSON.stringify({ threadId, turnId }),
}),
Bun.sleep(250).then(() => undefined),
]);
expect(interrupted).toBeInstanceOf(Response);
expect(await interrupted!.json()).toMatchObject({
status: "ok",
cancelled_browser_turns: 1,
});
expect(cancelled).toBeTrue();
const replacement = chatGptTurnSessions.getOrCreateAfterOwnerRetirement(
"slow-cleanup-replacement",
"slow-cleanup-owner",
() => {
replacementStarted = true;
return {
mode: "read-only",
browser: Promise.resolve("replacement"),
physicalSettlement: Promise.resolve(),
trace: new ChatGptTraceFeed(),
text: new ChatGptTextFeed(),
cancel: () => {},
};
},
);
await Bun.sleep(10);
expect(replacementStarted).toBeFalse();
resolvePhysical();
await replacement;
expect(replacementStarted).toBeTrue();
} finally {
resolvePhysical();
chatGptTurnSessions.clear();
await server.stop(true);
}
});
test("Interrupt retires a logically complete browser turn whose helper is still physically stuck", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const threadId = "thread_interrupt_logical_complete";
const turnId = "turn_interrupt_logical_complete";
let resolvePhysical!: () => void;
const physicalSettlement = new Promise<void>(resolve => { resolvePhysical = resolve; });
let cancelled = false;
chatGptTurnSessions.clear();
const session = chatGptTurnSessions.getOrCreate("logical-complete", () => ({
mode: "read-only",
browser: Promise.resolve("complete"),
physicalSettlement,
trace: new ChatGptTraceFeed(),
text: new ChatGptTextFeed(),
cancel: () => { cancelled = true; },
}), "logical-complete-trace", "logical-complete-owner", turnId, threadId);
await session.browserOutcome;
expect(session.isActive()).toBeFalse();
expect(session.isPhysicallySettled()).toBeFalse();
const server = startServer(config);
try {
const interrupted = await fetch(`http://127.0.0.1:${server.port}/admin/interrupt-turn`, {
method: "POST",
headers: {
authorization: `Bearer ${config.controlToken}`,
"content-type": "application/json",
},
body: JSON.stringify({ threadId, turnId }),
});
expect(await interrupted.json()).toMatchObject({
status: "ok",
cancelled_browser_turns: 1,
});
expect(cancelled).toBeTrue();
expect(chatGptTurnSessions.find("logical-complete")).toBeUndefined();
} finally {
resolvePhysical();
chatGptTurnSessions.clear();
await server.stop(true);
}
});
test("Interrupt cancels a detached structured compaction by exact native turn identity", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const threadId = "thread_interrupt_structured";
const turnId = "turn_interrupt_structured";
let aborted = false;
const run = runStructuredCompactionOnce(
`interrupt-structured-${Date.now()}-${Math.random()}`,
{
ownerKey: "interrupt-structured-owner",
traceIds: ["interrupt-structured-trace"],
nativeThreadId: threadId,
nativeTurnId: turnId,
},
signal => new Promise<string>((_resolve, reject) => {
signal.addEventListener("abort", () => {
aborted = true;
reject(signal.reason);
}, { once: true });
}),
);
const server = startServer(config);
try {
await Bun.sleep(0);
const interrupted = await fetch(`http://127.0.0.1:${server.port}/admin/interrupt-turn`, {
method: "POST",
headers: {
authorization: `Bearer ${config.controlToken}`,
"content-type": "application/json",
},
body: JSON.stringify({ threadId, turnId }),
});
expect(await interrupted.json()).toMatchObject({
status: "ok",
cancelled_compaction_runs: 1,
});
await expect(run).rejects.toThrow("Codex turn interrupted");
expect(aborted).toBeTrue();
} finally {
await server.stop(true);
}
});
test("authenticated lifecycle control cancels orphaned browser turns", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const server = startServer(config);
let cancelled = 0;
chatGptTurnSessions.clear();
chatGptTurnSessions.getOrCreate("orphan", () => ({
mode: "read-only",
browser: new Promise<string>(() => {}),
physicalSettlement: Promise.resolve(),
trace: new ChatGptTraceFeed(),
text: new ChatGptTextFeed(),
cancel: () => { cancelled += 1; },
}));
try {
const unauthorized = await fetch(`http://127.0.0.1:${server.port}/admin/cancel-turns`, {
method: "POST",
headers: { authorization: "Bearer invalid" },
});
expect(unauthorized.status).toBe(401);
expect(chatGptTurnSessions.activeCount()).toBe(1);
const response = await fetch(`http://127.0.0.1:${server.port}/admin/cancel-turns`, {
method: "POST",
headers: { authorization: `Bearer ${config.controlToken}` },
});
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
status: "ok",
cancelled_http_turns: 0,
cancelled_browser_turns: 1,
active_http_turns: 0,
active_browser_turns: 0,
});
expect(cancelled).toBe(1);
expect(chatGptTurnSessions.activeCount()).toBe(0);
} finally {
chatGptTurnSessions.clear();
await server.stop(true);
}
});
test("authenticated targeted cancellation terminates one browser trace without reopening it", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const server = startServer(config);
chatGptTurnSessions.clear();
let rejectTarget!: (error: Error) => void;
let targetCancelled = 0;
let otherCancelled = 0;
const targetBrowser = new Promise<string>((_resolve, reject) => { rejectTarget = reject; });
const target = chatGptTurnSessions.getOrCreate("target-key", () => ({
mode: "read-only",
browser: targetBrowser,
physicalSettlement: targetBrowser.then(() => undefined, () => undefined),
trace: new ChatGptTraceFeed(),
text: new ChatGptTextFeed(),
cancel: () => {
targetCancelled += 1;
rejectTarget(new Error("tab closed"));
},
}), "trace_target");
chatGptTurnSessions.getOrCreate("other-key", () => ({
mode: "read-only",
browser: new Promise<string>(() => {}),
physicalSettlement: Promise.resolve(),
trace: new ChatGptTraceFeed(),
text: new ChatGptTextFeed(),
cancel: () => { otherCancelled += 1; },
}), "trace_other");
try {
const unauthorized = await fetch(`http://127.0.0.1:${server.port}/admin/cancel-turn`, {
method: "POST",
headers: { "content-type": "application/json", authorization: "Bearer invalid" },
body: JSON.stringify({ traceId: "trace_target" }),
});
expect(unauthorized.status).toBe(401);
const response = await fetch(`http://127.0.0.1:${server.port}/admin/cancel-turn`, {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${config.controlToken}`,
},
body: JSON.stringify({ traceId: "trace_target" }),
});
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
status: "ok",
trace_id: "trace_target",
cancelled_browser_turns: 1,
cancelled_broker_turns: 0,
active_browser_turns: 1,
});
expect(targetCancelled).toBe(1);
expect(otherCancelled).toBe(0);
expect(target.settledOutcome()).toMatchObject({ type: "error" });
expect(chatGptTurnSessions.getOrCreate("target-key", () => {
throw new Error("cancelled trace must remain terminal");
}, "trace_target")).toBe(target);
} finally {
chatGptTurnSessions.clear();
await server.stop(true);
}
});
test("authenticated targeted cancellation aborts a shared structured compaction owner", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const server = startServer(config);
const handoffTraceId = "a1b2c3d4e5f6";
const traceId = `${handoffTraceId}_fallback`;
let aborted = false;
const run = runStructuredCompactionOnce(
`structured-${Date.now()}-${Math.random()}`,
{ ownerKey: `owner-${traceId}`, traceIds: [handoffTraceId, traceId] },
signal => new Promise<string>((_resolve, reject) => {
signal.addEventListener("abort", () => {
aborted = true;
reject(signal.reason);
}, { once: true });
}),
);
try {
await Bun.sleep(0);
const response = await fetch(`http://127.0.0.1:${server.port}/admin/cancel-turn`, {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${config.controlToken}`,
},
body: JSON.stringify({ traceId }),
});
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
status: "ok",
trace_id: traceId,
cancelled_compaction_runs: 1,
});
await expect(run).rejects.toThrow("The ChatGPT browser tab was closed");
expect(aborted).toBeTrue();
} finally {
await server.stop(true);
}
});
test("authenticated cancel-all aborts fresh structured compaction work", async () => {
const config = { ...defaultConfig("browser-only"), port: 0 };
const server = startServer(config);
const key = `structured-all-${Date.now()}-${Math.random()}`;
let aborted = false;
const run = runStructuredCompactionOnce(
key,
{ ownerKey: `owner-${key}`, traceIds: [`trace-${key}`] },
signal => new Promise<string>((_resolve, reject) => {
signal.addEventListener("abort", () => {
aborted = true;
reject(signal.reason);
}, { once: true });
}),
);
try {
await Bun.sleep(0);
const response = await fetch(`http://127.0.0.1:${server.port}/admin/cancel-turns`, {
method: "POST",
headers: { authorization: `Bearer ${config.controlToken}` },
});
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
status: "ok",
cancelled_compaction_runs: 1,
});
await expect(run).rejects.toThrow("Active turn cancelled by launcher");
expect(aborted).toBeTrue();
} finally {
await server.stop(true);
}
});
test("a Codex retry after tab cancellation receives terminal HTTP 400 without a new browser", async () => {
const config = defaultConfig("browser-only");
const turnId = "turn_cancelled_replay";
const body = {
model: "chatgpt-web/high",
stream: true,
client_metadata: {
"x-codex-turn-metadata": JSON.stringify({
thread_id: "thread_cancelled_replay",
turn_id: turnId,
}),
},
input: [{
type: "message",
role: "user",
content: [{ type: "input_text", text: "Run until the browser tab is closed" }],
internal_chat_message_metadata_passthrough: { turn_id: turnId },
}],
};
const parsed = parseRequest(body);
routeChatGptWebRequest(parsed, config);
const traceId = chatGptWebTraceId(providerConfig(config), parsed);
let rejectBrowser!: (error: Error) => void;
chatGptTurnSessions.clear();
const cancelledBrowser = new Promise<string>((_resolve, reject) => { rejectBrowser = reject; });
chatGptTurnSessions.getOrCreate("cancelled-replay", () => ({
mode: "read-only",
browser: cancelledBrowser,
physicalSettlement: cancelledBrowser.then(() => undefined, () => undefined),
trace: new ChatGptTraceFeed(),
text: new ChatGptTextFeed(),
cancel: reason => rejectBrowser(reason ?? new Error("cancelled")),
}), traceId);
try {
expect(await chatGptTurnSessions.cancelTrace(traceId)).toBe(1);
expect(chatGptTurnSessions.cancelledError(traceId)?.message).toContain("Codex turn was cancelled");
let adapterConstructions = 0;
const response = await responseRequest(new Request("http://127.0.0.1:17841/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
}), config, () => {
adapterConstructions += 1;
throw new Error("cancelled turn must not construct a new browser adapter");
});
expect(response.status).toBe(400);
expect(await response.json()).toEqual({
error: {
type: "client_closed_request",
code: "client_cancelled",
message: "The ChatGPT browser tab was closed, so the Codex turn was cancelled.",
},
});
expect(adapterConstructions).toBe(0);
} finally {
chatGptTurnSessions.clear();
}
});
test("a restart recovery turn without a new user instruction fails terminally instead of replaying the stopped prompt", async () => {
const config = defaultConfig("browser-only");
const previousTurnId = "turn_before_codex_restart";
const recoveryTurnId = "turn_after_codex_restart";
const body = {
model: "chatgpt-web/high",
stream: true,
client_metadata: {
"x-codex-turn-metadata": JSON.stringify({
thread_id: "thread_codex_restart",
turn_id: recoveryTurnId,
}),
},
input: [
{
type: "message",
role: "user",
content: [{ type: "input_text", text: "Run the original task" }],
internal_chat_message_metadata_passthrough: { turn_id: previousTurnId },
},
{
type: "message",
role: "developer",
content: [{ type: "input_text", text: "<skills_instructions>fresh skills</skills_instructions>" }],
internal_chat_message_metadata_passthrough: { turn_id: recoveryTurnId },
},
],
};
let adapterConstructions = 0;
const response = await responseRequest(new Request("http://127.0.0.1:17841/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
}), config, () => {
adapterConstructions += 1;
throw new Error("a context-only recovery turn must not construct a browser adapter");
});
expect(response.status).toBe(400);
expect(await response.json()).toEqual({
error: {
code: "invalid_request_error",
type: "invalid_request_error",
message: "ChatGPT web current user message conflicts with native Codex turn_id metadata",
},
});
expect(adapterConstructions).toBe(0);
});
test("a retryable failed turn can hand the exact user instruction to one successor turn", async () => {
const config = defaultConfig("browser-only");
const threadId = "thread_retry_turn_handoff";
const failedTurnId = "turn_retry_handoff_failed";
const retryTurnId = "turn_retry_handoff_successor";
const instruction = {
id: "msg_retry_handoff",
type: "message",
role: "user",
content: [{ type: "input_text", text: "Keep working after model capacity recovers" }],
internal_chat_message_metadata_passthrough: { turn_id: failedTurnId },
};
const body = (turnId: string) => ({
model: "chatgpt-web/high",
stream: false,
client_metadata: {
"x-codex-turn-metadata": JSON.stringify({ thread_id: threadId, turn_id: turnId }),
},
input: [instruction],
});
let attempts = 0;
const adapterFactory = (): ProviderAdapter => ({
name: "retry-handoff-test",
runTurn: async (parsed, _incoming, emit) => {
attempts += 1;
if (attempts === 1) {
emit({
type: "error",
message: "Selected model is at capacity. Please try a different model.",
status: 503,
errorType: "server_error",
code: "server_is_overloaded",
retryable: true,
});