forked from omnigent-ai/omnigent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_codex_native.py
More file actions
9872 lines (8652 loc) · 346 KB
/
Copy pathtest_codex_native.py
File metadata and controls
9872 lines (8652 loc) · 346 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
"""Tests for the native Codex wrapper helpers."""
from __future__ import annotations
import asyncio
import json
import os
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import click
import httpx
import pytest
import yaml
from omnigent import codex_native, codex_native_app_server, codex_native_forwarder
from omnigent._runner_startup import RunnerStartupProgress
from omnigent.codex_native_bridge import (
CodexNativeBridgeState,
clear_bridge_state,
read_bridge_state,
write_bridge_state,
)
from omnigent.codex_native_elicitation import codex_elicitation_id
from omnigent.spec import load
def _write_codex_auth(path: Path, payload: object) -> None:
"""Write a test Codex auth.json payload."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload), encoding="utf-8")
def _point_codex_auth_check_at(
monkeypatch: pytest.MonkeyPatch,
auth_path: Path,
*,
binary_present: bool,
launch: Any | None = None,
) -> None:
"""Redirect Codex availability checks away from the real machine state.
``launch`` pins what :func:`resolve_native_codex_launch` returns; the default
is the defer-to-Codex-login shape (``profile=None``, ``model_provider`` not
set → resolves to ``"openai"``), which is exactly the case where
``auth.json`` is the credential that decides availability. Provider-routed
tests pass an explicit launch.
"""
if launch is None:
launch = codex_native_app_server.NativeCodexLaunch(
config_overrides=[], model=None, profile=None
)
monkeypatch.setattr(codex_native, "resolve_native_codex_launch", lambda model=None: launch)
monkeypatch.setattr(
codex_native,
"_resolve_codex_auth_source",
lambda: codex_native._CodexAuthSource(auth_path=auth_path),
)
monkeypatch.setattr(
codex_native.shutil,
"which",
lambda name: f"/tmp/{name}" if binary_present else None,
)
def test_codex_auth_unavailable_reason_binary_missing(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Missing codex binary reports binary-missing before reading auth.json."""
auth_path = tmp_path / "codex-home" / "auth.json"
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=False)
assert codex_native._codex_auth_unavailable_reason() == "binary-missing"
def test_codex_auth_unavailable_reason_absent_auth_json_needs_auth(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Installed codex without auth.json reports needs-auth."""
auth_path = tmp_path / "codex-home" / "auth.json"
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=True)
assert codex_native._codex_auth_unavailable_reason() == "needs-auth"
def test_codex_auth_unavailable_reason_chatgpt_tokens_available(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A real ChatGPT/OAuth auth.json (tokens block) is available.
Mirrors the openai/codex ``AuthDotJson`` shape: ``auth_mode=chatgpt`` with a
``tokens`` object. There is no top-level expiry field — access-token expiry
lives in the JWT and is refreshed via ``refresh_token`` — so presence of the
tokens is what marks the credential configured.
"""
auth_path = tmp_path / "codex-home" / "auth.json"
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=True)
_write_codex_auth(
auth_path,
{
"auth_mode": "chatgpt",
"tokens": {
"id_token": "header.payload.sig",
"access_token": "header.payload.sig",
"refresh_token": "opaque-refresh",
"account_id": "org_test",
},
"last_refresh": "2026-06-25T15:04:05Z",
},
)
assert codex_native._codex_auth_unavailable_reason() is None
def test_codex_auth_unavailable_reason_api_key_available(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A real API-key auth.json (``auth_mode=api``) is available."""
auth_path = tmp_path / "codex-home" / "auth.json"
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=True)
_write_codex_auth(auth_path, {"auth_mode": "api", "OPENAI_API_KEY": "sk-test"})
assert codex_native._codex_auth_unavailable_reason() is None
def test_codex_auth_unavailable_reason_no_credential_needs_auth(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A parseable auth.json with no credential field reports needs-auth.
e.g. a stub that records ``auth_mode`` but carries neither an
``OPENAI_API_KEY`` nor a ``tokens`` block — there is nothing to authenticate
with, so the picker should warn rather than show Codex as ready.
"""
auth_path = tmp_path / "codex-home" / "auth.json"
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=True)
_write_codex_auth(auth_path, {"auth_mode": "chatgpt"})
assert codex_native._codex_auth_unavailable_reason() == "needs-auth"
def test_codex_auth_unavailable_reason_malformed_auth_needs_auth(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Installed codex with malformed auth.json reports needs-auth."""
auth_path = tmp_path / "codex-home" / "auth.json"
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=True)
auth_path.parent.mkdir(parents=True, exist_ok=True)
auth_path.write_text("{not json", encoding="utf-8")
assert codex_native._codex_auth_unavailable_reason() == "needs-auth"
def test_codex_auth_unavailable_reason_databricks_profile_available(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A Databricks-profile launch is available even with an EMPTY auth.json.
The reported bug: the launch mints its bearer via ``databricks auth token``
and never reads ``auth.json``, so gating on it is a false negative. auth.json
is deliberately absent here — availability must come from the launch.
"""
auth_path = tmp_path / "codex-home" / "auth.json" # never created
launch = codex_native_app_server.NativeCodexLaunch(
config_overrides=[], model=None, profile="my-profile"
)
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=True, launch=launch)
assert codex_native._codex_auth_unavailable_reason() is None
def test_codex_auth_unavailable_reason_provider_override_available(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A launch pinning a non-openai model_provider is available sans auth.json."""
auth_path = tmp_path / "codex-home" / "auth.json" # never created
launch = codex_native_app_server.NativeCodexLaunch(
config_overrides=['model_provider="omnigent_databricks"'], model=None, profile=None
)
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=True, launch=launch)
assert codex_native._codex_auth_unavailable_reason() is None
def test_codex_auth_unavailable_reason_resolver_failure_falls_back_to_auth_json(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A resolver blow-up fails safe onto the auth.json check (never raises)."""
auth_path = tmp_path / "codex-home" / "auth.json"
_point_codex_auth_check_at(monkeypatch, auth_path, binary_present=True)
def _boom(model: object = None) -> object:
raise RuntimeError("corrupt config")
monkeypatch.setattr(codex_native, "resolve_native_codex_launch", _boom)
# No auth.json → falls through to needs-auth rather than propagating.
assert codex_native._codex_auth_unavailable_reason() == "needs-auth"
class _FakeTerminalClient:
"""
Minimal async client for terminal-launch helper tests.
:param response: HTTP response returned from ``post``.
"""
def __init__(self, response: httpx.Response) -> None:
self.response = response
self.posts: list[tuple[str, dict[str, Any], float | None]] = []
async def post(
self,
url: str,
*,
json: dict[str, Any],
timeout: float | None = None,
) -> httpx.Response:
"""
Capture a terminal-launch request.
:param url: Request URL.
:param json: JSON request body.
:param timeout: Request timeout.
:returns: Canned response.
"""
self.posts.append((url, json, timeout))
return self.response
class _FakeCodexWebSocket:
"""
Minimal websocket for Codex app-server handshake tests.
It immediately responds to the ``initialize`` request and records
every outbound payload.
"""
def __init__(self) -> None:
self.sent: list[str] = []
self.closed = False
self.responses: asyncio.Queue[str] = asyncio.Queue()
async def send(self, payload: str) -> None:
"""
Capture an outbound websocket text frame.
:param payload: JSON-RPC text frame.
:returns: None.
"""
self.sent.append(payload)
message = json.loads(payload)
if message.get("method") == "initialize":
await self.responses.put(json.dumps({"id": message["id"], "result": {}}))
def __aiter__(self) -> _FakeCodexWebSocket:
"""
Return the async iterator used by the client reader task.
:returns: This websocket.
"""
return self
async def __anext__(self) -> str:
"""
Yield the next queued inbound websocket text frame.
:returns: JSON-RPC text frame.
"""
return await self.responses.get()
async def close(self) -> None:
"""
Mark the fake websocket closed.
:returns: None.
"""
self.closed = True
class _FakeCodexAppServerClient:
"""
Test double for ``CodexAppServerClient``.
:param response: JSON-RPC response returned from ``request``.
:param error: Optional exception raised from ``request``.
:param events: Optional events yielded from ``iter_events``.
"""
def __init__(
self,
response: dict[str, Any] | None = None,
error: Exception | None = None,
events: list[dict[str, Any]] | None = None,
) -> None:
self.response = response or {"result": {"thread": {"id": "thread_123"}}}
self.error = error
self.events = events or []
self.connected = False
self.closed = False
self.requests: list[tuple[str, dict[str, Any]]] = []
self.responses: list[tuple[int | str, dict[str, Any]]] = []
async def connect(self) -> None:
"""
Mark the fake client connected.
:returns: None.
"""
self.connected = True
async def request(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
"""
Capture one JSON-RPC request.
:param method: JSON-RPC method.
:param params: JSON-RPC params.
:returns: Canned JSON-RPC response.
"""
self.requests.append((method, params))
if self.error is not None:
raise self.error
return self.response
async def iter_events(self) -> Any:
"""
Return an empty event stream.
:returns: Async iterator with no events.
"""
for event in self.events:
yield event
async def respond(self, request_id: int | str, result: dict[str, Any]) -> None:
"""
Capture one JSON-RPC response sent to the fake app-server.
:param request_id: JSON-RPC request id.
:param result: JSON-RPC result payload.
:returns: None.
"""
self.responses.append((request_id, result))
async def close(self) -> None:
"""
Mark the fake client closed.
:returns: None.
"""
self.closed = True
def test_clear_bridge_state_removes_stale_runtime_state(tmp_path: Path) -> None:
"""
Clearing bridge state removes the stale runtime pointer.
New app-server launches reuse the same bridge directory, so a leftover
``state.json`` must disappear before web-message forwarding can read
it. A regression that leaves the old state in place would make
``read_bridge_state`` return the stale thread id here.
:param tmp_path: Temporary bridge directory.
:returns: None.
"""
bridge_dir = tmp_path / "bridge"
write_bridge_state(
bridge_dir,
CodexNativeBridgeState(
session_id="conv_123",
socket_path="ws://127.0.0.1:1234",
thread_id="019e96aa-0be2-7343-8d3b-6f914d60936b",
codex_home=str(tmp_path / "codex-home"),
),
)
clear_bridge_state(bridge_dir)
assert read_bridge_state(bridge_dir) is None
def test_preload_codex_thread_for_resume_resumes_and_closes(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
Preloading uses Codex ``thread/resume`` before bridge state is exposed.
This helper is the guard against a web turn racing ahead of the TUI
and hitting ``turn/start`` on an app-server that has not loaded the
persisted thread yet. If the request method or params regress, this
test fails on the captured fake client request.
:param monkeypatch: Pytest monkeypatch fixture.
:returns: None.
"""
fake_client = _FakeCodexAppServerClient()
def fake_client_factory(*_args: Any, **_kwargs: Any) -> _FakeCodexAppServerClient:
"""
Return the fake app-server client.
:returns: Fake client.
"""
return fake_client
monkeypatch.setattr(
"omnigent.codex_native_app_server.CodexAppServerClient",
fake_client_factory,
)
asyncio.run(
codex_native_app_server.preload_codex_thread_for_resume(
"ws://127.0.0.1:1234",
"019e96aa-0be2-7343-8d3b-6f914d60936b",
)
)
assert fake_client.connected is True
assert fake_client.requests == [
(
"thread/resume",
{
"threadId": "019e96aa-0be2-7343-8d3b-6f914d60936b",
"excludeTurns": True,
},
)
]
assert fake_client.closed is True
def _started_event(turn_id: str) -> dict[str, Any]:
"""
Build a Codex ``turn/started`` notification.
:param turn_id: Codex turn id, e.g. ``"turn_123"``.
:returns: App-server event payload.
"""
return {"method": "turn/started", "params": {"turn": {"id": turn_id}}}
def _thread_started_event(thread_id: str) -> dict[str, Any]:
"""
Build a Codex ``thread/started`` notification.
:param thread_id: Codex thread id, e.g. ``"thread_123"``.
:returns: App-server event payload.
"""
return {"method": "thread/started", "params": {"thread": {"id": thread_id}}}
def _completed_event(turn_id: str | None, *, thread_id: str | None = None) -> dict[str, Any]:
"""
Build a Codex ``turn/completed`` notification.
:param turn_id: Codex turn id, e.g. ``"turn_123"``, or ``None``
when testing legacy or malformed terminal events.
:param thread_id: Optional Codex thread id, e.g. ``"thread_123"``.
:returns: App-server event payload.
"""
params: dict[str, Any] = {}
if turn_id is not None:
params["turnId"] = turn_id
if thread_id is not None:
params["threadId"] = thread_id
return {"method": "turn/completed", "params": params}
def _failed_event(turn_id: str | None, *, thread_id: str | None = None) -> dict[str, Any]:
"""
Build a Codex ``turn/failed`` notification.
:param turn_id: Codex turn id, e.g. ``"turn_123"``, or ``None``
when testing legacy or malformed terminal events.
:param thread_id: Optional Codex thread id, e.g. ``"thread_123"``.
:returns: App-server event payload.
"""
params: dict[str, Any] = {}
if turn_id is not None:
params["turnId"] = turn_id
if thread_id is not None:
params["threadId"] = thread_id
return {"method": "turn/failed", "params": params}
def _agent_message_event(
turn_id: str,
item_id: str,
text: str,
*,
thread_id: str = "thread_123",
) -> dict[str, Any]:
"""
Build a Codex completed assistant-message notification.
:param turn_id: Codex turn id, e.g. ``"turn_123"``.
:param item_id: Codex item id, e.g. ``"item_123"``.
:param text: Assistant text payload, e.g. ``"done"``.
:param thread_id: Codex thread id, e.g. ``"thread_123"``.
:returns: App-server event payload.
"""
return {
"method": "item/completed",
"params": {
"threadId": thread_id,
"turnId": turn_id,
"item": {
"type": "agentMessage",
"id": item_id,
"text": text,
},
},
}
def _agent_message_delta_event(turn_id: str, item_id: str, delta: object) -> dict[str, Any]:
"""
Build a Codex assistant-message delta notification.
:param turn_id: Codex turn id, e.g. ``"turn_123"``.
:param item_id: Codex item id, e.g. ``"item_123"``.
:param delta: Delta payload to include in the event, e.g. ``"hi"``.
:returns: App-server event payload.
"""
return {
"method": "item/agentMessage/delta",
"params": {
"threadId": "thread_123",
"turnId": turn_id,
"itemId": item_id,
"delta": delta,
},
}
def _plan_delta_event(turn_id: str, item_id: str, delta: object) -> dict[str, Any]:
"""
Build a Codex plan delta notification.
:param turn_id: Codex turn id, e.g. ``"turn_123"``.
:param item_id: Codex plan item id, e.g. ``"item_plan"``.
:param delta: Delta payload to include in the event, e.g.
``"1. Inspect"``.
:returns: App-server event payload.
"""
return {
"method": "item/plan/delta",
"params": {
"threadId": "thread_123",
"turnId": turn_id,
"itemId": item_id,
"delta": delta,
},
}
def _expected_delta_data(
delta: str,
turn_id: str,
item_id: str,
*,
item_type: str = "agentMessage",
) -> dict[str, Any]:
"""
Build the Omnigent event data expected for one Codex native text delta.
:param delta: Coalesced text fragment, e.g. ``"hello"``.
:param turn_id: Codex turn id, e.g. ``"turn_123"``.
:param item_id: Codex item id, e.g. ``"item_agent"``.
:param item_type: Codex item type, e.g. ``"agentMessage"``.
:returns: Expected ``external_output_text_delta`` data payload.
"""
return {
"delta": delta,
"message_id": f"codex:thread_123:{turn_id}:{item_type}:{item_id}",
"index": 0,
"final": False,
}
def _expected_status_data(status: str, turn_id: str) -> dict[str, Any]:
"""
Build the Omnigent event data expected for one Codex native status edge.
:param status: Omnigent session status, e.g. ``"running"``.
:param turn_id: Codex turn id, e.g. ``"turn_123"``.
:returns: Expected ``external_session_status`` data payload.
"""
return {"status": status, "response_id": f"codex_{turn_id}"}
def _usage_event(input_tokens: int, context_window: int = 200_000) -> dict[str, Any]:
"""
Build a Codex token-usage update event.
:param input_tokens: Context token count, e.g. ``1234``.
:param context_window: Context window size, e.g. ``200000``.
:returns: App-server event payload.
"""
return {
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "thread_123",
"tokenUsage": {
"total": {
"inputTokens": input_tokens,
"contextWindow": context_window,
},
},
},
}
def _usage_coalescer(
client: httpx.AsyncClient,
session_id: str = "conv_123",
) -> codex_native_forwarder._SessionUsageCoalescer:
"""
Build the required Codex usage coalescer for direct handler tests.
:param client: HTTP client used by the coalescer.
:param session_id: Omnigent session id, e.g. ``"conv_123"``.
:returns: Usage coalescer bound to ``session_id``.
"""
return codex_native_forwarder._SessionUsageCoalescer(client, session_id)
def _elicitation_tracker() -> codex_native_forwarder._CodexElicitationTaskTracker:
"""
Build the required Codex elicitation tracker for direct handler tests.
:returns: Fresh tracker with no pending hook tasks.
"""
return codex_native_forwarder._CodexElicitationTaskTracker()
def test_materialize_codex_agent_spec_uses_codex_native_harness(
tmp_path: Path, monkeypatch
) -> None:
"""
The generated wrapper spec is self-contained and selects the
isolated ``codex-native`` harness rather than the existing
non-TUI ``codex`` harness.
"""
# Pin the host shells so the declared terminals are deterministic
# ($SHELL=bash → the default/first terminal is ``bash``).
monkeypatch.setattr("shutil.which", lambda name: f"/usr/bin/{name}")
monkeypatch.setenv("SHELL", "/bin/bash")
spec_path = codex_native._materialize_codex_agent_spec(
tmp_path,
model="gpt-test",
)
raw = yaml.safe_load(spec_path.read_text(encoding="utf-8"))
assert raw["name"] == "codex-native-ui"
# Exact executor block: the spec must NOT carry a profile key —
# the --profile CLI flag was removed, so routing is resolved at
# launch time (provider config / global auth / ambient detection).
assert raw["executor"] == {
"harness": "codex-native",
"model": "gpt-test",
}
def test_materialized_codex_agent_spec_loads_as_valid_omnigent_yaml(
tmp_path: Path,
) -> None:
"""
The generated wrapper spec passes Omnigent YAML validation.
This guards the session-create path, which registers the generated
spec bundle and fails before Codex starts if ``codex-native`` is not
accepted by the spec adapter.
"""
spec_path = codex_native._materialize_codex_agent_spec(
tmp_path,
model="gpt-test",
)
spec = load(spec_path)
assert spec.executor.config["harness"] == "codex-native"
# The native wrapper opts into the spawn-write surface so the
# wrapped codex can author agent configs and launch them as child
# sessions; the bridge relay derives its tool set from this spec
# via ToolManager, so a dropped flag silently removes
# sys_session_create/send/close from the native CLI.
assert spec.spawn is True
# The native wrapper declares one terminal per installed shell so the
# relay advertises the sys_terminal_* family to the wrapped codex (the
# relay gate is a non-empty ``terminals:`` block on this spec); a
# dropped block silently removes the terminal tools from the native CLI.
assert spec.terminals is not None
assert spec.terminals["bash"].command == "bash"
@pytest.mark.parametrize(
("codex_args", "thread_id", "remote_url", "expected"),
[
# Fresh thread over a Unix socket (local ``omnigent codex``
# cold start): no ``resume``/thread id, transport passed verbatim.
(
(),
None,
"unix:///tmp/app-server.sock",
["--remote", "unix:///tmp/app-server.sock"],
),
# Resume an existing thread over a Unix socket (local reattach).
(
(),
"thread_local",
"unix:///tmp/app-server.sock",
["resume", "--remote", "unix:///tmp/app-server.sock", "thread_local"],
),
# Fresh thread over a loopback ws endpoint.
(
(),
None,
"ws://127.0.0.1:9876",
["--remote", "ws://127.0.0.1:9876"],
),
# Resume an existing thread over a loopback ws endpoint: the
# host-spawned runner path. The app-server listens on ws:// there
# (the codex CLI lacked unix:// listen support), so
# the auto-created terminal must attach over that same ws URL. A
# regression hardcoding ``unix://`` would break exactly this case.
(
(),
"thread_host",
"ws://127.0.0.1:9876",
["resume", "--remote", "ws://127.0.0.1:9876", "thread_host"],
),
# Leading codex args are preserved ahead of the attach flags.
(
("--model", "gpt-5.4-mini"),
"thread_x",
"ws://127.0.0.1:9876",
[
"--model",
"gpt-5.4-mini",
"resume",
"--remote",
"ws://127.0.0.1:9876",
"thread_x",
],
),
],
)
def test_build_codex_remote_args_passes_transport_verbatim(
codex_args: tuple[str, ...],
thread_id: str | None,
remote_url: str,
expected: list[str],
) -> None:
"""
``build_codex_remote_args`` emits the TUI ``--remote`` attach argv
for both transports and both thread states.
The transport URL is passed through verbatim so one builder serves
both the local Unix-socket path and the host-spawned ``ws://`` path,
and ``resume <thread_id>`` is appended iff a thread id is supplied.
If this regressed to a hardcoded ``unix://`` prefix, the ws cases
would fail and the host-spawned Codex terminal could not reach its
TCP app-server (no terminal would render in the web UI).
"""
assert (
codex_native_app_server.build_codex_remote_args(
codex_args=codex_args,
thread_id=thread_id,
remote_url=remote_url,
)
== expected
)
@pytest.mark.parametrize(
("thread_id", "expected"),
[
# Fresh thread: -c overrides precede the bare --remote attach.
(
None,
[
"-c",
'model="databricks-gpt-5-5"',
"-c",
'model_provider="omnigent_databricks"',
"--remote",
"ws://127.0.0.1:9876",
],
),
# Resume: -c overrides are global flags and MUST precede the
# ``resume`` subcommand (codex rejects globals placed after it).
(
"thread_host",
[
"-c",
'model="databricks-gpt-5-5"',
"-c",
'model_provider="omnigent_databricks"',
"resume",
"--remote",
"ws://127.0.0.1:9876",
"thread_host",
],
),
],
)
def test_build_codex_remote_args_emits_config_overrides_before_subcommand(
thread_id: str | None,
expected: list[str],
) -> None:
"""
``build_codex_remote_args`` emits each ``config_overrides`` entry as a
``-c <value>`` global flag ahead of the attach flags.
The ``--remote`` TUI is a separate process that does not inherit the
app-server's ``-c`` flags; without these the TUI falls back to the
OpenAI built-in provider (``requires_openai_auth = true``), renders
the first-run login onboarding screen, and never creates a thread —
so a host-spawned session hangs in ``running`` with no response.
Asserting the exact argv (not just membership) guards two things at
once: that the overrides are forwarded at all, and that they land
*before* the ``resume`` subcommand — codex treats ``-c`` as a global
option and rejects it when placed after a subcommand, which would
abort TUI startup and reintroduce the hang.
"""
assert (
codex_native_app_server.build_codex_remote_args(
codex_args=(),
thread_id=thread_id,
remote_url="ws://127.0.0.1:9876",
config_overrides=(
'model="databricks-gpt-5-5"',
'model_provider="omnigent_databricks"',
),
)
== expected
)
@pytest.mark.parametrize(
("codex_args", "expected"),
[
# ``--flag value`` pair: both dropped.
(("--sandbox", "read-only"), []),
(("--ask-for-approval", "on-request"), []),
# Option-adjacent: the next token is ANOTHER flag, not this flag's
# value, so it must survive (the over-match bug dropped --model).
(("--sandbox", "--model", "gpt"), ["--model", "gpt"]),
# ``--flag=value`` single token: dropped whole, consumes nothing after.
(("--ask-for-approval=on-failure",), []),
(("--sandbox=read-only", "--model", "gpt"), ["--model", "gpt"]),
# Short aliases: ``-a`` (== --ask-for-approval) triggers the SAME codex
# startup abort as the long form, so it must be stripped too; ``-s``
# (== --sandbox) is harmless but dropped for consistency. Both spellings
# (space-separated and ``=value``-joined) are handled.
(("-a", "never"), []),
(("-a=never",), []),
(("-s", "read-only"), []),
(("-s=read-only", "--model", "gpt"), ["--model", "gpt"]),
# Short alias option-adjacent to another flag: the next flag survives.
(("-a", "--model", "gpt"), ["--model", "gpt"]),
# Trailing flag at end-of-list: dropped cleanly, no value to consume.
(("--model", "gpt", "--sandbox"), ["--model", "gpt"]),
# Unrelated arg next to a stripped pair is preserved.
(
("--model", "gpt", "--sandbox", "read-only", "--cwd", "/x"),
["--model", "gpt", "--cwd", "/x"],
),
# A pre-existing bypass flag is de-duped (the caller re-adds one copy).
(("--dangerously-bypass-approvals-and-sandbox", "--model", "gpt"), ["--model", "gpt"]),
# No conflicting flags: everything passes through untouched.
(("--model", "gpt-5.4-mini"), ["--model", "gpt-5.4-mini"]),
],
)
def test_strip_approval_sandbox_flags_only_consumes_real_values(
codex_args: tuple[str, ...],
expected: list[str],
) -> None:
"""
``_strip_approval_sandbox_flags`` drops the conflicting flags without
over-matching the token that follows them.
A ``--sandbox`` / ``--ask-for-approval`` flag consumes the next token as
its value ONLY when that token is a real value (does not start with
``-``); a following flag or end-of-list consumes nothing, so unrelated
args like ``--model gpt`` are never swallowed. The ``--flag=value``
single-token spelling is dropped whole.
"""
assert codex_native_app_server._strip_approval_sandbox_flags(codex_args) == expected
def test_build_codex_remote_args_default_keeps_approval_flags_no_bypass() -> None:
"""
Default (``bypass_sandbox=False``) emits NO bypass flag and preserves the
approval/sandbox flags the approval-mode presets pass through.
The web "Full access" / "Read only" presets are sent as
``--sandbox`` / ``--ask-for-approval`` pairs inside ``codex_args``. With
bypass off those must reach the TUI verbatim and the dangerous bypass
flag must never appear — a regression here would either drop a user's
chosen approval preset or silently escalate to full bypass.
"""
args = codex_native_app_server.build_codex_remote_args(
codex_args=("--sandbox", "read-only", "--ask-for-approval", "on-request"),
thread_id=None,
remote_url="ws://127.0.0.1:9876",
)
assert "--dangerously-bypass-approvals-and-sandbox" not in args
assert args == [
"--sandbox",
"read-only",
"--ask-for-approval",
"on-request",
"--remote",
"ws://127.0.0.1:9876",
]
@pytest.mark.parametrize(
("codex_args", "thread_id", "expected"),
[
# Fresh thread, no conflicting flags: a single bypass flag is prepended.
(
(),
None,
[
"--dangerously-bypass-approvals-and-sandbox",
"--remote",
"ws://127.0.0.1:9876",
],
),
# Conflicting approval-preset flags are stripped (flag + its value),
# unrelated args (model) survive, and the bypass flag is added once.
# codex aborts if the bypass flag is combined with --sandbox /
# --ask-for-approval, so leaving them in would break TUI startup.
(
("--sandbox", "danger-full-access", "--ask-for-approval", "never", "--model", "gpt"),
None,
[
"--dangerously-bypass-approvals-and-sandbox",
"--model",
"gpt",
"--remote",
"ws://127.0.0.1:9876",
],
),
# Resume path: the bypass flag is a global flag and MUST precede the
# ``resume`` subcommand, and a pre-existing bypass flag is de-duped.
(
("--dangerously-bypass-approvals-and-sandbox", "--sandbox", "read-only"),
"thread_x",
[
"--dangerously-bypass-approvals-and-sandbox",
"resume",
"--remote",
"ws://127.0.0.1:9876",
"thread_x",
],
),
],
)
def test_build_codex_remote_args_bypass_emits_flag_and_strips_conflicts(
codex_args: tuple[str, ...],
thread_id: str | None,
expected: list[str],
) -> None:
"""
``bypass_sandbox=True`` emits one ``--dangerously-bypass-approvals-and-
sandbox`` and strips the conflicting ``--sandbox`` / ``--ask-for-approval``
pairs.
See :func:`omnigent.codex_native_app_server._strip_approval_sandbox_flags`.
Asserting the exact argv guards three things: the bypass flag is present
exactly once, the conflicting flag pairs are removed (with their values),
and the bypass flag lands before any ``resume`` subcommand (codex rejects
a global flag placed after a subcommand).
"""
assert (
codex_native_app_server.build_codex_remote_args(
codex_args=codex_args,
thread_id=thread_id,
remote_url="ws://127.0.0.1:9876",
bypass_sandbox=True,
)
== expected
)
def test_codex_app_server_client_uses_codex_remote_handshake(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
"""
The Python client matches Codex's Unix-socket websocket transport
and completes the initialize/initialized handshake.
"""