diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index d13ca4f..49eaf8f 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -44,6 +44,7 @@ jobs: tests/ui/test_dsh_blockers.py tests/ui/test_dsh_blocker_sources.py tests/ui/test_dsh_diagnosis_lifecycle.py + tests/ui/test_pr10_review_edges.py tests/ui/test_query_observability.py tests/packaging/test_dsh_runtime_staging.py tests/packaging/test_release_configuration.py diff --git a/README.md b/README.md index 03fb0b1..2f2a37f 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ DSH助手围绕真实任务中心工作,支持: - 查询任务快照、执行预检、影响范围和实际执行历史。 - 在原生确认后按冻结范围执行任务,支持安全暂停、原队列恢复和排期授权。 - 顶部 **AI 自动介入** 开关默认开启并记住设置;异常、BOM 校验失败、预检阻断、资源释放问题和后台操作长期无进展时自动新建诊断对话,收集脱敏证据,按规则重试或清理自有资源并核验,未解决则转受限 Git 工单。 -- 只读诊断期间可继续选择、创建任务,也可正常关闭窗口。顶部和助手面板均提供 **取消 AI 诊断**:停止模型请求、保存本地证据并转人工接管;已进入执行的 CAD 步骤仍按原暂停/强停机制安全收尾。诊断与复盘共享等待预算,默认 180 秒,随模型超时设置调整为 90–300 秒。 +- 只读诊断期间可继续选择、创建任务,也可正常关闭窗口。顶部和助手面板均提供 **取消 AI 诊断**:停止模型请求、保存本地证据并转人工接管;已进入执行的 CAD 步骤仍按原暂停/强停机制安全收尾。拒绝关闭或取消未保存计划的关闭确认时,诊断继续。诊断与复盘从原生会话准备好后共享等待预算,默认 180 秒,随模型超时设置调整为 90–300 秒;运行时启动和会话创建另有最多 300 秒的等待上限,不挤占分析时间。 - 后台读取异常先在约 200 毫秒后复查,连续失败才介入;同一持续阻塞不会周期性重复建会话,关闭再开启自动介入可主动重新诊断。面板分别显示清理次数及独立核验结果;资源自行释放显示“自行解除”,不会计作 AI 修复。资源清理使用独立控制,不显示 CAD 暂停或强停按钮。 - 在右侧任务监管中查看运行、影响、排期、经验、工单和用量;审计损坏、证据缺失和未知计数会明确显示。 diff --git a/docs/testing/2026-11-05-dsh-pr19-review219.md b/docs/testing/2026-11-05-dsh-pr19-review219.md new file mode 100644 index 0000000..7664c95 --- /dev/null +++ b/docs/testing/2026-11-05-dsh-pr19-review219.md @@ -0,0 +1,40 @@ +# PR #19 评论 #219 专项修复验证 + +本轮修复 `775bc23` 二次审查提出的四项问题,仅运行直接相关回归及 DSH 新增功能测试,没有运行旧全量套件、构建 EXE 或合并。 + +## 修复行为 + +- 主窗口把自动诊断的取消 API 当作可选能力,缺少 `can_cancel`/`cancel` 的替身不会使事件循环或关闭流程抛异常。更新既有运行控制交接替身,并把该回归文件加入 CI;另有缺少取消 API 的专项验证。 +- 关闭正在保存的窗口,或在未保存计划确认中选择取消时,保留只读诊断。确定关闭后才取消并退出原生运行时;占用执行通道的诊断在排队关闭时仍会取消,允许安全收尾。 +- 面板按 `verification_status`、`cleanup_performed` 及事件终态区分自行解除、实际清理和取消前已完成清理,避免把未执行清理说成修复成功。 +- 原生启动与会话创建单独最多等待 300 秒。会话创建、命名完成并发出 `started` 后,Python 与 host 才开始同一份模型等待预算;默认 180 秒,按设置限制在 90–300 秒。复盘使用剩余额度,不能重新获取一整份预算。Python 将剩余额度传给 host;host 保留事件截止时间,并对缓存数量限额。 +- 取消、原生失败和启动超时均能唤醒等待线程;内部同步事件不会进入返回分析结果、证据或 JSON。 + +## 验证结果 + +合并专项命令:**159 passed,107.64 秒,退出码 0**。 + +```text +python -m pytest tests/dsh/test_incidents.py tests/ui/test_dsh_native_menu.py tests/ui/test_dsh_blockers.py tests/ui/test_dsh_blocker_sources.py tests/ui/test_dsh_diagnosis_lifecycle.py tests/ui/test_query_observability.py tests/ui/test_pr10_review_edges.py tests/ui/test_ui_polish.py::test_search_feedback_and_no_match_state_are_visible -q --junitxml=build/pr19-review219-feature-tests.xml +``` + +该命令包含评论给出的既有失败复现范围。新增 UI 测试覆盖拒绝关闭、保存中关闭、可选取消 API,以及模拟 75 秒冷启动后仍保留完整 180 秒分析预算,40 秒后复盘只余 140 秒。 + +以下无网络 Node 验证全部通过,另对修改的 host/client 执行了语法检查: + +```text +node tools/verify_dsh_incident_panel.mjs +node tools/verify_dsh_model_results.mjs +node tools/verify_dsh_diagnosis_cancel.mjs +``` + +原生取消工具额外覆盖 host 侧 75 秒创建延迟不消耗预算、诊断和复盘共享剩余额度;前端工具同时验证自行解除和取消前完成清理的核验文案。 + +真实运行时验收: + +- `tools/verify_dsh_blocker_recovery.py` 通过。真实模型经原生 Harness 完成清理及停滞诊断;受控资源实际清理 1 次,实时任务上下文读取 0 次,模型调用 3 次,保留本地待提交工单 1 份。 +- `tools/accept_dsh_blockers.py` 通过。真实 QApplication/QTest 点击导入 BOM,在文件选择框选中无效 XLSX;失败后自动建立会话,真实模型完成诊断和复盘并保存证据。另一资源会话实际清理 1 次,独立读取为空后 `resolved`;CAD 读取 0 次,工程文件哈希不变,应用正常关闭,无未捕获异常。 + +验收使用隔离数据目录、受控内存资源,禁用远程工单发布;没有修改真实工程、清理用户进程或提交提供商配置与密钥。本地证据:`build/pr19-review219-feature-tests.xml`、`build/dsh-blocker-recovery-6290f525/report.json`、`build/pr19-review219-desktop/20261105-141420/`,均忽略提交。 + +独立只读审查复核了四项修改及等待/关闭边界,无遗留发现。CI 已加入此前漏掉的 UI 回归文件;远端 CI 的实际结果以 PR 检查为准。 diff --git a/integration/dsh/task-plugin/client.js b/integration/dsh/task-plugin/client.js index d512b9f..9baff64 100644 --- a/integration/dsh/task-plugin/client.js +++ b/integration/dsh/task-plugin/client.js @@ -34,7 +34,12 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{ const remaining=verification?.remaining_resources; const truncated=Array.isArray(remaining)&&remaining.some(row=>row?.__truncated__); const remainingCount=Array.isArray(remaining)?remaining.filter(row=>!row?.__truncated__).length:0; - const verificationText=verification?.resources_released===true?'资源释放已独立核验通过;不代表 CAD 任务成功。': + const observedCleared=verification?.verification_status==='observed_cleared'||data?.automation?.status==='observed_cleared'; + const cleanupPerformed=verification?.cleanup_performed===true; + const verificationText=observedCleared&&verification?.resources_released===true?'资源已独立观察为空;未执行 AI 清理,也不代表 CAD 任务成功。': + data?.automation?.status==='cancelled'&&verification?.resources_released===true&&cleanupPerformed?'诊断已取消;取消前已执行清理并独立确认资源为空,不代表 CAD 任务成功。': + verification?.resources_released===true&&cleanupPerformed?'资源释放已独立核验通过;不代表 CAD 任务成功。': + verification?.resources_released===true?'资源释放已观察为空;清理执行状态未知,不代表 CAD 任务成功。': !Array.isArray(remaining)?'资源释放尚未核验通过;剩余资源数量未知。': truncated?(remainingCount?'资源释放尚未核验通过;至少 '+remainingCount+' 项资源尚未释放(明细已截断)。':'资源释放尚未核验通过;剩余资源数量未知(明细已截断)。'): remaining.length?'资源释放尚未核验通过;剩余 '+remaining.length+' 项资源。':'资源释放尚未核验通过;当前未见剩余资源,仍需确认。'; diff --git a/integration/dsh/task-plugin/host.mjs b/integration/dsh/task-plugin/host.mjs index ec4dbd0..98c9f9d 100644 --- a/integration/dsh/task-plugin/host.mjs +++ b/integration/dsh/task-plugin/host.mjs @@ -17,6 +17,7 @@ export async function readContext(){ export async function apply(ctx){ const pending=new Set(); const incidentSnapshots=new Map(),incidentSessions=new Map(); + const incidentDeadlines=new Map(); const creations=new Map(); const diagnoses=new Map(); // Automatic sessions own their inbox: discard queued prompts as well as the active turn. @@ -144,9 +145,12 @@ export async function apply(ctx){ if(typeof request.request_id!=='string'||diagnoses.has(request.request_id)){ emit({status:'failed',error:'invalid_incident_request'});return; } + if(request.model_budget_ms!==undefined&&(!Number.isFinite(request.model_budget_ms)||request.model_budget_ms<=0||request.model_budget_ms>300000)){ + emit({status:'failed',error:'invalid_incident_request'});return; + } let cancel; const cancelled=new Promise(resolve=>{cancel=resolve;}); - const active={sessionId:null,cancelled:false,stopReason:null,cancel}; + const active={incidentId:request.incident_id,sessionId:null,cancelled:false,stopReason:null,cancel}; diagnoses.set(request.request_id,active); const checkCancelled=()=>{if(active.stopReason)throw Error(active.stopReason);}; void(async()=>{ @@ -160,6 +164,9 @@ export async function apply(ctx){ } active.sessionId=sessionId; checkCancelled(); + const budget=request.model_budget_ms??Math.min(300000,Math.max(90000,usage.snapshot().settings.response_timeout_seconds*2000)); + incidentDeadlines.set(request.incident_id,Math.min(incidentDeadlines.get(request.incident_id)??Infinity,Date.now()+budget)); + if(incidentDeadlines.size>256)incidentDeadlines.delete(incidentDeadlines.keys().next().value); incidentSnapshots.set(sessionId,{...request.snapshot,revision:request.incident_id}); emit({status:'started',session_id:sessionId}); const agent=ctx.agents.get(sessionId); @@ -182,7 +189,7 @@ export async function apply(ctx){ })(),cancelled.then(()=>{throw Error('diagnosis_cancelled');}),new Promise((_,reject)=>{timer=setTimeout(()=>{ active.stopReason='diagnosis_timeout'; cancelDiagnosisSession(sessionId);reject(Error('diagnosis_timeout')); - },Math.min(300000,Math.max(90000,usage.snapshot().settings.response_timeout_seconds*2000)));})]); + },Math.max(0,incidentDeadlines.get(request.incident_id)-Date.now()));})]); }finally{clearTimeout(timer);} checkCancelled(); const events=agent.session.snapshotEvents(); @@ -195,6 +202,9 @@ export async function apply(ctx){ emit({status:'completed',session_id:sessionId,reply,transcript}); })().catch(error=>emit({status:active.cancelled?'cancelled':'failed', error:active.cancelled?'diagnosis_cancelled':error.message==='diagnosis_timeout'?'diagnosis_timeout':'native_diagnosis_failed'})) - .finally(()=>diagnoses.delete(request.request_id)); + .finally(()=>{ + diagnoses.delete(request.request_id); + if(active.stopReason)incidentDeadlines.delete(active.incidentId); + }); }); } 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 de104d8..0be4a0a 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_automation.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_automation.py @@ -132,7 +132,9 @@ class DshAutomation(QObject): self._owns_execution_lane = not item.read_only and (item.authorized or item.cleanup_allowed) self._uses_cad_controls = self._owns_execution_lane and item.authorized self.cancel_event = Event() - self._analysis_deadline = monotonic() + self._diagnosis_budget_seconds() + # Start the shared model budget when the Harness session is ready; + # startup/session creation must not consume diagnosis time. + self._analysis_deadline = None self._current_identity = (task_id, code, run_id) if run_id == 'observation': run_id = uuid4().hex @@ -200,6 +202,8 @@ class DshAutomation(QObject): self.cancel_event.set() for request_id, (complete, holder) in list(self.waiters.items()): holder.update(status='cancelled', error='diagnosis_cancelled') + if holder.get('_ready') is not None: + holder['_ready'].set() complete.set() self.cancel_requested.emit(request_id) self._publish_context() @@ -226,17 +230,27 @@ class DshAutomation(QObject): if remaining <= 0: raise TimeoutError('native_diagnosis_total_timeout') request_id = uuid4().hex - complete, holder = Event(), {} + complete, holder = Event(), {'_ready': Event()} self.waiters[request_id] = (complete, holder) try: self.model_requested.emit({'request_id': request_id, 'incident_id': incident_id, - 'snapshot': snapshot, 'evidence': evidence[:38000], 'phase': phase}) + 'snapshot': snapshot, 'evidence': evidence[:38000], 'phase': phase, + 'model_budget_ms': max(1, int(remaining * 1000))}) + if self._analysis_deadline is None: + if not holder['_ready'].wait(300): + self._native_unavailable = True + self.cancel_requested.emit(request_id) + raise TimeoutError('native_diagnosis_startup_timeout') + remaining = (self._analysis_deadline or monotonic() + self._diagnosis_budget_seconds()) - monotonic() + if remaining <= 0: + self.cancel_requested.emit(request_id) + raise TimeoutError('native_diagnosis_total_timeout') if not complete.wait(remaining): self.cancel_requested.emit(request_id) raise TimeoutError('native_diagnosis_total_timeout') if holder.get('status') != 'completed': raise RuntimeError(holder.get('error', 'native_diagnosis_failed')) - return holder + return {key: value for key, value in holder.items() if key != '_ready'} finally: self.waiters.pop(request_id, None) @@ -253,19 +267,28 @@ class DshAutomation(QObject): def _runtime_stopped(self): for complete, holder in list(self.waiters.values()): holder.update(status='failed', error='native_harness_stopped') + if holder.get('_ready') is not None: + holder['_ready'].set() complete.set() def _diagnosis_event(self, value): if value.get('request_id') not in self.waiters: return if value.get('status') == 'started': + if self._analysis_deadline is None: + self._analysis_deadline = monotonic() + self._diagnosis_budget_seconds() self.latest['session_id'] = value['session_id'] + holder = self.waiters[value['request_id']][1] + if holder.get('_ready') is not None: + holder['_ready'].set() self._publish_context() else: waiter = self.waiters.get(value.get('request_id')) if waiter: complete, holder = waiter holder.update(value) + if holder.get('_ready') is not None: + holder['_ready'].set() complete.set() def _state_changed(self, row): 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 b2b91c4..1283ad5 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -336,12 +336,13 @@ class TrialTaskCenterWindow(MaterialMainWindow): QMessageBox.warning(self, '已保留待恢复任务', self._archive_close_notice) def closeEvent(self, event): - self._cancel_dsh_diagnosis() if self._close_saving: event.ignore() return if self._workers or self.history_panel._worker or (self._dsh_operations and self._dsh_operations.worker): self._close_pending = True + if self._dsh_automation and getattr(self._dsh_automation, '_owns_execution_lane', False): + self._cancel_dsh_diagnosis() self.plan_panel.cancel_operation() self._pause_queue() self._set_operator_message('操作尚未结束,请等当前步骤安全收尾后关闭。', 'warning') @@ -374,12 +375,16 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._run_async(lambda: archive_completed_session(self.service), self._session_archived) return if self._dsh_view is not None and getattr(self._dsh_view, 'is_running', False): + # All confirmation/retention branches have passed; the remaining + # asynchronous shutdown is part of an accepted close request. + self._cancel_dsh_diagnosis() event.ignore() if not self._dsh_stopping: self._dsh_stopping = True self._dsh_view.stopped.connect(lambda: QTimer.singleShot(0, self.close)) self._dsh_view.shutdown() return + self._cancel_dsh_diagnosis() for name, widget in self._layout_widgets().items(): self._layout_settings.setValue(f'single_project/{name}', widget.saveState()) self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData()) @@ -479,7 +484,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._task_context_failed(error, auto_intervene=auto_intervene) def _update_gates(self): - cancellable = bool(self._dsh_automation and self._dsh_automation.can_cancel) + cancellable = bool(self._dsh_automation and getattr(self._dsh_automation, 'can_cancel', False)) self.cancel_diagnosis_button.setVisible(cancellable) self.cancel_diagnosis_button.setEnabled(cancellable) busy = bool(self._workers) or self._loading or self.history_panel._worker is not None @@ -1324,8 +1329,9 @@ class TrialTaskCenterWindow(MaterialMainWindow): QMessageBox.warning(self, '操作未完成', message) def _cancel_dsh_diagnosis(self): - if self._dsh_automation is not None: - self._dsh_automation.cancel() + cancel = getattr(self._dsh_automation, 'cancel', None) + if cancel is not None: + cancel() def _set_auto_intervention(self, enabled): self._layout_settings.setValue('dsh/auto_intervention', enabled) diff --git a/tests/ui/test_dsh_diagnosis_lifecycle.py b/tests/ui/test_dsh_diagnosis_lifecycle.py index ff39a62..b22781d 100644 --- a/tests/ui/test_dsh_diagnosis_lifecycle.py +++ b/tests/ui/test_dsh_diagnosis_lifecycle.py @@ -83,6 +83,24 @@ def test_readonly_diagnosis_does_not_prevent_window_close(slow_diagnosis, qtbot) assert not published +@pytest.mark.parametrize('reason', ['unsaved', 'saving']) +def test_cancelled_close_confirmation_keeps_diagnosis_running(slow_diagnosis, qtbot, monkeypatch, ui, reason): + window, automation, _, start = slow_diagnosis + start() + if reason == 'unsaved': + monkeypatch.setattr(window.plan_panel, 'has_unsaved_plans', lambda: True) + monkeypatch.setattr(window, '_close_plan_confirmer', lambda: 'cancel') + else: + window._close_saving = True + window.close() + assert not window._closed + assert not automation.cancel_event.is_set() + window._close_saving = False + automation.cancel() + qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) + ui.settle() + + def test_resource_diagnosis_has_no_cad_pause_or_force_controls(slow_diagnosis, qtbot, ui): window, automation, published, start = slow_diagnosis view = start(read_only=False, cleanup=True) @@ -115,6 +133,50 @@ def test_model_wait_is_limited_by_remaining_total_budget(slow_diagnosis, monkeyp ui.settle() +def test_model_budget_starts_when_harness_session_is_ready(slow_diagnosis, monkeypatch): + _, automation, _, _ = slow_diagnosis + complete = module.Event() + automation.waiters['request'] = (complete, {}) + monkeypatch.setattr(module, 'monotonic', lambda: 100.0) + automation._analysis_deadline = None + automation._diagnosis_event({'request_id': 'request', 'status': 'started', 'session_id': 'session'}) + assert automation._analysis_deadline == 100.0 + automation._diagnosis_budget_seconds() + + +def test_cold_session_wait_does_not_consume_shared_model_budget(slow_diagnosis, monkeypatch, ui): + window, automation, _, _ = slow_diagnosis + window._open_dsh() + clock, waits = [100.0], [] + + class ControlledEvent: + def __init__(self): + self.set_flag = False + + def set(self): + self.set_flag = True + + def wait(self, timeout): + waits.append(timeout) + if timeout == 300: + clock[0] += 75 # Controlled cold session creation. + request_id = next(iter(automation.waiters)) + automation._diagnosis_event({'request_id': request_id, 'status': 'started', 'session_id': 'session'}) + automation._diagnosis_event({'request_id': request_id, 'status': 'completed', 'reply': '{"action":"none"}'}) + return self.set_flag + + monkeypatch.setattr(module, 'Event', ControlledEvent) + monkeypatch.setattr(module, 'monotonic', lambda: clock[0]) + result = automation._analyze('a' * 24, {'task_id': ''}, 'evidence', 'diagnose') + assert waits == [300, 180] + assert '_ready' not in result + clock[0] += 40 + with pytest.raises(TimeoutError): + automation._analyze('a' * 24, {'task_id': ''}, 'evidence', 'reflect') + assert waits[-1] == 140 + assert window._dsh_view.requests[-1]['model_budget_ms'] == 140000 + ui.settle() + + def test_native_cancel_removes_queued_request_and_sends_only_target_id(): from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView sent = [] @@ -139,3 +201,14 @@ def test_completed_incident_removes_embedded_cancel_action(slow_diagnosis, qtbot assert window._dsh_view.automation['can_cancel'] is False assert not window.cancel_diagnosis_button.isVisible() ui.settle() + + +def test_optional_automation_without_cancel_api_keeps_gates_and_close_usable(ui, monkeypatch, qtbot): + ui.settle() + window = ui.window + monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(enqueue=lambda *a, **kw: True)) + window._update_gates() + assert not window.cancel_diagnosis_button.isVisible() + window._cancel_dsh_diagnosis() + window.close() + qtbot.waitUntil(lambda: window._closed) diff --git a/tests/ui/test_pr10_review_edges.py b/tests/ui/test_pr10_review_edges.py index ca33d85..5a83013 100644 --- a/tests/ui/test_pr10_review_edges.py +++ b/tests/ui/test_pr10_review_edges.py @@ -137,7 +137,8 @@ def test_worker_exception_handoff_keeps_original_run_control(ui,qtbot,monkeypatc from dx_productivity.trial_task_center.errors import TaskCenterError window=ui.window;task_id=window._task_id captured=[] - window._dsh_automation=SimpleNamespace(enqueue=lambda *args,**kwargs:captured.append(kwargs)or True) + window._dsh_automation=SimpleNamespace(can_cancel=False,cancel=lambda:None, + enqueue=lambda *args,**kwargs:captured.append(kwargs)or True) window._dsh_authorized_tasks.add(task_id) window._begin_run(task_id) control=window._batch_stop;run_id=window._dsh_run_id diff --git a/tools/verify_dsh_diagnosis_cancel.mjs b/tools/verify_dsh_diagnosis_cancel.mjs index 1ecbb98..44b74cc 100644 --- a/tools/verify_dsh_diagnosis_cancel.mjs +++ b/tools/verify_dsh_diagnosis_cancel.mjs @@ -8,7 +8,8 @@ import {randomUUID,createHash} from 'node:crypto'; const deferred=()=>{let resolve;const promise=new Promise(yes=>{resolve=yes;});return {promise,resolve};}; const tick=()=>new Promise(resolve=>setImmediate(resolve)); const events=[],handlers=new Map(),routes=new Map(),sessions=new Map(),prompts=[],cancelled=[]; -let nextCreate=null,nextPrompt=null,latestTimeout; +let nextCreate=null,nextPrompt=null,latestTimeout,now=1000000; +const timeouts=[]; const context={task_id:'',revision:'current'}; const ctx={on:(name,fn)=>handlers.set(name,fn),effect:()=>{}, connection:{admit:()=>({})},tools:{register:()=>{},guard:()=>{}}, @@ -36,7 +37,8 @@ const ctx={on:(name,fn)=>handlers.set(name,fn),effect:()=>{}, },agents:{get:id=>sessions.get(id)}}; let source=await readFile(new URL('../integration/dsh/task-plugin/host.mjs',import.meta.url),'utf8'); source=source.replace(/^import .*;\r?\n/gm,'').replace(/export /g,''); -const sandbox={path,randomUUID,createHash,setTimeout:(callback,ms)=>{latestTimeout=callback;return setTimeout(callback,ms);},clearTimeout,console, +const sandbox={path,randomUUID,createHash,Date:class extends Date{static now(){return now;}}, + setTimeout:(callback,ms)=>{latestTimeout=callback;timeouts.push(ms);return setTimeout(callback,ms);},clearTimeout,console, readFile:async()=>JSON.stringify(context),appendFile:async()=>{},defineTool:value=>value, registerRuntimeUsage:async()=>({dispose:()=>{},snapshot:()=>({settings:{response_timeout_seconds:90}})}), registerLifecycle:()=>{},lifecycleNames:[],registerFileTools:()=>{},fileToolNames:[],modelSnapshot:value=>value, @@ -46,8 +48,8 @@ const sandbox={path,randomUUID,createHash,setTimeout:(callback,ms)=>{latestTimeo vm.createContext(sandbox); vm.runInContext(source+'\nglobalThis.applyPlugin=apply;',sandbox); await sandbox.applyPlugin(ctx); -const start=id=>handlers.get('dx/diagnose-request')({request_id:id,incident_id:createHash('sha256').update(id).digest('hex').slice(0,24), - phase:'diagnose',snapshot:{task_id:''},evidence:'controlled fixture'}); +const start=(id,options={})=>handlers.get('dx/diagnose-request')({request_id:id,incident_id:createHash('sha256').update(id).digest('hex').slice(0,24), + phase:'diagnose',snapshot:{task_id:''},evidence:'controlled fixture',...options}); const waitFor=async predicate=>{for(let i=0;i<100&&!predicate();i++)await tick();assert.ok(predicate(),'expected lifecycle event');}; const terminal=id=>events.find(event=>event.request_id===id&&['completed','cancelled','failed'].includes(event.status)); @@ -99,6 +101,25 @@ timingOut.resolve(); await waitFor(()=>cancelled.filter(id=>id===timeoutSession).length===2); assert.equal(sessions.get(timeoutSession).pending.length,0,'timeout must clear the late automatic inbox'); +nextCreate=deferred();const coldCreate=nextCreate; +const sharedIncident=createHash('sha256').update('shared-budget').digest('hex').slice(0,24); +start('budget-diagnose',{incident_id:sharedIncident,model_budget_ms:180000}); +now+=75000;coldCreate.resolve(); +await waitFor(()=>events.some(event=>event.request_id==='budget-diagnose'&&event.status==='started')); +assert.equal(timeouts.at(-1),180000,'cold creation must not consume model budget'); +const budgetSession=events.find(event=>event.request_id==='budget-diagnose'&&event.status==='started').session_id; +now+=40000; +sessions.get(budgetSession).rows.push({type:'assistant/message',data:{message:{content:[{type:'text',text:'{"action":"none"}'}]}}}); +sessions.get(budgetSession).idle.resolve(); +await waitFor(()=>terminal('budget-diagnose')); +nextPrompt=deferred();const reflectAdmission=nextPrompt; +start('budget-reflect',{incident_id:sharedIncident,phase:'reflect',model_budget_ms:140000}); +await waitFor(()=>events.some(event=>event.request_id==='budget-reflect'&&event.status==='started')); +assert.equal(timeouts.at(-1),140000,'reflection must consume the remaining shared budget'); +handlers.get('dx/diagnose-cancel')({request_id:'budget-reflect'}); +reflectAdmission.resolve(); +await waitFor(()=>terminal('budget-reflect')); + async function action(revision){ const req={method:'POST',async *[Symbol.asyncIterator](){yield JSON.stringify({action:'cancel_diagnosis',task_id:'',revision});}}; const res={status:200,writeHead(code){this.status=code;},end(){},setHeader(){}}; diff --git a/tools/verify_dsh_incident_panel.mjs b/tools/verify_dsh_incident_panel.mjs index b4f2ff9..ce38df6 100644 --- a/tools/verify_dsh_incident_panel.mjs +++ b/tools/verify_dsh_incident_panel.mjs @@ -39,7 +39,7 @@ function render(automation){ } const element=(tree,id)=>nodes(tree).find(node=>node.props['data-testid']===id); -let tree=render({status:'resolved',cleanup_attempts:1,verification:{resources_released:true,remaining_resources:[]}}); +let tree=render({status:'resolved',cleanup_attempts:1,verification:{verification_status:'complete',cleanup_performed:true,resources_released:true,remaining_resources:[]}}); assert.match(text([element(tree,'dx-auto-cleanup-attempts')]),/1/); assert.match(text([element(tree,'dx-auto-verification')]),/资源释放已独立核验通过/); assert.match(text([element(tree,'dx-auto-verification')]),/不代表 CAD 任务成功/); @@ -49,14 +49,18 @@ tree=render({status:'pending_issue',cleanup_attempts:0,verification:{resources_r assert.match(text([element(tree,'dx-auto-verification')]),/剩余资源数量未知/); tree=render({status:'pending_issue',cleanup_attempts:1,verification:{resources_released:false,remaining_resources:[{}, {__truncated__:true}]}}); assert.match(text([element(tree,'dx-auto-verification')]),/至少 1 项资源/); -tree=render({status:'observed_cleared',cleanup_attempts:0,verification:{resources_released:true,remaining_resources:[]}}); +tree=render({status:'observed_cleared',cleanup_attempts:0,verification:{verification_status:'observed_cleared',cleanup_performed:false,resources_released:true,remaining_resources:[]}}); assert.equal(text([element(tree,'dx-auto-status')]),'阻塞已自行解除,未执行清理'); +assert.match(text([element(tree,'dx-auto-verification')]),/未执行 AI 清理/); +assert.ok(!text([element(tree,'dx-auto-verification')]).includes('核验通过')); assert.ok(!text(tree).includes('正在保留现场'),'a cleared incident must not still claim diagnosis is running'); assert.equal(element(tree,'dx-auto-cancel'),undefined); tree=render({status:'cancelled',cleanup_attempts:0,can_cancel:false}); assert.equal(text([element(tree,'dx-auto-status')]),'诊断已取消,证据已保留'); assert.ok(!text(tree).includes('正在保留现场'),'a cancelled incident must not still claim diagnosis is running'); assert.equal(element(tree,'dx-auto-cancel'),undefined); +tree=render({status:'cancelled',cleanup_attempts:1,verification:{verification_status:'complete',cleanup_performed:true,resources_released:true,remaining_resources:[]}}); +assert.match(text([element(tree,'dx-auto-verification')]),/取消前已执行清理/); tree=render({status:'analyzing',task_id:'other-incident-task',can_cancel:true}); const cancel=element(tree,'dx-auto-cancel'); assert.ok(cancel,'an active diagnosis can be cancelled after selecting another task');