-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmobile_codex_control.py
More file actions
1521 lines (1317 loc) · 57.7 KB
/
Copy pathmobile_codex_control.py
File metadata and controls
1521 lines (1317 loc) · 57.7 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 argparse
import json
import os
import re
import socket
import sqlite3
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import webbrowser
from collections import deque
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Callable
try:
import tkinter as tk
except ImportError: # pragma: no cover
tk = None
APP_TITLE = "移动 Codex 控制台"
APP_PORT = 3001
PROXY_PORT = 8080
PHONE_ACTIVITY_WINDOW_MINUTES = 10
LOCAL_PANEL_URL = f"http://127.0.0.1:{APP_PORT}"
APP_HEALTH_URL = f"{LOCAL_PANEL_URL}/health"
PROXY_HEALTH_URL = f"http://127.0.0.1:{PROXY_PORT}/health"
REMOTE_TARGET = f"http://127.0.0.1:{PROXY_PORT}"
def resolve_workspace() -> Path:
candidates = []
if getattr(sys, "frozen", False):
executable_dir = Path(sys.executable).resolve().parent
candidates.extend([executable_dir, executable_dir.parent, executable_dir.parent.parent])
else:
source_dir = Path(__file__).resolve().parent
candidates.extend([source_dir, source_dir.parent])
for candidate in candidates:
if (candidate / "scripts" / "start-mobile-codex-stack.ps1").exists():
return candidate
return Path(__file__).resolve().parent
WORKSPACE = resolve_workspace()
SCRIPTS_DIR = WORKSPACE / "scripts"
APP_STDERR_LOG = WORKSPACE / "tmp" / "logs" / "mobile-codex-app.stderr.log"
MOBILE_USER_AGENT = re.compile(r"android|iphone|ipad|mobile|ios|harmony", re.IGNORECASE)
MOBILE_OS = {"android", "ios"}
NGINX_MONTHS = {
"Jan": 1,
"Feb": 2,
"Mar": 3,
"Apr": 4,
"May": 5,
"Jun": 6,
"Jul": 7,
"Aug": 8,
"Sep": 9,
"Oct": 10,
"Nov": 11,
"Dec": 12,
}
def resolve_tailscale_path() -> Path:
configured = os.environ.get("MOBILE_CODEX_TAILSCALE")
if configured:
return Path(configured)
return Path(r"C:\Program Files\Tailscale\tailscale.exe")
def resolve_ascii_alias_path() -> Path:
configured = os.environ.get("MOBILE_CODEX_ASCII_ALIAS")
if configured:
return Path(configured)
system_drive = os.environ.get("SystemDrive", "C:")
return Path(system_drive) / "mobileCodexHelper_ascii"
ASCII_ALIAS_PATH = resolve_ascii_alias_path()
TAILSCALE = resolve_tailscale_path()
NGINX_ACCESS_LOG = ASCII_ALIAS_PATH / ".runtime" / "nginx" / "logs" / "mobile-codex.access.log"
NGINX_ERROR_LOG = ASCII_ALIAS_PATH / ".runtime" / "nginx" / "logs" / "mobile-codex.error.log"
def inspect_auth_db(path: Path) -> tuple[int, set[str]]:
if not path.exists():
return -1, set()
try:
connection = sqlite3.connect(path)
try:
tables = {
row[0]
for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'table'")
}
score = 0
if "users" in tables:
score += 1
if "trusted_devices" in tables:
score += 3
if "device_approval_requests" in tables:
score += 3
if "users" in tables:
user_count = connection.execute("SELECT COUNT(*) FROM users").fetchone()[0]
if user_count:
score += 2
return score, tables
finally:
connection.close()
except sqlite3.Error:
return -1, set()
def resolve_auth_db_path() -> Path:
candidates = []
env_database_path = os.environ.get("DATABASE_PATH")
if env_database_path:
candidates.append(Path(env_database_path))
candidates.extend(
[
WORKSPACE / "vendor" / "claudecodeui-1.25.2" / "server" / "database" / "auth.db",
Path.home() / ".cloudcli" / "auth.db",
Path.home() / ".codex" / "auth.db",
]
)
best_path = candidates[0]
best_score = -1
seen: set[str] = set()
for candidate in candidates:
normalized = str(candidate.resolve()) if candidate.exists() else str(candidate)
if normalized in seen:
continue
seen.add(normalized)
score, _tables = inspect_auth_db(candidate)
if score > best_score:
best_path = candidate
best_score = score
return best_path
AUTH_DB_PATH = resolve_auth_db_path()
@dataclass
class StatusBlock:
label: str
ok: bool
headline: str
detail: str
level: str = "error"
def to_dict(self) -> dict[str, Any]:
return {
"label": self.label,
"ok": self.ok,
"headline": self.headline,
"detail": self.detail,
"level": self.level,
}
@dataclass
class ListenerInfo:
port: int
pid: int
name: str
path: str
def summary(self) -> str:
parts = [f"端口 {self.port}", f"PID {self.pid}"]
if self.name:
parts.append(self.name)
return " | ".join(parts)
def ensure_stdio_utf8() -> None:
for stream_name in ("stdout", "stderr"):
stream = getattr(sys, stream_name, None)
if stream and hasattr(stream, "reconfigure"):
try:
stream.reconfigure(encoding="utf-8", errors="replace")
except ValueError:
pass
ensure_stdio_utf8()
def now_local() -> datetime:
return datetime.now().astimezone()
def parse_datetime(value: str | None) -> datetime | None:
if not value:
return None
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
if parsed.year <= 1:
return None
return parsed
except ValueError:
return None
def format_datetime(value: str | None) -> str:
dt = parse_datetime(value)
if not dt:
return "暂无"
return dt.astimezone().strftime("%Y-%m-%d %H:%M:%S")
def minutes_since(value: str | None) -> float | None:
dt = parse_datetime(value)
if not dt:
return None
return (now_local() - dt.astimezone()).total_seconds() / 60
def format_age_text(value: str | None) -> str:
delta = minutes_since(value)
if delta is None:
return "时间未知"
if delta < 1:
return "刚刚"
return f"{int(delta)} 分钟前"
def is_recent(value: str | None, minutes: int = PHONE_ACTIVITY_WINDOW_MINUTES) -> bool:
delta = minutes_since(value)
return delta is not None and delta <= minutes
def summarize_connection_error(message: str) -> str:
if "10061" in message:
return "端口未监听,服务未启动"
return message
def subprocess_window_options() -> dict[str, Any]:
if sys.platform != "win32":
return {}
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = 0
return {
"creationflags": getattr(subprocess, "CREATE_NO_WINDOW", 0),
"startupinfo": startupinfo,
}
def run_command(args: list[str], timeout: int = 20) -> subprocess.CompletedProcess[str]:
return subprocess.run(
args,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
check=False,
cwd=str(WORKSPACE),
**subprocess_window_options(),
)
def wait_for(predicate: Callable[[], bool], timeout: float, interval: float = 1.0) -> bool:
deadline = time.time() + timeout
while time.time() < deadline:
if predicate():
return True
time.sleep(interval)
return predicate()
def powershell_file(script_name: str, timeout: int = 60) -> subprocess.CompletedProcess[str]:
script_path = SCRIPTS_DIR / script_name
return run_command(
[
"powershell",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
str(script_path),
],
timeout=timeout,
)
def run_powershell_json(command: str, timeout: int = 12) -> Any | None:
result = run_command(
[
"powershell",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-Command",
command,
],
timeout=timeout,
)
if result.returncode != 0:
return None
text = result.stdout.strip()
if not text:
return None
try:
return json.loads(text)
except json.JSONDecodeError:
return None
def http_health(url: str, timeout: float = 2.5) -> tuple[bool, str]:
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
body = response.read(200).decode("utf-8", errors="replace")
return True, f"{response.status} {response.reason} | {body[:80]}"
except urllib.error.HTTPError as exc:
return False, f"HTTP {exc.code} {exc.reason}"
except Exception as exc: # noqa: BLE001
return False, summarize_connection_error(str(exc))
def is_port_open(port: int, host: str = "127.0.0.1", timeout: float = 0.8) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(timeout)
return sock.connect_ex((host, port)) == 0
def normalize_dns_name(value: str | None) -> str | None:
if not value:
return None
return value[:-1] if value.endswith(".") else value
def parse_nginx_timestamp(value: str) -> str | None:
match = re.match(
r"^(?P<day>\d{2})/(?P<month>[A-Za-z]{3})/(?P<year>\d{4}):"
r"(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2}) (?P<offset>[+-]\d{4})$",
value,
)
if not match:
return None
month = NGINX_MONTHS.get(match.group("month"))
if month is None:
return None
offset = match.group("offset")
iso = (
f"{match.group('year')}-{month:02d}-{match.group('day')}T"
f"{match.group('hour')}:{match.group('minute')}:{match.group('second')}"
f"{offset[:3]}:{offset[3:]}"
)
try:
return datetime.fromisoformat(iso).isoformat()
except ValueError:
return None
def get_listener_map(ports: list[int] | None = None) -> dict[int, ListenerInfo]:
target_ports = ports or [APP_PORT, PROXY_PORT]
ports_literal = ",".join(str(port) for port in target_ports)
command = f"""
$ports = @({ports_literal})
$listeners = foreach ($item in Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object {{ $ports -contains $_.LocalPort }}) {{
$proc = Get-Process -Id $item.OwningProcess -ErrorAction SilentlyContinue
[PSCustomObject]@{{
port = [int]$item.LocalPort
pid = [int]$item.OwningProcess
name = if ($proc) {{ $proc.ProcessName }} else {{ '' }}
path = if ($proc -and $proc.Path) {{ $proc.Path }} else {{ '' }}
}}
}}
if ($listeners) {{
$listeners | ConvertTo-Json -Compress
}}
"""
data = run_powershell_json(command)
if not data:
return {}
items = [data] if isinstance(data, dict) else data if isinstance(data, list) else []
listener_map: dict[int, ListenerInfo] = {}
for item in items:
try:
port = int(item.get("port"))
listener_map[port] = ListenerInfo(
port=port,
pid=int(item.get("pid")),
name=str(item.get("name") or ""),
path=str(item.get("path") or ""),
)
except (TypeError, ValueError):
continue
return listener_map
def describe_listener(listener: ListenerInfo | None) -> str:
if not listener:
return "端口未监听"
return listener.summary()
def describe_service(health_ok: bool, health_detail: str, listener: ListenerInfo | None) -> str:
listener_text = describe_listener(listener)
if health_ok:
return f"{listener_text} | {health_detail}" if listener else health_detail
if listener:
return f"{listener_text} | 健康检查未通过:{health_detail}"
return health_detail
def normalize_remote_health_detail(detail: str) -> str:
lowered = detail.lower()
if "handshake operation timed out" in lowered or "timed out" in lowered:
return "本机自检超时,手机端可能仍可访问"
if "10061" in detail:
return "远程入口未监听"
return f"本机自检失败:{detail}"
def build_remote_block(remote: dict[str, Any], app_ok: bool, proxy_ok: bool) -> tuple[StatusBlock, dict[str, Any]]:
if not remote["published"]:
block = StatusBlock("远程发布", False, "未开启", "远程发布未开启", "error")
return block, {"value": "未开启", "detail": block.detail, "level": "error"}
if not app_ok or not proxy_ok:
detail = f"{remote['url']} | 已发布,但本地服务未启动" if remote["url"] else "已发布,但本地服务未启动"
block = StatusBlock("远程发布", False, "已发布,待服务启动", detail, "warning")
return block, {"value": "已发布", "detail": detail, "level": "warning"}
if remote["health_ok"]:
detail = f"{remote['url']} | 远程健康正常" if remote["url"] else remote["detail"]
block = StatusBlock("远程发布", True, "可访问", detail, "success")
return block, {"value": "可访问", "detail": detail, "level": "success"}
health_summary = normalize_remote_health_detail(remote["health_detail"])
detail = f"{remote['url']} | {health_summary}" if remote["url"] else health_summary
block = StatusBlock("远程发布", True, "已发布,待验证", detail, "warning")
return block, {"value": "已发布", "detail": detail, "level": "warning"}
def load_tailscale_status() -> dict[str, Any]:
if not TAILSCALE.exists():
return {"ok": False, "error": f"Tailscale CLI 未找到:{TAILSCALE}"}
result = run_command([str(TAILSCALE), "status", "--json"])
if result.returncode != 0:
return {"ok": False, "error": result.stderr.strip() or result.stdout.strip() or "读取 Tailscale 状态失败"}
try:
return {"ok": True, "data": json.loads(result.stdout)}
except json.JSONDecodeError as exc:
return {"ok": False, "error": f"Tailscale 返回的 JSON 无法解析: {exc}"}
def load_serve_status() -> dict[str, Any]:
if not TAILSCALE.exists():
return {"ok": False, "error": f"Tailscale CLI 未找到:{TAILSCALE}"}
result = run_command([str(TAILSCALE), "serve", "status", "--json"])
if result.returncode != 0:
return {"ok": False, "error": result.stderr.strip() or result.stdout.strip() or "读取远程发布状态失败"}
try:
return {"ok": True, "data": json.loads(result.stdout)}
except json.JSONDecodeError as exc:
return {"ok": False, "error": f"远程发布状态 JSON 无法解析: {exc}"}
def build_remote_status(tailscale_status: dict[str, Any], serve_status: dict[str, Any]) -> dict[str, Any]:
serve_data = serve_status.get("data") if serve_status.get("ok") else {}
web_entries = list((serve_data or {}).get("Web", {}).items())
if not web_entries:
return {
"published": False,
"url": None,
"target": None,
"detail": "远程发布未开启",
"health_ok": False,
"health_detail": "未执行远程健康检查",
}
host_and_port, config = web_entries[0]
host = str(host_and_port).replace(":443", "")
target = (((config or {}).get("Handlers") or {}).get("/") or {}).get("Proxy")
tailscale_data = tailscale_status.get("data") if tailscale_status.get("ok") else {}
fallback_dns = normalize_dns_name((((tailscale_data or {}).get("Self") or {}).get("DNSName")))
url = f"https://{host or fallback_dns}" if (host or fallback_dns) else None
health_ok = False
health_detail = "未执行远程健康检查"
if url:
health_ok, health_detail = http_health(f"{url}/health", timeout=2.5)
return {
"published": True,
"url": url,
"target": target,
"detail": f"已发布到 {target}" if target else "远程发布已开启",
"health_ok": health_ok,
"health_detail": health_detail,
}
def pick_mobile_display_name(peer: dict[str, Any]) -> str:
host_name = str(peer.get("HostName") or "").strip()
dns_name = normalize_dns_name(peer.get("DNSName")) or ""
tail_ip = (peer.get("TailscaleIPs") or [""])[0]
if host_name and host_name.lower() != "localhost":
return host_name
if dns_name:
return dns_name
if tail_ip:
return tail_ip
return "未命名手机"
def extract_mobile_peers(tailscale_status: dict[str, Any]) -> list[dict[str, Any]]:
if not tailscale_status.get("ok"):
return []
peers = []
for peer_id, peer in (tailscale_status["data"].get("Peer") or {}).items():
os_name = str(peer.get("OS") or "").lower()
if os_name not in MOBILE_OS:
continue
peers.append(
{
"id": peer_id,
"display_name": pick_mobile_display_name(peer),
"host_name": peer.get("HostName") or "",
"dns_name": normalize_dns_name(peer.get("DNSName")) or "",
"os": os_name,
"online": bool(peer.get("Online")),
"active": bool(peer.get("Active")),
"last_handshake": peer.get("LastHandshake") or "",
"last_seen": peer.get("LastSeen") or "",
"tail_ip": (peer.get("TailscaleIPs") or [""])[0],
"relay": peer.get("Relay") or "",
}
)
peers.sort(key=lambda item: (not item["online"], not item["active"], item["display_name"]))
return peers
def tail_lines(file_path: Path, max_lines: int = 200) -> list[str]:
if not file_path.exists():
return []
lines: deque[str] = deque(maxlen=max_lines)
with file_path.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
stripped = line.rstrip()
if stripped:
lines.append(stripped)
return list(lines)
def recent_mobile_requests(limit: int = 6) -> list[dict[str, Any]]:
pattern = re.compile(
r'^(?P<ip>\S+) - \S+ \[(?P<time>[^\]]+)\] "(?P<method>\S+) (?P<path>\S+) [^"]+" '
r'(?P<status>\d{3}) (?P<bytes>\d+) "(?P<referrer>[^"]*)" "(?P<ua>.*)"$'
)
parsed: list[dict[str, Any]] = []
for line in tail_lines(NGINX_ACCESS_LOG):
match = pattern.match(line)
if not match:
continue
user_agent = match.group("ua")
if not MOBILE_USER_AGENT.search(user_agent):
continue
parsed.append(
{
"ip": match.group("ip"),
"time": parse_nginx_timestamp(match.group("time")) or match.group("time"),
"method": match.group("method"),
"path": match.group("path"),
"status": int(match.group("status")),
"user_agent": user_agent,
}
)
parsed.sort(key=lambda item: str(item["time"]), reverse=True)
unique: list[dict[str, Any]] = []
seen = set()
for item in parsed:
key = (item["time"], item["method"], item["path"], item["status"], item["user_agent"])
if key in seen:
continue
seen.add(key)
unique.append(item)
if len(unique) >= limit:
break
return unique
def tail_error_lines(limit: int = 8) -> list[str]:
combined = []
for label, path in (("后端", APP_STDERR_LOG), ("nginx", NGINX_ERROR_LOG)):
lines = tail_lines(path, max_lines=40)
interesting = [line for line in lines if re.search(r"error|warn|fail|502|trace|deprecat", line, re.I)]
if interesting:
combined.extend([f"[{label}] {line}" for line in interesting[-4:]])
return combined[-limit:]
def open_auth_db() -> sqlite3.Connection:
connection = sqlite3.connect(AUTH_DB_PATH)
connection.row_factory = sqlite3.Row
return connection
def list_pending_device_approvals(limit: int = 20) -> list[dict[str, Any]]:
if not AUTH_DB_PATH.exists():
return []
try:
with open_auth_db() as connection:
rows = connection.execute(
"""
SELECT
dar.request_token,
dar.device_id,
dar.device_name,
dar.platform,
dar.app_type,
dar.requested_ip,
dar.requested_user_agent,
dar.created_at,
u.username
FROM device_approval_requests dar
LEFT JOIN users u ON u.id = dar.user_id
WHERE dar.status = 'pending'
ORDER BY dar.created_at DESC
LIMIT ?
""",
(limit,),
).fetchall()
except sqlite3.OperationalError:
return []
approvals = []
for row in rows:
item = dict(row)
item["display_name"] = item.get("device_name") or item.get("device_id") or "未命名设备"
approvals.append(item)
return approvals
def list_approved_devices(limit: int = 50) -> list[dict[str, Any]]:
if not AUTH_DB_PATH.exists():
return []
try:
with open_auth_db() as connection:
rows = connection.execute(
"""
SELECT
td.device_id,
td.device_name,
td.platform,
td.app_type,
td.first_approved_at,
td.last_seen,
td.last_login,
td.last_ip,
u.username
FROM trusted_devices td
LEFT JOIN users u ON u.id = td.user_id
WHERE td.is_active = 1
ORDER BY COALESCE(td.last_login, td.last_seen, td.first_approved_at) DESC
LIMIT ?
""",
(limit,),
).fetchall()
except sqlite3.OperationalError:
return []
devices = []
for row in rows:
item = dict(row)
item["display_name"] = item.get("device_name") or item.get("device_id") or "未命名设备"
devices.append(item)
return devices
def resolve_device_request(request_token: str, approved: bool) -> bool:
if not AUTH_DB_PATH.exists():
return False
try:
with open_auth_db() as connection:
row = connection.execute(
"""
SELECT *
FROM device_approval_requests
WHERE request_token = ? AND status = 'pending'
LIMIT 1
""",
(request_token,),
).fetchone()
if row is None:
return False
if approved:
connection.execute(
"""
INSERT INTO trusted_devices (
user_id,
device_id,
device_name,
platform,
app_type,
first_approved_at,
last_seen,
last_login,
last_ip,
last_user_agent,
is_active
)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?, ?, 1)
ON CONFLICT(user_id, device_id)
DO UPDATE SET
device_name = excluded.device_name,
platform = excluded.platform,
app_type = excluded.app_type,
last_seen = CURRENT_TIMESTAMP,
last_login = CURRENT_TIMESTAMP,
last_ip = excluded.last_ip,
last_user_agent = excluded.last_user_agent,
is_active = 1
""",
(
row["user_id"],
row["device_id"],
row["device_name"],
row["platform"],
row["app_type"],
row["requested_ip"],
row["requested_user_agent"],
),
)
connection.execute(
f"""
UPDATE device_approval_requests
SET
status = ?,
updated_at = CURRENT_TIMESTAMP,
{"approved_at" if approved else "rejected_at"} = CURRENT_TIMESTAMP,
resolved_note = ?
WHERE request_token = ? AND status = 'pending'
""",
("approved" if approved else "rejected", "Desktop tool action", request_token),
)
connection.commit()
return True
except sqlite3.OperationalError:
return False
def collect_status() -> dict[str, Any]:
listener_map = get_listener_map()
app_listener = listener_map.get(APP_PORT)
proxy_listener = listener_map.get(PROXY_PORT)
app_ok, app_health_detail = http_health(APP_HEALTH_URL)
proxy_ok, proxy_health_detail = http_health(PROXY_HEALTH_URL)
app_detail = describe_service(app_ok, app_health_detail, app_listener)
proxy_detail = describe_service(proxy_ok, proxy_health_detail, proxy_listener)
tailscale_status = load_tailscale_status()
serve_status = load_serve_status()
remote = build_remote_status(tailscale_status, serve_status)
peers = extract_mobile_peers(tailscale_status)
approved_devices = list_approved_devices()
pending_approvals = list_pending_device_approvals()
mobile_online = sum(1 for peer in peers if peer["online"])
recent_requests = recent_mobile_requests()
latest_request_time = recent_requests[0]["time"] if recent_requests else None
recent_phone_activity = is_recent(latest_request_time)
active_phone_websockets = sum(
1 for request in recent_requests if request["path"] == "/ws" and request["status"] == 101 and is_recent(request["time"])
)
tailscale_data = tailscale_status.get("data") if tailscale_status.get("ok") else {}
backend_state = (tailscale_data.get("BackendState") if tailscale_data else None) or "不可用"
dns_name = normalize_dns_name((((tailscale_data or {}).get("Self") or {}).get("DNSName")))
current_device = peers[0]["display_name"] if peers else "暂未发现手机设备"
latest_activity_summary = (
f"{recent_requests[0]['path']} · {format_datetime(latest_request_time)}"
if recent_requests
else "暂无手机访问记录"
)
remote_block, remote_summary = build_remote_block(remote, app_ok, proxy_ok)
remote_available = remote["published"] and remote["health_ok"] and app_ok and proxy_ok
blocks = [
StatusBlock("PC 应用服务", app_ok, "运行中" if app_ok else "未启动", app_detail, "success" if app_ok else "error"),
StatusBlock("nginx 代理", proxy_ok, "运行中" if proxy_ok else "未启动", proxy_detail, "success" if proxy_ok else "error"),
StatusBlock(
"Tailscale",
bool(tailscale_status.get("ok") and backend_state == "Running"),
"运行中" if bool(tailscale_status.get("ok") and backend_state == "Running") else backend_state,
dns_name or tailscale_status.get("error", "未获取到域名"),
"success" if bool(tailscale_status.get("ok") and backend_state == "Running") else "error",
),
remote_block,
StatusBlock(
"手机连接状态",
mobile_online > 0,
f"{mobile_online}/{len(peers)} 在线",
current_device,
"success" if mobile_online > 0 else "error",
),
StatusBlock(
"手机最近访问",
recent_phone_activity,
"最近 10 分钟内有访问" if recent_phone_activity else "最近 10 分钟内无访问",
latest_activity_summary,
"success" if recent_phone_activity else "error",
),
]
return {
"checked_at": now_local().strftime("%Y-%m-%d %H:%M:%S"),
"local_url": LOCAL_PANEL_URL,
"remote_url": remote["url"],
"blocks": [block.to_dict() for block in blocks],
"mobile_peers": peers,
"approved_devices": approved_devices,
"pending_device_approvals": pending_approvals,
"recent_mobile_requests": recent_requests,
"diagnostics": [f"[本地] 认证数据库:{AUTH_DB_PATH}"] + tail_error_lines(),
"summary": {
"app_running": app_ok,
"nginx_running": proxy_ok,
"tailscale_running": bool(tailscale_status.get("ok") and backend_state == "Running"),
"remote_enabled": remote["published"],
"remote_reachable": remote["health_ok"],
"remote_available": remote_available,
"remote_level": remote_summary["level"],
"remote_value": remote_summary["value"],
"remote_detail": remote_summary["detail"],
"approved_devices": len(approved_devices),
"pending_approvals": len(pending_approvals),
"mobile_online": mobile_online,
"mobile_total": len(peers),
"recent_phone_requests": len(recent_requests),
"recent_phone_websockets": active_phone_websockets,
"recent_phone_activity": recent_phone_activity,
"healthy_local_services": int(app_ok) + int(proxy_ok),
"listener_summary": {
str(APP_PORT): app_listener.summary() if app_listener else "端口未监听",
str(PROXY_PORT): proxy_listener.summary() if proxy_listener else "端口未监听",
},
},
}
def stack_is_running() -> bool:
app_ok, _ = http_health(APP_HEALTH_URL, timeout=1.5)
proxy_ok, _ = http_health(PROXY_HEALTH_URL, timeout=1.5)
return app_ok and proxy_ok
def remote_publish_is_enabled() -> bool:
tailscale_status = load_tailscale_status()
serve_status = load_serve_status()
remote = build_remote_status(tailscale_status, serve_status)
return bool(remote["published"])
def stack_is_stopped() -> bool:
if is_port_open(APP_PORT, timeout=0.4) or is_port_open(PROXY_PORT, timeout=0.4):
return False
app_ok, _ = http_health(APP_HEALTH_URL, timeout=0.8)
proxy_ok, _ = http_health(PROXY_HEALTH_URL, timeout=0.8)
return not app_ok and not proxy_ok
def wait_for_remote_reachable(timeout: float = 8.0) -> bool:
def _remote_ok() -> bool:
status = collect_status()
return bool(status["summary"]["remote_reachable"])
return wait_for(_remote_ok, timeout=timeout, interval=1.0)
def perform_action(action: str) -> str:
if action == "start":
result = powershell_file("start-mobile-codex-stack.ps1", timeout=30)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "启动整套服务失败")
if not wait_for(stack_is_running, timeout=20, interval=1.5):
listeners = get_listener_map()
detail = ";".join(describe_listener(listeners.get(port)) for port in (APP_PORT, PROXY_PORT))
raise RuntimeError(f"服务启动命令已执行,但本地健康检查仍未通过:{detail}")
return "整套服务已启动"
if action == "stop":
result = powershell_file("stop-mobile-codex-stack.ps1", timeout=20)
if TAILSCALE.exists():
run_command([str(TAILSCALE), "serve", "reset"], timeout=10)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "停止整套服务失败")
if not wait_for(stack_is_stopped, timeout=15, interval=1.0):
powershell_file("stop-mobile-codex-stack.ps1", timeout=20)
if not wait_for(stack_is_stopped, timeout=10, interval=1.0):
listeners = get_listener_map()
remaining = [listeners.get(port) for port in (APP_PORT, PROXY_PORT) if listeners.get(port)]
detail = ";".join(item.summary() for item in remaining) if remaining else "端口探测仍显示服务未完全退出"
raise RuntimeError(f"停止命令已执行,但本地端口仍未完全释放:{detail}")
return "整套服务已停止"
if action == "enable_remote":
result = run_command([str(TAILSCALE), "serve", "--bg", REMOTE_TARGET], timeout=20)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "开启远程发布失败")
if not wait_for(remote_publish_is_enabled, timeout=12, interval=1.0):
raise RuntimeError("远程发布命令已执行,但 Tailscale Serve 状态仍未生效")
if wait_for_remote_reachable(timeout=8):
return "远程发布已开启,远程地址可访问"
return "远程发布已开启,若手机端暂时打不开请等待几秒后刷新"
if action == "disable_remote":
result = run_command([str(TAILSCALE), "serve", "reset"], timeout=10)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "关闭远程发布失败")
if not wait_for(lambda: not remote_publish_is_enabled(), timeout=8, interval=0.8):
raise RuntimeError("远程发布关闭命令已执行,但 Serve 状态仍存在")
return "远程发布已关闭"
if action == "open_local":
webbrowser.open(LOCAL_PANEL_URL)
return "已打开本地控制面板"
raise ValueError(f"不支持的操作:{action}")
class ControlApp:
REFRESH_MS = 15000
def __init__(self) -> None:
if tk is None:
raise RuntimeError("当前 Python 环境缺少 tkinter,无法显示桌面界面")
self.root = tk.Tk()
self.root.title(APP_TITLE)
self.root.geometry("1260x900")
self.root.minsize(1120, 800)
self.root.configure(bg="#eef3f8")
self.status_text = tk.StringVar(value="就绪")
self.last_refresh_text = tk.StringVar(value="尚未刷新")
self.local_url_text = tk.StringVar(value=f"本地面板:{LOCAL_PANEL_URL}")
self.remote_url_text = tk.StringVar(value="远程地址:未开启")
self.block_labels: list[dict[str, tk.Label]] = []
self.metric_widgets: dict[str, dict[str, Any]] = {}
self.pending_approval_items: list[dict[str, Any]] = []
self.selected_approval_token: str | None = None
self._busy = False
self._build_ui()
self.refresh_status()
def _build_ui(self) -> None:
container = tk.Frame(self.root, bg="#eef3f8")
container.pack(fill="both", expand=True, padx=14, pady=14)
title = tk.Label(
container,
text=APP_TITLE,
font=("Microsoft YaHei UI", 22, "bold"),
bg="#eef3f8",
fg="#112033",
)
title.pack(anchor="w")
subtitle = tk.Label(
container,
text="用于在电脑端一键控制 Codex 服务,并集中查看本机服务、远程发布与手机连接状态。",
font=("Microsoft YaHei UI", 10),
bg="#eef3f8",
fg="#4f6072",
)
subtitle.pack(anchor="w", pady=(4, 10))
endpoint_bar = tk.Frame(container, bg="#dbe8f6", bd=1, relief="solid")
endpoint_bar.pack(fill="x", pady=(0, 12))
tk.Label(
endpoint_bar,
textvariable=self.local_url_text,
font=("Microsoft YaHei UI", 10, "bold"),
bg="#dbe8f6",