dsh-app-controls 0.0.0-stage → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,975 @@
1
+ #!/usr/bin/env python3
2
+ """DeepSeek Harness — KDE system tray controller.
3
+
4
+ A small PyQt5 tray icon that talks to the running dsh-app-controls host over
5
+ the loopback Unix socket (`~/.local/state/dsh-app-controls/control.sock`).
6
+
7
+ Features: status/tooltip, open/focus the Web GUI, open the plugin/plugins-settings
8
+ pages, check for updates, update with progress, restart/stop the service (the
9
+ open page closes itself), open logs, copy the URL and notifications. The tray
10
+ enable/disable and autostart state are managed by the plugin settings panel;
11
+ the icon waits for Plasma's tray at login and pins itself into the panel.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import fcntl
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import socket
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+ from urllib.parse import urlsplit
26
+
27
+ from PyQt5.QtCore import QLineF, QObject, QPointF, QRectF, QTimer, QUrl, Qt
28
+ from PyQt5.QtGui import QColor, QGuiApplication, QIcon, QPainter, QPalette, QPen, QPixmap
29
+ from PyQt5.QtNetwork import QLocalSocket
30
+ from PyQt5.QtWidgets import QAction, QApplication, QMenu, QMessageBox, QSystemTrayIcon
31
+
32
+ HOME = Path.home()
33
+ PLUGIN_DIR = Path(__file__).resolve().parent.parent
34
+ STATE_DIR = Path(os.environ.get("XDG_STATE_HOME", HOME / ".local/state")) / "dsh-app-controls"
35
+ SOCKET_PATH = STATE_DIR / "control.sock"
36
+ TRAY_LOG = STATE_DIR / "tray.log"
37
+ TRAY_PID_FILE = STATE_DIR / "tray.pid"
38
+ WEB_LOG = HOME / ".local/state/dsh-web/web.log"
39
+ LAUNCHER = os.environ.get("DSH_WEB_LAUNCHER", str(HOME / ".local/bin/dsh-web-launch"))
40
+ URL = os.environ.get("DSH_WEB_URL", "http://127.0.0.1:3080/")
41
+ AUTOSTART = HOME / ".config/autostart/dsh-tray.desktop"
42
+ LOCK_FILE = STATE_DIR / "tray.lock"
43
+ ICON_SVG = PLUGIN_DIR / "icon.svg"
44
+
45
+ STATUS_INTERVAL_MS = 2000
46
+ UPDATE_INTERVAL_MS = 30 * 60 * 1000
47
+ THEME_INTERVAL_MS = 3000
48
+ REQUEST_TIMEOUT_MS = 4000
49
+ CHECK_TIMEOUT_MS = 30000
50
+ START_TIMEOUT_SECONDS = 45
51
+ RESTART_POLL_MS = 250
52
+ RESTART_TIMEOUT_SECONDS = 30
53
+ DSH_PATCH = HOME / ".dsh/profiles/web/cordis.patch.yml"
54
+
55
+ _STATE_COLORS = {
56
+ "running": "#3fae63",
57
+ "stopped": "#8a8f98",
58
+ "starting": "#f0a020",
59
+ "updating": "#f0a020",
60
+ "stopping": "#8a8f98",
61
+ "error": "#e5484d",
62
+ }
63
+
64
+
65
+ def log(message: str) -> None:
66
+ try:
67
+ STATE_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
68
+ with open(TRAY_LOG, "a", encoding="utf-8") as handle:
69
+ handle.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {message}\n")
70
+ except Exception:
71
+ pass
72
+
73
+
74
+ def dsh_theme_preference() -> str:
75
+ """Read the DSH Web profile's theme preference without requiring PyYAML."""
76
+ try:
77
+ text = DSH_PATCH.read_text(encoding="utf-8")
78
+ except Exception:
79
+ return "system"
80
+
81
+ # The preference lives in the `ui-theme` loader entry in the profile patch.
82
+ # A YAML parser is preferred, but the patch may contain loader tags that a
83
+ # plain safe_load rejects, so fall back to a narrow block scan.
84
+ try:
85
+ import yaml # type: ignore
86
+
87
+ document = yaml.safe_load(text)
88
+ for item in document if isinstance(document, list) else []:
89
+ if not isinstance(item, dict):
90
+ continue
91
+ name = str(item.get("name") or "")
92
+ if item.get("id") != "ui-theme" and not name.endswith("dsh-client-ui-theme"):
93
+ continue
94
+ config = item.get("config")
95
+ preference = config.get("preference") if isinstance(config, dict) else None
96
+ if preference in ("light", "dark", "system"):
97
+ return str(preference)
98
+ except Exception:
99
+ pass
100
+
101
+ block = re.search(r"(?ms)^\s*-\s*id:\s*['\"]?ui-theme['\"]?\s*$.*?(?=^\s*-\s*id:|\Z)", text)
102
+ if block:
103
+ preference = re.search(r"(?m)^\s+preference:\s*['\"]?(light|dark|system)['\"]?\s*$", block.group(0))
104
+ if preference:
105
+ return preference.group(1)
106
+ return "system"
107
+
108
+
109
+ def probe_status(timeout: float = 2.0) -> dict:
110
+ """Synchronous status probe used by --check (no Qt event loop needed)."""
111
+ import socket as pysocket
112
+
113
+ try:
114
+ with pysocket.socket(pysocket.AF_UNIX, pysocket.SOCK_STREAM) as sock:
115
+ sock.settimeout(timeout)
116
+ sock.connect(str(SOCKET_PATH))
117
+ sock.sendall(json.dumps({"command": "status", "id": 1}).encode() + b"\n")
118
+ data = b""
119
+ while b"\n" not in data:
120
+ chunk = sock.recv(65536)
121
+ if not chunk:
122
+ break
123
+ data += chunk
124
+ line = data.split(b"\n", 1)[0]
125
+ return json.loads(line.decode("utf-8", "replace"))
126
+ except Exception as error:
127
+ return {"ok": False, "error": "unreachable", "message": str(error)}
128
+
129
+
130
+ class ControlRequest(QObject):
131
+ """One newline-delimited JSON request over the host's Unix socket."""
132
+
133
+ def __init__(self, parent, payload: dict, timeout_ms: int, callback):
134
+ super().__init__(parent)
135
+ self.payload = payload
136
+ self.callback = callback
137
+ self.done = False
138
+ self.buffer = bytearray()
139
+ self.socket = QLocalSocket(self)
140
+ self.socket.connected.connect(self._on_connected)
141
+ self.socket.readyRead.connect(self._on_ready)
142
+ self.socket.errorOccurred.connect(self._on_error)
143
+ self.timer = QTimer(self)
144
+ self.timer.setSingleShot(True)
145
+ self.timer.timeout.connect(lambda: self._finish({"ok": False, "error": "timeout"}))
146
+ self.timer.start(timeout_ms)
147
+ self.socket.connectToServer(str(SOCKET_PATH))
148
+
149
+ def _on_connected(self) -> None:
150
+ try:
151
+ self.socket.write(json.dumps(self.payload).encode("utf-8") + b"\n")
152
+ except Exception:
153
+ self._finish({"ok": False, "error": "write-failed"})
154
+
155
+ def _on_ready(self) -> None:
156
+ self.buffer.extend(bytes(self.socket.readAll()))
157
+ index = self.buffer.find(b"\n")
158
+ if index < 0:
159
+ return
160
+ line = bytes(self.buffer[:index]).decode("utf-8", "replace")
161
+ try:
162
+ response = json.loads(line)
163
+ except Exception:
164
+ response = {"ok": False, "error": "bad-response"}
165
+ self._finish(response)
166
+
167
+ def _on_error(self, _error) -> None:
168
+ self._finish({"ok": False, "error": "unreachable"})
169
+
170
+ def _finish(self, response: dict) -> None:
171
+ if self.done:
172
+ return
173
+ self.done = True
174
+ self.timer.stop()
175
+ try:
176
+ self.socket.abort()
177
+ except Exception:
178
+ pass
179
+ callback = self.callback
180
+ try:
181
+ callback(response)
182
+ finally:
183
+ self.deleteLater()
184
+
185
+
186
+ class Tray(QSystemTrayIcon):
187
+ def __init__(self, app: QApplication):
188
+ super().__init__()
189
+ self.app = app
190
+ self.status = None
191
+ self.job = None
192
+ self.update = None
193
+ self.checking = False
194
+ self.polling = False
195
+ self.starting = False
196
+ self.start_deadline = 0.0
197
+ self.restart_pending = False
198
+ self.restart_waiting = False
199
+ self.restart_deadline = 0.0
200
+ self.tray_update = False
201
+ self.suppress_stop_notice = False
202
+ self.last_job_finished = None
203
+ self.last_notified_update = None
204
+ self.requests = set()
205
+ self._request_id = 0
206
+ self.state = "stopped"
207
+ self.dark = False
208
+ self._theme_key = None
209
+ self._theme_pref = None
210
+ self.check_result = None
211
+ self.check_result_deadline = 0.0
212
+
213
+ self.dark = self._resolve_dark()
214
+ self.menu = QMenu()
215
+ self.menu.setToolTipsVisible(True)
216
+ self.menu.setMinimumWidth(272)
217
+ self._build_menu()
218
+ self._apply_theme(force=True)
219
+ self.setContextMenu(self.menu)
220
+ self.activated.connect(self._on_activated)
221
+ self._apply_state("stopped")
222
+ self.show()
223
+ QTimer.singleShot(1200, self._ensure_visible)
224
+ QTimer.singleShot(6000, self._ensure_visible)
225
+
226
+ self.poll_timer = QTimer(self)
227
+ self.poll_timer.timeout.connect(self.poll)
228
+ self.poll_timer.start(STATUS_INTERVAL_MS)
229
+ self.check_timer = QTimer(self)
230
+ self.check_timer.timeout.connect(lambda: self.request_check(mode="auto"))
231
+ self.check_timer.start(UPDATE_INTERVAL_MS)
232
+ self.theme_timer = QTimer(self)
233
+ self.theme_timer.timeout.connect(self._sync_theme)
234
+ self.theme_timer.start(THEME_INTERVAL_MS)
235
+ QTimer.singleShot(400, self.poll)
236
+ QTimer.singleShot(1800, lambda: self.request_check(mode="auto"))
237
+
238
+ # ── theme and menu ──────────────────────────────────────────────────────
239
+ def _resolve_dark(self) -> bool:
240
+ try:
241
+ preference = dsh_theme_preference()
242
+ except Exception:
243
+ preference = "system"
244
+ self._theme_pref = preference
245
+ if preference == "dark":
246
+ return True
247
+ if preference == "light":
248
+ return False
249
+ return self.app.palette().color(QPalette.Window).lightness() < 128
250
+
251
+ def _colors(self) -> dict[str, str]:
252
+ if self.dark:
253
+ return {
254
+ "bg": "#24262d",
255
+ "text": "#f2f3f5",
256
+ "muted": "#969ba6",
257
+ "border": "#3a3e47",
258
+ "hover": "#343842",
259
+ "accent": "#6d8cff",
260
+ "danger": "#ff8181",
261
+ }
262
+ return {
263
+ "bg": "#ffffff",
264
+ "text": "#20242c",
265
+ "muted": "#777d88",
266
+ "border": "#e1e4ea",
267
+ "hover": "#f0f3f8",
268
+ "accent": "#4d6bfe",
269
+ "danger": "#cf4d4d",
270
+ }
271
+
272
+ def _menu_style(self) -> str:
273
+ c = self._colors()
274
+ return f"""
275
+ QMenu {{
276
+ background-color: {c['bg']};
277
+ color: {c['text']};
278
+ border: 1px solid {c['border']};
279
+ border-radius: 10px;
280
+ padding: 6px;
281
+ }}
282
+ QMenu::item {{
283
+ padding: 8px 22px 8px 10px;
284
+ margin: 1px 2px;
285
+ border-radius: 6px;
286
+ color: {c['text']};
287
+ background: transparent;
288
+ }}
289
+ QMenu::item:selected {{
290
+ background-color: {c['hover']};
291
+ color: {c['text']};
292
+ }}
293
+ QMenu::item:disabled {{
294
+ color: {c['muted']};
295
+ background: transparent;
296
+ }}
297
+ QMenu::separator {{
298
+ height: 1px;
299
+ background: {c['border']};
300
+ margin: 5px 8px;
301
+ }}
302
+ """
303
+
304
+ def _apply_theme(self, force: bool = False) -> None:
305
+ try:
306
+ preference = dsh_theme_preference()
307
+ base = self.app.palette().color(QPalette.Window)
308
+ dark = True if preference == "dark" else False if preference == "light" else base.lightness() < 128
309
+ key = (preference, dark, base.name())
310
+ if not force and key == self._theme_key:
311
+ return
312
+ self._theme_pref = preference
313
+ self.dark = dark
314
+ self._theme_key = key
315
+ self.menu.setStyleSheet(self._menu_style())
316
+ self._apply_action_icons()
317
+ self._refresh_menu()
318
+ log(f"tray theme: {preference} ({'dark' if dark else 'light'})")
319
+ except Exception as error:
320
+ log(f"could not apply tray theme: {error}")
321
+
322
+ def _sync_theme(self) -> None:
323
+ self._apply_theme()
324
+
325
+ def _menu_icon(self, kind: str, color: str | None = None) -> QIcon:
326
+ c = QColor(color or self._colors()["text"])
327
+ size = 18
328
+ pixmap = QPixmap(size, size)
329
+ pixmap.fill(Qt.transparent)
330
+ painter = QPainter(pixmap)
331
+ painter.setRenderHint(QPainter.Antialiasing)
332
+ pen = QPen(c, 1.7, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
333
+ painter.setPen(pen)
334
+ painter.setBrush(Qt.NoBrush)
335
+
336
+ if kind == "open":
337
+ painter.drawRoundedRect(QRectF(2.5, 3.5, 13, 11), 2, 2)
338
+ painter.drawLine(QLineF(2.5, 7, 15.5, 7))
339
+ painter.setBrush(c)
340
+ painter.drawEllipse(QPointF(4.8, 5.2), 0.7, 0.7)
341
+ elif kind == "plugins":
342
+ for x, y in ((3, 3), (10, 3), (3, 10), (10, 10)):
343
+ painter.drawRoundedRect(QRectF(x, y, 5, 5), 1.5, 1.5)
344
+ elif kind == "settings":
345
+ for y, knob in ((5, 6), (9, 12), (13, 8)):
346
+ painter.drawLine(3, y, 15, y)
347
+ painter.setBrush(c)
348
+ painter.drawEllipse(QPointF(knob, y), 1.6, 1.6)
349
+ elif kind in ("update", "restart"):
350
+ painter.drawArc(3, 3, 12, 12, 45 * 16, 270 * 16)
351
+ painter.drawLine(13, 3, 15, 6)
352
+ painter.drawLine(15, 6, 11, 6)
353
+ if kind == "restart":
354
+ painter.setBrush(c)
355
+ painter.drawEllipse(8, 8, 2, 2)
356
+ elif kind == "stop":
357
+ painter.setBrush(c)
358
+ painter.drawRoundedRect(QRectF(4, 4, 10, 10), 2, 2)
359
+ elif kind == "logs":
360
+ painter.drawRoundedRect(QRectF(3, 2.5, 12, 13), 2, 2)
361
+ for y in (6, 9, 12):
362
+ painter.drawLine(6, y, 12, y)
363
+ elif kind == "copy":
364
+ painter.drawRoundedRect(QRectF(5, 3, 9, 11), 1.5, 1.5)
365
+ painter.drawRoundedRect(QRectF(3, 6, 9, 11), 1.5, 1.5)
366
+ elif kind == "quit":
367
+ painter.drawArc(3, 3, 12, 12, 45 * 16, 270 * 16)
368
+ painter.drawLine(9, 2, 9, 9)
369
+ painter.end()
370
+ icon = QIcon()
371
+ icon.addPixmap(pixmap, QIcon.Normal)
372
+ icon.addPixmap(pixmap, QIcon.Active)
373
+ icon.addPixmap(pixmap, QIcon.Disabled)
374
+ return icon
375
+
376
+ def _apply_action_icons(self) -> None:
377
+ c = self._colors()
378
+ self.open_action.setIcon(self._menu_icon("open", c["accent"]))
379
+ self.plugins_action.setIcon(self._menu_icon("plugins", c["text"]))
380
+ self.settings_action.setIcon(self._menu_icon("settings", c["text"]))
381
+ self.update_action.setIcon(self._menu_icon("update", c["accent"]))
382
+ self.restart_action.setIcon(self._menu_icon("restart", c["text"]))
383
+ self.stop_action.setIcon(self._menu_icon("stop", c["danger"]))
384
+ self.logs_action.setIcon(self._menu_icon("logs", c["text"]))
385
+ self.copy_action.setIcon(self._menu_icon("copy", c["text"]))
386
+ self.quit_action.setIcon(self._menu_icon("quit", c["danger"]))
387
+ self.status_action.setIcon(self._status_icon())
388
+
389
+ def _status_icon(self) -> QIcon:
390
+ color = QColor(_STATE_COLORS.get(self.state, _STATE_COLORS["running"]))
391
+ size = 18
392
+ pixmap = QPixmap(size, size)
393
+ pixmap.fill(Qt.transparent)
394
+ painter = QPainter(pixmap)
395
+ painter.setRenderHint(QPainter.Antialiasing)
396
+ painter.setPen(QPen(color, 1.2))
397
+ painter.setBrush(QColor(color.red(), color.green(), color.blue(), 55))
398
+ painter.drawEllipse(QRectF(3, 3, 12, 12))
399
+ painter.setPen(Qt.NoPen)
400
+ painter.setBrush(color)
401
+ painter.drawEllipse(QPointF(9, 9), 2.5, 2.5)
402
+ painter.end()
403
+ icon = QIcon()
404
+ icon.addPixmap(pixmap, QIcon.Normal)
405
+ icon.addPixmap(pixmap, QIcon.Active)
406
+ icon.addPixmap(pixmap, QIcon.Disabled)
407
+ return icon
408
+
409
+ def _build_menu(self) -> None:
410
+ self.open_action = QAction("打开 DeepSeek Harness", self)
411
+ self.open_action.triggered.connect(self.open_dsh)
412
+ self.menu.addAction(self.open_action)
413
+
414
+ self.plugins_action = QAction("打开插件管理", self)
415
+ self.plugins_action.triggered.connect(self.open_plugins)
416
+ self.menu.addAction(self.plugins_action)
417
+
418
+ self.settings_action = QAction("插件设置", self)
419
+ self.settings_action.triggered.connect(self.open_settings)
420
+ self.menu.addAction(self.settings_action)
421
+
422
+ self.status_action = QAction("状态:正在连接…", self)
423
+ self.status_action.setEnabled(False)
424
+ self.menu.addAction(self.status_action)
425
+ self.menu.addSeparator()
426
+
427
+ self.update_action = QAction("检查更新", self)
428
+ self.update_action.triggered.connect(self.on_update_action)
429
+ self.menu.addAction(self.update_action)
430
+
431
+ self.restart_action = QAction("重启服务", self)
432
+ self.restart_action.triggered.connect(self.restart_dsh)
433
+ self.menu.addAction(self.restart_action)
434
+
435
+ self.stop_action = QAction("停止服务", self)
436
+ self.stop_action.triggered.connect(self.stop_dsh)
437
+ self.menu.addAction(self.stop_action)
438
+
439
+ self.logs_action = QAction("打开日志", self)
440
+ self.logs_action.triggered.connect(self.open_logs)
441
+ self.menu.addAction(self.logs_action)
442
+
443
+ self.copy_action = QAction("复制访问地址", self)
444
+ self.copy_action.triggered.connect(self.copy_url)
445
+ self.menu.addAction(self.copy_action)
446
+ self.menu.addSeparator()
447
+
448
+ self.quit_action = QAction("退出托盘", self)
449
+ self.quit_action.triggered.connect(self.app.quit)
450
+ self.menu.addAction(self.quit_action)
451
+ self._refresh_menu()
452
+
453
+ # ── socket ──────────────────────────────────────────────────────────────
454
+ def _request(self, payload: dict, callback, timeout_ms: int = REQUEST_TIMEOUT_MS) -> None:
455
+ self._request_id += 1
456
+ payload = dict(payload)
457
+ payload.setdefault("id", self._request_id)
458
+ holder = {}
459
+
460
+ def done(response: dict) -> None:
461
+ self.requests.discard(holder.get("request"))
462
+ callback(response)
463
+
464
+ request = ControlRequest(self, payload, timeout_ms, done)
465
+ holder["request"] = request
466
+ self.requests.add(request)
467
+
468
+ def poll(self) -> None:
469
+ if self.polling:
470
+ return
471
+ self.polling = True
472
+ self._request({"command": "status"}, self._on_status, timeout_ms=3000)
473
+
474
+ def request_check(self, mode: str = "auto") -> None:
475
+ """Check in the background; only an available update raises a notification."""
476
+ if self.checking:
477
+ return
478
+ self.checking = True
479
+ self.check_result = None
480
+ self.check_result_deadline = 0.0
481
+ self._refresh_menu()
482
+
483
+ def done(response: dict) -> None:
484
+ self.checking = False
485
+ if response.get("ok") and response.get("update"):
486
+ self.update = response["update"]
487
+ if self.update.get("updateAvailable"):
488
+ candidate = self.update.get("candidate")
489
+ if candidate != self.last_notified_update:
490
+ self.last_notified_update = candidate
491
+ self._notify(
492
+ "有可用更新",
493
+ f"DeepSeek Harness {candidate}(当前 {self.update.get('current')})",
494
+ )
495
+ elif mode == "manual":
496
+ self._set_check_result("已是最新版本")
497
+ elif mode == "manual":
498
+ self._set_check_result("检查失败")
499
+ self._refresh_menu()
500
+
501
+ self._request({"command": "check-update"}, done, timeout_ms=CHECK_TIMEOUT_MS)
502
+
503
+ def _set_check_result(self, text: str) -> None:
504
+ self.check_result = text
505
+ self.check_result_deadline = time.time() + 5.0
506
+ QTimer.singleShot(5200, self._clear_check_result)
507
+
508
+ def _clear_check_result(self) -> None:
509
+ if self.check_result is None:
510
+ return
511
+ if time.time() < self.check_result_deadline:
512
+ return
513
+ self.check_result = None
514
+ self._refresh_menu()
515
+
516
+ # ── status handling ─────────────────────────────────────────────────────
517
+ def _on_status(self, response: dict) -> None:
518
+ self.polling = False
519
+ if not response.get("ok"):
520
+ self._handle_unreachable()
521
+ return
522
+ had_status = self.status is not None
523
+ self.status = response
524
+ self.starting = False
525
+ self.start_deadline = 0.0
526
+ self.job = response.get("job") if isinstance(response.get("job"), dict) else None
527
+ if isinstance(response.get("update"), dict):
528
+ self.update = response["update"]
529
+ if not had_status:
530
+ log("connected to DeepSeek Harness control socket")
531
+
532
+ if self.job and self.job.get("active"):
533
+ self._apply_state("updating")
534
+ elif response.get("quitRequested"):
535
+ self._apply_state("stopping")
536
+ else:
537
+ self._apply_state("running")
538
+
539
+ if self.job and self.job.get("done") and self.job.get("finishedAt") != self.last_job_finished:
540
+ self.last_job_finished = self.job.get("finishedAt")
541
+ if self.job.get("error"):
542
+ self._notify("更新失败", self.job.get("message") or "更新失败")
543
+ elif self.job.get("source") == "tray":
544
+ self._notify("更新完成", f"已更新到 {self.job.get('to')},服务即将退出")
545
+ self.suppress_stop_notice = True
546
+ self.tray_update = False
547
+
548
+ if (
549
+ isinstance(self.update, dict)
550
+ and self.update.get("updateAvailable")
551
+ and self.update.get("candidate") != self.last_notified_update
552
+ ):
553
+ self.last_notified_update = self.update.get("candidate")
554
+ self._notify(
555
+ "有可用更新",
556
+ f"DeepSeek Harness {self.update.get('candidate')}(当前 {self.update.get('current')})",
557
+ )
558
+ self._refresh_menu()
559
+
560
+ def _handle_unreachable(self) -> None:
561
+ was_running = self.status is not None
562
+ self.status = None
563
+ self.job = None
564
+ if self.starting:
565
+ if time.time() > self.start_deadline:
566
+ self.starting = False
567
+ self._notify("启动失败", "DeepSeek Harness 未在预期时间内启动,请查看日志。")
568
+ else:
569
+ self._apply_state("starting")
570
+ return
571
+ if was_running and not self.suppress_stop_notice and not self.tray_update:
572
+ self._notify("DeepSeek Harness 已停止", "本地服务已退出。")
573
+ self.suppress_stop_notice = False
574
+ self._apply_state("stopped")
575
+ if self.restart_pending:
576
+ self._begin_restart_wait()
577
+ self._refresh_menu()
578
+
579
+ # ── actions ─────────────────────────────────────────────────────────────
580
+ def open_dsh(self) -> None:
581
+ if self.status is not None:
582
+ self._run_launcher()
583
+ else:
584
+ self.launch()
585
+
586
+ def open_plugins(self) -> None:
587
+ if self.status is None:
588
+ self._notify("服务未运行", "请先点击托盘图标启动 DeepSeek Harness。")
589
+ return
590
+ self._run_launcher("dsh-app-controls/plugins")
591
+
592
+ def open_settings(self) -> None:
593
+ if self.status is None:
594
+ self._notify("服务未运行", "请先点击托盘图标启动 DeepSeek Harness。")
595
+ return
596
+ self._run_launcher("dsh-app-controls/settings")
597
+
598
+ def launch(self) -> None:
599
+ if self.starting:
600
+ return
601
+ self.starting = True
602
+ self.start_deadline = time.time() + START_TIMEOUT_SECONDS
603
+ self.suppress_stop_notice = False
604
+ self._apply_state("starting")
605
+ try:
606
+ subprocess.Popen(
607
+ [LAUNCHER],
608
+ cwd=str(HOME),
609
+ start_new_session=True,
610
+ stdout=subprocess.DEVNULL,
611
+ stderr=subprocess.DEVNULL,
612
+ )
613
+ except Exception as error:
614
+ self.starting = False
615
+ self._notify("启动失败", f"无法运行启动器:{error}")
616
+ self._apply_state("stopped")
617
+ return
618
+ self._refresh_menu()
619
+ QTimer.singleShot(START_TIMEOUT_SECONDS * 1000, self._start_timeout)
620
+
621
+ def _start_timeout(self) -> None:
622
+ if self.starting and self.status is None:
623
+ self.starting = False
624
+ self._notify("启动失败", "DeepSeek Harness 未启动成功,请查看日志。")
625
+ self._apply_state("stopped")
626
+ self._refresh_menu()
627
+
628
+ def _run_launcher(self, hash_value: str | None = None) -> None:
629
+ env = dict(os.environ)
630
+ if hash_value:
631
+ env["DSH_WEB_HASH"] = hash_value
632
+ else:
633
+ env.pop("DSH_WEB_HASH", None)
634
+ try:
635
+ subprocess.Popen(
636
+ [LAUNCHER],
637
+ cwd=str(HOME),
638
+ env=env,
639
+ start_new_session=True,
640
+ stdout=subprocess.DEVNULL,
641
+ stderr=subprocess.DEVNULL,
642
+ )
643
+ except Exception as error:
644
+ self._notify("无法打开窗口", str(error))
645
+
646
+ def _service_port_open(self) -> bool:
647
+ """Whether the Web service's TCP port is still accepting connections."""
648
+ parts = urlsplit(URL)
649
+ host = parts.hostname or "127.0.0.1"
650
+ port = parts.port or (443 if parts.scheme == "https" else 80)
651
+ try:
652
+ with socket.create_connection((host, port), timeout=0.2):
653
+ return True
654
+ except OSError:
655
+ return False
656
+
657
+ def _begin_restart_wait(self) -> None:
658
+ if self.restart_waiting or not self.restart_pending:
659
+ return
660
+ self.restart_waiting = True
661
+ self.restart_deadline = time.time() + RESTART_TIMEOUT_SECONDS
662
+ log("restart: waiting for the old service to release the port")
663
+ QTimer.singleShot(RESTART_POLL_MS, self._restart_tick)
664
+
665
+ def _restart_tick(self) -> None:
666
+ if not self.restart_waiting:
667
+ return
668
+ if not self.restart_pending:
669
+ self.restart_waiting = False
670
+ return
671
+ if not self._service_port_open():
672
+ self.restart_waiting = False
673
+ self.restart_pending = False
674
+ log("restart: old service stopped; launching a new one")
675
+ self.launch()
676
+ return
677
+ if time.time() >= self.restart_deadline:
678
+ self.restart_waiting = False
679
+ self.restart_pending = False
680
+ log("restart: timed out waiting for the old service to stop")
681
+ self._notify("重启失败", "旧服务没有及时退出,请查看日志后重试。")
682
+ self._apply_state("stopped")
683
+ return
684
+ QTimer.singleShot(RESTART_POLL_MS, self._restart_tick)
685
+
686
+ def stop_dsh(self) -> None:
687
+ if self.status is None:
688
+ return
689
+ answer = QMessageBox.question(
690
+ None,
691
+ "停止 DeepSeek Harness",
692
+ "停止本地 DeepSeek Harness 服务并关闭窗口?",
693
+ QMessageBox.Yes | QMessageBox.No,
694
+ QMessageBox.No,
695
+ )
696
+ if answer != QMessageBox.Yes:
697
+ return
698
+ self.suppress_stop_notice = True
699
+ self.restart_pending = False
700
+ self.restart_waiting = False
701
+ self._apply_state("stopping")
702
+ self._request({"command": "quit"}, self._on_quit_response)
703
+
704
+ def restart_dsh(self) -> None:
705
+ if self.status is None:
706
+ if not self.restart_waiting:
707
+ self.launch()
708
+ return
709
+ if self.restart_waiting:
710
+ return
711
+ self.suppress_stop_notice = True
712
+ self.restart_pending = True
713
+ self._apply_state("stopping")
714
+ self._request({"command": "quit"}, self._on_quit_response)
715
+
716
+ def _on_quit_response(self, response: dict) -> None:
717
+ if response.get("ok"):
718
+ return
719
+ message = response.get("message") or response.get("error") or "未知错误"
720
+ self.restart_waiting = False
721
+ if self.restart_pending:
722
+ self.restart_pending = False
723
+ self._notify("重启失败", message)
724
+ else:
725
+ self._notify("停止失败", message)
726
+
727
+ def on_update_action(self) -> None:
728
+ if self.job and self.job.get("active"):
729
+ return
730
+ if isinstance(self.update, dict) and self.update.get("updateAvailable"):
731
+ candidate = self.update.get("candidate")
732
+ answer = QMessageBox.question(
733
+ None,
734
+ "更新 DeepSeek Harness",
735
+ f"更新到 {candidate}(当前 {self.update.get('current')})?\n更新完成后服务会退出,需要重新启动。",
736
+ QMessageBox.Yes | QMessageBox.No,
737
+ QMessageBox.No,
738
+ )
739
+ if answer != QMessageBox.Yes:
740
+ return
741
+ self.tray_update = True
742
+ self._request({"command": "update"}, self._on_update_start, timeout_ms=CHECK_TIMEOUT_MS)
743
+ else:
744
+ self.request_check(mode="manual")
745
+
746
+ def _on_update_start(self, response: dict) -> None:
747
+ if not response.get("ok"):
748
+ self.tray_update = False
749
+ self._notify("无法开始更新", response.get("message") or response.get("error") or "未知错误")
750
+ return
751
+ self._notify("开始更新", f"DeepSeek Harness {response.get('from')} → {response.get('to')}")
752
+
753
+ def open_logs(self) -> None:
754
+ target = WEB_LOG if WEB_LOG.exists() else TRAY_LOG
755
+ if not target.exists():
756
+ target = STATE_DIR
757
+ from PyQt5.QtGui import QDesktopServices
758
+
759
+ QDesktopServices.openUrl(QUrl.fromLocalFile(str(target)))
760
+
761
+ def copy_url(self) -> None:
762
+ QGuiApplication.clipboard().setText(URL)
763
+ self._notify("已复制访问地址", URL)
764
+
765
+ def _pin_in_panel(self) -> None:
766
+ """KDE may put a new SNI/XEmbed icon in the expanded tray; pin it."""
767
+ desktop = os.environ.get("XDG_CURRENT_DESKTOP", "")
768
+ if "KDE" not in desktop.upper() and "PLASMA" not in desktop.upper():
769
+ return
770
+ qdbus = shutil.which("qdbus6") or shutil.which("qdbus")
771
+ if not qdbus:
772
+ return
773
+ script = r'''
774
+ var ps = panels();
775
+ for (var pi = 0; pi < ps.length; pi++) {
776
+ var ws = ps[pi].widgets();
777
+ for (var i = 0; i < ws.length; i++) {
778
+ var w = ws[i];
779
+ if (w.type === "org.kde.plasma.systemtray") {
780
+ w.currentConfigGroup = ["General"];
781
+ function add(key, item) {
782
+ var raw = String(w.readConfig(key) || "");
783
+ var arr = raw.length ? raw.split(",") : [];
784
+ if (arr.indexOf(item) === -1) arr.push(item);
785
+ w.writeConfig(key, arr.filter(function(x){ return x.length > 0; }).join(","));
786
+ }
787
+ add("shownItems", "dsh-tray");
788
+ add("knownItems", "dsh-tray");
789
+ add("extraItems", "dsh-tray");
790
+ var hidden = String(w.readConfig("hiddenItems") || "").split(",").filter(function(x){ return x.length > 0 && x !== "dsh-tray"; });
791
+ w.writeConfig("hiddenItems", hidden.join(","));
792
+ w.reloadConfig();
793
+ }
794
+ }
795
+ }
796
+ '''
797
+ try:
798
+ subprocess.run(
799
+ [qdbus, "org.kde.plasmashell", "/PlasmaShell", "org.kde.PlasmaShell.evaluateScript", script],
800
+ timeout=8,
801
+ stdout=subprocess.DEVNULL,
802
+ stderr=subprocess.DEVNULL,
803
+ )
804
+ log("pinned tray icon in KDE panel")
805
+ except Exception as error:
806
+ log(f"could not pin tray icon: {error}")
807
+
808
+ def _ensure_visible(self) -> None:
809
+ try:
810
+ if QSystemTrayIcon.isSystemTrayAvailable():
811
+ if not self.isVisible():
812
+ self.show()
813
+ self._pin_in_panel()
814
+ except Exception as error:
815
+ log(f"could not ensure tray visibility: {error}")
816
+
817
+ def _on_activated(self, reason) -> None:
818
+ if reason in (QSystemTrayIcon.Trigger, QSystemTrayIcon.MiddleClick):
819
+ self.open_dsh()
820
+
821
+ # ── presentation ────────────────────────────────────────────────────────
822
+ def _apply_state(self, state: str) -> None:
823
+ self.state = state
824
+ self.setIcon(self._make_icon(state))
825
+ self.setToolTip(self._tooltip(state))
826
+ self._refresh_menu()
827
+
828
+ def _make_icon(self, state: str) -> QIcon:
829
+ pixmap = QPixmap(64, 64)
830
+ pixmap.fill(Qt.transparent)
831
+ painter = QPainter(pixmap)
832
+ painter.setRenderHint(QPainter.Antialiasing)
833
+ painter.setPen(Qt.NoPen)
834
+ base = QColor("#4D6BFE")
835
+ if state == "stopped":
836
+ base = QColor("#5b6068")
837
+ painter.setBrush(base)
838
+ painter.drawRoundedRect(4, 4, 56, 56, 16, 16)
839
+ painter.setPen(QPen(QColor("#ffffff"), 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
840
+ painter.drawLine(32, 16, 32, 33)
841
+ painter.drawArc(16, 18, 32, 32, 40 * 16, 280 * 16)
842
+ dot = QColor(_STATE_COLORS.get(state, _STATE_COLORS["running"]))
843
+ painter.setPen(QPen(QColor("#ffffff"), 2))
844
+ painter.setBrush(dot)
845
+ painter.drawEllipse(43, 43, 16, 16)
846
+ painter.end()
847
+ return QIcon(pixmap)
848
+
849
+ def _tooltip(self, state: str) -> str:
850
+ lines = ["DeepSeek Harness"]
851
+ if self.status is not None:
852
+ version = self.status.get("version") or "?"
853
+ port = self.status.get("port")
854
+ where = f"127.0.0.1:{port}" if port else URL
855
+ uptime = self._format_uptime(self.status.get("uptimeMs") or 0)
856
+ lines.append(f"运行中 · {version} · {where} · 已运行 {uptime}")
857
+ else:
858
+ lines.append("已停止")
859
+ if self.job and self.job.get("active"):
860
+ lines.append(f"更新中 · {self.job.get('percent', 0)}%")
861
+ elif isinstance(self.update, dict) and self.update.get("updateAvailable"):
862
+ lines.append(f"可更新到 {self.update.get('candidate')}")
863
+ lines.append("左键打开 · 右键菜单")
864
+ return "\n".join(lines)
865
+
866
+ @staticmethod
867
+ def _format_uptime(ms: int) -> str:
868
+ total = max(0, round(ms / 1000))
869
+ hours, remainder = divmod(total, 3600)
870
+ minutes, seconds = divmod(remainder, 60)
871
+ if hours:
872
+ return f"{hours}h {minutes:02d}m"
873
+ if minutes:
874
+ return f"{minutes}m {seconds:02d}s"
875
+ return f"{seconds}s"
876
+
877
+ def _refresh_menu(self) -> None:
878
+ running = self.status is not None
879
+ if running:
880
+ version = self.status.get("version") or "?"
881
+ port = self.status.get("port")
882
+ text = f"运行中 · {version}" + (f" · :{port}" if port else "")
883
+ else:
884
+ text = "已停止"
885
+ if self.job and self.job.get("active"):
886
+ text = f"更新中 · {self.job.get('percent', 0)}%"
887
+ elif self.status is not None and self.status.get("quitRequested"):
888
+ text = "正在退出…"
889
+ self.status_action.setText(f"状态:{text}")
890
+
891
+ if self.checking:
892
+ self.update_action.setText("正在检查更新…")
893
+ self.update_action.setEnabled(False)
894
+ elif self.job and self.job.get("active"):
895
+ self.update_action.setText(f"正在更新 {self.job.get('percent', 0)}%")
896
+ self.update_action.setEnabled(False)
897
+ elif isinstance(self.update, dict) and self.update.get("updateAvailable"):
898
+ self.update_action.setText(f"更新到 {self.update.get('candidate')}")
899
+ self.update_action.setEnabled(True)
900
+ elif self.check_result:
901
+ self.update_action.setText(self.check_result)
902
+ self.update_action.setEnabled(False)
903
+ else:
904
+ self.update_action.setText("检查更新")
905
+ self.update_action.setEnabled(True)
906
+
907
+ self.status_action.setIcon(self._status_icon())
908
+ self.restart_action.setText("重启服务" if running else "启动服务")
909
+ self.plugins_action.setEnabled(running)
910
+ self.settings_action.setEnabled(running)
911
+ self.stop_action.setEnabled(running)
912
+ self.copy_action.setEnabled(running)
913
+ self.logs_action.setEnabled(True)
914
+
915
+ def _notify(self, title: str, message: str) -> None:
916
+ log(f"{title}: {message}")
917
+ if QSystemTrayIcon.supportsMessages():
918
+ self.showMessage(title, message, QSystemTrayIcon.Information, 6000)
919
+
920
+
921
+ def run_check() -> int:
922
+ app = QApplication.instance() or QApplication(sys.argv)
923
+ print(f"python: {sys.version.split()[0]}")
924
+ print(f"qt platform: {app.platformName()}")
925
+ print(f"tray available: {QSystemTrayIcon.isSystemTrayAvailable()}")
926
+ print(f"socket: {SOCKET_PATH}")
927
+ print(f"autostart: {AUTOSTART} exists={AUTOSTART.exists()}")
928
+ print(f"status: {json.dumps(probe_status(), ensure_ascii=False)}")
929
+ return 0
930
+
931
+
932
+ def main() -> int:
933
+ if "--check" in sys.argv:
934
+ return run_check()
935
+ STATE_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
936
+ lock = open(LOCK_FILE, "w", encoding="utf-8")
937
+ try:
938
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
939
+ except BlockingIOError:
940
+ print("dsh-tray is already running", file=sys.stderr)
941
+ return 0
942
+ try:
943
+ TRAY_PID_FILE.write_text(str(os.getpid()), encoding="utf-8")
944
+ except Exception:
945
+ pass
946
+ app = QApplication(sys.argv)
947
+ app.setApplicationName("dsh-tray")
948
+ app.setQuitOnLastWindowClosed(False)
949
+ holder = {}
950
+
951
+ def wait_for_tray(attempt: int = 0) -> None:
952
+ if QSystemTrayIcon.isSystemTrayAvailable():
953
+ holder["tray"] = Tray(app)
954
+ return
955
+ if attempt < 30:
956
+ if attempt == 0:
957
+ log("system tray not ready; waiting")
958
+ QTimer.singleShot(2000, lambda: wait_for_tray(attempt + 1))
959
+ return
960
+ log("system tray is not available")
961
+ print("system tray is not available", file=sys.stderr)
962
+ app.quit()
963
+
964
+ QTimer.singleShot(0, wait_for_tray)
965
+ try:
966
+ return app.exec_()
967
+ finally:
968
+ try:
969
+ TRAY_PID_FILE.unlink()
970
+ except Exception:
971
+ pass
972
+
973
+
974
+ if __name__ == "__main__":
975
+ raise SystemExit(main())