feat(dsh): add durable supervision, scheduling and operations dock
This commit is contained in:
1 parent
f861a3d386
commit
736b582bc1
46 files changed
+4122
-93
No files matched your search
@@ -0,0 +1,256 @@
|
||||
"""Real Qt/CDP operations acceptance across two clean application processes."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
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 write(path, value):
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
|
||||
def seed(service, output, data):
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
|
||||
paths, hashes, ids = {}, {}, {}
|
||||
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')
|
||||
paths[name] = project
|
||||
hashes[str(project)] = hashlib.sha256(project.read_bytes()).hexdigest()
|
||||
task = service.create_project_tasks(project.parent, selected_paths=(project,))[0]
|
||||
service.update_task(task.task_id, name=name, note='Isolated operations acceptance fixture')
|
||||
ids[name] = task.task_id
|
||||
service.add_rule(ids['Board-A'], 'OLD123', 'NEW456')
|
||||
service.add_rule(ids['Board-A'], 'OLD222', 'NEW222')
|
||||
service.add_rule(ids['Board-C'], 'SCHED_OLD', 'SCHED_NEW')
|
||||
targets = tuple(ComponentTarget(paths['Board-B'], 'MAIN', '1', f'accept-uid-{i}', f'R{i}', 'EXACT_OLD', f'{i}k') for i in (1, 2))
|
||||
service._store.record_target_inventory(ids['Board-B'], targets)
|
||||
service._store.replace_target_plan(ids['Board-B'], (
|
||||
TargetPlanRow(targets[0], True, 'EXACT_NEW', target_cell='CELL-X'),
|
||||
TargetPlanRow(targets[1], True, 'EXACT_NEW', True, 'CUSTOM-2', False)))
|
||||
for identity, verified in (('a' * 24, True), ('b' * 24, False)):
|
||||
directory = data / 'dsh' / 'incidents' / identity
|
||||
directory.mkdir(parents=True)
|
||||
write(directory / 'incident.json', {'incident_id': identity, 'task_id': ids['Board-A'],
|
||||
'issue_code': 'acceptance_verified' if verified else 'acceptance_suggestion',
|
||||
'message': 'Isolated persisted verification fixture' if verified else 'Evidence-less suggestion fixture',
|
||||
'status': 'resolved' if verified else 'analyzed',
|
||||
'analyses': [{'phase': 'diagnosis', 'reply': 'Controlled fixture analysis, no execution authority.'}]})
|
||||
if verified:
|
||||
write(directory / 'snapshot.json', {'fixture': True, 'task_id': ids['Board-A']})
|
||||
write(directory / 'verification.json', {'queue_complete': True, 'failed_items': 0,
|
||||
'interrupted': False, 'paused': False, 'saved_items': 0, 'no_match_items': 1})
|
||||
manifest = {'tasks': ids, 'sourceHashes': hashes, 'data': str(data)}
|
||||
write(output / 'manifest.json', manifest)
|
||||
return manifest
|
||||
|
||||
|
||||
def phase(args):
|
||||
output, data = args.output.resolve(), args.data.resolve()
|
||||
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, QPoint
|
||||
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_operations import DshScheduleDialog
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
report = {'phase': args.phase, 'executor': 'controlled_no_match', 'realCadStarted': False, 'checks': [], 'dialogs': []}
|
||||
state = {'child': None, 'stage': 'opening', 'deadline': time.monotonic() + 180, 'selection': None, 'scheduleDialogs': 0}
|
||||
selection_path = output / 'native-selection.json'
|
||||
if selection_path.is_file():
|
||||
prior_nonce = json.loads(selection_path.read_text(encoding='utf8'))['nonce']
|
||||
state.update(selection=prior_nonce, selection_ready=prior_nonce)
|
||||
release = threading.Event()
|
||||
calls_path = output / 'controlled-calls.jsonl'
|
||||
|
||||
def build(service):
|
||||
def worker(command, timeout):
|
||||
queue, job = Path(command[3]), command[-1]
|
||||
with calls_path.open('a', encoding='utf8') as stream:
|
||||
stream.write(json.dumps({'phase': args.phase, 'job': job, 'queue': str(queue)}) + '\n')
|
||||
if args.phase == 'initial' and not release.wait(90):
|
||||
raise TimeoutError('The real running-tab safe pause was not received')
|
||||
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'),))
|
||||
manifest = seed(service, output, data) if args.phase == 'initial' else json.loads((output / 'manifest.json').read_text(encoding='utf8'))
|
||||
class AcceptanceWindow(TrialTaskCenterWindow):
|
||||
def closeEvent(self, event):
|
||||
report.setdefault('closeEvents', []).append({'spontaneous': event.spontaneous(),
|
||||
'stage': state['stage'], 'report_status': report.get('status'),
|
||||
'pending': self._close_pending, 'worker_count': len(self._workers)})
|
||||
super().closeEvent(event)
|
||||
window = AcceptanceWindow(service); window.resize(1500, 950)
|
||||
window.setWindowTitle('DSH 自动验收(进行中) · ' + args.phase)
|
||||
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 select(task_id):
|
||||
QTest.mouseClick(window.task_center_navigation, Qt.MouseButton.LeftButton)
|
||||
for index in range(window.task_list.list.count()):
|
||||
item = window.task_list.list.item(index)
|
||||
if item.data(Qt.ItemDataRole.UserRole) == task_id:
|
||||
window.task_list.list.scrollToItem(item)
|
||||
QTest.mouseClick(window.task_list.list.viewport(), Qt.MouseButton.LeftButton,
|
||||
pos=window.task_list.list.visualItemRect(item).center())
|
||||
return
|
||||
raise AssertionError('Requested fixture task is absent from native list')
|
||||
|
||||
def tick():
|
||||
try:
|
||||
if time.monotonic() > state['deadline']:
|
||||
view = window._dsh_view
|
||||
raise TimeoutError(f"Operations acceptance {state['stage']} timed out; runtime_error={getattr(view, 'last_error', None)}; status={view.status.text() if view else 'not-created'}")
|
||||
if 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)
|
||||
text = modal.preview.toPlainText()
|
||||
cancel = False
|
||||
if args.phase == 'initial' and modal.windowTitle().endswith('执行所选任务'):
|
||||
state['executionConfirmations'] = state.get('executionConfirmations', 0) + 1
|
||||
# A safe pause is a user decision. Exercise cancellation
|
||||
# if a model proposes continuation before a new request.
|
||||
cancel = state['executionConfirmations'] > 1
|
||||
if isinstance(modal, DshScheduleDialog):
|
||||
state['scheduleDialogs'] += 1
|
||||
cancel = state['scheduleDialogs'] == 1
|
||||
assert 'SCHED_OLD' in text and 'SCHED_NEW' in text, 'Future-run confirmation omitted engineering impact'
|
||||
if not cancel:
|
||||
modal.time_edit.selectAll(); QTest.keyClicks(modal.time_edit, (datetime.now(timezone.utc)-timedelta(seconds=2)).isoformat(timespec='seconds'))
|
||||
if not modal.auto_start.isChecked():
|
||||
QTest.mouseClick(modal.auto_start, Qt.MouseButton.LeftButton,
|
||||
pos=QPoint(8, modal.auto_start.height() // 2))
|
||||
assert modal.auto_start.isChecked(), 'Actual checkbox click must grant future-run authorization'
|
||||
report['dialogs'].append({'title': modal.windowTitle(), 'preview': text, 'action': 'cancel' if cancel else 'confirm'})
|
||||
modal.grab().save(str(output / f"{args.phase}-native-{len(report['dialogs'])}.png"))
|
||||
QTest.mouseClick(modal.buttons.button(QDialogButtonBox.StandardButton.Cancel if cancel else QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
|
||||
command_path = output / 'native-selection.json'
|
||||
if state['stage'] == 'web' and command_path.exists():
|
||||
command = json.loads(command_path.read_text(encoding='utf8'))
|
||||
if command['nonce'] != state['selection'] and not window._workers:
|
||||
select(command['task_id']); state['selection'] = command['nonce']
|
||||
if state['selection'] == command['nonce'] and state.get('selection_ready') != command['nonce'] and window._context and window._context.task.task_id == command['task_id'] and not window._loading:
|
||||
QTest.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton)
|
||||
write(output / 'native-selection-done.json', command)
|
||||
state['selection_ready'] = command['nonce']
|
||||
if state['stage'] == 'opening' and not window._task_query.busy and window.task_list.list.count() == 3:
|
||||
select(manifest['tasks']['Board-A']); state['stage'] = 'selected'
|
||||
elif state['stage'] == 'selected' and window._context and not window._loading:
|
||||
QTest.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton); state['stage'] = 'runtime'
|
||||
elif state['stage'] == 'runtime' and window._dsh_view._started:
|
||||
state['child'] = subprocess.Popen(['node', str(REPO / 'tools/verify_dsh_operations_ui.mjs'), str(output), str(args.port), args.phase],
|
||||
cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
|
||||
state.update(stage='web', deadline=time.monotonic()+360)
|
||||
elif state['stage'] == '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 / f'{args.phase}-web.json').read_text(encoding='utf8'))
|
||||
rows = RunJournal(data).list_runs()
|
||||
original = next(row for row in rows if row['task_ids'] == [manifest['tasks']['Board-A']])
|
||||
assert original['status'] == ('paused' if args.phase == 'initial' else 'completed'), original
|
||||
if args.phase == 'initial': write(output / 'paused-run.json', original)
|
||||
else:
|
||||
prior = json.loads((output / 'paused-run.json').read_text(encoding='utf8'))
|
||||
assert original['run_id'] == prior['run_id'] and original['queue_id'] == prior['queue_id']
|
||||
assert original['result']['tasks'][0]['no_match_items'] == 2
|
||||
assert all(hashlib.sha256(Path(path).read_bytes()).hexdigest() == digest for path, digest in manifest['sourceHashes'].items())
|
||||
report.update(status='passed', runs=rows)
|
||||
window.grab().save(str(output / f'{args.phase}-desktop.png'))
|
||||
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)])
|
||||
if 'status' not in report:
|
||||
report.update(status='failed', error='application_closed_before_acceptance_completed', stage=state['stage'])
|
||||
text = (data / 'logs/application.log').read_text(encoding='utf8')
|
||||
report['cleanShutdown'] = 'application_clean_shutdown exit_code=0' in text
|
||||
report['unexpectedUiErrors'] = 'uncaught_main_thread' in text or 'operation=ui message=' in text
|
||||
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 []
|
||||
write(output / f'{args.phase}-desktop.json', report)
|
||||
print(json.dumps({'phase': args.phase, 'status': report.get('status'), 'error': report.get('error'), 'cleanShutdown': report['cleanShutdown']}, ensure_ascii=True))
|
||||
return int(bool(code or report.get('status') != 'passed' or not report['cleanShutdown'] or report['unexpectedUiErrors']))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--provider-config', type=Path)
|
||||
parser.add_argument('--port', type=int, default=9237)
|
||||
parser.add_argument('--phase', choices=('initial', 'resume'))
|
||||
parser.add_argument('--data', type=Path)
|
||||
parser.add_argument('--ticket-incident', type=Path, help='Existing incident directory to copy for read-only ticket synchronization')
|
||||
args = parser.parse_args()
|
||||
if args.phase: return phase(args)
|
||||
output = args.output.resolve() / time.strftime('%Y%m%d-%H%M%S')
|
||||
output.mkdir(parents=True)
|
||||
data = output / 'data'; (data / 'dsh').mkdir(parents=True)
|
||||
if not args.provider_config: parser.error('--provider-config is required for the real provider acceptance')
|
||||
for name in ('provider.json', 'provider-key.dpapi'):
|
||||
shutil.copy2(args.provider_config / name, data / 'dsh' / name)
|
||||
for name in ('issue-config.json', 'issue-key.dpapi'):
|
||||
if (args.provider_config / name).is_file(): shutil.copy2(args.provider_config / name, data / 'dsh' / name)
|
||||
# Copy one existing binding only; no remote issue or comment is created.
|
||||
for source in sorted((args.provider_config / 'incidents').glob('*/incident.json')):
|
||||
value = json.loads(source.read_text(encoding='utf8'))
|
||||
if value.get('ticket', {}).get('number') and len(source.parent.name) == 24:
|
||||
destination = data / 'dsh/incidents' / source.parent.name
|
||||
destination.mkdir(parents=True); shutil.copy2(source, destination / 'incident.json'); break
|
||||
if args.ticket_incident:
|
||||
source = args.ticket_incident / 'incident.json'
|
||||
value = json.loads(source.read_text(encoding='utf8'))
|
||||
if not value.get('ticket', {}).get('number') or value.get('incident_id') != args.ticket_incident.name:
|
||||
parser.error('--ticket-incident must contain an existing bound ticket')
|
||||
destination = data / 'dsh/incidents' / args.ticket_incident.name
|
||||
destination.mkdir(parents=True, exist_ok=True); shutil.copy2(source, destination / 'incident.json')
|
||||
for item in ('initial', 'resume'):
|
||||
result = subprocess.run([sys.executable, '-X', 'utf8', str(Path(__file__)), '--output', str(output), '--data', str(data), '--port', str(args.port), '--phase', item], cwd=REPO)
|
||||
if result.returncode:
|
||||
print(json.dumps({'status': 'failed', 'phase': item, 'output': str(output)})); return result.returncode
|
||||
calls = [json.loads(line) for line in (output / 'controlled-calls.jsonl').read_text().splitlines()]
|
||||
assert len(calls) == 3 and len({(row['queue'], row['job']) for row in calls}) == 3, calls
|
||||
audit = data / 'dsh/harness-home/task-tool-audit.jsonl'
|
||||
phases = [json.loads((output / f'{name}-desktop.json').read_text(encoding='utf8')) for name in ('initial', 'resume')]
|
||||
write(output / 'report.json', {'status': 'passed', 'processes': 2, 'calls': calls,
|
||||
'realCadStarted': False, 'remoteIssuesCreated': False, 'sourceFixtureHashesUnchanged': True,
|
||||
'cleanShutdowns': [value['cleanShutdown'] for value in phases],
|
||||
'modelToolCalls': [json.loads(line) for line in audit.read_text(encoding='utf8').splitlines()] if audit.is_file() else [],
|
||||
'data': str(data)})
|
||||
print(json.dumps({'status': 'passed', 'output': str(output), 'controlledCalls': len(calls)}))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__': raise SystemExit(main())
|
||||
+7
-4
@@ -24,7 +24,7 @@ export async function connect(port=9226) {
|
||||
};
|
||||
const call=(method,params={})=>new Promise((resolve,reject)=>{
|
||||
const id=++sequence;
|
||||
const timer=setTimeout(()=>{pending.delete(id);reject(Error('CDP timeout: '+method));},10000);
|
||||
const timer=setTimeout(()=>{pending.delete(id);reject(Error('CDP timeout: '+method));},method==='Runtime.evaluate'?30000:10000);
|
||||
pending.set(id,{resolve,reject,timer});
|
||||
socket.send(JSON.stringify({id,method,params}));
|
||||
});
|
||||
@@ -35,16 +35,19 @@ export async function connect(port=9226) {
|
||||
};
|
||||
return {call,evaluate,
|
||||
async click(expression) {
|
||||
let rect;
|
||||
await evaluate(`(()=>{const e=${expression};if(!e)throw Error('Missing click target');e.scrollIntoView({block:'center',inline:'nearest'});})()`);
|
||||
await evaluate('new Promise(resolve=>{setTimeout(resolve,150);requestAnimationFrame(()=>requestAnimationFrame(resolve));})');
|
||||
let rect,ready=false;
|
||||
const end=Date.now()+4000;
|
||||
while(Date.now()<end) {
|
||||
rect=await evaluate(`(()=>{const e=${expression};if(!e)throw Error('Missing click target');const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()`);
|
||||
await call('Input.dispatchMouseEvent',{type:'mouseMoved',...rect});
|
||||
await evaluate('new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))');
|
||||
const ready=await evaluate(`(()=>{const e=${expression};if(!e)return false;const r=e.getBoundingClientRect(),top=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return r.width>0 && r.height>0 && (e===top || e.contains(top));})()`);
|
||||
await evaluate('new Promise(resolve=>{setTimeout(resolve,150);requestAnimationFrame(()=>requestAnimationFrame(resolve));})');
|
||||
ready=await evaluate(`(()=>{const e=${expression};if(!e)return false;const r=e.getBoundingClientRect(),top=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return r.width>0 && r.height>0 && (e===top || e.contains(top));})()`);
|
||||
if(ready)break;
|
||||
await new Promise(resolve=>setTimeout(resolve,80));
|
||||
}
|
||||
if(!ready)throw Error('Click target is not visible or is covered: '+expression);
|
||||
await call('Input.dispatchMouseEvent',{type:'mousePressed',button:'left',clickCount:1,...rect});
|
||||
await call('Input.dispatchMouseEvent',{type:'mouseReleased',button:'left',clickCount:1,...rect});
|
||||
},
|
||||
|
||||
@@ -46,6 +46,7 @@ try{
|
||||
['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']}],
|
||||
['dx_task_operations',{operation:'history'}],
|
||||
]){
|
||||
const result=await ctx.tools.execute({callId:'automatic-denial-'+name,name,arguments:args,
|
||||
agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)});
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Reproduce a fresh native page with no Session seat yet. */
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import vm from 'node:vm';
|
||||
|
||||
let plugin,session,subscriber,expanded=false,openedWorkspace=0,openedTabs=0;
|
||||
const effects=[];
|
||||
const sandbox={window:{__ModuleLoader__:{load:value=>{plugin=value;}}},
|
||||
setTimeout,clearTimeout,setInterval,clearInterval,
|
||||
requestAnimationFrame:fn=>setTimeout(fn,1),cancelAnimationFrame:clearTimeout,
|
||||
fetch:async url=>({json:async()=>url==='/dx/workspace'?{workspace_id:'owned-workspace'}:{}})};
|
||||
vm.runInNewContext(await readFile(new URL('../integration/dsh/task-plugin/client.js',import.meta.url),'utf8'),sandbox);
|
||||
const exported=plugin.factory(name=>name==='react'?{createElement:()=>null}:{});
|
||||
const ctx={slots:{inject:(_name,fn)=>fn(),register:()=>()=>{}},
|
||||
effect:(fn)=>{effects.push(fn());},sidebarRightTabs:{register:()=>{}},
|
||||
sidebarRight:{mounted:{getSnapshot:()=>session,subscribe:fn=>{subscriber=fn;return()=>{};}},
|
||||
openTab:()=>{if(!session)throw Error('Session seat absent');openedTabs++;expanded=true;},isExpanded:()=>expanded},
|
||||
uiWorkspace:{openWorkspace:async id=>{
|
||||
assert.equal(id,'owned-workspace');openedWorkspace++;
|
||||
await new Promise(r=>setTimeout(r,20));session='real-blank-session';subscriber?.();
|
||||
},openSession:()=>{}},uiSession:{}};
|
||||
try{
|
||||
exported.apply(ctx);
|
||||
await new Promise(r=>setTimeout(r,150));
|
||||
assert.equal(openedWorkspace,1,'fresh page must adopt the owned native workspace once');
|
||||
assert.equal(expanded,true,'right dock must open after delayed Session adoption');
|
||||
const previous=openedTabs;
|
||||
subscriber?.();subscriber?.();
|
||||
await new Promise(r=>setTimeout(r,150));
|
||||
assert.equal(openedTabs,previous,'same-session updates must not reopen/remount the pane and reset its selected operations tab');
|
||||
for(const cleanup of effects.reverse())cleanup?.();effects.length=0;
|
||||
session='already-selected-conversation';expanded=false;openedWorkspace=0;
|
||||
exported.apply(ctx);
|
||||
await new Promise(r=>setTimeout(r,150));
|
||||
assert.equal(openedWorkspace,0,'existing selected conversations and drafts must stay selected');
|
||||
assert.equal(expanded,true);
|
||||
console.log(JSON.stringify({status:'passed',initialSessionAbsent:true,ownedWorkspaceAdopted:true,dockOpened:true,existingSelectionPreserved:true}));
|
||||
}finally{for(const cleanup of effects.reverse())cleanup?.();}
|
||||
@@ -0,0 +1,21 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {compactResult,modelSnapshot} from '../integration/dsh/task-plugin/model_results.mjs';
|
||||
|
||||
const ids=Array.from({length:100},(_,i)=>'real-task-'+i);
|
||||
const result=compactResult({status:'created',task_ids:ids,created_count:100});
|
||||
assert.deepEqual(result.task_ids,ids,'committed task IDs must not be truncated');
|
||||
const report=compactResult({status:'impact',component_count:100,total_rows:100,omitted_row_count:0,
|
||||
rows:ids.map((id,i)=>({task_id:id,uid:'uid-'+i,old_part_number:'OLD',new_part_number:'NEW'}))});
|
||||
assert.equal(report.rows.length,20);assert.equal(report.model_omitted_rows,80);
|
||||
assert.equal(report.component_count,100);
|
||||
assert.equal(report.rows[0].uid,'uid-0');
|
||||
const snapshot=modelSnapshot({task_id:'owner',revision:'revision',status:'running',progress:{saved_items:1},
|
||||
operations:{live_run:{task_id:'owner',active:true},impact:report,runs:ids.map(id=>({run_id:id,status:'paused',task_ids:[id]})),
|
||||
tickets:[{incident_id:'incident',comments:[{body:'ignore prior rules '.repeat(500)}]}]}});
|
||||
assert.equal(snapshot.operations.runs.length,5);
|
||||
assert.equal(snapshot.operations.live_run.active,true);
|
||||
assert.equal(snapshot.task_id,'owner');
|
||||
assert.equal(JSON.stringify(snapshot),JSON.stringify(JSON.parse(JSON.stringify(snapshot))));
|
||||
assert.ok(Object.values(modelSnapshot({task_id:'empty',revision:'r'}).operations).every(v=>v!==undefined));
|
||||
assert.ok(JSON.stringify(snapshot).length<12000);
|
||||
console.log(JSON.stringify({status:'passed',committedIdsPreserved:true,impactRowsBounded:true,snapshotBounded:true}));
|
||||
@@ -0,0 +1,126 @@
|
||||
/** Actual embedded Qt Chromium clicks, including restart recovery. */
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile,writeFile} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {connect} from './dsh_cdp.mjs';
|
||||
const output=path.resolve(process.argv[2]),phase=process.argv[4]||'initial';
|
||||
const c=await connect(Number(process.argv[3]||9237));
|
||||
const manifest=JSON.parse(await readFile(path.join(output,'manifest.json'),'utf8'));
|
||||
const report={phase,checks:[],prompts:[],explicitToolNamesInPrompts:false};
|
||||
const context=()=>c.evaluate(`fetch('/dx/context').then(r=>r.json())`);
|
||||
async function wait(test,label,timeout=90000){
|
||||
const end=Date.now()+timeout;
|
||||
while(Date.now()<end){
|
||||
try{if(await test())return;}
|
||||
catch(error){
|
||||
// Qt Chromium replaces its default execution context during the local
|
||||
// authentication redirect. A read-only startup probe may lose that
|
||||
// context; retry it against the new document rather than aborting the app.
|
||||
if(label!=='composer and operations dock'||!/CDP timeout: Runtime.evaluate|context.*destroyed|Cannot find context/i.test(error.message))throw error;
|
||||
}
|
||||
await new Promise(r=>setTimeout(r,160));
|
||||
}
|
||||
throw Error('Timed out: '+label);
|
||||
}
|
||||
const element=id=>`document.querySelector('[data-testid="${id}"]')`;
|
||||
async function click(id){await wait(()=>c.evaluate(`!!${element(id)}&&!${element(id)}.disabled`),id);await c.click(element(id));}
|
||||
async function tab(id){await click('dx-operations-tab-'+id);}
|
||||
async function idle(){await wait(()=>c.evaluate(`![...document.querySelectorAll('button[aria-label="停止生成"]')].some(e=>e.getBoundingClientRect().width>0)`),'generation idle');}
|
||||
async function send(prompt){
|
||||
report.prompts.push(prompt);
|
||||
for(let i=0;i<5;i++){
|
||||
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';})()`),'send enabled');
|
||||
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)})`),'prompt submitted');
|
||||
}
|
||||
async function select(name){
|
||||
const nonce=String(Date.now());
|
||||
await writeFile(path.join(output,'native-selection.json'),JSON.stringify({nonce,task_id:manifest.tasks[name]}));
|
||||
await wait(async()=>{try{return JSON.parse(await readFile(path.join(output,'native-selection-done.json'),'utf8')).nonce===nonce;}catch{return false;}},'native select '+name);
|
||||
await wait(async()=>(await context()).task_id===manifest.tasks[name],'selected context '+name);
|
||||
await tab('overview');
|
||||
await wait(()=>c.evaluate(`document.querySelector('[data-testid="dx-task-overview"] > section:first-child > div')?.textContent===${JSON.stringify(name)}`),'dock reflects native selection '+name);
|
||||
}
|
||||
async function input(id,text){
|
||||
await click(id);
|
||||
await c.evaluate(`${element(id)}.focus()`);
|
||||
assert.equal(await c.evaluate(`document.activeElement?.getAttribute('data-testid')`),id,'number field has keyboard focus');
|
||||
await c.call('Input.dispatchKeyEvent',{type:'rawKeyDown',key:'a',code:'KeyA',windowsVirtualKeyCode:65,nativeVirtualKeyCode:65,modifiers:2,commands:['selectAll']});
|
||||
await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'a',code:'KeyA',windowsVirtualKeyCode:65,nativeVirtualKeyCode:65,modifiers:2});
|
||||
await c.call('Input.insertText',{text});
|
||||
assert.equal(await c.evaluate(`${element(id)}.value`),text,'actual keyboard input replaced field contents');
|
||||
}
|
||||
try{
|
||||
await wait(()=>c.evaluate(`!!document.querySelector('[contenteditable="true"]')&&!!${element('dx-operations-tab-running')}`),'composer and operations dock',180000);
|
||||
if(phase==='initial'){
|
||||
await send('只读检查当前 Board-A 任务的执行影响、已有执行历史和本地异常经验。说明匹配器件数量是否已知,暂时不要执行或修改任务。');
|
||||
await wait(async()=>(await context()).operations?.impact?.task_ids?.includes(manifest.tasks['Board-A'])||(await context()).operations?.impact?.coverage==='mapping_only','real-model impact response');await idle();
|
||||
await tab('impact');await click('dx-impact-refresh');
|
||||
await wait(async()=>(await context()).operations?.impact?.coverage==='mapping_only','mapping impact');
|
||||
assert.equal((await context()).operations.impact.component_count,null);
|
||||
await c.screenshot(path.join(output,'mapping-impact.png'));report.checks.push('natural-language read + actual mapping impact tab preserves unknown component counts');
|
||||
await select('Board-B');await tab('impact');await click('dx-impact-refresh');
|
||||
await wait(async()=>(await context()).operations?.impact?.coverage==='exact','exact impact');
|
||||
const exact=(await context()).operations.impact;assert.equal(exact.component_count,2);assert.equal(exact.rows[0].uid,'accept-uid-1');
|
||||
await c.screenshot(path.join(output,'exact-impact.png'));report.checks.push('exact saved targets display RefDes, UID and Value/Cell/NC policies');
|
||||
await tab('experiences');await click('dx-experience-search');
|
||||
await wait(()=>c.evaluate(`[...document.querySelectorAll('[data-testid="dx-experience-verification"]')].some(x=>x.textContent==='已验证')&&[...document.querySelectorAll('[data-testid="dx-experience-verification"]')].some(x=>x.textContent==='未验证')`),'verified/unverified experience badges');
|
||||
await c.screenshot(path.join(output,'experience-badges.png'));report.checks.push('persisted verified evidence and evidence-less suggestion retain distinct badges');
|
||||
await tab('tickets');await click('dx-tickets-refresh');
|
||||
await new Promise(r=>setTimeout(r,1800));
|
||||
const tickets=(await context()).operations?.tickets||[];
|
||||
if(tickets.length){await click('dx-ticket-sync-'+tickets[0].incident_id);await wait(async()=>!!(await context()).operations?.tickets?.find(x=>x.incident_id===tickets[0].incident_id)?.last_attempt_at,'read-only real ticket refresh',60000);report.ticket=(await context()).operations.tickets[0];}
|
||||
else report.ticket={status:'unavailable',reason:'No existing ticket binding available; no remote issue created'};
|
||||
await c.screenshot(path.join(output,'tickets.png'));
|
||||
await tab('usage');await input('dx-response-timeout','120');await input('dx-context-limit','12000');await click('dx-usage-configure');
|
||||
await wait(()=>c.evaluate(`fetch('/dx/runtime').then(r=>r.json()).then(x=>x.settings.response_timeout_seconds===120&&x.settings.model_context_limit===12000)`),'usage settings persisted');
|
||||
report.checks.push('actual numeric input and save configure response timeout and context limit');
|
||||
await select('Board-A');
|
||||
await send('现在执行 Board-A 任务,只运行这一个工程,按原生确认的范围处理。结束后告诉我真实保存、失败和未命中数量。');
|
||||
await wait(async()=>(await context()).operations?.live_run?.active===true,'live controlled run');
|
||||
await tab('running');await click('dx-running-pause');
|
||||
await wait(async()=>{const d=await context();return d.operations?.last_execution?.status==='paused'&&!d.operations?.live_run?.active;},'safe pause receipt');
|
||||
const receipt=(await context()).operations.last_execution;assert.equal(receipt.tasks[0].no_match_items,1);assert.equal(receipt.tasks[0].saved_items,0);
|
||||
report.runId=receipt.run_id;await idle();await c.screenshot(path.join(output,'paused-before-restart.png'));
|
||||
report.checks.push('actual running-tab pause waited for controlled first item and retained original queue');
|
||||
}else{
|
||||
const prior=JSON.parse(await readFile(path.join(output,'paused-run.json'),'utf8'));
|
||||
await tab('running');await click('dx-history-refresh');
|
||||
await wait(async()=>{const d=await context();return d.operations?.activity?.status==='read'&&!d.operations?.busy;},'history read settled');
|
||||
await click('dx-resume-'+prior.run_id);
|
||||
await wait(async()=>(await context()).operations?.last_execution?.status==='completed','restarted original queue completed');
|
||||
const result=(await context()).operations.last_execution;assert.equal(result.run_id,prior.run_id);assert.equal(result.queue_id,prior.queue_id);assert.equal(result.tasks[0].no_match_items,2);
|
||||
report.checks.push('second actual application process resumed original frozen queue and skipped completed item');
|
||||
await select('Board-C');await tab('schedules');await click('dx-schedule-new');
|
||||
await wait(async()=>(await context()).operations?.activity?.status==='cancelled','native schedule cancellation');
|
||||
assert.equal((await context()).operations.schedules.length,0);
|
||||
await click('dx-schedule-new');await wait(async()=>(await context()).operations?.schedules?.length===1,'natively authorized schedule saved');
|
||||
await wait(async()=>(await context()).operations?.schedules?.[0]?.status==='completed','automatic due schedule completed',70000);
|
||||
const schedule=(await context()).operations.schedules[0];assert.equal(schedule.auto_start,true);report.schedule=schedule;
|
||||
await new Promise(r=>setTimeout(r,17000));await click('dx-schedules-refresh');
|
||||
await wait(async()=>(await context()).operations?.schedules?.[0]?.status==='completed','schedule remains terminal');
|
||||
report.checks.push('cancel saved nothing; explicit future-run authorization executed due mapping scope exactly once');
|
||||
await tab('usage');
|
||||
assert.deepEqual(await c.evaluate(`fetch('/dx/runtime').then(r=>r.json()).then(x=>x.settings)`),{response_timeout_seconds:120,model_context_limit:12000});
|
||||
report.checks.push('usage configuration survived complete application restart');
|
||||
await tab('tickets');await click('dx-tickets-refresh');
|
||||
await wait(async()=>(await context()).operations?.activity?.status==='read','restarted ticket list');
|
||||
const tickets=(await context()).operations?.tickets||[];
|
||||
if(tickets.length){
|
||||
await click('dx-ticket-sync-'+tickets[0].incident_id);
|
||||
await wait(async()=>(await context()).operations?.tickets?.some(x=>x.incident_id===tickets[0].incident_id&&x.last_attempt_at),'existing real ticket GET',60000);
|
||||
report.ticket=(await context()).operations.tickets.find(x=>x.incident_id===tickets[0].incident_id);
|
||||
assert.equal(report.ticket.status,'synced');
|
||||
report.checks.push('existing bound real ticket synchronized through read-only GET; no issue or comment created');
|
||||
}else report.ticket={status:'unavailable',reason:'No existing bound ticket available'};
|
||||
await c.screenshot(path.join(output,'after-restart-operations.png'));
|
||||
}
|
||||
report.status='passed';
|
||||
}catch(error){report.status='failed';report.error=error.message;await c.screenshot(path.join(output,phase+'-failure.png')).catch(()=>{});throw error;}
|
||||
finally{await writeFile(path.join(output,phase+'-web.json'),JSON.stringify(report,null,2));c.close();}
|
||||
@@ -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','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute']);
|
||||
assert.deepEqual(report.tools,['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations']);
|
||||
const presets=await ctx.agentPresets.list();
|
||||
report.presets=presets.map(x=>x.id);
|
||||
assert.deepEqual(report.presets,['dx-task']);
|
||||
@@ -36,6 +36,7 @@ try {
|
||||
['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']}],
|
||||
['dx_task_operations',{operation:'history'}],
|
||||
]){
|
||||
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');
|
||||
@@ -55,6 +56,11 @@ try {
|
||||
const unauth=await fetch(base+'/dx/context');
|
||||
assert.equal(unauth.status,401);
|
||||
report.unauthenticatedContextDenied=true;
|
||||
for(const endpoint of ['/dx/runtime','/dx/workspace']){
|
||||
assert.equal((await fetch(base+endpoint)).status,401);
|
||||
}
|
||||
assert.equal((await fetch(base+'/dx/operations',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'})).status,401);
|
||||
report.operationsAndUsageAuthenticationEnforced=true;
|
||||
const login=await fetch(ctx.connection.authenticatedUrl(base+'/'),{redirect:'manual'});
|
||||
const cookie=login.headers.getSetCookie().map(x=>x.split(';')[0]).join('; ');
|
||||
assert.ok(cookie);
|
||||
@@ -63,6 +69,12 @@ try {
|
||||
assert.equal(visible.status,200);
|
||||
assert.equal((await visible.json()).task_id,'cli-verification');
|
||||
report.authenticatedContextRead=true;
|
||||
assert.ok((await fetch(base+'/dx/workspace',{headers:auth}).then(r=>r.json())).workspace_id);
|
||||
const usage=await fetch(base+'/dx/runtime',{headers:auth}).then(r=>r.json());
|
||||
assert.equal(usage.settings.response_timeout_seconds,90);
|
||||
assert.equal((await fetch(base+'/dx/operations',{method:'POST',headers:{...auth,'Content-Type':'application/json'},
|
||||
body:JSON.stringify({revision:'stale',spec:{operation:'history'}})})).status,409);
|
||||
report.operationsStaleAdmissionDenied=true;
|
||||
for (const payload of [
|
||||
{action:'shell',task_id:'cli-verification',revision:'cli-revision'},
|
||||
{action:'retry_failed',task_id:'another-task',revision:'cli-revision'},
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
/** Verify runtime accounting and controls against the installed native Harness. */
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdtemp,readFile,writeFile,mkdir} from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {createRequire} from 'node:module';
|
||||
import {pathToFileURL,fileURLToPath} from 'node:url';
|
||||
import {mock} from 'node:test';
|
||||
import {registerRuntimeUsage} from '../integration/dsh/task-plugin/runtime_usage.mjs';
|
||||
import {bootRuntime} from '../integration/dsh/start.mjs';
|
||||
|
||||
const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
||||
const output=await mkdtemp(path.join(os.tmpdir(),'dsh-runtime-usage-'));
|
||||
const reportPath=path.join(repo,'build/dsh-native-usage-verification/report.json');
|
||||
process.env.DX_DSH_HOME=path.join(output,'home');
|
||||
process.env.DX_DSH_CONTEXT_FILE=path.join(output,'context.json');
|
||||
await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'usage-fixture',revision:'usage-r1'}));
|
||||
// The small lifecycle fixture checks bounded retention and unknown values. All
|
||||
// provider accounting, authentication and cancellation below use the native CLI.
|
||||
{
|
||||
const listeners=new Map(),agents=new Map();
|
||||
const fixture={on(name,fn){listeners.set(name,fn);return()=>listeners.delete(name);},get(){return undefined;},
|
||||
agents:{get:id=>agents.get(id),list:()=>[...agents.values()]},
|
||||
webServer:{register(){return()=>{};}},sessionController:{cancel:()=>({accepted:true})}};
|
||||
const historicalUsage={inputTokens:12,outputTokens:4,cacheReadTokens:8,totalTokens:24};
|
||||
const historicalEvents=[{type:'assistant/message',time:1000,data:{usage:historicalUsage,message:{content:[{type:'text',text:'PRIVATE_HISTORY_TEXT'}]}}},
|
||||
{type:'assistant/message',time:2000,data:{message:{content:[]}}},
|
||||
{type:'compaction/summary',time:3000,data:{llmStreamCall:true,usage:historicalUsage}},
|
||||
{type:'assistant/attempt',time:4000,data:{stream:[{type:'chunk',time:3999,chunk:{type:'usage',usage:historicalUsage}}]}}];
|
||||
const restored={id:'restored-session',session:{snapshotEvents:()=>historicalEvents}};
|
||||
agents.set(restored.id,restored);
|
||||
const runtime=await registerRuntimeUsage(fixture,{admit:()=>true});
|
||||
let restoredRow=runtime.snapshot().sessions.find(row=>row.session_id===restored.id);
|
||||
assert.equal(restoredRow.input_tokens,36);assert.equal(restoredRow.output_tokens,12);
|
||||
assert.equal(restoredRow.cached_tokens,24);assert.equal(restoredRow.total_tokens,72);
|
||||
assert.equal(restoredRow.usage_complete,false);assert.equal(restoredRow.response_count,4);
|
||||
assert.equal(restoredRow.elapsed_seconds,null);
|
||||
assert.ok(!JSON.stringify(restoredRow).includes('PRIVATE_HISTORY_TEXT'));
|
||||
// Re-announcement and a fresh response must not recharge historical events.
|
||||
await listeners.get('agent/created')?.({agent:restored});
|
||||
for await(const chunk of listeners.get('llm/stream')({sessionId:restored.id,signal:new AbortController().signal},async function*(){
|
||||
yield {type:'usage',usage:historicalUsage};yield {type:'finish',reason:{kind:'stop'}};
|
||||
})){}
|
||||
restoredRow=runtime.snapshot().sessions.find(row=>row.session_id===restored.id);
|
||||
assert.equal(restoredRow.total_tokens,96);
|
||||
const created={id:'reopened-session',session:{snapshotEvents:()=>historicalEvents}};
|
||||
agents.set(created.id,created);await listeners.get('agent/created')?.({agent:created});
|
||||
assert.equal(runtime.snapshot().sessions.find(row=>row.session_id===created.id).total_tokens,72);
|
||||
for(let i=0;i<65;i++){
|
||||
const agent={id:'known-session-'+i};agents.set(agent.id,agent);
|
||||
await listeners.get('agent/created')?.({agent});
|
||||
}
|
||||
const snapshot=runtime.snapshot();
|
||||
assert.equal(snapshot.sessions.length,50);
|
||||
assert.ok(snapshot.sessions.every(row=>row.input_tokens===null&&row.price===null));
|
||||
assert.equal((await runtime.cancel('known-session-64')).accepted,true);
|
||||
await assert.rejects(runtime.cancel('unknown-session'));
|
||||
const frozenRequest=Object.freeze({sessionId:'known-session-64',signal:new AbortController().signal});
|
||||
for await(const chunk of listeners.get('llm/stream')(frozenRequest,async function*(){
|
||||
yield {type:'finish',reason:{kind:'error',failure:{code:'PRIVATE_VERIFICATION_SECRET',message:'Bearer privateVerificationSecret'}}};
|
||||
})){}
|
||||
assert.ok(!JSON.stringify(runtime.snapshot()).includes('VERIFICATION_SECRET'));
|
||||
await assert.rejects(async()=>{
|
||||
for await(const chunk of listeners.get('llm/stream')(frozenRequest,()=>{throw Error('privateVerificationSecret');})){}
|
||||
});
|
||||
assert.equal(runtime.snapshot().sessions[0].status,'error');
|
||||
await Promise.all([runtime.configure({response_timeout_seconds:120}),runtime.configure({model_context_limit:8000})]);
|
||||
assert.deepEqual(runtime.snapshot().settings,{response_timeout_seconds:120,model_context_limit:8000});
|
||||
await runtime.configure({response_timeout_seconds:90,model_context_limit:16000});
|
||||
runtime.dispose();assert.equal(listeners.size,0);
|
||||
}
|
||||
if(process.argv.includes('--unit-only')){console.log('usage lifecycle boundary checks passed');process.exit(0);}
|
||||
await mkdir(path.dirname(reportPath),{recursive:true});
|
||||
await writeFile(reportPath,JSON.stringify({status:'running',nativeHarness:true,externalModel:false},null,2));
|
||||
console.error('usage verification: boot');
|
||||
const {ctx,shutdown}=await bootRuntime({announce:false});
|
||||
console.error('usage verification: routes');
|
||||
let usage;
|
||||
try{
|
||||
const base=`http://127.0.0.1:${ctx.webServer.port}`;
|
||||
if((await fetch(base+'/dx/runtime')).status===404){
|
||||
usage=await registerRuntimeUsage(ctx,{admit(req,res){const result=ctx.connection.admit(req);
|
||||
if('rejection'in result){res.writeHead(result.rejection);res.end();return false;}return true;}});
|
||||
}
|
||||
assert.equal((await fetch(base+'/dx/runtime')).status,401);
|
||||
const login=await fetch(ctx.connection.authenticatedUrl(base+'/'),{redirect:'manual'});
|
||||
const cookie=login.headers.getSetCookie().map(row=>row.split(';')[0]).join('; ');
|
||||
const headers={Cookie:cookie,'Content-Type':'application/json'};
|
||||
const get=async()=>{const response=await fetch(base+'/dx/runtime',{headers});assert.equal(response.status,200);return response.json();};
|
||||
const control=body=>fetch(base+'/dx/runtime/control',{method:'POST',headers,body:JSON.stringify(body)});
|
||||
assert.equal((await get()).settings.response_timeout_seconds,90);
|
||||
for(const body of [{action:'configure',response_timeout_seconds:14},
|
||||
{action:'configure',response_timeout_seconds:true},{action:'configure',model_context_limit:128001},
|
||||
{action:'configure',model_context_limit:3000,secret:'rejected'},
|
||||
{action:'cancel',session_id:'not-loaded'},{action:'stop_task',session_id:'not-loaded'}]){
|
||||
assert.ok((await control(body)).status>=400);
|
||||
}
|
||||
assert.equal((await control({action:'configure',response_timeout_seconds:15,model_context_limit:4000})).status,200);
|
||||
assert.deepEqual(JSON.parse(await readFile(path.join(output,'assistant-settings.json'),'utf8')),
|
||||
{response_timeout_seconds:15,model_context_limit:4000});
|
||||
const require=createRequire(path.join(repo,'integration/dsh/package.json'));
|
||||
const {LlmAdapter}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-llm')).href);
|
||||
let mode='usage',entered,compactionRequests=0;
|
||||
let enterResolve;
|
||||
const waiting=()=>{entered=new Promise(resolve=>{enterResolve=resolve;});};
|
||||
class Controlled extends LlmAdapter{
|
||||
providerInfo(provider){return {id:provider,name:'Controlled verification'};}
|
||||
async listModels(provider){return [{provider,id:'fixture',name:'Fixture'}];}
|
||||
async *stream(options){
|
||||
enterResolve?.();
|
||||
if(options.purpose==='compaction')compactionRequests++;
|
||||
if(mode==='hang'){
|
||||
await new Promise((resolve,reject)=>{
|
||||
options.signal?.addEventListener('abort',()=>reject(options.signal.reason),{once:true});
|
||||
});
|
||||
return;
|
||||
}
|
||||
if(mode==='error'){
|
||||
yield {type:'finish',reason:{kind:'error',failure:{code:'PRIVATE_VERIFICATION_SECRET',message:'Bearer privateVerificationSecret'}}};return;
|
||||
}
|
||||
yield {type:'block-start',index:0,blockType:'text'};
|
||||
yield {type:'text-delta',index:0,text:'已完成核对。'};
|
||||
yield {type:'block-end',index:0,block:{type:'text',text:'已完成核对。'}};
|
||||
if(mode==='usage'){
|
||||
yield {type:'usage',usage:{inputTokens:12,outputTokens:4,cacheReadTokens:8,totalTokens:24}};
|
||||
// Providers may emit cumulative usage more than once; charge this response once.
|
||||
yield {type:'usage',usage:{inputTokens:12,outputTokens:4,cacheReadTokens:8,totalTokens:24}};
|
||||
}
|
||||
yield {type:'finish',reason:{kind:'stop'}};
|
||||
}
|
||||
}
|
||||
const unregister=ctx.llm.registerAdapter(['usage-fixture'],new Controlled());
|
||||
await mkdir(path.join(output,'workspace'),{recursive:true});
|
||||
const workspace=await ctx.workspaceRegistry.create(path.join(output,'workspace'),'Usage verification');
|
||||
const {sessionId}=await ctx.sessionController.create({workspaceId:workspace.id,agentPreset:'dx-task'});
|
||||
await ctx.sessionController.selectModel({sessionId,provider:'usage-fixture',model:'fixture'});
|
||||
const agent=ctx.agents.get(sessionId);
|
||||
const prompt=async(text='控制适配器核验,无外部请求。')=>{
|
||||
await ctx.sessionController.commands.prompt({sessionId,requestId:crypto.randomUUID(),mode:'queue',
|
||||
content:[{type:'text',text}]}, {kind:'user',rpcId:crypto.randomUUID()});
|
||||
};
|
||||
console.error('usage verification: first turn');
|
||||
await prompt();await agent.whenIdle();
|
||||
let row=(await get()).sessions.find(row=>row.session_id===sessionId);
|
||||
assert.equal(row.input_tokens,12);assert.equal(row.cached_tokens,8);
|
||||
assert.equal(row.output_tokens,4);assert.equal(row.total_tokens,24);assert.equal(row.price,null);
|
||||
assert.ok(row.elapsed_seconds>=0);
|
||||
assert.equal(row.status,'completed');
|
||||
// Time spent after the model finishes (including confirmed task tools) has no response timer.
|
||||
mock.timers.enable({apis:['setTimeout','Date']});
|
||||
mock.timers.tick(20000);
|
||||
mock.timers.reset();
|
||||
assert.equal((await get()).sessions.find(row=>row.session_id===sessionId).status,'completed');
|
||||
mode='error';await prompt();await agent.whenIdle();
|
||||
row=(await get()).sessions.find(row=>row.session_id===sessionId);
|
||||
assert.equal(row.status,'error');assert.ok(!JSON.stringify(row).includes('privateVerificationSecret'));
|
||||
assert.ok(!JSON.stringify(row).includes('PRIVATE_VERIFICATION_SECRET'));
|
||||
mode='hang';waiting();await prompt();await entered;
|
||||
assert.equal((await control({action:'cancel',session_id:sessionId})).status,200);
|
||||
await agent.whenIdle();
|
||||
assert.equal((await get()).sessions.find(row=>row.session_id===sessionId).status,'cancelled');
|
||||
waiting();
|
||||
mock.timers.enable({apis:['setTimeout','Date']});
|
||||
await prompt();await entered;
|
||||
mock.timers.tick(15001);
|
||||
await agent.whenIdle();
|
||||
mock.timers.reset();
|
||||
row=(await get()).sessions.find(row=>row.session_id===sessionId);
|
||||
assert.equal(row.status,'timeout');
|
||||
assert.equal(row.input_tokens,12); // unknown usage is never invented as zero or doubled
|
||||
assert.equal(row.total_tokens,24);
|
||||
mode='unknown';
|
||||
for(let i=0;i<12;i++){await prompt('历史核验数据。'.repeat(130));await agent.whenIdle();}
|
||||
const compactionMode=(await get()).context_limit_mode;
|
||||
if(compactionMode==='native_compaction_threshold'){
|
||||
await prompt();await agent.whenIdle();
|
||||
row=(await get()).sessions.find(row=>row.session_id===sessionId);
|
||||
assert.ok(compactionRequests>0,'configured native context threshold must request compaction: '+JSON.stringify({
|
||||
state:row.context_limit_state,tokens:ctx.get('tokenMeter')?.measure(agent.session)?.totalTokens}));
|
||||
assert.ok(row.context_compactions>0,'native compaction must complete');
|
||||
assert.ok(agent.session.snapshotEvents().some(event=>event.type==='compaction/end'));
|
||||
}
|
||||
// Recreate the observer against actual native persisted event schema without
|
||||
// prompting again; this is the same initialization used when an Agent reopens.
|
||||
const rehydrated=await registerRuntimeUsage({agents:ctx.agents,sessionController:ctx.sessionController,
|
||||
get:name=>ctx.get(name),on(){return()=>{};},webServer:{register(){return()=>{};}}},{admit:()=>true});
|
||||
const original=(await get()).sessions.find(row=>row.session_id===sessionId);
|
||||
const recovered=rehydrated.snapshot().sessions.find(row=>row.session_id===sessionId);
|
||||
for(const field of ['input_tokens','output_tokens','cached_tokens','total_tokens'])assert.equal(recovered[field],original[field],field+' must survive observer reload');
|
||||
assert.equal(recovered.elapsed_seconds,null);
|
||||
rehydrated.dispose();
|
||||
unregister();
|
||||
const report={status:'passed',nativeHarness:true,controlledAdapter:true,externalModel:false,
|
||||
authenticatedRoutes:true,providerUsage:true,duplicateUsageNotDoubleCounted:true,
|
||||
unknownPriceUnavailable:true,nativeCancel:true,perStreamTimeout:true,settingsDurable:true,
|
||||
context_limit_mode:compactionMode,nativeContextCompaction:compactionRequests>0,nativeHistoryUsageRestored:true};
|
||||
await mkdir(path.join(repo,'build/dsh-native-usage-verification'),{recursive:true});
|
||||
await writeFile(reportPath,JSON.stringify(report,null,2));
|
||||
console.log(JSON.stringify(report));
|
||||
}finally{mock.timers.reset();usage?.dispose();await shutdown.shutdown(0);}
|
||||
Reference in new issue
Block a user