Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba69f86628 | ||
|
|
46deb9cec8 | ||
|
|
488bf027cc |
No files matched your search
@@ -49,8 +49,9 @@ jobs:
|
||||
npm install --prefix /opt/ci-node --no-audit --no-fund node@24.11.1
|
||||
node --version
|
||||
npm ci --prefix integration/dsh --no-audit --no-fund
|
||||
- name: Read-only model availability (real Harness, no remote model calls)
|
||||
- name: Runtime and model availability (real Harness, no remote model calls)
|
||||
run: |
|
||||
node tools/verify_dsh_runtime.mjs
|
||||
node tools/verify_dsh_model_availability.mjs
|
||||
node --test tests/integration/test_dsh_standard_compat.mjs
|
||||
node tools/verify_dsh_incident_restart.mjs
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Issue 33 D5 · BOM 未知列验收
|
||||
|
||||
现场 B3 的 `INVALID_C1_bad_header_extra_col.xlsx` 带有 `extra_column`。名称归一化将未知列映射为空,后续只复制模板定义的列。导入成功时,工作区原先只报告保存行数与失败行数。
|
||||
|
||||
现在 BOM 导入保留模板列的精确映射,并为每个被忽略的具名列显示来源文件、原始列名与警告计数。详情和任务事件同时记录这些警告。缺失必需列时,导入停止,错误详情列出具体缺失项并对相近列名给出改名建议。
|
||||
|
||||
## Windows 11 重放
|
||||
|
||||
通过 Qt 工作区的“导入 BOM”按钮和真实任务服务运行,测试替换的是文件选择对话框的返回值。现场文件复制到临时目录,仅把第一条记录的工程名称与路径绑定到临时工程,保留了原始表头和替换字段。
|
||||
|
||||
| 工作簿 | 结果 |
|
||||
| --- | --- |
|
||||
| 两个额外列「供应商」「备注」 | 保存 1 行、失败 0 行、警告 2 项。详情逐列列名,任务事件记录同一组警告 |
|
||||
| 现场 B3 `extra_column` | 保存 1 行、失败 0 行、警告 1 项。详情保留该列名 |
|
||||
| 用「新料号编码」替换必需的「新料号」 | 指出缺少「新料号」,并建议将「新料号编码」改为「新料号」 |
|
||||
| 缺少「新料号」 | 指出具体缺失项 |
|
||||
| 表头公式与额外列中的数据公式 | 分别拒绝表头公式和第 2 行公式 |
|
||||
| 原模板 | 保存 1 行、失败 0 行,无警告 |
|
||||
|
||||
BOM 草稿导入时未启动工程位号采集。回归还检查了由监督子进程返回的真实预览报告能携带同样的警告。包含现场工作簿重放的定向回归共通过 110 项。
|
||||
|
||||
## 复跑
|
||||
|
||||
在仓库根目录运行。现场文件从工单附件 `05_实测证据/paper2_bom` 解出。普通回归可省略 `DX_ISSUE33_D5_FIELD`,此时跳过现场文件重放。
|
||||
|
||||
```powershell
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:PYTHONPATH = (Resolve-Path src).Path
|
||||
$env:DX_ISSUE33_D5_FIELD = 'C:/path/to/INVALID_C1_bad_header_extra_col.xlsx'
|
||||
python -m pytest -q -s tests/v1_1/test_bom_header_feedback.py tests/v1_1/test_bom_import_report.py tests/v1_1/test_bom_pending.py tests/v1_1/test_bom_sources_supervision.py tests/trial_task_center/test_bom_import_review.py tests/trial_task_center/test_item_value_and_bom_sources.py
|
||||
```
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
主工具顶部固定显示左右两个入口:左侧 **任务中心**,右侧 **DSH助手**,单击直接切换,无需展开菜单。助手也可按 `Ctrl+Shift+D` 打开;切回任务中心再进入助手时保留同一个网页、会话和未发送草稿。右侧“任务监管”读取主工具当前选中的任务。
|
||||
|
||||
这里直接运行 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的官方前端与运行时,固定 npm 版本 `0.2.1-rc.5`,通过 Qt WebEngine 嵌入主窗口。官方三栏框架、原生 SVG、鲸鱼悬停动画、输入编辑器、模型选择、侧栏与停靠交互均由上游代码提供。项目增加任务监管插件和“DSH助手”名称,不再使用 Qt 控件重画聊天页面。上游许可见 `licenses/DeepSeek-Harness-MIT.txt`。
|
||||
这里直接运行 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的官方前端与运行时,通过 Qt WebEngine 嵌入主窗口。当前 npm 版本以 `integration/dsh/package.json` 为准。官方三栏框架、原生 SVG、鲸鱼悬停动画、输入编辑器、模型选择、侧栏与停靠交互均由上游代码提供。项目增加任务监管插件和“DSH助手”名称,不再使用 Qt 控件重画聊天页面。上游许可见 `licenses/DeepSeek-Harness-MIT.txt`。
|
||||
|
||||
不显示上游账户登录、注册、充值和首次产品引导,也不注册其账户模型提供方。左下角 **工具设置** 单击打开原生设置页,包含“DSH工具”“通用设置”和“模型”;首页提示和任务监管面板围绕器件替换任务。输入框下方选择已配置的模型。
|
||||
|
||||
@@ -178,6 +178,14 @@ node tools/verify_dsh_runtime.mjs
|
||||
python tools/accept_dsh_desktop.py
|
||||
```
|
||||
|
||||
源码工作区可从 npm 更新 DSH。先退出任务中心,运行更新命令,再重新打开任务中心。
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File tools/Install-DshRuntime.ps1 -Version latest
|
||||
```
|
||||
|
||||
将 `latest` 换成 `0.2.2-rc.5` 这样的完整版本号即可安装指定版本。脚本先在临时目录启动候选运行时并验证任务插件,通过后更新依赖声明、锁文件和实际依赖。更新成功时会打印 `build/dsh-update-…` 路径,其中 `previous` 保存旧运行时,`verification/report.json` 记录验收结果。便携版随应用打包 DSH,通过重新构建的应用发行包更新。
|
||||
|
||||
CLI 验证启动真实官方内核,检查工具与 preset 名单,实际读取快照、执行禁止工具探针,并测试本机请求认证、跨任务与过期动作边界。桌面验收启动真实主工具,用 Qt 鼠标事件单击左右导航,用 Chromium Input 事件操作官方页面,核对全新数据下无账户或引导弹窗、工具设置、任务刷新、会话、侧栏、SVG 动画、模型选择、草稿保留、取消确认和正常退出。验收只使用独立测试数据,不启动 CAD 或修改用户工程;未配置模型的验收不计为真实模型回复验证。
|
||||
|
||||
已配置本机模型时,可执行真实 API 桌面验收:
|
||||
|
||||
Generated
+4138
-3271
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,15 @@
|
||||
"name": "dxdesigner-dsh-runtime",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {"doctor": "node start.mjs --doctor", "start": "node start.mjs"},
|
||||
"engines": {"node": ">=24.9.0"},
|
||||
"dependencies": {"@deepseek-ai/dsh": "0.2.1-rc.5", "fflate": "0.8.3"}
|
||||
"scripts": {
|
||||
"doctor": "node start.mjs --doctor",
|
||||
"start": "node start.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.9.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh": "0.2.2-rc.5",
|
||||
"fflate": "0.8.3"
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export const FILE_TOOLS=['read','read_image','write','edit','glob','grep','worki
|
||||
|
||||
const root = path.dirname(fileURLToPath(import.meta.url));
|
||||
const require = createRequire(import.meta.url);
|
||||
export const VERSION = '0.2.1-rc.5';
|
||||
export const VERSION = require('./package.json').dependencies['@deepseek-ai/dsh'];
|
||||
export const DISABLED = [
|
||||
'desktop-product-telemetry','product-analytics','session-telemetry-otel',
|
||||
];
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
DeepSeek Harness native frontend and runtime
|
||||
Pinned release: @deepseek-ai/dsh 0.2.1-rc.5
|
||||
Package: @deepseek-ai/dsh
|
||||
Source: https://github.com/deepseek-ai/deepseek-harness
|
||||
|
||||
MIT License
|
||||
|
||||
@@ -12,9 +12,6 @@ from uuid import uuid4
|
||||
from .snapshot import TaskSnapshot
|
||||
from ..trial_task_center.path_access import retry_sharing_violation
|
||||
|
||||
HARNESS_VERSION = '0.2.1-rc.5'
|
||||
|
||||
|
||||
def integration_root() -> Path:
|
||||
if getattr(sys, 'frozen', False):
|
||||
return Path(sys._MEIPASS) / 'dsh-runtime'
|
||||
|
||||
@@ -48,6 +48,7 @@ class BomImportReport:
|
||||
source_map_path: Path | None = None
|
||||
passed_preview: BomBatchPreview | None = None
|
||||
deferred: bool = False
|
||||
warnings: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def total_rows(self):
|
||||
|
||||
@@ -77,7 +77,9 @@ def resolution_binding(store, task_id):
|
||||
|
||||
def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
|
||||
"""Persist routed spreadsheet requests without opening CAD or resolving parts."""
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, allow_partial=allow_partial)
|
||||
warnings = []
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
|
||||
allow_partial=allow_partial, warnings=warnings)
|
||||
scope = _scope(service._store, task_id)
|
||||
paths = tuple(project.path for _, project in scope)
|
||||
names = {project.path: task.name for task, project in scope}
|
||||
@@ -93,7 +95,8 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
|
||||
write_routed_bom(normalized, rows, routes, project_names=names)
|
||||
append_task_event(service._logging, level='INFO', task_id=task_id,
|
||||
operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验',
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
|
||||
'warnings': warnings})
|
||||
try:
|
||||
report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress,
|
||||
on_phase=on_phase, spreadsheet_only=True, allow_partial=allow_partial)
|
||||
@@ -110,7 +113,7 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
|
||||
if report.deferred and result.project_path not in failed_paths:
|
||||
reason = '表格已保存,执行前核验工程位号'
|
||||
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason))
|
||||
report = replace(report, rows=tuple(annotated), source_map_path=mapping)
|
||||
report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
|
||||
if report.deferred:
|
||||
accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True)
|
||||
if result.project_path not in failed_paths)
|
||||
|
||||
@@ -245,7 +245,8 @@ class TaskCenterService:
|
||||
on_phase(BomImportPhase.READING, message)
|
||||
if on_progress is not None:
|
||||
on_progress(message)
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
|
||||
warnings = []
|
||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, warnings=warnings,
|
||||
**({'allow_partial': True} if allow_partial else {}))
|
||||
scope = _scope(self._store, task_id)
|
||||
paths = tuple(project.path for _, project in scope)
|
||||
@@ -278,7 +279,7 @@ class TaskCenterService:
|
||||
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
|
||||
annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row,
|
||||
reason=reason + f';来源:{source.source} 第 {source.excel_row} 行'))
|
||||
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping)
|
||||
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
|
||||
return bind_source_report(annotated_report,
|
||||
tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping)
|
||||
|
||||
@@ -290,7 +291,8 @@ class TaskCenterService:
|
||||
write_routed_bom(normalized, rows, routes, project_names=names)
|
||||
append_task_event(self._logging, level='INFO', task_id=task_id,
|
||||
operation='preview_bom_sources', message='BOM 导入来源记录已保存',
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
|
||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
|
||||
'warnings': warnings})
|
||||
report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
|
||||
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime,
|
||||
**({'allow_partial': True} if allow_partial else {}))
|
||||
|
||||
@@ -779,21 +779,22 @@ class ProjectPlanPanel(QWidget):
|
||||
report = state.report
|
||||
if report is None:
|
||||
return '', '', ''
|
||||
warning_summary = f' · 警告 {len(report.warnings)} 项' if report.warnings else ''
|
||||
if report.deferred:
|
||||
failed_paths = {row.project_path for row in report.rows if row.status == 'failed'}
|
||||
accepted = tuple(row for row in report.rows if row.project_path not in failed_paths)
|
||||
summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、'
|
||||
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行。')
|
||||
details = [summary, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
|
||||
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行{warning_summary}。')
|
||||
details = [summary, *report.warnings, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
|
||||
details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}'
|
||||
for row in report.rows)
|
||||
return summary, '\n'.join(details), 'BOM 已保存 · 待核验 · 详情'
|
||||
return summary, '\n'.join(details), f'BOM 已保存 · 待核验{warning_summary} · 详情'
|
||||
outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过'
|
||||
summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、'
|
||||
f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;'
|
||||
f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、'
|
||||
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个。')
|
||||
details = [summary, *report.errors]
|
||||
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个{warning_summary}。')
|
||||
details = [summary, *report.errors, *report.warnings]
|
||||
if report.source_map_path is not None:
|
||||
details.append(f'导入来源记录:{report.source_map_path}')
|
||||
details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}'
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""Safe multi-file BOM loading and project routing for workspace imports."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from difflib import get_close_matches
|
||||
import hashlib
|
||||
from pathlib import Path, PureWindowsPath
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .bom_import_report import BomImportReport, BomInspectionError
|
||||
from .bom_plan import BOM_HEADERS, _normal_headers, _part_number_text, write_bom_template
|
||||
from .errors import TaskCenterError
|
||||
|
||||
@@ -55,7 +57,37 @@ def _selected_xlsx(sources):
|
||||
return tuple(sorted(paths, key=lambda path: str(path).casefold()))
|
||||
|
||||
|
||||
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False):
|
||||
_REQUIRED_HEADERS = (
|
||||
('old_part_number', '旧料号'), ('new_part_number', '新料号'), ('refdes', '位号'),
|
||||
)
|
||||
|
||||
|
||||
def _source_headers(path, cells):
|
||||
headers = _normal_headers(tuple(cell.value for cell in cells))
|
||||
names = tuple(name for name in headers if name)
|
||||
unknown = tuple(str(cell.value).strip() for cell, name in zip(cells, headers, strict=True)
|
||||
if not name and cell.value is not None and str(cell.value).strip())
|
||||
if any(cell.data_type == 'f' for cell in cells):
|
||||
reason = 'BOM 表头不接受公式'
|
||||
elif len(names) != len(set(names)):
|
||||
reason = 'BOM 列名重复'
|
||||
else:
|
||||
missing = [(name, label) for name, label in _REQUIRED_HEADERS if name not in names]
|
||||
if not missing:
|
||||
return {name: index for index, name in enumerate(headers) if name}, unknown
|
||||
labels = '、'.join(label for _, label in missing)
|
||||
hints = []
|
||||
for name, label in missing:
|
||||
matches = (get_close_matches(label, unknown, n=1, cutoff=.7)
|
||||
or get_close_matches(name, unknown, n=1, cutoff=.8))
|
||||
if matches:
|
||||
hints.append(f'请将「{matches[0]}」改为「{label}」')
|
||||
reason = '。'.join([f'BOM 缺少必需列「{labels}」', *hints])
|
||||
message = f'{path.name} 第 1 行:{reason}'
|
||||
raise BomInspectionError(TaskCenterError('bom_import', message), BomImportReport((), (), errors=(message,)))
|
||||
|
||||
|
||||
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False, warnings=None):
|
||||
"""Read every selected workbook before any CAD operation starts."""
|
||||
from .operation_control import check_cancelled
|
||||
|
||||
@@ -74,17 +106,7 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
|
||||
if len(workbook.worksheets) != 1:
|
||||
raise ValueError('BOM 只能包含一个工作表')
|
||||
rows = iter(workbook.active.iter_rows())
|
||||
header_cells = next(rows, ())
|
||||
headers = _normal_headers(tuple(cell.value for cell in header_cells))
|
||||
names = tuple(name for name in headers if name)
|
||||
if len(names) != len(set(names)):
|
||||
raise ValueError('BOM 列名重复')
|
||||
required = {'old_part_number', 'new_part_number', 'refdes'}
|
||||
if not required <= set(names):
|
||||
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
|
||||
if any(cell.data_type == 'f' for cell in header_cells):
|
||||
raise ValueError('BOM 表头不接受公式')
|
||||
positions = {name: index for index, name in enumerate(headers) if name}
|
||||
positions, unknown = _source_headers(path, next(rows, ()))
|
||||
for excel_row, cells in enumerate(rows, 2):
|
||||
check_cancelled(stop_event)
|
||||
formula = any(cell.data_type == 'f' for cell in cells)
|
||||
@@ -116,6 +138,8 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
|
||||
result.append(SourceRow(path, excel_row, values, value_mode, source_sha256))
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256:
|
||||
raise ValueError('BOM 来源在读取期间已改变,请重新导入')
|
||||
if warnings is not None:
|
||||
warnings.extend(f'{path.name}:已忽略未知列「{name}」' for name in unknown)
|
||||
except TaskCenterError:
|
||||
raise
|
||||
except Exception as error:
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
|
||||
from test_bom_batch import batch, records_for
|
||||
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['extra', 'near', 'missing', 'header_formula', 'row_formula', 'original'])
|
||||
def test_bom_header_feedback_through_workspace(case, batch, tmp_path, qtbot, monkeypatch):
|
||||
service, _, tasks, targets, inventory_calls = batch
|
||||
task = tasks[0]
|
||||
record = records_for(tasks, targets)[0]
|
||||
source = write_bom_template(tmp_path / f'{case}.xlsx', [record])
|
||||
workbook = load_workbook(source)
|
||||
sheet = workbook.active
|
||||
if case == 'extra':
|
||||
sheet['L1'], sheet['L2'] = '供应商', 'Example supplier'
|
||||
sheet['M1'], sheet['M2'] = '备注', 'Example note'
|
||||
elif case == 'near':
|
||||
sheet['D1'] = '新料号编码'
|
||||
elif case == 'missing':
|
||||
sheet['D1'] = None
|
||||
elif case == 'header_formula':
|
||||
sheet['L1'] = '=1+1'
|
||||
elif case == 'row_formula':
|
||||
sheet['L1'], sheet['L2'] = '备注', '=1+1'
|
||||
workbook.save(source)
|
||||
workbook.close()
|
||||
assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch)
|
||||
|
||||
|
||||
def test_field_extra_column_through_workspace(batch, tmp_path, qtbot, monkeypatch):
|
||||
field = os.environ.get('DX_ISSUE33_D5_FIELD')
|
||||
if not field:
|
||||
pytest.skip('set DX_ISSUE33_D5_FIELD to replay the field attachment')
|
||||
service, _, tasks, targets, inventory_calls = batch
|
||||
source = tmp_path / Path(field).name
|
||||
workbook = load_workbook(field)
|
||||
sheet = workbook.active
|
||||
# Rebind to the local fixture project. Keep the original Excel header and BOM cells.
|
||||
sheet['A2'] = tasks[0].name
|
||||
sheet['B2'] = str(targets[tasks[0].task_id][0].project_path)
|
||||
workbook.save(source)
|
||||
workbook.close()
|
||||
assert_workspace_import('field', source, tasks[0], service, inventory_calls, qtbot, monkeypatch)
|
||||
|
||||
|
||||
def assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch):
|
||||
window = TrialTaskCenterWindow(service)
|
||||
window.auto_intervention_check.setChecked(False)
|
||||
qtbot.addWidget(window)
|
||||
window.open_task(task.task_id)
|
||||
panel = window.plan_panel
|
||||
qtbot.waitUntil(panel.import_bom_button.isEnabled, timeout=5000)
|
||||
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([str(source)], 'Excel (*.xlsx)'))
|
||||
panel.import_bom_button.click()
|
||||
qtbot.waitUntil(lambda: not window._workers, timeout=8000)
|
||||
status = window.run_panel.operator_band.text()
|
||||
print(status)
|
||||
pending = service.pending_bom(task.task_id)
|
||||
assert not inventory_calls
|
||||
if case in {'extra', 'field', 'original', 'near', 'missing', 'header_formula'}:
|
||||
panel.report_toggle.setChecked(True)
|
||||
assert panel.report_dialog is not None
|
||||
details = panel.report_dialog.view.toPlainText()
|
||||
print(details)
|
||||
if case in {'extra', 'field', 'original'}:
|
||||
assert len(pending) == 1
|
||||
assert panel.last_bom_report.failed_rows == 0 and panel.last_bom_report.deferred
|
||||
if case == 'extra':
|
||||
assert '失败 0 行' in status and '警告 2 项' in status
|
||||
assert all(text in details for text in ('已忽略', '供应商', '备注', source.name))
|
||||
assert pending[0].record.new == 'NEW-0'
|
||||
events = (service._logging.root / 'tasks' / task.task_id / 'events.jsonl').read_text(encoding='utf-8')
|
||||
entries = [json.loads(line) for line in events.splitlines()]
|
||||
entry = next(event for event in entries if event['operation'] == 'import_bom_drafts')
|
||||
assert tuple(entry['details']['warnings']) == panel.last_bom_report.warnings
|
||||
elif case == 'field':
|
||||
assert '警告 1 项' in status and 'extra_column' in details
|
||||
else:
|
||||
assert '警告' not in status and '已忽略' not in details
|
||||
else:
|
||||
assert not pending
|
||||
if case == 'near':
|
||||
assert '缺少必需列「新料号」' in status
|
||||
assert '「新料号编码」' in details and '改为「新料号」' in details
|
||||
elif case == 'missing':
|
||||
assert '缺少必需列「新料号」' in status and '新料号' in details
|
||||
elif case == 'header_formula':
|
||||
assert 'BOM 表头不接受公式' in status and 'BOM 表头不接受公式' in details
|
||||
else:
|
||||
assert '第 2 行不接受公式' in status
|
||||
window.close()
|
||||
@@ -9,6 +9,8 @@ from test_bom_batch import batch
|
||||
|
||||
|
||||
def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tmp_path):
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
||||
service, store, tasks, targets, calls = batch
|
||||
for task in tasks:
|
||||
@@ -17,9 +19,14 @@ def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tm
|
||||
'project_name': task.name, 'project_path': str(targets[task.task_id][0].project_path),
|
||||
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number',
|
||||
},)) for index, task in enumerate(tasks))
|
||||
workbook = load_workbook(sources[0])
|
||||
workbook.active['M1'] = '备注'
|
||||
workbook.save(sources[0])
|
||||
workbook.close()
|
||||
service._supervised = True
|
||||
report = service.preview_bom_sources(tasks[0].task_id, sources)
|
||||
assert report.passed_rows == 2 and report.preview is not None
|
||||
assert report.warnings == ('source-0.xlsx:已忽略未知列「备注」',)
|
||||
assert tuple(row.source_file for row in report.rows) == tuple(str(path.resolve()) for path in sources)
|
||||
assert all(row.source_row == 2 for row in report.rows)
|
||||
assert report.source_map_path.is_file()
|
||||
|
||||
@@ -1,14 +1,74 @@
|
||||
param()
|
||||
param(
|
||||
[string]$Version
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$dshRepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$dshRuntimeRoot = Join-Path $dshRepoRoot 'integration/dsh'
|
||||
$dshNodeCommand = Get-Command node -ErrorAction Stop
|
||||
$dshNodeVersion = & $dshNodeCommand.Source -p 'process.versions.node'
|
||||
if ([version]$dshNodeVersion -lt [version]'24.9.0') { throw 'DSH requires Node.js 24.9.0 or later.' }
|
||||
Push-Location -LiteralPath $dshRuntimeRoot
|
||||
$dshNpm = (Get-Command npm.cmd -ErrorAction Stop).Source
|
||||
$dshRegistry = 'https://registry.npmjs.org/'
|
||||
|
||||
$dshBuild = Join-Path $dshRepoRoot 'build'
|
||||
New-Item -ItemType Directory -Path $dshBuild -Force | Out-Null
|
||||
$dshInstallLock = [IO.File]::Open((Join-Path $dshBuild 'dsh-install.lock'), 'OpenOrCreate', 'ReadWrite', 'None')
|
||||
try {
|
||||
& npm.cmd ci --ignore-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { throw 'DSH installation failed.' }
|
||||
& $dshNodeCommand.Source start.mjs --doctor
|
||||
if ($LASTEXITCODE -ne 0) { throw 'DSH runtime verification failed.' }
|
||||
} finally { Pop-Location }
|
||||
if (-not $Version) {
|
||||
& $dshNpm --prefix $dshRuntimeRoot ci --ignore-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { throw 'DSH installation failed.' }
|
||||
& $dshNodeCommand.Source (Join-Path $dshRuntimeRoot 'start.mjs') --doctor
|
||||
if ($LASTEXITCODE -ne 0) { throw 'DSH runtime verification failed.' }
|
||||
return
|
||||
}
|
||||
|
||||
if ($Version -cnotmatch '\A(?:latest|\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\z') {
|
||||
throw 'Use latest or an exact version, for example 0.2.2-rc.5.'
|
||||
}
|
||||
|
||||
# Keep the candidate and previous installation on the same volume for rename.
|
||||
$dshStage = Join-Path $dshBuild ('dsh-update-' + [Guid]::NewGuid().ToString('N'))
|
||||
$dshCandidate = Join-Path $dshStage 'candidate'
|
||||
$dshPrevious = Join-Path $dshStage 'previous'
|
||||
$dshEntries = @('package.json', 'package-lock.json', 'node_modules')
|
||||
$dshBackedUp = @()
|
||||
$dshPublished = @()
|
||||
New-Item -ItemType Directory -Path $dshCandidate, $dshPrevious -Force | Out-Null
|
||||
try {
|
||||
Copy-Item -LiteralPath @(
|
||||
(Join-Path $dshRuntimeRoot 'package.json')
|
||||
(Join-Path $dshRuntimeRoot 'package-lock.json')
|
||||
(Join-Path $dshRuntimeRoot 'start.mjs')
|
||||
(Join-Path $dshRuntimeRoot 'task-plugin')
|
||||
) -Destination $dshCandidate -Recurse
|
||||
& $dshNpm --prefix $dshCandidate install --save-exact --ignore-scripts --no-audit --no-fund --registry=$dshRegistry "@deepseek-ai/dsh@$Version"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'DSH candidate installation failed.' }
|
||||
& $dshNodeCommand.Source (Join-Path $PSScriptRoot 'verify_dsh_runtime.mjs') $dshCandidate (Join-Path $dshStage 'verification')
|
||||
if ($LASTEXITCODE -ne 0) { throw 'DSH candidate failed the runtime check. The previous runtime is still available.' }
|
||||
|
||||
foreach ($dshEntry in $dshEntries) {
|
||||
$dshLive = Join-Path $dshRuntimeRoot $dshEntry
|
||||
if (Test-Path -LiteralPath $dshLive) {
|
||||
Move-Item -LiteralPath $dshLive -Destination (Join-Path $dshPrevious $dshEntry)
|
||||
$dshBackedUp += $dshEntry
|
||||
}
|
||||
Move-Item -LiteralPath (Join-Path $dshCandidate $dshEntry) -Destination $dshLive
|
||||
$dshPublished += $dshEntry
|
||||
}
|
||||
} catch {
|
||||
try {
|
||||
foreach ($dshEntry in $dshPublished) {
|
||||
Move-Item -LiteralPath (Join-Path $dshRuntimeRoot $dshEntry) -Destination (Join-Path $dshCandidate $dshEntry)
|
||||
}
|
||||
foreach ($dshEntry in $dshBackedUp) {
|
||||
Move-Item -LiteralPath (Join-Path $dshPrevious $dshEntry) -Destination (Join-Path $dshRuntimeRoot $dshEntry)
|
||||
}
|
||||
} catch {
|
||||
throw "DSH rollback failed. Previous files: $dshPrevious. $($_.Exception.Message)"
|
||||
}
|
||||
throw
|
||||
}
|
||||
Write-Output "DSH updated. Previous files and verification: $dshStage"
|
||||
} finally {
|
||||
$dshInstallLock.Dispose()
|
||||
}
|
||||
@@ -13,7 +13,8 @@ const {loadProfileDirectory,composeEntries}=await load('@deepseek-ai/dsh-app-boo
|
||||
const {runProfile,INSTALL_ANCHOR}=await load('@deepseek-ai/dsh/profile-boot');
|
||||
const {createLaunchEnvironmentSnapshot}=await load('@deepseek-ai/dsh-launch-environment');
|
||||
const installed=require('@deepseek-ai/dsh/package.json');
|
||||
if(installed.version!=='0.2.1-rc.5')throw Error('Runtime version mismatch');
|
||||
const expected=require('../package.json').dependencies['@deepseek-ai/dsh'];
|
||||
if(installed.version!==expected)throw Error('Runtime version mismatch');
|
||||
const original=loadProfileDirectory('paired-source',path.resolve(source),INSTALL_ANCHOR);
|
||||
const effective=composeEntries([...original.layers.map(layer=>layer.patches),original.patches]);
|
||||
// Copy effective routing/model/shell budgets, never credential values to reports.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** Check actual shell file access separately from model behavior. */
|
||||
import {executeTool} from './dsh_tool_probe.mjs';
|
||||
import {mkdir,mkdtemp,writeFile} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
@@ -17,7 +18,7 @@ try{
|
||||
const agent=ctx.agents.get(sessionId);
|
||||
const filename=path.join(process.env.DX_DSH_WORKSPACE,'input.txt');
|
||||
await writeFile(filename,'SHELL_FILE_READ_OK');
|
||||
const result=await ctx.tools.execute({agent,callId:crypto.randomUUID(),name:'pwsh',
|
||||
const result=await executeTool(ctx, {agent,callId:crypto.randomUUID(),name:'pwsh',
|
||||
arguments:{description:'Read the owned shell verification file',command:`[System.IO.File]::ReadAllText('${filename.replaceAll("'","''")}')`},signal:AbortSignal.timeout(30000)});
|
||||
console.log(JSON.stringify({root,result}));
|
||||
}finally{await shutdown.shutdown(0);}
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Run one tool through the installed Harness batch executor. */
|
||||
export async function executeTool(ctx, {callId, name, arguments: args, ...options}) {
|
||||
const {results} = await ctx.tools.execute({
|
||||
...options,
|
||||
calls: [{type: 'tool-call', id: callId, name, arguments: JSON.stringify(args ?? {})}],
|
||||
});
|
||||
return results[0].result;
|
||||
}
|
||||
@@ -1,13 +1,19 @@
|
||||
/** Real native Harness incident diagnosis; no engineering mutations or issue writes. */
|
||||
import {executeTool} from './dsh_tool_probe.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdir,writeFile} from 'node:fs/promises';
|
||||
import {mkdir,mkdtemp,writeFile} from 'node:fs/promises';
|
||||
import {createRequire} from 'node:module';
|
||||
import path from 'node:path';
|
||||
import {pathToFileURL} from 'node:url';
|
||||
import {bootRuntime} from '../integration/dsh/start.mjs';
|
||||
|
||||
const output=path.resolve('build/dsh-auto-runtime');
|
||||
await mkdir(output,{recursive:true});
|
||||
process.env.DX_DSH_HOME=path.join(output,'home');
|
||||
process.env.DX_DSH_CONTEXT_FILE=path.join(output,'context.json');
|
||||
const offline=process.argv.includes('--fixture');
|
||||
const fixture=offline?await mkdtemp(path.join(output,'run-')):output;
|
||||
if(offline)for(const key of ['DSH_API_KEY','DSH_API_BASE','DSH_MODEL','DX_DSH_MODELS'])delete process.env[key];
|
||||
process.env.DX_DSH_HOME=path.join(fixture,'home');
|
||||
process.env.DX_DSH_CONTEXT_FILE=path.join(fixture,'context.json');
|
||||
await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'different-current-task',revision:'other',status:'draft'}));
|
||||
const snapshot={task_id:'auto-failure-fixture',revision:'incident',status:'failed',issue_code:'worker_error',
|
||||
issue:'受控诊断验收:执行前 worker 失败,没有工程写入。',rules_count:1,progress:{failed_items:1,total:1,completed:0}};
|
||||
@@ -31,6 +37,27 @@ process.stdout.write=function(chunk,...args){
|
||||
};
|
||||
let timer;
|
||||
try{
|
||||
if(offline){
|
||||
const require=createRequire(new URL('../integration/dsh/start.mjs',import.meta.url));
|
||||
const {LlmAdapter}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-llm')).href);
|
||||
let snapshotRequested=false;
|
||||
class DiagnosticFixture extends LlmAdapter{
|
||||
providerInfo(provider){return {id:provider,name:'Auto runtime fixture'};}
|
||||
async listModels(provider){return [{provider,id:'fixture',name:'Fixture'}];}
|
||||
async *stream(options){
|
||||
const readSnapshot=options.purpose!=='session-title'&&!snapshotRequested;
|
||||
if(readSnapshot)snapshotRequested=true;
|
||||
const block=readSnapshot
|
||||
?{type:'tool-call',id:crypto.randomUUID(),name:'dx_task_snapshot',arguments:'{}'}
|
||||
:{type:'text',text:'Controlled diagnosis fixture. {"action":"none"}'};
|
||||
yield {type:'block-start',index:0,blockType:block.type};
|
||||
yield {type:'block-end',index:0,block};
|
||||
yield {type:'finish',reason:{kind:readSnapshot?'tool-calls':'stop'}};
|
||||
}
|
||||
}
|
||||
ctx.llm.registerAdapter(['auto-runtime-fixture'],new DiagnosticFixture());
|
||||
await ctx.agentDefaultModel.saveSelection({provider:'auto-runtime-fixture',model:'fixture'});
|
||||
}
|
||||
timer=setTimeout(()=>rejectResult(Error('native_auto_test_timeout')),135000);
|
||||
ctx.emit('dx/diagnose-request',{request_id:'cli-auto-request',incident_id:'0123456789abcdef01234567',
|
||||
phase:'diagnose',snapshot,evidence:JSON.stringify(snapshot)});
|
||||
@@ -38,7 +65,7 @@ try{
|
||||
const previousParent=process.env.DX_DSH_PARENT_PIPE;
|
||||
process.env.DX_DSH_PARENT_PIPE='1';
|
||||
try{
|
||||
const denial=await ctx.tools.execute({callId:'automatic-creation-denial',name:'dx_task_create',
|
||||
const denial=await executeTool(ctx, {callId:'automatic-creation-denial',name:'dx_task_create',
|
||||
arguments:{name:'Must never open a dialog'},agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)});
|
||||
assert.equal(denial.isError,true);
|
||||
assert.equal(creationBodyRan,false,'Automatic incident must be denied before desktop request emission');
|
||||
@@ -48,7 +75,7 @@ try{
|
||||
['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,
|
||||
const result=await executeTool(ctx, {callId:'automatic-denial-'+name,name,arguments:args,
|
||||
agent:ctx.agents.get(sessionId),signal:AbortSignal.timeout(1500)});
|
||||
assert.equal(result.isError,true);
|
||||
assert.equal(creationBodyRan,false);
|
||||
@@ -65,7 +92,7 @@ try{
|
||||
assert.ok(!text.includes('different-current-task'));
|
||||
const report={status:'passed',session_id:value.session_id,reply:value.reply,
|
||||
incidentBoundSnapshot:true,automaticTaskCreationDenied:true,toolResults:tools};
|
||||
await writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2));
|
||||
await writeFile(path.join(fixture,'report.json'),JSON.stringify(report,null,2));
|
||||
original(JSON.stringify(report)+'\n');
|
||||
}finally{
|
||||
clearTimeout(timer);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** Exercise actual Harness file tools against owned folders and ZIP archives. */
|
||||
import {executeTool} from './dsh_tool_probe.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdir,mkdtemp,writeFile,readFile,readdir} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
@@ -24,7 +25,7 @@ try{
|
||||
const names=ctx.tools.schemas(agent).map(x=>x.name);
|
||||
for(const name of ['read','read_image','write','edit','glob','grep','working_directory','extract_zip'])
|
||||
assert.ok(names.includes(name),'Missing file capability: '+name);
|
||||
const call=async(name,args)=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent,signal:AbortSignal.timeout(20000)});
|
||||
const call=async(name,args)=>executeTool(ctx, {name,arguments:args,callId:crypto.randomUUID(),agent,signal:AbortSignal.timeout(20000)});
|
||||
const ok=async(name,args)=>{
|
||||
const result=await call(name,args);assert.equal(result.isError,false,name+': '+JSON.stringify(result));return result;
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** Real Harness, two processes: automatic diagnosis must stay isolated after restart. */
|
||||
import {executeTool} from './dsh_tool_probe.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdir,mkdtemp,writeFile,readFile,unlink,symlink} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
@@ -96,7 +97,7 @@ if(!phase){
|
||||
const resumed=await ctx.sessionController.resolveAgent(sessionId);
|
||||
assert.ok(resumed.agent,JSON.stringify(resumed.error));
|
||||
const agent=resumed.agent;
|
||||
const call=(owner,name,args={})=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent:owner,signal:AbortSignal.timeout(5000)});
|
||||
const call=(owner,name,args={})=>executeTool(ctx, {name,arguments:args,callId:crypto.randomUUID(),agent:owner,signal:AbortSignal.timeout(5000)});
|
||||
const snapshot=await call(agent,'dx_task_snapshot');
|
||||
assert.equal(snapshot.isError,false,JSON.stringify(snapshot));
|
||||
assert.equal(snapshot.value.task_id,'incident-original','historical diagnosis must not read the current task');
|
||||
|
||||
@@ -12,8 +12,9 @@ export async function verifyModelSettings(c, output) {
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
const endpoint=`http://127.0.0.1:${server.address().port}/v1`;
|
||||
const visible=selector=>`[...document.querySelectorAll(${JSON.stringify(selector)})].find(e=>e.getBoundingClientRect().width>0)`;
|
||||
const button=text=>`[...document.querySelectorAll('button')].find(e=>e.getBoundingClientRect().width>0&&e.textContent.trim()===${JSON.stringify(text)})`;
|
||||
const rendered=`e.getBoundingClientRect().width>0&&!e.closest('details:not([open])')`;
|
||||
const visible=selector=>`[...document.querySelectorAll(${JSON.stringify(selector)})].find(e=>${rendered})`;
|
||||
const button=text=>`[...document.querySelectorAll('button')].find(e=>${rendered}&&e.textContent.trim()===${JSON.stringify(text)})`;
|
||||
async function wait(expression){
|
||||
const end=Date.now()+20000;
|
||||
while(Date.now()<end){if(await c.evaluate(expression))return;await new Promise(r=>setTimeout(r,100));}
|
||||
@@ -49,7 +50,7 @@ export async function verifyModelSettings(c, output) {
|
||||
const candidate=`[...document.querySelectorAll('[role="dialog"] label')].find(e=>e.textContent.includes('issue16-fixture-model'))?.querySelector('input[type="checkbox"]')`;
|
||||
if(!await c.evaluate(`(${candidate})?.checked`))await c.click(candidate);
|
||||
assert.equal(await c.evaluate(`(${candidate})?.checked`),true);
|
||||
await c.click(button('添加所选'));
|
||||
await c.click(button('更新列表'));
|
||||
await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`);
|
||||
await c.screenshot(path.join(output,'custom-model-discovery.png'));
|
||||
await c.click(button('创建提供商'));
|
||||
@@ -58,7 +59,7 @@ export async function verifyModelSettings(c, output) {
|
||||
// Reopen the real editor to read committed fields, not the submitted draft.
|
||||
await c.click(`[...document.querySelectorAll('li')].find(e=>e.textContent.includes('issue16-fixture'))?.querySelector('button')`);
|
||||
await wait(`document.body.innerText.includes('自定义设置')`);
|
||||
await c.click(`[...document.querySelectorAll('summary')].find(e=>e.textContent.includes('自定义设置'))`);
|
||||
await c.click(`[...document.querySelectorAll('summary')].find(e=>e.textContent.includes('自定义设置')&&e.closest('details').querySelector('input[aria-label="API 地址"]')?.value===${JSON.stringify(endpoint)})`);
|
||||
await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`);
|
||||
await c.screenshot(path.join(output,'custom-model-persisted.png'));
|
||||
return {status:'passed',provider:'issue16-fixture',model:'issue16-fixture-model',requests,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** Compare the embedded assistant with the installed official Standard preset. */
|
||||
import {executeTool} from './dsh_tool_probe.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdir,mkdtemp,writeFile,readFile} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
@@ -29,7 +30,7 @@ try{
|
||||
assert.deepEqual(names(embedded),names(native),'Existing dx-task sessions must retain the full native tool catalog');
|
||||
for(const tool of ['read','write','edit','pwsh','get_goal','create_goal','update_goal','todo_write','subagent'])
|
||||
assert.ok(names(embedded).includes(tool),'Missing native capability: '+tool);
|
||||
const call=(name,args)=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent:embedded,signal:AbortSignal.timeout(20000)});
|
||||
const call=(name,args)=>executeTool(ctx, {name,arguments:args,callId:crypto.randomUUID(),agent:embedded,signal:AbortSignal.timeout(20000)});
|
||||
const filename=path.join(process.env.DX_DSH_WORKSPACE,'native-write.txt');
|
||||
const written=await call('write',{file_path:filename,content:'native file operations'});
|
||||
assert.equal(written.isError,false,JSON.stringify(written));
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
/** Exercise the real official runtime and policy pipeline without CAD or a model. */
|
||||
import {executeTool} from './dsh_tool_probe.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdir,writeFile} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {fileURLToPath,pathToFileURL} from 'node:url';
|
||||
import {createRequire} from 'node:module';
|
||||
import {bootRuntime,TASK_TOOLS} from '../integration/dsh/start.mjs';
|
||||
|
||||
const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
||||
const output=path.join(repo,'build/dsh-native-cli-verification');
|
||||
const runtime=path.resolve(process.argv[2]??path.join(repo,'integration/dsh'));
|
||||
const {bootRuntime,TASK_TOOLS,VERSION}=await import(pathToFileURL(path.join(runtime,'start.mjs')).href);
|
||||
const output=path.resolve(process.argv[3]??path.join(repo,'build/dsh-native-cli-verification'));
|
||||
await mkdir(output,{recursive:true});
|
||||
delete process.env.DX_DSH_PARENT_PIPE;
|
||||
if(process.argv[2]){
|
||||
for(const key of ['DSH_API_KEY','DSH_API_BASE','DSH_MODEL','DX_DSH_MODELS','DSH_PERMISSION_MODE'])delete process.env[key];
|
||||
}
|
||||
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:'cli-verification',status:'paused',
|
||||
revision:'cli-revision',rules_count:2,progress:{},issue:'',issue_code:'',events:[]}));
|
||||
const {ctx,shutdown}=await bootRuntime({announce:false});
|
||||
const report={};
|
||||
const report={version:VERSION};
|
||||
try {
|
||||
const schemas=ctx.tools.schemas();
|
||||
report.tools=schemas.map(x=>x.name);
|
||||
@@ -26,10 +32,10 @@ try {
|
||||
report.configuredModels=(await ctx.llm.listModels('dx')).map(model=>model.id);
|
||||
assert.ok(report.configuredModels.includes(process.env.DSH_MODEL));
|
||||
}
|
||||
const snapshot=await ctx.tools.execute({callId:'verify-read',name:'dx_task_snapshot',arguments:{},signal:new AbortController().signal});
|
||||
const snapshot=await executeTool(ctx, {callId:'verify-read',name:'dx_task_snapshot',arguments:{},signal:new AbortController().signal});
|
||||
assert.equal(snapshot.isError,false,JSON.stringify(snapshot));
|
||||
report.snapshotRead=true;
|
||||
const desktopOnly=await ctx.tools.execute({callId:'verify-desktop-only',name:'dx_task_create',arguments:{name:'CLI must not mutate'},signal:new AbortController().signal});
|
||||
const desktopOnly=await executeTool(ctx, {callId:'verify-desktop-only',name:'dx_task_create',arguments:{name:'CLI must not mutate'},signal:new AbortController().signal});
|
||||
assert.equal(desktopOnly.isError,true);
|
||||
report.creationRequiresDesktopConfirmation=true;
|
||||
for(const [name,args] of [
|
||||
@@ -38,16 +44,16 @@ try {
|
||||
['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)});
|
||||
const result=await executeTool(ctx, {callId:'desktop-only-'+name,name,arguments:args,signal:AbortSignal.timeout(2000)});
|
||||
assert.equal(result.isError,true,name+' requires parent desktop');
|
||||
}
|
||||
report.lifecycleRequiresDesktop=true;
|
||||
const require=createRequire(path.join(repo,'integration/dsh/package.json'));
|
||||
const require=createRequire(path.join(runtime,'package.json'));
|
||||
const {defineTool}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-tools')).href);
|
||||
let bodyRan=false;
|
||||
const release=ctx.tools.register(defineTool({name:'forbidden_probe',description:'Never executes',parameters:{},
|
||||
output:{schema:{type:'boolean'},render:()=>[{type:'text',text:'probe'}]},execute:async()=>{bodyRan=true;return true;}}));
|
||||
const extension=await ctx.tools.execute({callId:'verify-extension',name:'forbidden_probe',arguments:{},signal:new AbortController().signal});
|
||||
const extension=await executeTool(ctx, {callId:'verify-extension',name:'forbidden_probe',arguments:{},signal:new AbortController().signal});
|
||||
release();
|
||||
assert.equal(extension.isError,false);
|
||||
assert.equal(bodyRan,true);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** PR18 #197: no silently omitted names, bounded workers, real cancellation. */
|
||||
import {executeTool} from './dsh_tool_probe.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdir,mkdtemp,writeFile,readdir,readFile} from 'node:fs/promises';
|
||||
import {spawnSync} from 'node:child_process';
|
||||
@@ -25,7 +26,7 @@ process.env.DX_DSH_HOME=path.join(root,'home');process.env.DX_DSH_CONTEXT_FILE=p
|
||||
await writeFile(process.env.DX_DSH_CONTEXT_FILE,'{"task_id":"zip-review","revision":"zip-review","status":"observe"}');
|
||||
const {ctx,shutdown}=await bootRuntime({announce:false});
|
||||
try{
|
||||
const call=(file,signal=AbortSignal.timeout(30000))=>ctx.tools.execute({name:'extract_zip',
|
||||
const call=(file,signal=AbortSignal.timeout(30000))=>executeTool(ctx, {name:'extract_zip',
|
||||
arguments:{file_path:path.join(root,file),output_directory:root},callId:crypto.randomUUID(),signal});
|
||||
const before=await readdir(root);
|
||||
for(const file of ['proto.zip','proto-bad.zip']){
|
||||
|
||||
Reference in new issue
Block a user