Improve dashboard diagnostics and update UI

This commit is contained in:
Your Name committed 2026-06-28 21:26:48 +08:00
1 parent a870e0cbf9
commit c0cb274728
6 files changed
+332 -24

No files matched your search

@@ -136,6 +136,27 @@ def _write_valid_png_bytes(tmp_file: str, data: bytes) -> bool:
return False
def _stderr_tail(stderr: bytes | str | None, limit: int = 800) -> str:
if stderr is None:
return ""
if isinstance(stderr, bytes):
text = stderr.decode("utf-8", errors="replace")
else:
text = str(stderr)
return text.strip()[-limit:]
def _format_completed_error(error: subprocess.CalledProcessError) -> str:
parts = [f"returncode={error.returncode}"]
stderr = _stderr_tail(getattr(error, "stderr", None))
stdout = _stderr_tail(getattr(error, "output", None))
if stderr:
parts.append(f"stderr={stderr}")
if stdout:
parts.append(f"stdout={stdout}")
return ", ".join(parts)
def capture_screenshot_direct(
self: "underlying_operations", device_id, path: str = "pic"
) -> bool:
@@ -211,6 +232,15 @@ def capture_screenshot_direct(
except Exception:
pass
return False
except subprocess.CalledProcessError as stdout_error:
try:
_uo_log(
"[截图] shell stdout回退失败:" + _format_completed_error(stdout_error),
"WARNING",
)
except Exception:
pass
return False
except Exception as stdout_error:
try:
_uo_log(
@@ -260,7 +290,7 @@ def capture_screenshot_direct(
process = subprocess.Popen(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
stderr=subprocess.PIPE,
bufsize=0,
)
@@ -299,7 +329,7 @@ def capture_screenshot_direct(
except Exception:
done_event = None
stdout_data, _ = process.communicate(timeout=execout_timeout_sec)
stdout_data, stderr_data = process.communicate(timeout=execout_timeout_sec)
if done_event is not None:
done_event.set()
@@ -307,6 +337,8 @@ def capture_screenshot_direct(
raise subprocess.CalledProcessError(
process.returncode,
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
output=stdout_data,
stderr=stderr_data,
)
with open(tmp_file, "wb", buffering=262144) as f:
@@ -427,7 +459,10 @@ def capture_screenshot_direct(
except Exception:
pass
except Exception as e:
_uo_log(f"[截图] exec-out 异常:{e}")
if isinstance(e, subprocess.CalledProcessError):
_uo_log(f"[截图] exec-out 异常:{_format_completed_error(e)}")
else:
_uo_log(f"[截图] exec-out 异常:{e}")
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
@@ -440,7 +475,7 @@ def capture_screenshot_direct(
shell_screencap_start = time_module.time()
remote_shot = path_config.get_android_screenshot_path()
remote_shot_alt = path_config.get_android_screenshot_alt_path()
subprocess.run(
shell_result = subprocess.run(
[
adb,
"-s",
@@ -451,10 +486,13 @@ def capture_screenshot_direct(
remote_shot,
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stderr=subprocess.PIPE,
check=True,
timeout=10,
)
shell_stderr = _stderr_tail(getattr(shell_result, "stderr", None))
if shell_stderr:
logging.info("[截图] 回退方案-shell screencap stderr=%s", shell_stderr)
shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0
logging.info(
"[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s",
@@ -463,13 +501,16 @@ def capture_screenshot_direct(
)
pull_start = time_module.time()
subprocess.run(
pull_result = subprocess.run(
[adb, "-s", device_id, "pull", remote_shot, tmp_file],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stderr=subprocess.PIPE,
check=True,
timeout=10,
)
pull_stderr = _stderr_tail(getattr(pull_result, "stderr", None))
if pull_stderr:
logging.info("[截图] 回退方案-adb pull stderr=%s", pull_stderr)
pull_dur = (time_module.time() - pull_start) * 1000.0
logging.info(
"[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id
@@ -567,6 +608,14 @@ def capture_screenshot_direct(
)
except Exception:
pass
except subprocess.CalledProcessError as fallback_error:
try:
_uo_log(
"[截图] 回退方案失败,继续尝试 shell stdout 回退:"
+ _format_completed_error(fallback_error)
)
except Exception:
pass
except Exception as fallback_error:
try:
_uo_log(f"[截图] 回退方案失败,继续尝试 shell stdout 回退:{fallback_error}")
+167 -5
View File
@@ -2,6 +2,8 @@ from __future__ import annotations
import json
import os
import platform
import subprocess
import time
import zipfile
from dataclasses import dataclass
@@ -12,9 +14,11 @@ from urllib import request
from douyin.core import path_config
from douyin.license.license_manager import get_default_license_path, get_default_verify_url
DEFAULT_MAX_ARCHIVE_BYTES = 8 * 1024 * 1024
DEFAULT_MAX_SOURCE_BYTES = 2 * 1024 * 1024
DEFAULT_MAX_FILES = 12
DEFAULT_MAX_ARCHIVE_BYTES = 32 * 1024 * 1024
DEFAULT_MAX_SOURCE_BYTES = 4 * 1024 * 1024
DEFAULT_MAX_FILES = 32
DEFAULT_MAX_IMAGE_BYTES = 5 * 1024 * 1024
SENSITIVE_KEY_PARTS = ("key", "token", "secret", "password", "license", "card")
@dataclass(frozen=True)
@@ -56,6 +60,121 @@ def _tail_bytes(path: Path, limit: int) -> bytes:
return f.read(limit)
def _safe_rel(path: Path, base: Path) -> str:
try:
return path.relative_to(base).as_posix()
except Exception:
return path.name
def _redact_value(key: str, value: Any) -> Any:
key_l = str(key or "").lower()
if isinstance(value, dict):
return {str(k): _redact_value(str(k), v) for k, v in value.items()}
if isinstance(value, list):
return [_redact_value(key, item) for item in value]
if any(part in key_l for part in SENSITIVE_KEY_PARTS):
return "<redacted>"
return value
def _read_redacted_config() -> dict[str, Any] | None:
try:
path = Path(path_config.get_config_path())
obj = json.loads(path.read_text(encoding="utf-8-sig"))
if not isinstance(obj, dict):
return None
return {str(k): _redact_value(str(k), v) for k, v in obj.items()}
except Exception:
return None
def _candidate_state_files(state_dir: Path) -> list[Path]:
if not state_dir.exists():
return []
names = {
"reservations.json",
"room_pos_map.json",
"high_value_rooms.json",
"runtime_stats.json",
"dashboard_stats.json",
}
files = [p for p in state_dir.rglob("*.json") if p.is_file() and p.name in names]
return sorted(files, key=lambda p: p.stat().st_mtime, reverse=True)
def _candidate_pic_files(pic_dir: Path) -> list[Path]:
if not pic_dir.exists():
return []
preferred = []
for name in (
"screenshot.png",
"screenshot.png.tmp",
"screenshot.jpg",
"latest.png",
"last_match.png",
):
p = pic_dir / name
if p.is_file():
preferred.append(p)
def _is_diagnostic_pic(path: Path) -> bool:
suffix = path.suffix.lower()
if suffix in {".png", ".jpg", ".jpeg"}:
return True
return path.name.lower().endswith(".png.tmp")
recent = sorted(
[p for p in pic_dir.rglob("*") if p.is_file() and _is_diagnostic_pic(p)],
key=lambda p: p.stat().st_mtime,
reverse=True,
)
result: list[Path] = []
for item in [*preferred, *recent]:
if item not in result:
result.append(item)
if len(result) >= 12:
break
return result
def _run_command(cmd: list[str], timeout: int = 5) -> dict[str, Any]:
try:
proc = subprocess.run(cmd, text=True, capture_output=True, timeout=timeout)
return {
"cmd": cmd,
"returncode": proc.returncode,
"stdout": (proc.stdout or "")[-4000:],
"stderr": (proc.stderr or "")[-2000:],
}
except Exception as exc:
return {"cmd": cmd, "error": f"{type(exc).__name__}: {exc}"}
def _diagnostic_environment() -> dict[str, Any]:
payload: dict[str, Any] = {
"created_at": int(time.time()),
"platform": platform.platform(),
"python": platform.python_version(),
"cwd": os.getcwd(),
"project_root": path_config.get_project_root(),
"logs_dir": path_config.get_logs_dir(),
"pic_dir": path_config.get_pic_dir(),
"state_dir": path_config.get_state_dir(),
}
adb = ""
try:
from gui.gui_core import find_adb_executable
adb = str(find_adb_executable() or "")
except Exception:
adb = str(os.environ.get("ADB") or "adb")
payload["adb"] = adb
payload["adb_version"] = _run_command([adb, "version"]) if adb else {"error": "adb not found"}
payload["adb_devices"] = _run_command([adb, "devices", "-l"]) if adb else {"error": "adb not found"}
return payload
def build_diagnostic_log_archive(
*,
output_dir: str | os.PathLike[str] | None = None,
@@ -79,17 +198,60 @@ def build_diagnostic_log_archive(
"files": [],
}
for file in files:
rel = file.relative_to(logs_dir).as_posix()
rel = _safe_rel(file, logs_dir)
data = _tail_bytes(file, max_source_bytes)
zf.writestr(f"logs/{rel}", data)
manifest["files"].append(
{
"path": rel,
"path": f"logs/{rel}",
"original_size": file.stat().st_size,
"included_size": len(data),
"mtime": int(file.stat().st_mtime),
}
)
try:
pic_dir = Path(path_config.get_pic_dir())
for file in _candidate_pic_files(pic_dir):
if file.stat().st_size > DEFAULT_MAX_IMAGE_BYTES:
continue
rel = _safe_rel(file, pic_dir)
zf.write(file, f"pic/{rel}")
manifest["files"].append(
{
"path": f"pic/{rel}",
"original_size": file.stat().st_size,
"included_size": file.stat().st_size,
"mtime": int(file.stat().st_mtime),
}
)
except Exception as exc:
manifest["pic_error"] = str(exc)
try:
state_dir = Path(path_config.get_state_dir())
for file in _candidate_state_files(state_dir):
rel = _safe_rel(file, state_dir)
data = _tail_bytes(file, max_source_bytes)
zf.writestr(f"state/{rel}", data)
manifest["files"].append(
{
"path": f"state/{rel}",
"original_size": file.stat().st_size,
"included_size": len(data),
"mtime": int(file.stat().st_mtime),
}
)
except Exception as exc:
manifest["state_error"] = str(exc)
redacted_cfg = _read_redacted_config()
if redacted_cfg is not None:
zf.writestr(
"config/config.redacted.json",
json.dumps(redacted_cfg, ensure_ascii=False, indent=2),
)
zf.writestr(
"diagnostics/environment.json",
json.dumps(_diagnostic_environment(), ensure_ascii=False, indent=2),
)
zf.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2))
if archive.stat().st_size > max_archive_bytes:
+60 -11
View File
@@ -143,9 +143,9 @@ class DashboardApp:
).pack(side="right", padx=(0, 8))
tool_row = tk.Frame(top, bg=theme.SURFACE)
tool_row.pack(fill="x", padx=20, pady=(4, 14))
tool_row.grid_columnconfigure(0, minsize=360)
tool_row.grid_columnconfigure(0, minsize=350)
tool_row.grid_columnconfigure(1, weight=1)
tool_row.grid_columnconfigure(2, minsize=350)
tool_row.grid_columnconfigure(2, minsize=318)
device_group = tk.Frame(tool_row, bg=theme.SURFACE)
device_group.grid(row=0, column=0, sticky="ew", padx=(0, 16))
@@ -170,10 +170,11 @@ class DashboardApp:
).pack(anchor="w", pady=(0, 7))
device_button_row = tk.Frame(device_actions, bg=theme.SURFACE)
device_button_row.pack(anchor="w")
button(device_button_row, "刷新设备", self.refresh_devices, width=136).pack(side="left", padx=(0, 9))
self.scan_button = button(device_button_row, "扫描 WiFi", self.scan_wifi, width=136)
self.scan_button.pack(side="left", padx=(0, 9))
button(device_button_row, "WiFi ADB", self.open_wifi_adb, width=126).pack(side="left")
button(device_button_row, "刷新设备", self.refresh_devices, width=120).pack(side="left", padx=(0, 6))
self.scan_button = button(device_button_row, "扫描 WiFi", self.scan_wifi, width=124)
self.scan_button.pack(side="left", padx=(0, 6))
button(device_button_row, "WiFi ADB", self.open_wifi_adb, width=112).pack(side="left", padx=(0, 6))
button(device_button_row, "上传日志", self.upload_logs, width=112).pack(side="left")
primary_actions = tk.Frame(tool_row, bg=theme.SURFACE)
primary_actions.grid(row=0, column=2, sticky="e")
@@ -186,8 +187,8 @@ class DashboardApp:
).pack(anchor="e", pady=(0, 7))
primary_button_row = tk.Frame(primary_actions, bg=theme.SURFACE)
primary_button_row.pack(anchor="e")
button(primary_button_row, "保存配置", self.save_config, width=138).pack(side="left", padx=(0, 10))
button(primary_button_row, "截图+OCR", self.screenshot_ocr, kind="primary", width=156).pack(side="left")
button(primary_button_row, "保存配置", self.save_config, width=130).pack(side="left", padx=(0, 8))
button(primary_button_row, "截图+OCR", self.screenshot_ocr, kind="primary", width=148).pack(side="left")
main = ttk.Frame(shell, style="Dashboard.TFrame")
main.pack(fill="both", expand=True, padx=20, pady=(6, 6))
@@ -536,18 +537,66 @@ class DashboardApp:
if not self._ensure_license_ready():
return
self.status_var.set("正在检查更新")
progress = self._show_update_progress("正在连接更新服务器")
def worker() -> None:
try:
result = perform_forced_update(settings=load_manual_update_settings())
self.root.after(0, lambda: self._show_update_result(result))
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_result(result)))
except UpdateError as exc:
self.root.after(0, lambda: self._show_update_error(str(exc)))
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_error(str(exc))))
except Exception as exc:
self.root.after(0, lambda: self._show_update_error(f"检查更新异常:{exc}"))
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_error(f"检查更新异常:{exc}")))
threading.Thread(target=worker, daemon=True).start()
def _show_update_progress(self, message: str) -> tk.Toplevel:
win = tk.Toplevel(self.root)
win.title("检查更新")
win.transient(self.root)
win.resizable(False, False)
win.configure(bg=theme.SURFACE)
win.protocol("WM_DELETE_WINDOW", lambda: None)
frame = tk.Frame(win, bg=theme.SURFACE, padx=24, pady=22)
frame.pack(fill="both", expand=True)
tk.Label(
frame,
text="正在检查更新",
bg=theme.SURFACE,
fg=theme.TEXT,
font=("Microsoft YaHei UI", 16, "bold"),
).pack(anchor="w")
tk.Label(
frame,
text=message,
bg=theme.SURFACE,
fg=theme.MUTED,
font=theme.FONT_UI,
).pack(anchor="w", pady=(8, 14))
bar = ttk.Progressbar(frame, mode="indeterminate", length=340)
bar.pack(fill="x")
bar.start(12)
try:
win.update_idletasks()
x = self.root.winfo_rootx() + (self.root.winfo_width() - win.winfo_width()) // 2
y = self.root.winfo_rooty() + (self.root.winfo_height() - win.winfo_height()) // 2
win.geometry(f"+{max(0, x)}+{max(0, y)}")
win.grab_set()
except Exception:
pass
return win
def _finish_update_progress(self, progress: tk.Toplevel, callback) -> None:
try:
progress.grab_release()
except Exception:
pass
try:
progress.destroy()
except Exception:
pass
callback()
def _show_update_result(self, result) -> None:
self.status_var.set(result.message or "更新检查完成")
if result.exit_required:
-1
View File
@@ -198,4 +198,3 @@ def build_license(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> Non
row = tk.Frame(box, bg=theme.SURFACE)
row.pack(fill="x", padx=20, pady=(0, 16))
button(row, "验证卡密", ctx.action("verify_license"), kind="primary").pack(side="left", padx=(0, 8))
button(row, "上传诊断日志", ctx.action("upload_logs"), kind="soft").pack(side="left", padx=(0, 8))
+1
View File
@@ -28,6 +28,7 @@ BUTTON_ICONS = {
"打开目录": "□",
"验证卡密": "✓",
"上传诊断日志": "⇧",
"上传日志": "⇧",
"检查更新": "↻",
"刷新状态": "⟳",
"保存日志配置": "✓",
+48
View File
@@ -32,6 +32,54 @@ def test_build_diagnostic_log_archive_tails_logs_only(tmp_path, monkeypatch):
assert zf.read("logs/unified.log") == b"a" * 10
def test_build_diagnostic_log_archive_includes_runtime_context_and_recent_images(tmp_path, monkeypatch):
from douyin.core import path_config
from douyin.diagnostics import log_upload
logs_dir = tmp_path / "logs"
logs_dir.mkdir()
pic_dir = tmp_path / "pic"
pic_dir.mkdir()
state_dir = tmp_path / "state"
state_dir.mkdir()
cfg_path = tmp_path / "config.json"
(logs_dir / "screenshot_calls.jsonl").write_text("call\n", encoding="utf-8")
(pic_dir / "screenshot.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"x" * 2048)
(pic_dir / "screenshot.png.tmp").write_bytes(b"broken screenshot output")
(pic_dir / "latest.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"y" * 2048)
(state_dir / "room_pos_map.json").write_text('{"1": "room"}', encoding="utf-8")
cfg_path.write_text(
json.dumps(
{
"device_id": "dev-1",
"license": {"card_key": "DG-SHOULD-NOT-LEAK"},
"api_token": "secret",
},
ensure_ascii=False,
),
encoding="utf-8",
)
monkeypatch.setattr(path_config, "get_logs_dir", lambda: str(logs_dir))
monkeypatch.setattr(path_config, "get_pic_dir", lambda: str(pic_dir))
monkeypatch.setattr(path_config, "get_state_dir", lambda: str(state_dir))
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg_path))
archive = log_upload.build_diagnostic_log_archive(output_dir=tmp_path, max_archive_bytes=1024 * 1024)
with zipfile.ZipFile(archive) as zf:
names = set(zf.namelist())
assert "logs/screenshot_calls.jsonl" in names
assert "pic/screenshot.png" in names
assert "pic/screenshot.png.tmp" in names
assert "pic/latest.png" in names
assert "state/room_pos_map.json" in names
assert "config/config.redacted.json" in names
assert "diagnostics/environment.json" in names
redacted = json.loads(zf.read("config/config.redacted.json").decode("utf-8"))
assert redacted["license"]["card_key"] == "<redacted>"
assert redacted["api_token"] == "<redacted>"
def test_license_server_log_upload_overwrites_same_card(tmp_path):
from fastapi.testclient import TestClient