feat: create task-center project tasks from native DSH conversations

This commit is contained in:
阿白叔 committed 2026-10-30 14:42:50 +08:00
1 parent e9b77186dc
commit ef40f339cd
23 files changed
+773 -31

No files matched your search

+58 -9
View File
@@ -9,6 +9,8 @@ import subprocess
import sys
import time
import shutil
import hashlib
import traceback
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
@@ -23,10 +25,19 @@ def main():
parser.add_argument('--incident', action='store_true', help='Inject a read-only controlled failure and verify automatic diagnosis and Git escalation')
parser.add_argument('--outbox-only', action='store_true', help='Verify failed publication stays in local outbox without creating another real issue')
parser.add_argument('--without-git', action='store_true', help='Simulate a client with no Git credentials or executable')
parser.add_argument('--create-task', action='store_true', help='Create real project tasks from a live native model conversation')
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'))
project_root = output / 'source-projects'
source_hashes = {}
if args.create_task:
for name in ('Board-A', 'Board-B'):
path = project_root / name / 'board.prj'
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf8')
source_hashes[str(path)] = hashlib.sha256(path.read_bytes()).hexdigest()
if args.provider_config:
(data / 'dsh').mkdir(parents=True, exist_ok=True)
for name in ('provider.json', 'provider-key.dpapi'):
@@ -45,15 +56,18 @@ def main():
os.environ.pop('QT_QPA_PLATFORM', None)
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtWidgets import QApplication, QMessageBox, QDialogButtonBox
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
from dx_productivity.trial_task_center.ui.dsh_task_creation import DshTaskCreationDialog
report = {'driver': 'Qt QTest mouse clicks + Chromium CDP Input events', 'checks': []}
state = {'phase': 'select', 'child': None, 'deadline': time.monotonic() + (420 if args.incident else 240 if args.live_model else 150)}
state = {'phase': 'select', 'child': None, 'creation_step': 'input',
'deadline': time.monotonic() + (420 if args.incident else 300 if args.create_task else 240 if args.live_model else 150)}
def build_window(service):
service.create_task('DSH接入验收任务')
if not args.create_task:
service.create_task('DSH接入验收任务')
window = TrialTaskCenterWindow(service)
window.resize(1380, 860)
@@ -80,11 +94,29 @@ def main():
if time.monotonic() > state['deadline']:
raise TimeoutError('Native desktop acceptance timed out')
modal = QApplication.activeModalWidget()
if args.create_task and isinstance(modal, DshTaskCreationDialog):
if state['creation_step'] == 'input':
assert modal.name_edit.text() == 'DSH对话换料验收'
assert modal.spec['rules'][0]['old_part_number'] == 'OLD123'
assert modal.spec['rules'][0]['new_part_number'] == 'NEW456'
QTest.keyClicks(modal.directory, str(project_root))
QTest.mouseClick(modal.scan, Qt.MouseButton.LeftButton)
report['checks'].append('typed source directory and clicked native project scan for model-authored draft')
state['creation_step'] = 'reading'
elif state['creation_step'] == 'reading' and modal._worker is None and modal.projects.count() == 2:
QTest.mouseClick(modal.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
report['checks'].append('clicked native confirm to create both selected project tasks')
state['creation_step'] = 'confirmed'
if isinstance(modal, QMessageBox) and modal.windowTitle().startswith('DSH助手'):
button = modal.button(QMessageBox.StandardButton.No)
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
report['checks'].append('clicked No in the actual Qt confirmation dialog')
if state['phase'] == 'select' and window.task_list.list.count() and not window._task_query.busy:
if state['phase'] == 'select' and args.create_task and not window._task_query.busy:
assert window.task_list.list.count() == 0
click_navigation(window.dsh_action)
state['phase'] = 'ready'
report['checks'].append('opened native assistant from an empty task center')
elif state['phase'] == 'select' and window.task_list.list.count() and not window._task_query.busy:
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())
@@ -102,7 +134,7 @@ def main():
report['checks'].append('clicked task row and opened DSH with one click on the right navigation item')
state['phase'] = 'ready'
elif state['phase'] == 'ready' and window._dsh_view is not None and window._dsh_view._started:
script = 'verify_dsh_incident_ui.mjs' if args.incident else 'verify_dsh_native_ui.mjs'
script = 'verify_dsh_task_creation_ui.mjs' if args.create_task else 'verify_dsh_incident_ui.mjs' if args.incident else 'verify_dsh_native_ui.mjs'
command = ['node', str(REPO / 'tools' / script), str(output), str(args.port), '--confirm-cancel']
if args.live_model:
command.append('--live-model')
@@ -122,7 +154,7 @@ def main():
assert window.content_stack.currentWidget() is window._dsh_view
report['checks'].append('clicked left navigation for task center and right navigation for the same native page')
state['phase'] = 'check-preserved'
def preserved(text):
def validate_preserved(text):
if '请分析当前任务' not in (text or ''):
failed(AssertionError('Composer draft was lost when switching navigation items'))
return
@@ -139,11 +171,27 @@ def main():
report['incident'] = row
report['checks'].append('real native automatic diagnosis and reflection, evidence and ' +
('retryable local issue outbox' if args.outbox_only else 'Git issue attachment') + ' completed without CAD mutations')
if args.create_task:
tasks = service._store.list_tasks()
assert len(tasks) == 2 and window.task_list.list.count() == 2
assert all(task.primary_project_id and task.status.value == 'draft' and task.copy_part_number_to_value for task in tasks)
assert all([(r.old_part_number, r.new_part_number) for r in service._store.list_rules(task.task_id)] == [('OLD123', 'NEW456')] for task in tasks)
assert all(hashlib.sha256(Path(path).read_bytes()).hexdigest() == digest for path, digest in source_hashes.items())
assert not list(data.rglob('command.tsv'))
report['createdTasks'] = [{'task_id': t.task_id, 'name': t.name} for t in tasks]
report['sourceProjectHashesUnchanged'] = True
report['checks'].append('real SQLite tasks, names, rules, Value policy and project bindings verified with unchanged source files')
window.grab().save(str(output / 'dsh-in-tool.png'))
report['status'] = 'passed'
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
timer.stop()
window.close()
def preserved(text):
try:
validate_preserved(text)
except Exception as error:
report['callbackTraceback'] = traceback.format_exc()
failed(error)
window._dsh_view.web.page().runJavaScript("document.querySelector('[contenteditable=true]')?.textContent", preserved)
except Exception as error:
failed(error)
@@ -163,14 +211,15 @@ def main():
report['cleanShutdown'] = 'application_clean_shutdown exit_code=0' in log
report['uncaughtErrors'] = 'uncaught_main_thread' in log
report['unexpectedUiErrors'] = 'operation=ui message=' in log
if args.live_model or args.incident:
if args.live_model or args.incident or args.create_task:
audit_file = data / 'dsh/harness-home/task-tool-audit.jsonl'
audit = [json.loads(line) for line in audit_file.read_text(encoding='utf8').splitlines()] if audit_file.is_file() else []
report['modelToolCalls'] = audit
report['modelToolSucceeded'] = any(row['name'] == 'dx_task_snapshot' and row['is_error'] is False for row in audit)
expected_tool = 'dx_task_create' if args.create_task else 'dx_task_snapshot'
report['modelToolSucceeded'] = any(row['name'] == expected_tool and row['is_error'] is False for row in audit)
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
print(json.dumps(report, ensure_ascii=True))
return 0 if report['cleanShutdown'] and not report['uncaughtErrors'] and not report['unexpectedUiErrors'] and (not (args.live_model or args.incident) or report['modelToolSucceeded']) else 1
return 0 if report['cleanShutdown'] and not report['uncaughtErrors'] and not report['unexpectedUiErrors'] and (not (args.live_model or args.incident or args.create_task) or report['modelToolSucceeded']) else 1
if __name__ == '__main__':
+18 -3
View File
@@ -13,13 +13,17 @@ const snapshot={task_id:'auto-failure-fixture',revision:'incident',status:'faile
issue:'受控诊断验收:执行前 worker 失败,没有工程写入。',rules_count:1,progress:{failed_items:1,total:1,completed:0}};
const {ctx,shutdown}=await bootRuntime({announce:false});
const original=process.stdout.write.bind(process.stdout);
let resolveResult,rejectResult;
let resolveResult,rejectResult,resolveStarted;
let creationBodyRan=false;
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_DIAGNOSIS ')) {
const value=JSON.parse(line.slice('DX_DSH_DIAGNOSIS '.length));
if(value.status==='completed')resolveResult(value);
if(value.status==='started')resolveStarted(value.session_id);
else if(value.status==='completed')resolveResult(value);
else if(value.status==='failed')rejectResult(Error(value.error));
return true;
}
@@ -30,6 +34,17 @@ try{
timer=setTimeout(()=>rejectResult(Error('native_auto_test_timeout')),135000);
ctx.emit('dx/diagnose-request',{request_id:'cli-auto-request',incident_id:'0123456789abcdef01234567',
phase:'diagnose',snapshot,evidence:JSON.stringify(snapshot)});
const sessionId=await Promise.race([started,result.then(()=>{throw Error('Missing started event');})]);
const previousParent=process.env.DX_DSH_PARENT_PIPE;
process.env.DX_DSH_PARENT_PIPE='1';
try{
const denial=await ctx.tools.execute({callId:'automatic-creation-denial',name:'dx_task_create',
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');
}finally{
if(previousParent===undefined)delete process.env.DX_DSH_PARENT_PIPE;else process.env.DX_DSH_PARENT_PIPE=previousParent;
}
const value=await result;
assert.ok(value.reply.length>20);
const tools=value.transcript.filter(e=>e.type==='tool/result');
@@ -38,7 +53,7 @@ try{
assert.ok(text.includes('auto-failure-fixture'));
assert.ok(!text.includes('different-current-task'));
const report={status:'passed',session_id:value.session_id,reply:value.reply,
incidentBoundSnapshot:true,toolResults:tools};
incidentBoundSnapshot:true,automaticTaskCreationDenied:true,toolResults:tools};
await writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2));
original(JSON.stringify(report)+'\n');
}finally{
+4 -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']);
assert.deepEqual(report.tools,['dx_task_snapshot','dx_task_create']);
const presets=await ctx.agentPresets.list();
report.presets=presets.map(x=>x.id);
assert.deepEqual(report.presets,['dx-task']);
@@ -29,6 +29,9 @@ try {
const snapshot=await ctx.tools.execute({callId:'verify-read',name:'dx_task_snapshot',arguments:{},signal:new AbortController().signal});
assert.equal(snapshot.isError,false,JSON.stringify(snapshot));
report.snapshotRead=true;
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;
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;
+44
View File
@@ -0,0 +1,44 @@
/** Use real native conversation input to create tasks through the Qt confirmation. */
import assert from 'node:assert/strict';
import {writeFile,mkdir} from 'node:fs/promises';
import path from 'node:path';
import {connect} from './dsh_cdp.mjs';
const output=path.resolve(process.argv[2]);
await mkdir(output,{recursive:true});
const c=await connect(Number(process.argv[3]||9227));
const report={driver:'Qt Chromium CDP Input events',checks:[]};
async function wait(expression,timeout=30000){
const end=Date.now()+timeout;
while(Date.now()<end){if(await c.evaluate(expression))return;await new Promise(resolve=>setTimeout(resolve,150));}
throw Error('Task creation UI condition timed out: '+expression);
}
try{
await wait(`!!document.querySelector('[contenteditable="true"]')`,50000);
await c.click(`document.querySelector('[contenteditable="true"]')`);
await c.call('Input.insertText',{text:'请现在调用 dx_task_create 创建名为“DSH对话换料验收”的工程任务,备注“真实对话验收”,替换规则 OLD123 → NEW456,把料号复制到 Value。工程目录我会在本机原生窗口中选择。仅创建任务,不采集、不替换。完成后告诉我实际创建数量和真实 task_id。'});
await c.click(`document.querySelector('button[aria-label="发送消息"]')`);
report.checks.push('typed and sent natural-language task creation request through official composer');
await wait(`fetch('/dx/context').then(r=>r.json()).then(d=>d.creation?.result?.status==='created')`,180000);
const context=await c.evaluate(`fetch('/dx/context').then(r=>r.json())`);
assert.equal(context.creation.result.created_count,2);
assert.equal(context.creation.result.task_ids.length,2);
assert.equal(context.creation.result.cad_execution_started,false);
await wait(`![...document.querySelectorAll('button[aria-label="停止生成"]')].some(e=>e.getBoundingClientRect().width>0)`,100000);
const reply=await c.evaluate(`[...document.querySelectorAll('[data-chat-group-part="response"]')].map(e=>e.innerText).join(String.fromCharCode(10))`);
assert.ok(context.creation.result.task_ids.every(id=>reply.includes(id)),'The model must report the actual committed task IDs');
report.checks.push('native model tool completed after Qt confirmation and reported both committed task IDs');
report.created=context.creation.result;
report.reply=reply;
report.liveTurnCompleted=true;
await c.screenshot(path.join(output,'dsh-created-tasks.png'));
await c.click(`document.querySelector('[contenteditable="true"]')`);
await c.call('Input.insertText',{text:'请分析当前任务接下来如何配置。'});
report.status='passed';
await writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2));
console.log(JSON.stringify(report));
}catch(error){
await c.screenshot(path.join(output,'failure.png')).catch(()=>{});
await writeFile(path.join(output,'report.json'),JSON.stringify({...report,status:'failed',error:error.message},null,2));
throw error;
}finally{c.close();}