-
Notifications
You must be signed in to change notification settings - Fork 561
Expand file tree
/
Copy pathtest_gateway_cmd.py
More file actions
1532 lines (1179 loc) · 53.9 KB
/
Copy pathtest_gateway_cmd.py
File metadata and controls
1532 lines (1179 loc) · 53.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import contextlib
import json
import os
import platform
import signal
import sys
import tomllib
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from urllib.error import URLError
import pytest
import typer
from typer.testing import CliRunner
from opensquilla.cli import gateway_cmd, gateway_lifecycle
from opensquilla.cli.gateway_cmd import gateway_startup_guidance
from opensquilla.cli.main import app
from opensquilla.paths import default_opensquilla_home
runner = CliRunner()
Manager = gateway_lifecycle.GatewayLifecycleManager
def _env_command(env_key: str) -> str:
# Mirrors next_steps.set_env_command: recovery ``command`` fields are the
# bare command on every platform (no "PowerShell:" label).
if platform.system().lower().startswith("win"):
return f'$env:{env_key} = "<your-key>"'
return f'export {env_key}="<your-key>"'
def _payload(result):
return json.loads(result.stdout)
def _write_pidfile(record: dict) -> None:
path = gateway_lifecycle.gateway_pidfile_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(record), encoding="utf-8")
def _record(pid: int = 1234, *, port: int = 18791) -> dict:
return {
"pid": pid,
"host": "127.0.0.1",
"port": port,
"url": f"http://127.0.0.1:{port}",
"healthUrl": f"http://127.0.0.1:{port}/health",
"logPath": str(gateway_lifecycle.gateway_log_path()),
"startedAt": "2026-05-04T00:00:00Z",
"argv": [
sys.executable,
"-m",
"opensquilla.cli.main",
"gateway",
"run",
"--listen",
"127.0.0.1",
"--port",
str(port),
],
}
def _patch_health(monkeypatch, value: bool) -> None:
monkeypatch.setattr(Manager, "_probe_health", lambda self: value)
def _patch_wait_for_health(monkeypatch, value: bool) -> None:
monkeypatch.setattr(Manager, "_wait_for_health", lambda self: value)
def _patch_pid_running(monkeypatch, value: bool) -> None:
monkeypatch.setattr(Manager, "_pid_running", lambda self, pid: value)
def _profile_tree_snapshot(home: Path) -> dict[str, tuple[str, bytes]]:
snapshot: dict[str, tuple[str, bytes]] = {}
for path in sorted(home.rglob("*")):
relative = path.relative_to(home).as_posix()
snapshot[relative] = ("directory", b"") if path.is_dir() else ("file", path.read_bytes())
return snapshot
def _unsafe_desktop_profile(home: Path, *, port: int = 0) -> None:
state = home / "state"
lifecycle = state / "gateway"
lifecycle.mkdir(parents=True)
missing_workspace = home.parent / "missing-workspace"
# config_version = 999 is the remaining hard startup gate: a config
# authored by a newer build must never be reinterpreted by this one.
(home / "config.toml").write_text(
"config_version = 999\n"
f"state_dir = {json.dumps(str(state))}\n"
f"workspace_dir = {json.dumps(str(missing_workspace))}\n",
encoding="utf-8",
)
(lifecycle / "gateway.json").write_text(
json.dumps(_record(pid=999_999, port=port)),
encoding="utf-8",
)
logs = home / "logs"
logs.mkdir()
(logs / "gateway.log").write_bytes(b"synthetic-existing-log\n")
def _safe_desktop_profile(home: Path) -> None:
state = home / "state"
workspace = home / "workspace"
state.mkdir(parents=True)
workspace.mkdir()
(workspace / "SOUL.md").write_text("synthetic-safe-profile\n", encoding="utf-8")
(home / "config.toml").write_text(
f"state_dir = {json.dumps(str(state))}\n"
f"workspace_dir = {json.dumps(str(workspace))}\n",
encoding="utf-8",
)
class _FakeHealthResponse:
status = 200
def __enter__(self):
return self
def __exit__(self, exc_type, exc, traceback) -> None:
return None
def test_gateway_startup_guidance_shows_operator_next_steps() -> None:
guidance = gateway_startup_guidance("127.0.0.1", 18791)
assert "[bold]Web UI:[/bold] http://127.0.0.1:18791/control/" in guidance
assert "[bold]API base:[/bold] http://127.0.0.1:18791" in guidance
debug_log = default_opensquilla_home() / "logs" / "debug.log"
assert f"[bold]Debug log:[/bold] {debug_log}" in guidance
assert "[dim]Keep this terminal open. Press Ctrl+C to stop.[/dim]" in guidance
def test_gateway_run_turns_missing_onboarding_env_into_recovery_hint(
tmp_path,
monkeypatch,
) -> None:
target = tmp_path / "custom.toml"
target.write_text(
'[llm]\n'
'provider = "openrouter"\n'
'model = "deepseek/deepseek-v4-flash"\n'
'api_key = "sk-or"\n'
'\n'
'[memory.embedding]\n'
'provider = "openai"\n'
'\n'
'[memory.embedding.remote]\n'
'api_key_env = "OPENAI_EMBEDDINGS_API_KEY"\n',
encoding="utf-8",
)
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
monkeypatch.delenv("OPENAI_EMBEDDINGS_API_KEY", raising=False)
async def fail_start_gateway_server(**_kwargs):
raise ValueError(
"memory.embedding.provider='openai' requires "
"memory.embedding.remote.api_key"
)
monkeypatch.setattr(gateway_cmd, "_gateway_bind_available", lambda *_args: True)
monkeypatch.setattr(gateway_cmd, "start_gateway_server", fail_start_gateway_server)
result = runner.invoke(app, ["gateway", "run", "--config", str(target)])
assert result.exit_code == 1
output = result.stdout + (result.stderr or "")
compact = "".join(output.split())
assert "Gateway could not start" in output
assert (
f"Set memory key: {_env_command('OPENAI_EMBEDDINGS_API_KEY')}".replace(" ", "")
in compact
)
expected_config = str(target).replace("\\", "/")
normalized = compact.replace("\\", "/")
assert "opensquillaonboardstatus--config" in normalized
assert expected_config in normalized
assert normalized.index("opensquillaonboardstatus--config") < normalized.index(
expected_config
)
assert "Traceback" not in output
def test_gateway_run_reports_invalid_config_without_traceback(
tmp_path,
monkeypatch,
) -> None:
target = tmp_path / "custom.toml"
target.write_text("workspace_dir = [\n", encoding="utf-8")
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
result = runner.invoke(app, ["gateway", "run", "--config", str(target)])
assert result.exit_code == 1
output = result.stdout + (result.stderr or "")
compact = "".join(output.split())
assert "Invalid gateway config" in output
assert "custom.toml" in compact
assert "recoveryrecover-config" in compact
assert "Traceback" not in output
def test_gateway_run_memory_recovery_command_is_bare_on_windows(
tmp_path,
monkeypatch,
) -> None:
"""The recovery ``command`` field is machine-shaped on every surface: the
gateway-run fallback entry must carry the bare set-env command on Windows
(no "PowerShell:" label), matching env_recovery_commands."""
from opensquilla.onboarding import next_steps
target = tmp_path / "custom.toml"
target.write_text(
'[llm]\n'
'provider = "openrouter"\n'
'model = "dummy/model"\n'
'api_key = "sk-dummy"\n'
'\n'
'[memory.embedding.remote]\n'
'api_key_env = "DUMMY_UNSET_EMBED_KEY"\n',
encoding="utf-8",
)
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
monkeypatch.delenv("DUMMY_UNSET_EMBED_KEY", raising=False)
monkeypatch.setattr(next_steps, "_is_windows", lambda: True)
async def fail_start_gateway_server(**_kwargs):
raise ValueError(
"memory.embedding.provider='openai' requires "
"memory.embedding.remote.api_key"
)
monkeypatch.setattr(gateway_cmd, "_gateway_bind_available", lambda *_args: True)
monkeypatch.setattr(gateway_cmd, "start_gateway_server", fail_start_gateway_server)
result = runner.invoke(app, ["gateway", "run", "--config", str(target)])
assert result.exit_code == 1
output = result.stdout + (result.stderr or "")
compact = "".join(output.split())
expected = 'Set memory key: $env:DUMMY_UNSET_EMBED_KEY = "<your-key>"'
assert expected.replace(" ", "") in compact
assert "PowerShell" not in output
def test_gateway_lifecycle_paths_use_state_root(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
assert gateway_lifecycle.gateway_pidfile_path() == (
tmp_path / "home" / "state" / "gateway" / "gateway.json"
)
assert gateway_lifecycle.gateway_log_path() == tmp_path / "home" / "logs" / "gateway.log"
def test_safe_desktop_gateway_start_uses_external_lifecycle_state(
tmp_path: Path,
monkeypatch,
) -> None:
home = tmp_path / "opensquilla"
user_state = tmp_path / "user-state"
_safe_desktop_profile(home)
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(home))
monkeypatch.setenv("OPENSQUILLA_PROFILE_KIND", "desktop-primary")
monkeypatch.setenv("OPENSQUILLA_TEST", "1")
monkeypatch.setenv("OPENSQUILLA_USER_STATE_DIR", str(user_state))
calls = []
def fake_popen(argv, **kwargs):
calls.append((argv, kwargs))
return SimpleNamespace(pid=4242)
monkeypatch.setattr(gateway_lifecycle.subprocess, "Popen", fake_popen)
_patch_health(monkeypatch, False)
_patch_wait_for_health(monkeypatch, True)
result = runner.invoke(app, ["gateway", "start", "--port", "0", "--json"])
assert result.exit_code == 0, result.stdout
payload = _payload(result)
pidfile = Path(payload["pidfile"])
log_path = Path(payload["logPath"])
assert payload["state"] == "running"
assert calls
assert home not in pidfile.parents
assert home not in log_path.parents
assert user_state in pidfile.parents
assert user_state in log_path.parents
@pytest.mark.parametrize("action", ["start", "restart"])
def test_unsafe_desktop_gateway_lifecycle_blocks_before_spawn_or_write(
action: str,
tmp_path: Path,
monkeypatch,
) -> None:
home = tmp_path / "opensquilla"
user_state = tmp_path / "user-state"
_unsafe_desktop_profile(home)
before = _profile_tree_snapshot(home)
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(home))
monkeypatch.setenv("OPENSQUILLA_PROFILE_KIND", "desktop-primary")
monkeypatch.setenv("OPENSQUILLA_TEST", "1")
monkeypatch.setenv("OPENSQUILLA_USER_STATE_DIR", str(user_state))
def fail_spawn(self, argv):
raise AssertionError("unsafe Desktop profile must not spawn a gateway")
monkeypatch.setattr(Manager, "_spawn_gateway", fail_spawn)
result = getattr(Manager(port=0, health_timeout=0), action)()
assert result.ok is False
assert result.state == "recovery_required"
assert result.code == "DESKTOP_PROFILE_RECOVERY_REQUIRED"
assert result.details["stableCode"] == "config_schema_too_new"
assert _profile_tree_snapshot(home) == before
assert not user_state.exists()
@pytest.mark.parametrize("action", ["start", "restart"])
def test_desktop_lifecycle_rejects_config_outside_profile_before_write(
action: str,
tmp_path: Path,
monkeypatch,
) -> None:
home = tmp_path / "opensquilla"
user_state = tmp_path / "user-state"
_safe_desktop_profile(home)
outside = tmp_path / "outside.toml"
outside.write_text("synthetic = true\n", encoding="utf-8")
before = _profile_tree_snapshot(home)
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(home))
monkeypatch.setenv("OPENSQUILLA_PROFILE_KIND", "desktop-primary")
monkeypatch.setenv("OPENSQUILLA_TEST", "1")
monkeypatch.setenv("OPENSQUILLA_USER_STATE_DIR", str(user_state))
result = getattr(
Manager(config_path=str(outside), port=0, health_timeout=0),
action,
)()
assert result.ok is False
assert result.code == "DESKTOP_PROFILE_RECOVERY_REQUIRED"
assert result.details["stableCode"] == "desktop_config_outside_profile"
assert result.details["allowedActions"] == ["retry-primary"]
assert "launch-recovery-profile" not in result.details["allowedActions"]
assert "primary profile" in result.message
assert _profile_tree_snapshot(home) == before
assert not user_state.exists()
def test_desktop_gateway_run_rejects_config_outside_profile_before_loading_it(
tmp_path: Path,
monkeypatch,
) -> None:
home = tmp_path / "opensquilla"
_safe_desktop_profile(home)
outside = tmp_path / "outside.toml"
outside.write_text("synthetic = true\n", encoding="utf-8")
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(home))
monkeypatch.setenv("OPENSQUILLA_PROFILE_KIND", "desktop-primary")
def fail_load(*_args, **_kwargs):
raise AssertionError("out-of-profile config must be rejected before load")
monkeypatch.setattr(gateway_cmd.GatewayConfig, "load", fail_load)
result = runner.invoke(app, ["gateway", "run", "--config", str(outside)])
assert result.exit_code == 1
assert "DESKTOP_CONFIG_OUTSIDE_PROFILE" in result.stdout
@pytest.mark.parametrize(
"lock_error_name",
["ProfileLockBusyError", "LegacyGatewayRunningError"],
)
def test_gateway_run_emits_stable_profile_in_use_error_without_sensitive_path(
tmp_path: Path,
monkeypatch,
lock_error_name: str,
) -> None:
from opensquilla import recovery
sensitive_profile = tmp_path / "customer-private-profile"
lock_error = getattr(recovery, lock_error_name)
@contextlib.contextmanager
def busy_profile_guard(**_kwargs):
raise lock_error(
f"profile is in use by another writer: {sensitive_profile}"
)
yield # pragma: no cover - contextmanager shape only
def fail_run_gateway(**_kwargs) -> None:
raise AssertionError("gateway must not start without the profile lock")
monkeypatch.setattr(recovery, "guarded_desktop_profile", busy_profile_guard)
monkeypatch.setattr(gateway_cmd, "run_gateway", fail_run_gateway)
result = runner.invoke(app, ["gateway", "run"])
assert result.exit_code == 1
output = result.stdout + (result.stderr or "")
assert output.count("OPENSQUILLA_PROFILE_IN_USE") == 1
assert "Another OpenSquilla process is still using this profile" in output
assert "restart the computer" in output
assert "Do not delete profile lock files" in output
assert str(sensitive_profile) not in output
assert lock_error_name not in output
assert "Traceback" not in output
def test_gateway_help_lists_lifecycle_commands() -> None:
result = runner.invoke(app, ["gateway", "--help"])
assert result.exit_code == 0
assert "run" in result.stdout
assert "start" in result.stdout
assert "status" in result.stdout
assert "stop" in result.stdout
assert "restart" in result.stdout
def test_gateway_subapp_disables_pretty_exceptions() -> None:
from opensquilla.cli.main import gateway_app
assert gateway_app.pretty_exceptions_enable is False
def test_gateway_start_help_explains_config_backed_target_defaults() -> None:
result = runner.invoke(app, ["gateway", "start", "--help"])
assert result.exit_code == 0
assert "Port to bind (default: config port, usually 18791)" in result.stdout
assert "Host to bind (default: config host, usually 127.0.0.1)" in result.stdout
def test_gateway_status_json_reports_not_started(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
_patch_health(monkeypatch, False)
result = runner.invoke(app, ["gateway", "status", "--json"])
assert result.exit_code == 0
payload = _payload(result)
assert payload["ok"] is True
assert payload["state"] == "not_started"
assert payload["managed"] is False
def test_gateway_status_gateway_url_probes_remote_https_health(monkeypatch) -> None:
urls = []
def fake_urlopen(request, timeout):
urls.append(request.full_url)
assert timeout == 0.5
return _FakeHealthResponse()
monkeypatch.setattr(gateway_lifecycle, "urlopen", fake_urlopen)
result = runner.invoke(
app,
["gateway", "status", "--gateway", "https://squilla.example.com", "--json"],
)
assert result.exit_code == 0, result.stdout
payload = _payload(result)
assert payload["ok"] is True
assert payload["remote"] is True
assert payload["managed"] is False
assert payload["state"] == "running"
assert payload["gatewayUrl"] == "wss://squilla.example.com/ws"
assert payload["url"] == "https://squilla.example.com"
assert payload["healthUrl"] == "https://squilla.example.com/health"
assert urls == ["https://squilla.example.com/health"]
def test_gateway_status_gateway_url_reports_remote_unavailable(monkeypatch) -> None:
urls = []
def fake_urlopen(request, timeout):
urls.append(request.full_url)
assert timeout == 0.5
raise OSError("offline")
monkeypatch.setattr(gateway_lifecycle, "urlopen", fake_urlopen)
result = runner.invoke(
app,
["gateway", "status", "--gateway", "wss://squilla.example.com/ws", "--json"],
)
assert result.exit_code == 1, result.stdout
payload = _payload(result)
assert payload["ok"] is False
assert payload["remote"] is True
assert payload["managed"] is False
assert payload["state"] == "unavailable"
assert payload["code"] == "REMOTE_GATEWAY_UNAVAILABLE"
assert payload["gatewayUrl"] == "wss://squilla.example.com/ws"
assert payload["url"] == "https://squilla.example.com"
assert payload["healthUrl"] == "https://squilla.example.com/health"
assert urls == [
"https://squilla.example.com/health",
"https://squilla.example.com/healthz",
]
assert [attempt["errorType"] for attempt in payload["details"]["attempts"]] == [
"OSError",
"OSError",
]
def test_gateway_status_reports_stale_without_mutating_pidfile(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
_write_pidfile(_record(pid=9999))
before = gateway_lifecycle.gateway_pidfile_path().read_text(encoding="utf-8")
_patch_pid_running(monkeypatch, False)
_patch_health(monkeypatch, False)
result = runner.invoke(app, ["gateway", "status", "--json"])
assert result.exit_code == 0
assert _payload(result)["state"] == "stale"
assert gateway_lifecycle.gateway_pidfile_path().read_text(encoding="utf-8") == before
def test_gateway_start_refuses_unmanaged_healthy_gateway(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
_patch_health(monkeypatch, True)
result = runner.invoke(app, ["gateway", "start", "--json"])
assert result.exit_code == 3
payload = _payload(result)
assert payload["ok"] is False
assert payload["state"] == "unmanaged"
assert payload["code"] == "UNMANAGED_GATEWAY_RUNNING"
assert "http://127.0.0.1:18791" in payload["message"]
assert "host=127.0.0.1" in payload["message"]
assert "port=18791" in payload["message"]
assert not gateway_lifecycle.gateway_pidfile_path().exists()
def test_gateway_start_uses_same_interpreter_cli_boundary(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
calls = []
def fake_popen(argv, **kwargs):
calls.append((argv, kwargs))
return SimpleNamespace(pid=4242)
monkeypatch.setattr(gateway_lifecycle.subprocess, "Popen", fake_popen)
_patch_health(monkeypatch, False)
_patch_wait_for_health(monkeypatch, True)
result = runner.invoke(
app,
["gateway", "start", "--listen", "127.0.0.2", "--port", "18888", "--json"],
)
assert result.exit_code == 0, result.stdout
payload = _payload(result)
assert payload["state"] == "running"
assert payload["pid"] == 4242
argv, kwargs = calls[0]
assert argv[:5] == [sys.executable, "-m", "opensquilla.cli.main", "gateway", "run"]
assert "--listen" in argv
assert argv[argv.index("--listen") + 1] == "127.0.0.2"
assert kwargs["shell"] is False
def test_gateway_start_frozen_binary_invokes_subcommand_directly(tmp_path, monkeypatch) -> None:
# In a PyInstaller-frozen desktop bundle sys.executable already is the CLI
# entrypoint, so "-m opensquilla.cli.main" would be handed to Typer as
# arguments and the child would exit on a usage error.
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
monkeypatch.setattr(sys, "frozen", True, raising=False)
calls = []
def fake_popen(argv, **kwargs):
calls.append((argv, kwargs))
return SimpleNamespace(pid=4243)
monkeypatch.setattr(gateway_lifecycle.subprocess, "Popen", fake_popen)
_patch_health(monkeypatch, False)
_patch_wait_for_health(monkeypatch, True)
result = runner.invoke(
app,
["gateway", "start", "--listen", "127.0.0.2", "--port", "18888", "--json"],
)
assert result.exit_code == 0, result.stdout
argv, _ = calls[0]
assert argv[:3] == [sys.executable, "gateway", "run"]
assert "-m" not in argv
assert "opensquilla.cli.main" not in argv
assert argv[argv.index("--listen") + 1] == "127.0.0.2"
def test_gateway_start_uses_explicit_config_path(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
default_config = tmp_path / "default.toml"
custom_config = tmp_path / "custom.toml"
monkeypatch.setenv("OPENSQUILLA_GATEWAY_CONFIG_PATH", str(default_config))
calls = []
def fake_popen(argv, **kwargs):
calls.append((argv, kwargs))
return SimpleNamespace(pid=4245)
monkeypatch.setattr(gateway_lifecycle.subprocess, "Popen", fake_popen)
_patch_health(monkeypatch, False)
_patch_wait_for_health(monkeypatch, True)
result = runner.invoke(
app,
["gateway", "start", "--config", str(custom_config), "--json"],
)
assert result.exit_code == 0, result.stdout
argv, kwargs = calls[0]
assert argv[argv.index("--config") + 1] == str(custom_config)
assert kwargs["env"]["OPENSQUILLA_GATEWAY_CONFIG_PATH"] == str(custom_config)
record = json.loads(gateway_lifecycle.gateway_pidfile_path().read_text(encoding="utf-8"))
assert record["configPath"] == str(custom_config)
def test_gateway_start_uses_config_host_port_when_flags_are_omitted(
tmp_path, monkeypatch
) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
custom_config = tmp_path / "custom.toml"
custom_config.write_text('host = "127.0.0.2"\nport = 19999\n', encoding="utf-8")
calls = []
def fake_popen(argv, **kwargs):
calls.append((argv, kwargs))
return SimpleNamespace(pid=4246)
monkeypatch.setattr(gateway_lifecycle.subprocess, "Popen", fake_popen)
_patch_health(monkeypatch, False)
_patch_wait_for_health(monkeypatch, True)
result = runner.invoke(
app,
["gateway", "start", "--config", str(custom_config), "--json"],
)
assert result.exit_code == 0, result.stdout
argv, _kwargs = calls[0]
assert argv[argv.index("--listen") + 1] == "127.0.0.2"
assert argv[argv.index("--port") + 1] == "19999"
payload = _payload(result)
assert payload["url"] == "http://127.0.0.2:19999"
def test_gateway_start_rejects_out_of_range_port_before_spawn(
tmp_path, monkeypatch
) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
def fail_popen(*_args, **_kwargs):
raise AssertionError("invalid port must not spawn a gateway")
monkeypatch.setattr(gateway_lifecycle.subprocess, "Popen", fail_popen)
result = runner.invoke(app, ["gateway", "start", "--port", "65536", "--json"])
assert result.exit_code == 2
assert "65536 is not in the range 0<=x<=65535" in result.stderr
def test_gateway_status_uses_config_host_port_when_flags_are_omitted(
tmp_path, monkeypatch
) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
custom_config = tmp_path / "custom.toml"
custom_config.write_text('host = "127.0.0.2"\nport = 19999\n', encoding="utf-8")
probes = []
def fake_probe(self):
probes.append((self.host, self.port))
return False
monkeypatch.setattr(Manager, "_probe_health", fake_probe)
result = runner.invoke(
app,
["gateway", "status", "--config", str(custom_config), "--json"],
)
assert result.exit_code == 0, result.stdout
assert probes == [("127.0.0.2", 19999)]
payload = _payload(result)
assert payload["url"] == "http://127.0.0.2:19999"
def test_gateway_run_uses_config_host_port_when_flags_are_omitted(
tmp_path, monkeypatch
) -> None:
custom_config = tmp_path / "custom.toml"
custom_config.write_text('host = "127.0.0.2"\nport = 19999\n', encoding="utf-8")
captured = {}
class FakeServer:
def __init__(self, task):
self._task = task
async def close(self, _reason):
return None
async def fake_start_gateway_server(
*, config, subscription_manager, run, _startup_started_at
):
captured["config"] = config
captured["startup_started_at"] = _startup_started_at
async def done():
return None
import asyncio
return FakeServer(asyncio.create_task(done()))
monkeypatch.setattr(gateway_cmd, "_gateway_bind_available", lambda *_args: True)
monkeypatch.setattr(gateway_cmd, "start_gateway_server", fake_start_gateway_server)
with pytest.raises(typer.Exit) as exc_info:
gateway_cmd.run_gateway(
port=None,
bind=None,
listen="",
debug=False,
config_path=str(custom_config),
)
assert exc_info.value.exit_code == 1
assert captured["config"].host == "127.0.0.2"
assert captured["config"].port == 19999
assert isinstance(captured["startup_started_at"], float)
def test_gateway_run_records_cli_flags_as_runtime_overrides(
tmp_path, monkeypatch
) -> None:
"""Boot-time --listen/--port/--debug are runtime state, not operator
config edits: run_gateway must record runtime provenance for the fields
it mutates so the sparse persister can keep them out of config.toml."""
custom_config = tmp_path / "custom.toml"
custom_config.write_text('host = "127.0.0.1"\nport = 18791\n', encoding="utf-8")
captured = {}
class FakeServer:
def __init__(self, task):
self._task = task
async def close(self, _reason):
return None
async def fake_start_gateway_server(
*, config, subscription_manager, run, _startup_started_at
):
captured["config"] = config
async def done():
return None
return FakeServer(asyncio.ensure_future(done()))
monkeypatch.setattr(gateway_cmd, "_gateway_bind_available", lambda *_args: True)
monkeypatch.setattr(gateway_cmd, "start_gateway_server", fake_start_gateway_server)
with pytest.raises(typer.Exit) as exc_info:
gateway_cmd.run_gateway(
port=18888,
bind=None,
listen="0.0.0.0",
debug=True,
config_path=str(custom_config),
)
assert exc_info.value.exit_code == 1
overrides = captured["config"].runtime_field_overrides()
assert overrides["host"] == ("127.0.0.1", "0.0.0.0")
assert overrides["port"] == (18791, 18888)
assert overrides["debug"] == (False, True)
def test_gateway_run_flags_do_not_leak_into_config_via_unrelated_persist(
tmp_path, monkeypatch
) -> None:
"""F4 regression: `gateway run --listen 0.0.0.0 --debug` for a one-off
session followed by an onboarding-surface save of an unrelated section
must not bake host/debug into config.toml permanently."""
from opensquilla.onboarding.config_store import load_config, persist_config
from opensquilla.onboarding.mutations import upsert_search_provider
custom_config = tmp_path / "custom.toml"
custom_config.write_text('host = "127.0.0.1"\nport = 18791\n', encoding="utf-8")
captured = {}
class FakeServer:
def __init__(self, task):
self._task = task
async def close(self, _reason):
return None
async def fake_start_gateway_server(
*, config, subscription_manager, run, _startup_started_at
):
captured["config"] = config
async def done():
return None
return FakeServer(asyncio.ensure_future(done()))
monkeypatch.setattr(gateway_cmd, "_gateway_bind_available", lambda *_args: True)
monkeypatch.setattr(gateway_cmd, "start_gateway_server", fake_start_gateway_server)
with pytest.raises(typer.Exit) as exc_info:
gateway_cmd.run_gateway(
port=None,
bind=None,
listen="0.0.0.0",
debug=True,
config_path=str(custom_config),
)
assert exc_info.value.exit_code == 1
boot_config = captured["config"]
assert boot_config.host == "0.0.0.0"
assert boot_config.debug is True
# Web-UI save of an unrelated onboarding section: the mutation clone
# inherits the boot config's provenance and is what the RPC layer
# persists (rpc_onboarding._persist -> persist_config).
res = upsert_search_provider(
boot_config, provider_id="tavily", api_key="tvly-synthetic-run"
)
persist_config(res.config, path=custom_config)
data = tomllib.loads(custom_config.read_text())
assert data["search_api_key"] == "tvly-synthetic-run"
assert data["host"] == "127.0.0.1" # transient --listen never lands
assert data.get("debug", False) is False # transient --debug never lands
assert data.get("port", 18791) == 18791
# The file is still what the operator wrote plus the search save: a
# fresh load must not come up publicly bound or in debug mode.
reloaded = load_config(custom_config)
assert reloaded.host == "127.0.0.1"
assert reloaded.debug is False
def test_gateway_run_keeps_missing_explicit_config_path_for_setup(
tmp_path,
monkeypatch,
) -> None:
custom_config = tmp_path / "first-run.toml"
captured = {}
class FakeServer:
def __init__(self, task):
self._task = task
async def close(self, _reason):
return None
async def fake_start_gateway_server(
*, config, subscription_manager, run, _startup_started_at
):
captured["config"] = config
async def done():
return None
import asyncio
return FakeServer(asyncio.create_task(done()))
monkeypatch.setattr(gateway_cmd, "_gateway_bind_available", lambda *_args: True)
monkeypatch.setattr(gateway_cmd, "start_gateway_server", fake_start_gateway_server)
with pytest.raises(typer.Exit) as exc_info:
gateway_cmd.run_gateway(
port=19876,
bind=None,
listen="",
debug=False,
config_path=str(custom_config),
)
assert exc_info.value.exit_code == 1
assert captured["config"].config_path == str(custom_config)
assert not custom_config.exists()
def test_gateway_run_preflights_occupied_port_before_building_services(
tmp_path,
monkeypatch,
) -> None:
custom_config = tmp_path / "custom.toml"
custom_config.write_text('host = "127.0.0.2"\nport = 19999\n', encoding="utf-8")
async def fail_start_gateway_server(**_kwargs):
raise AssertionError("gateway services should not build when bind preflight fails")
monkeypatch.setattr(gateway_cmd, "start_gateway_server", fail_start_gateway_server)
monkeypatch.setattr(gateway_cmd, "_gateway_bind_available", lambda host, port: False)
result = runner.invoke(
app,
["gateway", "run", "--config", str(custom_config)],
)
assert result.exit_code == 1
assert "127.0.0.2:19999 is already in use" in result.stdout
def test_gateway_start_waits_for_readiness_after_liveness(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
calls = []
health_checks = 0
ready_checks = []
def fake_popen(argv, **kwargs):
calls.append((argv, kwargs))
return SimpleNamespace(pid=4244)
def fake_health(self):
nonlocal health_checks
health_checks += 1
return health_checks > 1
def fake_ready(self):
ready_checks.append(True)
return len(ready_checks) > 1
monkeypatch.setattr(gateway_lifecycle.subprocess, "Popen", fake_popen)
monkeypatch.setattr(Manager, "_probe_health", fake_health)
monkeypatch.setattr(Manager, "_probe_ready", fake_ready, raising=False)
monkeypatch.setattr(gateway_lifecycle.time, "sleep", lambda _seconds: None)
result = runner.invoke(app, ["gateway", "start", "--json"])
assert result.exit_code == 0, result.stdout
assert _payload(result)["state"] == "running"
assert calls
assert len(ready_checks) == 2
def test_gateway_health_probe_uses_loopback_for_wildcard_bind(monkeypatch) -> None:
urls = []
def fake_urlopen(request, timeout):
urls.append(request.full_url)
assert timeout == 0.5
return _FakeHealthResponse()
monkeypatch.setattr(gateway_lifecycle, "urlopen", fake_urlopen)
manager = Manager(host="0.0.0.0", port=18888)
assert manager._probe_health() is True
assert urls == ["http://127.0.0.1:18888/health"]
def test_gateway_start_with_wildcard_listen_keeps_bind_and_reports_probe_host(
tmp_path,
monkeypatch,
) -> None:
monkeypatch.setenv("OPENSQUILLA_STATE_DIR", str(tmp_path / "home"))
calls = []
def fake_popen(argv, **kwargs):
calls.append((argv, kwargs))
return SimpleNamespace(pid=4243)
monkeypatch.setattr(gateway_lifecycle.subprocess, "Popen", fake_popen)
_patch_health(monkeypatch, False)
_patch_wait_for_health(monkeypatch, True)