From 0a2d700e852290144b331c371854eef16b56f098 Mon Sep 17 00:00:00 2001
From: taisuii <93462725+taisuii@users.noreply.github.com>
Date: Mon, 23 Nov 2026 23:17:10 +0800
Subject: [PATCH 01/20] =?UTF-8?q?feat:=20=E9=9D=A2=E6=9D=BF=E8=AE=BE?=
=?UTF-8?q?=E5=A4=87=E7=AE=A1=E7=90=86=E4=B8=8E=E6=B3=A8=E5=85=A5=E8=8C=83?=
=?UTF-8?q?=E5=9B=B4=E5=85=A5=E5=8F=A3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
connections.json 持久化 selected 与每设备 session_token(0600 不变);
panel 增加 /api/devices(列表/添加/删除/切换/存 token)与 /api/apps、
/api/injection-scope、/api/apps/relaunch 中转,token 跟随选中设备;
零设备也可启动面板。页面在会话弹层加设备区(在线/配对/切换/增删),
新增注入页:分组应用列表、搜索、注入开关、运行中改动标待重启并提供
重启并应用。
---
src/idh/cli.py | 172 ++++++++++++++++++++++++++++++++++++----
src/idh/config.py | 65 +++++++++++++--
src/idh/panel-device.js | 2 +
src/idh/panel.html | 104 +++++++++++++++++++++++-
tests/test_config.py | 28 ++++++-
5 files changed, 347 insertions(+), 24 deletions(-)
diff --git a/src/idh/cli.py b/src/idh/cli.py
index 86d75be..9262fd3 100755
--- a/src/idh/cli.py
+++ b/src/idh/cli.py
@@ -21,8 +21,11 @@
clear_endpoints,
config_path,
load_saved_endpoints,
+ load_selected,
remove_endpoint,
save_endpoint,
+ save_endpoint_token,
+ save_selected,
)
from .gateway import (
GatewayServer,
@@ -799,6 +802,11 @@ def _run_auto_update(args: argparse.Namespace) -> None:
_PANEL_SESSION_ROUTE = re.compile(r"/api/sessions(?:/[A-Za-z0-9_-]{1,64}(?:/events)?)?")
_PANEL_SETTINGS_ROUTE = "/api/session-settings"
_PANEL_SETTINGS_MAX_BYTES = 4096
+# 设备侧注入接口(GET 读 / POST 写)与本机设备注册表
+_PANEL_DEVICE_READ = {"/api/apps", "/api/injection-scope"}
+_PANEL_DEVICE_WRITE = {"/api/injection-scope", "/api/apps/relaunch"}
+_PANEL_DEVICES_ROUTE = "/api/devices"
+_BUNDLE_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,254}")
def _panel_request(
@@ -824,10 +832,9 @@ def _run_panel(args: argparse.Namespace) -> int:
endpoints = _manual_endpoints(args.endpoint, include_saved=not args.no_saved)
try:
endpoint = _resolve_device(endpoints, None, command="panel")
- except SystemExit as exc:
- print(str(exc), file=sys.stderr)
- return 1
- if endpoint.kind != "device":
+ except SystemExit:
+ endpoint = None # 零设备启动:面板照常起,由页面里的设备入口添加
+ if endpoint is not None and endpoint.kind != "device":
print("idh: panel serves a device connection", file=sys.stderr)
return 2
host, _, port_text = args.bind.rpartition(":")
@@ -839,12 +846,45 @@ def _run_panel(args: argparse.Namespace) -> int:
except ValueError:
print("idh: --bind must use 127.0.0.1 or localhost and a valid port", file=sys.stderr)
return 2
+ saved_selected = load_selected()
+ if saved_selected:
+ for saved in load_saved_endpoints():
+ if saved.mcp_url.casefold() == saved_selected.casefold() and saved.kind == "device":
+ endpoint = saved
+ break
+ current = {"endpoint": endpoint}
+
+ def device_token(ep: AppEndpoint) -> str:
+ saved = ep.properties.get("session_token") or ""
+ return saved or os.environ.get("IDH_DEVICE_SESSION_TOKEN", "").strip()
+
+ def device_records() -> dict:
+ saved = [item for item in load_saved_endpoints() if item.kind == "device"]
+ probed = _probed_endpoints(saved)
+ selected = current["endpoint"].mcp_url
+ return {
+ "devices": [
+ {
+ "id": item.mcp_url,
+ "address": item.base_url,
+ "kind": item.kind,
+ "online": item.properties.get("status") == "online",
+ "selected": item.mcp_url == selected,
+ "paired": bool(device_token(item)),
+ }
+ for item in probed
+ ],
+ "selected": selected,
+ }
+
try:
- code, health = _panel_request(endpoint, "/health")
- if code != 200 or not isinstance(health, dict) or health.get("service") != "idhjd":
- raise UsageError("idh: panel serves a device connection")
+ if current["endpoint"] is not None:
+ code, health = _panel_request(current["endpoint"], "/health")
+ if code != 200 or not isinstance(health, dict) or health.get("service") != "idhjd":
+ raise UsageError("idh: panel serves a device connection")
panel_files = files("idh")
- metadata = f''.encode()
+ device_url = current["endpoint"].base_url if current["endpoint"] else ""
+ metadata = f''.encode()
page = panel_files.joinpath("panel.html").read_bytes().replace(
b"", metadata
)
@@ -897,11 +937,69 @@ def relay_settings(self, body: bytes | None = None) -> None:
return
self.write_json(code, data if isinstance(data, dict) else {"error": "settings_unavailable"})
+ def device_action(self, body: bytes) -> None:
+ try:
+ request = json.loads(body)
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ request = None
+ if not isinstance(request, dict):
+ self.write_json(400, {"error": "invalid_device_request"})
+ return
+ action = request.get("action")
+ if action == "add":
+ try:
+ endpoint = AppEndpoint.from_url(str(request.get("address") or ""))
+ except ValueError:
+ self.write_json(400, {"error": "invalid_address"})
+ return
+ probed = probe_endpoint(endpoint, timeout=3)
+ if probed.properties.get("status") == "online" and probed.kind != "device":
+ self.write_json(400, {"error": "not_a_device"})
+ return
+ save_endpoint(probed)
+ self.write_json(200, device_records())
+ return
+ target = str(request.get("id") or "")
+ if action == "select":
+ for saved in load_saved_endpoints():
+ if saved.kind == "device" and saved.mcp_url.casefold() == target.casefold():
+ save_selected(saved.mcp_url)
+ current["endpoint"] = saved
+ self.write_json(200, device_records())
+ return
+ self.write_json(404, {"error": "unknown_device"})
+ return
+ if action == "remove":
+ try:
+ removed = remove_endpoint(target)
+ except ValueError:
+ removed = False
+ if not removed:
+ self.write_json(404, {"error": "unknown_device"})
+ return
+ if current["endpoint"] and current["endpoint"].mcp_url.casefold() == target.casefold():
+ save_selected(next((e.mcp_url for e in load_saved_endpoints() if e.kind == "device"), ""))
+ current["endpoint"] = next((e for e in load_saved_endpoints() if e.kind == "device"), None)
+ self.write_json(200, device_records())
+ return
+ if action == "token":
+ token = str(request.get("token") or "").strip()
+ if not token or not token.isascii() or any(ch.isspace() for ch in token):
+ self.write_json(400, {"error": "invalid_token"})
+ return
+ if not save_endpoint_token(target, token):
+ self.write_json(404, {"error": "unknown_device"})
+ return
+ self.write_json(200, device_records())
+ return
+ self.write_json(400, {"error": "invalid_device_request"})
+
def do_POST(self) -> None:
if not self.valid_host():
self.send_error(400)
return
- if self.path != _PANEL_SETTINGS_ROUTE:
+ allowed = {_PANEL_SETTINGS_ROUTE, _PANEL_DEVICES_ROUTE} | _PANEL_DEVICE_WRITE
+ if self.path not in allowed:
self.send_error(404)
return
if self.headers.get_all("Origin") != [f"http://{self.headers['Host']}"]:
@@ -925,7 +1023,45 @@ def do_POST(self) -> None:
if len(body) != length:
self.write_json(400, {"error": "incomplete_settings"})
return
- self.relay_settings(body)
+ if self.path == _PANEL_SETTINGS_ROUTE:
+ self.relay_settings(body)
+ return
+ if self.path == _PANEL_DEVICES_ROUTE:
+ self.device_action(body)
+ return
+ endpoint = current["endpoint"]
+ token = device_token(endpoint) if endpoint else ""
+ if not endpoint or not token:
+ self.write_json(401, {"error": "session_pairing_required"})
+ return
+ try:
+ request = json.loads(body)
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ request = None
+ if not isinstance(request, dict):
+ self.write_json(400, {"error": "invalid_request"})
+ return
+ if self.path == "/api/apps/relaunch":
+ bundle = str(request.get("bundleId") or "")
+ if not _BUNDLE_ID.fullmatch(bundle) or bundle.startswith("com.apple."):
+ self.write_json(400, {"error": "invalid_bundle_id"})
+ return
+ else:
+ ids = [request.get(key) for key in ("add", "remove")]
+ if any(not isinstance(value, list) or len(value) > 256 or
+ any(not _BUNDLE_ID.fullmatch(str(item)) for item in value)
+ for value in ids):
+ self.write_json(400, {"error": "invalid_bundle_id"})
+ return
+ try:
+ code, data = _panel_request(endpoint, self.path, token, body=body)
+ except (HTTPException, OSError, ValueError, UsageError):
+ self.write_json(502, {"error": "device_unavailable"})
+ return
+ if code not in {200, 400, 401, 403, 404, 409, 500}:
+ self.write_json(502, {"error": "device_unavailable"})
+ return
+ self.write_json(code, data if isinstance(data, dict) else {"error": "device_unavailable"})
def do_GET(self) -> None:
if not self.valid_host():
@@ -934,6 +1070,9 @@ def do_GET(self) -> None:
if self.path == _PANEL_SETTINGS_ROUTE:
self.relay_settings()
return
+ if self.path == _PANEL_DEVICES_ROUTE:
+ self.write_json(200, device_records())
+ return
try:
target = urlsplit(self.path)
except ValueError:
@@ -950,15 +1089,20 @@ def do_GET(self) -> None:
kind = "text/html; charset=utf-8"
elif not target.query and target.path in assets:
body, kind = assets[target.path]
- elif session_route or self.path == "/health":
+ elif session_route or self.path == "/health" or (
+ not target.query and target.path in _PANEL_DEVICE_READ
+ ):
+ if current["endpoint"] is None:
+ self.send_error(502)
+ return
token = ""
- if session_route:
- token = os.environ.get("IDH_DEVICE_SESSION_TOKEN", "").strip()
+ if session_route or target.path in _PANEL_DEVICE_READ:
+ token = device_token(current["endpoint"])
if not token:
self.send_error(401)
return
try:
- code, data = _panel_request(endpoint, self.path, token)
+ code, data = _panel_request(current["endpoint"], self.path, token)
except (HTTPException, OSError, ValueError, UsageError):
self.send_error(502)
return
diff --git a/src/idh/config.py b/src/idh/config.py
index 8905f75..28e1419 100755
--- a/src/idh/config.py
+++ b/src/idh/config.py
@@ -56,9 +56,11 @@ def load_saved_endpoints(path: Path | None = None) -> list[AppEndpoint]:
kind = item.get("kind")
if kind is not None and kind not in _KINDS:
raise ValueError(f"connection config has an unknown kind: {target}")
- loaded.append(
- AppEndpoint.from_url(url).with_kind(kind if isinstance(kind, str) else None)
- )
+ endpoint = AppEndpoint.from_url(url).with_kind(kind if isinstance(kind, str) else None)
+ token = item.get("session_token")
+ if isinstance(token, str) and token:
+ endpoint = endpoint.with_properties({"session_token": token})
+ loaded.append(endpoint)
return loaded
except ValueError as exc:
if str(exc).startswith("connection config"):
@@ -111,19 +113,68 @@ def clear_endpoints(path: Path | None = None) -> int:
return len(existing)
-def _write_endpoints(endpoints: Iterable[AppEndpoint], target: Path) -> None:
+def load_selected(path: Path | None = None) -> str | None:
+ target = path or config_path()
+ try:
+ data = json.loads(target.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError):
+ return None
+ selected = data.get("selected") if isinstance(data, dict) else None
+ return selected if isinstance(selected, str) and selected else None
+
+
+def save_selected(value: str, path: Path | None = None) -> None:
+ target = path or config_path()
+ _write_endpoints(load_saved_endpoints(target), target, selected=value)
+
+
+def save_endpoint_token(value: str, token: str, path: Path | None = None) -> bool:
+ target = path or config_path()
+ canonical = AppEndpoint.from_url(value).mcp_url.casefold()
+ endpoints = load_saved_endpoints(target)
+ updated = False
+ items: list[AppEndpoint] = []
+ for item in endpoints:
+ if item.mcp_url.casefold() == canonical:
+ item = item.with_properties({"session_token": token})
+ updated = True
+ items.append(item)
+ if not updated:
+ return False
+ _write_endpoints(items, target)
+ return True
+
+
+def _write_endpoints(
+ endpoints: Iterable[AppEndpoint], target: Path, *, selected: str | None = None
+) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
+ if selected is None and target.exists():
+ # 其它写路径不改当前选中,读旧文件保留
+ try:
+ data = json.loads(target.read_text(encoding="utf-8"))
+ if isinstance(data, dict) and isinstance(data.get("selected"), str):
+ selected = data["selected"]
+ except (OSError, UnicodeError, json.JSONDecodeError):
+ pass
items = sorted(endpoints, key=lambda item: item.mcp_url.casefold())
- if any(item.kind for item in items):
- payload = {
+ if any(item.kind or item.properties.get("session_token") for item in items):
+ payload: dict[str, object] = {
"version": CONFIG_VERSION_KIND,
"endpoints": [
- {"url": item.mcp_url, **({"kind": item.kind} if item.kind else {})}
+ {
+ "url": item.mcp_url,
+ **({"kind": item.kind} if item.kind else {}),
+ **({"session_token": item.properties["session_token"]}
+ if item.properties.get("session_token") else {}),
+ }
for item in items
],
}
else:
payload = {"version": CONFIG_VERSION, "endpoints": [item.mcp_url for item in items]}
+ if selected:
+ payload["selected"] = selected
fd, temporary = tempfile.mkstemp(prefix=f".{target.name}.", dir=target.parent, text=True)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
diff --git a/src/idh/panel-device.js b/src/idh/panel-device.js
index 07e02c2..e0d8140 100644
--- a/src/idh/panel-device.js
+++ b/src/idh/panel-device.js
@@ -256,6 +256,8 @@
const {pathname, searchParams} = new URL(url, location.origin);
const selection = Number(searchParams.get("cat") ?? -1);
const method = options.method || "GET";
+ // 设备管理与注入范围:由本机面板服务直接处理/中转,不走会话适配
+ if (/^\/api\/(apps|injection-scope|devices)(\/|$)/.test(pathname)) return realFetch(url, options);
try {
if (method === "GET" && pathname === "/api/settings/export") return await deviceSettings();
if (method === "POST" && pathname === "/api/settings/import") return await deviceSettings(options.body);
diff --git a/src/idh/panel.html b/src/idh/panel.html
index 1e03692..e833bc2 100644
--- a/src/idh/panel.html
+++ b/src/idh/panel.html
@@ -86,6 +86,10 @@
.dropdown-item[aria-checked=true],.dropdown-item[aria-selected=true] { background:var(--active); color:var(--blue) }
.dropdown-item span:first-child { min-width:0; overflow-wrap:anywhere }
.dropdown-sub { display:block; color:var(--muted); font-size:11px; margin-top:2px }
+ .device-add { display:flex; gap:6px; padding:4px 9px 9px }
+ .device-add input { flex:1; min-width:0; font:inherit; font-size:12px; padding:5px 8px; border:1px solid var(--line); border-radius:5px; background:var(--bg); color:var(--ink) }
+ .device-remove { color:var(--muted); padding:2px 7px; border-radius:4px; cursor:pointer }
+ .device-remove:hover { background:var(--surface-3); color:var(--ink) }
.dropdown-divider { height:1px; background:var(--line); margin:5px 6px }
.proc-details { display:grid; grid-template-columns:auto minmax(0,1fr); gap:6px 12px; margin:0; padding:4px 10px 10px; font-size:11.5px }
.proc-details dt { color:var(--muted) }
@@ -303,6 +307,12 @@
+
设备
+
+
+
+
+
切换设备会话
@@ -389,6 +399,16 @@
+
+
+
+
+