diff --git a/README.md b/README.md index 2fcd859..7bc85aa 100644 --- a/README.md +++ b/README.md @@ -20,10 +20,11 @@ DSH助手围绕真实任务中心工作,支持: - 用自然语言创建任务、修改规则、复制或归档任务;工程选择和提交仍由原生窗口确认。 - 查询任务快照、执行预检、影响范围和实际执行历史。 +- 识别已保存的逐项 Value 策略(继承、保留、Part Label、料号或自定义);可从对话打开当前任务的原生 BOM 多文件选择流程,校验后仍需核对预览并手动保存。 - 在原生确认后按冻结范围执行任务,支持安全暂停、原队列恢复和排期授权。 - 顶部 **AI 自动介入** 开关默认开启并记住设置;异常、BOM 校验失败、预检阻断、资源释放问题和后台操作长期无进展时自动新建诊断对话,收集脱敏证据,按规则重试或清理自有资源并核验,未解决则转受限 Git 工单。 - 右上角使用无外框的 **AI 状态灯**:绿色待机、黄色介入中、红色未配置/不可用或待人工处理;关闭 **AI 自动介入** 后显示灰色静默。悬浮可查看介入原因、所属任务和当前阶段。未配置模型或 API Key 时,仅提示状态,不自动启动诊断、复盘或工单流程,也不弹窗、锁住任务操作;仍可手动打开助手配置模型。 -- 只读诊断期间可继续选择、创建任务,也可正常关闭窗口。在助手面板取消诊断,或右键状态灯选择 **取消本次 AI 介入**,会停止模型请求、保存本地证据并转人工接管;已进入执行的 CAD 步骤仍按原暂停/强停机制安全收尾。拒绝关闭或取消未保存计划的关闭确认时,诊断继续。诊断与复盘从原生会话准备好后共享等待预算,默认 180 秒,随模型超时设置调整为 90–300 秒;运行时启动和会话创建另有最多 300 秒的等待上限,不挤占分析时间。 +- AI 等待模型、复盘、工单上报及后台查询使用独立工作通道,不锁住普通任务操作。只有实际修复及核验占用任务执行通道;执行前重新核对任务证据和所属轮次,期间有新任务、未保存编辑或现场变化则放弃旧建议,保留证据且不自动重排。在助手面板取消诊断,或右键状态灯选择 **取消本次 AI 介入**,会停止模型请求、保存本地证据并转人工接管;已进入执行的 CAD 步骤仍按原暂停/强停机制安全收尾。拒绝关闭或取消未保存计划的关闭确认时,诊断继续。诊断与复盘从原生会话准备好后共享等待预算,默认 180 秒,随模型超时设置调整为 90–300 秒;运行时启动和会话创建另有最多 300 秒的等待上限,不挤占分析时间。 - 后台读取异常先在约 200 毫秒后复查,连续失败才介入;同一持续阻塞不会周期性重复建会话,关闭再开启自动介入可主动重新诊断。面板分别显示清理次数及独立核验结果;资源自行释放显示“自行解除”,不会计作 AI 修复。资源清理使用独立控制,不显示 CAD 暂停或强停按钮。 - 模型配置的后台检查不会取消健康的在途诊断,也不会把“配置恢复”当成用户重新开启开关。同一异常保持原事件编号,完成后不因配置状态波动重新发诊断;只恢复此前尚未开始的待处理项。仅新异常、用户重新导入或主动关闭再开启允许再次介入。 - 在右侧任务监管中查看运行、影响、排期、经验、工单和用量;审计损坏、证据缺失和未知计数会明确显示。 diff --git a/docs/testing/2026-11-05-dsh-main-parity-nonblocking.md b/docs/testing/2026-11-05-dsh-main-parity-nonblocking.md new file mode 100644 index 0000000..4ea5f30 --- /dev/null +++ b/docs/testing/2026-11-05-dsh-main-parity-nonblocking.md @@ -0,0 +1,42 @@ +# DSH 主分支能力适配与非阻塞验收 + +## 范围 + +2026-11-05 重新拉取 `origin/main`,最新提交为 `08ddf4c`,已包含在当前分支中,无需重复合并。此次补齐逐项 Value 策略、任务详情中的已保存策略,以及从对话交由原生多文件 BOM 导入流程处理的能力。 + +AI 诊断、复盘及工单上报不预占任务执行通道。配置、监管和生命周期读取分别使用独立线程池。实际清理或重试才通过 GUI 申请独占执行权,核验后释放;执行权或原任务证据变化时拒绝旧建议,不排队抢占、不消耗重试预算。原执行器的租约和中断保护继续生效。 + +同一持续异常保留去重状态;配置检查波动不会重启已完成的介入。无任务归属的同一观察事件在本次会话中也不重复诊断,用户主动关闭再开启可创建新一轮。后台预览晚到时重新检查执行与加载状态,不在普通任务运行中弹出确认窗口。 + +## 定向验证 + +全部模型回复、工单发布和 CAD 动作为受控替身;不调用真实模型、不提交测试工单、不修改用户工程。 + +后端命令: + +```powershell +python -m pytest tests/dsh/test_incident_admission.py tests/dsh/test_incidents.py tests/dsh/test_impact.py -q --basetemp=build/ai-admission-backend-final +``` + +结果:**88 passed**。覆盖持续异常去重、跨错误码共享单次重试预算、拒绝执行不消耗预算、模型等待期间证据变化、不确定结果不重放,以及修复执行权在复盘和发布前释放。 + +UI 命令: + +```powershell +python -m pytest tests/ui/test_dsh_ai_nonblocking.py tests/ui/test_dsh_diagnosis_lifecycle.py tests/ui/test_dsh_operations.py tests/ui/test_dsh_status_indicator.py tests/ui/test_dsh_task_lifecycle.py tests/ui/test_dsh_blockers.py tests/ui/test_dsh_blocker_sources.py tests/ui/test_query_observability.py tests/v1_1/test_query_cancellation.py -q --basetemp=build/ai-main-parity-ui-final +``` + +结果:**148 passed**。在全局线程池限制为一个线程、AI 查询由 Event 挂起时,普通任务仍能启动;授权重试和资源诊断等待期间不占任务控制;真实 Qt 信号准入仅在受控清理时占用通道,复盘前释放;旧诊断结束不清除新任务的暂停控制;准入超时后的迟到释放不会保留执行权。还覆盖无 Key 状态、配置波动去重、原生 BOM 交接、Value 策略和晚到预览的确认窗口门禁。 + +以下两项离线 Node 验证均通过: + +```powershell +node tools/verify_dsh_incident_panel.mjs +node tools/verify_dsh_model_results.mjs +``` + +变更 Python 文件语法解析和 `git diff --check` 通过。新增并发回归先确认修复前失败,再确认修复后通过。 + +## 验证边界 + +本次仅验证新增能力及直接受影响的回归,不运行旧功能全量测试,不重新打包 EXE。真实模型时延、远端工单和 CAD 替换结果不由上述离线结果证明。 diff --git a/docs/user/dsh-ai-supervision.md b/docs/user/dsh-ai-supervision.md index 5c6f0fe..91e7aa8 100644 --- a/docs/user/dsh-ai-supervision.md +++ b/docs/user/dsh-ai-supervision.md @@ -50,6 +50,8 @@ DSH 使用独立原生子窗口承载 WebEngine,切回任务中心后保留原 “复制这个任务到新工程”会复制规则配置和启用状态、备注及 Value 策略,然后打开原生工程选择窗口。确认的是窗口里展示的配置草稿;不会复制执行证据。新工程已有未完成任务时保持原配置。“归档这个任务”只把所选任务移入回收站,保留规则和证据,不永久删除。切换任务只改变任务中心选择,不操作工程。 +可要求“为当前任务导入 BOM”:确认后打开任务中心原生 Excel 多文件选择,随后由原工具校验和暂存预览。助手仅报告已交由导入流程,不宣称已经导入或保存;请核对报告并手动保存计划。请求必须指向当前已选中并加载的任务,模型不能代选文件或跳过原生流程。任务详情和影响预览按已保存的逐项 Value 策略显示,包含继承、保留、Part Label、料号及自定义值。 + “检查这个任务能否执行”会核对保存的配置、工程文件可用性、启用规则或位号、失败/中断证据和待释放后台资源,返回具体阻断原因。预检不连接 CAD,不代表许可、备份、替换或保存已经成功。 “按顺序执行这几个任务”或“继续这个任务未完成的部分”会展示真实任务编号、工程路径、启用范围与执行影响,并等待原生确认。一次最多选择 20 个不同任务;执行计划在进入原队列租约后再次核对。新执行在进入执行器前保存运行回执和队列检查点;恢复原运行时重新核对原顺序、冻结计划和已有证据,复用原检查点,不重复已经收尾的项。未保存的位号编辑、待核验中断和未准备的失败重试会阻断执行。 @@ -68,6 +70,8 @@ DSH 使用独立原生子窗口承载 WebEngine,切回任务中心后保留原 同一来源、任务和错误的持续阻塞只报告一次,恢复正常后解除去重。关闭开关会撤销待处理介入;重新开启时检查仍存在的阻塞。BOM 已完成或阻塞已消失时,会取消尚未启动的旧事件。全局资源事件的证据与工单按钮不受当前选中任务影响。 +模型等待、复盘、工单上报、配置检查和监管读取使用独立工作通道,不占普通任务执行通道。实际重试或清理前才申请执行权,并在核验完成后释放;新任务已启动、原任务证据改变或存在未保存计划时,旧建议不执行、不等待抢占、不自动重新排队,证据仍保留。旧诊断结束不会暂停或清掉后来任务的控制状态。只读查询晚到的预览也会再次检查当前执行状态,避免在任务运行中弹出确认窗口。 + 资源释放故障允许 AI 建议一次 **清理后台资源**:通过原资源服务检查空闲队列、租约及进程身份,清理后独立重新读取待释放记录。只有记录为空且无核验错误才显示已解决;清理失败或仍有残留,继续复盘、保存证据并转工单。资源清理不代表工程执行成功,也不会自动接续 CAD 队列;原运行的暂停和强停意图保留。 没有关联任务的应用异常也会创建诊断对话、保留日志证据,但不会自动执行工程操作。用户取消和助手自身启动失败不触发自动介入,避免取消被误判或启动错误循环。不同事件使用独立会话,同一事件的诊断和复盘沿用该会话。 diff --git a/integration/dsh/task-plugin/client.js b/integration/dsh/task-plugin/client.js index 9baff64..7e68d31 100644 --- a/integration/dsh/task-plugin/client.js +++ b/integration/dsh/task-plugin/client.js @@ -124,7 +124,7 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{ const blockerList=values=>values?.length?detail('阻断原因',values.map(value=>blockers[value]||value).join(';')):null; function ImpactPanel({report,scope,perform,pending}){ const rows=report?.rows||[]; - const policy=row=>row.value_policy==='preserve'?'保留原 Value':row.value_policy==='custom'?'自定义 Value':'复制元件库标签(实际值待执行读取)'; + const policy=row=>row.value_policy==='preserve'?'保留原 Value':row.value_policy==='custom'?'自定义 Value':row.value_policy==='part_number'?'使用新料号':'复制元件库标签(实际值待执行读取)'; const columns=['范围','工程 / 图页','位号 / UID','旧料号 → 新料号','旧 Value → 拟议 Value','Cell / NC']; return h('div',{'data-testid':'dx-operations-impact'}, actions(button('dx-impact-refresh','查看当前任务影响',()=>perform({operation:'impact',task_ids:scope}),pending||!scope.length)), diff --git a/integration/dsh/task-plugin/host.mjs b/integration/dsh/task-plugin/host.mjs index 98c9f9d..b36b41f 100644 --- a/integration/dsh/task-plugin/host.mjs +++ b/integration/dsh/task-plugin/host.mjs @@ -96,7 +96,7 @@ export async function apply(ctx){ description:'Create real DxDesigner project tasks with replacement rules. Opens the native task preview and project selector; the user confirms the project scope. Returns actual task IDs after creation or cancellation. Does not execute CAD. A directory may be omitted: the user can supply it in the native dialog. project_directory only prefills that dialog and is never scanned automatically. Include only options explicitly requested by the user; omit unspecified options to retain task-center defaults. Available to interactive conversations, denied in automatic incident sessions.', parameters:{name:{type:'string',required:true,description:'Short task name'},note:{type:'string'}, project_directory:{type:'string',description:'Optional directory suggested by the user; only displayed for native confirmation'}, - copy_part_number_to_value:{type:'boolean',description:'Copy the part number into Value. Default false; set true only when requested.'}, + copy_part_number_to_value:{type:'boolean',description:'Task default: false preserves original Value, true copies the new library Part Label (known only at execution). Default false; set true only when requested. Per-item overrides belong to the native target plan/BOM value_mode column.'}, rules:{type:'array',items:{type:'object',additionalProperties:false,properties:{ old_part_number:{type:'string',required:true},new_part_number:{type:'string',required:true}, target_cell:{type:'string',description:'Optional explicit target package/cell, unrelated to Value'}, diff --git a/integration/dsh/task-plugin/lifecycle.mjs b/integration/dsh/task-plugin/lifecycle.mjs index ae38d2f..632f739 100644 --- a/integration/dsh/task-plugin/lifecycle.mjs +++ b/integration/dsh/task-plugin/lifecycle.mjs @@ -31,16 +31,16 @@ export function registerLifecycle(ctx){ const ids={type:'array',required:true,items:{type:'string'},description:'1 to 20 distinct real task IDs obtained from current records, in execution order. Never infer IDs.'}; const definitions=[ {name:'dx_task_catalog',capability:'catalog',parameters:{task_id:{type:'string',description:'Optional real task ID to also read its saved rule mappings, Value policy and execution phase.'}}, - description:'List real tasks and their IDs, names, groups, statuses and notes. Optionally read one task in detail, including existing rule mappings. Use to resolve natural-language task references before changing, copying or executing a task. Reads saved records only. Interactive conversations only.'}, + description:'List real tasks and their IDs, names, groups, statuses and notes. Optionally read one task in detail, including existing rule mappings and bounded saved target identities/Value policies. Target value_mode is the explicit saved selection: inherit uses the task default, preserve retains original Value, part_label reads the library label during execution, part_number uses the replacement number, custom uses explicit text. value_policy is its effective mode; omitted_targets reports unreturned targets. Use real IDs before changing, copying or executing. Reads saved records only. Interactive conversations only.'}, {name:'dx_task_preflight',capability:'preflight',parameters:{task_ids:ids}, description:'Check the selected saved tasks before execution. Reports project availability, enabled rules/targets, existing execution evidence, unresolved failures and resource blockers. No CAD connection or engineering writes. Returns concrete blockers; does not guarantee a successful CAD run. Interactive conversations only.'}, {name:'dx_task_manage',capability:'manage',parameters:{ - operation:{type:'string',required:true,enum:['select','copy','update','archive']},task_id:{type:'string',required:true}, + operation:{type:'string',required:true,enum:['select','copy','update','archive','import_bom']},task_id:{type:'string',required:true}, patch:{type:'object',additionalProperties:false,description:'Only for update. Omit fields the user did not request. Rule edits propagate to the existing task batch and are shown in the native preview.',properties:{ name:{type:'string'},note:{type:'string'},copy_part_number_to_value:{type:'boolean'}, rules:{type:'array',items:{type:'object',additionalProperties:false,properties:{old_part_number:{type:'string',required:true}, new_part_number:{type:'string'},target_cell:{type:'string'},custom_value:{type:'string'},custom_value_enabled:{type:'boolean'},sync_nc:{type:'boolean'},enabled:{type:'boolean'}}}}}}}, - description:'Manage an existing real task. select changes the task-center selection. update previews explicit metadata and existing rule changes, then waits for native user confirmation. archive moves only that task to the recycle bin, preserving evidence. copy copies mapping configuration and opens the native selector for NEW engineering scope; never duplicates execution evidence or executes CAD. Returns committed IDs/results or cancellation. Native user confirmation cannot be supplied by model arguments. Interactive conversations only.'}, + description:'Manage an existing real task. select changes the task-center selection. update previews explicit metadata and existing rule changes, then waits for native user confirmation. archive moves only that task to the recycle bin, preserving evidence. copy copies mapping configuration and opens the native selector for NEW engineering scope; never duplicates execution evidence or executes CAD. import_bom requires the task already selected and loaded: after native confirmation opens the existing multi-file Excel picker, validation and preview workflow. User chooses files and separately saves the checked batch plan; handed_off never means imported or saved. File paths and confirmation are never model arguments. Returns committed IDs/results or cancellation. Native user confirmation cannot be supplied by model arguments. Interactive conversations only.'}, {name:'dx_task_execute',capability:'execute',parameters:{operation:{type:'string',required:true,enum:['start','pause','resume']},task_ids:{type:'array',items:{type:'string'},description:ids.description},run_id:{type:'string',description:'For resume only, use the real saved run ID from execution history. Original frozen scope/order and existing checkpoint are inspected, then natively confirmed.'}}, description:'Start or continue the existing serial execution queue for an explicit ordered list of real task IDs. Prechecks and native confirmation are required; actual execution can replace and save engineering files using existing backup, interruption and verification gates. Waits for real results including saved, failed and no-match counts. For pause, provide exactly the active run scope; requests safe stopping after the current item and returns pause_requested, not a claim that stopping has completed. No force-stop, no new CAD scripting or hidden retry. Interactive conversations only.'}, {name:'dx_task_operations',capability:'operations',parameters:{ diff --git a/integration/dsh/task-plugin/model_results.mjs b/integration/dsh/task-plugin/model_results.mjs index 8a66b9d..165ba77 100644 --- a/integration/dsh/task-plugin/model_results.mjs +++ b/integration/dsh/task-plugin/model_results.mjs @@ -24,6 +24,11 @@ export function compactResult(value){ delete result.plan_hashes;delete result.fingerprint;delete result.full_fingerprint; if(result.rows)Object.assign(result,impact(result)); if(result.impact)result.impact=impact(result.impact); + if(result.detail?.targets){ + const targets=result.detail.targets; + result.detail={...result.detail,targets:targets.slice(0,20), + omitted_targets:(result.detail.omitted_targets||0)+Math.max(0,targets.length-20)}; + } if(result.tasks?.length>50){result.model_omitted_tasks=result.tasks.length-50;result.tasks=result.tasks.slice(0,50);} if(result.tasks)result.tasks=result.tasks.map(t=>({...t,...t.note?{note:short(t.note,300)}:{}})); if(result.runs)result.runs=result.runs.slice(0,5).map(run); diff --git a/src/dx_productivity/dsh/impact.py b/src/dx_productivity/dsh/impact.py index bcfcac2..64c9a2d 100644 --- a/src/dx_productivity/dsh/impact.py +++ b/src/dx_productivity/dsh/impact.py @@ -42,6 +42,13 @@ def _limit(limit: object) -> int: def _policy(task, row) -> tuple[str, str | None]: if bool(getattr(row, "custom_value_enabled", False)): return "custom", str(getattr(row, "custom_value", "")) + mode = getattr(row, "value_mode", "inherit") + if mode == "custom": + return "custom", str(getattr(row, "custom_value", "")) + if mode == "part_number": + return mode, row.new_part_number + if mode in {"preserve", "part_label"}: + return mode, None 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. @@ -72,6 +79,7 @@ def _target_row(task, task_id: str, row) -> dict[str, Any]: "old_value": target.old_value, "proposed_value": proposed, "value_policy": value_policy, + "value_mode": row.value_mode, "target_cell": target_cell, "target_cell_policy": target_cell, "sync_nc": sync_nc, diff --git a/src/dx_productivity/dsh/incidents.py b/src/dx_productivity/dsh/incidents.py index 6a3b317..4431fce 100644 --- a/src/dx_productivity/dsh/incidents.py +++ b/src/dx_productivity/dsh/incidents.py @@ -1,6 +1,7 @@ """Durable automatic diagnosis, bounded repair, verification and escalation.""" from __future__ import annotations +from contextlib import nullcontext from hashlib import sha256 from itertools import islice import json @@ -127,10 +128,11 @@ def decision(reply): class IncidentRunner: - def __init__(self, data_root, service, analyze, publish, notify=lambda row: None): + def __init__(self, data_root, service, analyze, publish, notify=lambda row: None, *, action_scope=None): self.data_root, self.service = Path(data_root), service self.analyze, self.publish, self.notify = analyze, publish, notify self.decisions = DecisionLog(self.data_root) + self.action_scope = action_scope or (lambda action: nullcontext()) def _record_decision(self, record, evidence, *, outcome, human_takeover=False): refs = [] @@ -215,6 +217,8 @@ class IncidentRunner: snapshot['trigger'] = trigger return snapshot, context snapshot, context = take_snapshot() + # Keep the original immutable evidence across the asynchronous model wait. + context_fingerprint = repr(context) record['task_name'] = snapshot.get('task_name', task_id) budget_id = sha256(f'{task_id}:{run_id}'.encode()).hexdigest()[:24] budget_path = self.data_root / 'dsh' / 'retry-budget' / (budget_id + '.json') @@ -275,35 +279,42 @@ class IncidentRunner: update('cleaning_resources') cleanup = {} try: - pending = tuple(self.service.pending_batch_resources()) - cleanup['resources_before'] = _bounded_details(pending) - if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()): - raise ValueError('cleanup_gate_changed') - if pending: - update('cleaning_resources', cleanup_attempts=1) - if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()): - raise ValueError('cleanup_gate_changed') - record['action'] = 'cleanup_resources' - write_json(state_path, record) - if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()): - record['action'] = 'none' - raise ValueError('cleanup_gate_changed') - cleanup['returned_resources'] = _bounded_details(self.service.cleanup_batch_resources()) + with self.action_scope('cleanup_resources'): + try: + pending = tuple(self.service.pending_batch_resources()) + cleanup['resources_before'] = _bounded_details(pending) + if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()): + raise ValueError('cleanup_gate_changed') + if pending: + update('cleaning_resources', cleanup_attempts=1) + if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()): + raise ValueError('cleanup_gate_changed') + record['action'] = 'cleanup_resources' + write_json(state_path, record) + if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()): + record['action'] = 'none' + raise ValueError('cleanup_gate_changed') + cleanup['returned_resources'] = _bounded_details(self.service.cleanup_batch_resources()) + except Exception as error: + cleanup['error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]}) + if 'resources_before' not in cleanup: + cleanup['resources_before_error'] = cleanup['error'] + evidence.event('cleanup_failed', **cleanup['error']) + try: + remaining = tuple(self.service.pending_batch_resources()) + cleanup['remaining_resources'] = _bounded_details(remaining) + cleanup['remaining_resources_observed'] = True + released = not remaining + except Exception as error: + cleanup['verification_error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]}) + cleanup['remaining_resources'], released = None, None + cleanup['remaining_resources_observed'] = False + evidence.event('cleanup_verification_unavailable', **cleanup['verification_error']) except Exception as error: - cleanup['error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]}) - if 'resources_before' not in cleanup: - cleanup['resources_before_error'] = cleanup['error'] - evidence.event('cleanup_failed', **cleanup['error']) - try: - remaining = tuple(self.service.pending_batch_resources()) - cleanup['remaining_resources'] = _bounded_details(remaining) - cleanup['remaining_resources_observed'] = True - released = not remaining - except Exception as error: - cleanup['verification_error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]}) - cleanup['remaining_resources'], released = None, None + cleanup['error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]}) + cleanup.setdefault('remaining_resources', None) cleanup['remaining_resources_observed'] = False - evidence.event('cleanup_verification_unavailable', **cleanup['verification_error']) + released = None incomplete = 'error' in cleanup or 'verification_error' in cleanup performed = record['action'] == 'cleanup_resources' verification_status = 'incomplete' if incomplete else ('observed_cleared' if released and not performed else 'complete') @@ -331,48 +342,48 @@ class IncidentRunner: if cancel_event.is_set(): return cancelled() if safe: - # Consume before entering a service mutation. A crash or changed error - # code must never buy another replay of the same authorized run. - budget_path.parent.mkdir(parents=True, exist_ok=True) try: - with budget_path.open('x', encoding='utf8') as stream: - json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream) - stream.flush() - os.fsync(stream.fileno()) - except FileExistsError: - safe = False - gates['retry_budget_available'] = False - write_json(evidence.directory / 'gates.json', gates) - if safe: - update('retrying', attempts=1) - try: - # Re-read at the actual mutation boundary; the model never supplies parameters. - current = self.service.task_context(task_id) - if (current.interrupted or current.phase != 'retry' or stop_event.is_set() or cancel_event.is_set() - or (execution_enabled is not None and not execution_enabled.is_set())): - raise ValueError('retry_gate_changed') - record['action'] = 'retry_failed' - write_json(state_path, record) - if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()): - record['action'] = 'none' - raise ValueError('retry_gate_changed') - self.service.prepare_failed_quick_run(task_id) - prepared = self.service.task_context(task_id) - p = prepared.progress - expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number, - 'part_label' if prepared.task.copy_part_number_to_value else 'preserve') - if (prepared.interrupted or not p.next_project_path or stop_event.is_set() or cancel_event.is_set() - or (execution_enabled is not None and not execution_enabled.is_set())): - raise ValueError('retry_execution_gate_changed') - outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event) - update('verifying') - current = self.service.task_context(task_id) - p = current.progress - verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items, - 'saved_items': p.saved_items, 'completed_items': p.completed_items, - 'interrupted': current.interrupted, 'paused': outcome.paused} - write_json(evidence.directory / 'verification.json', verification) - record['verification'] = verification + with self.action_scope('retry_failed'): + # Re-read at the actual mutation boundary; the model never supplies parameters. + current = self.service.task_context(task_id) + if (repr(current) != context_fingerprint or current.interrupted or current.phase != 'retry' or stop_event.is_set() or cancel_event.is_set() + or (execution_enabled is not None and not execution_enabled.is_set())): + raise ValueError('retry_gate_changed') + # Consume before entering a service mutation. A crash or changed error + # code must never buy another replay of the same authorized run. + budget_path.parent.mkdir(parents=True, exist_ok=True) + try: + with budget_path.open('x', encoding='utf8') as stream: + json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream) + stream.flush() + os.fsync(stream.fileno()) + except FileExistsError: + gates['retry_budget_available'] = False + write_json(evidence.directory / 'gates.json', gates) + raise ValueError('retry_budget_spent') + update('retrying', attempts=1) + record['action'] = 'retry_failed' + write_json(state_path, record) + if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()): + record['action'] = 'none' + raise ValueError('retry_gate_changed') + self.service.prepare_failed_quick_run(task_id) + prepared = self.service.task_context(task_id) + p = prepared.progress + expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number, + 'part_label' if prepared.task.copy_part_number_to_value else 'preserve') + if (prepared.interrupted or not p.next_project_path or stop_event.is_set() or cancel_event.is_set() + or (execution_enabled is not None and not execution_enabled.is_set())): + raise ValueError('retry_execution_gate_changed') + outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event) + update('verifying') + current = self.service.task_context(task_id) + p = current.progress + verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items, + 'saved_items': p.saved_items, 'completed_items': p.completed_items, + 'interrupted': current.interrupted, 'paused': outcome.paused} + write_json(evidence.directory / 'verification.json', verification) + record['verification'] = verification if cancel_event.is_set(): return cancelled() if p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused: diff --git a/src/dx_productivity/dsh/task_lifecycle.py b/src/dx_productivity/dsh/task_lifecycle.py index 098f310..dd97029 100644 --- a/src/dx_productivity/dsh/task_lifecycle.py +++ b/src/dx_productivity/dsh/task_lifecycle.py @@ -27,6 +27,10 @@ def catalog(service, task_id=None): 'rules': [asdict(rule) for rule in context.rules], 'targets_count': len(context.targets), 'copy_part_number_to_value': context.task.copy_part_number_to_value, 'interrupted': context.interrupted, 'phase': context.phase} + if context.task.target_plan_mode: + from .impact import execution_impact + report = execution_impact(service, [task_id]) + result['detail'].update(targets=report['rows'], omitted_targets=report['omitted_row_count']) return result @@ -99,11 +103,13 @@ def preview(service, raw): if not isinstance(raw, dict) or set(raw) - {'operation', 'task_id', 'patch'}: raise TaskCenterError('assistant_fields', '任务操作包含不支持的字段。') op = raw.get('operation') - if op not in {'select', 'copy', 'update', 'archive'}: + if op not in {'select', 'copy', 'update', 'archive', 'import_bom'}: raise TaskCenterError('assistant_operation', '不支持此任务操作。') context = _context(service, raw.get('task_id')) if context.task.status is TaskStatus.DELETED: raise TaskCenterError('assistant_deleted', '任务已归档,请先在回收站恢复。') + if op == 'import_bom': + service._editable_rules(context.task.task_id, lambda: None) patch = raw.get('patch', {}) if not isinstance(patch, dict) or set(patch) - {'name', 'note', 'copy_part_number_to_value', 'rules'} or (patch and op != 'update'): raise TaskCenterError('assistant_patch', '只支持修改名称、备注、Value 开关和已有料号规则。') diff --git a/src/dx_productivity/trial_task_center/ui/dsh_automation.py b/src/dx_productivity/trial_task_center/ui/dsh_automation.py index e5105ed..fce7261 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_automation.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_automation.py @@ -2,6 +2,7 @@ from __future__ import annotations import json +from contextlib import contextmanager from collections import deque from copy import deepcopy from dataclasses import dataclass @@ -36,6 +37,7 @@ class DshAutomation(QObject): model_requested = Signal(object) state_changed = Signal(object) cancel_requested = Signal(str) + action_requested = Signal(object) def __init__(self, window): super().__init__(window) @@ -47,23 +49,23 @@ class DshAutomation(QObject): self.latest = {} self.waiters = {} self.worker = None - self._pool = QThreadPool(self) + self._pool = QThreadPool(QApplication.instance()) self._pool.setMaxThreadCount(1) self.execution_enabled = Event() if window.auto_intervention_check.isChecked(): self.execution_enabled.set() self._current_identity = None self.current_request = None - self._owns_execution_lane = True + self._owns_execution_lane = False self._uses_cad_controls = False self.cancel_event = Event() self._analysis_deadline = None - self._previous_run_stop = None self._connected_view = None self._native_unavailable = False self.model_requested.connect(self._request_model) self.state_changed.connect(self._state_changed) self.cancel_requested.connect(self._cancel_model) + self.action_requested.connect(self._admit_action) self._restore_pending() def _restore_pending(self): @@ -90,6 +92,9 @@ class DshAutomation(QObject): for item in self.pending: self._forget((item.task_id, item.code, item.run_id)) self.pending.clear() + for identity in tuple(self.seen): + if identity[2] == 'observation': + self._forget(identity) def cancel_pending(self, run_id): for item in list(self.pending): @@ -146,8 +151,10 @@ class DshAutomation(QObject): self.current_request = item task_id, code, message, authorized, run_id, original_stop = ( item.task_id, item.code, item.message, item.authorized, item.run_id, item.stop) - self._owns_execution_lane = not item.read_only and (item.authorized or item.cleanup_allowed) - self._uses_cad_controls = self._owns_execution_lane and item.authorized + self._owns_execution_lane = False + self._uses_cad_controls = False + self._admitted_action = None + self._observed_run_id = w._dsh_run_id self.cancel_event = Event() # Start the shared model budget when the Harness session is ready; # startup/session creation must not consume diagnosis time. @@ -176,13 +183,10 @@ class DshAutomation(QObject): # Carry the original run's stop/force intent through the asynchronous # handoff, including pauses requested after enqueue but before drain. stop = original_stop if original_stop is not None else StopControl() - self._previous_run_stop = original_stop if original_stop is not None else w._dsh_run_stop - # The same worker gate reserves the mutation lane throughout diagnosis. - if self._uses_cad_controls: - w._batch_stop = stop - w._active_quick_run_task_id = task_id or None + self._action_stop = stop runner = IncidentRunner(self.root, w.service, self._analyze, - GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit) + GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit, + action_scope=self._action_scope) allow_execution = authorized and not item.read_only and not w.plan_panel.has_unsaved_plans() permission = self.execution_enabled cancellation = self.cancel_event @@ -195,8 +199,6 @@ class DshAutomation(QObject): def _start_worker(self, worker): w = self.window self.worker = worker - if self._owns_execution_lane: - w._workers.add(worker) worker.signals.succeeded.connect(self._completed) worker.signals.failed.connect(self._failed) worker.signals.finished.connect(self._finished) @@ -204,6 +206,78 @@ class DshAutomation(QObject): self._publish_context() self._pool.start(worker) + @contextmanager + def _action_scope(self, action): + request = {'action': action, 'worker': self.worker, 'complete': Event(), 'holder': {}} + self.action_requested.emit(request) + # Admission runs on the GUI thread; a timed-out request cannot acquire later. + if not request['complete'].wait(5): + request['holder']['abandoned'] = True + request['holder']['release'] = True + self.action_requested.emit(request) + raise ValueError('ai_action_admission_timeout') + if not request['holder'].get('admitted'): + raise ValueError('ai_action_context_changed') + try: + yield + finally: + request['complete'].clear() + request['holder']['release'] = True + self.action_requested.emit(request) + request['complete'].wait(5) + + def _admit_action(self, request): + if request['holder'].get('release'): + self._release_action(request) + request['complete'].set() + return + w = self.window + try: + item = self.current_request + if (request['holder'].get('abandoned') or w._closed or self.cancel_event.is_set() + or not self.execution_enabled.is_set() or not w.auto_intervention_check.isChecked() + or item is None or item.read_only or request['worker'] is not self.worker + or w._workers or w._loading or w._batch_stop is not None + or w._dsh_run_id != self._observed_run_id + or w.plan_panel.has_unsaved_plans() + or (w._dsh_lifecycle and (w._dsh_lifecycle.worker or w._dsh_lifecycle.dialog)) + or (w._dsh_task_creation and (w._dsh_task_creation.worker or w._dsh_task_creation.dialog)) + or w._dsh_operations.dialog): + return + if request['action'] == 'retry_failed': + if not item.authorized or self._action_stop.is_set(): + return + elif request['action'] != 'cleanup_resources' or not item.cleanup_allowed: + return + self._admitted_action = request + self._owns_execution_lane = True + self._uses_cad_controls = request['action'] == 'retry_failed' + if self._uses_cad_controls: + w._batch_stop = self._action_stop + w._active_quick_run_task_id = item.task_id + w._workers.add(self.worker) + request['holder']['admitted'] = True + w._update_gates() + finally: + request['complete'].set() + + def _release_action(self, request): + if getattr(self, '_admitted_action', None) is not request: + return + w = self.window + w._workers.discard(request['worker']) + if self._uses_cad_controls and w._batch_stop is self._action_stop: + w._batch_stop = None + w._active_quick_run_task_id = None + self._admitted_action = None + self._owns_execution_lane = False + self._uses_cad_controls = False + if not w._closed: + # Refresh only this task's visible evidence; never finish a newer run. + if self.current_request and w._task_id == self.current_request.task_id: + w._load_task_data(auto_intervene=False) + w._update_gates() + def _forget(self, identity): self.seen.discard(identity) try: @@ -362,23 +436,19 @@ class DshAutomation(QObject): def _finished(self): w = self.window + if getattr(self, '_admitted_action', None) is not None: + self._release_action(self._admitted_action) w._workers.discard(self.worker) self.worker = None if self._current_identity: w._dsh_blockers.completed(self._current_identity[2]) - if self._current_identity[2] == 'observation' or self._current_identity[2].startswith('blocker-'): + if self._current_identity[2].startswith('blocker-'): self._forget(self._current_identity) self._current_identity = None self.current_request = None self._publish_context() if w._closed: return - if self._uses_cad_controls: - w._finish_run() - w._dsh_run_stop = self._previous_run_stop - if self._owns_execution_lane: - # A passive refresh must not create an incident about this diagnosis. - w._load_task_data(auto_intervene=False) w._resource_status.refresh() w._update_gates() if w._close_pending: diff --git a/src/dx_productivity/trial_task_center/ui/dsh_operations.py b/src/dx_productivity/trial_task_center/ui/dsh_operations.py index ee3fa21..b7c0951 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_operations.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_operations.py @@ -72,6 +72,8 @@ class DshOperationsController(QObject): self.decisions = DecisionLog(self.root) self.dialog = None self.worker = None + self._read_pool = QThreadPool(QApplication.instance()) + self._read_pool.setMaxThreadCount(1) self.request_id = None self._request_task_ids = () self._read_failures = {} @@ -149,6 +151,12 @@ class DshOperationsController(QObject): code=getattr(error, 'code', 'operations_error')) def _work(self, action, done, *, request_id=None, reserve_lane=True): + if request_id and self.request_id != request_id: + return + if reserve_lane and (self.window._closed or self.window._workers or self.window._loading): + if request_id: + self._respond(request_id, status='busy', message='任务状态已变化,请在当前操作结束后重新确认。') + return self._observed_execution = self._execution_state() worker = ServiceWorker(action) self.worker = worker @@ -177,6 +185,8 @@ class DshOperationsController(QObject): getattr(error, 'message', '托管记录暂不可读,请检查本地记录。')) self._state('unavailable', '监管记录暂不可用,已有执行不受影响。') def finished(): + if not isValid(self.window): + return self.window._dsh_blockers.unwatch(worker) self.window._workers.discard(worker) if self.worker is worker: @@ -190,7 +200,7 @@ class DshOperationsController(QObject): worker.signals.succeeded.connect(succeeded); worker.signals.failed.connect(failed) worker.signals.finished.connect(finished) self.window._update_gates() - QThreadPool.globalInstance().start(worker) + (QThreadPool.globalInstance() if reserve_lane else self._read_pool).start(worker) def _read_blockers(self, value): self._read_recovered('operations:read') @@ -333,7 +343,7 @@ class DshOperationsController(QObject): # 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) + self._work(lambda: self._read(synchronize_tickets=self._ticks % 20 == 0), ready, reserve_lane=False) def _dispatch(self, row, *, automatic, request_id=None): if not isValid(self.window) or self.window._closed: @@ -388,22 +398,22 @@ class DshOperationsController(QObject): def read(value): self.cache.update(value) self._respond(key, status='read', **value) - self._work(self._read, read, request_id=key) + self._work(self._read, read, request_id=key, reserve_lane=False) 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) + self._work(lambda: execution_impact(self.window.service, spec.get('task_ids')), impact, request_id=key, reserve_lane=False) 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) + self._work(lambda: self.experiences.search(spec.get('issue_code', '')), found, request_id=key, reserve_lane=False) 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) + self._work(lambda: self.tickets.refresh(spec.get('incident_id')), synced, request_id=key, reserve_lane=False) elif op == 'open_incident': incident = spec.get('incident_id') if not isinstance(incident, str) or not re.fullmatch('[a-f0-9]{24}', incident): @@ -427,18 +437,21 @@ class DshOperationsController(QObject): 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) + return draft, report, execution_impact(self.window.service, draft['task_ids']) + self._work(prepare, lambda result: self._schedule_ready(key, *result), request_id=key, reserve_lane=False) elif op in {'cancel_schedule', 'run_schedule', 'reconcile_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) + self._work(loaded, lambda row: self._schedule_action(key, op, row), request_id=key, reserve_lane=False) - def _schedule_ready(self, key, draft, report): - self.cache['impact'] = execution_impact(self.window.service, draft['task_ids']) + def _schedule_ready(self, key, draft, report, impact): + if self.window._workers or self.window._closed: + self._respond(key, status='busy', message='任务状态已变化,未打开排期确认。') + return + self.cache['impact'] = impact self.dialog = DshScheduleDialog(draft, report, self.window) dialog = self.dialog self._state('awaiting_confirmation', '请核对排期时间、依赖和自动执行授权。') @@ -464,6 +477,9 @@ class DshOperationsController(QObject): dialog.accepted.connect(accept); dialog.rejected.connect(reject); dialog.open() def _schedule_action(self, key, op, row): + if self.window._workers or self.window._closed: + self._respond(key, status='busy', message='任务状态已变化,未提交排期操作。') + return if op == 'run_schedule': self.request_id = None QTimer.singleShot(0, lambda: self._dispatch(row, automatic=False, request_id=key)) diff --git a/src/dx_productivity/trial_task_center/ui/dsh_status.py b/src/dx_productivity/trial_task_center/ui/dsh_status.py index f6eaf62..cb343e7 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_status.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_status.py @@ -1,7 +1,7 @@ """Non-blocking model readiness and visible automatic-intervention state.""" -from PySide6.QtCore import QObject, QPointF, QRectF, QSize, Qt, QTimer +from PySide6.QtCore import QObject, QPointF, QRectF, QSize, Qt, QThreadPool, QTimer from PySide6.QtGui import QColor, QFontMetricsF, QPainter -from PySide6.QtWidgets import QToolButton +from PySide6.QtWidgets import QApplication, QToolButton from ...dsh.availability import check_availability from ...dsh.evidence import scrub @@ -58,7 +58,9 @@ class DshStatusController(QObject): self.window = window self.availability = {'available': False, 'code': 'checking', 'message': '正在检查本地 AI 配置。'} self._runtime_error = '' - self.query = LatestQuery(self) + self._read_pool = QThreadPool(QApplication.instance()) + self._read_pool.setMaxThreadCount(1) + self.query = LatestQuery(self, pool=self._read_pool) self.timer = QTimer(self) self.timer.setInterval(5000) self.timer.timeout.connect(self.refresh) diff --git a/src/dx_productivity/trial_task_center/ui/dsh_task_lifecycle.py b/src/dx_productivity/trial_task_center/ui/dsh_task_lifecycle.py index 8f75755..959e90f 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_task_lifecycle.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_task_lifecycle.py @@ -5,7 +5,8 @@ import re from uuid import uuid4 from PySide6.QtCore import QObject, QThreadPool, QTimer -from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout +from PySide6.QtWidgets import QApplication, QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout +from shiboken6 import isValid from ...dsh import task_lifecycle as api from ..errors import TaskCenterError @@ -39,6 +40,8 @@ class DshTaskLifecycleController(QObject): self.dialog = None self.request_id = None self.worker = None + self._read_pool = QThreadPool(QApplication.instance()) + self._read_pool.setMaxThreadCount(1) self.results = {} self.active_ids = () self._request_task_ids = () @@ -91,15 +94,16 @@ class DshTaskLifecycleController(QObject): status='rejected' if isinstance(error, TaskCenterError) else 'failed', message=getattr(error, 'message', '操作未完成,请核对任务中心日志。'), code=getattr(error, 'code', 'assistant_error')) - def _work(self, operation, done, *, executing=False): + def _work(self, operation, done, *, executing=False, reserve_lane=True): worker = ServiceWorker(operation) self.worker = worker - self.window._workers.add(worker) + if reserve_lane: + self.window._workers.add(worker) request_id = self.request_id owner = self._request_task_ids[0] if self._request_task_ids else '' self.window._dsh_blockers.watch(worker, 'DSH task operation', owner, area='lifecycle') def succeeded(result): - if self.request_id != request_id or self.window._closed: + if not isValid(self.window) or self.request_id != request_id or self.window._closed: return try: done(result) @@ -107,6 +111,8 @@ class DshTaskLifecycleController(QObject): failed(error) worker.signals.succeeded.connect(succeeded) def failed(error): + if not isValid(self.window) or self.window._closed or self.request_id != request_id: + return if executing: self.window._finish_run() self.active_ids = () @@ -114,10 +120,14 @@ class DshTaskLifecycleController(QObject): self.window._metadata_changed(None) self._failed(request_id, error, report_blocker=not executing) def finished(): + if not isValid(self.window): + return self.window._dsh_blockers.unwatch(worker) if self.worker is worker: self.worker = None self.window._workers.discard(worker) + if self.window._closed: + return self.window._bind_dsh_context() self.window._update_gates() if self.window._close_pending: @@ -125,7 +135,7 @@ class DshTaskLifecycleController(QObject): worker.signals.failed.connect(failed) worker.signals.finished.connect(finished) self.window._update_gates() - QThreadPool.globalInstance().start(worker) + (QThreadPool.globalInstance() if reserve_lane else self._read_pool).start(worker) def request(self, value): request_id = value.get('request_id') @@ -172,11 +182,11 @@ class DshTaskLifecycleController(QObject): if not record['resume_ready'] or not record['remaining_task_ids'] or not record.get('diff', {}).get('safe', False): 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])) + self._work(inspect, lambda pair: self._preflight_ready(request_id, capability, pair[0]['task_ids'], pair[1], resume=pair[0]), reserve_lane=False) 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)) + lambda result: self._respond(request_id, status='read', **result), reserve_lane=False) elif capability in {'preflight', 'execute'}: if not isinstance(spec, dict) or set(spec) - ({'task_ids', 'operation'} if capability == 'execute' else {'task_ids'}) or (capability == 'execute' and spec.get('operation') != 'start'): self._failed(request_id, TaskCenterError('assistant_fields', '执行请求字段无效。')); return @@ -184,13 +194,26 @@ class DshTaskLifecycleController(QObject): if self.window.plan_panel.has_unsaved_plan(ids if isinstance(ids, list) else ()): self._failed(request_id, TaskCenterError('assistant_dirty', '所选任务有未保存位号计划,请先保存。')); return self._work(lambda: api.preflight(self.window.service, ids), - lambda report: self._preflight_ready(request_id, capability, ids, report)) + lambda report: self._preflight_ready(request_id, capability, ids, report), reserve_lane=False) elif capability == 'manage': - self._work(lambda: api.preview(self.window.service, spec), lambda plan: self._plan_ready(request_id, plan)) + self._work(lambda: api.preview(self.window.service, spec), lambda plan: self._plan_ready(request_id, plan), reserve_lane=False) else: self._failed(request_id, TaskCenterError('assistant_capability', '未开放此能力。')) + def _allow_transition(self, request_id): + if not isValid(self.window) or self.window._closed or self.request_id != request_id: + return False + creation = self.window._dsh_task_creation + if (self.window._workers or self.window._loading or self.window._batch_stop is not None + or self.window._active_quick_run_task_id or self.window.history_panel._worker is not None + or (creation and creation.request_id) or self.window._dsh_operations.busy): + self._respond(request_id, status='busy', message='任务中心状态已变化,请等待当前操作收尾后重新请求。') + return False + return True + def _show(self, title, text, accepted): + if not self._allow_transition(self.request_id): + return self._state('awaiting_confirmation', title=title, preview=text) self.dialog = DshLifecycleDialog(title, text, self.window) dialog = self.dialog @@ -208,11 +231,38 @@ class DshTaskLifecycleController(QObject): dialog.open() def _plan_ready(self, request_id, plan): + if not self._allow_transition(request_id): + return spec = plan['spec']; op = spec['operation']; task_id = spec['task_id'] if op == 'select': self.window.open_task(task_id) self._respond(request_id, status='selected', task_id=task_id) return + if op == 'import_bom': + panel = self.window.plan_panel + def eligible(): + return (self.window._task_id == task_id and panel.task_id == task_id + and self.window._context is not None and not self.window._loading + and not self.window._workers and panel.import_bom_button.isEnabled()) + if not eligible(): + self._failed(request_id, TaskCenterError('assistant_bom_scope', '请先选择并加载该任务,确认其 BOM 导入可用后重试。')) + return + text = ('打开该任务的原生 BOM 导入窗口,可多选 Excel 文件。\n' + '文件选择后由任务中心校验并暂存预览;请在位号计划中核对报告后手动保存本批计划。\n' + '本次确认只打开文件选择,不代表导入或保存成功,不执行 CAD。') + def launch_import(): + if self.request_id != request_id: + return + if self.window._closed or not eligible(): + self._failed(request_id, TaskCenterError('assistant_bom_scope', '任务选择或导入状态已变化,请重新确认。')) + return + self.window.content_stack.setCurrentIndex(0) + self.window.mapping_tabs.setCurrentWidget(panel) + panel.import_bom() + self._respond(request_id, status='handed_off', task_id=task_id, cad_execution_started=False, + message='已交由原生 BOM 文件选择和校验流程;导入结果请核对位号计划中的报告,保存需另行确认。') + self._show('导入 BOM', text, launch_import) + return if op == 'copy': # Project scope and configuration preview use the existing creation controller. try: @@ -221,7 +271,7 @@ class DshTaskLifecycleController(QObject): self._failed(request_id, error); return self._state('awaiting_confirmation', title='复制任务:请选择新工程') def launch(): - if self.request_id != request_id: + if not self._allow_transition(request_id): return creation = self.window._dsh_task_creation self.copy_requests.add(request_id) @@ -238,7 +288,7 @@ class DshTaskLifecycleController(QObject): else: text += '\n\n仅写入任务配置,不执行 CAD。同批规则变更会应用到以上全部任务。' def apply(): - if self.request_id != request_id: + if not self._allow_transition(request_id): return if self.window._workers or self.window._closed or self.window.plan_panel.has_unsaved_plan([t['task_id'] for t in plan['affected_tasks']]): self._failed(request_id, TaskCenterError('assistant_busy', '任务正在处理或有未保存计划,请重新确认。')); return @@ -268,7 +318,7 @@ class DshTaskLifecycleController(QObject): 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)) + schedule=pair[0], automatic=automatic), reserve_lane=False) def _preflight_ready(self, request_id, capability, ids, report, *, resume=None, schedule=None, automatic=False): self.window._dsh_operations.cache['impact'] = report.get('impact', {}) @@ -300,6 +350,8 @@ class DshTaskLifecycleController(QObject): if self.worker is not None and not self.active_ids: QTimer.singleShot(100, start) return + if not self._allow_transition(request_id): + 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 run_id = resume['run_id'] if resume else uuid4().hex diff --git a/src/dx_productivity/trial_task_center/ui/main_window.py b/src/dx_productivity/trial_task_center/ui/main_window.py index 48b2452..c08a8e5 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -346,7 +346,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): if self._close_saving: event.ignore() return - if self._workers or self.history_panel._worker or (self._dsh_operations and self._dsh_operations.worker): + if self._workers or self.history_panel._worker: self._close_pending = True if self._dsh_automation and getattr(self._dsh_automation, '_owns_execution_lane', False): self._cancel_dsh_diagnosis() diff --git a/src/dx_productivity/trial_task_center/ui/queries.py b/src/dx_productivity/trial_task_center/ui/queries.py index 132b816..75ffbf9 100644 --- a/src/dx_productivity/trial_task_center/ui/queries.py +++ b/src/dx_productivity/trial_task_center/ui/queries.py @@ -8,8 +8,9 @@ from .workers import ServiceWorker class LatestQuery(QObject): settled = Signal() - def __init__(self, parent=None): + def __init__(self, parent=None, *, pool=None): super().__init__(parent) + self._pool = pool if pool is not None else QThreadPool.globalInstance() self._generation = 0 self._active = {} self._pending = None @@ -68,7 +69,7 @@ class LatestQuery(QObject): worker.signals.succeeded.connect(self._received) worker.signals.failed.connect(self._failed) worker.signals.finished.connect(self._finished) - QThreadPool.globalInstance().start(worker) + self._pool.start(worker) def _current(self): entry = self._active.get(self.sender()) diff --git a/tests/dsh/test_impact.py b/tests/dsh/test_impact.py index 9dd159f..3bd11ec 100644 --- a/tests/dsh/test_impact.py +++ b/tests/dsh/test_impact.py @@ -157,3 +157,34 @@ def test_saved_plan_hash_errors_are_not_replaced_with_synthetic_hashes(setup, mo with pytest.raises(TaskCenterError) as caught: execution_impact(service, [tasks[0].task_id]) assert caught.value.code == 'controlled_read_error' + + +@pytest.mark.parametrize('task_default', [False, True]) +@pytest.mark.parametrize('mode', ['inherit', 'preserve', 'part_label', 'part_number', 'custom']) +def test_per_item_value_policy_matches_saved_execution_mode(setup, task_default, mode): + service, store, tasks, _ = setup + task_id = tasks[0].task_id + rows = store.list_target_plan(task_id) + item = replace(rows[0], value_mode=mode, custom_value_enabled=False, custom_value='CUSTOM') + store.replace_target_plan(task_id, (item, *rows[1:])) + store.set_copy_part_number_to_value(task_id, task_default) + result = execution_impact(service, [task_id])['rows'][0] + effective = ('part_label' if task_default else 'preserve') if mode == 'inherit' else mode + assert result['value_mode'] == mode + assert result['value_policy'] == effective + assert result['proposed_value'] == {'preserve': 'V1', 'part_label': None, 'part_number': 'NEW', 'custom': 'CUSTOM'}[effective] + + +def test_catalog_exposes_bounded_saved_item_value_policies(setup): + from dx_productivity.dsh.task_lifecycle import catalog + service, store, tasks, paths = setup + task_id = tasks[1].task_id + targets = tuple(ComponentTarget(paths[1], 'MAIN', '1', f'uid{i}', f'R{i}', 'OLD', 'ORIGINAL') for i in range(105)) + store.record_target_inventory(task_id, targets) + store.replace_target_plan(task_id, tuple(TargetPlanRow(target, True, 'NEW', value_mode='part_number') for target in targets)) + detail = catalog(service, task_id)['detail'] + assert detail['targets_count'] == 105 + assert len(detail['targets']) == 100 and detail['omitted_targets'] == 5 + assert detail['targets'][0]['value_mode'] == 'part_number' + assert detail['targets'][0]['proposed_value'] == 'NEW' + assert detail['targets'][0]['uid'] == 'uid0' diff --git a/tests/dsh/test_incident_admission.py b/tests/dsh/test_incident_admission.py new file mode 100644 index 0000000..e560cb4 --- /dev/null +++ b/tests/dsh/test_incident_admission.py @@ -0,0 +1,73 @@ +from contextlib import contextmanager +from pathlib import Path + +from test_incidents import Service, ResourceService, analyze, cleanup_model, make_runner + + +def test_rejected_admission_never_mutates_or_spends_retry_budget(tmp_path): + service = Service() + @contextmanager + def scope(action): + raise ValueError('execution_lane_changed') + yield + runner = make_runner(tmp_path, service) + runner.action_scope = scope + result = runner.run('t', 'worker_error', 'failure', execution_authorized=True) + assert service.calls == [] + assert result['attempts'] == 0 + assert not list((tmp_path / 'dsh/retry-budget').glob('*.json')) + + +def test_changed_task_after_model_wait_never_retries(tmp_path): + service = Service() + def model(*args): + service.progress.saved_items += 1 + return analyze() + result = make_runner(tmp_path, service, model).run('t', 'worker_error', 'failure', execution_authorized=True) + assert not service.calls + assert result['attempts'] == 0 + assert not list((tmp_path / 'dsh/retry-budget').glob('*.json')) + + +def test_action_scope_released_before_reflection_and_publication(tmp_path): + active, phases = [], [] + @contextmanager + def scope(action): + active.append(action) + try: + yield + finally: + active.pop() + service = Service(fixed=False) + execute = service.execute_quick_run_queue + def execute_scoped(*args, **kwargs): + assert active == ['retry_failed'] + return execute(*args, **kwargs) + service.execute_quick_run_queue = execute_scoped + def model(*args): + assert not active + phases.append(args[-1]) + return analyze() + def publish(*args): + assert not active + return {'status': 'unavailable'} + runner = make_runner(tmp_path, service, model, publish) + runner.action_scope = scope + runner.run('t', 'worker_error', 'failure', execution_authorized=True) + assert phases == ['diagnose', 'reflect'] + assert service.calls == ['prepare', 'execute'] + assert not active + + +def test_cleanup_rejected_admission_does_not_release_resources(tmp_path): + service = ResourceService() + @contextmanager + def scope(action): + raise ValueError('execution_lane_changed') + yield + runner = make_runner(tmp_path, service, cleanup_model) + runner.action_scope = scope + result = runner.run('t', 'batch_resources_pending', 'failure', cleanup_allowed=True) + assert not service.calls + assert result['cleanup_attempts'] == 0 + assert result['status'] != 'resolved' diff --git a/tests/ui/test_dsh_ai_nonblocking.py b/tests/ui/test_dsh_ai_nonblocking.py new file mode 100644 index 0000000..db3f4e4 --- /dev/null +++ b/tests/ui/test_dsh_ai_nonblocking.py @@ -0,0 +1,274 @@ +"""AI observation must leave the desktop execution lane available.""" +from threading import Event +from types import SimpleNamespace + +import pytest +from PySide6.QtCore import QThreadPool + +from dx_productivity.trial_task_center.ui.workers import ServiceWorker +from .test_dsh_diagnosis_lifecycle import slow_diagnosis +from .test_dsh_operations import setup_view + + +pytestmark = pytest.mark.usefixtures('ai_ready') + + +@pytest.fixture +def single_execution_thread(ui, qtbot): + ui.settle() + pool = QThreadPool.globalInstance() + previous = pool.maxThreadCount() + pool.setMaxThreadCount(1) + yield pool + qtbot.waitUntil(lambda: pool.activeThreadCount() == 0, timeout=5000) + pool.setMaxThreadCount(previous) + + +@pytest.mark.parametrize('source', ['timer', 'history']) +def test_operations_observation_never_reserves_or_starves_task_execution( + ui, monkeypatch, qtbot, single_execution_thread, source): + window = ui.window + view = setup_view(ui, monkeypatch) + operations = window._dsh_operations + started, release, executed = Event(), Event(), Event() + + def read(**_kwargs): + started.set() + assert release.wait(5), 'Controlled operations read was not released' + return {'schedules': []} + + monkeypatch.setattr(operations, '_read', read) + if source == 'timer': + operations.tick() + else: + operations.request({'request_id': 'a' * 32, 'spec': {'operation': 'history'}}) + try: + qtbot.waitUntil(started.is_set, timeout=5000) + assert operations.worker not in window._workers + assert window.task_list.new_button.isEnabled() + window._run_async(executed.set, lambda _: None) + qtbot.waitUntil(executed.is_set, timeout=1000) + assert not release.is_set(), 'Task work must start before the AI read finishes' + finally: + release.set() + qtbot.waitUntil(lambda: operations.worker is None and not window._workers, timeout=5000) + if source == 'history': + assert view.lifecycle_results[-1]['status'] == 'read' + + +def test_availability_check_cannot_starve_task_worker( + ui, monkeypatch, qtbot, single_execution_thread): + from dx_productivity.trial_task_center.ui import dsh_status + + status = ui.window._dsh_status + status.timer.stop() + qtbot.waitUntil(lambda: not status.query.busy, timeout=5000) + started, release, executed = Event(), Event(), Event() + + def check(_root): + started.set() + assert release.wait(5), 'Controlled availability check was not released' + return {'available': True, 'code': 'available', 'message': 'Controlled readiness'} + + monkeypatch.setattr(dsh_status, 'check_availability', check) + status.refresh() + worker = ServiceWorker(executed.set) + try: + qtbot.waitUntil(started.is_set, timeout=5000) + single_execution_thread.start(worker) + qtbot.waitUntil(executed.is_set, timeout=1000) + assert not release.is_set() + finally: + release.set() + qtbot.waitUntil(lambda: not status.query.busy, timeout=5000) + + +@pytest.mark.parametrize('kind', ['authorized_retry', 'resource_cleanup']) +def test_model_wait_never_owns_task_controls(slow_diagnosis, qtbot, kind): + window, automation, _, start = slow_diagnosis + if kind == 'resource_cleanup': + start(read_only=False, cleanup=True) + else: + automation.enqueue(window._task_id, 'execution_failed', 'Controlled authorized failure', + execution_authorized=True, run_id='b' * 32) + automation._drain() + qtbot.waitUntil(lambda: bool(window._dsh_view.requests), timeout=5000) + try: + assert automation.worker not in window._workers + assert window._batch_stop is None + assert window._active_quick_run_task_id is None + assert window.task_list.new_button.isEnabled() + finally: + automation.cancel() + qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) + + +def test_finishing_old_diagnosis_preserves_new_manual_run(slow_diagnosis, ui, qtbot): + window, automation, _, _ = slow_diagnosis + automation.enqueue(window._task_id, 'execution_failed', 'Controlled old failure', + execution_authorized=True, run_id='c' * 32) + automation._drain() + qtbot.waitUntil(lambda: bool(window._dsh_view.requests), timeout=5000) + owner = ui.tasks[1].task_id + window._begin_run(owner) + manual_stop = window._batch_stop + manual_run = window._dsh_run_id + try: + automation.cancel() + qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) + assert window._batch_stop is manual_stop + assert window._active_quick_run_task_id == owner + assert window._dsh_run_id == manual_run + assert window._dsh_live_run['active'] + assert not manual_stop.is_set() + finally: + window._finish_run() + + +def reply_to_model(view, action='none'): + request = view.requests[-1] + view.diagnosis_event.emit({'status': 'started', 'request_id': request['request_id'], + 'session_id': 'controlled-session'}) + view.diagnosis_event.emit({'status': 'completed', 'request_id': request['request_id'], + 'session_id': 'controlled-session', + 'reply': '{"summary":"Controlled diagnosis","action":"' + action + '"}'}) + + +def test_cleanup_reserves_lane_only_during_service_action( + slow_diagnosis, monkeypatch, qtbot): + from dx_productivity.trial_task_center.ui import dsh_automation + + window, automation, _, start = slow_diagnosis + started, release = Event(), Event() + pending = [{'state': 'blocked', 'kind': 'controlled_test_resource'}] + publications = [] + + def cleanup(): + started.set() + assert release.wait(5), 'Controlled cleanup was not released' + return tuple(pending) + + def publish(*_args): + publications.append(automation.worker in window._workers) + return {'status': 'unavailable'} + + monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: tuple(pending)) + monkeypatch.setattr(window.service, 'cleanup_batch_resources', cleanup) + monkeypatch.setattr(dsh_automation, 'GitIssuePublisher', lambda _path: publish) + view = start(read_only=False, cleanup=True) + reply_to_model(view, 'cleanup_resources') + try: + qtbot.waitUntil(started.is_set, timeout=5000) + assert automation.worker in window._workers + assert automation._owns_execution_lane + assert window._batch_stop is None + finally: + release.set() + qtbot.waitUntil(lambda: len(view.requests) == 2, timeout=5000) + assert view.requests[-1]['phase'] == 'reflect' + assert automation.worker not in window._workers + assert not automation._owns_execution_lane + assert window.task_list.new_button.isEnabled() + pending.clear() + reply_to_model(view) + qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) + assert publications == [False] + + +@pytest.mark.parametrize('action', ['cleanup_resources', 'retry_failed']) +def test_new_manual_run_denies_old_ai_mutation_without_touching_controls( + slow_diagnosis, ui, monkeypatch, qtbot, action): + from dx_productivity.trial_task_center.ui import dsh_automation + + window, automation, published, start = slow_diagnosis + mutations = [] + monkeypatch.setattr(window.service, 'cleanup_batch_resources', lambda: mutations.append('cleanup')) + monkeypatch.setattr(window.service, 'prepare_failed_quick_run', lambda _task: mutations.append('prepare')) + if action == 'cleanup_resources': + view = start(read_only=False, cleanup=True) + else: + context = SimpleNamespace(task=SimpleNamespace(status=SimpleNamespace(value='running')), + interrupted=False, phase='retry') + monkeypatch.setattr(dsh_automation.IncidentRunner, '_snapshot', + lambda _self, task_id, _code, _message: ({'task_id': task_id, 'status': 'running'}, context)) + automation.enqueue(window._task_id, 'execution_failed', 'Controlled retryable failure', + execution_authorized=True, run_id='d' * 32) + automation._drain() + qtbot.waitUntil(lambda: bool(window._dsh_view.requests), timeout=5000) + view = window._dsh_view + window._begin_run(ui.tasks[1].task_id) + manual_stop = window._batch_stop + owner = window._active_quick_run_task_id + try: + reply_to_model(view, action) + qtbot.waitUntil(lambda: len(view.requests) == 2, timeout=5000) + assert not mutations + assert automation.worker not in window._workers + assert window._batch_stop is manual_stop + assert window._active_quick_run_task_id == owner + assert not manual_stop.is_set() + assert 'ai_action_context_changed' in str(automation.latest) + assert not list(ui.data.glob('dsh/retry-budget/*.json')) + reply_to_model(view) + qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) + assert window._batch_stop is manual_stop + assert window._active_quick_run_task_id == owner + assert len(published) == 1 + finally: + window._finish_run() + + +def test_completed_taskless_observation_does_not_start_another_model_run( + slow_diagnosis, qtbot): + window, automation, published, start = slow_diagnosis + view = start() + reply_to_model(view) + qtbot.waitUntil(lambda: len(view.requests) == 2, timeout=5000) + reply_to_model(view) + qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) + assert ('', 'operation_stalled', 'observation') in automation.seen + assert automation.enqueue('', 'operation_stalled', 'same persistent global error', read_only=True) + automation._drain() + qtbot.wait(20) + assert len(view.requests) == 2 + assert automation.worker is None + assert not automation.pending + assert len(published) == 1 + automation.set_enabled(False) + automation.set_enabled(True) + assert automation.enqueue('', 'operation_stalled', 'explicit new episode', read_only=True) + automation._drain() + qtbot.waitUntil(lambda: len(view.requests) == 3, timeout=5000) + automation.cancel() + qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) + + +def test_admission_timeout_releases_even_if_gui_just_admitted(ui, monkeypatch): + from dx_productivity.trial_task_center.ui import dsh_automation as module + from dx_productivity.trial_task_center.stop_control import StopControl + + ui.settle() + window = ui.window + automation = module.DshAutomation(window) + automation.worker = object() + automation.current_request = module.IncidentRequest('', 'batch_resources_pending', '', + False, 'observation', cleanup_allowed=True) + automation._observed_run_id = window._dsh_run_id + automation._action_stop = StopControl() + + class ExpiringEvent: + def set(self): + pass + def wait(self, _timeout): + return False + + monkeypatch.setattr(module, 'Event', ExpiringEvent) + try: + with pytest.raises(ValueError, match='admission_timeout'): + with automation._action_scope('cleanup_resources'): + pytest.fail('Timed-out admission must not mutate') + assert not automation._owns_execution_lane + assert automation.worker not in window._workers + assert automation._admitted_action is None + finally: + automation.worker = None diff --git a/tests/ui/test_dsh_diagnosis_lifecycle.py b/tests/ui/test_dsh_diagnosis_lifecycle.py index 6fcc99e..a69bd0d 100644 --- a/tests/ui/test_dsh_diagnosis_lifecycle.py +++ b/tests/ui/test_dsh_diagnosis_lifecycle.py @@ -106,7 +106,7 @@ def test_cancelled_close_confirmation_keeps_diagnosis_running(slow_diagnosis, qt def test_resource_diagnosis_has_no_cad_pause_or_force_controls(slow_diagnosis, qtbot, ui): window, automation, published, start = slow_diagnosis view = start(read_only=False, cleanup=True) - assert automation.worker in window._workers + assert automation.worker not in window._workers assert window._batch_stop is None assert not window.run_panel.stop_queue_button.isVisible() assert not window.run_panel.force_stop_button.isVisible() diff --git a/tests/ui/test_dsh_operations.py b/tests/ui/test_dsh_operations.py index c5810f2..d2594cc 100644 --- a/tests/ui/test_dsh_operations.py +++ b/tests/ui/test_dsh_operations.py @@ -11,6 +11,23 @@ def setup_view(ui, monkeypatch): return ui.window._dsh_view +def test_confirmed_operation_rechecks_lane_after_read_preview(ui, monkeypatch): + view = setup_view(ui, monkeypatch) + ctl = ui.window._dsh_operations + ctl.request_id = '7' * 32 + other_worker = object() + ui.window._workers.add(other_worker) + called = [] + try: + ctl._work(lambda: called.append('mutation'), lambda _: None, request_id='7' * 32) + assert ctl.worker is None + assert ui.window._workers == {other_worker} + assert view.lifecycle_results[-1]['status'] == 'busy' + assert not called + finally: + ui.window._workers.discard(other_worker) + + @pytest.mark.parametrize('missing', [False, True]) def test_terminal_history_sums_persisted_counts_and_preserves_unknown(ui, monkeypatch, qtbot, missing): from dx_productivity.dsh.task_lifecycle import preflight diff --git a/tests/ui/test_dsh_task_lifecycle.py b/tests/ui/test_dsh_task_lifecycle.py index 66b524f..e1613c4 100644 --- a/tests/ui/test_dsh_task_lifecycle.py +++ b/tests/ui/test_dsh_task_lifecycle.py @@ -212,3 +212,175 @@ def test_pause_uses_active_stop_control_and_refuses_other_scope(ui, monkeypatch) assert ui.window._batch_stop.is_set() and not ui.window._batch_stop.force_event.is_set() assert view.lifecycle_results[-1]['status'] == 'pause_requested' ui.window._finish_run() + + +def test_bom_handoff_requires_native_confirmation_and_never_claims_import(ui, monkeypatch, qtbot): + ctl, view = controller(ui, monkeypatch) + opened = [] + monkeypatch.setattr(ui.window.plan_panel, 'import_bom', lambda: opened.append(ui.window.plan_panel.task_id)) + ctl.request(request(ui, 'import_bom')) + qtbot.waitUntil(lambda: ctl.dialog is not None or bool(view.lifecycle_results), timeout=5000) + assert ctl.dialog is not None + assert '多选' in ctl.dialog.preview.toPlainText() + assert not opened and not ui.calls + qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton) + qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000) + assert opened == [ui.tasks[0].task_id] + assert view.lifecycle_results[-1]['status'] == 'handed_off' + assert view.lifecycle_results[-1]['cad_execution_started'] is False + ctl.request(request(ui, 'import_bom')) + assert len(opened) == 1 + assert not ui.calls + ui.settle() + + +def test_bom_handoff_rechecks_selected_task_after_confirmation(ui, monkeypatch, qtbot): + ctl, view = controller(ui, monkeypatch) + opened = [] + monkeypatch.setattr(ui.window.plan_panel, 'import_bom', lambda: opened.append(True)) + ctl.request(request(ui, 'import_bom')) + qtbot.waitUntil(lambda: ctl.dialog is not None or bool(view.lifecycle_results), timeout=5000) + assert ctl.dialog is not None + ui.open(ui.tasks[1]) + qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton) + qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000) + assert view.lifecycle_results[-1]['status'] == 'rejected' + assert not opened + ui.settle() + + +@pytest.mark.parametrize('capability', ['catalog', 'preflight', 'manage']) +def test_lifecycle_reads_do_not_reserve_ordinary_task_lane(ui, monkeypatch, qtbot, capability): + from threading import Event + ctl, view = controller(ui, monkeypatch) + ui.settle() + entered, release = Event(), Event() + api = lifecycle() + function = {'catalog': 'catalog', 'preflight': 'preflight', 'manage': 'preview'}[capability] + original = getattr(api, function) + def slow(*args, **kwargs): + entered.set() + assert release.wait(5) + return original(*args, **kwargs) + monkeypatch.setattr(api, function, slow) + spec = ({'task_id': ui.tasks[0].task_id} if capability == 'catalog' else + {'task_ids': [ui.tasks[0].task_id]} if capability == 'preflight' else + {'operation': 'update', 'task_id': ui.tasks[0].task_id, 'patch': {'name': 'Preview'}}) + ctl.request({'request_id': 'f' * 32, 'capability': capability, 'spec': spec}) + try: + qtbot.waitUntil(entered.is_set, timeout=5000) + lane_reserved = bool(ui.window._workers) + ordinary_execution_enabled = ui.window.run_panel.quick_run_button.isEnabled() + finally: + release.set() + qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000) + if ctl.dialog is not None: + ctl.dialog.reject() + ui.settle() + assert not lane_reserved + assert ordinary_execution_enabled + + +def test_select_does_not_claim_success_if_ordinary_mutation_starts_during_read(ui, monkeypatch, qtbot): + from threading import Event + ctl, view = controller(ui, monkeypatch) + ui.settle() + entered, release = Event(), Event() + api = lifecycle() + original = api.preview + def slow(*args): + entered.set() + assert release.wait(5) + return original(*args) + monkeypatch.setattr(api, 'preview', slow) + ctl.request({'request_id': '3' * 32, 'capability': 'manage', + 'spec': {'operation': 'select', 'task_id': ui.tasks[1].task_id}}) + busy = object() + try: + qtbot.waitUntil(entered.is_set, timeout=5000) + ui.window._workers.add(busy) + release.set() + qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000) + result = view.lifecycle_results[-1] + selected = ui.window._task_id + finally: + release.set() + ui.window._workers.discard(busy) + qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000) + ui.settle() + assert result['status'] == 'busy' + assert selected == ui.tasks[0].task_id + + +@pytest.mark.parametrize('operation', ['update', 'archive', 'copy', 'execute']) +@pytest.mark.parametrize('busy_kind', ['worker', 'run', 'loading']) +def test_delayed_preview_does_not_open_modal_after_manual_activity(ui, monkeypatch, qtbot, operation, busy_kind): + from threading import Event + from dx_productivity.trial_task_center.stop_control import StopControl + from dx_productivity.trial_task_center.ui.operation_state import ContextReadPhase + ctl, view = controller(ui, monkeypatch) + ui.settle() + entered, release = Event(), Event() + api = lifecycle() + function = 'preflight' if operation == 'execute' else 'preview' + original = getattr(api, function) + def slow(*args, **kwargs): + value = original(*args, **kwargs) + entered.set() + assert release.wait(5) + return value + monkeypatch.setattr(api, function, slow) + value = ({'request_id': '4' * 32, 'capability': 'execute', + 'spec': {'operation': 'start', 'task_ids': [ui.tasks[0].task_id]}} if operation == 'execute' else + request(ui, operation, **({'patch': {'name': 'Uncommitted'}} if operation == 'update' else {}))) + ctl.request(value) + busy = object() + previous_phase = ui.window._context_phase + try: + qtbot.waitUntil(entered.is_set, timeout=5000) + if busy_kind == 'worker': + ui.window._workers.add(busy) + elif busy_kind == 'run': + ui.window._batch_stop = StopControl() + else: + ui.window._context_phase = ContextReadPhase.LOADING + release.set() + qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000) + qtbot.waitUntil(lambda: ctl.dialog is not None or ui.window._dsh_task_creation.dialog is not None + or bool(view.lifecycle_results), timeout=5000) + modal_opened = ctl.dialog is not None or ui.window._dsh_task_creation.dialog is not None + result = view.lifecycle_results[-1] if view.lifecycle_results else {} + finally: + release.set() + ui.window._workers.discard(busy) + ui.window._batch_stop = None + ui.window._context_phase = previous_phase + if ctl.dialog is not None: + ctl.dialog.reject() + if ui.window._dsh_task_creation.dialog is not None: + ui.window._dsh_task_creation.dialog.reject() + ui.settle() + assert not modal_opened + assert result['status'] == 'busy' + assert not ui.calls + + +def test_cancelled_read_failure_does_not_replace_cancellation(ui, monkeypatch, qtbot): + from threading import Event + ctl, view = controller(ui, monkeypatch) + entered, release = Event(), Event() + def slow(*args): + entered.set() + assert release.wait(5) + raise TaskCenterError('controlled_read_failure', 'Read failed after cancellation') + monkeypatch.setattr(lifecycle(), 'catalog', slow) + value = {'request_id': '5' * 32, 'capability': 'catalog', 'spec': {}} + ctl.request(value) + try: + qtbot.waitUntil(entered.is_set, timeout=5000) + ctl.cancel(value) + finally: + release.set() + qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000) + ui.settle() + assert [result['status'] for result in view.lifecycle_results] == ['cancelled'] diff --git a/tools/verify_dsh_incident_panel.mjs b/tools/verify_dsh_incident_panel.mjs index ce38df6..b0fb101 100644 --- a/tools/verify_dsh_incident_panel.mjs +++ b/tools/verify_dsh_incident_panel.mjs @@ -3,11 +3,11 @@ import assert from 'node:assert/strict'; import {readFile} from 'node:fs/promises'; import vm from 'node:vm'; -let plugin,TaskPanel,data,stateIndex; +let plugin,TaskPanel,data,stateIndex,tab='overview'; const requests=[]; const React={ createElement:(type,props,...children)=>({type,props:props||{},children}), - useState:()=>[[data,'','overview',false,null][stateIndex++],()=>{}], + useState:()=>[[data,'',tab,false,null][stateIndex++],()=>{}], useEffect:()=>{} }; const sandbox={window:{__ModuleLoader__:{load:value=>{plugin=value;}}}, @@ -68,4 +68,13 @@ assert.equal(text([cancel]),'取消 AI 诊断'); await cancel.props.onClick(); assert.equal(requests.length,1); assert.deepEqual(requests[0],{url:'/dx/action',body:{action:'cancel_diagnosis',task_id:'selected-task',revision:'fresh-revision'}}); +tab='impact'; +data={task_id:'selected-task',operations:{impact:{coverage:'exact',component_count:1,rows:[{ + task_id:'selected-task',uid:'target',enabled:true,component_count:1,value_mode:'part_number', + value_policy:'part_number',old_part_number:'OLD',new_part_number:'NEW',old_value:'ORIGINAL',proposed_value:'NEW' +}]}}}; +stateIndex=0; +tree=expand(TaskPanel()); +assert.match(text(tree),/使用新料号/); +assert.ok(!text(tree).includes('复制元件库标签'),'part_number must not be mislabeled as Part Label'); console.log(JSON.stringify({status:'passed',cleanupEvidenceVisible:true,terminalStatusesAccurate:true,cancelActionRouted:true})); diff --git a/tools/verify_dsh_model_results.mjs b/tools/verify_dsh_model_results.mjs index c358057..4c009e5 100644 --- a/tools/verify_dsh_model_results.mjs +++ b/tools/verify_dsh_model_results.mjs @@ -2,6 +2,13 @@ import assert from 'node:assert/strict'; import {compactResult,modelSnapshot} from '../integration/dsh/task-plugin/model_results.mjs'; const ids=Array.from({length:100},(_,i)=>'real-task-'+i); +const detail=compactResult({detail:{task_id:'task',targets_count:105,omitted_targets:5, + targets:ids.map(uid=>({uid,value_mode:'inherit',value_policy:'part_label',proposed_value:null}))}}).detail; +assert.equal(detail.targets.length,20); +assert.equal(detail.omitted_targets,85); +assert.equal(detail.targets_count,105); +assert.equal(detail.targets[0].value_mode,'inherit'); +assert.equal(detail.targets[0].value_policy,'part_label'); const result=compactResult({status:'created',task_ids:ids,created_count:100}); assert.deepEqual(result.task_ids,ids,'committed task IDs must not be truncated'); const report=compactResult({status:'impact',component_count:100,total_rows:100,omitted_row_count:0,