File size: 24,624 Bytes
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import json
import os
import sys
import tomllib
import uuid
from dataclasses import dataclass, field
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock

import pytest

from free_claude_code.application.code_sessions import CodeService
from free_claude_code.application.code_sessions.models import (
    CodeConflictError,
    CodeUnavailableError,
)
from free_claude_code.application.model_metadata import ProviderModelInfo
from free_claude_code.application.ports import ModelCatalogSnapshot, RequestRuntimePort
from free_claude_code.config.paths import launcher_temp_dir_path
from free_claude_code.config.settings import Settings
from free_claude_code.core.gateway_model_ids import no_thinking_gateway_model_id
from free_claude_code.runtime.code_sessions_sqlite import SQLiteCodeStore
from free_claude_code.runtime.codex_app_server import (
    CodexAppServer,
    CodexHarnessFactory,
)
from tests.code_sessions_support import FakeHarness, close_code_database


@dataclass
class FactoryPeer:
    mode: str = "factory-ready"
    command: tuple[str, ...] = ()
    env: dict[str, str] = field(default_factory=dict, repr=False)
    catalog: Path | None = None
    process: asyncio.subprocess.Process | None = None


@pytest.fixture
def factory_peer(tmp_path, monkeypatch):
    peer = FactoryPeer()
    spawn = asyncio.create_subprocess_exec

    async def start(*command, **kwargs):
        if command[0] != "test-codex":
            return await spawn(*command, **kwargs)
        peer.command, peer.env = command, dict(kwargs["env"])
        config = tomllib.loads(
            "\n".join(command[i + 1] for i, arg in enumerate(command) if arg == "-c")
        )
        path = config.get("model_catalog_json")
        peer.catalog = Path(path) if path else None
        peer.process = await spawn(
            sys.executable,
            str(Path(__file__).with_name("codex_fake_process.py")),
            peer.mode,
            path or "",
            str(tmp_path / "catalog-at-exit.json"),
            **kwargs,
        )
        return peer.process

    monkeypatch.setattr(asyncio, "create_subprocess_exec", start)
    return peer


@pytest.fixture
def factory_runtime():
    runtime = MagicMock(spec=RequestRuntimePort)
    runtime.current_settings.return_value = Settings(
        model="nvidia_nim/default", port=8182, proxy_auth_token="factory-token"
    )
    runtime.cached_model_info.return_value = None
    runtime.cached_prefixed_model_infos.return_value = (
        ProviderModelInfo(
            "open_router/selected", supports_thinking=False, context_window_tokens=32000
        ),
    )
    runtime.wait_for_model_catalog.return_value = ModelCatalogSnapshot(
        runtime.current_settings(), runtime.cached_prefixed_model_infos()
    )
    runtime.acquire.side_effect = AssertionError("Setup must not acquire a provider")
    return runtime


@pytest.mark.asyncio
async def test_factory_open_preserves_setup_and_catalog_until_process_exit(
    tmp_path, factory_peer, factory_runtime
):
    env = dict(os.environ) | {
        "CODEX_HOME": str(tmp_path / "codex-home"),
        "CODEX_THREAD_ID": "parent-thread",
        "OPENAI_API_KEY": "parent-token",
        "OPENAI_CUSTOM": "parent-route",
        "KEEP_ME": "yes",
    }
    before = dict(env)
    factory = CodexHarnessFactory(factory_runtime, binary="test-codex", env=env)
    selection = await factory.prepare("open_router/selected", None, "config")
    native = await selection.open(str(tmp_path), AsyncMock())
    try:
        config = tomllib.loads(
            "\n".join(
                factory_peer.command[i + 1]
                for i, arg in enumerate(factory_peer.command)
                if arg == "-c"
            )
        )
        assert config["model"] == no_thinking_gateway_model_id(selection.model)
        assert config["model_providers"]["fcc"] == {
            "name": "Free Claude Code",
            "base_url": "http://127.0.0.1:8182/v1",
            "auth": {"command": "fcc-codex", "args": ["--print-proxy-auth-token"]},
            "wire_api": "responses",
            "stream_idle_timeout_ms": 2147483647,
        }
        assert factory_peer.command[-5:] == (
            "-c",
            "features.default_mode_request_user_input=true",
            "-c",
            "tools.experimental_request_user_input.enabled=true",
            "app-server",
        )
        assert factory_peer.env["CODEX_HOME"] == env["CODEX_HOME"]
        assert factory_peer.env["KEEP_ME"] == "yes"
        assert "CODEX_THREAD_ID" not in factory_peer.env
        assert not any(key.startswith("OPENAI_") for key in factory_peer.env)
        assert "127.0.0.1" in factory_peer.env["NO_PROXY"].split(",")
        assert env == before
        assert factory_peer.catalog is not None
        catalog = json.loads(factory_peer.catalog.read_text())
        assert any(model["slug"] == config["model"] for model in catalog["models"])
        assert "factory-token" not in factory_peer.catalog.read_text()
        assert native.process.returncode is None
    finally:
        await native.close()
    assert native.process.returncode == 0
    assert json.loads((tmp_path / "catalog-at-exit.json").read_text()) == catalog
    assert not factory_peer.catalog.parent.exists()


@pytest.mark.asyncio
@pytest.mark.parametrize("failure", ["reject", "cancel"])
async def test_factory_initialization_failure_reaps_before_catalog_cleanup(
    tmp_path, monkeypatch, factory_peer, factory_runtime, failure
):
    factory_peer.mode = "factory-fail" if failure == "reject" else "factory-wait"
    initialized = asyncio.Event()
    write = CodexAppServer._write

    async def observe_write(native, message):
        await write(native, message)
        if message.get("method") == "initialize":
            initialized.set()

    monkeypatch.setattr(CodexAppServer, "_write", observe_write)
    factory = CodexHarnessFactory(factory_runtime, binary="test-codex")
    selection = await factory.prepare("open_router/selected", None, "config")
    opening = asyncio.create_task(selection.open(str(tmp_path), AsyncMock()))
    try:
        await asyncio.wait_for(initialized.wait(), 3)
        if failure == "cancel":
            opening.cancel()
        error = asyncio.CancelledError if failure == "cancel" else CodeConflictError
        with pytest.raises(error):
            await asyncio.wait_for(opening, 8)
    finally:
        if not opening.done():
            opening.cancel()
        await asyncio.gather(opening, return_exceptions=True)
    assert factory_peer.process.returncode == 0
    assert json.loads((tmp_path / "catalog-at-exit.json").read_text())["models"]
    assert not factory_peer.catalog.parent.exists()


@pytest.mark.asyncio
async def test_history_open_needs_no_fcc_setup_or_inventory(tmp_path, factory_peer):
    runtime = MagicMock(spec=RequestRuntimePort)
    for name in (
        "current_settings",
        "cached_model_info",
        "cached_prefixed_model_infos",
    ):
        getattr(runtime, name).side_effect = AssertionError(
            "History needs no inventory"
        )
    env = dict(os.environ) | {"CODEX_THREAD_ID": "parent", "OPENAI_API_KEY": "keep"}
    factory = CodexHarnessFactory(runtime, binary="test-codex", env=env)
    native = await factory.open_history(str(tmp_path), AsyncMock())
    try:
        assert factory_peer.command == ("test-codex", "app-server")
        assert factory_peer.env == env
        assert factory_peer.catalog is None
        assert not launcher_temp_dir_path().exists()
    finally:
        await native.close()
    assert native.process.returncode == 0
    assert json.loads((tmp_path / "catalog-at-exit.json").read_text()) is None


@pytest.mark.asyncio
async def test_child_warning_during_shutdown_allows_connection_replacement(
    database_factory, tmp_path, monkeypatch
):
    harness = FakeHarness()
    prepare = harness.prepare
    connections = []
    releases = []
    warning = asyncio.Event()

    async def selection_for(model, effort, mode):
        selection = await prepare(model, effort, mode)

        async def open_native(cwd, sink):
            release = tmp_path / f"release-{len(connections)}"
            releases.append(release)

            async def receive(event):
                await sink(event)
                if event.kind == "notice" and event.thread_id == "child":
                    warning.set()

            native = CodexAppServer(
                [
                    sys.executable,
                    str(Path(__file__).with_name("codex_fake_process.py")),
                    "child-warning-on-close",
                    str(release),
                ],
                dict(os.environ),
                cwd,
                receive,
                model_slugs={model: model},
                fingerprints=selection.catalog,
            )
            await native.start()
            connections.append(native)
            return native

        monkeypatch.setattr(selection, "open", open_native)
        return selection

    monkeypatch.setattr(harness, "prepare", selection_for)
    service = CodeService(
        SQLiteCodeStore(database_factory(tmp_path / "code.db", tmp_path / "code.lock")),
        harness,
    )
    await service.start()
    observing = asyncio.create_task(warning.wait())
    try:
        session = await service.create_session(str(uuid.uuid4()), str(tmp_path))
        await service.send(
            session.id,
            str(uuid.uuid4()),
            session.revision,
            "First",
            expected_epoch=service.epoch,
        )
        await asyncio.wait_for(service.wait_idle(session.id), 3)
        first = await service.get_detail(session.id)
        assert first.run is not None
        assert first.run.status == "completed"
        harness.configurations[harness.model] = "replacement"
        await service.send(
            session.id,
            str(uuid.uuid4()),
            first.session.revision,
            "Next",
            expected_epoch=service.epoch,
        )
        dispatcher = connections[0]._dispatcher
        assert dispatcher is not None
        processed, _ = await asyncio.wait(
            (observing, dispatcher), timeout=3, return_when=asyncio.FIRST_COMPLETED
        )
        assert processed, "The close-time warning was never processed"
        releases[0].touch()
        await asyncio.wait_for(service.wait_idle(session.id), 3)
        detail = await service.get_detail(session.id)
        assert detail.run is not None
        assert detail.run.status == "completed", detail.run.error
        assert len(connections) == 2 and connections[0].process.returncode is not None
        assert all(item.kind != "notice" for item in detail.items)
    finally:
        for release in releases:
            release.touch()
        observing.cancel()
        await asyncio.gather(observing, return_exceptions=True)
        await service.close()
        await close_code_database(service)


@pytest.mark.asyncio
@pytest.mark.parametrize("profile", [None, {"id": "custom"}])
async def test_complete_mode_overrides_restore_native_defaults(
    tmp_path, monkeypatch, profile
):
    defaults = {
        "approvalPolicy": {"granular": {"sandbox_approval": True, "rules": False}},
        "approvalsReviewer": "user",
        "activePermissionProfile": profile,
        "sandbox": {
            "type": "workspaceWrite",
            "writableRoots": [str(tmp_path / "extra")],
            "networkAccess": True,
            "excludeTmpdirEnvVar": True,
            "excludeSlashTmp": True,
        },
    }
    native = CodexAppServer(
        [],
        {},
        str(tmp_path),
        AsyncMock(),
        model_slugs={"provider/model": "native-slug"},
    )
    rpc = AsyncMock(return_value={"thread": {"id": "native", "turns": []}, **defaults})
    monkeypatch.setattr(native, "rpc", rpc)
    thread = await native.create_thread()
    assert thread.permission_defaults == defaults
    assert rpc.call_args.args[1] == {"cwd": str(tmp_path), "modelProvider": "fcc"}
    rpc.return_value = {"turn": {"id": "turn"}}
    harness = FakeHarness()
    expected = {
        "ask": {
            "approvalPolicy": "on-request",
            "approvalsReviewer": "user",
            "permissions": ":workspace",
        },
        "auto_review": {
            "approvalPolicy": "on-request",
            "approvalsReviewer": "auto_review",
            "permissions": ":workspace",
        },
        "full_access": {
            "approvalPolicy": "never",
            "approvalsReviewer": "user",
            "permissions": ":danger-full-access",
        },
        "config": {
            "approvalPolicy": defaults["approvalPolicy"],
            "approvalsReviewer": "user",
            **(
                {"permissions": "custom"}
                if profile
                else {"sandboxPolicy": defaults["sandbox"]}
            ),
        },
    }
    for mode in ("ask", "auto_review", "full_access", "config"):
        selection = await harness.prepare(harness.model, "high", mode)
        await native.start_turn("hello", selection, "input", thread.permission_defaults)
        params = rpc.call_args.args[1]
        assert {
            key: value
            for key, value in params.items()
            if key
            in {"approvalPolicy", "approvalsReviewer", "permissions", "sandboxPolicy"}
        } == expected[mode]
        assert params["model"] == "native-slug" and params["effort"] == "high"


@pytest.mark.asyncio
async def test_missing_native_permission_settings_rejects_thread_preparation(
    tmp_path, monkeypatch
):
    native = CodexAppServer([], {}, str(tmp_path), AsyncMock())
    monkeypatch.setattr(
        native, "rpc", AsyncMock(return_value={"thread": {"id": "native", "turns": []}})
    )
    with pytest.raises(CodeUnavailableError, match="permission"):
        await native.create_thread()


async def connect(tmp_path, mode):
    events = []
    completed = asyncio.Event()
    prompted = asyncio.Event()

    async def receive(event):
        events.append(event)
        if event.kind == "turn_completed":
            completed.set()
        if event.kind == "prompt":
            prompted.set()

    native = CodexAppServer(
        [sys.executable, str(Path(__file__).with_name("codex_fake_process.py")), mode],
        dict(os.environ),
        str(tmp_path),
        receive,
        model_slugs={"provider/model": "provider/model"},
        fingerprints={"provider/model": "capabilities-1"},
    )
    await native.start()
    return native, events, completed, prompted


@pytest.mark.asyncio
async def test_jsonl_sink_preserves_usage_before_turn_completion(tmp_path):
    events = []
    usage_received = asyncio.Event()
    release_usage = asyncio.Event()
    completed = asyncio.Event()

    async def receive(event):
        events.append(event.kind)
        if event.kind == "context_usage":
            usage_received.set()
            await release_usage.wait()
        elif event.kind == "turn_completed":
            completed.set()

    native = CodexAppServer(
        [
            sys.executable,
            str(Path(__file__).with_name("codex_fake_process.py")),
            "ordered-usage",
        ],
        dict(os.environ),
        str(tmp_path),
        receive,
        model_slugs={"provider/model": "provider/model"},
        fingerprints={"provider/model": "capabilities-1"},
    )
    try:
        await native.start()
        await native.create_thread()
        turn_id = await native.start_turn(
            "hello",
            (await FakeHarness().prepare("provider/model", None, "config")),
            "input-1",
            FakeHarness().permission_defaults,
        )
        assert turn_id == "turn-1"
        await asyncio.wait_for(usage_received.wait(), 3)
        assert not completed.is_set()
        release_usage.set()
        await asyncio.wait_for(completed.wait(), 3)
        assert [
            kind for kind in events if kind in {"context_usage", "turn_completed"}
        ] == ["context_usage", "turn_completed"]
    finally:
        release_usage.set()
        await native.close()


@pytest.mark.asyncio
async def test_jsonl_large_unicode_events_can_precede_rpc_ack(tmp_path):
    native, events, completed, _ = await connect(tmp_path, "large")
    try:
        assert (await native.create_thread()).id == "native-1"
        assert (
            await native.start_turn(
                "hello",
                (await FakeHarness().prepare("provider/model", None, "config")),
                "input-1",
                FakeHarness().permission_defaults,
            )
            == "turn-1"
        )
        await asyncio.wait_for(completed.wait(), 3)
        texts = [
            event.item.text for event in events if event.item and event.item.complete
        ]
        assert texts == ["snow ☃ " * 16000]
    finally:
        await native.close()


@pytest.mark.asyncio
async def test_terminal_storage_failure_drains_the_native_dispatcher(
    database_factory, tmp_path, monkeypatch
):
    harness = FakeHarness()
    prepare = harness.prepare
    connections = []

    async def select(model, effort, mode):
        selection = await prepare(model, effort, mode)

        async def open_native(cwd, sink):
            native = CodexAppServer(
                [
                    sys.executable,
                    str(Path(__file__).with_name("codex_fake_process.py")),
                    "large",
                ],
                dict(os.environ),
                cwd,
                sink,
                model_slugs={model: model},
                fingerprints=selection.catalog,
            )
            await native.start()
            connections.append(native)
            return native

        monkeypatch.setattr(selection, "open", open_native)
        return selection

    monkeypatch.setattr(harness, "prepare", select)
    store = SQLiteCodeStore(
        database_factory(tmp_path / "code.db", tmp_path / "code.lock")
    )
    save = store.save_progress
    rejected = []

    async def reject_terminal(session, revision, **values):
        run = values.get("run")
        if run is not None and run.status == "completed":
            rejected.append(run)
            raise CodeUnavailableError("Terminal commit failed")
        await save(session, revision, **values)

    monkeypatch.setattr(store, "save_progress", reject_terminal)
    service = CodeService(store, harness)
    await service.start()
    try:
        session = await service.create_session(str(uuid.uuid4()), str(tmp_path))
        await service.send(
            session.id,
            str(uuid.uuid4()),
            session.revision,
            "hello",
            expected_epoch=service.epoch,
        )
        await asyncio.wait_for(service.wait_idle(session.id), 5)
        assert len(rejected) == 1 and len(connections) == 1
        native = connections[0]
        assert native.process.returncode is not None
        assert native._reader.done() and native._dispatcher.done()
        saved = await store.latest_run(session.id)
        assert saved is not None and saved.status == "running"
        with pytest.raises(CodeUnavailableError):
            await service.get_detail(session.id)
    finally:
        await asyncio.wait_for(service.close(), 5)
        await close_code_database(service)


@pytest.mark.asyncio
async def test_server_rpc_during_start_preserves_numeric_zero_id(tmp_path):
    native, events, completed, prompted = await connect(tmp_path, "prompt")
    try:
        await native.create_thread()
        await native.start_turn(
            "hello",
            (await FakeHarness().prepare("provider/model", None, "config")),
            "input-1",
            FakeHarness().permission_defaults,
        )
        await asyncio.wait_for(prompted.wait(), 3)
        response = native.prepare_answer(0, {"choice": "0"})
        await native.respond(0, response)
        await asyncio.wait_for(completed.wait(), 3)
        assert any(event.item and event.item.text == "accept" for event in events)
        assert any(
            event.kind == "resolved" and event.request_id == 0 for event in events
        )
    finally:
        await native.close()


@pytest.mark.asyncio
async def test_cancelled_creation_waiter_retains_late_native_identity(tmp_path):
    native, _, _, _ = await connect(tmp_path, "delayed-create")
    try:
        creation = asyncio.create_task(native.create_thread())
        await native.rpc("test/barrier", {})
        creation.cancel()
        with pytest.raises(asyncio.CancelledError):
            await creation
        await native.rpc("test/release-create", {})
        assert native.thread_id == "native-1"
    finally:
        await native.close()


@pytest.mark.asyncio
async def test_eof_completes_pending_calls_and_cleanup(tmp_path):
    native, _, _, _ = await connect(tmp_path, "large")
    try:
        with pytest.raises(CodeUnavailableError):
            await native.rpc("test/eof", {})
    finally:
        await native.close()
    assert native.process.returncode is not None


@pytest.mark.asyncio
@pytest.mark.parametrize("method", ["test/malformed", "test/malformed-flood"])
async def test_malformed_frame_reports_closed_only_after_process_termination(
    tmp_path, method
):
    closed = asyncio.Event()
    returncodes = []

    async def receive(event):
        if event.kind == "closed":
            returncodes.append(native.process.returncode)
            closed.set()

    native = CodexAppServer(
        [
            sys.executable,
            str(Path(__file__).with_name("codex_fake_process.py")),
            "large",
        ],
        dict(os.environ),
        str(tmp_path),
        receive,
    )
    try:
        await native.start()
        with pytest.raises(CodeUnavailableError):
            await native.rpc(method, {})
        await asyncio.wait_for(closed.wait(), 8)
        assert returncodes and returncodes[0] is not None
        assert native.process.stdout is not None and native.process.stdout.at_eof()
    finally:
        if native.process.stdout is not None and not native.process.stdout.at_eof():
            await native.process.stdout.read()
        await native.close()


@pytest.mark.asyncio
async def test_spawned_agent_prompt_is_visible_in_its_registered_root_session(tmp_path):
    native, events, completed, prompted = await connect(tmp_path, "child-prompt")
    try:
        await native.create_thread()
        await native.start_turn(
            "delegate",
            (await FakeHarness().prepare("provider/model", None, "config")),
            "input-1",
            FakeHarness().permission_defaults,
        )
        await asyncio.wait_for(prompted.wait(), 3)
        event = next(event for event in events if event.kind == "prompt")
        assert event.thread_id == "native-1"
        assert event.prompt.turn_id is None
        assert event.prompt.raw["threadId"] == "child-1"
        await native.respond(0, native.prepare_answer(0, {"choice": "0"}))
        await asyncio.wait_for(completed.wait(), 3)
    finally:
        await native.close()


@pytest.mark.asyncio
@pytest.mark.parametrize("reasoning", [True, False])
async def test_turn_start_resets_sticky_effort_and_preserves_client_identity(
    tmp_path, monkeypatch, reasoning
):
    async def receive(event):
        pass

    native = CodexAppServer(
        [],
        {},
        str(tmp_path),
        receive,
        model_slugs={"provider/model": "native-slug"},
        reasoning={"provider/model": reasoning},
    )
    native.thread_id = "thread"
    requests = []

    async def rpc(method, params):
        assert method == "turn/start"
        requests.append(params)
        return {"turn": {"id": "turn"}}

    monkeypatch.setattr(native, "rpc", rpc)
    harness = FakeHarness()
    for effort in (None, "high", "off", "max", None):
        await native.start_turn(
            "hello",
            (await harness.prepare("provider/model", effort, "config")),
            "operation",
            harness.permission_defaults,
        )
    assert [request.get("effort") for request in requests] == (
        ["medium", "high", "none", "max", "medium"] if reasoning else [None] * 5
    )
    assert [request.get("summary") for request in requests] == (
        ["auto", "auto", "none", "auto", "auto"] if reasoning else [None] * 5
    )
    assert all(
        request["clientUserMessageId"] == "operation"
        and request["model"] == "native-slug"
        for request in requests
    )