diff --git a/docs/superpowers/plans/2026-10-30-dsh-task-lifecycle.md b/docs/superpowers/plans/2026-10-30-dsh-task-lifecycle.md new file mode 100644 index 0000000..6794c24 --- /dev/null +++ b/docs/superpowers/plans/2026-10-30-dsh-task-lifecycle.md @@ -0,0 +1,11 @@ +# DSH task lifecycle implementation + +The user approved conversational task management, execution preflight and execution control. Extend the existing native Harness integration, retaining natural intent inference through function schemas and the existing CAD service boundaries. + +1. Add Qt-free lifecycle reads, previews and atomic confirmed edits. List real task IDs, patch task metadata and existing mapping rules, archive to the recycle bin, and copy configuration through the existing project-selection dialog. Include all batch-rule members in previews and stale-state checks. Persist mutation receipts to prevent replay. +2. Add execution preflight based on saved task contexts, interrupted state, project availability, enabled scope and pending resources. Report actual blockers without claiming a CAD connectivity check. Freeze execution plan hashes and check them inside the existing task-queue lease before any executor runs. +3. Add a bounded parent-process request/result bridge and native lifecycle controller. Native dialogs show affected tasks, fields and execution scope. Start/continue use the existing serial task queue; pause uses the active StopControl. Return actual queue results and distinguish paused, failed, completed and no-match outcomes. +4. Expose catalog, preflight, management and execution schemas to interactive sessions. Automatic incident sessions remain snapshot-only. Keep business prompts free of tool routing. Show lifecycle state in the existing right-hand native slot. +5. Write failing domain/UI tests before implementation, then verify atomicity, stale previews, cancellation, copy, execution and pause. Extend CLI policy probes and run a real-model Qt/CDP acceptance using fixture engineering files and a controlled executor. Run relevant regressions and record validation limits. + +Implementation is inline in this already-authorized session. No deployment, release binary or real engineering mutation is included. diff --git a/docs/testing/2026-10-30-dsh-task-lifecycle.md b/docs/testing/2026-10-30-dsh-task-lifecycle.md new file mode 100644 index 0000000..365fd0a --- /dev/null +++ b/docs/testing/2026-10-30-dsh-task-lifecycle.md @@ -0,0 +1,52 @@ +# DSH conversational task lifecycle acceptance + +Implemented on `codex/dsh`: real task lookup and selection, metadata and existing mapping edits with native batch-impact preview, configuration copy through the native project selector, recycle-bin archive, execution preflight, confirmed serial execution/continuation and safe StopControl pause. + +The model receives six bounded backend schemas. Business prompts contain no tool names or routing instructions. Automatic incident sessions remain limited to their event-bound snapshot; management, catalog, preflight, creation and execution requests are denied before desktop emission. + +## Automated verification + +Targeted tests cover real SQLite records, shared-rule propagation, persistent duplicate-request receipts, stale previews, missing projects, deleted tasks, native cancellation, cancellation while reading, retention of receipts during confirmed writes, disabled rule copying, StopControl scope and real controlled queue results. Queue tests reject changed confirmed plan hashes inside the queue lease before the executor runs. Derived target Cell resets and custom Value enablement are included in the preview and committed from the same normalized patch. + +The complete relevant regression command is: + +```powershell +pytest -q tests/dsh tests/ui tests/packaging/test_dx_part_replace_build.py tests/trial_task_center/test_application.py tests/trial_task_center/test_quick_run.py tests/v1_1/test_task_queue.py tests/v1_1/test_diagnostics_bundle.py tests/v1_1/test_project_context.py +node tools/verify_dsh_runtime.mjs +``` + +`tools/verify_dsh_auto_runtime.mjs` was run with the configured test provider. It verified a real model turn, immutable incident binding and rejection of every new capability in an automatic session. CLI policy checks verified the exact six-tool roster, desktop-only operations, unauthorized tools, authentication and stale/cross-task routes. + +Final verification in the isolated `codex/dsh` worktree: **160 passed in 63.80 seconds**; the real Harness CLI check returned `status: passed`. A credential scan of all 25 changed files found neither the configured model API key nor the prefilled issue token. Runtime dependencies are reused through an ignored local junction; the token bootstrap remains ignored. + +## Real model and desktop acceptance + +Command: + +```powershell +python tools/accept_dsh_lifecycle.py --output build/dsh-lifecycle-accepted --provider-config "$env:LOCALAPPDATA/DxProductivity/trial-task-center/dsh" --port 9235 +``` + +Provider: `skyworth-deepseek-v4.1-flash` through the previously configured test API. Credentials were passed through the existing local encrypted configuration, never through the prompt or report. + +The passing run used the real main window, official Harness page, Chromium Input events and Qt QTest mouse clicks. Eight natural-language messages triggered 20 real backend calls. The run: + +1. Found and selected Board-A, changed its name and note, and modified a shared mapping after confirming both affected tasks. +2. Read execution readiness without claiming a CAD connectivity check. +3. Confirmed execution scope in Qt, opened another conversation and requested a safe pause through natural language. The actual StopControl stopped after the current queue item. +4. Confirmed continuation and executed the remaining item exactly once. The receipts reported saved 0, failed 0, no-match 2; no-match was not presented as a replacement save. +5. Copied configuration to a newly selected Board-C project through the real directory scan and confirmation controls; received a new persisted task ID. +6. Archived only the copy, preserving the original task. +7. Clicked Cancel on a proposed rename and confirmed that the original database name remained unchanged. + +Final database metadata, shared rules, task bindings, archive target and executor call count were independently checked. All three source fixture hashes were unchanged. Clean shutdown was recorded without uncaught or unexpected UI errors. + +Artifacts are under `build/dsh-lifecycle-accepted/`: `desktop-report.json`, `report.json`, native confirmation captures, `dsh-execution-results.png`, `dsh-lifecycle-in-tool.png` and the isolated SQLite data directory. The full passing artifacts were generated in the shared checkout before moving the same verified source into the isolated `codex/dsh` worktree. + +## Limits and review + +The executor was controlled to produce two no-match results; no real DxDesigner process or user engineering file was modified. This verifies integration and control flow, not CAD connectivity or successful part replacement. No release EXE was built. + +Independent read-only review found a cancellation receipt race and an omitted derived Cell reset in previews. Both were corrected and covered by tests. The final review reported no remaining Critical or Important findings. + +Configuration copy deliberately confirms a displayed draft; later edits to the source do not rewrite that draft. A continuation reconfirms the requested scope and order and starts a queue checkpoint over the same tasks' saved execution progress. It preserves completed task steps rather than reusing an unrelated native group checkpoint. diff --git a/docs/user/dsh-ai-supervision.md b/docs/user/dsh-ai-supervision.md index 56423fe..8bc2bd8 100644 --- a/docs/user/dsh-ai-supervision.md +++ b/docs/user/dsh-ai-supervision.md @@ -24,18 +24,32 @@ 目录提示只预填窗口,不由模型自动扫描;工程范围以原生窗口勾选为准。确认前取消窗口或中止对话不会创建任务;确认后已提交的事务以真实回执为准。一个请求内的新任务、规则和回执事务提交,失败全部回滚;同一请求重放不重复创建,已有未完成任务的工程不被改名或改规则。创建上限为 100 个工程、30 条规则;活动执行时不创建。 +### 在对话中管理和执行任务 + +可以直接说“找到电源板任务,把备注改为本周验证,旧料号 A 对应的新料号改成 B”。助手查找真实记录和规则,展示名称、备注、Value 策略及规则变更;同批规则会列出全部受影响任务。更换料号导致的旧封装选择清空、自定义 Value 开启等连带变化也会出现在预览中。确认时若任务已被其他操作修改,旧预览失效,需重新核对。 + +“复制这个任务到新工程”会复制规则配置和启用状态、备注及 Value 策略,然后打开原生工程选择窗口。确认的是窗口里展示的配置草稿;不会复制执行证据。新工程已有未完成任务时保持原配置。“归档这个任务”只把所选任务移入回收站,保留规则和证据,不永久删除。切换任务只改变任务中心选择,不操作工程。 + +“检查这个任务能否执行”会核对保存的配置、工程文件可用性、启用规则或位号、失败/中断证据和待释放后台资源,返回具体阻断原因。预检不连接 CAD,不代表许可、备份、替换或保存已经成功。 + +“按顺序执行这几个任务”或“继续这个任务未完成的部分”会展示真实任务编号、工程路径、启用范围,并等待原生确认。一次最多选择 20 个不同任务;执行计划在进入原队列租约后再次核对。继续使用原任务保存的执行进度,重新确认本次范围与顺序,创建本次队列检查点;不重复已经收尾的步骤。未保存的位号编辑、待核验中断和未准备的失败重试会阻断执行。 + +执行中可请求“安全暂停当前执行”,程序只设置当前运行的 StopControl,等待当前项安全收尾;“已请求暂停”与“已经暂停”分别返回。执行回执包含真实保存、失败、未命中和待核验状态。未命中不是已替换保存;确认后中止模型等待也不会撤销已经提交的配置事务,最终结果以持久回执和任务证据为准。 + +### 自动异常介入 + 任务操作报错、单任务收尾有失败项,或批次包含失败/阻断任务时,会自动切入 DSH助手并创建专属诊断会话,不需要手动提问。原执行收尾后,AI 读取出错任务绑定的快照和脱敏事件;即使切换任务,诊断也不会串到另一个任务。 已经由用户确认执行的任务,遇到已知可重试错误且现有服务确认“可重试、没有待核验结果”时,AI 可建议一次自动重试。程序通过原服务准备失败项、执行并重新读取真实进度;只有队列完成、失败为零且没有中断标记,才显示处理通过。模型建议或重试准备成功都不算解决;暂停请求会阻止继续重试。 未解决时,AI 再做一轮复盘,保存结论、依据、未知项和后续验证方法,并尝试提交 Git 工单。事件以任务、原执行轮次和错误码去重;同一任务同一原执行轮次的不同错误码共享一次重试额度,执行前持久记录,重启不重置。未知错误、未授权执行和未核验状态仅诊断取证,不自动重放工程写入。 -- 普通对话注册 `dx_task_snapshot`(快照)和 `dx_task_create`(原生确认后创建任务);自动异常诊断会话只允许快照,创建调用在工具执行前被拒绝。Shell、通用文件访问、插件安装、子智能体及模型直接 CAD 写入工具均未注册;额外工具会被 guard 阻断。 +- 普通对话开放快照、创建、任务列表及详情、预检、任务管理、受控执行六项能力;自动异常诊断会话只允许事件快照,其他调用在执行前被拒绝。Shell、通用文件访问、插件安装、子智能体及模型直接 CAD 写入工具均未注册;额外工具会被 guard 阻断。 - **刷新任务上下文**重新发布当前任务快照。 - 手动点击 **准备失败项重试**须在任务中心确认,并通过现有重试按钮的状态检查;该按钮只准备重试。自动介入使用上文限定的一次重试闭环。 - **安全暂停**须确认且当前确有执行控制器,使用原队列的安全边界暂停。 - 跨任务、过期版本、未知参数、未知动作及同一版本的重复动作请求均拒绝。网页请求必须经过本机 Harness 的登录与 Origin 校验。 -- 规则修改、工程写入和不确定状态恢复仍从任务中心原流程进行,不新增模型直接执行入口。UI 显示“已提交”不表示工程已保存或核验成功。 +- 规则修改与工程写入通过上述原生确认和现有任务中心服务;不确定状态恢复仍从任务中心原流程进行。模型不能提供“已确认”参数来跳过确认,UI 显示“已提交”不表示工程已保存或核验成功。 Harness 使用任务中心数据目录下独立的 `dsh/harness-home` 保存会话和设置,浏览器偏好在 `dsh/browser`;不加载个人 Harness profile 或 Codex 凭据。服务只监听回环地址,遥测关闭;关闭主工具时先结束所属运行时。上述限制由应用的插件组合和 guard 实现,不是操作系统沙箱。 diff --git a/integration/dsh/start.mjs b/integration/dsh/start.mjs index df657de..d9d09bb 100644 --- a/integration/dsh/start.mjs +++ b/integration/dsh/start.mjs @@ -62,7 +62,7 @@ export async function bootRuntime({announce=true} = {}) { await readFile(path.join(root,'task-plugin/client.js')); if (process.argv.includes('--doctor')) { console.log(JSON.stringify({status:'ready',version:VERSION,frontend:'official', - tools:['dx_task_snapshot','dx_task_create'],genericTools:false,node:process.version})); + tools:['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute'],genericTools:false,node:process.version})); return; } if (!process.env.DX_DSH_HOME || !process.env.DX_DSH_CONTEXT_FILE) throw Error('Task center context is required'); @@ -92,7 +92,7 @@ export async function bootRuntime({announce=true} = {}) { environment:createLaunchEnvironmentSnapshot([{source:'process',values:process.env}])}); await ctx.loader.await(); const names=ctx.tools.schemas().map(tool=>tool.name); - if(names.length!==2 || !['dx_task_snapshot','dx_task_create'].every(name=>names.includes(name))) { + if(names.length!==6 || !['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute'].every(name=>names.includes(name))) { await shutdown.shutdown(1); throw Error('The task capability guard did not initialize; assistant startup refused.'); } @@ -105,6 +105,7 @@ export async function bootRuntime({announce=true} = {}) { const command=JSON.parse(line); if(command.type==='diagnose')ctx.emit('dx/diagnose-request',command); else if(command.type==='task_creation_result')ctx.emit('dx/task-creation-result',command); + else if(command.type==='task_lifecycle_result')ctx.emit('dx/task-lifecycle-result',command); }catch{} }); process.stdin.on('end',()=>void shutdown.shutdown(0)); diff --git a/integration/dsh/task-plugin/client.js b/integration/dsh/task-plugin/client.js index be4fbe9..59c8067 100644 --- a/integration/dsh/task-plugin/client.js +++ b/integration/dsh/task-plugin/client.js @@ -11,7 +11,7 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{ h('h3',null,'工作方式'), h('p',null,'在顶部切换任务中心和 DSH助手。会话、任务选择和未发送草稿会保留。'), h('h3',null,'任务能力'), - h('ul',null,...['在对话中描述任务名和替换规则,由原生窗口确认工程后创建真实任务','异常后自动创建诊断会话,收集证据','已授权执行遇到明确失败时,按规则最多重试一次并核验','无法解决时复盘,保存诊断和完整证据链,尝试提交 Git 工单','手动刷新任务上下文、准备重试或安全暂停'].map(text=>h('li',{key:text},text))), + h('ul',null,...['在对话中创建任务、查找和切换任务、复制配置到新工程','修改名称、备注、Value 策略与已有规则,预览同批影响后确认;归档保留证据','执行前预检所选任务,显示阻断原因;确认工程范围后启动或继续现有队列','对话请求安全暂停,返回实际保存、失败与未命中计数','异常后自动创建诊断会话,收集证据','已授权执行遇到明确失败时,按规则最多重试一次并核验','无法解决时复盘,保存诊断和完整证据链,尝试提交 Git 工单'].map(text=>h('li',{key:text},text))), h('h3',null,'模型与数据'), h('p',null,'使用主工具配置的模型,在输入框下方选择。会话保存在本机任务中心数据目录。'), h('h3',null,'异常工单'), @@ -42,6 +42,17 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{ h('div',{style:{whiteSpace:'pre-wrap',color:'var(--dsw-alias-label-secondary)',lineHeight:1.8}},text)); return h('div',{'data-testid':'dx-task-panel',style:{padding:20,overflow:'auto',height:'100%',boxSizing:'border-box'}}, section('当前任务',data?(data.task_name||data.task_id||'尚未选择任务'):'读取中…'), + data?.lifecycle?.request_id&&h('section',{'data-testid':'dx-task-lifecycle',style:{marginBottom:24}}, + h('h3',{style:{fontSize:14,fontWeight:500}},data.lifecycle.title||'对话任务操作'), + h('p',{'data-testid':'dx-lifecycle-status'},({checking:'正在核对真实任务',awaiting_confirmation:'请核对原生确认窗口', + applying:'正在保存配置',executing:'正在执行,等待实际结果',updated:'配置已更新',archived:'已移入回收站', + selected:'已切换任务',created:'已复制到新工程',preflight:'预检已完成',blocked:'执行已阻断',read:'任务记录已读取', + completed:'执行流程已结束,请核对各项计数',paused:'已安全暂停',cancelled:'已取消',rejected:'当前状态不允许操作',failed:'操作未完成'}[data.lifecycle.status]||data.lifecycle.status)), + data.lifecycle.preview&&h('p',{style:{whiteSpace:'pre-wrap',maxHeight:220,overflow:'auto',fontSize:12}},data.lifecycle.preview), + data.lifecycle.result?.tasks?.map(t=>h('p',{key:t.task_id,style:{whiteSpace:'pre-wrap',fontSize:12}}, + (t.name||t.task_id)+'\n'+(t.blockers?.length?t.blockers.join('\n'):t.saved_items!==undefined? + `已保存 ${t.saved_items} · 失败 ${t.failed_items} · 未命中 ${t.no_match_items}`:''))), + data.lifecycle.result?.message&&h('p',{style:{fontSize:12}},data.lifecycle.result.message)), data?.creation?.request_id&&h('section',{'data-testid':'dx-task-creation',style:{marginBottom:24}}, h('h3',{style:{fontSize:14,fontWeight:500}},'对话创建任务'), h('p',null,data.creation.name), @@ -68,7 +79,7 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{ h('button',{key:action,disabled:!data?.task_id,onClick:()=>request(action),style:{display:'block',width:'100%',textAlign:'left',marginTop:8,padding:'10px 12px', border:'1px solid var(--dsw-alias-border-l2)',background:'var(--dsw-alias-bg-base)',color:'var(--dsw-alias-label-primary)',borderRadius:12,cursor:'pointer'}},title)), h('p',{role:'status',style:{fontSize:12,color:'var(--dsw-alias-label-secondary)'}},data?.action_result||notice), - section('能力边界','对话可填写新任务,工程范围由原生窗口确认;创建仅写任务配置。\n自动诊断只读事件快照,处理沿用既有执行规则;不确定状态保留现场,转人工与工单。'), + section('能力边界','任务修改与执行展示具体范围后由原生窗口确认;预检核对保存的配置,不代表 CAD 已连通。\n自动诊断只读事件快照,处理沿用既有执行规则;不确定状态保留现场,转人工与工单。'), section('监管记录',(data?.events||[]).join('\n')||'等待任务事件')); } return{inject:['slots','sidebarRightTabs','sidebarRight','uiSession','uiWorkspace'],apply(ctx){ diff --git a/integration/dsh/task-plugin/host.mjs b/integration/dsh/task-plugin/host.mjs index cdd0ad2..564aaa4 100644 --- a/integration/dsh/task-plugin/host.mjs +++ b/integration/dsh/task-plugin/host.mjs @@ -2,6 +2,7 @@ import {readFile,appendFile} from 'node:fs/promises'; import path from 'node:path'; import {randomUUID,createHash} from 'node:crypto'; import {defineTool} from '@deepseek-ai/dsh-tools'; +import {registerLifecycle,lifecycleNames} from './lifecycle.mjs'; export const inject=['webServer','connection','tools','workspaceRegistry','sessionController','agents']; const actions=new Set(['retry_failed','pause_task','refresh_snapshot','retry_issue','open_evidence']); @@ -16,10 +17,10 @@ export async function apply(ctx){ const creations=new Map(); let auditTail=Promise.resolve(); ctx.on('tools/result',(exec,result)=>{ - if(!['dx_task_snapshot','dx_task_create'].includes(exec.name))return; + if(!['dx_task_snapshot','dx_task_create',...lifecycleNames].includes(exec.name))return; const row={at:new Date().toISOString(),name:exec.name,call_id:exec.callId,is_error:result.isError, task_id:result.value?.task_id||'',revision:result.value?.revision||'', - ...exec.name==='dx_task_create'?{status:result.value?.status,task_ids:result.value?.task_ids||[]}: {}}; + status:result.value?.status,task_ids:result.value?.task_ids||result.value?.tasks?.map(t=>t.task_id)||[]}; auditTail=auditTail.then(()=>appendFile(path.join(process.env.DX_DSH_HOME,'task-tool-audit.jsonl'),JSON.stringify(row)+'\n')) .catch(()=>{console.error('dx-task: could not persist tool audit');}); }); @@ -92,7 +93,8 @@ export async function apply(ctx){ return await promise; }finally{clearTimeout(timer);exec.signal.removeEventListener('abort',cancel);creations.delete(request_id);} }})); - ctx.tools.guard(exec=>exec.name==='dx_task_snapshot'||(exec.name==='dx_task_create'&&!incidentSnapshots.has(exec.agent?.id))? + registerLifecycle(ctx); + ctx.tools.guard(exec=>exec.name==='dx_task_snapshot'||(['dx_task_create',...lifecycleNames].includes(exec.name)&&!incidentSnapshots.has(exec.agent?.id))? undefined:'This tool is not enabled for this session. Automatic incident sessions may only read their snapshot.'); const workspace=await ctx.workspaceRegistry.create(process.env.DX_DSH_WORKSPACE,'DxDesigner 任务中心'); ctx.on('dx/diagnose-request',request=>{ diff --git a/integration/dsh/task-plugin/lifecycle.mjs b/integration/dsh/task-plugin/lifecycle.mjs new file mode 100644 index 0000000..23d171b --- /dev/null +++ b/integration/dsh/task-plugin/lifecycle.mjs @@ -0,0 +1,49 @@ +import {createHash} from 'node:crypto'; +import {defineTool} from '@deepseek-ai/dsh-tools'; + +export const lifecycleNames=['dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute']; + +export function registerLifecycle(ctx){ + const pending=new Map(); + ctx.on('dx/task-lifecycle-result',value=>pending.get(value.request_id)?.resolve(value)); + ctx.effect(()=>()=>{for(const request of pending.values())request.reject(Error('Task center disconnected'));},'dx-task: lifecycle requests'); + async function request(capability,spec,exec){ + if(process.env.DX_DSH_PARENT_PIPE!=='1')throw Error('This capability requires the task-center desktop.'); + if(!spec||typeof spec!=='object'||JSON.stringify(spec).length>16000)throw Error('Invalid task request'); + const request_id=createHash('sha256').update((exec.agent?.id||'')+':'+exec.callId).digest('hex').slice(0,32); + if(pending.has(request_id))return pending.get(request_id).promise; + let resolve,reject,timer; + const promise=new Promise((yes,no)=>{resolve=yes;reject=no;}); + const cancel=()=>{ + process.stdout.write('DX_DSH_LIFECYCLE_CANCEL '+JSON.stringify({request_id})+'\n'); + reject(Error('Conversation wait cancelled. Confirmed configuration writes may still finish. If execution started, a safe pause was requested; inspect actual task receipts.')); + }; + pending.set(request_id,{promise,resolve,reject}); + try{ + exec.signal.throwIfAborted();exec.signal.addEventListener('abort',cancel,{once:true}); + timer=setTimeout(cancel,capability==='execute'&&spec.operation==='start'?86400000:300000); + process.stdout.write('DX_DSH_LIFECYCLE_REQUEST '+JSON.stringify({request_id,capability,spec})+'\n'); + return await promise; + }finally{clearTimeout(timer);exec.signal.removeEventListener('abort',cancel);pending.delete(request_id);} + } + const output={schema:{type:'object',additionalProperties:true},render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]}; + 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.'}, + {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}, + 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.'}, + {name:'dx_task_execute',capability:'execute',parameters:{operation:{type:'string',required:true,enum:['start','pause']},task_ids:ids}, + 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.'}, + ]; + for(const {capability,...definition} of definitions){ + ctx.tools.register(defineTool({...definition,output,execute:(spec,exec)=>request(capability,spec,exec)})); + } +} diff --git a/src/dx_productivity/dsh/native_runtime.py b/src/dx_productivity/dsh/native_runtime.py index 8b6241c..b71ce29 100644 --- a/src/dx_productivity/dsh/native_runtime.py +++ b/src/dx_productivity/dsh/native_runtime.py @@ -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) -> dict: +def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None, creation=None, lifecycle=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 {}} + 'task_name': str(task_name)[:128], 'automation': automation or {}, 'creation': creation or {}, 'lifecycle': lifecycle 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' diff --git a/src/dx_productivity/dsh/task_creation.py b/src/dx_productivity/dsh/task_creation.py index eb1906b..84ee765 100644 --- a/src/dx_productivity/dsh/task_creation.py +++ b/src/dx_productivity/dsh/task_creation.py @@ -27,12 +27,16 @@ def validate_creation_spec(raw): if not isinstance(rules, list) or len(rules) > 30: raise TaskCenterError('assistant_task_rules', '一次最多创建 30 条替换规则。') for row in rules: - if not isinstance(row, dict) or set(row) - {'old_part_number', 'new_part_number', 'target_cell', 'custom_value', 'sync_nc'}: + if not isinstance(row, dict) or set(row) - {'old_part_number', 'new_part_number', 'target_cell', 'custom_value', 'sync_nc', 'enabled'}: raise TaskCenterError('assistant_task_rule_fields', '替换规则字段无效。') normalized = {'old_part_number': text(row.get('old_part_number'), 128, True), 'new_part_number': text(row.get('new_part_number'), 128, True), 'target_cell': text(row.get('target_cell', ''), 128), 'sync_nc': row.get('sync_nc', True)} + if 'enabled' in row: + if not isinstance(row['enabled'], bool): + raise TaskCenterError('assistant_task_rule_option', '规则启用状态必须为明确开关。') + normalized['enabled'] = row['enabled'] if 'custom_value' in row: normalized['custom_value'] = text(row['custom_value'], 500) if not isinstance(normalized['sync_nc'], bool): @@ -81,8 +85,8 @@ def create_confirmed_tasks(service, request_id, raw, root, selected_paths): tasks.append(store.set_copy_part_number_to_value(task.task_id, spec['copy_part_number_to_value'])) if tasks: for rule in spec['rules']: - mutate_batch_rules(service, tasks[0].task_id, 'add', **rule, - enabled=True, custom_value_enabled='custom_value' in rule) + mutate_batch_rules(service, tasks[0].task_id, 'add', **({'enabled': True} | rule), + custom_value_enabled='custom_value' in rule) result = {'status': 'created' if tasks else 'existing', 'created_count': len(tasks), 'existing_count': len(existing_ids), 'task_ids': [task.task_id for task in tasks] or existing_ids, 'existing_task_ids': existing_ids, 'rules_count': len(spec['rules']), 'cad_execution_started': False, diff --git a/src/dx_productivity/dsh/task_lifecycle.py b/src/dx_productivity/dsh/task_lifecycle.py new file mode 100644 index 0000000..3e39bda --- /dev/null +++ b/src/dx_productivity/dsh/task_lifecycle.py @@ -0,0 +1,214 @@ +"""Bounded task intents, immutable previews and confirmed task-center mutations.""" +from dataclasses import asdict +from hashlib import sha256 +import json +import re + +from ..trial_task_center.errors import TaskCenterError +from ..trial_task_center.models import TaskStatus +from ..trial_task_center.batch_rules import members, mutate_batch_rules +from ..trial_task_center.rule_validation import validate_mapping_pairs + + +def _digest(value): + return sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, default=str).encode()).hexdigest() + + +def _summary(task): + return {'task_id': task.task_id, 'name': task.name, 'status': task.status.value, + 'group_id': task.group_id, 'note': task.note[:2000]} + + +def catalog(service, task_id=None): + result = {'tasks': [_summary(t) for t in service.tasks()][:500], 'limit': 500} + if task_id is not None: + context = _context(service, task_id) + result['detail'] = {**_summary(context.task), 'project': str(context.project.path) if context.project else '', + '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} + return result + + +def _context(service, task_id): + if not isinstance(task_id, str) or not task_id or len(task_id) > 128: + raise TaskCenterError('assistant_task_id', '请使用任务列表中的真实任务编号。') + return service.task_context(task_id) + + +def fingerprint(service, ids): + return _digest([asdict(_context(service, key)) for key in ids]) + + +def preflight(service, task_ids): + 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): + raise TaskCenterError('assistant_task_scope', '请选择 1 至 20 个不同的真实任务。') + tasks, paths, hashes = [], set(), {} + pending = bool(service.pending_batch_resources()) + for task_id in task_ids: + context = _context(service, task_id) + state = execution_state(context) + blockers = [] + if not state.execute: + blockers.append(state.message) + if context.phase == 'retry': + blockers.append('存在失败项,请先核对证据并准备失败项重试。') + path = context.project.path if context.project else None + if path is None or not path.is_file(): + blockers.append('工程文件不存在或不可访问。') + elif str(path.resolve()).casefold() in paths: + blockers.append('本次范围重复包含同一个工程。') + else: + paths.add(str(path.resolve()).casefold()) + count = sum(row.enabled for row in (context.targets if context.task.target_plan_mode else context.rules)) + if not count: + blockers.append('没有已启用的替换规则或位号。') + try: + service._execution_rules(task_id) + except TaskCenterError as error: + blockers.append(error.message) + if pending: + blockers.append('上一次执行的后台资源尚未释放。') + hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id) + tasks.append({**_summary(context.task), 'project': str(path or ''), 'enabled_rules': count, + '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, + 'plan_hashes': hashes, 'fingerprint': fingerprint(service, task_ids), + 'cad_connection_checked': False, + 'message': '已核对保存的配置和执行证据;CAD 连接、备份与保存核验由正式执行流程完成。'} + + +def _text(value, limit, required=False): + if not isinstance(value, str) or len(value) > limit or '\x00' in value or (required and not value.strip()): + raise TaskCenterError('assistant_patch', '任务或规则文本无效。') + return value.strip() + + +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'}: + raise TaskCenterError('assistant_operation', '不支持此任务操作。') + context = _context(service, raw.get('task_id')) + if context.task.status is TaskStatus.DELETED: + raise TaskCenterError('assistant_deleted', '任务已归档,请先在回收站恢复。') + 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 开关和已有料号规则。') + patch = dict(patch) + if op == 'update' and not patch: + raise TaskCenterError('assistant_patch', '请明确需要修改的字段。') + for key, limit in [('name', 120), ('note', 2000)]: + if key in patch: + patch[key] = _text(patch[key], limit, key == 'name') + if 'copy_part_number_to_value' in patch and not isinstance(patch['copy_part_number_to_value'], bool): + raise TaskCenterError('assistant_patch', 'Value 策略必须为明确开关。') + affected = members(service._store, context.task.task_id) if 'rules' in patch else (context.task,) + changes = [] + for key in ('name', 'note', 'copy_part_number_to_value'): + if key in patch: + changes.append({'task_id': context.task.task_id, 'field': key, + 'before': getattr(context.task, key), 'after': patch[key]}) + if 'copy_part_number_to_value' in patch: + if not service.can_edit_value_options(context.task.task_id): + raise TaskCenterError('quick_run_options_locked', '当前任务的 Value 策略已冻结。') + if 'rules' in patch: + rows = patch['rules'] + if not isinstance(rows, list) or not 1 <= len(rows) <= 30: + raise TaskCenterError('assistant_patch', '一次可修改 1 至 30 条已有规则。') + for task in affected: + if task.status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED}: + raise TaskCenterError('rules_locked', f'同批任务「{task.name}」已冻结。') + service._editable_rules(task.task_id, lambda: None) + existing = {r.old_part_number.casefold(): r for r in context.rules} + normalized, seen = [], set() + for row in rows: + if not isinstance(row, dict) or set(row) - {'old_part_number', 'new_part_number', 'target_cell', 'custom_value', 'custom_value_enabled', 'sync_nc', 'enabled'}: + raise TaskCenterError('assistant_patch', '规则修改字段无效。') + row = dict(row) + old = _text(row.get('old_part_number'), 128, True).casefold() + if old not in existing or old in seen or len(row) < 2: + raise TaskCenterError('assistant_patch', '只能按唯一旧料号修改已有规则。') + seen.add(old) + row['old_part_number'] = existing[old].old_part_number + for key in ('new_part_number', 'target_cell', 'custom_value'): + if key in row: + row[key] = _text(row[key], 500 if key == 'custom_value' else 128, key == 'new_part_number') + for key in ('sync_nc', 'enabled', 'custom_value_enabled'): + if key in row and not isinstance(row[key], bool): + raise TaskCenterError('assistant_patch', '规则开关必须为布尔值。') + if 'new_part_number' in row and row['new_part_number'] != existing[old].new_part_number: + row.setdefault('target_cell', '') + if 'custom_value' in row: + row.setdefault('custom_value_enabled', True) + for key, value in row.items(): + if key != 'old_part_number': + changes.append({'task_id': '同批全部任务', 'field': row['old_part_number'] + '.' + key, + 'before': getattr(existing[old], key), 'after': value}) + normalized.append(row) + pairs = {r.old_part_number.casefold(): r.new_part_number for r in context.rules} + for row in normalized: + pairs[row['old_part_number'].casefold()] = row.get('new_part_number', pairs[row['old_part_number'].casefold()]) + validate_mapping_pairs(pairs.items()) + patch['rules'] = normalized + ids = [t.task_id for t in affected] + return {'spec': {'operation': op, 'task_id': context.task.task_id, **({'patch': patch} if patch else {})}, + 'affected_tasks': [_summary(t) for t in affected], 'changes': changes, + 'fingerprint': fingerprint(service, ids)} + + +def apply_confirmed(service, request_id, plan): + if not isinstance(request_id, str) or not re.fullmatch('[a-f0-9]{32}', request_id): + raise TaskCenterError('assistant_request_id', '任务请求编号无效。') + digest = _digest(plan) + def apply(): + store = service._store + with store.transaction(): + prior = store.assistant_operation_receipt(request_id) + if prior: + if prior['request_hash'] != digest: + raise TaskCenterError('assistant_request_conflict', '请求编号已用于另一项操作。') + return prior['result'] | {'replayed': True} + current = preview(service, plan['spec']) + if current != plan: + raise TaskCenterError('assistant_stale', '任务配置已变化,请重新生成预览后确认。') + spec = plan['spec']; task_id = spec['task_id']; op = spec['operation'] + if op == 'archive': + store.soft_delete_task(task_id) + status = 'archived' + elif op == 'update': + patch = spec['patch']; task = store.get_task(task_id) + if 'name' in patch or 'note' in patch: + store.update_task(task_id, name=patch.get('name', task.name), note=patch.get('note', task.note)) + if 'copy_part_number_to_value' in patch: + store.set_copy_part_number_to_value(task_id, patch['copy_part_number_to_value']) + for row in patch.get('rules', []): + rule = next(r for r in service.rules(task_id) if r.old_part_number == row['old_part_number']) + options = {key: getattr(rule, key) for key in ('old_part_number', 'new_part_number', 'enabled', + 'target_cell', 'custom_value', 'custom_value_enabled', 'sync_nc')} + options.update(row) + mutate_batch_rules(service, task_id, 'update', rule_id=rule.rule_id, **options) + status = 'updated' + else: + raise TaskCenterError('assistant_operation', '此操作不属于配置写入。') + result = {'status': status, 'task_id': task_id, 'task_ids': [t['task_id'] for t in plan['affected_tasks']], + 'cad_execution_started': False} + store.record_assistant_operation(request_id, digest, result) + return result + return service._idle_quick_run_operation('assistant_task_change', plan['spec']['task_id'], apply) + + +def copy_spec(service, task_id): + context = _context(service, task_id) + if context.legacy: + raise TaskCenterError('assistant_legacy', '历史任务请在任务中心查看后重新创建。') + return {'name': context.task.name[:115] + ' 副本', 'note': context.task.note, + 'copy_part_number_to_value': context.task.copy_part_number_to_value, + 'rules': [{'old_part_number': r.old_part_number, 'new_part_number': r.new_part_number, + 'target_cell': r.target_cell, 'sync_nc': r.sync_nc, 'enabled': r.enabled, + **({'custom_value': r.custom_value} if r.custom_value_enabled else {})} for r in context.rules]} diff --git a/src/dx_productivity/trial_task_center/store.py b/src/dx_productivity/trial_task_center/store.py index 1eaf0b4..11b22d3 100644 --- a/src/dx_productivity/trial_task_center/store.py +++ b/src/dx_productivity/trial_task_center/store.py @@ -160,6 +160,17 @@ class TaskStore: def _initialize_schema(self) -> None: return self._schema._initialize_schema() + def assistant_operation_receipt(self, request_id): + with self._lock: + row = self._connection.execute('SELECT request_hash, result_json FROM assistant_task_operations WHERE request_id = ?', + (request_id,)).fetchone() + return None if row is None else {'request_hash': row['request_hash'], 'result': json.loads(row['result_json'])} + + def record_assistant_operation(self, request_id, request_hash, result): + with self.transaction(): + self._connection.execute('INSERT INTO assistant_task_operations VALUES (?, ?, ?)', + (request_id, request_hash, json.dumps(result, ensure_ascii=False))) + def _create_schema_v1(self) -> None: return self._schema._create_schema_v1() diff --git a/src/dx_productivity/trial_task_center/store_schema.py b/src/dx_productivity/trial_task_center/store_schema.py index 1d22a8f..705c2e0 100644 --- a/src/dx_productivity/trial_task_center/store_schema.py +++ b/src/dx_productivity/trial_task_center/store_schema.py @@ -54,6 +54,8 @@ class StoreSchema: self._store._create_target_plan_schema() self._store._connection.execute('''CREATE TABLE IF NOT EXISTS assistant_task_creations ( request_id TEXT PRIMARY KEY, request_hash TEXT NOT NULL, result_json TEXT NOT NULL)''') + self._store._connection.execute('''CREATE TABLE IF NOT EXISTS assistant_task_operations ( + request_id TEXT PRIMARY KEY, request_hash TEXT NOT NULL, result_json TEXT NOT NULL)''') def _create_schema_v1(self) -> None: statements = ( diff --git a/src/dx_productivity/trial_task_center/task_queue.py b/src/dx_productivity/trial_task_center/task_queue.py index 5dc1971..0b15ed8 100644 --- a/src/dx_productivity/trial_task_center/task_queue.py +++ b/src/dx_productivity/trial_task_center/task_queue.py @@ -129,15 +129,16 @@ 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) -> TaskQueueResult: + queue_id: str | None = None, runtime=None, expected_plan_hashes=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}, stop_event=stop_event) + return service._supervise('execute_task_queue', {'task_ids': task_ids, 'queue_id': queue_id, + 'expected_plan_hashes': expected_plan_hashes}, 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) + queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes) owned_runtime.result = result return result ids = tuple(task_ids) @@ -157,6 +158,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。') runtime.bind_logs(service._logging, ids) 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 len(token) != 32 or any(char not in '0123456789abcdef' for char in token): raise TaskCenterError('task_queue_state', '任务队列编号无效。') 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 09952df..0509a67 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_automation.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_automation.py @@ -66,7 +66,8 @@ class DshAutomation(QObject): w = self.window if w._closed or self.worker is not None or not self.pending: return - if w._workers or w._loading: + 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)): QTimer.singleShot(200, self._drain) return task_id, code, message, authorized, run_id = self.pending.pop(0) diff --git a/src/dx_productivity/trial_task_center/ui/dsh_native.py b/src/dx_productivity/trial_task_center/ui/dsh_native.py index 5dbd39e..3d2dd26 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_native.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_native.py @@ -31,6 +31,8 @@ class NativeHarnessView(QWidget): diagnosis_event = Signal(object) task_creation_requested = Signal(object) task_creation_cancelled = Signal(object) + lifecycle_requested = Signal(object) + lifecycle_cancelled = Signal(object) def __init__(self, data_root: Path, parent=None): super().__init__(parent) @@ -40,6 +42,7 @@ class NativeHarnessView(QWidget): self.context = None self.automation = {} self.creation = {} + self.lifecycle = {} self._diagnosis_queue = [] self._pending_context = None self._context_attempts = 0 @@ -81,7 +84,7 @@ class NativeHarnessView(QWidget): def bind(self, snapshot: TaskSnapshot, *, events=(), action_result='', task_name=''): self._pending_context = (snapshot, {'events': tuple(events), 'action_result': action_result, 'task_name': task_name, - 'automation': dict(self.automation), 'creation': dict(self.creation)}) + 'automation': dict(self.automation), 'creation': dict(self.creation), 'lifecycle': dict(getattr(self, 'lifecycle', {}))}) self._context_attempts = 0 self._publish_pending_context() @@ -107,6 +110,10 @@ class NativeHarnessView(QWidget): if self.is_running: self.process.write((json.dumps({'type': 'task_creation_result', **result}, ensure_ascii=False) + '\n').encode('utf8')) + def complete_lifecycle(self, result): + if self.is_running: + self.process.write((json.dumps({'type': 'task_lifecycle_result', **result}, ensure_ascii=False) + '\n').encode('utf8')) + def request_diagnosis(self, request): if self._started: self.process.write((json.dumps({'type': 'diagnose', **request}, ensure_ascii=False) + '\n').encode('utf8')) @@ -169,6 +176,10 @@ class NativeHarnessView(QWidget): self.task_creation_requested.emit(json.loads(line[len('DX_DSH_CREATE_REQUEST '):])) elif line.startswith('DX_DSH_CREATE_CANCEL '): self.task_creation_cancelled.emit(json.loads(line[len('DX_DSH_CREATE_CANCEL '):])) + elif line.startswith('DX_DSH_LIFECYCLE_REQUEST '): + self.lifecycle_requested.emit(json.loads(line[len('DX_DSH_LIFECYCLE_REQUEST '):])) + elif line.startswith('DX_DSH_LIFECYCLE_CANCEL '): + self.lifecycle_cancelled.emit(json.loads(line[len('DX_DSH_LIFECYCLE_CANCEL '):])) elif line.startswith('DX_DSH_ACTION '): request = json.loads(line[len('DX_DSH_ACTION '):]) if self.context and request.get('task_id') == self.context['task_id'] and request.get('revision') == self.context['revision']: diff --git a/src/dx_productivity/trial_task_center/ui/dsh_task_creation.py b/src/dx_productivity/trial_task_center/ui/dsh_task_creation.py index 41a33ba..7de3449 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_task_creation.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_task_creation.py @@ -3,7 +3,7 @@ from __future__ import annotations import re -from PySide6.QtCore import QObject, QThreadPool, QTimer +from PySide6.QtCore import QObject, QThreadPool, QTimer, Signal from PySide6.QtWidgets import QDialogButtonBox, QLabel, QLineEdit, QPlainTextEdit from ...dsh.task_creation import validate_creation_spec @@ -23,7 +23,7 @@ class DshTaskCreationDialog(DirectoryTaskDialog): preview = QPlainTextEdit(objectName='dshTaskDraftPreview') preview.setReadOnly(True) preview.setMaximumHeight(150) - rows = [f"{r['old_part_number']} → {r['new_part_number']}" + (f" · 封装 {r['target_cell']}" if r['target_cell'] else '') + rows = [f"{r['old_part_number']} → {r['new_part_number']}" + (' · 已禁用' if not r.get('enabled', True) else '') + (f" · 封装 {r['target_cell']}" if r['target_cell'] else '') + (f" · Value {r['custom_value']}" if 'custom_value' in r else '') + (' · 同步 NC' if r['sync_nc'] else ' · 不同步 NC') for r in spec['rules']] preview.setPlainText((spec['note'] + '\n\n' if spec['note'] else '') + ('替换规则:\n' + '\n'.join(rows) if rows else '暂未填写替换规则,创建后可在任务中心补齐。') + @@ -37,6 +37,8 @@ class DshTaskCreationDialog(DirectoryTaskDialog): class DshTaskCreationController(QObject): + completed = Signal(object) + def __init__(self, window, view): super().__init__(window) self.window, self.view = window, view @@ -55,6 +57,7 @@ class DshTaskCreationController(QObject): def _respond(self, result): self._state(result['status'], result=result) self.view.complete_task_creation(result) + self.completed.emit(result) self.results[result['request_id']] = result if len(self.results) > 100: self.results.pop(next(iter(self.results))) @@ -69,7 +72,9 @@ class DshTaskCreationController(QObject): return if self.request_id == request_id: return - if self.request_id is not None or self.worker is not None or self.window._workers or self.window._closed: + 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)): self.view.complete_task_creation({'request_id': request_id, 'status': 'busy', 'message': '任务中心当前正在处理其他操作,请收尾后再创建。'}) return 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 new file mode 100644 index 0000000..1d7c092 --- /dev/null +++ b/src/dx_productivity/trial_task_center/ui/dsh_task_lifecycle.py @@ -0,0 +1,282 @@ +"""Native task previews and existing queue execution for Harness conversations.""" +from __future__ import annotations + +import re + +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 .workers import ServiceWorker + + +class DshLifecycleDialog(QDialog): + def __init__(self, title, text, parent): + super().__init__(parent) + self.setWindowTitle('DSH助手 · ' + title) + self.setObjectName('dshLifecyclePreview') + self.resize(740, 550) + layout = QVBoxLayout(self) + layout.addWidget(QLabel(title)) + self.preview = QPlainTextEdit(text, objectName='dshLifecycleText') + self.preview.setReadOnly(True) + layout.addWidget(self.preview) + self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) + self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('确认' + title) + self.buttons.accepted.connect(self.accept) + self.buttons.rejected.connect(self.reject) + layout.addWidget(self.buttons) + self.setModal(True) + + +class DshTaskLifecycleController(QObject): + def __init__(self, window, view): + super().__init__(window) + self.window, self.view = window, view + self.dialog = None + self.request_id = None + self.worker = None + self.results = {} + self.active_ids = () + self.copy_requests = set() + view.lifecycle_requested.connect(self.request) + view.lifecycle_cancelled.connect(self.cancel) + view.stopped.connect(self.runtime_stopped) + window._dsh_task_creation.completed.connect(self._copied) + + def _copied(self, result): + key = result['request_id'] + if key in self.copy_requests: + self.copy_requests.discard(key) + if self.request_id is None: + self.request_id = key + self._respond(key, **{k: v for k, v in result.items() if k != 'request_id'}) + + def _state(self, status, **values): + self.view.lifecycle = {'request_id': self.request_id, 'status': status, **values} + self.window._bind_dsh_context() + + def _respond(self, request_id, **result): + result = {'request_id': request_id, **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 + self.view.complete_lifecycle(result) + + def _failed(self, request_id, error): + if not isinstance(error, TaskCenterError): + self.window.service.report_ui_error(error) + self._respond(request_id, 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): + worker = ServiceWorker(operation) + self.worker = worker + self.window._workers.add(worker) + request_id = self.request_id + def succeeded(result): + if self.request_id != request_id or self.window._closed: + return + try: + done(result) + except Exception as error: + failed(error) + worker.signals.succeeded.connect(succeeded) + def failed(error): + if executing: + self.window._finish_run() + self.active_ids = () + self.window._show_error(error, owner_task_id=self._execution_owner) + self.window._metadata_changed(None) + self._failed(request_id, error) + def finished(): + self.worker = None + self.window._workers.discard(worker) + self.window._update_gates() + if self.window._close_pending: + QTimer.singleShot(0, self.window.close) + worker.signals.failed.connect(failed) + worker.signals.finished.connect(finished) + self.window._update_gates() + QThreadPool.globalInstance().start(worker) + + def request(self, value): + request_id = value.get('request_id') + if not isinstance(request_id, str) or not re.fullmatch('[a-f0-9]{32}', request_id): + return + if request_id in self.results: + self.view.complete_lifecycle(self.results[request_id]); return + if self.request_id == request_id: + return + spec = value.get('spec', {}) + capability = value.get('capability') + # 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 ()) + 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): + self._respond(request_id, status='rejected', message='没有与所选范围一致的活动执行。'); return + self.window._pause_queue() + self._respond(request_id, status='pause_requested', task_ids=list(allowed), + message='已请求安全暂停,当前项收尾后才会停止。尚未声称已暂停。') + 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)): + self._respond(request_id, status='busy', message='请等待当前操作或确认窗口收尾。'); return + self.request_id = request_id + self._state('checking') + 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)) + 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 + ids = spec.get('task_ids') + 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)) + elif capability == 'manage': + self._work(lambda: api.preview(self.window.service, spec), lambda plan: self._plan_ready(request_id, plan)) + else: + self._failed(request_id, TaskCenterError('assistant_capability', '未开放此能力。')) + + def _show(self, title, text, accepted): + self._state('awaiting_confirmation', title=title, preview=text) + self.dialog = DshLifecycleDialog(title, text, self.window) + dialog = self.dialog + request_id = self.request_id + def yes(): + self.dialog = None + dialog.deleteLater() + # A read worker's finished signal can arrive after its result signal. + QTimer.singleShot(0, accepted) + def no(): + self.dialog = None + dialog.deleteLater() + self._respond(request_id, status='cancelled', message='用户已取消,未提交变更或执行。') + dialog.accepted.connect(yes); dialog.rejected.connect(no) + dialog.open() + + def _plan_ready(self, request_id, plan): + 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 == 'copy': + # Project scope and configuration preview use the existing creation controller. + try: + draft = api.copy_spec(self.window.service, task_id) + except Exception as error: + self._failed(request_id, error); return + self._state('awaiting_confirmation', title='复制任务:请选择新工程') + def launch(): + if self.request_id != request_id: + return + creation = self.window._dsh_task_creation + self.copy_requests.add(request_id) + self.request_id = None + creation.request({'request_id': request_id, 'spec': draft}) + QTimer.singleShot(0, launch) + return + text = '\n'.join(f"{t['name']} [{t['task_id']}]" for t in plan['affected_tasks']) + labels = {'name': '名称', 'note': '备注', 'copy_part_number_to_value': '料号复制到 Value'} + for change in plan['changes']: + text += f"\n\n{labels.get(change['field'], change['field'])}:{change['before']} → {change['after']}" + if op == 'archive': + text += '\n\n移入回收站,保留执行证据;不永久删除,不修改工程。' + else: + text += '\n\n仅写入任务配置,不执行 CAD。同批规则变更会应用到以上全部任务。' + def apply(): + if self.request_id != 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 + self._state('applying') + def done(result): + self.window._metadata_changed(None) + self._respond(request_id, **result) + 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): + 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'] + def start(): + if self.request_id != 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 + self._state('executing', task_ids=ids) + self.active_ids = tuple(ids) + self._execution_owner = ids[0] + self.window._dsh_authorized_tasks.update(ids) + self.window._begin_run(ids[0]) + 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': '请按每项实际计数判断;未命中不表示已替换保存。'} + def done(result): + self.window._finish_run(); self.active_ids = () + self.window._metadata_changed(None) + for task in result['tasks']: + 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) + self._work(operation, done, executing=True) + self._show('执行所选任务', text, start) + + def cancel(self, value): + if value.get('request_id') in self.copy_requests: + self.window._dsh_task_creation.cancel(value) + return + if value.get('request_id') != self.request_id: + return + if self.worker is not None: + # A service worker has no safe cancellation point. Do not clear its + # request or claim cancellation while an update or queue is already + # committing; the worker must publish the real receipt. + if not self.dialog and not self.active_ids: + # A read-only preflight/catalog can be abandoned safely. The + # later result must be ignored so it cannot open a confirmation + # dialog after the model has cancelled its request. + if self.view.lifecycle.get('status') == 'checking': + self._respond(self.request_id, status='cancelled', message='已取消,未提交变更。') + return + if self.dialog: + self.dialog.reject() + elif self.active_ids and self.window._batch_stop: + self.window._pause_queue() + else: + self._respond(self.request_id, status='cancelled', message='请求已取消,未提交变更或执行。') + + def runtime_stopped(self): + if self.request_id: + self.cancel({'request_id': self.request_id}) 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 041e020..638119b 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -36,6 +36,7 @@ class TrialTaskCenterWindow(QMainWindow): self._dsh = DshSupervisor(DshServiceAdapter(service).execute) self._dsh_view = None self._dsh_task_creation = None + self._dsh_lifecycle = None self._dsh_stopping = False self._dsh_automation = None self._dsh_run_id = 'observation' @@ -880,6 +881,8 @@ class TrialTaskCenterWindow(QMainWindow): 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_view.action_requested.connect(self._handle_dsh_action) self.content_stack.addWidget(self._dsh_view) self._bind_dsh_context() @@ -968,7 +971,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): + 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)): return worker = ServiceWorker(operation) self._workers.add(worker) diff --git a/tests/ui/test_dsh_native_menu.py b/tests/ui/test_dsh_native_menu.py index f4b72a2..bae36a0 100644 --- a/tests/ui/test_dsh_native_menu.py +++ b/tests/ui/test_dsh_native_menu.py @@ -8,6 +8,8 @@ class HarnessView(QWidget): action_requested = Signal(object) task_creation_requested = Signal(object) task_creation_cancelled = Signal(object) + lifecycle_requested = Signal(object) + lifecycle_cancelled = Signal(object) stopped = Signal() def __init__(self, parent): @@ -15,6 +17,8 @@ class HarnessView(QWidget): self.starts = 0 self.binds = [] self.creation = {} + self.lifecycle = {} + self.lifecycle_results = [] self.results = [] def start(self): @@ -30,6 +34,9 @@ class HarnessView(QWidget): def complete_task_creation(self, value): self.results.append(value) + def complete_lifecycle(self, value): + self.lifecycle_results.append(value) + def test_direct_navigation_opens_harness_and_returns_without_losing_task(ui, monkeypatch, qtbot): window = ui.window diff --git a/tests/ui/test_dsh_task_lifecycle.py b/tests/ui/test_dsh_task_lifecycle.py new file mode 100644 index 0000000..7b3bd02 --- /dev/null +++ b/tests/ui/test_dsh_task_lifecycle.py @@ -0,0 +1,214 @@ +import pytest +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QDialogButtonBox + +from dx_productivity.trial_task_center.errors import TaskCenterError + + +def lifecycle(): + from dx_productivity.dsh import task_lifecycle + return task_lifecycle + + +def test_catalog_and_preflight_use_real_tasks_and_do_not_execute(ui): + api = lifecycle() + catalog = api.catalog(ui.service) + assert {t['task_id'] for t in catalog['tasks']} == {t.task_id for t in ui.tasks} + report = api.preflight(ui.service, [ui.tasks[0].task_id]) + assert report['ready'] and report['tasks'][0]['enabled_rules'] == 1 + assert report['cad_connection_checked'] is False + assert not ui.calls + detail = api.catalog(ui.service, ui.tasks[0].task_id)['detail'] + assert detail['rules'][0]['old_part_number'] == 'OLD' + assert detail['rules'][0]['new_part_number'] == 'NEW' + ui.service.delete_task(ui.tasks[0].task_id) + report = api.preflight(ui.service, [ui.tasks[0].task_id]) + assert not report['ready'] and report['tasks'][0]['blockers'] + + +def test_confirmed_rule_change_previews_batch_and_commits_once(ui): + api = lifecycle() + spec = {'operation': 'update', 'task_id': ui.tasks[0].task_id, + 'patch': {'name': 'Renamed', 'rules': [{'old_part_number': 'OLD', 'new_part_number': 'NEXT'}]}} + plan = api.preview(ui.service, spec) + assert {t['task_id'] for t in plan['affected_tasks']} == {t.task_id for t in ui.tasks} + assert ui.store.list_rules(ui.tasks[0].task_id)[0].new_part_number == 'NEW' + result = api.apply_confirmed(ui.service, 'a' * 32, plan) + assert result['status'] == 'updated' + assert ui.store.get_task(ui.tasks[0].task_id).name == 'Renamed' + for task in ui.tasks: + assert ui.store.list_rules(task.task_id)[0].new_part_number == 'NEXT' + assert api.apply_confirmed(ui.service, 'a' * 32, plan)['replayed'] + from dx_productivity.trial_task_center.store import TaskStore + reopened = TaskStore(ui.store.path) + try: + assert reopened.assistant_operation_receipt('a' * 32)['result'] == result + finally: + reopened.close() + assert not ui.calls + + +def test_preview_includes_derived_cell_reset_and_custom_value_enable(ui): + api = lifecycle() + rule = ui.store.list_rules(ui.tasks[0].task_id)[0] + ui.service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW', enabled=True, target_cell='QFN') + plan = api.preview(ui.service, {'operation': 'update', 'task_id': ui.tasks[0].task_id, + 'patch': {'rules': [{'old_part_number': 'OLD', 'new_part_number': 'NEXT', 'custom_value': 'Explicit value'}]}}) + changes = {row['field']: row for row in plan['changes']} + assert changes['OLD.target_cell']['before'] == 'QFN' and changes['OLD.target_cell']['after'] == '' + assert changes['OLD.custom_value_enabled']['after'] is True + api.apply_confirmed(ui.service, '9' * 32, plan) + actual = ui.store.list_rules(ui.tasks[0].task_id)[0] + assert actual.target_cell == '' and actual.custom_value_enabled + + +def test_stale_preview_rejects_all_changes_and_invalid_patch_is_not_applied(ui): + api = lifecycle() + plan = api.preview(ui.service, {'operation': 'update', 'task_id': ui.tasks[0].task_id, + 'patch': {'name': 'Unapplied'}}) + ui.service.update_task(ui.tasks[0].task_id, name='Changed elsewhere', note='') + with pytest.raises(TaskCenterError, match='assistant_stale'): + api.apply_confirmed(ui.service, 'b' * 32, plan) + assert ui.store.get_task(ui.tasks[0].task_id).name == 'Changed elsewhere' + with pytest.raises(TaskCenterError): + api.preview(ui.service, {'operation': 'update', 'task_id': ui.tasks[0].task_id, + 'patch': {'confirmed': True}}) + + +def test_archive_keeps_evidence_and_preflight_detects_missing_project(ui): + api = lifecycle() + task_id = ui.tasks[0].task_id + plan = api.preview(ui.service, {'operation': 'archive', 'task_id': task_id}) + assert api.apply_confirmed(ui.service, 'c' * 32, plan)['status'] == 'archived' + assert ui.store.get_task(task_id).status.value == 'deleted' + assert ui.store.list_rules(task_id) + ui.service.restore_task(task_id) + ui.store.list_projects(task_id)[0].path.unlink() + assert not api.preflight(ui.service, [task_id])['ready'] + + +def controller(ui, monkeypatch): + from test_dsh_native_menu import HarnessView + monkeypatch.setattr(type(ui.window), '_create_dsh_view', lambda self: HarnessView(self)) + ui.window._open_dsh() + return ui.window._dsh_lifecycle, ui.window._dsh_view + + +def request(ui, operation, **values): + return {'request_id': 'd' * 32, 'capability': 'manage', + 'spec': {'operation': operation, 'task_id': ui.tasks[0].task_id, **values}} + + +def test_dialog_cancel_and_stale_confirm_do_not_modify(ui, monkeypatch, qtbot): + ctl, view = controller(ui, monkeypatch) + ctl.request(request(ui, 'update', patch={'name': 'Never'})) + qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000) + qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Cancel), Qt.MouseButton.LeftButton) + assert view.lifecycle_results[-1]['status'] == 'cancelled' + assert ui.service.get_task(ui.tasks[0].task_id).name != 'Never' + ui.settle() + + +def test_dialog_executes_existing_queue_and_reports_real_no_match(ui, monkeypatch, qtbot): + ctl, view = controller(ui, monkeypatch) + ctl.request({'request_id': 'e' * 32, 'capability': 'execute', + 'spec': {'operation': 'start', 'task_ids': [ui.tasks[0].task_id]}}) + qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000) + assert not ui.calls + qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton) + qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=15000) + result = view.lifecycle_results[-1] + assert result['status'] == 'completed' and result['tasks'][0]['no_match_items'] == 1 + assert result['tasks'][0]['saved_items'] == 0 and ui.calls + ui.settle() + + +def test_cancel_during_preview_read_never_opens_later_dialog(ui, monkeypatch, qtbot): + ctl, view = controller(ui, monkeypatch) + value = request(ui, 'update', patch={'name': 'Never'}) + ctl.request(value) + ctl.cancel({'request_id': value['request_id']}) + ui.settle() + assert ctl.dialog is None + assert view.lifecycle_results[-1]['status'] == 'cancelled' + + +def test_abort_during_confirmed_commit_retains_actual_mutation_receipt(ui, monkeypatch, qtbot): + from threading import Event + ctl, view = controller(ui, monkeypatch) + api = lifecycle(); original = api.apply_confirmed + entered, release = Event(), Event() + def delayed(*args): + entered.set() + assert release.wait(5) + return original(*args) + monkeypatch.setattr(api, 'apply_confirmed', delayed) + value = request(ui, 'update', patch={'name': 'Committed truthfully'}) + ctl.request(value) + qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000) + qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton) + try: + qtbot.waitUntil(entered.is_set, timeout=5000) + ctl.cancel({'request_id': value['request_id']}) + assert not view.lifecycle_results + finally: + release.set() + qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000) + assert view.lifecycle_results[-1]['status'] == 'updated' + assert ui.service.get_task(ui.tasks[0].task_id).name == 'Committed truthfully' + assert ui.store.assistant_operation_receipt(value['request_id'])['result']['status'] == 'updated' + ui.settle() + + +def test_stale_native_preview_rejects_confirmation(ui, monkeypatch, qtbot): + ctl, view = controller(ui, monkeypatch) + ctl.request(request(ui, 'update', patch={'name': 'Never'})) + qtbot.waitUntil(lambda: ctl.dialog is not None and ctl.worker is None, timeout=5000) + ui.service.update_task(ui.tasks[0].task_id, name='External edit', note='') + 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]['code'] == 'assistant_stale' + assert ui.service.get_task(ui.tasks[0].task_id).name == 'External edit' + ui.settle() + + +def test_copy_opens_native_new_scope_dialog_and_returns_actual_ids(ui, monkeypatch, qtbot, tmp_path): + ctl, view = controller(ui, monkeypatch) + ui.service.update_rule(ui.store.list_rules(ui.tasks[0].task_id)[0].rule_id, + old_part_number='OLD', new_part_number='NEW', enabled=False) + root = tmp_path / 'new-scope'; root.mkdir() + project = root / 'new.prj' + project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n') + ctl.request(request(ui, 'copy')) + creation = ui.window._dsh_task_creation + qtbot.waitUntil(lambda: creation.dialog is not None, timeout=5000) + dialog = creation.dialog + assert not dialog.spec['rules'][0]['enabled'] + qtbot.keyClicks(dialog.directory, str(root)) + qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton) + qtbot.waitUntil(lambda: dialog._worker is None and dialog.projects.count() == 1, timeout=5000) + qtbot.mouseClick(dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton) + qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000) + result = view.lifecycle_results[-1] + assert result['created_count'] == 1 + assert not ui.store.list_rules(result['task_ids'][0])[0].enabled + assert result['task_ids'][0] not in {t.task_id for t in ui.tasks} + assert not ui.calls + ui.settle() + + +def test_pause_uses_active_stop_control_and_refuses_other_scope(ui, monkeypatch): + from dx_productivity.trial_task_center.stop_control import StopControl + ctl, view = controller(ui, monkeypatch) + owner = ui.tasks[0].task_id + ui.window._active_quick_run_task_id = owner + ui.window._batch_stop = StopControl() + ctl.request({'request_id': '1' * 32, 'capability': 'execute', + 'spec': {'operation': 'pause', 'task_ids': [ui.tasks[1].task_id]}}) + assert not ui.window._batch_stop.is_set() + assert view.lifecycle_results[-1]['status'] == 'rejected' + ctl.request({'request_id': '2' * 32, 'capability': 'execute', + 'spec': {'operation': 'pause', 'task_ids': [owner]}}) + 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() diff --git a/tests/v1_1/test_task_queue.py b/tests/v1_1/test_task_queue.py index 19c1990..38c025a 100644 --- a/tests/v1_1/test_task_queue.py +++ b/tests/v1_1/test_task_queue.py @@ -63,6 +63,13 @@ def test_tasks_execute_in_confirmed_order_and_finished_queue_does_not_repeat(tmp assert len(service.calls) == 4 +def test_changed_confirmed_plan_is_rejected_before_any_executor(tmp_path): + service = Service(tmp_path) + with pytest.raises(TaskCenterError, match='assistant_stale'): + execute_task_queue(service, ('A',), stop_event=Event(), expected_plan_hashes={'A': 'stale'}) + assert not service.calls + + def test_safe_failure_is_reported_and_next_task_runs(tmp_path): service = Service(tmp_path, {'A': TaskCenterError('quick_run_preflight', 'target absent')}) result = execute_task_queue(service, ('A', 'B'), stop_event=Event()) diff --git a/tools/accept_dsh_lifecycle.py b/tools/accept_dsh_lifecycle.py new file mode 100644 index 0000000..7fd8221 --- /dev/null +++ b/tools/accept_dsh_lifecycle.py @@ -0,0 +1,157 @@ +"""Real-model Qt/CDP lifecycle acceptance with an isolated, controlled executor.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import threading +import time +import traceback + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO / 'src')) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--port', type=int, default=9235) + parser.add_argument('--provider-config', type=Path, required=True) + args = parser.parse_args() + output = args.output.resolve(); output.mkdir(parents=True, exist_ok=True) + data = output / ('data-' + time.strftime('%Y%m%d-%H%M%S')) + (data / 'dsh').mkdir(parents=True) + for name in ('provider.json', 'provider-key.dpapi'): + shutil.copy2(args.provider_config / name, data / 'dsh' / name) + hashes = {} + for name in ('Board-A', 'Board-B', 'Board-C'): + project = output / 'projects' / name / 'board.prj' + project.parent.mkdir(parents=True, exist_ok=True) + project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf8') + hashes[str(project)] = hashlib.sha256(project.read_bytes()).hexdigest() + os.environ.pop('QT_QPA_PLATFORM', None) + os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = f'127.0.0.1:{args.port}' + from PySide6.QtCore import QTimer, Qt + from PySide6.QtTest import QTest + from PySide6.QtWidgets import QApplication, QDialogButtonBox + from dx_productivity.trial_task_center import application + from dx_productivity.trial_task_center.quick_run import QuickRunPreparer + from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow + from dx_productivity.trial_task_center.ui.dsh_task_lifecycle import DshLifecycleDialog + from dx_productivity.trial_task_center.ui.dsh_task_creation import DshTaskCreationDialog + + report = {'driver': 'Real provider + Qt QTest + Chromium CDP', 'checks': [], 'executor': 'controlled_no_match', 'realCadStarted': False} + state = {'child': None, 'phase': 'select', 'deadline': time.monotonic() + 900, 'calls': [], 'dialogs': set()} + release = threading.Event() + + def build(service): + def worker(command, timeout): + queue, job = Path(command[3]), command[-1] + state['calls'].append(job) + if len(state['calls']) == 1 and not release.wait(120): + raise TimeoutError('Conversation did not request safe pause') + with (queue / 'status.tsv').open('a', encoding='utf8') as stream: + stream.write(f'{job}\tno_match\tbatch_closed\tNo matching components\n') + return subprocess.CompletedProcess(command, 0, '', '') + service._supervised = False + service._quick_run_preparer = QuickRunPreparer(data, process_runner=worker, + cscript_resolver=lambda: Path('cscript.exe'), sheet_discoverer=lambda _path: (('MAIN', '1'),)) + tasks = service.create_project_tasks(output / 'projects', selected_paths=tuple(output / 'projects' / name / 'board.prj' for name in ('Board-A', 'Board-B'))) + service.add_rule(tasks[0].task_id, 'OLD123', 'NEW456') + service.add_rule(tasks[0].task_id, 'OLD222', 'NEW222') + window = TrialTaskCenterWindow(service); window.resize(1440, 900) + # Acceptance data stays inspectable after closing. + window.archive_on_close_check.setChecked(False) + def fail(error): + release.set() + report.update(status='failed', error=str(error), traceback=traceback.format_exc()) + child = state['child'] + if child and child.poll() is None: + child.terminate() + timer.stop() + window.close() + def tick(): + try: + if time.monotonic() > state['deadline']: + raise TimeoutError('Lifecycle desktop acceptance timed out') + if state['calls'] and window._batch_stop and window._batch_stop.is_set(): + release.set() + modal = QApplication.activeModalWidget() + if isinstance(modal, DshLifecycleDialog) and not modal.property('acceptanceClicked'): + modal.setProperty('acceptanceClicked', True) + state['dialogs'].add(id(modal)) + text = modal.preview.toPlainText() + modal.grab().save(str(output / f"native-confirm-{len(state['dialogs'])}.png")) + cancel = 'CANCEL_ME' in text + button = QDialogButtonBox.StandardButton.Cancel if cancel else QDialogButtonBox.StandardButton.Ok + report['checks'].append({'nativeDialog': modal.windowTitle(), 'clicked': 'cancel' if cancel else 'confirm', 'preview': text}) + QTest.mouseClick(modal.buttons.button(button), Qt.MouseButton.LeftButton) + if isinstance(modal, DshTaskCreationDialog): + if not modal.directory.text(): + QTest.keyClicks(modal.directory, str(output / 'projects/Board-C')) + QTest.mouseClick(modal.scan, Qt.MouseButton.LeftButton) + elif modal._worker is None and modal.projects.count() == 1: + modal.grab().save(str(output / 'native-copy-project-selection.png')) + QTest.mouseClick(modal.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton) + report['checks'].append('clicked real project scan and confirm for copied configuration') + if state['phase'] == 'select' and not window._task_query.busy and window.task_list.list.count() == 2: + item = window.task_list.list.item(0) + QTest.mouseClick(window.task_list.list.viewport(), Qt.MouseButton.LeftButton, pos=window.task_list.list.visualItemRect(item).center()) + state['phase'] = 'open' + elif state['phase'] == 'open' and window._context and not window._loading: + QTest.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton) + state['phase'] = 'ready' + elif state['phase'] == 'ready' and window._dsh_view._started: + state['child'] = subprocess.Popen(['node', str(REPO / 'tools/verify_dsh_lifecycle_ui.mjs'), str(output), str(args.port)], + cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0) + state['phase'] = 'web' + elif state['phase'] == 'web' and state['child'].poll() is not None: + stdout, stderr = state['child'].communicate() + if state['child'].returncode: + raise RuntimeError(stderr.decode('utf8', 'replace')) + report['web'] = json.loads((output / 'report.json').read_text(encoding='utf8')) + assert len(state['calls']) == 2, state['calls'] + stored = service._store.list_tasks() + original = next(t for t in stored if t.name == 'DSH管理验收任务') + assert original.note == '自然语言管理验收' and original.status.value == 'completed' + assert any(r.old_part_number == 'OLD123' and r.new_part_number == 'NEW789' for r in service.rules(original.task_id)) + from dx_productivity.trial_task_center.models import TaskStatus + archived = service.tasks(TaskStatus.DELETED) + assert len(archived) == 1 and archived[0].task_id != original.task_id + assert all(hashlib.sha256(Path(p).read_bytes()).hexdigest() == digest for p, digest in hashes.items()) + report['checks'].extend(['SQLite metadata and shared rules verified', 'two real queue items completed through controlled executor', + 'copy created a new bound task, archive preserved original task', 'all three source fixture hashes unchanged']) + QTest.mouseClick(window.task_center_navigation, Qt.MouseButton.LeftButton) + window.grab().save(str(output / 'task-center-after-lifecycle.png')) + QTest.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton) + window.grab().save(str(output / 'dsh-lifecycle-in-tool.png')) + report['status'] = 'passed' + timer.stop(); window.close() + except Exception as error: + fail(error) + timer = QTimer(window); timer.setInterval(150); timer.timeout.connect(tick); timer.start() + return window + application._load_window = lambda: build + code = application.main(['--data-root', str(data)]) + report['calls'] = state['calls'] + report['data'] = str(data) + audit = data / 'dsh/harness-home/task-tool-audit.jsonl' + report['modelToolCalls'] = [json.loads(line) for line in audit.read_text(encoding='utf8').splitlines()] if audit.is_file() else [] + log = data / 'logs/application.log' + text = log.read_text(encoding='utf8') if log.is_file() else '' + report['cleanShutdown'] = 'application_clean_shutdown exit_code=0' in text + report['unexpectedUiErrors'] = 'uncaught_main_thread' in text or 'operation=ui message=' in text + (output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8') + print(json.dumps({'status': report.get('status'), 'error': report.get('error'), 'checks': len(report['checks']), + 'toolCalls': len(report['modelToolCalls']), 'cleanShutdown': report['cleanShutdown'], 'output': str(output)}, ensure_ascii=True)) + return 0 if not code and report.get('status') == 'passed' and report['cleanShutdown'] and not report['unexpectedUiErrors'] else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/verify_dsh_auto_runtime.mjs b/tools/verify_dsh_auto_runtime.mjs index 5189817..8a278c4 100644 --- a/tools/verify_dsh_auto_runtime.mjs +++ b/tools/verify_dsh_auto_runtime.mjs @@ -19,7 +19,7 @@ const started=new Promise(resolve=>{resolveStarted=resolve;}); const result=new Promise((resolve,reject)=>{resolveResult=resolve;rejectResult=reject;}); process.stdout.write=function(chunk,...args){ const line=String(chunk); - if(line.startsWith('DX_DSH_CREATE_REQUEST '))creationBodyRan=true; + if(line.startsWith('DX_DSH_CREATE_REQUEST ')||line.startsWith('DX_DSH_LIFECYCLE_REQUEST '))creationBodyRan=true; if(line.startsWith('DX_DSH_DIAGNOSIS ')) { const value=JSON.parse(line.slice('DX_DSH_DIAGNOSIS '.length)); if(value.status==='started')resolveStarted(value.session_id); @@ -42,6 +42,16 @@ try{ arguments:{name:'Must never open a dialog'},agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)}); assert.equal(denial.isError,true); assert.equal(creationBodyRan,false,'Automatic incident must be denied before desktop request emission'); + for(const [name,args] of [ + ['dx_task_catalog',{}],['dx_task_preflight',{task_ids:['auto-failure-fixture']}], + ['dx_task_manage',{operation:'archive',task_id:'auto-failure-fixture'}], + ['dx_task_execute',{operation:'start',task_ids:['auto-failure-fixture']}], + ]){ + const result=await ctx.tools.execute({callId:'automatic-denial-'+name,name,arguments:args, + agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)}); + assert.equal(result.isError,true); + assert.equal(creationBodyRan,false); + } }finally{ if(previousParent===undefined)delete process.env.DX_DSH_PARENT_PIPE;else process.env.DX_DSH_PARENT_PIPE=previousParent; } diff --git a/tools/verify_dsh_lifecycle_ui.mjs b/tools/verify_dsh_lifecycle_ui.mjs new file mode 100644 index 0000000..1d9aadd --- /dev/null +++ b/tools/verify_dsh_lifecycle_ui.mjs @@ -0,0 +1,84 @@ +/** Natural-language lifecycle intents through the real embedded official UI. */ +import assert from 'node:assert/strict'; +import {writeFile} from 'node:fs/promises'; +import path from 'node:path'; +import {connect} from './dsh_cdp.mjs'; + +const output=path.resolve(process.argv[2]); +const c=await connect(Number(process.argv[3]||9235)); +const report={checks:[],prompts:[],explicitToolNamesInPrompts:false,executor:'controlled_no_match'}; +const context=()=>c.evaluate(`fetch('/dx/context').then(r=>r.json())`); +async function wait(test,timeout=110000){ + const end=Date.now()+timeout; + while(Date.now()setTimeout(r,160));} + throw Error('Lifecycle UI condition timed out'); +} +async function idle(){await wait(()=>c.evaluate(`![...document.querySelectorAll('button[aria-label="停止生成"]')].some(e=>e.getBoundingClientRect().width>0)`));} +async function send(prompt){ + report.prompts.push(prompt); + await writeFile(path.join(output,'progress.json'),JSON.stringify(report,null,2)); + // A newly mounted Lexical composer can replace its first DOM node while the + // new-session transition finishes. Wait for real typed text before sending. + for(let attempt=0;attempt<5;attempt++){ + await c.click(`document.querySelector('[contenteditable="true"]')`); + await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'a',code:'KeyA',modifiers:2}); + await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'a',code:'KeyA',modifiers:2}); + await c.call('Input.insertText',{text:prompt}); + await new Promise(r=>setTimeout(r,350)); + if(await c.evaluate(`document.querySelector('[contenteditable="true"]')?.textContent.includes(${JSON.stringify(prompt)})`))break; + } + await wait(()=>c.evaluate(`(()=>{const e=document.querySelector('button[aria-label="发送消息"]');return e&&!e.disabled&&e.getAttribute('aria-disabled')!=='true'&&document.querySelector('[contenteditable="true"]')?.textContent.includes(${JSON.stringify(prompt)});})()`)); + await c.click(`document.querySelector('button[aria-label="发送消息"]')`); + await wait(()=>c.evaluate(`!document.querySelector('[contenteditable="true"]')?.textContent.includes(${JSON.stringify(prompt)})&&document.body.innerText.includes(${JSON.stringify(prompt)})`)); +} +async function state(status){await wait(async()=>{const d=await context();return d.lifecycle?.result?.status===status;});return (await context()).lifecycle.result;} +try{ + await wait(()=>c.evaluate(`!!document.querySelector('[contenteditable="true"]')`),45000); + await send('先列出任务,找到工程目录 Board-A 对应的任务并切换到它。将这个任务改名为“DSH管理验收任务”,备注设为“自然语言管理验收”,已有旧料号 OLD123 对应的新料号改成 NEW789,其余配置保留。先不要执行。'); + const changed=await state('updated');await idle(); + assert.equal(changed.task_ids.length,2); + report.taskId=changed.task_id; + report.checks.push('natural-language lookup, select and shared-rule edit committed after native clicks'); + await send('检查 DSH管理验收任务 现在能否运行,列出执行前的阻断原因。只检查,不要开始运行。'); + const checked=await state('preflight');await idle(); + assert.equal(checked.ready,true);assert.equal(checked.cad_connection_checked,false); + report.checks.push('preflight returned real readiness without claiming CAD connectivity'); + await send('现在执行 DSH管理验收任务,只运行这一个任务。请通过主工具确认范围,结束后告诉我实际保存、失败和未命中的数量。'); + await wait(async()=>{const d=await context();return d.lifecycle?.status==='executing';}); + await c.click(`document.querySelectorAll('button[aria-label="新建会话"]')[1]`); + await wait(()=>c.evaluate(`!!document.querySelector('svg[class*="fish"]')&&!document.querySelector('[data-chat-group-part="response"]')&&!!document.querySelector('[contenteditable="true"]')`)); + await new Promise(r=>setTimeout(r,600)); + await send('请安全暂停当前正在执行的任务,等待当前项收尾,不要强制结束。'); + const paused=await state('paused');await idle(); + assert.equal(paused.tasks[0].no_match_items,1);assert.equal(paused.tasks[0].saved_items,0); + report.checks.push('second live conversation requested real StopControl pause; first execution returned actual paused evidence'); + await send('继续执行 DSH管理验收任务 尚未完成的部分,保留已经完成的结果。通过主工具确认后执行,并告诉我真实数量。'); + const completed=await state('completed');await idle(); + assert.equal(completed.tasks[0].no_match_items,2);assert.equal(completed.tasks[0].saved_items,0); + assert.equal(completed.tasks[0].failed_items,0); + report.checks.push('continue executed remaining item once and reported no-match rather than replacement success'); + await c.screenshot(path.join(output,'dsh-execution-results.png')); + await send('复制 DSH管理验收任务 的规则、备注和 Value 配置,创建一个副本任务。新工程目录我来选,不复制执行结果,也不要开始替换。'); + const copied=await state('created');await idle(); + assert.equal(copied.created_count,1);assert.ok(!copied.task_ids.includes(report.taskId)); + report.copyId=copied.task_ids[0]; + report.checks.push('copy used actual native project selection and returned new committed task ID'); + await send('把刚才复制出来的副本任务移入回收站,保留证据,不要归档原来的 DSH管理验收任务。'); + const archived=await state('archived');await idle(); + assert.equal(archived.task_id,report.copyId); + report.checks.push('archive targeted only copied task and preserved source task'); + await send('将原来的 DSH管理验收任务 名称改为 CANCEL_ME,我会在确认窗口里决定。不要执行工程。'); + await state('cancelled');await idle(); + report.checks.push('real Qt cancellation reached model without applying task mutation'); + await c.screenshot(path.join(output,'dsh-lifecycle-complete.png')); + await c.click(`document.querySelector('[contenteditable="true"]')`); + await c.call('Input.insertText',{text:'请分析当前任务接下来如何配置。'}); + report.status='passed'; +}catch(error){ + report.status='failed';report.error=error.message; + await c.screenshot(path.join(output,'failure.png')).catch(()=>{}); + throw error; +}finally{ + await writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2)); + c.close(); +} diff --git a/tools/verify_dsh_runtime.mjs b/tools/verify_dsh_runtime.mjs index 7447c68..5f9172d 100644 --- a/tools/verify_dsh_runtime.mjs +++ b/tools/verify_dsh_runtime.mjs @@ -18,7 +18,7 @@ const report={}; try { const schemas=ctx.tools.schemas(); report.tools=schemas.map(x=>x.name); - assert.deepEqual(report.tools,['dx_task_snapshot','dx_task_create']); + assert.deepEqual(report.tools,['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute']); const presets=await ctx.agentPresets.list(); report.presets=presets.map(x=>x.id); assert.deepEqual(report.presets,['dx-task']); @@ -32,6 +32,15 @@ try { const desktopOnly=await ctx.tools.execute({callId:'verify-desktop-only',name:'dx_task_create',arguments:{name:'CLI must not mutate'},signal:new AbortController().signal}); assert.equal(desktopOnly.isError,true); report.creationRequiresDesktopConfirmation=true; + for(const [name,args] of [ + ['dx_task_catalog',{}],['dx_task_preflight',{task_ids:['fixture']}], + ['dx_task_manage',{operation:'archive',task_id:'fixture'}], + ['dx_task_execute',{operation:'start',task_ids:['fixture']}], + ]){ + const result=await ctx.tools.execute({callId:'desktop-only-'+name,name,arguments:args,signal:AbortSignal.timeout(2000)}); + assert.equal(result.isError,true,name+' requires parent desktop'); + } + report.lifecycleRequiresDesktop=true; const require=createRequire(path.join(repo,'integration/dsh/package.json')); const {defineTool}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-tools')).href); let bodyRan=false;