merge: preserve DSH lifecycle while syncing target branch

This commit is contained in:
阿白叔 committed 2026-10-31 14:48:59 +08:00
commit d3bdff81e5
70 files changed
+3030 -201

No files matched your search

@@ -101,6 +101,9 @@ class BatchCadRuntime:
self._project_attempts = {}
self._logging = None
self._active_evidence = None
self._active_attempts = []
self._close_failure = None
self._close_failure_rebuild = False
def bind_logs(self, context, task_ids):
"""Keep every participating task's final release outcome visible."""
@@ -119,7 +122,10 @@ class BatchCadRuntime:
def __exit__(self, error_type, error, traceback):
if error is not None and self._active_evidence is not None:
attempts = [item for values in self._project_attempts.values() for item in values]
# Only the current generation can still own an in-flight CAD write.
# Earlier projects retain audit evidence but their closed checkpoint
# proves that they no longer need the live CAD/desktop wait.
attempts = list(self._active_attempts)
try:
self._retain_uncertain(self._active_evidence, None, attempts, error)
except WorkerMonitorError:
@@ -252,6 +258,7 @@ class BatchCadRuntime:
'session_id': self.session_id, 'generation': self.generation, 'attempt_id': attempt_id,
'evidence_root': str(root), 'project_path': str(project), 'project_closed': True,
'worker_closed': True, 'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid']})
self._active_attempts = []
def run_worker(self, command, timeout, *, abort_event=None, cooperative_abort=False):
from .discovery_cache import project_fingerprint
@@ -270,7 +277,12 @@ class BatchCadRuntime:
self._save()
generation = self.generation + (self.desktop is None)
project, directory, expected = self._prepare_attempts(root, command, attempt_id, generation)
self._active_attempts = list(expected)
self._ensure_desktop(abort_event)
# Make the current task/attempt durable before any worker or CAD
# mutation can begin. A crash in the following window must protect
# this task rather than a stale completed task from session.json.
self._save(active_task=self.record['active_task'], active_attempt=attempt_id)
before = project_fingerprint(project, self.root)
status = internal_path(root / 'status.tsv')
status_before = status.read_bytes() if status.exists() else None
@@ -381,13 +393,22 @@ class BatchCadRuntime:
if self.record['state'] == 'released':
return
reason = reason or ('rebuild' if rebuilding else 'batch_end')
if self._close_failure is not None and self._close_failure_rebuild and reason != 'manual_retry':
raise BatchResourceCleanupError(str(self._close_failure), completed_result=self.result,
cleanup_error=self._close_failure)
if reason == 'manual_retry':
self._close_failure = None
started = time.monotonic()
self._release_log('started', reason=reason)
try:
self._close_resources(rebuilding=rebuilding)
except Exception as error:
self._close_failure = error
self._close_failure_rebuild = rebuilding
self._release_log('failed', reason=reason, elapsed=time.monotonic() - started, error=error)
raise
self._close_failure = None
self._close_failure_rebuild = False
self._release_log('succeeded', reason=reason, elapsed=time.monotonic() - started)
def _close_resources(self, *, rebuilding=False):
@@ -404,8 +425,10 @@ class BatchCadRuntime:
except Exception as error:
if rebuilding:
self.record['shutdown_warning'] = str(error)
else:
errors.append(str(error))
# A rebuild must not proceed while the previous CAD owner has
# an unconfirmed shutdown. Keep the warning for diagnostics,
# but retain the failure in the resource gate as well.
errors.append(str(error))
finally:
cad_record = getattr(cad, 'record', {})
cad_record = cad_record if isinstance(cad_record, dict) else {}
@@ -11,6 +11,7 @@ import subprocess
import sys
import threading
import time
from collections import deque
from uuid import uuid4
from .errors import TaskCenterError
@@ -23,6 +24,15 @@ _LIVE_SUPERVISORS = {}
_WRITE_OPERATIONS = frozenset({'execute_task_queue', 'execute_quick_run_queue', 'execute_quick_run', 'recover_quick_run'})
def _decode_process_output(value):
if not isinstance(value, bytes):
return str(value)
try:
return value.decode('utf-8')
except UnicodeDecodeError:
return value.decode('mbcs' if os.name == 'nt' else 'utf-8', errors='replace')
def _mark_interrupted(root, journal, reason):
from .batch_resources import write_record, _valid_record
from .stop_control import protect_interruption
@@ -59,29 +69,46 @@ def _worker_context(root):
def _force_owned_supervisor(root, journal, process):
"""Persist uncertainty before terminating the exact process/Job we own."""
from .batch_resources import write_record
path = Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json'
if (journal.get('force_state') in {'termination_requested', 'confirmed'}
and process.poll() is not None):
return
journal['stop_mode'] = 'forced'
journal['force_requested_at'] = time.time()
journal.setdefault('force_requested_at', time.time())
journal['force_state'] = 'requested'
write_record(path, journal)
# The running worker can cross a task boundary while evidence is written.
# Protect all possible targets before force; keep their saved results intact.
journal['protect_all_targets'] = True
_mark_interrupted(root, journal, '用户明确强制结束;写入与保存结果须核验,禁止自动重放。')
try:
_mark_interrupted(root, journal, '用户明确强制结束;写入与保存结果须核验,禁止自动重放。')
except Exception as error:
journal.update(state='blocked', force_state='protection_failed', force_error=str(error))
try:
write_record(path, journal)
except OSError:
pass # The durable requested state still blocks a later replay.
raise
try:
process.terminate()
except Exception as error:
if not getattr(process, 'cleanup_record', {}).get('forced_termination'):
raise
journal['force_cleanup_error'] = str(error)
try:
from .batch_resources import write_record
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
except OSError:
pass # The forced intent and uncertainty were already durably saved.
journal['force_state'] = 'termination_requested'
try:
write_record(path, journal)
except OSError:
pass # Intent and uncertainty already exist; exit still requires confirmation.
def _retain_supervisor_after_control_error(root, journal, process, control, error):
"""Do not turn a GUI/transport exception into an unconfirmed Job kill."""
from .batch_resources import write_record
control.set()
control.waiting_for_resolution = True
control.resolution_error = str(error)
control.control_error = '控制通信异常,已请求安全停止并保留应用;可导出诊断或明确强制结束:' + str(error)
journal['protect_all_targets'] = True
try:
@@ -93,7 +120,14 @@ def _retain_supervisor_after_control_error(root, journal, process, control, erro
{'version': VERSION, 'batch_id': journal['batch_id'], 'attempt_id': journal['attempt_id']})
except OSError:
pass # Keep ownership; failure to request stop is not permission to kill.
last_notice = time.monotonic()
while True:
if time.monotonic() - last_notice >= 15:
import logging
logging.getLogger(__name__).warning(
'supervisor_retained_waiting_for_resolution batch_id=%s error=%s',
journal['batch_id'], control.control_error)
last_notice = time.monotonic()
if control.force_event.is_set():
try:
_force_owned_supervisor(root, journal, process)
@@ -218,7 +252,7 @@ def _environment():
def _finish_response(root, journal, response, context):
"""A supervisor exit may release its last USER reference. Never repeat work."""
from .batch_resources import cleanup_pending_resources, write_record
from .supervisor_result import validated_outcome, resource_pending_error
from .supervisor_result import validated_outcome, resource_pending_error, application_shutdown_error
result, error, primary = validated_outcome(journal['operation'], response)
pending = cleanup_pending_resources(root, logging_context=context)
related = tuple(item for item in pending if item.get('session_id') == journal['batch_id'] or not item.get('session_id'))
@@ -230,18 +264,34 @@ def _finish_response(root, journal, response, context):
if related:
raise resource_pending_error(journal['operation'], result, error, primary)
resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json')
def preserve_shutdown_failure(detail):
try:
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
except OSError as record_error:
context.logger.error('supervisor_shutdown_record_failed batch_id=%s error=%s',
journal['batch_id'], record_error)
journal['shutdown_record_error'] = str(record_error)
try:
resource = json.loads(resource_path.read_text(encoding='utf-8'))
except FileNotFoundError:
resource = {}
shutdown = resource.get('cad_shutdown') or {}
except (OSError, ValueError, TypeError) as failure:
journal.update(state='blocked', shutdown_record_error=str(failure))
preserve_shutdown_failure(failure)
raise application_shutdown_error(result, error, primary) from failure
shutdown = resource.get('cad_shutdown') if isinstance(resource, dict) else None
if shutdown is None and isinstance(resource, dict):
shutdown = {}
if (not isinstance(shutdown, dict)
or not isinstance(shutdown.get('cleanup_errors', ()), (list, tuple))
or any(not isinstance(item, dict) for item in shutdown.get('cleanup_errors', ()))):
journal.update(state='blocked', shutdown_record_error='invalid shutdown record shape')
preserve_shutdown_failure('invalid shutdown record shape')
raise application_shutdown_error(result, error, primary)
if (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination')
or shutdown.get('diagnostic_errors')
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))):
failure = TaskCenterError('application_shutdown_failed',
'已核验业务结果保留,但应用未正常收尾;请查看退出诊断,不能将资源消失视为正常退出。')
failure.completed_result, failure.cleanup_error = result, error
raise failure
raise application_shutdown_error(result, error, primary)
if response.get('business_succeeded'):
if response.get('error'):
context.logger.info('supervisor_resource_recovery_passed batch_id=%s business_replayed=false', journal['batch_id'])
@@ -293,29 +343,55 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
'interactive_stop': isinstance(stop_event, StopControl)})
journal['request_sha256'] = hashlib.sha256(internal_path(request).read_bytes()).hexdigest()
write_record(directory / 'supervisor.json', journal)
from .supervisor_evidence import LifecycleEvidence
lifecycle = LifecycleEvidence(directory)
lifecycle.try_append('supervisor_starting', operation=operation)
gate, messages = MessageGate(batch_id, attempt_id), queue.Queue()
api, process, reader = _Win32Api(), None, None
stderr_reader = None
stdout_tail, stderr_tail = deque(maxlen=65536), deque(maxlen=65536)
sent_cancel, last_heartbeat = False, time.monotonic()
transport_error = None
ownership_cleanup_error = None
force_accepted = False
last_message = None
def receive():
try:
while line := process.stdout.readline(1024 * 1024):
if isinstance(line, bytes):
decoded = _decode_process_output(line)
stdout_tail.extend(decoded)
else:
decoded = str(line)
stdout_tail.extend(decoded)
try:
messages.put(json.loads(line))
messages.put(json.loads(decoded))
except (ValueError, UnicodeError):
messages.put({'type': 'invalid'})
finally:
messages.put(None)
def receive_stderr():
if process is None or process.stderr is None:
return
while True:
line = process.stderr.readline(1024 * 1024)
if not line:
return
if isinstance(line, bytes):
stderr_tail.extend(_decode_process_output(line))
else:
stderr_tail.extend(str(line))
try:
# A normal input-desktop supervisor owns its private-desktop children.
# Only the supervisor, never the GUI, creates a private desktop.
process = api.create_process(_command(internal_path(request)), None, legacy_path(root),
_environment(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
_environment(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
journal.update(state='running', process=process_identity(process))
write_record(directory / 'supervisor.json', journal)
reader = threading.Thread(target=receive, daemon=True)
reader.start()
stderr_reader = threading.Thread(target=receive_stderr, daemon=True)
stderr_reader.start()
while process.poll() is None or not messages.empty():
force = getattr(stop_event, 'force_event', None)
if force is not None and force.is_set() and process.poll() is None:
@@ -331,7 +407,8 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
if stop_event is not None and stop_event.is_set() and not sent_cancel:
try:
write_record(directory / 'cancel.json', {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id})
journal.update(stop_mode='safe', stop_requested_at=time.time())
journal.setdefault('stop_mode', 'safe')
journal.setdefault('stop_requested_at', time.time())
write_record(directory / 'supervisor.json', journal)
sent_cancel = True
except OSError as error:
@@ -346,6 +423,7 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
continue
if value is None or not gate.accept(value):
continue
last_message = value
last_heartbeat = time.monotonic()
if value['type'] == 'progress' and on_progress is not None:
on_progress(value['payload'])
@@ -375,20 +453,57 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
process.close() # Waits, and confines termination to the owned Job.
api.close_pending()
except Exception as error:
ownership_cleanup_error = error
if process is not None:
_LIVE_SUPERVISORS[directory / 'supervisor.json'] = (api, process)
transport_error = error if transport_error is None else TaskCenterError(
'batch_resources_pending', f'监督进程错误:{transport_error};收尾错误:{error}')
if reader is not None:
reader.join(3)
if stderr_reader is not None:
stderr_reader.join(3)
from .supervisor_evidence import write_process_evidence
try:
write_process_evidence(directory, exit_code=getattr(process, 'returncode', None),
stdout=''.join(stdout_tail), stderr=''.join(stderr_tail),
cleanup=getattr(process, 'cleanup_record', None), last_message=last_message)
except OSError as evidence_error:
journal['diagnostic_write_error'] = str(evidence_error)
service._logging.logger.error('supervisor_evidence_write_failed batch_id=%s error=%s',
batch_id, evidence_error)
lifecycle.try_append('supervisor_exit',
exit_code=getattr(process, 'returncode', None),
stdout_chars=len(stdout_tail), stderr_chars=len(stderr_tail))
if force_accepted:
from .batch_resources import cleanup_pending_resources
try:
cleanup_pending_resources(root, logging_context=service._logging)
pending = cleanup_pending_resources(root, logging_context=service._logging)
if pending:
ownership_cleanup_error = TaskCenterError('batch_resources_pending', '强制结束后的资源仍待清理。')
except Exception as error:
ownership_cleanup_error = error
service._logging.logger.error('forced_stop_cleanup_pending batch_id=%s error=%s', batch_id, error)
raise TaskCenterError('user_forced_stop',
failure = TaskCenterError('user_forced_stop',
'已按确认强制结束;已保存的执行证据保留,当前结果待核验。请先核验恢复,不要重复替换。')
failure.primary_error = transport_error
if ownership_cleanup_error is not None:
journal.update(force_state='confirmation_failed', force_cleanup_error=str(ownership_cleanup_error))
else:
journal.update(force_state='confirmed', force_confirmed_at=time.time())
try:
write_record(directory / 'supervisor.json', journal)
except OSError as persistence_error:
if ownership_cleanup_error is not None:
combined = TaskCenterError('batch_resources_pending',
f'退出确认异常:{ownership_cleanup_error};确认记录写入失败:{persistence_error}')
combined.primary_error, combined.cleanup_error = ownership_cleanup_error, persistence_error
ownership_cleanup_error = combined
else:
ownership_cleanup_error = persistence_error
if ownership_cleanup_error is not None:
from .supervisor_result import resource_pending_error
raise resource_pending_error(operation, None, ownership_cleanup_error, failure)
raise failure
try:
try:
response = json.loads(internal_path(directory / 'result.json').read_text(encoding='utf-8'))
@@ -407,13 +522,30 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
from .supervisor_result import validated_outcome, resource_pending_error
decoded_result, decoded_error, decoded_primary = validated_outcome(operation, response['payload'])
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
_mark_interrupted(root, journal, transport_error or error)
from .supervisor_evidence import MissingSupervisorResult, InvalidSupervisorResult
failure_type = MissingSupervisorResult if isinstance(error, FileNotFoundError) else InvalidSupervisorResult
cause = transport_error or failure_type(exit_code=getattr(process, 'returncode', None),
stdout_tail=''.join(stdout_tail), stderr_tail=''.join(stderr_tail))
if process is None and transport_error is not None:
cause = TaskCenterError('worker_start_failed', '后台进程启动失败,未开始业务执行:' + str(transport_error))
try:
_mark_interrupted(root, journal, cause)
except OSError as protection_error:
journal.update(state='blocked', outcome='interrupted', protection_error=str(protection_error))
try:
write_record(directory / 'supervisor.json', journal)
except OSError:
service._logging.logger.exception('supervisor_protection_record_failed batch_id=%s', batch_id)
failure = TaskCenterError('interruption_protection_failed',
'后台进程结果不确定,且中断保护写入失败;已阻止继续执行,请保留诊断并核验工程。')
failure.primary_error, failure.cleanup_error = cause, protection_error
raise failure from protection_error
# Recheck physical resources even when final business results are
# missing; this never authorizes repeating the interrupted job.
from .batch_resources import cleanup_pending_resources
cleanup_pending_resources(root, logging_context=service._logging)
failure = TaskCenterError('supervisor_interrupted',
'批次监督进程未留下可信结果;保留保护记录,不自动重试。' +
failure = cause if isinstance(cause, TaskCenterError) else TaskCenterError(
'supervisor_interrupted', '批次监督进程未留下可信结果;保留保护记录,不自动重试。' +
(f' 首发原因:{transport_error}' if transport_error else ''))
failure.primary_error = transport_error or error
raise failure from (transport_error or error)
@@ -51,7 +51,7 @@ def _admit_request(directory, request, request_bytes):
time.sleep(.02)
own = process_identity(type('WorkerIdentity', (), {'pid': os.getpid(), 'handle': win32api.GetCurrentProcess()})())
if journal['process'] != own:
raise ValueError('Supervisor request belongs to another process')
raise ValueError(f'Supervisor request belongs to another process: expected={journal["process"]!r} actual={own!r}')
# Atomic exclusive publication makes requests one-shot, including retained
# requests invoked manually or racing a delayed/duplicate launch.
with internal_path(directory / 'claim.json').open('x', encoding='utf-8') as stream:
@@ -63,11 +63,6 @@ def _admit_request(directory, request, request_bytes):
def run(request_path):
from .batch_resources import write_record
from .batch_runtime import BatchCadRuntime
from .batch_supervisor import _worker_context
from .logging_setup import configure_logging
from .service import TaskCenterService
from .store import TaskStore
output, owns_output = _output_stream()
request_path = canonical_path(request_path, strict=True)
@@ -79,9 +74,17 @@ def run(request_path):
raise ValueError('Invalid batch supervisor request')
root = canonical_path(request['root'])
directory = root / 'batch-resources' / batch_id
from .supervisor_evidence import LifecycleEvidence
evidence = LifecycleEvidence(directory)
if request_path != directory / 'request.json':
raise ValueError('Supervisor request ownership path mismatch')
_admit_request(directory, request, request_bytes)
evidence.try_append('worker_started', pid=os.getpid())
from .batch_runtime import BatchCadRuntime
from .batch_supervisor import _worker_context
from .logging_setup import configure_logging
from .service import TaskCenterService
from .store import TaskStore
_worker_context(root)
from .stop_control import StopControl
stop = StopControl() if request.get('interactive_stop', False) else threading.Event()
@@ -128,6 +131,7 @@ def run(request_path):
thread.start()
response = {'business_succeeded': False, 'status': 'error'}
try:
evidence.try_append('business_started', operation=request['operation'])
arguments = decode(request['arguments'])
operation = request['operation']
def progress(message):
@@ -166,6 +170,7 @@ def run(request_path):
else:
result = getattr(service, operation)(**arguments, runtime=runtime)
runtime.result = result
evidence.try_append('business_finished', operation=operation, succeeded=True)
response.update(status='ok', business_succeeded=True, result=encode(result))
write_record(directory / 'business-result.json', {'version': VERSION, 'batch_id': batch_id,
'attempt_id': attempt_id, 'generation': max(1, runtime.generation), 'payload': response})
@@ -173,16 +178,21 @@ def run(request_path):
from .bom_import_state import BomImportPhase
phase(BomImportPhase.RELEASING, '本批位号核验结束,正在释放后台资源…')
except Exception as error:
evidence.try_append('business_failed', operation=operation, error=type(error).__name__)
response['operation_error'] = encode_error(error)
raise
finally:
evidence.try_append('resources_releasing')
except Exception as error:
context.report_exception('batch_supervisor', error)
response.update(status='error', error=encode_error(error))
finally:
evidence.try_append('worker_closing', status=response.get('status'), business_succeeded=response.get('business_succeeded'))
finished.set()
thread.join(3)
store.close()
emit('result', response, persist=True)
evidence.try_append('result_committed', status=response.get('status'), business_succeeded=response.get('business_succeeded'))
if owns_output:
output.close()
return 0
@@ -14,7 +14,8 @@ MAX_FILE_BYTES = 4 * 1024 * 1024
MAX_BUNDLE_BYTES = 32 * 1024 * 1024
MAX_FILES = 512
_BATCH_NAMES = {'session.json', 'supervisor.json', 'request.json', 'result.json',
'business-result.json', 'supervisor.log', 'resource-release.log', 'cancel.json'}
'business-result.json', 'supervisor.log', 'resource-release.log', 'cancel.json',
'process.json', 'lifecycle.jsonl'}
_QUICK_NAMES = {'private-desktop.json', 'checkpoint.json', 'status.json',
'uncertain.flag', 'resolved-uncertain.flag', 'protection.json', 'cleanup.json',
'project-session.json', 'project-checkpoint.json', 'status.tsv'}
@@ -15,6 +15,7 @@ import math
import os
from pathlib import Path
import subprocess
import sys
import time
from threading import get_native_id
from typing import Mapping, Sequence
@@ -125,6 +126,15 @@ class _Win32Api:
def create_process(self, command: Sequence[str], desktop: str, cwd: Path | None, env: Mapping[str, str] | None,
*, stdout=None, stderr=None):
# Windows venv python.exe redirects to a second process. Launch the
# interpreter directly with its venv identity, so the handle we own is
# also the process that admits the request and creates desktop windows.
if (not getattr(sys, 'frozen', False) and sys.prefix != sys.base_prefix
and os.path.normcase(os.path.abspath(str(command[0]))) == os.path.normcase(sys.executable)
and getattr(sys, '_base_executable', None)):
command = (sys._base_executable, *command[1:])
env = dict(os.environ if env is None else env)
env['__PYVENV_LAUNCHER__'] = sys.executable
startup = self.process.STARTUPINFO()
startup.lpDesktop = desktop
flags = self.con.CREATE_NO_WINDOW | self.con.CREATE_SUSPENDED
@@ -148,6 +158,9 @@ class _Win32Api:
process.thread = thread
self.job.AssignProcessToJobObject(job, handle)
process.job_assigned = True
if not self.job.IsProcessInJob(handle, job):
raise TaskCenterError('private_desktop', 'Owned process Job membership was not confirmed')
process.cleanup_record['job_membership_verified'] = True
self.process.ResumeThread(thread)
thread.Close()
process.thread = None
@@ -87,6 +87,8 @@ def read_snapshot(path):
raise ValueError("Invalid snapshot Value or NC option")
if any(len(row) != 8 for row in components):
raise ValueError("Invalid component snapshot")
if any(not row[1].strip() or not row[2].strip() for row in components):
raise ValueError("Snapshot component UID or Refdes is empty")
if len({row[1] for row in components}) != len(components):
raise ValueError("Duplicate snapshot UID")
if metadata[0][2].casefold() == metadata[0][3].casefold():
@@ -346,11 +348,32 @@ def attach():
return app, api
def attribute_value(component, name):
attribute = component.FindAttribute(name)
if attribute is None:
return ""
return str(attribute.InstanceValue or attribute.Value)
def attribute_value(component, name, *, required=False, fallback=""):
"""Read a CAD attribute without allowing optional COM failures to hang a run.
Identity and source Part Number callers pass ``required=True``. Display,
baseline and optional policy fields degrade to the supplied fallback; a
later comparison can still reject a changed or incomplete result.
"""
try:
attribute = component.FindAttribute(name)
if attribute is None:
value = fallback
else:
try:
instance = attribute.InstanceValue
except Exception:
instance = None
try:
base = attribute.Value
except Exception:
base = None
value = instance or base or fallback
return str(value)
except Exception as error:
if required:
raise ValueError(f"required attribute {name!r} is unavailable") from error
return fallback
def selection(component, value):
@@ -360,7 +383,22 @@ def selection(component, value):
def components_on_sheet(app, api):
return [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 0)]
components = [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 0)]
uids = [_component_uid(component) for component in components]
if len(set(uids)) != len(uids):
raise ValueError("Duplicate component UID on sheet")
return components
def _component_uid(component):
value = getattr(component, 'UID', None)
uid = '' if value is None else str(value).strip()
if uid:
return uid
refdes = str(getattr(component, 'Refdes', '') or '').strip()
if not refdes:
raise ValueError("Component UID and Refdes are empty; cannot safely identify the target")
return '@REFDES|' + refdes
def check_active_context(app, metadata):
@@ -376,7 +414,7 @@ def check_context(app, api, metadata, records, require_selection=True):
check_active_context(app, metadata)
components = components_on_sheet(app, api)
wanted = {row[1] for row in records}
by_uid = {str(component.UID): component for component in components}
by_uid = {_component_uid(component): component for component in components}
if len(by_uid) != len(components):
raise ValueError("Duplicate component UID on sheet")
if len(metadata) == 10:
@@ -386,15 +424,16 @@ def check_context(app, api, metadata, records, require_selection=True):
for uid, (refdes, old_value) in selectors.items():
component = by_uid.get(uid)
if (component is None or str(component.Refdes) != refdes or
attribute_value(component, "Part Number").casefold() != metadata[2].casefold() or
attribute_value(component, "Part Number", required=True).casefold() != metadata[2].casefold() or
attribute_value(component, "Value") != old_value):
raise ValueError("Selected target changed since inventory")
else:
actual = {str(component.UID) for component in components if attribute_value(component, "Part Number").casefold() == metadata[2].casefold()}
actual = {_component_uid(component) for component in components if attribute_value(component, "Part Number", required=True).casefold() == metadata[2].casefold()}
if actual != wanted:
raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}")
if require_selection:
selected = {str(api.IVdComp(component._oleobj_).UID) for component in app.ActiveView.Query(128, 1)}
selected = {_component_uid(api.IVdComp(component._oleobj_))
for component in app.ActiveView.Query(128, 1)}
if selected != wanted:
raise ValueError(f"Selected component set differs from snapshot: expected={sorted(wanted)!r} actual={sorted(selected)!r}")
return components
@@ -424,7 +463,7 @@ def verify_unselected_snapshot(snapshot, components, selected_uids):
raise ValueError("Duplicate unselected component UID")
current = {}
for component in components:
uid = str(component.UID)
uid = _component_uid(component)
if uid in selected_uids:
continue
current[uid] = (str(component.Refdes), *(attribute_value(component, name)
@@ -438,7 +477,7 @@ def select_snapshot_batch(app, api, metadata, records):
components = check_context(app, api, metadata, records, require_selection=False)
wanted = {row[1] for row in records}
for component in components:
selection(component, str(component.UID) in wanted)
selection(component, _component_uid(component) in wanted)
return check_context(app, api, metadata, records)
@@ -460,7 +499,7 @@ def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=No
try:
progress('select_replacements')
for component in components:
selection(component, str(component.UID) in replacement_uids)
selection(component, _component_uid(component) in replacement_uids)
for slot in range(1, int(slot_count) + 1):
progress(f'promote_slot_{slot}')
app.ActiveView.Block.PromoteSymbolNumbers(1, slot)
@@ -468,10 +507,10 @@ def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=No
promoted = []
for item in app.ActiveView.Query(4096, 0):
pin = api.IVdCmpPin(item._oleobj_)
if str(pin.Component.UID) in replacement_uids:
if _component_uid(pin.Component) in replacement_uids:
if not str(pin.Number).strip():
raise ValueError("Native target-library pin number promotion failed")
promoted.append({"uid": str(pin.Component.UID), "number": str(pin.Number)})
promoted.append({"uid": _component_uid(pin.Component), "number": str(pin.Number)})
if not promoted:
raise ValueError("Replacement produced no pins")
return promoted
@@ -488,7 +527,7 @@ def _promotion_phase(snapshot, report, phase):
def replacement_matches(components, records, target, require_part_label, *, library_row=None):
current_by_uid = {str(component.UID): component for component in components}
current_by_uid = {_component_uid(component): component for component in components}
if len(current_by_uid) != len(components):
raise ValueError('Duplicate component UID on sheet')
expected_name = expected_label = None
@@ -502,15 +541,15 @@ def replacement_matches(components, records, target, require_part_label, *, libr
candidate = current_by_uid.get(record[1])
if candidate is None:
raise ValueError('Native replacement lost component UID identity')
if attribute_value(candidate, "Part Number").casefold() != target.casefold():
if attribute_value(candidate, "Part Number", required=True).casefold() != target.casefold():
return None
identity = str(candidate.Refdes).strip() or f"UID={candidate.UID}"
part_name = attribute_value(candidate, 'Part Name')
part_name = attribute_value(candidate, 'Part Name', required=True)
if not part_name:
raise ValueError(
f"Native replacement Part Name readback failed; refdes={identity}; uid={candidate.UID}"
)
part_label = attribute_value(candidate, 'Part Label') if require_part_label or expected_label else ''
part_label = attribute_value(candidate, 'Part Label', required=require_part_label or bool(expected_label)) if require_part_label or expected_label else ''
if require_part_label and not part_label:
raise ValueError(
f"Native replacement Part Label readback failed; refdes={identity}; uid={candidate.UID}; "
@@ -519,7 +558,7 @@ def replacement_matches(components, records, target, require_part_label, *, libr
if expected_name is not None and (part_name != expected_name
or (expected_label and part_label != expected_label)):
raise ValueError(f'Native replacement does not match the selected target library identity; uid={candidate.UID}')
matches.append(str(candidate.UID))
matches.append(_component_uid(candidate))
if len(set(matches)) != len(records):
raise ValueError("Duplicate replacement association")
return matches
@@ -533,7 +572,7 @@ def verify_replacement_readback(snapshot, components, metadata, records, before_
# The persisted U baseline already covers exactly these identity fields.
verify_unselected_snapshot(snapshot, components, {row[1] for row in records})
else:
current = {str(component.UID): component for component in components}
current = {_component_uid(component): component for component in components}
for uid, identity in untouched.items():
component = current.get(uid)
actual = None if component is None else (
@@ -566,9 +605,9 @@ def run_native(snapshot, report):
if len(metadata) == 10:
verify_unselected_snapshot(snapshot, components, wanted)
source_uids = {
str(component.UID)
_component_uid(component)
for component in components
if str(component.UID) in wanted and attribute_value(component, "Part Number").casefold() == metadata[2].casefold()
if _component_uid(component) in wanted and attribute_value(component, "Part Number", required=True).casefold() == metadata[2].casefold()
}
if source_uids != wanted:
binding = require_resumable_transaction(snapshot, report, metadata, records)
@@ -592,11 +631,11 @@ def run_native(snapshot, report):
report["stage"] = "native_replace_verified"
return
components = select_snapshot_batch(app, api, metadata, records)
before_uids = {str(component.UID) for component in components}
untouched = None if len(metadata) == 10 else {str(component.UID): (
before_uids = {_component_uid(component) for component in components}
untouched = None if len(metadata) == 10 else {_component_uid(component): (
str(component.Refdes),
*(attribute_value(component, name) for name in ("Part Number", "Value", "Part Name", "Part Label"))
) for component in components if str(component.UID) not in wanted}
) for component in components if _component_uid(component) not in wanted}
view_handle = int(app.ActiveViewHandle)
process_id = win32process.GetWindowThreadProcessId(view_handle)[1]
main_handle = win32gui.GetAncestor(view_handle, 2)
@@ -733,7 +772,7 @@ def run_native(snapshot, report):
ready = wait_for_native_target(read_target, metadata[3], columns[2], slot_count)
components = check_context(app, api, metadata, records, require_selection=False)
for component in components:
selection(component, str(component.UID) in wanted)
selection(component, _component_uid(component) in wanted)
for identifier in (1704, 1105, 1697, 1700):
check_radio(dialog, identifier)
check_context(app, api, metadata, records)
@@ -781,10 +820,10 @@ def run_native(snapshot, report):
refs = {record[2] for record in records}
report['replacement_timeout'].update(
component_count=len(current),
components=[dict(uid=str(c.UID), refdes=str(c.Refdes),
components=[dict(uid=_component_uid(c), refdes=str(c.Refdes),
attributes={name: attribute_value(c, name)
for name in ('Part Number', 'Part Name', 'Part Label', 'Value')})
for c in current if str(c.UID) in wanted or str(c.Refdes) in refs])
for c in current if _component_uid(c) in wanted or str(c.Refdes) in refs])
except Exception as error:
report['replacement_timeout']['component_readback_error'] = str(error)
try:
@@ -116,8 +116,17 @@ class ProjectSessionWorker:
if interactive:
# The monitor owns the safe/unsafe distinction. Do not
# turn a GUI close or ordinary pause into a timed kill.
force_event = getattr(getattr(self.runtime, 'stop_event', None), 'force_event', None)
last_notice = time.monotonic()
while not self._done.wait(.1):
pass
if force_event is not None and force_event.is_set():
self._abort.set()
break
if time.monotonic() - last_notice >= 15:
import logging
logging.getLogger(__name__).warning(
'project_session_awaiting_close token=%s', self.token)
last_notice = time.monotonic()
close_grace = 60 if self.private_desktop else min(30, max(10, self._timeout))
if not self._done.wait(close_grace):
self._abort.set()
@@ -31,6 +31,9 @@ def protect_interruption(root, reason):
# A previous create/write/fsync may have failed. Existence alone does
# not establish durable evidence; preserve its bytes but sync again.
with marker.open('r+b') as existing:
if not existing.read(1):
existing.write(str(reason).encode('utf-8'))
existing.flush()
os.fsync(existing.fileno())
else:
with stream:
@@ -0,0 +1,106 @@
"""Durable, bounded evidence for one supervised batch attempt."""
from __future__ import annotations
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import threading
from .errors import TaskCenterError
from .path_access import internal_path
def _atomic_json(path: Path, value: dict) -> None:
from .batch_resources import write_record
write_record(path, value)
def _tail(value: str, limit: int) -> str:
value = str(value or '')
limit = max(0, int(limit))
return value.encode('utf-8')[-limit:].decode('utf-8', errors='ignore') if limit else ''
class LifecycleEvidence:
def __init__(self, directory: Path):
self.directory = internal_path(directory)
self.path = self.directory / 'lifecycle.jsonl'
self._lock = threading.Lock()
def append(self, event: str, **fields) -> dict:
row = {'at': datetime.now(timezone.utc).isoformat(), 'event': str(event), **fields}
with self._lock:
self.directory.mkdir(parents=True, exist_ok=True)
with self.path.open('a', encoding='utf-8', newline='') as stream:
stream.write(json.dumps(row, ensure_ascii=True, allow_nan=False, sort_keys=True) + '\n')
stream.flush()
os.fsync(stream.fileno())
return row
def events(self) -> tuple[dict, ...]:
try:
lines = self.path.read_text(encoding='utf-8').splitlines()
except FileNotFoundError:
return ()
rows = []
for line in lines:
try:
row = json.loads(line)
if isinstance(row, dict):
rows.append(row)
except ValueError:
continue # A hard exit may leave an incomplete last append.
return tuple(rows)
def try_append(self, event: str, **fields) -> str:
"""Supplemental tracing must not replace business or protection evidence."""
try:
self.append(event, **fields)
except OSError as error:
return str(error)
return ''
def write_process_evidence(directory: Path, *, exit_code, stdout='', stderr='', limit=65536,
cleanup=None, last_message=None) -> dict:
value = {'exit_code': exit_code, 'stdout_tail': _tail(stdout, limit), 'stderr_tail': _tail(stderr, limit),
'cleanup': cleanup, 'last_message': last_message,
'recorded_at': datetime.now(timezone.utc).isoformat()}
_atomic_json(internal_path(directory) / 'process.json', value)
return value
class SupervisorResultEvidenceError(TaskCenterError):
code_name = 'worker_result_missing'
description = '后台进程未留下可信结果'
def __init__(self, *, exit_code=None, stdout_tail='', stderr_tail=''):
stdout_tail = _tail(stdout_tail if isinstance(stdout_tail, str) else '', 65536)
stderr_tail = _tail(stderr_tail if isinstance(stderr_tail, str) else '', 65536)
self.exit_code = exit_code
self.stdout_tail = stdout_tail
self.stderr_tail = stderr_tail
detail = f'{self.description};退出码={exit_code!r}。保留保护记录,请先核验恢复,禁止自动重放。'
if stderr_tail:
detail += f'; stderr={stderr_tail[-512:]}'
super().__init__(self.code_name, detail)
@classmethod
def from_directory(cls, directory: Path):
try:
value = json.loads((internal_path(directory) / 'process.json').read_text(encoding='utf-8'))
except (FileNotFoundError, OSError, ValueError, TypeError):
value = {}
if not isinstance(value, dict):
value = {}
return cls(exit_code=value.get('exit_code'), stdout_tail=value.get('stdout_tail', ''),
stderr_tail=value.get('stderr_tail', ''))
class MissingSupervisorResult(SupervisorResultEvidenceError):
"""No committed result survived the worker exit."""
class InvalidSupervisorResult(SupervisorResultEvidenceError):
code_name = 'worker_result_invalid'
description = '后台进程结果损坏或身份校验不通过'
@@ -48,3 +48,24 @@ def resource_pending_error(operation, result, error, primary_error=None):
elif getattr(error, 'bom_report', None) is not None:
failure.bom_report = replace(error.bom_report, preview=None)
return failure
def application_shutdown_error(result, error, primary_error=None):
"""Retain diagnostics, but never expose a plan after abnormal shutdown."""
from dataclasses import replace
from .bom_import_report import BomImportReport
from .errors import TaskCenterError
if isinstance(result, BomImportReport):
result = replace(result, preview=None)
failure = TaskCenterError('application_shutdown_failed',
'应用未正常收尾,已有报告和核验结果保留;请查看退出诊断。')
failure.completed_result = result
failure.cleanup_error = error
failure.primary_error = primary_error
for candidate in (result, getattr(error, 'bom_report', None),
getattr(primary_error, 'bom_report', None)):
if isinstance(candidate, BomImportReport):
failure.bom_report = replace(candidate, preview=None)
break
return failure
@@ -1,4 +1,5 @@
"""Menu presentation for existing buttons, preserving their live business gates."""
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMenu,QWidget
@@ -12,10 +13,15 @@ class CommandMenu(QMenu):
self.aboutToShow.connect(self.sync)
def add_button(self,button):
explicitly_hidden = (button.isHidden() and
button.testAttribute(Qt.WidgetAttribute.WA_WState_ExplicitShowHide))
button.setParent(self.storage)
# Only the parent is hidden. Explicit visibility remains the state gate.
button.show()
# Reparenting hides even new, unshown buttons. Preserve an explicit
# business hide, while allowing ordinary newly constructed commands.
button.setVisible(not explicitly_hidden)
action=self.addAction(button.text())
action.setEnabled(button.isEnabled())
action.setVisible(not button.isHidden())
def invoke():
if button.isEnabled() and not button.isHidden():
button.click()
@@ -1,5 +1,6 @@
"""Task metadata and replacement-rule editing dialogs."""
from PySide6.QtCore import QSignalBlocker, QThreadPool
from shiboken6 import isValid
from PySide6.QtWidgets import (QWidget, QDialog, QLineEdit, QTextEdit, QFormLayout, QLabel,
QDialogButtonBox, QCheckBox, QComboBox, QPushButton, QHBoxLayout)
from .workers import ServiceWorker
@@ -151,7 +152,8 @@ class _MappingDialog(QDialog):
worker = ServiceWorker(lambda: self._cell_loader(pn))
self._cell_workers.add(worker)
def current():
if self._cell_closed or generation != self._cell_generation or pn != self.new_edit.text().strip():
if (not isValid(self) or self._cell_closed or generation != self._cell_generation
or pn != self.new_edit.text().strip()):
return False
try:
same_context = context == self._cell_context()
@@ -3,6 +3,15 @@ from dataclasses import dataclass
from ..models import TaskStatus
def pending_batch_tasks(tasks, group_id):
"""Use the persisted batch order for both execution and its UI controls."""
if not group_id:
return ()
return tuple(sorted((task for task in tasks if task.group_id == group_id
and task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}),
key=lambda task: task.group_position))
@dataclass(frozen=True, slots=True)
class ExecutionState:
editable: bool = False
@@ -12,7 +12,7 @@ from ..errors import TaskCenterError
from ..models import TaskStatus
from ..version import VERSION
from .dialogs import _TaskDialog, _MappingDialog
from .execution_state import execution_state
from .execution_state import execution_state, pending_batch_tasks
from .mapping_table import MappingTable
from .messages import ERROR_TEXT, _format_live_log_line, format_operation_error
from .project_plan import DirectoryTaskDialog, ProjectPlanPanel
@@ -24,6 +24,7 @@ from .icons import apply_icons, icon
from .task_list import TaskList
from .workers import ServiceWorker
from .queries import LatestQuery
from .resource_status import ResourceStatus
from .task_log import TaskLogPresenter
from .execution_feedback import format_feedback
from .operation_state import ContextReadPhase, OperationPhase, OperationState
@@ -104,6 +105,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._context_query = LatestQuery(self)
self._task_query = LatestQuery(self)
self._feedback_query = LatestQuery(self)
self._resource_status = ResourceStatus(lambda: service.pending_batch_resources(), self)
self._run_started_at = 0.0
self._quick_run_elapsed = QElapsedTimer()
self._quick_run_timer = QTimer(self)
@@ -175,6 +177,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
widget.restoreState(saved)
from .dsh_operations import DshOperationsController
self._dsh_operations = DshOperationsController(self)
self._resource_status.changed.connect(self._update_gates)
self._resource_status.refresh()
self._refresh_task_list()
self._update_gates()
if (self.service.layout_settings_path.parent / 'dsh' / 'incidents').is_dir():
@@ -347,6 +351,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._context_query.close()
self._task_query.close()
self._feedback_query.close()
self._resource_status.close()
self._log_presenter.query.close()
self._quick_run_timer.stop()
if self._dsh_view is not None:
@@ -423,9 +428,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _update_gates(self):
busy = bool(self._workers) or self._loading
resources_pending = bool(self.service.pending_batch_resources())
self.run_panel.cleanup_resources_button.setVisible(resources_pending)
self.run_panel.cleanup_resources_button.setEnabled(resources_pending and not busy)
resources_pending = self._resource_status.blocked
self.run_panel.cleanup_resources_button.setVisible(resources_pending and self._resource_status.known)
self.run_panel.cleanup_resources_button.setEnabled(resources_pending and self._resource_status.known and not busy)
state = execution_state(self._context, busy=busy,
dirty=self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor())
group_unsaved = self._group_has_unsaved_plans() if state.editable or state.new_round else False
@@ -483,7 +488,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
and t.status is not TaskStatus.DELETED}
group_dirty = self.plan_panel.has_unsaved_plan(group_ids)
group_active = any(t.status in {TaskStatus.RUNNING, TaskStatus.PAUSED} for t in self._tasks if t.task_id in group_ids)
self.task_list.queue_button.setEnabled(grouped and not busy and not group_dirty and not bool(context.interrupted) and not resources_pending)
batch_pending = pending_batch_tasks(self._tasks, context.task.group_id if grouped else None)
self.task_list.queue_button.setEnabled(bool(batch_pending) and not busy and not group_dirty
and not context.interrupted and not resources_pending)
for button in (self.task_list.up_button, self.task_list.down_button):
button.setEnabled(grouped and not busy and not group_active
and self.task_list.sort.currentData() == 'execution'
@@ -494,7 +501,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if self._loading and not self._message:
self.run_panel.operator_band.setText('正在读取任务,可继续选择其他任务。')
if not busy:
self.run_panel.execution_status.setText('资源待清理' if resources_pending else '任务读取失败' if read_failed else
self.run_panel.execution_status.setText('正在检查后台资源' if not self._resource_status.known else
'资源状态读取失败' if self._resource_status.error is not None else
'资源待清理' if resources_pending else '任务读取失败' if read_failed else
'结果待核验' if context and context.interrupted else '空闲')
def _group_has_unsaved_plans(self):
@@ -685,8 +694,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if not self.task_list.queue_button.isEnabled():
return
group = self._context.task.group_id
tasks = sorted((t for t in self._tasks if t.group_id == group and t.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}),
key=lambda t: t.group_position)
tasks = pending_batch_tasks(self._tasks, group)
if not tasks:
return
token, ids = self._project_queues.get(group, (None, tuple(t.task_id for t in tasks)))
@@ -833,10 +841,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _startup_resource_recheck(self):
if self._closed:
return
if self._workers or self._loading:
if self._workers or self._loading or not self._resource_status.known or self._resource_status.busy:
QTimer.singleShot(250, self._startup_resource_recheck)
return
if self.service.pending_batch_resources():
if self._resource_status.blocked:
self._update_gates()
self._cleanup_batch_resources() # Resource-only; never resumes a queue.
@@ -935,8 +943,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _confirm_quick_run(self, scope, selected_projects, enabled_rules):
context = self._context
names = context.project.path if scope == 'current' else '\n'.join(
f'{t.group_position+1}. {t.name}' for t in sorted(self._tasks, key=lambda t: t.group_position)
if t.group_id == context.task.group_id and t.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED})
f'{t.group_position+1}. {t.name}' for t in pending_batch_tasks(self._tasks, context.task.group_id))
text = (f'执行范围:{names}\n\n' + (f'勾选目标/规则:{enabled_rules}\n' if scope == 'current' else f'按顺序处理 {selected_projects} 个工程任务。\n')
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
@@ -1147,6 +1154,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
except Exception as error:
operation_error = error
self._close_pending = False
if execution:
# A result renderer is part of the worker lifecycle.
# If it fails, release the execution controls just as
# the service failure path does.
self._finish_run()
self.operation_state = self.operation_state.finish(error)
self._show_error(error)
def failed(error):
@@ -1169,6 +1181,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if not isValid(self) or self._closed:
return
self._bind_dsh_context()
self._resource_status.refresh()
self.plan_panel.finish_operation(error=operation_error)
self._close_saving = False
if self._close_pending and not self._closed:
@@ -10,8 +10,10 @@ from ctypes import wintypes
import sys
from PySide6.QtCore import QEvent, QObject, QTimer, Qt
from PySide6.QtGui import QColor, QGuiApplication, QPainter
from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPalette
from PySide6.QtWidgets import QMainWindow
from shiboken6 import isValid
from .theme import WINDOW_BACKGROUND
class MaterialMainWindow(QMainWindow):
@@ -19,7 +21,9 @@ class MaterialMainWindow(QMainWindow):
def paintEvent(self, event):
if not self.property('acrylicEnabled'):
painter = QPainter(self)
painter.fillRect(event.rect(), QColor('#edf1f5'))
color = (self.palette().color(QPalette.ColorRole.Window)
if self.property('highContrastFallback') else QColor(WINDOW_BACKGROUND))
painter.fillRect(event.rect(), color)
painter.end()
super().paintEvent(event)
@@ -30,6 +34,19 @@ class WindowsAcrylic:
if sys.platform == 'win32':
self._user = ctypes.WinDLL('user32', use_last_error=True)
def high_contrast(self) -> bool:
if self._user is None:
return False
class HighContrast(ctypes.Structure):
_fields_ = [('size', wintypes.UINT), ('flags', wintypes.DWORD),
('scheme', wintypes.LPWSTR)]
contrast = HighContrast()
contrast.size = ctypes.sizeof(contrast)
if not self._user.SystemParametersInfoW(0x0042, contrast.size,
ctypes.byref(contrast), 0):
raise OSError('Cannot read Windows high-contrast policy')
return bool(contrast.flags & 1)
def available(self) -> bool:
if self._user is None or QGuiApplication.platformName() != 'windows':
return False
@@ -37,15 +54,7 @@ class WindowsAcrylic:
return False
try:
import winreg
class HighContrast(ctypes.Structure):
_fields_ = [('size', wintypes.UINT), ('flags', wintypes.DWORD),
('scheme', wintypes.LPWSTR)]
contrast = HighContrast()
contrast.size = ctypes.sizeof(contrast)
if not self._user.SystemParametersInfoW(0x0042, contrast.size,
ctypes.byref(contrast), 0):
return False
if contrast.flags & 1 or self._user.GetSystemMetrics(0x1000):
if self.high_contrast() or self._user.GetSystemMetrics(0x1000):
return False
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
@@ -92,18 +101,20 @@ class AcrylicController(QObject):
self._enabled = False
self._handle = None
self._signature = None
self._normal_stylesheet = None
window.setProperty('acrylicEnabled', False)
window.setProperty('highContrastFallback', False)
# Set up an alpha surface before creating HWND; keep the native frame.
if QGuiApplication.platformName() == 'windows':
window.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
window.installEventFilter(self)
self._timer = QTimer(self)
self._timer.setInterval(2000)
self._timer.setInterval(30000)
self._timer.timeout.connect(self._poll)
self._timer.start()
def _poll(self):
if self.window.isVisible():
if isValid(self.window) and self.window.isVisible():
self.refresh()
def set_reduced_transparency(self, reduced: bool):
@@ -113,18 +124,31 @@ class AcrylicController(QObject):
def _surface(self, enabled, *, repaint=True):
self._enabled = bool(enabled)
self.window.setProperty('acrylicEnabled', bool(enabled))
# Dynamic ancestor selectors affect chrome children as well as the root.
self.window.setStyleSheet(self.window.styleSheet())
# Named/focused controls override generic palette selectors. Removing
# the custom sheet lets Qt honor the system palette for every control.
if self.window.property('highContrastFallback'):
if self._normal_stylesheet is None:
self._normal_stylesheet = self.window.styleSheet()
self.window.setStyleSheet('')
else:
stylesheet = (self._normal_stylesheet if self._normal_stylesheet is not None
else self.window.styleSheet())
self._normal_stylesheet = None
self.window.setStyleSheet(stylesheet)
if repaint:
self.window.update()
def refresh(self):
if not isValid(self) or not isValid(self.window):
return
try:
allowed = not self.reduced and self.backend.available()
high_contrast = bool(getattr(self.backend, 'high_contrast', lambda: False)())
allowed = not self.reduced and not high_contrast and self.backend.available()
except (OSError, AttributeError):
high_contrast = True # An unreadable policy must keep a solid surface.
allowed = False
handle = int(self.window.winId()) if allowed else self._handle
signature = (handle, allowed)
signature = (handle, allowed, high_contrast)
if signature == self._signature:
return
self._signature = signature
@@ -134,6 +158,8 @@ class AcrylicController(QObject):
updates_enabled = self.window.updatesEnabled()
self.window.setUpdatesEnabled(False)
try:
contrast_changed = self.window.property('highContrastFallback') != high_contrast
self.window.setProperty('highContrastFallback', high_contrast)
if self._enabled:
# Paint opaque before removing native blur; avoids an unreadable alpha surface.
self._surface(False, repaint=False)
@@ -143,6 +169,8 @@ class AcrylicController(QObject):
pass
self._handle = handle
if not allowed:
if contrast_changed:
self._surface(False, repaint=False)
return
try:
enabled = self.backend.enable(handle)
@@ -161,6 +189,6 @@ class AcrylicController(QObject):
def eventFilter(self, watched, event):
if event.type() in (QEvent.Type.Show, QEvent.Type.WinIdChange,
QEvent.Type.WindowActivate):
QTimer.singleShot(0, self.refresh)
QEvent.Type.WindowActivate, QEvent.Type.ApplicationPaletteChange):
QTimer.singleShot(0, self, self.refresh)
return super().eventFilter(watched, event)
@@ -0,0 +1,69 @@
"""Background resource checks with a conservative snapshot for UI controls."""
from PySide6.QtCore import QObject, QTimer, Signal
from .queries import LatestQuery
class ResourceStatus(QObject):
changed = Signal()
def __init__(self, read, parent=None):
super().__init__(parent)
self._read = read
self._query = LatestQuery(self)
self._query.settled.connect(self._settled)
self._refresh_again = False
self._closed = False
self.known = False
self.records = ()
self.error = None
self._timer = QTimer(self)
self._timer.setInterval(2000)
self._timer.timeout.connect(self._poll)
self._timer.start()
@property
def busy(self):
return self._query.busy
@property
def blocked(self):
return not self.known or self.error is not None or bool(self.records)
def refresh(self):
if self._closed:
return
if self.busy:
# An operation finished during this read. Recheck afterward rather
# than letting an older result clear the resource gate.
self._refresh_again = True
return
self._query.request(self._read, self._received, self._failed)
def _poll(self):
# Slow reads must finish; periodic polling must not invalidate them.
if not self.busy:
self.refresh()
def _received(self, records):
if self._refresh_again:
return
self.records = tuple(records)
self.known = True
self.error = None
self.changed.emit()
def _failed(self, error):
self.known = True
self.error = error
self.changed.emit()
def _settled(self):
if self._refresh_again and not self._closed:
self._refresh_again = False
self.refresh()
def close(self):
self._closed = True
self._timer.stop()
self._query.close()
@@ -49,11 +49,9 @@ class RunPanel(QWidget):
self.more_menu=CommandMenu(self)
for button in (self.diagnostics_button,self.cleanup_resources_button,self.history_button,self.reset_layout_button):
self.more_menu.add_button(button)
self.more_menu.addSeparator()
self.more_menu.add_button(self.force_stop_button)
self.more_button=QToolButton(objectName='executionMoreMenu')
self.more_button.setText('更多操作')
self.more_button.setToolTip('诊断、轮次证据、布局与异常操作')
self.more_button.setToolTip('诊断、资源清理、轮次证据与布局')
self.more_button.setIcon(icon('more'))
self.more_button.setMenu(self.more_menu)
self.more_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
@@ -65,7 +63,7 @@ class RunPanel(QWidget):
heading.addWidget(self.more_button)
buttons=QHBoxLayout()
buttons.addWidget(self.operator_band,1)
for button in (self.retry_button,self.recover_button,self.new_round_button,self.stop_queue_button,self.quick_run_button):
for button in (self.retry_button,self.recover_button,self.new_round_button,self.stop_queue_button,self.force_stop_button,self.quick_run_button):
buttons.addWidget(button)
layout = QVBoxLayout(self)
layout.setContentsMargins(12,8,12,9)
@@ -1,8 +1,9 @@
"""Frosted window chrome and opaque, readable engineering data surfaces."""
from .theme import WINDOW_BACKGROUND
APP_STYLESHEET = """
QWidget { background: transparent; color: #344359; font-family: "Segoe UI", "Microsoft YaHei UI"; font-size: 13px; }
QMainWindow { background: #edf1f5; }
QMainWindow { background: @WINDOW_BACKGROUND@; }
QMainWindow[acrylicEnabled="true"] { background: transparent; }
QDialog, QMessageBox, QMenu { background: #f8fafc; }
QToolTip { background: #ffffff; color: #344359; border: 1px solid #ccd6e2; padding: 5px; }
@@ -108,4 +109,4 @@ QTableView { outline: none; }
QTableView::item:selected { background: #e6eef8; color: #294969; }
QTableView::item:focus { border: 1px solid #9bb3d0; }
QToolButton[appearance="quiet"]:checked { background: rgba(255,255,255,155); border-color: rgba(255,255,255,220); color: #3f638e; }
"""
""".replace('@WINDOW_BACKGROUND@', WINDOW_BACKGROUND)
@@ -7,7 +7,7 @@ import re
from typing import Iterable
from PySide6.QtCore import Qt, QSignalBlocker, Signal, QSize, QRect
from PySide6.QtGui import QColor,QFont,QIcon
from PySide6.QtGui import QColor,QFont,QIcon,QPalette
from PySide6.QtWidgets import (QComboBox,QHBoxLayout,QLabel,QLineEdit,QListWidget,
QListWidgetItem,QPushButton,QVBoxLayout,QWidget,QToolButton,QMenu,
QStyledItemDelegate,QStyleOptionViewItem,QStyle,QApplication)
@@ -34,19 +34,23 @@ class TaskItemDelegate(QStyledItemDelegate):
style=option.widget.style()if option.widget else QApplication.style()
style.drawControl(QStyle.ControlElement.CE_ItemViewItem,opt,painter,option.widget)
painter.save()
high_contrast=bool(option.widget and option.widget.window().property('highContrastFallback'))
system_text=opt.palette.color(QPalette.ColorRole.HighlightedText
if option.state&QStyle.StateFlag.State_Selected else QPalette.ColorRole.Text)
rect=option.rect.adjusted(12,11,-12,-10)
picture.paint(painter,QRect(rect.left(),rect.top()+7,20,20))
left=rect.left()+31;available=rect.right()-left-(24 if order else 0)
font=QFont(option.font);font.setWeight(QFont.Weight.DemiBold);painter.setFont(font)
painter.setPen(QColor('#35577d')if option.state&QStyle.StateFlag.State_Selected else QColor('#526983'))
painter.setPen(system_text if high_contrast else
QColor('#35577d')if option.state&QStyle.StateFlag.State_Selected else QColor('#526983'))
label=painter.fontMetrics().elidedText(name,Qt.TextElideMode.ElideRight,available)
painter.drawText(QRect(left,rect.top(),available,23),Qt.AlignmentFlag.AlignVCenter,label)
font.setWeight(QFont.Weight.Normal);font.setPointSizeF(max(8,option.font.pointSizeF()-1));painter.setFont(font)
colors={'执行中':'#8a744d','失败':'#a15f59','已完成':'#638775','待执行':'#6b8ba8'}
painter.setPen(QColor(colors.get(status,'#8999ac')))
painter.setPen(system_text if high_contrast else QColor(colors.get(status,'#8999ac')))
painter.drawText(QRect(left,rect.top()+27,available,19),Qt.AlignmentFlag.AlignVCenter,status)
if order:
painter.setPen(QColor('#94a4b8'))
painter.setPen(system_text if high_contrast else QColor('#94a4b8'))
painter.drawText(QRect(rect.right()-20,rect.top()+2,20,19),Qt.AlignmentFlag.AlignRight,order)
painter.restore()
@@ -0,0 +1,3 @@
"""Shared colors for Qt styling and native-window fallback painting."""
WINDOW_BACKGROUND = '#edf1f5'
@@ -9,8 +9,8 @@ from pathlib import Path
import queue
import re
import subprocess
import threading
import time
import threading
from uuid import uuid4
@@ -18,6 +18,9 @@ class WorkerMonitorError(subprocess.SubprocessError):
pass
_PROGRESS_FAILURE_LOGGED: dict[str, float] = {}
class ProgressWatch:
def __init__(self, token: str, job_id: str, idle_timeout: float, started: float) -> None:
if idle_timeout <= 0:
@@ -131,8 +134,15 @@ def _atomic_text(path: Path, text: str) -> None:
def _publish_progress(path: Path, snapshot: dict) -> None:
try:
_atomic_text(path, json.dumps(snapshot, ensure_ascii=False))
except OSError:
pass # Display telemetry failure must not terminate a possible CAD write.
except OSError as error:
# Telemetry cannot interrupt a CAD write, but the lost state must remain diagnosable.
import logging
now = time.monotonic()
key = str(path)
last = _PROGRESS_FAILURE_LOGGED.get(key, 0.0)
if now - last >= 15:
logging.getLogger(__name__).warning('worker_progress_publish_failed path=%s error=%s', path, error)
_PROGRESS_FAILURE_LOGGED[key] = now
def _decode(data: bytes) -> str: