-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmobile_dev.py
More file actions
2721 lines (2397 loc) · 109 KB
/
Copy pathmobile_dev.py
File metadata and controls
2721 lines (2397 loc) · 109 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
#!/usr/bin/env python3
"""Utilities for the mobile-codex-dev skill.
The commands are intentionally read-only except for printing formatted output.
They help Codex quickly inspect a project, run setup checks, check ngrok
availability, and format a compact mobile handoff.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from datetime import datetime
from pathlib import Path
from typing import Any
KNOWN_PORTS = {
"next": 3000,
"next.js": 3000,
"remix": 3000,
"vite": 5173,
"sveltekit": 5173,
"astro": 4321,
"angular": 4200,
"storybook": 6006,
"django": 8000,
"fastapi": 8000,
"flask": 5000,
"rails": 3000,
"jupyter": 8888,
}
DEFAULT_NGROK_API_URL = "http://127.0.0.1:4040/api/tunnels"
COMMON_PORTS = [3000, 4200, 4321, 5000, 5173, 6006, 8000, 8080, 8888]
NGROK_SETUP_URL = "https://dashboard.ngrok.com/get-started/setup/mac-os"
UPSTREAM_REPO_URL = "https://github.com/spduk/mobilecodex"
UPSTREAM_GIT_URL = "https://github.com/spduk/mobilecodex.git"
MIN_NGROK_VERSION = (3, 20, 0)
PROOF_DIR_NAMES = ["proof", "screenshots", "artifacts"]
PROOF_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".pdf", ".html", ".txt", ".log", ".md", ".json"}
SECRET_FILE_PATTERNS = [".env", ".env.*", "*secret*", "*token*", "*credential*", "*.pem", "*.key"]
SKIP_DIR_NAMES = {".git", "node_modules", ".venv", "venv", "__pycache__", "target", "dist", "build", ".next", ".cache"}
MAX_PROOF_COPY_BYTES = 5 * 1024 * 1024
MEMORY_DIR_NAME = ".mobilecodex"
MEMORY_FILE_NAME = "memory.json"
CONTEXT_CACHE_FILE_NAME = "context-cache.md"
REQUIRED_SKILL_FILES = [
"SKILL.md",
"agents/openai.yaml",
"references/command-proof.md",
"references/mobile-handoff.md",
"references/stack-playbooks.md",
"references/final-flow-memory.md",
"references/verification-checklists.md",
"references/web-previews.md",
"scripts/mobile_dev.py",
]
def read_json(path: Path) -> dict[str, Any]:
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
def file_exists(root: Path, *names: str) -> bool:
return any((root / name).exists() for name in names)
def detect_package_manager(root: Path) -> str | None:
if (root / "pnpm-lock.yaml").exists():
return "pnpm"
if (root / "yarn.lock").exists():
return "yarn"
if (root / "bun.lockb").exists() or (root / "bun.lock").exists():
return "bun"
if (root / "package-lock.json").exists():
return "npm"
if (root / "package.json").exists():
return "npm"
return None
def detect_ports_from_scripts(scripts: dict[str, str]) -> list[int]:
ports: set[int] = set()
patterns = [
r"(?:--port|-p)\s+([0-9]{2,5})",
r"PORT=([0-9]{2,5})",
r"localhost:([0-9]{2,5})",
r"127\.0\.0\.1:([0-9]{2,5})",
]
for script in scripts.values():
for pattern in patterns:
for match in re.finditer(pattern, script):
ports.add(int(match.group(1)))
return sorted(ports)
def detect_project(root: Path) -> dict[str, Any]:
root = root.resolve()
package_json = read_json(root / "package.json") if (root / "package.json").exists() else {}
scripts = package_json.get("scripts", {}) if isinstance(package_json.get("scripts"), dict) else {}
dependencies = {}
for key in ("dependencies", "devDependencies", "peerDependencies"):
value = package_json.get(key)
if isinstance(value, dict):
dependencies.update(value)
signals: list[str] = []
commands: list[str] = []
ports = set(detect_ports_from_scripts(scripts))
package_manager = detect_package_manager(root)
if package_json:
signals.append("node")
if package_manager:
for name in ("dev", "start", "build", "test", "typecheck", "lint"):
if name in scripts:
commands.append(f"{package_manager} run {name}")
for dep in dependencies:
dep_lower = dep.lower()
if dep_lower in ("next", "vite", "astro", "@sveltejs/kit", "@angular/core", "storybook"):
label = "sveltekit" if dep_lower == "@sveltejs/kit" else dep_lower.replace("@angular/core", "angular")
signals.append(label)
if label in KNOWN_PORTS:
ports.add(KNOWN_PORTS[label])
if file_exists(root, "Cargo.toml"):
signals.append("rust")
commands.extend(["cargo test", "cargo run -- --help"])
html_files = sorted(root.glob("*.html"))
if html_files:
signals.append("static-html")
commands.append("python -m http.server 8000")
ports.add(8000)
if file_exists(root, "pyproject.toml", "requirements.txt", "setup.py"):
signals.append("python")
commands.extend(["py -m pytest", "py -m <module-or-script> --help"])
if file_exists(root, "go.mod"):
signals.append("go")
commands.extend(["go test ./...", "go run ."])
if file_exists(root, "pubspec.yaml"):
signals.append("flutter")
commands.extend(["flutter test", "flutter run -d chrome"])
if file_exists(root, "app.json", "app.config.js", "app.config.ts"):
signals.append("expo-or-react-native")
if package_manager:
commands.append(f"{package_manager} run start")
if file_exists(root, "docker-compose.yml", "docker-compose.yaml", "compose.yml"):
signals.append("docker-compose")
commands.append("docker compose up")
if file_exists(root, "Makefile"):
signals.append("make")
commands.append("make")
if file_exists(root, "justfile", "Justfile"):
signals.append("just")
commands.append("just --list")
return {
"root": str(root),
"signals": sorted(set(signals)),
"package_manager": package_manager,
"package_scripts": scripts,
"candidate_ports": sorted(ports),
"candidate_commands": dedupe(commands),
"references": recommend_references(signals),
}
def recommend_references(signals: list[str]) -> list[str]:
refs = ["references/mobile-handoff.md", "references/command-proof.md"]
web_signals = {
"next",
"vite",
"astro",
"sveltekit",
"angular",
"storybook",
"expo-or-react-native",
"flutter",
"static-html",
}
if web_signals.intersection(signals):
refs.insert(0, "references/web-previews.md")
refs.append("references/verification-checklists.md")
if signals:
refs.append("references/stack-playbooks.md")
return dedupe(refs)
def dedupe(items: list[str]) -> list[str]:
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
def compact_list(items: list[str], limit: int = 12) -> list[str]:
return [item for item in dedupe([str(item).strip() for item in items if str(item).strip()])][:limit]
def infer_dev_command(detected: dict[str, Any]) -> str | None:
commands = detected.get("candidate_commands") or []
for preferred in ("run dev", "run start", "python -m http.server"):
for command in commands:
if preferred in command:
return command
return commands[0] if commands else None
def infer_test_command(detected: dict[str, Any]) -> str | None:
commands = detected.get("candidate_commands") or []
for command in commands:
if any(token in command for token in (" run test", "pytest", "cargo test", "go test", "flutter test")):
return command
return None
def load_memory(root: Path) -> dict[str, Any]:
path = memory_path(root)
if not path.exists():
return {
"workspace": str(root.resolve()),
"preferred_dev_command": None,
"preferred_preview_port": None,
"package_manager": None,
"preferred_test_command": None,
"ngrok_domain": None,
"stack_quirks": [],
"session_learnings": [],
"updated_at": None,
}
data = read_json(path)
if not data:
try:
path.rename(path.with_suffix(".invalid.json"))
except Exception:
pass
return {
"workspace": str(root.resolve()),
"preferred_dev_command": None,
"preferred_preview_port": None,
"package_manager": None,
"preferred_test_command": None,
"ngrok_domain": None,
"stack_quirks": [],
"session_learnings": [],
"updated_at": None,
}
data.setdefault("workspace", str(root.resolve()))
data.setdefault("stack_quirks", [])
data.setdefault("session_learnings", [])
return data
def save_memory(root: Path, data: dict[str, Any]) -> Path:
data["workspace"] = str(root.resolve())
data["updated_at"] = datetime.now().isoformat(timespec="seconds")
path = memory_path(root)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
return path
def refresh_memory_from_project(root: Path, memory: dict[str, Any]) -> dict[str, Any]:
detected = detect_project(root)
if not memory.get("package_manager") and detected.get("package_manager"):
memory["package_manager"] = detected["package_manager"]
if not memory.get("preferred_dev_command"):
memory["preferred_dev_command"] = infer_dev_command(detected)
if not memory.get("preferred_test_command"):
memory["preferred_test_command"] = infer_test_command(detected)
ports = detected.get("candidate_ports") or []
if not memory.get("preferred_preview_port") and ports:
memory["preferred_preview_port"] = ports[0]
memory["detected_signals"] = detected.get("signals") or []
memory["candidate_commands"] = compact_list(detected.get("candidate_commands") or [], 16)
memory["candidate_ports"] = ports[:12]
return memory
def find_ngrok() -> str | None:
path = shutil.which("ngrok")
if path:
return path
candidates = [
Path.home()
/ "AppData"
/ "Local"
/ "Microsoft"
/ "WinGet"
/ "Packages"
/ "Ngrok.Ngrok_Microsoft.Winget.Source_8wekyb3d8bbwe"
/ "ngrok.exe",
Path.home() / "scoop" / "shims" / "ngrok.exe",
Path.home() / "scoop" / "apps" / "ngrok" / "current" / "ngrok.exe",
]
for candidate in candidates:
if candidate.exists():
return str(candidate)
return None
def now_stamp() -> str:
return datetime.now().strftime("%Y%m%d-%H%M%S")
def workspace_key(root: Path) -> str:
return hashlib.sha256(str(root.resolve()).encode("utf-8")).hexdigest()[:16]
def mobilecodex_temp_root(root: Path) -> Path:
return Path(tempfile.gettempdir()) / "mobilecodex" / workspace_key(root)
def registry_path(root: Path) -> Path:
return mobilecodex_temp_root(root) / "servers.json"
def logs_dir(root: Path) -> Path:
return mobilecodex_temp_root(root) / "logs"
def memory_dir(root: Path) -> Path:
return root.resolve() / MEMORY_DIR_NAME
def memory_path(root: Path) -> Path:
return memory_dir(root) / MEMORY_FILE_NAME
def context_cache_path(root: Path) -> Path:
return memory_dir(root) / CONTEXT_CACHE_FILE_NAME
def run_git(root: Path, args: list[str], timeout: float = 8.0) -> tuple[int | None, str]:
git = shutil.which("git")
if not git:
return None, "git not found"
try:
completed = subprocess.run(
[git, *args],
cwd=root,
check=False,
capture_output=True,
text=True,
timeout=timeout,
)
except Exception as exc:
return None, str(exc)
output = (completed.stdout or completed.stderr).strip()
return completed.returncode, output
def git_info(root: Path) -> dict[str, Any]:
branch_code, branch = run_git(root, ["rev-parse", "--abbrev-ref", "HEAD"])
commit_code, commit = run_git(root, ["log", "-1", "--pretty=%h %s"])
status_code, status = run_git(root, ["status", "--short"])
dirty_files = [line for line in status.splitlines() if line.strip()] if status_code == 0 else []
return {
"available": branch_code == 0,
"branch": branch if branch_code == 0 else "unavailable",
"last_commit": commit if commit_code == 0 else "unavailable",
"dirty_count": len(dirty_files),
"dirty_files": dirty_files[:25],
"dirty_truncated": max(0, len(dirty_files) - 25),
}
def port_statuses(ports: list[int]) -> dict[str, str]:
return {str(port): ("free" if port_is_free(port) else "in_use") for port in ports}
def port_accepts_connections(port: int, host: str = "127.0.0.1", timeout: float = 0.4) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(timeout)
try:
return sock.connect_ex((host, port)) == 0
except OSError:
return False
def is_relative_to(path: Path, parent: Path) -> bool:
try:
path.resolve().relative_to(parent.resolve())
return True
except ValueError:
return False
def is_secret_path(path: Path) -> bool:
name = path.name.lower()
for pattern in SECRET_FILE_PATTERNS:
regex = "^" + re.escape(pattern.lower()).replace("\\*", ".*") + "$"
if re.match(regex, name):
return True
return False
def is_skipped_dir(path: Path) -> bool:
return any(part in SKIP_DIR_NAMES for part in path.parts)
def collect_proof_artifacts(root: Path, *, limit: int = 12, exclude: Path | None = None) -> list[dict[str, Any]]:
candidates: list[Path] = []
search_roots = [root / name for name in PROOF_DIR_NAMES]
temp_root = mobilecodex_temp_root(root)
if temp_root.exists():
search_roots.append(temp_root)
for search_root in search_roots:
if not search_root.exists():
continue
for path in search_root.rglob("*"):
if not path.is_file():
continue
if exclude and is_relative_to(path, exclude):
continue
if is_skipped_dir(path.relative_to(search_root) if is_relative_to(path, search_root) else path):
continue
if is_secret_path(path):
continue
if path.suffix.lower() not in PROOF_EXTENSIONS:
continue
candidates.append(path)
candidates = sorted(candidates, key=lambda item: item.stat().st_mtime, reverse=True)
artifacts: list[dict[str, Any]] = []
for path in candidates[:limit]:
try:
stat = path.stat()
except OSError:
continue
artifacts.append(
{
"path": str(path.resolve()),
"size": stat.st_size,
"modified": datetime.fromtimestamp(stat.st_mtime).isoformat(timespec="seconds"),
}
)
return artifacts
def run_version_command(command: list[str], timeout: float = 8.0) -> dict[str, Any]:
try:
completed = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
timeout=timeout,
)
except Exception as exc:
return {
"available": False,
"exit_code": None,
"output": str(exc),
}
output = (completed.stdout or completed.stderr).strip()
return {
"available": completed.returncode == 0,
"exit_code": completed.returncode,
"output": first_non_empty_line(output),
}
def first_non_empty_line(value: str) -> str:
for line in value.splitlines():
stripped = line.strip()
if stripped:
return stripped
return ""
def make_check(
name: str,
status: str,
detail: str,
next_step: str,
*,
required: bool = True,
proof: str | list[str] | dict[str, Any] | None = None,
) -> dict[str, Any]:
return {
"name": name,
"status": status,
"required": required,
"detail": detail,
"proof": proof or "not available",
"next": next_step,
}
def command_check(
name: str,
binary: str,
version_args: list[str],
install_next: str,
*,
required: bool = True,
) -> dict[str, Any]:
path = shutil.which(binary)
if not path:
return make_check(
name,
"action_required",
f"{binary} is not installed or not on PATH",
install_next,
required=required,
proof=f"`{binary}` not found",
)
result = run_version_command([path, *version_args])
if not result["available"]:
return make_check(
name,
"action_required",
f"{binary} exists but did not run cleanly",
install_next,
required=required,
proof=[f"path {path}", f"exit {result['exit_code']}", result["output"]],
)
return make_check(
name,
"ok",
f"{binary} is available",
"No action needed.",
required=required,
proof=[f"path {path}", result["output"]],
)
def collect_ngrok_config_paths(ngrok_path: str | None) -> list[Path]:
paths: list[Path] = []
if ngrok_path:
result = run_version_command([ngrok_path, "config", "check"], timeout=8)
output = str(result.get("output") or "")
paths.extend(Path(match) for match in re.findall(r"([A-Za-z]:\\[^\r\n]+ngrok\.ya?ml|/[^\s]+ngrok\.ya?ml)", output))
home = Path.home()
appdata = Path.home()
if sys.platform.startswith("win"):
appdata_env = Path(str(Path.home()))
appdata_value = os.environ.get("APPDATA")
if appdata_value:
appdata_env = Path(appdata_value)
appdata = appdata_env
paths.extend(
[
appdata / "ngrok" / "ngrok.yml",
home / ".ngrok2" / "ngrok.yml",
home / ".config" / "ngrok" / "ngrok.yml",
home / "Library" / "Application Support" / "ngrok" / "ngrok.yml",
]
)
return dedupe_paths(paths)
def dedupe_paths(paths: list[Path]) -> list[Path]:
seen: set[str] = set()
result: list[Path] = []
for path in paths:
key = str(path)
if key not in seen:
seen.add(key)
result.append(path)
return result
def ngrok_has_authtoken(paths: list[Path]) -> tuple[bool, list[str]]:
checked: list[str] = []
token_pattern = re.compile(r"^\s*(?:authtoken|token)\s*:\s*(\S+)", re.IGNORECASE | re.MULTILINE)
nested_pattern = re.compile(r"^\s*authtoken\s*:\s*(\S+)", re.IGNORECASE | re.MULTILINE)
for path in paths:
checked.append(str(path))
if not path.exists():
continue
try:
content = path.read_text(encoding="utf-8", errors="replace")
except Exception:
continue
if token_pattern.search(content) or nested_pattern.search(content):
return True, checked
return False, checked
def parse_semver(text: str) -> tuple[int, int, int] | None:
match = re.search(r"(\d+)\.(\d+)\.(\d+)", text)
if not match:
return None
return tuple(int(part) for part in match.groups())
def ngrok_doctor_check() -> dict[str, Any]:
ngrok = find_ngrok()
if not ngrok:
return make_check(
"ngrok preview setup",
"action_required",
"ngrok is not installed or not on PATH",
f"Create an ngrok account, install the ngrok agent from {NGROK_SETUP_URL}, then run `ngrok config add-authtoken <token>` using the dashboard token.",
proof="`ngrok` not found",
)
version = run_version_command([ngrok, "version"])
version_text = str(version.get("output") or "version unavailable")
parsed_version = parse_semver(version_text)
if parsed_version and parsed_version < MIN_NGROK_VERSION:
return make_check(
"ngrok preview setup",
"action_required",
f"ngrok is installed but the agent is too old ({version_text})",
f"Update ngrok to 3.20.0 or newer, then rerun setup. Start from {NGROK_SETUP_URL} if the local updater is unavailable.",
proof=[f"path {ngrok}", version_text],
)
config_paths = collect_ngrok_config_paths(ngrok)
has_token, checked = ngrok_has_authtoken(config_paths)
if not has_token:
return make_check(
"ngrok preview setup",
"action_required",
"ngrok is installed but no local authtoken config was found",
f"Open {NGROK_SETUP_URL}, copy your authtoken, then run `ngrok config add-authtoken <token>` on this machine.",
proof=[f"path {ngrok}", version_text, f"checked {', '.join(checked) if checked else 'no config paths'}"],
)
return make_check(
"ngrok preview setup",
"ok",
"ngrok is installed and an authtoken config was found",
"No action needed before requesting public phone previews. After setup, start a local preview and run `ngrok-preview --port <port>` to confirm the phone URL works.",
proof=[f"path {ngrok}", version_text, f"config checked {', '.join(checked)}"],
)
def playwright_doctor_check(root: Path) -> dict[str, Any]:
candidates = [
shutil.which("playwright"),
str(root / "node_modules" / ".bin" / ("playwright.cmd" if sys.platform.startswith("win") else "playwright")),
]
existing = [candidate for candidate in candidates if candidate and Path(candidate).exists()]
package_json = read_json(root / "package.json") if (root / "package.json").exists() else {}
deps: dict[str, Any] = {}
for key in ("dependencies", "devDependencies"):
value = package_json.get(key)
if isinstance(value, dict):
deps.update(value)
if existing:
result = run_version_command([existing[0], "--version"])
return make_check(
"browser proof tooling",
"ok" if result["available"] else "warning",
"Playwright CLI is available" if result["available"] else "Playwright CLI exists but did not run cleanly",
"No action needed." if result["available"] else "Run `npx playwright install chromium` or reinstall the project browser tooling.",
proof=[f"path {existing[0]}", result["output"]],
)
if "@playwright/test" in deps or "playwright" in deps:
return make_check(
"browser proof tooling",
"warning",
"Playwright is listed in package.json, but the local CLI was not found",
"Run the project install command, then `npx playwright install chromium` if browser binaries are missing.",
proof="package.json includes Playwright dependency",
)
npx = shutil.which("npx")
if npx:
return make_check(
"browser proof tooling",
"warning",
"No local Playwright dependency was found, but `npx playwright` is available for screenshot fallback",
"Add `@playwright/test` to the project for full console/network UX proof, or use the npx fallback for screenshots.",
required=False,
proof=f"npx {npx}",
)
return make_check(
"browser proof tooling",
"action_required",
"No Playwright CLI or project dependency was found for repeatable browser proof",
"Install browser proof tooling with `npm install -D @playwright/test` and `npx playwright install chromium`, or rely on Codex's built-in browser only when it is available.",
proof="no local Playwright CLI found",
)
def port_is_free(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind(("127.0.0.1", port))
except OSError:
return False
return True
def ports_doctor_check(ports: list[int]) -> dict[str, Any]:
results = {str(port): ("free" if port_is_free(port) else "in_use") for port in ports}
in_use = [port for port, status in results.items() if status == "in_use"]
if in_use:
return make_check(
"common preview ports",
"warning",
f"Some common ports are already in use: {', '.join(in_use)}",
"Reuse the running server only after identifying it, or choose another free port before creating a public preview.",
required=False,
proof=results,
)
return make_check(
"common preview ports",
"ok",
"Common preview ports are free",
"No action needed.",
required=False,
proof=results,
)
def process_is_running(pid: int) -> bool:
if pid <= 0:
return False
if sys.platform.startswith("win"):
try:
completed = subprocess.run(
["tasklist", "/FI", f"PID eq {pid}", "/FO", "CSV", "/NH"],
check=False,
capture_output=True,
text=True,
timeout=5,
)
except Exception:
return False
return str(pid) in completed.stdout
try:
os.kill(pid, 0)
return True
except OSError:
return False
def terminate_process(pid: int) -> tuple[bool, str]:
if sys.platform.startswith("win"):
try:
completed = subprocess.run(
["taskkill", "/PID", str(pid), "/T", "/F"],
check=False,
capture_output=True,
text=True,
timeout=10,
)
except Exception as exc:
return False, str(exc)
output = (completed.stdout or completed.stderr).strip()
return completed.returncode == 0, output
try:
os.kill(pid, 15)
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
if not process_is_running(pid):
return True, "terminated"
time.sleep(0.2)
os.kill(pid, 9)
return True, "killed after timeout"
except Exception as exc:
return False, str(exc)
def load_registry(root: Path) -> dict[str, Any]:
path = registry_path(root)
if not path.exists():
return {"workspace": str(root.resolve()), "servers": []}
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {"workspace": str(root.resolve()), "servers": []}
if not isinstance(data.get("servers"), list):
data["servers"] = []
return data
def save_registry(root: Path, data: dict[str, Any]) -> None:
path = registry_path(root)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
def normalize_server_entry(entry: dict[str, Any]) -> dict[str, Any]:
port = int(entry.get("port") or 0)
pid = int(entry.get("pid") or 0)
running = process_is_running(pid)
port_open = port_accepts_connections(port) if port else False
status = "running" if running and port_open else "process_running" if running else "stopped"
normalized = dict(entry)
normalized.update(
{
"pid": pid,
"port": port,
"local_url": entry.get("local_url") or (f"http://127.0.0.1:{port}" if port else ""),
"status": status,
"port_open": port_open,
"pid_running": running,
"last_checked": datetime.now().isoformat(timespec="seconds"),
}
)
return normalized
def current_ngrok_tunnel_for_port(port: int | None = None) -> dict[str, Any] | None:
try:
return extract_ngrok_url(read_ngrok_api(DEFAULT_NGROK_API_URL), port)
except Exception:
return None
def list_servers(root: Path) -> list[dict[str, Any]]:
data = load_registry(root)
servers = [normalize_server_entry(server) for server in data.get("servers", []) if isinstance(server, dict)]
for server in servers:
tunnel = current_ngrok_tunnel_for_port(int(server.get("port") or 0))
server["ngrok_url"] = tunnel.get("public_url") if tunnel else ""
if servers != data.get("servers", []):
data["servers"] = servers
save_registry(root, data)
return servers
def render_servers_markdown(root: Path, servers: list[dict[str, Any]]) -> str:
lines = ["# MobileCodex Server Registry", "", f"Workspace: `{root.resolve()}`", f"Registry: `{registry_path(root)}`", ""]
if not servers:
lines.append("No registered servers.")
return "\n".join(lines)
for server in servers:
lines.extend(
[
f"- `{server['name']}`: {server['status']}",
f" - PID: `{server['pid']}`",
f" - Port: `{server['port']}`",
f" - URL: {server['local_url']}",
f" - ngrok: {server.get('ngrok_url') or 'not running'}",
f" - Command: `{server['command']}`",
f" - Log: `{server['log_file']}`",
]
)
return "\n".join(lines)
def server_start(args: argparse.Namespace) -> int:
root = Path(args.root).resolve()
command = list(args.server_command or [])
if command and command[0] == "--":
command = command[1:]
if not command:
print_json_or_markdown(
{"result": "server start blocked", "proof": "no command was provided", "next": "Pass a command after `--`."},
args.format,
"Server Start",
)
return 2
registry = load_registry(root)
existing = [normalize_server_entry(item) for item in registry.get("servers", []) if isinstance(item, dict)]
if any(item.get("name") == args.name and item.get("status") != "stopped" for item in existing):
print_json_or_markdown(
{
"result": "server start blocked",
"proof": f"a registered server named `{args.name}` already exists",
"next": "Use `server-list` to inspect it or `server-stop --name` before starting a replacement.",
},
args.format,
"Server Start",
)
return 2
log_dir = logs_dir(root)
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / f"{args.name}-{args.port}-{now_stamp()}.log"
log_handle = log_file.open("a", encoding="utf-8", errors="replace")
try:
process = subprocess.Popen(
command,
cwd=root,
stdout=log_handle,
stderr=subprocess.STDOUT,
text=True,
)
except Exception as exc:
log_handle.close()
print_json_or_markdown(
{"result": "server start blocked", "proof": f"`{' '.join(command)}` failed: {exc}", "next": "Fix the command and retry."},
args.format,
"Server Start",
)
return 2
finally:
try:
log_handle.flush()
except Exception:
pass
time.sleep(args.wait)
entry = {
"name": args.name,
"command": " ".join(command),
"command_args": command,
"cwd": str(root),
"pid": process.pid,
"port": args.port,
"local_url": f"http://127.0.0.1:{args.port}",
"log_file": str(log_file),
"started_at": datetime.now().isoformat(timespec="seconds"),
}
entry = normalize_server_entry(entry)
registry["workspace"] = str(root)
registry["servers"] = [item for item in existing if item.get("name") != args.name]
registry["servers"].append(entry)
save_registry(root, registry)
log_handle.close()
print_json_or_markdown(
{
"result": "server registered",
"preview": entry["local_url"],
"proof": [
f"command `{entry['command']}`",
f"pid {entry['pid']}",
f"port {entry['port']} status {entry['status']}",
f"log file {entry['log_file']}",
],
"next": "Use `server-list` to inspect it or `server-stop` when the preview is no longer needed.",
},
args.format,
"Server Start",
)
return 0 if entry["pid_running"] else 2
def server_list(args: argparse.Namespace) -> int:
root = Path(args.root).resolve()
servers = list_servers(root)
data = {"workspace": str(root), "registry": str(registry_path(root)), "servers": servers}
if args.format == "json":
print(json.dumps(data, indent=2))
else:
print(render_servers_markdown(root, servers))
return 0
def server_stop(args: argparse.Namespace) -> int:
root = Path(args.root).resolve()
registry = load_registry(root)
servers = [normalize_server_entry(item) for item in registry.get("servers", []) if isinstance(item, dict)]
matches = []
for server in servers:
if args.name and server.get("name") == args.name:
matches.append(server)
elif args.port and int(server.get("port") or 0) == args.port:
matches.append(server)
if not matches:
print_json_or_markdown(
{
"result": "server stop blocked",
"proof": "no matching registered server was found",
"next": "Use `server-list` to inspect registered servers. This command only stops registry-owned processes.",
},
args.format,
"Server Stop",
)
return 2
stopped: list[str] = []
failed: list[str] = []