github-ai-mcp 1.0.2__py3-none-any.whl
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.
- github_ai_mcp/__init__.py +1 -0
- github_ai_mcp/__main__.py +3 -0
- github_ai_mcp/cli/__init__.py +1 -0
- github_ai_mcp/cli/app.py +128 -0
- github_ai_mcp/config.py +112 -0
- github_ai_mcp/core/__init__.py +1 -0
- github_ai_mcp/core/git_engine.py +76 -0
- github_ai_mcp/core/github_api.py +86 -0
- github_ai_mcp/core/job_engine.py +889 -0
- github_ai_mcp/core/locking.py +41 -0
- github_ai_mcp/desktop/__init__.py +1 -0
- github_ai_mcp/desktop/control.py +26 -0
- github_ai_mcp/desktop/entry.py +77 -0
- github_ai_mcp/desktop/legal.py +9 -0
- github_ai_mcp/desktop/prerequisites.py +31 -0
- github_ai_mcp/desktop/processes.py +116 -0
- github_ai_mcp/desktop/runtime.py +34 -0
- github_ai_mcp/desktop/setup.py +408 -0
- github_ai_mcp/desktop/startup.py +64 -0
- github_ai_mcp/desktop/streams.py +50 -0
- github_ai_mcp/desktop/supervisor.py +358 -0
- github_ai_mcp/desktop/tunnel.py +242 -0
- github_ai_mcp/exceptions.py +6 -0
- github_ai_mcp/gui/__init__.py +1 -0
- github_ai_mcp/gui/app.py +969 -0
- github_ai_mcp/gui/workers.py +26 -0
- github_ai_mcp/security/__init__.py +1 -0
- github_ai_mcp/security/auth_github.py +67 -0
- github_ai_mcp/security/auth_mcp.py +38 -0
- github_ai_mcp/security/paths.py +34 -0
- github_ai_mcp/security/policy.py +40 -0
- github_ai_mcp/security/secret_scan.py +24 -0
- github_ai_mcp/server.py +97 -0
- github_ai_mcp/storage/__init__.py +1 -0
- github_ai_mcp/storage/database.py +88 -0
- github_ai_mcp/tool_definitions.py +185 -0
- github_ai_mcp-1.0.2.dist-info/METADATA +33 -0
- github_ai_mcp-1.0.2.dist-info/RECORD +42 -0
- github_ai_mcp-1.0.2.dist-info/WHEEL +5 -0
- github_ai_mcp-1.0.2.dist-info/entry_points.txt +2 -0
- github_ai_mcp-1.0.2.dist-info/licenses/LICENSE +21 -0
- github_ai_mcp-1.0.2.dist-info/top_level.txt +1 -0
github_ai_mcp/gui/app.py
ADDED
|
@@ -0,0 +1,969 @@
|
|
|
1
|
+
"""Russian/English local administration GUI; shares the CLI/MCP application service."""
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
from typing import cast
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from PySide6.QtCore import QThreadPool, QTimer, Qt
|
|
8
|
+
from PySide6.QtGui import QAction, QPen, QIcon
|
|
9
|
+
from PySide6.QtWidgets import (QGridLayout, QMenu, QSystemTrayIcon, QStyle, QStyledItemDelegate, QStyleOptionViewItem, QApplication, QComboBox, QDialog, QDialogButtonBox,
|
|
10
|
+
QHBoxLayout, QInputDialog, QLabel, QLineEdit, QListWidget,
|
|
11
|
+
QMainWindow, QMessageBox, QPlainTextEdit, QPushButton,
|
|
12
|
+
QSplitter, QVBoxLayout, QWidget, QCheckBox, QFormLayout, QSpinBox)
|
|
13
|
+
|
|
14
|
+
from github_ai_mcp.config import Config, save_config
|
|
15
|
+
from github_ai_mcp.exceptions import AppError
|
|
16
|
+
from github_ai_mcp.gui.workers import Task
|
|
17
|
+
from github_ai_mcp.desktop.supervisor import Supervisor
|
|
18
|
+
|
|
19
|
+
TEXT = {
|
|
20
|
+
"ru": ["Панель управления", "Репозитории", "Задания", "Просмотр изменений", "GitHub",
|
|
21
|
+
"Службы", "Настройки", "Журнал / поддержка", "Обновить", "Создать задание",
|
|
22
|
+
"Изменить файл", "Удалить файл", "Одобрить снимок", "Создать коммиты", "Отправить ветку в GitHub",
|
|
23
|
+
"Создать pull request", "Восстановить прерванное задание", "Отменить задание", "Вход GitHub", "Выйти GitHub",
|
|
24
|
+
"Запустить MCP", "Остановить MCP", "Сохранить настройки", "Переключить тему"],
|
|
25
|
+
"en": ["Dashboard", "Repositories", "Jobs", "Change review", "GitHub", "Services",
|
|
26
|
+
"Settings", "Logs / support", "Refresh", "Create job", "Edit file", "Delete file",
|
|
27
|
+
"Approve snapshot", "Create commits", "Push branch to GitHub", "Create pull request", "Recover interrupted job", "Cancel job",
|
|
28
|
+
"GitHub login", "GitHub logout", "Start MCP", "Stop MCP", "Save settings", "Toggle theme"],
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class NavigationDelegate(QStyledItemDelegate):
|
|
33
|
+
def paint(self, painter, option, index):
|
|
34
|
+
focus = bool(option.state & QStyle.StateFlag.State_HasFocus)
|
|
35
|
+
styled = QStyleOptionViewItem(option)
|
|
36
|
+
styled.state &= ~QStyle.StateFlag.State_HasFocus
|
|
37
|
+
super().paint(painter, styled, index)
|
|
38
|
+
if focus:
|
|
39
|
+
painter.save()
|
|
40
|
+
painter.setPen(QPen(option.palette.highlight().color(), 2))
|
|
41
|
+
painter.setBrush(Qt.BrushStyle.NoBrush)
|
|
42
|
+
painter.drawRoundedRect(option.rect.adjusted(3, 3, -3, -3), 5, 5)
|
|
43
|
+
painter.restore()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Window(QMainWindow):
|
|
47
|
+
def __init__(self, service, config_path: Path, bootstrap=False):
|
|
48
|
+
super().__init__()
|
|
49
|
+
self.service, self.config_path = service, config_path.resolve()
|
|
50
|
+
self.job_id = None
|
|
51
|
+
self.preview = None
|
|
52
|
+
self.dark = True
|
|
53
|
+
self.tasks: list[Task] = []
|
|
54
|
+
self.pool = QThreadPool.globalInstance()
|
|
55
|
+
self.supervisor = Supervisor(self.config_path)
|
|
56
|
+
self.service_busy = False
|
|
57
|
+
self.service_generation = 0
|
|
58
|
+
self.poll_busy = False
|
|
59
|
+
self.exiting = False
|
|
60
|
+
self.github_actor = ""
|
|
61
|
+
self.last_github_check = 0.0
|
|
62
|
+
self.service_labels = {}
|
|
63
|
+
self.service_buttons = []
|
|
64
|
+
self.service_button_names = {}
|
|
65
|
+
from github_ai_mcp.desktop.runtime import asset_path
|
|
66
|
+
self.setWindowIcon(QIcon(str(asset_path("github-ai-mcp.ico"))))
|
|
67
|
+
self.setWindowTitle("GitHub-AI-MCP · Local control")
|
|
68
|
+
self.resize(1240, 820)
|
|
69
|
+
self.setMinimumSize(960, 650)
|
|
70
|
+
layout = QVBoxLayout()
|
|
71
|
+
header = QHBoxLayout()
|
|
72
|
+
self.summary = QLabel()
|
|
73
|
+
self.language_selector = QComboBox()
|
|
74
|
+
self.language_selector.addItems(["ru", "en"])
|
|
75
|
+
self.language_selector.setCurrentText(service.config.locale)
|
|
76
|
+
self.language_selector.currentTextChanged.connect(self.translate)
|
|
77
|
+
header.addWidget(self.summary, 1)
|
|
78
|
+
header.addWidget(self.language_selector)
|
|
79
|
+
layout.addLayout(header)
|
|
80
|
+
services = QGridLayout()
|
|
81
|
+
for row, name in enumerate(("mcp", "tunnel")):
|
|
82
|
+
label = QLabel()
|
|
83
|
+
label.setWordWrap(True)
|
|
84
|
+
self.service_labels[name] = label
|
|
85
|
+
services.addWidget(label, row, 0)
|
|
86
|
+
for column, action in enumerate(("start", "stop", "restart"), 1):
|
|
87
|
+
button = QPushButton()
|
|
88
|
+
button.clicked.connect(lambda checked=False, n=name, a=action: self.control_service(a, n))
|
|
89
|
+
services.addWidget(button, row, column)
|
|
90
|
+
self.service_buttons.append((button, action))
|
|
91
|
+
button.setObjectName(f"{name}_{action}")
|
|
92
|
+
self.service_button_names[f"{name}_{action}"] = button
|
|
93
|
+
self.github_label = QLabel()
|
|
94
|
+
services.addWidget(self.github_label, 2, 0)
|
|
95
|
+
self.setup_button = QPushButton()
|
|
96
|
+
self.setup_button.clicked.connect(self.setup)
|
|
97
|
+
services.addWidget(self.setup_button, 2, 1)
|
|
98
|
+
self.stop_all_button = QPushButton()
|
|
99
|
+
self.stop_all_button.clicked.connect(lambda: self.control_service("stop_all"))
|
|
100
|
+
services.addWidget(self.stop_all_button, 2, 2)
|
|
101
|
+
self.exit_button = QPushButton()
|
|
102
|
+
self.exit_button.clicked.connect(self.exit_application)
|
|
103
|
+
services.addWidget(self.exit_button, 2, 3)
|
|
104
|
+
self.diagnostics_button = QPushButton("Run Diagnostics / Диагностика")
|
|
105
|
+
self.diagnostics_button.clicked.connect(lambda: self.execute(self.safe_diagnostics))
|
|
106
|
+
services.addWidget(self.diagnostics_button, 3, 0)
|
|
107
|
+
self.copy_diagnostics_button = QPushButton("Copy Safe Diagnostics / Копировать диагностику")
|
|
108
|
+
self.copy_diagnostics_button.clicked.connect(lambda: self.execute(self.safe_diagnostics,
|
|
109
|
+
lambda result: QApplication.clipboard().setText(json.dumps(result, ensure_ascii=False, indent=2))))
|
|
110
|
+
services.addWidget(self.copy_diagnostics_button, 3, 1, 1, 3)
|
|
111
|
+
services.setColumnStretch(0, 1)
|
|
112
|
+
self.services_panel = QWidget()
|
|
113
|
+
self.services_panel.setLayout(services)
|
|
114
|
+
self.nav = QListWidget()
|
|
115
|
+
self.nav.setItemDelegate(NavigationDelegate(self.nav))
|
|
116
|
+
self.nav.currentRowChanged.connect(self.refresh)
|
|
117
|
+
self.jobs = QComboBox()
|
|
118
|
+
self.jobs.currentIndexChanged.connect(self.select_job)
|
|
119
|
+
self.repo = QComboBox()
|
|
120
|
+
self.repo.addItems(list(service.config.repositories))
|
|
121
|
+
self.repo.currentIndexChanged.connect(self.refresh)
|
|
122
|
+
selectors = QHBoxLayout()
|
|
123
|
+
self.repo_label = QLabel()
|
|
124
|
+
selectors.addWidget(self.repo_label)
|
|
125
|
+
selectors.addWidget(self.repo, 1)
|
|
126
|
+
self.job_label = QLabel()
|
|
127
|
+
selectors.addWidget(self.job_label)
|
|
128
|
+
selectors.addWidget(self.jobs, 2)
|
|
129
|
+
layout.addLayout(selectors)
|
|
130
|
+
self.log_filter = QLineEdit()
|
|
131
|
+
self.log_filter.textChanged.connect(self.filter_logs)
|
|
132
|
+
self.output = QPlainTextEdit()
|
|
133
|
+
self.output.setReadOnly(True)
|
|
134
|
+
self.settings = QPlainTextEdit()
|
|
135
|
+
self.settings.setPlainText(json.dumps(service.config.model_dump(mode="json"), ensure_ascii=False, indent=2))
|
|
136
|
+
self.settings.hide()
|
|
137
|
+
right = QWidget()
|
|
138
|
+
right_layout = QVBoxLayout(right)
|
|
139
|
+
self.health_summary = QLabel()
|
|
140
|
+
self.health_summary.setWordWrap(True)
|
|
141
|
+
right_layout.addWidget(self.health_summary)
|
|
142
|
+
self.overview = QWidget()
|
|
143
|
+
overview_layout = QGridLayout(self.overview)
|
|
144
|
+
self.overview_cards = {}
|
|
145
|
+
for index, name in enumerate(("repositories", "jobs", "mode", "next")):
|
|
146
|
+
card = QLabel()
|
|
147
|
+
card.setWordWrap(True)
|
|
148
|
+
card.setMargin(18)
|
|
149
|
+
card.setMinimumHeight(100)
|
|
150
|
+
card.setObjectName("overview_card")
|
|
151
|
+
overview_layout.addWidget(card, index // 2, index % 2)
|
|
152
|
+
self.overview_cards[name] = card
|
|
153
|
+
right_layout.addWidget(self.overview)
|
|
154
|
+
self.guidance = QLabel()
|
|
155
|
+
self.guidance.setWordWrap(True)
|
|
156
|
+
right_layout.addWidget(self.guidance)
|
|
157
|
+
right_layout.addWidget(self.github_label)
|
|
158
|
+
right_layout.addWidget(self.services_panel)
|
|
159
|
+
self.advanced = QCheckBox()
|
|
160
|
+
self.advanced.toggled.connect(self.refresh)
|
|
161
|
+
right_layout.addWidget(self.advanced)
|
|
162
|
+
right_layout.addWidget(self.log_filter)
|
|
163
|
+
right_layout.addWidget(self.output)
|
|
164
|
+
right_layout.addWidget(self.settings)
|
|
165
|
+
split = QSplitter()
|
|
166
|
+
split.addWidget(self.nav)
|
|
167
|
+
split.addWidget(right)
|
|
168
|
+
split.setSizes([220, 900])
|
|
169
|
+
layout.addWidget(split, 1)
|
|
170
|
+
self.action_buttons = {}
|
|
171
|
+
callbacks = {
|
|
172
|
+
"refresh": self.refresh, "new_job": self.new_job, "edit_file": self.edit_file,
|
|
173
|
+
"delete_file": self.delete_file, "approve": self.approve,
|
|
174
|
+
"commit": lambda: self.job_operation("create_file_commits"),
|
|
175
|
+
"push": lambda: self.job_operation("publish_branch"), "pr": self.pr,
|
|
176
|
+
"recover": lambda: self.job_operation("resume_job"),
|
|
177
|
+
"cancel_job": lambda: self.job_operation("cancel_job"),
|
|
178
|
+
"login": self.login, "logout": self.logout, "save": self.save,
|
|
179
|
+
"theme": lambda: self.theme(), "add_repository": self.add_repository,
|
|
180
|
+
"branches": lambda: self.repository_operation("list_branches"),
|
|
181
|
+
"history": lambda: self.repository_operation("list_recent_commits"),
|
|
182
|
+
"contributions": lambda: self.repository_operation("check_contribution_eligibility"),
|
|
183
|
+
}
|
|
184
|
+
self.action_bar = QVBoxLayout()
|
|
185
|
+
for name, callback in callbacks.items():
|
|
186
|
+
button = QPushButton()
|
|
187
|
+
button.setObjectName(name)
|
|
188
|
+
button.clicked.connect(callback)
|
|
189
|
+
self.action_bar.addWidget(button)
|
|
190
|
+
self.action_buttons[name] = button
|
|
191
|
+
right_layout.addLayout(self.action_bar)
|
|
192
|
+
self.content_spacer = QWidget()
|
|
193
|
+
right_layout.addWidget(self.content_spacer, 1)
|
|
194
|
+
self.settings_form = QWidget()
|
|
195
|
+
form = QFormLayout(self.settings_form)
|
|
196
|
+
self.mode_selector = QComboBox()
|
|
197
|
+
self.mode_selector.addItems(["READ_ONLY", "LOCAL_REVIEW", "AUTO_APPROVED"])
|
|
198
|
+
self.mode_selector.setCurrentText(service.config.mode)
|
|
199
|
+
self.port_selector = QSpinBox()
|
|
200
|
+
self.port_selector.setRange(1024, 65535)
|
|
201
|
+
self.port_selector.setValue(service.config.port)
|
|
202
|
+
self.mode_label, self.port_label = QLabel(), QLabel()
|
|
203
|
+
form.addRow(self.mode_label, self.mode_selector)
|
|
204
|
+
form.addRow(self.port_label, self.port_selector)
|
|
205
|
+
self.launch_settings = QPushButton()
|
|
206
|
+
self.launch_settings.clicked.connect(self.setup)
|
|
207
|
+
form.addRow(self.launch_settings)
|
|
208
|
+
right_layout.insertWidget(4, self.settings_form)
|
|
209
|
+
container = QWidget()
|
|
210
|
+
container.setLayout(layout)
|
|
211
|
+
self.setCentralWidget(container)
|
|
212
|
+
self.legal_action = QAction(self)
|
|
213
|
+
self.legal_action.triggered.connect(self.show_legal)
|
|
214
|
+
self.menuBar().addAction(self.legal_action)
|
|
215
|
+
self.translate()
|
|
216
|
+
self.theme(False)
|
|
217
|
+
self.reload_jobs()
|
|
218
|
+
self.nav.setCurrentRow(0)
|
|
219
|
+
self.refresh()
|
|
220
|
+
self.tray = QSystemTrayIcon(self.windowIcon(), self)
|
|
221
|
+
menu = QMenu(self)
|
|
222
|
+
self.show_action = QAction("GitHub-AI-MCP", self)
|
|
223
|
+
self.show_action.triggered.connect(self.showNormal)
|
|
224
|
+
menu.addAction(self.show_action)
|
|
225
|
+
self.exit_action = QAction(self.exit_button.text(), self)
|
|
226
|
+
self.exit_action.triggered.connect(self.exit_application)
|
|
227
|
+
menu.addAction(self.exit_action)
|
|
228
|
+
self.tray.setContextMenu(menu)
|
|
229
|
+
self.tray.activated.connect(lambda reason: self.showNormal() if reason == QSystemTrayIcon.ActivationReason.DoubleClick else None)
|
|
230
|
+
if QSystemTrayIcon.isSystemTrayAvailable():
|
|
231
|
+
self.tray.show()
|
|
232
|
+
self.timer = QTimer(self)
|
|
233
|
+
self.timer.setInterval(3000)
|
|
234
|
+
self.timer.timeout.connect(self.poll_services)
|
|
235
|
+
self.timer.start()
|
|
236
|
+
self.poll_services()
|
|
237
|
+
if bootstrap:
|
|
238
|
+
QTimer.singleShot(0, self.startup)
|
|
239
|
+
|
|
240
|
+
def translate(self, *_):
|
|
241
|
+
labels = TEXT[self.language_selector.currentText()]
|
|
242
|
+
row = max(self.nav.currentRow(), 0)
|
|
243
|
+
self.nav.blockSignals(True)
|
|
244
|
+
self.nav.clear()
|
|
245
|
+
self.nav.addItems(labels[:8])
|
|
246
|
+
self.nav.setCurrentRow(row)
|
|
247
|
+
self.nav.blockSignals(False)
|
|
248
|
+
names = ["refresh", "new_job", "edit_file", "delete_file", "approve", "commit", "push",
|
|
249
|
+
"pr", "recover", "cancel_job", "login", "logout", "save", "theme"]
|
|
250
|
+
indices = list(range(8, 20)) + [22, 23]
|
|
251
|
+
for name, index in zip(names, indices):
|
|
252
|
+
self.action_buttons[name].setText(labels[index])
|
|
253
|
+
self.action_buttons["branches"].setText(self.tr_text("View repository branches", "Посмотреть ветки репозитория"))
|
|
254
|
+
self.action_buttons["history"].setText(self.tr_text("View recent commits", "Посмотреть последние коммиты"))
|
|
255
|
+
self.action_buttons["contributions"].setText(self.tr_text("Check contribution eligibility", "Проверить учёт вклада в GitHub"))
|
|
256
|
+
self.action_buttons["add_repository"].setText(self.tr_text("Add authorized repository", "Добавить разрешённый репозиторий"))
|
|
257
|
+
self.log_filter.setPlaceholderText(self.tr_text("Search diagnostic events", "Поиск событий в журнале"))
|
|
258
|
+
self.advanced.setText(self.tr_text("Advanced: raw JSON", "Дополнительно: исходный JSON"))
|
|
259
|
+
self.mode_label.setText(self.tr_text("Security mode", "Режим безопасности"))
|
|
260
|
+
self.port_label.setText(self.tr_text("Local MCP port", "Локальный порт MCP"))
|
|
261
|
+
self.launch_settings.setText(self.tr_text("Configure credentials, tunnel and startup", "Настроить подключение, туннель и запуск"))
|
|
262
|
+
self.launch_settings.setToolTip(self.tr_text("Configure local integrations. Tunnel is optional.", "Настройка локальных интеграций. Туннель необязателен."))
|
|
263
|
+
self.update_actions()
|
|
264
|
+
self.legal_action.setText(self.tr_text("About / Legal", "О программе / Лицензии"))
|
|
265
|
+
self.repo_label.setText(self.tr_text("Repository", "Репозиторий"))
|
|
266
|
+
self.job_label.setText(self.tr_text("Job", "Задание"))
|
|
267
|
+
self.setup_button.setToolTip(self.tr_text("Configure optional tunnel and startup", "Настроить необязательный туннель и запуск"))
|
|
268
|
+
self.stop_all_button.setToolTip(self.tr_text("Stop this application's owned MCP and tunnel processes", "Остановить принадлежащие приложению процессы MCP и туннеля"))
|
|
269
|
+
self.exit_button.setToolTip(self.tr_text("Stop owned services and exit", "Остановить собственные службы и закрыть приложение"))
|
|
270
|
+
for button, action in self.service_buttons:
|
|
271
|
+
button.setText({"start": self.tr_text("Start", "Запустить"), "stop": self.tr_text("Stop", "Остановить"),
|
|
272
|
+
"restart": self.tr_text("Restart", "Перезапустить")}[action])
|
|
273
|
+
self.setup_button.setText(self.tr_text("Setup", "Настройка запуска"))
|
|
274
|
+
self.stop_all_button.setText(self.tr_text("Stop all", "Остановить всё"))
|
|
275
|
+
self.exit_button.setText(self.tr_text("Exit application", "Закрыть приложение"))
|
|
276
|
+
if hasattr(self, "exit_action"):
|
|
277
|
+
self.exit_action.setText(self.exit_button.text())
|
|
278
|
+
self.github_label.setText("GitHub: " + (self.github_actor or self.tr_text("Not verified", "Не проверен")))
|
|
279
|
+
if hasattr(self, "latest_service_status"):
|
|
280
|
+
self.render_services(self.latest_service_status)
|
|
281
|
+
self.output.setPlaceholderText(self.tr_text("Select a repository or job. Use Setup to connect services.", "Выберите репозиторий или задание. Откройте настройку запуска для подключения служб."))
|
|
282
|
+
self.summary.setText(f"GitHub-AI-MCP · {self.service.config.mode} · "
|
|
283
|
+
f"{len(self.service.config.repositories)} {self.tr_text('repositories', 'репозиториев')} · 127.0.0.1:{self.service.config.port}")
|
|
284
|
+
|
|
285
|
+
def tr_text(self, en, ru):
|
|
286
|
+
return ru if self.language_selector.currentText() == "ru" else en
|
|
287
|
+
|
|
288
|
+
def theme(self, toggle=True):
|
|
289
|
+
if toggle:
|
|
290
|
+
self.dark = not self.dark
|
|
291
|
+
bg, fg, panel, border = ("#101923", "#edf3fa", "#1b2a3b", "#52677e") if self.dark else ("#f4f7fa", "#162435", "#ffffff", "#667c90")
|
|
292
|
+
self.setStyleSheet(f"QWidget {{background:{bg};color:{fg};font-size:14px;}} "
|
|
293
|
+
f"QPlainTextEdit,QListWidget,QComboBox,QLineEdit {{background:{panel};border:2px solid {border};"
|
|
294
|
+
"border-radius:8px;padding:6px;} QPushButton {background:#205d96;color:white;"
|
|
295
|
+
"padding:8px;border:2px solid transparent;border-radius:7px;}"
|
|
296
|
+
"QPushButton:hover {background:#286ea9;} QPushButton:pressed {background:#154570;}"
|
|
297
|
+
"QPushButton:focus,QLineEdit:focus,QComboBox:focus,QPlainTextEdit:focus {border:2px solid #72baff;}"
|
|
298
|
+
"QPushButton:disabled {background:#455565;color:#e2e8f0;}"
|
|
299
|
+
f"QLabel#overview_card {{background:{panel};border:1px solid {border};border-radius:10px;}} "
|
|
300
|
+
"QListWidget::item {padding:10px;margin:2px;border-radius:6px;}"
|
|
301
|
+
"QListWidget::item:hover {background:#364f69;}"
|
|
302
|
+
"QListWidget::item:selected {background:#205d96;color:white;} QLabel {padding:4px;}")
|
|
303
|
+
|
|
304
|
+
def execute(self, fn, callback=None):
|
|
305
|
+
if self.tasks:
|
|
306
|
+
self.statusBar().showMessage(self.tr_text("Wait for the current operation", "Дождитесь текущей операции"))
|
|
307
|
+
return
|
|
308
|
+
page = self.nav.currentRow()
|
|
309
|
+
task = Task(fn)
|
|
310
|
+
self.tasks.append(task)
|
|
311
|
+
self.statusBar().showMessage(self.tr_text("Working…", "Выполняется…"))
|
|
312
|
+
self.update_actions()
|
|
313
|
+
def done(value):
|
|
314
|
+
self.statusBar().showMessage(self.tr_text("Done", "Готово"))
|
|
315
|
+
self.tasks.remove(task)
|
|
316
|
+
self.update_actions()
|
|
317
|
+
if self.nav.currentRow() == page:
|
|
318
|
+
self.display(value)
|
|
319
|
+
if callback:
|
|
320
|
+
callback(value)
|
|
321
|
+
self.reload_jobs()
|
|
322
|
+
self.update_actions()
|
|
323
|
+
def failed(error):
|
|
324
|
+
self.supervisor.log("gui", error)
|
|
325
|
+
self.statusBar().showMessage(error)
|
|
326
|
+
QMessageBox.warning(self, "GitHub-AI-MCP", error)
|
|
327
|
+
self.tasks.remove(task)
|
|
328
|
+
self.update_actions()
|
|
329
|
+
task.signals.done.connect(done)
|
|
330
|
+
task.signals.failed.connect(failed)
|
|
331
|
+
self.pool.start(task)
|
|
332
|
+
|
|
333
|
+
def display(self, value):
|
|
334
|
+
self.last_display = value
|
|
335
|
+
if self.advanced.isChecked():
|
|
336
|
+
text = json.dumps(value, ensure_ascii=False, indent=2, default=str)
|
|
337
|
+
elif isinstance(value, dict) and "diffs" in value:
|
|
338
|
+
text = "\n\n".join(str(item.get("diff", item)) if isinstance(item, dict) else str(item)
|
|
339
|
+
for item in value["diffs"])
|
|
340
|
+
elif self.nav.currentRow() == 0:
|
|
341
|
+
text = self.tr_text(
|
|
342
|
+
"Choose Repositories to add a repository. Create a job in Jobs, then review its changes.\n"
|
|
343
|
+
"READ_ONLY allows inspection only. Services manages the local MCP server and optional tunnel.",
|
|
344
|
+
"Добавьте репозиторий в разделе «Репозитории». Создайте задание в разделе «Задания», затем проверьте изменения.\n"
|
|
345
|
+
"READ_ONLY разрешает только просмотр. Раздел «Службы» управляет MCP и необязательным туннелем.")
|
|
346
|
+
else:
|
|
347
|
+
labels = {"state": self.tr_text("State", "Состояние"), "repository": self.tr_text("Repository", "Репозиторий"),
|
|
348
|
+
"target_branch": self.tr_text("Branch", "Ветка"), "id": self.tr_text("Job ID", "ID задания"),
|
|
349
|
+
"pr_url": "Pull request", "created_commits": self.tr_text("Commits", "Коммиты")}
|
|
350
|
+
records = value if isinstance(value, list) else [value]
|
|
351
|
+
text = "\n\n".join("\n".join(f"{labels.get(k, k)}: {v}" for k, v in record.items()
|
|
352
|
+
if k in labels or not isinstance(v, dict)) if isinstance(record, dict) else str(record)
|
|
353
|
+
for record in records)
|
|
354
|
+
if self.output.toPlainText() != text:
|
|
355
|
+
self.output.setPlainText(text)
|
|
356
|
+
|
|
357
|
+
def selected_job(self):
|
|
358
|
+
if self.job_id:
|
|
359
|
+
try:
|
|
360
|
+
return self.service.db.get(self.job_id)
|
|
361
|
+
except AppError:
|
|
362
|
+
pass
|
|
363
|
+
return None
|
|
364
|
+
|
|
365
|
+
def update_actions(self):
|
|
366
|
+
if not hasattr(self, "action_buttons"):
|
|
367
|
+
return
|
|
368
|
+
row = self.nav.currentRow()
|
|
369
|
+
job = self.selected_job()
|
|
370
|
+
state = job["state"] if job else ""
|
|
371
|
+
writable = self.service.config.mode != "READ_ONLY"
|
|
372
|
+
editable = bool(job and not job.get("commits") and state in
|
|
373
|
+
{"SNAPSHOT_READY", "PATCHING", "PREVIEW_READY", "CHECK_FAILED"})
|
|
374
|
+
recovery = bool(job and ((state in {"COMMITTING", "RECOVERY_REQUIRED"} and job.get("final_tree"))
|
|
375
|
+
or (state == "CHECK_FAILED" and job.get("commits")) or state == "PUBLISHING"))
|
|
376
|
+
pages = {"refresh": {0, 1, 2, 3, 4, 5, 7}, "new_job": {1, 2},
|
|
377
|
+
"edit_file": {3}, "delete_file": {3}, "approve": {3}, "commit": {3, 4},
|
|
378
|
+
"push": {4}, "pr": {4}, "recover": {2}, "cancel_job": {2},
|
|
379
|
+
"login": {4}, "logout": {4}, "save": {6}, "theme": {6}, "add_repository": {1}, "branches": {1}, "history": {1}, "contributions": {4}}
|
|
380
|
+
allowed = {"new_job": writable and bool(self.repo.currentText()),
|
|
381
|
+
"edit_file": writable and editable, "delete_file": writable and editable,
|
|
382
|
+
"approve": writable and editable and bool(self.preview and self.preview.get("job_id") == self.job_id),
|
|
383
|
+
"commit": writable and bool(job) and state in {"PREVIEW_READY", "CHECK_FAILED"},
|
|
384
|
+
"push": self.service.config.mode == "AUTO_APPROVED" and state == "VERIFIED",
|
|
385
|
+
"pr": self.service.config.mode == "AUTO_APPROVED" and state == "PUBLISHED",
|
|
386
|
+
"recover": writable and recovery,
|
|
387
|
+
"cancel_job": writable and bool(job) and state not in {"CANCELLED", "COMPLETED", "NO_CHANGE"}}
|
|
388
|
+
for name in ("branches", "history", "contributions"):
|
|
389
|
+
allowed[name] = bool(self.repo.currentText())
|
|
390
|
+
# Evaluate existing policy without changing state or granting permissions.
|
|
391
|
+
policy_errors = {}
|
|
392
|
+
if job:
|
|
393
|
+
for name, action in (("commit", "commit"), ("push", "push"), ("pr", "pr")):
|
|
394
|
+
try:
|
|
395
|
+
self.service.policy.authorize(job, action)
|
|
396
|
+
except AppError as error:
|
|
397
|
+
allowed[name] = False
|
|
398
|
+
policy_errors[name] = error.code
|
|
399
|
+
tips = {
|
|
400
|
+
"branches": ("Inspect branches of the selected authorized repository", "Посмотреть ветки выбранного разрешённого репозитория"),
|
|
401
|
+
"history": ("Read recent repository commits without modifying them", "Прочитать последние коммиты без изменения репозитория"),
|
|
402
|
+
"contributions": ("Check author email association and GitHub contribution conditions; no writes", "Проверить email автора и условия учёта вклада в GitHub без изменений"),
|
|
403
|
+
"refresh": ("Refresh this section", "Обновить выбранный раздел"),
|
|
404
|
+
"new_job": ("Create an isolated workspace before editing repository files", "Создать отдельную рабочую копию для изменения файлов"),
|
|
405
|
+
"edit_file": ("Edit a file in the selected job workspace", "Изменить файл в рабочей копии выбранного задания"),
|
|
406
|
+
"delete_file": ("Delete a workspace file after confirmation", "Удалить файл рабочей копии после подтверждения"),
|
|
407
|
+
"approve": ("Approve this exact reviewed snapshot for one hour; changes invalidate approval", "Одобрить проверенный снимок на час; изменение файлов отменяет одобрение"),
|
|
408
|
+
"commit": ("Create one Git commit per reviewed changed path; policy and checks still apply", "Создать один коммит на каждый проверенный путь; политика и проверки обязательны"),
|
|
409
|
+
"push": ("Push the selected job branch to its authorized remote; requires approval", "Отправить ветку задания в разрешённый репозиторий; требуется одобрение"),
|
|
410
|
+
"pr": ("Create a pull request from the published job branch into the repository default branch", "Создать pull request из опубликованной ветки в основную ветку репозитория"),
|
|
411
|
+
"recover": ("Recover commits, retry final checks or reconcile an interrupted push; never force-push", "Восстановить коммиты, повторить проверки или сверить прерванную отправку; без принудительной отправки"),
|
|
412
|
+
"cancel_job": ("Mark the selected job CANCELLED. Retain workspace; published changes remain", "Пометить задание CANCELLED. Рабочая копия и опубликованные изменения сохранятся"),
|
|
413
|
+
"login": ("Verify a GitHub PAT and save it in the OS credential vault", "Проверить GitHub PAT и сохранить в защищённом хранилище ОС"),
|
|
414
|
+
"logout": ("Remove the local credential after confirmation; revoke separately on GitHub", "Удалить локальный токен после подтверждения; отзыв на GitHub выполняется отдельно"),
|
|
415
|
+
"save": ("Save trusted settings; restart to apply", "Сохранить доверенные настройки; для применения нужен перезапуск"),
|
|
416
|
+
"theme": ("Switch between dark and light themes", "Переключить тёмную и светлую тему"),
|
|
417
|
+
"add_repository": ("Allow access to a repository with explicitly authorized Git author identity", "Разрешить доступ к репозиторию с явно указанным автором Git"),
|
|
418
|
+
}
|
|
419
|
+
for name, button in self.action_buttons.items():
|
|
420
|
+
visible = row in pages[name] and (name != "recover" or recovery)
|
|
421
|
+
button.setVisible(visible)
|
|
422
|
+
enabled = allowed.get(name, True) and not self.tasks
|
|
423
|
+
if button.isEnabled() != enabled:
|
|
424
|
+
button.setEnabled(enabled)
|
|
425
|
+
reason = ""
|
|
426
|
+
if not enabled:
|
|
427
|
+
if self.tasks:
|
|
428
|
+
reason = self.tr_text("An operation is running. Wait for completion.", "Выполняется операция. Дождитесь завершения.")
|
|
429
|
+
elif not writable and name in allowed:
|
|
430
|
+
reason = self.tr_text("READ_ONLY prohibits changes.", "READ_ONLY запрещает изменения.")
|
|
431
|
+
elif name == "new_job" and not self.repo.currentText():
|
|
432
|
+
reason = self.tr_text("Add and select an authorized repository.", "Добавьте и выберите разрешённый репозиторий.")
|
|
433
|
+
elif name in {"push", "pr"} and self.service.config.mode != "AUTO_APPROVED":
|
|
434
|
+
reason = self.tr_text("Remote writes require AUTO_APPROVED and approval.", "Отправка требует AUTO_APPROVED и одобрения.")
|
|
435
|
+
elif not job:
|
|
436
|
+
reason = self.tr_text("Select a job first.", "Сначала выберите задание.")
|
|
437
|
+
elif name == "approve" and not self.preview:
|
|
438
|
+
reason = self.tr_text("Refresh and read the current change review first.", "Сначала обновите и прочитайте текущие изменения.")
|
|
439
|
+
elif name in policy_errors:
|
|
440
|
+
reasons = {"APPROVAL_REQUIRED": ("Approve the exact snapshot or configure a scoped grant.", "Одобрите точный снимок либо настройте ограниченный грант."),
|
|
441
|
+
"IDENTITY_REQUIRED": ("Authorize the repository's real Git author identity.", "Разрешите использование реального автора Git в настройках репозитория.")}
|
|
442
|
+
reason = self.tr_text(*reasons.get(policy_errors[name], ("Blocked by security policy.", "Запрещено политикой безопасности.")))
|
|
443
|
+
else:
|
|
444
|
+
reason = self.tr_text(f"Unavailable in job state {state}.", f"Недоступно в состоянии задания {state}.")
|
|
445
|
+
button.setToolTip(self.tr_text(*tips[name]) + ("\n" + reason if reason else ""))
|
|
446
|
+
if not self.service.config.repositories:
|
|
447
|
+
guidance = self.tr_text("No repositories configured. Add an authorized repository to begin.", "Нет репозиториев. Добавьте разрешённый репозиторий для начала работы.")
|
|
448
|
+
else:
|
|
449
|
+
guidance = self.tr_text("Selected job", "Выбранное задание") + f": {self.job_id or '—'} · {state or '—'}"
|
|
450
|
+
if not writable:
|
|
451
|
+
guidance += "\n" + self.tr_text("READ_ONLY: inspection only. Writes are disabled by policy.", "READ_ONLY: только просмотр. Изменения запрещены политикой.")
|
|
452
|
+
self.guidance.setText(guidance)
|
|
453
|
+
self.overview.setVisible(row == 0 and not self.advanced.isChecked())
|
|
454
|
+
active = sum(j["state"] not in {"CANCELLED", "COMPLETED", "NO_CHANGE"} for j in self.service.db.list_jobs()
|
|
455
|
+
if j["repository"] in self.service.config.repositories)
|
|
456
|
+
self.overview_cards["repositories"].setText(self.tr_text("AUTHORIZED REPOSITORIES", "РАЗРЕШЁННЫЕ РЕПОЗИТОРИИ") + f"\n{len(self.service.config.repositories)}")
|
|
457
|
+
self.overview_cards["jobs"].setText(self.tr_text("ACTIVE JOBS", "АКТИВНЫЕ ЗАДАНИЯ") + f"\n{active}")
|
|
458
|
+
self.overview_cards["mode"].setText(self.tr_text("SECURITY MODE", "РЕЖИМ БЕЗОПАСНОСТИ") + f"\n{self.service.config.mode}")
|
|
459
|
+
self.overview_cards["next"].setText(self.tr_text("NEXT STEP\nAdd a repository, create a job and review its changes.", "СЛЕДУЮЩИЙ ШАГ\nДобавьте репозиторий, создайте задание и проверьте изменения."))
|
|
460
|
+
self.health_summary.setVisible(row == 0)
|
|
461
|
+
self.content_spacer.setVisible(row in {0, 5})
|
|
462
|
+
self.log_filter.setVisible(row == 7)
|
|
463
|
+
self.services_panel.setVisible(row == 5)
|
|
464
|
+
self.github_label.setVisible(row in {0, 4})
|
|
465
|
+
self.settings_form.setVisible(row == 6 and not self.advanced.isChecked())
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def reload_jobs(self):
|
|
469
|
+
jobs = [j for j in self.service.db.list_jobs() if j["repository"] in self.service.config.repositories]
|
|
470
|
+
self.jobs.blockSignals(True)
|
|
471
|
+
self.jobs.clear()
|
|
472
|
+
for job in jobs:
|
|
473
|
+
self.jobs.addItem(f"{job['id'][:8]} · {job['state']} · {job['target_branch']}", job["id"])
|
|
474
|
+
if self.job_id:
|
|
475
|
+
self.jobs.setCurrentIndex(self.jobs.findData(self.job_id))
|
|
476
|
+
elif jobs:
|
|
477
|
+
self.job_id = jobs[0]["id"]
|
|
478
|
+
self.jobs.blockSignals(False)
|
|
479
|
+
self.update_actions()
|
|
480
|
+
|
|
481
|
+
def select_job(self, *_):
|
|
482
|
+
self.job_id = self.jobs.currentData()
|
|
483
|
+
self.preview = None
|
|
484
|
+
self.refresh()
|
|
485
|
+
|
|
486
|
+
def dashboard(self):
|
|
487
|
+
result = self.service.health_check()
|
|
488
|
+
import time
|
|
489
|
+
if time.monotonic() - self.last_github_check >= 300:
|
|
490
|
+
try:
|
|
491
|
+
result["github_actor"] = self.service.github.request("GET", "/user")["login"]
|
|
492
|
+
except AppError as e:
|
|
493
|
+
result["github_actor"] = e.code
|
|
494
|
+
else:
|
|
495
|
+
result["github_actor"] = self.github_actor
|
|
496
|
+
return result
|
|
497
|
+
|
|
498
|
+
def refresh(self, *_):
|
|
499
|
+
row = self.nav.currentRow()
|
|
500
|
+
repo, job_id = self.repo.currentText(), self.job_id
|
|
501
|
+
self.update_actions()
|
|
502
|
+
self.settings.setVisible(row == 6 and self.advanced.isChecked())
|
|
503
|
+
self.output.setVisible(row not in {0, 5, 6} or (row in {0, 5} and self.advanced.isChecked()))
|
|
504
|
+
if row == 0:
|
|
505
|
+
self.execute(self.dashboard, self.dashboard_done)
|
|
506
|
+
elif row == 1 and repo:
|
|
507
|
+
self.execute(lambda: self.service.get_repository_info(repo))
|
|
508
|
+
elif row == 2:
|
|
509
|
+
self.display([self.service._report(j) for j in self.service.db.list_jobs()
|
|
510
|
+
if j["repository"] in self.service.config.repositories])
|
|
511
|
+
elif row == 3 and job_id:
|
|
512
|
+
def get_all():
|
|
513
|
+
preview = self.service.preview_job(job_id, limit=50)
|
|
514
|
+
while preview["next_offset"] is not None:
|
|
515
|
+
more = self.service.preview_job(job_id, offset=preview["next_offset"], limit=50)
|
|
516
|
+
if more["fingerprint"] != preview["fingerprint"]:
|
|
517
|
+
raise AppError("STALE_APPROVAL", "Snapshot changed during review")
|
|
518
|
+
preview["diffs"].extend(more["diffs"])
|
|
519
|
+
preview["next_offset"] = more["next_offset"]
|
|
520
|
+
return preview
|
|
521
|
+
self.execute(get_all, lambda value: self.accept_preview(value))
|
|
522
|
+
elif row == 4 and job_id:
|
|
523
|
+
self.execute(lambda: self.service.get_job_status(job_id))
|
|
524
|
+
elif row == 5:
|
|
525
|
+
self.poll_services()
|
|
526
|
+
self.output.setPlainText(self.tr_text("Local MCP requires its protected token. The external tunnel is optional.\nA live tunnel process does not confirm an external connection.", "Локальный MCP требует защищённый токен. Внешний туннель необязателен.\nРаботающий процесс туннеля не подтверждает внешнее подключение."))
|
|
527
|
+
elif row == 7:
|
|
528
|
+
self.log_text = self.supervisor.logs()
|
|
529
|
+
self.filter_logs()
|
|
530
|
+
elif row not in {6}:
|
|
531
|
+
self.output.setPlainText(self.tr_text("Select a repository or job to view this section.", "Выберите репозиторий или задание для просмотра раздела."))
|
|
532
|
+
|
|
533
|
+
def filter_logs(self, *_):
|
|
534
|
+
query = self.log_filter.text().casefold()
|
|
535
|
+
text = getattr(self, "log_text", "")
|
|
536
|
+
if query:
|
|
537
|
+
text = "\n".join(line for line in text.splitlines() if query in line.casefold())
|
|
538
|
+
self.output.setPlainText(text)
|
|
539
|
+
|
|
540
|
+
def accept_preview(self, value):
|
|
541
|
+
if value.get("job_id") == self.job_id:
|
|
542
|
+
self.preview = value
|
|
543
|
+
|
|
544
|
+
def ask(self, label):
|
|
545
|
+
value, ok = QInputDialog.getText(self, "GitHub-AI-MCP", label)
|
|
546
|
+
return value if ok and value else None
|
|
547
|
+
|
|
548
|
+
def repository_operation(self, name):
|
|
549
|
+
repository = self.repo.currentText()
|
|
550
|
+
if not repository:
|
|
551
|
+
return
|
|
552
|
+
if name == "check_contribution_eligibility":
|
|
553
|
+
job = self.selected_job()
|
|
554
|
+
branch = job["target_branch"] if job and job["repository"] == repository else self.service.config.repositories[repository].default_branch
|
|
555
|
+
self.execute(lambda: self.service.check_contribution_eligibility(repository, branch))
|
|
556
|
+
else:
|
|
557
|
+
self.execute(lambda: getattr(self.service, name)(repository))
|
|
558
|
+
|
|
559
|
+
def new_job(self):
|
|
560
|
+
repo = self.repo.currentText()
|
|
561
|
+
if not repo:
|
|
562
|
+
QMessageBox.information(self, "Repositories", self.tr_text('Add an allowlisted repository in Settings first', 'Сначала добавьте разрешённый репозиторий в настройках'))
|
|
563
|
+
return
|
|
564
|
+
title = self.ask(self.tr_text('Unique task title (English)', 'Название задачи по-английски (уникальное)'))
|
|
565
|
+
if title:
|
|
566
|
+
self.execute(lambda: self.service.create_job(repo, title, task_name=title),
|
|
567
|
+
lambda j: setattr(self, "job_id", j["id"]))
|
|
568
|
+
|
|
569
|
+
def edit_file(self):
|
|
570
|
+
if not self.job_id:
|
|
571
|
+
return
|
|
572
|
+
path = self.ask(self.tr_text('Repository-relative path', 'Путь относительно репозитория'))
|
|
573
|
+
if not path:
|
|
574
|
+
return
|
|
575
|
+
message = self.ask(self.tr_text('Commit subject: fix: … / feat: …', 'Сообщение коммита: fix: … / feat: …'))
|
|
576
|
+
if not message:
|
|
577
|
+
return
|
|
578
|
+
job_id = self.job_id
|
|
579
|
+
def prepare():
|
|
580
|
+
job = self.service.db.get(job_id)
|
|
581
|
+
try:
|
|
582
|
+
current = self.service.read_file(job["repository"], path, job_id)
|
|
583
|
+
except AppError as e:
|
|
584
|
+
if e.code != "NOT_FOUND":
|
|
585
|
+
raise
|
|
586
|
+
current = {"content": "", "checksum": None}
|
|
587
|
+
return current
|
|
588
|
+
def edit(current):
|
|
589
|
+
dialog = QDialog(self)
|
|
590
|
+
dialog.setWindowTitle(path)
|
|
591
|
+
dialog.resize(800, 600)
|
|
592
|
+
box = QVBoxLayout(dialog)
|
|
593
|
+
editor = QPlainTextEdit(current["content"])
|
|
594
|
+
box.addWidget(editor)
|
|
595
|
+
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
|
596
|
+
buttons.accepted.connect(dialog.accept)
|
|
597
|
+
buttons.rejected.connect(dialog.reject)
|
|
598
|
+
box.addWidget(buttons)
|
|
599
|
+
if dialog.exec() == QDialog.DialogCode.Accepted:
|
|
600
|
+
content = editor.toPlainText()
|
|
601
|
+
def write():
|
|
602
|
+
self.service.plan_changes(job_id, {path: message})
|
|
603
|
+
return self.service.write_file(job_id, path, content, current["checksum"])
|
|
604
|
+
self.preview = None
|
|
605
|
+
self.execute(write)
|
|
606
|
+
self.execute(prepare, edit)
|
|
607
|
+
|
|
608
|
+
def delete_file(self):
|
|
609
|
+
if not self.job_id:
|
|
610
|
+
return
|
|
611
|
+
path = self.ask(self.tr_text('Delete repository-relative file path', 'Удалить файл: путь относительно репозитория'))
|
|
612
|
+
if path and QMessageBox.question(self, self.tr_text('Delete', 'Удаление'), path) == QMessageBox.StandardButton.Yes:
|
|
613
|
+
job_id = self.job_id
|
|
614
|
+
def delete():
|
|
615
|
+
job = self.service.db.get(job_id)
|
|
616
|
+
current = self.service.read_file(job["repository"], path, job_id)
|
|
617
|
+
self.service.plan_changes(job_id, {path: "chore: delete " + path})
|
|
618
|
+
return self.service.delete_file(job_id, path, current["checksum"])
|
|
619
|
+
self.preview = None
|
|
620
|
+
self.execute(delete)
|
|
621
|
+
|
|
622
|
+
def approve(self):
|
|
623
|
+
if not self.job_id or not self.preview or self.preview["job_id"] != self.job_id:
|
|
624
|
+
QMessageBox.information(self, self.tr_text('Approval', 'Одобрение'), self.tr_text('Open Change review and read the current diff first', 'Откройте просмотр изменений и прочитайте текущий diff'))
|
|
625
|
+
return
|
|
626
|
+
actions = ["commit"]
|
|
627
|
+
if self.service.config.mode == "AUTO_APPROVED":
|
|
628
|
+
choice, ok = QInputDialog.getItem(self, self.tr_text('Approval', 'Одобрение'), self.tr_text('Approve exact snapshot for one hour', 'Одобрить точный снимок на один час'),
|
|
629
|
+
["commit", "commit,push", "commit,push,pr"], 0, False)
|
|
630
|
+
if not ok:
|
|
631
|
+
return
|
|
632
|
+
actions = choice.split(",")
|
|
633
|
+
if QMessageBox.question(self, self.tr_text('Human approval', 'Одобрение пользователя'), f"Approve {actions}?\n{self.preview['fingerprint']}\n"
|
|
634
|
+
+ self.tr_text("Clone hooks/filters are disabled. Host tests run only if locally trusted.", "Хуки и фильтры отключены. Тесты выполняются только при локальном доверии.")) == QMessageBox.StandardButton.Yes:
|
|
635
|
+
ident, fingerprint = self.job_id, self.preview["fingerprint"]
|
|
636
|
+
self.execute(lambda: self.service.approve_local(ident, fingerprint, actions))
|
|
637
|
+
|
|
638
|
+
def job_operation(self, name):
|
|
639
|
+
if self.job_id:
|
|
640
|
+
ident = self.job_id
|
|
641
|
+
job = self.service.db.get(ident)
|
|
642
|
+
descriptions = {
|
|
643
|
+
"cancel_job": self.tr_text("Cancel this job? Its workspace is retained. Commits and changes already published to GitHub will not be undone.", "Отменить задание? Рабочая копия сохранится. Коммиты и уже опубликованные в GitHub изменения не будут отменены."),
|
|
644
|
+
"resume_job": self.tr_text("Recover interrupted commits, retry final verification or reconcile publication according to the current state. Remote divergence stops recovery.", "Восстановить прерванные коммиты, повторить итоговую проверку или сверить публикацию по текущему состоянию. Расхождение удалённой ветки остановит восстановление."),
|
|
645
|
+
"publish_branch": self.tr_text("Push this branch to its configured remote?", "Отправить эту ветку в настроенный удалённый репозиторий?"),
|
|
646
|
+
"create_file_commits": self.tr_text("Create commits for the reviewed changes?", "Создать коммиты для проверенных изменений?"),
|
|
647
|
+
}
|
|
648
|
+
text = f"{ident} · {job['state']}\n{job['repository']} · {job['target_branch']}\n" + descriptions[name]
|
|
649
|
+
if QMessageBox.question(self, "GitHub-AI-MCP", text) != QMessageBox.StandardButton.Yes:
|
|
650
|
+
return
|
|
651
|
+
self.execute(lambda: getattr(self.service, name)(ident))
|
|
652
|
+
|
|
653
|
+
def pr(self):
|
|
654
|
+
if not self.job_id:
|
|
655
|
+
return
|
|
656
|
+
title = self.ask(self.tr_text('PR title', 'Заголовок PR'))
|
|
657
|
+
description = self.ask(self.tr_text('PR summary', 'Описание PR'))
|
|
658
|
+
if title and description:
|
|
659
|
+
ident = self.job_id
|
|
660
|
+
job = self.service.db.get(ident)
|
|
661
|
+
target = self.service.config.repositories[job["repository"]].default_branch
|
|
662
|
+
if QMessageBox.question(self, "Pull request", f"{job['repository']}\n{job['target_branch']} → {target}\n{title}\n{description}") != QMessageBox.StandardButton.Yes:
|
|
663
|
+
return
|
|
664
|
+
self.execute(lambda: self.service.create_pull_request(ident, title, description))
|
|
665
|
+
|
|
666
|
+
def login(self):
|
|
667
|
+
token, ok = QInputDialog.getText(self, self.tr_text('GitHub login', 'Вход GitHub'), self.tr_text('Fine-grained PAT → OS credential vault', 'Fine-grained PAT → защищённое хранилище ОС'),
|
|
668
|
+
QLineEdit.EchoMode.Password)
|
|
669
|
+
if ok and token:
|
|
670
|
+
if QMessageBox.question(self, "GitHub", self.tr_text("Save this token? It will replace any existing local GitHub credential.", "Сохранить этот токен? Он заменит существующий локальный токен GitHub.")) != QMessageBox.StandardButton.Yes:
|
|
671
|
+
return
|
|
672
|
+
from github_ai_mcp.security.auth_github import store_token
|
|
673
|
+
def login():
|
|
674
|
+
from github_ai_mcp.core.github_api import GitHub
|
|
675
|
+
actor = GitHub(token).request("GET", "/user")["login"]
|
|
676
|
+
store_token(token)
|
|
677
|
+
return {"github_actor": actor}
|
|
678
|
+
self.execute(login, self.dashboard_done)
|
|
679
|
+
|
|
680
|
+
def logout(self):
|
|
681
|
+
if QMessageBox.question(self, "GitHub", self.tr_text("Delete the saved local GitHub token? This does not revoke it on GitHub.", "Удалить сохранённый локальный токен GitHub? Это не отзывает его на GitHub.")) != QMessageBox.StandardButton.Yes:
|
|
682
|
+
return
|
|
683
|
+
from github_ai_mcp.security.auth_github import logout
|
|
684
|
+
def delete_token():
|
|
685
|
+
logout()
|
|
686
|
+
return {"revoke_url": "https://github.com/settings/tokens"}
|
|
687
|
+
self.execute(delete_token, lambda _: self.dashboard_done({"github_actor": "AUTH_REQUIRED"}))
|
|
688
|
+
|
|
689
|
+
def save(self):
|
|
690
|
+
try:
|
|
691
|
+
config = Config.model_validate_json(self.settings.toPlainText()) if self.advanced.isChecked() else self.service.config.model_copy(deep=True)
|
|
692
|
+
if not self.advanced.isChecked():
|
|
693
|
+
config.mode = self.mode_selector.currentText()
|
|
694
|
+
config.port = self.port_selector.value()
|
|
695
|
+
config.locale = self.language_selector.currentText()
|
|
696
|
+
if QMessageBox.question(self, self.tr_text('Trusted configuration', 'Доверенная конфигурация'), self.tr_text('Save local policy? Restart GUI/server to apply.', 'Сохранить локальную политику? Для применения перезапустите приложение.')) != QMessageBox.StandardButton.Yes:
|
|
697
|
+
return
|
|
698
|
+
save_config(self.config_path, config)
|
|
699
|
+
QMessageBox.information(self, self.tr_text('Saved', 'Сохранено'), self.tr_text('Restart GUI and server to apply configuration', 'Перезапустите приложение для применения настроек'))
|
|
700
|
+
except Exception:
|
|
701
|
+
QMessageBox.warning(self, self.tr_text('Configuration', 'Конфигурация'), self.tr_text('Invalid JSON/schema or file not writable', 'Неверный JSON, схема или файл недоступен для записи'))
|
|
702
|
+
|
|
703
|
+
def show_legal(self):
|
|
704
|
+
from github_ai_mcp.desktop.legal import legal_files
|
|
705
|
+
from github_ai_mcp.desktop.runtime import program_root
|
|
706
|
+
dialog = QDialog(self)
|
|
707
|
+
dialog.setWindowTitle(self.tr_text("GitHub-AI-MCP — Legal", "GitHub-AI-MCP — Лицензии"))
|
|
708
|
+
dialog.resize(820, 620)
|
|
709
|
+
layout = QVBoxLayout(dialog)
|
|
710
|
+
selector = QComboBox()
|
|
711
|
+
files = legal_files()
|
|
712
|
+
for path in files:
|
|
713
|
+
selector.addItem(path.relative_to(program_root()).as_posix(), str(path))
|
|
714
|
+
layout.addWidget(selector)
|
|
715
|
+
viewer = QPlainTextEdit()
|
|
716
|
+
viewer.setReadOnly(True)
|
|
717
|
+
layout.addWidget(viewer)
|
|
718
|
+
def read(index):
|
|
719
|
+
if index >= 0:
|
|
720
|
+
viewer.setPlainText(Path(selector.itemData(index)).read_text(encoding="utf-8", errors="replace"))
|
|
721
|
+
selector.currentIndexChanged.connect(read)
|
|
722
|
+
read(0)
|
|
723
|
+
close = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
|
|
724
|
+
close.button(QDialogButtonBox.StandardButton.Close).setText(self.tr_text("Close", "Закрыть"))
|
|
725
|
+
close.rejected.connect(dialog.reject)
|
|
726
|
+
layout.addWidget(close)
|
|
727
|
+
dialog.exec()
|
|
728
|
+
|
|
729
|
+
def dashboard_done(self, value):
|
|
730
|
+
if "github_actor" in value:
|
|
731
|
+
self.github_actor = value["github_actor"]
|
|
732
|
+
import time
|
|
733
|
+
self.last_github_check = time.monotonic()
|
|
734
|
+
valid = bool(self.github_actor) and self.github_actor not in {"AUTH_REQUIRED", "GITHUB_ERROR", "VAULT_UNAVAILABLE", "RETRYABLE_ERROR", "RATE_LIMITED", "PERMISSION_DENIED"}
|
|
735
|
+
note = self.tr_text("Verified account · credential from OS vault", "Аккаунт проверен · токен из защищённого хранилища ОС") if valid else self.tr_text("Account not verified; a saved token may be invalid or unavailable", "Аккаунт не проверен; сохранённый токен может быть недействителен или недоступен")
|
|
736
|
+
self.github_label.setText("GitHub: " + self.github_actor + "\n" + note)
|
|
737
|
+
if "services" in value:
|
|
738
|
+
self.render_services(value["services"])
|
|
739
|
+
|
|
740
|
+
def add_repository(self):
|
|
741
|
+
from github_ai_mcp.config import Repository
|
|
742
|
+
dialog = QDialog(self)
|
|
743
|
+
dialog.setWindowTitle(self.action_buttons["add_repository"].text())
|
|
744
|
+
form = QFormLayout(dialog)
|
|
745
|
+
fields = {}
|
|
746
|
+
for key, en, ru in [("name", "Repository owner/name", "Репозиторий владелец/имя"),
|
|
747
|
+
("source", "HTTPS URL or absolute local path", "HTTPS URL или абсолютный локальный путь"),
|
|
748
|
+
("author_name", "Authorized Git author name", "Имя автора Git"),
|
|
749
|
+
("author_email", "Authorized Git author email", "Email автора Git")]:
|
|
750
|
+
fields[key] = QLineEdit()
|
|
751
|
+
form.addRow(self.tr_text(en, ru), fields[key])
|
|
752
|
+
consent = QCheckBox(self.tr_text("I authorize this repository and author identity", "Я разрешаю доступ к репозиторию и использование указанного автора"))
|
|
753
|
+
form.addRow(consent)
|
|
754
|
+
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
|
755
|
+
buttons.button(QDialogButtonBox.StandardButton.Ok).setText(self.tr_text("Add", "Добавить"))
|
|
756
|
+
buttons.button(QDialogButtonBox.StandardButton.Cancel).setText(self.tr_text("Close dialog", "Закрыть диалог"))
|
|
757
|
+
buttons.accepted.connect(dialog.accept)
|
|
758
|
+
buttons.rejected.connect(dialog.reject)
|
|
759
|
+
form.addRow(buttons)
|
|
760
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or not consent.isChecked():
|
|
761
|
+
return
|
|
762
|
+
try:
|
|
763
|
+
name = fields["name"].text().strip()
|
|
764
|
+
if name in self.service.config.repositories:
|
|
765
|
+
raise ValueError("Repository already exists")
|
|
766
|
+
config = self.service.config.model_copy(deep=True)
|
|
767
|
+
if not fields["author_email"].text().strip():
|
|
768
|
+
raise ValueError("Explicit author email required")
|
|
769
|
+
config.repositories[name] = Repository(source=fields["source"].text().strip(),
|
|
770
|
+
author_name=fields["author_name"].text().strip(), author_email=fields["author_email"].text().strip(), identity_authorized=True)
|
|
771
|
+
config = Config.model_validate(config.model_dump())
|
|
772
|
+
save_config(self.config_path, config)
|
|
773
|
+
self.service.config = config
|
|
774
|
+
self.service.policy.config = config
|
|
775
|
+
self.settings.setPlainText(json.dumps(config.model_dump(mode="json"), ensure_ascii=False, indent=2))
|
|
776
|
+
self.repo.addItem(name)
|
|
777
|
+
self.repo.setCurrentText(name)
|
|
778
|
+
self.translate()
|
|
779
|
+
except (ValueError, OSError):
|
|
780
|
+
QMessageBox.warning(self, "GitHub-AI-MCP", self.tr_text("Invalid repository or identity, duplicate name, or configuration not writable.", "Неверный репозиторий или автор, имя уже существует либо настройки недоступны для записи."))
|
|
781
|
+
|
|
782
|
+
def safe_diagnostics(self):
|
|
783
|
+
from github_ai_mcp.desktop import startup
|
|
784
|
+
status = self.supervisor.status()
|
|
785
|
+
# No raw stderr/error text in exports; stable states and observations only.
|
|
786
|
+
services = {name: {key: value for key, value in item.items() if key != "error"}
|
|
787
|
+
for name, item in status.items()}
|
|
788
|
+
registration = startup.status(self.config_path)
|
|
789
|
+
return {"services": services, "startup": {key: value for key, value in registration.items() if key != "error"}}
|
|
790
|
+
|
|
791
|
+
def render_services(self, status):
|
|
792
|
+
previous = getattr(self, "latest_service_status", {})
|
|
793
|
+
self.latest_service_status = status
|
|
794
|
+
if self.service.config.critical_notifications and QSystemTrayIcon.isSystemTrayAvailable():
|
|
795
|
+
for name, item in status.items():
|
|
796
|
+
if item["state"] in {"Failed", "Degraded"} and previous.get(name, {}).get("state") != item["state"]:
|
|
797
|
+
self.tray.showMessage("GitHub-AI-MCP", name + ": " + item["state"], QSystemTrayIcon.MessageIcon.Warning)
|
|
798
|
+
if self.nav.currentRow() == 5 and self.advanced.isChecked():
|
|
799
|
+
self.display(status)
|
|
800
|
+
self.health_summary.setText("MCP: " + self.tr_text(status["mcp"]["state"], {"Running": "Работает", "Starting": "Запускается", "Stopped": "Остановлен", "Failed": "Ошибка"}.get(status["mcp"]["state"], status["mcp"]["state"]))
|
|
801
|
+
+ " · " + self.tr_text("Optional tunnel", "Необязательный туннель") + ": "
|
|
802
|
+
+ self.tr_text(status["tunnel"]["state"], {"Not configured": "Не настроен", "Running": "Процесс работает, подключение не проверено", "Stopped": "Остановлен", "Starting": "Запускается", "Failed": "Ошибка", "Running, connection unverified": "Процесс работает, соединение не проверено", "External process detected, ownership unverified": "Внешний процесс, не управляется", "Reconnecting": "Повторный запуск", "Degraded": "Нарушена работа"}.get(status["tunnel"]["state"], status["tunnel"]["state"])))
|
|
803
|
+
states = {"Running, connection unverified": "Процесс работает, соединение не проверено", "External process detected, ownership unverified": "Найден внешний процесс, не управляется", "Reconnecting": "Повторный запуск", "Degraded": "Нарушена работа", "Running": "Работает", "Starting": "Запускается", "Stopped": "Остановлен", "Failed": "Ошибка", "Not configured": "Не настроен"}
|
|
804
|
+
for name, label in self.service_labels.items():
|
|
805
|
+
item = status[name]
|
|
806
|
+
state = item["state"] if self.language_selector.currentText() == "en" else states.get(item["state"], item["state"])
|
|
807
|
+
detail = item.get("endpoint", item.get("profile", ""))
|
|
808
|
+
if name == "tunnel" and item["process_alive"]:
|
|
809
|
+
detail += " · " + self.tr_text("connection unverified", "соединение не подтверждено")
|
|
810
|
+
if name == "tunnel" and item.get("observations"):
|
|
811
|
+
observation = item["observations"]
|
|
812
|
+
verified = observation.get("mcp") == observation.get("control-plane") == "Recent successful observation"
|
|
813
|
+
detail += " · " + self.tr_text("recent local evidence verified" if verified else "local evidence unverified",
|
|
814
|
+
"есть свежие локальные подтверждения" if verified else "локальные подтверждения не получены")
|
|
815
|
+
error = item["error"]
|
|
816
|
+
errors = {"Service exited unexpectedly": "Процесс службы неожиданно завершился. Проверьте журнал, клиент и профиль.",
|
|
817
|
+
"Owned process is alive but authenticated health verification failed; check service logs": "Процесс работает, но защищённая проверка MCP не прошла. Проверьте журнал.",
|
|
818
|
+
"Port occupied by an external instance; this controller does not own it": "Порт занят чужим процессом. Измените порт или остановите процесс в его приложении."}
|
|
819
|
+
if self.language_selector.currentText() == "ru":
|
|
820
|
+
error = errors.get(error, error)
|
|
821
|
+
text = (f"{'MCP' if name == 'mcp' else self.tr_text('Optional tunnel', 'Необязательный туннель')}: {state} · {detail}"
|
|
822
|
+
+ ("\n" + error if error else ""))
|
|
823
|
+
if label.text() != text:
|
|
824
|
+
label.setText(text)
|
|
825
|
+
for action in ("start", "stop", "restart"):
|
|
826
|
+
button = self.service_button_names[f"{name}_{action}"]
|
|
827
|
+
enabled = not self.service_busy and (not item["process_alive"] if action == "start" else item["process_alive"] and item.get("owned", False))
|
|
828
|
+
if name == "tunnel" and item["state"] in {"Not configured", "External process detected, ownership unverified"}:
|
|
829
|
+
enabled = False
|
|
830
|
+
if button.isEnabled() != enabled:
|
|
831
|
+
button.setEnabled(enabled)
|
|
832
|
+
tip = self.tr_text(f"{action.capitalize()} the {name} service. Only owned processes are controlled.", f"Служба {name}: {button.text().lower()}. Управление только собственными процессами.")
|
|
833
|
+
if not enabled:
|
|
834
|
+
if self.service_busy:
|
|
835
|
+
tip += "\n" + self.tr_text("Wait for the service operation.", "Дождитесь операции со службой.")
|
|
836
|
+
elif item["state"] == "Not configured":
|
|
837
|
+
tip += "\n" + self.tr_text("Select the official tunnel client in setup.", "Выберите официальный клиент туннеля в настройке запуска.")
|
|
838
|
+
else:
|
|
839
|
+
tip += "\n" + self.tr_text("The service is already running." if action == "start" else "The service is stopped.", "Служба уже запущена." if action == "start" else "Служба остановлена.")
|
|
840
|
+
button.setToolTip(tip)
|
|
841
|
+
|
|
842
|
+
def service_work(self, fn, quiet=False):
|
|
843
|
+
if self.service_busy:
|
|
844
|
+
return
|
|
845
|
+
self.service_busy = True
|
|
846
|
+
if not quiet:
|
|
847
|
+
self.service_generation += 1
|
|
848
|
+
for button, _ in self.service_buttons:
|
|
849
|
+
button.setEnabled(False)
|
|
850
|
+
self.stop_all_button.setEnabled(False)
|
|
851
|
+
task = Task(fn)
|
|
852
|
+
# Separate from Git tasks; the supervisor serializes lifecycle changes.
|
|
853
|
+
self.service_task = task
|
|
854
|
+
def finish(value):
|
|
855
|
+
self.service_busy = False
|
|
856
|
+
if not quiet:
|
|
857
|
+
self.stop_all_button.setEnabled(True)
|
|
858
|
+
self.render_services(value)
|
|
859
|
+
if "github_actor" in value:
|
|
860
|
+
self.dashboard_done(value)
|
|
861
|
+
def failed(error):
|
|
862
|
+
self.service_busy = False
|
|
863
|
+
self.poll_services()
|
|
864
|
+
if not quiet:
|
|
865
|
+
QMessageBox.warning(self, "GitHub-AI-MCP", error)
|
|
866
|
+
task.signals.done.connect(finish)
|
|
867
|
+
task.signals.failed.connect(failed)
|
|
868
|
+
self.pool.start(task)
|
|
869
|
+
|
|
870
|
+
def control_service(self, action, name=None):
|
|
871
|
+
self.service_work(lambda: getattr(self.supervisor, action)(name) if name else self.supervisor.stop_all())
|
|
872
|
+
|
|
873
|
+
def poll_services(self):
|
|
874
|
+
if self.poll_busy or self.service_busy or self.exiting:
|
|
875
|
+
return
|
|
876
|
+
self.poll_busy = True
|
|
877
|
+
generation = self.service_generation
|
|
878
|
+
task = Task(self.supervisor.poll)
|
|
879
|
+
self.poll_task = task
|
|
880
|
+
def done(status):
|
|
881
|
+
self.poll_busy = False
|
|
882
|
+
if generation == self.service_generation and not self.service_busy and not self.exiting:
|
|
883
|
+
self.render_services(status)
|
|
884
|
+
def failed(error):
|
|
885
|
+
self.poll_busy = False
|
|
886
|
+
self.statusBar().showMessage(error)
|
|
887
|
+
task.signals.done.connect(done)
|
|
888
|
+
task.signals.failed.connect(failed)
|
|
889
|
+
self.pool.start(task)
|
|
890
|
+
|
|
891
|
+
def setup(self):
|
|
892
|
+
from github_ai_mcp.desktop.setup import Setup
|
|
893
|
+
self.service.config.locale = self.language_selector.currentText()
|
|
894
|
+
dialog = Setup(self.service.config, self.config_path, self.pool, self)
|
|
895
|
+
if dialog.exec() == QDialog.DialogCode.Accepted:
|
|
896
|
+
self.settings.setPlainText(json.dumps(self.service.config.model_dump(mode="json"), ensure_ascii=False, indent=2))
|
|
897
|
+
self.service_work(self.supervisor.reload_config)
|
|
898
|
+
self.translate()
|
|
899
|
+
|
|
900
|
+
def startup(self):
|
|
901
|
+
from github_ai_mcp.desktop.runtime import bundled_tool
|
|
902
|
+
if not self.service.config.setup_complete:
|
|
903
|
+
self.setup()
|
|
904
|
+
if self.service.config.setup_complete and self.service.config.autostart_services:
|
|
905
|
+
def start():
|
|
906
|
+
for name, enabled in (("mcp", self.service.config.start_mcp),
|
|
907
|
+
("tunnel", self.service.config.start_tunnel and bool(self.service.config.tunnel_client or bundled_tool("tunnel-client")))):
|
|
908
|
+
if enabled:
|
|
909
|
+
try:
|
|
910
|
+
self.supervisor.start(name)
|
|
911
|
+
except AppError:
|
|
912
|
+
pass # Each service retains its error; optional failure never crashes GUI.
|
|
913
|
+
return self.supervisor.status()
|
|
914
|
+
self.service_work(start)
|
|
915
|
+
|
|
916
|
+
def exit_application(self):
|
|
917
|
+
if self.tasks or self.service_busy or self.poll_busy:
|
|
918
|
+
QMessageBox.information(self, "GitHub-AI-MCP", self.tr_text("Wait for the current operation, then exit", "Дождитесь операции, затем закройте приложение"))
|
|
919
|
+
return
|
|
920
|
+
self.timer.stop()
|
|
921
|
+
self.exiting = True
|
|
922
|
+
self.setEnabled(False)
|
|
923
|
+
task = Task(self.supervisor.stop_all)
|
|
924
|
+
self.exit_task = task
|
|
925
|
+
def finished(_):
|
|
926
|
+
self.tray.hide()
|
|
927
|
+
self.close()
|
|
928
|
+
cast(QApplication, QApplication.instance()).quit()
|
|
929
|
+
def failed(error):
|
|
930
|
+
self.exiting = False
|
|
931
|
+
self.setEnabled(True)
|
|
932
|
+
self.timer.start()
|
|
933
|
+
QMessageBox.warning(self, "GitHub-AI-MCP", error)
|
|
934
|
+
task.signals.done.connect(finished)
|
|
935
|
+
task.signals.failed.connect(failed)
|
|
936
|
+
self.pool.start(task)
|
|
937
|
+
|
|
938
|
+
def closeEvent(self, event):
|
|
939
|
+
if self.exiting:
|
|
940
|
+
event.accept()
|
|
941
|
+
return
|
|
942
|
+
if self.service.config.background_on_close and QSystemTrayIcon.isSystemTrayAvailable():
|
|
943
|
+
self.hide()
|
|
944
|
+
event.ignore()
|
|
945
|
+
elif self.tasks or self.service_busy or self.poll_busy:
|
|
946
|
+
event.ignore()
|
|
947
|
+
self.statusBar().showMessage(self.tr_text("Wait for operation", "Дождитесь операции"))
|
|
948
|
+
else:
|
|
949
|
+
event.ignore()
|
|
950
|
+
self.exit_application()
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def run(service, config_path):
|
|
954
|
+
from github_ai_mcp.core.locking import lock
|
|
955
|
+
app = cast(QApplication, QApplication.instance() or QApplication(sys.argv))
|
|
956
|
+
app.setQuitOnLastWindowClosed(False)
|
|
957
|
+
try:
|
|
958
|
+
with lock(service.config.data_dir / "locks", "desktop-controller"):
|
|
959
|
+
window = Window(service, config_path, bootstrap=True)
|
|
960
|
+
if service.config.minimize_on_startup and QSystemTrayIcon.isSystemTrayAvailable():
|
|
961
|
+
window.hide()
|
|
962
|
+
else:
|
|
963
|
+
window.show()
|
|
964
|
+
try:
|
|
965
|
+
app.exec()
|
|
966
|
+
finally:
|
|
967
|
+
window.supervisor.stop_all()
|
|
968
|
+
except AppError as error:
|
|
969
|
+
QMessageBox.warning(None, "GitHub-AI-MCP", str(error))
|