forked from omnigent-ai/omnigent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_claude_native.py
More file actions
6238 lines (5359 loc) · 224 KB
/
Copy pathtest_claude_native.py
File metadata and controls
6238 lines (5359 loc) · 224 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 Claude Code terminal wrapper helpers."""
from __future__ import annotations
import asyncio
import contextlib
import importlib.metadata
import io
import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import click
import httpx
import pytest
import websockets
import yaml
from websockets.exceptions import ConnectionClosedError
from websockets.frames import Close
from omnigent import claude_native
from omnigent._runner_startup import RunnerStartupProgress
from omnigent._startup_profile import StartupProfiler
from omnigent._terminal_picker_theme import PICKER_ACCENT, PICKER_MUTED
from omnigent.runner.identity import OMNIGENT_INTERNAL_WS_ORIGIN
from omnigent.spec import load_omnigent_yaml
from omnigent.terminals.ws_bridge import (
WS_CLOSE_TERMINAL_DETACHED,
WS_CLOSE_TERMINAL_NOT_FOUND,
)
def test_claude_terminal_request_pins_launch_cwd(tmp_path, monkeypatch) -> None:
"""
The terminal launch body pins ``cwd`` to the user's launch dir.
Regression for the interaction where the wrapper runs on the same
host as the runner subprocess, so ``Path.cwd()`` here equals the
runner's ``RUNNER_WORKSPACE`` env. If the wrapper omits ``cwd`` /
sends the placeholder ``"."``, the runner falls through to
``compute_default_env_root`` which (under
``per_session_workspace=True``) returns
``<workspace>/<conversation_id>`` -- a directory the runner never
creates. tmux then silently launches in ``$HOME``.
Test also guards: ``bridge_inject_dir`` stays a boolean opt-in
(sending the path string would resurrect a directory-traversal
vector the runner now ignores) and the experimental Claude
Channels flag is not snuck in.
"""
monkeypatch.chdir(tmp_path)
body = claude_native._claude_terminal_request(
("--resume", "claude-session", "-p", "hi"),
command="claude",
bridge_dir=Path("/tmp/omnigent-test-bridge"),
)
assert body["terminal"] == "claude"
assert body["session_key"] == "main"
# Boolean opt-in only — sending the path string would resurrect the
# directory-traversal vector the runner now ignores.
assert body["bridge_inject_dir"] is True
spec = body["spec"]
assert spec["command"] == "claude"
assert spec["env"] == {
"ENABLE_TOOL_SEARCH": "true",
"CLAUDE_CODE_DISABLE_AGENT_VIEW": "1",
}
assert spec["os_env_type"] == "caller_process"
# Claude Code emits long interactive transcripts; this value is
# the tmux history limit for the native terminal.
assert spec["scrollback"] == 100000
# The wrapper pins cwd explicitly to the launch directory; assert
# the literal value, not just "some path is set", so a regression
# back to a placeholder like ``"."`` is caught.
assert spec["cwd"] == str(tmp_path.resolve())
assert "log_file" not in spec
args = spec["args"]
assert args[:4] == ["--resume", "claude-session", "-p", "hi"]
mcp_index = args.index("--mcp-config")
mcp_config = json.loads(args[mcp_index + 1])
assert mcp_config["mcpServers"]["omnigent"]["args"] == [
"-I",
"-m",
"omnigent.claude_native_bridge",
"serve-mcp",
"--bridge-dir",
"/tmp/omnigent-test-bridge",
]
# The experimental Claude Channels flag is blocked at the org
# policy layer — the wrapper must not pass it. Web-UI input now
# goes through tmux send-keys.
assert "--dangerously-load-development-channels" not in args
settings = json.loads(args[args.index("--settings") + 1])
assert sorted(settings["hooks"]) == [
"MessageDisplay",
"PostToolUse",
"PreCompact",
"SessionStart",
"Stop",
"StopFailure",
"TaskCompleted",
"TaskCreated",
"UserPromptSubmit",
]
def test_claude_terminal_request_default_launch_is_unwrapped(tmp_path, monkeypatch) -> None:
"""Without ``OMNIGENT_CLAUDE_LAUNCHER`` the command/args are unchanged."""
monkeypatch.delenv("OMNIGENT_CLAUDE_LAUNCHER", raising=False)
monkeypatch.chdir(tmp_path)
body = claude_native._claude_terminal_request(
("--resume", "s"),
command="claude",
bridge_dir=Path("/tmp/omnigent-test-bridge"),
)
spec = body["spec"]
assert spec["command"] == "claude"
assert spec["args"][:2] == ["--resume", "s"]
def test_claude_terminal_request_launcher_plugin_wraps(tmp_path, monkeypatch) -> None:
"""
A registered launcher plugin rewrites the spawn command, keeping the bridge.
Exercises the local-CLI wiring of :func:`resolve_claude_launch`: with a
launcher plugin selected, the terminal spec runs the wrapped command
(here ``isaac -- <augmented args>``) while the Omnigent bridge
(``--mcp-config`` / ``--settings``) survives intact in the passed-through
argv.
"""
from omnigent.claude_launcher import ClaudeLauncher
class _IsaacLauncher(ClaudeLauncher):
def launch(self, command, args):
return "isaac", ["--", *args]
entry_point = SimpleNamespace(name="isaac", load=lambda: _IsaacLauncher)
monkeypatch.setattr(importlib.metadata, "entry_points", lambda *, group: [entry_point])
monkeypatch.setenv("OMNIGENT_CLAUDE_LAUNCHER", "isaac")
monkeypatch.chdir(tmp_path)
body = claude_native._claude_terminal_request(
("--resume", "s"),
command="claude",
bridge_dir=Path("/tmp/omnigent-test-bridge"),
)
spec = body["spec"]
assert spec["command"] == "isaac"
# Claude's argv is now passed through isaac after the ``--`` separator.
assert spec["args"][0] == "--"
assert spec["args"][1:3] == ["--resume", "s"]
# The bridge MCP + hook injection still rides along.
assert "--mcp-config" in spec["args"]
assert "--settings" in spec["args"]
def test_claude_terminal_request_injects_claude_config() -> None:
"""
Ucode config reaches the terminal env, settings, and model argv.
This test pins the native ``omnigent claude`` launch boundary:
a regression that reads ucode but forgets to pass the resulting
Databricks gateway values to the terminal resource would leave
Claude Code on its default provider path.
"""
config = claude_native.ClaudeNativeUcodeConfig(
env={
"ANTHROPIC_BASE_URL": "https://example.databricks.com/ai-gateway/anthropic",
"CLAUDE_CODE_API_KEY_HELPER_TTL_MS": "900000",
"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1",
},
api_key_helper="printf token",
model="databricks-claude-opus-test",
)
body = claude_native._claude_terminal_request(
("--print", "hi"),
command="claude",
bridge_dir=Path("/tmp/omnigent-test-bridge"),
claude_config=config,
)
spec = body["spec"]
assert spec["command"] == "env"
assert spec["env"] == {
"ANTHROPIC_BASE_URL": "https://example.databricks.com/ai-gateway/anthropic",
"CLAUDE_CODE_API_KEY_HELPER_TTL_MS": "900000",
"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1",
"ENABLE_TOOL_SEARCH": "true",
"CLAUDE_CODE_DISABLE_AGENT_VIEW": "1",
}
args = spec["args"]
assert args[:9] == [
"-u",
"ANTHROPIC_API_KEY",
"-u",
"CLAUDECODE",
"claude",
"--print",
"hi",
"--model",
"databricks-claude-opus-test",
]
settings = json.loads(args[args.index("--settings") + 1])
assert settings["apiKeyHelper"] == "printf token"
assert "hooks" in settings
def test_claude_terminal_request_preserves_user_model_arg() -> None:
"""
User-selected Claude model wins over the ucode default.
The ucode model is a default, not a forced override. If this
regresses, users who pass ``--model`` would silently get the
workspace default instead of the model they explicitly requested.
"""
config = claude_native.ClaudeNativeUcodeConfig(
env={"ANTHROPIC_BASE_URL": "https://example.databricks.com/ai-gateway/anthropic"},
api_key_helper="printf token",
model="databricks-claude-opus-test",
)
body = claude_native._claude_terminal_request(
("--model", "user-model", "--print", "hi"),
command="claude",
bridge_dir=Path("/tmp/omnigent-test-bridge"),
claude_config=config,
)
args = body["spec"]["args"]
assert args[:9] == [
"-u",
"ANTHROPIC_API_KEY",
"-u",
"CLAUDECODE",
"claude",
"--model",
"user-model",
"--print",
"hi",
]
assert args.count("--model") == 1
def test_ucode_config_for_profile_reads_allowlisted_claude_state(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
Profile-backed native Claude config reads only required ucode fields.
The extra ``ANTHROPIC_AUTH_TOKEN`` in fake ucode env is deliberate:
the native wrapper must not blindly forward arbitrary state-file
environment values into the terminal launch body.
"""
from omnigent.onboarding.ucode_state import UcodeAgentState, UcodeWorkspaceState
workspace_state = UcodeWorkspaceState(
workspace_url="https://example.databricks.com",
agents={
"claude": UcodeAgentState(
model="databricks-claude-opus-test",
base_url="https://example.databricks.com/ai-gateway/anthropic",
auth_command="printf token",
auth_refresh_interval_ms=123456,
env={
"ANTHROPIC_BASE_URL": "https://example.databricks.com/ai-gateway/anthropic",
"ANTHROPIC_AUTH_TOKEN": "must-not-leak",
},
)
},
)
monkeypatch.setattr(
"omnigent.onboarding.databricks_config.get_workspace_url_for_profile",
lambda profile: "https://example.databricks.com",
)
monkeypatch.setattr(
"omnigent.onboarding.ucode_state.read_ucode_state",
lambda workspace_url: workspace_state,
)
config = claude_native._ucode_config_for_profile("test-profile")
assert config == claude_native.ClaudeNativeUcodeConfig(
env={
"ANTHROPIC_BASE_URL": "https://example.databricks.com/ai-gateway/anthropic",
"CLAUDE_CODE_API_KEY_HELPER_TTL_MS": "123456",
"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1",
},
api_key_helper="printf token",
model="databricks-claude-opus-test",
)
def test_ucode_config_for_profile_sets_model_tier_env_vars(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
ANTHROPIC_DEFAULT_*_MODEL env vars are set from workspace claude_models.
When ``claude_models`` lists all four tiers the corresponding
``ANTHROPIC_DEFAULT_FABLE_MODEL``, ``ANTHROPIC_DEFAULT_OPUS_MODEL``,
``ANTHROPIC_DEFAULT_SONNET_MODEL``, and ``ANTHROPIC_DEFAULT_HAIKU_MODEL``
vars are injected into the terminal env so that Claude Code's ``/model``
picker natively shows Databricks gateway model IDs instead of normalising
them to canonical Anthropic names.
"""
from omnigent.onboarding.ucode_state import UcodeAgentState, UcodeWorkspaceState
workspace_state = UcodeWorkspaceState(
workspace_url="https://example.databricks.com",
claude_models={
"fable": "databricks-claude-fable-5",
"opus": "databricks-claude-opus-4-7",
"sonnet": "databricks-claude-sonnet-4-6",
"haiku": "databricks-claude-haiku-4-5",
},
agents={
"claude": UcodeAgentState(
model="databricks-claude-opus-4-7",
base_url="https://example.databricks.com/ai-gateway/anthropic",
auth_command="printf token",
)
},
)
monkeypatch.setattr(
"omnigent.onboarding.databricks_config.get_workspace_url_for_profile",
lambda profile: "https://example.databricks.com",
)
monkeypatch.setattr(
"omnigent.onboarding.ucode_state.read_ucode_state",
lambda workspace_url: workspace_state,
)
config = claude_native._ucode_config_for_profile("test-profile")
assert config is not None
assert config.env["ANTHROPIC_DEFAULT_FABLE_MODEL"] == "databricks-claude-fable-5"
assert config.env["ANTHROPIC_DEFAULT_OPUS_MODEL"] == "databricks-claude-opus-4-7"
assert config.env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "databricks-claude-sonnet-4-6"
assert config.env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "databricks-claude-haiku-4-5"
def test_ucode_config_for_profile_sets_only_present_tier_env_vars(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
Only tiers present in claude_models get ANTHROPIC_DEFAULT_* env vars.
If ``claude_models`` only has one tier (e.g. ``"sonnet"``), only
``ANTHROPIC_DEFAULT_SONNET_MODEL`` is set — the other three are absent.
"""
from omnigent.onboarding.ucode_state import UcodeAgentState, UcodeWorkspaceState
workspace_state = UcodeWorkspaceState(
workspace_url="https://example.databricks.com",
claude_models={"sonnet": "databricks-claude-sonnet-4-6"},
agents={
"claude": UcodeAgentState(
model="databricks-claude-sonnet-4-6",
base_url="https://example.databricks.com/ai-gateway/anthropic",
auth_command="printf token",
)
},
)
monkeypatch.setattr(
"omnigent.onboarding.databricks_config.get_workspace_url_for_profile",
lambda profile: "https://example.databricks.com",
)
monkeypatch.setattr(
"omnigent.onboarding.ucode_state.read_ucode_state",
lambda workspace_url: workspace_state,
)
config = claude_native._ucode_config_for_profile("test-profile")
assert config is not None
assert config.env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "databricks-claude-sonnet-4-6"
assert "ANTHROPIC_DEFAULT_FABLE_MODEL" not in config.env
assert "ANTHROPIC_DEFAULT_OPUS_MODEL" not in config.env
assert "ANTHROPIC_DEFAULT_HAIKU_MODEL" not in config.env
def test_ucode_config_for_profile_sets_custom_model_option_for_second_sonnet(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
A ``claude_models["sonnet_5"]`` entry pins Claude Code's one custom
``/model`` slot (``ANTHROPIC_CUSTOM_MODEL_OPTION``) to the newer Sonnet,
offered as an opt-in *alongside* the ``sonnet`` tier alias, which stays
on the workspace's existing default Sonnet (4.6). The default is
unchanged; Sonnet 5 is an additional, explicit choice.
"""
from omnigent.onboarding.ucode_state import UcodeAgentState, UcodeWorkspaceState
workspace_state = UcodeWorkspaceState(
workspace_url="https://example.databricks.com",
claude_models={
"sonnet": "databricks-claude-sonnet-4-6",
"sonnet_5": "databricks-claude-sonnet-5",
},
agents={
"claude": UcodeAgentState(
model="databricks-claude-sonnet-4-6",
base_url="https://example.databricks.com/ai-gateway/anthropic",
auth_command="printf token",
)
},
)
monkeypatch.setattr(
"omnigent.onboarding.databricks_config.get_workspace_url_for_profile",
lambda profile: "https://example.databricks.com",
)
monkeypatch.setattr(
"omnigent.onboarding.ucode_state.read_ucode_state",
lambda workspace_url: workspace_state,
)
config = claude_native._ucode_config_for_profile("test-profile")
assert config is not None
assert config.env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "databricks-claude-sonnet-4-6"
assert config.env["ANTHROPIC_CUSTOM_MODEL_OPTION"] == "databricks-claude-sonnet-5"
assert config.env["ANTHROPIC_CUSTOM_MODEL_OPTION_NAME"] == "Sonnet 5"
def test_ucode_config_for_profile_omits_model_tier_vars_when_no_claude_models(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
No ANTHROPIC_DEFAULT_* env vars are set when claude_models is empty.
Older ucode state files may not include ``claude_models``. In that
case the env dict must not gain any spurious default model overrides.
"""
from omnigent.onboarding.ucode_state import UcodeAgentState, UcodeWorkspaceState
workspace_state = UcodeWorkspaceState(
workspace_url="https://example.databricks.com",
claude_models={},
agents={
"claude": UcodeAgentState(
model="databricks-claude-opus-4-7",
base_url="https://example.databricks.com/ai-gateway/anthropic",
auth_command="printf token",
)
},
)
monkeypatch.setattr(
"omnigent.onboarding.databricks_config.get_workspace_url_for_profile",
lambda profile: "https://example.databricks.com",
)
monkeypatch.setattr(
"omnigent.onboarding.ucode_state.read_ucode_state",
lambda workspace_url: workspace_state,
)
config = claude_native._ucode_config_for_profile("test-profile")
assert config is not None
for key in config.env:
assert not key.startswith("ANTHROPIC_DEFAULT_"), (
f"Unexpected model-tier env var {key!r} when claude_models is empty"
)
def test_ucode_config_for_profile_defaults_model_when_ucode_omits_it(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
A ucode state with no model defaults to the Databricks gateway model.
Some workspaces (e.g. the OSS integration gateway) cache the gateway
URL + auth command but neither a per-agent ``model`` nor any
``claude_models`` tiers. Without a default the native Claude CLI falls
back to its host-config model (an Anthropic-direct id like ``opus[1m]``)
that the Databricks gateway rejects with "model ... may not exist".
"""
from omnigent.onboarding.ucode_state import UcodeAgentState, UcodeWorkspaceState
workspace_state = UcodeWorkspaceState(
workspace_url="https://example.databricks.com",
claude_models={},
agents={
"claude": UcodeAgentState(
model=None,
base_url="https://example.databricks.com/ai-gateway/anthropic",
auth_command="printf token",
)
},
)
monkeypatch.setattr(
"omnigent.onboarding.databricks_config.get_workspace_url_for_profile",
lambda profile: "https://example.databricks.com",
)
monkeypatch.setattr(
"omnigent.onboarding.ucode_state.read_ucode_state",
lambda workspace_url: workspace_state,
)
config = claude_native._ucode_config_for_profile("test-profile")
assert config is not None
# The verified routable gateway endpoint name, not the CLI's own default.
assert config.model == "databricks-claude-opus-4-8"
def test_ucode_config_for_profile_fails_loud_on_malformed_claude_state(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A selected malformed Claude ucode entry surfaces a setup error."""
from omnigent.onboarding.ucode_state import UcodeAgentState, UcodeWorkspaceState
workspace_state = UcodeWorkspaceState(
workspace_url="https://example.databricks.com",
agents={"claude": UcodeAgentState(auth_command="printf token")},
)
monkeypatch.setattr(
"omnigent.onboarding.databricks_config.get_workspace_url_for_profile",
lambda profile: "https://example.databricks.com",
)
monkeypatch.setattr(
"omnigent.onboarding.ucode_state.read_ucode_state",
lambda workspace_url: workspace_state,
)
with pytest.raises(click.ClickException, match="missing Claude base URL"):
claude_native._ucode_config_for_profile("test-profile")
def test_attach_url_encodes_path_components() -> None:
"""Attach URLs preserve base paths and percent-encode ids."""
url = claude_native._attach_url(
"https://example.com/base/",
"conv with space",
"terminal/odd:id",
)
assert (
url == "wss://example.com/base/v1/sessions/conv%20with%20space/"
"resources/terminals/terminal%2Fodd%3Aid/attach"
)
def test_materialized_session_spec_is_valid_terminal_metadata(tmp_path: Path) -> None:
"""
The generated bundled agent spec validates for Omnigent session creation.
The session agent only exists so the Sessions API can create a
normal session row; Claude itself is launched as a terminal
resource after creation, not through this executor block.
"""
path = claude_native._materialize_claude_agent_spec(tmp_path)
raw = yaml.safe_load(path.read_text())
assert raw["name"] == "claude-native-ui"
assert raw["prompt"].startswith("Claude Code is running in the session terminal.")
# ``context_window`` is the conservative pre-first-turn default;
# the statusLine forwarder overrides it once the real number is
# observed (see ``omnigent.claude_native_status``).
assert raw["executor"] == {"harness": "claude-native", "context_window": 200_000}
# os_env block is required for the runner's filesystem APIs not
# to 404 (see _require_os_env in omnigent/runner/app.py).
assert raw["os_env"] == {
"type": "caller_process",
"cwd": ".",
"sandbox": {"type": "none"},
}
spec = load_omnigent_yaml(path)
assert spec.executor.type == "omnigent"
assert spec.executor.config["harness"] == "claude-native"
assert spec.os_env is not None
# The native wrapper opts into the spawn-write surface so the
# wrapped Claude Code 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 raw["spawn"] is True
assert spec.spawn is True
# The native wrapper declares a default shell terminal so the
# relay advertises the sys_terminal_* family to the wrapped
# Claude Code (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["shell"].command == "bash"
def test_remote_run_preflights_local_claude_binary(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
``--server`` mode still requires a local Claude executable.
``--server`` only selects the AP/web UI/control plane. Claude
itself is launched by the local runner, so the wrapper must fail
before contacting the server when the local binary is missing.
"""
called_remote = False
def fake_which(command: str) -> str | None:
"""
Report the fake Claude command as missing and tmux as present.
:param command: Command name passed to ``shutil.which``.
:returns: Fake executable path or ``None``.
"""
if command == "missing-claude":
return None
if command == "tmux":
return "/usr/bin/tmux"
return f"/usr/bin/{command}"
def fake_remote(
base_url: str,
spec_path: Path,
*,
session_id: str | None,
claude_args: tuple[str, ...],
command: str,
) -> None:
"""Record an unexpected remote launch attempt.
:param base_url: Remote server URL.
:param spec_path: Generated wrapper spec path.
:param session_id: Optional session id.
:param claude_args: Passthrough Claude arguments.
:param command: Claude executable name.
:returns: None.
"""
nonlocal called_remote
del base_url, spec_path, session_id, claude_args, command
called_remote = True
monkeypatch.setattr(claude_native.shutil, "which", fake_which)
monkeypatch.setattr(claude_native, "_run_with_remote_server", fake_remote)
with pytest.raises(click.ClickException, match="missing-claude"):
claude_native.run_claude_native(
server="https://example.com/",
session_id="conv_abc",
claude_args=("--resume", "claude-native"),
command="missing-claude",
)
assert called_remote is False
def test_local_run_preflights_local_claude_binary(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
Local-server mode also requires a local Claude executable.
The Omnigent server and web UI are local in this mode, but Claude is
still launched by a local runner-owned terminal resource.
"""
called_local = False
def fake_which(command: str) -> str | None:
"""
Report the fake Claude command as missing and tmux as present.
:param command: Command name passed to ``shutil.which``.
:returns: Fake executable path or ``None``.
"""
if command == "missing-claude":
return None
if command == "tmux":
return "/usr/bin/tmux"
return f"/usr/bin/{command}"
def fake_local(
spec_path: Path,
*,
session_id: str | None,
claude_args: tuple[str, ...],
command: str,
) -> None:
"""
Record an unexpected local launch attempt.
:param spec_path: Generated wrapper spec path.
:param session_id: Optional session id.
:param claude_args: Passthrough Claude arguments.
:param command: Claude executable name.
:returns: None.
"""
nonlocal called_local
del spec_path, session_id, claude_args, command
called_local = True
monkeypatch.setattr(claude_native.shutil, "which", fake_which)
monkeypatch.setattr(claude_native, "_run_with_local_server", fake_local)
with pytest.raises(click.ClickException, match="missing-claude"):
claude_native.run_claude_native(
server=None,
session_id=None,
claude_args=(),
command="missing-claude",
)
assert called_local is False
def test_run_preflights_local_tmux(monkeypatch: pytest.MonkeyPatch) -> None:
"""
The native wrapper fails before setup when local tmux is unavailable.
This catches regressions where the wrapper would start a server or
runner and only fail after terminal-resource launch.
"""
def fake_which(command: str) -> str | None:
"""
Report Claude as present and tmux as missing.
:param command: Command name passed to ``shutil.which``.
:returns: Fake executable path or ``None``.
"""
if command == "tmux":
return None
return f"/usr/bin/{command}"
monkeypatch.setattr(claude_native.shutil, "which", fake_which)
with pytest.raises(click.ClickException, match="tmux"):
claude_native.run_claude_native(
server=None,
session_id=None,
claude_args=(),
command="claude",
)
def test_local_run_persists_launch_state_on_fresh_session(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""
The local-server fresh-session path persists launch state.
Both ``_run_with_local_server`` and ``_run_with_remote_server``
carry the same ``_record_launch_for_fresh_session`` call site, so the
duplicated block is easy to break in only one of the two
when one is touched and the other isn't. This test pins the
local variant; a copy-paste regression that forgets to wire
the call there would surface here without affecting the remote
test (and vice versa).
"""
from omnigent.claude_native_state import read_launch_state
workspace = tmp_path / "workspace"
workspace.mkdir()
spec_path = tmp_path / "claude.yaml"
spec_path.write_text("name: claude-native-ui\nprompt: hi\n")
opened: list[tuple[str, str, bool]] = []
class _Proc:
"""Stub for the local server subprocess."""
def poll(self) -> None:
"""Pretend the server is alive."""
def fake_start_server(*args: object, **kwargs: object) -> Any:
"""Return a minimal server handle without spawning anything."""
del args, kwargs
return SimpleNamespace(
proc=_Proc(),
runner_id="runner_local",
log_path=None,
)
async def fake_prepare(**kwargs: object) -> claude_native.PreparedClaudeTerminal:
"""Return a prepared terminal pointing at a freshly-minted conv id."""
del kwargs
return claude_native.PreparedClaudeTerminal(
session_id="conv_local_fresh",
terminal_id=claude_native.claude_terminal_resource_id(),
bridge_dir=tmp_path / "bridge",
reattached=False,
)
async def fake_attach(
attach_url: str,
*,
headers: dict[str, str],
terminal_gone_probe: object | None = None,
) -> bool:
"""Exit immediately so the attach loop returns."""
del attach_url, headers, terminal_gone_probe
return True
monkeypatch.chdir(workspace)
monkeypatch.setattr("omnigent.chat._find_free_port", lambda: 12345)
monkeypatch.setattr("omnigent.chat._start_local_server", fake_start_server)
monkeypatch.setattr("omnigent.chat._stop_local_server", lambda server: None)
monkeypatch.setattr("omnigent.chat._wait_for_server", lambda *a, **k: None)
monkeypatch.setattr("omnigent.chat._bundle_agent", lambda path: b"bundle")
monkeypatch.setattr(claude_native, "_prepare_claude_terminal", fake_prepare)
monkeypatch.setattr(claude_native, "attach_local_terminal", fake_attach)
monkeypatch.setattr(
claude_native,
"open_conversation_link_if_enabled",
lambda **kwargs: opened.append(
(
kwargs["base_url"],
kwargs["conversation_id"],
kwargs["enabled"],
)
),
)
claude_native._run_with_local_server(
spec_path,
session_id=None,
resume_picker=False,
claude_args=(),
command="claude",
auto_open_conversation=True,
)
state = read_launch_state("conv_local_fresh")
assert state is not None, (
"local-server fresh-session create did not persist launch state. "
"The local variant of the call site is broken (or missing); the "
"remote variant is exercised by a sibling test, so failing here "
"narrows the regression to ``_run_with_local_server``."
)
assert state.working_directory == str(workspace.resolve()), (
f"recorded cwd {state.working_directory!r} does not match the "
f"workspace the wrapper ran in ({str(workspace.resolve())!r})."
)
captured = capsys.readouterr()
web_ui = "Web UI: http://127.0.0.1:12345/c/conv_local_fresh"
resume_hint = "Resume with: omnigent claude --resume conv_local_fresh"
assert web_ui in captured.err
assert resume_hint in captured.err
assert captured.err.index(web_ui) < captured.err.index(resume_hint)
assert opened == [("http://127.0.0.1:12345", "conv_local_fresh", True)]
def test_local_resume_does_not_print_redundant_resume_hint(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""
``omnigent claude --resume`` does not echo another resume prompt.
The final hint is useful when a fresh launch creates a new
conversation id. On an explicit resume, the user already supplied
that id; printing the same prompt again creates persistent noise.
"""
spec_path = tmp_path / "claude.yaml"
spec_path.write_text("name: claude-native-ui\nprompt: hi\n", encoding="utf-8")
class _Proc:
"""Stub for the local server subprocess."""
def poll(self) -> None:
"""
Pretend the server is alive.
:returns: None.
"""
def fake_start_server(*args: object, **kwargs: object) -> Any:
"""
Return a minimal server handle without spawning anything.
:param args: Positional startup args.
:param kwargs: Keyword startup args.
:returns: Fake local server handle.
"""
del args, kwargs
return SimpleNamespace(proc=_Proc(), runner_id="runner_local", log_path=None)
async def fake_prepare(**kwargs: object) -> claude_native.PreparedClaudeTerminal:
"""
Return a prepared terminal for the resumed conversation.
:param kwargs: Terminal preparation kwargs.
:returns: Prepared fake terminal.
"""
del kwargs
return claude_native.PreparedClaudeTerminal(
session_id="conv_existing",
terminal_id=claude_native.claude_terminal_resource_id(),
bridge_dir=tmp_path / "bridge",
reattached=False,
)
async def fake_attach(
attach_url: str,
*,
headers: dict[str, str],
terminal_gone_probe: object | None = None,
) -> bool:
"""
Exit immediately so the attach loop returns.
:param attach_url: Terminal attach URL.
:param headers: Auth headers.
:param terminal_gone_probe: Optional terminal-gone callback.
:returns: ``True`` for user-requested exit.
"""
del attach_url, headers, terminal_gone_probe
return True
monkeypatch.setattr("omnigent.chat._find_free_port", lambda: 12346)
monkeypatch.setattr("omnigent.chat._start_local_server", fake_start_server)
monkeypatch.setattr("omnigent.chat._stop_local_server", lambda server: None)
monkeypatch.setattr("omnigent.chat._wait_for_server", lambda *a, **k: None)
monkeypatch.setattr(claude_native, "_prepare_claude_terminal", fake_prepare)
monkeypatch.setattr(claude_native, "attach_local_terminal", fake_attach)
claude_native._run_with_local_server(
spec_path,
session_id="conv_existing",
resume_picker=False,
claude_args=(),
command="claude",
)
captured = capsys.readouterr()
assert "Web UI: http://127.0.0.1:12346/c/conv_existing" in captured.err
assert "Resume with:" not in captured.err
def test_remote_daemon_run_attaches_without_cli_forwarder(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
"""
Daemon-routed ``omnigent claude`` leaves forwarding to the runner.
The daemon path launches a runner, the runner auto-creates the
Claude terminal, and that auto-create starts the transcript
forwarder. The CLI should only attach to tmux/WebSocket. If this
call site omits ``run_transcript_forwarder=False``, the CLI starts a
second forwarder on the same bridge and every transcript item is
posted to Omnigent twice.
:param monkeypatch: Pytest monkeypatch fixture.
:param tmp_path: Temporary directory for the generated spec and bridge.
:returns: None.
"""
spec_path = tmp_path / "claude.yaml"
spec_path.write_text("name: claude-native-ui\nprompt: hi\n", encoding="utf-8")
captured_attach: dict[str, Any] = {}
recorded_launches: list[str] = []
async def fake_prepare(**kwargs: object) -> claude_native.PreparedClaudeTerminal:
"""
Return a runner-owned prepared terminal.
:param kwargs: Daemon preparation kwargs.
:returns: Prepared fake terminal using a session-keyed bridge.
"""
assert kwargs["host_id"] == "host_test"
assert kwargs["workspace"] == str(Path.cwd().resolve())
assert isinstance(kwargs["startup_progress"], RunnerStartupProgress)
return claude_native.PreparedClaudeTerminal(
session_id="conv_daemon",
terminal_id=claude_native.claude_terminal_resource_id(),
bridge_dir=tmp_path / "bridge",
reattached=False,
tmux_socket="/tmp/claude.sock",
tmux_target="claude:main",
)
async def fake_attach_with_forwarder_switch(**kwargs: object) -> claude_native._AttachOutcome:
"""
Capture attach-helper kwargs without starting an attach loop.
:param kwargs: Arguments passed to
:func:`_attach_with_transcript_forwarder`.
:returns: ``EXITED`` so the remote runner path completes.
"""
captured_attach.update(kwargs)
return claude_native._AttachOutcome.EXITED
monkeypatch.setattr("omnigent.chat._bundle_agent", lambda path: b"bundle")
monkeypatch.setattr(
"omnigent.chat._remote_headers",
lambda server_url=None: {"Authorization": "Bearer tok"},
)
monkeypatch.setattr("omnigent.chat._server_auth", lambda server_url=None: None)
monkeypatch.setattr("omnigent.cli._ensure_host_daemon", lambda base_url: None)
monkeypatch.setattr(
"omnigent.host.identity.load_or_create_host_identity",
lambda: SimpleNamespace(host_id="host_test"),
)