test: allow injected desktop supervision on non-Windows

This commit is contained in:
阿白叔 committed 2026-10-14 15:56:50 +08:00
1 parent a18d4dbee6
commit 6b52aa534e
8 files changed
+798 -1769

No files matched your search

@@ -100,7 +100,7 @@ class PrivateDesktop:
self.close()
def _create(self) -> None:
if os.name != "nt":
if os.name != "nt" and self._api is None:
return
self._api = self._api or _Win32Api()
self._handle = self._api.create_desktop(self.name)
@@ -0,0 +1,102 @@
"""Task metadata and replacement-rule editing dialogs."""
from PySide6.QtWidgets import QWidget, QDialog, QLineEdit, QTextEdit, QFormLayout, QLabel, QDialogButtonBox, QCheckBox
class _TaskDialog(QDialog):
def __init__(self, parent: QWidget | None, name: str = "", note: str = "") -> None:
super().__init__(parent)
self.setWindowTitle("任务")
self.name_edit = QLineEdit(name)
self.note_edit = QTextEdit(note)
self.note_edit.setFixedHeight(70)
form = QFormLayout(self)
form.addRow("名称", self.name_edit)
form.addRow("备注", self.note_edit)
self.validation = QLabel(objectName="taskValidation")
self.validation.setStyleSheet("color: #b42318")
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
self.buttons.accepted.connect(self._accept_if_valid)
self.buttons.rejected.connect(self.reject)
form.addRow(self.validation)
form.addRow(self.buttons)
def values(self) -> tuple[str, str]:
return self.name_edit.text().strip(), self.note_edit.toPlainText().strip()
def _accept_if_valid(self) -> None:
if not self.name_edit.text().strip():
self.validation.setText("请输入任务名称。")
return
self.accept()
class _MappingDialog(QDialog):
def __init__(
self,
parent: QWidget | None,
old: str = "",
new: str = "",
enabled: bool = True,
custom_value_enabled: bool = False,
custom_value: str = "",
sync_nc: bool = True,
) -> None:
super().__init__(parent)
self.setWindowTitle("替换规则")
self.old_edit = QLineEdit(old)
self.new_edit = QLineEdit(new)
self.enabled_check = QCheckBox("启用此规则")
self.enabled_check.setChecked(enabled)
self.custom_value_check = QCheckBox("替换后写入自定义 Value")
self.custom_value_check.setChecked(custom_value_enabled)
self.custom_value_edit = QLineEdit(custom_value)
self.custom_value_edit.setPlaceholderText("输入替换后的 Value")
self.custom_value_edit.setEnabled(custom_value_enabled)
self.custom_value_check.toggled.connect(self.custom_value_edit.setEnabled)
self.sync_nc_check = QCheckBox("识别并同步原 Value 中的 /NC")
self.sync_nc_check.setChecked(sync_nc)
form = QFormLayout(self)
form.addRow("旧物料编码", self.old_edit)
form.addRow("新物料编码", self.new_edit)
form.addRow("执行状态", self.enabled_check)
form.addRow("自定义 Value", self.custom_value_check)
form.addRow("Value 内容", self.custom_value_edit)
form.addRow("NC 处理", self.sync_nc_check)
self.validation = QLabel(objectName="mappingValidation")
self.validation.setStyleSheet("color: #b42318")
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
self.buttons.accepted.connect(self._accept_if_valid)
self.buttons.rejected.connect(self.reject)
form.addRow(self.validation)
form.addRow(self.buttons)
def values(self) -> tuple[str, str, bool, bool, str, bool]:
return (
self.old_edit.text().strip(),
self.new_edit.text().strip(),
self.enabled_check.isChecked(),
self.custom_value_check.isChecked(),
self.custom_value_edit.text().strip(),
self.sync_nc_check.isChecked(),
)
def _accept_if_valid(self) -> None:
old, new, _enabled, custom_enabled, custom_value, _sync_nc = self.values()
if not old or not new:
self.validation.setText("请输入旧料号和新料号。")
return
if old.casefold() == new.casefold():
self.validation.setText("旧料号和新料号不能相同。")
return
if custom_enabled and not custom_value:
self.validation.setText("勾选自定义 Value 后请输入 Value 内容。")
return
if any(character in custom_value for character in "\t\r\n"):
self.validation.setText("自定义 Value 不能包含制表符或换行。")
return
self.accept()
@@ -0,0 +1,39 @@
"""Pure execution gates, calculated from one context without service calls."""
from dataclasses import dataclass
from ..models import TaskStatus
@dataclass(frozen=True, slots=True)
class ExecutionState:
editable: bool = False
execute: bool = False
retry: bool = False
recover: bool = False
execute_text: str = '执行当前任务'
message: str = '点击新建,在弹窗中选择工程。'
def execution_state(context, *, busy=False, dirty=False):
if context is None:
return ExecutionState()
if context.legacy:
return ExecutionState(message='历史任务仅供查看,请为工程创建独立任务。')
task = context.task
project = context.project
if not project or task.status is TaskStatus.DELETED:
return ExecutionState(message='任务已删除,可从已删除列表恢复。')
editable = task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED} and not context.has_evidence and not busy
retry = context.phase == 'retry' and not context.interrupted and not busy and not dirty
pending = bool(context.progress.next_project_path) and not context.progress.queue_complete
execute = (pending and task.status in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.RUNNING, TaskStatus.PAUSED}
and project.available and not context.interrupted and not busy and not dirty)
text = '继续当前任务' if task.status is TaskStatus.PAUSED else '执行当前任务'
message = ('结果待核验,请先恢复中断步骤。' if context.interrupted else
'位号计划有未保存编辑,请先保存。' if dirty else
'正在处理当前步骤,暂停会等待安全收尾。' if busy else
'任务已完成。' if context.progress.queue_complete and not retry else
'有失败项,可核对原因后重试。' if retry else
'工程不可用,请检查路径。' if not project.available else
'先填写旧、新料号,再采集并勾选位号。' if not pending else
'配置就绪,可执行当前任务或按顺序执行本批任务。')
return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,141 @@
"""Operator messages and log formatting shared by the desktop UI."""
from datetime import datetime
import json
ERROR_TEXT = {
"task_required": "请先选择任务。",
"directory_required": "请先选择工程目录。",
"discovery_root_locked": "旧目录已有执行记录,不能在同一任务中更换目录;请新建任务。",
"disposable_copy_required": "请确认所选工程已保存,并允许程序在执行前创建完整备份。",
"selected_project_required": "请至少选择一个可用工程。",
"enabled_rule_required": "请至少添加并启用一条替换规则。",
"active_project_exists": "已有其他工程正在处理,请等待其结束。",
"probe_baseline_missing": "未找到探测结果文件,请先在 DxDesigner 中运行只读探测。",
"profile_unchanged": "探测结果没有更新,请重新运行只读探测。",
"comparison_failed": "替换前后数据核验失败,请查看日志和错误编号。",
"rules_locked": "任务执行期间不能修改替换规则。",
"task_running": "请先暂停任务,再删除任务。",
"task_not_deleted": "只有“已删除”中的任务可以彻底删除;任务状态可能已变化,请刷新后重试。",
"permanent_delete_confirmation": "彻底删除需要明确确认,此操作不能通过“恢复”撤销。",
"quick_run_pending": "检测到可能已改动图纸的旧替换任务,请先核对工程后再继续。",
"quick_run_status": "执行状态文件无效,已拒绝覆盖,请查看日志。",
"quick_run_execution": "当前替换步骤失败,图页可能已被修改,请查看具体原因和执行证据。",
"quick_run_rollback_verified": "替换校验失败,但原生回滚已验证,工程已恢复到替换前状态;请排除原因后重新确认。",
"quick_run_preflight": "当前项在替换前校验失败,未调用原生替换;后续项已停止。请核对目标料号及库配置,排除原因后再确认继续。",
"quick_run_session": "本次执行在启动或工程检查阶段停止,尚未开始本项替换。请按具体原因处理后重试。",
"quick_run_complete": "当前任务中的替换规则已经全部完成。",
"quick_run_cscript": "未找到 Windows 脚本运行组件,无法连接 DxDesigner。",
"quick_run_command": "替换命令文件无效,请查看日志。",
"quick_run_uncertain": "无法确认本次替换结果,请使用“核验并恢复中断任务”,不要直接清锁重跑。",
"quick_run_recovery": "中断任务恢复未通过,原保护状态仍保留。",
"quick_run_recovery_confirmation": "请先确认核验恢复范围。",
"quick_run_busy": "已有替换操作正在执行,请等待当前操作结束。",
"quick_run_manual_operation": "此任务使用自动队列,不能混用人工流程的跳过、采集和重试操作。",
"quick_run_task_state": "当前任务状态不允许执行自动队列,请先恢复任务或检查其状态。",
"quick_run_backup": "本项工程精简备份未通过,队列已停止,尚未开始本项替换。可排除原因后重试,或使用“忽略备份失败并继续”。",
"quick_run_queue_progress": "队列进度异常,已停止自动继续。",
"quick_run_options_locked": "已有自动队列证据,工程目录、工程选择及规则选项已冻结;请先完成或恢复当前队列。",
"quick_run_selection_changed": "待执行工程、规则或 Value 选项发生变化,请重新确认。",
"evidence_missing": "没有找到当前任务的执行证据。",
"duplicate_source": "同一旧料号只能配置一次。",
"mapping_chain": "替换规则不能形成连续替换链。",
"mapping_cycle": "替换规则不能形成循环。",
"equal_rule": "旧料号和新料号不能相同。",
"blank_part_number": "旧料号和新料号不能为空。",
"custom_value": "勾选自定义 Value 后必须填写内容,且不能包含制表符或换行。",
"task_name": "任务名称为空或已经存在。",
}
DIALOG_ERROR_TEXT = {
"duplicate_source": "该旧料号已经存在,请修改现有规则或输入其他旧料号。",
"mapping_chain": "目标料号同时是另一条规则的旧料号,请拆分任务后再执行。",
"mapping_cycle": "这些规则形成了循环,请修改旧料号或新料号。",
"equal_rule": "旧料号和新料号不能相同。",
"blank_part_number": "请输入旧料号和新料号。",
"custom_value": "勾选自定义 Value 后必须填写内容,且不能包含制表符或换行。",
"task_name": "任务名称为空或已经存在,请使用其他名称。",
}
def _nc_sync_log_lines(message: str) -> tuple[str, ...]:
_, marker, details = str(message).partition("NC synced:")
if not marker:
return ()
suffix = " (detected /NC and synchronized)"
return tuple(
f"位号 {entry.removesuffix(suffix).strip()},识别到 NC,已同步"
for entry in details.strip().split("; ")
if entry.strip()
)
def _format_task_log_lines(lines: tuple[str, ...]) -> tuple[str, ...]:
return tuple(_format_task_log_line(line) for line in lines)
def _format_task_log_line(line: str) -> str:
try:
event = json.loads(line)
except (json.JSONDecodeError, TypeError):
return _aligned_log_line("", "INFO", "legacy", str(line))
if not isinstance(event, dict):
return _aligned_log_line("", "INFO", "legacy", str(line))
timestamp = str(event.get("timestamp_utc") or "").replace("T", " ").removesuffix("Z")[:19]
level = str(event.get("level") or "INFO").upper()
if level not in {"INFO", "WARNING", "ERROR"}:
level = "INFO"
operation = str(event.get("operation") or "")
details = event.get("details") if isinstance(event.get("details"), dict) else {}
message = str(event.get("message") or "").strip()
if operation == "value_policy_changed":
enabled = bool(
details.get(
"copy_part_label_to_value",
details.get("copy_part_number_to_value", False),
)
)
message = (
"Value 选项已更新:替换后写入目标 Part Label。"
if enabled
else "Value 选项已更新:保留原生替换后的 Value。"
)
elif operation == "quick_run_prepared":
message = "自动替换运行环境已准备。"
elif operation == "quick_run_executed" and details.get("state") == "no_match":
message = "当前规则在该图页未命中,已正常跳过。"
elif operation == "quick_run_queue_paused":
message = "自动队列已在项目边界暂停。"
elif operation == "confirm_native_attempt":
message = "已确认原生替换操作。"
elif not message:
message = operation.replace("_", " ") or "任务状态已更新。"
error_id = str(event.get("error_id") or "").strip()
if error_id:
message = f"{message} 错误编号:{error_id}"
return _aligned_log_line(timestamp, level, operation or "task", message)
def _format_live_log_line(line: str) -> str:
message = str(line)
level = "ERROR" if message.startswith("错误") else "WARNING" if message.startswith(("失败", "警告")) else "INFO"
return _aligned_log_line(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), level, "ui", message)
def _aligned_log_line(timestamp: str, level: str, operation: str, message: str) -> str:
return (
f"{_fit_log_column(timestamp, 19)} | "
f"{_fit_log_column(level, 7)} | "
f"{_fit_log_column(operation, 28)} | {message}"
)
def _fit_log_column(value: str, width: int) -> str:
text = str(value)
if len(text) <= width:
return text.ljust(width)
return f"{text[: width - 3]}..."
@@ -0,0 +1,42 @@
"""Read-only identity and result of the task's single bound project."""
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget
class ProjectSummary(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.name = QLabel('未选择任务')
self.path = QLabel(objectName='boundProjectPath')
self.path.setWordWrap(True)
self.path.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.state = QLabel()
self.state.setWordWrap(True)
self.refresh_button = QPushButton('重新读取工程', objectName='refreshBoundProject')
heading = QHBoxLayout()
heading.addWidget(self.name, 1)
heading.addWidget(self.refresh_button)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addLayout(heading)
layout.addWidget(self.path)
layout.addWidget(self.state)
def populate(self, context):
if context is None:
self.name.setText('未选择任务')
self.path.clear()
self.state.setText('点击新建,在弹窗中读取并选择工程。')
return
project = context.project
self.name.setText(project.display_name if project else context.task.name)
self.path.setText(str(project.path) if project else '')
if context.legacy:
self.state.setText('历史任务仅供查看;请通过新建弹窗为工程创建独立任务。')
elif not project.available:
self.state.setText('工程不可用,请检查原路径后重新读取。')
else:
labels = {'draft': '待配置', 'ready': '待执行', 'running': '执行中', 'paused': '已暂停',
'completed': '已完成', 'failed': '失败', 'deleted': '已删除'}
self.state.setText(f'工程已绑定 · {labels.get(context.task.status.value, context.task.status.value)}'
+ (f' · {project.summary}' if project.summary else ''))
@@ -1,71 +1,48 @@
"""Operator guidance, commands, and read-only task log widgets."""
from __future__ import annotations
from PySide6.QtWidgets import QCheckBox, QHBoxLayout, QLabel, QProgressBar, QPushButton, QTextEdit, QToolButton, QVBoxLayout, QWidget
"""Explicit single-task execution, recovery and safe pause controls."""
from PySide6.QtWidgets import (QCheckBox, QHBoxLayout, QLabel, QProgressBar,
QPushButton, QTextEdit, QToolButton, QVBoxLayout, QWidget)
class RunPanel(QWidget):
def __init__(self) -> None:
def __init__(self):
super().__init__()
self.operator_band = QLabel("请选择任务,并扫描工程目录。", objectName="operatorBand")
self.operator_band.setWordWrap(True)
self.queue_summary = QLabel("未选择任务", objectName="queueSummary")
self.execution_status = QLabel("空闲", objectName="executionStatus")
self.queue_summary = QLabel('未选择任务', objectName='queueSummary')
self.execution_status = QLabel('空闲', objectName='executionStatus')
self.execution_status.setWordWrap(True)
self.busy_indicator = QProgressBar(objectName="quickRunBusyIndicator")
self.operator_band = QLabel(objectName='operatorBand')
self.operator_band.setWordWrap(True)
self.busy_indicator = QProgressBar(objectName='quickRunBusyIndicator')
self.busy_indicator.setRange(0, 0)
self.busy_indicator.setTextVisible(False)
self.busy_indicator.setFixedHeight(4)
self.busy_indicator.hide()
self.start_button = QPushButton("开始任务", objectName="startTaskButton")
self.quick_run_button = QPushButton("确认并执行替换", objectName="quickRunButton")
self.stop_queue_button = QPushButton("完成当前项后暂停", objectName="stopQueueButton")
self.stop_queue_button.hide()
self.continue_without_backup_button = QPushButton(
"忽略备份失败并继续", objectName="continueWithoutBackupButton"
)
self.continue_without_backup_button.setToolTip(
"仅在精简原理图备份失败后启用。继续执行将无法保证该工程可从本工具备份回滚。"
)
self.continue_without_backup_button.hide()
self.recover_button = QPushButton("核验并恢复中断任务", objectName="recoverQuickRunButton")
self.recover_button.setToolTip("先备份并核验已保存工程;不重复调用原生替换。混合状态或连接异常时保留保护。")
self.pause_button = QPushButton("暂停", objectName="pauseTaskButton")
self.resume_button = QPushButton("继续", objectName="resumeTaskButton")
self.capture_before_button = QPushButton("采集替换前结果", objectName="captureBeforeButton")
self.confirm_attempt_button = QPushButton("已完成原生替换", objectName="confirmNativeAttemptButton")
self.capture_after_button = QPushButton("采集替换后结果", objectName="captureAfterButton")
self.copy_value_check = QCheckBox("替换后将 Part Label 写入 Value", objectName="copyPartNumberToValue")
self.copy_value_check.setToolTip("勾选:将替换后目标器件的 Part Label 写入 Value。未勾选:保留原生替换后的 Value,不创建缺失字段。两种模式均继承已有 Value 的位置、字体等显示样式。队列生成后不可更改。")
self.toggle_log_button = QToolButton(objectName="toggleLogButton")
self.toggle_log_button.setText("显示日志")
self.quick_run_button = QPushButton('执行当前任务', objectName='quickRunButton')
self.stop_queue_button = QPushButton('完成当前项后暂停', objectName='stopQueueButton')
self.retry_button = QPushButton('重试失败项', objectName='retryTaskItems')
self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton')
self.copy_value_check = QCheckBox('替换后将 Part Label 写入 Value', objectName='copyPartNumberToValue')
self.copy_value_check.setToolTip('每行自定义 Value 优先;同步 NC 由每行开关控制。开始执行后选项冻结。')
self.toggle_log_button = QToolButton(objectName='toggleLogButton')
self.toggle_log_button.setText('显示日志')
self.toggle_log_button.setCheckable(True)
self.reset_layout_button = QToolButton(objectName="resetLayoutButton")
self.reset_layout_button.setText("重置布局")
self.log_view = QTextEdit(objectName="logView")
self.reset_layout_button = QToolButton(objectName='resetLayoutButton')
self.reset_layout_button.setText('重置布局')
self.log_view = QTextEdit(objectName='logView')
self.log_view.setReadOnly(True)
self.log_view.setMinimumHeight(40)
self.log_view.setMinimumHeight(60)
self.log_view.hide()
self.toggle_log_button.toggled.connect(self.log_view.setVisible)
self.toggle_log_button.toggled.connect(lambda checked: self.toggle_log_button.setText("收起日志" if checked else "显示日志"))
commands = QHBoxLayout()
for button in (
self.quick_run_button,
self.stop_queue_button,
self.continue_without_backup_button,
self.recover_button,
):
commands.addWidget(button)
commands.addStretch(1)
commands.addWidget(self.toggle_log_button)
commands.addWidget(self.reset_layout_button)
self.toggle_log_button.toggled.connect(lambda on: self.toggle_log_button.setText('收起日志' if on else '显示日志'))
buttons = QHBoxLayout()
for button in (self.quick_run_button, self.retry_button, self.recover_button, self.stop_queue_button):
buttons.addWidget(button)
buttons.addStretch()
buttons.addWidget(self.toggle_log_button)
buttons.addWidget(self.reset_layout_button)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.queue_summary)
layout.addWidget(self.execution_status)
layout.addWidget(self.busy_indicator)
layout.addWidget(self.operator_band)
layout.addWidget(self.copy_value_check)
layout.addLayout(commands)
for widget in (self.queue_summary, self.execution_status, self.busy_indicator,
self.operator_band, self.copy_value_check):
layout.addWidget(widget)
layout.addLayout(buttons)
layout.addWidget(self.log_view, 1)
+33 -1
View File
@@ -61,7 +61,7 @@ def test_original_window_edits_target_plan_and_nc_without_export(qtbot, tmp_path
rows = service.target_plan(task.task_id)
assert rows[0].enabled and not rows[0].sync_nc and not rows[1].enabled
assert not table.dirty
assert not window.directory_path.isEnabled()
assert window.findChild(type(window.plan_panel.find_text), 'directoryPath') is None
assert window.run_panel.quick_run_button.isEnabled()
assert not (tmp_path / 'plan.xlsx').exists()
# Switching tasks must not conceal an unsaved draft from group execution.
@@ -70,3 +70,35 @@ def test_original_window_edits_target_plan_and_nc_without_export(qtbot, tmp_path
assert window.plan_panel.has_unsaved_plan((task.task_id,))
window.close()
store.close()
def test_single_project_summary_and_local_gates_do_not_query_service_again(qtbot, tmp_path, monkeypatch):
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
from PySide6.QtWidgets import QPushButton, QTableWidget
root = tmp_path / 'projects'
root.mkdir()
path = root / 'board.prj'
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='ascii')
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_project_tasks(root)[0]
service.add_rule(task.task_id, 'OLD', 'NEW')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
assert window.findChild(QTableWidget, 'projectTable') is None
for name in ('scanProjectsButton', 'selectAllProjectsButton', 'clearProjectsButton',
'retryProjectButton', 'skipProjectButton', 'startTaskButton'):
assert window.findChild(QPushButton, name) is None
assert window.project_summary.path.text() == str(path)
assert window.run_panel.quick_run_button.text() == '执行当前任务'
monkeypatch.setattr(service, 'get_task', lambda *a: (_ for _ in ()).throw(AssertionError('extra DB read')))
monkeypatch.setattr(service, 'projects', lambda *a: (_ for _ in ()).throw(AssertionError('extra DB read')))
window._update_gates()
assert window.run_panel.quick_run_button.isEnabled()
window.close()
store.close()