fix(dsh): retain stop intent and decode split UTF-8 output

This commit is contained in:
阿白叔 committed 2026-10-31 14:49:55 +08:00
1 parent 6f9f820f85
commit 0bc1f64edc
7 files changed
+265 -9

No files matched your search

@@ -0,0 +1,29 @@
# PR #10 第二轮审查修复(2026-10-31)
对应[评论 #117](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/10#issuecomment-117),基于已同步 main 的 `6f9f820`,仍在独立检出中验证,不包含主工作区未提交的 DSH 生命周期文件。
## P1:原执行轮次的停止意图
审查复现成立:用户在最后一步请求安全暂停或强制结束,而末项返回 `batch_failed` 时,队列可能已耗尽,`paused=False`。原实现先清除 `_batch_stop`,诊断开始时新建 `StopControl`,导致自动重试的 `not_stopped` 门禁失去原始停止请求。
现在窗口在运行收尾时保留原执行轮次的 `StopControl`(包括 `force_event`),排入诊断队列时将该对象与原 `run_id` 一起捕获。`DshAutomation` 直接复用该对象;等待诊断启动及模型回复期间的停止请求也能被同一对象观察。单任务结果、批次结果及 worker 异常回调统一经过这一传递。诊断、证据和待提交工单仍可保存,但停止后的轮次不会准备或执行失败项重试,也不会消耗重试额度。
新的显式确认执行通过 `_begin_run` 创建新轮次与新控制对象;不会清除或重置旧轮次的停止请求。回归验证了暂停后用户重新准备并确认执行的路径,正常重试仍可用。
## P2:运行时输出的 UTF-8 分块
审查复现成立:QProcess 输出块边界可落在中文字符的 UTF-8 字节中间,按块 `decode(..., 'replace')` 会把合法中文改成替换字符,而 JSON 仍能解析。
stdout 和 stderr 现分别使用持续的增量 UTF-8 解码器;stdout 完成解码后再按行解析原协议。每次启动(含重试启动)均清空协议行缓冲和两个解码器,旧进程的半行或未完成字符不会混入新进程。无改变协议前缀、任务参数、Origin 校验或动作门禁。
## 回归证据
新增 `tests/ui/test_pr10_review_edges.py` 共 15 项:
- 单任务/批次 × 未暂停、暂停、强制结束、暂停后重新授权。使用真实 `TaskCenterService`、执行队列、持久化、`DshAutomation` 和 `IncidentRunner`,只替换外部 CAD、模型、工单传输与线程派发。明确断言末项结果 `paused=False`,停止后执行器仅调用一次,正常对照允许两次;重新授权路径仍可执行并重试。
- worker 异常收尾覆盖未暂停、暂停和强制结束三种情况,验证诊断收到同一个原控制对象、原 run ID 和授权上下文。
- CREATE_REQUEST 在每个字节位置拆成两块,涵盖中文、目录、自定义 Value、μ 与 emoji;多行 DIAGNOSIS 每字节分块;stderr 中文分块;通过真实 `start()` 路径验证重启清空旧半行和 UTF-8 状态。
修改前复现暂停/强制结束的 4 个错误重试,以及两个 Unicode 损坏用例;正常对照通过。修改后新增 15 项通过,独立复核同样通过 15 项。`tests/ui tests/dsh` 加安全停止相关回归共 156 项通过。完整 `tests/v1_1 tests/ui tests/dsh tests/packaging` 回归 **1101 项通过**,无忽略/跳过项,1 条已有 pywinauto COM 模式警告,结果见本目录的 `pr10-review-117-tests.json`。
本轮未启动 CAD、真实模型、浏览器运行时或远端工单传输;未重建 EXE。真实源码协议方法通过信号接收器及 QProcess 字节流替身调用。
@@ -0,0 +1,15 @@
{
"command": "python -m pytest -q tests/v1_1 tests/ui tests/dsh tests/packaging --junitxml=build/pr10-review-117-tests.xml",
"tests": 1101,
"failures": 0,
"errors": 0,
"skipped": 0,
"seconds": 333.04,
"review_comment": 117,
"main_base": "2cf526e1769f354cd7e57861c4b0df9f165565dd",
"isolated_checkout": true,
"test_exclusions": [],
"warnings": [
"pywinauto: Revert to STA COM threading mode"
]
}
+2
View File
@@ -30,6 +30,8 @@
未解决时,AI 再做一轮复盘,保存结论、依据、未知项和后续验证方法,并尝试提交 Git 工单。事件以任务、原执行轮次和错误码去重;同一任务同一原执行轮次的不同错误码共享一次重试额度,执行前持久记录,重启不重置。未知错误、未授权执行和未核验状态仅诊断取证,不自动重放工程写入。
用户在原执行轮次请求安全暂停或强制结束后,该停止意图会随轮次传递到自动诊断;即使最后一个失败项已收尾、队列结果显示“已结束”,也不会自动准备或执行重试。诊断和证据上报仍可继续。只有用户重新确认执行新轮次,才会创建新的执行控制对象;原轮次的停止记录不会被清除。
- 普通对话注册 `dx_task_snapshot`(快照)和 `dx_task_create`(原生确认后创建任务);自动异常诊断会话只允许快照,创建调用在工具执行前被拒绝。Shell、通用文件访问、插件安装、子智能体及模型直接 CAD 写入工具均未注册;额外工具会被 guard 阻断。
- **刷新任务上下文**重新发布当前任务快照。
- 手动点击 **准备失败项重试**须在任务中心确认,并通过现有重试按钮的状态检查;该按钮只准备重试。自动介入使用上文限定的一次重试闭环。
@@ -47,13 +47,13 @@ class DshAutomation(QObject):
except (OSError, ValueError, KeyError):
continue
def enqueue(self, task_id, issue_code, message, *, execution_authorized=False, run_id='observation'):
def enqueue(self, task_id, issue_code, message, *, execution_authorized=False, run_id='observation', stop_event=None):
# Offscreen UI unit tests have no Chromium surface or local provider.
if QApplication.platformName().casefold() == 'offscreen':
return False
if issue_code == 'operation_cancelled' or not task_id:
return False
item = (task_id, issue_code, message, execution_authorized, run_id)
item = (task_id, issue_code, message, execution_authorized, run_id, stop_event)
identity = (task_id, issue_code, run_id)
if identity in self.seen:
return True
@@ -69,7 +69,7 @@ class DshAutomation(QObject):
if w._workers or w._loading:
QTimer.singleShot(200, self._drain)
return
task_id, code, message, authorized, run_id = self.pending.pop(0)
task_id, code, message, authorized, run_id, original_stop = self.pending.pop(0)
self.latest = {}
self._native_unavailable = False
try:
@@ -82,7 +82,9 @@ class DshAutomation(QObject):
view.diagnosis_event.connect(self._diagnosis_event)
view.stopped.connect(self._runtime_stopped)
self._connected_view = view
stop = StopControl()
# Carry the original run's stop/force intent through the asynchronous
# handoff, including pauses requested after enqueue but before drain.
stop = original_stop if original_stop is not None else StopControl()
# The same worker gate reserves the mutation lane throughout diagnosis.
w._batch_stop = stop
w._active_quick_run_task_id = task_id
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
import codecs
from pathlib import Path
from PySide6.QtCore import QProcess, QProcessEnvironment, QTimer, QUrl, Signal
@@ -43,7 +44,7 @@ class NativeHarnessView(QWidget):
self._diagnosis_queue = []
self._pending_context = None
self._context_attempts = 0
self._buffer = ''
self._reset_output()
self._started = False
self._stopping = False
self.last_error = ''
@@ -116,6 +117,7 @@ class NativeHarnessView(QWidget):
def start(self):
if self.is_running:
return
self._reset_output()
if self.context is None and self._pending_context is None:
self.bind(TaskSnapshot('', 'observe'))
root = integration_root()
@@ -124,7 +126,6 @@ class NativeHarnessView(QWidget):
return
self._stopping = False
self._started = False
self._buffer = ''
self.status.setText('正在加载 DeepSeek Harness 官方界面…')
self.status.show()
self.retry.hide()
@@ -143,8 +144,13 @@ class NativeHarnessView(QWidget):
self.process.start()
self.timeout.start(60000)
def _reset_output(self):
self._buffer = ''
self._stdout_decoder = codecs.getincrementaldecoder('utf8')('replace')
self._stderr_decoder = codecs.getincrementaldecoder('utf8')('replace')
def _stdout(self):
self._buffer += bytes(self.process.readAllStandardOutput()).decode('utf8', 'replace')
self._buffer += self._stdout_decoder.decode(bytes(self.process.readAllStandardOutput()))
lines = self._buffer.split('\n')
self._buffer = lines.pop()
for line in lines:
@@ -175,7 +181,7 @@ class NativeHarnessView(QWidget):
self.action_requested.emit(request)
def _stderr(self):
self.last_error = (self.last_error + bytes(self.process.readAllStandardError()).decode('utf8', 'replace'))[-12000:]
self.last_error = (self.last_error + self._stderr_decoder.decode(bytes(self.process.readAllStandardError())))[-12000:]
def _failed(self, text):
if self._stopping or not isValid(self.status):
@@ -43,6 +43,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._dsh_stopping = False
self._dsh_automation = None
self._dsh_run_id = 'observation'
self._dsh_run_stop = None
self._dsh_authorized_tasks = set()
self.task_center_action = QAction('任务中心', self)
self.task_center_action.triggered.connect(lambda: self.content_stack.setCurrentIndex(0))
@@ -700,6 +701,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
from uuid import uuid4
self._dsh_run_id = uuid4().hex
self._batch_stop = StopControl()
self._dsh_run_stop = self._batch_stop
self._active_quick_run_task_id = task_id
self._run_started_at = time.time()
self._quick_run_elapsed.start()
@@ -708,6 +710,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._message = ''
def _finish_run(self):
# Completion may report paused=False after the final failed item.
# Keep the original stop/force object for incidents from this run;
# only a newly authorized _begin_run replaces it with a fresh control.
if self._batch_stop is not None:
self._dsh_run_stop = self._batch_stop
self._quick_run_timer.stop()
self._feedback_query.invalidate()
self._active_quick_run_task_id = None
@@ -1117,4 +1124,5 @@ class TrialTaskCenterWindow(MaterialMainWindow):
from .dsh_automation import DshAutomation
self._dsh_automation = DshAutomation(self)
return self._dsh_automation.enqueue(task_id, issue_code, message,
execution_authorized=task_id in self._dsh_authorized_tasks, run_id=self._dsh_run_id)
execution_authorized=task_id in self._dsh_authorized_tasks, run_id=self._dsh_run_id,
stop_event=self._batch_stop if self._batch_stop is not None else self._dsh_run_stop)
+194
View File
@@ -0,0 +1,194 @@
"""Exercise PR #10 review boundaries through the real service and protocol parser."""
import json
from pathlib import Path
import subprocess
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QMessageBox,QWidget
@pytest.mark.parametrize('scope',['single','batch'])
@pytest.mark.parametrize('stop_kind',['none','pause','force','pause_then_reauthorize'])
def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monkeypatch,scope,stop_kind):
from dx_productivity.trial_task_center.ui import dsh_automation
window=ui.window;task=ui.tasks[0]
window._tasks=(task,)
window._quick_run_confirmer=lambda *args:True
window._update_gates()
calls=[];outcomes=[];controls=[]
def executor(command,timeout):
calls.append(command[-1])
if len(calls)==1:
controls.append(window._batch_stop)
if stop_kind in {'pause','pause_then_reauthorize'}:window._pause_queue()
elif stop_kind=='force':window._force_batch_stop()
failure_count=2 if stop_kind=='pause_then_reauthorize'else 1
state='batch_failed'if len(calls)<=failure_count else'no_match'
with (Path(command[3])/'status.tsv').open('a',encoding='utf8')as stream:
stream.write(f'{command[-1]}\t{state}\tbatch_closed\tControlled result\n')
return subprocess.CompletedProcess(command,0,'','')
# Keep the real service, queue, persistence, IncidentRunner and Qt handoff;
# replace only external CAD/model/issue transports and background dispatch.
monkeypatch.setattr(ui.service.for_project_task(task.task_id)._quick_run_preparer,'_process_runner',executor)
monkeypatch.setattr(QMessageBox,'question',lambda *args:QMessageBox.StandardButton.Yes)
def dispatch(operation,callback,*args,**kwargs):
result=operation();outcomes.append(result);callback(result)
monkeypatch.setattr(window,'_run_async',dispatch)
monkeypatch.setattr(window,'_open_dsh',lambda:None)
automation=dsh_automation.DshAutomation(window)
window._dsh_automation=automation
monkeypatch.setattr(dsh_automation.QApplication,'platformName',lambda:'review-test')
monkeypatch.setattr(automation,'_analyze',lambda *args:{'reply':json.dumps({'summary':'Retry suggestion','action':'retry_failed'})})
monkeypatch.setattr(dsh_automation,'GitIssuePublisher',lambda *args:lambda *args:{'status':'unavailable'})
if scope=='single':window._prepare_quick_run()
else:window._execute_project_tasks()
assert len(outcomes)==1
# This is the review's edge: the queue is exhausted, so paused is False
# even though the original control may carry a stop/force request.
assert outcomes[0].paused is False
qtbot.waitUntil(lambda:automation.worker is None and
automation.latest.get('status')in {'resolved','pending_issue','escalated'},timeout=10000)
ui.settle()
record=automation.latest
assert len(calls)==(2 if stop_kind=='none'else 1)
assert record['gates']['not_stopped']is (stop_kind=='none')
assert record['attempts']==(1 if stop_kind=='none'else 0)
if stop_kind=='force':assert controls[0].force_event.is_set()
if stop_kind!='none':
assert controls[0].is_set()
assert not list((ui.data/'dsh/retry-budget').glob('*.json'))
if stop_kind=='pause_then_reauthorize':
original_run=record['run_id']
window._retry_failed();ui.settle()
window._tasks=(ui.service.get_task(task.task_id),)
window._update_gates()
if scope=='single':window._prepare_quick_run()
else:window._execute_project_tasks()
qtbot.waitUntil(lambda:automation.worker is None and
automation.latest.get('run_id')!=original_run and
automation.latest.get('status')=='resolved',timeout=10000)
ui.settle()
assert len(calls)==3
assert automation.latest['gates']['not_stopped']
assert controls[0].is_set() # New authorization never clears old intent.
class ProtocolSignals(QWidget):
task_creation_requested=Signal(object)
diagnosis_event=Signal(object)
task_creation_cancelled=Signal(object)
action_requested=Signal(object)
def protocol_state(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
sink=ProtocolSignals();qtbot.addWidget(sink)
chunks=[]
state=SimpleNamespace(_signal_owner=sink,
process=SimpleNamespace(readAllStandardOutput=lambda:chunks.pop(0)),
task_creation_requested=sink.task_creation_requested,diagnosis_event=sink.diagnosis_event,
task_creation_cancelled=sink.task_creation_cancelled,action_requested=sink.action_requested,
context={'task_id':'t','revision':'rev'},last_error='')
state._reset_output=lambda:NativeHarnessView._reset_output(state)
state._reset_output()
return state,chunks
@pytest.mark.parametrize('stop_kind',['none','pause','force'])
def test_worker_exception_handoff_keeps_original_run_control(ui,qtbot,monkeypatch,stop_kind):
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_authorized_tasks.add(task_id)
window._begin_run(task_id)
control=window._batch_stop;run_id=window._dsh_run_id
started,release=Event(),Event()
def fail():
started.set()
assert release.wait(5)
raise TaskCenterError('worker_error','Controlled final-step failure')
monkeypatch.setattr(QMessageBox,'question',lambda *args:QMessageBox.StandardButton.Yes)
try:
window._run_async(fail,lambda _:None,expected_task_id=task_id)
qtbot.waitUntil(started.is_set)
if stop_kind=='pause':window._pause_queue()
elif stop_kind=='force':window._force_batch_stop()
finally:
release.set()
ui.settle()
assert len(captured)==1
assert captured[0]['stop_event'] is control
assert captured[0]['stop_event'].is_set()is (stop_kind!='none')
assert captured[0]['execution_authorized']
assert captured[0]['run_id']==run_id
def test_protocol_preserves_utf8_at_every_byte_boundary(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
received=[];state.task_creation_requested.connect(received.append)
payload={'request_id':'a'*32,'spec':{'name':'电阻替换🔧','directory_hint':'C:/工程/主板',
'rules':[{'old_part_number':'旧料号','new_part_number':'新料号','custom_value':'电容值μF'}]}}
line=('DX_DSH_CREATE_REQUEST '+json.dumps(payload,ensure_ascii=False)+'\n').encode('utf8')
# Includes splits inside each Chinese character, the emoji and JSON syntax.
for split in range(1,len(line)):
chunks.append(line[:split]);NativeHarnessView._stdout(state)
chunks.append(line[split:]);NativeHarnessView._stdout(state)
assert received[-1]==payload
assert len(received)==len(line)-1
def test_protocol_preserves_multiple_event_lines_in_single_byte_chunks(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
received=[];state.diagnosis_event.connect(received.append)
values=[{'reply':'诊断结论:电阻值正常'},{'reply':'复盘:无需替换'}]
stream=''.join('DX_DSH_DIAGNOSIS '+json.dumps(v,ensure_ascii=False)+'\n'for v in values).encode('utf8')
for byte in stream:
chunks.append(bytes([byte]));NativeHarnessView._stdout(state)
assert received==values
def test_runtime_restart_discards_partial_protocol_and_utf8_characters(qtbot,tmp_path,monkeypatch):
from dx_productivity.trial_task_center.ui import dsh_native
state,chunks=protocol_state(qtbot)
received=[];state.task_creation_requested.connect(received.append)
old=('DX_DSH_CREATE_REQUEST '+json.dumps({'name':'旧请求'},ensure_ascii=False)+'\n').encode('utf8')
chunks.append(old[:old.index('旧'.encode('utf8'))+1]);dsh_native.NativeHarnessView._stdout(state)
assert not received
state.process.readAllStandardError=lambda:'电'.encode('utf8')[:1]
dsh_native.NativeHarnessView._stderr(state)
for method in ('setProcessEnvironment','setWorkingDirectory','setProgram','setArguments','start'):
setattr(state.process,method,lambda *args:None)
state.is_running=False
state.data_root=tmp_path
state.status=SimpleNamespace(setText=lambda *args:None,show=lambda:None)
state.retry=SimpleNamespace(hide=lambda:None)
state.timeout=SimpleNamespace(start=lambda *args:None)
package=tmp_path/'node_modules/@deepseek-ai/dsh/package.json'
package.parent.mkdir(parents=True);package.write_text('{}')
monkeypatch.setattr(dsh_native,'integration_root',lambda:tmp_path)
monkeypatch.setattr(dsh_native,'node_executable',lambda:'test-node')
monkeypatch.setattr(dsh_native,'launch_environment',lambda *args:{})
dsh_native.NativeHarnessView.start(state)
new={'name':'新请求'}
chunks.append(('DX_DSH_CREATE_REQUEST '+json.dumps(new,ensure_ascii=False)+'\n').encode('utf8'))
dsh_native.NativeHarnessView._stdout(state)
assert received==[new]
state.process.readAllStandardError=lambda:'正常'.encode('utf8')
dsh_native.NativeHarnessView._stderr(state)
assert state.last_error=='正常'
def test_stderr_preserves_utf8_across_process_chunks(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
state.process.readAllStandardError=lambda:chunks.pop(0)
message='运行时诊断:电阻替换🔧'
for byte in message.encode('utf8'):
chunks.append(bytes([byte]));NativeHarnessView._stderr(state)
assert state.last_error==message