add pause resume controls to ui
This commit is contained in:
1 parent
3c7cb45bec
commit
d81e00ddbc
13 files changed
+367
-12
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
"""底部操作按钮区(开始运行 / 停止 / 强制停止 / 发送返回键 / 状态标签)。
|
"""底部操作按钮区(开始运行 / 暂停继续 / 停止 / 强制停止 / 发送返回键 / 状态标签)。
|
||||||
|
|
||||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的 widget 创建段 + 4 个按钮回调
|
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的 widget 创建段 + 4 个按钮回调
|
||||||
(``start_run`` / ``stop_run`` / ``force_stop_run`` / ``send_back_key``)。
|
(``start_run`` / ``stop_run`` / ``force_stop_run`` / ``send_back_key``)。
|
||||||
@@ -24,7 +24,7 @@ def setup_action_buttons(
|
|||||||
save_ui_to_config: Callable[[], None],
|
save_ui_to_config: Callable[[], None],
|
||||||
get_params: Callable[[], Any],
|
get_params: Callable[[], Any],
|
||||||
) -> None:
|
) -> None:
|
||||||
"""构建底部操作按钮区(开始/停止/强制停止/发送返回键 + 状态标签)。"""
|
"""构建底部操作按钮区(开始/暂停继续/停止/强制停止/发送返回键 + 状态标签)。"""
|
||||||
|
|
||||||
def start_run() -> None:
|
def start_run() -> None:
|
||||||
if runner.is_running():
|
if runner.is_running():
|
||||||
@@ -65,6 +65,18 @@ def setup_action_buttons(
|
|||||||
runner.stop()
|
runner.stop()
|
||||||
status_var.set("已停止")
|
status_var.set("已停止")
|
||||||
|
|
||||||
|
def pause_resume_run() -> None:
|
||||||
|
if not runner.is_running():
|
||||||
|
on_line("[暂停] 当前没有正在运行的进程")
|
||||||
|
status_var.set("未运行")
|
||||||
|
return
|
||||||
|
if getattr(runner, "is_paused", lambda: False)():
|
||||||
|
ok = runner.resume()
|
||||||
|
status_var.set("运行中" if ok else "继续失败")
|
||||||
|
else:
|
||||||
|
ok = runner.pause()
|
||||||
|
status_var.set("已暂停" if ok else "暂停失败")
|
||||||
|
|
||||||
def force_stop_run() -> None:
|
def force_stop_run() -> None:
|
||||||
"""强制终止后台进程(包括可能残留的子进程)。"""
|
"""强制终止后台进程(包括可能残留的子进程)。"""
|
||||||
runner.force_stop()
|
runner.force_stop()
|
||||||
@@ -78,6 +90,9 @@ def setup_action_buttons(
|
|||||||
on_line(f"[错误] 发送返回键失败: {e}")
|
on_line(f"[错误] 发送返回键失败: {e}")
|
||||||
|
|
||||||
ttk.Button(actions, text="开始运行", command=start_run).pack(side=LEFT, padx=(0, 8))
|
ttk.Button(actions, text="开始运行", command=start_run).pack(side=LEFT, padx=(0, 8))
|
||||||
|
ttk.Button(actions, text="暂停/继续", command=pause_resume_run).pack(
|
||||||
|
side=LEFT, padx=(0, 4)
|
||||||
|
)
|
||||||
ttk.Button(actions, text="停止", command=stop_run).pack(side=LEFT, padx=(0, 4))
|
ttk.Button(actions, text="停止", command=stop_run).pack(side=LEFT, padx=(0, 4))
|
||||||
ttk.Button(actions, text="强制停止", command=force_stop_run).pack(
|
ttk.Button(actions, text="强制停止", command=force_stop_run).pack(
|
||||||
side=LEFT, padx=(0, 8)
|
side=LEFT, padx=(0, 8)
|
||||||
|
|||||||
@@ -150,6 +150,7 @@ class DashboardApp:
|
|||||||
inner_bottom = tk.Frame(bottom, bg=theme.SURFACE)
|
inner_bottom = tk.Frame(bottom, bg=theme.SURFACE)
|
||||||
inner_bottom.pack(fill="x", padx=14, pady=11)
|
inner_bottom.pack(fill="x", padx=14, pady=11)
|
||||||
button(inner_bottom, "开始运行", self.start_run, kind="primary", width=132).pack(side="left", padx=(0, 8))
|
button(inner_bottom, "开始运行", self.start_run, kind="primary", width=132).pack(side="left", padx=(0, 8))
|
||||||
|
button(inner_bottom, "暂停/继续", self.pause_resume_run, width=124).pack(side="left", padx=4)
|
||||||
button(inner_bottom, "停止", self.stop_run, width=96).pack(side="left", padx=4)
|
button(inner_bottom, "停止", self.stop_run, width=96).pack(side="left", padx=4)
|
||||||
button(inner_bottom, "强制停止", self.force_stop_run, kind="danger", width=132).pack(side="left", padx=4)
|
button(inner_bottom, "强制停止", self.force_stop_run, kind="danger", width=132).pack(side="left", padx=4)
|
||||||
button(inner_bottom, "发送返回键", self.send_back_key, width=146).pack(side="left", padx=8)
|
button(inner_bottom, "发送返回键", self.send_back_key, width=146).pack(side="left", padx=8)
|
||||||
@@ -172,6 +173,8 @@ class DashboardApp:
|
|||||||
color, bg = theme.RED, theme.RED_SOFT
|
color, bg = theme.RED, theme.RED_SOFT
|
||||||
elif "运行" in text or "扫描" in text:
|
elif "运行" in text or "扫描" in text:
|
||||||
color, bg = theme.TEAL, theme.TEAL_SOFT
|
color, bg = theme.TEAL, theme.TEAL_SOFT
|
||||||
|
elif "暂停" in text:
|
||||||
|
color, bg = theme.AMBER, theme.AMBER_SOFT
|
||||||
elif "未" in text:
|
elif "未" in text:
|
||||||
color, bg = theme.AMBER, theme.AMBER_SOFT
|
color, bg = theme.AMBER, theme.AMBER_SOFT
|
||||||
self.status_pill.configure(text=text, fg=color, bg=bg)
|
self.status_pill.configure(text=text, fg=color, bg=bg)
|
||||||
@@ -339,6 +342,17 @@ class DashboardApp:
|
|||||||
self.runner.stop()
|
self.runner.stop()
|
||||||
self.status_var.set("已停止")
|
self.status_var.set("已停止")
|
||||||
|
|
||||||
|
def pause_resume_run(self) -> None:
|
||||||
|
if not self.runner.is_running():
|
||||||
|
self.status_var.set("未运行")
|
||||||
|
return
|
||||||
|
if self.runner.is_paused():
|
||||||
|
ok = self.runner.resume()
|
||||||
|
self.status_var.set("运行中" if ok else "继续失败")
|
||||||
|
else:
|
||||||
|
ok = self.runner.pause()
|
||||||
|
self.status_var.set("已暂停" if ok else "暂停失败")
|
||||||
|
|
||||||
def force_stop_run(self) -> None:
|
def force_stop_run(self) -> None:
|
||||||
self.runner.force_stop()
|
self.runner.force_stop()
|
||||||
self.status_var.set("已停止(强制)")
|
self.status_var.set("已停止(强制)")
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ BUTTON_ICONS = {
|
|||||||
"保存配置": "✓",
|
"保存配置": "✓",
|
||||||
"截图+OCR": "▧",
|
"截图+OCR": "▧",
|
||||||
"开始运行": "▶",
|
"开始运行": "▶",
|
||||||
|
"暂停/继续": "Ⅱ",
|
||||||
"停止": "■",
|
"停止": "■",
|
||||||
"强制停止": "!",
|
"强制停止": "!",
|
||||||
"发送返回键": "↩",
|
"发送返回键": "↩",
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from dataclasses import dataclass
|
|||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from douyin.core import path_config
|
from douyin.core import path_config
|
||||||
|
from gui.process_pause import resume_process_tree, suspend_process_tree
|
||||||
|
|
||||||
# 从子包 re-export 顶层符号(保持兼容)
|
# 从子包 re-export 顶层符号(保持兼容)
|
||||||
from gui.gui_core_pkg import (
|
from gui.gui_core_pkg import (
|
||||||
@@ -55,6 +56,7 @@ class Runner:
|
|||||||
self._last_log_ts: Optional[float] = None
|
self._last_log_ts: Optional[float] = None
|
||||||
self._exit_code: Optional[int] = None
|
self._exit_code: Optional[int] = None
|
||||||
self._pid: Optional[int] = None
|
self._pid: Optional[int] = None
|
||||||
|
self._paused: bool = False
|
||||||
self._counters: dict[str, int] = {}
|
self._counters: dict[str, int] = {}
|
||||||
self._fudai_last: dict[str, object] = {
|
self._fudai_last: dict[str, object] = {
|
||||||
"content": "",
|
"content": "",
|
||||||
@@ -88,6 +90,10 @@ class Runner:
|
|||||||
def is_running(self) -> bool:
|
def is_running(self) -> bool:
|
||||||
return self._proc is not None and self._proc.poll() is None
|
return self._proc is not None and self._proc.poll() is None
|
||||||
|
|
||||||
|
def is_paused(self) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
return bool(self._paused and self._proc is not None and self._proc.poll() is None)
|
||||||
|
|
||||||
def _append_log_line(self, line: str) -> None:
|
def _append_log_line(self, line: str) -> None:
|
||||||
if line is None:
|
if line is None:
|
||||||
return
|
return
|
||||||
@@ -163,6 +169,7 @@ class Runner:
|
|||||||
start_ts = self._start_ts
|
start_ts = self._start_ts
|
||||||
last_log_ts = self._last_log_ts
|
last_log_ts = self._last_log_ts
|
||||||
exit_code = self._exit_code
|
exit_code = self._exit_code
|
||||||
|
paused = bool(self._paused and self._proc is not None and self._proc.poll() is None)
|
||||||
counters = dict(self._counters)
|
counters = dict(self._counters)
|
||||||
fudai_last = dict(self._fudai_last)
|
fudai_last = dict(self._fudai_last)
|
||||||
wins = list(self._wins[-20:]) # 只返回最近20条
|
wins = list(self._wins[-20:]) # 只返回最近20条
|
||||||
@@ -175,6 +182,7 @@ class Runner:
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"running": bool(running),
|
"running": bool(running),
|
||||||
|
"paused": paused,
|
||||||
"pid": pid,
|
"pid": pid,
|
||||||
"start_ts": start_ts,
|
"start_ts": start_ts,
|
||||||
"last_log_ts": last_log_ts,
|
"last_log_ts": last_log_ts,
|
||||||
@@ -383,6 +391,7 @@ class Runner:
|
|||||||
with self._lock:
|
with self._lock:
|
||||||
self._proc = p
|
self._proc = p
|
||||||
self._pid = p.pid
|
self._pid = p.pid
|
||||||
|
self._paused = False
|
||||||
self._start_ts = time.time()
|
self._start_ts = time.time()
|
||||||
self._exit_code = None
|
self._exit_code = None
|
||||||
self._last_log_ts = time.time()
|
self._last_log_ts = time.time()
|
||||||
@@ -420,6 +429,7 @@ class Runner:
|
|||||||
rc = self._proc.wait()
|
rc = self._proc.wait()
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._exit_code = rc
|
self._exit_code = rc
|
||||||
|
self._paused = False
|
||||||
|
|
||||||
# 如果进程立即退出且没有输出,说明可能有问题
|
# 如果进程立即退出且没有输出,说明可能有问题
|
||||||
if not has_output and rc != 0:
|
if not has_output and rc != 0:
|
||||||
@@ -437,6 +447,7 @@ class Runner:
|
|||||||
if rc is not None:
|
if rc is not None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._exit_code = rc
|
self._exit_code = rc
|
||||||
|
self._paused = False
|
||||||
self._emit_line(f"[进程结束] exit_code={rc}")
|
self._emit_line(f"[进程结束] exit_code={rc}")
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@@ -496,10 +507,58 @@ class Runner:
|
|||||||
self._emit_line(f"[错误] 发送返回键异常: {str(e)}")
|
self._emit_line(f"[错误] 发送返回键异常: {str(e)}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def pause(self) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
proc = self._proc
|
||||||
|
pid = self._pid or (proc.pid if proc is not None else None)
|
||||||
|
already_paused = self._paused
|
||||||
|
if proc is None or proc.poll() is not None or not pid:
|
||||||
|
self._emit_line("[暂停] 当前没有正在运行的进程")
|
||||||
|
with self._lock:
|
||||||
|
self._paused = False
|
||||||
|
return False
|
||||||
|
if already_paused:
|
||||||
|
self._emit_line("[暂停] 当前已经是暂停状态")
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
suspend_process_tree(int(pid))
|
||||||
|
with self._lock:
|
||||||
|
self._paused = True
|
||||||
|
self._emit_line("[暂停] 已暂停运行进程")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
self._emit_line(f"[暂停] 暂停失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def resume(self) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
proc = self._proc
|
||||||
|
pid = self._pid or (proc.pid if proc is not None else None)
|
||||||
|
already_paused = self._paused
|
||||||
|
if proc is None or proc.poll() is not None or not pid:
|
||||||
|
self._emit_line("[继续] 当前没有可恢复的运行进程")
|
||||||
|
with self._lock:
|
||||||
|
self._paused = False
|
||||||
|
return False
|
||||||
|
if not already_paused:
|
||||||
|
self._emit_line("[继续] 当前不在暂停状态")
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
resume_process_tree(int(pid))
|
||||||
|
with self._lock:
|
||||||
|
self._paused = False
|
||||||
|
self._emit_line("[继续] 已恢复运行进程")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
self._emit_line(f"[继续] 恢复失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
def stop(self) -> None:
|
def stop(self) -> None:
|
||||||
if not self.is_running():
|
if not self.is_running():
|
||||||
return
|
return
|
||||||
assert self._proc is not None
|
assert self._proc is not None
|
||||||
|
if self.is_paused():
|
||||||
|
self.resume()
|
||||||
self._emit_line("[停止] 正在终止进程...")
|
self._emit_line("[停止] 正在终止进程...")
|
||||||
self._proc.terminate()
|
self._proc.terminate()
|
||||||
try:
|
try:
|
||||||
@@ -519,6 +578,12 @@ class Runner:
|
|||||||
|
|
||||||
self._emit_line(f"[停止] 强制终止进程 (pid={pid}) ...")
|
self._emit_line(f"[停止] 强制终止进程 (pid={pid}) ...")
|
||||||
|
|
||||||
|
if self.is_paused() and pid:
|
||||||
|
try:
|
||||||
|
resume_process_tree(int(pid))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
# 先尝试通过 Popen 对象 kill
|
# 先尝试通过 Popen 对象 kill
|
||||||
try:
|
try:
|
||||||
if proc is not None and proc.poll() is None:
|
if proc is not None and proc.poll() is None:
|
||||||
@@ -552,3 +617,4 @@ class Runner:
|
|||||||
with self._lock:
|
with self._lock:
|
||||||
self._proc = None
|
self._proc = None
|
||||||
self._pid = None
|
self._pid = None
|
||||||
|
self._paused = False
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""Process-tree pause/resume helpers shared by the desktop and Web UI."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
|
||||||
|
def _run_powershell_tree_action(pid: int, action: str) -> None:
|
||||||
|
if action not in {"suspend", "resume"}:
|
||||||
|
raise ValueError(f"unsupported process action: {action}")
|
||||||
|
native_call = "[NativeMethods]::SuspendProcess($_)" if action == "suspend" else "[NativeMethods]::ResumeProcess($_)"
|
||||||
|
script = f"""
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
Add-Type @"
|
||||||
|
using System;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
public static class NativeMethods {{
|
||||||
|
[DllImport("kernel32.dll", SetLastError=true)]
|
||||||
|
public static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
||||||
|
[DllImport("kernel32.dll", SetLastError=true)]
|
||||||
|
public static extern bool CloseHandle(IntPtr handle);
|
||||||
|
[DllImport("ntdll.dll")]
|
||||||
|
public static extern int NtSuspendProcess(IntPtr processHandle);
|
||||||
|
[DllImport("ntdll.dll")]
|
||||||
|
public static extern int NtResumeProcess(IntPtr processHandle);
|
||||||
|
public static void SuspendProcess(int pid) {{
|
||||||
|
IntPtr h = OpenProcess(0x0800, false, pid);
|
||||||
|
if (h == IntPtr.Zero) throw new InvalidOperationException("OpenProcess failed: " + pid);
|
||||||
|
try {{
|
||||||
|
int rc = NtSuspendProcess(h);
|
||||||
|
if (rc != 0) throw new InvalidOperationException("NtSuspendProcess failed: " + rc);
|
||||||
|
}} finally {{
|
||||||
|
CloseHandle(h);
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
public static void ResumeProcess(int pid) {{
|
||||||
|
IntPtr h = OpenProcess(0x0800, false, pid);
|
||||||
|
if (h == IntPtr.Zero) throw new InvalidOperationException("OpenProcess failed: " + pid);
|
||||||
|
try {{
|
||||||
|
int rc = NtResumeProcess(h);
|
||||||
|
if (rc != 0) throw new InvalidOperationException("NtResumeProcess failed: " + rc);
|
||||||
|
}} finally {{
|
||||||
|
CloseHandle(h);
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
"@
|
||||||
|
$ids = New-Object System.Collections.Generic.List[int]
|
||||||
|
function Add-Tree([int]$p) {{
|
||||||
|
if ($ids.Contains($p)) {{ return }}
|
||||||
|
$ids.Add($p) | Out-Null
|
||||||
|
Get-CimInstance Win32_Process -Filter "ParentProcessId=$p" |
|
||||||
|
ForEach-Object {{ Add-Tree ([int]$_.ProcessId) }}
|
||||||
|
}}
|
||||||
|
Add-Tree {int(pid)}
|
||||||
|
$ids | Sort-Object -Unique | ForEach-Object {{ {native_call} }}
|
||||||
|
"""
|
||||||
|
proc = subprocess.run(
|
||||||
|
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
timeout=8,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
if proc.returncode != 0:
|
||||||
|
detail = (proc.stderr or proc.stdout or "").strip()
|
||||||
|
raise RuntimeError(detail or f"{action} failed for pid={pid}")
|
||||||
|
|
||||||
|
|
||||||
|
def suspend_process_tree(pid: int) -> None:
|
||||||
|
"""Pause a process and its children."""
|
||||||
|
pid = int(pid or 0)
|
||||||
|
if pid <= 0:
|
||||||
|
raise ValueError("missing pid")
|
||||||
|
if os.name == "nt":
|
||||||
|
_run_powershell_tree_action(pid, "suspend")
|
||||||
|
return
|
||||||
|
|
||||||
|
import signal
|
||||||
|
|
||||||
|
os.kill(pid, signal.SIGSTOP)
|
||||||
|
|
||||||
|
|
||||||
|
def resume_process_tree(pid: int) -> None:
|
||||||
|
"""Resume a process and its children."""
|
||||||
|
pid = int(pid or 0)
|
||||||
|
if pid <= 0:
|
||||||
|
raise ValueError("missing pid")
|
||||||
|
if os.name == "nt":
|
||||||
|
_run_powershell_tree_action(pid, "resume")
|
||||||
|
return
|
||||||
|
|
||||||
|
import signal
|
||||||
|
|
||||||
|
os.kill(pid, signal.SIGCONT)
|
||||||
@@ -47,6 +47,7 @@ from gui.web_gui_pkg.net_config import get_web_gui_host, get_web_gui_port
|
|||||||
from gui.web_gui_pkg.routes import handle_get, handle_post
|
from gui.web_gui_pkg.routes import handle_get, handle_post
|
||||||
from gui.web_gui_pkg import proc_runner_ops as _proc_ops
|
from gui.web_gui_pkg import proc_runner_ops as _proc_ops
|
||||||
from gui.web_gui_pkg import proc_runner_stats as _proc_stats
|
from gui.web_gui_pkg import proc_runner_stats as _proc_stats
|
||||||
|
from gui.process_pause import resume_process_tree, suspend_process_tree
|
||||||
|
|
||||||
BASE_DIR = path_config.PROJECT_ROOT
|
BASE_DIR = path_config.PROJECT_ROOT
|
||||||
CONFIG_PATH = path_config.get_config_path()
|
CONFIG_PATH = path_config.get_config_path()
|
||||||
@@ -92,6 +93,7 @@ class ProcRunner:
|
|||||||
self._last_log_ts: Optional[float] = None
|
self._last_log_ts: Optional[float] = None
|
||||||
self._exit_code: Optional[int] = None
|
self._exit_code: Optional[int] = None
|
||||||
self._pid: Optional[int] = None
|
self._pid: Optional[int] = None
|
||||||
|
self._paused: bool = False
|
||||||
self._owned_run_cli_pids: set[int] = set()
|
self._owned_run_cli_pids: set[int] = set()
|
||||||
|
|
||||||
# 运行统计(基于 stdout 日志解析)
|
# 运行统计(基于 stdout 日志解析)
|
||||||
@@ -215,6 +217,10 @@ class ProcRunner:
|
|||||||
with self._lock:
|
with self._lock:
|
||||||
return self._proc is not None and self._proc.poll() is None
|
return self._proc is not None and self._proc.poll() is None
|
||||||
|
|
||||||
|
def is_paused(self) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
return bool(self._paused and self._proc is not None and self._proc.poll() is None)
|
||||||
|
|
||||||
def _list_project_run_cli_processes(self) -> list[tuple[int, str]]:
|
def _list_project_run_cli_processes(self) -> list[tuple[int, str]]:
|
||||||
"""列出当前仓库下运行的 run_cli.py 进程(含 pid 与命令行)。"""
|
"""列出当前仓库下运行的 run_cli.py 进程(含 pid 与命令行)。"""
|
||||||
entries: list[tuple[int, str]] = []
|
entries: list[tuple[int, str]] = []
|
||||||
@@ -363,6 +369,11 @@ class ProcRunner:
|
|||||||
pid = self._pid
|
pid = self._pid
|
||||||
p = self._proc
|
p = self._proc
|
||||||
self._append_log(f"[停止] 强制停止请求 pid={pid or '-'}")
|
self._append_log(f"[停止] 强制停止请求 pid={pid or '-'}")
|
||||||
|
if self.is_paused() and pid:
|
||||||
|
try:
|
||||||
|
resume_process_tree(int(pid))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
try:
|
try:
|
||||||
if p is not None and p.poll() is None:
|
if p is not None and p.poll() is None:
|
||||||
p.kill()
|
p.kill()
|
||||||
@@ -379,6 +390,7 @@ class ProcRunner:
|
|||||||
with self._lock:
|
with self._lock:
|
||||||
self._proc = None
|
self._proc = None
|
||||||
self._pid = None
|
self._pid = None
|
||||||
|
self._paused = False
|
||||||
if pid:
|
if pid:
|
||||||
self._owned_run_cli_pids.discard(int(pid))
|
self._owned_run_cli_pids.discard(int(pid))
|
||||||
self._exit_code = self._exit_code if self._exit_code is not None else -9
|
self._exit_code = self._exit_code if self._exit_code is not None else -9
|
||||||
@@ -395,6 +407,8 @@ class ProcRunner:
|
|||||||
p = self._proc
|
p = self._proc
|
||||||
if p is None or p.poll() is not None:
|
if p is None or p.poll() is not None:
|
||||||
return
|
return
|
||||||
|
if self.is_paused():
|
||||||
|
self.resume()
|
||||||
self._append_log("[网页] 停止:终止进程")
|
self._append_log("[网页] 停止:终止进程")
|
||||||
try:
|
try:
|
||||||
p.terminate()
|
p.terminate()
|
||||||
@@ -409,12 +423,59 @@ class ProcRunner:
|
|||||||
try:
|
try:
|
||||||
self._proc = None
|
self._proc = None
|
||||||
self._pid = None
|
self._pid = None
|
||||||
|
self._paused = False
|
||||||
if getattr(p, "pid", None):
|
if getattr(p, "pid", None):
|
||||||
self._owned_run_cli_pids.discard(int(p.pid))
|
self._owned_run_cli_pids.discard(int(p.pid))
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
self._append_log("[网页] 停止:已尝试终止并清理进程引用")
|
self._append_log("[网页] 停止:已尝试终止并清理进程引用")
|
||||||
|
|
||||||
|
def pause(self) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
p = self._proc
|
||||||
|
pid = self._pid or (p.pid if p is not None else None)
|
||||||
|
already_paused = self._paused
|
||||||
|
if p is None or p.poll() is not None or not pid:
|
||||||
|
self._append_log("[网页] 暂停:当前没有正在运行的进程")
|
||||||
|
with self._lock:
|
||||||
|
self._paused = False
|
||||||
|
return False
|
||||||
|
if already_paused:
|
||||||
|
self._append_log("[网页] 暂停:当前已经是暂停状态")
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
suspend_process_tree(int(pid))
|
||||||
|
with self._lock:
|
||||||
|
self._paused = True
|
||||||
|
self._append_log("[网页] 暂停:已暂停运行进程")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
self._append_log(f"[网页] 暂停失败:{e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def resume(self) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
p = self._proc
|
||||||
|
pid = self._pid or (p.pid if p is not None else None)
|
||||||
|
already_paused = self._paused
|
||||||
|
if p is None or p.poll() is not None or not pid:
|
||||||
|
self._append_log("[网页] 继续:当前没有可恢复的运行进程")
|
||||||
|
with self._lock:
|
||||||
|
self._paused = False
|
||||||
|
return False
|
||||||
|
if not already_paused:
|
||||||
|
self._append_log("[网页] 继续:当前不在暂停状态")
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
resume_process_tree(int(pid))
|
||||||
|
with self._lock:
|
||||||
|
self._paused = False
|
||||||
|
self._append_log("[网页] 继续:已恢复运行进程")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
self._append_log(f"[网页] 继续失败:{e}")
|
||||||
|
return False
|
||||||
|
|
||||||
def _append_log(self, line: str) -> None:
|
def _append_log(self, line: str) -> None:
|
||||||
# 清理ANSI转义序列,避免在Web界面显示异常字符
|
# 清理ANSI转义序列,避免在Web界面显示异常字符
|
||||||
line = strip_ansi_escape_codes(line)
|
line = strip_ansi_escape_codes(line)
|
||||||
@@ -739,6 +800,7 @@ class ProcRunner:
|
|||||||
with self._lock:
|
with self._lock:
|
||||||
self._proc = p
|
self._proc = p
|
||||||
self._pid = p.pid
|
self._pid = p.pid
|
||||||
|
self._paused = False
|
||||||
self._owned_run_cli_pids.add(int(p.pid))
|
self._owned_run_cli_pids.add(int(p.pid))
|
||||||
self._start_ts = time.time()
|
self._start_ts = time.time()
|
||||||
self._exit_code = None
|
self._exit_code = None
|
||||||
@@ -772,6 +834,7 @@ class ProcRunner:
|
|||||||
self._append_log(f"[网页] 进程退出(无输出):退出码={rc}")
|
self._append_log(f"[网页] 进程退出(无输出):退出码={rc}")
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._exit_code = rc
|
self._exit_code = rc
|
||||||
|
self._paused = False
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -810,6 +873,7 @@ class ProcRunner:
|
|||||||
try:
|
try:
|
||||||
self._proc = None
|
self._proc = None
|
||||||
self._pid = None
|
self._pid = None
|
||||||
|
self._paused = False
|
||||||
self._owned_run_cli_pids.discard(int(p.pid))
|
self._owned_run_cli_pids.discard(int(p.pid))
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ def get_stats(self: Any, include_events: bool = False) -> dict:
|
|||||||
start_ts = self._start_ts
|
start_ts = self._start_ts
|
||||||
last_log_ts = self._last_log_ts
|
last_log_ts = self._last_log_ts
|
||||||
exit_code = self._exit_code
|
exit_code = self._exit_code
|
||||||
|
paused = bool(getattr(self, "_paused", False) and self._proc is not None and self._proc.poll() is None)
|
||||||
log_len = len(self._log)
|
log_len = len(self._log)
|
||||||
counters = dict(self._counters)
|
counters = dict(self._counters)
|
||||||
fudai_last = dict(self._fudai_last)
|
fudai_last = dict(self._fudai_last)
|
||||||
@@ -125,6 +126,7 @@ def get_stats(self: Any, include_events: bool = False) -> dict:
|
|||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"running": bool(running),
|
"running": bool(running),
|
||||||
|
"paused": paused,
|
||||||
"pid": pid,
|
"pid": pid,
|
||||||
"start_ts": start_ts,
|
"start_ts": start_ts,
|
||||||
"last_log_ts": last_log_ts,
|
"last_log_ts": last_log_ts,
|
||||||
@@ -145,4 +147,3 @@ def get_stats(self: Any, include_events: bool = False) -> dict:
|
|||||||
payload["events"] = events[-200:]
|
payload["events"] = events[-200:]
|
||||||
|
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
@@ -182,7 +182,12 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
|||||||
qlow = q.lower()
|
qlow = q.lower()
|
||||||
filtered = [l for l in cand if qlow in (l or "").lower()]
|
filtered = [l for l in cand if qlow in (l or "").lower()]
|
||||||
return handler._send_json(
|
return handler._send_json(
|
||||||
{"next": total, "lines": filtered, "running": runner.is_running()}
|
{
|
||||||
|
"next": total,
|
||||||
|
"lines": filtered,
|
||||||
|
"running": runner.is_running(),
|
||||||
|
"paused": runner.is_paused(),
|
||||||
|
}
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
import traceback
|
import traceback
|
||||||
@@ -192,7 +197,12 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
|||||||
level="ERROR",
|
level="ERROR",
|
||||||
)
|
)
|
||||||
return handler._send_json(
|
return handler._send_json(
|
||||||
{"next": 0, "lines": [], "running": runner.is_running()}
|
{
|
||||||
|
"next": 0,
|
||||||
|
"lines": [],
|
||||||
|
"running": runner.is_running(),
|
||||||
|
"paused": runner.is_paused(),
|
||||||
|
}
|
||||||
)
|
)
|
||||||
since = 0
|
since = 0
|
||||||
try:
|
try:
|
||||||
@@ -202,7 +212,12 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
|||||||
try:
|
try:
|
||||||
next_idx, lines = runner.get_logs_since(since)
|
next_idx, lines = runner.get_logs_since(since)
|
||||||
return handler._send_json(
|
return handler._send_json(
|
||||||
{"next": next_idx, "lines": lines, "running": runner.is_running()}
|
{
|
||||||
|
"next": next_idx,
|
||||||
|
"lines": lines,
|
||||||
|
"running": runner.is_running(),
|
||||||
|
"paused": runner.is_paused(),
|
||||||
|
}
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
import traceback
|
import traceback
|
||||||
@@ -212,7 +227,12 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
|||||||
level="ERROR",
|
level="ERROR",
|
||||||
)
|
)
|
||||||
return handler._send_json(
|
return handler._send_json(
|
||||||
{"next": 0, "lines": [], "running": runner.is_running()}
|
{
|
||||||
|
"next": 0,
|
||||||
|
"lines": [],
|
||||||
|
"running": runner.is_running(),
|
||||||
|
"paused": runner.is_paused(),
|
||||||
|
}
|
||||||
)
|
)
|
||||||
if u.path == "/api/logfile-tail":
|
if u.path == "/api/logfile-tail":
|
||||||
qs = parse_qs(u.query)
|
qs = parse_qs(u.query)
|
||||||
@@ -657,6 +677,28 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
|
|||||||
if u.path == "/api/force-stop":
|
if u.path == "/api/force-stop":
|
||||||
runner.force_stop()
|
runner.force_stop()
|
||||||
return handler._send_json({"ok": True, "message": "已执行强制停止"})
|
return handler._send_json({"ok": True, "message": "已执行强制停止"})
|
||||||
|
if u.path == "/api/pause":
|
||||||
|
ok = runner.pause()
|
||||||
|
return handler._send_json(
|
||||||
|
{
|
||||||
|
"ok": bool(ok),
|
||||||
|
"running": runner.is_running(),
|
||||||
|
"paused": runner.is_paused(),
|
||||||
|
"message": "已暂停" if ok else "暂停失败",
|
||||||
|
},
|
||||||
|
status=200 if ok else 409,
|
||||||
|
)
|
||||||
|
if u.path == "/api/resume":
|
||||||
|
ok = runner.resume()
|
||||||
|
return handler._send_json(
|
||||||
|
{
|
||||||
|
"ok": bool(ok),
|
||||||
|
"running": runner.is_running(),
|
||||||
|
"paused": runner.is_paused(),
|
||||||
|
"message": "已继续" if ok else "继续失败",
|
||||||
|
},
|
||||||
|
status=200 if ok else 409,
|
||||||
|
)
|
||||||
if u.path == "/api/back-key":
|
if u.path == "/api/back-key":
|
||||||
body = handler._read_json()
|
body = handler._read_json()
|
||||||
requested_device_id = str(body.get("device_id") or "").strip()
|
requested_device_id = str(body.get("device_id") or "").strip()
|
||||||
|
|||||||
+2
-1
@@ -1,4 +1,4 @@
|
|||||||
const BUSY_DISABLED_BUTTONS = new Set(["btnStart", "btnSave"]);
|
const BUSY_DISABLED_BUTTONS = new Set(["btnStart", "btnSave", "btnPauseResume"]);
|
||||||
|
|
||||||
let logIdx = 0;
|
let logIdx = 0;
|
||||||
let pollTimer = null;
|
let pollTimer = null;
|
||||||
@@ -54,6 +54,7 @@ window.addEventListener("DOMContentLoaded", async () => {
|
|||||||
$("btnLoad").addEventListener("click", async () => { await loadConfig(); });
|
$("btnLoad").addEventListener("click", async () => { await loadConfig(); });
|
||||||
$("btnSave").addEventListener("click", async () => { await saveConfig(); });
|
$("btnSave").addEventListener("click", async () => { await saveConfig(); });
|
||||||
$("btnStart").addEventListener("click", async () => { await startRun(); });
|
$("btnStart").addEventListener("click", async () => { await startRun(); });
|
||||||
|
$("btnPauseResume").addEventListener("click", async () => { await pauseResumeRun(); });
|
||||||
$("btnStop").addEventListener("click", async () => { await stopRun(); });
|
$("btnStop").addEventListener("click", async () => { await stopRun(); });
|
||||||
const deviceSelect = $("device");
|
const deviceSelect = $("device");
|
||||||
if (deviceSelect) deviceSelect.addEventListener("change", updateDeviceOverview);
|
if (deviceSelect) deviceSelect.addEventListener("change", updateDeviceOverview);
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ const UI_COPY = Object.freeze({
|
|||||||
starting: "启动中",
|
starting: "启动中",
|
||||||
startingMeta: "正在向后端发送启动请求",
|
startingMeta: "正在向后端发送启动请求",
|
||||||
failed: "启动失败",
|
failed: "启动失败",
|
||||||
|
paused: "已暂停",
|
||||||
|
pausedMeta: "运行进程已暂停,点击继续可恢复",
|
||||||
stopping: "停止中",
|
stopping: "停止中",
|
||||||
stoppingMeta: "已请求后端停止运行",
|
stoppingMeta: "已请求后端停止运行",
|
||||||
meta: (pid, uptimeSeconds) => `PID ${pid ?? "-"} / 运行时长 ${fmtDuration(uptimeSeconds)}`,
|
meta: (pid, uptimeSeconds) => `PID ${pid ?? "-"} / 运行时长 ${fmtDuration(uptimeSeconds)}`,
|
||||||
|
|||||||
@@ -169,6 +169,41 @@ async function stopRun() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function pauseResumeRun() {
|
||||||
|
const btn = document.getElementById("btnPauseResume");
|
||||||
|
const paused = btn?.dataset.paused === "1";
|
||||||
|
setButtonBusy("btnPauseResume", true);
|
||||||
|
try {
|
||||||
|
const result = await apiPost(paused ? "/api/resume" : "/api/pause", {});
|
||||||
|
const isPaused = !!result.paused;
|
||||||
|
appendLog([isPaused ? "[WEB] 已暂停运行" : "[WEB] 已继续运行"]);
|
||||||
|
toast(isPaused ? "已暂停运行" : "已继续运行", "success");
|
||||||
|
updatePauseResumeButton(!!result.running, isPaused);
|
||||||
|
setRunOverview(
|
||||||
|
isPaused ? UI_COPY.runOverview.paused : "运行中",
|
||||||
|
isPaused ? UI_COPY.runOverview.pausedMeta : "运行进程已恢复",
|
||||||
|
isPaused ? RUN_TONE.idle : RUN_TONE.running
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
appendLog([`[WEB] 暂停/继续失败: ${e?.message || e}`]);
|
||||||
|
toast(`暂停/继续失败:${e?.message || e}`, "error", { duration: 4000 });
|
||||||
|
} finally {
|
||||||
|
setButtonBusy("btnPauseResume", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePauseResumeButton(running, paused) {
|
||||||
|
const btn = document.getElementById("btnPauseResume");
|
||||||
|
if (!btn) return;
|
||||||
|
btn.disabled = !running;
|
||||||
|
btn.dataset.paused = paused ? "1" : "0";
|
||||||
|
const label = paused ? "继续" : "暂停";
|
||||||
|
const icon = paused
|
||||||
|
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4v16l13-8z"/></svg>'
|
||||||
|
: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg>';
|
||||||
|
btn.innerHTML = `<span class="btnIcon" aria-hidden="true">${icon}</span>${label}`;
|
||||||
|
}
|
||||||
|
|
||||||
async function pollLogs() {
|
async function pollLogs() {
|
||||||
try {
|
try {
|
||||||
const data = await apiGet(`/api/logs?since=${logIdx}`);
|
const data = await apiGet(`/api/logs?since=${logIdx}`);
|
||||||
@@ -474,11 +509,12 @@ async function pollStats() {
|
|||||||
const s = await apiGet(`/api/stats?t=${Date.now()}`);
|
const s = await apiGet(`/api/stats?t=${Date.now()}`);
|
||||||
// 数据到位,去掉骨架
|
// 数据到位,去掉骨架
|
||||||
document.querySelectorAll(".stat .statValue.skeleton, .stat .statHint.skeleton").forEach((el) => el.classList.remove("skeleton"));
|
document.querySelectorAll(".stat .statValue.skeleton, .stat .statHint.skeleton").forEach((el) => el.classList.remove("skeleton"));
|
||||||
const running = s.running ? "运行中" : "未运行";
|
const running = s.paused ? UI_COPY.runOverview.paused : (s.running ? "运行中" : "未运行");
|
||||||
setTextIfExists("statRunning", running);
|
setTextIfExists("statRunning", running);
|
||||||
const runningEl = document.getElementById("statRunning");
|
const runningEl = document.getElementById("statRunning");
|
||||||
if (runningEl) {
|
if (runningEl) {
|
||||||
runningEl.classList.toggle("stateOk", !!s.running);
|
runningEl.classList.toggle("stateOk", !!s.running && !s.paused);
|
||||||
|
runningEl.classList.toggle("stateWarn", !!s.paused);
|
||||||
runningEl.classList.toggle("stateMuted", !s.running);
|
runningEl.classList.toggle("stateMuted", !s.running);
|
||||||
}
|
}
|
||||||
setTextIfExists("statPid", s.pid ?? "-");
|
setTextIfExists("statPid", s.pid ?? "-");
|
||||||
@@ -497,10 +533,12 @@ async function pollStats() {
|
|||||||
|
|
||||||
setRunOverview(
|
setRunOverview(
|
||||||
running,
|
running,
|
||||||
UI_COPY.runOverview.meta(s.pid, s.uptime_seconds),
|
s.paused ? UI_COPY.runOverview.pausedMeta : UI_COPY.runOverview.meta(s.pid, s.uptime_seconds),
|
||||||
s.running ? RUN_TONE.running : RUN_TONE.idle
|
s.paused ? RUN_TONE.idle : (s.running ? RUN_TONE.running : RUN_TONE.idle)
|
||||||
);
|
);
|
||||||
document.body.classList.toggle("is-running", !!s.running);
|
document.body.classList.toggle("is-running", !!s.running);
|
||||||
|
document.body.classList.toggle("is-paused", !!s.paused);
|
||||||
|
updatePauseResumeButton(!!s.running, !!s.paused);
|
||||||
// 页面标题随运行状态更新
|
// 页面标题随运行状态更新
|
||||||
try {
|
try {
|
||||||
const baseTitle = "抖音挂机控制台";
|
const baseTitle = "抖音挂机控制台";
|
||||||
|
|||||||
@@ -26,6 +26,12 @@
|
|||||||
</span>
|
</span>
|
||||||
开始运行
|
开始运行
|
||||||
</button>
|
</button>
|
||||||
|
<button id="btnPauseResume" class="btn btnSoft">
|
||||||
|
<span class="btnIcon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg>
|
||||||
|
</span>
|
||||||
|
暂停
|
||||||
|
</button>
|
||||||
<button id="btnStop" class="btn btnDangerSoft">
|
<button id="btnStop" class="btn btnDangerSoft">
|
||||||
<span class="btnIcon" aria-hidden="true">
|
<span class="btnIcon" aria-hidden="true">
|
||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>
|
||||||
|
|||||||
@@ -334,6 +334,12 @@ function initKeyboardShortcuts() {
|
|||||||
if (btn && !btn.disabled) btn.click();
|
if (btn && !btn.disabled) btn.click();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (key === "p") {
|
||||||
|
e.preventDefault();
|
||||||
|
const btn = document.getElementById("btnPauseResume");
|
||||||
|
if (btn && !btn.disabled) btn.click();
|
||||||
|
return;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,6 +412,7 @@ function initShortcutsHelp() {
|
|||||||
{ keys: [mod, "K"], desc: "聚焦配置搜索" },
|
{ keys: [mod, "K"], desc: "聚焦配置搜索" },
|
||||||
{ keys: [mod, "S"], desc: "保存配置" },
|
{ keys: [mod, "S"], desc: "保存配置" },
|
||||||
{ keys: [mod, "Enter"], desc: "开始运行" },
|
{ keys: [mod, "Enter"], desc: "开始运行" },
|
||||||
|
{ keys: [mod, "P"], desc: "暂停/继续" },
|
||||||
{ keys: ["Esc"], desc: "清空搜索 / 关闭弹层" },
|
{ keys: ["Esc"], desc: "清空搜索 / 关闭弹层" },
|
||||||
{ keys: ["?"], desc: "显示此帮助" },
|
{ keys: ["?"], desc: "显示此帮助" },
|
||||||
];
|
];
|
||||||
|
|||||||
Reference in new issue
Block a user