feat: add confirmed DSH task management and execution control

This commit is contained in:
阿白叔 committed 2026-10-30 15:45:45 +08:00
1 parent be382a117d
commit f861a3d386
25 files changed
+1190 -25

No files matched your search

+157
View File
@@ -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())
+11 -1
View File
@@ -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;
}
+84
View File
@@ -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()<end){if(await test())return;await new Promise(r=>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();
}
+10 -1
View File
@@ -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;