feat(dsh): add durable supervision, scheduling and operations dock

This commit is contained in:
阿白叔 committed 2026-10-30 18:13:56 +08:00
1 parent f861a3d386
commit 736b582bc1
46 files changed
+4122 -93

No files matched your search

@@ -0,0 +1,38 @@
"""Safe local DSH response settings; provider credentials stay elsewhere."""
import json
from pathlib import Path
from uuid import uuid4
DEFAULTS = {'response_timeout_seconds': 90, 'model_context_limit': 16000}
def validate(raw):
if not isinstance(raw, dict) or set(raw) - set(DEFAULTS):
raise ValueError('unsupported assistant setting')
value = dict(DEFAULTS); value.update(raw)
if type(value['response_timeout_seconds']) is not int or not 15 <= value['response_timeout_seconds'] <= 600:
raise ValueError('response timeout must be 15..600 seconds')
if type(value['model_context_limit']) is not int or not 2000 <= value['model_context_limit'] <= 128000:
raise ValueError('model context limit must be 2000..128000 tokens')
return value
def load_settings(data_root):
try:
return validate(json.loads((Path(data_root) / 'dsh/assistant-settings.json').read_text(encoding='utf8')))
except (OSError, ValueError, TypeError):
return dict(DEFAULTS)
def save_settings(data_root, raw):
from ..trial_task_center.path_access import retry_sharing_violation
value = validate(raw)
path = Path(data_root) / 'dsh/assistant-settings.json'
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name('settings-' + uuid4().hex + '.tmp')
try:
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf8')
retry_sharing_violation(lambda: temporary.replace(path), target=path)
finally:
temporary.unlink(missing_ok=True)
return value
+71
View File
@@ -0,0 +1,71 @@
"""Execute a natively confirmed frozen scope and persist its actual receipt."""
from __future__ import annotations
from . import task_lifecycle as tasks
from .run_journal import RunJournal
from .scheduling import ScheduleStore
from ..trial_task_center.errors import TaskCenterError
from ..trial_task_center.task_queue import execute_task_queue
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None):
if tasks.fingerprint(service, task_ids) != report['fingerprint']:
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
journal = RunJournal(root)
schedules = ScheduleStore(root)
initialized = False
claimed = False
try:
if schedule:
current = next((r for r in schedules.evaluate(service) if r['schedule_id'] == schedule['schedule_id']), None)
if not current or not current['ready'] or current['plan_hashes'] != report['plan_hashes']:
raise TaskCenterError('schedule_blocked', '排期计划、依赖或执行条件已变化,未启动。')
schedules.claim(schedule['schedule_id']); claimed = True
if resume:
inspected = journal.inspect(service, resume['run_id'])
if not inspected['resume_ready'] or inspected['plan_hashes'] != report['plan_hashes']:
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
journal.resume(run_id)
else:
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
initialized = True
result = execute_task_queue(service, tuple(task_ids), stop_event=stop,
expected_plan_hashes=report['plan_hashes'],
queue_id=run_id if resume and resume['queue_available'] else None,
checkpoint_id=None if resume and resume['queue_available'] else run_id)
except Exception as error:
failure = {'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id,
'code': getattr(error, 'code', 'execution_interrupted'), 'message': '执行未完成,请按原队列证据核验后接续。'}
if initialized:
journal.finish(run_id, failure)
if claimed:
schedules.finish(schedule['schedule_id'], 'interrupted', run_id=run_id, receipt=failure)
raise
entries = [{'task_id': e.task_id, 'state': e.state, 'message': e.message} for e in result.entries]
status = ('blocked' if result.paused and any(e['state'] == 'blocked' for e in entries)
else 'paused' if result.paused else 'failed' if any(e['state'] == 'failed' for e in entries) else 'completed')
receipt = {'status': status, 'run_id': run_id, 'queue_id': result.queue_id, 'paused': result.paused,
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
'entries': entries, 'tasks': [], 'reporting_errors': [],
'message': '请按每项实际计数判断;未命中不表示已替换保存。'}
# Persist the executor's known outcome before optional readback/enrichment.
journal.finish(run_id, receipt)
for entry in entries:
actual = {**entry, 'saved_items': None, 'failed_items': None, 'no_match_items': None,
'interrupted': None, 'queue_complete': None}
try:
context = service.task_context(entry['task_id']); p = context.progress
actual.update(name=context.task.name, saved_items=p.saved_items, failed_items=p.failed_items,
no_match_items=p.no_match_items, interrupted=context.interrupted, queue_complete=p.queue_complete)
except Exception as error:
receipt['reporting_errors'].append({'task_id': entry['task_id'], 'code': getattr(error, 'code', 'context_unavailable')})
receipt['tasks'].append(actual)
journal.finish(run_id, receipt)
if claimed:
try:
schedules.finish(schedule['schedule_id'], 'interrupted' if status in {'paused', 'blocked'} else status,
run_id=run_id, receipt=receipt)
except Exception as error:
receipt['reporting_errors'].append({'code': getattr(error, 'code', 'schedule_receipt_unavailable')})
journal.finish(run_id, receipt)
return receipt
+189
View File
@@ -0,0 +1,189 @@
"""A bounded, read-only index of previously recorded DSH incident evidence."""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
import re
from .evidence import scrub, write_json
_IDENTIFIER = re.compile(r"^[0-9a-f]{24}$")
_KNOWN_EVIDENCE = (
"verification.json", "snapshot.json", "snapshot-after.json", "gates.json",
"actions.json", "diagnostics-before.zip", "diagnostics-after.zip", "manifest.json",
)
def _text(value, limit):
# Scrub before bounding so truncation cannot expose a partial credential.
return scrub(value)[:limit] if isinstance(value, str) else ""
def _attempts(value):
return value if type(value) is int and value in (0, 1) else 0
def _retry_error(value):
if not isinstance(value, dict):
return None
return {key: _text(value.get(key), limit) for key, limit in
(("type", 128), ("code", 160), ("detail", 1000))}
def _outcome(verification, *, verified):
result = {"verified": verified}
if isinstance(verification, dict):
for key in ("queue_complete", "interrupted", "paused"):
if type(verification.get(key)) is bool:
result[key] = verification[key]
for key in ("saved_items", "failed_items", "no_match_items", "completed_items"):
if type(verification.get(key)) is int and 0 <= verification[key] <= 10**9:
result[key] = verification[key]
return result
def _newest(value):
try:
date = datetime.fromisoformat(value.replace("Z", "+00:00"))
return date.replace(tzinfo=timezone.utc).timestamp() if date.tzinfo is None else date.timestamp()
except (TypeError, ValueError, OverflowError, OSError):
return 0
class ExperienceStore:
"""Index only incident records and named evidence files; never crawl CAD files."""
def __init__(self, data_root):
self.data_root = Path(data_root)
self.root = self.data_root / "dsh" / "incidents"
self._rows: list[dict] = []
def refresh(self) -> list[dict]:
rows = []
if self.root.is_dir():
for directory in sorted(self.root.iterdir(), key=lambda p: p.name):
path = directory / "incident.json"
if not directory.is_dir() or directory.is_symlink() or not path.is_file() or path.is_symlink():
continue
record = self._read_json(path, 256 * 1024)
if not isinstance(record, dict):
continue
row = self._entry(directory, record)
if row:
rows.append(row)
self._rows = rows
write_json(self.data_root / "dsh" / "experience" / "index.json", {"version": 1, "entries": rows})
return [dict(row) for row in rows]
def _entry(self, directory: Path, record: dict) -> dict | None:
incident_id = str(record.get("incident_id", directory.name))
if not _IDENTIFIER.fullmatch(incident_id) or incident_id != directory.name:
return None
issue_code = str(record.get("issue_code", ""))[:160]
message = str(record.get("message", ""))[:2000]
task_id = str(record.get("task_id", ""))[:128]
evidence_refs = []
# Evidence identity is explicit and bounded. Do not recurse into project/CAD files.
for name in _KNOWN_EVIDENCE:
candidate = directory / name
if candidate.is_file() and not candidate.is_symlink():
evidence_refs.append(candidate.relative_to(self.data_root).as_posix())
verification = None
verification_path = directory / "verification.json"
if verification_path.is_file() and not verification_path.is_symlink():
value = self._read_json(verification_path, 32 * 1024)
verification = scrub(value) if isinstance(value, dict) else None
verified = self._verified(verification, evidence_refs)
analyses = []
if isinstance(record.get("analyses"), list):
for analysis in record["analyses"][:2]:
if isinstance(analysis, dict):
analyses.append({"phase": _text(analysis.get("phase"), 64),
"reply": _text(analysis.get("reply", analysis.get("error")), 1500)})
actions = {}
actions_path = directory / "actions.json"
if actions_path.is_file() and not actions_path.is_symlink():
value = self._read_json(actions_path, 32 * 1024)
if isinstance(value, dict):
# Fixed observational fields only: model tool calls, commands and
# claimed authorizations never become reusable execution rights.
actions = {"attempts": _attempts(value.get("attempts")),
"retry_error": _retry_error(value.get("retry_error")),
"retry_skipped": _text(value.get("retry_skipped"), 1000),
"outcome": _outcome(value.get("verification"), verified=verified)}
newest = _text(record.get("updated_utc") or record.get("created_utc"), 64)
if not newest:
newest = datetime.fromtimestamp((directory / "incident.json").stat().st_mtime,
timezone.utc).isoformat()
return scrub({
"incident_id": incident_id,
"task_id": task_id,
"issue_code": issue_code,
"message": message,
"status": str(record.get("status", ""))[:64],
"verified": verified,
"verification": verification,
"analyses": analyses,
"attempts": _attempts(record.get("attempts")),
"actions": actions,
"retry_error": _retry_error(record.get("retry_error")),
"retry_skipped": _text(record.get("retry_skipped"), 1000),
"outcome": _outcome(verification, verified=verified),
"updated_utc": newest,
"evidence_refs": evidence_refs,
"ticket": {}, # Ticket closure is feedback, never verification.
} | ({"task_name": str(record["task_name"])[:128]} if "task_name" in record else {}))
@staticmethod
def _verified(verification, evidence_refs: list[str]) -> bool:
# verification.json itself is the assertion; require at least one separate
# persisted evidence artifact (snapshot, gates, or diagnostic bundle).
if not isinstance(verification, dict) or len(evidence_refs) < 2:
return False
# These are persisted worker facts, rather than a model's ``resolved`` claim.
return (verification.get("queue_complete") is True
and type(verification.get("failed_items")) is int
and verification.get("failed_items") == 0
and verification.get("interrupted") is False
and verification.get("paused") is False)
def search(self, issue_code: str = "", *, limit: int = 5) -> list[dict]:
if not isinstance(limit, int) or limit <= 0:
return []
if not self._rows:
self.refresh()
query = str(issue_code or "").strip().casefold()
matches = []
for row in self._rows:
context = " ".join((row.get("issue_code", ""), row.get("message", ""),
row.get("task_id", ""), row.get("task_name", ""),
json.dumps(row.get("analyses", []), ensure_ascii=False),
json.dumps(row.get("actions", {}), ensure_ascii=False),
row.get("retry_skipped", ""))).casefold()
if not query or query in context:
matches.append(dict(row))
matches.sort(key=lambda row: (row.get("verified") is True,
bool(query) and row.get("issue_code", "").casefold() == query,
_newest(row.get("updated_utc", "")), row["incident_id"]), reverse=True)
return matches[:min(limit, 50)]
def summary(self) -> dict:
if not self._rows:
self.refresh()
counts = {}
for row in self._rows:
code = row.get("issue_code", "") or "unknown"
counts[code] = counts.get(code, 0) + 1
return {"total": len(self._rows), "verified": sum(bool(row["verified"]) for row in self._rows),
"unverified": sum(not row["verified"] for row in self._rows), "by_issue_code": counts}
@staticmethod
def _read_json(path, limit):
try:
with path.open("rb") as stream:
raw = stream.read(limit + 1)
return json.loads(raw) if len(raw) <= limit else None
except (OSError, ValueError, TypeError):
return None
+194
View File
@@ -0,0 +1,194 @@
"""Read-only execution impact reports for saved DSH task plans.
This module deliberately consumes persisted task contexts and target plans only.
It never scans CAD files or attempts to resolve mapping rules against a project.
"""
from __future__ import annotations
from hashlib import sha256
import json
from typing import Any
from ..trial_task_center.errors import TaskCenterError
_MAX_TASKS = 20
_MAX_LIMIT = 100
def _hash(value: Any) -> str:
encoded = json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(",", ":"), allow_nan=False).encode("utf-8")
return sha256(encoded).hexdigest()
def _scope(task_ids: object) -> tuple[str, ...]:
if not isinstance(task_ids, (list, tuple)) or not 1 <= len(task_ids) <= _MAX_TASKS:
raise TaskCenterError("assistant_task_scope", "请选择 1 至 20 个不同的真实任务。")
if any(not isinstance(task_id, str) or not task_id or len(task_id) > 128 for task_id in task_ids):
raise TaskCenterError("assistant_task_scope", "任务编号无效。")
if len(set(task_ids)) != len(task_ids):
raise TaskCenterError("assistant_task_scope", "请选择 1 至 20 个不同的真实任务。")
return tuple(task_ids)
def _limit(limit: object) -> int:
if type(limit) is not int or not 1 <= limit <= _MAX_LIMIT:
raise TaskCenterError("assistant_impact_limit", "影响预览条数必须是 1 至 100 的整数。")
return limit
def _policy(task, row) -> tuple[str, str | None]:
if bool(getattr(row, "custom_value_enabled", False)):
return "custom", str(getattr(row, "custom_value", ""))
if bool(getattr(task, "copy_part_number_to_value", False)):
# The library label is only known during the CAD execution read. It is
# unsafe for a preview to present the replacement part number as Value.
return "part_label", None
return "preserve", None
def _target_row(task, task_id: str, row) -> dict[str, Any]:
target = row.target
value_policy, proposed = _policy(task, row)
if value_policy == "preserve":
proposed = target.old_value
sync_nc = bool(getattr(row, "sync_nc", True))
target_cell = getattr(row, "target_cell", "")
return {
"task_id": task_id,
"project": str(target.project_path),
"coverage": "exact",
"enabled": bool(row.enabled),
"component_count": int(bool(row.enabled)),
"schematic_name": target.schematic_name,
"sheet": target.sheet_number,
"sheet_number": target.sheet_number,
"refdes": target.refdes,
"uid": target.uid,
"old_part_number": target.old_part_number,
"new_part_number": row.new_part_number,
"old_value": target.old_value,
"proposed_value": proposed,
"value_policy": value_policy,
"target_cell": target_cell,
"target_cell_policy": target_cell,
"sync_nc": sync_nc,
"nc_policy": "sync" if sync_nc else "preserve",
"mapping_scope": None,
}
def _mapping_row(task, context, task_id: str, rule) -> dict[str, Any]:
value_policy, proposed = _policy(task, rule)
project = getattr(context, "project", None)
project_path = str(project.path) if project is not None else ""
sync_nc = bool(getattr(rule, "sync_nc", True))
return {
"task_id": task_id,
"project": project_path,
"coverage": "mapping_only",
"enabled": bool(getattr(rule, "enabled", True)),
"component_count": None,
"schematic_name": None,
"sheet": None,
"sheet_number": None,
"refdes": None,
"uid": None,
"old_part_number": rule.old_part_number,
"new_part_number": rule.new_part_number,
"old_value": None,
"proposed_value": proposed,
"value_policy": value_policy,
"target_cell": getattr(rule, "target_cell", ""),
"target_cell_policy": getattr(rule, "target_cell", ""),
"sync_nc": sync_nc,
"nc_policy": "sync" if sync_nc else "preserve",
"mapping_scope": {"old_part_number": rule.old_part_number,
"new_part_number": rule.new_part_number},
}
def execution_impact(service, task_ids, *, limit: int = 100) -> dict[str, Any]:
"""Return a bounded, deterministic report of the saved execution scope.
Mapping tasks retain ``component_count=None`` because no CAD inventory is
consulted. Exact target plans count enabled saved rows and include their
stable identities and policies.
"""
ids = _scope(task_ids)
bound = _limit(limit)
from ..trial_task_center.task_queue import _plan_hash
all_rows: list[dict[str, Any]] = []
task_reports: list[dict[str, Any]] = []
plan_hashes: dict[str, str] = {}
coverage_values: list[str] = []
known_component_count = 0
enabled_scope = 0
for task_id in ids:
context = service.task_context(task_id)
task = context.task
exact = bool(getattr(task, "target_plan_mode", False))
task_rows: list[dict[str, Any]] = []
if exact:
# service.target_plan() is the authoritative saved-row API and
# retains target_cell on versions whose context projection is old.
saved_rows = tuple(service.target_plan(task_id))
task_rows = [_target_row(task, task_id, row) for row in saved_rows]
task_coverage = "exact"
task_count = sum(row["component_count"] for row in task_rows)
known_component_count += task_count
enabled_scope += task_count
else:
task_rows = [_mapping_row(task, context, task_id, rule)
for rule in tuple(getattr(context, "rules", ()))]
task_coverage = "mapping_only"
enabled_scope += sum(1 for row in task_rows if row["enabled"])
coverage_values.append(task_coverage)
plan_hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
project = getattr(context, "project", None)
task_reports.append({
"task_id": task_id,
"name": getattr(task, "name", ""),
"project": str(project.path) if project is not None else "",
"coverage": task_coverage,
"component_count": task_count if exact else None,
"enabled_scope": sum(row["component_count"] for row in task_rows) if exact else sum(1 for row in task_rows if row["enabled"]),
"total_rows": len(task_rows),
"returned_rows": 0,
"omitted_row_count": 0,
})
all_rows.extend(task_rows)
full_payload = {"task_ids": list(ids), "rows": all_rows, "plan_hashes": plan_hashes}
full_fingerprint = _hash(full_payload)
visible_rows = all_rows[:bound]
remaining = bound
for report in task_reports:
count = min(report["total_rows"], remaining)
report["returned_rows"] = count
report["omitted_row_count"] = report["total_rows"] - count
remaining -= count
omitted = len(all_rows) - len(visible_rows)
coverage = coverage_values[0] if len(set(coverage_values)) == 1 else "mixed"
return {
"task_ids": list(ids),
"coverage": coverage,
"component_count": known_component_count if coverage == "exact" else None,
"known_component_count": known_component_count,
"enabled_scope": enabled_scope,
"tasks": task_reports,
"rows": visible_rows,
"total_rows": len(all_rows),
"returned_rows": len(visible_rows),
"omitted_row_count": omitted,
"truncated": bool(omitted),
"limit": bound,
"plan_hashes": plan_hashes,
"fingerprint": full_fingerprint,
"full_fingerprint": full_fingerprint,
"cad_connection_checked": False,
"read_only": True,
}
+16
View File
@@ -0,0 +1,16 @@
"""Bounded live execution state shared by the task center and DSH dock."""
def read_live_run(service, feedback, *, elapsed, pause_requested, run_id, task_ids):
task_id = feedback.task_id or (task_ids[0] if task_ids else None)
context = service.task_context(task_id) if task_id else None
progress = context.progress if context else None
return {'active': True, 'run_id': run_id, 'task_id': task_id,
'task_ids': list(task_ids), 'name': context.task.name if context else '',
'stage': feedback.stage, 'stage_seconds': feedback.stage_seconds,
'elapsed_seconds': int(elapsed), 'pause_requested': bool(pause_requested),
'saved_items': getattr(progress, 'saved_items', 0),
'failed_items': getattr(progress, 'failed_items', 0),
'no_match_items': getattr(progress, 'no_match_items', 0),
'completed_items': getattr(progress, 'completed_items', 0),
'total_items': getattr(progress, 'total_items', 0), 'component_count_known': False}
+2 -2
View File
@@ -42,11 +42,11 @@ def launch_environment(data_root: Path) -> dict[str, str]:
return env
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None, creation=None, lifecycle=None) -> dict:
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None, creation=None, lifecycle=None, operations=None) -> dict:
data_root.mkdir(parents=True, exist_ok=True)
value = snapshot.safe_dict() | {'revision': uuid4().hex,
'events': [str(e)[:300] for e in events][-20:], 'action_result': str(action_result)[:300],
'task_name': str(task_name)[:128], 'automation': automation or {}, 'creation': creation or {}, 'lifecycle': lifecycle or {}}
'task_name': str(task_name)[:128], 'automation': automation or {}, 'creation': creation or {}, 'lifecycle': lifecycle or {}, 'operations': operations or {}}
temporary = data_root / ('context-' + uuid4().hex + '.tmp')
temporary.write_text(json.dumps(value, ensure_ascii=False), encoding='utf8')
destination = data_root / 'task-context.json'
+221
View File
@@ -0,0 +1,221 @@
"""Durable, Qt-free execution run receipts and read-only recovery inspection."""
from __future__ import annotations
from dataclasses import asdict, is_dataclass
from contextlib import contextmanager
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import sqlite3
from typing import Any
from ..trial_task_center.errors import TaskCenterError
_ID = re.compile(r"^[0-9a-f]{32}$")
_TASK_ID = re.compile(r"(?:[0-9a-f]{32}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})")
def _now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def _json(value: Any) -> Any:
if is_dataclass(value):
return _json(asdict(value))
if isinstance(value, Path):
return str(value)
if isinstance(value, (tuple, list)):
return [_json(item) for item in value]
if isinstance(value, dict):
return {str(key): _json(item) for key, item in value.items()}
return value
def _check_scope(run_id: str, task_ids: Any, plan_hashes: Any) -> tuple[list[str], dict[str, str]]:
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
raise TaskCenterError("run_id", "run identifier is invalid")
if not isinstance(task_ids, (list, tuple)) or not 1 <= len(task_ids) <= 20:
raise TaskCenterError("run_scope", "run must contain 1 to 20 tasks")
ids = list(task_ids)
if any(not isinstance(item, str) or not _TASK_ID.fullmatch(item) for item in ids) or len(set(ids)) != len(ids):
raise TaskCenterError("run_scope", "task identifiers are invalid")
if not isinstance(plan_hashes, dict) or set(plan_hashes) != set(ids) or any(
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value) for value in plan_hashes.values()
):
raise TaskCenterError("run_plan", "frozen plan hashes are invalid")
return ids, dict(plan_hashes)
class RunJournal:
def __init__(self, data_root):
self.data_root = Path(data_root)
self.data_root.mkdir(parents=True, exist_ok=True)
self.path = self.data_root / "dsh-state.sqlite3"
with self._connect() as db:
db.execute("""CREATE TABLE IF NOT EXISTS run_journal (
run_id TEXT PRIMARY KEY, queue_id TEXT NOT NULL UNIQUE, task_ids TEXT NOT NULL,
plan_hashes TEXT NOT NULL, schedule_id TEXT, status TEXT NOT NULL,
started_utc TEXT NOT NULL, finished_utc TEXT, result TEXT)""")
db.execute("""CREATE TABLE IF NOT EXISTS run_journal_receipts (
receipt_id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL,
finished_utc TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL)""")
@contextmanager
def _connect(self):
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
db.row_factory = sqlite3.Row
db.execute("PRAGMA busy_timeout=10000")
db.execute("PRAGMA journal_mode=WAL")
try:
yield db
finally:
db.close()
@staticmethod
def _row(row):
if row is None:
return None
return {"run_id": row["run_id"], "queue_id": row["queue_id"],
"task_ids": json.loads(row["task_ids"]), "plan_hashes": json.loads(row["plan_hashes"]),
"schedule_id": row["schedule_id"], "status": row["status"],
"started_utc": row["started_utc"], "finished_utc": row["finished_utc"],
"result": json.loads(row["result"]) if row["result"] else None}
def begin(self, run_id, task_ids, plan_hashes, *, schedule_id=None):
ids, hashes = _check_scope(run_id, task_ids, plan_hashes)
if schedule_id is not None and (not isinstance(schedule_id, str) or not _ID.fullmatch(schedule_id)):
raise TaskCenterError("schedule_id", "schedule identifier is invalid")
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
existing = db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone()
if existing:
current = self._row(existing)
if current["task_ids"] != ids or current["plan_hashes"] != hashes or current["schedule_id"] != schedule_id:
raise TaskCenterError("run_conflict", "run is already bound to another frozen scope")
db.execute("COMMIT")
return current
started = _now()
db.execute("INSERT INTO run_journal VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL)",
(run_id, run_id, json.dumps(ids), json.dumps(hashes, sort_keys=True), schedule_id, "running", started))
db.execute("COMMIT")
return self.get(run_id)
def finish(self, run_id, result):
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
raise TaskCenterError("run_id", "run identifier is invalid")
value = _json(result)
status = value.get("status") if isinstance(value, dict) else getattr(result, "status", None)
if status not in {"completed", "failed", "paused", "blocked", "interrupted"}:
status = "completed" if isinstance(value, dict) and value.get("paused") is False else "paused"
entries = value.get("entries", []) if isinstance(value, dict) else []
if any(entry.get("state") == "blocked" for entry in entries):
status = "blocked"
elif any(entry.get("state") == "failed" for entry in entries) and status == "completed":
status = "failed"
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
if db.execute("SELECT 1 FROM run_journal WHERE run_id = ?", (run_id,)).fetchone() is None:
raise TaskCenterError("run_missing", "run does not exist")
stamp = _now()
payload = json.dumps(value, ensure_ascii=False)
db.execute("INSERT INTO run_journal_receipts (run_id, finished_utc, status, result) VALUES (?, ?, ?, ?)",
(run_id, stamp, status, payload))
db.execute("UPDATE run_journal SET status = ?, finished_utc = ?, result = ? WHERE run_id = ?",
(status, stamp, payload, run_id))
db.execute("COMMIT")
return self.get(run_id)
def resume(self, run_id):
"""Mark a natively reconfirmed continuation; keep its last durable receipt."""
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status FROM run_journal WHERE run_id = ?", (run_id,)).fetchone()
if row is None:
raise TaskCenterError("run_missing", "run does not exist")
if row["status"] not in {"running", "paused", "blocked", "interrupted"}:
raise TaskCenterError("run_terminal", "this run has no resumable execution")
db.execute("UPDATE run_journal SET status = 'running', finished_utc = NULL WHERE run_id = ?", (run_id,))
db.execute("COMMIT")
return self.get(run_id)
def get(self, run_id):
with self._connect() as db:
return self._row(db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone())
def list_runs(self, limit=20):
if not isinstance(limit, int) or not 1 <= limit <= 1000:
raise TaskCenterError("run_limit", "run limit is invalid")
with self._connect() as db:
rows = db.execute("SELECT * FROM run_journal ORDER BY started_utc DESC LIMIT ?", (limit,)).fetchall()
return [self._row(row) for row in rows]
def inspect(self, service, run_id):
row = self.get(run_id)
if row is None:
raise TaskCenterError("run_missing", "run does not exist")
blockers: list[str] = []
checkpoint = self.data_root / "task-queues" / f"{run_id}.json"
queue = None
try:
queue = json.loads(checkpoint.read_text(encoding="utf-8"))
if queue.get("version") != 1 or queue.get("task_ids") != row["task_ids"] or queue.get("plan_hashes") != row["plan_hashes"]:
raise ValueError
entries = queue["entries"]
if set(entries) != set(row["task_ids"]) or any(
not isinstance(entry, dict) or set(entry) != {"state", "message"} or
entry["state"] not in {"pending", "running", "paused", "blocked", "completed", "failed", "skipped"} or
not isinstance(entry["message"], str) for entry in entries.values()
):
raise ValueError
except (OSError, ValueError, TypeError, KeyError, json.JSONDecodeError):
queue = None
blockers.append("queue_missing" if not checkpoint.exists() else "queue_invalid")
counters = {"completed": 0, "total": 0, "saved_items": 0, "failed_items": 0, "no_match_items": 0}
tasks = []
has_evidence = False
for task_id in row["task_ids"]:
item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0}
try:
context = service.task_context(task_id)
has_evidence = has_evidence or context.has_evidence
progress = context.progress
item.update({"status": context.task.status.value, "interrupted": bool(context.interrupted),
"saved_items": int(getattr(progress, "saved_items", 0)),
"failed_items": int(getattr(progress, "failed_items", 0)),
"no_match_items": int(getattr(progress, "no_match_items", 0)),
"total_items": int(getattr(progress, "total_items", 0))})
for key in ("saved_items", "failed_items", "no_match_items"):
counters[key] += item[key]
counters["total"] += item["total_items"]
if context.interrupted:
blockers.append("interrupted")
if getattr(progress, "failed_items", 0):
blockers.append("failed_items")
from ..trial_task_center.task_queue import _plan_hash
if _plan_hash(service.for_project_task(task_id), task_id) != row["plan_hashes"][task_id]:
blockers.append("plan_changed")
except Exception:
blockers.append("task_unavailable")
tasks.append(item)
if queue:
counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"])
remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}]
if "queue_missing" in blockers and not has_evidence:
# The receipt may have committed before the executor created its checkpoint.
# A native reconfirmation can safely create the original queue; no auto replay.
blockers.remove("queue_missing")
if remaining:
try:
from .task_lifecycle import preflight
if not preflight(service, remaining)["ready"]:
blockers.append("preflight_blocked")
except Exception:
blockers.append("preflight_unavailable")
elif service.pending_batch_resources():
blockers.append("resources_pending")
blockers = list(dict.fromkeys(blockers))
return {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
"remaining_task_ids": remaining, "blockers": blockers, "resume_ready": not blockers,
"requires_confirmation": True,
"cad_execution_started": False, "original_scope": {"task_ids": row["task_ids"], "plan_hashes": row["plan_hashes"]}}
+241
View File
@@ -0,0 +1,241 @@
"""Durable scheduling decisions. This module never starts a worker or CAD operation."""
from __future__ import annotations
from datetime import datetime, timezone
from contextlib import contextmanager
import json
from pathlib import Path
import re
import sqlite3
from typing import Any
from uuid import uuid4
from ..trial_task_center.errors import TaskCenterError
_ID = re.compile(r"^[0-9a-f]{32}$")
_TASK_ID = re.compile(r"(?:[0-9a-f]{32}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})")
_PRIORITY = {"low": 0, "normal": 1, "high": 2, "urgent": 3}
_FIELDS = {"task_ids", "priority", "not_before", "due_at", "dependencies", "auto_start", "idle_only", "title"}
def _utc(value, *, required=False):
if value is None and not required:
return None
if not isinstance(value, str):
raise TaskCenterError("schedule_datetime", "datetime must be an ISO 8601 string with timezone")
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError as error:
raise TaskCenterError("schedule_datetime", "datetime must be an ISO 8601 string with timezone") from error
if parsed.tzinfo is None:
raise TaskCenterError("schedule_datetime", "datetime timezone is required")
return parsed.astimezone(timezone.utc).isoformat(timespec="seconds")
def _now():
return datetime.now(timezone.utc)
def _ids(values, *, required=True):
if not isinstance(values, (list, tuple)) or (required and not 1 <= len(values) <= 20):
raise TaskCenterError("schedule_scope", "schedule must contain 1 to 20 task identifiers")
values = list(values)
if len(values) > 20 or any(not isinstance(value, str) or not _TASK_ID.fullmatch(value) for value in values) or len(set(values)) != len(values):
raise TaskCenterError("schedule_scope", "task identifiers are invalid")
return values
class ScheduleStore:
def __init__(self, data_root):
self.data_root = Path(data_root)
self.data_root.mkdir(parents=True, exist_ok=True)
self.path = self.data_root / "dsh-state.sqlite3"
with self._connect() as db:
db.execute("""CREATE TABLE IF NOT EXISTS schedules (
schedule_id TEXT PRIMARY KEY, task_ids TEXT NOT NULL, plan_hashes TEXT NOT NULL,
priority TEXT NOT NULL, not_before TEXT NOT NULL, due_at TEXT, dependencies TEXT NOT NULL,
auto_start INTEGER NOT NULL, idle_only INTEGER NOT NULL, title TEXT NOT NULL,
status TEXT NOT NULL, created_utc TEXT NOT NULL, updated_utc TEXT NOT NULL,
claimed_utc TEXT, finished_utc TEXT, run_id TEXT, result TEXT)""")
@contextmanager
def _connect(self):
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
db.row_factory = sqlite3.Row
db.execute("PRAGMA busy_timeout=10000")
db.execute("PRAGMA journal_mode=WAL")
try:
yield db
finally:
db.close()
@staticmethod
def _row(row):
if row is None:
return None
return {"schedule_id": row["schedule_id"], "task_ids": json.loads(row["task_ids"]),
"plan_hashes": json.loads(row["plan_hashes"]), "priority": row["priority"],
"not_before": row["not_before"], "due_at": row["due_at"],
"dependencies": json.loads(row["dependencies"]), "auto_start": bool(row["auto_start"]),
"idle_only": bool(row["idle_only"]), "title": row["title"], "status": row["status"],
"created_utc": row["created_utc"], "updated_utc": row["updated_utc"],
"claimed_utc": row["claimed_utc"], "finished_utc": row["finished_utc"],
"run_id": row["run_id"], "result": json.loads(row["result"]) if row["result"] else None}
def get(self, schedule_id):
with self._connect() as db:
return self._row(db.execute("SELECT * FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone())
def list_schedules(self):
with self._connect() as db:
return [self._row(row) for row in db.execute("SELECT * FROM schedules ORDER BY not_before, created_utc").fetchall()]
def _validate_spec(self, spec, plan_hashes):
if not isinstance(spec, dict) or set(spec) - _FIELDS:
raise TaskCenterError("schedule_fields", "schedule contains unsupported fields")
ids = _ids(spec.get("task_ids"))
if not isinstance(spec.get("priority", "normal"), str) or spec.get("priority", "normal") not in _PRIORITY:
raise TaskCenterError("schedule_priority", "schedule priority is invalid")
before = _utc(spec.get("not_before"), required=True)
due = _utc(spec.get("due_at"))
if due and due < before:
raise TaskCenterError("schedule_datetime", "due time cannot precede not-before time")
dependencies = _ids(spec.get("dependencies", []), required=False)
if set(ids) & set(dependencies):
raise TaskCenterError("schedule_dependency", "schedule cannot depend on itself")
if not isinstance(spec.get("auto_start", False), bool) or not isinstance(spec.get("idle_only", True), bool):
raise TaskCenterError("schedule_fields", "schedule switches must be booleans")
title = spec.get("title", "")
if not isinstance(title, str) or len(title) > 200 or "\x00" in title:
raise TaskCenterError("schedule_title", "schedule title is invalid")
if not isinstance(plan_hashes, dict) or set(plan_hashes) != set(ids) or any(
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value) for value in plan_hashes.values()
):
raise TaskCenterError("schedule_plan", "frozen plan hashes are invalid")
return ids, dict(plan_hashes), spec.get("priority", "normal"), before, due, dependencies, bool(spec.get("auto_start", False)), bool(spec.get("idle_only", True)), title
def _check_cycles(self, db, ids, dependencies):
graph = {}
for stored in db.execute("SELECT * FROM schedules WHERE status IN ('pending', 'claimed')").fetchall():
row = self._row(stored)
for task_id in row["task_ids"]:
graph.setdefault(task_id, set()).update(row["dependencies"])
for task_id in ids:
graph.setdefault(task_id, set()).update(dependencies)
def visit(node, active, seen):
if node in active:
return True
if node in seen:
return False
seen.add(node); active.add(node)
if any(visit(dep, active, seen) for dep in graph.get(node, ())):
return True
active.remove(node)
return False
if any(visit(node, set(), set()) for node in graph):
raise TaskCenterError("schedule_dependency_cycle", "schedule dependencies contain a cycle")
def preview(self, spec, plan_hashes):
"""Normalize a native confirmation draft without saving or granting authority."""
ids, _, priority, before, due, deps, auto_start, idle_only, title = self._validate_spec(spec, plan_hashes)
with self._connect() as db:
self._check_cycles(db, ids, deps)
return {"task_ids": ids, "priority": priority, "not_before": before, "due_at": due,
"dependencies": deps, "auto_start": auto_start, "idle_only": idle_only, "title": title}
def save(self, spec, plan_hashes):
ids, hashes, priority, before, due, deps, auto_start, idle_only, title = self._validate_spec(spec, plan_hashes)
schedule_id = uuid4().hex
stamp = _now().isoformat(timespec="seconds")
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
self._check_cycles(db, ids, deps)
db.execute("INSERT INTO schedules VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL)",
(schedule_id, json.dumps(ids), json.dumps(hashes, sort_keys=True), priority, before, due,
json.dumps(deps), int(auto_start), int(idle_only), title, "pending", stamp, stamp))
db.execute("COMMIT")
return self.get(schedule_id)
def cancel(self, schedule_id):
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
if row is None:
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
if row["status"] != "pending":
db.execute("ROLLBACK"); raise TaskCenterError("schedule_owned", "claimed or finished schedules cannot be cancelled")
db.execute("UPDATE schedules SET status = 'cancelled', updated_utc = ? WHERE schedule_id = ?", (_now().isoformat(timespec="seconds"), schedule_id))
db.execute("COMMIT")
return self.get(schedule_id)
def claim(self, schedule_id):
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
if row is None:
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
if row["status"] != "pending":
db.execute("ROLLBACK"); raise TaskCenterError("schedule_claimed", "schedule is already claimed or finished")
stamp = _now().isoformat(timespec="seconds")
db.execute("UPDATE schedules SET status = 'claimed', claimed_utc = ?, updated_utc = ? WHERE schedule_id = ?", (stamp, stamp, schedule_id))
db.execute("COMMIT")
return self.get(schedule_id)
def finish(self, schedule_id, status, **values):
if status not in {"completed", "failed", "interrupted", "cancelled"}:
raise TaskCenterError("schedule_status", "schedule finish status is invalid")
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
if row is None:
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
if row["status"] != "claimed":
db.execute("ROLLBACK"); raise TaskCenterError("schedule_status", "only a claimed schedule can finish")
stamp = _now().isoformat(timespec="seconds")
db.execute("UPDATE schedules SET status = ?, updated_utc = ?, finished_utc = ?, run_id = ?, result = ? WHERE schedule_id = ?",
(status, stamp, stamp, values.get("run_id"), json.dumps(values, ensure_ascii=False), schedule_id))
db.execute("COMMIT")
return self.get(schedule_id)
def _completed(self, service, task_id):
try:
context = service.task_context(task_id)
progress = context.progress
return context.task.status.value == "completed" and not context.interrupted and bool(progress.queue_complete) and not getattr(progress, "failed_items", 0)
except Exception:
return False
def evaluate(self, service, *, now=None, busy=False):
when = now or _now()
if when.tzinfo is None:
raise TaskCenterError("schedule_datetime", "evaluation time timezone is required")
rows = []
from ..trial_task_center.task_queue import _plan_hash
for row in self.list_schedules():
blockers = []
if row["status"] == "claimed": blockers.append("already_claimed")
elif row["status"] != "pending": blockers.append("finished")
if datetime.fromisoformat(row["not_before"]) > when.astimezone(timezone.utc): blockers.append("not_due")
if busy: blockers.append("worker_busy")
try:
for task_id in row["task_ids"]:
if service.task_context(task_id).task.status.value == "paused":
blockers.append("task_paused")
if _plan_hash(service.for_project_task(task_id), task_id) != row["plan_hashes"][task_id]:
blockers.append("plan_changed")
except Exception:
blockers.append("task_unavailable")
try:
from .task_lifecycle import preflight
check = preflight(service, row["task_ids"])
if not check["ready"]:
blockers.append("preflight_blocked")
except Exception:
blockers.append("preflight_unavailable")
if row["dependencies"] and not all(self._completed(service, task_id) for task_id in row["dependencies"]): blockers.append("dependency_incomplete")
blockers = list(dict.fromkeys(blockers))
rows.append({**row, "blockers": blockers, "ready": not blockers,
"requires_confirmation": True, "dispatchable": False,
"scope": {"task_ids": row["task_ids"], "plan_hashes": row["plan_hashes"]}})
rows.sort(key=lambda item: (-_PRIORITY[item["priority"]], item["not_before"], item["created_utc"]))
return rows
+7 -3
View File
@@ -40,7 +40,7 @@ def fingerprint(service, ids):
return _digest([asdict(_context(service, key)) for key in ids])
def preflight(service, task_ids):
def preflight(service, task_ids, *, allow_completed=False):
from ..trial_task_center.ui.execution_state import execution_state
from ..trial_task_center.task_queue import _plan_hash
if not isinstance(task_ids, list) or not 1 <= len(task_ids) <= 20 or len(set(task_ids)) != len(task_ids):
@@ -51,7 +51,9 @@ def preflight(service, task_ids):
context = _context(service, task_id)
state = execution_state(context)
blockers = []
if not state.execute:
finished = (allow_completed and context.task.status is TaskStatus.COMPLETED
and context.progress.queue_complete and not context.progress.failed_items and not context.interrupted)
if not state.execute and not finished:
blockers.append(state.message)
if context.phase == 'retry':
blockers.append('存在失败项,请先核对证据并准备失败项重试。')
@@ -76,7 +78,9 @@ def preflight(service, task_ids):
'phase': context.phase, 'blockers': list(dict.fromkeys(blockers)),
'saved_items': context.progress.saved_items, 'failed_items': context.progress.failed_items,
'no_match_items': context.progress.no_match_items})
return {'ready': all(not t['blockers'] for t in tasks), 'tasks': tasks,
from .impact import execution_impact
impact = execution_impact(service, task_ids)
return {'ready': all(not t['blockers'] for t in tasks), 'tasks': tasks, 'impact': impact,
'plan_hashes': hashes, 'fingerprint': fingerprint(service, task_ids),
'cad_connection_checked': False,
'message': '已核对保存的配置和执行证据;CAD 连接、备份与保存核验由正式执行流程完成。'}
+177
View File
@@ -0,0 +1,177 @@
"""Read-only tracking of the fixed issue associated with an existing incident."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import urllib.parse
import urllib.request
from .evidence import scrub, write_json
from .git_issues import GitIssuePublisher, NoRedirect
from .issue_credentials import issue_target
_IDENTIFIER = re.compile(r"^[0-9a-f]{24}$")
_MAX_COMMENTS = 20
_MAX_BYTES = 2 * 1024 * 1024
class TicketTracker:
def __init__(self, data_root):
self.data_root = Path(data_root)
self.incidents = self.data_root / "dsh" / "incidents"
self.cache_root = self.data_root / "dsh" / "ticket-cache"
self.config_path = self.data_root / "dsh" / "issue-config.json"
def refresh(self, incident_id: str) -> dict:
if not isinstance(incident_id, str) or not _IDENTIFIER.fullmatch(incident_id):
raise ValueError("invalid_incident_id")
incident_path = self.incidents / incident_id / "incident.json"
local = self._read_json(incident_path)
if not isinstance(local, dict) or local.get("incident_id") != incident_id:
return self._unavailable(incident_id, "incident_unavailable")
ticket = local.get("ticket")
if not isinstance(ticket, dict):
return self._unavailable(incident_id, "ticket_unavailable")
try:
target = issue_target(self.config_path)
except (OSError, ValueError, TypeError):
return self._unavailable(incident_id, "invalid_issue_config")
expected = self._target_url(target, ticket)
if expected is None:
return self._unavailable(incident_id, "invalid_ticket_target")
# Strict local target checks complete before credentials are obtained.
try:
config, auth, source = GitIssuePublisher(self.config_path).connection()
except Exception as error:
return self._unavailable(incident_id, type(error).__name__)
if not auth:
return self._unavailable(incident_id, source)
if self._target_url(config, ticket) != expected:
return self._unavailable(incident_id, "invalid_ticket_target")
try:
owner, repo = config["repository"].split("/", 1)
parsed = urllib.parse.urlsplit(config["server"])
api = f"{parsed.scheme}://{parsed.netloc}/api/v1/repos/{owner}/{repo}/issues/{ticket['number']}"
opener = urllib.request.build_opener(NoRedirect())
issue = self._get(opener, api, auth)
if not isinstance(issue, dict) or not self._remote_matches(issue, incident_id, expected, ticket["number"]):
return self._unavailable(incident_id, "ticket_identity_mismatch")
count = issue.get("comments", 0)
page = max(1, (count - 1) // _MAX_COMMENTS + 1) if type(count) is int and 0 <= count <= 10**7 else 1
comments = self._get(opener, api + "/comments?" + urllib.parse.urlencode({"page": page, "limit": _MAX_COMMENTS}), auth)
if not isinstance(comments, list):
comments = []
comments = [scrub(self._comment(row)) for row in comments[:_MAX_COMMENTS] if isinstance(row, dict)]
now = datetime.now(timezone.utc).isoformat()
result = scrub({"incident_id": incident_id, "number": ticket["number"], "url": expected,
"state": str(issue.get("state", "unknown"))[:32],
"title": str(issue.get("title", ""))[:300], "updated_at": issue.get("updated_at"),
"comments": comments, "status": "synced", "last_sync_at": now, "last_attempt_at": now,
"credential_source": source, "locally_verified": False})
self._save_cache(incident_id, result)
return result
except Exception as error:
return self._unavailable(incident_id, type(error).__name__)
def list_tickets(self) -> list[dict]:
try:
target = issue_target(self.config_path)
except (OSError, ValueError, TypeError):
return []
rows = []
if not self.incidents.is_dir():
return rows
# Discover tickets from the existing incident binding, not cache filenames
# or a caller-provided URL. Listing is entirely local and does not obtain auth.
for directory in sorted(self.incidents.iterdir(), key=lambda value: value.name):
identity = directory.name
if not _IDENTIFIER.fullmatch(identity) or not directory.is_dir() or directory.is_symlink():
continue
incident = self._read_json(directory / "incident.json")
if not isinstance(incident, dict) or incident.get("incident_id") != identity:
continue
ticket = incident.get("ticket")
if not isinstance(ticket, dict):
continue
expected = self._target_url(target, ticket)
if expected is None:
continue
binding = {"incident_id": identity, "number": ticket["number"], "url": expected,
"status": "not_synced", "last_sync_at": None, "locally_verified": False}
value = self._read_json(self.cache_root / f"{identity}.json")
if (not isinstance(value, dict) or value.get("incident_id") != identity
or value.get("number", ticket["number"]) != ticket["number"]
or value.get("url", expected) != expected):
value = {}
rows.append(scrub(binding | value))
if len(rows) >= 100:
break
return rows
def _target_url(self, config: dict, ticket: dict):
number = ticket.get("number")
url = ticket.get("url") or ticket.get("html_url")
if isinstance(number, bool) or not isinstance(number, int) or number <= 0 or number > 2**31:
return None
if not isinstance(url, str):
return None
try:
server = urllib.parse.urlsplit(str(config.get("server", "")))
value = urllib.parse.urlsplit(url)
owner, repo = str(config.get("repository", "")).split("/", 1)
if (server.scheme != "https" or not server.hostname or server.username or server.password
or server.path not in {"", "/"} or server.query or server.fragment
or not all(re.fullmatch(r"[\w.-]+", part) and part not in {".", ".."} for part in (owner, repo))):
return None
expected = f"{server.scheme}://{server.netloc}/{owner}/{repo}/issues/{number}"
if (value.scheme, value.netloc, value.path, value.query, value.fragment, value.username, value.password) != (
server.scheme, server.netloc, f"/{owner}/{repo}/issues/{number}", "", "", None, None):
return None
return expected
except (ValueError, TypeError):
return None
@staticmethod
def _remote_matches(issue, incident_id, expected, number):
return (issue.get("number") == number and issue.get("html_url") == expected
and (f"[DSH:{incident_id}]" in str(issue.get("title", ""))
or f"[DSH:{incident_id}]" in str(issue.get("body", ""))))
@staticmethod
def _comment(row):
return {"id": row.get("id"), "body": str(row.get("body", ""))[:4000],
"created_at": row.get("created_at"), "updated_at": row.get("updated_at"),
"user": {"login": str((row.get("user") or {}).get("login", ""))[:128]}}
@staticmethod
def _get(opener, url, auth):
request = urllib.request.Request(url, headers=auth | {"Accept": "application/json"}, method="GET")
with opener.open(request, timeout=25) as response:
return json.loads(response.read(_MAX_BYTES))
def _unavailable(self, incident_id, error):
cached = self._read_json(self.cache_root / f"{incident_id}.json")
result = dict(cached) if isinstance(cached, dict) else {"incident_id": incident_id}
result.update(status="unavailable", error=error, last_attempt_at=datetime.now(timezone.utc).isoformat())
# Exception text can contain credentials or URLs. Keep only the typed error.
result = scrub(result)
self._save_cache(incident_id, result)
return result
def _save_cache(self, incident_id, value):
self.cache_root.mkdir(parents=True, exist_ok=True)
write_json(self.cache_root / f"{incident_id}.json", value)
@staticmethod
def _read_json(path):
try:
if not path.is_file() or path.is_symlink():
return None
with path.open("rb") as stream:
raw = stream.read(_MAX_BYTES + 1)
return json.loads(raw) if len(raw) <= _MAX_BYTES else None
except (OSError, ValueError, TypeError):
return None
@@ -84,6 +84,7 @@ def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
row['uid'], row['refdes'], row['old_part_number'], row['old_value']),
bool(row['enabled']), row['new_part_number'], bool(row['custom_value_enabled']),
row['custom_value'], bool(row['sync_nc']),
row['target_cell'],
)
targets = records(
"SELECT * FROM target_plan WHERE task_id = ? ORDER BY project_path, schematic_name, sheet_number, refdes, uid",
@@ -129,16 +129,17 @@ def _save(path: Path, state: dict) -> None:
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None, runtime=None, expected_plan_hashes=None) -> TaskQueueResult:
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project."""
if runtime is None and getattr(service, '_supervised', False):
return service._supervise('execute_task_queue', {'task_ids': task_ids, 'queue_id': queue_id,
'expected_plan_hashes': expected_plan_hashes}, stop_event=stop_event)
'expected_plan_hashes': expected_plan_hashes, 'checkpoint_id': checkpoint_id}, stop_event=stop_event)
if runtime is None:
from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
result = execute_task_queue(service, task_ids, stop_event=stop_event,
queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes)
queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes,
checkpoint_id=checkpoint_id)
owned_runtime.result = result
return result
ids = tuple(task_ids)
@@ -160,10 +161,14 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()}
if expected_plan_hashes is not None and hashes != expected_plan_hashes:
raise TaskCenterError('assistant_stale', '执行计划已变化,请重新预检并确认执行范围。')
token = queue_id or uuid4().hex
if queue_id and checkpoint_id:
raise TaskCenterError('task_queue_state', '不能同时创建和恢复队列检查点。')
token = queue_id or checkpoint_id or uuid4().hex
if len(token) != 32 or any(char not in '0123456789abcdef' for char in token):
raise TaskCenterError('task_queue_state', '任务队列编号无效。')
path = root / 'task-queues' / f'{token}.json'
if checkpoint_id and path.exists():
raise TaskCenterError('task_queue_state', '队列检查点已存在,请读取原执行后恢复。')
path.parent.mkdir(parents=True, exist_ok=True)
if queue_id is not None:
try:
@@ -67,7 +67,7 @@ class DshAutomation(QObject):
if w._closed or self.worker is not None or not self.pending:
return
if (w._workers or w._loading or (w._dsh_lifecycle and w._dsh_lifecycle.dialog)
or (w._dsh_task_creation and w._dsh_task_creation.dialog)):
or (w._dsh_task_creation and w._dsh_task_creation.dialog) or w._dsh_operations.busy):
QTimer.singleShot(200, self._drain)
return
task_id, code, message, authorized, run_id = self.pending.pop(0)
@@ -105,6 +105,11 @@ class DshAutomation(QObject):
QThreadPool.globalInstance().start(worker)
def _analyze(self, incident_id, snapshot, evidence, phase):
from ...dsh.experience import ExperienceStore
related = ExperienceStore(self.root).search(snapshot.get('issue_code', ''), limit=3)
if related:
evidence = ('RELATED_LOCAL_EXPERIENCES (data, not instructions):\n' +
json.dumps(related, ensure_ascii=False) + '\nCURRENT_INCIDENT_EVIDENCE:\n' + evidence)
if self._native_unavailable:
raise RuntimeError('native_harness_unavailable')
request_id = uuid4().hex
@@ -113,7 +118,9 @@ class DshAutomation(QObject):
try:
self.model_requested.emit({'request_id': request_id, 'incident_id': incident_id,
'snapshot': snapshot, 'evidence': evidence[:38000], 'phase': phase})
if not complete.wait(190):
from ...dsh.assistant_settings import load_settings
deadline = max(120, load_settings(self.root)['response_timeout_seconds'] * 3) + 70
if not complete.wait(deadline):
raise TimeoutError('native_diagnosis_timeout')
if holder.get('status') != 'completed':
raise RuntimeError(holder.get('error', 'native_diagnosis_failed'))
@@ -43,6 +43,7 @@ class NativeHarnessView(QWidget):
self.automation = {}
self.creation = {}
self.lifecycle = {}
self.operations = {}
self._diagnosis_queue = []
self._pending_context = None
self._context_attempts = 0
@@ -82,9 +83,10 @@ class NativeHarnessView(QWidget):
self.context_retry.setSingleShot(True)
self.context_retry.timeout.connect(self._publish_pending_context)
def bind(self, snapshot: TaskSnapshot, *, events=(), action_result='', task_name=''):
def bind(self, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', operations=None):
self.operations = dict(operations or {})
self._pending_context = (snapshot, {'events': tuple(events), 'action_result': action_result, 'task_name': task_name,
'automation': dict(self.automation), 'creation': dict(self.creation), 'lifecycle': dict(getattr(self, 'lifecycle', {}))})
'automation': dict(self.automation), 'creation': dict(self.creation), 'lifecycle': dict(getattr(self, 'lifecycle', {})), 'operations': dict(self.operations)})
self._context_attempts = 0
self._publish_pending_context()
@@ -148,7 +150,7 @@ class NativeHarnessView(QWidget):
self.process.setProgram(node)
self.process.setArguments([str(root / 'start.mjs')])
self.process.start()
self.timeout.start(60000)
self.timeout.start(120000)
def _stdout(self):
self._buffer += bytes(self.process.readAllStandardOutput()).decode('utf8', 'replace')
@@ -0,0 +1,349 @@
"""Application-owned operations, persisted planning and native confirmations."""
from __future__ import annotations
from datetime import datetime, timedelta
import json
import re
from uuid import uuid4
from shiboken6 import isValid
from PySide6.QtCore import QObject, QThreadPool, QTimer
from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox, QDialogButtonBox,
QFormLayout, QLabel, QLineEdit, QPlainTextEdit)
from ...dsh import task_lifecycle as tasks
from ...dsh.run_journal import RunJournal
from ...dsh.scheduling import ScheduleStore
from ...dsh.experience import ExperienceStore
from ...dsh.ticket_tracking import TicketTracker
from ...dsh.impact import execution_impact
from ..errors import TaskCenterError
from .dsh_task_lifecycle import DshLifecycleDialog
from .workers import ServiceWorker
class DshScheduleDialog(DshLifecycleDialog):
def __init__(self, spec, report, parent):
scope = '\n'.join(f"{t['name']} [{t['task_id']}]\n{t['project']}" for t in report['tasks'])
impact = report.get('impact', {})
scope += '\n\n' + ('器件数量未知,仅有料号映射。' if impact.get('component_count') is None else f"已选中 {impact['component_count']} 个器件。")
for row in impact.get('rows', []):
scope += f"\n{row.get('refdes') or '映射范围'}:{row['old_part_number']} → {row['new_part_number']} · Value {row.get('value_policy')} · Cell {row.get('target_cell') or '自动匹配'} · NC {row.get('sync_nc')}"
super().__init__('保存任务排期', scope + '\n\n应用打开且空闲时检查排期;计划变化、未保存编辑、暂停或待核验结果会阻断。', parent)
self.setObjectName('dshScheduleDialog')
form = QFormLayout()
self.title_edit = QLineEdit(spec.get('title', ''), objectName='dshScheduleTitle')
self.time_edit = QLineEdit(spec['not_before'], objectName='dshScheduleTime')
self.due_edit = QLineEdit(spec.get('due_at') or '', objectName='dshScheduleDue')
self.priority = QComboBox(objectName='dshSchedulePriority')
for name, key in [('低', 'low'), ('普通', 'normal'), ('高', 'high'), ('紧急', 'urgent')]:
self.priority.addItem(name, key)
self.priority.setCurrentIndex(self.priority.findData(spec.get('priority', 'normal')))
self.dependencies = QLineEdit(','.join(spec.get('dependencies', [])), objectName='dshScheduleDependencies')
self.auto_start = QCheckBox('授权到时空闲自动执行并保存以上工程(仍检查原有门禁)', objectName='dshScheduleAutoStart')
self.auto_start.setChecked(spec.get('auto_start', False))
for label, widget in [('名称', self.title_edit), ('最早运行时间(含时区)', self.time_edit),
('截止时间(可留空)', self.due_edit), ('优先级', self.priority), ('前置任务编号(逗号分隔)', self.dependencies)]:
form.addRow(label, widget)
self.layout().insertLayout(1, form)
self.layout().insertWidget(2, self.auto_start)
self.resize(820, 700)
self.spec = spec
def values(self):
return {**self.spec, 'title': self.title_edit.text().strip(), 'not_before': self.time_edit.text().strip(),
'due_at': self.due_edit.text().strip() or None, 'priority': self.priority.currentData(),
'dependencies': [x.strip() for x in self.dependencies.text().split(',') if x.strip()],
'auto_start': self.auto_start.isChecked(), 'idle_only': True}
class DshOperationsController(QObject):
def __init__(self, window):
super().__init__(window)
self.window = window
self.root = window.service.layout_settings_path.parent
self.runs = RunJournal(self.root)
self.schedules = ScheduleStore(self.root)
self.experiences = ExperienceStore(self.root)
self.tickets = TicketTracker(self.root)
self.dialog = None
self.worker = None
self.request_id = None
self.results = {}
self.cache = {'runs': [], 'schedules': [], 'experiences': [], 'tickets': [], 'activity': {}}
self.timer = QTimer(self)
self.timer.setInterval(15000)
self.timer.timeout.connect(self.tick)
self._ticks = 0
if QApplication.platformName().casefold() != 'offscreen':
self.timer.start()
QTimer.singleShot(0, self.refresh)
@property
def busy(self):
return bool(self.worker or self.dialog or self.request_id)
def attach(self, view):
view.stopped.connect(self.runtime_stopped)
def context(self):
return {**self.cache, 'busy': bool(self.busy or self.window._workers or self._other_dialog())}
def _state(self, status, message='', **values):
self.cache['activity'] = {'status': status, 'message': message, **values}
self.window._bind_dsh_context()
def _respond(self, request_id, **result):
value = {'request_id': request_id, **result}
self.results[request_id] = value
if len(self.results) > 100:
self.results.pop(next(iter(self.results)))
if self.request_id == request_id:
self.request_id = None
self._state(result['status'], result.get('message', ''))
if self.window._dsh_view:
self.window._dsh_view.complete_lifecycle(value)
def _failed(self, request_id, error):
if not isinstance(error, (TaskCenterError, ValueError)):
self.window.service.report_ui_error(error)
self._respond(request_id, status='rejected', message=getattr(error, 'message', '操作未完成,请核对输入或保留日志。'),
code=getattr(error, 'code', 'operations_error'))
def _work(self, action, done, *, request_id=None, reserve_lane=True):
worker = ServiceWorker(action)
self.worker = worker
if reserve_lane:
self.window._workers.add(worker)
def succeeded(value):
if not isValid(self.window) or self.window._closed or (request_id and self.request_id != request_id):
return
try:
done(value)
except Exception as error:
self._failed(request_id or uuid4().hex, error)
def failed(error):
if not isValid(self.window) or self.window._closed:
return
if request_id:
self._failed(request_id, error)
else:
self._state('unavailable', '监管记录暂不可用,已有执行不受影响。')
def finished():
self.window._workers.discard(worker)
if self.worker is worker:
self.worker = None
if not isValid(self.window) or self.window._closed:
return
self.window._bind_dsh_context()
self.window._update_gates()
if self.window._close_pending:
QTimer.singleShot(0, self.window.close)
worker.signals.succeeded.connect(succeeded); worker.signals.failed.connect(failed)
worker.signals.finished.connect(finished)
self.window._update_gates()
QThreadPool.globalInstance().start(worker)
def _read(self, *, synchronize_tickets=False):
service = self.window.service
runs = []
for row in self.runs.list_runs():
value = self.runs.inspect(service, row['run_id'])
if not value.get('remaining_task_ids') or value['status'] == 'completed':
value['resume_ready'] = False
runs.append(value)
tickets = self.tickets.list_tickets()
if synchronize_tickets:
# One existing ticket per refresh keeps the desktop responsive and
# avoids polling every model turn or creating any remote content.
candidates = sorted(tickets, key=lambda row: row.get('last_attempt_at') or '')
if candidates:
self.tickets.refresh(candidates[0]['incident_id'])
tickets = self.tickets.list_tickets()
return {'runs': runs, 'schedules': self.schedules.evaluate(service),
'experiences': self.experiences.refresh()[:20], 'tickets': tickets[:20]}
def refresh(self, *, synchronize_tickets=False):
if self.window._closed or self.window._workers or self.busy or self._other_dialog():
return
def done(value):
self.cache.update(value)
self.window._bind_dsh_context()
self._work(lambda: self._read(synchronize_tickets=synchronize_tickets), done, reserve_lane=False)
def _other_dialog(self):
lifecycle = self.window._dsh_lifecycle
creation = self.window._dsh_task_creation
return bool((lifecycle and lifecycle.request_id) or (creation and creation.request_id))
def tick(self):
if self.window._closed or self.window._workers or self.busy or self._other_dialog():
return
self._ticks += 1
def ready(value):
self.cache.update(value)
self.window._bind_dsh_context()
candidate = next((r for r in value['schedules'] if r['ready'] and r['auto_start']), None)
if candidate and not self.window.plan_panel.has_unsaved_plan(candidate['task_ids']):
# Preserve the original native future-run authorization. This
# is not a model-supplied confirmation flag.
QTimer.singleShot(0, lambda: self._dispatch(candidate, automatic=True))
self._work(lambda: self._read(synchronize_tickets=self._ticks % 20 == 0), ready)
def _dispatch(self, row, *, automatic, request_id=None):
if not isValid(self.window) or self.window._closed:
return
if self.worker:
# The read result can arrive before that worker's finished signal.
QTimer.singleShot(100, lambda: self._dispatch(row, automatic=automatic, request_id=request_id))
return
if self.window._workers or self.window._closed or self.busy:
return
self.window._ensure_dsh_view()
self.window._dsh_lifecycle.start_schedule(row, automatic=automatic, request_id=request_id)
def request(self, value):
key = value.get('request_id'); spec = value.get('spec')
if not isinstance(key, str) or not re.fullmatch('[a-f0-9]{32}', key):
return
if key in self.results:
if self.window._dsh_view:
self.window._dsh_view.complete_lifecycle(self.results[key])
return
if not isinstance(spec, dict):
self._failed(key, ValueError('invalid operation')); return
op = spec.get('operation')
if op == 'pause':
if set(spec) != {'operation', 'task_ids'}:
self._failed(key, ValueError('invalid pause')); return
self.window._dsh_lifecycle.request({'request_id': key, 'capability': 'execute',
'spec': {'operation': 'pause', 'task_ids': spec['task_ids']}})
return
if op == 'resume':
if set(spec) != {'operation', 'run_id'}:
self._failed(key, ValueError('invalid resume')); return
self.window._dsh_lifecycle.request({'request_id': key, 'capability': 'execute',
'spec': {'operation': 'resume', 'run_id': spec['run_id']}})
return
if self.busy or self.window._workers or self._other_dialog() or self.window._closed:
self._respond(key, status='busy', message='请等待当前操作或确认窗口收尾。'); return
self.request_id = key
self._state('checking')
allowed = {
'refresh': set(), 'history': set(), 'impact': {'task_ids'}, 'experience': {'issue_code'}, 'tickets': set(),
'refresh_ticket': {'incident_id'}, 'schedule_dialog': {'task_ids'}, 'cancel_schedule': {'schedule_id'},
'run_schedule': {'schedule_id'}, 'open_incident': {'incident_id'},
'schedule': {'task_ids', 'priority', 'not_before', 'due_at', 'dependencies', 'auto_start', 'idle_only', 'title'}}
if op not in allowed or set(spec) - ({'operation'} | allowed[op]):
self._failed(key, ValueError('unknown operation fields')); return
if op in {'refresh', 'history', 'tickets'}:
def read(value):
self.cache.update(value)
self._respond(key, status='read', **value)
self._work(self._read, read, request_id=key)
elif op == 'impact':
def impact(report):
self.cache['impact'] = report
self._respond(key, status='impact', **report)
self._work(lambda: execution_impact(self.window.service, spec.get('task_ids')), impact, request_id=key)
elif op == 'experience':
def found(rows):
self.cache['experiences'] = rows
self._respond(key, status='experience', experiences=rows)
self._work(lambda: self.experiences.search(spec.get('issue_code', '')), found, request_id=key)
elif op == 'refresh_ticket':
def synced(row):
self.cache['tickets'] = self.tickets.list_tickets()[:20]
self._respond(key, status='ticket', ticket=row)
self._work(lambda: self.tickets.refresh(spec.get('incident_id')), synced, request_id=key)
elif op == 'open_incident':
incident = spec.get('incident_id')
if not isinstance(incident, str) or not re.fullmatch('[a-f0-9]{24}', incident):
self._failed(key, ValueError('invalid incident')); return
path = self.root / 'dsh/incidents' / incident
if not (path / 'incident.json').is_file():
self._failed(key, ValueError('incident unavailable')); return
from PySide6.QtCore import QUrl
from PySide6.QtGui import QDesktopServices
QDesktopServices.openUrl(QUrl.fromLocalFile(str(path)))
self._respond(key, status='opened', incident_id=incident)
elif op in {'schedule', 'schedule_dialog'}:
ids = spec.get('task_ids')
if self.window.plan_panel.has_unsaved_plan(ids if isinstance(ids, list) else ()):
self._failed(key, TaskCenterError('assistant_dirty', '请先保存所选任务的位号计划。')); return
raw = {k: v for k, v in spec.items() if k != 'operation'}
if op == 'schedule_dialog':
raw['not_before'] = (datetime.now().astimezone()+timedelta(hours=1)).isoformat(timespec='seconds')
def prepare():
report = tasks.preflight(self.window.service, ids)
draft = self.schedules.preview(raw, report['plan_hashes'])
for dependency in draft['dependencies']:
self.window.service.get_task(dependency)
return draft, report
self._work(prepare, lambda result: self._schedule_ready(key, *result), request_id=key)
elif op in {'cancel_schedule', 'run_schedule'}:
def loaded():
row = self.schedules.get(spec.get('schedule_id'))
if row is None:
raise ValueError('schedule missing')
return row
self._work(loaded, lambda row: self._schedule_action(key, op, row), request_id=key)
def _schedule_ready(self, key, draft, report):
self.cache['impact'] = execution_impact(self.window.service, draft['task_ids'])
self.dialog = DshScheduleDialog(draft, report, self.window)
dialog = self.dialog
self._state('awaiting_confirmation', '请核对排期时间、依赖和自动执行授权。')
def accept():
value = dialog.values(); self.dialog = None; dialog.deleteLater()
if self.window.plan_panel.has_unsaved_plan(value['task_ids']):
self._failed(key, TaskCenterError('assistant_dirty', '存在未保存编辑,请重新确认排期。')); return
self._state('saving', '正在保存已确认排期。')
def save():
current = tasks.preflight(self.window.service, value['task_ids'])
if current['plan_hashes'] != report['plan_hashes'] or current['fingerprint'] != report['fingerprint']:
raise TaskCenterError('assistant_stale', '计划已变化,请重新生成排期预览。')
for dependency in value['dependencies']:
self.window.service.get_task(dependency)
return self.schedules.save(value, report['plan_hashes'])
def saved(row):
self.cache['schedules'] = self.schedules.evaluate(self.window.service)
self._respond(key, status='scheduled', schedule=row, message='排期已保存;仅在主工具打开且门禁通过时运行。')
QTimer.singleShot(0, lambda: self._work(save, saved, request_id=key))
def reject():
self.dialog = None; dialog.deleteLater()
self._respond(key, status='cancelled', message='已取消,未保存排期。')
dialog.accepted.connect(accept); dialog.rejected.connect(reject); dialog.open()
def _schedule_action(self, key, op, row):
if op == 'run_schedule':
self.request_id = None
QTimer.singleShot(0, lambda: self._dispatch(row, automatic=False, request_id=key))
return
self.dialog = DshLifecycleDialog('取消排期', (row['title'] or row['schedule_id']) + '\n只取消尚未领取的排期,不强制结束正在执行的任务。', self.window)
dialog = self.dialog
def accept():
self.dialog = None; dialog.deleteLater()
self._state('saving', '正在取消已确认排期。')
def done(value):
self.cache['schedules'] = self.schedules.evaluate(self.window.service)
self._respond(key, status='schedule_cancelled', schedule=value)
QTimer.singleShot(0, lambda: self._work(lambda: self.schedules.cancel(row['schedule_id']), done, request_id=key))
def reject():
self.dialog = None; dialog.deleteLater(); self._respond(key, status='cancelled', message='未取消排期。')
dialog.accepted.connect(accept); dialog.rejected.connect(reject); dialog.open()
def cancel(self, value):
if value.get('request_id') != self.request_id:
return
if self.dialog:
self.dialog.reject()
elif self.cache['activity'].get('status') == 'checking':
self._respond(self.request_id, status='cancelled', message='已取消读取,未提交变更。')
def runtime_stopped(self):
if self.dialog:
self.dialog.reject()
def close(self):
self.timer.stop()
@@ -74,7 +74,7 @@ class DshTaskCreationController(QObject):
return
lifecycle = self.window._dsh_lifecycle
if (self.request_id is not None or self.worker is not None or self.window._workers or self.window._closed
or (lifecycle and lifecycle.dialog is not None)):
or (lifecycle and lifecycle.dialog is not None) or self.window._dsh_operations.busy):
self.view.complete_task_creation({'request_id': request_id, 'status': 'busy',
'message': '任务中心当前正在处理其他操作,请收尾后再创建。'})
return
@@ -131,6 +131,7 @@ class DshTaskCreationController(QObject):
def finished():
self.window._workers.discard(worker)
self.worker = None
self.window._bind_dsh_context()
self.window._update_gates()
if self.window._close_pending:
QTimer.singleShot(0, self.window.close)
@@ -2,13 +2,14 @@
from __future__ import annotations
import re
from uuid import uuid4
from PySide6.QtCore import QObject, QThreadPool, QTimer
from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout
from ...dsh import task_lifecycle as api
from ..errors import TaskCenterError
from ..task_queue import execute_task_queue
from ...dsh.execution_runs import execute_confirmed_run
from .workers import ServiceWorker
@@ -60,12 +61,18 @@ class DshTaskLifecycleController(QObject):
def _respond(self, request_id, **result):
result = {'request_id': request_id, **result}
if 'queue_id' in result:
self.window._dsh_last_execution = dict(result)
self.results[request_id] = result
if len(self.results) > 100:
self.results.pop(next(iter(self.results)))
if self.request_id == request_id:
self._state(result['status'], result=result)
self.request_id = None
elif result['status'] in {'busy', 'rejected'}:
self.window._dsh_operations.cache['activity'] = {'status': result['status'],
'message': result.get('message', '当前操作尚未收尾,请稍后重试。')}
self.window._bind_dsh_context()
self.view.complete_lifecycle(result)
def _failed(self, request_id, error):
@@ -95,8 +102,10 @@ class DshTaskLifecycleController(QObject):
self.window._metadata_changed(None)
self._failed(request_id, error)
def finished():
self.worker = None
if self.worker is worker:
self.worker = None
self.window._workers.discard(worker)
self.window._bind_dsh_context()
self.window._update_gates()
if self.window._close_pending:
QTimer.singleShot(0, self.window.close)
@@ -115,11 +124,16 @@ class DshTaskLifecycleController(QObject):
return
spec = value.get('spec', {})
capability = value.get('capability')
if capability == 'operations':
self.window._dsh_operations.request(value)
return
# Pause must be available during an execution. It can never select a different run.
if capability == 'execute' and isinstance(spec, dict) and spec.get('operation') == 'pause':
ids = spec.get('task_ids')
owner = self.window._active_quick_run_task_id
allowed = self.active_ids or ((owner,) if owner else ())
live = self.window._dsh_live_run
published = tuple(live.get('task_ids', ())) if live.get('active') else ()
allowed = self.active_ids or published or ((owner,) if owner else ())
if (set(spec) != {'operation', 'task_ids'} or not isinstance(ids, list) or not ids
or len(ids) != len(set(ids)) or set(ids) != set(allowed)
or not owner or self.window._batch_stop is None):
@@ -130,10 +144,20 @@ class DshTaskLifecycleController(QObject):
return
creation = self.window._dsh_task_creation
if (self.request_id or self.worker or self.window._workers or self.window._closed
or (creation and creation.request_id)):
or (creation and creation.request_id) or self.window._dsh_operations.busy):
self._respond(request_id, status='busy', message='请等待当前操作或确认窗口收尾。'); return
self.request_id = request_id
self._state('checking')
if capability == 'execute' and isinstance(spec, dict) and spec.get('operation') == 'resume':
if set(spec) != {'operation', 'run_id'}:
self._failed(request_id, TaskCenterError('assistant_fields', '接续请求字段无效。')); return
def inspect():
record = self.window._dsh_operations.runs.inspect(self.window.service, spec['run_id'])
if not record['resume_ready'] or not record['remaining_task_ids']:
raise TaskCenterError('run_blocked', '原执行不可直接接续:' + ', '.join(record['blockers']))
return record, api.preflight(self.window.service, record['task_ids'], allow_completed=True)
self._work(inspect, lambda pair: self._preflight_ready(request_id, capability, pair[0]['task_ids'], pair[1], resume=pair[0]))
return
if capability == 'catalog' and isinstance(spec, dict) and not set(spec) - {'task_id'}:
self._work(lambda: api.catalog(self.window.service, spec.get('task_id')),
lambda result: self._respond(request_id, status='read', **result))
@@ -209,40 +233,54 @@ class DshTaskLifecycleController(QObject):
self._work(lambda: api.apply_confirmed(self.window.service, request_id, plan), done)
self._show('归档任务' if op == 'archive' else '修改任务', text, apply)
def _preflight_ready(self, request_id, capability, ids, report):
def start_schedule(self, row, *, automatic=False, request_id=None):
if self.request_id or self.worker or self.window._workers or self.window._closed:
return
request_id = request_id or uuid4().hex
self.request_id = request_id
self._state('checking')
def check():
current = next((r for r in self.window._dsh_operations.schedules.evaluate(self.window.service)
if r['schedule_id'] == row['schedule_id']), None)
if not current or not current['ready'] or (automatic and not current['auto_start']):
raise TaskCenterError('schedule_blocked', '排期尚未满足时间、依赖或执行门禁。')
return current, api.preflight(self.window.service, current['task_ids'])
self._work(check, lambda pair: self._preflight_ready(request_id, 'execute', pair[0]['task_ids'], pair[1],
schedule=pair[0], automatic=automatic))
def _preflight_ready(self, request_id, capability, ids, report, *, resume=None, schedule=None, automatic=False):
self.window._dsh_operations.cache['impact'] = report.get('impact', {})
if capability == 'preflight' or not report['ready']:
self._respond(request_id, status='preflight' if capability == 'preflight' else 'blocked', **report)
return
text = '\n\n'.join(f"{t['name']} [{t['task_id']}]\n工程:{t['project']}\n启用规则/位号:{t['enabled_rules']}" for t in report['tasks'])
text += '\n\n将按以上顺序执行/继续既有队列,可能替换并保存工程。保留已有备份、核验与中断门禁。\n' + report['message']
impact = report.get('impact', {})
text += '\n\n执行影响:' + ('器件数量未知,仅有料号映射,执行时按实际命中核验。' if impact.get('component_count') is None else f"已保存计划选中 {impact['component_count']} 个器件。")
for row in impact.get('rows', [])[:100]:
text += f"\n{row.get('refdes') or '映射范围'} · {row['old_part_number']} → {row['new_part_number']} · Value {row.get('value_policy')} · Cell {row.get('target_cell') or '自动匹配'} · NC {row.get('sync_nc')}"
if resume:
text += '\n\n恢复原队列:' + resume['run_id'] + ';保留已完成项,不重复替换。'
def start():
if self.request_id != request_id:
return
if self.worker is not None and not self.active_ids:
QTimer.singleShot(100, start)
return
if self.window._workers or self.window._closed or self.window.plan_panel.has_unsaved_plan(ids):
self._failed(request_id, TaskCenterError('assistant_busy', '任务状态已变化,请重新预检。')); return
self._state('executing', task_ids=ids)
run_id = resume['run_id'] if resume else uuid4().hex
self._state('executing', task_ids=ids, run_id=run_id)
self.active_ids = tuple(ids)
self._execution_owner = ids[0]
self.window._dsh_authorized_tasks.update(ids)
self.window._begin_run(ids[0])
self.window._dsh_run_id = run_id
self.window._dsh_live_run.update(run_id=run_id, task_ids=list(ids))
stop = self.window._batch_stop
def operation():
if api.fingerprint(self.window.service, ids) != report['fingerprint']:
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
result = execute_task_queue(self.window.service, tuple(ids), stop_event=stop,
expected_plan_hashes=report['plan_hashes'])
actual = []
for entry in result.entries:
context = self.window.service.task_context(entry.task_id)
p = context.progress
actual.append({'task_id': entry.task_id, 'state': entry.state, 'message': entry.message,
'saved_items': p.saved_items, 'failed_items': p.failed_items,
'no_match_items': p.no_match_items, 'interrupted': context.interrupted,
'queue_complete': p.queue_complete})
status = ('failed' if any(t['state'] in {'blocked', 'failed'} or t['interrupted'] or t['failed_items'] for t in actual)
else 'paused' if result.paused else 'completed')
return {'status': status, 'queue_id': result.queue_id, 'paused': result.paused, 'tasks': actual,
'message': '请按每项实际计数判断;未命中不表示已替换保存。'}
return execute_confirmed_run(self.window.service, self.window.service.layout_settings_path.parent,
ids, report, stop, run_id, resume=resume, schedule=schedule)
def done(result):
self.window._finish_run(); self.active_ids = ()
self.window._metadata_changed(None)
@@ -250,10 +288,15 @@ class DshTaskLifecycleController(QObject):
if task['state'] in {'failed', 'blocked'} or task['failed_items']:
self.window._queue_dsh_incident(task['task_id'], 'execution_failed', task['message'])
self._respond(request_id, **result)
QTimer.singleShot(0, self.window._dsh_operations.refresh)
self._work(operation, done, executing=True)
self._show('执行所选任务', text, start)
if automatic:
QTimer.singleShot(0, start)
else:
self._show('执行所选任务', text, start)
def cancel(self, value):
self.window._dsh_operations.cancel(value)
if value.get('request_id') in self.copy_requests:
self.window._dsh_task_creation.cancel(value)
return
@@ -273,7 +316,8 @@ class DshTaskLifecycleController(QObject):
if self.dialog:
self.dialog.reject()
elif self.active_ids and self.window._batch_stop:
self.window._pause_queue()
if value.get('reason') != 'conversation_cancelled':
self.window._pause_queue()
else:
self._respond(self.request_id, status='cancelled', message='请求已取消,未提交变更或执行。')
@@ -37,9 +37,12 @@ class TrialTaskCenterWindow(QMainWindow):
self._dsh_view = None
self._dsh_task_creation = None
self._dsh_lifecycle = None
self._dsh_operations = None
self._dsh_stopping = False
self._dsh_automation = None
self._dsh_run_id = 'observation'
self._dsh_live_run = {'active': False}
self._dsh_last_execution = {}
self._dsh_authorized_tasks = set()
self.task_center_action = QAction('任务中心', self)
self.task_center_action.triggered.connect(lambda: self.content_stack.setCurrentIndex(0))
@@ -151,6 +154,8 @@ class TrialTaskCenterWindow(QMainWindow):
saved = self._layout_settings.value(f'single_project/{name}')
if saved is not None:
widget.restoreState(saved)
from .dsh_operations import DshOperationsController
self._dsh_operations = DshOperationsController(self)
self._refresh_task_list()
self._update_gates()
if (self.service.layout_settings_path.parent / 'dsh' / 'incidents').is_dir():
@@ -252,7 +257,7 @@ class TrialTaskCenterWindow(QMainWindow):
if self._close_saving:
event.ignore()
return
if self._workers:
if self._workers or (self._dsh_operations and self._dsh_operations.worker):
self._close_pending = True
self.plan_panel.cancel_operation()
self._pause_queue()
@@ -260,6 +265,8 @@ class TrialTaskCenterWindow(QMainWindow):
event.ignore()
return
self._close_pending = False
if self._dsh_operations and self._dsh_operations.dialog:
self._dsh_operations.dialog.reject()
if self.plan_panel.has_unsaved_plans():
choice = self._close_plan_confirmer()
if choice == 'cancel':
@@ -294,6 +301,8 @@ class TrialTaskCenterWindow(QMainWindow):
self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
self._closed = True
if self._dsh_operations:
self._dsh_operations.close()
self._context_query.close()
self._task_query.close()
self._feedback_query.close()
@@ -594,6 +603,9 @@ class TrialTaskCenterWindow(QMainWindow):
return
context = self._context
enabled = sum(row.enabled for row in context.targets) if context.task.target_plan_mode else sum(r.enabled for r in context.rules)
from ...dsh import task_lifecycle as lifecycle
report = lifecycle.preflight(self.service, [context.task.task_id])
self._dsh_confirmation_impact = report.get('impact', {})
if not self._quick_run_confirmer('current', 1, enabled):
return
self._dsh_authorized_tasks.add(context.task.task_id)
@@ -603,8 +615,22 @@ class TrialTaskCenterWindow(QMainWindow):
task_id = context.task.task_id
self._begin_run(task_id)
stop = self._batch_stop
self._run_async(lambda: self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop),
self._show_batch_result, self.run_panel.quick_run_button, expected_task_id=task_id)
run_id = self._dsh_run_id
def execute():
from ...dsh.execution_runs import execute_confirmed_run
current = self.service.task_context(task_id); p = current.progress
actual = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
'part_label' if current.task.copy_part_number_to_value else 'preserve')
if actual != expected:
raise TaskCenterError('assistant_stale', '确认时的执行范围或 Value 策略已变化。')
return execute_confirmed_run(self.service, self.service.layout_settings_path.parent,
[task_id], report, stop, run_id)
def done(receipt):
from ..batch import BatchRunResult
self._show_batch_result(BatchRunResult(self.service.quick_run_progress(task_id), receipt['paused']))
self._dsh_last_execution = receipt
self._bind_dsh_context()
self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id)
def _execute_project_tasks(self):
if not self.task_list.queue_button.isEnabled():
@@ -618,11 +644,20 @@ class TrialTaskCenterWindow(QMainWindow):
if self.plan_panel.has_unsaved_plan(ids):
self._set_operator_message('本批任务有未保存计划,请先逐个保存。', 'warning')
return
report = None
if len(ids) <= 20:
from ...dsh import task_lifecycle as lifecycle
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
self._dsh_confirmation_impact = report.get('impact', {}) if report else {}
if not self._quick_run_confirmer('batch', len(ids), 0):
return
self._dsh_authorized_tasks.update(ids)
from ..task_queue import execute_task_queue
self._begin_run(ids[0])
self._dsh_live_run['task_ids'] = list(ids)
run_id = token or self._dsh_run_id
self._dsh_run_id = run_id
self._dsh_live_run['run_id'] = run_id
stop = self._batch_stop
def done(result):
if result.paused:
@@ -641,8 +676,28 @@ class TrialTaskCenterWindow(QMainWindow):
self._show_task_log(force=True)
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,
self.task_list.queue_button)
def execute():
if report is None:
return execute_task_queue(self.service, ids, stop_event=stop, queue_id=token)
from ...dsh.execution_runs import execute_confirmed_run
from ..task_queue import TaskQueueEntry, TaskQueueResult
resume = None
if token:
resume = self._dsh_operations.runs.inspect(self.service, token)
receipt = execute_confirmed_run(self.service, self.service.layout_settings_path.parent,
list(ids), report, stop, run_id, resume=resume)
result = TaskQueueResult(receipt['queue_id'], tuple(TaskQueueEntry(**entry) for entry in receipt['entries']),
receipt['paused'])
return result, receipt
def completed(value):
if isinstance(value, tuple):
result, receipt = value
done(result)
self._dsh_last_execution = receipt
self._bind_dsh_context()
else:
done(value)
self._run_async(execute, completed, self.task_list.queue_button)
def _begin_run(self, task_id):
from uuid import uuid4
@@ -652,6 +707,9 @@ class TrialTaskCenterWindow(QMainWindow):
self._run_started_at = time.time()
self._quick_run_elapsed.start()
self._quick_run_timer.start()
self._dsh_live_run = {'active': True, 'run_id': self._dsh_run_id, 'task_id': task_id,
'task_ids': [task_id], 'pause_requested': False, 'stage': 'starting',
'elapsed_seconds': 0, 'saved_items': 0, 'failed_items': 0, 'no_match_items': 0}
self.run_panel.busy_indicator.show()
self._message = ''
@@ -662,12 +720,18 @@ class TrialTaskCenterWindow(QMainWindow):
self._batch_stop = None
self.run_panel.busy_indicator.hide()
self.run_panel.stop_queue_button.setText('完成当前项后暂停')
if self._dsh_live_run.get('active'):
self._dsh_last_execution = dict(self._dsh_live_run)
self._dsh_live_run = {'active': False}
self._bind_dsh_context()
def _pause_queue(self):
if self._batch_stop:
self._batch_stop.set()
self.run_panel.stop_queue_button.setText('等待当前项收尾…')
self._set_operator_message('已请求暂停;当前项安全收尾后停止。', 'warning')
self._dsh_live_run['pause_requested'] = True
self._bind_dsh_context()
self._update_gates()
def _force_batch_stop(self):
@@ -824,6 +888,10 @@ class TrialTaskCenterWindow(QMainWindow):
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
+ '\n确认后连续执行,暂停等待当前步骤收尾;状态不确定时停止。')
impact = getattr(self, '_dsh_confirmation_impact', {})
if impact:
text += '\n\n执行影响:' + ('器件数量未知,执行时按实际命中核验。' if impact['component_count'] is None else f"已选中 {impact['component_count']} 个器件。")
text += '\n' + '\n'.join(f"{row.get('refdes') or '映射'}:{row['old_part_number']} → {row['new_part_number']} · Value {row.get('value_policy')} · Cell {row.get('target_cell') or '自动匹配'} · NC {row.get('sync_nc')}" for row in impact['rows'])
return QMessageBox.question(self, '确认执行当前任务' if scope == 'current' else '确认顺序执行本批任务', text,
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes
@@ -831,16 +899,32 @@ class TrialTaskCenterWindow(QMainWindow):
def _update_quick_run_elapsed(self):
if self._batch_stop is not None and not self._feedback_query.busy:
task_id, started = self._active_quick_run_task_id, self._run_started_at
def received(value):
run_id = self._dsh_run_id
elapsed = self._quick_run_elapsed.elapsed() // 1000
pause_requested = bool(self._batch_stop and self._batch_stop.is_set())
scope = list(self._dsh_live_run.get('task_ids') or [task_id])
def read(control):
from ...dsh.live_state import read_live_run
feedback = self.service.execution_feedback(task_id, started_after=started, read_control=control)
live = read_live_run(self.service, feedback, elapsed=elapsed,
pause_requested=pause_requested, run_id=run_id, task_ids=scope)
return feedback, live
def received(pair):
if self._batch_stop is None or run_id != self._dsh_run_id:
return
value, live = pair
self._active_quick_run_task_id = value.task_id or task_id
name = next((t.name for t in self._tasks if t.task_id == value.task_id), value.task_id or '')
self.run_panel.execution_status.setText(format_feedback(
value, name, self._quick_run_elapsed.elapsed() // 1000,
bool(self._batch_stop and self._batch_stop.is_set())))
live['message'] = self.run_panel.execution_status.text()
self._dsh_live_run = live
self._bind_dsh_context()
if self._batch_stop and self._batch_stop.control_error:
self._set_operator_message(self._batch_stop.control_error, 'warning')
self._update_gates()
self._feedback_query.request(lambda control: self.service.execution_feedback(task_id, started_after=started, read_control=control),
self._feedback_query.request(read,
received, lambda _: None, cancellable=True)
if self.run_panel.toggle_log_button.isChecked():
self._refresh_live_task_log()
@@ -877,21 +961,25 @@ class TrialTaskCenterWindow(QMainWindow):
self.run_panel.operator_band.style().polish(self.run_panel.operator_band)
def _open_dsh(self):
self._ensure_dsh_view()
self.content_stack.setCurrentWidget(self._dsh_view)
if self._dsh_automation is not None and self._dsh_automation.latest:
self._dsh_automation._publish_context()
def _ensure_dsh_view(self):
if self._dsh_view is None:
self._dsh_view = self._create_dsh_view()
from .dsh_task_creation import DshTaskCreationController
self._dsh_task_creation = DshTaskCreationController(self, self._dsh_view)
from .dsh_task_lifecycle import DshTaskLifecycleController
self._dsh_lifecycle = DshTaskLifecycleController(self, self._dsh_view)
self._dsh_operations.attach(self._dsh_view)
self._dsh_view.action_requested.connect(self._handle_dsh_action)
self.content_stack.addWidget(self._dsh_view)
self._bind_dsh_context()
self._dsh_view.start()
else:
self._bind_dsh_context()
self.content_stack.setCurrentWidget(self._dsh_view)
if self._dsh_automation is not None and self._dsh_automation.latest:
self._dsh_automation._publish_context()
def _create_dsh_view(self):
# Load Chromium only when the menu is opened; all task-center paths stay lazy.
@@ -905,17 +993,23 @@ class TrialTaskCenterWindow(QMainWindow):
status = getattr(getattr(self, '_context', None), 'task', None)
status_value = getattr(getattr(status, 'status', None), 'value', 'observe')
progress = getattr(self._context, 'progress', None)
live = dict(self._dsh_live_run)
if live.get('active'):
live.update(task_id=self._active_quick_run_task_id or task_id,
elapsed_seconds=self._quick_run_elapsed.elapsed() // 1000)
operations = {**(self._dsh_operations.context() if self._dsh_operations else {}),
'live_run': live, 'last_execution': dict(self._dsh_last_execution)}
counts = {key: getattr(progress, source, 0) for key, source in (
('completed', 'completed_items'), ('total', 'total_items'), ('saved_items', 'saved_items'),
('failed_items', 'failed_items'), ('no_match_items', 'no_match_items'))}
latest = next((r['snapshot'] for r in reversed(self._dsh.history)
if r['snapshot']['task_id'] == task_id), {})
self._dsh_view.bind(TaskSnapshot(task_id, str(status_value),
self._dsh_view.bind(TaskSnapshot(task_id, 'running' if live.get('active') and live.get('task_id') == task_id else str(status_value),
progress=counts,
rules_count=len(getattr(self._context, 'rules', ())),
issue=latest.get('issue', ''), issue_code=latest.get('issue_code', '')),
events=[r['classification'] for r in self._dsh.history if r['snapshot']['task_id'] == task_id],
action_result=action_result, task_name=getattr(status, 'name', ''))
action_result=action_result, task_name=getattr(status, 'name', ''), operations=operations)
def _handle_dsh_action(self, request):
view = self._dsh_view
@@ -972,7 +1066,8 @@ class TrialTaskCenterWindow(QMainWindow):
def _run_async(self, operation, callback, button=None, *, expected_task_id=None,
retain_result=False, operation_area='', **_unused):
if (self._workers or self._closed or (self._dsh_task_creation is not None and self._dsh_task_creation.dialog is not None)
or (self._dsh_lifecycle is not None and self._dsh_lifecycle.dialog is not None)):
or (self._dsh_lifecycle is not None and self._dsh_lifecycle.dialog is not None)
or (self._dsh_operations is not None and self._dsh_operations.dialog is not None)):
return
worker = ServiceWorker(operation)
self._workers.add(worker)
@@ -1020,6 +1115,7 @@ class TrialTaskCenterWindow(QMainWindow):
self._workers.discard(worker)
if not isValid(self) or self._closed:
return
self._bind_dsh_context()
self.plan_panel.finish_operation(error=operation_error)
self._close_saving = False
if self._close_pending and not self._closed: