feat: show persisted per-reference replacement details in task logs
This commit is contained in:
1 parent
10581df3e2
commit
20d8b81a34
6 files changed
+191
-23
No files matched your search
@@ -13,6 +13,12 @@ V1.1.0 沿用原有任务视图和料号规则编辑,增加按工程拆分的
|
||||
|
||||
执行状态、失败重试和中断核验集中在底部操作区。界面不再维护当前任务的工程选择列表,避免工程范围和按钮范围混淆。
|
||||
|
||||
## 执行日志与修改明细
|
||||
|
||||
任务执行结束或暂停后,底部自动展开日志。每个完成步骤按位号列出旧、新物料号,例如:`图页 MAIN:1 · 已保存并核验 · 位号 R1:4100-CA0000-T7 → 4100-CA0000-T0`;识别到 NC 并同步时另列说明。未命中、失败和保存后待核验分别显示状态,不计为成功修改。
|
||||
|
||||
明细来自执行器实际回读结果,不以勾选计划代替执行结果。同一工程的不同图页、规则分别保留记录;重新打开已完成任务会自动显示其日志。运行时显示最近 100 条事件,结束后显示所有保留的事件(包括轮转日志)。历史版本未记录的中间步骤无法事后补全。
|
||||
|
||||
## 可选 Excel 操作
|
||||
|
||||
无需导出也能完成全部编辑。需要在 Excel 中操作时,可导出完整位号计划,或点击“BOM 模板”生成更适合物料工程师编辑的 BOM 表。BOM 一行可以填写多个位号(逗号、分号、空格或顿号分隔),并填写旧料号、新料号、替换开关、Value 和同步 NC。
|
||||
|
||||
@@ -283,23 +283,24 @@ def execute_batch(
|
||||
if updated.completed_items <= progress.completed_items or updated.total_items != progress.total_items:
|
||||
_write_uncertain_flag(preparer._data_root / 'quick-run/uncertain.flag', 'batch_progress_mismatch')
|
||||
raise TaskCenterError('quick_run_queue_progress', '执行器返回后队列进度异常,已停止,避免重复执行。')
|
||||
if project_completed or updated.queue_complete or last_result.state in {
|
||||
# Keep every verified step: one project can contain many sheets and rules.
|
||||
project_id = next(
|
||||
(project.project_id for project in projects if _path_key(project.path) == _path_key(current)),
|
||||
None,
|
||||
)
|
||||
event_level = 'WARNING' if last_result.state in {
|
||||
BATCH_FAILED_STATE,
|
||||
BATCH_SAVED_UNVERIFIED_STATE,
|
||||
}:
|
||||
project_id = next(
|
||||
(project.project_id for project in projects if _path_key(project.path) == _path_key(current)),
|
||||
None,
|
||||
)
|
||||
event_level = 'WARNING' if last_result.state in {
|
||||
BATCH_FAILED_STATE,
|
||||
BATCH_SAVED_UNVERIFIED_STATE,
|
||||
} else 'INFO'
|
||||
append_task_event(service._logging, level=event_level,
|
||||
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
|
||||
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
|
||||
'completed_items': updated.completed_items, 'total_items': updated.total_items,
|
||||
'completed_projects': len(updated.completed_project_paths)})
|
||||
} else 'INFO'
|
||||
append_task_event(service._logging, level=event_level,
|
||||
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
|
||||
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
|
||||
'project_path': str(current),
|
||||
'schematic_name': progress.next_schematic_name,
|
||||
'sheet_number': progress.next_sheet_number,
|
||||
'old_part_number': expected[1], 'new_part_number': expected[2],
|
||||
'completed_items': updated.completed_items, 'total_items': updated.total_items,
|
||||
'completed_projects': len(updated.completed_project_paths)})
|
||||
service._logging.logger.info('quick_run_batch_item task_id=%s state=%s completed=%s total=%s',
|
||||
task_id, last_result.state, updated.completed_items, updated.total_items)
|
||||
progress = updated
|
||||
|
||||
@@ -11,7 +11,7 @@ import threading
|
||||
from typing import TypeVar
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .logging_setup import LoggingContext, _tail_utf8_lines, append_task_event
|
||||
from .logging_setup import LoggingContext, _EVENT_BACKUP_COUNT, _tail_utf8_lines, append_task_event
|
||||
from .models import ProjectRecord, ProjectStatus, RuleRecord, TaskRecord, TaskStatus
|
||||
from .quick_run import QuickRunPreparer, QuickRunProgress, QuickRunResult, QuickRunStepResult, _path_key
|
||||
from .runner import OperatorInstruction, RunnerSnapshot, TrialRunner
|
||||
@@ -793,11 +793,19 @@ class TaskCenterService:
|
||||
evidence = preparer.evidence_path(task_id)
|
||||
return evidence == preparer._data_root / "quick-run"
|
||||
|
||||
def tail_log(self, task_id: str, *, limit: int = 100) -> tuple[str, ...]:
|
||||
if limit < 1:
|
||||
def tail_log(self, task_id: str, *, limit: int | None = 100) -> tuple[str, ...]:
|
||||
if limit is not None and limit < 1:
|
||||
raise TaskCenterError("log_limit", "log line limit must be positive")
|
||||
self._store.get_task(task_id)
|
||||
path = self._logging.root / "tasks" / task_id / "events.jsonl"
|
||||
try:
|
||||
if limit is None:
|
||||
# Completed tasks show all retained steps, including rotated logs.
|
||||
with self._logging._event_lock:
|
||||
paths = [path.with_name(f'{path.name}.{i}') for i in range(_EVENT_BACKUP_COUNT, 0, -1)]
|
||||
paths.append(path)
|
||||
return tuple(line for source in paths if source.exists()
|
||||
for line in source.read_text(encoding='utf-8').splitlines())
|
||||
return _tail_utf8_lines(path, limit) if path.exists() else ()
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise TaskCenterError("log_read", "cannot read task event log") from error
|
||||
|
||||
@@ -12,7 +12,7 @@ from ..version import VERSION
|
||||
from .dialogs import _TaskDialog, _MappingDialog
|
||||
from .execution_state import execution_state
|
||||
from .mapping_table import MappingTable
|
||||
from .messages import ERROR_TEXT, DIALOG_ERROR_TEXT, _format_live_log_line, _format_task_log_lines, _nc_sync_log_lines
|
||||
from .messages import ERROR_TEXT, DIALOG_ERROR_TEXT, _format_live_log_line, _format_task_log_lines
|
||||
from .project_plan import DirectoryTaskDialog, ProjectPlanPanel
|
||||
from .project_summary import ProjectSummary
|
||||
from .run_panel import RunPanel
|
||||
@@ -157,7 +157,11 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
return
|
||||
self._task_id = task_id
|
||||
self._message = ''
|
||||
self._live_log_text = None
|
||||
self.run_panel.log_view.clear()
|
||||
self._load_task_data()
|
||||
if self._context and (self._context.progress.saved_items or self._context.phase in {'complete', 'retry'}):
|
||||
self._show_task_log()
|
||||
|
||||
def _load_task_data(self):
|
||||
try:
|
||||
@@ -376,6 +380,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._finish_run()
|
||||
self._metadata_changed(None)
|
||||
failures = sum(e.state in {'failed', 'blocked'} for e in result.entries)
|
||||
self._show_task_log()
|
||||
self._set_operator_message(f'本批任务已暂停。失败/阻断 {failures} 项。' if result.paused else f'本批任务已结束。失败 {failures} 项。',
|
||||
'warning' if result.paused or failures else 'success')
|
||||
self._run_async(lambda: execute_task_queue(self.service, ids, stop_event=stop, queue_id=token), done,
|
||||
@@ -406,9 +411,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
def _show_batch_result(self, result):
|
||||
self._finish_run()
|
||||
self._metadata_changed(None)
|
||||
for item in result.item_messages:
|
||||
for line in _nc_sync_log_lines(item) or (item,):
|
||||
self._append_log(line)
|
||||
self._show_task_log()
|
||||
p = result.progress
|
||||
self._set_operator_message(f"{'任务已暂停' if result.paused else '当前任务已结束'}:已保存 {p.saved_items},失败 {p.failed_items},未命中 {p.no_match_items}。",
|
||||
'warning' if result.paused or p.failed_items else 'success')
|
||||
@@ -468,10 +471,18 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
return
|
||||
task_id = self._active_quick_run_task_id or self._task_id
|
||||
if task_id:
|
||||
text = '\n'.join(_format_task_log_lines(self.service.tail_log(task_id)))
|
||||
limit = 100 if self._active_quick_run_task_id else None
|
||||
text = '\n'.join(_format_task_log_lines(self.service.tail_log(task_id, limit=limit)))
|
||||
if text != self._live_log_text:
|
||||
self.run_panel.log_view.setPlainText(text)
|
||||
self._live_log_text = text
|
||||
else:
|
||||
self.run_panel.log_view.clear()
|
||||
self._live_log_text = None
|
||||
|
||||
def _show_task_log(self):
|
||||
self.run_panel.toggle_log_button.setChecked(True)
|
||||
self._refresh_live_task_log()
|
||||
|
||||
def _append_log(self, line):
|
||||
self.run_panel.log_view.append(_format_live_log_line(line))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Operator messages and log formatting shared by the desktop UI."""
|
||||
from datetime import datetime
|
||||
import json
|
||||
import re
|
||||
|
||||
ERROR_TEXT = {
|
||||
"task_required": "请先选择任务。",
|
||||
@@ -69,6 +70,26 @@ def _nc_sync_log_lines(message: str) -> tuple[str, ...]:
|
||||
)
|
||||
|
||||
|
||||
def _replacement_log_lines(message: str, state: str) -> tuple[str, ...]:
|
||||
"""Render native readback results; never turn a plan or failed step into success."""
|
||||
if state not in {'saved_ok', 'restored_ok'}:
|
||||
return ()
|
||||
_, marker, summary = message.partition('Replacements:')
|
||||
if not marker:
|
||||
return ()
|
||||
for suffix in (' Display verified:', ' NC synced:', ' Saved, reopened'):
|
||||
summary = summary.partition(suffix)[0]
|
||||
status = '已保存并核验' if state == 'saved_ok' else '已替换并回读,尚未确认保存'
|
||||
lines = []
|
||||
for entry in summary.strip().split('; '):
|
||||
match = re.fullmatch(r'(\S+) (.+?) -> (.+)', entry.strip())
|
||||
if not match:
|
||||
return () # Preserve unfamiliar native output verbatim for diagnosis.
|
||||
refdes, old, new = match.groups()
|
||||
lines.append(f'{status} · 位号 {refdes}:{old} → {new}')
|
||||
return tuple(lines)
|
||||
|
||||
|
||||
def _format_task_log_lines(lines: tuple[str, ...]) -> tuple[str, ...]:
|
||||
return tuple(_format_task_log_line(line) for line in lines)
|
||||
|
||||
@@ -105,6 +126,18 @@ def _format_task_log_line(line: str) -> str:
|
||||
message = "自动替换运行环境已准备。"
|
||||
elif operation == "quick_run_executed" and details.get("state") == "no_match":
|
||||
message = "当前规则在该图页未命中,已正常跳过。"
|
||||
elif operation == "quick_run_executed":
|
||||
state = details.get('state')
|
||||
replacements = _replacement_log_lines(message, state)
|
||||
if replacements:
|
||||
location = ':'.join(str(details[key]) for key in ('schematic_name', 'sheet_number')
|
||||
if details.get(key))
|
||||
prefix = f'图页 {location} · ' if location else ''
|
||||
message = '\n'.join(prefix + entry for entry in (*replacements, *_nc_sync_log_lines(message)))
|
||||
elif state == 'batch_saved_unverified':
|
||||
message = f'已保存但核验未通过,修改结果待确认。{message}'
|
||||
elif state in {'batch_failed', 'hard_failure'}:
|
||||
message = f'本步骤失败,未计入成功修改。{message}'
|
||||
elif operation == "quick_run_queue_paused":
|
||||
message = "自动队列已在项目边界暂停。"
|
||||
elif operation == "confirm_native_attempt":
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
from dx_productivity.trial_task_center.ui.messages import _format_task_log_lines
|
||||
|
||||
|
||||
def replacement_message(ref, old='OLD', new='NEW'):
|
||||
return (f'Native replacement and parameter readback passed on current sheet. '
|
||||
f'Replacements: {ref} {old} -> {new} Display verified: attributes=3. '
|
||||
'Saved, reopened for readback, and closed.')
|
||||
|
||||
|
||||
def test_completed_log_lists_each_refdes_and_does_not_claim_unverified_success():
|
||||
def event(state, message):
|
||||
return json.dumps({'operation': 'quick_run_executed', 'message': message,
|
||||
'details': {'state': state, 'schematic_name': 'MAIN', 'sheet_number': '2'}})
|
||||
|
||||
# Use the actual native grammar: each RefDes has its own old/new pair.
|
||||
text = '\n'.join(_format_task_log_lines((event('saved_ok', replacement_message('R1')
|
||||
.replace('R1 OLD -> NEW', 'R1 OLD -> NEW; R2 OLD -> NEW')),)))
|
||||
assert '位号 R1:OLD → NEW' in text
|
||||
assert '位号 R2:OLD → NEW' in text
|
||||
assert '已保存并核验' in text and 'MAIN:2' in text
|
||||
for state in ('batch_failed', 'batch_saved_unverified', 'hard_failure', 'no_match'):
|
||||
text = '\n'.join(_format_task_log_lines((event(state, replacement_message('R1')),)))
|
||||
assert '已保存并核验' not in text
|
||||
text = '\n'.join(_format_task_log_lines((event('restored_ok', replacement_message('R1')),)))
|
||||
assert '尚未确认保存' in text and '已保存并核验' not in text
|
||||
|
||||
|
||||
def test_all_steps_survive_reopening_completed_task(qtbot, tmp_path):
|
||||
root = tmp_path / 'project'; root.mkdir()
|
||||
path = root / 'board.prj'
|
||||
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
data = tmp_path / 'data'
|
||||
calls = []
|
||||
|
||||
def worker(command, timeout):
|
||||
evidence = Path(command[3])
|
||||
job = command[-1]
|
||||
index = len(calls)
|
||||
calls.append(job)
|
||||
old, new, ref = (('OLD', 'NEW', 'R1'), ('OLD2', 'NEW2', 'C2'))[index]
|
||||
with (evidence / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\tawaiting_native_replace\t\tcaptured\n')
|
||||
stream.write(f'{job}\tsaved_ok\tbatch_closed\t{replacement_message(ref, old, new)}\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
preparer = QuickRunPreparer(data, process_runner=worker,
|
||||
cscript_resolver=lambda: Path('cscript.exe'), sheet_discoverer=lambda _: (('MAIN', '1'),))
|
||||
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer)
|
||||
task = service.create_project_tasks(root)[0]
|
||||
service.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
service.add_rule(task.task_id, 'OLD2', 'NEW2')
|
||||
window = TrialTaskCenterWindow(service); qtbot.addWidget(window)
|
||||
window.open_task(task.task_id)
|
||||
assert not window.run_panel.toggle_log_button.isChecked()
|
||||
progress = service.quick_run_progress(task.task_id)
|
||||
result = service.execute_quick_run_queue(task.task_id,
|
||||
expected_item=(str(progress.next_project_path), 'OLD', 'NEW', 'preserve'), stop_event=Event())
|
||||
assert result.progress.queue_complete and len(calls) == 2
|
||||
window._show_batch_result(result)
|
||||
assert window.run_panel.toggle_log_button.isChecked()
|
||||
assert window.run_panel.log_view.toPlainText().count('位号 R1:OLD → NEW') == 1
|
||||
window.close(); store.close()
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(data))
|
||||
window = TrialTaskCenterWindow(service); qtbot.addWidget(window)
|
||||
window.open_task(task.task_id)
|
||||
assert window.run_panel.toggle_log_button.isChecked()
|
||||
text = window.run_panel.log_view.toPlainText()
|
||||
assert '位号 R1:OLD → NEW' in text
|
||||
assert '位号 C2:OLD2 → NEW2' in text
|
||||
# Switching to a draft clears the previous task's modification details.
|
||||
other = service.create_task('another')
|
||||
window.open_task(other.task_id)
|
||||
assert '位号 R1' not in window.run_panel.log_view.toPlainText()
|
||||
window.close(); store.close()
|
||||
|
||||
|
||||
def test_completed_task_log_keeps_more_than_100_steps_and_rotated_entries(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
task = service.create_task('long task')
|
||||
log = tmp_path / 'data' / 'tasks' / task.task_id / 'events.jsonl'
|
||||
log.parent.mkdir(parents=True, exist_ok=True)
|
||||
first = json.dumps({'operation': 'quick_run_executed', 'details': {'state': 'saved_ok'},
|
||||
'message': replacement_message('R0')})
|
||||
log.with_name(log.name + '.1').write_text(first + '\n', encoding='utf-8')
|
||||
log.write_text('\n'.join(json.dumps({'operation': 'quick_run_executed',
|
||||
'details': {'state': 'saved_ok'}, 'message': replacement_message(f'R{i}')})
|
||||
for i in range(1, 106)) + '\n', encoding='utf-8')
|
||||
assert len(service.tail_log(task.task_id)) == 100
|
||||
full = service.tail_log(task.task_id, limit=None)
|
||||
assert len(full) == 106
|
||||
assert '位号 R0:OLD → NEW' in _format_task_log_lines(full)[0]
|
||||
assert '位号 R105:OLD → NEW' in _format_task_log_lines(full)[-1]
|
||||
store.close()
|
||||
Reference in new issue
Block a user